Although the Mac is prized for its ease of use, repetitive tasks such as changing large groups of file names and creating workflows that span several applications can be anything but easy. Sooner or later, you’ll want to automate an action or series of actions to reduce your toil and increase your productivity—even if you’re simply reducing the number of steps you must take to reply to an e-mail message. Software that does some of these things for you is available—usually designed for a specific purpose or application, and often for a price. But luckily, Mac OS already has the ultimate automation solution: AppleScript. It’s easy, powerful, and free—and it’s already on your computer.
At first sight, learning to script may seem daunting. But with a little guidance, you can be on your way to automating many of your computing tasks. In this introduction to AppleScript, we’ll take a look at the fundamentals of understanding and writing AppleScripts, and then we’ll walk through the creation of a sample Finder script. (This tutorial is written for Mac OS X 10.1 or higher and will not work with earlier systems.)
What Is AppleScript?
AppleScript is a language used to automate the actions of Mac OS and many of its applications. Whether a task is as simple as copying a file or as complex as building a catalog, AppleScript can intelligently perform the requisite actions for you, controlling applications and making decisions based on its observations or on information provided by its interaction with the person running the script.
Who Uses It Every day, businesses and individuals use AppleScript to create newspapers and books, manage networks, build DVDs, process images, generate Web pages, back up files and folders, make videos, and much more. In addition to loads of Apple applications such as iTunes, AppleWorks, Mail, and Terminal, many third-party applications—including QuarkXPress, Microsoft Entourage, Adobe Photoshop, FileMaker Pro, and Qualcomm Eudora—can take advantage of AppleScript.
How It Works You create AppleScripts with Apple’s free Script Editor application, using the AppleScript language. Each script contains a series of sequential instructions. To automate actions, you launch a script; your Mac communicates those instructions to your applications, which then perform the actions as instructed.
Scripts can be launched, or run , from within Script Editor, or they can be saved as either script files or script applications that are available from within other applications. You can access script files from an application’s script menu or from Mac OS X’s systemwide Script Menu utility. You launch script applications, or applets , just as you do other applications—by double-clicking on their icons in the Finder or by clicking on their Dock or Finder toolbar icons.
Nuts and Bolts
AppleScript is based on the concept of scriptable objects belonging to or being contained in other scriptable objects—it’s sort of like having sets of nested Russian dolls inside your Mac. A file sits in a folder, which belongs to the hard disk; or a word is part of a paragraph, which belongs to a story. Understanding the relationship between scriptable objects is a key to learning how to write scripts.
All Together Now Consider the following statement: On the Macintosh computer, everything is an object . The computer, the desktop, the disks it displays, the folders on the disks, and the files in those folders—all of these items are objects. So are applications, their documents, and the data in those documents. Now consider this: Everything belongs to, is related to, is contained in, or is part of something else. The file is in the folder, which is in the disk, which is on the desktop, which is on the computer. This relationship can apply to text as well:the letter is in the word, which is in the line, which is part of the paragraph, which is contained in the story.
This relationship between objects is referred to as hierarchical or, in military terms, the chain of command. AppleScript uses this hierarchical structure to identify particular scriptable objects, and it will be in the scripts you write. Just remember that in scripts, objects are described in terms of their position in the hierarchical structure.
Properties and Values Disks, files, folders, font suitcases, packages, and windows are all objects or elements belonging to the Finder application. They are the items the Finder uses in the organization and display of information. Each of these items has particular properties that define or describe it. Some of these properties are unique to each item, while others are shared by all items.
For example, while an Internet location file (or link) is the only Finder element that has a property describing a location on the Internet, it has some properties common to all Finder elements, such as its icon’s size and position in a folder window or on the desktop. And like other Finder elements, such as a folder or document file, a link file has a name property whose value is displayed with its icon and can be edited by the computer user.
An important rule to remember is that every scriptable application contains elements or objects that have properties. These properties have values that can be read or manipulated.
This rule applies to the Finder application, as well as all scriptable applications. All elements of the Finder have properties—for example, their name, size, and location. And all these properties have values, some of which can be edited and some of which can only be read.
Getting Familiar
In our overview of AppleScript, we’ll examine the properties of a Finder window in detail and learn how to manipulate them with scripts.
The Script Editor To write a script, we’ll use the Script Editor application installed in your system. You’ll find this application in the AppleScript folder located in the Applications folder on your hard drive.
Script Editor displays a multipaned window, known as a script window, with two panes. The top pane contains the description field, which is for optional comments or instructions regarding the use of the script. The bottom pane contains the script field, which is for the text of the script itself. (By default, the script window is rather small, so you may want to expand it.)
Our First Script We’ll begin learning AppleScript by writing a series of simple script commands in the form of tell statements—single-line scripts beginning with the verb tell . This verb is used to direct script actions at a specific application or scriptable object. A tell statement has two parts: a reference to the object to be scripted and the action to be performed. Using this format—or syntax—we can write scripts instructing the Finder to perform whatever actions we desire. To see an example, type the following in the script window (making sure the word Finder is inside straight, not curly, quotation marks):
tell application "Finder" to close every window.
Click on the Check Syntax button in the script window to confirm that the script was written correctly and to prepare it for use. Next, click on the Run button to play the script. The OS will read the script and send the appropriate commands to the Finder, which will then follow those instructions and close any open windows. Congratulations—you’ve written and run your first AppleScript!
Note that
Finderis enclosed in quotation marks in the script—names and text data are always treated this way in scripts. This punctuation prevents Script Editor from seeing the text as commands or instructions when it checks and prepares the script. Delete the previous script from the script window, and enter, check, and run the following script:
tell application "Finder" to open the startup disk.
A new Finder window will appear on the desktop. Finder windows are different from other windows used by the Finder, in that they have a toolbar and display the contents of disks or folders. We’ll use this newly opened window as we examine the properties of a Finder window.
The Name Property
The first Finder-window property we’ll examine is its name property. A window’s name is the text shown in its title bar. In the case of Finder windows, the text is the name of the folder or disk whose contents are displayed within the Finder window.
Name Game To retrieve the value of the window’s name property, we’ll use the get command. The verb get is used when we want to extract information or data from a scriptable element or object. Enter and run the following script: tell application “Finder” to get the name of front window.
To see the result of the request, look in the result window (choose Show Result from the Controls menu in Script Editor, or type Command-L). You’ll see that the title of the open Finder window also happens to be the name of your start-up disk.
For Finder windows, the name property is a reference (or read-only) property—it can be used to refer to a window, but its value cannot be changed by a script. The value of a Finder window’s name property will always be the name of the folder or disk whose contents it displays.
As the following script demonstrates, you can use the name property as a means to refer to a specific window. Delete the previous script from the script window, and then enter, check, and run the following script (replace Macintosh HD with the name of the open Finder window if it’s different):
tell application "Finder" to close window "Macintosh HD". The Macintosh HD window should close. Note that this script is a fully qualified tell statement—it both refers to the object receiving the commands (in this case, the open window) and indicates the desired action to take (closing the window).
The Index Property
If you’re writing a script that will be used on multiple computers, using the name property is not always the best way to locate a specific window. Another, more generic way to refer to an open Finder window is through its index property.
Look Up My Number The value of this reference property is a number corresponding to the window’s numeric position in the stacking order of open Finder windows. For example, the frontmost Finder window will always have an index value of 1, while the last Finder window will always have an index value equal to the total number of open Finder windows. To see how this property can be used, first reopen the previous window, using this script: tell application “Finder” to open the startup disk.
Now run the following script:
tell application "Finder" to get the index of Finder window "Macintosh HD".
The result of this script in the result window will be the number 1 , since only one window is open at this point. Open a second window and run:
tell application "Finder" to open home.
A second window displaying the contents of your Home directory will now appear on the desktop.
Note the use of startup disk and home in the previous scripts. Startup disk and home are special terms reserved by the Finder application to identify important locations. They’re generic, and they’ll work regardless of how drives and folders are named on the computer.
Now you can see whether the addition of the new window has affected the index value of the target window. Run the following:
tell application "Finder" to get the index of Finder window "Macintosh HD". The result of this script is 2, since the target window is the second window in the stack of open windows on the desktop.
The index property can be used to identify any open window, and since the AppleScript language was designed to be like English and to be written in a conversational manner, there are several ways to reach the same result (for more on this, see “AppleScript at a Glance”).
The Target Property
The value of the target property is a reference to the folder or disk whose contents are displayed in the Finder window. Unlike the values in our previous examples, this value can be both read and changed.
Where Am I? With your Home folder at the forefront, use this script to get the value of the target property:
tell application "Finder" to get the target of the front window. This returns folder username of folder Users of startup disk of application “Finder” .
As you can see, the result of this script is a reference to the folder whose contents are displayed in the Finder window, in this case your Home directory. This reference describes the target folder in terms of its position in its object hierarchy. The returned object reference clearly shows that the target folder is contained by the Users folder, which is on the start-up disk, which is an element of the Finder application. You’ll use this hierarchical reference structure often in the scripts you write.
Next, we’ll change the targets of the open Finder windows. To change the value of a property, use the verb set. Run the following script:
tell application "Finder" to set the target of the front Finder window to the startup disk. You’ll notice that the frontmost Finder window now displays the contents of the start-up disk. Now try this script:
tell application "Finder" to set the target of the last Finder window to home. The second Finder window now displays the contents of your Home directory.
To summarize, the target property of a Finder window has a value that is a reference to a specific folder or disk whose contents are displayed within the Finder window. This value can be changed by using the verb set in conjunction with an object reference to the new target folder. An object reference describes an object in terms of its position in its object hierarchy, or—in the case of a folder object—where it is on its parent disk.
Now, let’s continue our overview of the properties of a Finder window.
The Current View Property
The next Finder-window property we’ll examine is the current view property. The value of this property is the method used to display the contents of the Finder window. This property has three possible values—icon view, list view, and column view—and can be both read and edited.
Point of View To see your frontmost window’s view status, run the following: tell application “Finder” to get the current view of the front Finder window. This returns one of the following terms: icon view, list view, or column view. In order to change the current view to list view, you can run this script: tell application “Finder” to set the current view of the front Finder window to list view. You can then easily change the view to another by substituting column view or icon view for list view.
The Position Property
The value of the position property determines where a Finder window is placed on the desktop. This value is displayed as a list of two numbers that describe the position of the top left corner of the Finder window in relation to the top and left sides of the desktop display. The value of the position property can be both read and edited, and you’ll use this property in the scripts you write for organizing window placement.
Know Your Place Delete the previous script from the script window, and then enter, check, and run the following script:
tell application "Finder" to get the position of the front Finder window. This returns a bracketed list of two numbers, such as {14, 64}, describing the window’s position relative to the top left point of the desktop display. The first is the horizontal distance in pixels from the left side of the desktop display; the second, the vertical distance in pixels from the top of the desktop display.
Let’s change the value of the position property of the front Finder window, to move the window to the top left of the screen. Delete the previous script from the script window, and then enter, check, and run the following script:
tell application "Finder" to set the position of the front Finder window to {72, 90}. The front Finder window has now been moved so that its top left corner is 72 pixels from the left side of the desktop and 90 pixels from the top of the desktop.
The Bounds Property
If you find yourself always resizing windows, you’ll probably write scripts with the bounds property. The value of this property describes the size and position of the target window. A list of four numbers, a window’s bounds are described by two points: the top left point and the bottom right point of the window. These two coordinates are used to outline the rectangular shape of the window. Like the position property, the value of the bounds property can be read and edited.
The Shape of Things First, let’s get the bounds of the frontmost window:
tell application "Finder" to get the bounds of the front window. The value of the bounds property is returned as a four-item list, such as {14, 64, 512, 481}, and describes the window’s boundaries in relation to the screen.
By changing the value of the bounds property, a Finder window can be resized and positioned anywhere on the desktop. For example, the following script will place the front Finder window at the top left of the desktop (just below the menu bar) and resize the window to 400 pixels in width and 300 pixels in height. Again, the verb set is used in this script: tell application “Finder” to set the bounds of the front window to {0, 44, 500, 344}. The Finder window will now be resized to the top left of the desktop, just beneath the menu bar.
Make a Selection There is one more verb we’ll learn for use with windows— select , to make a window become active or move in front of any other open windows: tell application “Finder” to select the last Finder window. The Finder window that was behind the front Finder window will now be moved to the front of the open windows.
Desktop Setup Script
Using all the properties and verbs we’ve covered so far, you now have the tools to create a script you can use to quickly restore a cluttered desktop to a default window configuration.
Tell Block To set the desktop window display to the desired format, this script will perform a series of eight commands. But instead of writing a group of individual
tellstatements, we’ll shorten the time it takes to write our script by enclosing the commands in a
tellblock—used to target multiple actions at a scriptable object (in this case, the Finder application) and to make scripts easier to read and write.
A
tellblock begins with the verb tell followed by a reference to a target object. The various actions to be performed are then listed, each on its own line. The
tellblock ends with the closing statement
end tell. All actions inside the
tellblock target the object referenced in the opening statement. You’ll always want to use a
tellblock in your scripts when you’re addressing more than one action at a scriptable object.
The ScriptDelete any remaining script from the script window, and then enter, check, and run the following script:
tell application "Finder" close every window open home set the current view of the front window to icon view set the bounds of the front window to {14, 64, 512, 481} open folder "Documents" of home set the current view of the front window to list view set the bounds of the front window to {523, 64, 907, 482} select window of home end tell
You should now see two Finder windows placed side-by-side on the desktop—one in icon view, the other in list view—with your Home directory as the active window.
Save the script as a script applet and install it in the Finder toolbar (see below). Choose Save from Script Editor’s File menu. In the dialog box that appears, navigate to the Library folder in your Home directory. Click on the New Folder button and create a new folder named Toolbar Scripts in the Library folder.
Next, enter a name and save the script as a self-running application named Setup by choosing Application from the File Format pop-up menu in the dialog box. Make sure the Startup Screen option is not checked, and then click on the Save button. The new script applet will be saved in the newly created folder in your Library folder.
Switch to the desktop and open the Toolbar Scripts folder you just created. Drag the script applet icon to the Finder window toolbar, and release the mouse. The script will now be available from within any open Finder window. Anytime you want to return your desktop to your default setup, just click on the script icon in the toolbar (and with your newfound knowledge of AppleScript, you can customize this script to your liking).
The Last Word
Now that you’ve finished your initial foray into the world of AppleScript—having learned what it is, how it works, and how to script the Finder to control the display of Finder windows—you have the background you’ll need to write more-advanced scripts.
Sal Soghoian is a noted AppleScript guru and serves as AppleScript product manager for Apple Computer.
Finder Window Properties
Reference Properties
name: the text displayed in the title bar of the window:
tell application "Finder" to get the name of the front window
index: a number indicating the position of the window in the stack of open windows: tell application “Finder” to get the index of the front window
Editable Properties
bounds: a list of coordinates defining the top left and bottom right corners of a window:
tell application "Finder" to set the bounds of Finder window 1 to {0, 22, 400, 300}
collapsed: a true or false value indicating whether the window has been minimized to the Dock:
tell application "Finder" to set collapsed of every window to false
current view: the method currently used to display content in the window—options are icon view, list view, column view:
tell application "Finder" to set the current view of Finder window 1 to icon view
position: a list of coordinates indicating the horizontal and vertical offset of the window from the left and top sides of the screen:
tell application "Finder" to set the position of the front Finder window to {0, 22}
target: a reference to the folder or directory whose contents are displayed in the window:
tell application "Finder" to set the target of the front Finder window to home
zoomed: a true or false value that indicates whether the window has been expanded:
tell application "Finder" to set zoomed of the front Finder window to true
Referring to a Finder Window
refer by window name:
Finder window "Documents"
refer by index:
Finder window 1
refer by descriptive index:
the first Finder window;
the second Finder window;
the fifth Finder window;
the 1st Finder window;
the 23rd Finder window
refer by position relative to other windows:
the front Finder window;
the middle Finder window;
the back Finder window;
the last Finder window
refer by random selection:
some Finder window
Verbs or Commands Used with Finder Windows
Accessing the Value of a Property of a Window
get: used to access the current values of a window property:
tell application "Finder" to get the target of the front Finder window
Changing the Values of a Window Property
set: used to apply a new value to a window property:
tell application "Finder" to set the target of the front Finder window to home
Controlling Windows
open: causes a window to become visible in the Finder:
tell application "Finder" to open the startup disk
close: causes a window to close:
tell application "Finder" to close every Finder window
select: causes a window to come to the front:
tell application "Finder" to select the last Finder window
Tell Statement
contains a reference to the target object and the action to be performed:
tell application "Finder" to set the target of the last Finder window to home
Tell Block
used instead of multiple tell statements; targets multiple actions at a scriptable object:
tell application "Finder" set the target of the front window to home set the current view of the front window to icon view set the position of the front window to {0, 22} end tell
a nested tell block streamlines multiple targeted actions in a tell block:
tell application "Finder" tell the front window set its target to home set its current view to icon view set its position to {0, 22} end tell