I can't make AppleScript create a file with a custom name

I want to make application "TextEdit" create a file in Desktop folder. However it doesn't compile with a constant error message popping up. The script:


tell application "TextEdit"

make new document named "Personal letter" at desktop ¬

with properties {text:"Dear NAME_PLACEHOLDER,

You're invited to join us in the office on Monday for pizza"}

end tell


Tried to change "desktop" to the full reference (folder "Desktop" of folder user_name etc) - no difference.

tellaWhat am I doing wrong?

Mac OS X (10.7.5), MacBook Pro 15.4 mid-2012

Posted on Jan 5, 2017 1:43 PM

Reply
16 replies

Jan 7, 2017 2:21 PM in response to scrutinizer82

I just booted up into Lion 10.7.5, and am using this simple AppleScript:


set textHeading to "Test RTF Creation"

set prtf to (path to desktop as text) & "foo.rtf"


tell application "TextEdit"

launch

set newDoc to makenewdocumentwith properties {name:prtf}

makenewparagraphat beginning of text of newDocwith datatextHeading & return

-- make new paragraph at end of text of newDoc with data moreData

tell text of newDoc

set font to "Helvetica Neue"

set size to 16

-- red text

set color of paragraph 1 to {65535, 0, 0}

end tell

-- close newDoc saving in file prtf

savenewDocastextinfileprtf

end tell

return

The script will run correctly, and write an RTF document to the Desktop whether you use either of the following syntax choices:

  • closenewDocsaving infileprtf
  • savenewDocas text in fileprtf


In either case, TextEdit runs, writes the document, and then quits. If you encounter a script error when running AppleScript against TextEdit, it will remain open, and should be quit.

Jan 5, 2017 2:52 PM in response to scrutinizer82

Using TextEdit to create a file isn't the best way.


Here is some code which creates a file.

(* 
  This applescript demonstaties how to create a log file.

    Author: rccharles
    
    Write debug text to the file debugLog.txt in your home folder ( ~/debugLog.txt ).
    
    example of the file ~/debugLog.txt:
    

thePath = Ext-Remainder:
End of program.  

    
    fyi:
    
    The applescript log statements are ignored when not running from the script editor.
    
    Not to be confused, this applescript contains log statements that have nothing to do with creating a log file. 
    They are to help the script auther write the script.
    
 *)



on run
    -- thePath points to the folder in which to create the debug log.
    global thePath
    (* Use the path to clause to create a generalized  path statements *)
    set thePath to (path to home folder as string)
    set firstRunning to ""
    
    -- Write a message into the applescript editor event log.
    log "  --- Starting on " & ((current date) as string) & " --- "
    
    
    
    debug("thePath = " & thePath)
    
    debug("End of program.  ")
    
    
    
end run

-- ----------------------------------------------------------

on appendToFile(fileId, theData)
    
    local theSize, writeWhere
    
    set theSize to (get eof fileId)
    set writeWhere to theSize + 1 as integer
    write theData to fileId starting at writeWhere
    
end appendToFile


-- ----------------------------------------------------------

on debug(theMessage)
    global thePath
    local theSize, startupDiskName, pathToLog, fileReference, appPath, unixReturn
    
    -- Use unix line end character
    set lf to ASCII character 10
    
    set pathToLog to (thePath & "outputfile.txt")
    try
        
        set fileReference to (open for access file pathToLog ¬
            with write permission)
        
        -- use lf for unix line ends
        -- use return for mac line ends
        appendToFile(fileReference, theMessage & lf)
        
        close access fileReference
        
    on error mes
        try
            log "  We got an error when writing to  " & mes
            close access fileReference
        end try
    end try
    
end debug

Jan 5, 2017 3:14 PM in response to scrutinizer82

And the AppleScript that allows you to change the filename extension between ".txt" and ".rft", with monochrome, or rich text results in the document.


set EXT to "txt"

-- set EXT to "rtf"

set personal_doc to ((path to desktop as text) & "Personal_letter." & EXT) as text

set textTE to "Dear NAME_PLACEHOLDER," & return & "You're invited to join us in the office on Monday for pizza"

set redColor to {65535, 0, 0}


tell application "TextEdit"

activate


set newDoc to (makenewdocumentwith properties {name:personal_doc})

makenewparagraphat beginning of text of newDocwith datatextTE


if EXT contains "rtf" then

tell text of newDoc

set the font to "Baskerville"

set the size to 16

set the color of paragraph 1 to redColor

end tell

end if


closenewDocsaving infilepersonal_doc with saving

-- always let the file extension show in the finder after saving

tell application "Finder" to set extension hidden of (file personal_doc as alias) to false


end tell

Jan 5, 2017 7:04 PM in response to scrutinizer82

The make new document at syntax does not make a file. It creates a document in some position in the application's document hierarchy.

As you can see in the Dictionary, documents are contained by an application, so a new document will be created within the documents of the TextEdit application. It would be as if you use the File>New menu command.

document n [inh. item; see also TextEdit suite] : A document.

ELEMENTS

contained by application, application.


For instance, you can make a new document at the beginning or the end of the list of open documents:

tell application "TextEdit"

make new document at end of documents

end tell

You'd have to then save the document. Here is how it might look:


property fileName : "Personal Letter.txt"

property messageText : "Dear NAME_PLACEHOLDER," & return & return & "You're invited to join us in the office on Monday for pizza"

tell application "TextEdit"

set myDocument to make new document at end of documents with properties {text:messageText}

save myDocument in file ((path to desktop folder as string) & fileName)

quit

end tell

Jan 7, 2017 3:26 AM in response to VikingOSX

Hi, VikingOSX

The part with saving on closing:

VikingOSX wrote:


closenewDocsaving infilepersonal_doc with saving


I was scrutinizing an example script in the textbook I'm learning AppleScript from - the main reason for starting this thread - and the author rendered it as following:

save in file (desktop_path & name_ref & " letter.rtf")

close saving no


My question: what's the difference between close saving (in) and save (in)//close saving? If it isn't then what's the purpose of using similar syntax leading to the similar result?

Jan 7, 2017 7:37 AM in response to scrutinizer82

The first rule of AppleScript, and its interface to applications via their scripting dictionaries — is that Apple continually changes both the AppleScript language, and the scripting dictionaries to their applications — with each new release of the operating system. That AppleScript book that you are using only showed TextEdit scripting dictionary syntax that was valid when the book was written, and cannot reflect Apple changes since.


Two years ago, I wrote a simple AppleScript that created a rich text document in TextEdit, and saved the document to the Desktop. A far simpler Save syntax now explodes when run against TextEdit in El Capitan. After much trial and cursing, the Save syntax that I provided you is what actually works in TextEdit on El Capitan, and conforms to its entry in that scripting dictionary entry.


In the Script Editor File menu, select Open Dictionary... and choose TextEdit. Look at the syntax for Save. If you are not on El Capitan, then use the Save syntax as spelled out in the dictionary.


Where AppleScript itself offers multiple ways to write code, the scripting dictionaries are quite resolute on allowed syntax.

Jan 9, 2017 2:34 PM in response to VikingOSX

Ok, I cracked it. The next phase was to make a personal letter to each of three persons of a list in 3 separate files with filenames containing the name of the corresponding person instead of both "Personal" (i.e., "Stan letter.rtf", "Ben letter.rtf" etc) and the placeholder "NAME_PLACEHOLDER" (so as to create "Dear Stan" line). The code is below. I get only the filename part working but not the "NAME_PLACEHOLDER" part. What's wrong?


I'm posting the entire code consisting of the TextEdit doc and individualized personal letters creation steps I used.



set doc_extension to "rtf"

set my_sign to "Kindest regards" & return & "My_initials"

set doc_contents to "Dear NAME_PLACEHOLDER" & return & return & "You're invited to join us in the office on Monday for pizza" & return & my_sign

set doc_name to (path to desktop as text) & "Personal letter" & "." & doc_extension


tell application "TextEdit"

activate

tell application "Finder"

if file doc_name exists then

delete file doc_name

end if

end tell

set new_doc to make new document with properties {text:doc_contents, name:doc_name}


tell text of new_doc

if doc_extension is "rtf" then

set font to "MyriadPro-Regular"


set size to 18

end if

end tell

close new_doc saving in file doc_name saving yes

tell application "Finder" to set extension hidden of file doc_name to false


end tell



set names_list to {"Ben", "Jen", "Sten"}

set desktop_path to ((path to desktop) as text)



repeat with name_ref in names_list

tell application "Finder"

if file ((desktop_path & name_ref & " letter." & doc_extension)) exists then

delete file (desktop_path & name_ref & " letter." & doc_extension)

end if

end tell

tell application "TextEdit"

open (desktop_path & "Personal letter." & doc_extension) as alias

tell document 1

set (every word where it is "NAME_PLACEHOLDER") to contents of name_ref

save in file (desktop_path & name_ref & " letter." & doc_extension)

close saving yes

end tell


end tell

end repeat

Jan 9, 2017 5:12 PM in response to scrutinizer82

Understand that every word of "NAME_PLACEHOLDER" returns {"NAME", "PLACEHOLDER"} without the connecting underscore. The following replacement AppleScript simply grabs the greeting, and the name_ref, and rewrites the first paragraph with that content. I have added a return after the name_ref to open a newline before the message.


repeat with name_ref in names_list

tell application "Finder"

if file ((desktop_path & name_ref & " letter." & doc_extension)) exists then

deletefile (desktop_path & name_ref & " letter." & doc_extension)

end if

end tell

tell application "TextEdit"

open (desktop_path & "Personal letter." & doc_extension) as alias

tell document 1

set greeting to first word of first paragraph

-- set (every word where it is "NAME_PLACEHOLDER") to contents of name_ref

set first paragraph to greeting & space & name_ref & return

saveinfile (desktop_path & name_ref & " letter." & doc_extension)

closesavingyes

end tell

end tell

end repeat

The link that rccharles provided to that replacement handler is a very useful tool.



end tell

Jan 10, 2017 2:46 PM in response to VikingOSX

Thank you very much,

That way the script worked. However I'm wondering why

(1)"contents of name_ref" (contents of a reference object) didn't do the trick? I picked that up from the aforementioned textbook where the author used that property in repeat with…in.. statement to accomplish the task (true, he did that on Snow Leopard whereas I tried to do on Lion).

(2) when writing the first half of the script (for creating the TexEdit doc) I tried to use "name extension" property of the element of the class "file" (that I took notice of browsing its properties) when assigning "rtf" value, however it failed. What could be a reason? What is this property for, what it does? Is this possible to use it in this script?

Jan 10, 2017 4:49 PM in response to scrutinizer82

TextEdit does not have any name extension defined in its scripting dictionary. Both Finder and System Events do.


In the follow example, I use alias because the file actually exists on disk. In both instances, "rtf" is returned.


set anRTF to (path to documents folder as text) & "_Doctest:" & "pcloud.rtf" as alias


tell application "Finder"

set foo to name extension of anRTF

end tell


tell application "System Events"

set foo to name extension of anRTF

end tell

return

Jan 11, 2017 2:47 PM in response to VikingOSX

Ah, so "name extension" can be used only in conjunction with existing files?

Also, to repeat, when do you use the property "contents of" a reference object? I used in the script and it failed. Is it just because of every word keywords?


P.S. By the way, MacOS X technologies forum is the most helpful one of all of Apple Support Communities forums out there. If only other were as useful.

Jan 11, 2017 4:12 PM in response to scrutinizer82

The Finder or System Events usage of name extension implies an existing file (alias). Bookmark MacScripter.


set aList to {"foo", "bar", "baz"}

log (contents of aList)

(*foo, bar, baz*)

log (contents of item 1 of aList)

(*foo*)


tell application "Finder"

set docx_list to (every item in entire contents of folder afile whose kind is "Microsoft Word Document") as alias list

end tell

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

I can't make AppleScript create a file with a custom name

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.