AppleScript

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 and remained popular after QuarkXpress (and other applications) were ported to Microsoft Windows.

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, and access and modify information and documents. AppleScript can be used to create automated workflows which can reduce the amount of time it takes to perform various tasks, minimize the opportunity for human error, provide consistent output and facilitate a manageable production system.

For example, an appleScript might open a photo in a photo-editing application; reduce its resolution; add a border; add a photo credit; export a Web-ready copy; write a Web link for the 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. A large complex script could be developed to run only once, while other scripts are used again and again, further leveraging the development time to make it 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 can get 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.

Nearly all applications share a number of commands (open a file; close a document; print; save; quit; etc.). Each scriptable application contains the AppleScript 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. The Apple Event dictionary is distributed as part of the application, and is evaluated by AppleScript at runtime and when scripts are compiled. For many applications that support plug-ins, the plug-ins themselves may be AppleScriptable and would include an Apple Event dictionary that would be merged with the Application's dictionary at run time.

Hello World!

In AppleScript, the classic Hello World! program is written like this:

say "Hello World!"

When run, the above program causes the computer to say the phrase "Hello World!" in its default voice.

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.

Recordable Applications

Some applications send Apple Events when their menus are clicked, or other user interface actions are taken. These applications are said to be "recordable" because Script Editor can record their user interface Apple Events, creating an AppleScript macro line-by-line as you work.

Note that while a script is recording, you can't run it. However, you can do everything else: move the insertion point; add, edit, or remove code; even compile your script. The recordable application collaborates in a sense with your AppleScript writing, rather than replacing it. This approach typically yields more practical results than attempting to record an entire script from start to finish.

Only a small minority of scriptable applications is recordable. Examples include Finder and BBEdit. Studying the code that is produced by a recordable application as you work can aid in learning how to write scripts for that application.

AppleScript and Cocoa

With each version of Mac OS X it has become simpler for developers to implement AppleScript within their applications using the Cocoa API. In the Mac OS events are handled by applications, but, in the Cocoa API, events are decoded into a "high level" command by the NSApplication object, and the messages dispatched directly to the correct object. All Cocoa API 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 specifies the objects any particular application "knows".

The heart of the AppleScript language is the use of 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 defines a number of objects--like "document" or "paragraph"--and corresponding actions--like "cut" and "close". The system also defines ways to refer to properties of objects, so one can 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 method calls:

getTIFF("my bitmap").getPixel(3,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 Development Tools

Automator

Automator enables graphical, drag-and-drop editing of AppleScript workflows, with no knowledge of AppleScript coding required. Automator is included with Mac OS X.

Script Editor

Script Editor is an editor for AppleScripts that is included with Mac OS X. Scripts are written into document editing window and can be compiled and run from the Script Editor window. Scripts can also be saved as AppleScript applications (applets) or compiled scripts. Script Editor also provides access to a reference library of AppleScript dictionaries corresponding to the scriptable applications on your computer, and can log the Events and Results of scripts run from Script Editor for debugging purposes.

Script Menu

The Script Menu provides access to appleScripts from the Mac OS X menu bar. The Script Menu can be activated using the AppleScript Utility application. When activated Script Menu displays a default library of functional AppleScripts which can be used as examples. Selecting a script in the Script Menu launches it. Keyboard shortcuts can also be assigned to AppleScripts in the Scipt Menu using Keyboard & Mouse Settings.

AppleScript Utility

Is an application found in the AppleScript folder in the Mac OS X Applications folder. The AppleScript Utility allows the user to: Set the Default Script Edior; Enable GUI Scripting; Set Up Folder Actions; Show the Script Menu in the Menu Bar.

Xcode

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.

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 functions, text and math operations.

See also

Books

  • Adam Goldstein: AppleScript: The Missing Manual
    • 1st, O’Reilly 2005; ISBN 10: 0-596-00850-3
  • Matt Neuburg: AppleScript: The Definitive Guide
  • Bruce W. Perry: AppleScript in a Nutshell
    • 1st, O’Reilly 2001; ISBN 10: 1-56592-841-5
  • MacScripter — Updated listing of AppleScript books
  • Computer-Books.us — Online AppleScript books
  • *

    External links

  • Official page at Apple.com
  • MacScripter — AppleScripting community
  • William Cook, Donn Denman, Warren Harris, Kurt Piersol, Jens Alfke — AppleScript designers
  • "AppleScript" - (paper on the history and development of AppleScript; PDF)

Search another word or see applescripton Dictionary | Thesaurus |Spanish
Copyright © 2014 Dictionary.com, LLC. All rights reserved.
  • Please Login or Sign Up to use the Recent Searches feature