Results for AppleScript
On this page:
 

An English-like command language for the Macintosh introduced with System 7 Pro and supported in Mac OS X, even though OS X has its own Unix commands. Like the command lines and batch files in DOS/Windows, AppleScript is used to invoke numerous functions and automate repetitive tasks. A variety of pre-written scripts are available, and Apple's Script Editor is used to write one's own.



 
 
Wikipedia: 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.


AppleScript
Developer: Apple Inc.
Latest release: 1.10.7/ 2006-06-30
OS: 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. The Mac OS required extensive upgrades to implement AppleScript. (See below for details). Much of the underlying technology changes were made as part of the massive System 7 release, notably the Apple events concept. AppleScript was vying for developer attention along with many other new technologies introduced at the same time (Balloon help, Publish and Subscribe, etc.). For some applications, AppleScript was among the most difficult of the System 7 technologies to implement, requiring a re-write of major portions of the "low level" code in an application. Apple's own application framework, MacApp, did not directly support Apple events for some time.

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 no effort on the part of the developer, and are "well-scriptable" for the cost of writing a text file. 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 primarily as a Desktop scripting language, offering users an intelligent mechanism to control applications and documents in order to create automated workflows. AppleScript scripts act like an automatic pilot for the Mac, temporarily taking control of the system from the user in order to perform repetitive tasks on their behalf as efficiently as possible. Automating a workflow with AppleScript reduces the amount of time it takes to perform, 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. (Recent versions of AppleScript can also manipulate user interfaces, which is useful for applications which have not exposed their object models, but this is a late addition and not the preferred way to use AppleScript.)

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 a 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, 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".

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 block" construct:

<source lang="applescript"> tell application "Microsoft Word"

 quit

end tell </source>

Alternatively, the tell block may be expressed in one line by using an infinitive:

<source lang="applescript"> tell application "Microsoft Word" to quit </source>

Though 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:

<source lang="applescript"> quit application "Microsoft Word" </source>

The concept of an object hierarchy can be expressed using nested blocks:

<source lang="applescript"> 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 </source>

The concept of an object hierarchy can also be expressed using nested prepositional phrases:

<source lang="applescript"> pixel 7 of row 3 of TIFF image "my bitmap" </source>

which in another programming language might be expressed as sequential function calls:

<source lang="applescript"> getTIFF("my bitmap").getRow(3).getPixel(7); </source>

Many applications do not store pointers directly into anything but the lowest level objects; for instance, a word processor almost certainly has an object that returns all of the characters in a document, but may not have objects representing pages, paragraphs or documents as a whole. Since the authors intended AppleScript to be added to existing applications without too much redesign, they also provided a second way to write accessors known as iterators. Using iterators requires the developer only to keep track of the current location of an object, and provide a method to find the "next one". For instance, paragraph objects could be supported with a single pointer to the current paragraph, and a method that finds the next one by looking for a return character.

Note the similarities between the AEOM model and the considerably more recent DOM system used in XML. Both decompose a document into a hierarchy of objects, and offer the programmer a standardized iterative method to access the contents. Differences between the systems lie primarily in the user-level syntax, with AppleScript introducing a number of different ways to refer to any particular object. For instance, 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 very simple tasks, AppleScript can be used for self-contained applets. For instance, the script:

<source lang="applescript"> 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" </source>

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 well beyond its humble beginnings. AppleScript Studio is a development environment, which comes free with Mac OS X, which uses AppleScript as the primary programming language, in conjunction with the Cocoa framework used to construct graphical user interfaces.

With Mac OS X v10.3 ("Panther") and Mac OS X v10.4 ("Tiger"), AppleScript Studio and Project Builder have been rolled into the Xcode IDE. Interface Builder, another component of Xcode, lets you build a user interface in a drag-and-drop fashion (similar to Visual Basic) and then "run" the user interface to see what the forms and menus looks like.

Script Editor

Panther and Tiger also come with an enhanced version of Script Editor for writing, editing, compiling and running AppleScripts. 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 dialects

AppleScript initially supported the idea of multiple dialects: different syntactic representations of the same script. The standard dialect was English; French and Japanese dialects were also produced. (A C dialect was publicly discussed, but never shipped.) A dialect could redefine the keywords and even the grammar of the language, so that, for instance, commands in the Japanese dialect had the verb at the end. Because AppleScript stores scripts in a compiled form, it could compile a script in one dialect and decompile it in another. While the project was a technical success, few application developers provided terminology in multiple languages, which meant that scripts were a confusing mix of languages in most cases. Support for multiple dialects was dropped by Apple in Mac OS 8.5.

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:

<source lang="applescript"> on run

 -- do something when this script is launched

end run </source>

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:

<source lang="applescript"> on open theItems

 -- do something when filesystem items are dropped on this script

end open </source>

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:

<source lang="applescript"> on idle

 -- do something, then pause, then do it again, then pause, etc.
 return 20

end idle </source>

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 architecture was the ability to write language extensions, which were based on Hypercard's external commands. Such an extension was called a "scripting addition", or osax for Open Scripting Architecture eXtension. (The coiners of the term osax, Jon Pugh and Donald Olson, consider the proper spelling to use all lowercase letters: osax and osaxen.) Because an extension adds terms to the language, it sometimes became problematic to predict how the AppleScript compiler would behave given a specific syntax depending upon which osaxen were installed at runtime.

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.
  • iMacros for Firefox - third-party browser-based macro tool

Books

External links

Official

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:

Other Resources


 
 

Join the WikiAnswers Q&A community. Post a question or answer questions about "AppleScript" at WikiAnswers.

 

Copyrights:

Computer Desktop Encyclopedia. THIS COPYRIGHTED DEFINITION IS FOR PERSONAL USE ONLY.
All other reproduction is strictly prohibited without permission from the publisher.
© 1981-2008 Computer Language Company Inc.  All rights reserved.  Read more
Wikipedia. This article is licensed under the GNU Free Documentation License. It uses material from the Wikipedia article "AppleScript" Read more

Search for answers directly from your browser with the FREE Answers.com Toolbar!  
Click here to download now. 

Get Answers your way! Check out all our free tools and products.

On this page:   E-mail   print Print  Link  

 

Keep Reading

Mentioned In: