AppleScript

From Wikipedia, the free encyclopedia

Jump to: navigation, search
AppleScript
Image:AppleScript Editor Logo.png
Developer Apple Inc.
Latest release 2.0/ 2007-10-26; 525 days ago
OS System 7, Mac OS 8, Mac OS 9, Mac OS X
License Apple EULA (parts available under APSL)
Website 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.

Contents

[edit] 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. This in turn led to AppleScript being widely adopted within the publishing and prepress world, often tying together entire complex workflows. This was a key factor in retaining the Macintosh's dominant position in publishing and prepress, even after QuarkXpress and other publishing 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.

[edit] 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.

An important characteristic of AppleScript is that the same script can address more than one application, and pass data and commands between them (interapplication communication). This is possible because all Mac programs tend to use somewhat standard Apple Events to communicate with the operating system; AppleScript leverages this to allow the programs to communicate with each other as well.

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, creating a Web-ready photo gallery. The script might then upload the gallery to the user's Web site using an FTP client. 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.

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.

[edit] Hello World!

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

say "Hello World!"

The result is that your computer will say hello word in the default voice. In order to change the default voice go to the voice tab in "System Preferences". Or you can write the script like this:

say "Hello World!" using "Alex"

"Alex" is just an example. There are many other voices

[edit] 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.

[edit] 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 are 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.

[edit] AppleScript and Cocoa

With each version of Mac OS X it has become simpler for developers to implement AppleScript[1] 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.

[edit] 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.

[edit] AppleScript development tools

[edit] Automator

Automator enables graphical, drag-and-drop editing and creation of workflows by joining together modules, or actions, (that can be created in a number of languages, including AppleScript), with no knowledge of AppleScript coding required. Automator workflows can be saved as applications for later use. Automator is included with Mac OS X 10.4 and later.

[edit] Script Editor

Script Editor is an editor for AppleScript 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 Apple Events 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.

[edit] Script Menu

The system-wide script menu provides access to AppleScripts from the Mac OS X menu bar, visible no matter what application is running. Selecting a script in the script menu launches it.

The script menu can be activated using the AppleScript Utility application. When first activated, the script menu displays a default library of fairly generic, functional AppleScripts, which can also be opened in Script Editor and used as examples for learning AppleScript. Keyboard shortcuts can also be assigned to AppleScripts in the script menu using the System Preferences "Keyboard & Mouse Settings".

A few applications (such as BBEdit) also have their own script menus, which show only the scripts for use within that application.

[edit] AppleScript Utility

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.

[edit] AppleScript Studio

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 Studio is not an actual standalone product, but rather a marketing name for the ability of Xcode to create applications using AppleScript.

[edit] Script Debugger

Script Debugger, from Late Night Software, is a third-party commercial IDE for AppleScript. Script Debugger is a more advanced AppleScript environment that allows you to debug AppleScripts via single stepping, breakpoints, stepping in and out of functions/subroutines, variable tracking, etc. Script Debugger also contains an advanced dictionary browser that allows you to see the dictionary in action in real world situations. That is, rather than just a listing of what the dictionary covers, you can open a document in say Apple's Pages, and see how the dictionary's terms apply to that document, making it easier to figure out what parts of the dictionary you would want to use. Script Debugger is not designed to create scripts with a GUI, other than basic alerts and dialogs, but is focused more on the coding and debugging of scripts.

[edit] FaceSpan

FaceSpan, from Late Night Software, is a third-party commercial IDE for creating AppleScript applications with GUIs. It has much of the same functionality as Xcode's AppleScript abilities, but without the ability to talk to the larger Cocoa frameworks.

[edit] Smile

Smile, from Satimage is a third-party commercial IDE for creating AppleScripts, and is a more advanced AppleScript environment than Apple's Script Editor.

[edit] 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"

[edit] 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".)

[edit] Open Scripting Architecture

An important aspect of the AppleScript implementation is the Open Scripting Architecture (OSA).[2] Apple provides 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.

[edit] References

[edit] Further reading

[edit] External links

Personal tools