Understanding AppleScript Syntax

 < Day Day Up > 

Creating Advanced Automation with AppleScript

Although Automator is a great tool for stringing together prebuilt actions to create an automated workflow, it is neither the first nor the only means of automating actions on your Macintosh. AppleScript, originally introduced in the early '90s, provides much greater control over your entire system.

AppleScript is intended to provide a means for Macintosh users to develop complex scripts with the ability to evaluate conditions and branch, if needed. The syntax is surprisingly simple and can be understood even if you've never seen a programming language before. For example, consider the following code:

 tell application "Finder"     activate     close window "Applications" end tell 

It doesn't look like a programming language, but it is. This small example instructs Tiger to activate the Finder application and then close an open window with the title Applications.

Using a language that can almost be read aloud and understood, normal users can write scripts that combine the capabilities of multiple applications.

Using the Script Editor

The easiest way to get started with AppleScript is with the Script Editor. In addition to being a context-sensitive programming editor, it also acts as a script recorder. A user can open the Script Editor, click Record, and generate an AppleScript by using the editor to monitor his actions while interacting with a recordable application unfortunately, very few are.

The Script Editor serves as your primary entry and testing point for any AppleScript development, either recorded or entered by hand.

Script Editor Controls

Launch the Script Editor (/Applications/AppleScript/Script Editor) to begin scripting. Figure 4.8 shows the initial editor window.

Figure 4.8. The Script Editor is used when editing or recording AppleScripts.

The Script Editor recording and editing tools include

  • Record/Stop/Run Similar to a tape deck, these buttons are used to control recording and playback of an AppleScript. Click the Record button (Command-D) to start monitoring your system for Apple events within scriptable applications. These events are then stored in a script. The Stop button (Command-.) is used to stop recording, whereas the Run button (Command-R) executes the actions.

  • Compile Reviews the syntax of the current script for errors and automatically reformats the script if needed.

  • Bundle Contents If the script is saved as an application or script bundle, this button becomes active. A bundle is a folder structure that appears as a single file. Clicking Bundle Contents reveals the inner structure of the bundle and allows you to drag in additional script resources, images, and the like so that they can all be distributed as part of your script.

  • Content The content area is used to compose and edit script content. It functions like any text editor, but has the benefit of automatically formatting code when syntax is checked or the script is run.

  • Description/Result/Event Log This area is used to display information from or about the script, depending on the active button at the bottom of the window.

To start using the editor, click the Record button, switch to the Finder, and then open and drag a few windows around. As you work in the Finder, an AppleScript will build in the editor window. Click Stop to finish the code block and prepare it for execution. Figure 4.9 displays a script that has just finished generating.

Figure 4.9. Click Record to monitor your actions and build an AppleScript; click Stop to finish the script.

You can immediately replay the recorded actions by clicking the Run button.

Exploring the Scripting Dictionary

Obviously, the biggest draw to AppleScript is the capability to create scripts from scratch. Recording is a good way to get a quick start, but it can't be used to generate anything truly useful. The basic AppleScript syntax is covered later in this chapter in the section "Understanding AppleScript Syntax." Even this, however, is useless without knowledge of what commands an application can accept. Thankfully, each scriptable application contains a dictionary that shows the scripting features it supports.

To access a scripting dictionary for any application or scripting addition, choose File, Open Dictionary from the menu. A list of the available scriptable applications is displayed, as demonstrated by Figure 4.10. You can select multiple applications by holding down the Apple key.

Figure 4.10. Choose from the available scriptable applications.

Be aware that some applications might not be shown. The Browse button at the bottom of the window opens a standard File Open dialog for choosing an arbitrary file. After you've picked an application from the default or browse view, a dictionary browser window appears, as shown in Figure 4.11.

Figure 4.11. The dictionary documents the available AppleScript functions.

The browser toolbar works like many of Apple's other applications: The arrows move back and forth through dictionary entries and the search field provides an instant lookup of any key term you might need.

Below the toolbar are several columns. In the default view mode, the first column allows you to select suites of dictionary entries. A suite is simply a categorization for a certain types of AppleScript functionality. The DVD Player, for example, has a DVD Suite that contains all the necessary information for working with DVDs. Some applications might include other suites as well, such as a Standard Suite that provides everything you need to open and close documents, print, and so on. These additional suites are shared throughout the system and enable programmers to use a common syntax when doing everything from creating a new web browser window to creating a new text document.

When a suite is selected, all the available entries within that suite appear to the right and a complete summary of all suite keywords is displayed in the pane below the columns, as shown in Figure 4.12.

Figure 4.12. When a suite is selected, all entries are displayed in the lower pane.

To show a given entry within a suite, select it in the second pane and only its description will appear.

So, what are these entries? What do they represent? Each item within a suite is labeled as either a noun (n.) or a verb (v.); that is, a command or an event. Nouns are classes that you can either get information about or act on in some way. A class is an abstraction of a component of an application you work with, such as a file. When you work with a class, you work with an instance of a class, which is called an object. Objects can have properties that can be set or modified to effect changes to the object. In some cases, you might notice additional entries in the far-right column after you've selected an object. These entries are properties of the noun.

Since suites contain classes, commands, and objects contain properties and other objects, and because Apple has decided to refer to commands as commands, verbs, and events, and classes as nouns…things can get pretty confusing. To help make some sense of it, Apple adds one of five icons to the right of a dictionary entry to help quickly define its role:

Orange "S" A suite.

Blue "C" A command (or verb, or event).

Purple "C" A class.

Purple "P" An object property.

Orange "E" An object that is contained in another object.

For example, the Address Book suite contains a Person object. For a given Person, there are many different properties that can be assigned, as can be shown in Figure 4.13, as well as other objects contained within the Person.

Figure 4.13. The Person object contains many attributes that describe a person.

Each property is has a certain data type, such as an integer, image, text string, and so on. In this example, the title attribute of a person is a Unicode text string, whereas the image attribute is a TIFF.

By digging even further through the dictionary, we can find that there is a specific property of the Address Book application called my card, which, in turn, is an instance of the Person class representing the current user, as shown in Figure 4.14.

Figure 4.14. The my card object represents the currently active user.

The only way to find everything you can do with AppleScript is to dig and experiment. The dictionary browser provides two other browsing modes to help.

Using Alternative Browsing Modes

By default, the dictionary browser shows suites. In some cases, however, you might be more interested in seeing a hierarchical view of what is contained within a given set of objects, or viewing the entire inheritance tree for the application from top to bottom.


The Containment view, the middle button in the view controls of the toolbar, bases its display on how objects are contained within one another. For example, the Address Book application starts with an Application container. Within that container are documents, groups, people, and windows each of which, in turn, can contain additional elements. Groups, for example, can contain people and more groups. Because groups can contain groups, you could find yourself browsing an infinite loop, as seen in Figure 4.15.

Figure 4.15. The Containment view displays elements based on what other elements they contain.

The last viewing mode, Inheritance, uses the object hierarchy of the system to browse a dictionary. AppleScript is an object-oriented environment. This means that the classes you browse can inherit information and features from parent classes and subclasses can, in turn, inherit information from them. Remember earlier we mentioned that the Address Book application object contains a property called my card that, in turn, is a Person object describing the currently active user. Although this property is specific to the Address Book application, there are other generic properties, such as the application name and version, that are automatically inherited from a parent application object. A view of this inheritance can be seen in Figure 4.16.

Figure 4.16. Objects inherit properties from parent classes.

Unfortunately, object-oriented programming is a bit beyond the scope of this book. If you find these views at all confusing, stick to the Suites view, which provides a much cleaner organization for most users.

Entering a Sample Script

Let's see how the Person class can be used to return an attribute about someone in the Address book. Go back to the main Script Editor window and enter the following code:

 1: tell application "Address Book" 2:   get the job title of my card 3:   set myTitle to the result 4:   display dialog myTitle 5: end tell 

When finished, click the Run button and a dialog box will appear with your Address Book title as the contents. Note that if you don't have a Job Title set, you'll need to choose Card, Add Field, Job Title within the Address Book application.

Line 1 indicates that instructions will be sent to the Address Book application. Line 2 gets the job title for the Person object contained in the special property "my card" (me). Line 3 sets a variable called myTitle to the results of the previous get command. Line 4 displays a dialog box containing the contents of myTitle. Finally, line 5 stops talking to Address Book.

This example introduces the structure you will see in most AppleScript programs. The tell, set, and get statements form the basis of scripts. The objects and the parameters that can be modified, however, must be looked up in the application's dictionary.


The Script Editor features a Script Assistant that will automatically complete recognized pieces of code as you type. Before you can use the assistant, you must first enable it within the Editing pane of the Script Editor preferences, and then quit and restart the editor.

If the Script Assistant recognizes what you're typing, it places an ellipsis (…) after your cursor. When this is displayed, pressing F5 will show the potential code completions. Use the up and down arrows to choose the one you want, and then press the Return key to insert the code into your script.

Viewing Results

As you saw in the preceding sample script, when an AppleScript function returns a result, it is stored in a special temporary variable called result. This variable can be used to access a value without the need for additional variables. For example, lines 3 and 4 of the preceding script could be condensed to

 display dialog the result 

To display the contents of the result container within the Script Editor, choose View, Show Result (Command-2) from the menu, or click the Result button at the bottom of the Script Editor window. Tiger displays the current value of result below the script.

Tracing Events

To trace the execution of a script as it runs, use the event log. This log keeps track of the events (commands) sent to an application and displays the results that are returned immediately. Click the Event Log button or press Command-3 to show the event log in the lower pane of the Script Editor window. Figure 4.17 shows the event log after replaying a simple script to get the location of a Finder window.

Figure 4.17. The event log can be used to monitor script execution.

Saving Scripts

After you've created a script that functions the way you want, you can save it in several different ways. Select File, Save As, and then choose from the following options, depending on what you want to do with the script:

There are five possible file formats for scripts:

  • Script Saves the script as a compiled binary file.

  • Application Saves the script for double-click execution under Tiger.

  • Script Bundle Saves the script in the binary script format but also within a folder bundle, allowing you to add additional resources (other files and so on) within the bundle structure.

  • Application Bundle Saves the script in a double-clickable application format but as a folder bundle, enabling you to add additional files and resources.

  • Text Saves the contents of the script in a plain-text file.

In addition to the file format, you can also choose the line ending format if saving to a text file, and whether the file should be run only (not allow editing), display a startup screen, and stay open (after it has finished executing).

Changing Scripting Preferences

The Script Editor automatically highlights and formats AppleScript as you type. To change the default font styles and formatting, choose Preferences from the application menu.

The five categories of Script Editor preferences are as follows:

  • General The default scripting language to be used. AppleScript is the only language available without installing third-party software.

  • Editing Control line wrap settings, control tab indentation, and enable and disable the Script Assistant.

  • Formatting Choose font size, color, syntax highlighting, and so on.

  • History Enable or disable a running history of AppleScript-generated results and events.

  • Plugins Display any third-party plug-ins that have been installed.


To use another editor as your AppleScript editor, use the AppleScript Utility (path: /Applications/AppleScript/AppleScript Utility) to change the Default Script Editor setting.

     < Day Day Up > 

    Mac OS X Tiger Unleashed
    Mac OS X Tiger Unleashed
    ISBN: 0672327465
    EAN: 2147483647
    Year: 2005
    Pages: 251

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net