How to create a blank RTF file in AppleScript

applescripttext;textedit

I want to be able to create a new TextEdit document with an AppleScript file. The AppleScript file will then be triggered by a system-wide keyboard shortcut via FastScripts. Specifically, I want the AppleScript to:

  1. Prompt the user to enter a filename.
  2. Create a blank TextEdit file with that filename and save it to a predetermined location. I would like the file to be a rich text document (which is the default type of document created in TextEdit when one clicks "File" → "New").
  3. Set the preset font size of that file to be 18.
  4. Open the file in TextEdit, with window bounds of {160, 10, 883, 639}. (Note that TextEdit will most likely not already be open when the AppleScript file is run.)
  5. Ensure that the blinking cursor is on the second line of the document, so that the user can immediately begin typing. (I hate typing on the very first line in TextEdit, from a visual standpoint, and have to first hit enter every time that I create a new file before I can begin typing.)

Here is what I have:

-- Getting file name from user:  
repeat
    set customFilename to the text returned of (display dialog "Save as:" with title "Do you want to create a new, blank TextEdit RTF document?" default answer "")



-- Ensuring that the user provides a name:  
    if customFilename is "" then
        beep
        display alert "The filename cannot be empty." message "Please enter a name to continue."
    else
        exit repeat
    end if
end repeat



-- Creating the desired file path:
set filePath to "/Users/Me/Desktop/"
set fullFilepath to filePath & customFilename & ".rtf"



-- Checking if the file already exists:
tell application "Finder"

    set formattedFullFilepath to POSIX path of fullFilepath 
    if exists formattedFullFilepath as POSIX file then
        tell current application
            display dialog "The file \"" & formattedFullFilepath & "\" already exists!" & "

" & "Do you want to overwrite the file?" buttons {"No", "Yes"} default button 1 with title "File Already Exists..." with icon caution

            if the button returned of the result is "No" then
                return
            end if
        end tell
    end if
end tell

That's where I am, at this point.

I'm not sure how exactly to approach the rest. I could create a new TextEdit document within TextEdit itself, and then save the file with the custom filename. Or I could create the RTF file outside of TextEdit, and then open the file with TextEdit.

Similarly, the AppleScript can either insert the blank line by keystroke after the file is opened, or the AppleScript can actually write the line to the file when the file is created.

And I have no idea how to set the preset font size for a specific document in AppleScript (without changing the application-wide default font size), or if it is even possible.

Best Answer

Having read your question, here is an example of how I would code it.


--  # The variables for the target file's fully qualified pathname and custom filename needs to be global as they are called from both the handlers and other code.

global theCustomRichTextFilePathname
global customFilename

--  # The createCustomRTFDocument handler contains a custom template for the target RTF document.

on createCustomRTFDocument()
    tell current application
        set customRTFDocumentTemplate to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»
        try
            set referenceNumber to open for access theCustomRichTextFilePathname with write permission
            write customRTFDocumentTemplate to referenceNumber
            close access referenceNumber
        on error eStr number eNum
            activate
            display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with title "File I/O Error..." with icon caution
            try
                close access referenceNumber
            end try
            return
        end try
    end tell
end createCustomRTFDocument

--  # The openDocument handler opens and set the bounds of the theCustomRichTextFilePathname document while placing the cursor on the second line.

on openDocument()
    try
        tell application "TextEdit"
            open file theCustomRichTextFilePathname
            activate
            tell application "System Events"
                set displayedName to get displayed name of file theCustomRichTextFilePathname
                if displayedName contains ".rtf" then
                    tell application "TextEdit"
                        set bounds of window (customFilename & ".rtf") to {160, 22, 883, 639}
                    end tell
                    key code 125
                else
                    tell application "TextEdit"
                        set bounds of window customFilename to {160, 22, 883, 639}
                    end tell
                    key code 125
                end if
            end tell
        end tell
    on error eStr number eNum
        activate
        display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with icon caution
        return
    end try
end openDocument

--  # Get the name for the RTF document, ensuring it is not blank.

repeat
    set customFilename to the text returned of (display dialog "Save as:" with title "Do you want to create a new, blank TextEdit RTF document?" default answer "")
    if customFilename is "" then
        beep
        display alert "The filename cannot be empty!" message "Please enter a name to continue..."
    else
        exit repeat
    end if
end repeat

--  # Concatenate the default location (the User's Desktop) with the chosen filename while adding the proper file extension.

set theCustomRichTextFilePathname to ((path to desktop) & customFilename & ".rtf") as string

--  # Check to see if the target file already exists. If it does not exist, create and open it. If it does exist, either open it or overwrite it and open it, based on decision made.

tell application "Finder"
    try
        if exists file theCustomRichTextFilePathname then
            tell current application
                display dialog "The file \"" & POSIX path of theCustomRichTextFilePathname & "\" already exists!" & return & return & "Do you want to overwrite the file?" & return & return & "If yes, the file will be placed in the Trash." buttons {"No", "Yes"} default button 1 with title "File Already Exists..." with icon caution
                if the button returned of result is "No" then
                    --  # The file already exists, chose not to overwrite it, just open the document.
                    my openDocument()
                else
                    --  # The file already exists, chose to overwrite it, then open the document.
                    tell application "Finder"
                        delete the file theCustomRichTextFilePathname
                    end tell
                    my createCustomRTFDocument()
                    my openDocument()
                end if
            end tell
        else
            --  # The file does not already exist. Create and open the document.
            tell current application
                my createCustomRTFDocument()
                my openDocument()
            end tell
        end if
    on error eStr number eNum
        activate
        display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with icon caution
        return
    end try
end tell

How to create the Custom RTF Document Template, customRTFDocumentTemplate, used in the on createCustomRTFDocument() handler:

In TextEdit create a new Rich Text document and set the font and size as desired, then add any default content, in this case a newline. With this done, press ⌘A to select all, then ⌘C to copy this information to the Clipboard.

Now in Script Editor use the following command to get the RTF class data from the Clipboard.

get the clipboard as «class RTF »

What is returned will be used as the Custom RTF Document Template by assigning it to a variable in the actual script, e.g.:

set customRTFDocumentTemplate to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»

Note that the above template has the default font, Helvetica, with size set to 18 and one blank line as its content. If you want a different font then Helvetica, set both the font and size before adding content, a blank line in this case, then use the info above to get is as RTF class data from the Clipboard.

Also note that in the on openDocument() handler, the bounds list is set to {160, 22, 883, 639} not {160, 10, 883, 639} as the second item in the bounds list should not be less then the height of the menu bar.