3

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.

3 Answers 3

1

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.

9
  • user3439894 to the rescue! Flawless! Feb 1, 2017 at 1:01
  • @rubik's sphere, I wouldn't say it flawless but thanks, however I've modified the on openDocument() handler in AppleScript code to handle whether or not the extension is hidden. The file should be created with it not hidden however if it gets hidden the mod I made to the handler accounts for it. Note that I could have just said set bounds of front window to {...} but I wrote it this way so it only acts on the named window so if there is by chance some error, it's not going to move and resize another TextEdit window that may be open at the same time. Feb 1, 2017 at 3:16
  • On the first point, excellent thinking. On the second point, I concur, the new way is superior; I was actually having some issues with the bounds not always working properly the old way. Feb 1, 2017 at 3:25
  • @rubik's sphere, I was missing a return statement in the on createCustomRTFDocument() handler, so you should update your working code. Also the «data RTF ... » assigned to customRTFDocumentTemplate is just a working example and you should replace it with «data RTF ... » created from your system and why I gave instructions on how to get that info. Feb 1, 2017 at 16:58
  • I know that this is unrelated, but do you know how I can use a variable in the set customRTFDocumentTemplate to «data RTF 7B5C72» statement (I had to truncate the statement in this comment because of the character limit)? I've tried: set myVariable to "7B5C72" followed by set customRTFDocumentTemplate to «data RTF myVariable». But it does not work. Feb 7, 2017 at 6:08
0

I've taken a different approach aside from the file check. It took me quite a while to figure out how to create the rtf file correctly:

repeat
    set filename to (display dialog "Here goes your file name." default answer ("") as string)'s text returned
    if filename is "" then
        beep
        display alert "The filename cannot be empty." message "Please enter a name to continue."
    else
        exit repeat
    end if
end repeat

set filepath to POSIX path of ((path to home folder)) & "Desktop/" & filename & ".rtf"

tell application "Finder"
    if exists filepath as POSIX file then
        tell current application
            display dialog "The file \"" & filepath & "\" 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

do shell script "cat <<EOF >> " & filepath & "
{\\rtf1\\ansi\\ansicpg1252\\cocoartf1504\\cocoasubrtf820
{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;}
{\\colortbl;\\red255\\green255\\blue255;}
{\\*\\expandedcolortbl;;}
\\paperw11900\\paperh16840\\margl1440\\margr1440\\vieww12600\\viewh7800\\viewkind0
\\pard\\tx566\\tx1133\\tx1700\\tx2267\\tx2834\\tx3401\\tx3968\\tx4535\\tx5102\\tx5669\\tx6236\\tx6803\\pardirnatural\\partightenfactor0

\\f0\\fs36 \\cf0 \\\\
}
EOF"

do shell script "head -n 9 r" & filename & ".rtf" & " >> " & filename & ".rtf" & filepath & " | cut -d ' ' -f 1"
do shell script "open " & filepath
tell application "TextEdit" to activate
tell application "System Events" to keystroke (key code 125)

Happy writing!

8
  • It works great. I found a minor issue, though. If the user supplies a name that contains a space, the AppleScript will give an error. So, you have to add set filepath to quoted form of filepath in your code to fix this. Also, if TextEdit does not have the black dot underneath its logo in the Dock, about 1 in every 10 times that I run your script, the cursor is not moved to the second line. Instead, as the file opens, I hear a beep and the cursor remains on the first line. Do you think that the code should contain a delay above the final line, to prevent this issue? Jan 29, 2017 at 5:25
  • Also, can you modify your code so that the TextEdit window that is opened has bounds of {160, 10, 883, 639}? Is tell application "TextEdit" to set bounds of front window to {160, 10, 883, 639} as the final line the best way to do this? Thank you. Jan 29, 2017 at 5:45
  • @oa-, Aside from the fact that it's malformed, just what exactly is do shell script "head -n 9 r" & filename & ".rtf" & " >> " & filename & ".rtf" & filepath & " | cut -d ' ' -f 1" supposed to be doing!? Why does it even need to be a part of the script? Jan 31, 2017 at 20:00
  • @rubik'ssphere Thanks for the hint regarding the file name. Yes, changing the delay to 2 or 3 seconds should fix it.
    – oa-
    Feb 1, 2017 at 9:25
  • @rubik'ssphere Yes, setting the bounds with your code seems alright to me.
    – oa-
    Feb 1, 2017 at 9:25
0

While TextEdit is, in general, a decent app, it often frustrates me and one of the major pain points is the simple act of setting a font size automatically like this — especially when the app comes with the ability to set defaults for new documents. And it's even worse in that the mac has stationery (which probably goes as far back as Applescript does) which would seem to be just right for this type of task.

Anyway, while this question is long since asked and answered, its subject is one that I've often been frustrated by so here is another kick at the can, with brevity being its key feature. It works in Sierra but apparently not so much in Catalina.

use scripting additions
set rdat to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»
tell application "TextEdit"
    set fs to (path to desktop) as text
    set fn to choose file name default location alias fs -- include .rtf extension
    set ndo to make new document with properties {text:rdat}
    set bounds of window 1 to {160, 22, 883, 639}
    save ndo in fn without replacing    
end tell
tell application "Finder" to open fn
delay 0.5
tell application "TextEdit"
    set last paragraph of document 1 to linefeed
end tell

In a nutshell, you enter a filename and a document with that name and a pre-sized paragraph is created, then the bounds are set and it is saved, closed, re-opened.

Notes: Using save like this will alert you when a file with that name already exists. Including the file extension will set the document type to rich text. 'Setting' text can provide a method of setting the insertion point. Unfortunately, TextEdit has some issues when setting formatting this way and closing/re-opening is the only way I know to get around it. I borrowed the 'data rtf' here from user3439894's answer.

2
  • JSYK... In macOS Catalina, your script errors with error "Finder got an error: Handler can’t handle objects of this class." number -10010 -- Also, while the default format of a TextEdit document is Rich text, nonetheless, many uses set it to Plain text, and when set to Plain text your script creates a Plain text document, not a Rich text document as requested by the OP. My script creates a Rich text document regardless of the format preference of TextEdit. Jun 19, 2021 at 1:09
  • I default to plain text myself, which is why this functionality is interesting to me. But when I do this in Sierra, it creates a rich text document (based upon the filename extension) but it needs to refresh, which happens with the close/open. It seems weird that the Finder can't open a file. Do you often see that error?
    – Mockman
    Jun 19, 2021 at 1:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .