Apple Script Language Guide
Apple Script Language Guide
Division.
A binary arithmetic operator that divides the number to its left
by the number to its right.
Class of operands: integer (page 89), real (page 93)
Class of result: real
/
(Option-slash on U.S. keyboard)
Integral division.
A binary arithmetic operator that divides the number to its left
by the number to its right and returns the integral part of the
answer as its result.
Class of operands: integer (page 89), real (page 93)
Class of result: integer
div
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 89), real (page 93)
Class of result: integer, real
mod
184
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
Description AppleScript operator
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 89), real (page 93)
Class of result: real
^
Coercion (or object conversion).
Abinary operator that converts the left-hand operand to the class
listed to its right.
Not all values can be coerced to all classes. The coercions that
AppleScript can perform are listed in Coercion (Object
Conversion) (page 32). The additional coercions, if any, that an
application can perform is listed in its dictionary.
Class of operands: The right-hand operand must be a class
identifier; the left-hand operand must be a value that can be
converted to that class.
Class of result: The class specified by the class identifier to the
right of the operator
as
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 82)
Class of result: boolean
not
A reference to.
A unary operator that causes AppleScript to return a
reference (page 95) object that specifies the location of the
operand to its right. A reference is evaluated at run time, not at
compile time.
See a reference to (page 188) for more information.
Class of operand: any class type
Class of result: reference
[a] (ref [to] | reference to)
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 rightit performs the multiplication operation 2 * 5 first, because multiplication has higher
precedence than addition.
12 + 2 * 5 --result: 22
Table 9-2 (page 186) 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.
185
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
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.
Table 9-2 Operator precedence
Type of operator Associativity Operators Order
Grouping Innermost to outermost ( ) 1
Plus or minus sign for numbers Unary +
2
Exponentiation
(note that this is different from standard math, in which
exponentiation takes precedence over unary plus or minus)
Right to left ^ 3
Multiplication and division Left to right *
/
div
mod
4
Addition and subtraction Left to right +
5
Concatenation Left to right & 6
Coercion Left to right as 7
Comparison None <
>
8
Equality and inequality None =
9
Logical negation Unary not 10
Logical and Left to right and 11
Logical or Left to right or 12
The following sections provide additional detail about how AppleScript evaluates operators in expressions:
& (concatenation) (page 187)
a reference to (page 188)
186
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
contains, is contained by (page 189)
equal, is not equal to (page 190)
greater than, less than (page 191)
starts with, ends with (page 192)
& (concatenation)
The concatenation operator (&) concatenates text objects, joins record objects into a record, and joins
other objects into a list.
Table 9-1 (page 179) 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:
66 & "Route " --result: {66, "Route "} (a list)
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:
item 1 of {"This"} & {"and", "that"} -- "Thisandthat"
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
{ name:"Matt", mileage:"8000" } & { name:"Steve", framesize:58 }
is
{ name:"Matt", mileage:"8000", frameSize:58 }
All Other Classes
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:
1 & 2 --result: {1, 2}
{"this"} & "hello" --result: {"this", "hello"}
{"this"} & {a:1, b:2} --result: {"this", 1, 2}
187
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
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:
{"This"} & {"and", "that"} --result: {"This", "and", "that"}
{"This"} & item 1 of {"and", "that"} --result: {"This", "and"}
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 89).
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 95) class and Object Specifiers (page 29).
Examples
The following statement creates a reference object that contains an object specifier to the Finder startup
disk:
tell app "Finder" to set diskRef to a ref to startup disk
--result: startup disk of application "Finder"
The following shows how to obtain a reference object that refers to an item in a list:
set itemRef to a reference to item 3 of {1, "hello", 755, 99}
--result: item 3 of {1, "hello", 755, 99}
set newTotal to itemRef + 45 --result: 800
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:
contents of itemRef --result: 755
The next examples demonstrate howusing 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:
tell application "iTunes"
set curTrack to current track
--result: file track id 2703 of user playlist id 2425
-- of source id 46 of application "iTunes"
display dialog (name of curTrack as string) -- "Shattered"
next track -- play next song
display dialog (name of curTrack as string) -- "Shattered"
end tell
Because curTrack is a specific track object, its name doesnt change when the current track changes. But
observe the result when using a reference to the current track:
188
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
tell application "iTunes"
set trackRef to a reference to current track
--result: current track of application "iTunes"
display dialog (name of trackRef as string) -- "Shattered"
next track -- play next song
display dialog (name of trackRef as string) -- "Strange Days"
end tell
Because trackRef is a reference object containing an object specifier, the specifier identifies the new
track when the current track changes.
contains, is contained by
The contains and is contained by operators work with lists, records, and text objects.
Table 9-1 (page 179) summarizes the use of these operators and their synonyms.
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:
{ "this", "is", 1 + 1, "cool" } contains { "is", 2 }
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:
{ "this", "is", 2, "cool" } contains { 2, "is" }
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:
{ "is", 2} is contained by { "this", "is", 2, "cool" }
Both contains and is contained by work if the sublist is a single valueas with the concatenation
operator (&), single values are coerced to one-item lists. For example, both of the following expressions
evaluate to true:
{ "this", "is", 2, "cool" } contains 2
2 is contained by { "this", "is", 2, "cool" }
However, the following expressions, containing nested lists, both evaluate to false:
{"this", "is", {2}, "cool"} contains 2 -- false
{"this", "is", {2}, "cool"} contains {2} -- 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. Arecord is contained by another record if all the properties in the left-hand
189
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
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:
{ name:"Matt", mileage:"8000", description:"fast"}
contains { description:"fast", name:"Matt" }
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,
"operand" contains "era"
is true, but
"operand" contains "dna"
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:
"era" is contained by "operand"
Text comparisons can be affected by considering and ignoring statements, as described in the Text
section of equal, is not equal to (page 190).
equal, is not equal to
The equal and is not equal to operators can handle operands of any class. Two expressions of different
classes are generally not equal, although for scalar operands, such as booleans, integers, and reals, two
operands are the same if they have the same value.
Table 9-1 (page 179) 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:
{ 7, 23, "Hello" } = {7, 23, "Goodbye"} --result: false
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:
{ name:"Matt", mileage:"8000" } = { mileage:"8000", name:"Matt"}
190
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
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 97) 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 fromlowercase letters unless you use a considering statement
to consider the case attribute. For example:
"DUMPtruck" is equal to "dumptruck" --result: true
considering case
"DUMPtruck" is equal to "dumptruck" --result: false
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 193)).
greater than, less than
The greater than and less than operators work with dates, integers, real numbers, and text objects.
Table 9-1 (page 179) 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.
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 users language preference. With the preference set to English, the
following two statements both evaluate to true:
"zebra" comes after "aardvark"
"zebra" > "aardvark"
The following two statements also evaluate to true:
"aardvark" comes before "zebra"
"aardvark" < "zebra"
Text comparisons can be affected by considering and ignoring statements, as described in the Text
section of equal, is not equal to (page 190).
191
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators Reference
starts with, ends with
The starts with and ends with operators work with lists and text objects.
Table 9-1 (page 179) 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:
{ "this", "is", 2, "cool" } ends with "cool"
{ "this", "is", 2, "cool" } starts with "this"
{ "this", "is", 2, "cool" } starts with { "this", "is" }
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:
"operand" starts with "opera"
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:
"operand" ends with "and"
Text comparisons can be affected by considering and ignoring statements, as described in the Text
section of equal, is not equal to (page 190).
192
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Operators 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).
considering and ignoring Statements
The considering and ignoring statements cause AppleScript to consider or ignore specific characteristics
as it executes groups of statements. There are two kinds of considering and ignoring statements:
Those that specify attributes to be considered or ignored in performing text comparisons.
Those that specify whether AppleScript should consider or ignore responses from an application.
considering / ignoring (text comparison)
Specify how AppleScript should treats attributes, such as case, in performing text comparisons.
Syntax
considering attribute [, attribute ... and attribute ]
[ but ignoring attribute [, attribute ... and attribute ] ]
[ statement ]...
end considering
ignoring attribute [, attribute ... and attribute ]
[ but considering attribute [, attribute ... and attribute ] ]
[ statement ]...
193
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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 191) 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, "rsum" 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
If this attribute is ignored,text objects are compared as if no punctuation marks (such as .
, ? : ; ! ' " `) are present; for example "What? he inquired." is equal to "what
he inquired".
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.
statement
Any AppleScript statement.
Examples
The following examples showhowconsidering and ignoring statements for various attributes can change
the value of text comparisons.
"Hello Bob" = "HelloBob" --result: false
ignoring white space
"Hello Bob" = "HelloBob" --result: true
end ignoring
"BOB" = "bob" --result: true
considering case
"BOB" = "bob" --result: false
end considering
194
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
"a" = "" --result: false
ignoring diacriticals
"a" = "" --result: true
end considering
"Babs" = "bbs" --result: false
ignoring case
"Babs" = "bbs" --result: false
end ignoring
ignoring case and diacriticals
"Babs" = "bbs" --result: true
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.
Special Considerations
Because text item delimiters (described in version (page 39)) 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 / ignoring (application responses)
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 neednt wait while Finder
is performing a potentially lengthy task:
tell application "Finder"
ignoring application responses
empty the trash
end ignoring
end tell
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:
tell application "Finder"
195
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
ignoring application responses
empty the trash
-- other statements that ignore application responses
considering application responses
set itemName to name of first item of startup disk
end considering
-- other statements that ignore application responses
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 fromAppleScript 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 isnt
found), in an application (for example, when the script specifies an object that doesnt exist), and in the script
itself. An error message is a message that is supplied by an application, AppleScript, or Mac 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 errorwhich can then be handled by an error handlerwith 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 207) statement. In the on error branch of a
try statement, a script may be able to recover gracefully fromthe 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.
error
Signals an error in a script.
Syntax
error [ errorMessage ] [ number errorNumber ]
[ partial resultresultList ]
[ from offendingObject ] [ to expectedType ]
Placeholders
errorMessage
Atext 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.
196
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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, Mac 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 233).
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 207) statement to handle a simple error, and demonstrates howyou
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
word 5 of "one two three"
on error eStr number eNum partial result rList from badObj to expectedType
-- statements that take action based on the error
display dialog "Doing some preliminary handling..."
-- then resignal the error
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
word 5 of "one two three"
on error
-- statements to execute in case of error
error "There are not enough words."
end try
For more comprehensive examples, see Working with Errors (page 237).
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.
197
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
if (simple)
Executes a statement if a Boolean expression evaluates to true.
Syntax
if boolean then statement
Placeholders
boolean
A Boolean expression.
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 ageOfCat > 1 then display dialog "This is not a kitten."
if (compound)
Executes a group (or groups) of statements if a Boolean expression (or expressions) evaluates to true.
Syntax
if boolean [ then ]
[ statement ]...
[else if boolean [ then ]
[ 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):
198
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
if currentTemp < 60 then
set response to "It's a little chilly today."
else if currentTemp > 80 then
set response to "It's getting hotter today."
else
set response to "It's a nice day today."
end if
display dialog response
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
45).
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 199).
repeat (forever)
Repeats a statement (or statements) until an exit statement is encountered.
Important: A repeat (forever) statement will never complete unless you cause it to do so.
To terminate a repeat (forever) statement, you can:
199
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
Use an exit (page 199) statement and design the logic so that it eventually encounters the exit
statement.
Use a return (page 214) statement, which exits the handler or script that contains the loop, and
therefore the loop as well.
Use a try (page 207) statement and rely on an error condition to exit the loop.
Syntax
repeat
[ statement ]...
end [ repeat ]
Placeholders
statement
Any AppleScript statement.
Examples
This form of the repeat statement is similar to the repeat until (page 201) 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 performperiodic tasks, such as checking
for an operation to complete. See idle Handlers (page 76) for more information.
repeat (number) times
Repeats a statement (or statements) a specified number of times.
Syntax
repeat integer [ times ]
[ statement ]...
200
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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
repeat power - 1 times
set returnVal to returnVal * 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
repeat until boolean
[ statement ]...
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:
set userDone to false
repeat until userDone
set userDone to enterDataRecord()
201
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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
repeat while boolean
[ 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.
Examples
The following example uses the repeat while form of the repeat statement to allow a user to enter
database records. In this case, weve just reversed the logic shown in the repeat until (page 201) example.
Here, the handler enterDataRecord(), which is not shown, returns true if the user is not done entering
records:
set userNotDone to true
repeat while userNotDone
set userNotDone to enterDataRecord()
end repeat
repeat with loopVariable (from startValue to stopValue)
Repeats a statement (or statements) until the value of the controlling loop variable exceeds the value of the
predefined stop value.
Syntax
repeat with loopVariable from startValue to stopValue [ by stepValue ]
[ statement ]...
202
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
end [ repeat ]
Placeholders
loopVariable
Controls the number of iterations. It can be a previously defined variable or a newvariable 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
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
repeat with n from 2 to x
set returnVal to returnVal * n
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 doesnt change the execution
of the loop.
repeat with loopVariable (in list)
Loops through the items in a specified list.
203
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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
repeat with loopVariable in list
[ statement ]...
end [ repeat ]
Placeholders
loopVariable
Any previously defined variable or a newvariable 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).
set wordList to words in "Where is the hammer?"
repeat with currentWord in wordList
log currentWord
if contents of currentWord is equal to "hammer" then
display dialog "I found the hammer!"
end if
end repeat
The statement log currentWord logs the current list itemto Script Editors log window. For more information,
see Debugging AppleScript Scripts (page 45).
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:
repeat with i in {1, 2, 3, 4}
set listItem to i
end repeat
204
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
--result: item 4 of {1, 2, 3, 4} --result: an object specifier
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:
repeat with i in {1, 2, 3, 4}
set listItem to contents of i
end repeat
--result: 4
You can also use the list items directly in expressions:
set total to 0
repeat with i in {1, 2, 3, 4}
set total to total + i
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 targetthat 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 objects 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:
tell application "Finder"
set frontWindowName to name of front window
-- any number of additional statements can appear here
end tell
You can nest tell statements inside other tell statements, as long as you follow the syntax and rules
described in tell (compound) (page 206).
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 40) and in Calling Handlers in a
tell Statement (page 72).
A tell statement that targets a local application doesnt cause it to launch, if it is not already running. For
example, a script can examine the is running property of the targeted application (page 80) object to
determine if the application is running before attempting to send it any commands. If it is not running it
wont 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 108) command to bring it to the front, if
needed.
A tell statement that targets a remote application will not cause it to launchin fact, it will not compile
or run unless the application is already running. Nor is it possible to access the is running property of an
application on a remote computer.
205
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
tell (simple)
Specifies a target object and a command to send to it.
Syntax
tell referenceToObject to statement
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:
tell front window of application "Finder" to close
For more information on how to specify an application object, see the application (page 80) class.
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:
tell application "Finder"
close front window
end tell
tell front window of application "Finder" to close
tell application "Finder" to close front window
The following example shows a nested tell statement:
206
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
tell application "Finder"
tell document 1 of application "TextEdit"
set newName to word 1 -- handled by TextEdit
end tell
set len to count characters in newName -- handled by AppleScript
if (len > 2) and (len < 15) then -- comparisons handled by AppleScript
set name of first item of disk "HD" to newName -- handled by Finder
end if
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 196) and AppleScript Error Handling (page 36).
try
Attempts to execute a list of AppleScript statements, calling an error handler if any of the statements results
in an error.
Atry 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 ]...
[ on error [ errorMessage ] [ number errorNumber ] [ from offendingObject ]
[ partial result resultList ] [ to expectedType ]
[ statement ]... ]
end [ error | try ]
Placeholders
statement
Any AppleScript statement.
207
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
errorMessage
A text object, that describes the error.
errorNumber
The error number, an integer. For possible values, see Error Numbers and Error Messages (page 233).
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 39).
Examples
The following example shows howyou can use a try statement to handle the Cancel button for a display
alert (page 124) 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
display alert "Hello" buttons {"Cancel", "Yes", "No"} cancel button 1
on error errText number errNum
if (errNum is equal to -128) then
-- User cancelled.
display dialog "User cancelled."
else
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
display alert "Hello" buttons {"Cancel", "Yes", "No"} cancel button 1
on error number -128
-- Either do something special to handle Cancel, or just ignore it.
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
repeat with i from 1 to "Toronto"
-- do something that depends on variable "i"
208
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
end repeat
on error from obj to newClass
log {obj, newClass} -- Display from and to info in log window.
end try
This repeat statement fails because the text object "Toronto" cannot be coerced to an integer (page
89). 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 Editors Event Log History window (and to the script
windows Event Log pane). The result is (*Toronto, integer*), indicating the error occurred while trying to
coerce Toronto to an integer.
For additional examples, see Working with Errors (page 237).
using terms from Statements
A using terms from statement lets you specify which terminology AppleScript should use in compiling
the statements in a script. Whereas a tell statement specifies the default target (often an application) to
which commands are sent and the terminology to use, a using terms from statement specifies only the
terminology.
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 applications 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.
using terms from
Instructs AppleScript to use the terminology from the specified application in compiling the enclosed
statements.
Syntax
using terms from application
[ statement ]...
end [ using terms from ]
Placeholders
application
A specifier for an application object.
statement
Any AppleScript statement.
209
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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:
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
-- statements to process each message in theMessages
end tell
end perform mail action with messages
end using terms from
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 44).
with timeout Statements
You can use a with timeout statement to control how long AppleScript waits for a command to execute
before timing out. By default, when an application fails to respond to a command, AppleScript waits for two
minutes before reporting an error and halting execution.
with timeout
Specifies how long AppleScript waits for a response to a command that is sent to another application.
Syntax
with timeout [ of ] integerExpression second[s]
[ statement ]...
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 doesnt complete the close operation within 20 seconds, the operation times out.
tell application "TextEdit"
with timeout of 20 seconds
close document 1 saving ask
end timeout
end tell
210
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
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 operationit merely stops execution of the script. If you want the
script to continue, you can wrap the statements in a try (page 207) 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 neednt wait for application commands to complete. For more
information, see considering and ignoring Statements (page 193).
with transaction Statements
When you execute a script, AppleScript may send one or more Apple events to targeted applications. A
transaction is a set of operations that are applied as a single uniteither all of the changes are applied or
none are. This mechanism works only with applications that support it.
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
with transaction [ session ]
[ 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.)
tell application "Small DB"
with transaction
set oldName to Field "Name"
set oldAddress to Field "Address"
set newName to display dialog
"Please type a new name"
211
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
default answer oldName
set newAddress to display dialog
"Please type the new address"
default answer oldAddress
set Field "Name" to newName
set Field "Address" to newAddress
end transaction
end tell
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:
tell application "Super DB"
set mySession to make session with data {user: "Bob", password: "Secret"}
with transaction mySession
...
end transaction
end tell
212
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 0
Control Statements Reference
This chapter provides reference for handlers, which are defined and introduced in About Handlers (page
67). It describes the types of parameters you can use with handlers and howyou 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 newlocation, 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
set x to display dialog "Start beeping?" buttons {"Yes", "No"}
if button returned of x is "Yes" then
continue beep numTimes -- Let AppleScript handle the beep.
-- In this example, nothing to do after returning from the continue.
end beep
beep 3 --result: local beep handler invoked; shows dialog before beeping
tell my parent to beep 3 -- result: AppleScript beep command invoked
213
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
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
scripts 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 applications
default quit handler, see quit Handlers (page 76).
For additional examples, see Using the continue Statement in Script Objects (page 63).
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:
return 2 -- returns integer value 2
If you include a return statement without an expression, AppleScript exits the handler immediately and no
value is returned:
return -- no value returned
See other sections throughout Handler Reference (page 213) 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 doesnt 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.
214
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
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 218) is a simple script that uses
two return statements.
For related information, see AppleScript Error Handling (page 36).
Handler Syntax (Labeled Parameters)
A handler is a collection of statements that can be invoked by name. This section describes the syntax for
handlers that use labeled parameters.
Labeled parameters are identified by their labels and can be listed in any order.
Syntax
( on | to ) handlerName
[ [ of | in ] directParamName ]
[ ASLabel userParamName ]...
[ given userLabel:userParamName [, userLabel:userParamName ]...]
[ 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 followthe word given; any additional pairs are separated
by commas.
userParamName
An identifier for a parameter variable.
215
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
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 214) statement.
Examples
For examples and related conceptual information, see Handlers with Labeled Parameters (page 68).
Discussion
A handler written to respond to an application command (like those in Handlers in Script Applications (page
73)) 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.
Calling a Handler with Labeled Parameters
This section describes the syntax for calling a handler with labeled parameters.
Syntax
handlerName
[ [ of | in ] directParam ]
[ [ ASLabel paramValue ...]
| [ with labelForTrueParam [, labelForTrueParam ]...
[ ( and | , ) labelForTrueParam ] ]
| [ without labelForFalseParam [, labelForFalseParam ]...]
[ ( and | , ) labelForFalseParam ] ]
| [ given userLabel:paramValue [, userLabel:paramValue ]...]...
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.
216
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
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.
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 68).
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 68).
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:
with rounding, smoothing and curling
with rounding without smoothing, curling
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.
217
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
Handler Syntax (Positional Parameters)
A handler is a collection of statements that can be invoked by name. This section describes the syntax for
handlers that use positional parameters.
Important: The parentheses that surround the parameter list in the following definition are part of the syntax.
Syntax
on | to handlerName ( [ userParamName [, userParamName ]...] )
[ 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 51).
Examples
For examples and related conceptual information, see Handlers with Positional Parameters (page 69).
Calling a Handler with Positional Parameters
A call for a handler with positional parameters must list the parameters in the same order as they are specified
in the handler definition.
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 69)
Discussion
When you call a handler with positional parameters, you supply the following:
218
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
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.
219
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
220
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 1
Handler Reference
Folder Actions is a feature of Mac OS X that lets you associate AppleScript scripts with folders. A Folder Action
script is executed when the folder to which it is attached is opened or closed, moved or resized, or has items
added or removed. 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. Awell 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 /Applications/AppleScript. 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 213)) 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.
When a Folder Action handler is invoked, none of the parameters is optional.
A Folder Action handler does not return a value.
Heres 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.
221
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
2. In that script, write a handler that conforms to the syntax documented here for the adding folder
items to (page 222) 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.
5. Use the Folder Actions Setup application, located in /Applications/AppleScript, to:
a. Enable folder actions for your image folder.
b. Add a script to that folder, choosing the script you created.
adding folder items to
A script handler that is invoked after items are added to its associated folder.
Syntax
on adding folder items to alias after receiving listOfAlias
[ statement ]...
end [ adding folder items to ]
Placeholders
alias
An alias (page 79) 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.
on adding folder items to this_folder after receiving these_items
tell application "Finder"
if not (exists folder "Done" of this_folder) then
make new folder at this_folder with properties {name:"Done"}
end if
set the destination_folder to folder "Done" of this_folder as alias
set the destination_directory to POSIX path of the destination_folder
end tell
repeat with i from 1 to number of items in these_items
set this_item to item i of these_items
set the item_info to info for this_item
if this_item is not the destination_folder and
the name extension of the item_info is not in {"zip", "sit"} then
222
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
set the item_path to the quoted form of the POSIX path of this_item
set the destination_path to the quoted form of
(destination_directory & (name of the item_info) & ".zip")
do shell script ("/usr/bin/ditto -c -k -rsrc --keepParent "
& item_path & " " & destination_path)
end if
end repeat
end adding folder items to
closing folder window for
A script handler that is invoked after a folders associated window is closed.
Syntax
on closing folder window for alias
[ statement ]...
end [ closing folder window for ]
Placeholders
alias
An alias (page 79) that identifies the folder that was closed.
statement
Any AppleScript statement.
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.
-- This script is designed for use with Mac OS X v10.2 and later.
on closing folder window for this_folder
tell application "Finder"
repeat with EachFolder in (get every folder of folder this_folder)
try
close window of EachFolder
end try
end repeat
end tell
end closing folder window for
moving folder window for
A script handler that is invoked after a folders associated windowis moved or resized. Not currently available.
Syntax
on moving folder window for alias from bounding rectangle
[ statement ]...
end [ moving folder window for ]
Placeholders
alias
An alias (page 79) that identifies the folder that was moved or resized.
You can use this alias to obtain the folder windows new coordinates from the Finder.
223
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
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
on moving folder window for this_folder from original_coordinates
tell application "Finder"
set this_name to the name of this_folder
set the bounds of the container window of this_folder
to the original_coordinates
end tell
display dialog "Window \"" & this_name & "\" has been returned to it's
original size and position." buttons {"OK"} default button 1
end moving folder window for
Special Considerations
Warning: In Mac 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 79) 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 Mac OS X v10.4, this script displays
text from the Comments field of the specified folder.)
-- This script is designed for use with Mac OS X v10.2 and later.
property dialog_timeout : 30 -- set the amount of time before dialogs auto-answer.
on opening folder this_folder
tell application "Finder"
activate
set the alert_message to the comment of this_folder
if the alert_message is not "" then
224
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
display dialog alert_message buttons {"Open Comments", "Clear
Comments", "OK"} default button 3 giving up after dialog_timeout
set the user_choice to the button returned of the result
if the user_choice is "Clear Comments" then
set comment of this_folder to ""
else if the user_choice is "Open Comments" then
open information window of this_folder
end if
end if
end tell
end opening folder
Special Considerations
Spotlight was introduced in Mac 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.
removing folder items from
A script handler that is invoked after items have been removed from its associated folder.
Syntax
on removing folder items from alias after losinglistOfAliasOrText
[ statement ]...
end [ removing folder items from ]
Placeholders
alias
An alias (page 79) 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.
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.
on removing folder items from this_folder after losing these_items
tell application "Finder"
set this_name to the name of this_folder
end tell
set the item_count to the count of these_items
display dialog (item_count as text) & " items have been removed " & "from
folder \"" & this_name & "\"." buttons {"OK"} default button 1
end removing folder items from
225
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
226
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1 2
Folder Actions Reference
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 18) in AppleScript Lexical
Conventions (page 17).)
The keywords in Table A-1 (page 227) 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 viewmany additional scripting terms defined by Apple,
but not part of the AppleScript language, in AppleScript Terminology and Apple Event Codes.
Table A-1 AppleScript reserved words, with descriptions
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) about
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) above
used to describe position in the Relative (page 176) reference form; used as part
of operator (comes after, does not come after) with classes such as
date (page 85), integer (page 89), and text (page 97)
after
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) against
logical and operatorsee Table 9-1 (page 179) and
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) apart from
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) around
coercion operatorsee Table 9-1 (page 179) as
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) aside from
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) at
used with Index (page 172) and Relative (page 176) reference forms; in back
of is synonymous with after and behind
back
used to describe position in the Relative (page 176) reference form; used as an
operator (comes before, does not come before) with classes such as
date (page 85), integer (page 89), and text (page 97); synonymous with in
front of
before
specifies an insertion location at the beginning of a containersee the boundary
specifier descriptions for the Range (page 175) reference form
beginning
synonymous with after and in back of behind
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) below
227
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) beneath
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) beside
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) between
used in considering and ignoring Statements (page 193) but
used with binary containment operator contains, is contained by (page 189);
also used as handler parameter labelsee Handler Syntax (Labeled
Parameters) (page 215)
by
a control statementsee considering and ignoring Statements (page 193) considering
binary containment operatorsee contains, is contained by (page 189) contain,
contains
changes the flow of executionsee continue (page 213) continue
an AppleScript commandsee copy (page 121) copy
division operatorsee Table 9-1 (page 179) div
used with operators such as does not equal, does not come before, and
does not containsee Table 9-1 (page 179)
does
specifies a position in a containersee Index (page 172) reference form eighth
used with if control statementsee if Statements (page 197) else
marks the end of a script or handler definition, or of a compound statement, such
as a tell or repeat statement; also specifies an insertion location at the end of a
containersee the boundary specifier descriptions for the Range (page 175)
reference form
end
binary comparison operatorsee equal, is not equal to (page 190) equal, equals
error (page 196) control statement; also used withtry (page 207) statement error
specifies every object in a containersee Every (page 168) reference form every
terminates a repeat loopsee exit (page 199) exit
a Boolean literalsee Boolean (page 20) false
specifies a position in a containersee Index (page 172) reference form fifth
specifies a position in a containersee Index (page 172) reference form first
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) for
specifies a position in a containersee Index (page 172) reference form fourth
228
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
usedinspecifyinga range of objects ina containersee Range (page 175) reference
form; also used as handler parameter labelsee Handler Syntax (Labeled
Parameters) (page 215)
from
in front of is used to describe position in the Relative (page 176) reference
form; synonymous with before
front
an AppleScript commandsee get (page 129) get
a special handler parameter labelsee Handler Syntax (Labeled Parameters) (page
215)
given
specifies the scope for a variable (see also local)see Global Variables (page
49)
global
a control statementsee if Statements (page 197) if
a control statementsee considering and ignoring Statements (page 193) ignoring
used in construction object specifierssee Containers (page 30); also used with
the Relative (page 176) reference formfor example in front of and in back
of
in
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) instead of
put into is a deprecated synonym for the copy (page 121) command; also used
as handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215)
into
used with various comparison operatorssee Table 9-1 (page 179) is
refers to the current target (of it)see The it and me Keywords (page 40) it
synonym for of itsee The it and me Keywords (page 40) its
specifies a position in a containersee Index (page 172) reference form last
specifies the scope for a variable (see also global)see Local Variables (page
48)
local
refers to the current script (of me)see The it and me Keywords (page 40) me
specifies a position in a containersee Index (page 172) reference form middle
remainder operatorsee Table 9-1 (page 179) mod
synonym for of mesee The it and me Keywords (page 40) my
specifies a position in a containersee Middle (page 173) reference form ninth
logical negation operatorsee Table 9-1 (page 179) not
used in construction object specifierssee Containers (page 30); used with or as
part of many other terms, including of me , in front of , and so on
of
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) on
229
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) onto
logical or operatorsee Table 9-1 (page 179) or
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) out of
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) over
prop is an abbreviation for propertysee The it and me Keywords (page 40) prop, property
put into is a deprecated synonym for the copy (page 121) command put
ref is an abbreviation for referencesee reference (page 95) ref/reference
a control statementsee repeat Statements (page 199) repeat
exits from a handlersee return (page 214) return
deprecated returning
used to declare a script object; also the class of a script objectsee the script (page
97) class and Script Objects (page 57)
script
specifies a position in a containersee Index (page 172) reference form second
an AppleScript commandsee set (page 154) set
specifies a position in a containersee Index (page 172) reference form seventh
handler parameter labelsee Handler Syntax (Labeled Parameters) (page 215) since
specifies an index position in a containersee Index (page 172) reference form sixth
specifies an object in a containersee Arbitrary (page 167) reference form some
a control statementsee tell Statements (page 205) tell
specifies a position in a containersee Index (page 172) reference form tenth
synonym for whose that
syntactic no-op, used to make script statements look more like natural language the
used with if control statementsee if Statements (page 197) then
specifies a position in a containersee Index (page 172) reference form third
usedinspecifyinga range of objects ina containersee Range (page 175) reference
form
through, thru
used with with timeout control statementsee with timeout (page 210) timeout
used with repeat control statementsee repeat (number) times (page 200) times
230
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
used in many places, including copy (page 121) and set (page 154) commands; in
the Range (page 175) 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 202); with the partial result parameter in try
Statements (page 207)
to
usedwithwith transaction control statementsee with transaction (page
211)
transaction
a Boolean literalsee Boolean (page 20) true
an error-handling statementsee try Statements (page 207) try
used with repeat control statementsee repeat until (page 201) until
used with the Filter (page 169) reference formto specify a Boolean test expression
(synonymous with whose)
where
used with repeat control statementsee repeat while (page 202) while
used with the Filter (page 169) reference formto specify a Boolean test expression
(synonymous with where)
whose
used in commands to specify various kinds of parameters, including true for some
Boolean for parameterssee, for example, the with prompt and multiple
selections allowedparameters tothe choose from list (page 116) command;
also used with application make commands to specify properties (with
properties)
with
used in commands to specify false for a Boolean for a parametersee, for example,
the multiple selections allowed parameter to the choose from list (page
116) command
without
231
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
232
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X A
AppleScript Keywords
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.
Table B-1 AppleScript errors
Error message Error number
Unknown error. -2700
Cant divide <number> by zero. -2701
The result of a numeric operation was too large. -2702
<reference> can't be launched because it is not an application. -2703
<reference> isn't scriptable. -2704
The application has a corrupted dictionary. -2705
Stack overflow. -2706
Internal table overflow. -2707
Attempt to create a value larger than the allowable size. -2708
Can't get the event dictionary. -2709
Can't both consider and ignore <attribute>. -2720
Can't perform operation on text longer than 32K bytes. -2721
Message size too large for the 7.0 Finder. -2729
A <language element> can't go after this <language element>. -2740
Expected <language element> but found <language element>. -2741
The <name> parameter is specified more than once. -2750
The <name> property is specified more than once. -2751
AppleScript Errors 233
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X B
Error Numbers and Error Messages
Error message Error number
The <name> handler is specified more than once. -2752
The variable <name> is not defined. -2753
Can't declare <name> as both a local and global variable. -2754
Exit statement was not in a repeat loop. -2755
Tell statements are nested too deeply. -2760
<name> is illegal as a formal parameter. -2761
<name> is not a parameter name for the event <event>. -2762
No result was returned for some argument of this expression. -2763
Operating System Errors
An operating system error is an error that occurs when AppleScript or an application requests services from
the Mac OS. They are rare, and often there is nothing you can do about them in a script, other than report
them. A few, such as "User canceled", make sense for scripts to handleas shown, for an example, in
the Examples section for the display dialog (page 125) command.
Table B-2 Mac OS errors
Error message Error number
No error. 0
Disk <name> full. -34
Disk <name> wasnt found. -35
Bad name for file -37
File <name> wasnt open. -38
End of file error. -39
Too many files open. -42
File <name> wasnt found. -43
Disk <name> is write protected. -44
File <name> is locked. -45
Disk <name> is locked. -46
File <name> is busy. -47
234
Operating System Errors
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X B
Error Numbers and Error Messages
Error message Error number
Duplicate file name. -48
File <name> is already open. -49
Parameter error. -50
File reference number error. -51
File not open with write permission. -61
Out of memory. -108
Folder <name> wasnt found. -120
Disk <name> is disconnected. -124
User cancelled. -128
A resource wasnt found. -192
Application isnt running -600
Not enough room to launch application with special requirements. -601
Application is not 32-bit clean. -602
More memory needed than is specified in the size resource. -605
Application is background-only. -606
Buffer is too small. -607
No outstanding high-level event. -608
Connection is invalid. -609
Not enough system memory to connect to remote application. -904
Remote access is not allowed. -905
<name> isnt running or program linking isnt enabled. -906
Cant find remote machine. -915
Invalid date and time <date string>. -30720
Operating System Errors 235
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X B
Error Numbers and Error Messages
236
Operating System Errors
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X B
Error Numbers and Error Messages
This appendix provides a detailed example of handling errors with try Statements (page 207) and error
Statements (page 196). 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 cant be handled. It also shows how to check for just a particular
error number that you are interested in.
Catching Errors in a Handler
The SumIntegerList handler expects a list of integers. If any item in the passed list is not an integer,
SumIntegerList signals error number 750 and returns 0. The handler includes an error handler that
displays a dialog if the error number is equal to 750; if the error number is not equal to 750, the handler
resignals the error with an error statement so that other statements in the call chain can handle the unknown
error. If no statement handles the error, AppleScript displays an error dialog and execution stops.
on SumIntegerList from itemList
try
-- Initialize return value.
set integerSum to 0
-- Before doing sum, check that all items in list are integers.
if ((count items in itemList) is not equal to
(count integers in itemList)) then
-- If all items arent integers, signal an error.
error number 750
end if
-- Use a repeat statement to sum the integers in the list.
repeat with currentItem in itemList
set integerSum to integerSum + currentItem
end repeat
return integerSum -- Successful completion of handler.
on error errStr number errorNumber
-- If our own error number, warn about bad data.
if the errorNumber is equal to 750 then
display dialog "All items in the list must be integers."
return integerSum -- Return the default value (0).
else
-- An unknown error occurred. Resignal, so the caller
-- can handle it, or AppleScript can display the number.
error errStr number errorNumber
end if
end try
end SumIntegerList
The SumIntegerList handler handles various error conditions. For example, the following call completes
without error:
set sumList to {1, 3, 5}
set listTotal to SumIntegerList from sumList --result: 9
Catching Errors in a Handler 237
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X C
Working with Errors
The following call passes bad datathe list contains an item that isnt an integer:
set sumList to {1, 3, 5, "A"}
set listTotal to SumIntegerList from sumList
if listTotal is equal to 0 then
-- the handler didnt total the list;
-- do something to handle the error (not shown)
end if
The SumIntegerList routine checks the list and signals an error 750 because the list contains at least one
non-integer item. The routines 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 doesnt handle it, AppleScript displays an error dialog and execution halts.
The SumIntegerList routine does not return a value.
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
set sumList to {1, 3, 5}
set listTotal to SumIntegerList from sumList
on error errMsg number errorNumber
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.
Simplified Error Checking
AppleScript provides a mechanism to streamline the way you can catch and handle individual errors. It is
often necessary for a script to handle a particular error, but not others. It is possible to catch an error, check
for the error number you are interested in, and use an error statement to resignal for other errors. For example:
try
open for access file "MyFolder:AddressData" with write permission
on error msg number n from f to t partial result p
if n = -49 then -- File already open error
display dialog "I'm sorry but the file is already open."
else
error msg number n from f to t partial result p
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
open for access file "MyFolder:AddressData" with write permission
238
Simplified Error Checking
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X C
Working with Errors
on error number -49
display dialog "I'm sorry but the file is already open."
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.
Simplified Error Checking 239
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X C
Working with Errors
240
Simplified Error Checking
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X C
Working with Errors
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 Editors 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 scriptthis is the event code representation for a display dialog (page 125) 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.
When a Dictionary Is Not Available
AppleScript uses double angle brackets in a Script Editor script window when it cant identify a term. That
happens when it encounters a term that isnt part of the AppleScript language and isnt defined in an
application or scripting addition dictionary that is available when the script is opened or compiled.
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 canalsohappenif the file StandardAdditions.osaxis 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.
When AppleScript Displays Data in Raw Format
Double angle brackets can also occur in results. For example, if the value of a variable is a script object
named Joe, AppleScript represents the script object as shown in this script:
script Joe
property theCount : 0
end script
set scriptObjectJoe to Joe
scriptObjectJoe
When a Dictionary Is Not Available 241
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X D
Double Angle Brackets
--result: script Joe
Similarly, if Script Editor cant display a variables 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 datas 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.
Entering Script Information in Raw Format
You can enter double angle brackets, or chevrons (), directly into a script by typing Option-Backslash and
Shift-Option-Backslash. You might want to do this if youre working on a script that needs to use terminology
that isnt available on your current machinefor example, if youre working at home and dont have the
latest dictionary for a scriptable application you are developing, but you know the codes for a supported
term.
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.
Sending Raw Apple Events From a Script
The termevent sysodlog is actually the rawformfor an Apple event with event class 'syso' and event
ID 'dlog' (the display dialog command). For a list of many of the four-character codes and their related
terminology used by Apple, see AppleScript Terminology and Apple Event Codes Reference.
You can use rawsyntax 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.
242
Entering Script Information in Raw Format
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X D
Double Angle Brackets
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.
List of Unsupported Terms
handle CGI request
This command is not supported.
internet address
An Internet or intranet address for the TCP/IP protocol. Only used for compatibility with WebSTAR
AppleScript CGI scripts, this term is not supported by AppleScript itself.
web page
An HTML page. This class is not supported.
List of Unsupported Terms 243
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X E
Unsupported Terms
244
List of Unsupported Terms
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
A P P E N D I X E
Unsupported Terms
absolute object specifier An object specifier that
has enough information to identify an object or
objects uniquely. For an object specifier to an
application object to be complete, its outermost
container must be the application itself. See relative
object specifier.
Apple event An interprocess message that
encapsulates a high-level task in a single package that
can be passed across process boundaries, performed,
and responded to with a reply event.When an
AppleScript script is executed, a statement that targets
a scriptable application may result in an Apple event
being sent to that application.
AppleScript A scripting language that makes
possible direct control of scriptable applications and
scriptable parts of Mac OS X.
AppleScript command A script command provided
by AppleScript. AppleScript commands do not have
to be included in tell statements.
application command A command that is defined
by scriptable application to provide access to a
scriptable feature. An application command must
either be included in a tell statement or include the
name of the application in its direct parameter.
applicationobject An object stored in an application
or its documents and managed by the application.
arbitrary reference form A reference form that
specifies an arbitrary object in a container.
assignment statement A statement that assigns a
value to a variable. Assignment statements use the
copy or set commands.
attribute A characteristic that can be considered or
ignored in a considering or ignoring statement.
binary operator An operator that derives a new
value from a pair of values.
boolean A logical truth value; see the boolean class.
Booleanexpression An expression whose value can
be either true or false.
chevrons See double angle brackets.
child script object A script object that inherits
properties and handlers from another object, called
the parent.
class (1) A category for objects that share
characteristics such as properties and elements and
respond to the same commands. (2) The label for the
AppleScript class propertya reserved word that
specifies the class to which an object belongs.
coercion The process of converting an object from
one class to another. For example, an integer value
can be coerced into a real value. Also, the software
that performs such a conversion. Also known as object
conversion.
command A word or series of words that requests
an action. See also handler.
comment Text that remains in a script after
compilation but is ignored by AppleScript when the
script is executed.
compile In AppleScript, to convert a script from the
form typed into a script editor to a form that can be
used by AppleScript. The process of compiling a script
includes syntax and vocabulary checks. A script is
compiled when you first run it and again when you
modify it and then run it again, save it, or check its
syntax.
245
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
Glossary
compiled script The form to which a script is
converted when you compile it.
composite value A value that contains other values.
Lists, records, and strings are examples of composite
values.
compound statement A statement that occupies
more than one line and contains other statements. A
compound statement begins with a reserved word
indicating its function and ends with the word end.
See also simple statement.
conditional statement See if statement.
considering statement A control statement that
lists a specific set of attributes to be considered when
AppleScript performs operations on strings or sends
commands to applications.
constant A reserved word with a predefined value;
see the constant class.
container An object that contains one or more other
objects, known as elements. You specify containers
with the reserved words of or in.
continuation character A character used in Script
Editor to extend a statement to the next line. With a
U.S. keyboard, you can enter this character by typing
Option-l (lower-case L).
continue statement A statement that controls when
and how other statements are executed. AppleScript
defines standard control statements such as if,
repeat, and while.
control statement A statement that causes
AppleScript to exit the current handler and transfer
execution to the handler with the same name in the
parent. A continue statement can also be used to
invoke an inherited handler in the local context.
current application The application that is using
the AppleScript component to compile and execute
scripts (typically, Script Editor).
current script The script currently being executed.
current target The object that is the current default
target for commands.
data A class used for data that do not belong to any
of the other AppleScript classes; see the data class.
date A class that specifies a time, day of the month,
month, and year; see the date class.
declaration The first occurrence of a variable or
property identifier in a script. The form and location
of the declaration determine how AppleScript treats
the identifier in that scriptfor example, as a
property, global variable, or local variable.
default target The object that receives a command
if no object is specified or if the object is incompletely
specified in the command. Default (or implicit) targets
are specified in tell statements.
delegation The handing off of control to another
object. In AppleScript, the use of a continue
statement to call a handler in a parent object or the
current application.
dialect A version of the AppleScript language that
resembles a specific human language or programming
language. As of AppleScript 1.3, English is the only
dialect supported.
dictionary The set of commands, objects, and other
terminology that is understood by an application or
other scriptable entity. You can display an
applications dictionary with Script Editor.
direct parameter The parameter immediately
following a command, which typically specifies the
object to which the command is sent.
double angle brackets Characters () typically used
by AppleScript to enclose raw data. With a U.S.
keyboard, you can enter double angle brackets (also
known as chevrons) by typing Option-Backslash and
Shift-Option-Backslash.
element An object contained within another object.
An object can typically contain zero or more of each
of its elements.
empty list A list containing no items. See the list
class.
error expression An expression, usually a text
object, that describes an error.
246
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
G L O S S A R Y
error handler A collection of statements that are
executed in response to an error message. See the
try statement.
error message A message that is supplied by an
application, by AppleScript, or by Mac OS X when an
error occurs during the handling of a command.
error number An integer that identifies an error.
evaluation The conversion of an expression to a
value.
every reference form A reference form that specifies
every object of a particular type in a container.
exit statement A statement used in the body of a
repeat statement to exit the Repeat statement.
explicit run handler A handler at the top level of a
script object that begins with on run and ends
with end. A single script object can include an
explicit run handler or an implicit run handler, but
not both.
expression In AppleScript, any series of words that
has a value.
filter A phrase, added to a reference to a system or
application object, that specifies elements in a
container that match one or more conditions.
filter reference form A reference form that specifies
all objects in a container that match a condition
specified by a Boolean expression.
formal parameter See parameter variable.
global variable A variable that is available anywhere
in the script in which it is defined.
handler A collection of statements that can be
invoked by name. See also command.
identifier A series of characters that identifies a value
or handler in AppleScript. Identifiers are used to name
variables, handlers, parameters, properties, and
commands.
ID reference form A reference form that specifies
an object by the value of its ID property.
if statement A control statement that contains one
or more Boolean expressions whose results determine
whether to execute other statements within the if
statement.
ignoring statement A control statement that lists
a specific set of attributes to be ignored when
AppleScript performs operations on text strings or
sends commands to applications.
implicit run handler All the statements at the top
level of a script except for property definitions,
script object definitions, and other handlers. A
single script object can include an explicit run
handler or an implicit run handler, but not both.
index reference form A reference form that specifies
an object by describing its position with respect to
the beginning or end of a container.
inheritance The ability of a child script object to
take on the properties and handlers of a parent object.
inheritance chain The hierarchy of objects that
AppleScript searches to find the target for a command
or the definition of a term.
initializing a script object The process of creating a
script object fromthe properties and handlers listed
in a script object definition. AppleScript creates a
script object when it runs a script or handler that
contains a script object definition.
insertion point A location where another object or
objects can be added.
integer A positive or negative number without a
fractional part; see the integer class.
item A value in a list or record. An item can be
specified by its offset from the beginning or end of
the list or record.
keyword A word that is part of the AppleScript
language. Synonymous with reserved word.
labeled parameter A parameter that is identified
by a label. See also positional parameter.
lifetime The period of time over which a variable or
property is in existence.
247
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
G L O S S A R Y
list An ordered collection of values; see the list
class.
literal A value that evaluates to itself.
local variable A variable that is available only in the
handler in which it is defined. Variables that are
defined within handlers are local unless they are
explicitly declared as global variables.
log statement A script statement that reports the
value of one or more variables to the Event Log pane
of a script window, and to the Event Log History
window, if it is open.
loop A series of statements that is repeated.
loop variable A variable whose value controls the
number of times the statements in a repeat
statement are executed.
middle reference form A reference form that
specifies the middle object of a particular class in a
container. (This form is rarely used.)
name reference form A reference form that specifies
an object by namethat is, by the value of its name
property.
nested control statement A control statement that
is contained within another control statement.
number A synonym for the AppleScript classes
integer and real.
object An instantiation of a class definition, which
can include properties and actions.
object conversion See coercion.
object specifier A phrase specifies the information
needed to find another object in terms of the objects
in which it is contained. See also absolute object
specifier, relative object specifier, and reference form.
operand An expression from which an operator
derives a value.
operation The evaluation of an expression that
contains an operator.
operator A symbol, word, or phrase that derives a
value from another value or pair of values.
optional parameter A parameter that need not be
included for a command to be successful.
outside property, variable, or statement A
property, variable, or statement in a script object
but occurs outside of any handlers or nested script
objects.
parameter variable An identifier in a handler
definition that represents the actual value of a
parameter when the handler is called. Also called a
formal parameter.
parent object An object from which another script
object, called the child, inherits properties and
handlers. A parent object may be any object, such as
a list or an application object, but it is typically
another script object.
positional parameter A handler parameter that is
identified by the order in which it is listed. In a handler
call, positional parameters are enclosed in parentheses
and separated by commas. They must be listed in the
order in which they appear in the corresponding
handler definition.
property A labeled container in which to store a
value. Properties can specify characteristics of objects.
property reference form A reference form that
specifies a property of an application object,
record or script object.
range reference form A reference form that specifies
a series of objects of the same class in the same
container.
raw format AppleScript terms enclosed in double
angle brackets, or chevrons (). AppleScript uses raw
format because it cannot find a script term in any
available dictionary, or cannot display data in its
native format.
real A number that can include a decimal fraction;
see the real class.
record An unordered collection of properties,
identified by unique labels; see the record class.
248
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
G L O S S A R Y
recordable application An application that uses
Apple events to report user actions for recording
purposes. When recording is turned on, Script Editor
creates statements corresponding to any significant
actions you perform in a recordable application.
recursive handler A handler that calls itself.
reference An object that encapsulates an object
specifier.
reference form The syntax for identifying an object
or group of objects in an application or other
containerthat is, the syntax for constructing an
object specifier.AppleScript defines reference forms
for arbitrary, every, filter, ID, index, middle, name,
property, range, and relative.
relative object specifier An object specifier that
does not include enough information to identify an
object or objects uniquely. When AppleScript
encounters a partial object specifier, it uses the default
object specified in the enclosing tell statement to
complete the reference. See absolute object specifier.
relative reference form A reference form that
specifies an object or location by describing its
position in relation to another object, known as the
base, in the same container.
repeat statement A control statement that contains
a series of statements to be repeated and, in most
cases, instructions that specify when the repetition
stops.
required parameter A parameter that must be
included for a command to be successful.
reservedword A word that is part of the AppleScript
language. Synonymous with keyword.
result A value generated when a command is
executed or an expression evaluated.
return statement A statement that exits a handler
and optionally returns a specified value.
scope The range over which AppleScript recognizes
a variable or property, which determines where else
in a script you may refer to that variable or property.
script A series of written instructions that, when
executed, cause actions in applications or Mac OS X.
scriptable application An application 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.
script application An application whose only
function is to run the script associated with it.
script editor An application used to create and
modify scripts.
Script Editor The script-editing application
distributed with AppleScript.
scripting addition A file that provides additional
commands or coercions you can use in scripts. If a
scripting addition is located in the Scripting Additions
folder, its terminology is available for use by any
script.
scripting addition command A command that is
implemented as a scripting addition.
script object 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 object definition A compound statement that
contains a collection of properties, handlers, and other
AppleScript statements.
simple statement One that can be written on a single
line. See also compound statement.
simple value A value, such as an integer or a
constant, that does not contain other values.
Standard suite A set of standard AppleScript
terminology that a scriptable application should
support if possible. The Standard suite contains
commands such as count, delete, duplicate, and
make, and classes such as application, document,
and window.
statement A series of lexical elements that follows
a particular AppleScript syntax. Statements can
include keywords, variables, operators, constants,
expressions, and so on. See also compoundstatement,
simple statement.
249
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
G L O S S A R Y
statement block One or more statements enclosed
in a compound statement and having an end
statement.
string A synonym for the text class.
styled text Text that may include style and font
information. Not supported in AppleScript 2.0.
suite Within an application's scriptability information,
a grouping of terms associated with related
operations.
synonym An AppleScript word, phrase, or language
element that has the same meaning as another
AppleScript word, phrase, or language element. For
example, the operator does not equalis a synonym
for .
syntax The arrangement of words in an AppleScript
statement.
syntax description The rules for constructing a valid
AppleScript statement of a particular type.
system object An object that is part of a scriptable
element of Mac OS X.
target The recipient of a command. Potential targets
include application objects, script objects
(including the current script), and the current
application.
tell statement A control statement that specifies
the default target for the statements it contains.
test A Boolean expression that specifies the
conditions of a filter or an if statement.
text An ordered series of characters (a text string);
see the text class.
try statement 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 cause an error.
unary operator An operator that derives a new value
from a single value.
Unicode An international standard that uses a 16-bit
encoding to uniquely specify the characters and
symbols for all commonly used languages.
Unicode code point A unique number that
represents a character and allows it to be represented
in an abstract way, independent of how it is rendered.
Unicode text A class that represents an ordered
series of two-byte Unicode characters.
user-defined command A command that is
implemented by a handler defined in a scriptobject.
using terms from statement A control statement
that instructs AppleScript to use the terminology from
the specified application in compiling the enclosed
statements.
variable A named container in which to store a
value.
with timeout statement A control statement that
specifies the amount of time AppleScript waits for
application commands to complete before stopping
execution of the script.
with transaction statement A control statement
that allows you to take advantage of applications that
support the notion of a transactiona sequence of
related events that should be performed as if they
were a single operation, such that either all of the
changes are applied or none are.
250
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
G L O S S A R Y
This table describes the changes to AppleScript Language Guide.
Notes Date
Updated to describe AppleScript features through Mac OS X v10.5 and
AppleScript 2.0.
2008-03-11
The previous release of AppleScript Language Guide was on May 5, 1999.
251
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
R E V I S I O N H I S T O R Y
Document Revision History
252
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
R E V I S I O N H I S T O R Y
Document Revision History
Symbols
* operator 183
+ operator 184
/ operator 184
= operator 180
> operator 180
>= operator 181
\ character 100
^ operator 185
{} characters 89
| in identifiers 18
| in syntax definitions 15
characters 241242
character 20
operator 184
operator 184
operator 180
operator 181
operator 181
A
a reference to operator 31, 95, 185, 188
about handler parameter label 215
above handler parameter label 215
absolute object specifiers 30
activate command 108
adding folder items to Folder Actions handler 222
addition operator 184
addition
of date values 86
administrator privileges parameter
of command do shell script 129
after reserved word 176
against handler parameter label 215
alert volume parameter
of command set volume 158
alias class 79
alias
specifying a file by 41
aliases and files 4143
aliases
working with 42
altering line endings parameter
of command do shell script 129
& (concatenation) operator 187
& operator 180
& operator 187
and operator 179
angle brackets in scripts 241242
apart from handler parameter label 215
Apple event code 24
Apple events 13
AppleScript character set (Unicode) 17
AppleScript constant 37
AppleScript 37
current application 39
AppleScript global constants 37
AppleScript property
missing value 40
pi constant 37
result 38
text constants 38
text item delimiters 38
version 39
AppleScript suite 105
AppleScript
commands 35
constants 37
defined 13
error numbers 233, 234
fundamentals 2546
keywords 18, 227231
lexical conventions 1724
script objects 5765
unsupported terms 243
variables and properties 4756
application class 80
application commands 35
application object 34
applications
253
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
Index
remote 44
arbitrary reference form 167
arithmetic, date-time 86
around handler parameter label 215
as operator 32, 185
as parameter
of command choose application 111
of command display alert 124
of command do shell script 129
of command get 130
of command path to (application) 142
of command path to (folder) 145
of command read 149
of command the clipboard 163
of command write 165
as user name parameter
of command mount volume 139
ASCII character command 108
ASCII number command 109
aside from handler parameter label 215
assignment statement 22
associativity, of operators 185
at handler parameter label 215
B
back of reserved words 176
back reserved word 172, 177
backslash character in text 100
beep command 110
before parameter
of command read 148
before reserved word 176
beginning reserved word 177
begins with operator 182
behind reserved word 176
below handler parameter label 215
beneath handler parameter label 215
beside handler parameter label 215
between handler parameter label 215
binary operator 179
Bonjour
and remote applications 44, 118
service types 119
boolean class 82
Boolean constants 20, 40, 83
boolean expressions 197
brackets 15
but keyword 193
buttons parameter
of command display alert 124
of command display dialog 126
by handler parameter label 215
C
cancel button name parameter
of command choose from list 117
cancel button parameter
of command display alert 125
of command display dialog 126
case attribute 194
character element 99
character
elements of a text object 99
chevrons 24, 241
child script objects 61
choose application command 110
choose color command 111
choose file command 112
choose file name command 114
choose folder command 115
choose from list command 116
choose remote application command 118
choose URL command 119
class class 83
class property 79, 80, 82, 84, 85, 89, 90, 92, 93, 94, 97,
98, 103
class
defined 79
reference 79104
classes
mutable 49
Clipboard Commands suite 105
clipboard info command 120
close access command 120
closing folder window for Folder Actions handler
223
coercion operator (as) 185
coercion
see object conversion 32
comes after operator 180
comes before operator 181
commands
AppleScript 35
application 35
defined 105
direct parameter of 36
reference 105165
scripting addition 35
target of 35
user-defined 35
waiting for completion of 211
comments 19
254
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
block 19
end-of-line 19
completion
of commands 211
compound statements 23
concatenation operator (&) 180, 187
considering / ignoring (application
responses) control statement 195
considering / ignoring (text comparison)
control statement 193
considering and ignoring statements 193
considering statements (application responses) 195
considering statements (string comparison) 193
constant class 84
constant
defined 20
constants
AppleScript 37
Boolean 20, 40, 83
days of the week 86
months of the year 86
text 100
white space 100
constructor functions 59
containers 30
contains operator 182, 189
contains, is contained by operator 189
contents property 31, 96
continue statement
defined 213
in script objects 63
control statements reference 193212
conventions in this book 15
copy command 121
count command 122
current application and parent property 39
current application constant 39
current date command 123
current script 40
current target 40
D
date class 85
date string property 86
date, relative 88
date-time arithmetic 86
day property 86
days of the week constants 86
debugging tips 45
flow of control 45
log statements 46
third party debuggers 46
default answer parameter
of command display dialog 126
default button parameter
of command display alert 125
of command display dialog 126
default color parameter
of command choose color 112
default items parameter
of command choose from list 117
default location parameter
of command choose file 113
of command choose file name 114
of command choose folder 115
default name parameter
of command choose file name 114
delay command 123
delegation 63
diacriticals attribute 194
dictionary
defined 25
displaying 25
when not available 241
direct parameter of commands 36
display alert command 124
display dialog command 125
displaying parameter
of command say 153
div operator 184
division operator () 184
do shell script command 128
does not come after operator 181
does not come before operator 181
does not contain operator 183
does not equal operator 180
double angle brackets 241242
double-quote character 100
E
editable URL parameter
of command choose URL 119
eighth reserved word 172
elements of objects 28
ellipsis in syntax definitions 15
else clause 199
else if clause 199
empty list 89
empty selection allowed parameter
of command choose from list 117
enabling remote applications 44
end reserved word 177
255
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
ends with operator 182, 192
eppc-style specifier 44
equal operator 190
equal, is not equal to operator 190
equals operator 180
error control statement 196
error numbers
AppleScript 233, 234
defined 196
error reporting parameter
of command open location 141
error
expression 196
handlers 207
handling 36
message 196
user cancelled 37
errors
resignaling in scripts 237
signaling in scripts 196
types of 37
working with 237239
evaluation
defined 22
of expressions 22
Event Log History window 209
event timed out error message 211
every reference form 168
every reserved word 168
exit control statement 199
exit from repeat loop 199
explicit run handlers 74
exponent operator (^) 185
expressions 22
boolean 197
evaluation of 22
F
false constant 40, 83
fifth reserved word 172
file class 88
File Commands suite 105
File Read/Write suite 106
files and aliases 4143
files, specifying
by alias 41
by name 43
by pathname 43
filter reference form 169
first reserved word 172
Folder Actions reference 221225
folder creation parameter
of command path to (folder) 145
for handler parameter label 215
for parameter
of command clipboard info 120
of command read 148
of command write 164
fourth reserved word 172
from handler parameter label 215
from parameter
of command path to (folder) 145
of command random number 146
of command read 148
from reserved word 175
from table parameter
of command localized string 136
front of reserved words 176
front reserved word 172, 177
frontmost property 80
G
get command 129
get eof command 131
get volume settings command 131
given handler parameter label 215
giving up after parameter
of command display alert 125
of command display dialog 127
global constants
of AppleScript 37
global variables 49, 52
persistence of 53
scope of 51
greater than operator 180, 191
greater than or equal to operator 181
greater than, less than operator 191
H
handle CGI request (unsupported) 243
handlers
call syntax
labeled parameters 216
positional parameters 218
calling from a tell statement 72
defined 67
defining simple 68
defining syntax
labeled parameters 215
256
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
no parameters 68
positional parameters 218
errors in 71
for errors 207
for stay-open script applications 7677
idle 76
in script applications 73
libraries of 72
open 75
overview 6777
quit 76
recursive 71
reference 213219
run 74
scope of identifiers declared within 55
has parameter
of command system attribute 161
hidden answer parameter
of command display dialog 126
hyphens attribute 194
I
id property 80, 98
ID reference form 171
id reserved word 171
identifiers 18
idle handlers 76
if (compound) control statement 198
if (simple) control statement 198
ignoring statements (application responses) 195
ignoring statements (string comparison) 193
implicit run handlers 74
implicitly specified subcontainers 29
in AppleTalk zone parameter
of command mount volume 139
in back of reserved words 176
in bundle parameter
of command localized string 136
of command path to resource 146
in directory parameter
of command path to resource 146
in front of reserved words 176
in parameter
of command offset 139
of command run script 152
of command store script 159
of command summarize 160
in
for specifying a container 30
with date objects 88
index reference form 172
index reserved word 172
info for command 132
inheritance 6065
examples of 61
initializing script objects 59
input volume parameter
of command set volume 158
insertion point 36
insertion point object
and index reference form 177
and relative reference form 176
instead of handler parameter label 215
integer class 89
integral division operator 184
internet address (unsupported) 243
Internet suite 106
into handler parameter label 215
invisibles parameter
of command choose file 113
of command choose folder 115
of command list folder 135
is contained by operator 183, 189
is equal to operator 180
is not contained by operator 183
is not equal to operator 190
is not greater than operator 181
is not less than operator 181
is not operator 180
is operator 180
it keyword 40
item element 90
items 89, 96
its reserved word 40
K
keywords, AppleScript 18, 227
L
labeled parameters, of handlers 68
language elements in syntax definitions 15
large lists
inserting in 91
last reserved word 172
launch command 134
length property 90, 94, 98
less than operator 181, 191
less than or equal to operator 181
libraries of handlers 72
257
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
lifetime of variables and properties 51
linefeed constant 100
list class 89
list disks command 134
list folder command 135
lists
inserting in large 91
merging 91
literal expressions 20
load script command 72, 135
local variables 48, 52, 59
scope of 51
localized string command 136
location parameters 36
log command 138
log statements 46
loop variable 202, 203
lowercase letters 194
< operator 181
<= operator 181
M
me keyword 40
merging lists 91
message parameter
of command display alert 124
middle reference form 173
middle reserved word 173
minus symbol () 184
Miscellaneous Commands suite 106
missing value constant 40
mod operator 184
month property 86
months of the year constants 86
mount volume command 138
moving folder window for Folder Actions handler
223
multiple selections allowed parameter
of command choose application 111
of command choose file 113
of command choose folder 115
of command choose from list 117
multiplication operator (*) 183
mutable classes 49
my reserved word 64
my
in tell statements 72
N
name property 80
name reference form 173
name
specifying a file by 43
named reserved word 174
nested tell statements 205
examples 206
ninth reserved word 172
not operator 185
number class 92
numeric literal 21
O
object conversion (coercion) 32
object conversion
table of supported conversions 32
object specifiers 22, 29
absolute 30
contents of 29
evaluating with contents property 31
implicitly specified subcontainers 29
in reference objects 31
relative 30
objects
elements of 28
properties of 28
script
initializing 59
parent 6165
sending commands to 59
using in AppleScript 26
of me
in tell statements 72
of my keyword 40
of parameter
of command offset 139
of type parameter
of command choose file 113
of
for specifying a container 30
with date objects 88
offset command 139
OK button name parameter
of command choose from list 117
on handler parameter label 215
on server parameter
of command mount volume 138
onto handler parameter label 215
open for access command 140
258
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
open handlers 75
open location command 141
opening folder Folder Actions handler 224
operators
binary 179
defined 179
listed, with descriptions 179185
precedence 185
reference 179192
unary 179
or operator 179
out of handler parameter label 215
output muted parameter
of command set volume 158
output volume parameter
of command set volume 157
over handler parameter label 215
P
paragraph element 99
parameter variables 59, 213
parameters
direct 36
in continue statements 213
labeled 68
location 36
passing by reference versus value 71
patterned 70
positional 69
parent property 61
parent script objects 6165
password parameter
of command do shell script 129
path to (application) command 142
path to (folder) command 143
path to resource command 145
pathname
specifying a file by 43
paths, specifying a file with 42
patterned parameters 70
persistence
of global variables 53
of script properties 53
pi constant 37
placeholders in syntax definitions 15
plural object names 168
plus symbol (+) 184
positional parameters, of handlers 69
POSIX file class 93
POSIX files
using with files and aliases 3643
POSIX path property 79
possessive notation ('s) 30
possessive object names 30
precedence
of attributes 195
of operations 185
properties
declaring 47
lifetime of 51
of objects 28
of script objects 58
scope of 51
property reference form 174
punctuation attribute 194
put, (Deprecated--use copy) 230
Q
quit handlers 76
" character 100
quoted form property 98
R
random number command 146
range reference form 175
raw apple events 242
raw data
displayed by AppleScript 241
entering in a script 242
raw format 241
read command 147
real class 93
record class 94
recursion 71
recursive handlers 71
reference class 95
reference forms 167177
arbitrary 167
defined 167
every 168
filter 169
ID 171
index 172
middle 173
name 173
property 174
range 175
relative 176
relative object specifiers 30
259
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
relative reference form 176
relative to
with date objects 88
remainder operator 184
remote applications 44
choosing 118
enabling 44
targeting 44
removing folder items fromFolder Actions handler
225
reopen command 134
repeat (forever) control statement 199
repeat (number) times control statement 200
repeat control statements 199
repeat until control statement 201
repeat while control statement 202
repeat with loopVariable (from startValue to
stopValue) control statement 202
repeat with loopVariable (in list) control
statement 203
replacing parameter
of command store script 159
reserved words (see keywords) 227
rest of property 90
rest property 90
Result pane 24, 38
result property 38
result variable 24
result, of statement 24
return character
in text objects 101
return constant 100
return statement 214
in handler definition 67
returning, Deprecated reserved word 230
reverse property 90
RGB color class 96
round command 149
rounding parameter
of command round 150
run command 151
run handlers 74
explicit 74
implicit 74
in script objects 58, 60
run script command 152
running property 81
runTarget parameter
of command run 151
S
saving to parameter
of command say 153
say command 153
scope
of variables and properties 51
shadowing 52, 61
script applications 73
calling 77
handlers for 73
Mac OS 9 compatible 73
modern bundle format 73
startup screen in 73
stay-open 73
script class 97
Script Editor
Event Log History window 46, 209
location in system 25
overview 25
script objects 5765
child 61
contents of 27
defined 57
initializing 59
parent 6165
scope of identifiers declared at top level of 52
sending commands to 59
syntax of 57
script properties
persistence of 53
scope of 51
script, current 40
scripting addition
command 35
overview 34
scripting components command 154
Scripting suite 106
second reserved word 172
set command 154
set eof command 156
set the clipboard to command 156
set volume command 157
seventh reserved word 172
short-circuiting, during evaluation 179
showing package contents parameter
of command choose file 113
of command choose folder 115
showing parameter
of command choose URL 119
simple statements 23
since handler parameter label 215
sixth reserved word 172
260
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
size parameter
of command info for 132
slash symbol (/) 184
some reserved word 167
space constant 100
special characters
in identifiers 18
in text 100
Standard suite 107
starting at parameter
of command write 164
starts with operator 182, 192
starts with, ends with operator 192
startup screen in script applications 73
statements 23
compound 23
simple 23
stay-open script applications 73
store script command 158
storing values in variables 22
string class 102
String Commands suite 107
subtraction of date values 86
subtraction operator () 184
suites
AppleScript 105
Clipboard Commands 105
File Commands 105
File Read/Write 106
Internet 106
Miscellaneous Commands 106
Scripting 106
Standard 107
String Commands 107
User Interaction 107
summarize command 159
synonyms for whose 169
system attribute command 160
system info command 161
T
tab character
in text objects 101
tab constant 100
target, current 40
target
of commands 35
targeting remote applications 44
tell (compound) control statement 206
tell (simple) control statement 206
tell statements 36, 205
nested 205
nested, examples of 206
tenth reserved word 172
terminating
handler execution 214
repeat statement execution 199
test
Boolean 197
in filter reference form 169
text class 97
text element 99
text item delimiters
AppleScript property 38
text literal 21
text
as replacement for string 97
constants 38, 100
special characters in 100
that reserved word 169
the clipboard command 163
the reserved word (syntactic no-op) 230
then reserved word 198
third reserved word 172
through handler parameter label 215
through reserved word 175
thru handler parameter label 215
thru reserved word 175
time property 86
time string property 86
time to GMT command 163
timeout, default value 210
times reserved word 201
to parameter
of command copy 121
of command random number 146
of command read 148
of command set 154
of command set eof 156
of command write 164
transaction reserved word 211
true constant 40, 83
try control statement 207
try statements 207
U
unary operators 179
under handler parameter label 215
Unicode text class 102
unit types class 103
Unix executable
making script into 19
261
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X
unsupported terms 243
until parameter
of command read 148
uppercase letters 194
user cancelled error 37
User Interaction suite 107
user name parameter
of command do shell script 129
user-defined commands 35
using delimiter parameter
of command read 148
using delimiters parameter
of command read 148
using parameter
of command say 153
using terms from control statement 209
V
variables 22
declaring 48
declaring with copy command 50
declaring with set command 49
defined 22
global 49, 51, 52
lifetime of 51
local 48, 51, 52, 59
scope of 51
version property 39, 81
vertical bar character (|) in identifiers 18
vertical bars (|)
in syntax definitions 15
W
waiting until completion parameter
of command say 153
web page (unsupported) 243
weekday property 86
where reserved word 169
while reserved word 202
white space attribute 194
white space constants 100
whose reserved word 169
whose
synonyms for 169
with clause 217
with icon parameter
of command display dialog 127
with parameters parameter
of command run script 152
with password parameter
of command mount volume 139
with prompt parameter
of command choose application 111
of command choose file 112
of command choose file name 114
of command choose folder 115
of command choose from list 117
of command choose remote application 118
with seed parameter
of command random number 147
with timeout control statement 210
with timeout statements 210, 211
with title parameter
of command choose application 111
of command choose from list 117
of command choose remote application 118
of command display dialog 127
with transaction control statement 211
without clause 217
word element 99
working with errors 237
write command 164
write permission parameter
of command open for access 140
Y
year property 86
262
2008-03-11 | 2008 Apple Inc. All Rights Reserved.
I N D E X