Apple Script Language Guide
Apple Script Language Guide
Contents
AppleScript Fundamentals 25
Script Editor Application 25
AppleScript and Objects 27
What Is in a Script Object 27
Properties 29
Elements 29
2
Contents
Object Specifiers 30
What Is in an Object Specifier 30
Containers 31
Absolute and Relative Object Specifiers 32
Object Specifiers in Reference Objects 32
Coercion (Object Conversion) 34
Scripting Additions 36
Commands Overview 37
Types of Commands 37
Target 38
Direct Parameter 39
Parameters That Specify Locations 40
AppleScript Error Handling 40
Global Constants in AppleScript 41
AppleScript Constant 41
current application Constant 44
missing value Constant 45
true, false Constants 45
The it and me Keywords 45
Aliases and Files 47
Specifying Paths 47
Working With Aliases 48
Working With Files 49
Remote Applications 50
Enabling Remote Applications 50
eppc-Style Specifiers 50
Targeting Remote Applications 51
Debugging AppleScript Scripts 52
Feedback From Your Script 52
Logging 52
Third Party Debuggers 53
3
Contents
Script Objects 68
Defining Script Objects 68
Initializing Script Objects 70
Sending Commands to Script Objects 71
Script Libraries 72
Creating a Library 73
Using a Library 74
Inheritance in Script Objects 75
The AppleScript Inheritance Chain 75
Defining Inheritance Through the parent Property 76
Some Examples of Inheritance 76
Using the continue Statement in Script Objects 79
About Handlers 83
Handler Basics 83
Defining a Simple Handler 84
Handlers with Labeled Parameters 85
Handlers with Positional Parameters 86
Handlers with Patterned Positional Parameters 87
Handlers with Interleaved Parameters 88
Parameter Specifications 89
Recursive Handlers 90
Errors in Handlers 91
Passing by Reference Versus Passing by Value 91
Calling Handlers in a tell Statement 92
Handlers in Script Applications 92
run Handlers 93
open Handlers 94
idle and quit Handlers for Stay-Open Applications 95
Calling a Script Application From a Script 97
Class Reference 99
alias 99
application 100
boolean 103
class 105
constant 106
4
Contents
date 107
file 111
integer 111
list 112
number 116
POSIX file 117
real 117
record 118
reference 120
RGB color 122
script 122
text 124
unit types 131
5
Contents
6
Contents
Index 218
Middle 220
Name 221
Property 222
Range 222
Relative 224
7
Contents
if (compound) 252
repeat Statements 253
exit 253
repeat (forever) 253
repeat (number) times 254
repeat until 255
repeat while 256
repeat with loopVariable (from startValue to stopValue) 257
repeat with loopVariable (in list) 258
tell Statements 260
tell (simple) 261
tell (compound) 262
try Statements 263
try 263
use Statements 266
use (AppleScript) 267
use (scripting additions) 267
use (application or script) 268
use (framework) 270
using terms from Statements 270
using terms from 271
with timeout Statements 272
with timeout 272
with transaction Statements 273
with transaction 274
8
Contents
Glossary 313
Index 321
9
Figures, Tables, and Listings
AppleScript Fundamentals 25
Figure 2-1 The Finder dictionary in Script Editor (in OS X v10.5) 26
Table 2-1 Default coercions supported by AppleScript 35
Script Objects 68
Listing 4-1 A pair of script objects with a simple parent-child relationship 77
Class Reference 99
Table 6-1 Special characters in text 126
Table 6-2 White space constants 127
10
Figures, Tables, and Listings
11
Introduction to AppleScript Language Guide
This document is a guide to the AppleScript language—its lexical conventions, syntax, keywords, and other
elements. It is intended primarily for use with AppleScript 2.0 or later and OS X version 10.5 or later.
AppleScript 2.0 can use scripts developed for any version of AppleScript from 1.1 through 1.10.7, any scripting
addition created for AppleScript 1.5 or later for OS X, and any scriptable application for Mac OS v7.1 or later.
A script created with AppleScript 2.0 can be used by any version of AppleScript back to version 1.1, provided
it does not use features of AppleScript, scripting additions, or scriptable applications that are unavailable in
that version.
Important: Descriptions and examples for the terms in this document have been tested with AppleScript
2.0 in OS X v10.5 (Leopard). Except for terms that are noted as being new in Leopard, most descriptions
and examples work with previous system versions, but have not been tested against all of them.
If you need detailed information about prior system and AppleScript versions, see AppleScript Release Notes
(OS X v10.4 and earlier) .
What Is AppleScript?
AppleScript is a scripting language created by Apple. It allows users to directly control scriptable Macintosh
applications, as well as parts of OS X itself. You can create scripts—sets of written instructions—to automate
repetitive tasks, combine features from multiple scriptable applications, and create complex workflows.
Note: Apple also provides the Automator application, which allows users to automate common
tasks by hooking together ready-made actions in a graphical environment. For more information,
see Automator Documentation.
A scriptable application is one that can be controlled by a script. For AppleScript, that means being responsive
to interapplication messages, called Apple events, sent when a script command targets the application. (Apple
events can also be sent directly from other applications and OS X.)
AppleScript itself provides a very small number of commands, but it provides a framework into which you can
plug many task-specific commands—those provided by scriptable applications and scriptable parts of OS X.
12
Introduction to AppleScript Language Guide
Who Should Read This Document?
Most script samples and script fragments in this guide use scriptable features of the Finder application, scriptable
parts of OS X, or scriptable applications distributed with OS X, such as TextEdit (located in /Applications).
AppleScript Language Guide assumes you are familiar with the high-level information about AppleScript found
in AppleScript Overview .
The first five chapters introduce components of the language and basic concepts for using it, then provide
additional overview on working with script objects and handler routines:
● AppleScript Lexical Conventions (page 16) describes the characters, symbols, keywords, and other language
elements that make up statements in an AppleScript script.
● AppleScript Fundamentals (page 25) describes basic concepts that underly the terminology and rules
covered in the rest of this guide.
● Variables and Properties (page 54) describes common issues in working with variables and properties,
including how to declare them and how AppleScript interprets their scope.
● Script Objects (page 68) describes how to define, initialize, send commands to, and use inheritance with
script objects.
● About Handlers (page 83) provides information on using handlers (a type of function available in
AppleScript) to factor and reuse code.
13
Introduction to AppleScript Language Guide
Conventions Used in This Guide
● Control Statements Reference (page 245) describes statements that control when and how other statements
are executed. It covers standard conditional statements, as well as statements used in error handling and
other operations.
● Handler Reference (page 276) shows the syntax for defining and calling handlers and describes other
statements you use with handlers.
The following appendixes provide additional information about the AppleScript language and how to work
with errors in scripts:
● AppleScript Keywords (page 292) lists the keywords of the AppleScript language, provides a brief description
for each, and points to related information.
● Error Numbers and Error Messages (page 298) describes error numbers and error messages you may see
in working with AppleScript scripts.
● Working with Errors (page 302) provides detailed examples of handling errors with try Statements (page
263) and error Statements (page 249).
● Double Angle Brackets (page 306) describes when you are likely to see double angle brackets (or
chevrons—«») in scripts and how you can work with them.
● Unsupported Terms (page 311) lists terms that are no longer supported in AppleScript.
Important: This document sometimes uses the continuation character (¬) for sample statements that don’t
fit on one line on a document page. It also uses the continuation character in some syntax statements to
identify an item that, if included, must appear on the same line as the previous item. The continuation
character itself is not a required part of the syntax—it is merely a mechanism for including multiple lines
in one statement.
14
Introduction to AppleScript Language Guide
See Also
language Plain computer font indicates an element that you type exactly as shown. If
element there are special symbols (for example, + or &), you also type them exactly as
shown.
placeholder Italic text indicates a placeholder that you replace with an appropriate value.
[optional] Brackets indicate that the enclosed language element or elements are optional.
[optional]... Three ellipsis points (...) after a group defined by brackets indicate that you can
repeat the group of elements within brackets 0 or more times.
a|b|c Vertical bars separate elements in a group from which you must choose a single
element. The elements are often grouped within parentheses or brackets.
Filenames shown in Most filenames shown in examples in this document include extensions, such
scripts as rtf for a TextEdit document. Use of extensions in scripts is generally
dependent on the “Show all file extensions” setting in the Advanced pane of
Finder Preferences.
To work with the examples on your computer, you may need to modify either
that setting or the filenames.
See Also
These Apple documents provide additional information for working with AppleScript:
● See Getting Started with AppleScript for a guided quick start, useful to both scripters and developers.
● See AppleScript Overview , including the chapter Scripting with AppleScript, for a high-level overview of
AppleScript and its related technologies.
● See Getting Started With Scripting & Automation for information on the universe of scripting technologies
available in OS X.
● See AppleScript Terminology and Apple Event Codes for a list of many of the scripting terms defined by
Apple.
For additional information on working with the AppleScript language and creating scripts, see one of the
comprehensive third-party documents available in bookstores and online.
15
AppleScript Lexical Conventions
This chapter provides an overview of the vocabulary and conventions of the AppleScript Language. It starts
with the character set and introduces elements of increasing complexity.
After reading this chapter, you should have an understanding of the basic language components used to
construct AppleScript expressions and statements.
Character Set
Starting in OS X v10.5 (AppleScript 2.0), the character set for AppleScript is Unicode. AppleScript preserves all
characters correctly worldwide, and comments and text constants in scripts may contain any Unicode characters.
16
AppleScript Lexical Conventions
Identifiers
AppleScript syntax uses several non-ASCII characters, which can be typed using special key combinations. For
information on characters that AppleScript treats specially, see the sections Identifiers (page 17),
Comments (page 19), Text (page 21), The Continuation Character (page 19), and Raw Codes (page 24) in this
chapter, as well as Table 9-1 (page 226) in Operators Reference (page 226).
Identifiers
An AppleScript identifier is a series of characters that identifies a class name, variable, or other language element,
such as labels for properties and handlers.
An identifier must begin with a letter and can contain any of these characters:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_
Identifiers are not case sensitive. For example, the identifiers myvariable and MyVariable are equivalent.
AppleScript remembers and enforces the first capitalization it comes across for an identifier. So if it first
encounters an identifier as myAccount, it will later, during compilation, change versions such as MyAccount
and myaccount to myAccount.
The following are not valid identifiers: C-, back&forth, 999, Why^Not.
AppleScript provides a loophole to the preceding rules: identifiers whose first and last characters are vertical
bars (|) can contain any characters. The leading and trailing vertical bars are not considered part of the identifier.
Important: This use of vertical bars can make scripts difficult to read, and is not recommended.
An identifier can contain additional vertical bars preceded by a backslash (\) character, as in the identifier
|This\|Or\|That|. Use of the backslash character is described further in the Special String Characters section
of the text (page 124) class.
Keywords
A keyword is a reserved word in the AppleScript language. Keywords consist of lower-case, alphabetic characters:
abcdefghijklmnopqrstuvwxyz. In a few cases, such as aside from, they come in pairs.
17
AppleScript Lexical Conventions
Keywords
Important: You should not attempt to reuse keywords in your scripts for variable names or other purposes.
Developers should not re-define keywords in the terminology for their scriptable applications.
Table 1-1 lists the keywords reserved in AppleScript 2.0 (which are the same as those used in AppleScript 1.x).
For additional information, see Table A-1 (page 292), which provides a brief description for each keyword and
points to related information, where available.
without
18
AppleScript Lexical Conventions
Comments
Comments
A comment is text that is ignored by AppleScript when a script is executed. You can use comments to describe
what is happening in the script or make other kinds of notes. There are three kinds of comments:
● A block comment begins with the characters (* and ends with the characters *). Block comments must
be placed between other statements. That means they can be placed on the same line at the beginning
or end of a statement, but cannot be embedded within a simple (one-line) statement.
● An end-of-line comment begins with the characters -- (two hyphens) and ends with the end of the line:
● Starting in version 2.0, AppleScript also supports use of the # symbol as an end-of-line comment. This
allows you to make a plain AppleScript script into a Unix executable by beginning it with the following
line and giving it execute permission:
#!/usr/bin/osascript
Compiled scripts that use # will run normally on pre-2.0 systems, and if edited will display using --.
Executable text scripts using #!/usr/bin/osascript will not run on pre-2.0 systems, since the # will
be considered a syntax error.
You can nest comments—that is, comments can contain other comments, as in this example:
--nested comments
*)
19
AppleScript Lexical Conventions
Literals and Constants
A continuation character within a quoted text string is treated like any other character.
Boolean
AppleScript defines the Boolean values true and false and supplies the boolean (page 103) class.
Constant
Global Constants in AppleScript (page 41) describes constants that can be used throughout your scripts. For
related information, see the constant (page 106) class.
List
A list defines an ordered collection of values, known as items, of any class. As depicted in a script, a list consists
of a series of expressions contained within braces and separated by commas, such as the following:
A list can contain other lists. An empty list (containing no items) is represented by a pair of empty braces: {}.
AppleScript provides the list (page 112) class for working with lists.
Number
A numeric literal is a sequence of digits, possibly including other characters, such as a unary minus sign, period
(in reals), or "E+" (in exponential notation). The following are some numeric literals:
20
AppleScript Lexical Conventions
Operators
-94596
3.1415
9.9999999999E+10
AppleScript defines classes for working with real (page 117) and integer (page 111) values, as well as the
number class, which serves as a synonym for either real or integer.
Record
A record is an unordered collection of labeled properties. A record appears in a script as a series of property
definitions contained within braces and separated by commas. Each property definition consists of a unique
label, a colon, and a value for the property. For example, the following is a record with two properties:
{product:"pen", price:2.34}
Text
A text literal consists of a series of Unicode characters enclosed in a pair of double quote marks, as in the
following example:
AppleScript text objects are instances of the text (page 124) class, which provides mechanisms for working
with text. The Special String Characters section of that class describes how to use white space, backslash
characters, and double quotes in text.
Operators
An operator is a symbol, word, or phrase that derives a value from another value or pair of values. For example,
the multiplication operator (*) multiplies two numeric operands, while the concatenation operator (&) joins
two objects (such as text strings). The is equal operator performs a test on two Boolean values.
For detailed information on AppleScript’s operators, see Operators Reference (page 226).
21
AppleScript Lexical Conventions
Variables
Variables
A variable is a named container in which to store a value. Its name, which you specify when you create the
variable, follows the rules described in Identifiers (page 17). You can declare and initialize a variable at the
same time with a copy (page 153) or set (page 197) command. For example:
copy 33 to myAge
When AppleScript encounters a variable, it evaluates the variable by getting its value. A variable is contained
in a script and its value is normally lost when you close the script that contains it.
AppleScript variables can hold values of any class. For example, you can assign the integer value 17 to a variable,
then later assign the Boolean value true to the same variable.
Expressions
An expression is any series of lexical elements that has a value. Expressions are used in scripts to represent or
derive values. The simplest kinds of expressions, called literal expressions, are representations of values in
scripts. More complex expressions typically combine literals, variables, operators, and object specifiers.
When you run a script, AppleScript converts its expressions into values. This process is known as evaluation.
For example, when the following simple expression is evaluated, the result is 21:
3 * 7 --result: 21
An object specifier specifies some or all of the information needed to find another object. For example, the
following object specifier specifies a named document:
22
AppleScript Lexical Conventions
Statements
Statements
A statement is a series of lexical elements that follows a particular AppleScript syntax. Statements can include
keywords, variables, operators, constants, expressions, and so on.
Every script consists of statements. When AppleScript executes a script, it reads the statements in order and
carries out their instructions.
A control statement is a statement that determines when and how other statements are executed. AppleScript
defines standard control statements such as if, repeat, and while statements, which are described in detail
in Control Statements Reference (page 245).
Note: You can use a continuation character (¬) to extend a simple statement onto a second line.
A compound statement is written on more than one line, can contain other statements, and has the word end
(followed, optionally, by the first word of the statement) in its last line. For example the following is a compound
tell statement:
end tell
Commands
A command is a word or series of words used in an AppleScript statement to request an action. Every command
is directed at a target, which is the object that responds to the command. The target is usually an application
object or an object in OS X, but it can also be a script object or a value in the current script.
The following statement uses AppleScript’s get (page 164) command to obtain the name of a window; the
target is the front window of the Finder application:
23
AppleScript Lexical Conventions
Results
For more information on command types, parameters, and targets, see Commands Overview (page 37).
Results
The result of a statement is the value generated, if any, when the statement is executed. For example, executing
the statement 3 + 4 results in the value 7. The result of the statement set myText to "keyboard" is the
text object "keyboard". A result can be of any class. AppleScript stores the result in the globally available
property result, described in AppleScript Constant (page 41).
Raw Codes
When you open, compile, edit, or run scripts with a script editor, you may occasionally see terms enclosed in
double angle brackets, or chevrons («»), in a script window or in another window. These terms are called raw
format or raw codes , because they represent the underlying Apple event codes that AppleScript uses to
represent scripting terms.
For compatibility with Asian national encodings, “ and” “ are ” allowed as synonyms for “«” and “»” ( (Option- \
and Option-Shift- \, respectively, on a U.S. keyboard), since the latter do not exist in some Asian encodings.
For more information on raw codes, see Double Angle Brackets (page 306).
24
AppleScript Fundamentals
This chapter describes basic concepts that underlie the terminology and rules covered in the rest of this guide.
● Script Editor Application (page 25)
● AppleScript and Objects (page 27)
● Object Specifiers (page 30)
● Coercion (Object Conversion) (page 34)
● Scripting Additions (page 36)
● Commands Overview (page 37)
● AppleScript Error Handling (page 40)
● Global Constants in AppleScript (page 41)
● The it and me Keywords (page 45)
● Aliases and Files (page 47)
● Remote Applications (page 50)
● Debugging AppleScript Scripts (page 52)
Script Editor can display the result of executing an AppleScript script and can display a log of the Apple events
that are sent during execution of a script. In the Script Editor Preferences, you can also choose to keep a history
of recent results or event logs.
Script Editor has text formatting preferences for various types of script text, such as language keywords,
comments, and so on. You can also turn on or off the Script Assistant, a code completion tool that can suggest
and fill in scripting terms as you type. In addition, Script Editor provides a contextual menu to insert many
types of boilerplate script statements, such as conditionals, comments, and error handlers.
25
AppleScript Fundamentals
Script Editor Application
A dictionary is the part of a scriptable application that specifies the scripting terms it understands. You can
choose File > Open Dictionary in Script Editor to display the dictionary of a scriptable application or scripting
addition on your computer. Or you can drag an application icon to the Script Editor icon to display its dictionary
(if it has one).
To display a list that includes just the scriptable applications and scripting additions provided by OS X, choose
Window > Library. Double-click an item in the list to display its dictionary. Figure 2-1 shows the dictionary for
the Finder application in OS X v10.5. The dictionary is labeled as “[Link]”. The sdef format, along with
other terminology formats, is described in “Specifying Scripting Terminology” in AppleScript Overview .
26
AppleScript Fundamentals
AppleScript and Objects
27
AppleScript Fundamentals
AppleScript and Objects
A run handler contains statements AppleScript executes when the script is run. (For more information,
see run Handlers (page 93).)
● An implicit run handler (optional):
An implicit run handler consists of any statements outside of any contained handlers or script objects.
● Additional handlers (optional):
A handler is the equivalent of a subroutine. (For details, see About Handlers (page 83).)
● Additional script objects (optional):
A script object can contain nested script objects, each of which is defined just like a top-level script
object, except that a nested script object is bracketed with statements that mark its beginning and end.
(For details, see Script Objects (page 68).)
Here is an example of a simple script with one property, one handler, one nested script object, and an implicit
run handler with two statements:
on greetClient(nameOfClient)
end greetClient
script testGreet
greetClient(defaultClientName)
end script
The first statement in the run handler is run testGreet, which runs the nested script object testGreet.
That script object calls the handler greetClient(), passing the property defaultClientName. The
handler displays a dialog, greeting the default client, Mary Smith.
The second statement in the run handler calls greetClient() directly, passing the string "Joe Jones".
28
AppleScript Fundamentals
AppleScript and Objects
Properties
A property of an object is a characteristic that has a single value and a label, such as the name property of a
window or the month property of a date. The definition for any AppleScript class includes the name and class
for each of its properties. Property names must be unique within a class. Property values can be read/write or
read only.
The AppleScript date (page 107) class, for example, defines both read/write and read only properties. These
include the weekday property, which is read only, and the month, day, and year properties, which are
read/write. That’s because the value of the weekday property depends on the other properties—you can’t set
an arbitrary weekday for an actual date.
The class of a property can be a simple class such as boolean (page 103) or integer (page 111), a composite
class such as a point class (made up of two integers), or a more complex class.
Most classes only support predefined properties. However, for the script (page 122) class, AppleScript lets
you to define additional properties. For information on how to do this, see Defining Properties (page 54). You
can also define properties for record (page 118) objects.
Elements
An element is an object contained within another object. The definition for any AppleScript class includes the
element types it can contain. An object can typically contain zero or more of each of its elements.
For a given element type, an object can contain many elements or none, and the number of elements that it
contains may change over time. For example, it is possible for a list (page 112) object to contain no items (it
can be an empty list). At a later time, the same list might contain many items.
Whether you can add elements to or remove elements from an object depends on the class and the element.
For example, a text object is immutable—you cannot add or remove text once the object is created. For a
list object, you cannot remove items, but you can use the set command to add an item to the beginning
or end:
29
AppleScript Fundamentals
Object Specifiers
Object Specifiers
An object specifier specifies the information needed to find another object in terms of the objects in which it
is contained. An object specifier can refer to an application object, such as a window or file, or to an AppleScript
object, such as an item in a list or a property in a record.
An object specifier is fully evaluated (or resolved) only when a script is run, not when it is compiled. A script
can contain a valid object specifier (such as third document of application "TextEdit" that causes
an error when the script is executed (because, for example, there may be less than three documents open).
Applications typically return object specifiers in response to commands. For example, if you ask the Finder for
a window, it returns information that specifies the window object your script asked for (if it exists). The top-level
container in an object specifier is typically the application itself.
You create an object specifier every time your script uses a phrase that describes the path to an object or
property, such as name of window 1 of application "Finder". When you use the a reference
to (page 237) operator, it creates a reference (page 120) object that wraps an object specifier.
The difference between an object specifier and the object it refers to is like the difference between a building
address and the building itself. The address is a series of words and numbers, such as “2121 Oak Street, San
Francisco, CA” that identifies a location (on a street, in a city, in a state). It is distinct from the building itself. If
the building at that location is torn down and replaced with a new building, the address remains the same.
In the following example, the class of the object is paragraph. The container is the phrase of document 1.
Because this phrase is inside a tell statement, the tell statement provides the top-level container, of
application "TextEdit". The distinguishing information (the reference form) is the combination of the
class, paragraph, and an index value, 1, which together indicate the first paragraph.
paragraph 1 of document 1
end tell
30
AppleScript Fundamentals
Object Specifiers
Note: If you examine the dictionary for the TextEdit application, you might think this script should
say paragraph 1 of text of document 1. However, where the meaning is unambiguous,
some applications make life easier for scripters by allowing them to omit a container from an object
specifier. TextEdit uses this feature in supplying an implicitly specified subcontainer for the text in a
document. That is, if an object specifier identifies an object, such as a word or paragraph, that is
contained in a document’s text, TextEdit automatically supplies the of text part of the object
specifier.
In addition to the index reference form, you can specify objects in a container by name, by range, by ID, and
by the other forms described in Reference Forms (page 212).
Containers
A container is an object that contains one or more objects or properties. In an object specifier, a container
specifies where to find an object or a property. To specify a container, use the word of or in, as in the following
statement (from a Finder tell block):
A container can be an object or a series of objects, listed from the innermost to the outermost containing
object, as in the following:
end tell
You can also use the possessive form ('s) to specify containers. In the following example, the innermost
container is first window and the object it contains is a name property:
end tell
In this example, the target of the tell statement ("TextEdit") is the outer container for the object specifier.
31
AppleScript Fundamentals
Object Specifiers
In contrast, a relative object specifier does not specify enough information to identify an object or objects
uniquely; for example:
When AppleScript encounters a relative object specifier in a tell statement, it attempts to use the default
target specified by the statement to complete the object specifier. Though it isn’t generally needed, this implicit
target can be specified explicitly using the keyword it, which is described in The it and me Keywords (page
45).
The default target of a tell statement is the object that receives commands if no other object is specified.
For example, the following tell statement tells the Finder to get a name using the previous relative object
specifier.
end tell
When AppleScript encounters a relative object specifier outside any tell statement, it tries to complete the
object specifier by looking up the inheritance chain described in Inheritance in Script Objects (page 75).
-- an object specifier
32
AppleScript Fundamentals
Object Specifiers
end tell
In this script, the variable docRef is a reference whose object specifier refers to the first document of the
application TextEdit—which happens to be named “New [Link]” in this case. However, the object that
docRef refers to can change. If you open a second TextEdit document called “Second [Link]” so that its
window is in front of the previous document, then run this script again, it will return the name of the
now-frontmost document, “Second [Link]”.
You could instead create a reference with a more specific object specifier:
end tell
If you run this script after opening a second document, it will still return the name of the original document,
“New [Link]”, if the document exists.
After you create a reference object with the a reference to operator, you can use the contents property
to get the value of the object that it refers to. That is, using the contents property causes the reference’s
object specifier to be evaluated. In the following script, for example, the content of the variable myWindow is
the window reference itself.
myWindow
contents of myWindow
get myWindow
Note that the result of the get command is to return the reference’s object specifier, not to resolve the specifier
to the object it specifies.
33
AppleScript Fundamentals
Coercion (Object Conversion)
When it can, AppleScript will implicitly dereference a reference object (without use of the contents property),
as in the following example:
name of myWindow --result: "[Link]" (if that is the first window's name)
For related information, see the Discussion section for the reference (page 120) class.
Not all classes can be coerced to all other class types. Table 2-1 summarizes the coercions that AppleScript
supports for commonly used classes. For more information about each coercion, see the corresponding class
definition in Class Reference (page 99).
AppleScript provides many coercions, either as a built-in part of the language or through the Standard Additions
scripting addition. You can use these coercions outside of a tell block in your script. However, coercion of
application class types may be dependent on the application and require a tell block that targets the
application.
The as operator specifies a specific coercion or set of coercions. For example, the following statement coerces
the integer 2 into the text "2" before storing it in the variable myText:
If you provide a command parameter or operand of the wrong class, AppleScript automatically coerces the
operand or parameter to the expected class, if possible. If the conversion can’t be performed, AppleScript
reports an error.
34
AppleScript Fundamentals
Coercion (Object Conversion)
When coercing text strings to values of class integer, number, or real, or vice versa, AppleScript uses the
current Numbers settings in the Formats pane in International preferences to determine what separators to
use in the string. When coercing strings to values of class date or vice versa, AppleScript uses the current
Dates settings in the Formats pane.
application (page 100) list (single-item) This is both an AppleScript class and
an application class.
text
35
AppleScript Fundamentals
Scripting Additions
record (page 118) list All labels are lost in the coercion and
the resulting list cannot be coerced
back to a record.
unit types (page 131) integer Can coerce between unit types in the
list (single-item)
same category, such as inches to
kilometers (length) or gallons to
real liters (liquid volume).
text
Scripting Additions
A scripting addition is a file or bundle that provides handlers you can use in scripts to perform commands and
coercions.
36
AppleScript Fundamentals
Commands Overview
Many of the commands described in this guide are defined in the Standard Additions scripting addition in OS
X. These commands are stored in the file [Link] in
/System/Library/ScriptingAdditions, and are available to any script. You can examine the terminology
for the Standard Additions by opening this file in Script Editor.
Note: A script can obtain the location of the Standard Additions with this script statement, which
uses the path to (folder) (page 182) command:
--result: "Hard_Disk:System:Library:ScriptingAdditions:"
Scripting additions can be embedded within bundled script applets by placing them in a folder named
Scripting Additions (note the space between “Scripting” and “Additions”) inside the bundle’ s
Contents/Resources/ folder. Note that Script Editor does not look for embedded scripting additions when
editing bundled applets. During script development, any required scripting additions must be properly installed
in /System/ScriptingAdditions, /Library/ScriptingAdditions, or
~/Library/ScriptingAdditions so that Script Editor can find them.
Developers can create their own scripting additions, as described in Technical Note TN1164, Scripting Additions
for Mac OS X . For related conceptual information, see AppleScript Overview , particularly the section “Extending
AppleScript with Coercions, Scripting Additions, and Faceless Background Applications” in the chapter Open
Scripting Architecture.
Commands Overview
A command is a word or a series of words used in AppleScript statements to request an action. Every command
is directed at a target, which is the object that responds to the command. The target is often an application
object (one that is stored in an application or its documents and managed by the application, such as a window
or document) or an object in OS X. However, it can also be a script object or a value in the current script.
Commands often return results. For example, the display dialog (page 158) command returns a record that
may contain text, a button name, and other information. Your script can examine this record to determine
what to do next. You can assign the result of a command to a variable you define, or access it through the
predefined AppleScript result variable.
Types of Commands
Scripts can make use of the following kinds of commands:
37
AppleScript Fundamentals
Commands Overview
● An AppleScript command is one that is built into the AppleScript language. There currently are five such
commands: get (page 164) , set (page 197), count (page 154), copy (page 153), and run (page 193). Except
for copy , each of these commands can also be implemented by applications. That is, there is an AppleScript
version of the command that works on AppleScript objects, but an application can define its own version
that works on the object types it defines.
● A scripting addition command is one that is implemented through the mechanism described in Scripting
Additions (page 36)). Although anyone can create a scripting addition (see Technical Note TN1164, Scripting
Additions for Mac OS X ), this guide documents only the scripting addition commands from the Standard
Additions, supplied by Apple as part of OS X. These commands are available to all scripts.
● A user-defined command is one that is implemented by a handler defined in a script object. To invoke
a user-defined command outside of a tell statement, simply use its name and supply values for any
parameters it requires. The command will use the current script as its target.
To invoke a user-defined command inside a tell statement, see Calling Handlers in a tell Statement (page
92).
● An application command is one that is defined by scriptable application to provide access to a scriptable
feature. They are typically enclosed in a tell statement that targets the application. You can determine
which commands an application supports by examining its dictionary in Script Editor.
Scriptable applications that ship with OS X, such as the Finder and System Events applications (located in
/System/Library/CoreServices), provide many useful scripting commands.
Third-party scriptable applications also provide commands you can use in scripts. Many support all or a
subset of the Standard commands, described in Technical Note TN2106, Scripting Interface Guidelines .
These include commands such as delete, duplicate, exists, and move, as well as application
implementations of AppleScript commands, such as get and set.
Target
There are two ways to explicitly specify an object as the target of a command: by supplying it as the direct
parameter of the command (described in the next section) or by specifying it as the target of a tell statement
that contains the command. If a script doesn’t explicitly specify the target with a tell statement, and it isn’t
handled by a handler in the script or by AppleScript itself, it is sent to the next object in the inheritance chain
(see The AppleScript Inheritance Chain (page 75)).
In the following script, the target of the get (page 164) command is the object specifier name of first
window. Because the enclosing tell statement specifies the Finder application, the full specifier is name of
first window of application "Finder", and it is the Finder application which obtains and returns the
requested information.
38
AppleScript Fundamentals
Commands Overview
end tell
When a command targets an application, the result may be an application object. If so, subsequent statements
that target the result object are sent to the application.
A script may also implicitly specify a target by using an application command imported using a use (page ?)
statement. For example, the extract address command in the following script targets the Mail application
because the command was imported from Mail:
Direct Parameter
The direct parameter is a value, usually an object specifier, that appears immediately next to a command and
specifies the target of the command. Not all commands have a direct parameter. If a command can have a
direct parameter, it is noted in the command’s definition.
In the following statement, the object specifier last file of window 1 of application "Finder" is
the direct parameter of the duplicate command:
The direct parameter usually appears immediately after the command, but may also appear immediately before
it. This can be easier to read for some commands, such as exists in this example:
-- continue processing...
end if
A tell statement specifies a default target for all commands contained within it, so the direct parameter is
optional. The following example has the same result as the previous example:
duplicate
end tell
39
AppleScript Fundamentals
AppleScript Error Handling
In the following example, the to parameter specifies the location to which to move the first paragraph. The
value of the to parameter of the duplicate command is the relative object specifier before paragraph
4, which is an insertion point. AppleScript completes the specifier with the target of the tell statement, front
document of application "TextEdit".
end tell
The phrases paragraph 1 and before paragraph 4 are called index and relative references, respectively.
For more information, see Reference Forms (page 212).
Scripts can handle errors by enclosing statements that may encounter an error within a try (page 263) statement.
The try statement includes an on error section that is invoked if an error occurs. AppleScript passes
information about the error, including an error number and an error message, to the on error section. This
allows scripts to examine the error number and to display information about it.
If the error occurs within a handler that does not provide a try statement, AppleScript looks for an enclosing
try statement where the handler was invoked. If none of the calls in the call chain is contained in a try
statement, AppleScript stops execution of the script and displays an error message (for any error number other
than -128, described below).
A script can use an error (page 250) statement to signal an error directly. Doing so invokes the AppleScript
error handling mechanism, which looks for an enclosing try statement to handle the error.
40
AppleScript Fundamentals
Global Constants in AppleScript
Some “errors” are the result of the normal operation of a command. For example, commands such as display
dialog (page 158) and choose file (page 142) signal error –128 (User canceled), if the user clicks the Cancel
button. Scripts routinely handle the user canceled error to ensure normal operation. For an example of how
to do this, see the Examples section for the display dialog command. If no try statement in a script handles
the -128 error, AppleScript halts execution of the script without displaying any error message.
For related information, see Results (page 24), error Statements (page 249), try Statements (page 263), Error
Numbers and Error Messages (page 298), and Working with Errors (page 302).
AppleScript Constant
The global constant AppleScript provides access to properties you can use throughout your scripts.
You can use the AppleScript identifier itself to distinguish an AppleScript property from a property of the
current target with the same name, as shown in the section version (page 44).
pi
This mathematical value represents the ratio of a circle's circumference to its diameter. It is defined as a real
number with the value 3.14159265359.
For example, the following statement computes the area of a circle with radius 7:
result
When a statement is executed, AppleScript stores the resulting value, if any, in the predefined property result.
The value remains there until another statement is executed that generates a value. Until a statement that
yields a result is executed, the value of result is undefined. You can examine the result in Script Editor by
looking in the Result pane of the script window.
41
AppleScript Fundamentals
Global Constants in AppleScript
Note: When an error occurs during script execution, AppleScript signals an error. It doesn’t return
error information in the result property. For more information, see AppleScript Error Handling (page
40).
Text Constants
AppleScript defines the text properties space, tab, return, linefeed, and quote. You effectively use these
properties as text constants to represent white space or a double quote (") character. They are described in
the Special String Characters section of the text (page 124) class.
Note: Prior to OS X Snow Leopard v10.6, AppleScript only used the first delimiter in the list when
getting text items.
Because text item delimiters respect considering and ignoring attributes in AppleScript 2.0, delimiters
are case-insensitive by default. Formerly, they were always case-sensitive. To enforce the previous behavior,
add an explicit considering case statement.
You can get and set the current value of the text item delimiters property. Normally, AppleScript doesn’t
use any delimiters. For example, if the text delimiters have not been explicitly changed, the statement
"breadmilkbutter10.45"
For printing or display purposes, it is usually preferable to set text item delimiters to something that’s
easier to read. For example, the script
42
AppleScript Fundamentals
Global Constants in AppleScript
The text item delimiters property can be used to extract individual names from a pathname. For example,
the script
If you change the text item delimiters property in Script Editor, it remains changed until you restore its
previous value or until you quit Script Editor and launch it again. If you change text item delimiters in
a script application, it remains changed in that application until you restore its previous value or until the script
application quits; however, the delimiters are not changed in Script Editor or in other script applications you
run.
Scripts commonly use an error handler to reset the text item delimiters property to its former value if
an error occurs (for more on dealing with errors, see AppleScript Error Handling (page 40)):
try
on error m number n
error m number n
end try
43
AppleScript Fundamentals
Global Constants in AppleScript
version
This property provides the current version of AppleScript. The following script shows how to check for a version
greater than or equal to version 1.9. The if statement is wrapped in a considering numeric strings
statement so that an AppleScript version such as 1.10.6 compares as larger than, say, version 1.9.
else
end if
end considering
Applications can have their own version property, so to access the AppleScript version explicitly, you use
the phrase version of AppleScript. This will work inside a tell block that targets another application,
such as the following:
end tell
The current application constant is an object specifier—if you ask AppleScript for its value, the result is
the object specifier:
However, if you ask for name of current application, AppleScript resolves the object specifier and
returns the current application’s name:
44
AppleScript Fundamentals
The it and me Keywords
For example, the following statements use the missing value constant to determine if a variable has changed:
end if
If a script hasn’t targeted anything, it and me refer to the same thing—the script—as shown in the following
example:
A tell statement specifies a default target. In the following example, the default target is the Finder application:
45
AppleScript Fundamentals
The it and me Keywords
end tell
You can use the words of me or my to indicate that the target of a command is the current script and not the
target of the tell statement. In the following example, the word my indicates that minimumValue() handler
is defined by the script, not by Finder:
end tell
You can also use of me or my to distinguish script properties from object properties. Suppose there is a TextEdit
document open named “[Link]”:
end tell
The following example shows how to specify different version properties in a Finder tell statement. The
Finder is the default target, but using version of me, my version, or version of AppleScript allows
you to specify the version of the top-level script object. (The top-level script object returns the AppleScript
version, because it inherits from AppleScript, as described in The AppleScript Inheritance Chain (page 75).)
46
AppleScript Fundamentals
Aliases and Files
end tell
For information on using it in a filter reference, see the Discussion section for the Filter (page 214) reference
form.
An alias object is a dynamic reference to an existing file system object. Because it is dynamic, it can maintain
the link to its designated file system object even if that object is moved or renamed.
A file object represents a specific file at a specific location in the file system. It can refer to an item that does
not currently exist, such as the name and location for a file that is to be created. A file object is not dynamic,
and always refers to the same location, even if a different item is moved into that place. The POSIX file (page
117) pseudo-class is roughly synonymous with file: POSIX file specifiers evaluate to a file object, but they
use different semantics for the name, as described in Specifying Paths (page 47).
The following sections describe how to specify file system objects by path and how to work with them in your
scripts.
Specifying Paths
You can create alias objects and file objects by supplying a name specifier, where the name is the path
to an item in the file system.
For alias and file specifiers, the path is an HFS path, which takes the form
"disk:item:subitem:subsubitem:...:item". For example, "Hard_Disk:Applications:[Link]"
is the HFS path to the Mail application, assuming your boot drive is named "Hard_Disk".
47
AppleScript Fundamentals
Aliases and Files
HFS paths with a leading colon, such as ":folder:file", are resolved relative to the HFS working directory.
However, their use is discouraged, because the location of the HFS working directory is unspecified, and there
is no way to control it from AppleScript.
For POSIX file specifiers, the path is a POSIX path, which takes the form
"/item/subitem/subsubitem/.../item". The disk name is not required for the boot disk. For example,
"/Applications/[Link]" is the POSIX path to the Mail application. You can see the POSIX path of an
item in Finder in the "Where" field of its Get Info window. Despite the name, POSIX file specifiers may refer to
folders or disks. Use of "~" to specify a home directory is not supported.
POSIX paths without a leading slash, such as "folder/file", are resolved relative to the POSIX working
directory. This is supported, but only is useful for scripts run from the shell—the working directory is the current
directory in the shell. The location of the POSIX working directory for applications is unspecified.
The following script first creates an alias to an existing file in the variable notesAlias, then uses the variable
in a tell statement that opens the file. It uses a try (page 263) statement to check for existence of the alias
before creating it, so that the alias is only created once, even if the script is run repeatedly.
try
on error
end try
Finding the object an alias refers to is called resolving an alias. AppleScript 2.0 attempts to resolve aliases only
when you run a script. However, in earlier versions, AppleScript attempts to resolve aliases at compile time.
Once you run the previous example, creating the alias, the script will be able to find the original file when you
run it again, even if the file’s name or location changes. (However, if you run the script again after recompiling
it, it will create a new alias.)
You can get the HFS path from an alias by coercing it to text:
48
AppleScript Fundamentals
Aliases and Files
You can use the POSIX path property to obtain a POSIX-style path to the item referred to by an alias:
If an alias doesn’t refer to an existing file system object then it is broken. You can’t create an alias to an object
that doesn’t exist, such as a file you plan to create. For that you use a file object, described in the next section.
For a sample script that shows how a script application can process a list of aliases it receives when a user
drops one or more file icons on it, see open Handlers (page 94).
You can use a file object to specify a name and location for a file that may not exist:
Similarly, you can let a user specify a new file with the choose file name (page 144) command, then use the
returned file object to create the file. In the following example, if the user cancels the choose file name
dialog, the rest of the script is not executed. If the user does supply a file name, the script opens the file, creating
it if necessary, then uses a try statement to make sure it closes the file when it is finished writing to it.
try
on error
end try
49
AppleScript Fundamentals
Remote Applications
Typically, when you pass a file object to a command that uses it to operate on a new or existing item in the
file system, the components of the path must exist for the command to succeed.
Remote Applications
A script can target an application on a remote computer if remote applications are enabled on that computer,
and if the script specifies the computer with an eppc-style specifier.
eppc-Style Specifiers
An eppc-style specifier takes the following format:
eppc://[user[:password]@]IP_address
ip_address
Either a numeric IP address in dotted decimal form (four numbers, from 0 to 255, separated by periods;
for example, [Link]) or a hostname. A hostname can be a Bonjour name.
The following are examples of valid eppc-style specifiers. If you supply the user name and password, no
authentication is required. If you do not supply it, authentication may be required.
50
AppleScript Fundamentals
Remote Applications
Important: If a part of the eppc-style specifier contains non-UTF-8 characters or white space, it must be
URL-encoded: for example, here is a user name that contains a space:
John%20Smith.
The following example uses an eppc-style specifier to target the Finder on a remote computer. It includes a
user name and password, so no authentication is required.
Important: If you compile an erroneous eppc-style address, you will have to quit and relaunch Script Editor
for changes to that address to take effect.
In some cases, you’ll need to use a using terms from (page 271) statement to tell AppleScript to compile
against the local version of an application. The following example uses that technique in telling the remote
Finder application to open the TextEdit application:
"eppc://myUserName:pwd@[Link]"
tell remoteFinder
end tell
If you omit the password (pwd) in the previous script, you will have to authenticate when you run the script.
51
AppleScript Fundamentals
Debugging AppleScript Scripts
A display dialog (page 158) command can display information about what’s happening in a script and, like
a breakpoint, it halts execution until you dismiss it (or until it times out, depending on the parameters you
pass). The following example displays the current script location and the value of a variable:
The say (page 195) command can get your attention by speaking the specified text. In the following example,
currentClient is a text object that stores a client name:
say "I'm in the clientName handler. The client is " & currentClient
Logging
Script Editor can display a log of the Apple events that are sent during execution of a script. In the Script Editor
Preferences, you can also choose to keep a history of recent results or event logs.
In addition, you can insert log (page 175) statements into a script. Log output is shown in the Event Log pane
of a script window, and also in the Event Log History window, if it is open.
The following simple example logs the current word in a repeat with loopVariable (in list) (page 258)
statement:
log currentWord
52
AppleScript Fundamentals
Debugging AppleScript Scripts
end if
end repeat
The following shows how the words appear in the log when the script is run:
(*Where*)
(*is*)
(*the*)
(*hammer*)
53
Variables and Properties
Variables and properties are introduced in previous chapters in this document. You use them in script objects
to store and manipulate values.
Important: In reading this chapter, you should be familiar with the information on implicit and explicit
run handlers in run Handlers (page 93).
The following sections cover common issues in working with variables and properties, including how to declare
them and how AppleScript interprets their scope in a script:
● Defining Properties (page 54)
● Declaring Variables (page 55)
● Scope of Variables and Properties (page 60)
Defining Properties
Property labels follow the rules described in Identifiers (page 17).
propertyLabel
An identifier.
expression
An AppleScript expression that sets the initial value for the property. Property definitions are evaluated
before variable assignments, so property definitions cannot contain variables.
property windowCount : 0
54
Variables and Properties
Declaring Variables
After you define a property, you can change its value with the copy (page 153) or set (page 197) command.
The value set by a property definition is not reset each time the script is run; instead, it persists until the script
is recompiled.
You cannot declare a property in a handler but a handler can access a property defined in its containing script
object.
Declaring Variables
Variable names follow the rules described in Identifiers (page 17).
To create a variable in AppleScript, you assign it a value using the copy (page 153) or set (page 197) command.
For example, the following statements create and initialize two variables, one named circumference and
one named savedResult:
As shown in this example, a variable assignment can make use of a previously defined variable. It can also
make use of properties declared in the same script object.
There are some obvious, and some more subtle, differences in using copy and set to create a variable—see
Using the copy and set Commands (page 57) for more information.
If you assign a new value to a variable that is already in use, it replaces the old value. You can assign a simple
value, an expression, or an object specifier—expressions are evaluated and object specifiers are resolved to
obtain the value to assign. To create a variable whose value is an object specifier itself, rather than the value
of the object specified, use the a reference to (page 237) operator.
The next two sections describe how you can explicitly define a local or a global variable. These variable
types differ primarily in their scope. Scope, which refers to where a variable is accessible within a script, is
described in detail in Scope of Variables and Properties (page 60).
Local Variables
You can declare explicit local variables using the following syntax:
55
Variables and Properties
Declaring Variables
variableName
An identifier.
You cannot assign an initial value to a local variable in its declaration, nor can you declare a class for the
variable. Instead, you use the copy (page 153) or set (page 197) command to initialize a variable and set its
class. For example:
Global Variables
The syntax for global variables is nearly identical to that for local variables:
variableName
An identifier.
global gAgentCount
As with local variables, you use the copy (page 153) or set (page 197) command to initialize global variables
and set their class types. For example:
set gStatementDate to current date -- get date from current date command
56
Variables and Properties
Declaring Variables
When more than one variable refers to a changeable (or mutable) object, a change to the object is observable
through any of the variables. The types of AppleScript objects that are mutable are date (page 107), list (page
112), record (page 118), and script (page 122) objects.
For objects that cannot be modified (immutable objects), variables created with the set command may seem
like copies—there’s no way to change the object the variables point to, so they seem independent. This is
demonstrated in the example in the next section that creates the variables myName and yourName.
end tell
The following example uses a mutable object. It creates two variables that refer to the same list, then modifies
the list through one of the variables:
set myList to { 1, 2, 3 }
After executing these statements, the statements item 1 of myList and item 1 of yourList both yield
4, because both variables refer to the same list.
Now suppose you’re working with an immutable object, such as a text object:
57
Variables and Properties
Declaring Variables
Both variables refer to the same text object, but text objects are not mutable, so there is no way to change
the the value myName such that it affects the value of yourName. (If you assign new text to one of the variables,
you are just creating a new, separate text object.)
The set command can assign several variables at once using a pattern, which may be a list or record: a list or
record of variables on one side, and a list or record of values on the other. Values are matched to variables
based on their position for a list, or based on their keys for a record. Not having enough values is an error; if
there are too many values, the extra ones are ignored. The order in which the values are evaluated and the
variables are assigned is unspecified, but all values are evaluated before any assignments are made.
The Examples section of the set (page 197) command shows some simple pattern assignments. Here is an
example with more complex patterns:
set {p, q, r} to x
p = 8
q = 94133
r = {firstName:"John", lastName:"Chapman"} *)
q = 94133
r = "Chapman" *)
In the final assignment statement above, {lastName:r} is a record that hasn’t been used before in the script,
and contains an item with label lastName and value r (a previously defined variable). The variable x has
previously been set to have a record that has an item with label lastName and value "Chapman". During the
assignment, the value of the item labeled lastName in the new record is set to the value of the item labeled
lastName in x—hence it now has the value "Chapman".
As this example demonstrates, the properties of a record need not be given in the same order and need not
all be used when you set a pattern to a pattern, as long as the patterns match. For details, see the set (page
197) command.
58
Variables and Properties
Declaring Variables
Note: Using patterns with the set command is similar to using patterned parameters with handlers,
which is described in Handlers with Patterned Positional Parameters (page 87).
To copy within an application, you should use the application’s duplicate command, if it has one. To copy
between applications, you can use the get (page 164) command to obtain information from one application
and the set (page 197) command to set it in another.
The copy command creates a deep copy—that is, if you copy a nested data structure, such as a list that contains
another list, the entire structure is copied, as shown in the following example. This example creates a record
(alpha), then a list (beta), then a list that contains the first record and list (gamma), then finally a copy of gamma
(delta). It then changes a property in the original record, alpha. The result shows that the property is changed
wherever alpha appears, except in the copy, delta:
If you make a copy of a reference object, it refers to the same object as the original (because both contain
the same object specifier):
59
Variables and Properties
Scope of Variables and Properties
The scope is the range over which AppleScript recognizes a declared identifier within a script object. The
scope of a variable depends on where you declare it and whether you declare it as global or local. The
scope of a property extends to the entire script object in which it is declared. After declaring a property, you
can reuse the same identifier as a separate variable only if you first declare it as a local variable.
Lifetime refers to the period of time over which a variable or property is in existence. Only the values of properties
and global variables can persist after a script is run.
In the discussions that follow, declarations and statements in a script object that occur outside of any handlers
or nested script objects are identified as outside .
The following examples show the four basic forms for declaring variables and properties in AppleScript:
● property x: 3
The scope of a property definition is the script object in which it is declared, including any handlers or
nested script objects. A property definition specifies an initial value. You cannot declare a property in
a handler.
The value set by a property definition is not reset each time the script is run; instead, it persists until the
script is recompiled.
● global x
The scope of a global variable can be limited to specific handlers or contained script objects or it can
extend throughout a top-level script object. A global declaration doesn’t set an initial value—it must
be initialized by a copy (page 153) or set (page 197) command before a script can access its value.
The value of a global variable is not reset each time a script is run, unless its initialization statement is
executed.
● local x
The scope of a local variable can be limited to specific handlers or contained script objects or it can
extend throughout a top-level script object. A local declaration doesn’t set an initial value—it must
be initialized by a copy or set command before a script can access its value.
The value of a local variable is reset each time the handler is run (either the run handler for the script,
or the specific handler in which the variable is declared).
● set x to 3
60
Variables and Properties
Scope of Variables and Properties
In the absence of a global variable declaration, the scope of a variable declared with the copy or set
command is normally restricted to the run handler for the script, making it implicitly local to that run
handler. However, a handler or nested script object can declare the same variable with a global declaration
to gain access to it.
The value of a variable declared with the copy or set command is reset each time a script is run.
If you want to use the same identifier in several different places in a script, you should either declare it as a
property or as a global variable.
It is often convenient to limit the scope of a particular identifier to a single handler or nested script object,
which you can do by defining it as a local variable in the handler or script object. Outside, the identifier
has no value associated with it and can be reused elsewhere in the script. When used this way, a local variable
is said to shadow (or block access to) a global variable or property with the same name, making the global
version inaccessible in the scope of the handler or script object where the local variable is declared.
Note: If you save a script as a script application, then run the application on read-only media, the
value of a modified property or global variable is not saved.
Table 3-1 Scope of property and variable declarations at the top level in a script object
61
Variables and Properties
Scope of Variables and Properties
The scope of a property in a script object extends to any subsequent statements anywhere in the script.
Consider the following example:
property currentCount : 0
increment()
on increment()
end increment
When it encounters the identifier currentCount anywhere in this script, AppleScript associates it with the
currentCount property.
The value of a property persists after the script in which the property is defined has been run. Thus, the value
of currentCount is 0 the first time this script is run, 1 the next time it is run, and so on. The property’s current
value is saved with the script object and is not reset to 0 until the script is recompiled—that is, modified
and then run again, saved, or checked for syntax.
The value of a global variable also persists after the script in which it is defined has been run. However,
depending on how it is initialized, a global variable may be reset each time the script is run again. The next
example shows how to initialize a global variable so that it is initialized only the first time a script is run, and
thus produces the same result as using a property in the previous example:
global currentCount
increment()
on increment()
try
on error
set currentCount to 1
end try
end increment
62
Variables and Properties
Scope of Variables and Properties
The first time the script is run, the statement set currentCount to currentCount + 1 generates an
error because the global variable currentCount has not been initialized. When the error occurs, the on
error block initializes currentCount. When the script is run again, the variable has already been initialized,
so the error branch is not executed, and the variable keeps its previous value. Persistence is accomplished, but
not as simply as in the previous example.
If you don’t want the value associated with an identifier to persist after a script is run but you want to use the
same identifier throughout a script, declare a global variable and use the set command to set its value each
time the script is run:
global currentCount
set currentCount to 0
on increment()
end increment
increment() --result: 1
increment() --result: 2
Each time the on increment handler is called within the script, the global variable currentCount increases
by 1. However, when you run the entire script again, currentCount is reset to 0.
In the absence of a global variable declaration, the scope of a variable declaration using the set command
is normally restricted to the run handler for the script. For example, this script declares two separate
currentCount variables:
set currentCount to 10
on increment()
set currentCount to 5
end increment
increment() --result: 5
currentCount --result: 10
The scope of the first currentCount variable’s declaration is limited to the run handler for the script. Because
this script has no explicit run handler, outside statements are part of its implicit run handler, as described in
run Handlers (page 93). The scope of the second currentCount declaration, within the on increment
handler, is limited to that handler. AppleScript keeps track of each variable independently.
63
Variables and Properties
Scope of Variables and Properties
To associate a variable in a handler with the same variable declared with the set command outside the handler,
you can use a global declaration in the handler, as shown in the next example. (This approach also works to
associate a variable in a nested script object.)
set currentCount to 0
on increment()
global currentCount
end increment
increment() --result: 1
currentCount --result: 1
To restrict the context of a variable to a script’s run handler regardless of subsequent global declarations,
you must declare it explicitly as a local variable, as shown in this example:
local currentCount
set currentCount to 10
on increment()
global currentCount
end increment
Because the currentCount variable in this example is declared as local to the script, and hence to its implicit
run handler, any subsequent attempt to declare the same variable as global results in an error.
If you declare an outside variable with the set command and then declare the same identifier as a property,
the declaration with the set command overrides the property definition. For example, the following script
returns 10, not 5. This occurs because AppleScript evaluates property definitions before it evaluates set
command declarations:
numClowns --result: 10
64
Variables and Properties
Scope of Variables and Properties
The next example, shows how to use a global variable declaration in a script object to associate a global
variable with an outside property:
property currentCount : 0
script Paula
property currentCount : 20
script Joe
global currentCount
on increment()
return currentCount
end increment
end script
end script
currentCount --result: 2
This script declares two separate currentCount properties: one outside any handlers (and script objects)
in the main script and one in the script object Paula but outside of any handlers or script objects within
Paula. Because the script Joe declares the global variable currentCount, AppleScript looks for
currentCount at the top level of the script, thus treating Joe’s currentCount and currentCount at the
top level of the script as the same variable.
Table 3-2 (page 66) summarizes the scope of variables declared in a handler. Examples of each form of
declaration follow.
65
Variables and Properties
Scope of Variables and Properties
global x Within handler only Reset when script is recompiled; if initialized in handler,
then reset when handler is run
The scope of a global variable declared in a handler is limited to that handler, although AppleScript looks
beyond the handler when it tries to locate an earlier occurrence of the same variable. Here’s an example:
set currentCount to 10
on increment()
global currentCount
end increment
increment() --result: 12
currentCount --result: 12
When AppleScript encounters the currentCount variable within the on increment handler, it doesn’t
restrict its search for a previous occurrence to that handler but keeps looking until it finds the declaration
outside any handler. However, the use of currentCount in any subsequent handler in the script is local to
that handler unless the handler also explicitly declares currentCount as a global variable.
The scope of a local variable declaration in a handler is limited to that handler, even if the same identifier
has been declared as a property outside the handler:
property currentCount : 10
on increment()
local currentCount
set currentCount to 5
end increment
increment() --result: 5
currentCount --result: 10
66
Variables and Properties
Scope of Variables and Properties
The scope of a variable declaration using the set command in a handler is limited to that handler:
script Henry
on increment()
end increment
return currentCount
end script
The scope of the first declaration of the first currentCount variable in the script object Henry is limited
to the run handler for the script object (in this case, an implicit run handler, consisting of the last two
statements in the script). The scope of the second currentCount declaration, within the on increment
handler, is limited to that handler. The two instances of currentCount are independent variables.
67
Script Objects
This chapter describes the script object, which is used to implement all AppleScript scripts. Before reading
this chapter, you should be familiar with the information in AppleScript and Objects (page 27).
A script object is a user-defined object that can combine data (in the form of properties) and actions (in the
form of handlers and additional script objects). Script objects support inheritance, allowing you to define a
hierarchy of objects that share properties and handlers. You can also extend or modify the behavior of a handler
in one script object when calling it from another script object.
The top-level script (page 122) object is the one that implements the overall script you are working on. Any
script object can contain nested script objects, each of which is defined just like a top-level script object,
except that a nested script object is bracketed with statements that mark its beginning and end.
68
Script Objects
Defining Script Objects
script variableName
[ handlerDefinition ]...
[ statement ]...
end [ script ]
variableName
A variable identifier for the script. You can refer to a script object by this name elsewhere in a script.
parentSpecifier
Specifies the parent of the script object, typically another script object.
For more information, see Inheritance in Script Objects (page 75).
propertyLabel
An identifier, unique within the script object, that specifies a characteristic of the object; equivalent
to an instance variable.
initialValue
The value that is assigned to the property each time the script object is initialized. script objects are
initialized when compiled. initialValue is required in property definitions.
handlerDefinition
A handler for a command the script object can respond to; equivalent to a method. For more information,
see About Handlers (page 83) and Handler Reference (page 276).
statement
Any AppleScript statement. Statements other than handler and property definitions are treated as if they
were part of an implicit handler definition for the run command; they are executed when a script
object receives the run command.
script John
property HowManyTimes : 0
to sayHello to someone
69
Script Objects
Initializing Script Objects
end sayHello
end script
It defines a script object that can handle the sayHello command. It assigns the script object to the
variable John. The definition includes a handler for the sayHello command. It also includes a property, called
HowManyTimes, that indicates how many times the sayHello command has been called.
A handler within a script object definition follows the same syntax rules as any other handler.
You can use a tell statement to send commands to a script object. For example, the following statement
sends the sayHello command the script object defined above.
You can manipulate the properties of script objects by using the get command to get the value of a property
and the set or copy command to change the value. The value of a property is persistent—it gets reset every
time you compile the script, but not when you run it.
A top-level script object is initialized each time the script’s run handler is executed. Similarly, if you define
a script within a handler, AppleScript initializes a script object each time the handler is called. The parameter
variables in the handler definition become local variables of the script object.
For example, the makePoint handler in the following script contains a script object definition for the script
object thePoint:
on makePoint(x, y)
script thePoint
property xCoordinate:x
property yCoordinate:y
70
Script Objects
Sending Commands to Script Objects
end script
return thePoint
end makePoint
AppleScript initializes the script object thePoint when it executes the makePoint command. After the
call to makePoint, the variable myPoint refers to this script object. The parameter variables in the makePoint
handler, in this case, x and y, become local variables of the script object. The initial value of x is 10, and the
initial value of y is 20, because those are the parameters passed to the makePoint handler that initialized the
script object.
If you added the following line to the end of the previous script and ran it, the variable myOtherPoint would
refer to a second instance of the script object thePoint, with different property values:
The makePoint script is a kind of constructor function that creates script objects representing points.
tell John
sayHello to "Herb"
sayHello to "Grace"
end tell
For a script object to respond to a command within a tell statement, either the script object or its parent
object must have a handler for the command. For more information about parent objects, see Inheritance in
Script Objects (page 75).
71
Script Objects
Script Libraries
A script object definition may include an implicit run handler, consisting of all executable statements that
are outside of any handler or nested script object, or it may include an explicit run handler that begins with
on run, but it may not contain both—such a script will not compile. If a script has no run handler (for example,
a script that serves as a library of handlers, as described in Saving and Loading Libraries of Handlers (page ?)),
executing the script does nothing. However, sending it an explicit run command causes an error. For more
information, see run Handlers (page 93).
The display dialog command in the following script object definition is the only executable statement
at the top level, so it constitutes the script object’s implicit run handler and is executed when the script
sends a run command to script object John, with the statement tell John to run.
script John
property HowManyTimes : 0
to sayHello to someone
end sayHello
end script
You can also use the possessive to send a command to a script object. For example, either of the following
two forms send the sayHello command to script John (the first version compiles into the second):
Script Libraries
A top-level script object saved in a Script Libraries folder becomes a script library usable by other scripts.
Libraries let you share and reuse handlers, reorganize large scripts into a set of smaller libraries that are easier
to manage, and build richer, higher-level functionality out of simpler libraries.
72
Script Objects
Script Libraries
Note: Libraries are supported in OS X Mavericks v10.9 (AppleScript 2.3) and later. To share properties
and handlers between scripts in prior OS versions, use the load script (page 172) command as
described in Libraries using Load Script (page 309).
Creating a Library
The basic requirement for a script to be a script library is its location: it must be a script document in a “Script
Libraries” folder in one of the following folders. When searching for a library, the locations are searched in the
order listed, and the first matching script is used:
1. If the script that references the library is a bundle, the script’s bundle Resources directory. This means
that scripts may be packaged and distributed with the libraries they use.
2. If the application running the script is a bundle, the application’s bundle Resources directory. This means
that script applications (“applets” and “droplets”) may be packaged and distributed with the libraries they
use. It also enables applications that run scripts to provide libraries for use by those scripts.
3. Any installed application bundle, in the application’s bundle Library directory. This allows distributing
libraries that are associated with an application, or creating applications that exist solely to distribute
libraries. Supported in OS X v10.11 and later.
4. The Library folder in the user’s home directory, ~/Library. This is the location to install libraries for use
by a single user, and is the recommended location during library development.
5. Any folders specified in the environment variable OSA_LIBRARY_PATH. This allows using a library without
installing it in one of the usual locations. The value of this variable is a colon-separated list of paths, such
as /opt/local/Script Libraries:/usr/local/Script Libraries. Unlike the other library
locations, paths specified in OSA_LIBRARY_PATH are used exactly as-is, without appending “Script Libraries”.
Supported in OS X v10.11 and later.
6. The computer Library folder, /Library. Libraries located here are available to all users of the computer.
7. The network Library folder, /Network/Library. Libraries located here are available to multiple computers
on a network.
8. The system Library folder, /System/Library. These are libraries provided by OS X.
Script libraries also have name, id, and version properties. It is recommended that you define all three,
especially for libraries you plan to distribute publicly: doing so allows clients to unambiguously identify particular
versions of libraries that have the functionality they need. These properties may be defined either as property
definitions within the script itself, or, for script bundles, in the [Link] file, which can be edited using the
Bundle Contents drawer in Script Editor. For details, see the script (page 122) class reference.
A script library may be a single-file (scpt) or bundle format (scptd). If a library is a bundle, it may define its own
terminology.
73
Script Objects
Script Libraries
To define terminology, create an sdef file as described in the Cocoa Scripting Guide under Preparing a Scripting
Definition File. Then, copy the file to the bundle’s Resources directory and set the [Link] key
OSAScriptingDefinition to the base name of the sdef file (that is, the file name without the “.sdef”
extension). Script Editor’s Bundle Contents drawer can do this for you: drag the file into the “Resources” list to
copy the file into the bundle, and enter the base name of the sdef file in the “Scripting Definition” field.
Using a Library
A script library defines a script object, which a client script may then reference and then send commands to,
as described in Sending Commands to Script Objects (page 71). Libraries are identified by name:
AppleScript will search the various Script Library folders, as described above in Creating a Library (page $@),
and create an instance of the library script. Unlike the result from load script, this instance is shared and
persists for at least the lifetime of the client script, so you do not have to save it in a variable, and state will be
preserved while the client script is running. For example, given this library script:
property nextNumberProperty : 0
on nextNumber()
return my nextNumberProperty
end nextNumber
This client script, despite referencing the library in full both times, will log “1” and then “2”:
74
Script Objects
Inheritance in Script Objects
Note: Library script instances are unique to, and persistent for the lifetime of, the AppleScript
interpreter that loads them. Script Editor, Script Menu, and Folder Actions all run their scripts using
a separate interpreter for each script; applets and AppleScriptObjC applications use a single interpreter
for the entire application; and other applications may do either. If you are designing a library, try to
not rely on persistent state in the library script itself, since its lifetime will vary depending on how
the client script is run.
Every script object has access to the properties, handlers, and script objects it defines, as well as to those
defined by its parent, and those of any other object in the inheritance chain, including AppleScript. That’s why
the constants and properties described in Global Constants in AppleScript (page 41) are available to any script.
75
Script Objects
Inheritance in Script Objects
Note: There is an exception to the previous claim. An explicit local variable can shadow (or block
access to) a global variable or property with the same name, making the global version inaccessible
in the scope of the handler or script object. For related information, see Scope of Variables and
Properties (page 60).
The object listed in a parent property definition is called the parent object, or parent. A script object that
includes a parent property is referred to as a child script object , or child. The parent property is not required,
though if one is not specified, every script is a child of the top-level script, as described in The AppleScript
Inheritance Chain (page 75). A script object can have many children, but a child script object can have
only one parent. The parent object may be any object, such as a list (page 112) or an application (page 100)
object, but it is typically another script object.
variable
An identifier for a variable that refers to the parent object.
A script object must be initialized before it can be assigned as a parent of another script object. This means
that the definition of a parent script object (or a command that calls a function that creates a parent script
object) must come before the definition of the child in the same script.
Listing 4-1 (page 77) shows the definitions of a parent script object called Alex and a child script object
called AlexJunior.
76
Script Objects
Inheritance in Script Objects
script Alex
on sayHello()
end sayHello
on getName()
return "Alex"
end getName
end script
script AlexJunior
property parent : Alex
on getName()
end getName
end script
Each script object defines a getName() handler to return its name. The script object Alex also defines
the sayHello() handler. Because AlexJunior declares Alex to be its parent object, it inherits the sayHello()
handler.
Using a tell statement to invoke the sayHello() handler of script object Alex returns "Hello, Alex".
Invoking the same handler of script object AlexJunior returns "Hello, Alex Jr"—although the same
sayHello() handler in Alex is executed, when that handler calls getName(), it’s the getName() in
AlexJunior that is executed.
The relationship between a parent script object and its child script objects is dynamic. If the properties
of the parent change, so do the inherited properties of the children. For example, the script object JohnSon
in the following script inherits its vegetable property from script object John.
77
Script Objects
Inheritance in Script Objects
script John
end script
script JohnSon
end script
vegetable of JohnSon
When you change the vegetable property of script object John with the set command, you also change
the vegetable property of the child script object Simple. The result of the last line of the script is "Swiss
chard".
Similarly, if a child changes one of its inherited properties, the value in the parent object also changes. For
example, the script object JohnSon in the following script inherits the vegetable property from script
object John.
script John
end script
script JohnSon
on changeVegetable()
set my vegetable to "Zucchini"
end changeVegetable
end script
vegetable of John
--result: "Zucchini"
When you change the vegetable property of script object JohnSon to "Zucchini" with the
changeVegetable command, the vegetable property of script object John also changes.
78
Script Objects
Inheritance in Script Objects
The previous example demonstrates an important point about inherited properties: to refer to an inherited
property from within a child script object, you must use the reserved word my or of me to indicate that the
value to which you’re referring is a property of the current script object. (You can also use the words of
parent to indicate that the value is a property of the parent script object.) If you don’t, AppleScript assumes
the value is a local variable.
For example, if you refer to vegetable instead of my vegetable in the changeVegetable handler in the
previous example, the result is "Spinach". For related information, see The it and me Keywords (page 45).
Normally, if a child script object and its parent both have handlers for the same command, the child uses
its own handler. However, the handler in a child script object can handle a command first, and then use a
continue statement to call the handler for the same command in the parent.
This handing off of control to another object is called delegation. By delegating commands to a parent script
object, a child can extend the behavior of a handler contained in the parent without having to repeat the
entire handler definition. After the parent handles the command, AppleScript continues at the place in the
child where the continue statement was executed.
The following script includes two script object definitions, Elizabeth and ChildOfElizabeth.
script Elizabeth
property HowManyTimes : 0
to sayHello to someone
79
Script Objects
Inheritance in Script Objects
end sayHello
end script
script ChildOfElizabeth
on sayHello to someone
else
continue sayHello to someone
end if
end sayHello
end script
--result: "Hello Bob", the first four times the tell is executed;
In this example, the handler defined by ChildOfElizabeth for the sayHello command checks the value
of the HowManyTimes property each time the handler is run. If the value is greater than 3, ChildOfElizabeth
returns a message refusing to say hello. Otherwise, ChildOfElizabeth calls the sayHello handler in the
parent script object (Elizabeth), which returns the standard hello message. The word someone in the
continue statement is a parameter variable. It indicates that the parameter received with the original sayHello
command will be passed to the handler in the parent script.
Note: The reserved word my in the statement if my HowManyTimes > 10 in this example is
required to indicate that HowManyTimes is a property of the script object. Without the word my,
AppleScript assumes that HowManyTimes is an undefined local variable.
A continue statement can change the parameters of a command before delegating it. For example, suppose
the following script object is defined in the same script as the preceding example. The first continue
statement changes the direct parameter of the sayHello command from "Bill" to "William". It does this
by specifying the value "William" instead of the parameter variable someone.
80
Script Objects
Inheritance in Script Objects
script AnotherChildOfElizabeth
on sayHello to someone
else
end if
end sayHello
end script
If you override a parent’s handler in this manner, the reserved words me and my in the parent’s handler no
longer refer to the parent, as demonstrated in the example that follows.
script Hugh
on identify()
me
end identify
end script
script Andrea
on identify()
continue identify()
end identify
end script
81
Script Objects
Inheritance in Script Objects
82
About Handlers
When script developers want to factor and re-use their code, they can turn to handlers. A handler is a collection
of statements that can be invoked by name. Handlers are also known as functions, subroutines, or methods.
This chapter describes how to work with handlers, in the following sections:
● Handler Basics (page 83)
● Handlers in Script Applications (page 92)
Handler Basics
A handler is a collection of statements that can be invoked by name. Handlers are useful in scripts that perform
the same action in more than one place. You can package statements that perform a specific task as a handler,
give it a descriptive name, and call it from anywhere in the script. This makes the script shorter and easier to
maintain.
A script can contain one or more handlers. However, you can not nest a handler definition within another
handler (although a script object defined in a handler can contain other handlers).
The definition for a handler specifies the parameters it uses, if any, and may specify a class or classes for the
parameter and a default value.
When you call a handler, you must list its parameters according to how they are specified in its definition.
Handlers may have labeled, positional, or interleaved parameters, described in subsequent sections. If a
parameter has a specified class, AppleScript will coerce the actual value to that class as if using the as operator.
If a parameter has a default value, that parameter may be omitted.
A handler definition can contain variable declarations and statements. It may use a return statement (described
in detail in “return” (page 277)) to return a value and exit the handler.
The sections that follow provide additional information on working with handlers:
● Defining a Simple Handler (page 84)
● Handlers with Labeled Parameters (page 85)
83
About Handlers
Handler Basics
end rock
rock around the current date -- call handler to display current date
A handler can have no parameters. To indicate that a handler has no parameters, you include a pair of empty
parentheses after the handler name in both the handler definition and the handler call. For example, the
following helloWorld script has no parameters.
on helloWorld()
end
84
About Handlers
Handler Basics
Handlers with labeled parameters can also have a direct parameter. With the exception of the direct parameter,
which must directly follow the handler name, labeled parameters can appear in any order, with the labels from
the handler definition identifying the parameter values. This includes parameters listed in given, with, and
without clauses (of which there can be any number).
The findNumbers handler in the following example uses the special label given to define a parameter with
the label given rounding.
set resultList to {}
copy (round x) to x
end if
end if
end repeat
return resultList
end findNumbers
The next statements show how to call findNumbers by passing a predefined list variable:
85
About Handlers
Handler Basics
You can also specify the value of the rounding parameter by using a with or without clause to indicate
true or false. (In fact, when you compile the previous examples, AppleScript automatically converts given
rounding:true to with rounding and given rounding:false to without rounding.) These examples
pass a list object directly, rather than using a list variable as in the previous case:
--result: {33}
end if
end check
The following statement calls the handler, causing it to display the "Congratulations!" message
In the following example, the minimumValue routine returns the smaller of two values:
on minimumValue(x, y)
if x < y then
return x
else
return y
86
About Handlers
Handler Basics
end if
end minimumValue
-- To call minimumValue:
The first line of the minimumValue handler specifies the parameters of the handler. To call a handler with
positional parameters you list the parameters in the same order as they are specified in the handler definition.
If a handler call is part of an expression, AppleScript uses the value returned by the handler to evaluate the
expression. For example, to evaluate the following expression, AppleScript first calls minimumValue, then
evaluates the rest of the expression.
on displayPoint({x, y})
end displayPoint
displayPoint(testPoint)
A parameter pattern can be much more complex than a single list. The handler in the next example takes two
numbers and a record whose properties include a list of bounds. The handler displays a dialog box summarizing
some of the passed information.
set q to a + b
set response to "Hello " & n & ", you are " & l & ¬
" inches tall and occupy position (" & x & ", " & y & ")."
87
About Handlers
Handler Basics
end hello
The properties of a record passed to a handler with patterned parameters don’t have to be given in the same
order in which they are given in the handler’s definition, as long as all the properties required to fit the pattern
are present.
The following call to minimumValue uses the value from a handler call to maximumValue as its second
parameter. The maximumValue handler (not shown) returns the larger of two passed numeric values.
A handler with interleaved parameters may have only one parameter, as in this example:
on areaOfCircleWithRadius:radius
return radius ^ 2 * pi
end areaOfCircleWithRadius:
on areaOfRectangleWithWidth:w height:h
88
About Handlers
Handler Basics
return w * h
end areaOfRectangleWithWidth:height:
To call a handler with interleaved parameters, list the parameters in the same order as they are specified in
the handler definition. Despite the resemblance to labeled parameters, the parameters may not be reordered.
Also, the call must be explicitly sent to an object, even if the target object is the default, it. For example:
Note: The actual name of an interleaved-parameter handler is all the name parts strung together
with underscores, and is equivalent to a handler defined using that name with positional parameters.
For example, these two handler declarations are equivalent:
on tableView_objectValueForTableColumn_row_(t, c, r)
Given a compiled script, AppleScript will automatically translate between the two forms depending
on whether or not the current system version supports interleaved parameters.
Parameter Specifications
The parameter “name” in a handler definition may be a simple name, as shown above, or it may additionally
specify a required class and, for labeled parameters, a default value. To specify a required class, follow the
name with as class or as {class ,…}. For example, you could declare a parameter to be specifically an integer
like this:
on factorial(x as integer)
The effect is as if the handler began with set x to x as integer; if coercing the actual value to an integer
fails, AppleScript throws an appropriate error, which may be caught with a try block. The class may be a list
of classes, as described in Operators Reference (page 226).
89
About Handlers
Handler Basics
Labeled parameters may be declared with a default value by following the formal parameter name with :literal .
Doing so makes the parameter optional when called. For example, this declares a make handler with a default
value for the with data parameter:
This handler can now be called without supplying a with data parameter; the handler would see theData
set to the specified default missing value, which it could then test for and handle appropriately.
A parameter may use both a type specification and a default value. For example, this declares a make handler
with a with properties parameter that must be a record and has a default value of an empty record:
Recursive Handlers
A recursive handler is a handler that calls itself. For example, this recursive handler generates a factorial. (The
factorial of a number is the product of all the positive integers from 1 to that number. For example, 4 factorial
is equal to 1 * 2 * 3 * 4, or 24. The factorial of 0 is 1.)
on factorial(x)
if x > 0 then
return x * factorial(x - 1)
else
return 1
end if
end factorial
-- To call factorial:
In the example above, the handler factorial is called once, passing the value 10. The handler then calls
itself recursively with a value of x - 1, or 9. Each time the handler calls itself, it makes another recursive call,
until the value of x is 0. When x is equal to 0, AppleScript skips to the else clause and finishes executing all
the partially executed handlers, including the original factorial call.
90
About Handlers
Handler Basics
When you call a recursive handler, AppleScript keeps track of the variables and pending statements in the
original (partially executed) handler until the recursive handler has completed. Because each call uses some
memory, the maximum number of pending handlers is limited by the available memory. As a result, a recursive
handler may generate an error before the recursive calls complete.
In addition, a recursive handler may not be the most efficient solution to a problem. For example, the factorial
handler shown above can be rewritten to use a repeat statement instead of a recursive call, as shown in the
example in repeat with loopVariable (from startValue to stopValue) (page 257).
Errors in Handlers
As with any AppleScript statements that may encounter an error, you can use a try statement to deal with
possible errors in a handler. A try (page 263) statement includes two collections of statements: one to be
executed in the general case, and a second to be executed only if an error occurs.
By using one or more try statements with a handler, you can combine the advantages of reuse and error
handling in one package. For a detailed example that demonstrates this approach, see Working with Errors (page
302).
As a result, a parameter’s class type determines whether information is effectively passed by value or by
reference:
● For mutable objects (those whose class is date (page 107), list (page 112), record (page 118), or
script (page 122)), information is passed by reference :
If a handler changes the value of a parameter of this type, the original object is changed.
● For all other class types, information is effectively passed by value :
Although AppleScript passes a reference to the original object, that object cannot be changed. If the
handler assigns a new value to a parameter of this type, the original object is unchanged.
If you want to pass by reference with a class type other than date, list, record, or script, you can pass a
reference object that refers to the object in question. Although the handler will have access only to a copy
of the reference object, the specified object will be the same. Changes to the specified object in the handler
will change the original object, although changes to the reference object itself will not.
91
About Handlers
Handlers in Script Applications
For example, the following script calls the minimumValue handler defined in Handlers with Positional
Parameters (page 86) from within a tell statement. If this call did not include the words of me, it would
cause an error, because AppleScript would send the minimumValue command to TextEdit, which does not
understand that message.
minimumValue(12, 400) of me
end tell
Instead of using the words of me, you could insert the word my before the handler call:
my minimumValue(12, 400)
When saving a script in Script Editor, you can create a script application by choosing either Application or
Application Bundle from the File Format options. Saving as Application results in a simple format that is
compatible with Mac OS 9. Saving as Application Bundle results in an application that uses the modern bundle
format, with its specified directory structure, which is supported back to OS X v10.3.
When creating a script application, you can also specify whether a startup screen should appear before the
application runs its script. Whatever you write in the Description pane of the script window in Script Editor is
displayed in the startup screen. You can also specify in Script Editor whether a script application should stay
open after running. The default is for the script to quit immediately after it is run.
92
About Handlers
Handlers in Script Applications
You can run a script application from the Finder much like any other application. If it has a startup screen, the
user must click the Run button or press the Return key before the script actually runs.
end tell
What this script does as a script application depends on what you specify when you save it. If you don’t specify
a startup screen or tell it to stay open, it will automatically execute once, closing the front Finder window, and
then quit.
If a script application modifies the value of a property, the changed value persists across launches of the
application. For related information, see Scope of Variables and Properties (page 60).
For information about some common script application handlers, see the following sections:
● run Handlers (page 93)
● open Handlers (page 94)
● idle and quit Handlers for Stay-Open Applications (page 95)
run Handlers
When you run a script or launch a script application, its run handler is invoked. A script’s run handler is defined
in one of two ways:
● As an implicit run handler, which consists of all statements declared outside any handler or nested script
object in a script.
Declarations for properties and global variables are not considered statements in this context—that is,
they are not considered to be part of an implicit run handler.
● As an explicit run handler, which is enclosed within on run and end statements, similar to other handlers.
Having both an implicit and an explicit run handler is not allowed, and causes a syntax error during compilation.
If a script has no run handler (for example, a script that serves as a library of handlers, as described in Saving
and Loading Libraries of Handlers (page ?)), executing the script does nothing. However, sending it an explicit
run command causes an error.
93
About Handlers
Handlers in Script Applications
The following script demonstrates an implicit run handler. The script consists of a statement that invokes the
sayHello handler, and the definition for the handler itself:
sayHello()
on sayHello()
end sayHello
The implicit run handler for this script consists of the statement sayHello(), which is the only statement
outside the handler. If you save this script as a script application and then run the application, the script receives
a run command, which causes it to execute the one statement in the implicit run handler.
You can rewrite the previous script to provide the exact same behavior with an explicit run handler:
on run
sayHello()
end run
on sayHello()
end sayHello
Whether a script is saved as a script application or as a compiled script, its run handler is invoked when the
script is run. You can also invoke a run handler in a script application from another script. For information
about how to do this, see Calling a Script Application From a Script (page 97).
open Handlers
Mac apps, including script applications, receive an open command whenever the user drops file, folder, or disk
icons on the application’s Finder icon, even if the application is already running.
If the script in a script application includes an open handler, the handler is executed when the application
receives the open command. The open handler takes a single parameter which provides a list of all the items
to be opened. Each item in the list is analias (page 99) object.
For example, the following open handler makes a list of the pathnames of all items dropped on the script
application’s icon and saves them in the frontmost TextEdit document:
94
About Handlers
Handlers in Script Applications
on open names
-- For now, just get the name and append a return character.
end repeat
return
end open
Files, folders, or disks are not moved, copied, or affected in any way by merely dropping them on a script
application. However, the script application’s handler can tell Finder to move, copy, or otherwise manipulate
the items. For examples that work with Finder items, see Folder Actions Reference (page 285).
You can also run an open handler by sending a script application the open command. For details, see Calling
a Script Application From a Script (page 97).
Two particular handlers that stay-open script applications often provide are an idle handler and a quit
handler.
95
About Handlers
Handlers in Script Applications
idle Handlers
If a stay-open script application includes an idle handler, AppleScript sends the script application periodic
idle commands—by default, every 30 seconds—allowing it to perform background tasks when it is not
performing other actions.
If an idle handler returns a positive number, that number becomes the rate (in seconds) at which the handler
is called. If the handler returns a non-numeric value, the rate is not changed. You can return 0 to maintain the
default delay of 30 seconds.
For example, when saved as a stay-open application, the following script beeps every 5 seconds:
on idle
beep
return 5
end idle
The result returned from a handler is just the result of the last statement, even if it doesn’t include the word
return explicitly. (See “return” (page 277) for more information.) For example, this handler gets called once
a minute, because the value of the last statement is 60:
on idle
set x to 10
beep
end idle
quit Handlers
AppleScript sends a stay-open script application a quit command whenever the user chooses the Quit menu
command or presses Command-Q while the application is active. If the script includes a quit handler, the
statements in the handler are run before the application quits.
A quit handler can be used to set script properties, tell another application to do something, display a dialog
box, or perform almost any other task. If the handler includes a continue quit statement, the script
application’s default quit behavior is invoked and it quits. If the quit handler returns before it encounters a
continue quit statement, the application doesn’t quit.
96
About Handlers
Calling a Script Application From a Script
Note: The continue statement passes control back to the application’s default quit handler. For
more information, see “continue” (page 276).
For example, this handler checks with the user before allowing the application to quit:
on quit
continue quit
end if
end quit
The launch command launches the script application without sending it an implicit run command. When
the run command is sent to the script application, it processes the command, sends back a reply if necessary,
and quits.
Similarly, to launch a non-stay-open application and run its stringTest handler (which takes a text object
as a parameter), use a launch command followed by a stringTest command, like this:
97
About Handlers
Calling a Script Application From a Script
launch
end tell
For information on how to create script applications, see Handlers in Script Applications (page 92).
98
Class Reference
A class is a category for objects that share characteristics. AppleScript defines classes for common objects used
in AppleScript scripts, such as aliases, Boolean values, integers, text, and so on.
Each object in a script is an instance of a specific class and has the same properties (including the class
property), can contain the same kinds of elements, and supports the same kinds of operations and coercions
as other objects of that type. Objects that are instances of AppleScript types can be used anywhere in a
script—they don’t need to be within a tell block that specifies an application.
Scriptable applications also define their own classes, such as windows and documents, which commonly
contain properties and elements based on many of the basic AppleScript classes described in this chapter.
Scripts obtain these objects in the context of the applications that define them. For more information on the
class types applications typically support, see “Standard Classes” in Technical Note TN2106, Scripting Interface
Guidelines.
alias
For related information, see file (page 111), POSIX file (page 117), and Aliases and Files (page 47).
class
POSIX path
Coercions Supported
AppleScript supports coercion of an alias object to a text (page 124) object or single-item list (page 112).
99
Class Reference
Examples
You can use the POSIX path property to obtain a POSIX-style path to the item referred to by an alias:
Discussion
You can only create an alias to a file or folder that already exists.
Special Considerations
AppleScript 2.0 attempts to resolve aliases only when you run a script. However, in earlier versions, AppleScript
attempts to resolve aliases at compile time.
application
An application object in a script has all of the properties described here, which are handled by AppleScript. It
may have additional properties, depending on the specific application it refers to.
class
frontmost
Starting in AppleScript 2.0, accessing an application’s frontmost property returns a Boolean value without launching
the application or sending it an event.
The value of frontmost for background-only applications, UI element applications such as System Events, and
applications that are not running is always false.
100
Class Reference
id
For example, the bundle identifier for the TextEdit application is "[Link]". Its four-character
signature code is 'ttxt'. If you ask for an application object’s id property, you will get the bundle identifier version,
unless the application does not have a bundle identifier and does have a signature code.
name
Starting in AppleScript 2.0, accessing an application’s name property returns the application name as text without
launching the application or sending it an event.
running
Accessing an application’s running property returns a Boolean value without launching the application or sending
it an event.
You can also ask the System Events utility application whether an application is running. While it requires more lines
in your script to do so, that option is available in earlier versions of the Mac OS.
version
Starting in AppleScript 2.0, accessing this property returns the application version as text without launching the
application or sending it an event.
Coercions Supported
AppleScript supports coercion of an application object to a single-item list (page 112).
Examples
You can determine whether an application on the current computer is running without launching it (this won’t
work if your target is on a remote computer):
if it is running then
pause
101
Class Reference
end if
end tell
end if
The following statements specify the TextEdit application by, respectively, its signature, its bundle id, and by
a POSIX path to a specific version of TextEdit:
application id "ttxt"
application id "[Link]"
application "/Applications/[Link]"
You can target a remote application with a tell statement. For details, see “Remote Applications” (page
50).
Special Considerations
Starting in OS X v10.5, there are several changes in application behavior:
● Applications launch hidden.
AppleScript has always launched applications if it needed to in order to send them a command. However,
they would always launch visibly, which could be visually disruptive. AppleScript now launches applications
hidden by default. They will not be visible unless the script explicitly says otherwise using activate.
● Applications are located lazily.
When running a script, AppleScript will not attempt to locate an application until it needs to in order to
send it a command. This means that a compiled script or script application may contain references to
applications that do not exist on the user’s system, but AppleScript will not ask where the missing
applications are until it encounters a relevant tell block. Previous versions of AppleScript would attempt
to locate every referenced application before running the script.
When opening a script for editing, AppleScript will attempt to locate all the referenced applications in the
entire script, which may mean asking where one is. Pressing the Cancel button only cancels the search for
that application; the script will continue opening normally, though custom terminology for that application
will display as raw codes. In older versions, pressing Cancel would cancel opening the script.
102
Class Reference
In prior versions of AppleScript, use of the new built-in application properties will fall back to sending an event
to the application, but the application may not handle these properties in the same way, or handle them at
all. (Most applications will handle name, version, and frontmost; id and running are uncommon.) The
other new features described above require AppleScript 2.0.
boolean
A boolean object evaluates to one of the AppleScript constants true or false. A Boolean expression contains
one or more boolean objects and evaluates to true or false.
class
Operators
The operators that take boolean objects as operands are and, or, not, &, =, and ≠, as well as their text
equivalents: is equal to, is not equal to, equals, and so on.
The = operator returns true if both operands evaluate to the same value (either true or false); the ≠ operator
returns true if the operands evaluate to different values.
The binary operators and and or take boolean objects as operands and return Boolean values. An and
operation, such as (2 > 1) and (4 > 3), has the value true if both its operands are true, and false
otherwise. An or operation, such as (theString = "Yes") or (today = "Tuesday"), has the value
true if either of its operands is true.
The unary not operator changes a true value to false or a false value to true.
The concatenation operator (&) creates a list containing the two boolean values on either side of it; for example:
For additional information on these operators, see Operators Reference (page 226).
103
Class Reference
Coercions Supported
AppleScript supports coercion of a boolean object to a single-item list (page 112), a text (page 124) object,
or an integer (page 111).
Examples
The following are simple Boolean expressions:
true
false
paragraphCount > 2
AppleScript supplies the Boolean constants true and false to serve as the result of evaluating a Boolean
operation. But scripts rarely need to use these literals explicitly because a Boolean expression itself evaluates
to a Boolean value. For example, consider the following two script snippets:
return true
else
return false
end if
The second, simpler version, just returns the value of the Boolean comparison companyName is equal to
"Acme Baking", so it doesn’t need to use a Boolean constant.
Discussion
When you pass a Boolean value as a parameter to a command, the form may change when you compile the
command. For example, the following line
104
Class Reference
It is standard for AppleScript to compile parameter expressions from the Boolean form (such as showing
package contents true or invisibles false) into the with form (with showing package contents
or without invisibles, respectively).
class
All classes have a class property that specifies the class type. The value of the class property is an identifier.
class
Operators
The operators that take class identifier values as operands are &, =, ≠, and as.
The coercion operator as takes an object of one class type and coerces it to an object of a type specified by a
class identifier. For example, the following statement coerces a text object into a corresponding real:
Coercions Supported
AppleScript supports coercion of a class identifier to a single-item list (page 112) or a text (page 124) object.
Examples
Asking for the class of a type such as integer results in a value of class:
105
Class Reference
constant
Constants are generally used for enumerated types. You cannot define constants in scripts; constants can be
defined only by applications and by AppleScript. See Global Constants in AppleScript (page 41) for more
information.
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always constant.
Operators
The operators that take constant objects as operands are &, =, ≠, and as.
Coercions Supported
AppleScript supports coercion of a constant object to a single-item list (page 112) or a text (page 124)
object.
Examples
One place you use constants defined by AppleScript is in text comparisons performed with considering or
ignoring statements (described in considering / ignoring (text comparison) (page 245)). For example,
in the following script statements, punctuation, hyphens, and white space are constants:
end considering
Discussion
Constants are not text strings, and they must not be surrounded by quotation marks.
106
Class Reference
In addition to the constants defined by AppleScript, applications often define enumerated types to be used
for command parameters or property values. For example, the iTunes search command defines these constants
for specifying the search area:
albums
all
artists
composers
displayed
songs
date
Specifies the day of the week, the date (month, day of the month, and year), and the time (hours, minutes, and
seconds).
To get the current date, use the command current date (page 155):
You can get and set the different parts of a date object through the date and time properties described below.
When you compile a script, AppleScript displays date and time values according to the format specified in
System Preferences.
class
day
Access: read/write
Class: integer (page 111)
Specifies the day of the month of a date object.
weekday
107
Class Reference
Specifies the day of the week of a date object, with one of these constants: Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, or Sunday.
month
Access: read/write
Class: constant (page 106)
Specifies the month of the year of a date object, with one of the constants January, February, March, April,
May, June, July, August, September, October, November, or December.
year
Access: read/write
Class: integer (page 111)
Specifies the year of a date object; for example, 2004.
time
Access: read/write
Class: integer (page 111)
Specifies the number of seconds since midnight of a date object; for example, 2700 is equivalent to 12:45 AM
(2700 / 60 seconds = 45 minutes).
date string
To obtain a compact version of the date, use short date string . For example, short date string of
(current date) --result: "1/27/08".
time string
Operators
The operators that take date object as operands are &, +, –, =, ≠, >, ≥, <, ≤, comes before, comes after,
and as. In expressions containing >, ≥, <, ≤, comes before, or comes after, a later time is greater than an
earlier time.
AppleScript supports the following operations on date objects with the + and – operators:
date + timeDifference
--result: date
date - date
108
Class Reference
--result: timeDifference
date - timeDifference
--result: date
where timeDifference is an integer (page 111) value specifying a time difference in seconds. To simplify
the notation of time differences, you can also use one or more of these of these constants:
minutes
60
hours
60 * minutes
days
24 * hours
weeks
7 * days
Here’s an example:
To express a time difference in more convenient form, divide the number of seconds by the appropriate
constant:
To get an integral number of hours, days, and so on, use the div operator:
To get the difference, in seconds, between the current time and Greenwich mean time, use the time to
GMT (page 208) command.
Coercions Supported
AppleScript supports coercion of a date object to a single-item list (page 112) or a text (page 124) object.
109
Class Reference
Examples
The following expressions show some options for specifying a date, along with the results of compiling the
statements. If you construct a date using only partial information, AppleScript fills in the missing pieces with
default values. The actual format is based on the settings in System Preferences.
date "7/16/70"
The following statements access various date properties (results depend on the date the statements are
executed):
If you want to specify a time relative to a date, you can do so by using of, relative to, or in, as shown in
the following examples.
110
Class Reference
Special Considerations
You can create a date object using a string that follows the date format specified in the Formats pane in
International preferences. For example, in US English:
file
A reference to a file, folder, or volume in the file system. A file object has exactly the same attributes as an
alias object, with the addition that it can refer to an item that does not exist.
For related information, see alias (page 99) and POSIX file (page 117). For a description of the format for a
file path, see Aliases and Files (page 47).
Coercions Supported
AppleScript supports coercion of a file object to a text (page 124) object or single-item list (page 112).
Examples
close access fp
Discussion
You can create a file object that refers to a file or folder that does not exist. For example, you can use the
choose file name (page 144) command to obtain a file object for a file that need not currently exist.
integer
class
Access: read-only
111
Class Reference
Operators
The operators that can have integer values as operands are +, -, *, ÷ (or /), div, mod, ^, =, ≠, >, ≥, <, and ≤.
The div operator always returns an integer value as its result. The +, –, *, mod, and ^ operators return values
of type integer or real.
Coercions Supported
AppleScript supports coercion of an integer value to a single-item list (page 112), a real (page 117) number,
or a text (page 124) object.
Examples
set myResult to 3 - 2
-1
1000
Discussion
The biggest value (positive or negative) that can be expressed as an integer in AppleScript is ±536870911,
which is equal to ±(2^29 – 1). Larger integers are converted to real numbers, expressed in exponential notation,
when scripts are compiled.
Note: The smallest possible integer value is actually -536870912 (-2^29), but it can only be
generated as a result of an expression. If you enter it directly into a script, it will be converted to a
real when you compile.
list
An ordered collection of values. The values contained in a list are known as items. Each item can belong to
any class.
112
Class Reference
A list appears in a script as a series of expressions contained within braces and separated by commas. An empty
list is a list containing no items. It is represented by a pair of empty braces: {}.
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always list.
length
rest
reverse
You can also refer to indexed list items by class. For example, integer 1 of {"oatmeal", 42, "new"}
returns 42.
Operators
The operators that can have list values as operands are &, =, ≠, starts with, ends with, contains, and
is contained by.
For detailed explanations and examples of how AppleScript operators treat lists, see Operators Reference (page
226).
113
Class Reference
Commands Handled
You can count the items in a list or the elements of a specific class in a list with the count (page 154) command.
You can also use the length property of a list:
Coercions Supported
AppleScript supports coercion of a single-item list to any class to which the item can be coerced if it is not part
of a list.
AppleScript also supports coercion of an entire list to a text (page 124) object if each of the items in the list
can be coerced to a text object, as in the following example:
The resulting text object concatenates all the items, separated by the current value of the AppleScript property
text item delimiters. This property defaults to an empty string, so the items are simply concatenated.
For more information, see text item delimiters (page 42).
Individual items in a list can be of any class, and AppleScript supports coercion of any value to a list that contains
a single item.
Examples
The following statement defines a list that contains a text object, an integer, and a Boolean value:
{ "it's", 2, true }
Each list item can be any valid expression. The following list has the same value as the previous list:
The following statements work with lists; note that the concatenation operator (&) joins two lists into a single
list:
114
Class Reference
{"This"} & {"is", "a", "list"} --result: {"This", "is", "a", "list"}
For large lists, it is more efficient to use the a reference to operator when inserting a large number of
items into a list, rather than to access the list directly. For example, using direct access, the following script
takes about 10 seconds to create a list of 10,000 integers (results will vary depending on the computer and
other factors):
set bigList to {}
end
But the following script, which uses the a reference to operator, creates a list of 100,000 integers (ten
times the size) in just a couple of seconds (again, results may vary):
set bigList to {}
end
Similarly, accessing the items in the previously created list is much faster using a reference to—the following
takes just a few seconds:
item n of bigListRef
end repeat
115
Class Reference
However, accessing the list directly, even for only 4,000 items, can take over a minute:
item n of bigList
end repeat
number
There is never an object whose class is number; the actual class of a "number" object is always one of the more
specific types, integer (page 111) or real (page 117).
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always either integer or real.
Operators
Because values identified as values of class number are really values of either class integer or class real, the
operators available are the operators described in the definitions of the integer (page 111) or real (page 117)
classes.
Coercions Supported
Coercing an object to number results in an integer object if the result of the coercion is an integer, or a
real object if the result is a non-integer number.
Examples
Any valid literal expression for an integer or a real value is also a valid literal expression for a number value:
-1
116
Class Reference
1000
10.2579432
1.0
1.
POSIX file
There is never an object whose class is POSIX file; the result of evaluating a POSIX file specifier is a file
object. The difference between file and POSIX file objects is in how they interpret name specifiers: a
POSIX file object interprets "name" as a POSIX path, while a file object interprets it as an HFS path.
For related information, see alias (page 99) and file (page 111). For a description of the format for a POSIX
path, see Aliases and Files (page 47).
Coercions Supported
See file (page 111).
Examples
The following example asks the user to specify a file name, starting in the temporary directory /tmp, which is
difficult to specify using a file specifier:
set fileName to choose file name default location (POSIX file "/tmp")
real
Numbers that can include a fractional part, such as 3.14159 and 1.0.
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always real.
117
Class Reference
Operators
The operators that can have real values as operands are +, -, *, ÷ (or /), div, mod, ^, =, ≠, >, ≥, <, and ≤.
The ÷ and / operators always return real values as their results. The +, -, *, mod, and ^ operators return real
values if either of their operands is a real value.
Coercions Supported
AppleScript supports coercion of a real value to an integer value, rounding any fractional part.
AppleScript also supports coercion of a real value to a single-item list (page 112) or a text (page 124) object.
Coercion to text uses the decimal separator specified in Numbers in the Formats pane in International
preferences.
Examples
10.2579432
1.0
1.
As shown in the third example, a decimal point indicates a real number, even if there is no fractional part.
Real numbers can also be written using exponential notation. A letter e is preceded by a real number (without
intervening spaces) and followed by an integer exponent (also without intervening spaces). The exponent can
be either positive or negative. To obtain the value, the real number is multiplied by 10 to the power indicated
by the exponent, as in these examples:
Discussion
Real numbers that are greater than or equal to 10,000.0 or less than or equal to 0.0001 are converted to
exponential notation when scripts are compiled. The largest value that can be evaluated (positive or negative)
is 1.797693e+308.
record
An unordered collection of labeled properties. The only AppleScript classes that support user-defined properties
are record and script.
118
Class Reference
A record appears in a script as a series of property definitions contained within braces and separated by commas.
Each property definition consists of a label, a colon, and the value of the property. For example, this is a record
with two properties: {product:"pen", price:2.34}.
Each property in a record has a unique label which distinguishes it from other properties in the collection. The
values assigned to properties can belong to any class. You can change the class of a property simply by assigning
a value belonging to another class.
class
Access: read/write
Class: class (page 105)
The class identifier for the record. By default, the value is record.
If you define a class property explicitly in a record, the value you define replaces the implicit class value. In the
following example, the class is set to integer:
length
Operators
The operators that can have records as operands are &, =, ≠, contains, and is contained by.
For detailed explanations and examples of how AppleScript operators treat records, see Operators
Reference (page 226).
Commands Handled
You can count the properties in a record with the count command:
Coercions Supported
AppleScript supports coercion of records to lists; however, all labels are lost in the coercion and the resulting
list cannot be coerced back to a record.
Examples
The following example shows how to change the value of a property in a record:
119
Class Reference
AppleScript evaluates expressions in a record before using the record in other expressions. For example, the
following two records are equivalent:
You cannot refer to properties in records by numeric index. For example, the following object specifier, which
uses the index reference form on a record, is not valid.
You can access the length property of a record to count the properties it contains:
You can get the same value with the count (page 154) command:
Discussion
After you define a record, you cannot add additional properties to it. You can, however, concatenate records.
For more information, see & (concatenation) (page 236).
reference
The result of the a reference to (page 237) operator is a reference object, and object specifiers returned
from application commands are implicitly turned into reference objects.
120
Class Reference
A reference object “wraps” an object specifier. If you target a reference object with the get (page 164)
command, the command returns the reference object itself. If you ask a reference object for its contents
property, it returns the enclosed object specifier. All other requests to a reference object are forwarded to
its enclosed object specifier. For example, if you ask for the class of a reference object, you get the class
of the object specified by its object specifier.
Other than the contents property, all other property requests are forwarded to the enclosed object specifier,
so the reference object appears to have all the properties of the referenced object.
contents
Operators
All operators are forwarded to the enclosed object specifier, so the reference object appears to support all the
operators of referenced object.
Coercions Supported
All coercions are forwarded to the enclosed object specifier, so the reference object appears to support all the
coercions of referenced object.
Examples
Reference objects are most often used to specify application objects. The following example creates a reference
to a window within the TextEdit application:
In subsequent script statements, you can use the variable myWindow in place of the longer term window
"[Link]" of application "TextEdit".
Because all property requests other than contents of are forwarded to its enclosed specifier, the reference
object appears to have all the properties of the referenced object. For example, both class of statements
in the following example return window:
121
Class Reference
RGB color
A type definition for a three-item list of integer values, from 0 to 65535, that specify the red, green, and blue
components of a color.
Examples
script
The syntax for a script object is described in Defining Script Objects (page 68).
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always script.
name
Access: read-only
Class: text (page 124)
The name of the script object, implicitly defined in AppleScript 2.3 and later. For top-level scripts, this is the name
of the file the script is saved in, unless explicitly defined otherwise using a property, or, for a top-level script saved
as a script bundle, using the [Link] key CFBundleName. Script Editor’s Bundle Contents drawer includes a “Name”
field to set this value. For other script objects, it is the name the script was defined with, as text.
122
Class Reference
id
Access: read-only
Class: text (page 124)
The unique identifier of the script object, implicitly defined in AppleScript 2.3 and later. Its value is missing value
unless explicitly defined using a property, or, for a top-level script saved as a script bundle, using the [Link] key
CFBundleIdentifier. Script Editor’s Bundle Contents drawer includes an “Identifier” field to set this value.
version
Access: read-only
Class: text (page 124)
The version of the script object, implicitly defined in AppleScript 2.3 and later. For top-level scripts, its value is "1.0"
unless explicitly defined using a property, or, for a script bundle, using the [Link] key
CFBundleShortVersionString. Script Editor’s Bundle Contents drawer includes a “Short Version” field to set
this value. For other script objects, its default value is missing value. While the version may resemble a number,
it is actually of type text (page 124). For best results, compare version strings using considering numeric
strings.
Commands Handled
You can copy a script object with the copy (page 153) command or create a reference to it with the set (page
197) command.
Coercions Supported
AppleScript supports coercion of a script object to a single-item list (page 112).
Examples
The following example shows a simple script object that displays a dialog. It is followed by a statement that
shows how to run the script:
script helloScript
end script
Discussion
A script object can contain other script objects, called child scripts, and can have a parent object. For
additional information, including more detailed examples, see Script Objects (page 68).
The name, id, and version properties are automatically defined in OS X Mavericks v10.9 (AppleScript 2.3)
and later, and are used to identify scripts used as libraries, as described in Script Objects (page 68).
123
Class Reference
text
Starting in AppleScript 2.0, AppleScript is entirely Unicode-based. There is no longer a distinction between
Unicode and non-Unicode text. Comments and text constants in scripts may contain any Unicode characters,
and all text processing is done in Unicode, so all characters are preserved correctly regardless of the user’s
language preferences.
For example, the following script works correctly in AppleScript 2.0, where it would not have in previous
versions:
set ru to "Русский"
For information on compatibility with previous AppleScript versions, including the use of string and Unicode
text as synonyms for text, see the Special Considerations section.
class
Access: read-only
Class: class (page 105)
The class identifier for the object. The value of this property is always text.
id
Access: read-only
Class: integer (page 111) or list (page 112) of integer
A value (or list of values) representing the Unicode code point (or code points) for the character (or characters) in
the text object. (A Unicode code point is a unique number that represents a character and allows it to be represented
in an abstract way, independent of how it is rendered. A character in a text object may be composed of one or
more code points.)
This property, added in AppleScript 2.0, can also be used as an address, which allows mapping between Unicode
code point values and the characters at those code points. For example, id of "A" returns 65, and character
id 65 returns "A".
The id of text longer than one code point is a list of integers, and vice versa: for example, id of "hello" returns
{104, 101, 108, 108, 111}, and string id {104, 101, 108, 108, 111} returns "hello".
(Because of a bug, text id ... does not work; you must use one of string, Unicode text, or character.)
These uses of the id property obsolete the older ASCII character (page 137) and ASCII number (page 138)
commands, since, unlike those, they cover the full Unicode character range and will return the same results regardless
of the user's language preferences.
124
Class Reference
length
quoted form
A text object can contain these elements (which may behave differently than similar elements used in
applications):
character
Specify by: Arbitrary (page 212), Every (page 213), Index (page 218), Middle (page 220), Range (page 222)
One or more Unicode characters that make up the text.
Starting in AppleScript 2.0, elements of text object count a combining character cluster (also known as
a Unicode grapheme cluster) as a single character. (This relates to a feature of Unicode that is unlikely to
have an impact on most scripters: some “characters” may be represented as either a single entity or as a
base character plus a series of combining marks.
For example, “é” may be encoded as either U+00E9 (LATIN SMALL LETTER E WITH ACUTE) or as U+0065
(LATIN SMALL LETTER E), U+0301 (COMBINING ACUTE ACCENT). Nonetheless, AppleScript 2.0 will count
both as one character, where older versions counted the base character and combining mark separately.
paragraph
Specify by: Arbitrary (page 212), Every (page 213), Index (page 218), Middle (page 220), Range (page 222)
A series of characters beginning immediately after either the first character after the end of the preceding
paragraph or the beginning of the text and ending with either a carriage return character (\r), a linefeed
character (\n), a return/linefeed pair (\r\n), or the end of the text. The Unicode "paragraph separator"
character (U+2029) is not supported.
Because paragraph elements are separated by a carriage return, linefeed, or carriage return/linefeed
pair, text ending with a paragraph break specifies a following (empty) paragraph. For example,
"this\nthat\n" has three paragraphs, not two: "this", "that", and "" (the empty paragraph after the
trailing linefeed).
Similarly, two paragraph breaks in a row specify an empty paragraph between them:
125
Class Reference
text
Specify by: Every (page 213), Name (page 221)
All of the text contained in the text object, including spaces, tabs, and all other characters.
You can use text to access contiguous characters (but see also the Discussion section below):
word
Specify by: Arbitrary (page 212), Every (page 213), Index (page 218), Middle (page 220), Range (page 222)
A continuous series of characters, with word elements parsed according to the word-break rules set in the
International preference pane.
Because the rules for parsing words are thus under user control, your scripts should not count on a
deterministic text parsing of words.
Operators
The operators that can have text objects as operands are &, =, ≠, >, ≥, <, ≤, starts with, ends with,
contains, is contained by, and as.
In text comparisons, you can specify whether white space should be considered or ignored. For more information,
see “considering and ignoring Statements” (page 245).
For detailed explanations and examples of how AppleScript operators treat text objects, see Operators
Reference (page 226).
126
Class Reference
White space refers to text characters that display as vertical or horizontal space. AppleScript defines the white
space constants return, linefeed, space, and tab to represent, respectively, a return character, a linefeed
character, a space character, and a tab character. (The linefeed constant became available in AppleScript
2.0.)
Although you effectively use these values as text constants, they are actually defined as properties of the global
constant AppleScript.
Constant Value
space ""
tab "\t"
return "\r"
linefeed "\n”
To enter white space in a string, you can just type the character—that is, you can press the Space bar to insert
a space, the Tab key to insert a tab character, or the Return key to insert a return. In the latter case, the string
will appear on two lines in the script, like the following:
When you run this script, "Hello" appears above “Goodbye” in the dialog.
You can also enter a tab, return, or linefeed with the equivalent two-character sequences. When a text object
containing any of the two-character sequences is displayed to the user, the sequences are converted. For
example, if you use the following text object in a display dialog (page 158) command:
127
Class Reference
it is displayed like this (unless you enable “Escape tabs and line breaks in strings” in the Editing tab of the of
Script Editor preferences):
item 1 1
item 2 2
To use the white space constants, you use the concatenation operator to join multiple text objects together,
as in the following example:
"Year" & tab & tab & "Units sold" & return & "2006" & tab ¬
& tab & "300" & return & "2007" & tab & tab & "453"
2006 300
2007 453
Coercions Supported
AppleScript supports coercion of an text object to a single-item list (page 112). If a text object represents
an appropriate number, AppleScript supports coercion of the text object to an integer or a real number.
Examples
You can define a text object in a script by surrounding text characters with quotation marks, as in these
examples:
Suppose you use the following statement to obtain a text object named docText that contains all the text
extracted from a particular document:
The following statements show various ways to work with the text object docText:
128
Class Reference
The next example prepares a text object to use with the display dialog command. It uses the quote
constant to insert \" into the text. When this text is displayed in the dialog (above a text entry field), it looks
like this: Enter the text in quotes ("text in quotes"):
The following example gets a POSIX path to a chosen folder and uses the quoted form property to ensure
correct quoting of the resulting string for use with shell commands:
Suppose that you choose the folder named iWork '08 in your Applications folder. The previous statement
would return the following result, which properly handles the embedded single quote and space characters
in the folder name:
"'/Applications/iWork '\\''08/'"
Discussion
To get a contiguous range of characters within a text object, use the text element. For example, the value
of the following statement is the text object "y thi":
The result of a similar statement using the character element instead of the text element is a list:
129
Class Reference
You cannot set the value of an element of a text object. For example, if you attempt to change the value of
the first character of the text object myName as shown next, you’ll get an error:
--result: error: you cannot set the values of elements of text objects
However, you can achieve the same result by getting the last four characters and concatenating them with
"D":
--result: "Doris"
This example doesn’t actually modify the existing text object—it sets the variable myName to refer to a new
text object with a different value.
Special Considerations
For compatibility with versions prior to AppleScript 2.0, string and Unicode text are still defined, but are
considered synonyms for text. For example, all three of these statements have the same effect:
someObject as text
someObject as string
In addition, text, string, and Unicode text will all compare as equal. For example, class of "foo"
is string is true, even though class of "foo" returns text. However, it is still possible for applications
to distinguish between the three different types, even though AppleScript itself does not.
Starting with AppleScript 2.0, there is no style information stored with text objects.
Because all text is Unicode text, scripts now always get the Unicode text behavior. This may be different from
the former string behavior for some locale-dependent operations, in particular word elements. To get the
same behavior with 2.0 and pre-2.0, add an explicit as Unicode text coercion, for example, words of
(someText as Unicode text).
Because text item delimiters (described in text item delimiters (page 42)) respect considering and
ignoring attributes in AppleScript 2.0, delimiters are case-insensitive by default. Formerly, they were always
case-sensitive. To enforce the previous behavior, add an explicit considering case statement.
130
Class Reference
Because AppleScript 2.0 scripts store all text as Unicode, any text constants count as a use of the former
Unicode text class, which will work with any version of AppleScript back to version 1.3. A script that contains
Unicode-only characters such as Arabic or Thai will run, but will not be correctly editable using versions prior
to AppleScript 2.0: the Unicode-only characters will be lost.
unit types
Used for working with measurements of length, area, cubic and liquid volume, mass, and temperature.
The unit type classes support simple objects that do not contain other values and have only a single property,
the class property.
class
Length: centimetres, centimeters, feet, inches, kilometres, kilometers, metres, meters, miles,
yards
Area: square feet, square kilometres, square kilometers, square metres, square meters,
square miles, square yards
Cubic volume: cubic centimetres, cubic centimeters, cubic feet, cubic inches, cubic metres,
cubic meters, cubic yards
Operators
None. You must explicitly coerce a unit type to a number type before you can perform operations with it.
Coercions Supported
You can coerce a unit type object to integer (page 111), single-item list (page 112), real (page 117), or
text (page 124). You can also coerce between unit types in the same category, such as inches to kilometers
(length) or gallons to liters (liquid volume). As you would expect, there is no coercion between categories,
such as from gallons to degrees Centigrade.
Examples
The following statements calculate the area of a circle with a radius of 7 yards, then coerce the area to square
feet:
131
Class Reference
The following statements set a variable to a value of 5.0 square kilometers, then coerce it to various other units
of area:
However, you cannot coerce an area measurement to a unit type in a different category:
132
Commands Reference
This chapter describes the commands available to perform actions in AppleScript scripts. For information on
how commands work, see Commands Overview (page 37).
The commands described in this chapter are available to any script—they are either built into the AppleScript
language or added to it through the standard scripting additions (described in Scripting Additions (page 36)).
Note: In the command descriptions below, if the first item in the Parameters list does not include
a parameter name, it is the direct parameter of the command (described in Direct Parameter (page
39)).
Table 7-1 lists each command according to the suite (or related group) of commands to which it belongs and
provides a brief description. Detailed command descriptions follow the table, in alphabetical order.
Command Description
AppleScript suite
activate (page 136) Brings an application to the front, and opens it if it is on the
local computer and not already running.
log (page 175) In Script Editor, displays a value in the Event Log History
window or in the Event Log pane of a script window.
133
Commands Reference
Command Description
list disks (page 171) Returns a list of the currently mounted volumes.
Deprecated Use tell application "System Events"
to get the name of every disk.
path to (application) (page 180) Returns the full path to the specified application.
path to (folder) (page 182) Returns the full path to the specified folder.
path to resource (page 186) Returns the full path to the specified resource.
close access (page 152) Closes a file that was opened for access.
open for access (page 178) Opens a disk file for the read (page 188) and write (page
209) commands.
read (page 188) Reads data from a file that has been opened for access.
write (page 209) Writes data to a file that was opened for access with write
permission.
Internet suite
open location (page 179) Opens a URL with the appropriate program.
current date (page 155) Returns the current date and time.
do shell script (page 163) Executes a shell script using the sh shell.
get volume settings (page 167) Returns the sound output and input volume settings.
134
Commands Reference
Command Description
set volume (page 201) Sets the sound output and/or input volume.
system attribute (page 205) Gets environment variables or attributes of this computer.
time to GMT (page 208) Returns the difference between local time and GMT
(Universal Time).
Scripting suite
load script (page 172) Returns a script object loaded from a file.
Standard suite
launch (page 170) Launches the specified application without sending it a run
command.
run (page 193) For an application, launches it. For a script application,
launches it and sends it the run command. For a script script
object, executes its run handler.
set (page 197) Assigns one or more values to one or more script variables
or application objects.
135
Commands Reference
Command Description
localized string (page 172) Returns the localized string for the specified key.
choose file name (page 144) Allows the user to specify a new file reference.
choose from list (page 147) Allows the user to choose one or more items from a list.
choose remote application (page 149) Allows the user to choose a running application on a remote
machine.
display dialog (page 158) Displays a dialog box, optionally requesting user input.
activate
Brings an application to the front, launching it if necessary.
136
Commands Reference
Syntax
Parameters
application
The application to activate.
Result
None.
Examples
Discussion
The activate command does not launch applications on remote machines. For examples of other ways to
specify an application, see the application (page 100) class and Remote Applications (page 50).
ASCII character
Returns the character for a specified number.
Important: This command is deprecated starting in AppleScript 2.0—use the id property of the text
class instead.
Syntax
Parameters
integer (page 111)
The character code, an integer between 0 and 255.
Result
A text (page 124) object containing the character that corresponds to the specified number.
137
Commands Reference
Examples
Discussion
The name “ASCII” is something of a misnomer. ASCII character uses the primary text encoding, as determined
by the user’s language preferences, to map between integers and characters. If the primary language is English,
the encoding is Mac OS Roman, if it is Japanese, the encoding is MacJapanese, and so on. For integers below
128, this is generally the same as ASCII, but for integers from 128 to 255, the results vary considerably.
Because of this unpredictability, ASCII character and ASCII number are deprecated starting in AppleScript
2.0. Use the id property of the text class instead, since it always uses the same encoding, namely Unicode.
ASCII number
Returns the number associated with a specified character.
Important: This command is deprecated starting in AppleScript 2.0—use the id property of the text
class instead.
Syntax
Parameters
text (page 124)
A text object containing at least one character. If there is more than one character, only the first one is
used.
Result
The character code of the specified character as an integer.
Examples
138
Commands Reference
Discussion
The result of ASCII number depends on the user’s language preferences; see the Discussion section of ASCII
character (page 137) for details.
beep
Plays the system alert sound one or more times.
Syntax
beep required
integer optional
Parameters
integer (page 111)
Number of times to beep.
Default Value:
1
Result
None.
Examples
Audible alerts can be useful when no one is expected to be looking at the screen:
choose application
Allows the user to choose an application.
Syntax
139
Commands Reference
as class optional
Parameters
with title text (page 124)
Title text for the dialog.
Default Value:
"Choose Application"
Result
The selected application, as either an application or alias object; for example, application "TextEdit".
If multiple selections are allowed, returns a list containing one item for each selected application, if any.
Signals a “user canceled” error if the user cancels the dialog. For an example of how to handle such errors, see
try Statements (page 263).
Examples
140
Commands Reference
Discussion
The choose application dialog initially presents a list of all applications registered with the system. To
choose an application not in that list, use the Browse button, which allows the user to choose an application
anywhere in the file system.
choose color
Allows the user to choose a color from a color picker dialog.
Syntax
Parameters
default color RGB color (page 122)
The color to show when the color picker dialog is first opened.
Default Value:
{0, 0, 0}: black.
Result
The selected color, represented as a list of three integers from 0 to 65535 corresponding to the red, green, and
blue components of a color; for example, {0, 65535, 0} represents green.
Signals a “user canceled” error if the user cancels the choose color dialog. For an example of how to handle
such errors, see try Statements (page 263).
Examples
This example lets the user choose a color, then uses that color to set the background color in their home folder
(when it is in icon view):
end tell
end tell
141
Commands Reference
choose file
Allows the user to choose a file.
Syntax
Parameters
with prompt text (page 124)
The prompt to be displayed in the dialog.
Default Value:
None; no prompt is displayed.
of type list (page 112) of text (page 124)
A list of Uniform Type Identifiers (UTIs); for example, {"[Link]", "[Link]"}. Only files of
the specified types will be selectable. For a list of system-defined UTIs, see Uniform Type Identifiers
Overview . To get the UTI for a particular file, use info for (page 167).
Note: Four-character file type codes, such as "PICT" or "MooV", are also supported, but are deprecated. To get the
file type code for a particular file, use info for (page 167).
Default Value:
None; any file can be chosen.
default location alias (page 99)
The folder to begin browsing in.
Default Value:
Browsing begins in the last selected location, or, if this is the first invocation, in the user’s Documents
folder.
142
Commands Reference
Result
The selected file, as an alias. If multiple selections are allowed, returns a list containing one alias for each
selected file, if any.
Signals a “user canceled” error if the user cancels the dialog. For an example of how to handle such errors, see
try Statements (page 263).
Examples
A UTI can specify a general class of files, not just a specific format. The following script allows the user to choose
any image file, whether its format is JPEG, PNG, GIF, or whatever. It also uses the default location parameter
combined with path to (folder) (page 182) to begin browsing in the user’s Pictures folder:
143
Commands Reference
Syntax
Parameters
with prompt text (page 124)
The prompt to be displayed near the top of the dialog.
Default Value:
"Specify new file name and location"
Result
The selected location, as a file. For example:
file "HD:Users:currentUser:Documents:untitled"
Signals a “user canceled” error if the user cancels the dialog. For an example of how to handle such errors, see
try Statements (page 263).
Examples
The following example supplies a non-default prompt and search location:
144
Commands Reference
set fileName to choose file name with prompt "Save report as:" ¬
Discussion
If you choose the name of a file or folder that exists in the selected location, choose file name offers the
choice of replacing the chosen item. However, choosing to replace does not actually replace the item.
choose folder
Allows the user to choose a directory, such as a folder or a disk.
Syntax
Parameters
with prompt text (page 124)
The prompt to be displayed in the dialog.
Default Value:
None; no prompt is displayed.
default location alias (page 99)
The folder to begin browsing in.
Default Value:
Browsing begins in the last selected location, or, if this is the first invocation, in the user’s Documents
folder.
invisibles boolean (page 103)
Show invisible folders?
Default Value:
false
145
Commands Reference
Result
The selected directory, as an alias. If multiple selections are allowed, returns a list containing one alias for
each selected directory, if any.
Signals a “user canceled” error if the user cancels the choose folder dialog. For an example of how to handle
such errors, see try Statements (page 263).
Examples
The following example specifies a prompt and allows multiple selections:
The following example gets a POSIX path to a chosen folder and uses the quoted form property (of the
text (page 124) class) to ensure correct quoting of the resulting string for use with shell commands:
Suppose that you choose the folder named iWork '08 in your Applications folder. The previous statement
would return the following result, which properly handles the embedded single quote and space characters
in the folder name:
"'/Applications/iWork '\\''08/'"
146
Commands Reference
Syntax
Parameters
list (page 112) (of number (page 116) or text (page 124))
A list of numbers and/or text objects for the user to choose from.
with title text (page 124)
Title text for the dialog.
Default Value:
None; no title is displayed.
with prompt text (page 124)
The prompt to be displayed in the dialog.
Default Value:
"Please make your selection:"
default items list (page 112) (of number (page 116) or text (page 124))
A list of numbers and/or text objects to be initially selected. The list cannot include multiple items unless
you also specify multiple selections allowed true. If an item in the default items list is not in
the list to choose from, it is ignored.
Default Value:
None; no items are selected.
147
Commands Reference
Result
If the user clicks the OK button, returns a list (page 112) of the chosen number (page 116) and/or text (page
124) items; if empty selection is allowed and nothing is selected, returns an empty list ({}). If the user clicks the
Cancel button, returns false.
Examples
This script selects from a list of all the people in Address Book who have defined birthdays, and gets the birthday
of the selected one. Notice the if the result is not false test (choose from list returns false
if the user clicks Cancel) and the set aName to item 1 of the result (choose from list returns a
list, even if it contains only one item).
set bDayList to name of every person whose birth date is not missing value
choose from list bDayList with prompt "Whose birthday would you like?"
display dialog aName & "'s birthday is " & date string of theBirthday
end if
148
Commands Reference
end tell
Discussion
For historical reasons, choose from list is the only dialog command that returns a result (false) instead
of signaling an error when the user presses the “Cancel” button.
Syntax
Parameters
with title text (page 124)
Title text for the choose remote application dialog.
Default Value:
None; no title is displayed.
with prompt text (page 124)
The prompt to be displayed in the dialog.
Default Value:
"Select an application:"
Result
The selected application, as an application (page 100) object.
Signals a “user canceled” error if the user cancels the dialog. For an example of how to handle such errors, see
try Statements (page 263).
Examples
set myApp to choose remote application with prompt "Choose a remote web browser:"
149
Commands Reference
Discussion
The user may choose a remote machine using Bonjour or by entering a specific IP address. There is no way to
limit the precise kind of application returned, so either limit your script to generic operations or validate the
user’s choice. If you want your script to send application-specific commands to the resulting application, you
will need a using terms from statement.
For information on targeting other machines, see Remote Applications (page 50).
choose URL
Allows the user to specify a URL.
Syntax
Parameters
showing list (page 112) (of service types or text (page 124))
A list that specifies the types of services to show, if available. The list can contain one or more of the
following service types, or one or more text objects representing Bonjour service types (described
below), or both:
● Web servers: shows http and https services
● FTP Servers: shows ftp services
● Telnet hosts: shows telnet services
● File servers: shows afp, nfs, and smb services
● News servers: shows nntp services
● Directory services: shows ldap services
● Media servers: shows rtsp services
● Remote applications: shows eppc services
A text object is interpreted as a Bonjour service type—for example, "_ftp._tcp" represents the file
transfer protocol. These types are listed in Technical Q&A 1312: Bonjour service types used in OS X.
Default Value:
File servers
150
Commands Reference
Result
The URL for the service, as a text object. This result may be passed to open location (page 179) or to any
application that can handle the URL, such as a browser for http URLs.
Signals a “user canceled” error if the user cancels the dialog. For an example of how to handle such errors, see
try Statements (page 263).
Examples
The following script asks the user to choose an URL, either by typing in the text input field or choosing one of
the Bonjour-located servers:
clipboard info
Returns information about the current clipboard contents.
Syntax
Parameters
for class (page 105)
Restricts returned information to only this data type.
Default Value:
None; returns information for all types of data as a list of lists, where each list represents a scrap
flavor.
151
Commands Reference
Result
A list (page 112) containing one entry {class, size} for each type of data on the clipboard. To retrieve
the actual data, use the the clipboard (page 208) command.
Examples
clipboard info
close access
Closes a file opened with the open for access command.
Syntax
Parameters
(alias (page 99) | file (page 111) | file descriptor )
The alias or file specifier or integer file descriptor of the file to close. A file descriptor must be obtained
as the result of an earlier open for access (page 178) call.
Result
None.
Examples
You should always close files that you open, being sure to account for possible errors while using the open
file:
try
on error e number n
end
close access fp
152
Commands Reference
Discussion
Any files left open will be automatically closed when the application exits.
copy
Copies one or more values, storing the result in one or more variables. This command only copies AppleScript
values, not application-defined objects.
Syntax
to variablePattern required
Parameters
expression
The expression whose value is to be copied.
to variablePattern
The name of the variable or pattern of variables in which to store the value or pattern of values. Patterns
may be lists or records.
Result
The new copy of the value.
Examples
As mentioned in the Discussion, copy creates an independent copy of the original value, and it creates a deep
copy. For example:
{alpha, beta}
Each variable reflects only the changes that were made directly to that variable. Compare this with the similar
example in set (page 197).
See the set (page 197) command for examples of using variable patterns. The behavior is the same except that
the values are copied.
153
Commands Reference
Discussion
The copy command may be used to assign new values to existing variables, or to define new variables. See
Declaring Variables with the copy Command (page 59) for additional details.
Using the copy command creates a new value that is independent of the original—a subsequent change to
that value does not change the original value. The copy is a “deep” copy, so sub-objects, such as lists within
lists, are also copied. Contrast this with the behavior of the set (page 197) command.
When using copy with an object specifier, the specifier itself is the value copied, not the object in the target
application that it refers to. copy therefore copies the object specifier, but does not affect the application data
at all. To copy the object in the target application, use the application’s duplicate command, if it has one.
Special Considerations
The syntax put expression into variablePattern is also supported, but is deprecated. It will be transformed
into the copy form when you compile the script.
count
Counts the number of elements in another object.
Syntax
Parameters
expression
An expression that evaluates to an object with elements, such as a list (page 112), record (page 118),
or application-defined container object. count will count the contained elements.
Result
The number of elements, as an integer (page 111).
Examples
In its simplest form, count, or the equivalent pseudo-property number, counts the item elements of a value.
This may be an AppleScript value, such as a list:
154
Commands Reference
If the value is an object specifier that evaluates to a list, count counts the items of that list. This may be an
Every (page 213) specifier:
end tell
…or similar. For more on object specifiers, see Object Specifiers (page 30).
current date
Returns the current date and time.
Syntax
Result
The current date and time, as a date (page 107) object.
Examples
current date --result: date "Tuesday, November 13, 2007 11:13:29 AM"
See the date (page 107) class for information on how to access the properties of a date, such as the day of the
week or month.
delay
Waits for a specified number of seconds.
Syntax
155
Commands Reference
delay required
number optional
Parameters
number (page 116)
The number of seconds to delay. The number may be fractional, such as 0.5 to delay half a second.
Default Value:
0
Result
None.
Examples
display dialog ("Elapsed time: " & elapsedTime & " seconds")
Discussion
delay does not make any guarantees about the actual length of the delay, and it cannot be more precise than
1/60th of a second. delay is not suitable for real-time tasks such as audio-video synchronization.
display alert
Displays a standardized alert containing a message, explanation, and from one to three buttons.
Syntax
as alertType optional
156
Commands Reference
Parameters
text (page 124)
The alert text, which is displayed in emphasized system font.
message text (page 124)
An explanatory message, which is displayed in small system font, below the alert text.
as alertType
The type of alert to show. You can specify one of the following alert types:
informational: the standard alert dialog
Default Value:
informational
157
Commands Reference
Result
If the user clicks a button that was not specified as the cancel button, display alert returns a record that
identifies the button that was clicked—for example, {button returned: "OK"}. If the command specifies
a giving up after value, the record will also contain a gave up:false item.
If the display alert command specifies a giving up after value, and the dialog is dismissed due to
timing out before the user clicks a button, the command returns a record indicating that no button was returned
and the command gave up: {button returned:"", gave up:true}
If the user clicks the specified cancel button, the command signals a “user canceled” error. For an example of
how to handle such errors, see try Statements (page 263).
Examples
For an additional example, see the Examples section for the try (page 263) statement.
display dialog
Displays a dialog containing a message, one to three buttons, and optionally an icon and a field in which the
user can enter text.
Syntax
158
Commands Reference
Parameters
text
The dialog text, which is displayed in emphasized system font.
default answer text (page 124)
The initial contents of an editable text field. This edit field is not present unless this parameter is present;
to have the field present but blank, specify an empty string: default answer ""
Default Value:
None; there is no edit field.
hidden answer boolean (page 103)
If true, any text in the edit field is obscured as in a password dialog: each character is displayed as a bullet.
Default Value:
false: text in the edit field is shown in cleartext.
159
Commands Reference
Result
A record containing the button clicked and text entered, if any. For example:
If the dialog does not allow text input, there is no text returned item in the returned record.
If the user clicks the specified cancel button, the command signals a “user canceled” error. For an example of
how to handle such errors, see try Statements (page 263).
If the display dialog command specifies a giving up after value, and the dialog is dismissed due to
timing out before the user clicks a button, it returns a record indicating that no button was returned and the
command gave up: {button returned:"", gave up:true}
Examples
The following example shows how to use many of the parameters to a display dialog command, how to
process possible returned values, and one way to handle a user cancelled error. The dialog displays two buttons
and prompts a user to enter a name, giving up if they do not make a response within fifteen seconds. It shows
160
Commands Reference
one way to handle the case where the user cancels the dialog, which results in AppleScript signaling an “error”
with the error number -128. The script uses additional display dialog commands to show the flow of logic
and indicate where you could add statements to handle particular outcomes.
try
giving up after 15 ¬
end try
if userCanceled then
end
The following example displays a dialog that asks for a password. It supplies a default answer of "wrong", and
specifies that the default answer, as well as any text entered by the user, is hidden (displayed as a series of
bullets). It gives the user up to three chances to enter a correct password.
repeat 3 times
161
Commands Reference
exit repeat
end if
end repeat
end if
The password text is copied from the return value dialogResult. The script doesn’t check for a user cancelled
error, so if the user cancels AppleScript stops execution of the script.
display notification
Posts a notification using the Notification Center, containing a title, subtitle, and explanation, and optionally
playing a sound.
Syntax
Parameters
text (page 124)
The body text of the notification. At least one of this and the title must be specified.
with title text (page 124)
The title of the notification. At least one of this and the body text must be specified.
subtitle text (page 124)
The subtitle of the notification.
sound name text (page 124)
The name of a sound to play when the notification appears. This may be the base name of any sound
installed in Library/Sounds.
162
Commands Reference
Result
None.
Examples
display notification "Encoding complete" subtitle "The encoded files are in the
folder " & folderName
Discussion
Exactly how the notification is presented is controlled by the “Notifications” preferences in System Preferences.
Users may opt to display a reduced form of notification, turn off the sound, or even not display them at all.
do shell script
Executes a shell script using the sh shell.
Syntax
as class optional
Parameters
text (page 124)
The shell script to execute.
as class (page 105)
Specifies the desired type of the result. The raw bytes returned by the command will be interpreted as
the specified class.
Default Value:
«class utf8»: UTF-8 text. If there is no as parameter and the output is not valid UTF-8, the output
will be interpreted as text in the primary encoding.
163
Commands Reference
Default Value:
true
Result
The output of the shell script.
Signals an error if the shell script exits with a non-zero status. The error number will be the status, the error
message will be the contents of stderr.
Examples
Discussion
For additional documentation and examples of the do shell script command, see Technical Note TN2065,
do shell script in AppleScript.
get
Evaluates an object specifier and returns the result.
164
Commands Reference
The command name get is typically optional—expressions that appear as statements or operands are
automatically evaluated as if they were preceded by get. However, get can be used to force early evaluation
of part of an object specifier.
Syntax
as class optional
Parameters
specifier
An object specifier to be evaluated. If the specifier refers to an application-defined object, the get
command is sent to that application. Technically, all values respond to get, but for all values other than
object specifiers, get is an identity operation: the result is the exact same value.
as class (page 105)
The desired class for the returned data. If the data is not of the desired type, AppleScript attempts to
coerce it to that type.
Default Value:
None; no coercion is performed.
Result
The value of the evaluated expression. See Reference Forms (page 212) for details on what the results of
evaluating various object specifiers are.
Examples
get can get properties or elements of AppleScript-defined objects, such as lists:
As noted above, the get is generally optional. For example, these statements are equivalent to the above two:
165
Commands Reference
However, an explicit get can be useful for forcing early evaluation of part of an object specifier. Consider:
--Finder got an error: Can’t get word 1 of name of folder "myname" of folder "Users"
of startup disk.
This fails because Finder does not know about elements of text, such as words. AppleScript does, however,
so the script has to make Finder get only the name of ... part:
--result: "myname"
The explicit get forces that part of the specifier to be evaluated; Finder returns a text result, from which
AppleScript can then get word 1.
get eof
Returns the length of a file, in bytes.
Syntax
Parameters
(alias (page 99) | file (page 111) | file descriptor )
The file to obtain the length for, as an alias, a file specifier, or an integer (page 111) file descriptor. A file
descriptor must be obtained as the result of an earlier open for access (page 178) call.
Result
The logical size of the file, that is, the length of its contents in bytes.
Examples
This example obtains an alias to a desktop picture folder and uses get eof to obtain its length:
set desktopPicturesFolderPath to ¬
166
Commands Reference
Syntax
Result
A record containing the sound output and input volume settings. All the integer settings are between 0 (silent)
and 100 (full volume):
Examples
info for
Return information for a file or folder.
Syntax
Parameters
(alias (page 99) | file (page 111))
An alias or file specifier for the file or folder.
167
Commands Reference
Result
A record containing information about the specified file or folder, with the following fields. Some fields are
only present for certain kinds of items:
168
Commands Reference
169
Commands Reference
Examples
Special Considerations
Because info for returns so much information, it can be slow, and because it only works on one file at a
time, it can be difficult to use. The recommended technique is to use System Events or Finder to ask for the
particular properties you want.
launch
Launches an application, if it is not already running, but does not send it a run command.
If an application is already running, sending it a launch command has no effect. That allows you to open an
application without performing its usual startup procedures, such as opening a new window or, in the case of
a script application, running its script. For example, you can use the launch command when you don’t want
an application to open and close visibly. This is less useful in AppleScript 2.0, which launches applications as
hidden by default (even with the run (page 193) command).
See the application (page 100) class reference for information on how to use an application object’s is
running property to determine if it is running without having to launch it.
Syntax
Parameters
application
The application to launch.
Result
None.
170
Commands Reference
Examples
Discussion
The launch command does not launch applications on remote machines. For examples of other ways to
specify an application, see the application (page 100) class.
Many applications also support the reopen command, which reactivates a running application or launches it
if it isn’t running. If the application is already running, this command has the same effect as double-clicking
the application icon in the Finder. Each application determines how it will implement the reopen
command—some may perform their usual startup procedures, such as opening a new window, while others
perform no additional operations.
list disks
Returns the names of the currently mounted volumes.
Important: This command is deprecated; use tell application "System Events" to get the
name of every disk.
Syntax
Result
A list (page 112) of text objects, one for each currently mounted volume.
list folder
Returns the names of the items in a specified folder.
Important: This command is deprecated; use tell application "System Events" to get the
name of every disk item of ....
Syntax
171
Commands Reference
Parameters
(alias (page 99) | file (page 111))
Specifies the folder to list.
invisibles boolean (page 103)
Show invisible files and folders?
Default Value:
true
Result
A list (page 112) of text (page 124) objects, one for each item in the specified folder.
load script
Returns a script object loaded from a specified file.
Syntax
Parameters
(alias (page 99) | file (page 111))
An alias or file specifier that specifies a script object. The file must be a compiled script (with
extension scpt) or script bundle (with extension scptd).
Result
The script object. You can get this object’s properties or call its handlers as if it were a local script object.
Examples
For examples, see Saving and Loading Libraries of Handlers (page ?) in About Handlers (page 83).
localized string
Returns the localized text for the specified key.
Syntax
172
Commands Reference
Parameters
text (page 124)
The key for which to obtain the localized text.
from table text (page 124)
The name of the strings file excluding the .strings suffix.
Default Value:
"Localizable"
Result
A text (page 124) object containing the localized text, or the original key if there is no localized text for that
key.
Examples
In order for localized string to be useful, you must create localized string data for it to use:
1. Save your script as an application bundle or script bundle.
173
Commands Reference
2. Create lproj folders in the Resources directory of the bundle for each localization: for example,
[Link], [Link]. Create files named [Link] in each one. When you are
done, the folder structure should look like this:
174
Commands Reference
3. Add key/value pairs to each [Link] file. Each pair is a line of text "key " = "value ";, for example:
Now localized string will return the appropriate values, as defined in your files. For example, when
running in French:
log
In Script Editor, displays a value in the Event Log History window or in the Event Log pane of a script window.
Syntax
log required
value optional
Parameters
value
The value to display. Expressions are evaluated but object specifiers are not resolved.
The displayed value is enclosed in block comment characters—for example, (*window 1*).
If you do not specify a value, log will display just the comment characters: (**).
175
Commands Reference
Result
None.
Examples
The following shows a simple use of logging:
log area -- result (in Event Log pane): (*square feet 301.0*)
Log statements can be useful for tracking a script’s progress. For an example that shows how to log statements
in a repeat loop, see Logging (page 52).
mount volume
Mounts the specified network volume.
Syntax
Parameters
text (page 124)
The name or URL (for example, afp://server/volume/) of the volume to mount.
on server text (page 124)
The server on which the volume resides; omit if URL path provided in direct parameter.
in AppleTalk zone text (page 124)
The AppleTalk zone in which the server resides; omit if URL path provided.
as user name text (page 124)
The user name with which to log in to the server; omit for guest access.
with password text (page 124)
The password for the user name; omit for guest access.
176
Commands Reference
Result
None.
Examples
Discussion
The mount volume command can connect to any file server that is supported by the Finder onnect
C To...
command, including Windows (smb), Samba, and FTP servers. On some kinds of servers, the as user name
and with password parameters may not bypass the login dialog, but encoding the name and password in
the URL (for example, smb://myname:passwd@[Link]/sharename) will mount it silently.
offset
Finds one piece of text inside another.
Syntax
offset required
of text required
in text required
Parameters
of text (page 124)
The source text to find the position of.
in text (page 124)
The target text to search in.
Result
An integer (page 111) value indicating the position, in characters, of the source text in the target, or 0 if not
found.
Examples
177
Commands Reference
considering case
end considering
Discussion
offset compares text as the equals operator does, including considering and ignoring conditions. The
values returned are counted the same way character elements of text are counted—for example, offset
of "c" in "école" is always 2, regardless of whether "école" is in Normalization Form C or D. The result
of matching part of a character cluster is undefined.
Syntax
Parameters
(alias (page 99) | file (page 111))
An alias or file specifier that specifies the file to open. You can only use an alias if the file exists.
write permission boolean (page 103)
Should writing to the file be allowed?
Default Value:
false: write and set eof commands on this file will fail with an error.
Result
A file descriptor, as an integer (page 111). This file descriptor may be used with any of the other file commands:
read (page 188), write (page 209), get eof (page 166), set eof (page 199), and close access (page 152).
Examples
The following example opens a file named "NewFile" in the specified location path to desktop, but does
not ask for write access:
178
Commands Reference
To open the file with write access, you would substitute the following line:
Discussion
Opening a file using open for access is not the same as opening a file using Finder. It is “open” only in the
sense that AppleScript has access to read (and optionally write) its contents; it does not appear in one of the
target application’s windows, and it does not even have to be one of the target application’s files. open for
access and the associated file commands (read, write, get eof, set eof) are typically used with text files.
They can also read and write arbitrary binary data, but this is not recommended unless you create the file
yourself or have detailed knowledge of the file format.
Calling open for access on a file returns an integer, termed a file descriptor , which represents an open
communication channel to the file’s data. This file descriptor remains open until the script calls close access
on it (or on the same file). Each file descriptor maintains a file pointer , which marks the current position within
the file and is initially set to the beginning of the file. read and write commands begin reading or writing at
the file pointer, unless instructed otherwise using a from or starting at parameter, and advance the file
pointer by the number of bytes read or written, so the next operation will begin where the previous one left
off.
A single file may be opened more than once, and therefore have several different file descriptors. Each file
descriptor maintains its own file pointer, and each must be closed separately. If you open more than one
channel at once with write permission, behavior is unspecified.
It is not strictly necessary to use open for access—all the other file commands can accept an alias; if the
file is not open, they will open it, do the operation, and then close it. Explicitly opening and closing the file
does have two potential advantages, however.
One is performance: if you are performing a number of operations on the same file, opening and closing it
repeatedly could become expensive. It is cheaper to explicitly open the file, do the work, and then explicitly
close it.
Two is ease of sequential read and write operations: because the file pointer tracks the progress through the
file, reading or writing several pieces of data from the same file is a simple matter. Doing the same thing without
using the file pointer requires calculating the data size yourself, which is not even possible in some cases.
open location
Opens a URL with the appropriate program.
179
Commands Reference
Syntax
Parameters
text (page 124)
The URL to open.
error reporting boolean (page 103)
This parameter exists only for historical reasons; it is no longer supported.
Result
None.
Examples
This example opens an Apple web page:
path to (application)
Returns the location of the specified application.
Syntax
path to required
application optional
as class optional
180
Commands Reference
Parameters
application
The application to locate. See the application (page 100) class reference for possible ways to specify an
application. You may also use one of the following identifiers:
current application
The script itself. For script applications, this is the same as current application, but for script
documents, it is the location of the document.
it
Default Value:
it
Result
The location of the specified application, as either an alias or a text object containing the path.
Examples
181
Commands Reference
path to (folder)
Returns the location of the specified special folder.
Syntax
as class optional
182
Commands Reference
Parameters
183
Commands Reference
folder constant
The special folder for which to return the path. You may specify one of the following folders:
application support
applications folder
desktop
documents folder
downloads folder
favorites folder
fonts
help
home folder
internet plugins
keychain folder
library folder
modem scripts
movies folder
music folder
pictures folder
preferences
printer descriptions
public folder
scripting additions
scripts folder
services folder
shared documents
shared libraries
sites folder
startup disk
startup items
system folder
system preferences
temporary items
184
Commands Reference
trash
users folder
utilities folder
workflows folder
The following folders are also defined, but are only meaningful when used with from Classic domain:
apple menu
control panels
extensions
printer drivers
printmonitor
shutdown folder
speakable items
stationery
voices
system domain
A folder in /System.
local domain
A folder in /Library.
network domain
A folder in /Network.
user domain
A folder in the Classic Mac OS system folder. Only meaningful on systems that support Classic.
Default Value:
The default domain for the specified folder. This varies depending on the folder.
185
Commands Reference
Result
The location of the specified folder, as either an alias or a text object containing the path.
Examples
path to resource
Returns the location of the specified resource.
Syntax
Parameters
text
The name of the requested resource.
in bundle (alias (page 99) | file (page 111))
An alias or file specifier that specifies the bundle containing the resource.
Default Value:
The current script bundle for a document-based script (a scptd bundle); otherwise, the current
application.
186
Commands Reference
Result
The location of the specified resource, as an alias (page 99).
Examples
The following example shows how you can get the path to a .icns file—in this case, in the Finder application.
end
--result: alias
"HD:System:Library:CoreServices:[Link]:Contents:Resources:[Link]"
random number
Returns a random number.
Syntax
to number optional
Parameters
from number (page 116)
The lowest number to return. Can be negative.
Default Value:
0.0
to number (page 116)
The highest number to return. Can be negative.
Default Value:
1.0
187
Commands Reference
Result
A number between the from and to limits, including the limit values. Depending on the limit values, the result
may be an integer or a real. If at least one limit is specified, and all specified limits are integers, the result is an
integer. Otherwise, the result is a real, and may have a fractional part.
Examples
Discussion
Random numbers are, by definition, random, which means that you may get the same number twice (or even
more) in a row, especially if the range of possible numbers is small.
The numbers generated are only pseudo-random, and are not considered cryptographically secure.
If you need to select one of a set of objects in a relationship, use some object rather than object (random
number from 1 to count objects ). See the Arbitrary (page 212) reference form for more details.
read
Reads data from a file.
Syntax
to integer optional
188
Commands Reference
as class optional
Parameters
(alias (page 99) | file (page 111) | file descriptor )
The file to read from, as an alias, a file specifier, or an integer (page 111) file descriptor. A file descriptor
must be obtained as the result of an earlier open for access (page 178) call.
from integer (page 111)
The byte position in the file to start reading from. The position is 1-based, so 1 is the first byte of the file,
2 the second, and so on. Negative integers count from the end of the file, so -1 is the last byte, -2 the
second-to-last, and so on.
Default Value:
The current file pointer (see open for access (page 178)) if the file is open, or the beginning of the
file if not.
for integer (page 111)
The number of bytes to read.
Default Value:
Read until the end of the file.
189
Commands Reference
text or string
The primary text encoding, as determined by the user’s language preferences set in the
International preference panel. (For example, Mac OS Roman for English, MacJapanese for Japanese,
and so on.)
Unicode text
UTF-16.
«class utf8»
UTF-8. (See Double Angle Brackets (page 306) for information on chevron or “raw” syntax.)
Any other class is possible, for example date or list, but is typically only useful if the data was written
using a write statement specifying the same value for the as parameter.
Default Value:
text
Result
The data read from the file. If the file is open, the file pointer is advanced by the number of bytes read, so the
next read command will start where the previous one left off.
Examples
The following example opens a file for read access, reads up to (and including) the first occurrence of ".",
closes the file, and displays the text it read. (See the Examples section for the write (page 209) command for
how to create a similar file for reading.)
close access fp
To read all the text in the file, replace set myText to read fp until "." with set myText to read
fp.
190
Commands Reference
Discussion
At most one of to, for, before, and until is allowed. Use of before, until, or using delimiter(s) will
interpret the file first as text and then coerce the text to whatever is specified in the as parameter. Otherwise,
it is treated as binary data (which may be interpreted as text if so specified.)
read cannot automatically detect the encoding used for a text file. If a file is not in the primary encoding, you
must supply an appropriate as parameter.
When reading binary data, read always uses big-endian byte order. This is only a concern if you are reading
binary files produced by other applications.
round
Rounds a number to an integer.
Syntax
Parameters
real (page 117)
The number to round.
191
Commands Reference
rounding roundingDirection
The direction to round. You may specify one of the following rounding directions:
up
Rounds to the next largest integer. This is the same as the math “ceiling” function.
down
Rounds down to the next smallest integer. This is the same as the math “floor” function.
toward zero
Rounds toward zero, discarding any fractional part. Also known as truncation.
to nearest
Rounds to the nearest integer; .5 cases are rounded to the nearest even integer. For example, 1.5
rounds to 2, 0.5 rounds to 0. Also known as “unbiased rounding” or “bankers’ rounding.” See
Discussion for details.
as taught in school
Rounds to the nearest integer; .5 cases are rounded away from zero. This matches the rules
commonly taught in elementary mathematics classes.
Default Value:
to nearest
Result
The rounded value, as an integer (page 111) if it is within the allowable range (±229), or as a real (page 117)
if not.
Examples
Rounding up or down is not the same as rounding away from or toward zero, though it may appear so for
positive numbers. For example:
To round to the nearest multiple of something other than 1, divide by that number first, round, and then
multiply. For example, to round a number to the nearest 0.01:
set x to 5.1234
192
Commands Reference
Discussion
The definition of to nearest is more accurate than as taught in school, but may be surprising if you
have not seen it before. For example:
Rounding 1.5 to 2 should come as no surprise, but as taught in school would have rounded 0.5 up to 1.
The problem is that when dealing with large data sets or with many subsequent rounding operations, always
rounding up introduces a slight upward skew in the results. The round-to-even rule used by to nearest
tends to reduce the total rounding error, because on average an equal portion of numbers will round down
as will round up.
run
Executes the run handler of the specified target.
To run an application, it must be on a local or mounted volume. If the application is already running, the effect
of the run command depends on the application. Some applications are not affected; others repeat their
startup procedures each time they receive a run command.
The run command launches an application as hidden; use activate (page 136) to bring the application to the
front.
For a script object, the run command causes either the explicit or the implicit run handler, if any, to be
executed. For related information, see run Handlers (page 93).
Syntax
Parameters
runTarget script
A script (page 122) or application (page 100) object.
Default Value:
it (the current target)
Result
The result, if any, returned by the specified object’s run handler.
193
Commands Reference
Examples
For information about using the run command with script objects, see Sending Commands to Script
Objects (page 71).
Discussion
To specify an application to run, you can supply a string with only the application name, as shown in the
Examples section. Or you can specify a location more precisely, using one of the forms described in Aliases
and Files (page 47). For examples of other ways to specify an application, see the application (page 100)
class.
It is not necessary to explicitly tell an application to run before sending it other commands; AppleScript will
do that automatically. To launch an application without invoking its usual startup behavior, use the launch (page
170) command. For further details, see Calling a Script Application From a Script (page 97).
run script
Runs a specified script or script file.
Syntax
in text optional
Parameters
(text (page 124) | alias (page 99) | file (page 111))
The script text, or an alias or file specifier that specifies the script file to run.
194
Commands Reference
Result
The result of the script’s run handler.
Examples
The following script targets the application Finder, escaping the double quotes around the application name
with the backslash character (for more information on using the backslash, see the Special String Characters
section in the text (page 124) class description):
run script "get name of front window of app \"Finder\"" --result: a window name
say
Speaks the specified text.
Syntax
Parameters
text (page 124)
The text to speak.
195
Commands Reference
Result
None.
Examples
say "You are not listening to me!" using "Bubbles" -- result: spoken in Bubbles
The following example saves the spoken text into a sound file:
scripting components
Returns a list of the names of all currently available scripting components, such as the AppleScript component.
196
Commands Reference
Syntax
Result
A list (page 112) of text (page 124) items, one for each installed scripting component.
Examples
Discussion
A scripting component is a software component, such as AppleScript, that conforms to the Open Scripting
Architecture (OSA) interface. The OSA provides an abstract interface for applications to compile, execute, and
manipulate scripts without needing to know the details of the particular scripting language. Each scripting
language corresponds to a single scripting component.
set
Assigns one or more values to one or more variables.
Syntax
to expression optional
Parameters
variablePattern
The name of the variable or pattern of variables in which to store the value or pattern of values. Patterns
can be lists or records.
to expression
The expression whose value is to be set. It can evaluate to any type of object or value.
Result
The value assigned.
Examples
set may be used to create new variables:
197
Commands Reference
tell application "Finder" to set name of startup disk to "Happy Fun Ball"
As mentioned in the Discussion, setting one variable to another makes both variables refer to the exact same
object. If the object is mutable, that is, it has writable properties or elements, changes to the object will appear
in both variables:
{alpha, beta}
Both variables show the same changes, because they both refer to the same object. Compare this with the
similar example in copy (page 153). Assigning a new object to a variable is not the same thing as changing the
object itself, and does not affect any other variables that refer to the same object. For example:
set beta to alpha --result: beta refers to the same object as alpha
--result: assigns a new object to alpha; this does not affect beta.
{alpha, beta}
set can assign several variables at once using a pattern, which may be a list or a record. For example:
198
Commands Reference
Since position of front window evaluates to a list of two integers, this sets x to the first item in the list
and y to the second item.
You can think of pattern assignment as shorthand for a series of simple assignments, but that is not quite
accurate, because the assignments are effectively simultaneous. That means that you can use pattern assignment
to exchange two variables:
To accomplish the second statement using only simple assignments, you would need a temporary third variable.
For more information on using the set command, including a more complex pattern example, see Declaring
Variables with the set Command (page 57).
Discussion
Using the set command to assign a value to a variable causes the variable to refer to the original value. In a
sense, it creates a new name for the same object. If multiple variables refer to a mutable object (that is, one
with writable properties or elements, such as a list or script object), changes to the object are observable
through any of the variables. If you want a separate copy, use the copy (page 153) command. This sharing only
applies to values in AppleScript itself; it does not apply to values in other applications. Changing the object a
variable refers to is not the same as altering the object itself, and does not affect other variables that refer to
the same object.
set eof
Sets the length of a file, in bytes.
Syntax
to integer required
Parameters
(alias (page 99) | file (page 111) | file descriptor )
The file to set the length of, as an alias, a file specifier, or as an integer file descriptor, which must be
obtained as the result of an earlier open for access (page 178) call.
199
Commands Reference
Result
None.
Signals a “write permission” error if the file was opened using open for access without write permission.
Examples
If you want to completely replace the contents of an existing file, the first step must be to change its length
to zero:
Syntax
Parameters
anything
The data (of any type) to place on the clipboard.
Result
None.
Examples
The following script places text on the clipboard, then retrieves the text in TextEdit with a the clipboard (page
208) command:
200
Commands Reference
end tell
Discussion
It is not necessary to use the clipboard to move data between scriptable applications. You can simply get the
data from the first application into a variable and set the appropriate data in the second application.
set volume
Sets the sound output, input, and alert volumes.
Syntax
number optional
Parameters
number (page 116)
The sound output volume, a real number from 0 to 7.
Important: This parameter is deprecated; if specified, all other parameters will be ignored.
201
Commands Reference
Result
None.
Examples
The following example saves the current volume settings, before increasing the output volume, saying some
text, and restoring the original value:
delay 1
store script
Stores a script object into a file.
Syntax
in fileSpecifier optional
202
Commands Reference
Parameters
script
The script object to store.
in (alias (page 99) | file (page 111))
An alias or file specifier that specifies the file to store the script object in.
Default Value:
None; a standard Save As dialog will be presented to allow the user to choose where to save the
script object.
replacing replacingConstant
Allow overwriting an existing file? You may specify one of the following constants:
yes
Present a dialog asking the user what to do; the options are Replace (overwrite the file), Cancel
(signal a “user canceled” error), or Save As (save to a different location).
Default Value:
ask
Result
None.
Examples
This example stores a script on disk, using the Save As dialog to specify a location on the desktop and the
name storedScript. It then creates an alias to the stored script and runs it with run script:
script test
end script
203
Commands Reference
The store script command stores only the contents of the script—in this case, the one statement, display
dialog "Test". It does not store the beginning and ending statements of the script definition.
summarize
Summarizes the specified text or text file.
Syntax
in integer optional
Parameters
textSpecifier
The text (page 124), or an alias (page 99) to a text file, to summarize.
in integer (page 111)
The number of sentences desired in the summary.
Default Value:
1
Result
A text (page 124) object containing a summarized version of the text or file.
Examples
This example summarizes Lincoln’s famous Gettysburg Address down to one sentence—a tough job even for
AppleScript:
set niceSpeech to "Four score and seven years ago our fathers brought forth on
this continent a new nation, conceived in Liberty, and dedicated to the proposition
that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation,
so conceived and so dedicated, can long endure. We are met on a great battle-field
of that war. We have come to dedicate a portion of that field, as a final resting
place for those who here gave their lives that that nation might live. It is
altogether fitting and proper that we should do this.
But, in a larger sense, we can not dedicate—we can not consecrate—we can not
hallow—this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will little
note, nor long remember what we say here, but it can never forget what they did
here. It is for us the living, rather, to be dedicated here to the unfinished work
which they who fought here have thus far so nobly advanced. It is rather for us
to be here dedicated to the great task remaining before us—that from these honored
204
Commands Reference
dead we take increased devotion to that cause for which they gave the last full
measure of devotion—that we here highly resolve that these dead shall not have
died in vain—that this nation, under God, shall have a new birth of freedom—and
that government of the people, by the people, for the people, shall not perish
from the earth."
system attribute
Get environment variables or attributes of this computer.
Syntax
Parameters
attribute
The attribute to test: either a Gestalt value or a shell environment variable name. Gestalt values are
described in Gestalt Manager Reference .
Default Value:
If the attribute is omitted, system attribute will return a list of the names of all currently defined
environment variables.
has integer (page 111)
For Gestalt values, an integer mask that is bitwise-ANDed with the Gestalt response. If the result is non-zero,
system attribute returns true, otherwise false.
Result
If the attribute specified is a Gestalt selector, either the Gestalt response code or true or false depending
on the has parameter.
If the attribute specified is an environment variable, the value of that variable, or an empty string ("") if it is
not defined.
Examples
To get the current shell:
205
Commands Reference
system attribute
*)
system info
Gets information about the system.
Syntax
Result
A record containing various information about the system and the current user. This record contains the
following fields:
206
Commands Reference
207
Commands Reference
Examples
the clipboard
Returns the contents of the clipboard.
Syntax
as class optional
Parameters
as class (page 105)
The type of data desired. the clipboard will attempt to find that “flavor” of data on the clipboard; if
it is not found, it will attempt to coerce whatever flavor is there.
Result
The data from the clipboard, which can be of any type.
Examples
The following script places text on the clipboard, and then appends the clipboard contents to the frontmost
TextEdit document:
make new paragraph at end of document 1 with data (return & the clipboard)
end tell
Discussion
It is not necessary to use the clipboard to move data between scriptable applications. You can simply get the
data from the first application into a variable and set the appropriate data in the second application.
time to GMT
Returns the difference between local time and GMT (Greenwich Mean Time) or Universal Time, in seconds.
208
Commands Reference
Syntax
Result
The integer (page 111) number of seconds difference between the current time zone and Universal Time.
Examples
The following example computes the time difference between the current location and Cupertino:
write
Writes data to a specified file.
Syntax
to fileSpecifier required
as class optional
Parameters
anything
The data to write to the file. This is typically text, but may be of any type. When reading the data back,
the read command must specify the same type, or the results are undefined.
209
Commands Reference
text or string
The primary text encoding, as determined by the user’s language preferences set in the
International preference panel. (For example, Mac OS Roman for English, MacJapanese for Japanese,
and so on.)
Unicode text
UTF-16.
«class utf8»
UTF-8.
Any other class is possible, for example date or list, but is typically only useful if the data will be read
using a read statement specifying the same value for the as parameter.
Default Value:
The class of the supplied data. See Special Considerations.
Result
None. If the file is open, write will advance the file pointer by the number of bytes written, so the next write
command will start writing where the last one ended.
Signals an error if the file is open without write permission, or if there is any other problem that prevents
writing to the file, such as a lack of disk space.
210
Commands Reference
Examples
The following example opens a file with write permission, creating it if it doesn’t already exist, writes text to
it, and closes it.
close access fp
Special Considerations
As specified above, write with no as parameter writes as the class of the supplied data, which means that in
AppleScript 2.0 write always writes text data using the primary encoding. Prior to 2.0, string and Unicode
text were distinct types, which meant that it would use primary encoding for string and UTF-16 for Unicode
text. For reliable results when creating scripts that will run on both 2.0 and pre-2.0, always specify the encoding
explicitly using as text or as Unicode text, as appropriate.
211
Reference Forms
This chapter describes AppleScript reference forms. A reference form specifies the syntax for identifying an
object or group of objects in an application or other container—that is, the syntax for constructing an object
specifier (described in Object Specifiers (page 30)).
For example, the following object specifier (from a script targeting the Finder) uses several index reference
forms, which identify an object by its number within a container:
Important: When you use a reference form, you specify the container in which the referenced object or
objects reside. This takes the form referenceForm of containerObject . You can also enclose a reference
form in a tell statement, which then serves to specify the outer container. For more information, see
Absolute and Relative Object Specifiers (page 32).
Some of the examples of reference forms shown in this chapter will not compile as shown. To compile
them, you may need to add an enclosing tell statement, targeting the Finder or the word processing
application TextEdit.
Arbitrary
Specifies an arbitrary object in a container. This form is useful whenever randomness is desired.
Because an arbitrary item is, by its nature, random, this form is not useful for operations such as processing
each item in a group of files, words, or other objects.
Syntax
some class
Placeholders
class
The class for an arbitrary object.
Examples
The following creates a new Mail message with a random signature (and depends on the user having at least
one signature):
212
Reference Forms
activate
end tell
end tell
Every
Specifies every object of a particular class in a container.
Syntax
every class
pluralClass
Placeholders
class
A singular class (such as word or paragraph).
pluralClass
The plural form for a class (such as words or paragraphs).
Value
The value of an every object specifier is a list of the objects from the container. If the container does not
contain any objects of the specified class, the list is an empty list: {}. For example, the value of the expression
every word of {1, 2, 3} is the empty list {}.
Examples
The following example uses an every object specifier to specify every word contained in a text string:
213
Reference Forms
every word of myText --result: {"That's", "all", "folks"} (a list of three words)
words of myText
The following example specifies a list of all the items in the Users folder of the startup disk (boot partition):
end tell
end tell
Discussion
Use of the every reference form implies the existence of an index property for the specified objects.
If you specify an every object specifier as the container from which to obtain a property or object, the result
is a list containing the specified property or object for each object of the container. The number of items in
the list is the same as the number of objects in the container.
Filter
Specifies all objects in a container that match a condition, or test, specified by a Boolean expression.
The filter form specifies application objects only. It cannot be used to filter the AppleScript objects list (page
112), record (page 118), or text (page 124). A term that uses the filter form is also known as a whose clause.
Note: You can use the words where or that as synonyms for whose.
A filter reference form can often be replaced by a repeat statement, or vice versa. For example, the following
script closes every TextEdit window that isn’t named "Old [Link]":
214
Reference Forms
end tell
You could instead obtain a list of open windows and set up a repeat statement that checks the name of each
window and closes the window if it isn’t named "Old [Link]". However, a whose clause is often the
fastest way to obtain the desired information.
Syntax
Placeholders
objectSpecifier
Specifies the container in which to look for objects that match the Boolean test.
whose | where
These words have the same meaning, and refer to all of the objects in the specified container that match
the conditions in the specified Boolean expression.
booleanTest
Any Boolean expression (see the boolean (page 103) class definition).
Value
The value of a filter reference form is a list of the objects that pass the test. If no objects pass the test, the list
is an empty list: {}.
Examples
The following example shows an object specifier for all open Finder windows that do not have the name
"AppleScript Language Guide".
end tell
215
Reference Forms
Discussion
In effect, a filter reduces the number of objects in a container. Instead of specifying every Finder window, the
following object specifier specifies just the windows that are currently zoomed:
To specify a container after a filter, you must enclose the filter and the object specifier it applies to in parentheses,
as in this example:
end tell
Within a test in a filter reference, the direct object is the object being tested. Though it isn’t generally needed,
this implicit target can be specified explicitly using the keyword it, which is described in The it and me
Keywords (page 45).
The following example shows several equivalent ways of constructing a filter reference to find all the files in
a folder that whose name contains the word “AppleScript”. While the term it refers to the Finder application
outside of the filter statements, within them of it refers to the current file being tested. The result of each
filter test is the same and is not changed by including or omitting the term of it:
-- same result
end tell
216
Reference Forms
A filter reference form includes one or more tests. Each test is a Boolean expression that compares a property
or element of each object being tested, or the objects themselves, with another object or value. Table 8-1 (page
217) shows some filter references, the Boolean expressions they contain, and what is being tested in each
reference.
windows whose name isn’t name isn’t "Hard The name property of each
"Hard Disk" Disk" window
files whose creator type creator type is The creator type property of
is "OMGR" "OMGR" each file
A test can be any Boolean expression. You can link multiple tests, as in the following statement:
ID
Specifies an object by the value of its id property.
You can use the ID reference form only with application objects that have an ID property.
Syntax
class id expression
Placeholders
expression
The id value.
Examples
The following examples use the ID reference form to specify an application by ID and a disk object by ID.
217
Reference Forms
end tell
Discussion
Use of the id reference form implies the existence of a id property for the specified objects.
Although id properties are most often integers, an id property can belong to any class. An application that
supports id properties for its scriptable objects must guarantee that the IDs are unique within a container.
Some applications may also provide additional guarantees, such as ensuring the uniqueness of an ID among
all objects.
The value of an id property is not typically modifiable. It does not change even if the object is moved within
the container. This allows you to save an object’s ID and use it to refer to the object for as long as the object
exists. In some scripts you may wish to refer to an object by its ID, rather than by a property such as its name,
which may change. Similarly, you could keep track of an item by its index, but indexes can change when items
in a container are added, deleted, or even renamed.
Note: A good way to keep track of files and folders is to use an alias (page 99).
Starting in AppleScript 2.0, objects of class application (page 100) have an id property, which represents the
application’s bundle identifier (the default) or its four-character signature code.
Also starting in AppleScript 2.0, objects of class text (page 124) have an id property, representing the Unicode
code point or points for the character or characters in the object. Because a text object’s ID is based on the
characters it contains, these IDs are not guaranteed to be unique, and in fact will be identical for two text
objects that store the same characters. And in fact, there is no way to tell two such objects apart by inspection.
Index
Specifies an object by describing its position with respect to the beginning or end of a container.
Syntax
( first | second | third | fourth | fifth | sixth | seventh | eighth | ninth | tenth ) class
218
Reference Forms
Placeholders
class
The class of the indexed object to obtain.
integer
An integer that describes the position of the object in relation to the beginning of the container (if integer
is a positive integer) or the end of the container (if integer is a negative integer).
st | nd | rd | th
Appended to the appropriate integer to form an index. For example, 1st, 2nd, 3rd.
first | second | third | fourth | fifth | sixth | seventh | eighth | ninth | tenth
Specify one of the ordinal indexes.
The forms first, second, and so on are equivalent to the corresponding integer forms (for example,
second word is equivalent to 2nd word). For objects whose index is greater than 10, you can use the
forms 12th, 23rd, 101st, and so on. (Note that any integer followed by any of the suffixes listed is valid;
for example, you can use 11rd to refer to the eleventh object.)
last | front | back
The front form (for example, front window) is equivalent to class 1 (window 1) or first class (first
window). The last and back forms (for example, last word and back window) refer to the last object
in a container. They are equivalent to class -1 (for example, window -1).
Examples
Each of the following object specifiers specifies the first item on the startup disk:
The following object specifiers specify the second word from the beginning of the third paragraph:
word 2 of paragraph 3
The following object specifiers specify the last word in the third paragraph:
word –1 of paragraph 3
219
Reference Forms
The following object specifiers specify the next-to-last word in the third paragraph.
word –2 of paragraph 3
Discussion
Indexes are volatile. Changing some other property of the object may change its index, as well as the index of
other like objects. For example, after deleting word 4 from a paragraph, the word no longer exists. But there
may still be a word 4—the word that was formerly word 5. After word 4 is deleted, any words with an index
higher than 4 will also have a new index. So the object an index specifies can change.
For a unique, persistent object specifier, you can use the id reference form (see ID (page 217)), if the application
supports it for the class of object you are working with. And for keeping track of a file, you can use an
alias (page 99) object.
Middle
Specifies the middle object of a particular class in a container. This form is rarely used.
Syntax
middle class
Placeholders
class
The class of the middle object to obtain.
Examples
end tell
220
Reference Forms
Discussion
The middle reference form generally works only when the index form also works.
AppleScript calculates the middle object by taking half the count, then rounding up. For example, the middle
word of a paragraph containing ten words is the fifth word; the middle of eleven words is the sixth.
Name
Specifies an object by name.
Syntax
Placeholders
class
The class for the specified object.
nameText
The value of the object’s name property.
Examples
The following statements identify objects by name:
document "[Link]"
Discussion
Use of the name reference form implies the existence of a name property for the specified objects.
In some applications, it is possible to have multiple objects of the same class in the same container with the
same name. For example, if there are two drives named “Hard Disk”, the following statement is ambiguous (at
least to the reader):
end tell
In such cases, it is up to the application to determine which object is specified by a name reference.
221
Reference Forms
Property
Specifies a property of an object.
Syntax
propertyLabel
Placeholders
propertyLabel
The label for the property.
Examples
The following example is an object specifier to a property of a Finder window. It lists the label for the window’s
property (zoomed) and its container (front window). zoomed is a Boolean property.
end tell
The following example is an object specifier to the UnitPrice property of a record (page 118) object. The
label of the property is UnitPrice and the container is the record object.
Discussion
Property labels are listed in class definitions in application dictionaries. Because a property’s label is unique
among the properties of an object, the label is all you need to specify the property—there is no need to specify
the class of the property.
Range
Specifies a series of objects of the same class in the same container. You can specify the objects with a pair of
indexes (such as words 12 thru 24) or with a pair of boundary objects (integers from integer 1 to
integer 3).
222
Reference Forms
Syntax
Placeholders
class
A singular class (such as window or word).
pluralClass
A plural class (such as windows or words).
boundarySpecifier1 and boundarySpecifier2
Specifiers to objects that bound the range. The range includes the boundary objects. You can use the
reserved word beginning in place of boundarySpecifier1 to indicate the position before the first object
of the container. Similarly, you can use the reserved word end in place of boundarySpecifier2 to indicate
the position after the last object in the container.
startIndex and stopIndex
The indexes of the first and last object of the range (such as 1 and 10 in words 1 thru 10).
Though integer indexes are the most common class, the start and stop indexes can be of any class. An
application determines which index classes are meaningful to it.
Value
The value of a range reference form is a list of the objects in the range. If the specified container does not
contain objects of the specified class, or if the range is out of bounds, an error is returned. For example, the
following range specifier results in an error because there are no words in the list:
Examples
The following example shows the boundary object form of a range specifier. When you compile this statement,
Script Editor converts from integer 1 to integer 2 to the form integers 1 thru 2.
223
Reference Forms
In the next example, the phrase folders 3 thru 4 is a range specifier that specifies a list of two folders in
the container startup disk:
end tell
Discussion
If you specify a range specifier as the container for a property or object, as in
the result is a list containing the specified property or object for each object of the container. The number of
items in the list is the same as the number of objects in the container.
To obtain a contiguous series of characters—instead of a list—from a text object, use the text class:
Relative
Specifies an object or an insertion point in a container by describing a position in relation to another object,
known as the base, in the same container.
Syntax
Placeholders
class
The class identifier of the specified object. If you omit this parameter, the specifier refers to an insertion
point.
224
Reference Forms
baseSpecifier
A specifier for the object.
before | [in] front of
These forms are equivalent, and refer to the object immediately preceding the base object.
after | [in] back of | behind
These forms are equivalent, and refer to the object immediately after the base.
beginning | front
These forms are equivalent, and refer to the first insertion point of the container (insertion point
1).
end | back
These forms are equivalent, and refer to the last insertion point of the container (insertion point
-1).
Although terms such as beginning and end sound like absolute positions, they are relative to the existing
contents of a container (that is, before or after the existing contents).
Examples
The two relative specifiers in the following tell block specify the same file by identifying its position relative
to another file on a disk:
end tell
The following example shows how to use various relative specifiers in a word processing document:
end tell
Discussion
The relative reference form generally works only when the index form also works.
You can specify only a single object with a relative specifier—an object that is either before or after the base
object.
225
Operators Reference
This chapter describes AppleScript operators. An operator is a symbol, word, or phrase that derives a value
from another value or pair of values. An operation is the evaluation of an expression that contains an operator.
An operand is an expression from which an operator derives a value.
AppleScript provides logical and mathematical operators, as well as operators for containment, concatenation,
and obtaining a reference to an object. Operators that operate on two values are called binary operators, while
operators that operate on a single value are known as unary operators.
The first part of this chapter contains two tables: Table 9-1 summarizes all of the operators that AppleScript
uses, and Table 9-2 (page 234) shows the order in which AppleScript evaluates operators within expressions.
The rest of the chapter shows how AppleScript evaluates representative operators in script expressions.
or Logical disjunction.
A binary logical operator that combines two Boolean values.
The result is true if either operand evaluates to true.
AppleScript checks the left-hand operand first and, if its is
true, ignores the right-hand operand. (This behavior is
called short-circuiting.)
Class of operands: boolean (page 103)
Class of result: boolean
226
Operators Reference
& Concatenation.
A binary operator that joins two values. If the left-hand
operand is a text object, the result is a text object (and
only in this case does AppleScript try to coerce the value
of the right-hand operand to match that of the left).
If the operand to the left is a record, the result is a record.
If the operand to the left belongs to any other class, the
result is a list.
For more information, see & (concatenation) (page 236).
Class of operands: any
Class of result: list (page 112), record (page 118),
text (page 124)
= Equality.
is equal A binary comparison operator that results in true if both
equals
operands have the same value. The operands can be of any
class.
[is] equal to
For more information, see equal, is not equal to (page
241).
Class of operands: boolean (page 103)
Class of result: boolean
227
Operators Reference
228
Operators Reference
229
Operators Reference
contain[s] Containment.
A binary containment operator that results in true if the
list, record, or text object to its right matches any part of
the list, record, or text object to its left.
Both operands must evaluate to values of the same class.
If they don’t, AppleScript attempts to coerce the right-hand
operand to the class of the operand to the left.
For more information, see contains, is contained
by (page 239).
230
Operators Reference
is in Containment.
is contained by A binary containment operator that results in true if the
list, record, or text object to its left matches any part of
the list, record, or text object to its right.
Both operands must evaluate to values of the same class.
If they don’t, AppleScript attempts to coerce the left-hand
operand to the class of the right-hand operand.
For more information, see contains, is contained
by (page 239).
is not in Non-containment.
is not contained by A binary containment operator that results in true if the
isn't contained by
list, record, or text object to its left does not match any
part of the list, record, or text object to its right.
Both operands must evaluate to values of the same class.
If they don’t, AppleScript attempts to coerce the left-hand
operand to the class of the right-hand operand.
For more information, see contains, is contained
by (page 239).
* Multiplication.
A binary arithmetic operator that multiplies the number to
its left and the number to its right.
Class of operands: integer (page 111), real (page 117)
Class of result: integer, real
231
Operators Reference
+ Addition.
A binary arithmetic operator that adds the number or date
to its left and the number or date to its right. Only integers
can be added to dates. AppleScript interprets such an
integer as a number of seconds.
As a unary operator, + has no effect and is removed on
compile.
Class of operands: date (page 107), integer (page 111),
real (page 117)
– Subtraction.
A binary or unary arithmetic operator.
The binary operator subtracts the number to its right from
the number or date to its left.
The unary operator makes the number to its right negative.
Only integers can be subtracted from dates. AppleScript
interprets such an integer as a number of seconds.
Class of operands: date (page 107), integer (page 111),
real (page 117)
/ Division.
÷ (Option-slash on U.S. keyboard) A binary arithmetic operator that divides the number to
its left by the number to its right.
Class of operands: integer (page 111), real (page 117)
Class of result: real
232
Operators Reference
mod Remainder.
A binary arithmetic operator that divides the number to
its left by the number to its right and returns the remainder
as its result.
Class of operands: integer (page 111), real (page 117)
Class of result: integer, real
^ Exponentiation.
A binary arithmetic operator that raises the number to its
left to the power of the number to its right.
Class of operands: integer (page 111), real (page 117)
Class of result: real
not Negation.
A unary logical operator that results in true if the operand
to its right is false, and false if the operand is true.
Class of operand: boolean (page 103)
Class of result: boolean
233
Operators Reference
When evaluating expressions, AppleScript uses operator precedence to determine which operations are
evaluated first. In the following expression, for example, AppleScript does not simply perform operations from
left to right—it performs the multiplication operation 2 * 5 first, because multiplication has higher precedence
than addition.
12 + 2 * 5 --result: 22
Table 9-2 (page 234) shows the order in which AppleScript performs operations. The column labeled
“Associativity” indicates the order in the case where there are two or more operands of the same precedence
in an expression. The word “None” in the Associativity column indicates that you cannot have multiple
consecutive occurrences of the operation in an expression. For example, the expression 3 = 3 = 3 is not
legal because the associativity for the equal operator is “none.”
To evaluate expressions with multiple unary operators of the same order, AppleScript applies the operator
closest to the operand first, then applies the next closest operator, and so on. For example, the expression not
not not true is evaluated as not (not (not true)).
You can enforce the order in which AppleScript performs operations by grouping expressions in parentheses,
which are evaluated first, starting with the innermost pair of parentheses.
234
Operators Reference
The following sections provide additional detail about how AppleScript evaluates operators in expressions:
● & (concatenation) (page 236)
● a reference to (page 237)
● Para
● contains, is contained by (page 239)
● equal, is not equal to (page 241)
● greater than, less than (page 242)
235
Operators Reference
& (concatenation)
The concatenation operator (&) concatenates text objects, joins record objects into a record, and joins other
objects into a list.
Table 9-1 (page 226) summarizes the use of use of this operator.
text
The concatenation of two text objects joins the characters from the left-hand text object to the characters
from the right-hand text object, without intervening spaces. For example, "dump" & "truck" evaluates to
the text object "dumptruck".
If the left-hand operand is a text object, but the right-hand operand is not, AppleScript attempts to coerce
the right-hand operand to a text object. For example, when AppleScript evaluates the expression "Route
" & 66 it coerces the integer 66 to the text object "66", and the result is the text object "Route 66".
However, you get a different result if you reverse the order of the operands:
In the following example, the left-hand operand is a text object and the right-hand operand is a list, so
concatenation results in a text object:
record
The concatenation of two records joins the properties of the left-hand record to the properties of the right-hand
record. If both records contain properties with the same name, the value of the property from the left-hand
record appears in the result. For example, the result of the expression
is
236
Operators Reference
Except for the cases described above for text objects and record objects, the concatenation operator (&)
joins lists. A non-list operand is considered to be a list containing that operand. The following example shows
concatenation of two integers, a list and a text string, and a list and a record, respectively:
If both the operands to be concatenated are lists, then the result is a list containing all the items in the left-hand
list, followed by all the items in the right-hand list. For example:
To join two lists and create a list of lists, rather than a single list, you can enclose each list in two sets of brackets:
{{1, 2}} & {{3, 4}} --result: {{1, 2}, {3, 4}}
For information on working efficiently with large lists, see list (page 112).
a reference to
The a reference to operator is a unary operator that returns a reference object. You can abbreviate this
operator to a ref to, or ref to, or even just ref.
For related information, see the reference (page 120) class and Object Specifiers (page 30).
Examples
The following statement creates a reference object that contains an object specifier to the Finder startup
disk:
The following shows how to obtain a reference object that refers to an item in a list:
237
Operators Reference
In the final line, AppleScript automatically resolves the object specifier contained in the reference itemRef
and obtains its value to use in the addition operation. To cause AppleScript to explicitly resolve a reference
object, you can use its contents property:
The next examples demonstrate how using a reference object can result in a different outcome than accessing
an object directly. The first example obtains a current track object from iTunes, gets the name, changes the
track, then gets the name again:
end tell
Because curTrack is a specific track object, its name doesn’t change when the current track changes. But
observe the result when using a reference to the current track:
end tell
Because trackRef is a reference object containing an object specifier, the specifier identifies the new track
when the current track changes.
238
Operators Reference
as (coercion)
The as operator converts, or coerces , a value of one class to a value of another class. Not all values are coercible
to all classes; see Coercion (Object Conversion) (page 34) for a list of allowed coercions.
The right-hand operand of as may be a single class, such as text, or a list of classes, such as {integer,
text}. When given a list, the as operator processes the list from the first type to the last, checking if the value
is an instance of that type; if one matches, the result is the original value. If none match, then it again processes
the list from the first type to the last, attempting to coerce the value to that type; the result is the result of the
first successful coercion. If none succeed, it throws an error.
Examples
This expression returns x as a number, suitable for use with a math operator. For example, if x was the text
"1.5", it would return the real value 1.5.
x as number
This expression returns x as either an integer or text, whichever succeeds first. For example, consider if x was
date "Wednesday, May 27, 2015 at 12:03:15 PM": date objects cannot be coerced to integers, but
they can be coerced to text, so the result is the date as text: "Wednesday, May 27, 2015 at 12:03:15
PM".
x as {integer, text}
The way lists of classes are processed means that the result of as can depend on the order of the classes. For
example, the result of 1.5 as {integer, text} is 2, but 1.5 as {text, integer} is "1.5". It is also
possible to have types that will never be reached. For example, in the expression x as {number, integer},
the integer coercion will never trigger, because number will always succeed first.
contains, is contained by
The contains and is contained by operators work with lists, records, and text objects.
Table 9-1 (page 226) summarizes the use of these operators and their synonyms.
239
Operators Reference
list
A list contains another list if the right-hand list is a sublist of the left-hand list. A sublist is a list whose items
appear in the same order and have the same values as any series of items in the other list. For example, the
following statement is true because 1 + 1 evaluates to 2, so that all the items in the right-hand list appear,
in the same order, in the left-hand list:
The following statement is false because the items in the right-hand list are not in the same order as the
matching items in the left-hand list:
A list is contained by another list if the left-hand list is a sublist of the right-hand list. For example, the
following expression is true:
Both contains and is contained by work if the sublist is a single value—as with the concatenation
operator (&), single values are coerced to one-item lists. For example, both of the following expressions evaluate
to true:
However, the following expressions, containing nested lists, both evaluate to false:
record
A record contains another record if all the properties in the right-hand record are included in the left-hand
record, and the values of properties in the right-hand record are equal to the values of the corresponding
properties in the left-hand record. A record is contained by another record if all the properties in the left-hand
record are included in the right-hand record, and the values of the properties in the left-hand record are equal
to the values of the corresponding properties in the right-hand record. The order in which the properties
appear does not matter. For example, the following is true:
240
Operators Reference
text
A text object contains another text object if the characters in the right-hand text object are equal to any
contiguous series of characters in the left-hand text object. For example,
is true, but
is false.
A text object is contained by another text object if the characters in the left-hand text object are equal to
any series of characters in the right-hand text object. For example, this statement is true:
Text comparisons can be affected by considering and ignoring statements, as described in the Text section
of equal, is not equal to (page 241).
Table 9-1 (page 226) summarizes the use of these operators and their synonyms.
list
Two lists are equal if they both contain the same number of items and if the value of an item in one list is
identical to the value of the item at the corresponding position in the other list:
241
Operators Reference
record
Two records are equal if they both contain the same collection of properties and if the values of properties
with the same label are equal. They are not equal if the records contain different collections of properties, or
if the values of properties with the same label are not equal. The order in which properties are listed does not
affect equality. For example, the following expression is true:
text
Two text objects are equal if they are both the same series of characters. They are not equal if they are different
series of characters. For related information, see the text (page 124) class.
Text comparisons can be affected by considering and ignoring statements, which instruct AppleScript to
selectively consider or ignore attributes of characters or types of characters. For example, unless you use an
ignoring statement, AppleScript compares text objects by considering all characters and punctuation.
AppleScript does not distinguish uppercase from lowercase letters unless you use a considering statement
to consider the case attribute. For example:
considering case
end considering
When comparing two text objects, if the test is not enclosed in a considering or ignoring statement,
then the comparison uses default values for considering and ignoring attributes (described in considering
/ ignoring (text comparison) (page 245)).
Table 9-1 (page 226) summarizes the use of these operators and their synonyms.
date
A date is greater than another date if it represents a later time. A date is less than another date if it represents
an earlier time.
242
Operators Reference
integer, real
An integer or a real number is greater than another integer or real number if it represents a larger number. It
is less than another integer or real number if it represents a smaller number.
text
To determine the ordering of two text objects, AppleScript uses the collation order set in the Language pane
of International preferences. A text object is greater than (comes after) another text object based on the
lexicographic ordering of the user’s language preference. With the preference set to English, the following two
statements both evaluate to true:
Text comparisons can be affected by considering and ignoring statements, as described in the Text section
of equal, is not equal to (page 241).
Table 9-1 (page 226) summarizes the use of these operators and their synonyms.
list
A list starts with the items in a second list if all the items in the second list are found at the beginning of
the first list. A list ends with the items in a second list if all the items in the second list are found at the end
of the first list. For example, the following three expressions are all true:
243
Operators Reference
text
A text object starts with the text in a second text object if all the characters in the second object are
found at the beginning of the first object. A text object ends with the text in a second text object if all
the characters in the second object are found at the end of the first object. For example, the following expression
is true:
A text object ends with another text object if the characters in the right-hand text object are the same as
the characters at the end of the left-hand text object. For example, the following expression is true:
Text comparisons can be affected by considering and ignoring statements, as described in the Text section
of equal, is not equal to (page 241).
244
Control Statements Reference
This chapter describes AppleScript control statements. A control statement is a statement that determines when
and how other statements are executed or how expressions are evaluated. For example, a control statement
may cause AppleScript to skip or repeat certain statements.
Simple statements can be written on one line, while compound statements can contain other statements,
including multiple clauses with nested and multi-line statements. A compound statement is known as a
statement block.
Compound statements begin with one or more reserved words, such as tell, that identify the type of control
statement. The last line of a compound statement always starts with end, and can optionally include the word
that begins the control statement (such as end tell).
Specify how AppleScript should treats attributes, such as case, in performing text comparisons.
Syntax
[ statement ]...
end considering
245
Control Statements Reference
[ statement ]...
end ignoring
Placeholders
attribute
A characteristic of the text:
case
If this attribute is ignored, uppercase letters are not distinguished from lowercase letters. See
Special Considerations below for related information. See also greater than, less than (page
242) for a description of how AppleScript sorts letters, punctuation, and other symbols.
diacriticals
If this attribute is ignored, text objects are compared as if no diacritical marks (such as ´, `, ˆ, ¨,
and ˜) are present; for example, "résumé" is equal to "resume".
hyphens
If this attribute is ignored, text objects are compared as if no hyphens are present; for example
"anti-war" is equal to "antiwar".
numeric strings
By default, this attribute is ignored, and text strings are compared according to their character
values. For example, if this attribute is considered, "1.10.1" > "1.9.4" evaluates as true;
otherwise it evaluates as false. This can be useful in comparing version strings.
punctuation
white space
If this attribute is ignored, the text objects are compared as if spaces, tab characters, and return
characters were not present; for example "Brick house" would be considered equal to
"Brickhouse".
Default Value:
Case and numeric strings are ignored; all others are considered.
246
Control Statements Reference
statement
Any AppleScript statement.
Examples
The following examples show how considering and ignoring statements for various attributes can change
the value of text comparisons.
end ignoring
considering case
end considering
ignoring diacriticals
end considering
ignoring case
end ignoring
end ignoring
Discussion
You can nest considering and ignoring statements. If the same attribute appears in both an outer and
inner statement, the attribute specified in the inner statement takes precedence. When attributes in an inner
considering or ignoring statement are different from those in outer statements, they are added to the
attributes to be considered and ignored.
247
Control Statements Reference
Special Considerations
Because text item delimiters (described in version (page 44)) respect considering and ignoring
attributes in AppleScript 2.0, delimiters are case-insensitive by default. Formerly, they were always case-sensitive.
To enforce the previous behavior, add an explicit considering case statement.
considering and ignoring are fully Unicode-aware. For example, with ignoring case, “ is equal to “ . ” ”
Also, the characters ignored by diacriticals, hyphens, punctuation, and white space are defined by Unicode
character classes:
● ignoring punctuation ignores category P*, which includes left- and right-quotation marks such as “
” « ».
● ignoring hyphens ignores category Pd, which includes em- and en-dashes.
● ignoring whitespace ignores category Z*, plus tab (\t), return (\r), and linefeed (\n), which includes
em-, en-, and non-breaking spaces.
Para
Permits a script to continue without waiting for an application to respond to commands that target it.
Syntax
considering | ignoring application responses
[ statement ]...
end [ considering | ignoring ]
Placeholders
statement
Any AppleScript statement.
Examples
The following example shows how to use an ignoring statement so that a script needn’t wait while Finder is
performing a potentially lengthy task:
end ignoring
end tell
248
Control Statements Reference
Your script may want to ignore most responses from an application, but wait for a response to a particular
statement. You can do so by nesting considering and ignoring statements:
end considering
end ignoring
end tell
Discussion
A response to an application command indicates whether the command completed successfully, and also
returns results and error messages, if there are any. When you use an ignoring application responses
block, you forego this information.
Results and error messages from AppleScript commands, scripting additions, and expressions are not affected
by the application responses attribute.
error Statements
During script execution, errors can occur in the operating system (for example, when a specified file isn’t found),
in an application (for example, when the script specifies an object that doesn’t exist), and in the script itself.
An error message is a message that is supplied by an application, AppleScript, or OS X when an error occurs
during the handling of a command. An error message can include an error number, which is an integer that
identifies the error; an error expression, which is an expression, usually a text object, that describes the error;
and other information.
A script can signal an error—which can then be handled by an error handler—with the error statement. This
allows scripts to supply their own messages for errors that occur within the script. For example, a script can
prepare to handle anticipated errors by using a try (page 263) statement. In the on error branch of a try
statement, a script may be able to recover gracefully from the error. If not, it can use an error statement to
resignal the error message it receives, modifying the message as needed to supply information specific to the
script.
249
Control Statements Reference
error
Syntax
[ partial resultresultList ] ¬
Placeholders
errorMessage
A text object describing the error. Although this parameter is optional, you should provide descriptions
for errors wherever possible. If you do not include an error description, an empty text object ("") is
passed to the error handler.
errorNumber
The error number for the error. This is an optional parameter. If you do not include a number parameter,
the value -2700 (unknown error) is passed to the error handler.
If the error you are signaling is a close match for one that already has an AppleScript error constant, you
can use that constant. If you need to create a new number for the error, avoid using one that conflicts
with error numbers defined by AppleScript, OS X, and the Apple Event Manager. In general, you should
use positive numbers from 500 to 10,000. For more information, see Error Numbers and Error
Messages (page 298).
resultList
A list of objects. Applies only to commands that return results for multiple objects. If results for some,
but not all, of the objects specified in the command are available, you can include them in the partial
result parameter. This is rarely supported by applications.
offendingObject
A reference to the object, if any, that caused the error.
expectedType
A class. If a parameter specified in the command was not of the expected class, and AppleScript was
unable to coerce it to the expected class, then you can include the expected class in the to parameter.
Examples
The following example uses a try (page 263) statement to handle a simple error, and demonstrates how you
can use an error statement to catch an error, then resignal the error exactly as it was received, causing
AppleScript to display an error dialog (and halt execution):
try
250
Control Statements Reference
on error eStr number eNum partial result rList from badObj to expectedType
error eStr number eNum partial result rList from badObj to expectedType
end try
In the next example, an error statement resignals an error, but omits any original error information and
supplies its own message to appear in the error dialog:
try
on error
end try
For more comprehensive examples, see Working with Errors (page 302).
if Statements
An if statement allows you to define statements or groups of statements that are executed only in specific
circumstances, based on the evaluation of one or more Boolean expressions.
An if statement is also called a conditional statement. Boolean expressions in if statements are also called
tests.
if (simple)
Syntax
Placeholders
boolean
A Boolean expression.
251
Control Statements Reference
statement
Any AppleScript statement.
Examples
This script displays a dialog if the value of the Boolean expression ageOfCat > 1 is true. (The variable
ageOfCat is set previously.)
if (compound)
Executes a group (or groups) of statements if a Boolean expression (or expressions) evaluates to true.
Syntax
if boolean [ then ]
[ statement ]...
[ statement ]...]...
[else
[ statement ]...]
end [ if ]
Placeholders
boolean
A Boolean expression.
statement
Any AppleScript statement.
Examples
The following example uses a compound if statement, with a final else clause, to display a statement based
on the current temperature (obtained separately):
252
Control Statements Reference
else
end if
Discussion
An if statement can contain any number of else if clauses; AppleScript looks for the first Boolean expression
contained in an if or else if clause that is true, executes the statements contained in its block (the
statements between one else if and the following else if or else clause), and then exits the if statement.
An if statement can also include a final else clause. The statements in its block are executed if no other test
in the if statement passes.
repeat Statements
You use a repeat statement to create loops or execute groups of repeated statements in scripts.
There are a number of types of repeat statement, each differing in the way it terminates the loop. Each of
the options, from repeating a loop a specific number of times, to looping over the items in a list, to looping
until a condition is met, and so on, lends itself to particular kinds of tasks.
For information on testing and debugging repeat statements, see Debugging AppleScript Scripts (page 52).
exit
Terminates a repeat loop and resumes execution with the statement that follows the repeat statement.
You can only use an exit statement inside a repeat statement. Though most commonly used with the
repeat (forever) form, you can also use an exit statement with other types of repeat statement.
Syntax
exit [ repeat ]
Examples
See the example in repeat (forever) (page 253).
repeat (forever)
253
Control Statements Reference
Important: A repeat (forever) statement will never complete unless you cause it to do so.
Syntax
repeat
[ statement ]...
end [ repeat ]
Placeholders
statement
Any AppleScript statement.
Examples
This form of the repeat statement is similar to the repeat until (page 255) form, except that instead of
putting a test in the repeat statement itself, you determine within the loop when it is time to exit. You might
use this form, for example, to wait for a lengthy or indeterminate operation to complete:
repeat
-- perform operations
if someBooleanTest then
exit repeat
end if
end repeat
In a script application that stays open, you can use an idle handler to perform periodic tasks, such as checking
for an operation to complete. See idle Handlers (page 96) for more information.
254
Control Statements Reference
Syntax
[ statement ]...
end [ repeat ]
Placeholders
integer
Specifies the number of times to repeat the statements in the body of the loop.
Instead of an integer, you can specify any value that can be coerced to an integer.
If the value is less than one, the body of the repeat statement is not executed.
statement
Any AppleScript statement.
Examples
The following handler uses the repeat (number) times form of the repeat statement to raise a passed
number to the passed power:
on raiseToTheNth(x, power)
set returnVal to x
end repeat
return returnVal
end raiseToTheNth
repeat until
Repeats a statement (or statements) until a condition is met. Tests the condition before executing any statements.
Syntax
[ statement ]...
255
Control Statements Reference
end [ repeat ]
Placeholders
boolean
A Boolean expression. If it has the value true when entering the loop, the statements in the loop are
not executed.
statement
Any AppleScript statement.
Examples
The following example uses the repeat until form of the repeat statement to allow a user to enter database
records. The handler enterDataRecord(), which is not shown, returns true if the user is done entering
records:
end repeat
repeat while
Repeats a statement (or statements) as long as a condition is met. Tests the condition before executing any
statements. Similar to the repeat until form, except that it continues while a condition is true, instead of
until it is true.
Syntax
[ statement ]...
end [ repeat ]
Placeholders
boolean
A Boolean expression. If it has the value false when entering the loop, the statements in the loop are
not executed.
statement
Any AppleScript statement.
256
Control Statements Reference
Examples
The following example uses the repeat while form of the repeat statement to allow a user to enter database
records. In this case, we’ve just reversed the logic shown in the repeat until (page 255) example. Here, the
handler enterDataRecord(), which is not shown, returns true if the user is not done entering records:
end repeat
Repeats a statement (or statements) until the value of the controlling loop variable exceeds the value of the
predefined stop value.
Syntax
[ statement ]...
end [ repeat ]
Placeholders
loopVariable
Controls the number of iterations. It can be a previously defined variable or a new variable you define in
the repeat statement.
startValue
Specifies a value that is assigned to loopVariable when the loop is entered.
You can specify an integer or any value that can be coerced to an integer.
stopValue
Specifies an value. When that value is exceeded by the value of loopVariable , iteration ends. If stopValue
is less than startValue , the body is not executed.
You can specify an integer or any value that can be coerced to an integer.
stepValue
Specifies a value that is added to loopVariable after each iteration of the loop. You can assign an integer
or a real value; a real value is rounded to an integer.
Default Value:
1
257
Control Statements Reference
statement
Any AppleScript statement.
Examples
The following handler uses the repeat with loopVariable (from startValue to stopValue) form
of the repeat statement to compute a factorial value (the factorial of a number is the product of all the positive
integers from 1 to that number):
on factorial(x)
set returnVal to 1
end repeat
return returnVal
end factorial
Discussion
You can use an existing variable as the loop variable in a repeat with loopVariable (from startValue
to stopValue) statement or define a new one in the statement. In either case, the loop variable is defined
outside the loop. You can change the value of the loop variable inside the loop body but it will get reset to
the next loop value the next time through the loop. After the loop completes, the loop variable retains its last
value.
AppleScript evaluates startValue , stopValue , and stepValue when it begins executing the loop and stores the
values internally. As a result, if you change the values in the body of the loop, it doesn’t change the execution
of the loop.
The number of iterations is equal to the number of items in the list. In the first iteration, the value of the variable
is a reference to the first item in list , in the second iteration, it is a reference to the second item in list , and so
on.
Syntax
[ statement ]...
258
Control Statements Reference
end [ repeat ]
Placeholders
loopVariable
Any previously defined variable or a new variable you define in the repeat statement (see Discussion).
list
A list or a object specifier (such as words 1 thru 5) whose value is a list.
list can also be a record; AppleScript coerces the record to a list (see Discussion).
statement
Any AppleScript statement.
Examples
The following script examines a list of words with the repeat with loopVariable (in list) form of
the repeat statement, displaying a dialog if it finds the word “hammer” in the list. Note that within the loop,
the loop variable (currentWord) is a reference to an item in a list, so in the test statement (if contents
of currentWord is equal to "hammer" then) it must be cast to text (as text).
log currentWord
end if
end repeat
The statement log currentWord logs the current list item to Script Editor’s log window. For more information,
see Debugging AppleScript Scripts (page 52).
Discussion
You can use an existing variable as the loop variable in a repeat with loopVariable (in list) statement
or define a new one in the repeat with… statement. In either case, the loop variable is defined outside the
loop. You can change the value of the loop variable inside the loop body but it will get reset to the next loop
value the next time through the loop. After the loop completes, the loop variable retains its last value.
AppleScript evaluates loopVariable in list as an object specifier that takes on the value of item 1 of list,
item 2 of list, item 3 of list, and so on until it reaches the last item in the list, as shown in the
following example:
259
Control Statements Reference
set listItem to i
end repeat
To set a variable to the value of an item in the list, rather than a reference to the item, use the contents of
property:
end repeat
--result: 4
set total to 0
end repeat
--result: 10
If the value of list is a record, AppleScript coerces the record to a list by stripping the property labels. For
example, {a:1, b:2, c:3} becomes {1, 2, 3}.
tell Statements
A tell statement specifies the default target—that is, the object to which commands are sent if they do not
include a direct parameter. Statements within a tell statement that use terminology from the targeted object
are compiled against that object’s dictionary.
The object of a tell statement is typically a reference to an application object or a script object. For example,
the following tell statement targets the Finder application:
end tell
260
Control Statements Reference
You can nest tell statements inside other tell statements, as long as you follow the syntax and rules
described in tell (compound) (page 262).
When you need to call a handler from within a tell statement, there are special terms you use to indicate
that the handler is part of the script and not a command that should be sent to the object of the tell statement.
These terms are described in The it and me Keywords (page 45) and in Calling Handlers in a tell Statement (page
92).
A tell statement that targets a local application doesn’t cause it to launch, if it is not already running. For
example, a script can examine the running property of the targeted application (page 100) object to determine
if the application is running before attempting to send it any commands. If it is not running it won’t be launched.
If a tell statement targets a local application and executes any statements that require a response from the
application, then AppleScript will launch the application if it is not already running. The application is launched
as hidden, but the script can send it an activate (page 136) command to bring it to the front, if needed.
A tell statement that targets a remote application will not cause it to launch—in fact, it will not compile or
run unless the application is already running. Nor is it possible to access the running property of an application
on a remote computer.
tell (simple)
Syntax
Placeholders
referenceToObject
Any object. Typically an object specifier or a reference object (which contains an object specifier).
statement
Any AppleScript statement.
Examples
This simple tell statement closes the front Finder window:
For more information on how to specify an application object, see the application (page 100) class.
261
Control Statements Reference
tell (compound)
Specifies a target object and one or more commands to send to it. A compound tell statement is different
from a simple tell statement in that it always includes an end statement.
Syntax
tell referenceToObject
[ statement ]...
end [ tell ]
Placeholders
referenceToObject
Any object. Typically an object specifier or a reference object (which contains an object specifier).
statement
Any AppleScript statement, including another tell statement.
Examples
The following statements show how to close a window using first a compound tell statement, then with two
variations of a simple tell statement:
end tell
end tell
if (len > 2) and (len < 15) then -- comparisons handled by AppleScript
end if
262
Control Statements Reference
end tell
This example works because in each case the terminology understood by a particular application is used within
a tell block targeting that application. However, it would not compile if you asked the Finder for word 1 of
a document, or told TextEdit to set name of the first item on a disk, because those applications do not support
those terms.
try Statements
A try statement provides the means for scripts to handle potential errors. It attempts to execute one or more
statements and, if an error occurs, executes a separate set of statements to deal with the error condition. If an
error occurs and there is no try statement in the calling chain to handle it, AppleScript displays an error and
script execution stops.
For related information, see error Statements (page 249) and AppleScript Error Handling (page 40).
try
Attempts to execute a list of AppleScript statements, calling an error handler if any of the statements results
in an error.
A try statement is a two-part compound statement that contains a series of AppleScript statements, followed
by an error handler to be invoked if any of those statements causes an error. If the statement that caused the
error is included in a try statement, then AppleScript passes control to the error handler. After the error handler
completes, control passes to the statement immediately following the end of the try statement.
Syntax
try
[ statement ]...
[ statement ]... ]
263
Control Statements Reference
Placeholders
statement
Any AppleScript statement.
errorMessage
A text object, that describes the error.
errorNumber
The error number, an integer. For possible values, see Error Numbers and Error Messages (page 298).
offendingObject
A reference to the object, if any, that caused the error.
resultList
A list that provides partial results for objects that were handled before the error occurred. The list can
contain values of any class. This parameter applies only to commands that return results for multiple
objects. This is rarely supported by applications.
expectedType
The expected class. If the error was caused by a coercion failure, the value of this variable is the class of
the coercion that failed. (The second example below shows how this works in a case where AppleScript
is unable to coerce a text object into an integer.)
variable
Either a global variable or a local variable that can be used in the handler. A variable can contain any
class of value. The scope of a local variable is the handler. The scope of a global variable extends to any
other part of the script, including other handlers and script objects. For related information about local
and global variables, see version (page 44).
Examples
The following example shows how you can use a try statement to handle the “Cancel” button for a display
alert (page 156) command. Canceling returns an error number of -128, but is not really an error. This test
handler just displays a dialog to indicate when the user cancels or when some other error occurs.
try
-- User cancelled.
else
264
Control Statements Reference
display dialog "Some other error: " & errNum & return & errText
end if
end try
You can also use a simplified version of the try statement that checks for just a single error number. In the
following example, only error -128 is handled. Any other error number is ignored by this try statement, but
is automatically passed up the calling chain, where it may be handled by other try statements.
try
end try
The following example demonstrates the use of the to keyword to capture additional information about an
error that occurs during a coercion failure:
try
end repeat
end try
This repeat statement fails because the text object "Toronto" cannot be coerced to an integer (page
111). The error handler simply writes the values of obj (the offending value, "Toronto") and newClass (the
class of the coercion that failed, integer) to Script Editor’s Event Log History window (and to the script
window’s Event Log pane). The result is “(*Toronto, integer*)”, indicating the error occurred while trying to
coerce “Toronto” to an integer.
265
Control Statements Reference
use Statements
A use statement declares a required resource for a script—an application, script library, framework, or version
of AppleScript itself—and can optionally import terminology from the resource for use elsewhere in the script.
The effects and syntax of use vary slightly depending on the used resource; the different cases are described
below.
Note: use statements are supported in OS X Mavericks v10.9 (AppleScript 2.3) and later.
The basic function of use is to require that a resource be present before the script begins executing. If the
requirement cannot be met, the script will fail to run. A use statement can also specify a minimum version for
the required resource, such as a minimum compatible version of an application. In this example, AppleScript
will ensure that Safari version 7.0 or later is available:
use statements can also import terminology from the used resource, making the terms available throughout
the script without requiring the use of tell or using terms from. AppleScript tracks where terms were
imported from, and sends events that use those terms to that target. Ordinarily, commands are sent to the
current target (it) as described in Target (page 38), but imported terminology overrides this. If…
● the event identifier is imported
● the direct parameter is an imported class or enumeration identifier
● the direct parameter is an object specifier ending with an imported term
…then the command is sent to the import source instead. This happens even if the command is inside a tell
block for a different target. For example, this script uses a command from Safari:
Importing happens by default, but can be suppressed using the without importing parameter, if applicable.
You can use this to add requirements to existing scripts without changing anything else about the script:
Because Safari's terms are not imported, the script will still need to use tell to send it events.
266
Control Statements Reference
use (AppleScript)
Declares a required minimum version of AppleScript, and that the script expects a newer behavior for how
scripting additions are handled, described in use (scripting additions) (page 267).
Syntax
use AppleScript [ version versionText ]
Placeholders
versionText
The required minimum version of AppleScript, as a version string such as "2.3.2". If omitted, its default
value is 2.3, the version in which use was introduced. This value is always text, not a number, and is
compared as if considering numeric strings is in effect. For example, "2.10" is greater than
"2.3", because 10 is greater than 3.
Examples
In its simplest form, use can be used to declare that the script uses AppleScript:
use AppleScript
This also implicitly means that the script uses AppleScript version 2.3 or later, when use was first introduced,
and that the script expects a newer behavior for how scripting additions are handled, described in use (scripting
additions) (page 267).
A use command can also explicitly specify a minimum required version of AppleScript:
Syntax
use scripting additions ¬
[ with importing | without importing | importing boolean ]
Placeholders
boolean
A boolean value,true or false. AppleScript will recompile this to with importing or without
importing. The default is with importing.
267
Control Statements Reference
Examples
Use use scripting additions to explictly declare that the script uses scripting addition commands:
Discussion
Scripting addition commands are handled differently if a script has use commands. If a script has one or more
use commands of any kind, scripting addition commands are not available by default. You must explicitly
indicate that you wish to use scripting additions, either with a use or using terms from command.
If a script uses use scripting additions, AppleScript may optimize scripting addition commands, sending
them to the current application instead of the current target (it) when it does not change the meaning to do
so. For example, random number (page 187) does not need to be sent to another application to work correctly,
and will always be sent to the current application when imported with use. Without a use scripting
additions command, AppleScript must use a less efficient dispatching scheme, so explicitly declaring them
is recommended.
Declares a required application or script library, and may import its terms for use later in the script.
Syntax
use [ identifier : ] ( script | application ) specifier ¬
[ version versionText ] ¬
Placeholders
versionText
The required minimum version of the resource as a version number, such as "2.3.2". This value is always
text, not a number, and is compared as if considering numeric strings is in effect. For example,
"2.10" is greater than "2.3", because 10 is greater than 3.
268
Control Statements Reference
identifier
An optional identifier for the resource.
specifier
Specifier data for the resource. This is typically a name, as in use application "Finder" or use
script "My Library", but may be any valid specifier form, such as by ID, as in use application
id "[Link]".
boolean
A boolean value,true or false. AppleScript will recompile this to with importing or without
importing. The default is with importing.
Examples
A use command may refer to an application:
If an optional identifier is given, it defines a property whose value is the required resource. This can make it
more convenient to refer to the resource, as in this example: the get statement uses the identifier Safari
instead of the full specifier application "Safari".
By using use with multiple applications, you can combine terms from different sources in ways impossible
using tell, because tell only makes one terminology source available at a time. For example, the following
script, in one statement, uses Mail and Safari to search the web for the sender of the currently selected mail
message. The get event is sent to Mail because it defines message viewer, while the search the web
event is sent to Safari.
269
Control Statements Reference
use (framework)
Syntax
use framework specifier
Placeholders
specifier
Specifier data for the resource. This may be a base name ("AppKit"), a full name ("[Link]"),
or a POSIX path ("/System/Library/Frameworks/[Link]").
Examples
Most scripts that use the AppleScript/Objective-C bridge should have at least one of these two use statements:
Discussion
When you declare a required framework, AppleScript ensures the framework is loaded before running your
script. To ensure that your AppleScript/Objective-C script libraries work correctly in any application, declare
all needed frameworks explicitly; otherwise, there is no guarantee that a given framework will be available,
and your script may fail.
The version parameter is not supported for frameworks; to check whether or not a framework supports a
certain feature, use NSClassFromString or -respondsToSelector:.
Note: OS X Yosemite v10.10 and later allow using Objective-C frameworks from any script. OS X
Mavericks v10.9 only allows using Objective-C frameworks from a script library.
270
Control Statements Reference
A using terms from statement can be useful in writing application event handler scripts, such as Mail rules.
Another use for this type of statement is with a script that targets an application on a remote computer that
may not be available when you compile the script (or the application may not be running). Or, you might be
developing locally and only want to test with the remote application at a later time. In either case, you can
use a using terms from statement to specify a local application (presumably with a terminology that
matches the one on the remote computer) to compile against.
Even if a statement contained within a using terms from statement compiles, the script may fail when run
because the target application’s terminology may differ from that used in compiling.
You can nest using terms from statements. When you do so, each script statement is compiled against the
terminology of the application named in the innermost enclosing using terms from statement.
Instructs AppleScript to use the terminology from the specified source in compiling the enclosed statements.
Syntax
using terms from ( application | script | scripting additions)
[ statement ]...
end [ using terms from ]
Placeholders
application
A specifier for an application object.
script
A specifier for a script library.
statement
Any AppleScript statement.
Examples
The following example shows how to use a using terms from statement in writing a Mail rule action script.
These scripts take the following form:
end tell
271
Control Statements Reference
To use the script, you open Preferences for the Mail application, create or edit a rule, and assign the script as
the action for the rule.
For an example that works with an application on a remote machine, see Targeting Remote Applications (page
51).
As discussed in use Statements (page 266), a script with any use statements does not make scripting addition
terms visible by default. You can enable scripting addition terms for specific parts of a script with using terms
from as in this example:
use AppleScript
-- scripting addition commands such as "display dialog" will not compile here...
using terms from scripting additions -- ...but will compile within this block.
Discussion
using terms from does not import terms as use does, and is subject to the same limits on terminology use
as tell. using terms from scripting additions does not enable optimization of scripting addition
commands as use scripting additions does.
with timeout
Specifies how long AppleScript waits for a response to a command that is sent to another application.
Syntax
[ statement ]...
272
Control Statements Reference
end [ timeout ]
Placeholders
integerExpression
The amount of time, in seconds, AppleScript should wait before timing out (and interrupting the
command).
statement
Any AppleScript statement.
Examples
The following script tells TextEdit to close its first document; if the document has been modified, it asks the
user if the document should be saved. It includes the statement with timeout of 20 seconds, so that if
the user doesn’t complete the close operation within 20 seconds, the operation times out.
end timeout
end tell
Discussion
When a command fails to complete in the allotted time (whether the default of two minutes, or a time set by
a with timeout statement), AppleScript stops running the script and returns the error "event timed out".
AppleScript does not cancel the operation—it merely stops execution of the script. If you want the script to
continue, you can wrap the statements in a try (page 263) statement. However, whether your script can send
a command to cancel an offending lengthy operation after a timeout is dependent on the application that is
performing the command.
A with timeout statement applies only to commands sent to application objects, not to commands sent to
the application that is running the script.
In some situations, you may want to use an ignoring application responses statement (instead of a
with timeout statement) so that your script needn’t wait for application commands to complete. For more
information, see considering and ignoring Statements (page 245).
273
Control Statements Reference
with transaction
Associates a single transaction ID with any events sent to a target application as a result of executing commands
in the body of the statement.
Syntax
[ statement ]...
end [ transaction ]
Placeholders
session
An object that identifies a specific session.
statement
Any AppleScript statement.
Examples
This example uses a with transaction statement to ensure that a record can be modified by one user
without being modified by another user at the same time. (In the following examples, “Small DB” and “Super
DB” are representative database applications.)
with transaction
end transaction
end tell
274
Control Statements Reference
The set statements obtain the current values of the Name and Address fields and invite the user to change
them. Enclosing these set statements in a single with transaction statement informs the application that
other users should not be allowed to access the same record at the same time.
A with transaction statement works only with applications that explicitly support it. Some applications
only support with transaction statements (like the one in the previous example) that do not take a session
object as a parameter. Other applications support both with transaction statements that have no parameter
and with transaction statements that take a session parameter.
The following example demonstrates how to specify a session for a with transaction statement:
set mySession to make session with data {user: "Bob", password: "Secret"}
with transaction mySession
...
end transaction
end tell
275
Handler Reference
This chapter provides reference for handlers, which are defined and introduced in About Handlers (page 83).
It describes the types of parameters you can use with handlers and how you invoke them. It also describes the
continue and return statements, which you use to control the flow of execution in handlers.
continue
A continue statement causes AppleScript to invoke the handler with the same name in the parent of the
current handler. If there is no such handler in the parent, AppleScript looks up the parent chain, ending with
the current application.
A continue statement is like a handler call, in that after execution completes in the new location, it resumes
with the statement after the continue statement.
Syntax
continue handlerName [ parameterList ]
Placeholders
handlerName
A required identifier that specifies the name of the current handler (which is also the name of the handler
in which to continue execution).
parameterList
The list of parameters to be passed to handlerName .
The list must follow the same format as the parameter definitions in the handler definition for the
command. For handlers with labeled parameters, this means that the parameter labels must match those
in the handler definition. For handlers with positional parameters, the parameters must appear in the
correct order.
You can list the parameter variables that were specified in the original command (and thus the original
values) or you can list values that may differ from those of the original variables.
Examples
You can write a handler that overrides an AppleScript command but uses a continue statement to pass
control on to the AppleScript command if desired:
on beep numTimes
276
Handler Reference
end beep
beep 3 --result: local beep handler invoked; shows dialog before beeping
When AppleScript encounters the statement beep 3, it invokes the local beep handler, which displays a dialog.
If the user clicks Yes, the handler uses a continue statement to pass the beep command to the script’s parent
(AppleScript), which handles the command by beeping. If the user clicks No, it does not continue the beep
command, and no sound is heard.
The final statement, tell my parent to beep 3, shows how to directly invoke the AppleScript beep
command, rather than the local handler.
For an example that uses a continue statement to exit a script handler and return control to the application’s
default quit handler, see quit Handlers (page 96).
For additional examples, see Using the continue Statement in Script Objects (page 79).
return
A return statement exits a handler and optionally returns a specified value. Execution continues at the place
in the script where the handler was called.
Syntax
return [ expression ]
Placeholders
expression
Represents the value to return.
Examples
The following statement, inserted in the body of a handler, returns the integer 2:
277
Handler Reference
If you include a return statement without an expression, AppleScript exits the handler immediately and no
value is returned:
See other sections throughout Handler Reference (page 276) for more examples of scripts that use the return
statement.
Discussion
If a handler does not include a return statement, AppleScript returns the value returned by the last statement.
If the last statement doesn’t return a value, AppleScript returns nothing.
When AppleScript has finished executing a handler (that is, when it executes a return statement or the last
statement in the handler), it passes control to the place in the script immediately after the place where the
handler was called. If a handler call is part of an expression, AppleScript uses the value returned by the handler
to evaluate the expression.
It is often considered good programming practice to have just one return statement and locate it at the end
of a handler. Doing so can provide the following benefits:
● The script is easier to understand.
● The script is easier to debug.
● You can place cleanup code in one place and make sure it is executed.
In some cases, however, it may make more sense to use multiple return statements. For example, the
minimumValue handler in Handler Syntax (Positional Parameters) (page 282) is a simple script that uses two
return statements.
Labeled parameters are identified by their labels and can be listed in any order.
Syntax
( on | to ) handlerName ¬
[ [ of | in ] directParamName ] ¬
278
Handler Reference
[ statement ]...
end [ handlerName ]
Placeholders
handlerName
An identifier that names the handler.
directParamName
An identifier for the direct parameter variable. If it is included, directParamName must be listed immediately
after the command name. The word of or in before directParamName is required in user-defined
handlers, but is optional in terminology-defined handlers (for example, those defined by applications).
If a user-defined handler includes a direct parameter, the handler must also include at least one variable
parameter.
ASLabel
An AppleScript-defined label. The available labels are: about, above, against, apart from, around,
aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto,
out of, over, since, thru (or through), under. These are the only labels that can be used without
the special label given. Each label must be unique among the labels for the handler (that is, you cannot
use the same label for more than one parameter).
userLabel
An identifier for a user-defined label, associated with a user-defined parameter. Each label must be unique.
The first userLabel -userParamName pair must follow the word given; any additional pairs are separated
by commas.
userParamName
An identifier for a parameter variable.
statement
Any AppleScript statement. These statements can include definitions of script objects, each of which,
like any script object, can contain handlers and other script objects. However, you cannot declare
another handler within a handler, except within a script object.
Handlers often contain a return (page 277) statement.
Examples
For examples and related conceptual information, see Handlers with Labeled Parameters (page 85).
279
Handler Reference
Discussion
A handler written to respond to an application command (like those in Handlers in Script Applications (page
92)) need not include all of the possible parameters defined for that command. For example, an application
might define a command with up to five possible parameters, but you could define a handler for that command
with only two of the parameters.
If a script calls a handler with more parameters than are specified in the handler definition, the extra parameters
are ignored.
Syntax
handlerName ¬
[ [ of | in ] directParam ] ¬
[ ( and | , ) labelForTrueParam ] ] ¬
[ ( and | , ) labelForFalseParam ] ] ¬
Placeholders
handlerName
An identifier that names the handler.
directParam
Any valid expression. The expression for the direct parameter must be listed first if it is included at all.
ASLabel
One of the following AppleScript-defined labels used in the definition of the handler: about, above,
against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from,
instead of, into, on, onto, out of, over, since, thru (or through), under.
280
Handler Reference
paramValue
The value of a parameter, which can be any valid expression.
labelForTrueParam
The label for a Boolean parameter whose value is true. You use this form in with clauses. Because the
value true is implied by the word with, you provide only the label, not the value. For an example, see
the findNumbers handler in Handlers with Labeled Parameters (page 85).
labelForFalseParam
The label for a Boolean parameter whose value is false. You use this form in without clauses. Because
the value false is implied by the word without, you provide only the label, not the value.
paramLabel
Any parameter label used in the definition of the handler that is not among the labels for ASLabel . You
must use the special label given to specify these parameters. For an example, see the findNumbers
handler below.
Examples
For examples, see Handlers with Labeled Parameters (page 85).
Discussion
When you call a handler with labeled parameters, you supply the following:
1. The handler name.
2. A value for the direct parameter, if the handler has one. It must directly follow the handler name.
3. One label-value pair for each AppleScript-defined label and parameter defined for the handler.
4. One label-value pair for each user-defined label and parameter defined for the handler that is not a boolean
value.
The first pair is preceded by the word given; a comma precedes each additional pair. The order of the
pairs does not have to match the order in the handler definition.
5. For each user-defined label and parameter defined for the handler that is a boolean value, you can either:
a. Supply the label, followed by a boolean expression (as with non-boolean parameters); for example:
given rounding:true
b. Use a combination of with and without clauses, as shown in the following examples:
281
Handler Reference
Note: AppleScript automatically converts between some forms when you compile. For
example, given rounding:true is converted to with rounding, and with rounding,
smoothing is converted to with rounding and smoothing.
Important: The parentheses that surround the parameter list in the following definition are part of the
syntax.
Syntax
[ statement ]...
end [ handlerName ]
Placeholders
handlerName
An identifier that names the handler.
userParamName
An identifier for a user-defined parameter variable.
statement
Any AppleScript statement, including global or local variable declarations. For information about the
scope of local and global variables, see Scope of Variables and Properties (page 60).
Examples
For examples and related conceptual information, see Handlers with Positional Parameters (page 86).
282
Handler Reference
Syntax
handlerName ( [ paramValue [, paramValue ]...] )
Placeholders
handlerName
An identifier that names the handler.
paramValue
The value of a parameter, which can be any valid expression. If there are two or more parameters, they
must be listed in the same order in which they were specified in the handler definition.
Examples
For examples, see Handlers with Positional Parameters (page 86)
Discussion
When you call a handler with positional parameters, you supply the following:
1. The handler name.
2. An opening and closing parenthesis.
3. If the handler has any parameters, then you also list, within the parentheses, the following:
One value for each parameter defined for the handler. The value can be any valid expression.
Syntax
on | tohandlerNamePart :userParamName [namePart :userParamName ]... )
[ statement ]...
end [ handlerName ]
Placeholders
handlerNamePart , namePart
An identifier that, combined with the other parts, forms the handler name.
userParamName
An identifier for a user-defined parameter variable.
statement
Any AppleScript statement, including global or local variable declarations. For information about the
scope of local and global variables, see Scope of Variables and Properties (page 60).
283
Handler Reference
Examples
For examples and related conceptual information, see Handlers with Interleaved Parameters (page 88).
Syntax
( tell scriptObject to | scriptObject 's | my ) handlerNamePart :paramValue [ namePart :paramValue ]...]
Placeholders
scriptObject
A script object to direct the handler call to, which can be any valid expression.
handlerNamePart , namePart
An identifier that names the handler.
paramValue
The value of a parameter, which can be any valid expression. If there are two or more parameters, they
must be listed in the same order in which they were specified in the handler definition.
Examples
For examples, see Handlers with Positional Parameters (page 86)
Discussion
When you call a handler with positional parameters, you supply the following:
1. A script object to direct the handler call to, either using tell script to, script 's, or my, equivalent to tell
me to.
284
Folder Actions Reference
Folder Actions is a feature of OS X that lets you associate AppleScript scripts with folders. A Folder Action script
is executed when the folder to which it is attached has items added or removed, or when its window is opened,
closed, moved, or resized. The script provides a handler that matches the appropriate format for the action,
as described in this chapter.
Folder Actions make it easy to create hot folders that respond to external actions to trigger a workflow. For
example, you can use a Folder Action script to initiate automated processing of any photo dropped in a targeted
folder. A well written Folder Action script leaves the hot folder empty. This avoids repeated application of the
action to the same files, and allows Folder Actions to perform more efficiently.
You can Control-click a folder to access some Folder Action features with the contextual menu in the Finder.
Or you can use the Folder Actions Setup application, located in /System/Library/CoreServices. This
application lets you perform tasks such as the following:
● Enable or disable Folder Actions.
● View the folders that currently have associated scripts
● View and edit the script associated with a folder.
● Add folders to or remove folders from the list of folders.
● Associate one or more scripts with a folder.
● Enable or disable all scripts associated with a folder.
● Enable or disable individual scripts associated with a folder.
● Remove scripts associated with a folder.
Folder Actions Setup looks for scripts located in /Library/Scripts/Folder Action Scripts and
~/Library/Scripts/Folder Action Scripts. You can use the sample scripts located in
/Library/Scripts/Folder Action Scripts or any scripts you have added to these locations, or you
can navigate to other scripts.
A Folder Action script provides a handler (see Handler Reference (page 276)) that is invoked when the specified
action takes place. When working with Folder Action handlers, keep in mind that:
● You do not invoke Folder Actions directly. Instead, when a triggering action takes place on a folder, the
associated handler is invoked automatically.
285
Folder Actions Reference
Here’s how you can use a Folder Action script to perform a specific action whenever an image file is dropped
on a specific image folder:
1. Create a script with Script Editor or another script application.
2. In that script, write a handler that conforms to the syntax documented here for the “adding folder
items to” (page 286) folder action. Your handler can use the aliases that are passed to it to access the
image files dropped on the folder.
3. Save the script as a compiled script or script bundle.
4. Put a copy of the script in /Library/Scripts/Folder Action Scripts or
~/Library/Scripts/Folder Action Scripts.
Syntax
on adding folder items to alias after receiving listOfAlias
[ statement ]...
end [ adding folder items to ]
Placeholders
alias
An alias (page 99) that identifies the folder that received the items.
listOfAlias
List of aliases that identify the items added to the folder.
statement
Any AppleScript statement.
Examples
The following Folder Action handler is triggered when items are added to the folder to which it is attached. It
makes an archived copy, in ZIP format, of the individual items added to the attached folder. Archived files are
placed in a folder named Done within the attached folder.
286
Folder Actions Reference
end if
end tell
set the item_path to the quoted form of the POSIX path of this_item
end if
end repeat
Syntax
on closing folder window for alias
[ statement ]...
end [ closing folder window for ]
Placeholders
alias
An alias (page 99) that identifies the folder that was closed.
statement
Any AppleScript statement.
287
Folder Actions Reference
Examples
The following Folder Action handler is triggered when the folder to which it is attached is closed. It closes any
open windows of folders within the targeted folder.
try
end try
end repeat
end tell
Syntax
on moving folder window for alias from bounding rectangle
[ statement ]...
end [ moving folder window for ]
Placeholders
alias
An alias (page 99) that identifies the folder that was moved or resized.
You can use this alias to obtain the folder window’s new coordinates from the Finder.
bounding rectangle
The previous coordinates of the window of the folder that was moved or resized. The coordinates are
provided as a list of four numbers, {left, top, right, bottom}; for example, {10, 50, 500, 300} for a window
whose origin is near the top left of the screen (but below the menu bar, if present).
statement
Any AppleScript statement.
Examples
288
Folder Actions Reference
to the original_coordinates
end tell
display dialog "Window \"" & this_name & "\" has been returned to its original
size and position." buttons {"OK"} default button 1
Special Considerations
Warning: In OS X v10.5, and possibly in previous OS versions, Folder Actions does not activate attached
moving folder window for scripts when the folder is moved.
opening folder
A script handler that is invoked when its associated folder is opened in a window.
Syntax
on opening folderalias
[ statement ]...
end [ opening folder ]
Placeholders
alias
An alias (page 99) that identifies the folder that was opened.
statement
Any AppleScript statement.
Examples
The following Folder Action handler is triggered when the folder it is attached to is opened. It displays any
text from the Spotlight Comments field of the targeted folder. (Prior to OS X v10.4, this script displays text from
the Comments field of the specified folder.)
289
Folder Actions Reference
activate
end if
end tell
Special Considerations
Spotlight was introduced in OS X v10.4. In prior versions of the Mac OS, the example script shown above works
with the Comments field of the specified folder, rather than the Spotlight Comments field.
Syntax
on removing folder items from alias after losinglistOfAliasOrText
[ statement ]...
end [ removing folder items from ]
Placeholders
alias
An alias (page 99) that identifies the folder from which the items were removed.
listOfAliasOrText
List of aliases that identify the items lost (removed) from the folder. For permanently deleted items, only
the names are provided (as text strings).
statement
Any AppleScript statement.
290
Folder Actions Reference
Examples
The following Folder Action handler is triggered when items are removed from the folder to which it is attached.
It displays an alert containing the number of items removed.
end tell
display dialog (item_count as text) & " items have been removed " & "from
folder \"" & this_name & "\"." buttons {"OK"} default button 1
291
AppleScript Keywords
This appendix lists AppleScript keywords (or reserved words ), provides a brief description for each, and points
to related information, where available. (See also Keywords (page 17) in AppleScript Lexical Conventions (page
16).)
The keywords in Table A-1 (page 292) are part of the AppleScript language. You should not attempt to reuse
them in your scripts for variable names or other purposes. Developers should not re-define keywords in the
terminology for their scriptable applications. You can view many additional scripting terms defined by Apple,
but not part of the AppleScript language, in AppleScript Terminology and Apple Event Codes.
about handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
above handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
after used to describe position in the Relative (page 224) reference form; used as part
of operator (comes after, does not come after) with classes such as
date (page 107), integer (page 111), and text (page 124)
against handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
apart from handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
around handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
aside from handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
back used with Index (page 218) and Relative (page 224) reference forms; in back
of is synonymous with after and behind
292
AppleScript Keywords
before used to describe position in the Relative (page 224) reference form; used as an
operator (comes before, does not come before) with classes such as
date (page 107), integer (page 111), and text (page 124); synonymous with in
front of
below handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
beneath handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
beside handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
between handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
does used with operators such as does not equal, does not come before, and
does not contain—see Table 9-1 (page 226)
equal, equals binary comparison operator—see equal, is not equal to (page 241)
293
AppleScript Keywords
error error (page 250) control statement; also used withtry (page 263) statement
every specifies every object in a container—see Every (page 213) reference form
for handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
front in front of is used to describe position in the Relative (page 224) reference
form; synonymous with before
given a special handler parameter label—see Handler Syntax (Labeled Parameters) (page
278)
global specifies the scope for a variable (see also local)—see Global Variables (page
56)
in used in construction object specifiers—see Containers (page 31); also used with
the Relative (page 224) reference form—for example in front of and in back
of
instead of handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
into put into is a deprecated synonym for the copy (page 153) command; also used
as handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
it refers to the current target (of it)—see The it and me Keywords (page 45)
294
AppleScript Keywords
local specifies the scope for a variable (see also global)—see Local Variables (page
55)
me refers to the current script (of me)—see The it and me Keywords (page 45)
onto handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
out of handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
over handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
prop, property prop is an abbreviation for property—see The it and me Keywords (page 45)
put put into is a deprecated synonym for the copy (page 153) command
returning deprecated
script used to declare a script object; also the class of a script object—see the
script (page 122) class and Script Objects (page 68)
295
AppleScript Keywords
since handler parameter label—see Handler Syntax (Labeled Parameters) (page 278)
sixth specifies an index position in a container—see Index (page 218) reference form
the syntactic no-op, used to make script statements look more like natural language
through, thru used in specifying a range of objects in a container—see Range (page 222)
reference form
timeout used with with timeout control statement—see with timeout (page 272)
times used with repeat control statement—see repeat (number) times (page 254)
to used in many places, including copy (page 153) and set (page 197) commands;
in the Range (page 222) reference form; by operators such as is equal to and
a reference to; with the control statement repeat with loopVariable
(from startValue to stopValue) (page 257); with the partial result parameter
in try Statements (page 263)
transaction used with with transaction control statement—see with transaction (page
274)
until used with repeat control statement—see repeat until (page 255)
where used with the Filter (page 214) reference form to specify a Boolean test expression
(synonymous with whose)
296
AppleScript Keywords
while used with repeat control statement—see repeat while (page 256)
whose used with the Filter (page 214) reference form to specify a Boolean test expression
(synonymous with where)
with used in commands to specify various kinds of parameters, including true for
some Boolean for parameters—see, for example, the with prompt and
multiple selections allowed parameters to the choose from list (page
147) command; also used with application make commands to specify properties
(with properties)
without used in commands to specify false for a Boolean for a parameter—see, for
example, the multiple selections allowed parameter to the choose from
list (page 147) command
297
Error Numbers and Error Messages
This appendix describes error numbers and error messages provided by AppleScript, as well as certain Mac OS
error numbers that may be of interest to scripters.
AppleScript Errors
An AppleScript error is an error that occurs when AppleScript processes script statements. Nearly all of these
are of interest to users. For errors returned by an application, see the documentation for that application.
298
Error Numbers and Error Messages
Operating System Errors
0 No error.
299
Error Numbers and Error Messages
Operating System Errors
300
Error Numbers and Error Messages
Operating System Errors
301
Working with Errors
This appendix provides a detailed example of handling errors with try Statements (page 263) and error
Statements (page 249). It shows how to use a try statement to check for bad data and other errors, and an
error statement to pass on any error that can’t be handled. It also shows how to check for just a particular
error number that you are interested in.
try
set integerSum to 0
-- Before doing sum, check that all items in list are integers.
end if
end repeat
302
Working with Errors
Catching Errors in a Handler
else
end if
end try
end SumIntegerList
The SumIntegerList handler handles various error conditions. For example, the following call completes
without error:
The following call passes bad data—the list contains an item that isn’t an integer:
The SumIntegerList routine checks the list and signals an error 750 because the list contains at least one
non-integer item. The routine’s error handler recognizes error number 750 and puts up a dialog to describe
the problem. The SumIntegerList routine returns 0. The script checks the return value and, if it is equal to
0, does something to handle the error (not shown).
Suppose some unknown error occurs while SumIntegerList is processing the integer list in the previous
call. When the unknown error occurs, the SumIntegerList error handler calls the error command to resignal
the error. Since the caller doesn’t handle it, AppleScript displays an error dialog and execution halts. The
SumIntegerList routine does not return a value.
303
Working with Errors
Simplified Error Checking
Finally, suppose the caller has its own error handler, so that if the handler passes on an error, the caller can
handle it. Assume again that an unknown error occurs while SumIntegerList is processing the integer list.
try
display dialog "An unknown error occurred: " & errorNumber as text
end try
In this case, when the unknown error occurs, the SumIntegerList error handler calls the error command
to resignal the error. Because the caller has an error handler, it is able to handle the error by displaying a dialog
that includes the error number. Execution can continue if it is meaningful to do so.
try
else
end if
end try
This script tries to open a file with write permission, but if the file is already opened, it just displays a dialog.
However, you can instead implement this more concisely as:
try
304
Working with Errors
Simplified Error Checking
end try
In this version, there is no need to list the message, from, to, or partial result parameters, in order to
pass them along. If the error is not -49 (file <name> is already open), this error handler will not catch the error,
and AppleScript will pass the error to the next handler in an outer scope.
One drawback to this approach is that you must use a literal constant for the error number in the on error
parameter list. You can't use global variable or property names because the number must be known when the
script is compiled.
305
Double Angle Brackets
When you type English language script statements in a Script Editor script window, AppleScript is able to
compile the script because the English terms are described either in the terminology built into the AppleScript
language or in the dictionary of an available scriptable application or scripting addition. When AppleScript
compiles your script, it converts it into an internal executable format, then reformats the text to conform to
settings in Script Editor’s Formatting preferences.
When you open, compile, edit, or run scripts with Script Editor, you may occasionally see terms enclosed in
double angle brackets, or chevrons («»). For example, you might see the term «event sysodlog» as part of
a script—this is the event code representation for a display dialog (page 158) command. The event code
representation is also known as raw format.
For compatibility with Asian national encodings, “ and” “ are ” allowed as synonyms for “«” and “»” ( (Option- \
and Option-Shift- \, respectively, on a U.S. keyboard), since the latter do not exist in some Asian encodings.
The following sections provide more information about when chevrons appear in scripts.
For example, if a script is compiled on one machine and later opened on another, the dictionary may not be
available, or may be from an older version of the application or scripting addition that does not support the
term.
This can also happen if the file [Link] is not present in /System/ScriptingAdditions.
Then, scripting addition commands such as display dialog will not be present and will be replaced with
chevron notation («event sysodlog») when you compile or run the script.
306
Double Angle Brackets
When AppleScript Displays Data in Raw Format
script Joe
property theCount : 0
end script
scriptObjectJoe
Similarly, if Script Editor can’t display a variable’s data directly in its native format, it uses double angle brackets
to enclose both the word data and a sequence of numerical values that represent the data. Although this may
not visually resemble the original data, the data’s original format is preserved.
This may occur because an application command returns a value that does not belong to any of the normal
AppleScript classes. You can store such data in variables and send them as parameters to other commands,
but Script Editor cannot display the data in its native format.
You can also use AppleScript to display the underlying codes for a script, using the following steps:
1. Create a script using standard terms compiled against an available application or scripting addition.
2. Save the script as text and quit Script Editor.
3. Remove the application or scripting addition from the computer.
4. Open the script again and compile it.
5. When AppleScript asks you to locate the application or scripting addition, cancel the dialog.
Script Editor can compile the script, but displays chevron format for any terms that rely on a missing dictionary.
307
Double Angle Brackets
Sending Raw Apple Events From a Script
You can use raw syntax to enter and execute events (even complex events with numerous parameters) when
there is no dictionary to support them. However, providing detailed documentation for how to do so is beyond
the scope of this guide.
308
Libraries using Load Script
OS X Mavericks v10.9 (AppleScript 2.3) introduces built-in support for script libraries, which are scripts containing
handlers that may be shared among many scripts. Scripts that must run on older versions of the OS can share
handlers between scripts using load script, as described here.
Note: The load script command loads the compiled script as a script object; for more
information, see Script Objects (page 68).
For example, the following script contains two handlers: areaOfCircle and factorial:
else
end if
end areaOfCircle
on factorial(x)
309
Libraries using Load Script
Saving and Loading Libraries of Handlers
set returnVal to 1
if x > 1 then
end repeat
end if
return returnVal
end factorial
In Script Editor, save the script as a compiled Script (which has extension scpt) or Script Bundle (extension
scptd) and name it “NumberLib”.
After saving the script as a compiled script, other scripts can use the load script command to load it. For
example, the following script loads the compiled script [Link], storing the resulting script object
in the variable numberLib. It then makes handler calls within a tell statement that targets the script object.
The compiled script must exist in the specified location for this script to work.
tell numberLibrary
end tell
310
Unsupported Terms
This appendix lists scripting terms that are not supported by AppleScript. Though you may see these terms in
a dictionary, script, or scripting addition, you should not count on their behavior.
311
Document Revision History
Date Notes
312
Glossary
absolute object specifier An object specifier that assignment statement A statement that assigns
has enough information to identify an object or a value to a variable. Assignment statements use the
objects uniquely. For an object specifier to an copy or set commands.
application object to be complete, its outermost
attribute A characteristic that can be considered
container must be the application itself. See relative
or ignored in a considering or ignoring
object specifier.
statement.
Apple event An interprocess message that
binary operator An operator that derives a new
encapsulates a command in a form that can be
value from a pair of values.
passed across process boundaries, performed, and
responded to with a reply event. When an boolean A logical truth value; see the boolean
AppleScript script is executed, a statement that class.
targets a scriptable application may result in an
Boolean expression An expression whose value
Apple event being sent to that application.
can be either true or false.
AppleScript A scripting language that makes
chevrons See double angle brackets.
possible direct control of scriptable applications and
scriptable parts of OS X. child script object A script object that inherits
properties and handlers from another object, called
AppleScript command A script command provided
the parent.
by AppleScript. AppleScript commands do not have
to be included in tell statements. class (1) A category for objects that share
characteristics such as properties and elements and
application command A command that is defined
respond to the same commands. (2) The label for
by scriptable application to provide access to a
the AppleScript class property—a reserved word
scriptable feature. An application command must
that specifies the class to which an object belongs.
either be included in a tell statement or include
the name of the application in its direct parameter. coercion The process of converting an object from
one class to another. For example, an integer value
application object An object stored in an
can be coerced into a real value. Also, the software
application or its documents and managed by the
that performs such a conversion. Also known as
application.
object conversion.
arbitrary reference form A reference form that
command A word or series of words that requests
specifies an arbitrary object in a container.
an action. See also handler.
313
Glossary
comment Text that remains in a script after continue statement A statement that controls
compilation but is ignored by AppleScript when the when and how other statements are executed.
script is executed. AppleScript defines standard control statements
such as if, repeat, and while.
compile In AppleScript, to convert a script from
the form typed into a script editor to a form that can control statement A statement that causes
be used by AppleScript. The process of compiling a AppleScript to exit the current handler and transfer
script includes syntax and vocabulary checks. A script execution to the handler with the same name in the
is compiled when you first run it and again when parent. A continue statement can also be used to
you modify it and then run it again, save it, or check invoke an inherited handler in the local context.
its syntax.
current application The application that is using
compiled script The form to which a script is the AppleScript component to compile and execute
converted when you compile it. scripts (typically, Script Editor).
composite value A value that contains other current script The script currently being executed.
values. Lists, records, and strings are examples of
current target The object that is the current default
composite values.
target for commands.
compound statement A statement that occupies
data A class used for data that do not belong to
more than one line and contains other statements.
any of the other AppleScript classes; see the data
A compound statement begins with a reserved word
class.
indicating its function and ends with the word end.
See also simple statement. date A class that specifies a time, day of the month,
month, and year; see the date class.
conditional statement See if statement.
declaration The first occurrence of a variable or
considering statement A control statement that
property identifier in a script. The form and location
lists a specific set of attributes to be considered when
of the declaration determine how AppleScript treats
AppleScript performs operations on strings or sends
the identifier in that script—for example, as a
commands to applications.
property, global variable, or local variable.
constant A reserved word with a predefined value;
default target The object that receives a command
see the constant class.
if no object is specified or if the object is
container An object that contains one or more incompletely specified in the command. Default (or
other objects, known as elements. You specify implicit) targets are specified in tell statements.
containers with the reserved words of or in.
delegation The handing off of control to another
continuation character A character used in Script object. In AppleScript, the use of a continue
Editor to extend a statement to the next line. With statement to call a handler in a parent object or the
a U.S. keyboard, you can enter this character by current application.
typing Option-l (lower-case L).
314
Glossary
dialect A version of the AppleScript language that every reference form A reference form that
resembles a specific human language or specifies every object of a particular type in a
programming language. As of AppleScript 1.3, container.
English is the only dialect supported.
exit statement A statement used in the body of a
dictionary The set of commands, objects, and other repeat statement to exit the Repeat statement.
terminology that is understood by an application or
explicit run handler A handler at the top level of
other scriptable entity. You can display an
a script object that begins with on run and ends
application’s dictionary with Script Editor.
with end. A single script object can include an
direct parameter The parameter immediately explicit run handler or an implicit run handler, but
following a command, which typically specifies the not both.
object to which the command is sent.
expression In AppleScript, any series of words that
double angle brackets Characters («») typically used has a value.
by AppleScript to enclose raw data. With a U.S.
filter A phrase, added to a reference to a system
keyboard, you can enter double angle brackets (also
or application object, that specifies elements in a
known as chevrons) by typing Option-Backslash and
container that match one or more conditions.
Shift-Option-Backslash.
filter reference form A reference form that
element An object contained within another
specifies all objects in a container that match a
object. An object can typically contain zero or more
condition specified by a Boolean expression.
of each of its elements.
formal parameter See parameter variable.
empty list A list containing no items. See the list
class. global variable A variable that is available
anywhere in the script in which it is defined.
error expression An expression, usually a text
object, that describes an error. handler A collection of statements that can be
invoked by name. See also command.
error handler A collection of statements that are
executed in response to an error message. See the identifier A series of characters that identifies a
try statement. value or handler in AppleScript. Identifiers are used
to name variables, handlers, parameters, properties,
error message A message that is supplied by an
and commands.
application, by AppleScript, or by OS X when an error
occurs during the handling of a command. ID reference form A reference form that specifies
an object by the value of its ID property.
error number An integer that identifies an error.
if statement A control statement that contains one
evaluation The conversion of an expression to a
or more Boolean expressions whose results
value.
determine whether to execute other statements
within the if statement.
315
Glossary
ignoring statement A control statement that lists lifetime The period of time over which a variable
a specific set of attributes to be ignored when or property is in existence.
AppleScript performs operations on text strings or
list An ordered collection of values; see the list
sends commands to applications.
class.
implicit run handler All the statements at the top
literal A value that evaluates to itself.
level of a script except for property definitions,
script object definitions, and other handlers. A local variable A variable that is available only in
single script object can include an explicit run the handler in which it is defined. Variables that are
handler or an implicit run handler, but not both. defined within handlers are local unless they are
explicitly declared as global variables.
index reference form A reference form that
specifies an object by describing its position with log statement A script statement that reports the
respect to the beginning or end of a container. value of one or more variables to the Event Log pane
of a script window, and to the Event Log History
inheritance The ability of a child script object to
window, if it is open.
take on the properties and handlers of a parent
object. loop A series of statements that is repeated.
inheritance chain The hierarchy of objects that loop variable A variable whose value controls the
AppleScript searches to find the target for a number of times the statements in a repeat
command or the definition of a term. statement are executed.
initializing a script object The process of creating middle reference form A reference form that
a script object from the properties and handlers specifies the middle object of a particular class in a
listed in a script object definition. AppleScript container. (This form is rarely used.)
creates a script object when it runs a script or
name reference form A reference form that
handler that contains a script object definition.
specifies an object by name—that is, by the value
insertion point A location where another object of its name property.
or objects can be added.
nested control statement A control statement that
integer A positive or negative number without a is contained within another control statement.
fractional part; see the integer class.
number A synonym for the AppleScript classes
item A value in a list or record. An item can be integer and real.
specified by its offset from the beginning or end of
object An instantiation of a class definition, which
the list or record.
can include properties and actions.
keyword A word that is part of the AppleScript
object conversion See coercion.
language. Synonymous with reserved word.
316
Glossary
object specifier A phrase specifies the information property reference form A reference form that
needed to find another object in terms of the objects specifies a property of an application object,
in which it is contained. See also absolute object record or script object.
specifier, relative object specifier, and reference form.
range reference form A reference form that
operand An expression from which an operator specifies a series of objects of the same class in the
derives a value. same container.
operation The evaluation of an expression that raw format AppleScript terms enclosed in double
contains an operator. angle brackets, or chevrons («»). AppleScript uses
raw format because it cannot find a script term in
operator A symbol, word, or phrase that derives a
any available dictionary, or cannot display data in
value from another value or pair of values.
its native format.
optional parameter A parameter that need not be
real A number that can include a decimal fraction;
included for a command to be successful.
see the real class.
outside property, variable, or statement A
record An unordered collection of properties,
property, variable, or statement in a script object
identified by unique labels; see the record class.
but occurs outside of any handlers or nested script
objects. recordable application An application that uses
Apple events to report user actions for recording
parameter variable An identifier in a handler
purposes. When recording is turned on, Script Editor
definition that represents the actual value of a
creates statements corresponding to any significant
parameter when the handler is called. Also called a
actions you perform in a recordable application.
formal parameter .
recursive handler A handler that calls itself.
parent object An object from which another
script object, called the child, inherits properties reference An object that encapsulates an object
and handlers. A parent object may be any object, specifier.
such as a list or an application object, but it is
reference form The syntax for identifying an object
typically another script object.
or group of objects in an application or other
positional parameter A handler parameter that is container—that is, the syntax for constructing an
identified by the order in which it is listed. In a object specifier. AppleScript defines reference forms
handler call, positional parameters are enclosed in for arbitrary, every, filter, ID, index, middle, name,
parentheses and separated by commas. They must property, range, and relative.
be listed in the order in which they appear in the
relative object specifier An object specifier that
corresponding handler definition.
does not include enough information to identify an
property A labeled container in which to store a object or objects uniquely. When AppleScript
value. Properties can specify characteristics of encounters a partial object specifier, it uses the
objects.
317
Glossary
default object specified in the enclosing tell Script Editor The script-editing application
statement to complete the reference. See absolute distributed with AppleScript.
object specifier.
scripting addition A file that provides additional
relative reference form A reference form that commands or coercions you can use in scripts. If a
specifies an object or location by describing its scripting addition is located in the Scripting
position in relation to another object, known as the Additions folder, its terminology is available for use
base, in the same container. by any script.
repeat statement A control statement that scripting addition command A command that is
contains a series of statements to be repeated and, implemented as a scripting addition.
in most cases, instructions that specify when the
script library A script saved in a Script Libraries
repetition stops.
folder so it can be used by other scripts.
required parameter A parameter that must be
script object A user-defined object that can
included for a command to be successful.
combine data (in the form of properties) and actions
reserved word A word that is part of the (in the form of handlers and additional script
AppleScript language. Synonymous with keyword. objects).
result A value generated when a command is script object definition A compound statement
executed or an expression evaluated. that contains a collection of properties, handlers,
and other AppleScript statements.
return statement A statement that exits a handler
and optionally returns a specified value. simple statement One that can be written on a
single line. See also compound statement.
scope The range over which AppleScript recognizes
a variable or property, which determines where else simple value A value, such as an integer or a
in a script you may refer to that variable or property. constant, that does not contain other values.
script A series of written instructions that, when Standard suite A set of standard AppleScript
executed, cause actions in applications or OS X. terminology that a scriptable application should
support if possible. The Standard suite contains
scriptable application An application that can be
commands such as count, delete, duplicate,
controlled by a script. For AppleScript, that means
and make, and classes such as application,
being responsive to interapplication messages, called
document, and window.
Apple events, sent when a script command targets
the application. statement A series of lexical elements that follows
a particular AppleScript syntax. Statements can
script application An application whose only
include keywords, variables, operators, constants,
function is to run the script associated with it.
expressions, and so on. See also compound
script editor An application used to create and statement, simple statement.
modify scripts.
318
Glossary
statement block One or more statements enclosed unary operator An operator that derives a new
in a compound statement and having an end value from a single value.
statement.
Unicode An international standard that uses a
string A synonym for the text class. 16-bit encoding to uniquely specify the characters
and symbols for all commonly used languages.
styled text Text that may include style and font
information. Not supported in AppleScript 2.0. Unicode code point A unique number that
represents a character and allows it to be
suite Within an application's scriptability
represented in an abstract way, independent of how
information, a grouping of terms associated with
it is rendered.
related operations.
Unicode text A class that represents an ordered
synonym An AppleScript word, phrase, or language
series of two-byte Unicode characters.
element that has the same meaning as another
AppleScript word, phrase, or language element. For use statement A control statement that declares a
example, the operator does not equal is a required resource for a script and may import
synonym for ≠. terminology from that resource.
319
Apple Inc.
Copyright © 2015 Apple Inc.
All rights reserved.
321
Index
322
Index
323
Index
324
Index
325
Index
326
Index
327
Index
328
Index
329
Index
330
Index
331
Index
332
Index
333