Introduction to AppleScript

AppleScript allows developers to control OSX and the applications that run on it by creating their own applications. It therefore provides developers access to sensor data managed by data loggers, GPS data from GPS apps, network services, and Apple's speech recognition/speech synthesis engine.Combined with AppleScript Studio, developers can rapidly prototype sophisticated multimodal applications.

AppleScript is a robust scripting language; English-like and easy to learn. It's a model for other very high-level languages like Lingo and ActionScript.


The AppleScript Editor window

Buttons:

Record: Records user actions as a script (applications launched, windows selected, buttons clicked, etc.)
Stop: Stops the script from running.
Run: Plays the script.
Check Syntax: Formats the script and checks for errors. Formatting options are under the formatting menu.

Windows:

Script window: Is where you write and debug scripts.
Event Log: Shows events and event results.
Result window: Shows the last result of a script.


Writing scripts

Comments are indicated by two hyphens preceding a line of code. To comment a block of code use (* at the start of the block and *) at the end of the block.

For long lines of code a continuation notation can be used. Insert your cursor where you want the code to continue to the next line, and press the option key and the return key together.

Handlers are denoted by on or to. The handler name is followed by ( ) for values passed to the handler. Subroutine handlers are modular pieces of code written by the author. Command handlers respond to Apple Events, such as on run, on open, on quit.


Saving Scripts

The options are text, compiled, and application (applet). Compiled scripts open in the script editor. Applets are double-clickable applications with the options to bypass a startup screen and remain open (good for cgi's). In addition, you can save scripts as run-only, which means they can't be opened in the script editor.


Scripting applications

Most applications on OSX support some level of AppleScript. Apps that ship with OSX, such as the iLife suite (iPhoto, iTunes, iDVD, etc.) and the core applications, like Finder, are fully scriptable. To see which other applications installed on your machine are scriptable, use the open dictionary menu command. Select an application and see what the objects and commands available are. Typically there is a standard required suite, and then there is an application-specific suite.

Most applications that are scriptable are recordable. That is you can click the record button and then perform a series of tasks with the app that are recorded as steps in an AppleScript. The extent to which all the functions of an app are recordable depends on how extensive the application-specific suite is.

Applications are controlled by AppleScript using a "tell block" which consists of a tell application command and a closing end tell statement. For example:

tell application "Finder"
empty the trash
beep
end tell

You can have nested tell statements, such as:

tell application "Finder"
set theFolder to make new folder at desktop with properties {name:"AppleScript Examples"}
tell theFolder
open
end tell
end tell

This example launches Apple's Applescript web site:

tell application "Internet Explorer"
Activate
OpenURL "http://www.apple.com/applescript"

end tell


AppleScript syntax

AppleScript has a basic structure of commands (verbs, if you will) and objects (nouns). Statements are "sentences" of commands and objects, which might contain expressions, such as setting the value of a variable. There are numerous ways you can refer to objects, such as:

set lastName to word 2 of the result

or

set lastName to last word of the result

Objects have properties as defined by the application's AppleScript dictionary. For example:

tell application "Finder"
make new folder at desktop with properties {name:"AppleScript Examples"}
end tell


Basic AppleScript commands

Like Unix shells, AppleScript does very little on its own. It needs a large suite of scriptable applications to be useful. Because of this some commands may vary from application to application, or the syntax may change slightly. But in general, these are the types of things that are supported by the core suite of commands. Application-specific commands are detailed in each application's AppleScript dictionary.

activate
Brings an application to the front.
Example:

activate application "HomeRun"

quit
Quits an application.
Example:

quit application "HomeRun"

open
Opens a document file.
Example:

tell application "Finder"
open file "Macintosh HD: sensordata"
end tell

print
Prints a document or window.

close
Closes the given window.
Example:

close front document of application "TextEdit"

count
Returns the number of items as the result.
Example:

count the words of front document of application "QuarkExpress"

delete
Deletes the given text.
Example:

tell front document of application "TextEdit"
delete the first word
end tell

get
Gets whatever information you ask for.
Example:

tell application "TextEdit"
get the font of the third word of front document
end tell

set
Changes the value of an object's property.
Example:

tell front document of application "TextEdit"
set the name to "Fun With AppleScript"
end tell

make
Creates a new window or text item.
Example:

tell application "QuarkExpress"
make new document
end tell

save
Saves the window to disk.

undo/copy/cut/paste/revert
Executes the familiar menu command.
Example:

tell application "GPSy"
copy latitude
copy longitude
end tell

display dialog
Displays a dialog with default buttons "cancel" and "OK".


AppleScript data types

Boolean: A statement evaluated to either true or false (as in: set loggedIn to true).

Integer: A whole number (100).

Real number: A number with a decimal point (110.1).

String: Denoted within quotations, a series of characters ("AppleScript is fun!").

List: An array containing many different data types, even other lists. The syntax is:

set myList to {1, 2, 3.5, "Look at me", {x, y, z}}

For example:

set myList to {1, 2, 3.5, "Look at me"}
repeat with theItem in myList
display dialog theItem
end repeat

Record: Names for items in the list (like fields in a database) and their associated values, such as:

set theRecord to {firstname:"Tony", lastname:"Scarlatos",email:"tony@cs.sunysb.edu",age:43}
display dialog email of theRecord

Date and text are additional data types.


AppleScript variables

A self-referencing variable is me, as in:

get the path to me (returns the path to the AppleScript)

To get the path to another application, use it, as in:

tell application "Internet Explorer"
get the path to it
end tell

Result is a variable that returns the result of each line of code as it executes.

Global variables are necessary to pass variable values through your scripts, for example to handlers. Declare a variable global:

global x

as in this example (countX is a handler):

global x
set x to 1
countX( )

on countX( )
repeat 3 times
display dialog x
set x to x + 1
end repeat
end countX

Comment out global x and see what happens.

Property is a data storage variable useful in coding. It defines a value that can be stated once and referenced throughout a script. If for example it contains a string, like a company's address, it can be changed once (at the top of a script) and the value will be updated though the entire script. The syntax is:

property companyAddress : "123 Main Street, Anywhere, USA"


If / Then / Else

These statements support the usual conventions, such as if X =1, if not X = 1, if X>1 and if X<5, if X=1or if X=2.


Repeat Loops

Infinite:

set x to 1
repeat
display dialog x
set x to x + 1
end repeat

Exit repeat:

set x to 1
repeat
display dialog x
set x to x + 1
if x =5 then
exit repeat
end if
end repeat

Conditional repeat:

set x to 1
repeat until x = 5
display dialog x
set x to x + 1
end repeat


Operator example

This example could be used as a currency converter, or to calculate sales tax.

display dialog "Enter the amount to be converted" default answer ""
set theAmount to the text returned of the result
display dialog "Enter the rate" default answer ""
set theRate to the text returned of the result
display dialog "Converted amount = " & theAmount * theRate


Catching Errors

Try blocks start with the command try and are closed by an end try. Within a try block some code may be tested in conjunction with an on error handler. This allows the developer to manage errors through AppleScript, preempting system error messages.


Basic AppleScript for User Interaction

Creating Dialogs

Type the following code into the AppleScript window, then click the 'run' button:

set x to "This is a dialog example"
display dialog x

This will give you the default dialog in AppleScript. Now type (and run the script):

display dialog "Do you like this class?" buttons {"No", "Yes"}

This allows you to name your buttons. To set a default choice, type:

display dialog "Do you like this class?" buttons {"No", "Yes"} default button "Yes"

To display a system icon, like the caution symbol, type:

display dialog "Do you like this class?" buttons {"No", "Yes"} default button "Yes" with icon caution

You can substitute other icons, like stop, or note, instead of caution. To dismiss a dialog without user interaction, type:

display dialog "You have received an error" buttons {"OK"} default button "OK" with icon stop giving up after 3

Capturing User Input

To capture which button a user has pressed, type and run the following script:

display dialog "Do you like this class?" buttons {"No", "Yes"} default button "Yes"
if button returned of result = "Yes" then
display dialog "You have made the correct choice."
else
display dialog "You're in trouble."
end if

If you want to capture text from a field and validate that it was entered correctly, try this:

repeat
display dialog "Please enter a number" default answer "" buttons{"OK"} default button "OK"
set theNum to the text returned of result
try
set theNum to theNum as integer
exit repeat
on error
display dialog "That is not a number"
end try
end repeat
display dialog "You entered the number: " & theNum

To allow a user to select a file, type:

choose file with prompt "Choose a file"
set thePath to result

You'll see the path returned in the result window. To allow a user to select a specific type of file, type:

set thePath to choose file of type "PDF" with prompt "Please choose a PDF file."

Change the script slightly to select a folder:

set thePath to choose folder with prompt "Please choose a folder to open."


Extracting Text from a File

tell application "Finder"
open "Macintosh HD: sensordata"
end tell
tell application "TextEdit"
get the attribute run of the first document
set rawdata to the attribute run of the first document as text
set info to last word of rawdata
display dialog info buttons {"OK"} default button "OK" giving up after 3
close first document
end tell

The script above uses the finder to locate and open a text file by giving it the full path. It then uses TextEdit to read in the file and locate a particular word. It displays the word in a dialog which closes itself, and then closes the file.


Scripting Speech

To use synthesized speech, use the say command, specifying the voice if you wish:

say "Hello, Earthlings" using "Zarvox"

To speak a user-entered string, type in this code:

display dialog "Welcome, please enter your name:" default answer ""
set theName to text returned of result
say "Hello," & theName

To recognize speech input type in this code:

tell application "SpeechRecognitionServer"
listen for {"Howdy", "Hello"}
if the result = "Howdy" then
say "How Y'all Doin'?"
else if the result = "Hello" then
say "Hi"
end if
end tell

This script will render input text to an .aiff (sound) file using synthesized speech:

property voice_names : {"Agnes", "Albert", "Bad News", "Bahh", "Bells", "Boing", "Bruce", "Bubbles", "Cellos", "Deranged", "Fred", "Good News", "Hysterical", "Junior", "Kathy", "Organ", "Princess", "Ralph", "Trinoids", "Victoria", "Whisper", "Zarvox"}
property default_voice : "Victoria"
set this_voice to ""
set this_string to "Welcome to the Multimodal Interfaces Class!"
try
repeat
display dialog "Enter the text to render to a sound file:" default answer this_string buttons {"Cancel", "Try", "Render"} default button 3
copy the result as list to {this_string, button_pressed}
if this_string is "" then
beep
else if the button_pressed is "Try" then
set this_voice to (choose from list voice_names default items default_voice with prompt "Pick the voice to use:") as string
if this_voice is "false" then
exit repeat
else
set default_voice to this_voice
end if
say this_string using this_voice
else
if this_voice is "" then
set this_voice to (choose from list voice_names default items default_voice with prompt "Pick the voice to use:") as string
if this_voice is "false" then
exit repeat
else
set default_voice to this_voice
end if
end if
set the target_file to choose file name with prompt "Name and location for the sound file:" default name "rendered.aiff"
say this_string using default_voice saving to target_file
exit repeat
end if
end repeat
on error error_message number error_number
if the error_number is not -128 then
display dialog error_message buttons {"Cancel"} default button 1
end if
end try


Resources:

Example scripts can be found under Applications > Applescript > Example Scripts. Scripts for Apple's scriptable applications (like the iLife suite - iDVD, iTunes, iPhoto) can be found at: http://www.apple.com/applescript/apps/

AppleScript Language Guide