BUY THIS BOOK
Add to Cart

Print Book $24.95


Add to Cart

PDF $16.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £17.50

What is this?

Looking to Reprint or License this content?

AppleScript: The Missing Manual
AppleScript: The Missing Manual

By Adam Goldstein
Book Price: $24.95 USD
£17.50 GBP
PDF Price: $16.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Setting Up AppleScript
Although AppleScript is fast and free, perhaps the best part about it is that it gets installed right along with Mac OS X. You don't need to download any files, install any CDs, or configure any nasty system files to get AppleScript to work. In fact, you've got an AppleScript folder tucked inside your Applications folder, right this very moment.
Figure 1-1: The Applications AppleScript folder has everything you need to start writing your own scripts. Since you're going to be spending a lot of time here, it's a good idea to put this folder in your Dock.
If you don't have this folder, chances are you're not running Mac OS X Panther. See Section P.4.3.1 for instructions on how to upgrade to the latest version, Mac OS X Panther (version 10.3).
Whenever you install Mac OS X—or buy a new Mac—you'll find these five icons in your AppleScript folder:
  • Example Scripts is simply an alias (shortcut) to your Library Scripts folder. This folder contains more than 100 example scripts for you to run, examine, and edit (Section 1.1.1).
  • Folder Actions Setup turns on the powerful folder actions feature of OS X. Once it's on, you can make the Finder run your very own scripts whenever you open a folder, add an icon to a folder, remove an icon from a folder, and so on. (A full explanation of Folder Actions appears on Chapter 11.)
  • Install Script Menu adds a new icon to the right side of your menu bar. With this menu in place, you can easily run your favorite AppleScripts from any program you want (read on for details).
  • Remove Script Menu hides the menu that appears when you double-click Install Script Menu.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Script Menu
To get your first taste of AppleScript, double-click Install Script Menu. When you do so, a curled-parchment icon appears right in your menu bar. (This icon is a recurring theme in Mac OS X that means, roughly, "What you're looking at has something to do with AppleScript.") Simply click the menu bar icon once to display the Script Menu (Figure 1-1).
All the scripts that appear in the Script Menu come from the Library Scripts folder. And, as described on Section 1.1.16.1, that means you can add your own scripts to the Script Menu in addition to tweaking the existing ones.
You can run any script just by selecting its name from the appropriate submenu. The following sections provide a breakdown of what the scripts do.
Here, you'll find a single Import Addresses script, designed to move your contacts into Mac OS X's Address Book from other applications, such as Entourage, Outlook Express, Palm Desktop, Eudora, Claris Emailer, and Netscape. If you've got a lot of friends, this script saves you from having to re-enter all their names, phone numbers, and email addresses by hand.
The scripts in the Helper Scripts submenu (just above Import Addresses) are off-limits to mere mortals. If you try to run any of the Helper Scripts, Mac OS X simply tells you to use the Import Addresses script instead.
Figure 1-2: The Script Menu is your key to running AppleScripts from just about any program. However, if you're using a program with a lot of menus (Word or Photoshop, for example), that program may clip off the Script Menu. To move the Script Menu to a less clip-prone position, simply -drag its icon farther to the right.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with the Scripts You Have
As you'll quickly realize from using the Script Menu, your Mac is teeming with dozens of free, built-in scripts. You can run, rename, and organize these scripts, as described on the preceding pages.
But if you're just starting to learn AppleScript, these scripts can be lifesavers. Not only can you examine how the scripts work, but you can also make changes and see how they affect the scripts' behavior. Best of all, if you get stuck when writing a new AppleScript, you can copy some of the code from the Script Menu's scripts and paste that code right into your own script.
The first step in working with a script, of course, is opening it up. Fortunately, this is an easy process: just double-click the script in the Finder. The script opens in Script Editor, the all-purpose AppleScript program described in Chapter 2.
When you're just learning AppleScript, you might as well start by looking at a simple script. Double-click Library Scripts Navigation Scripts New Application Window.scpt, and Script Editor opens the script file in a new window (Figure 1-9).
Figure 1-10: If you've never seen an AppleScript before, you may be surprised at how simple the code looks. As you can probably guess from the commands in the window, this script simply opens the Applications folder in the Finder.
At this point, you can click the Run button to see what the script actually does (in this case, the script opens a new Finder window and takes you to the Applications folder).
The next step in working with a script, of course, is understanding how the script actually works. Some commands are self-evident, while others require you to examine a program's dictionary—its master command list (Section 3.2.2)—to understand exactly what's going on. Luckily, the commands in the New Applications Window script are all pretty simple:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Using Script Editor
If you're going to write and edit AppleScripts, you're going to need some sort of program to help you out. For that, Apple has graciously supplied you with the aptly named Script Editor program. Script Editor is AppleScript's bread and butter—the program you'll use for just about everything as you learn the language. It's a text editor, script runner, documentation viewer, and antifreeze solution, all rolled into one. And although there are other AppleScript editors available (listed on Sidebar 2.6), you'll be best off sticking with Script Editor for now—if only because it's free and included with your computer.
You can start Script Editor in several ways:
  • Double-click its icon in the Applications AppleScript folder.
    Since you're going to be using Script Editor a lot, you might even like to store its icon in the Dock or the Finder's Sidebar, where you'll have easy access at a moment's notice.
  • Open a script anywhere on your computer.
    You can drag a script from your Library Scripts folder to Script Editor's icon, for example.
  • In the Script Menu, choose Basics Open Script Editor.
    This is the best method if you're tight on screen space, because you don't have to open any new windows.
As you can see from Figure 2-1, Script Editor's window is fairly basic, especially when compared to something like Photoshop or Microsoft Word. Along the top of the window, you'll see a toolbar with four simple buttons (Record, Stop, Run, and Compile), with an area beneath for you to type in your script.
Figure 2-1: Script Editor windows have several important sections. The toolbar at the top lets you test your script out or stop it when it's running. The upper text box is where you enter your commands, while the lower text box lets you add comments that describe what the script does.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Script Editor Look
As you can see from Figure 2-1, Script Editor's window is fairly basic, especially when compared to something like Photoshop or Microsoft Word. Along the top of the window, you'll see a toolbar with four simple buttons (Record, Stop, Run, and Compile), with an area beneath for you to type in your script.
Figure 2-1: Script Editor windows have several important sections. The toolbar at the top lets you test your script out or stop it when it's running. The upper text box is where you enter your commands, while the lower text box lets you add comments that describe what the script does.
Unfortunately, Apple gave many of Script Editor's tools nerdy, programmer-y names (Event Log, anyone?). This section of the book, therefore, is meant to clear up what all the buttons and doodads in Script Editor's interface do.
The four buttons you see at the top of your window make up the toolbar. They're all modeled after the buttons on an old audiocassette recorder (alright, all of them except Compile, which actually comes from Xcode, one of Apple's programmer tools [Section 14.5]).
You can run the same toolbar actions by using the commands or keyboard shortcuts in Script Editor's Script menu.

Section 2.1.1.1: Record

Strange as it may sound, you don't need to write AppleScript commands yourself to get a working script. If you simply click the Record button, Script Editor tries its best to write out the appropriate AppleScript commands for you, based on what you're doing with your Mac. That's a much easier arrangement than, for example, hand-typing a series of complicated commands yourself.
Unfortunately, using this recording trick is rarely the best way to create AppleScripts. That's because recording is based on what's currently happening on screen, so you can't make "general scenario" scripts that perform
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Script Formats
When you double-click one of the scripts in, say, your Library Scripts Finder Scripts folder,Script Editor opens a new window containing the AppleScript code for that script. On the other hand, if you double-click one of the scripts in your Library Scripts ColorSync folder, the script itself runs rather than opening up in Script Editor.
That might seem like a minor difference, but it highlights an important fact of AppleScript life: scripts come in different formats. If you hope to make it through the jungle of AppleScript files available on the Web (Section C.1)—and, perhaps, to post your own scripts there—you first have to understand the different formats AppleScript supports.
You can open any AppleScript-supported file by dragging it onto Script Editor's icon in the Finder or Dock. To save a script in a different format, you use the File Format pop-up menu in the Save dialog box (Figure 2-5).
There are three main formats:
  • Script files, which get a .scpt file extension.
  • Applications, which get a .app file extension (just like regular Mac OS X programs).
  • Text documents, which get the lengthy .applescript file extension.
Two other minor formats—called bundles—are also available. Page Sidebar 2.5 explains how and when to use these.
The following sections give you a better idea of when you should save a script as a particular script type.
Figure 2-5: The File Format pop-up is available whenever you choose Save or Save As from Script Editor's File menu. The other options in this dialog box are available only for certain formats; you can set the Line Endings, for instance, only if you're saving the file as Text.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting Script Editor's Preferences
Now that you've been using Script Editor for a little while, the boring text coloring is probably starting to get to you. Or maybe you're just sick of reading your scripts in a 12-point font. No matter what your complaint, chances are Script Editor can make things better for you.
Start out by opening Script Editor Preferences ( -,). You'll see five buttons in the toolbar, each for a different aspect of Script Editor's behavior. Click the category you want to customize (Figure 2-8), and continue reading.
Figure 2-8: Script Editor's Preferences window. Click a toolbar button to jump right to that particular pane.
Fresh out of the box, your Mac comes with only one language you can use in Script Editor: AppleScript. That's why Script Editor automatically understands your AppleScript commands when you create a new script and click Run.
However, some people install other programming languages—like JavaScript—for use in Script Editor (Sidebar 3.2), and that's where the Default Language pop-up menu comes in. With this menu, you can select what language you want to use for all new scripts. (If you ever want to override this setting for a single script, just use the Navigation Bar [Sidebar 2.4].)
The three sections of the Editing pane allow you to customize how text appears in Script Editor's windows. The Line Wrap preferences, for example, let you set whether text that's too long for one line continues onto the next one (Wrap Lines on) or scrolls off the side of the window (Wrap Lines off). If you've turned Wrap Lines on, you can even set how many space-widths the overflowing lines are indented.
The Tabs section, on the other hand, let you choose whether your script should be indented at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Building a Script from Scratch
So far, you've been on a quick tour of all the AppleScript stuff that comes with Mac OS X. You've learned how to add the Script Menu to your menu bar, how to use Script Editor, and even how to tweak one of the Script Menu's scripts. Now, you'll finally break free from the limits of your built-in scripts and start creating your own AppleScripts from scratch.
When most people refer to "scripting," this is what they're talking about: writing a new script all by themselves. With Script Editor as your trusty tool, you can link commands in the order you prefer, making it possible to create totally customized scripts to deal with the tasks you perform every day.
Before you can write the next blockbuster AppleScript, though, you first need to learn the basics. That's what this chapter's for: teaching you how to create your first simple script from the ground up.
The example scripts from this chapter can be found on the AppleScript Examples CD (see Sidebar 2.1 for instructions).
Just as you can't surf the Web without a Web browser, you can't create AppleScripts without a script-editing program. The aptly named Script Editor (in your Applications AppleScript folder) is the simplest program for the job, but feel free to try any of the other editors listed on Sidebar 2.6.
Before you start diving into the following sections, the first thing you'll need to do is launch Script Editor (Chapter 2). With this blank scripting slate before you, it's possible to accomplish such neat tasks as:
  • Displaying a dialog box using a single line of code (see below)
  • Performing basic arithmetic (see the next page)
  • Getting the contents of your Clipboard (the place where Mac OS X stores information when you choose Edit Cut or Edit Copy [see the next page])
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Started
Just as you can't surf the Web without a Web browser, you can't create AppleScripts without a script-editing program. The aptly named Script Editor (in your Applications AppleScript folder) is the simplest program for the job, but feel free to try any of the other editors listed on Sidebar 2.6.
Before you start diving into the following sections, the first thing you'll need to do is launch Script Editor (Chapter 2). With this blank scripting slate before you, it's possible to accomplish such neat tasks as:
  • Displaying a dialog box using a single line of code (see below)
  • Performing basic arithmetic (see the next page)
  • Getting the contents of your Clipboard (the place where Mac OS X stores information when you choose Edit Cut or Edit Copy [see the next page])
But that's only the beginning. So strap on that beanie with the propeller on top, and get ready to write your first lines of AppleScript.
As you saw on Section 1.1.4, dialog boxes are the most common way for AppleScript to interact with you. That's because, on their own, scripts can't display complex interface elements like pop-up menus, checkboxes, or toolbars. As you're starting out in AppleScript, therefore, you'll use the display dialog command even more than you breathe.
Here's how:
  1. With Script Editor open, type the following command in the Script Field:
    display dialog "Hello!
    I'm your first AppleScript."
    As you type in the command, you'll notice it appears as a bunch of purple text. That's Script Editor's way of telling you that it hasn't checked your command for AppleScript compliance yet.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Commanding Other Programs
Unless you plan to display dialog boxes in Script Editor all day, you're probably feeling pretty constrained by AppleScript right now. Yeah, you can display cool stuff in your dialog boxes, but that won't be enough to automate your Mac.
Luckily, you can use AppleScript to do other things—and one of the most powerful is the ability to control other applications. This feature alone unlocks a world of possibilities:
  • Automate your favorite word processor, so you can save all unsaved documents with a single click (Section 5.7.3).
  • Apply color-correction settings automatically using Adobe Photoshop (Section 7.2.2).
  • Convert song files in iTunes automatically while you recline in your lounge chair (Section 8.1.4).
Before you can write any of those complicated scripts, however, you must learn the basics of program control. This section, therefore, introduces the basics of how to send commands to specific programs, rather than just to Mac OS X itself.
When you want to target a program with your commands, you have to let AppleScript know which program to talk to. For such purposes, the tell statement is your best friend.
Say you want the Finder to open your Home folder, so you can copy some files onto your desktop. To do this, enter these commands in Script Editor, then click Run:
tell application "Finder"
    activate
    open home
end tell
Everything after the tell command is directed at the program you specify—in this case, the Finder. The activate command brings the program forward, while the open home command tells the Finder to open a new Finder window and for your Home folder. Finally, once AppleScript reaches the end tell command, it lets the Finder off the hook and stops sending it commands.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Manipulating Text
Since the ancient days of DOS, text has always played an important role in computing. Even today, 20 years after the first Mac came out, every computer Apple ships comes with a keyboard. What's more, Mac OS X's Unix core is strictly based on text: preference files are in plain text, and the commands you issue in Terminal (Section 13.1) are all, well, text.
The importance of text isn't lost on AppleScript, though. From its dialog box capabilities to the Text Suite—a standard set of AppleScript keywords that deals with the details of words, characters, and paragraphs (Section 4.6.1)—AppleScript handles text the way Mac OS X does: simply and powerfully. For example, you can harness AppleScript's text mojo to do things like:
  • Add a word count feature to TextEdit (Section 4.6)
  • Shrink all the fonts in a document simultaneously (Section 4.7.2)
  • Type and run AppleScript commands in just about any program—not just Script Editor—using an application's Services menu
AppleScript's text features are quite powerful, but they're not always easy to learn—especially if you're reading Apple's geeky help files. Thankfully, you don't have to; just continue reading this chapter instead.
The example scripts from this chapter can be found on the AppleScript Examples CD (see Sidebar 2.1 for instructions).
In AppleScript, pieces of text are stored in a format called strings. A string can contain as many letters, numbers, spaces, and punctuation marks as you'd like. In AppleScript, strings are typically placed between double quotes, like so:
"Yam farmer"
"5504.45"
"What the *#@&?!"
However, you won't get much use out of strings unless you can store them for later use—rather than having to constantly recreate them. To store a string, you use the set command, like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
String Notation
In AppleScript, pieces of text are stored in a format called strings. A string can contain as many letters, numbers, spaces, and punctuation marks as you'd like. In AppleScript, strings are typically placed between double quotes, like so:
"Yam farmer"
"5504.45"
"What the *#@&?!"
However, you won't get much use out of strings unless you can store them for later use—rather than having to constantly recreate them. To store a string, you use the set command, like this:
set welcomeMessage to "Take your shoes off before entering the building."
In the previous example, welcomeMessage is a variable: a name given to a stored value (Sidebar 4.1). Variables come in handy when you have a long string you want to recall later. Rather than having to type in all that text each and every time you want to use it, you just substitute the variable name anywhere you want the string to appear, like this:
set welcomeMessage to "Take your shoes off before entering the building."
display dialog welcomeMessage
            
In the previous example, AppleScript notices the welcomeMessage variable that follows the display dialog command, and substitutes in the value that you set on the previous line. That's why running the previous script would display a dialog box that says "Take your shoes off before entering the building."
When using variables, it's important to remember that you must set a variable before you can access it later on in your script. If you switched the two lines in the previous script, for example, AppleScript would display an error, because you would be referring to a variable (with display dialog) before you told AppleScript what the variable should contain (with set).
AppleScript's set-before-you-access requirement leads many programmers to set all the variables that a script will use at the very beginning of the script. Under this arrangement, if you refer to a variable later in your script, you can be sure that it's already been defined at the script's start, thereby avoiding "variable not defined" errors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Text Back from Dialog Boxes
So far, all you've done with dialog boxes is display information. That won't help you much if you want to get feedback to use in your scripts, though. Luckily, the display dialog command supports an extra option—default answer—which lets you type text into your dialog boxes as well. Try running this script:
display dialog "Enter your name:" default answer "Sylvester"
A dialog box appears on screen, with a text-entry field inside (Figure 4-1).
Still, even though you can enter text in your dialog boxes with the default answer option, you can't capture the text you entered and reuse it elsewhere in the script.
Or so you might think.
Figure 4-1: The default answer option is all you need to add a text field to a dialog box. Whatever you put in your script after default answer will be what appears in this dialog box at first (top), although you're free to delete the text and enter anything you'd like instead (bottom).
Luckily, using the power of variables, you can store the response to your dialog boxes for later use. Try running this script:
set userResponse to the text returned of (display dialog "Enter your name:" ¬
    default answer "Sylvester")
display dialog userResponse
            
The ¬ symbol, shown in the previous example, simply means "this command continues on the next line." This line-continuation symbol has no bearing on how AppleScript interprets your script, so you could theoretically retype the previous script as follows, and it would work exactly the same way:
set ¬
userResponse ¬
to the text returned ¬
of (display dialog ¬
"Enter your name:" ¬
default answer "Sylvester")
display dialog userResponse
In this book, scripts employ the line-continuation symbol because certain commands are simply too long to fit within the pages' margins. When entering these commands yourself, you can either type the ¬ symbol as written (by pressing Option-Return) or omit the ¬ symbol altogether and instead just type broken-up commands on a single line.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Linking Strings Together
In the previous script, the second command simply spits back whatever text is in the dialog box's text field when you press OK. It would be much cooler, however, if the script could give you a personalized greeting—something like Figure 4-2.
To achieve this feat of textual impressiveness, you have to use a feature known as concatenation— linking multiple strings together into one. In AppleScript, the way you concatenate strings is with an ampersand (& ), which tells AppleScript to "put together the strings on my left and right." Here's what the improved script would look like:
set userResponse to the text returned of (display dialog "Enter your name:" ¬
    default answer "Sylvester")
set theGreeting to "Hey, " & userResponse & "!"
display dialog theGreeting
            
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Multiline Strings
If you've spent any time working in a word processing program like TextEdit or Microsoft Word, you already know that text often spans multiple lines. Unlike typewriters from days of old, you don't have to hit the Return key when you reach the end of a line. Instead, the text just wraps around to the next line, and you continue typing until you reach the end of a paragraph.
There are, however, certain times when you might like to break text up onto multiple lines—such as typing your mailing address at the top of a letter—and for that, the trusty Return key is right there by your side. But what if you want to use such multiline strings in AppleScript, so you can display a dialog box containing a friend's address, for example?
Thankfully, AppleScript supports multiple-line strings as well, but you'll need to enlist some help from escape sequences. Escape sequences are little chunks of slashes and letters that tell AppleScript, "Please insert a special symbol here."
To insert a newline symbol in a string—thus knocking text onto the next line—you use the \n escape sequence. For example, if you ran the following script, you'd see the dialog box shown in Figure 4-3:
set multiLiner to "To whom it may concern,\nI want my money back.\nThanks."
display dialog multiLiner
If you find the \n sequence too geeky, you can instead just type Return in the middle of a string. For example, you could rewrite the above script as follows:
set multiLiner to "To whom it may concern,
I want my money back.
Thanks"
display dialog multiLiner
and it would work exactly the same way. Still, you'll often see older scripts use the \n sequence, so remember that it works the same way.
Figure 4-3: Using the escape sequence \n (which stands for "new line"), you can easily make strings that run multiple lines.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scripting TextEdit
TextEdit is a free word processor installed on your Mac, and it is—in many ways—the 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 lengthy—and quite detailed—dictionary. Take the time to peruse all the scripting suites now, so you can get a feel for what AppleScript and TextEdit can do together.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Word Count
If there's one feature that TextEdit lacks over its competitors, it's the ability to count the number of words in a document. With all the powerful searching, typographical, and speech tools TextEdit has, it almost makes you wonder whether an Apple programmer was just sick the day he was supposed to program that feature.
Thankfully, AppleScript comes to your aid—again. You can write a short script that not only counts the number of words in your document but also counts the paragraphs and even the number of characters in your document—great for tricking people into thinking you've written a lot for your term paper.
The key to all this text-based power is the Text Suite, a section of many programs' dictionaries that deals exclusively with the nitty-gritty of text (like counting individual characters). You'll find the Text Suite in the dictionaries of professional programs like Microsoft Word (Section 4.7)—but more immediately, you'll also find the Text Suite in TextEdit's dictionary. By employing the Text Suite as described in the following pages, you can write a script to count the number of words in any TextEdit document
If you open TextEdit's dictionary and browse the lefthand pane, you'll find that the Text Suite already includes entries for word, character, and paragraph. These are the fundamental nouns (or classes) of AppleScript's text handling. By using those keywords as follows, you can create a script to add a basic word count feature to TextEdit:
tell application "TextEdit"
    activate
    --Count the characters:
    set allCharacters to every character of the front document
    set numberOfCharacters to (count allCharacters)
    set characterText to "Characters: " & numberOfCharacters
    --Count the words:
    set allWords to every word of the front document
    set numberOfWords to (count allWords)
    set wordText to "Words: " & numberOfWords
    --Count the paragraphs:
    set allParagraphs to every paragraph of the front document
    set numberOfParagraphs to (count allParagraphs)
    set paragraphText to "Paragraphs: " & numberOfParagraphs
    --Assemble the text for the dialog box:
    set dialogText to characterText & return & wordText & return ¬
        & paragraphText
    display dialog dialogText
end tell
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Commanding Microsoft Word
If TextEdit were a sardine, Microsoft Word would be a blue whale. Mentioning the two together invites all sorts of comparisons: TextEdit takes up 5 MB, while Word takes up 20; TextEdit has six menus, Word has a dozen. The two programs, in fact, are illustrative of their respective companies' approaches: TextEdit is straightforward and simple, while Word is complex and feature-packed.
Still, Word's AppleScript support puts TextEdit to shame. Word includes the standard Text Suite (Section 4.6.1) but adds more than 50 commands of its own.
Many of Word's cool AppleScript commands are available only in the most recent release: Word 2004. Therefore, to ensure that the scripts in this chapter—and the rest of this book—work properly for you, you'd be best off upgrading to Word 2004 for the sake of compatibility.
In Section 4.6.1, you created a script that counted the number of characters, words, and paragraphs in an open TextEdit document. Of course, Word already has a word count feature (Tools Word Count). Still, it's a good exercise to adapt your existing TextEdit script for use with Word, to get a feel for the differences in what it's like to script the two programs.
The first step in adapting a TextEdit script is to replace the tell statement with one that directs Word instead of TextEdit.
                  tell application "Microsoft Word"
    activate
    . . .
end tell
You must use the phrase "Microsoft Word" in AppleScript; "Word" won't suffice.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running Scripts from Text
So far in this chapter, you've created a series of scripts that make new text. In this section, the roles are reversed: you'll create new text and have it run scripts for you.
The key to this is the Services menu, which you can find inside any application menu (the bolded menu, directly to the right of the Apple menu in the menu bar). For example, if you're in TextEdit, you access the AppleScript-related commands by choosing TextEdit Services Script Editor (Figure 4-8).
Services are a way of accessing one program's features while inside another program. For example, if someone sends you an email containing a short URL (one that doesn't have the http:// in front of it, like www.oreilly.com), you can select the URL with the mouse and then go to Mail Services Open URL.
After selecting Open URL from the Services menu, your Web browser jumps into action and opens that Web page for you. Pretty slick, huh?
Figure 4-8: The three AppleScript services. Unfortunately, only one has a keyboard combination, so you'll have to run the other two the old fashioned way: with the mouse.
Running one of these Services commands is a simple process:
  1. Type some AppleScript commands in the current program, then select them.
    If you're working in TextEdit, for example, you could type display dialog "Hello!" and then select it.
  2. Choose the AppleScript service you want to run from the menu bar.
The Services menu doesn't work properly in certain programs that haven't been completely updated for Mac OS X. Microsoft Word, for example, won't let you use the Services menu. On the other hand, TextEdit—and most other programs written in the last few years—work just fine with Services.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Controlling Files
Most people have a love-hate relationship with their computer. Sure, your Mac is a great tool for when you want to edit images or video, send and receive email, or play Halo. But your computer also serves as a digital file cabinet: a place where you can create and store files, move them around, organize them in folders, trash them when they're no longer needed, and copy them to another disk or computer on the fly.
Files, of course, are nothing more than individual packages of information that you keep on your hard drive. But for all the filing tasks they perform, most computer users tend to handle files manually: drag this file here, create a new folder there, and so on. After a while, these mundane tasks are what make people start to hate their computers.
If you're sick of dealing with your files one at a time—and taking up half your day in the process—there's no better tool in your arsenal than AppleScript. By commanding the Finder, AppleScript lets you:
  • Move all the files off your desktop in one fell swoop (Section 5.3.1.3)
  • Back up an important folder to a separate hard drive, just in case your computer dies (Section 5.4.1)
  • Rename all the files in a folder—without having to type their new names individually (Section 6.4.1)
For these jobs and more, AppleScript can save you annoyance, tedium, and—most of all—time.
The example scripts from this chapter can be found on the AppleScript Examples CD (see Sidebar 2.1 for instructions).
The one thing AppleScript can't save you from is the fact that files are essentially geeky things. Mac OS X's Unix heritage, while great news for programmers, also means that old Mac fans have to adapt to a few new file conventions—how to name files, what programs to open them with, and so on. Therefore, before you jump headfirst into controlling files with AppleScript, there are a few things you should know:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File Path Boot Camp
The one thing AppleScript can't save you from is the fact that files are essentially geeky things. Mac OS X's Unix heritage, while great news for programmers, also means that old Mac fans have to adapt to a few new file conventions—how to name files, what programs to open them with, and so on. Therefore, before you jump headfirst into controlling files with AppleScript, there are a few things you should know:
  • In Mac OS X, files should always have a file extension. A file extension is a short abbreviation added after a period in a file name. Microsoft Word files, for example, end in .doc, while sound files often end in .mp3 or .aiff.
    To Mac OS X (and Windows, for that matter) a file extension reveals what kind of information a file holds. In many cases, a file extension also tells Mac OS X which program should open a file: .doc files open in Microsoft Word, while .psd files open in Photoshop. (Of course, certain types of files can open in several different programs; .jpg files, for example, can open in just about any image-viewing program on the planet.)
    As a general rule, folders should not have file extensions. The exceptions are bundles—little folders that masquerade as files (Sidebar 2.5), like the .key files that Keynote produces.
    To see what's inside in a bundle, Control-click the bundle in the Finder and select Show Package Contents from the shortcut menu. In the new window that appears, you can sift through the files that comprise the package, discovering, for example, that Keynote "files" are actually made up of dozens of smaller files.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Displaying Folders
When you're working on a bunch of related documents at once, you might want to jump quickly to their folder in the Finder. Normally, of course, you'd switch to the Finder and navigate through your hard drive to get to the correct folder. Or perhaps, if you're a power user, you've already put the folder in the Finder's Sidebar for easy access. Either way, though, you have to switch to the Finder and open a new window, which is a massive waste of time.
Why go through all those steps when you can get AppleScript to do it for you? Using AppleScript, you can save a folder-opening script as an application (Section 2.2.2) and place the script on the Dock for easy access. From then on, all you'll need to do is click the script's icon in the Dock, and a Finder window pops open and takes you right to the folder you want.
"But wait," you say, "I could just put the folder's icon on the Dock, no script required." You are, of course, correct—and your method is what most people use for accessing commonly used folders. The trouble is, when you click a folder's icon on the Dock, you never know where the folder's window will open onscreen, or whether it'll be in List, Column, or Icon view. Plus, a folder icon on the Dock can open only one specific folder, whereas a script can open multiple folders at once—like your Music and Pictures folders—as shown the following example:
tell application "Finder"
    activate
    open the folder "Users:yourUsername:Music"
    open the folder "Users:yourUsername:Pictures"
end tell
Again, just save this script as an application (Section 2.2.2), and then drag the script's icon to your Dock. From then on, you'll be just one click away from opening two folders at once.
Of course, if you have more than two folders you'd like to open simultaneously, you can insert extra open commands in the previous script for those folders as well.
As you've seen, there's more than one way to open a folder from AppleScript. If you want to open your Applications folder, for example, you'd have five separate choices:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moving Files Around
Being able to display your files is useful, but it's only half of what the Finder can do. The other half, of course, is to move your files—putting them in a new folder, deleting them, and so on. With AppleScript, you can automate these actions and more.
The simplest action you can perform on a file is dragging it from one folder (or disk) to another. With AppleScript, it's also one of the simplest actions you can control in the Finder.
The key to this trick is the move command. It's part of the Finder's Standard Suite (Section 3.2.3), so it's a pretty common command. And, as the Finder's dictionary explains, the move command follows this simple structure:
tell application "Finder"
    move someItem to somePlace
end tell
In this example, someItem can be either a single item or a list of items. That makes the move command perfect for transferring whole clusters of files (or folders) in a single step. (See Chapter 6 for the lowdown on lists.)
And also, if you use the move command to transfer files from one disk to another, AppleScript (like the Finder) assumes that you mean to copy the files. If you want, you can then use the delete command (Section 5.5) to erase the files from the original disk.
Now, if you're the sort of person who always saves downloads and email attachments to your desktop, you've probably noticed your desktop getting pretty full. You might have so many icons that you've had to shrink them down (View Show View Options). Or perhaps your desktop is so cluttered that icons have started overlapping each other, obscuring all the important stuff you keep there.
No matter what the issue, AppleScript can help you clean up your desktop. With one fell swoop, a script can sweep up all the files and folders there, and stash them somewhere less intrusive.
You can use the move command for any number of other jobs, too: transferring sounds from an old folder to the Mac OS X-standard Music folder; moving downloaded files to a special Just Downloaded folder; or even sending files to another computer on your network (Chapter 9).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Backing Up Files
Content preview·Buy PDF of this chapter