Section 4.5. Scripting TextEdit


4.5. Scripting TextEdit

TextEdit is a free word processor installed on your Mac, and it isin many waysthe ideal Mac OS X program. TextEdit supports drag-and-dropped text and files, allows complex typographical control, and can check your spelling automatically as you type. Best of all, you can control TextEdit with AppleScript, opening up a whole new world of possibilities beyond just typing:

  • Create a new TextEdit document with a single click, rather than having to mouse up to File New (Section 4.5.1).

  • Insert the current date into a new TextEdit document automatically (Section 4.5.2).

  • Add a word count feature to TextEdit, so you can brag to your friends about the length of your business memos (Section 4.6).

To understand TextEdit's scripting abilities, you first have to open its dictionary to see the list of commands it can accept (Section 3.2.2). In Script Editor, choose File Open Dictionary (Shift--O), scroll down to TextEdit, and click Open. As you can see from the left pane of Figure 4-4, TextEdit has a rather lengthyand quite detaileddictionary. Take the time to peruse all the scripting suites now, so you can get a feel for what AppleScript and TextEdit can do together.

Power Users' Clinic
Extreme Dialog Boxes

As you already know, dialog boxes play a critical role in how you interact with your scripts. Thus far, however, you've only used one extra option in your dialog boxes: default answer (Section 4.2). Although that's useful for getting user responses, there are far more options you can tack onto the end of your display dialog commands to make them truly powerful user feedback tools:

  • The buttons option lets you specify which (and how many) buttons you want to appear at the bottom of the dialog box. You can specify a list of between one and three buttons of your choice. (If you don't specify any buttons, you'll end up with the usual Cancel and OK buttons.) The following example displays a dialog box with Nope and Yep for buttons:

display dialog "Got Milk?" buttons ¬     {"Nope", "Yep"}

  • The default button option sets the button that pulses blue in your dialog box. The default button is also the button that you can press Return or Enter to select. (If you don't specify a default button, OK is used.) For example, if you wanted to designate the Yep button as the default, you could write this:

display dialog "Got Milk?" buttons ¬     {"Nope", "Yep"} default button 2

  • The with icon option lets you specify a small imageeither stop (a stop sign), note (a cartoony face with a bubble coming out of its mouth), or caution (a yield sign)to appear inside your dialog box. For a quick dose of graphical fun, try this:

display dialog "Got Milk?" buttons ¬     {"Nope", "Yep"} ¬     default button 2 with icon note

  • The giving up after X option lets you hide the dialog box if there's no response after X number of seconds. To keep your dialog box onscreen for a maximum of 3 seconds, you would type this:

display dialog "Got Milk?" buttons {"Nope", "Yep"} ¬     default button 2 with icon note ¬     giving up after 3

(Keep in mind that you can add as many or as few of these options as you'd like. You could specify an icon, for example, but decide not to use any custom buttons.)

There's more to dialog boxes than just displaying information, though. If you insert the phrase text returned of or button returned of before the display dialog command, you can have your script figure out what text you typedor what button you clickedwhen the dialog box was onscreen. To store the clicked button in a variable called dialogResponse, you could type this:

set dialogResponse to the button ¬ returned of (display dialog "Got Milk?" ¬ buttons {"Nope", "Yep"})

Note that you have to surround the entire display dialog command in parentheses, or else AppleScript will throw a fit.

Finally, if you want a dialog box to appear on top of every running program, you should direct your command at the SystemUIServer program, like this:

tell application "SystemUIServer"     activate     display dialog ¬         "Your computer will crash ¬         in 4 seconds." end tell

Regardless of what program is running or how many programs you have open, this dialog box will appear in front of all of them. (Of course, your computer won't crash if you run that AppleScriptit's just a silly text message.)


4.5.1. Create a New TextEdit Document

Since you need a document to do anything useful in TextEdit, you might as well learn how to create a new document to hold that text. The trouble is, there's no create command in TextEdit's dictionary for making a new document.

This sort of dilemma, unfortunately, is fairly common in AppleScript. To find a command that does what you want, you have to look for synonyms of "create" instead: generate, produce, andaha!make. Once you find a synonym that's listed in the dictionary, just click it to read its definition in the right pane (Figure 4-4).

Figure 4-4. When you select a specific command (make, in this case) Script Editor shows the command in blue in the right pane. All the indented pieces below the command are additions you can append to the command. Optional additions (with properties, with data, and at) are in brackets, while required additions (new) aren't surrounded with brackets.


When you read the entry for make, you'll find that it has only one required addition: new. In other words, any command you write has to say make new <something>. Now the problem is, what should you put in place of something?

As it turns out, TextEdit's dictionary can help you find this bit of information, too. If you scroll through the Classes lists on the left, you'll come across a few nouns (Sidebar 3.4): character, paragraph, and word, for example. Finally, at the very bottom of the TextEdit Suite, you'll come across the term you wantdocumentwhich lets you create a new file. Now you have all the information you need to write your script:

tell application "TextEdit"     activate     make new document at the front end tell

The at the front portion of this script tells TextEdit where to place the new document window (in this case, TextEdit brings the new document window in front of any other TextEdit windows you have open). If you didn't have that little snippet, TextEdit would get confused by the plain make new document command and would show you an error dialog box, because it wouldn't know where to place the new window.

4.5.2. Adding Text to a New Document

Of course, there's nothing the previous script does that you can't do yourself by choosing File New. What can set your script apart, however, is automatically adding text to your new documentwhich is particularly helpful when you're typing a letter and want to insert the date at the beginning, for example.

The key to modifying your script like this, again, is the document entry in TextEdit's dictionary. If you look under the Properties heading in the right-side pane, you'll find the keyword text, which is describedquite creativelyas "the text of the document." This is precisely the property you should use to insert a string into your new TextEdit document:

If you look carefully in TextEdit's dictionary, there are actually two entries for document. The first entry, in the Standard Suite, simply represents a generic Mac OS X document. The second entry, in the TextEdit suite, represents TextEdit's personal kind of document. You can safely use properties from either entry when sending AppleScript commands to TextEdit documents.

tell application "TextEdit"     activate     make new document at the front     set dateString to "Created: " & current date     set the text of the front document to dateString end tell

Here you added two new lines of code to the AppleScript (both are marked in bold):

  • In the first new command, you create the dateString variable. This variable concatenates "Created: " and the current date command, resulting in a string something like "Created Wednesday, January 12, 2004 2:29:15 PM."

  • The second line tells TextEdit to insert the text from the dateString variable into the front document. This is where the text property comes into play. By telling your newly created document to set its text property to a particular string (in this case, the current date), you effectively insert that string into the document.

When you run this script, therefore, TextEdit obediently opens, creates a new document, and then adds a line for the current date.

4.5.3. Adding Formatting

Now you're getting somewhere. There are only two minor issues left with your script:

  • It doesn't insert a new line after the date.

  • It doesn't format the date in a different font and size than the rest of the document.

Once you clear these issues up, the script will be quite useful for making new documentslike business letterswith the date already inserted.

4.5.3.1 Inserting a new line after the date

To place a new line after the date, you have to modify the dateString variable in your script. Therefore, change the following line:

set dateString to "Created: " & (current date)

to:

set dateString to "Created: " & (current date) & return

If you'd like, you can access specific properties of the current date command from your script. For example, if you want to insert only the current timenot the entire dateyou could rewrite the previous command like this:

set dateString to "Created: " & time string of (current date) & return

Simply typing & return is enough to append a new line to your text, and thereby to insert a new line in TextEdit.

Using return accomplishes the same thing as the more foreign-looking \r escape sequence (Table 4-1)that is, it inserts a new line.

4.5.3.2 Changing the font and size

Finally, to change the font and size of your text, you have to make AppleScript set the appropriately named font and size properties of your TextEdit document. The following, therefore, is what your final script should look like:

tell application "TextEdit"     activate     make new document at the front     set dateString to "Created: " & (current date) & return     set the text of the front document to dateString     set the font of the first paragraph of the front document to "Zapfino"     set the size of the first paragraph of the front document to 14     You can change the font and size to anything you want end tell

When you run the script, you'll end up with a document that looks like Figure 4-5.

At this point, you have a fully functional script. What now?

If you're content to run your script from Script Editor for the rest of your life, go take a hot baththere's nothing left for you to do. On the other hand, if you want to run your script from elsewhere on your Mac, try one of the following tricks:

  • Save your script for use in the Script Menu. In Script Editor, choose File Save, type whatever name you want for the script (like "DateDoc"), and then navigate to the Library Scripts folder. Save your script in one of the subfolders here, and you'll be able to run the script anytime from the menu bar, using the system-wide Script Menu described on Section 1.1.

Before you click Save, make sure the File Format is set to Script (Section 2.2.1).

  • Save your script as a double-clickable program. In Script Editor, choose File Save As. For the File Format, choose Application, and save the script somewhere on your hard drive. When you double-click this new application in the Finder, Mac OS X runs your code (Section 2.2.2).

  • Put your script in the Dock. This option requires you to complete the previous trick first. Once you've done so, navigate to your new application in the Finder, and simply drag it into the right side of the Dock. Whenever you want to run your code from now on, just click the Dock icon.

Of course, you can perform these three tricks with any script you havenot just this TextEdit script.

Figure 4-5. Your own convenient business-letter starter. If you'd like, you can modify the script so it automatically adds "to whom it may concern," or some similarly business-sounding phrase to your document.




AppleScript. The Missing Manual
AppleScript: The Missing Manual
ISBN: 0596008503
EAN: 2147483647
Year: 2003
Pages: 150

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net