I'm using a code to format textedit files for lab data.
I currently am using AppleScript to create a document in TextEdit and adding text to it, but when I try to save it, TextEdit gives me the error "you do not have permission to save as blahblahblah." I have already tried changing the permission on the folder in which I'm saving it in, but I think it may have something to do with it being a file that AppleScript created.
The exact error output is a dialog box from TextEdit
The document “1.txt” could not be saved as “1”. You don’t have permission.
To view or change permissions, select the item in the Finder and choose File > Get Info.
The segments of my code that don't work are
tell application "TextEdit"
make new document with properties {name:("1.txt")}
end tell
--data formatting code here (n is set here)
tell application "TextEdit"
delay 1
close document 1 saving in ("/Users/bo/Desktop/Script Doc/" & (n as string))
set n to n + 1
make new document with properties {name:((n as string) & ".txt")}
delay 1
end tell
I have scoured other questions and I have found the code segments
open for access document 1
close access document 1
but I'm not sure how to implement these / if I even should, and if not, I'm not sure how to fix this issue.
Thanks in advance
Unfortunately, that error message isn't helping much. You are essentially trying to save into a string, which isn't going to work - you need to use a file specifier, for example:
close document 1 saving in POSIX file ("/Users/bo/Desktop/Script Doc/" & n & ".txt")
Note that not everything knows about POSIX paths, in which case you will need to coerce or specify it as in my example.
Saving directly to the Desktop works for me using the latest version of macOS Mojave
property outputPath : POSIX path of (((path to desktop as text) & "Script Doc") as alias)
property docNumber : 1
property docExtension : ".txt"
tell application "TextEdit"
set docName to (docNumber & docExtension) as text
set theText to "Your Desired Text Content"
set thisDoc to make new document with properties {name:docName, text:theText}
close thisDoc saving in POSIX file (outputPath & "/" & (name of thisDoc))
(* IF YOU WANT TO SAVE MULTIPLE FILES WITH CONSECUTIVE NAMES *)
set docNumber to docNumber + 1
set docName to (docNumber & docExtension) as text
set thisDoc2 to make new document with properties {name:docName} -- Removed Text Property This Time
close thisDoc2 saving in POSIX file (outputPath & "/" & (name of thisDoc2))
end tell
TextEdit is sandboxed. You cannot save documents in the standard desktop folder.
An alternative is to hard-code the path to the documents folder in the container of TextEdit.
tell application "TextEdit"
make new document with properties {name:"1.txt"}
end tell
set containerDocumentsFolder to (path to library folder from user domain as text) & "Containers:com.apple.TextEdit:Data:Documents:"
tell application "TextEdit"
close document 1 saving in containerDocumentsFolder & (n as string) & ".txt"
set n to n + 1
make new document with properties {name:(n as string) & ".txt"}
end tell
Related
I want to write an AppleScript which creates a new file in the same directory as the file I currently have open (in this case, in the application TexShop).
If I can get the path, then I can write a script like:
set thePath to get path to open window / tell TexShop to get path...?
set response to display dialog "Some text:" default answer ""
set toWrite to text returned of response
tell application "Finder" to set newFile to make new file at thePath
set openFile to open for access file (newFile as string) with write permission
write toWrite to openFile starting at eof
I am ultimately just looking for a way to specify where I want the file to go depending on changing circumstances, that is, when I am working on different files in different directories.
This following AppleScript code should help towards the goal of getting the path to the front most document in the front most application and the path to its containing folder.
(* The Delay Command Gives You Time To Bring The Desired App To The Front
Mainly For Use While Testing This Code In Script Editor.app *)
delay 5 -- Can Be Removed If Not Needed
tell application (path to frontmost application as text) to ¬
set documentPath to (get path of document 1) as POSIX file as alias
tell application "Finder" to set containingFolder to container ¬
of documentPath as alias
Here's a technique that should cover both scriptable and non-scriptable applications, with a caveat that it obviously can't return information that isn't provided by the developer through accessibility hooks. However, if it's scriptable, or if the developer chooses to expose app data for accessibility, then this will provide that little extra scope beyond the decreasing circle of AppleScriptable software:
tell application id "com.apple.systemevents" to tell (the first process ¬
where it is frontmost) to tell (a reference to the front window) ¬
to if it exists then tell its attribute "AXDocument"'s value to ¬
if it is not in [missing value, "file:///Irrelevent"] then ¬
return my (POSIXPathOfFolder for it)
false
on POSIXPathOfFolder for (fileURL as text)
local fileURL
set fp to "/tmp/rw" as «class furl»
close access (open for access fp)
set eof of fp to 0
write the fileURL to fp
read fp as «class furl»
POSIX path of (result & "::" as text)
end POSIXPathOfFolder
I also avoid employing Finder whenever possible, as it's slow, buggy, and temperamental. The handler at the bottom uses standard additions plus built-in features to get the containing folder of the retrieved document path.
If a document path is not made available, the script returns false.
I'm trying to do an applescript that pastes data into Numbers and then exports it as a csv file.
It's all working fine except that Numbers keeps my previous documents and opens them every time. This resulting in a new "Untitled" every time the script runs, so if the script is run 10 times - Numbers will open the 10 previous documents first.
I'm trying quit without saving and close this document without saving without results :(.
How can I make Numbers not open old unsaved files everytime Numbers is started?
on run
set theFilePath to "APPLE SSD SMO128B Media:Users:Henrik:Desktop:my.csv"
tell application "Numbers"
activate -- If script is run once before the old document that is exported but not saved will open here too
set thisDocument to make new document
tell thisDocument
delete every table of every sheet
end tell
end tell
tell application "System Events" to keystroke "v" using {option down, shift down, command down}
delay 1
tell application "Numbers"
export front document as CSV to file theFilePath
close thisDocument without saving
delay 1
end tell
tell application "Numbers" to quit without saving
end run
To avoid having Numbers reopening the files you created, you first need to actually save the document to a file, and then ask the Finder to delete it.
You can use the following code:
set documentName to "Test"
set targetFolder to path to downloads folder
set myFile to ((targetFolder as string) & documentName & ".numbers")
tell application "Numbers"
set myDocument to make new document
#Save the file, to delete it just afterward
save myDocument in file myFile
# Export the document
set exportFileName to documentName & ".pdf"
set the targetFilePath to ((targetFolder as string) & exportFileName)
export myDocument to file targetFilePath as PDF
close
quit saving no
end tell
tell application "Finder" to delete file myFile
Objective: Move all files and files in folders to destination folder and maintain the file structure [files and named folders]. Important for music files in albums.
Functional: Move all listed files in SmartFolder [named] to destinationFolder with serial / consecutive move operation and maintain the same file structure and copy of dataFiles listed in SmartFolder.
Key: All files were obtained for transfer. Normal CMD + A, CMD + C, CMD + V hangs up the computer and the transfer does not initiate. The AppleScript to move each dataObject to destinationPath is all.
Facts: How to reference objects [files, folders] and their proper reference format and accepted path syntax; path or POSIX, and use of alias. Basic operations. I ran an AppleScript to move filePath to pathDestination, and was otherwise successful, and would be nice to known the formalization syntax for path reference.
tell application "Finder"
move allFiles to destinationFolder
// recursive/repeat code to loop through all listed files and folder
end tell
Reference: Applescript, show all files with tag
[Moving / selecting listed files from 'smartfolder' containers as active windows and displayLists. It was an alt. solution since AppleScript will not reference the SmartFolder as an object, nor will it dynamically call the listProperty of the SmartFolder object unless called by an unknown or un-reference method or command.
Since your main issue, as far as I can tell, seems to be dealing with SmartFolders in AppleScript, which—as you said—cannot be referenced as folder objects, this little snippet might be of help:
set SmartFolder to "/Users/CK/My Smart Folder.savedSearch"
tell application "System Events" to get value of property list file SmartFolder
set {[Scope], Query} to {SearchScopes, RawQuery} of RawQueryDict of result
set AppleScript's text item delimiters to tab
set Command to {"mdfind -onlyin", ¬
quoted form of Scope as text, ¬
quoted form of Query as text} as text
set SearchResults to paragraphs of (do shell script Command)
--> returns a list of posix files
--> e.g. {"/Users/CK/Downloads/This is file one.txt", ...}
This will return a list of POSIX paths to files that match the search criteria.
I would recommend using System Events rather than Finder to deal with large numbers of files. It can also handle posix paths without the need to manually coerce them into aliases or whatever. So, given a posix path, such as the ones returned in the list using the above code snippet, you simply do this:
set myfile to item 1 of SearchResults
tell application "System Events" to move myfile to "/Users/CK/Desktop"
Without knowing more details of what your smart folder contains (since some searches could easily return a folder plus the contents of that folder, which you'd have to bear in mind when getting your AppleScript to recurse through the search results), I can't give you more than that. But, you said your main problems were being unable to handle SmartFolders and not knowing how to reference files/folders.
This works for me using the latest version of Sierra.
Set the value of property moveToNewFolderto the destination folder of your choice
This script creates a "Choose From List" Dialog, allowing you to choose any smart folder which resides on your system. It will then move all of these files and folders in the chosen smart folder, to your set destination folder.
property savedSearches : (path to home folder as string) & "Library" & ":Saved Searches"
property savedSearchesSubFolders : {}
property namesOfSavedSearchesSubFolders : {}
property selectedSearchFolder : ""
property selectedSearchFolderPath : missing value
property moveTheseItems : missing value
property moveToNewFolder : (path to desktop as text) & "untitled folder" -- change this value to your preferred destination folder
tell application "Finder"
activate
delay 0.1 -- may need to adjust delay time value
open savedSearches
delay 0.1 -- may need to adjust delay time value
reveal savedSearches
delay 0.1 -- may need to adjust delay time value
select savedSearches
delay 0.1 -- may need to adjust delay time value
set current view of Finder window 1 to column view
delay 0.1 -- may need to adjust delay time value
tell its Finder window (POSIX path of savedSearches)
delay 0.1 -- may need to adjust delay time value
set savedSearchesSubFolders to items
set namesOfSavedSearchesSubFolders to name of items
-- Allows to choose any smart folder from a list of all smart folders
set selectedSearchFolder to choose from list namesOfSavedSearchesSubFolders ¬
with title ¬
"Smart Search Folders" with prompt ¬
"Choose Your Folder" OK button name ¬
"OK" cancel button name "CANCEL"
set selectedSearchFolder to selectedSearchFolder as text
set selectedSearchFolderPath to savedSearches & ":" & selectedSearchFolder
set selectedSearchFolderPath to selectedSearchFolderPath as string
end tell
delay 0.2 -- may need to adjust delay time value
select selectedSearchFolderPath
tell Finder window 1
set defaultView to current view
set current view to list view
delay 0.1 -- may need to adjust delay time value
set current view to defaultView
delay 0.5 -- may need to adjust delay time value
tell application "System Events"
key code 0 using command down
end tell
end tell
set moveTheseItems to selection
end tell
tell application "Finder"
set resultObject to move moveTheseItems ¬
to moveToNewFolder ¬
with replacing
end tell
I have a script that changes the icon of a folder with the image you select and it works fine but I want to be able to have the script automatically select the first image of the folder and assign that as the image that will be used to create the icon.
This is what I have so far. It is unable to select the image and gives various error messages depending on what I try. Any help would be greatly appreciated!
set exePath to (path to home folder as text) & "downloads:SetFileIcon"
tell application "Finder"
set theSelection to selection -- This is a list of selected items, even if only 1 item is selected.
set theFile to (item 1 of theSelection) as text -- Get the first item in the list. We make it text so we can convert it to a posix path for SetFileIcon.
set theimage to item 1 of theSelection
set imagePath to (path to desktop folder as text) and theimage
end tell
do shell script quoted form of POSIX path of exePath & " -image " & quoted form of POSIX path of imagePath & " -file " & quoted form of POSIX path of theFile
A couple of issues with your script at first glance. First, you’re never asking for the contents of the folder. You set theFile to item 1 of theSelection and then you set theimage to item 1 of theSelection. I expect you meant to set theimage to item 1 of the document files of theFile. Note that theFile is actually the selected folder.
Second, “and” is a boolean operation; to concatenate text in AppleScript, use “ & ”. Thus, even if theimage contained the image’s name, you would need to use & theimage.
However, since you are asking the Finder for the information, the Finder already knows the full path to any particular file. So, once you get an image, you can ask the Finder for the path directly.
tell application "Finder"
-- This is a list of selected items, even if only 1 item is selected.
set theSelections to the selection
-- This code assumes that the first selected item is a folder
set theFolder to the first item of theSelections
-- we want the first document that is also an image
set theImages to the document files of theFolder whose kind contains "image"
set theImage to item 1 of theImages as text
-- and we want it's path
set imagePath to POSIX path of theImage
end tell
I am writing some text in to word file i want to change the color of that text any one can help on that one plz.
I want to print the 'message' from following script in red color.
Here is the Script:
set message to "mostly these windows are popup in application"
on ResultCreationFuction(message)
try
set text_to_save to message as text
tell application "System Events"
tell application "Finder"
set sortedList to sort (get files of folder "SofTestAutomationResult" of desktop) by modification date
set FileCount to get count of sortedList
set theFile to (item FileCount of sortedList) as alias
end tell
set file_ref to open for access theFile with write permission
write (text_to_save & return) to the file_ref starting at eof
close access file_ref
delay 2
end tell
end try
end ResultCreationFuction
Some Details:
The file is word which is all ready present on above location having name "10.012.2014_17_4_20.doc" (the name of .doc file is not fix)
What you are attempting is the wrong way to do it.
To manipulate content like that, including formatted text (not plain
text), you need to work within, ideally, a well-scriptable app, like
Pages (or Word, perhaps, but I don't have that on the machine I'm
writing this from).
Don't use System Events if you don't need to. Use the apps with the appropriate AppleEvents/dictionary, etc. If you don't know what I'm talking about, you need to take advantage of the infinite resource known as the web.
"Fuction" is just bad form.
I would suggest doing a lot more reading up on how AppleScript works (or scripting in general), but to start you out, here is a script I just wrote in pages which sets the color of a specific word of the open document after putting text in there:
tell application "Pages"
set body text of document 1 to "hello there mister fancy pants"
set color of word 3 of body text of page 1 of document 1 to {64614, 0, 111}
end tell
If you have Pages, try this by starting with a blank page and running this script. Obviously, you could get rid of "word 3 of" in the 2nd line, and the whole body text will be red.
I hope this makes sense and is of help.
[edit]
I should mention that even TextEdit is scriptable and can open Word documents. Here's an example using TextEdit:
tell application "TextEdit"
set text of document 1 to "hello mister fancy pants"
set color of words 2 thru 3 of text of document 1 to {65535, 0, 0}
end tell
There is a little danger of non-Word apps losing formatting of Word files. But it just seems you are attempting something very simple, and I'm not sure if Word is really necessary here.
You can't add color using the write to eof. You should open the document in Word and then insert the line and add the color. Here's a script that should demonstrate how:
set text_to_add to "mostly these windows are popup in application"
set theFile to ((path to desktop folder) & "10.012.2014_17_4_20.doc") as string
tell application "Microsoft Word"
set theFile to theFile as string -- assuming theFile is an alias or :: path
open file theFile
tell active document
set endOfDoc to end of content of text object -- insert the text to end of document
set theRange to create range start (endOfDoc - 1) end endOfDoc
insert text text_to_add at theRange
set myRange to create range start endOfDoc end (endOfDoc + (length of text_to_add))
set color index of font object of myRange to red
save
end tell
end tell