BUY THIS BOOK
Add to Cart

Print Book $39.99


Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £28.50

What is this?

Looking to Reprint or License this content?


AppleScript: The Definitive Guide
AppleScript: The Definitive Guide, Second Edition Scripting and Automating Your Mac

By Matt Neuburg
Book Price: $39.99 USD
£28.50 GBP
PDF Price: $31.99

Cover | Table of Contents


Table of Contents

Chapter 1: Why to Use AppleScript
If you've never used AppleScript before, you're probably in need of motivation as much as information. You'd like to know: "What is AppleScript?" You'd also like to know: "And why should I care, anyway?"
Those are good questions, and they are best answered by a brief explanation of what AppleScript is for. Therefore, this first chapter classifies the main uses of AppleScript, along with some examples.
By presenting AppleScript in action, in some typical real-life contexts, I hope to inspire you to imagine how you might use AppleScript in your own life. AppleScript is a big subject, and your best incentive to press ahead is a vision of some task you actually want to accomplish with it. At the same time, you'll have a far easier, more enjoyable experience of AppleScript if your aims are consonant with its nature and abilities.
In this chapter, the examples are not intended for you to run on your own computer. This is real-life code that works on my machine, but is not expected to run elsewhere. Nor are you expected to understand the code at this point. I'm just showing it to you for purposes of illustration, so glance over it and move on! When you've read more of the book and have learned some AppleScript, you'll understand how to adapt these examples to your own purposes.
Consider the many and various applications on your computer, and how you typically make them do things. With your hands, you choose menu items, click buttons, and generally wield the mouse and keyboard in the usual way. You also use applications as a source of information; you typically get this information by reading it off the screen, and you can communicate information from one application to another by copying and pasting. Mediating between your hands, your eyes, and the application is your brain: as your eyes get information from the application, your brain decides what to do next, and instructs your hands accordingly.
With AppleScript, you make applications do things programmatically. An AppleScript program has the power to give commands to the application, taking the place of your hands on the mouse and keyboard, and it has the power to ask the application questions, taking the place of your eyes reading the screen; the program itself makes the decisions about what to do next, thus taking the place of your brain. Thus, AppleScript lets you
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 Nature and Purpose of AppleScript
Consider the many and various applications on your computer, and how you typically make them do things. With your hands, you choose menu items, click buttons, and generally wield the mouse and keyboard in the usual way. You also use applications as a source of information; you typically get this information by reading it off the screen, and you can communicate information from one application to another by copying and pasting. Mediating between your hands, your eyes, and the application is your brain: as your eyes get information from the application, your brain decides what to do next, and instructs your hands accordingly.
With AppleScript, you make applications do things programmatically. An AppleScript program has the power to give commands to the application, taking the place of your hands on the mouse and keyboard, and it has the power to ask the application questions, taking the place of your eyes reading the screen; the program itself makes the decisions about what to do next, thus taking the place of your brain. Thus, AppleScript lets you automate the sorts of things you're accustomed to making applications do manually.
Why is that a good thing? For the same reason that any automation is good. AppleScript performs the same tasks you could perform manually, but it performs them faster, more accurately, and without your direct involvement—you needn't even be sitting at the computer. Some tasks, when performed manually, are tedious or repetitive or error-prone; it's downright annoying for you to have to perform them, whereas the computer never gets bored and never makes a mistake in calculation, and (let's face it) can perform them better than you.
For example, suppose you've got a folder full of image files and you want to change their names in a systematic way to image01.jpg, image02.jpg, and so forth. It isn't as if you don't know how to do this: you select the first image file with the mouse, press Return to start editing its name, type image01.jpg, and press Return again; then you select the next image file with mouse, and do it again, and so forth. The trouble is that you don't
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Is This Application Scriptable?
AppleScript isn't just a language; it's an underlying technology supporting that language. Because this technology is present as part of the system, you get it for free—so you may as well take advantage of it. And because you know this technology will be present on any Mac OS computer, you can share with others any useful AppleScript program you happen to write.
So AppleScript is omnipresent. But it's not omnipotent. AppleScript, remember, is all about telling an application to do automatically things of the sort you might make it do manually. But AppleScript does not let you tell every application to do everything it is capable of. AppleScript works by sending messages to the applications you are automating; these messages are called Apple events. You cannot send just any old Apple event to any old application. (Well, you can, but it might not have any effect.) The application to which you're sending an Apple event must recognize and respond to that Apple event. The ability to recognize and respond to a set of Apple events is a feature of the application. Giving the application this ability is up to the developers of the application—it isn't something that's within your power (unless you are also the developer of the application). An application that has this ability is said to be scriptable . If an application isn't scriptable, you're probably not going to be able to use AppleScript to automate it. (As you'll see in Chapter 24, there is sometimes a way around this limitation, but it should probably be used only as a last resort.) So, before you consider using AppleScript at all, you should have in mind some scriptable application that you want to automate with it.
Not only is AppleScript not omnipotent; it isn't even all that potent. AppleScript is a genuine programming language with some interesting and valuable features, but it's not very powerful or useful on its own. It takes some scriptable application to give AppleScript any real muscle. So, for instance, AppleScript's numeric abilities are limited (it has no built-in trigonometric or logarithmic functions ) and its facilites for text processing are fairly rudimentary (it doesn't support regular expressions , and it isn't even very good at extracting substrings). Granted, these shortcomings aren't as significant as they used to be. Mac OS X is loaded with other scripting languages, such as Perl, which are expert at regular expressions—and AppleScript can drive Perl (and vice versa), so success might simply be a matter of combining specialties appropriately. Nevertheless, the general spirit and intention of AppleScript is that the power should be invested mostly in various scriptable applications, not in AppleScript itself.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Calculation and Repetition
Computers are good at calculation and repetition . Humans, on the other hand, are liable to calculate inaccurately, and all the more so in the face of repetitive activity, which can make them careless, bored, and angry. Calculation and repetition on a computer should be performed by the computer—not by a human.
Here's an example straight off the Internet, where someone writes: "I want to rename a whole lot of image files based on the names of the folders they're in." One's eyes glaze over at the prospect of doing this by hand. Yet with AppleScript, it's a snap. The task would make a good droplet—a little application, written with AppleScript, with a Finder icon onto which you can drop files and folders you want processed. (More details appear in "Applet and Droplet" in Chapter 3 and "Applets" in Chapter 27.) Here's the AppleScript code for such a droplet; you drop a folder or folders onto its icon in the Finder, and it renames all items in each folder using that folder's name followed by a number:
on open folderList
    repeat with aFolder in folderList
        if kind of (info for aFolder) is "Folder" then
            renameStuffIn(aFolder)
        end if
    end repeat
end open
on renameStuffIn(theFolder)
    set ix to 0
    tell application "Finder"
        set folderName to name of theFolder
        set allItems to (get every item of theFolder)
        repeat with thisItem in allItems
            set ix to ix + 1
            set newName to folderName & ix
            set name of thisItem to newName
        end repeat
    end tell
end renameStuffIn
The parameter folderList tells us what was dropped onto the droplet. We process each dropped item, starting with a sanity check to make sure it's really a folder. If it is, we give each item in the folder a new name based on the folder's name along with a number that increases each time.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reduction
Even when a task doesn't involve repetition and calculation, it may involve many steps. If you can get AppleScript to perform many or all of those steps, you reduce the number of steps you have to perform. This can make for a noticeable improvement in your relationship with your computer, even if you perform this task fairly infrequently. Another advantage of reduction is that you no longer have to remember a sequence of steps; your AppleScript program remembers it for you.
Here's an example involving URLs. Often, working in some application, I see a URL that I'd like to "go to" in the approprate manner. If it's an http URL, my default browser should open and fetch that page. If it's an email address, my email program should create a new message to that addressee. In some applications you can just click a URL and the right thing happens, but many applications provide no such facility, so I have to resolve the URL manually. This means I must look at the URL and decide on the appropriate helper program; then I select and copy the URL; then I somehow start up the helper program; finally, I paste the URL into the appropriate location. In a browser, I must hit Return afterwards, in order to go to that URL; in an email program, I must create a new message first, in order to have something to paste into. This doesn't sound like very many steps, but it's all very annoying, especially in comparison to those applications where the right thing just happens with a single click.
The solution is an AppleScript program. I've assigned it a keyboard shortcut (ways of doing this are discussed in Chapter 2), so the procedure is this: select and copy the URL, then press the keyboard shortcut. That's a significant savings in time and trouble. Here's the script:
set theProc to (get path to frontmost 
 application as Unicode text)
tell application "Finder"
    activate
    delay 1 -- give time for clip to convert from Classic
    set theURL to (get the clipboard as string)
end tell
ignoring application responses
    try
        open location theURL
    end try
end ignoring
activate application theProc
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customization
No application in the world can meet everyone's desires and expectations, because whatever the application's features, it is impossible for the developers of that application to anticipate everything that every user will wish to do with it. AppleScript can be a solution to this problem. Scriptability can provide, in essence, an entire alternative user interface: instead of the graphical user interface of buttons and menus, it's a programming interface. An application's scriptability says to you: "Here are all the types of thing this application operates on, and here are the operations you can perform on them; if none of this application's menu items and buttons and other graphical interface items performs just the sequence of operations you desire, feel free to use AppleScript to create a sequence that does."
Here's a real-life example . On the Internet, someone asked about assigning track numbers in iTunes. A track number is an attribute of a song, which can be set in that song's Get Info dialog; it can be made to appear in the playlist display, and you can sort on it. Thus, track numbers can be used to control the order of playback in a playlist. This user wanted to assign track numbers immediately after "ripping" a CD to iTunes , so that the order in which the tracks appeared on the original CD, and in which they appeared in the initial playlist derived from that CD, could easily be restored within iTunes later on. In essence, the user was saying: "The tracks are already in their correct order within this playlist; how can I use that order to assign all the tracks a track number, in a single move?"
My response was: "Use AppleScript." Here's a script that does it:
set i to 1
tell application "iTunes"
    tell (get view of browser window 1)
        repeat with aTrack in (get every track)
            set track number of aTrack to i
            set i to i + 1
        end repeat
    end tell
end tell
An interesting philosophical debate then ensued. The user thanked me, but expressed regret that this was the "only way" to accomplish this task; iTunes, he said, should include this feature natively. My attitude was just the opposite: thanks to scriptability, iTunes
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Combining Specialties
Different applications are good at different things. Most users don't perform all tasks in a single application. For example, in a word processor, you wouldn't expect to perform extensive editing of pictures: a document might include pictures, but you'd create and edit them in some other program, and then incorporate them into the word processing document. That's how it should be, and that's how users typically like it, especially on Mac OS X where (in contrast to previous systems) there is no significant penalty to running several applications at the same time. "Swiss Army knife" programs that try to be all things to all users generally seem bloated with unnecessary features (such as Microsoft Word, with its Photoshop-like "graphics enhancement" features).
When it comes to assisting applications to combine their separate specialties, AppleScript really shines. Thanks to AppleScript, data can be moved back and forth between applications so that each can operate upon it in the appropriate manner. The result is a workflow in which multiple applications are coordinated, often without the intervention or even the awareness of the user.
Take, for example, SpamSieve . This superb application uses Bayesian algorithms to distinguish between spam and nonspam email messages with astonishing accuracy—far better than those email client programs, such as Entourage and Apple Mail, that include spam filtering of their own. But SpamSieve is not itself an email client. So in order to filter out spam as your email client application receives it, that email client application and SpamSieve must cooperate. The email client receives the mail messages, and hands them over to SpamSieve for evaluation; if SpamSieve marks a message as spam, it tells the email client application, which can then take appropriate action (such as moving the message into a Spam folder). Whenever you check for new mail messages, the two-way communication between your email client and SpamSieve takes place automatically, seamlessly, swiftly, invisibly—and entirely through AppleScript. Thus AppleScript effectively incorporates SpamSieve's brain and its special kind of intelligence into your email application; the two specialties (receiving email messages and storing them in folders, on the one hand, and knowing what is spam and what isn't, on the other) are combined.
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: Where to Use AppleScript
AppleScript, because it is implemented at system level, is omnipresent. Nevertheless, you do not use AppleScript at just any time and any place. AppleScript, like Archimedes' lever, may permit you to move the earth; but first, like Archimedes, you need a place to stand.
The various contexts and milieus in which AppleScript code can be executed may be conveniently grouped into a few general categories; this chapter presents these categories, along with some examples. In other words, this chapter describes the main places where you can use AppleScript. You'll discover that AppleScript is lurking, ready and at your command, in many corners of your computer.
The taxonomy presented here is somewhat artificial, and my names for the various kinds of context in which AppleScript can be used are mostly made up, but I don't think this makes the discussion any less useful. Bear in mind that the example scripts in this chapter are for the most part deliberately simple and contrived; the emphasis here is not on actual uses for AppleScript (as described in Chapter 1), but on places from which you can put it to use.
A script editor is an application such as Apple's own Script Editor (located in /Applications/AppleScript)—a general development environment where the user can create, edit, test, and run AppleScript code. A script editor application will almost certainly be central to your experience of AppleScript. Although you may use AppleScript code in other contexts, those contexts will generally provide no facilities for working on that code. Thus, no matter where you intend to use your code, you will first develop it in a script editor; if you wish to use it in some other context, you'll transfer it to that context from the script editor when you are satisfied that it is ready. If, using it in that other context, you discover there's a problem with it, you'll probably bring the code back into your script editor to test and improve it.
A script editor application will usually allow you to do things such as the following:
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 Editor
A script editor is an application such as Apple's own Script Editor (located in /Applications/AppleScript)—a general development environment where the user can create, edit, test, and run AppleScript code. A script editor application will almost certainly be central to your experience of AppleScript. Although you may use AppleScript code in other contexts, those contexts will generally provide no facilities for working on that code. Thus, no matter where you intend to use your code, you will first develop it in a script editor; if you wish to use it in some other context, you'll transfer it to that context from the script editor when you are satisfied that it is ready. If, using it in that other context, you discover there's a problem with it, you'll probably bring the code back into your script editor to test and improve it.
A script editor application will usually allow you to do things such as the following:
  • Edit a script in a convenient interface
  • Display a scriptable application's dictionary, which describes how to talk to it with AppleScript
  • Record user actions in AppleScript form, if a scriptable application is recordable
  • Compile a script, and display the compiled script in pretty-printed format (compilation is a necessary intermediate step between editing and running AppleScript code, and functions as an initial check on that code's validity)
  • Run the script's code
  • View the result, if any, of running the script's code
  • Save the script in any of the standard AppleScript formats
(Technical terms in this list are formally introduced in Chapter 3.)
There are three main candidates for use as a script editor: Apple's Script Editor , the freeware Smile, and the commercial Script Debugger. Each has its own advantages and peculiarities. You needn't feel confined to any single script editor; compiled scripts are a standard format, so any script editor can read the files of any other. (As of this writing, however, Smile still can't deal with bundle-formatted scripts.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Internally Scriptable Application
Some applications implement automation not through AppleScript but by means of some other language (possibly one unique to that application) that effectively operates entirely within that application. Such an application is internally scriptable . But even though such an application does not use AppleScript for its internal scripting, the developers might still wish it to be able to communicate with other applications. That means Apple events, and AppleScript is a convenient way (convenient both for the developers and for the end user) to construct and send Apple events. The internal scripting language can most likely operate on text, so a typical approach is to give
Figure 2-3: Script Debugger in action
Figure 2-4: Explorer view in Script Debugger
it the ability to treat text as AppleScript code (by compiling and running it). Even though you can use AppleScript code in an internally scriptable application, you wouldn't want to develop it there, as there is no provision for editing and testing your code, displaying a target application's dictionary, and so forth. Thus you'll usually develop your code in a script editor application and then copy it into the internally scriptable application.
A good example is the database application FileMaker Pro . It has an internal scripting language that can execute text as AppleScript. This text can be static or constructed dynamically ("calculated"). Figure 2-5 shows a case in point, with FileMaker Pro being used to communicate via AppleScript with Apple's Mail program. The idea is that you might like to store your contacts in a true database program, but then you might like to create and send an email message to one of them in a true email client (see "Combining Specialties" in Chapter 1). Thus, the FileMaker window (in front) displays a database of contacts; pressing the "To" button causes Mail to create a new email message (in back) using the email address from the current FileMaker record.
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 Runner
An application without facilities for editing or compiling scripts may nevertheless offer to execute compiled scripts for you on demand by way of some convenient interface, such as a menu . Such an application might be called a script runner . There is usually a requirement that a compiled script file be placed beforehand in some particular location where the script runner can find it. Because the script is compiled beforehand, a time-consuming step (compilation) is skipped, and execution typically proceeds considerably faster in a script runner than it does in an internally scriptable application where the code must be compiled from text on the fly.
Many scriptable applications act as script runners, typically by means of a special Script menu . This behavior is helpful because, having developed a script that drives such an application in a useful way, you might like some convenient interface for executing that script on future occasions; the application's Script menu provides such an interface. Scripts in an application's Script menu do not have to target that application, but the feature makes sense, and is provided, in the expectation that they will do so. (And when a script in an application's Script menu does target that application, there is sometimes a tremendous speed advantage over running that same script from elsewhere; see Chapter 22.)
For instance, as mentioned under "Customization" in Chapter 1, if you put scripts into ~/Library/iTunes/Scripts/, iTunes will generate a Script menu listing them and permitting you to run them; so that's a good place to store and access your scripts that customize iTunes.
BBEdit is a particularly fine example of a script runner. Whatever compiled scripts you place in ~/Library/Application Support/BBEdit/Scripts/ will appear as menu items in BBEdit's Script menu, where a script can be run by choosing its menu item. For even more convenient access, BBEdit lets you assign keyboard shortcuts to these menu items. BBEdit also implements some further conventions that have become a sort of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Automatic Location
An automatic location is much like a script runner. But there's a significant difference. A script runner finds compiled script files in a prearranged location and offers you an interface so that you can run them when you want to. An automatic location is a place where an application finds compiled script files and runs them automatically, with no intervention on your part. The application runs the script when it wants to—typically in reponse to the occurrence of certain events or stimuli. This doesn't mean you've no involvement, though; you were involved when you arranged for the application to find this script in this location, or to look for it in response to this particular event or stimulus.
BBEdit is an example. I've mentioned (in the previous section, "Script Runner") that BBEdit will use a menu to let you run scripts it finds in a Scripts folder within ~/Library/Application Support/BBEdit/. BBEdit looks for two additional folders in that location—Startup Items and Shutdown Items. These are repositories for scripts that BBEdit will run automatically in response to being launched and being quit, respectively. Similarly, when you choose from any of BBEdit's built-in menus, BBEdit will run an appropriately named script located in the Menu Scripts folder. Now, all these scripts and folders did not come into existence by themselves; you put them there. But once you've done that, since these are automatic locations, BBEdit runs the scripts automatically when the appropriate events occur.
Email clients, such as Apple's Mail and Microsoft Entourage, have "rules," which are essentially filter actions to be applied to mail messages. The usual configuration is to have these rules applied automatically when new mail arrives. One of the things such a rule can do is to run an AppleScript file. Again, these applications do not spontaneously invent the rules or include AppleScript files in them; you do that. But once you've done it, the application turns to the AppleScript file automatically in response to the arrival of new mail. iCal, too, can run an AppleScript file when the alarm for an upcoming event is triggered.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application
The reasons why an application might want to employ AppleScript are the same as the reasons why anyone else would—the application wishes to communicate with some other application by way of Apple events (see "Is This Application Scriptable?" in Chapter 1). It is possible to write an application that forms and sends raw Apple events directly, without using AppleScript; but AppleScript makes the task much easier for the developer of an application, just as it does for anyone else.
To write an application that uses AppleScript, you don't have to be a professional developer who spends 15 hours a day at the computer and wears a beanie with a propeller. (Of course, the beanie can't hurt, either.) In fact, writing an AppleScript application could be as simple as saving a script from a script editor application. It may be useful to distinguish three different "levels" of application into which AppleScript can be incorporated: an applet , an AppleScript Studio application, and a standard compiled application that happens to call AppleScript. I'll just briefly survey all three levels here; the first two are revisited in more detail in Chapter 27.
An applet is just a compiled script saved with a tiny application framework wrapped around it. This application framework is just sufficient to turn the script into a stand-alone application. You can make an applet very easily: save your script from within a script editor application, and as you do so, choose to save it as an Application. (You make this choice in the Save dialog; if the script has already been saved, you may need to choose File → Save As to bring up the Save dialog.) The result is an application that, when it runs, behaves almost exactly like your script when it runs.
If an applet behaves like the script it contains, why would you bother to make one? Why not simply leave the script as a compiled script file? One reason would be that you want the script to run in some context where merely opening a compiled script file would not run it. One obvious example is the Finder. Let's say there's some operation you frequently need to perform, and the way you want to perform it is by double-clicking something in the Finder. Perhaps you find the Script Menu too much trouble; perhaps you like having an icon right on your desktop, where you can see and access it easily by double-clicking it. Or perhaps you don't want it on your desktop; perhaps you'd like to put it in the toolbar area of your Finder windows. (The toolbar is the area of a Finder window above the files but below the titlebar.) Single-clicking a toolbar item is exactly like double-clicking the same item on the desktop or in a Finder window. But double-clicking a compiled script file in the Finder doesn't run it; it opens the script for editing in a script editor application. On the other hand, double-clicking an applet (or single-clicking it in the toolbar) does run the script. (Indeed, Apple provides, 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!
Unix
Mac OS X, under the hood, is Unix . It is possible to use AppleScript from the Unix command line in the Terminal and from shell-related environments such as Perl and Ruby scripts, by means of the osascript command. osascript can execute a compiled script file or can compile and execute a string (indicated by the -e switch).
You can enter script text directly at the command line by typing osascript and a return character, then typing the text, and finally signalling the end of the text with Control-D. There isn't much likelihood you'd want to do this, but at least it proves that osascript is working, and the code looks exactly like normal AppleScript:
% osascript -ss
tell app "Finder"
get name of every disk
end tell
^D
{"feathers", "gromit", "Network"}
(The -ss flag causes the result to appear in the familiar way that AppleScript usually formats a list of strings.)
Use of a literal string on the command line raises some difficulties of escaping characters parallel to those we've seen earlier in this chapter; there are various solutions, depending on what shell you're using. In a language such as Perl, you can take advantage of the language's "here document " facility, which makes it easy to enter a multiple-line script without having to escape any quotes. Once again, the code looks exactly like normal AppleScript:
#!/usr/bin/perl
$s = <<DONE;
    tell app "Finder"
        get name of every disk
    end
DONE
print `osascript -e '$s'`;
Chapter 25 contains full details about calling AppleScript from Unix, as well as communication in the reverse direction (through AppleScript's do shell script command).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hyperlinks
You can embed AppleScript code in an HTML hyperlink . The user can't actually execute AppleScript code by clicking such a link (the ability to do so would constitute a serious security hole). Rather, when the user clicks that link, the code is displayed in a script editor, ready to execute if the user desires.
The mechanism involved is the applescript URL protocol. The href attribute of the link's <a> tag must begin like this:
applescript://com.apple.scripteditor?
The specification of Script Editor's bundle identifier is apparently a security measure; it is required, but it is also superfluous, because applescript URLs cannot be made to target any other script editor application by changing this value.
applescript URLs can be made to target a desired application (or applet) by means of a preference set by the user at system level. Apple provides no interface for setting this preference; but the freeware RCDefaultApp preference pane is an excellent way to do it (http://www.rubicode.com/Software/RCDefaultApp/ ).
The next component of the URL is one of the following three expressions:
action=new&
action=insert&
action=append&
They signify, respectively, that AppleScript code should be inserted in a new Script Editor window, placed at the insertion point in the currently frontmost Script Editor window, or appended to the end of the currently frontmost Script Editor window. (If no Script Editor window is currently open, all three have the same effect.)
Finally, the AppleScript code itself appears, in this format:
script=theCode
As this is a URL, illegal characters in theCode must be URL-encoded using a percent sign and the character's ASCII value in hexadecimal; for example, a space must be encoded as %20, a quote must be encoded as %22, and a return character must be encoded as %0D. At http://www.apple.com/applescript/scripteditor/12.html, Apple provides a utility script that URL-encodes text that has been copied to the clipboard, and embeds it in an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Automator
Automator is a utility application, new in Tiger, that allows the user to construct a script (called a workflow ) from a series of steps (called actions) in a graphical interface without knowing a programming language. The default actions are in /System/Library/Automator/; additional actions may be installed into /Library/Automator/ or ~/Library/Automator, or they may be included in an application's bundle, where Automator can see them directly. Workflows can be saved as files to be run by Automator, as applications to be run independently (rather like an AppleScript applet), or as plug-ins for use by various applications: for example, a workflow saved as a Finder plug-in becomes a Finder contextual menu item, and a workflow saved as a Script Menu plug-in becomes a menu item in the Script Menu.
The default actions include a Run AppleScript action , which lets the user incorporate AppleScript code directly into a workflow. Even more interesting, an Automator action can easily be written using AppleScript, and instructions for doing this appear in Chapter 27. An action is a useful way to distribute a piece of AppleScript code to users. You can't know, after all, exactly what a user would like to do with your code, and some users don't understand programming well enough to customize AppleScript code in a script editor themselves. An Automator action can help to solve these problems. An action can easily be positioned among other actions in a workflow that the user constructs in order to achieve a desired result. Furthermore, an action has a graphical interface, which lets the user set various parameters to the AppleScript code without coming into direct contact with that code.
Figure 2-9 shows a simple Automator workflow; it puts up a dialog asking the user to chooose a folder, and lists the pathnames of the items within that folder into a new TextEdit document. Notice the graphical interface that allows the first action to be customized so that the dialog asks for a folder, not a file. Notice also the dataflow paradigm that links the actions: each action produces an output, which functions as the input to the next action in the sequence. The second action produces a list of files and folders (as aliases), but the third action expects text; nevertheless the workflow succeeds because Automator coerces from one type to another as necessary (here, turning a list of aliases into POSIX pathnames separated by return characters).
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: Basic Concepts
Previous chapters have been pure introduction. Chapter 1 has shown what AppleScript is good for; Chapter 2 has toured the places on your computer where you can use AppleScript. If you're new to AppleScript, you should now be feeling informed and motivated and ready to begin sinking your teeth into some solid facts. If you already have some familiarity with AppleScript, you may be leafing forward through this book, looking for the serious part to begin. Either way, look no further. This is it. The solid, serious stuff starts here.
This chapter formally defines and describes AppleScript—what it is, why it exists, where it lives, and how it works—along with all the basic terms and concepts connected with it. Subsequent chapters will provide further details about some of what's here, but they all presuppose the basis laid out in this chapter. Whether you think of it as an introduction, a survey, or a glossary, to understand this chapter is to know AppleScript's world.
AppleScript would be pointless without Apple events. Apple events lie at the heart of what AppleScript is, what it does, how it works, and why you're going to use it. From writing more efficient AppleScript code to understanding an application's dictionary, a basic acquaintance with Apple events will help you.
A long time ago, in a galaxy far away—actually it was probably in about 1989, in Cupertino, California—some very smart people were completely redesigning and modernizing the Macintosh operating system, creating what was to become System 7 (released in May 1991). And some of these people had a brilliant idea. The system, they decided, should support a messaging system, a way of letting one running application communicate with another. Such communication is called interapplication communication , and the messages sent between applications are called Apple events.
There are two parties to an interapplication communication: the application that initiates the message, and the application that receives it. I like to refer to these as the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Apple Events
AppleScript would be pointless without Apple events. Apple events lie at the heart of what AppleScript is, what it does, how it works, and why you're going to use it. From writing more efficient AppleScript code to understanding an application's dictionary, a basic acquaintance with Apple events will help you.
A long time ago, in a galaxy far away—actually it was probably in about 1989, in Cupertino, California—some very smart people were completely redesigning and modernizing the Macintosh operating system, creating what was to become System 7 (released in May 1991). And some of these people had a brilliant idea. The system, they decided, should support a messaging system, a way of letting one running application communicate with another. Such communication is called interapplication communication , and the messages sent between applications are called Apple events.
There are two parties to an interapplication communication: the application that initiates the message, and the application that receives it. I like to refer to these as the sender and the target , respectively; I find this clearer and more instructive than the more technical terms "client" and "server."
An Apple event is an astonishingly powerful thing. Hermes-like, it crosses borders: two completely independent applications, with no prior arrangement or synchronization, are suddenly talking to each other. What's more, Apple events work across a network, including the Internet, so these two applications can be on different computers. Or, just the opposite, an application can send an Apple event to itself. (Why would it want to do that? You'll find out, in the section "Recordability," later in this chapter.)
The breadth of what may be expressed in an Apple event is also quite amazing. Their structure amounts to a remarkably sophisticated grammar: Apple events are like little sentences, possessing (so to speak) verbs and nouns and modifiers, and this grammar is so cleverly and flexibly devised that individual Apple events can be constructed to say surprisingly complicated things, such as (speaking to a word processing program), "Look at the text of your first window and give me a reference to every line of it whose second word begins with the letter t," or (speaking to an email program), "Look in the mailbox where the incoming mail is, find the first mail message with a subject that starts with the word 'applescript,' and move it into the 'AppleScript' mailbox." Much of the grammar of the AppleScript language is as it is because of the grammar of Apple events.
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 Open Scripting Architecture
When System 7 was being created, along with Apple events and many other new technologies, it was already Apple's plan to create a language, AppleScript, that would give end users access to the power of Apple events. But, much to the disappointment of users and developers, there wasn't time to create AppleScript before the release of System 7 in mid-1991, and the bulk of the work was postponed until 1992-1993.
One of the conundrums facing the founders of AppleScript at this time was the architectural question of where the language should live. They could have made AppleScript the internal scripting language of a single application, like HyperCard's HyperTalk , but this would mean that the user would run AppleScript code entirely from within this one application, which was unacceptable. AppleScript needed to be available everywhere, and thus would somehow have to be part of the system. But what part? There was no good place, so a new one was created: the resulting structure is the Open Scripting Architecture (OSA).
Under the OSA, a scripting language is implemented by a something called a component . (Components were not invented specially for the OSA; they existed already in connection with QuickTime.) Think of a component as a piece of self-contained functionality made available at system level so that any program can hook up to it and use it. One thing that's special about components is that they can be installed and uninstalled dynamically. So an OSA-savvy program doesn't necessarily think in terms of any particular scripting language; it asks the system—in particular, the Component Manager —what scripting languages are presently installed, and if it wants to use one, the Component Manager provides access to it.
Because components are installed dynamically, this installation must actually take place while the computer is running. AppleScript is installed as the computer starts up and simply left in place, so that it's always available. You may recall that under Mac OS 9 there was an extension called AppleScript (in the Extensions folder of the system Folder). Its job was to install AppleScript as a component under the OSA as the computer started up. On Mac OS X, the same function is performed by a file called
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
The word "script," like a number of terms associated with AppleScript, is liable to be tossed rather loosely about in a bewildering variety of senses. Some of its meanings are technically important and therefore indispensable, so it will help if we pause to clarify its chief uses explicitly.
To "script" an application is to automate it, to drive it, to target it. People say, "I'd like to script the Finder to rename some files automatically." There is an implication that the Finder already has the power to do things to files, and that we are merely taking advantage of this power by dictating programmatically a sequence of actions that the Finder should take. This, after all, is why the Finder is said to be "scriptable" in the first place.
This sense of "script" is formalized in the way some sources define a "scripting language." This quotation comes from the ECMAScript Language Specification (http://www.ecma-international.org/publications/standards/ECMA-262.htm):
A scripting language is a programming language that is used to manipulate, customise, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language.
That is a perfect description of AppleScript. It has few powers of its own; it is meant primarily for controlling the powers of existing applications.
The preceding quotation from ECMA continues:
A scripting language is intended for use by both professional and nonprofessional programmers. To accommodate nonprofessional programmers, some aspects of the language may be somewhat less strict.
This leap is common enough, but in my view it is unwarranted. Most languages commonly referred to as scripting languages are full-fledged programming languages, and make no particular concession to informality or inexperience. There is arguably nothing easy, and certainly nothing simplistic, about Tcl, Perl, or Scheme. As far as ease of use is concerned, any distinction between a scripting language and a programming language is a distinction without a difference.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiling and Decompiling
To compile your AppleScript code is a necessary intermediate step between editing it and running it. This section explains what this means, and then discusses some of the implications for you, the AppleScript programmer.
To compile code means to transform it from editable text to a form that is understood by some engine that will run the code. The particular form depends upon the nature of the particular engine. At one end of the spectrum, the engine might be the computer's central processing unit (CPU), in which case the code is turned from text to machine-language instructions; that, for example, is how Fortran and C work. At the other end of the spectrum, one can postpone compilation until the program is actually running and a line of code is encountered; for example, in some implementations of BASIC , such as the one that came with the original Apple II, the runtime engine accepts pure text, compiling and executing that text one line at a time. A language that works this way is said to be interpreted.
In the early days of computers, most language implementations fell into one camp or the other, being either compiled or interpreted. These days, however, many popular scripting languages (such as Perl, Python, and Java) are implemented through a compromise technique where the entire program is initially compiled into an intermediate representation, which is then fed to a runtime engine that accepts and executes it a chunk at a time. In effect, such languages are compiled, then interpreted. AppleScript works this way.
Like those other scripting languages, AppleScript code is compiled into bytecode , meaning that, roughly speaking, the nouns and verbs of the original text are translated into a sort of compressed, coded equivalent, called tokens . These tokens are meaningful to the AppleScript scripting component's runtime engine (and illegible to everyone else). The runtime engine interprets the bytecode, parsing whatever tokens it meets along its path of execution, accumulating them into chunks, and translating these chunks further, as necessary, in order to execute them.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiled Script Files
A compiled script file is just what you think it is: it's a file containing the bytecode of a compiled script. Unlike text, a compiled script file can be executed without being compiled (because it's already compiled); the runtime engine is fed the bytecode and can leap into action immediately. A lengthy script can take several seconds to compile, so a compiled script file clearly saves some time and overhead when the script is executed. Obviously this architecture is advantageous when the script is not going to change and therefore will not need compiling ever again—when you distribute the script to others, for example. Applications that act as script runners typically operate on compiled script files (see "Script Runner" in Chapter 2). Script editor applications save a script as a compiled script file by default. When an application has asked the AppleScript scripting component to compile some text, a compiled script file is the only way for the compiled script to outlive that instance of the AppleScript scripting component, which will go out of existence when the host application quits.
(There is actually more to a script, and therefore there can be more to a compiled script file, than the compiled bytecode. I'll discuss these further contents of a compiled script file in "Persistence of Top-Level Entities" in Chapter 8 and "Closures and Stored Script Objects" in Chapter 10.)
You cannot save as a compiled script file code that, for whatever reason, will not compile. This seems tautological, but it can be surprising nevertheless, so it is worth mentioning.
To make things more complicated, a compiled script file can come in not one, not two, but three different formats :
Resource-fork file
The bytecode is kept in the file's resource fork ; there is no data fork . The type is 'osas'; the extension is .scpt. Historically, this is the oldest form. Script Editor will not create a file in this form (though Script Debugger can), but if Script Editor encounters such a file it can open, edit, and save it in the same form.
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 Text File
A script text file is exactly that: it's an ordinary text file, such as can be opened by any word processor, consisting of the uncompiled text of your script. Any script editor application will typically offer an option for saving a script as text. No bytecode is saved into the file, and the script need not be capable of compilation in order to be saved as text—as opposed to a compiled script file , which by definition can't be saved unless the script can be compiled. (Apple's Script Editor does also attempt to compile the script when you save it as text, and will report any compilation errors even though saving succeded; this seems like a bug.) The conventional extension for a script text file on Mac OS X is .applescript, but it is still of type 'TEXT'.
Most script runners will refuse to execute a script text file; they generally expect a compiled script file, whereas a script text file is not compiled (and the script runner is not willing to do the compilation).
A script text file is described by Apple's documentation as a kind of low-grade, last-resort alternative to a compiled script file. But it does have certain advantages. For one thing, obviously, you can save it even though you can't compile the script, so if you're developing a script that won't compile or that you'd rather not compile just now, you have a way to save it. Also there are matters of compatibility and portability. Recall that Apple's Script Editor can't create a compiled script file that will work on early versions of Mac OS 9 or before. And (as I'll discuss later in this chapter) a compiled script file can face difficulties if AppleScript can't locate a needed external referent, which can happen particularly when the script is moved to another computer. A script text file overcomes all these difficulties; it's just text, and therefore is absolutely portable to any machine running any system. Some version of AppleScript and the Script Editor will be present on just about any machine running Mac OS, so the file can be opened and, if the code is valid, the script can be compiled there.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Applet and Droplet
An applet is an application with very little graphical user interface, consisting essentially of a compiled script along with a minimal amount of standalone executable code, called the bootstrap code, along with some other resources necessary to make the application scriptable. The bootstrap code, which runs when the applet is launched, simply summons a scripting component called the Script Application Component ; this component does the rest, handing the compiled script over to the AppleScript scripting component for execution, and taking care of such application-like functionality as putting up the applet's menu and its description window if there is one. Thus an applet is a tiny application which, when launched, runs a compiled script embedded within it. A script editor application will allow you to make an applet as simply as saving a compiled script file, just by choosing applet format (called "application") when you save (or choose File → Save As).
When you save your script as an application, the script editor application looks to see whether it has an open handler. If it does, the application becomes a droplet . A droplet is just like an applet, except that it has a different creator type (the creator type for an applet is 'aplt', while for a droplet it's 'dplt') and a slightly different icon; functionally, the difference is that a droplet does something when file or folder icons are dropped onto its icon in the Finder. Typically, a droplet responds to the dropped items by processing them in some way (for an example, see "Calculation and Repetition" in Chapter 1). A droplet can also function like an applet: as a droplet, it does something when items are dropped onto its icon, while as an applet, it does something when it is launched from the Finder.
An applet's script remains editable unless you save it as run-only . Unlike a compiled script file, you can't edit an applet's script by opening the applet from the Finder, because that launches the applet. Instead, you open it from within a script editor application, using File → Open, or by dropping the applet's icon on the script editor application's icon in the Finder. A running applet may also display some graphical interface offering a chance to edit its script.
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 Addition
AppleScript is a little language, and at a very early stage it was felt to be a bit too little. An architecture was therefore devised w