AppleScript
Encyclopedia
AppleScript is a scripting language
created by Apple Inc. and built into Macintosh operating systems
since System 7
. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language.
AppleScript is primarily an inter-application
processing system, designed to exchange data between and control other applications in order to automate repetitive tasks. AppleScript has some limited processing abilities of its own – basic calculation abilities, and some more intricate text processing tools – and is extensible, allowing the addition of scripting additions which add new functions to the language itself. Mainly, however, AppleScript relies on the built-in functionality of other applications and processes to handle complex tasks.
AppleScript has some elements of object-oriented programming
, particularly in the construction of script objects, and some Lisp-like natural language processing
tendencies, but does not strictly conform to either category.
project. HyperCard contained an English language
-based scripting language called HyperTalk
, which could be used to program 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 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.
After some uncertainty about the future of AppleScript on Apple's next generation OS, the move to Mac OS X
(around 2002), and its Cocoa
frameworks greatly increased the usefulness and flexibility of AppleScript. Cocoa applications allow application developers to implement basic scriptability for their apps with minimal effort, broadening the number of applications that are directly scriptable. At the same time, the shift to the Unix underpinnings and AppleScript's ability to run Unix commands directly allowed AppleScripts much greater control over the operating system itself. AppleScript Studio, released with Mac OS X 10.2 as part of Xcode, and later AppleScriptObjC framework, released in Mac OS X 10.6, allows users to build native Cocoa applications using AppleScript.
AppleScript is one component of Mac OS X Automation technologies, along with Services
and Automator
.
s which can reduce the time and repetitiveness of various tasks, minimize the opportunity for human error, provide consistent output, and facilitate a manageable production system. AppleScript uses Apple Events
: a set of standardized data formats that the Macintosh operating system uses to send information to applications. Apple Events allow a script to work with multiple applications simultaneously, passing data between them so that complex tasks can be accomplished without human interaction. For example, an AppleScript to create a simple web gallery might do the following:
For the user, hundreds or thousands of steps in multiple applications have been reduced to the single act of running the script, and the task is accomplished in much less time and with no possibility of random human error. A large complex script could be developed to run only once, while other scripts are used again and again.
An application's AppleScript elements are visible in the application's Scripting Dictionary (distributed as part of the application), which can be viewed in any script editor. Elements are generally grouped into suites, according to loose functional relationships between them. There are two basic kinds of elements present in any suite: Classes and Commands. Classes are scriptable objects - for example, a text editing application will almost certainly have classes for Windows, Documents, and Texts - and these classes will have properties that can be changed (window size, document background color, text font size, etc.), and may contain other classes (a window will contain one or more documents, a document will contain text, a text object will contain paragraphs and words and characters). Commands, by contrast, are commands that can be given to scriptable objects. The general format for a block of AppleScript is to tell a scriptable object to run a command.
All scriptable applications share a few basic commands and objects (usually called the Standard Suite) - commands to open, close or save a file, to print something, to quit, to set data to variables - as well as a basic application object that gives the scriptable properties of the application itself. Many applications have numerous suites capable of performing any task the application itself can perform. In exceptional cases, applications may support plugins which include their own scripting dictionaries.
AppleScript was designed with the ability to build scripts intuitively by recording user actions. When the AppleScript Editor is open and the Record button clicked, any user actions on the computer - in any application that supports AppleEvents and AppleScript recording - are converted to their equivalent AppleScript commands and placed in the script editor window. The resulting script can be saved and re-run to duplicate the original actions, or modified to be more generally useful.
AppleScript has several user interface options, including dialogs, alerts, and list of choices.
Each user interaction method can return the values of buttons clicked, items chosen or text entered for further processing.
For example:
metaphor
, just as the graphical user interface
is designed on the desktop metaphor
. A well-written AppleScript should be clear enough to be read and understood by anyone, and easily edited. 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.
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:
Alternatively, the tell may be expressed in one line by using an infinitive
:
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:
The concept of an object hierarchy
can be expressed using nested blocks:
The concept of an object hierarchy
can also be expressed using nested prepositional phrases:
which in another programming language
might be expressed as sequential method calls
:
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.
and prewritten code snippets.
AppleScript Editor (called Script Editor in versions of Mac OS X prior to 10.6 Snow Leopard): The editor for AppleScript packaged with Mac OS X. Scripts are written in document editing windows where they can be compiled and run, and these windows contain various panes in which logged information, execution results, and other information is available for debugging purposes. Access to scripting dictionaries and prewritten code snippets is available through the application menus.
Xcode
, from Apple: A suite of tools for developing applications with features for editing AppleScripts or creating full-fledged applications written with AppleScript.
Smile
and SmileLab, available from (Satimage): A third-party freeware/commercial IDE for AppleScript, itself written entirely in AppleScript. Smile is free, and primarily designed for AppleScript development. SmileLab is commercial software with extensive additions for numerical analysis, graphing, machine automation and web production. Smile and SmileLab use an assortment of different windows - AppleScript windows for running and saving full scripts, AppleScript terminals for testing code line-by-line, unicode windows for working with text and XML. Users can create complex interfaces - called dialogs - for situations where the built-in dialogs in AppleScript are insufficient.
Script Debugger
, from Late Night Software
: A third-party commercial IDE for AppleScript. Script Debugger is a more advanced AppleScript environment that allows the script writer to debug AppleScripts via single stepping
, breakpoint
s, stepping in and out of functions/subroutines, variable tracking, etc. Script Debugger also contains an advanced dictionary browser that allows the user to see the dictionary in action in real world situations. That is, rather than just a listing of what the dictionary covers, one can open a document in Pages
, for example, and see how the dictionary's terms apply to that document, making it easier to determine which parts of the dictionary 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.
FaceSpan, from Late Night Software
: a third-party commercial IDE for creating AppleScript applications with Graphic User Interfaces. Development of FaceSpan has been suspended.
Script Menu: This system-wide 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. In 10.6.x, the script menu is activated from the preferences of the AppleScript Editor; in prior versions of Mac OS X, it was activated from 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. Scripts can be organized so that they only appear in the menu when particular applications are in the foreground.
Many Apple applications, some third party applications, and some add-ons provide their own script menus. These may be activated in different ways, but all function in essentially the same manner.
Hotkey Launchers: Keyboard shortcuts can be assigned to AppleScripts in the script menu using the System Preferences "Keyboard & Mouse Settings". Various third-party utilities are available - QuickKeys, Spark
, Quicksilver
, Alfred
, TextExpander - which can run AppleScripts on demand using key combinations.
Folder Actions: Using AppleScript folder actions, scripts can be launched when specific changes occur in folders (such as adding or removing files). Folder actions can be assigned by clicking on a folder and choosing Folder Actions Setup... from the contextual menu; the location of this command differs slightly in 10.6.x from earlier versions. This same action can be achieved with third-party utilities such as Hazel.
Unix command line and launchd: AppleScripts can be run from the Unix command line, or from launchd for scheduled tasks, by using the osascript command line tool. The osascript tool can run compiled scripts (.scpt files) and plain text files (.applescript files - these are compiled by the tool at runtime). Script applications can be run using the Unix open command.
: Automator is a graphical, modular editing environment in which workflows are built up from actions. It is intended to duplicate many of the functions of AppleScript without the necessity for programming knowledge. Automator has an action specifically designed to contain and run AppleScripts, for tasks that are too complex for Automator's simplified framework.
Scriptable core system applications: These background-only applications, packaged with Mac OS X, are used to allow AppleScript to access features that would not normally be scriptable. As of 10.6.3 they include the scriptable applications for VoiceOver (scriptable auditory and braille screen reader package), System Events (control of non-scriptable applications and access to certain system functions and basic file operations), Printer Setup Utility (scriptable utility for handling print jobs), Image Events (core image manipulation), HelpViewer (scriptable utility for showing help displays), Database Events (minimal SQLite3 database interface), and AppleScript Utility (for scripting a few AppleScript related preferences), as well as a few utility applications used by the system.
AppleScriptObjC: Part of the Xcode package, a cocoa development environment, which is available on the Mac OS X install CD but not installed by default. AppleScriptObjC allows AppleScripts to call Cocoa commands directly.
AppleScript Studio: Part of the Xcode package in 10.4 and 10.5, now deprecated. A framework for attaching Cocoa interfaces to AppleScript applications.
Scripting Additions (OSAX): Scripting additions are plug-ins for AppleScript developed by Apple or third parties. They are designed to extend the built-in command set, expanding AppleScript's features and making it somewhat less dependent on functionality provided by applications. For instance, Apple's Standard Addition.osax scripting addition adds a set of commands and classes that that are not part of AppleScript's core features - without this osax, AppleScript would have no capacity to display dialogs or use navigation services.
One important variation on this block structure is in the form of on - end ... blocks that are used to define handlers (function-like subroutines). Handlers begin with on functionName and ending with end functionName, and are not executed as part of the normal script flow unless called from somewhere in the script.
Handlers can also be defined using "to" on place of "on" and can be written to accept labeled parameters, not enclosed in parens.
There are four types of predefined handlers in AppleScript - run, open, idle, and quit - each of which is created in the same way as the run handler shown above.
Run handler: Defines the main code of the script, which is called when the script is run. Run handler blocks are optional, unless arguments are being passed to the script. If an explicit run handler block is omitted, then all code that is not contained inside handler blocks is executed as though it were in an implicit run handler.
Open handler: Defined using "on open theItems".
When a script containing an "open handler' is saved as an applet, the applet becomes a droplet. A droplet can be identified in the Finder by its icon, which includes an arrow, indicating items can be dropped onto the icon. The droplet's open hander is executed when files or folders are dropped onto droplet's icon. References to the items dropped on the droplet's icon are passed to the droplet's script as the parameter of the open handler. A droplet can also be launched the same way as an ordinary applet, executing its run handler.
Idle handler: A subroutine that is run periodically by the system when the application is idle.
An idle handler can be used in applets or droplets saved as stay-open applets, and is useful for scripts that watch for particular data or events. The length of the idle time is one second by default, but can be changed by including a 'return x' statement at the end of the subroutine, where x is he number of seconds the system should wait before running the handler again.
Quit handler: A handler that is run when the applet receives a Quit request. This can be used to save data or do other ending tasks before quitting.
Script objects:
Script objects may be defined explicitly using the syntax:
Script objects can use the same 'tell' structures that are used for application objects, and can be loaded from and saved to files. Runtime execution time can be reduced in some cases by using script objects.
Using the same technique for scripting addition commands can reduce errors and improve performance.
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 API
s 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. The MacRuby
development roadmap shows that OSA conformance is planned in version 0.6.
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.
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...
created by Apple Inc. and built into Macintosh operating systems
Mac OS
Mac OS is a series of graphical user interface-based operating systems developed by Apple Inc. for their Macintosh line of computer systems. The Macintosh user experience is credited with popularizing the graphical user interface...
since System 7
System 7
System 7 is the name of a Macintosh operating system introduced in 1991.System 7 may also refer to:* System 7 , a British dance/ambient band* System 7 , 1991 album* IBM System/7, a 1970s computer system...
. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language.
AppleScript is primarily an inter-application
Inter-process communication
In computing, Inter-process communication is a set of methods for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC methods are divided into methods for message passing, synchronization, shared...
processing system, designed to exchange data between and control other applications in order to automate repetitive tasks. AppleScript has some limited processing abilities of its own – basic calculation abilities, and some more intricate text processing tools – and is extensible, allowing the addition of scripting additions which add new functions to the language itself. Mainly, however, AppleScript relies on the built-in functionality of other applications and processes to handle complex tasks.
AppleScript has some elements of object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, particularly in the construction of script objects, and some Lisp-like natural language processing
Natural language processing
Natural language processing is a field of computer science and linguistics concerned with the interactions between computers and human languages; it began as a branch of artificial intelligence....
tendencies, but does not strictly conform to either category.
History
The AppleScript project was an outgrowth of the (now discontinued) HyperCardHyperCard
HyperCard is an application program created by Bill Atkinson for Apple Computer, Inc. that was among the first successful hypermedia systems before the World Wide Web. It combines database capabilities with a graphical, flexible, user-modifiable interface. HyperCard also features HyperTalk, written...
project. HyperCard contained an English language
English language
English is a West Germanic language that arose in the Anglo-Saxon kingdoms of England and spread into what was to become south-east Scotland under the influence of the Anglian medieval kingdom of Northumbria...
-based scripting language called HyperTalk
HyperTalk
HyperTalk is a high-level, procedural programming language created in 1987 by Dan Winkler and used in conjunction with Apple Computer's HyperCard hypermedia program by Bill Atkinson. The main target audience of HyperTalk was beginning programmers, hence HyperTalk programmers were usually called...
, which could be used to program a HyperCard stack. Apple engineers recognized that a similar scripting language could be designed to be used with any application
Application software
Application software, also known as an application or an "app", is computer software designed to help the user to perform specific tasks. Examples include enterprise software, accounting software, office suites, graphics software and media players. Many application programs deal principally with...
, and the AppleScript project was born as part of System 7
System 7 (Macintosh)
System 7 is a single-user graphical user interface-based operating system for Macintosh computers. It was introduced on May 13, 1991 by Apple Computer. It succeeded System 6, and was the main Macintosh operating system until it was succeeded by Mac OS 8 in 1997...
.
AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7). QuarkXPress
QuarkXPress
QuarkXPress is a computer application for creating and editing complex page layouts in a WYSIWYG environment. It runs on Mac OS X and Windows. It was first released by Quark, Inc...
(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 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.
After some uncertainty about the future of AppleScript on Apple's next generation OS, the move to Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...
(around 2002), and its Cocoa
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...
frameworks greatly increased the usefulness and flexibility of AppleScript. Cocoa applications allow application developers to implement basic scriptability for their apps with minimal effort, broadening the number of applications that are directly scriptable. At the same time, the shift to the Unix underpinnings and AppleScript's ability to run Unix commands directly allowed AppleScripts much greater control over the operating system itself. AppleScript Studio, released with Mac OS X 10.2 as part of Xcode, and later AppleScriptObjC framework, released in Mac OS X 10.6, allows users to build native Cocoa applications using AppleScript.
AppleScript is one component of Mac OS X Automation technologies, along with Services
Services menu
The Services menu is a user interface element in a computer operating system. The services are programs that accept input from the user selection, process it, and optionally put the result back in the clipboard. The concept originated in the NeXTSTEP operating system, from which it was carried...
and Automator
Automator (software)
Automator is an application developed by Apple for Mac OS X that implements point-and-click creation of workflows for automating repetitive tasks into batches for quicker alteration, thus saving time and effort over human intervention to manually change each file separately...
.
Basic concepts
AppleScript was designed to be used as an accessible end-user scripting language, offering users an intelligent mechanism to control applications, and to access and modify data and documents. AppleScript can be used to create automated workflowWorkflow
A workflow consists of a sequence of connected steps. It is a depiction of a sequence of operations, declared as work of a person, a group of persons, an organization of staff, or one or more simple or complex mechanisms. Workflow may be seen as any abstraction of real work...
s which can reduce the time and repetitiveness of various tasks, minimize the opportunity for human error, provide consistent output, and facilitate a manageable production system. AppleScript uses Apple Events
Apple events
Apple events are the canonical message-based interprocess communication mechanism in Mac OS, first appearing in System 7 and supported by every version since then, including Mac OS X. Apple events describe "high-level" events such as "open document" or "print file", whereas earlier OS's had...
: a set of standardized data formats that the Macintosh operating system uses to send information to applications. Apple Events allow a script to work with multiple applications simultaneously, passing data between them so that complex tasks can be accomplished without human interaction. For example, an AppleScript to create a simple web gallery might do the following:
- Open a photo in a photo-editing application (by sending that application an Open File Apple Event).
- Tell the photo-editing application to manipulate the image (e.g. reduce its resolution, add a border, add a photo credit)
- Tell the photo-editing application to save the changed image in a file in some different folder (by sending that application an Save and/or Close Apple Events).
- Send the new file path (via another Apple Event) to a text editor or web editor application
- Tell that editor application to write a link for the photo into an HTML file.
- Repeat the above steps for an entire folder of images (hundreds or even thousands of photos).
- Upload the HTML file and folder of revised photos to a website, by sending Apple Events to an FTP client, by using built-in AppleScript commands, or by sending Apple Events to Unix ftp utilities.
For the user, hundreds or thousands of steps in multiple applications have been reduced to the single act of running the script, and the task is accomplished in much less time and with no possibility of random human error. A large complex script could be developed to run only once, while other scripts are used again and again.
An application's AppleScript elements are visible in the application's Scripting Dictionary (distributed as part of the application), which can be viewed in any script editor. Elements are generally grouped into suites, according to loose functional relationships between them. There are two basic kinds of elements present in any suite: Classes and Commands. Classes are scriptable objects - for example, a text editing application will almost certainly have classes for Windows, Documents, and Texts - and these classes will have properties that can be changed (window size, document background color, text font size, etc.), and may contain other classes (a window will contain one or more documents, a document will contain text, a text object will contain paragraphs and words and characters). Commands, by contrast, are commands that can be given to scriptable objects. The general format for a block of AppleScript is to tell a scriptable object to run a command.
All scriptable applications share a few basic commands and objects (usually called the Standard Suite) - commands to open, close or save a file, to print something, to quit, to set data to variables - as well as a basic application object that gives the scriptable properties of the application itself. Many applications have numerous suites capable of performing any task the application itself can perform. In exceptional cases, applications may support plugins which include their own scripting dictionaries.
AppleScript was designed with the ability to build scripts intuitively by recording user actions. When the AppleScript Editor is open and the Record button clicked, any user actions on the computer - in any application that supports AppleEvents and AppleScript recording - are converted to their equivalent AppleScript commands and placed in the script editor window. The resulting script can be saved and re-run to duplicate the original actions, or modified to be more generally useful.
Hello, World!
In AppleScript, the traditional Hello, world! program could be written in many of different forms:AppleScript has several user interface options, including dialogs, alerts, and list of choices.
Each user interaction method can return the values of buttons clicked, items chosen or text entered for further processing.
For example:
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 languageNatural language programming
Natural language programming - NLP - is an ontology-assisted way of programming in terms of natural language sentences, e.g. English. A structured document with Content, sections and subsections for explanations of sentences forms a NLP document, which is actually a computer program.An example...
metaphor
Metaphor
A metaphor is a literary figure of speech that uses an image, story or tangible thing to represent a less tangible thing or some intangible quality or idea; e.g., "Her eyes were glistening jewels." Metaphor may also be used for any rhetorical figures of speech that achieve their effects via...
, just as the graphical user interface
Graphical user interface
In computing, a graphical user interface is a type of user interface that allows users to interact with electronic devices with images rather than text commands. GUIs can be used in computers, hand-held devices such as MP3 players, portable media players or gaming devices, household appliances and...
is designed on the desktop metaphor
Desktop metaphor
The desktop metaphor is an interface metaphor which is a set of unifying concepts used by graphical user interfaces to help users more easily interact with the computer. The desktop metaphor treats the monitor of a computer as if it is the user's desktop, upon which objects such as documents and...
. A well-written AppleScript should be clear enough to be read and understood by anyone, and easily edited. 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
AppleEvent Object Model
The AppleEvent Object Model was a set of protocols built on top of AppleEvents by which applications running under Mac OS could control each other's functions. Applications that implemented some part of the AEOM were called scriptable because they could be controlled via AppleScript...
(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.
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
Bytecode
Bytecode, also known as p-code , is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software interpreter as well as being suitable for further compilation into machine code...
Apple Events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In the Xcode
Xcode
Xcode is a suite of tools, developed by Apple, for developing software for Mac OS X and iOS. Xcode 4.2, the latest major version, is available on the Mac App Store for free for Mac OS X 10.7 , and on the Apple Developer Connection website for free to registered developers Xcode is a suite of tools,...
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:
Alternatively, the tell may be expressed in one line by using an infinitive
Infinitive
In grammar, infinitive is the name for certain verb forms that exist in many languages. In the usual description of English, the infinitive of a verb is its basic form with or without the particle to: therefore, do and to do, be and to be, and so on are infinitives...
:
For events in the "Core Suite" (activate, open, reopen, close, print, and quit), the application may be supplied as the direct object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
to transitive commands:
The concept of an object hierarchy
Hierarchy
A hierarchy is an arrangement of items in which the items are represented as being "above," "below," or "at the same level as" one another...
can be expressed using nested blocks:
The concept of an object hierarchy
Hierarchy
A hierarchy is an arrangement of items in which the items are represented as being "above," "below," or "at the same level as" one another...
can also be expressed using nested prepositional phrases:
which in another programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
might be expressed as sequential method calls
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
:
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.
Script editors
Script editors provide a unified programing environment for AppleScripts, including tools for composing, validating, compiling, running, and debugging scripts. They also provide mechanisms for opening and viewing AppleScript dictionaries from scriptable applications, saving scripts in a number of formats (compiled script files, application packages, script bundles, and plain text files), and usually provide features such as syntax highlightingSyntax highlighting
Syntax highlighting is a feature of some text editors that display text—especially source code—in different colors and fonts according to the category of terms. This feature eases writing in a structured language such as a programming language or a markup language as both structures and...
and prewritten code snippets.
AppleScript Editor (called Script Editor in versions of Mac OS X prior to 10.6 Snow Leopard): The editor for AppleScript packaged with Mac OS X. Scripts are written in document editing windows where they can be compiled and run, and these windows contain various panes in which logged information, execution results, and other information is available for debugging purposes. Access to scripting dictionaries and prewritten code snippets is available through the application menus.
Xcode
Xcode
Xcode is a suite of tools, developed by Apple, for developing software for Mac OS X and iOS. Xcode 4.2, the latest major version, is available on the Mac App Store for free for Mac OS X 10.7 , and on the Apple Developer Connection website for free to registered developers Xcode is a suite of tools,...
, from Apple: A suite of tools for developing applications with features for editing AppleScripts or creating full-fledged applications written with AppleScript.
Smile
Smile (software)
Smile is a Macintosh computer programming and working environment based on AppleScript. It features a number of production technologies and a natural fashion of having them work together...
and SmileLab, available from (Satimage): A third-party freeware/commercial IDE for AppleScript, itself written entirely in AppleScript. Smile is free, and primarily designed for AppleScript development. SmileLab is commercial software with extensive additions for numerical analysis, graphing, machine automation and web production. Smile and SmileLab use an assortment of different windows - AppleScript windows for running and saving full scripts, AppleScript terminals for testing code line-by-line, unicode windows for working with text and XML. Users can create complex interfaces - called dialogs - for situations where the built-in dialogs in AppleScript are insufficient.
Script Debugger
Script Debugger
Script Debugger is a Macintosh computer source code editor and debugging environment for the AppleScript programming language, and other languages based on Apple Inc.'s Open Scripting Architecture...
, from Late Night Software
Late Night Software
Late Night Software Ltd., is a privately held Canadian software company that has produced several applications, utilities, and developer's tools for the Macintosh computer platform. The company was established in 1995. Its president is Mark Alldritt....
: A third-party commercial IDE for AppleScript. Script Debugger is a more advanced AppleScript environment that allows the script writer to debug AppleScripts via single stepping
Program animation
Program animation or Stepping refers to the very common debugging method of executing code one "line" at a time. The programmer may examine the state of the program, machine, and related data before and after execution of a particular line of code...
, breakpoint
Breakpoint
In software development, a breakpoint is an intentional stopping or pausing place in a program, put in place for debugging purposes. It is also sometimes simply referred to as a pause....
s, stepping in and out of functions/subroutines, variable tracking, etc. Script Debugger also contains an advanced dictionary browser that allows the user to see the dictionary in action in real world situations. That is, rather than just a listing of what the dictionary covers, one can open a document in Pages
Pages
Pages is a word processor and page layout application developed by Apple. It is part of the iWork productivity suite and runs on the Mac OS X & iOS operating systems. The first version of Pages was announced on January 11, 2005, and was released one month later. The most recent Macintosh version,...
, for example, and see how the dictionary's terms apply to that document, making it easier to determine which parts of the dictionary 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.
FaceSpan, from Late Night Software
Late Night Software
Late Night Software Ltd., is a privately held Canadian software company that has produced several applications, utilities, and developer's tools for the Macintosh computer platform. The company was established in 1995. Its president is Mark Alldritt....
: a third-party commercial IDE for creating AppleScript applications with Graphic User Interfaces. Development of FaceSpan has been suspended.
Script launchers
AppleScripts can be run from a script editor, but it is usually more convenient to run scripts directly, without opening a script editor application. There are a number of options for doing so:Script Menu: This system-wide 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. In 10.6.x, the script menu is activated from the preferences of the AppleScript Editor; in prior versions of Mac OS X, it was activated from 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. Scripts can be organized so that they only appear in the menu when particular applications are in the foreground.
Many Apple applications, some third party applications, and some add-ons provide their own script menus. These may be activated in different ways, but all function in essentially the same manner.
Hotkey Launchers: Keyboard shortcuts can be assigned to AppleScripts in the script menu using the System Preferences "Keyboard & Mouse Settings". Various third-party utilities are available - QuickKeys, Spark
Spark (software)
Spark is a free open source instant messaging client for the XMPP XML-based protocol for queuing and exchanging audio and text messages and subscribed users lists over the Internet. It is written in Java. It can be used standalone or as an add-on or plugin to certain Web browsers. It appears...
, Quicksilver
Quicksilver (software)
Quicksilver is a computer utility software program for Mac OS X, originally developed by Blacktree Software and distributed freely. It is essentially a graphical shell for the Mac OS X operating system, allowing users to use the keyboard to rapidly perform tasks such as launching...
, Alfred
Alfred (software)
Alfred is an application launcher and search utility for Mac OS X. Alfred is free, though an optional paid upgrade is available.Using a keyboard shortcut chosen by the user, Alfred is able to quickly find and open software applications, files, and contacts on a particular machine...
, TextExpander - which can run AppleScripts on demand using key combinations.
Folder Actions: Using AppleScript folder actions, scripts can be launched when specific changes occur in folders (such as adding or removing files). Folder actions can be assigned by clicking on a folder and choosing Folder Actions Setup... from the contextual menu; the location of this command differs slightly in 10.6.x from earlier versions. This same action can be achieved with third-party utilities such as Hazel.
Unix command line and launchd: AppleScripts can be run from the Unix command line, or from launchd for scheduled tasks, by using the osascript command line tool. The osascript tool can run compiled scripts (.scpt files) and plain text files (.applescript files - these are compiled by the tool at runtime). Script applications can be run using the Unix open command.
Related scripting issues
AutomatorAutomator (software)
Automator is an application developed by Apple for Mac OS X that implements point-and-click creation of workflows for automating repetitive tasks into batches for quicker alteration, thus saving time and effort over human intervention to manually change each file separately...
: Automator is a graphical, modular editing environment in which workflows are built up from actions. It is intended to duplicate many of the functions of AppleScript without the necessity for programming knowledge. Automator has an action specifically designed to contain and run AppleScripts, for tasks that are too complex for Automator's simplified framework.
Scriptable core system applications: These background-only applications, packaged with Mac OS X, are used to allow AppleScript to access features that would not normally be scriptable. As of 10.6.3 they include the scriptable applications for VoiceOver (scriptable auditory and braille screen reader package), System Events (control of non-scriptable applications and access to certain system functions and basic file operations), Printer Setup Utility (scriptable utility for handling print jobs), Image Events (core image manipulation), HelpViewer (scriptable utility for showing help displays), Database Events (minimal SQLite3 database interface), and AppleScript Utility (for scripting a few AppleScript related preferences), as well as a few utility applications used by the system.
AppleScriptObjC: Part of the Xcode package, a cocoa development environment, which is available on the Mac OS X install CD but not installed by default. AppleScriptObjC allows AppleScripts to call Cocoa commands directly.
AppleScript Studio: Part of the Xcode package in 10.4 and 10.5, now deprecated. A framework for attaching Cocoa interfaces to AppleScript applications.
Scripting Additions (OSAX): Scripting additions are plug-ins for AppleScript developed by Apple or third parties. They are designed to extend the built-in command set, expanding AppleScript's features and making it somewhat less dependent on functionality provided by applications. For instance, Apple's Standard Addition.osax scripting addition adds a set of commands and classes that that are not part of AppleScript's core features - without this osax, AppleScript would have no capacity to display dialogs or use navigation services.
Classes (data types)
AppleScript has a number of built-in classes (or data types), though of course an application can and most likely will define extra data types for its own purposes. The basic data classes that should be universally recognized are as follows:- File system
- alias - a reference to a file system object (file or folder). The alias will maintain its link to the object if the object is moved or renamed.
- file - a reference to a file system object (file or folder). This is a static reference, and can point to an object that does not currently exist.
- POSIX file - a reference to a file system object (file or folder) in plain text, using Unix style notation.
- Basic objects
- application - an application object, used mostly as a specifier for tell statements (tell application "Finder" ...)
- script - a script object. Script objects are containers for scripts. Every AppleScript creates a script object when run, and script objects may be created within AppleScripts.
- class - a meta-object that specifies the type of other objects
- reference - a persistent, indirect pointer to a different object. 'Reference to X' will always return X's current value
- Standard data objects
- boolean - true/false value
- constant - a developer-only class that specifies a constant. AppleScript contains a number of predefined constants - pi, tab, return - but this allows for applications to define their own constants.
- number - rarely used over-arching class for integer and real. it is implicitly invoked when you set a variable to a value without checking whether the value is integer or real.
- integer
- real
- date - a date in AppleScript format. This class allows for a number of date and time manipulations.
- text - text. In versions of AppleScript before 2.0 (Mac OS X 10.5) the 'text' class was distinct from 'string' and 'Unicode text' and the three behaved somewhat differently; in 10.5 and later, they are all synonyms and all text is handled as Unicode.
- Container objects
- list - ordered list of objects. it can contain any class, including those defined by applications and other lists.
- record - keyed list of objects. like lists, except structured as key value pairs.
- Miscellaneous
- RGB color - specifies an RGB triplet, for use in commands and objects that work with colors.
- unit types - class that converts between standard units. For instance, a value can be defined as square yards, and then reported back as square feet merely by changing the unit type.
Language structures
Many AppleScript processes are managed by blocks of code, where a block begins with a command command and ends with an end command statement: for instance:Looping | Conditionals | Application Targeting | Error Handling |
---|---|---|---|
One important variation on this block structure is in the form of on - end ... blocks that are used to define handlers (function-like subroutines). Handlers begin with on functionName and ending with end functionName, and are not executed as part of the normal script flow unless called from somewhere in the script.
Function handler | Folder actions block | Run handler |
---|---|---|
Handlers can also be defined using "to" on place of "on" and can be written to accept labeled parameters, not enclosed in parens.
Handler with Labeled Parameters | Handler Using "to" and Labeled Parameters |
---|---|
There are four types of predefined handlers in AppleScript - run, open, idle, and quit - each of which is created in the same way as the run handler shown above.
Run handler: Defines the main code of the script, which is called when the script is run. Run handler blocks are optional, unless arguments are being passed to the script. If an explicit run handler block is omitted, then all code that is not contained inside handler blocks is executed as though it were in an implicit run handler.
Open handler: Defined using "on open theItems".
When a script containing an "open handler' is saved as an applet, the applet becomes a droplet. A droplet can be identified in the Finder by its icon, which includes an arrow, indicating items can be dropped onto the icon. The droplet's open hander is executed when files or folders are dropped onto droplet's icon. References to the items dropped on the droplet's icon are passed to the droplet's script as the parameter of the open handler. A droplet can also be launched the same way as an ordinary applet, executing its run handler.
Idle handler: A subroutine that is run periodically by the system when the application is idle.
An idle handler can be used in applets or droplets saved as stay-open applets, and is useful for scripts that watch for particular data or events. The length of the idle time is one second by default, but can be changed by including a 'return x' statement at the end of the subroutine, where x is he number of seconds the system should wait before running the handler again.
Quit handler: A handler that is run when the applet receives a Quit request. This can be used to save data or do other ending tasks before quitting.
Script objects:
Script objects may be defined explicitly using the syntax:
Script objects can use the same 'tell' structures that are used for application objects, and can be loaded from and saved to files. Runtime execution time can be reduced in some cases by using script objects.
Miscellaneous information
- Variables are not strictly typed, and do not need to be declared. Variables can take any data type (including scripts and functions). The following commands are examples of the creation of variables:
- Script objects are full objects - they can encapsulate methods and data and inherit data and behavior from a parent script.
- Subroutines cannot be called directly from application tell blocks. Use the 'my' or 'of me' keywords to do so.
Using the same technique for scripting addition commands can reduce errors and improve performance.
Open Scripting Architecture
An important aspect of the AppleScript implementation is the Open Scripting Architecture (OSA). Apple provides OSA for third-party scripting/automation products such as QuicKeys and UserLandUserLand Software
UserLand Software is a US software company founded by Dave Winer in 1988. UserLand sells Web content management and blogging software packages and services.-Company History:Dave Winer founded the company in 1988 after leaving Symantec in the spring of 1988...
Frontier, to function on an equal status with AppleScript. AppleScript was implemented as a scripting component
Component Manager
In Apple Macintosh computer programming, Component Manager was one of many approaches to sharing code that originated on the pre-PowerPC Macintosh. It was originally introduced as part of QuickTime, which remained the part of Mac OS that used it most heavily....
, 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 API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...
s 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
JavaScript OSA
JavaScript OSA, , is a freeware inter-process communication scripting language for the Macintosh computer....
component remains the only serious OSA language alternative to AppleScript, though the Macintosh versions of Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
, and Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...
all support native means of working with AppleEvents without being OSA components. The MacRuby
MacRuby
MacRuby is an implementation of the Ruby language that runs on the Objective-C runtime and CoreFoundation framework under development by Apple Inc. which "is supposed to replace RubyCocoa". It is based on Ruby 1.9 and uses the high performance Low Level Virtual Machine compiler infrastructure...
development roadmap shows that OSA conformance is planned in version 0.6.
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.
Further reading
- Mark Conway Munro, "AppleScript (Developer Reference)", Wiley (2010); ISBN 978-0-470-56229-1
- Hanaan Rosenthal & Hamish Sanderson, Learn AppleScript: The Comprehensive Guide to Scripting and Automation on Mac OS X, Third Edition, ApressApressApress, Inc. is a publisher of information technology books, based in New York City. It is a division of Springer Science+Business Media.Apress was founded by authors Gary Cornell and Dan Appleman. Its original name was Author's Press, shortened to APress, then Apress. In 2003, Apress purchased...
(2010); ISBN 978-1-4302-2361-0 - Sal SoghoianSal SoghoianSal Soghoian is the AppleScript Product Manager at Apple Inc.. Sal was an advocate for AppleScript years before being employed by Apple. Soghoian's job includes making public appearances to demonstrate Apple technologies, including the 2004 WWDC, when he appeared on stage with Steve Jobs to...
& Bill Cheeseman, Apple Training Series: AppleScript 1-2-3, Peachpit Press (2009); ISBN 0-321-14931-9 - Jerry Lee Ford Jr., AppleScript Programming for the Absolute Beginner, Course Technology (2007); ISBN 978-1-59863-384-9
- Matt Neuburg, AppleScript: The Definitive Guide, O'Reilly MediaO'Reilly MediaO'Reilly Media is an American media company established by Tim O'Reilly that publishes books and Web sites and produces conferences on computer technology topics...
(2006); ISBN 0-596-10211-9 - Adam Goldstein, AppleScript: The Missing Manual, O'Reilly MediaO'Reilly MediaO'Reilly Media is an American media company established by Tim O'Reilly that publishes books and Web sites and produces conferences on computer technology topics...
(2005); ISBN 0-596-00850-3 - Tom Trinko, AppleScript for Dummies, For Dummies (2004); ISBN 978-0-7645-7494-8
External links
- AppleScript Language Guide html pdf
- Official page for Application Developers at Apple.com
- MacScripter: AppleScripting community
- Mac OS X Automation
- AppleScript (PDF): paper on the history and development of AppleScript
- Doug's AppleScripts for iTunes: AppleScripts for iTunes with source provided