AppleScript
- For a WikiBook on programming with AppleScript, see Wikibooks:AppleScript Programming.
- This article describes the AppleScript programming language. The term "AppleScript" can also be used to refer to a script file written in this language.
Developer | Apple Inc. |
---|---|
Stable release | 2.0
/ 2007-10-26 |
OS | System 7, Mac OS 8, Mac OS 9, Mac OS X |
License | Apple EULA (parts available under APSL) |
Website | http://www.apple.com/applescript/ |
AppleScript is a scripting language devised by Apple Inc., and built into Mac OS. More generally, "AppleScript" is the word used to designate the Mac OS scripting interface, which is meant to operate in parallel with the graphical user interface.
History
The AppleScript project was an outgrowth of the HyperCard project. HyperCard had an English language-based scripting language called HyperTalk, which could be used for embedding logic and behavior into a HyperCard stack. Apple engineers recognized that a similar scripting language could be designed to be used with any application, and the AppleScript project was born as part of System 7.
AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7). QuarkXPress (ver. 3.2) was one of the first major software applications that supported AppleScript, and as a result, AppleScript was widely adopted within the publishing segment of the Apple market. It is arguable that the main reason that the Mac remained a powerhouse in the publishing market after Quark (and other applications) were ported to Microsoft Windows, was that Mac users could automate complex workflows.
The move to Mac OS X and its Cocoa frameworks has seen AppleScript come into its own. Cocoa applications offer basic scriptability with little effort on the part of the developer. AppleScript Studio, released with Mac OS X 10.2, allows users to build entire applications using AppleScript and Cocoa objects.
Basic concepts
AppleScript was designed to be used as an end-user scripting language, offering users an intelligent mechanism to control applications, information and documents in order to create automated workflows. AppleScript is designed as a scripting interface to control various applications. Automating a workflow with AppleScript often reduces the amount of time it takes to perform various tasks, reduces the opportunities for human error, provides consistent output and creates a manageable production system for working against deadlines.
For example, a script might open a photo in a photo-editing application, reduce its resolution, add a border, a photo credit, then export a Web-ready copy, then write a Web link for that photo into a text editor, then move on to the next photo in the set, and so on through hundreds or thousands of photos, eventually creating a Web-ready photo gallery, which the script uses an FTP client to upload to the user's Web site. For the user, hundreds of steps in multiple applications with potentially thousands of documents have been reduced to one: run a script. Even if the user were to use such a script only once, the initial AppleScript development time may be completely leveraged. In practice, scripts are used again and again, further leveraging the initial development time such that it becomes a trivial consideration.
An important AppleScript concept is that scripts drive applications in a fundamentally different way from the way users interact with them. Users manipulate the application's user interface, pulling down menus and clicking buttons; AppleScript scripts request and set values and invoke actions exposed by the application's internal object model. So, for example, rather than simulating keystrokes to enter text into fields in a database application, an AppleScript script would typically use commands that directly set the values of the desired fields of the record, possibly without the application even displaying the record being updated. AppleScript also has the ability to control non-scriptable applications through Graphical User Interface (GUI) scripting, which allows AppleScripts to select menu items, click buttons, enter text into text fields, and generally control the interfaces of most Mac OS X 10.x applications to handle operations not available through the scripting interface.
Since applications are all different from each other, the number of standard commands supported by all applications is fairly small. Each scriptable application publishes the terminology it understands in the form of an Apple Event dictionary, which AppleScript uses to determine the valid commands that can be issued in each application's context.
AppleScript in Mac OS X
AppleScript support is provided by many Mac OS X applications, from both Apple and third parties. Scriptable applications include Apple's Finder, Safari, iPhoto, and iTunes, as well as Adobe Illustrator and Photoshop, Bare Bones BBEdit and TextWrangler, Microsoft Word and Excel, VMwareFusion and many more.
Prior to System 7, the Mac OS application runtime had only a rudimentary event model that could specify a small and fixed number of low-level events such as "key was pressed" or "mouse was clicked". Each application was responsible for decoding these low-level events into meaningful high-level user actions, such as "choose cut from the Edit menu". In many cases, the code for reading the event and decoding it was mixed together; for instance, the code handling a mouse click might decode it to selecting the Quit item from the File menu, and then quit the application immediately.
Adding AppleScript support required the application author to fully separate this decoding from carrying out the command, a task Apple referred to as factoring (...the application). Application developers were encouraged to write two complete event handling "stacks", one for handling the low-level events (clicks, etc.), and another for high-level events (AppleEvents). The actual work code that handled these commands, once decoded, was to be completely separated and called identically from both stacks.
In Mac OS X AppleScript is simpler for developers to implement, particularly for those applications being developed in Cocoa. Unlike the Mac OS where events are handled by the applications, under Cocoa, events are decoded into a "high level" command by the NSApplication
object, and the messages dispatched directly to the correct object. That is, all Cocoa applications are "factored" by default; the developer doesn't write any of the event handling code (normally) and writes only the "work methods" that those events will call.
Another major advantage is that Cocoa objects are presented to the outside world (other applications and even machines) in a standardized format that anyone can examine directly. Under Cocoa, AppleScript is much "thinner"; the script engine decodes the script, translates object names from human-readable to their internal format, and then calls those methods on the target application directly.
The natural language metaphor
Whereas Apple Events are a way to send messages into applications, AppleScript is a particular language designed to send Apple Events. In keeping with the Mac OS tradition of ease-of-use, the AppleScript language is designed on the natural language metaphor, just as the graphical user interface is designed on the desktop metaphor. AppleScript programs are generally readable by anyone, and editable by most. The language is based largely on HyperCard's HyperTalk language, extended to refer not only to the HyperCard world of cards and stacks, but also theoretically to any document. To this end, the AppleScript team introduced the AppleEvent Object Model (AEOM), which specified the objects any particular application "knew".
The heart of the AppleScript language is the use terms that act as nouns and verbs that can be combined. For example, rather than a different verb to print a page, document or range of pages (printPage, printDocument, printRange) appleScript uses a single "print" verb which can be combined with an object, such as a page, a document or a range of pages.
print page 1
print document 2
print pages 1 thru 5 of document 2
Generally, AEOM defined a number of objects, like "document" or "paragraph", and the actions that could be done to them, like "cut" and "close". The system also defined ways to refer to properties of objects, so one could refer to the "third paragraph of the document 'Good Day'", or the "color of the last word of the front window". AEOM uses an application dictionary to associate the Apple Events with human-readable terms, allowing the translation back and forth between human-readable AppleScript and bytecode Apple Events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In the Xcode and Script Editor applications, this is under File → Open Dictionary.)
To designate which application is meant to be the target of such a message, AppleScript uses a "tell" construct:
tell application "Microsoft Word"
quit
end tell
Alternatively, the tell may be expressed in one line by using an infinitive:
tell application "Microsoft Word" to quit
For events in the "Core Suite" (activate, open, reopen, close, print, and quit), the application may be supplied as the direct object to transitive commands:
quit application "Microsoft Word"
The concept of an object hierarchy can be expressed using nested blocks:
tell application "QuarkXPress"
tell document 1
tell page 2
tell text box 1
set word 5 to "Apple"
end tell
end tell
end tell
end tell
The concept of an object hierarchy can also be expressed using nested prepositional phrases:
pixel 7 of row 3 of TIFF image "my bitmap"
which in another programming language might be expressed as sequential function calls:
getTIFF("my bitmap").getRow(3).getPixel(7);
AppleScript includes syntax for ordinal counting, "the first paragraph", as well as cardinal, "paragraph one". Likewise, the numbers themselves can be referred to as text or numerically, "five", "fifth" and "5" are all supported, they are called synonyms. Also, to add to the English-likeness, the word "the" can legally be used anywhere in the script in order to enhance readability: it has no effect on the functionality of the script.
AppleScript on its own
AppleScript is not dependent on other applications. For many tasks, AppleScript can be used for self-contained applets. For instance, the script:
set pix to 72
set answer to text returned of (display dialog "Enter in the number of inches" default answer "1")
display dialog answer & "in = " & (answer * pix) & "px"
brings up a dialog box requesting a number of inches from the user. This number is then converted to pixels, assuming 72 pixels per inch. A second dialog box is then brought up displaying the result.
AppleScript Studio
With Mac OS X, AppleScript has grown significantly. AppleScript Studio is a development environment, which comes with Mac OS X, and can use AppleScript as the primary programming language, in conjunction with the Cocoa framework used to construct graphical user interfaces.
Script Editor
The more recent versions of Script Editor for writing, editing, compiling and running AppleScripts have also been enhanced. One new feature of this editor is that if you right-click (or control-click) on the editing area, you get a pop-up menu with a large range of options for script fragments to paste into your script. This is an excellent feature for people learning to write AppleScript. From that menu, you can also open the directory where these scripts are kept. You can also add your own scripts (which will appear in the pop-up menu after you restart Script Editor). The Script editor also has a record button, which can be used to create AppleScript commands from user interface actions from certain applications. Recording works with a limited number of applications.
AppleScript language essentials
- basic data types are Boolean, string, integer, real, list, record and object
- different types can coexist in a list, including nested lists
- records are lists of key-value pairs
- standard control flow with if/else constructions and repeat (for, while, in) loops
- variables are instantiated when used, and are not strictly typed
- script objects can encapsulate methods and data
- script objects can inherit behavior from a parent script
- "tell" construct used to identify target of message
- applications can define terminology at runtime
- runtime compilation possible using "run script" construct
- persistence and modularity possible using "store script" and "load script"
Applets and Droplets
An AppleScript script can be saved as an applet, a script contained in a Mac application that runs the script when it's launched. When a user double-clicks an applet, the script's run handler is called.
Run handler:
on run
-- do something when this script is launched
end run
Every script has a run handler, but declaring it is optional. If the run handler is undeclared, commands in the script's top level, outside of any other handler, are considered to be an implicit run handler.
If the script has an open handler:
on open theItems
-- do something when filesystem items are dropped on this script
end open
then the applet becomes a droplet: when the user drags and drops filesystem items onto the script, it will be launched and the open handler will be invoked and a list of aliases will be set with the open handler's variable name. A droplet can also run as an applet: when double-clicked, the run handler is called. Adding a run handler with a choose file command to your droplet enables a second pathway for the user to provide the script with a list of filesystem items.
If the script has an idle handler:
on idle
-- do something, then pause, then do it again, then pause, etc.
return 20
end idle
then the applet will pause for a specified number of seconds (20 in this example) and will execute the script within the idle handler again, and again ...
(Note: "on" is a synonym for "to" when starting a handler; for example, "on run" instead of "to run".)
Open Scripting Architecture
An important aspect of the AppleScript implementation was the Open Scripting Architecture (OSA). Apple provided OSA for third-party scripting/automation products such as QuicKeys and UserLand Frontier, to function on an equal status with AppleScript. AppleScript was implemented as a scripting component, and the basic specs for interfacing such components to the OSA were public, allowing other developers to add their own scripting components to the system. Public client APIs for loading, saving and compiling scripts would work the same for all such components, which also meant that applets and droplets could hold scripts in any of those scripting languages.
Under Mac OS X, the JavaScript OSA component remains the only serious OSA language alternative to AppleScript, though the Macintosh versions of Perl, Python, Ruby, and Tcl all support native means of working with AppleEvents without being OSA components.
One of the most interesting features of the OSA are "scripting additions", or osax for Open Scripting Architecture eXtension, which were based on Hypercard's External Commands. Scripting Additions allow programmers to extend the function of AppleScript. Commands included as Scripting Additions are available system wide, and are not dependent on an application. Mac OS X includes a collection of scripting additions referred to as Standard Additions, which extends the function of AppleScript with a variety of new commands, including user interaction dialogs, reading and writing files, file system commands, date funtions, text and math operations.
See also
- Sal Soghoian — AppleScript product manager
- Script Debugger, a third-party AppleScript and OSA language editor.
- Smile (software), a scriptable AppleScript development environment.
- Automator — Apple technology for controlling applications that can be used with AppleScript, first implemented in Mac OS X 10.4 "Tiger", the version of Mac OS X released on April 29, 2005.
Books
- MacScripter — Applescripting and Cocoa Resources
- Computer-Books.us — Online AppleScript books
- Wikibooks:AppleScript Programming
External links
Official
- AppleScript – Official page at Apple.com
- AppleScript at Apple Developer Connection
- GUI Scripting Gives AppleScript scripts the ability to control otherwise non-scriptable applications. AppleScript scripts can select menu items, click buttons, enter text into text fields, and generally control the interfaces of most Mac OS X 10.x applications.
MacScripter
MacScripter is "a repository of information for AppleScript tutorials, latest scripts, scripting articles, FAQ, and related links for the Macintosh," and operates the following sites:
- ScriptBuilders – An archive of ready-to-run scripts, covering all scriptable Mac applications.
- Scripting Additions for AppleScript – Compiled C/C++ code that enhance the functionality of AppleScript.
- The AppleScript Sourcebook – An AppleScript FAQ: "It is designed to be useful both to scripters and to developers of scriptable applications and scripting additions."
- AppleScript.net Forums – A discussion board for AppleScript, Automator and Xcode.
- Automator Actions – An archive of ready-to-run Automator actions.
- AppleScript Central – "An up-to-date and comprehensive listing of AppleScript, Applescript Studio and Automator related web sites and resources."
- MacFreelancer – "The marketplace for businesses to post outsourced projects to a pool of quality Mac developers in a reverse auction style environment."
Other Resources
- Template:Dmoz
- William Cook, Donn Denman, Warren Harris, Kurt Piersol, Jens Alfke — AppleScript designers
- Scripteur Template:Fr icon – Scripting sur Macintosh: AppleScript et UserTalk
- MacCentral: AppleScript Primer (archived from 1999-2001) MacCentral
- "AppleScript" - (paper on the history and development of AppleScript; PDF)