Apple Script Language Guide
Apple Script Language Guide
English Dialect
Contents
Figures and Tables
Preface
xiii
xv
Audience
xv
Organization of This Guide
xvi
Sample Applications and Scripts
xvii
For More Information
xviii
Getting Started
xviii
Scripting Additions
xviii
Other AppleScript Dialects
xviii
Scriptable Applications
xviii
Conventions Used in This Guide
xix
Part 1
Introducing AppleScript
Chapter 1
What Is AppleScript?
3
What Can You Do With Scripts?
5
Automating Activities
5
Integrating Applications
7
Customizing Applications
7
Who Runs Scripts, and Who Writes Them?
Special Features of AppleScript
10
What Applications Are Scriptable?
11
iii
Chapter 2
Overview of AppleScript
13
Part 2
Chapter 3
Values
33
iv
33
31
Chapter 4
Commands
38
71
Types of Commands
71
Application Commands
72
AppleScript Commands
73
Scripting Addition Commands
74
User-Defined Commands
76
Using Command Definitions
77
Syntax
78
Parameters
78
Result
79
Examples
79
Errors
79
Using Parameters
80
Parameters That Specify Locations
80
Coercion of Parameters
81
Raw Data in Parameters
81
Using Results
82
Double Angle Brackets in Results and Scripts
83
Command Definitions
Close
87
Copy
88
Count
92
Data Size
97
Delete
98
Duplicate
99
Exists
99
Get
100
Launch
103
Make
105
Move
106
Open
107
Print
108
Quit
109
Run
110
Save
112
Set
113
Chapter 5
84
119
vi
Name
134
Property
135
Range
136
Relative
139
Using the Filter Reference Form
140
References to Files and Applications
143
References to Files
144
References to Applications
146
References to Local Applications
147
References to Remote Applications
148
Chapter 6
Expressions
149
Results of Expressions
149
Variables
150
Creating Variables
150
Using Variables
152
The A Reference To Operator
153
Data Sharing
154
Scope of Variables
155
Predefined Variables
156
Script Properties
156
Defining Script Properties
157
Using Script Properties
157
Scope of Script Properties
158
AppleScript Properties
158
Text Item Delimiters
158
Reference Expressions
160
Operations
161
Operators That Handle Operands of Various Classes
Equal, Is Not Equal To
168
Greater Than, Less Than
172
Starts With, Ends With
173
Contains, Is Contained By
175
Concatenation
177
Operator Precedence
178
Date-Time Arithmetic
180
168
vii
Chapter 7
Control Statements
183
Chapter 8
Handlers
221
Using Subroutines
221
Types of Subroutines
223
Scope of Subroutine Calls in Tell Statements
224
Checking the Classes of Subroutine Parameters
225
viii
201
Recursive Subroutines
225
Saving and Loading Libraries of Subroutines
226
Subroutine Definitions and Calls
228
Subroutines With Labeled Parameters
229
Subroutine Definition, Labeled Parameters
229
Subroutine Call, Labeled Parameters
230
Examples of Subroutines With Labeled Parameters
232
Subroutines With Positional Parameters
235
Subroutine Definition, Positional Parameters
235
Subroutine Call, Positional Parameters
236
Examples of Subroutines With Positional Parameters
238
The Return Statement
239
Return
240
Command Handlers
241
Command Handler Definition
241
Command Handlers for Script Applications
243
Run Handlers
243
Open Handlers
246
Handlers for Stay-Open Script Applications
247
Idle Handlers
248
Quit Handlers
249
Interrupting a Script Applications Handlers
250
Calling a Script Application
251
Scope of Script Variables and Properties
252
Scope of Properties and Variables Declared at the Top Level
of a Script
254
Scope of Properties and Variables Declared in a Script Object
258
Scope of Variables Declared in a Handler
263
Chapter 9
Script Objects
265
268
ix
Defining Inheritance
271
How Inheritance Works
272
The Continue Statement
277
Using Continue Statements to Pass Commands to Applications
The Parent Property and the Current Application
281
Using the Copy and Set Commands With Script Objects
283
289
Commands
289
References
294
Operators
296
Control Statements
299
Handlers
301
Script Objects
303
Variable and Property Assignments and Declarations
Predefined Variables
304
Constants
305
Placeholders
307
313
303
314
280
Text Item
339
Text Style Info
341
Window
342
Word
342
Scriptable Text Editor Commands
Copy
347
Cut
348
Data Size
349
Duplicate
349
Make
350
Move
351
Open
351
Paste
351
Revert
352
Save
353
Select
354
Scriptable Text Editor Errors
355
345
357
Glossary
Index
363
371
xi
Chapter 2
Overview of AppleScript
Figure 2-1
Figure 2-2
Chapter 3
Chapter 4
Chapter 5
Values
13
20
33
Figure 3-1
Figure 3-2
Table 3-1
Commands
69
39
71
Figure 4-1
Figure 4-2
Table 4-1
Table 4-2
77
95
85
119
Figure 5-2
Table 5-1
Table 5-2
Reference forms
126
Boolean expressions and tests in Filter references
142
xiii
Chapter 6
Chapter 8
Expressions
149
Table 6-1
Table 6-2
AppleScript operators
Operator precedence
Handlers
221
Figure 8-1
Figure 8-2
Figure 8-3
Chapter 9
Script Objects
Figure 9-1
Figure 9-2
Figure 9-3
Appendix A
Appendix B
265
Relationship between a simple child script and its parent
Another child-parent relationship
273
A more complicated child-parent relationship
274
273
289
Command syntax
290
Reference form syntax
294
Container notation in references
296
Operators
297
Control statements
300
Handler definitions and calls
302
Script objects
303
Assignments and declarations
304
Predefined variables
305
Constants defined by AppleScript
305
Placeholders used in syntax descriptions
308
313
Figure B-1
Table B-1
Table B-2
xiv
163
179
P R E F A C E
Audience
This guide is for anyone who wants to write new scripts or modify
existing scripts.
Before using this guide, you should read Getting Started With AppleScript to
learn what hardware and software you need to use AppleScript; how to install
AppleScript; and how to run, record, and edit scripts.
To make best use of this guide, you should already be familiar with at least one
of the following:
If youre not already familiar with the basics of scripting and programming
(such as variables, subroutines, and conditional statements such as If-Then),
you may want additional information to help you get started. You can find a
variety of introductory books on scripting and programmingincluding books
specifically about AppleScriptin many bookstores.
Macintosh software developers who want to create scriptable and recordable
applications should refer to Inside Macintosh: Interapplication Communication.
xv
P R E F A C E
xvi
Chapter 3, Values, describes the classes of data that can be stored and
manipulated in scripts and the coercions you can use to change a value
from one class to another.
Chapter 4, Commands, describes the types of commands available in
AppleScript, including application commands, AppleScript commands,
scripting addition commands, and user-defined commands. It also includes
descriptions of all AppleScript commands and standard application
commands.
Chapter 5, Objects and References, describes objects and their
characteristics and explains how to refer to objects in scripts.
Chapter 6, Expressions, describes types of expressions in AppleScript,
how AppleScript evaluates expressions, and operators you use to
manipulate values.
P R E F A C E
At the end of the guide are three appendixes, a glossary of AppleScript terms,
and an index.
xvii
P R E F A C E
Getting Started
See the companion book Getting Started With AppleScript to learn what
hardware and software you need to use AppleScript; how to install
AppleScript; and how to run, record, and edit scripts.
Scripting Additions
Scripting additions are files that provide additional commands you can use in
scripts. A standard set of scripting additions comes with AppleScript. Scripting
additions are also sold commercially, included with applications, and
distributed through electronic bulletin boards and user groups.
For information about using the scripting additions that come with AppleScript,
see the companion book AppleScript Scripting Additions Guide: English Dialect.
Scriptable Applications
Not all applications are scriptable. The advertising and packaging for an
application usually mention if it is scriptable. The documentation for a
scriptable application typically lists the AppleScript words that the application
understands.
xviii
P R E F A C E
[optional]
(a group)
[optional]...
(a group). . .
a|b|c
xix
P A R T
O N E
Introducing AppleScript
C H A P T E R
Figure 1-0
Listing 1-0
Table 1-0
What is AppleScript?
What Is AppleScript?
What Is AppleScript?
C H A P T E R
Figure 1-1
What Is AppleScript?
C H A P T E R
The script shown at the bottom of Figure 1-1 is written in AppleScript English,
which is a dialect of the AppleScript scripting language that resembles English.
This guide describes AppleScript English and how you can use it to write
scripts. Other dialects, such as AppleScript Japanese and AppleScript French,
are designed to resemble other human languages. Still others, such as the
Programmers Dialect, resemble other programming languages. For information about dialects other than AppleScript English, see the guide for the dialect
you want to use. For information about installing dialects, see Getting Started
With AppleScript.
All AppleScript dialects share many features with other scripting, programming,
and macro languages. If youve used any of these languages, youll find
AppleScript dialects very easy to learn and use.
AppleScript comes with an application called Script Editor that you can use to
create and modify scripts. You can also use Script Editor to translate scripts
from one AppleScript dialect to another.
Automating Activities
Scripts make it easy to perform repetitive tasks. For example, if you want
to change the style of the word AppleScript to bold throughout a document
named Introduction, you can write a script that does the job instead of
searching for each occurrence of the word, selecting it, and changing it from
the Style menu.
Figure 1-2 shows the script and what happens when you run it.
C H A P T E R
Figure 1-2
C H A P T E R
Integrating Applications
Scripts are ideal for performing tasks that involve more than one application.
A script can send instructions to one application, get the resulting data, and
then pass the data on to one or more additional applications. For example, a
script can collect information from a database application and copy it to a
spreadsheet application. Figure 1-3 shows a simple script that gets a value
from the Count cell of an inventory database and copies it to the Inventory
column of a spreadsheet.
In the same way, a script can use one application to perform an action on data
from another application. For example, suppose a word-processing application
includes a spelling checker and also supports an AppleScript command to
check spelling. You can check the spelling of a block of text from any other
application by writing a script that sends the AppleScript command and the
text to be checked to the word-processing application, which returns the results
to the application that runs the script.
If an action performed by an application can be controlled by a script, that
action can be also performed from the Script Editor or from any other
application that can run scripts. Every scriptable application is potentially a
toolkit of useful utilities that can be selectively combined with utilities from
other scriptable applications to perform highly specialized tasks.
Customizing Applications
C H A P T E R
Figure 1-3
C H A P T E R
Figure 1-4
If the script is a script application on the desktop, you can run it by doubleclicking its icon. You can also run any script by clicking the Run button in the
Script Editor window for that script.
C H A P T E R
Although everyone can run scripts, not everyone needs to write them. One
person who is familiar with a scripting language can create sophisticated
scripts that many people can use. For example, management information
specialists in a business can write scripts for everyone in the business to use.
Scripts are also sold commercially, included with applications, and distributed
through electronic bulletin boards and user groups.
AppleScript has a number of features that set it apart from both macro
programs and scripting languages that control a single program:
10
C H A P T E R
11
C H A P T E R
Figure 2-0
Listing 2-0
Table 2-0
Overview of AppleScript
13
C H A P T E R
Overview of AppleScript
Statements
Every script is a series of statements. Statements are structures similar to
sentences in human languages that contain instructions for AppleScript to
perform. When AppleScript runs a script, it reads the statements in order and
carries out their instructions. Some statements cause AppleScript to skip or
repeat certain instructions or change the way it performs certain tasks. These
statements, which are described in Chapter 7, are called control statements.
14
C H A P T E R
Overview of AppleScript
Figure 2-1
Script Editor
Writes, records, and runs scripts
1
4
Application
Responds to Apple events by performing actions
Sends Apple events to AppleScript extension
AppleScript
statements
(results)
AppleScript extension
Interprets script statements and
sends corresponding Apple events
Interprets Apple events and sends
results back to the Script Editor
3
Apple events
(results)
2
Apple events
(requests for action)
Statements
15
C H A P T E R
Overview of AppleScript
All statements, including control statements, fall into one of two categories:
simple statements or compound statements. Simple statements are statements
such as the following that are written on a single line.
tell application "Scriptable Text Editor" to print the front window
Compound statements are statements that are written on more than one line
and contain other statements. All compound statements have two things in
common: they can contain any number of statements, and they have the word
end (followed, optionally, by the first word of the statement) as their last line.
The simple statement of the first example in this section is equivalent to the
following compound statement.
tell application "Scriptable Text Editor"
print the front window
end tell
The compound Tell statement includes the lines tell application
"Scriptable Text Editor" and end tell, and all statements between
these two lines.
A compound statement can contain any number of statements. For example,
here is a Tell statement that contains two statements:
tell application "Scriptable Text Editor"
print front window
close front window
end tell
This example illustrates the advantage of using a compound Tell statement:
you can add additional statements within a compound statement.
Note
16
Statements
C H A P T E R
Overview of AppleScript
17
C H A P T E R
Overview of AppleScript
Dictionaries
To examine a definition of an object class, a command, or some other word
supported by an application, you can open that applications dictionary from
the Script Editor. A dictionary is a set of definitions for words that are
understood by a particular application. Unlike other scripting languages,
18
Dictionaries
C H A P T E R
Overview of AppleScript
AppleScript does not have a single fixed set of definitions for use with all
applications. Instead, when you write scripts in AppleScript, you use both
definitions provided by AppleScript and definitions provided by individual
applications to suit their capabilities.
Dictionaries tell you which objects are available in a particular application and
which commands you can use to control them. Typically, the documentation
for a scriptable application includes a complete list of the words in its
dictionary. For example, Appendix B of this book contains a complete list of the
words in the Scriptable Text Editor dictionary. In addition, if you are using the
Script Editor, you can view the list of commands and objects for a particular
application in a Dictionary window. For more information, see Getting Started
With AppleScript.
To use the words from an applications dictionary in a script, you must indicate
which application you want to manipulate. You can do this with a Tell
statement that lists the name of the application:
tell application "Scriptable Text Editor"
print front window
close front window
end tell
AppleScript reads the words in the applications dictionary at the beginning
of the Tell statement and uses them to interpret the statements in the Tell
statement. For example, AppleScript uses the words in the Scriptable Text
Editor dictionary to interpret the Print and Close commands in the Tell
statement shown in the example.
Another way to use an applications dictionary is to specify the application
name completely in a simple statement:
print front window of application "Scriptable Text Editor"
In this case, AppleScript uses the words in the Scriptable Text Editor dictionary
to interpret the words in this statement only.
When you use a Tell statement or specify an application name completely in
a statement, the AppleScript extension gets the dictionary resource for the
application and reads its dictionary of commands, objects, and other words.
Every scriptable application has a dictionary resource that defines the
commands, objects, and other words script writers can use in scripts to control
Dictionaries
19
C H A P T E R
Overview of AppleScript
the application. Figure 2-2 shows how AppleScript gets the words in the
Scriptable Text Editors dictionary.
Figure 2-2
Dictionary
resource
AppleScript
extension
Commands:
cut
make
print
...
Objects:
character
paragraph
window
...
Dictionary of
commands
and objects
Values
2
A value is a simple data structure that can be represented, stored, and
manipulated within AppleScript. AppleScript recognizes many types of values,
including character strings, real numbers, integers, lists, and dates. Values are
fundamentally different from application objects, which can be manipulated
from AppleScript, but are contained in applications or their documents. Values
can be created in scripts or returned as results of commands sent to applications.
20
Values
C H A P T E R
Overview of AppleScript
Expressions
Operations
2
The following are examples of AppleScript operations and their values. The
value of each operation is listed following the comment characters (--).
3 + 4
--value: 7
--value: false
Each operation contains an operator. The plus sign (+) in the first expression, as
well as the greater than symbol (>), the equal symbol (=) symbol, and the word
AND in the second expression, are operators. Operators transform values or
pairs of values into other values. Operators that operate on two values are
called binary operators. Operators that operate on a single value are known as
unary operators. Chapter 6, Expressions, contains a complete list of the
operators AppleScript supports and the rules for using them.
Expressions
21
C H A P T E R
Overview of AppleScript
Variables
2
When AppleScript encounters a variable in a script, it evaluates the variable by
getting its value. To create a variable, simply assign it a value:
copy "Mitch" to myName
The Copy command takes the datathe string "Mitch"and puts it in the
variable myName. You can accomplish the same thing with the Set command:
set myName to "Mitch"
Statements that assign values to variables are known as assignment statements.
You can retrieve the value in a variable with a Get command. Run the
following script and then display the result:
set myName to "Mitch"
get myName
You see that the value in myName is the value you stored with the Set command.
You can change the value of a variable by assigning it a new value. A variable
can hold only one value at a time. When you assign a new value to an existing
variable, you lose the old value. For example, the result of the Get command in
the following script is "Pegi".
set myName to "Mitch"
set myName to "Pegi"
get myName
22
Expressions
C H A P T E R
Overview of AppleScript
Script Objects
Script objects are objects you define and use in scripts. Like application objects,
script objects respond to commands and have specific information associated
with them. Unlike application objects, script objects are defined in scripts.
Script objects are an advanced feature of AppleScript. They allow you to use
object-oriented programming techniques to define new objects and commands.
Information contained in script objects can be saved and used by other scripts.
For information about defining and using script objects, see Chapter 9, Script
Objects. You should be familiar with the concepts in the rest of this guide
before attempting to use script objects.
Scripting Additions
Script Objects
23
C H A P T E R
Overview of AppleScript
Dialects
2
AppleScript scripts can be displayed in several different dialects, or representations of AppleScript that resemble human languages or programming
languages. The dialects available on a given computer are determined by the
Dialects folder, a folder in the Scripting Additions folder (which in turn is
located in the Extensions folder of the System Folder) that contains one dialect
file for each AppleScript dialect installed on your computer.
You can select any of the available dialects from the Script Editor. You can
tell which dialects are available by examining the pop-up menu in the lowerleft corner of a Script Editor window. You can change the dialect in which a
script is displayed by selecting a different dialect from the pop-up menu. The
behavior of a script when you run it is not affected by the dialect in which it
is displayed.
For more information about selecting dialects and formatting options from the
Script Editor, see Getting Started With AppleScript.
So far, youve been introduced to the key elements of the AppleScript language,
including statements, objects, commands, expressions, and script objects.
The reference section of this guide discusses these elements in more detail
and describes how to use them in scripts. Before you continue to the reference
section, however, youll need to know about a few additional elements
and features of the AppleScript scripting language that are not described in
the reference:
24
continuation characters
comments
identifiers
case sensitivity
abbreviations
compiling scripts
Dialects
C H A P T E R
Overview of AppleScript
Continuation Characters
25
C H A P T E R
Overview of AppleScript
Comments
2
To explain what a script does, you add comments. A comment is text that
remains in a script after compilation but is ignored by AppleScript when the
script is executed. There are two kinds of comments:
A block comment begins with the characters (* and ends with the
characters *). Block comments must be placed between other statements.
They cannot be embedded in simple statements.
An end-of-line comment begins with the characters -- and ends with the
end of the line.
You can nest comments, that is, comments can contain other comments.
Here are some sample comments:
--end-of-line comments extend to the end of the line;
(* Use block comments for comments that occupy
more than one line *)
copy result to theCount--stores the result in theCount
(* The following subroutine, findString, searches for a
string in a list of Scriptable Text Editor files *)
(* Here are examples of
--nested comments
(* another comment within a comment *)
*)
The following block comment causes an error because it is embedded in
a statement.
--the following block comment is illegal
tell application "Scriptable Text Editor"
get (* word 1 of *) paragraph 1 of front document
end tell
26
C H A P T E R
Overview of AppleScript
Because comments are not executed, you can prevent parts of scripts from
being executed by putting them within comments. You can use this trick,
known as commenting out, to isolate problems when debugging scripts or
temporarily block execution of any parts of script that arent yet finished.
Heres an example of commenting out an unfinished handler:
(*
on finish()
--under construction
end
*)
If you later remove (* and *), the handler is once again available.
Identifiers
2
An identifier is a series of characters that identifies a value or other language
element. For example, variable names are identifiers. In the following
statement, the variable name myName identifies the value "Fred".
set myName to "Fred"
Identifiers are also used as labels for properties and handlers. Youll learn
about these uses later in this guide.
An identifier must begin with a letter and can contain uppercase letters,
lowercase letters, numerals (09), and the underscore character (_). Here
are some examples of valid identifiers:
Yes
Agent99
Just_Do_It
The following are not valid identifiers:
C-Back&Forth
999
Why^Not
27
C H A P T E R
Overview of AppleScript
Identifiers whose first and last characters are vertical bars (|) can contain any
characters. For example, the following are legal identifiers:
|Back and Forth|
|Right*Now!|
Identifiers whose first and last characters are vertical bars can contain additional
vertical bars if the vertical bars are preceded by backslash (\) characters, as in
the identifier |This\|Or\|That|. A backslash character in an identifier must
be preceded by a backslash character, as in the identifier |/\\ Up \\/ Down|.
AppleScript identifiers are not case sensitive. For example, the variable
identifiers myvariable and MyVariable are equivalent.
Identifiers cannot be the same as any reserved wordsthat is, words in the
system dictionary or words in the dictionary of the application named in the
Tell statement. For example, you cannot create a variable whose identifier is
Yes within a Tell statement to the Scriptable Text Editor, because Yes is a
constant from the Scriptable Text Editor dictionary. In this case, AppleScript
returns a syntax error if you use Yes as a variable identifier.
Case Sensitivity
28
C H A P T E R
Overview of AppleScript
After you create the variable myName, you can refer to it by any of these names:
MYNAME
myname
MyName
mYName
When interpreting strings, such as "Pegi", AppleScript preserves the case of
the letters in the string, but does not use it in comparisons. For example, the
value of the variable myName defined earlier is always "Pegi", but the value
of the expression myName = "PEGI" is true.
Abbreviations
The AppleScript English dialect is designed to be intuitive and easy to understand. To this end, AppleScript English uses familiar words to represent objects
and commands and uses statements whose structure is similar to English
sentences. For the same reason, it typically uses real words instead of abbreviations. In a few cases, however, AppleScript supports abbreviations for long and
frequently used words.
One important example is the abbreviation app, which you can use to refer to
objects of class application. This is particularly useful in Tell statements. For
example, the following two Tell statements are equivalent:
tell application "Scriptable Text Editor"
print the front window
end tell
tell app "Scriptable Text Editor"
print the front window
end tell
29
C H A P T E R
Overview of AppleScript
30
P A R T
T W O
AppleScript Language
Reference
C H A P T E R
Figure 3-0
Listing 3-0
Table 3-0
Values
Values are data that can be represented, stored, and manipulated in scripts.
AppleScript recognizes many types of values, including character strings, real
numbers, integers, lists, and dates. Values are different from application
objects, which can also be manipulated from AppleScript but are contained in
applications or their documents.
Each value belongs to a value class, which is a category of values that are
represented in the same way and respond to the same operators. To find out
how to represent a particular value, or which operators it responds to, check its
value class definition. AppleScript can coerce a value of one class into a value
of another. The possible coercions depend on the class of the original value.
This chapter describes how to interpret value class definitions, discusses the
common characteristics of all value classes, and presents definitions of the
value classes supported in AppleScript. It also describes how to coerce values.
33
C H A P T E R
Values
Figure 3-1
List
A value of class List is an ordered collection of values. The values
contained in a list are known as items. Each item can belong to
any class.
LITERAL EXPRESSIONS
PROPERTIES
Class
Length
Rest
A list containing all items in the list except the first item.
Reverse
A list containing all items in the list, but in the opposite order.
Item
ELEMENTS
The operators that can have lists as operands are &, =, , Starts With, Ends
With, Contains, Is Contained By.
34
C H A P T E R
Values
Figure 3-1
35
C H A P T E R
Values
COMMANDS HANDLED
You can count the items in a list with the Count command. For example,
the value of the following statement is 6.
count {"a", "b", "c", 1, 2, 3}
--result: 6
You can also count elements of a specific class in a list. For example, the
value of the following statement is 3.
count integers in {"a", "b", "c", 1, 2, 3}
--result: 3
Another way to count the items in a list is with a Length property
reference:
length of {"a", "b", "c", 1, 2, 3}
--result: 6
REFERENCE FORMS
Use the following forms to refer to properties of lists and items in lists:
Property. For example, class of {"this", "is", "a", "list"}
specifies list.
Index. For example, item 3 of {"this", "is", "a", "list"}
specifies "a".
COERCIONS SUPPORTED
36
C H A P T E R
Values
Literal Expressions
Properties
3
A property of a value is a characteristic that is identified by a unique label and
has a single value. Simple values have only one property, called Class, that
identifies the class of the value. Composite values have a Class property, a
Length property, and in some cases additional properties.
Use the Name reference form to specify properties of values. For example, the
following reference specifies the Class property of an integer.
class of 101
--result: integer
The following reference specifies the Length property of a list.
length of {"This", "list", "has", 5, "items"}
--result: 5
You can optionally use the Get command with the Name reference form to
get the value of a property for a specified value. In most cases, you can also
use the Set command to set the additional properties listed in the definitions
of composite values. If a property cannot be set with the Set command, its
definition specifies that it is read-only.
37
C H A P T E R
Values
Elements
3
Elements of values are values contained within other values. Composite values
have elements; simple values do not. The sample value class definition in
Figure 3-1 shows one element, called an item.
Use references to refer to elements of composite values. For example, the
following reference specifies the third item in a list:
Operators
3
You use operators, such as the addition operator (+), the concatenation
operator (&), and the equality operator (=), to manipulate values. Values
that belong to the same class can be manipulated by the same operators.
The Operators section of a value class definition lists the operators that
can be used with values of a particular class.
For complete descriptions of operators and how to use them in expressions,
see Operations, which begins on page 161.
Commands Handled
Commands are requests for action. Simple values cannot respond to commands,
but composite values can. For example, lists can respond to the Count
command, as shown in the following example.
count {"This", "list", "has", 5, "items"}
--result: 5
Each composite value class definition includes a Commands Handled section
that lists commands to which values of that class can respond.
38
C H A P T E R
Values
Reference Forms
Coercions Supported
AppleScript can change a value of one class into a value of another class. This
is called coercion. The Coercions Supported section of a value class
definition describes the classes to which values of that class can be coerced.
Because a list consists of one or more values, any value can be added to a list or
coerced to a single-value list. The definition in Figure 3-1 also lists the value
classes to which individual items in a list can be coerced.
For more information about coercions, see Coercing Values, which begins
on page 68. For a summary of the coercions provided by AppleScript, see
Figure 3-2 on page 70.
This section describes the AppleScript value classes. Table 3-1 summarizes the
class identifiers recognized by AppleScript.
Three identifiers in Table 3-1 act only as synonyms for other value classes:
Number is a synonym for either Integer or Real, Text is a synonym for String,
and Styled Text is a synonym for a string that contains style and font
information. You can coerce values using these synonyms, but the class of the
resulting value is always the true value class.
39
C H A P T E R
Values
Table 3-1
Value class
identifier
Boolean
Class
A class identifier
Constant
Data
Date
Integer
List
Number
Real
Record
A collection of properties
Reference
A reference to an object
String
Styled Text
Text
For example, you can use the class identifier Text to coerce a date to a string:
set x to date "May 14, 1993" as text
class of x
--result: string
Although definitions for value class synonyms are included in the sections that
follow, they do not correspond to separate value classes. For more information
about coercing values using synonyms, see Coercing Values, which begins on
page 68.
40
C H A P T E R
Values
Boolean
3
A value of class Boolean is a logical truth value. The most common Boolean
values are the results of comparisons, such as 4 > 3 and WordCount = 5.
The two possible Boolean values are true and false.
LITERAL EXPRESSIONS
true
false
PROPERTY
Class
The class identifier for the object. This property is read-only, and
its value is always boolean.
ELEMENTS
None
OPERATORS
The operators that take Boolean values as operands are And, Or, Not, &, =,
and .
The = operator returns true if both operands evaluate to the same Boolean
value (either true or false); the operator returns true if the operands
evaluate to different Boolean values.
The binary operators And and Or take Boolean expressions as operands and
return Boolean values. An And operation, such as (2 > 1) and (4 > 3),
has the value true if both its operands are true, and false otherwise. An Or
operation, such as (theString = "Yes") or (today = "Tuesday"),
has the value true if either of its operands is true.
The unary Not operator changes a true value to false or a false value
to true.
COERCIONS SUPPORTED
41
C H A P T E R
Values
Class
3
A value of class Class is a class identifier. A class identifier is a reserved word
that specifies the class to which an object or value belongs. The Class property
of an object contains a class identifier value.
LITERAL EXPRESSIONS
string
integer
real
boolean
class
PROPERTY
Class
The class identifier for the object. This property is read-only, and
its value is always class.
ELEMENTS
None
OPERATORS
The operators that take class identifier values as operands are &, =, , and As.
The operator As takes a value of one class and coerces it to a value of a class
specified by a class identifier. For example,
"1.5" as real
coerces a string into the corresponding real number, 1.5. For more information
about coercing values, see Chapter 6, Expressions.
COERCIONS SUPPORTED
42
C H A P T E R
Values
Constant
3
A value of class Constant is a reserved word defined by AppleScript or an
application in its dictionary. Applications define sets of values that can be used
for parameters of a particular command; for example, the value of the saving
parameter of a Close command must be one of the three constants yes, no,
and ask.
LITERAL EXPRESSIONS
yes
no
ask
PROPERTY
Class
ELEMENTS
None
OPERATORS
The operators that take values of class Constant as operands are &, =, , and As.
COERCIONS HANDLED
NOTES
43
C H A P T E R
Values
Data
3
A value of class Data is data returned by an application (in response to a
command) that does not belong to any of the other value classes defined in this
section. A value of class Data is raw data that can only be stored in a variable.
PROPERTY
Class
ELEMENTS
None
OPERATORS
The operators that can take values of class Data as operands are = and .
COERCIONS SUPPORTED
Date
3
A complete Date value specifies the day of the week, the date (month, day
of the month, and year), and the time; if you provide only some of this
information, AppleScript fills in the missing pieces with default values. You
can get and set properties of a Date value that correspond to different parts
of the date and time information.
You can specify Date values in many different formats. The format always
begins with the word date followed by a string (within quotation marks)
containing the date and time information. You can spell out the day of the
week, month, or date. You can also use standard three-letter abbreviations
for the day and month.
44
C H A P T E R
Values
LITERAL EXPRESSIONS
PROPERTIES
Class
The class identifier for the object. This property is read-only, and
its value is always date.
Weekday
Month
Year
Time
Date
A string that consists of the date portion of the date value; for
example, "June 3, 1993".
ELEMENTS
None
45
C H A P T E R
Values
OPERATORS
The operators that take Date values as operands are &, +, , =, , >, , <, ,
Comes Before, Comes After, and As. In expressions containing >, , <, , Comes
Before, or Comes After, a later time is greater than an earlier time. The
following operations on Date values with the + and operators are supported:
date + timeDifference
--result: date
date - date
--result: timeDifference
date - timeDifference
--result: date
where date is a Date value and timeDifference is an Integer value specifying a
time difference in seconds. To simplify the notation of time differences, you can
also use one or more of these of these constants:
minutes
60
hours
60 * minutes
days
24 * hours
weeks
7 * days
Heres an example:
date "Apr 15, 1992" + 4 * days + 3 * hours + 2 * minutes
For more information about the way AppleScript operators treat Date values,
see Date-Time Arithmetic, which begins on page 180.
46
C H A P T E R
Values
REFERENCE FORMS
You can refer to properties of a Date value using the Property reference form.
weekday of date "May 3, 1993"
--result: Monday
time of date "May 3, 1993"
--result: "12:00 AM"
Note that AppleScript fills in a default time property for the date specified in
the second example.
If you want to specify a time relative to a date, you can do so as follows:
date "2:30 am" of date "May 3, 1993"
--result: date "May 3, 1993 2:30 AM"
date "Sept. 27, 1993" relative to date "3PM"
--result: date "September 27, 1993 3:00 PM"
In addition to of, you can also use the synonyms relative to or in for
this purpose.
COERCIONS SUPPORTED
NOTES
Regardless of the format you use when you type a date in a script, AppleScript
always displays Date values in the format shown in the following example,
which includes the full name of the day of the week and month and no leading
zeros for the date.
date "Sunday, January 3, 1992 12:05 PM"
If you dont specify a complete date, day, and time when typing a Date value,
AppleScript fills in information as needed. If you dont specify the date
information, AppleScript uses the date when the script is compiled. If you
47
C H A P T E R
Values
dont specify the time information, 12:00 AM (midnight) is the default. If you
omit AM or PM, AM is the default; however, if you specify 12:00 without AM
or PM, 12:00 PM is the default. If you specify the time using 24-hour time,
AppleScript converts it to the equivalent time using AM or PM; for example,
17:00 is equivalent to 5:00 PM.
To get the current date, use the scripting addition command Current Date.
For example,
if current date = date "Sunday, January 23, 1992 12:05 PM"
then print the front window
end if
For a complete description of the Current Date command, see the AppleScript
Scripting Additions Guide.
Integer
3
A value of class Integer is a positive or negative number without a
fractional part.
LITERAL EXPRESSIONS
1
2
-1
1000
PROPERTY
Class
The class identifier for the object. This property is read-only, and
its value is always integer.
ELEMENTS
None
48
C H A P T E R
Values
OPERATORS
The Div operator always returns an integer as its result. The +, , *, Mod, and ^
operators return integers or real numbers.
The operators that can have integers as operands are +, -, *, (or /), Div, Mod,
^, =, , >, , <, and .
COERCIONS SUPPORTED
NOTES
List
3
A value of class List is an ordered collection of values. The values contained in
a list are known as items. Each item can belong to any class.
LITERAL EXPRESSIONS
49
C H A P T E R
Values
PROPERTIES
Class
The class identifier for the value. This property is read-only, and
its value is always list.
Length
Rest
A list containing all items in the list except the first item.
Reverse
A list containing all items in the list, but in the opposite order.
Item
ELEMENT
OPERATORS
The operators that can have List values as operands are &, =, , Starts With,
Ends With, Contains, Is Contained By.
For detailed explanations and examples of how AppleScript operators treat
lists, see Operators That Handle Operands of Various Classes, which begins
on page 168.
50
C H A P T E R
Values
COMMANDS HANDLED
You can count the items in a list with the Count command. For example, the
value of the following statement is 6.
count {"a", "b", "c", 1, 2, 3}
--result: 6
You can also count elements of a specific class in a list. For example, the value
of the following statement is 3.
count integers in {"a", "b", "c", 1, 2, 3}
--result: 3
Another way to count the items in a list is with a Length property reference:
length of {"a", "b", "c", 1, 2, 3}
--result: 6
REFERENCE FORMS
Use the following reference forms to refer to properties of lists and items in lists:
51
C H A P T E R
Values
You cannot use the Relative, Name, ID, or Filter reference forms. For example,
the following reference, which uses the Filter reference form on a list, is
not valid.
the items in {"this", "is", "a", "list"} whose first
character is "t"
--result: not a valid reference
COERCIONS SUPPORTED
NOTES
To merge or add values to lists, use the concatenation operator (&). For example,
{"This"} & {"is", "a", "list"}
results in
{"This", "is", "a", "list"}
Note that the concatenation operator merges the items of the two lists into a
single list rather than making one list a value within the other list.
52
C H A P T E R
Values
Number
3
The class identifier Number is a synonym for Integer or Real; it describes a
positive or negative number that can be either of class Integer or
of class Real.
LITERAL EXPRESSIONS
1
2
-1
1000
10.2579432
1.0
1.
Any valid literal expression for an Integer or a Real value is also a valid literal
expression for a Number value.
PROPERTY
Class
The class identifier for the object. This property is read-only, and
its value is always either integer or real.
ELEMENTS
None
OPERATORS
Because values identified as values of class Number are really values of either
class Integer or class Real, the operators available are the operators described in
the definitions of the Integer or Real value classes, beginning on page 48 and
page 54, respectively.
53
C H A P T E R
Values
COERCIONS SUPPORTED
You can use the class identifier Number to coerce any value that can be coerced
to a Real value or an Integer value. However, the resulting value class is always
either Integer or Real:
set x to 1.5 as number
class of x --result: real
Real
3
Values that belong to the class Real are positive or negative numbers that can
include a decimal fraction, such as 3.14159 and 1.0.
LITERAL EXPRESSIONS
10.2579432
1.0
1.
As shown in the third example, a decimal point indicates a real number, even if
there is no fractional part.
Real numbers can also be written using exponential notation. A letter e is
preceded by a real number (without intervening spaces) and followed by an
integer exponent (also without intervening spaces). The exponent can be either
positive or negative. To obtain the value, the real number is multiplied by 10
to the power indicated by the exponent, as in these examples:
1.0e5 --equivalent to 1.0 * 10^5, or 100000
1.0e+5 --same as 1.0e5
1.0e-5 --equivalent to 1.0 * 10^-5, or .00001
PROPERTY
Class
54
The class identifier for the object. This property is read-only, and
its value is always real.
C H A P T E R
Values
ELEMENTS
None
OPERATORS
The and / operators always return Real values as their results. The +, -,
*, Mod, and ^ operators return Real values if either of their operands is a
Real value.
The operators that can have Real values as operands are +, -, *, (or /), Div,
Mod, ^, =, , >, , <, and .
COERCIONS SUPPORTED
NOTES
Real numbers that are greater than or equal to 10,000.0 or less than or equal to
0.0001 are converted to exponential notation when scripts are compiled. The
largest value that can be evaluated (positive or negative) is 1.79769e+308.
Record
3
A value of class Record is an unordered collection of properties. Like the
properties of application objects, each property has a label, and the properties
of a record are distinguished from each other by their label. There can be only
one property with a particular label in any record.
55
C H A P T E R
Values
LITERAL EXPRESSIONS
PROPERTIES
In addition to the properties that are specific to each record, two properties are
common to all records:
Class
The class identifier for the object. For most records, the value of
the Class property is record. However, the Class property of a
record is not read-only. AppleScript and applications use special
records for certain data. For example, the Scriptable Text Editor
uses special records to specify the styles (such as bold and
underline) of text objects. The value of the Class property for
these records is the class identifier Text Style Info, as illustrated
in this example:
{class:Text Style Info, On Styles:{Bold},
Off Styles:{ Italic, Outline, Shadow}}
Length
If you define a Class property explicitly in a record, the value you define
replaces the implicit Class property record described above.
56
C H A P T E R
Values
OPERATORS
The operators that can have records as operands are &, =, , Starts With, Ends
With, Contains, and Is Contained By.
For detailed explanations and examples of how AppleScript operators treat
records, see Operators That Handle Operands of Various Classes, which
begins on page 168.
COMMANDS HANDLED
You can count the properties in a record with the Count command. For
example, the value of the following statement is 2.
count of {name:"Sue", mileage:4000}
--result: 2
Another way to count the properties in a record is with a Length property
reference. For example, the value of the following reference is 3.
length of {name:"Sue", mileage:8000, city:"Sunnyvale"}
--result: 3
REFERENCE FORMS
The only reference form you can use with records is the Property reference
form. For example, the following reference specifies the Mileage property of
a record.
mileage of {name:"Sue", mileage:8000, city:"Sunnyvale"}
--result: 8000
You cannot refer to properties in records by numeric index. For example,
the following reference, which uses the Index reference form on a record,
is not valid.
item 2 of { name:"Sue", mileage:8000, city:"Sunnyvale" }
--result: not a valid reference
COERCIONS SUPPORTED
57
C H A P T E R
Values
NOTES
To specify a particular property of a record, you give its name. For example, if
you assign the record to a variable, as in
copy { name:"Mitchell", height:70.5, weight:165 } to writer
you can then get the value of the Name property with the expression
name of writer
A property of a record can contain a value of any class. You can change the
class of a property simply by assigning a value belonging to another class.
After you define a record, you cannot add additional properties to it. You can,
however, concatenate records. For more information, see Concatenation on
page 177.
Reference
3
A value of class Reference is a reference to an object. You can create a value of
class Reference by using the A Reference To operator. In addition, applications
can return references in response to commands.
A value of class Reference is different from the value of the object to which a
reference refers. For example, the reference
word 1 of front window of app "Scriptable Text Editor"
--result: a string
refers to a word object, whose value is a string, such as "Today". But a value
of class Reference created with the A Reference To operator is a structure
within AppleScript that refers (or points) to a specific object.
a reference to
"Scriptable
--result: word
"Scriptable
58
word
Text
1 of
Text
C H A P T E R
Values
The difference between a value of class Reference and the object it refers to is
analogous to the difference between an address and the building it refers to.
The address is a series of words and numbers, such as 1414 Maple Street, that
identifies the building. It is distinct from the building itself.
Values of class Reference are similar to pointers in other programming
languages, but unlike pointers, references can refer only to objects. For more
information about creating values of class Reference, see The A Reference To
Operator on page 153.
LITERAL EXPRESSIONS
PROPERTIES
Class
The class identifier for the object. This property is read-only, and
its value is always reference.
Contents
The value of the object to which the reference refers. The class
of the value depends on the reference. For information about
how to use the Contents property, see The A Reference To
Operator on page 153.
ELEMENTS
None
OPERATORS
59
C H A P T E R
Values
COERCIONS SUPPORTED
NOTES
60
C H A P T E R
Values
String
3
A value of class String is a character string (an ordered series of characters)
in AppleScript.
LITERAL EXPRESSIONS
PROPERTIES
Class
The class identifier for the object. This property is read-only, and
its value is always string.
Length
ELEMENTS
Paragraph
Text
61
C H A P T E R
Values
Word
OPERATORS
The operators that can have strings as operands are &, =, , >, , <, , Starts
With, Ends With, Contains, Is Contained By, and As.
For detailed explanations and examples of how AppleScript operators treat
strings, see Operators That Handle Operands of Various Classes, which
begins on page 168.
62
C H A P T E R
Values
REFERENCE FORMS
You can use the following reference forms to refer to elements of strings:
You cannot use the Relative, Name, ID, or Filter reference forms.
The backslash (\) and double-quote (") characters have special meaning in
strings. If you want to include either of these characters in a string, you must
use the equivalent two-character sequence:
Backslash character
\\
Double-quote character
\"
The tab and return characters can be included in strings, or they can be
represented by equivalent two-character sequences:
Tab character
\t
Return character
\r
63
C H A P T E R
Values
1
2
STRING CONSTANTS
Value
space
" "
tab
"\t"
return
"\r"
COERCIONS SUPPORTED
NOTES
64
C H A P T E R
Values
You cannot set the value of an element of a string. For example, if you attempt
to change the value of the first character of the string "boris" as shown in the
following example, youll get an error.
set myName to "boris"
set character 1 of myName to "D"
--results in an error, because you cannot set the values of
--elements of strings
Styled Text
3
The class identifier Styled Text is a synonym for a string that includes style and
font information.
LITERAL EXPRESSIONS
The only difference between a value of class String and a value of class Styled
Text is that the latter can include (but is not required to include) style and font
information. Thus any valid literal expression of class String is also valid as
class Styled Text.
PROPERTIES
Class
The class identifier for the object. This property is read-only, and
its value is always string.
Length
ELEMENTS
Styled text has the same character, word, paragraph, and text elements as
a string.
65
C H A P T E R
Values
OPERATORS
Because values identified as Styled Text values are really values of class String,
the operators available are the operators described in the definition of class
String: &, =, , >, , <, , Starts With, Ends With, Contains, Is Contained By,
and As.
For detailed explanations and examples of how AppleScript operators treat
strings, see Operators That Handle Operands of Various Classes, which
begins on page 168.
REFERENCE FORMS
You can use the same reference forms with styled text that you can use with
strings: Property, Index, Middle, Arbitrary, Every Element, and Range. For
details, see page 63.
You can use the same special characters, constants, and coercions with styled
text that you can use with strings. For details, see page 63. Note that literal
string constants do not include style and font information; in other words, they
are not styled text.
COERCIONS SUPPORTED
You can use the same coercions with styled text that you can use with strings:
coercion to an integer, number, real number, or single-item list, and coercion of
a list of strings to a single concatenated string.
You can use the class identifier Styled Text to coerce any string to styled text.
However, the resulting value is always of class String.
66
C H A P T E R
Values
NOTES
You cant change the style or font information from a script, but you can use
styled text to preserve style and font information when copying text objects
from applications to scripts. For example, you can use a script like this to
obtain styled text, manipulate it, and copy it back into a Scriptable Text Editor
document:
tell application "Scriptable Text Editor"
copy (word 1 of front document) to myStyledTitle
set myModifiedTitle to myStyledTitle & ", alpha release"
copy myModifiedTitle to word 1 of front document
end tell
Because the Scriptable Text Editor returns styled text when it returns the data
for text objects, you dont need to coerce the returned text to styled text. The
style and font of the first word are preserved both when the word is copied to
the variable myStyledTitle and when it is concatenated with the string
", alpha release". The modified title that is copied back to the document
consists of the original title with its original style and font, plus the unstyled
text, ", alpha release", which appears in the style and font of the character
immediately preceding it.
Styled text also contains information about the form in which the text is
written. If you copy non-Roman text to a variable in a script as styled text,
AppleScript preserves the original text information even though the
Script Editor may not be able to display it correctly. If you then copy the text
to an application that can handle the text in its original form, the text is
displayed correctly.
Text
3
You can use the class identifier Text as a synonym for the identifier String, for
example, in coercions:
"A string" as string = "A string" as text
--result: true
67
C H A P T E R
Values
Coercing Values
AppleScript coerces values in two ways:
The As operator specifies a particular coercion. You can use the As operator to
coerce a value to the correct class before using it as a command parameter or
operand. For example,
set myString to 2 as string
coerces the integer 2 into the string "2" before storing it in the variable
myString. Similarly,
"2" as integer + 8
coerces the string "2" to the integer 2, so that it can be added to the other
operand, 8.
68
Coercing Values
C H A P T E R
Values
Coercing Values
69
C H A P T E R
Values
Figure 3-2
Bo
ole
Cl an
as
s
Co
ns
Da tant
ta
Da
te
Int
eg
Si er
ng
l
Mu e-ite
lti- m l
Nu item ist
mb
lis
t
Re er
al
Re
co
St rd
rin
go
St
yle r te
d t xt
ex
t*
Coerce to
Coerce from
Boolean
Class
Constant
Data
Date
Integer
Single-item list
Multi-item list
Real
Record
String
* Only values that include style and font information can be coerced to styled text.
Only a list whose items can all be coerced to strings can be coerced to a string.
Only a real value that has no fractional part can be coerced to an integer.
Three of the identifiers mentioned at the top of Figure 3-2 act only as synonyms
for other value classes: number is a synonym for either integer or real,
text is a synonym for string, and styled text is a synonym for a string
that contains style and font information. You can coerce values using these
synonyms, but the class of the resulting value is always the appropriate value
class, not the synonym. Here are some examples:
set x to 1.5 as number
class of x
--result: real
70
Coercing Values
C H A P T E R
Values
set x to 4 as number
class of x
--result: integer
set x to "Hello" as text
class of x
--result: string
Coercing Values
71
C H A P T E R
Values
72
Coercing Values
C H A P T E R
Figure 4-0
Listing 4-0
Table 4-0
Commands
Types of Commands
Types of Commands
71
C H A P T E R
Commands
The sections that follow describe the different types of commands and
their targets.
Application Commands
Application commands are commands that cause actions in scriptable
applications. The target of an application command is an application object
or a script object. Different application objects respond to different commands.
To determine which commands a particular object can respond to, see the
definitions provided by the applications documentation. (For example, each
object definition in Appendix B, Scriptable Text Editor Dictionary, of this
book includes a list of commands that can act on that object.)
There are two ways to specify an object as the target of a command: in the
direct parameter of the command or in a Tell statement that contains
the command.
The direct parameter is a value, usually a reference, that appears immediately
after a command and specifies the target of the command. Not all commands
can have a direct parameter. If a command can have a direct parameter, the
commands definition says so.
For example, in the following statement, the reference word 1 of front
document of app "Scriptable Text Editor" is the direct parameter
of the Delete command:
delete word 1 of front document of app "Scriptable Text Editor"
A Tell statement is a statement that specifies a default target for all commands
contained within it. If a command is contained within a Tell statement, the
direct parameter is optional. If you leave out the direct parameter, AppleScript
uses the default target specified in the Tell statement. For example, the Delete
command in the following Tell statement has the same effect as the Delete
command in the previous example:
tell word 1 of front document of app "Scriptable Text Editor"
delete
end tell
72
Types of Commands
C H A P T E R
Commands
AppleScript Commands
AppleScript commands are commands that are built into the AppleScript
language. They act on values in scripts. The target of an AppleScript command
is a value in the current script, which is usually specified in the direct
parameter of the command.
There are only five AppleScript commands: Copy, Count, Get, Run, and Set. All
of these commands can also function as application commands. For the Count,
Get, Run, and Set commands, if the direct parameter is a value, then the
command functions as an AppleScript command. If the direct parameter is an
application object, the command functions as an application command.
For example, this Count command functions as an AppleScript command
because the direct parameter is a value (a list):
count {"How", "many", "items", "in", "this", "list"}
This Count command functions as an application command because the direct
parameter is an application object:
count words in paragraph 1 of front document of
application "Scriptable Text Editor"
For the Copy command, if the value of the to parameter is a reference to an
application object, then the command functions as an application command.
Otherwise, the command is an AppleScript command.
Types of Commands
73
C H A P T E R
Commands
For more examples of how to use Copy, Count, Get, Run, and Set, see the
command definitions later in this chapter.
74
Types of Commands
C H A P T E R
Commands
Dialog command, which displays the dialog box in the Script Editors layer
(that is, in front of any other Script Editor windows that may be open), while
the Script Editor is still the active application.
set theCount to number of words in front document of
app "Scriptable Text Editor"
if theCount > 500 then
display dialog "You have exceeded your word limit."
end
Each scripting addition that contains command handlers has its own dictionary,
which lists the reserved wordsincluding the command names, parameter
labels, and in some cases object namesused to invoke the commands supported by the scripting addition. If a scripting addition dictionary includes
words that are also part of an application dictionary, then you cannot use
those words within Tell statements to that application.
For example, the Offset command provided by the String Commands scripting
addition reports the offset, in characters, of a string within another string.
Offset is also a property of several Scriptable Text Editor objects and is thus a
word in the Scriptable Text Editor dictionary. Therefore, you cannot use Offset
as a scripting addition command within Tell statements to the Scriptable Text
Editor. If you do, youll get a syntax error, because AppleScript treats the word
Offset as a property of a text object.
tell front document of application "Scriptable Text Editor"
offset of "great" in "To be great"
end tell
--result: syntax error
If you specify a script object as the target of a scripting addition command, the
script object either handles the command itself (potentially modifying it) or
passes the command to the default target application. For more information
about scripting additions and script objects, see Using Continue Statements to
Pass Commands to Applications, which begins on page 280.
For information about the scripting additions available for AppleScript English
and definitions of the commands they provide, see the AppleScript Scripting
Additions Guide.
Types of Commands
75
C H A P T E R
Commands
User-Defined Commands
76
Types of Commands
C H A P T E R
Commands
Figure 4-1
application command
Move
referenceToObject
77
C H A P T E R
Commands
Syntax
4
Each command definition begins with a syntax description, which is a
template for using the command in a statement. Syntax descriptions use the
same typographic conventions used elsewhere in this guide: plain computer
font indicates a language element you must type exactly as shown; italic text
indicates a placeholder you must replace with an appropriate value; brackets
indicate the enclosed language element or elements are optional; three ellipsis
points indicate you can repeat the preceding element or elements one or more
times; and vertical bars separate elements from which you must choose a
single element.
For example, to use the Move command, you must replace directParameter with
a reference to the object to move and location with a reference to the location to
which to move it.
Parameters
4
Parameters are values that are included with a command. The Parameters
section of a command definition lists the parameters of a particular command
and the information you need to use them correctly.
Many commands include a direct parameter that specifies the object of the
action. If a command includes parameters other than the direct parameter, they
are identified by labels. Parameters that are identified by labels are called
labeled parameters. The direct parameter immediately follows the command;
labeled parameters can be listed in any order. The Move command defined
in Figure 4-1 has a direct parameter (referred to in the definition as
referenceToObject) that specifies the object to move and a labeled parameter
(whose label is to) that specifies where to move the object.
Each parameter value must belong to a particular class, which is listed in its
description in the command definition. For the Move command, the direct
parameter belongs to the class reference. Its value, a reference, is a phrase that
identifies the object to be moved. The to parameter also belongs to the class
reference. It specifies the location to which to move the object. References are
described in Chapter 5, Objects and References.
Parameters can be required or optional. Required parameters must be
included with the command; optional parameters need not be. Optional
parameters are enclosed in brackets in syntax descriptions. For optional
78
C H A P T E R
Commands
Result
4
Many, but not all, commands return results. The result of a command is the
value generated when the command is executed. The Result section of a
command definition tells whether a result is returned, and if so, lists its class.
For example, the result of the Move command shown in Figure 4-1 is a
reference to the object that was moved.
For more information about results, see Using Results on page 82.
Examples
4
Each command definition includes one or more short examples demonstrating
how to use the command. The example in Figure 4-1 shows how to use the
Move command to move a word in the Scriptable Text Editor.
Errors
4
Commands can return error messages as well as results. An error message is a
message that is returned by an application, AppleScript, or the operating
system if an error occurs during the handling of a command. The Errors
section of a command definition, if present, lists errors that are likely to be
returned by a particular command. This information can help you decide if you
need to write error handlers to respond to the error messages that are returned.
Error handlers are described in Chapter 8, Handlers.
Some errors are not the result of abnormal conditions but are the normal way
you get information about what happened during command execution. For
example, you use the Choose File command to ask the user to choose a file.
When AppleScript executes this command, it displays a dialog box similar to
the one you get when you choose Open from the File menu. If the user presses
79
C H A P T E R
Commands
the Cancel button in the dialog box, AppleScript returns error number 128
and the error string "User canceled". Your script must handle this error
for script execution to continue.
For a complete description of handling errors that occur during script
execution, see Chapter 8, Handlers.
Using Parameters
coerce parameters
80
Using Parameters
C H A P T E R
Commands
Coercion of Parameters
If a parameter doesnt belong to the right class, it may be possible to coerce it,
that is, to change it into a value of another class. For example, you can coerce
an integer such as 2 to the corresponding string "2" using the As operator:
2 as string
AppleScript performs some coercions, including the previous one, automatically. For example, in the following statement, the direct parameter of the
Copy command should be a string because it is being inserted into a text
editor document.
tell application "Scriptable Text Editor"
copy 12 to beginning of document "Introduction"
end tell
When AppleScript executes this statement, it automatically coerces the integer
12 to the string "12" and inserts the string at the beginning of the document.
The coercions that AppleScript can perform are listed in Chapter 3, Values.
Applications can also perform additional coercions, such as coercions for
classes that are specific to an application. These coercions are listed in the
documentation for the application.
Some application commands return values that do not belong to any of the
normal AppleScript value classes. An example is the Edit Graphic command
supported by some graphics applications. The values that are returned belong
to the class Data, which is described in Chapter 3, Values. Values of class
Data cannot be displayed by AppleScript, but they can be stored in variables
and sent as parameters in other commands. For example, if its necessary to use
Using Parameters
81
C H A P T E R
Commands
two different applications to edit a graphic, the data value returned by one
Edit Graphic command can be sent as the direct parameter of another Edit
Graphic command.
If an application returns values of class Data, its documentation should say so.
Using Results
The result of a command is the value generated when the command is executed.
You can display the result of a command in the Script Editor. For example, if
you run the following script,
tell front document of application "Scriptable Text Editor"
move word 1 to end of paragraph 1
end tell
and then choose Show Result from the Controls menu in the Script Editor,
youll see a value such as
word 32 of front document of application "Scriptable Text Editor"
You can use a command that returns a result as a value. For example, the Count
command in the following statement returns a value: the number of words in
the third paragraph.
count words in paragraph 3
You can use this statement anywhere a value is required by enclosing the
statement in parentheses. For example, the following statement sets the value
of numWords to the value returned by the Count command.
set numWords to (count words in paragraph 3)
In addition to displaying the result of a command in the result window,
AppleScript puts the result into a predefined variable called result. The value
remains there until the next command is executed. If the next command does
not return a result, the value of result is undefined. The following two
82
Using Results
C H A P T E R
Commands
commands show how to use the result variable to set the value of numWords
to the value returned by the Count command:
count words in paragraph 3
set numWords to result
When a direct parameter specifies more than one object, the result is a list that
contains a value for each object that was handled. Here is an example of a
command whose result is a list:
get paragraphs 1 thru 3 of first document
The result is a list of strings similar to the following. The first string is the value
of the first paragraph, the second string is the value of the second paragraph,
and the third string is the value of the third paragraph.
{"This is paragraph one.", "This is paragraph two."
"This is paragraph three."}
You may occasionally notice terms like this within double angle brackets in a
script or a result:
event sysodlog
In general, AppleScript uses double angle brackets when it cant locate the
dictionary it needs to identify a term or cant display a value directly. The first
word within the double angle brackets can be any of these: event, property,
class, data, preposition, keyform, constant, or script. The second
word varies depending on the context.
If double angle brackets appear unexpectedly in a script when you open it with
the Script Editor, it may be because a command used in the script is not present
in the Scripting Additions folder (which is located in the Extensions folder of
the System folder) for your computer. For example, if you create a script that
uses the Display Dialog command, then open the script at a later time or on a
83
C H A P T E R
Commands
different computer when the Display Dialog scripting addition is not present
in the Scripting Additions folder, AppleScript replaces the words display
dialog in the script with event sysodlog. In this case you should drop
the icon for the Display Dialog scripting addition into the Scripting Additions
folder before attempting to run the script.
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 x to Joe
x
--result: script Joe
(For more information about script objects, see Chapter 9, Script Objects.)
Similarly, if the value of a variable is of class Data and AppleScript cant
represent the data directly, the value of the data is represented within angle
brackets by the word data followed by some sequence of ASCII characters.
Although this may not resemble the original data, the datas original format
is preserved. You can treat the data like any other value, except that you
cant view it directly in any Script Editor window.
Command Definitions
The sections that follow are in alphabetical order by command name and
provide definitions for both AppleScript commands and standard application
commands. The general features of these types of commands are described in
Types of Commands,which begins on page 71. The command type is listed
opposite the command name on the first line of each definition.
For definitions of commands provided by the scripting additions that come
with AppleScript English, see the AppleScript Scripting Additions Guide. For
definitions of commands provided by other scripting additions, see the
documentation for those scripting additions.
84
Command Definitions
C H A P T E R
Commands
Table 4-1
Command
Required suite
Open
Opens a file.
Quit
Terminates an application.
Run
Standard suite
Close
Copy
Count
Data Size
Delete
Command Definitions
85
C H A P T E R
Commands
Table 4-1
Command
Summary
Duplicate
Exists
Get
Launch*
Make
Move
Save
Set
Table 4-2
Command
Summary
Copy
Count
Get
Run
Set
86
Command Definitions
C H A P T E R
Commands
Close
application command 4
A Close command is a request to close one or more objects.
SYNTAX
PARAMETERS
referenceToObject
A reference to the object or objects to close.
Class: Reference
referenceToFile A reference of the form file nameString or alias nameString
(see Notes).
Class: Reference
Default value: The file in which the object was last saved. If the
object hasnt been saved before, the application creates a file
with the specified name in the current directory.
saveOption
RESULT
None
Command Definitions
87
C H A P T E R
Commands
EXAMPLES
NOTES
To specify the name (nameString) of a file in which to save the object, use a
string of the form "Disk:Folder1:Folder2:...:Filename"; for details, see
References to Files, which begins on page 144. You can also specify a string
with only a filename ("Filename"). In this case, the application attempts to find
the file in the current directory. If it cant find the specified file, the application
creates a file with the specified name in the current directory.
Copy
88
Command Definitions
C H A P T E R
Commands
PARAMETERS
expression
variablePattern
referencePattern
A reference to the location to which to copy expression, a list of
reference patterns, or a record of reference patterns.
Class: Reference, list, or record
Default value: If you do not specify a new location, the object
specified in the direct parameter is copied and put on the
Clipboard.
referenceToObject
A reference to the object or objects to be copied, or a list of
reference patterns, or a record of reference patterns.
Class: Reference, list, or record
Default value: If this parameter is omitted, the object or objects in
the current selection are copied and put on the Clipboard.
RESULT
If the Copy command is used to create a variable, the result is the value that
was stored in the variable. If the command is used to copy an object, the result
Command Definitions
89
C H A P T E R
Commands
is a reference to the copied object; however, if the command does not include
parameters, there is no result.
Class: Varies
EXAMPLES
90
Command Definitions
C H A P T E R
Commands
NOTES
For more information about using the Copy command to create or change the
values of variables, see Variables, which begins on page 150.
If you use the Copy command without parameters and there is no selection to
be copied, the application does not change the contents of the Clipboard.
When copying objects between applications via the Clipboard, you must
use the Activate command to make the receiving application active before
attempting to paste from the Clipboard.
ERRORS
Error
number
Error message
1728
10006
Command Definitions
91
C H A P T E R
Commands
Count
PARAMETERS
className
compoundValue
92
Command Definitions
C H A P T E R
Commands
pluralClassName
The plural class name of the elements to be counted. The
elements of lists, records, and strings are listed in the value
class definitions in Chapter 3, Values.
Class: Class identifier
Default value: Item for lists, records, and application objects;
Character for strings (see Notes)
referenceToObject
A reference to the object or objects whose elements are to be
counted. If you do not specify this parameter, the application
counts the elements in the default target of the Tell statement.
Class: List, record, reference, or string
RESULT
The result of the AppleScript command is an integer that specifies the number
of elements of a specified class in a compound value.
The result of the application command is either an integer or a list of integers.
See Notes for details.
Class: Integer or list of integers
EXAMPLES
Command Definitions
93
C H A P T E R
Commands
This example shows another way to count the integers in the list:
count each integer in {"Yes", "No", "Maybe", 4, 5, 6}
--result: 3
In the following example, every word of document "simple" consists of
a list of words. The Scriptable Text Editor counts the words in the list.
tell application "Scriptable Text Editor"
count every word of document "simple"
end tell
--result: 12
The following statement is equivalent to the previous example:
tell application "Scriptable Text Editor"
count words of document "simple"
end tell
In the following example, referenceToObject is documents of application
"Scriptable Text Editor", which is a list of documents. The Scriptable
Text Editor counts the documents in the list.
tell application "Scriptable Text Editor"
repeat with i from 1 to (count of documents)
set the style of paragraph 1 of document i to
{outline, bold}
end repeat
end tell
NOTES
If you use the Count command on a string without specifying the class to be
counted, AppleScript counts the characters; for example,
count "This is a string"
--result: 16
94
Command Definitions
C H A P T E R
Commands
The result of the Count command depends on how you specify the range of
objects to be counted. For example, consider the following statement, given the
Scriptable Text Editor document in Figure 4-2:
tell document "simple" of app "Scriptable Text Editor"
count words from paragraph 2 to paragraph 3
end tell
--result: 8
Figure 4-2
Command Definitions
95
C H A P T E R
Commands
The counting in this example requires several steps, beginning with the
reference to the outermost container. The reference paragraphs 2 thru 3
specifies a list of two items, each of which is a paragraph:
{"This is paragraph two.", "This is paragraph three."}
On the basis of this list, the Scriptable Text Editor evaluates the reference
words of paragraphs 2 thru 3 as a list of two items, each of which is
a list of the words in one paragraph:
{{"This", "is", "paragraph", "two."},
"This, "is","paragraph", "three."}}
Finally, the Scriptable Text Editor counts the items in each list and returns a list
of two items, each of which specifies the number of words in one paragraph:
{4, 4}.
References to nested containers are always evaluated before counting takes
place, beginning with the outermost container. Heres another example:
tell document "simple" of app "Scriptable Text Editor"
count characters of words of paragraphs 2 thru 3
end tell
--result: {{4, 2, 9, 3}, {4, 2, 9, 5}}
The previous example demonstrated that the reference words of
paragraphs 2 thru 3 specifies a list of two items, each of which is a
list of the words in one paragraph:
{{"This", "is", "paragraph", "two."},
{"This, "is","paragraph", "three."}}
The Scriptable Text Editor counts the items in each list and returns a list of two
items, each of which is a list of the number of characters in each of the words in
one paragraph:
{{4, 2, 9, 3}, {4, 2, 9, 5}}
96
Command Definitions
C H A P T E R
Commands
Data Size
application command 4
A Data Size command is a request for the size, in bytes, of the data of one or
more objects. The value returned is the size of the data (a value) that would
result from a Get command on the same object or objects.
SYNTAX
PARAMETERS
referenceToObject
A reference to the object or objects whose data size is to be
returned.
Class: Reference
className
The class of data for which to determine the size (see Notes).
Class: Class identifier
Default value: The default value class for the object
RESULT
Command Definitions
97
C H A P T E R
Commands
EXAMPLE
NOTES
Delete
application command 4
A Delete command is a request to delete one or more objects.
SYNTAX
delete referenceToObject
PARAMETER
referenceToObject
A reference to the object or objects to be deleted.
Class: Reference
RESULT
None
EXAMPLE
98
Command Definitions
C H A P T E R
Commands
Duplicate
application command 4
A Duplicate command is a request to make a copy of an object or objects and
insert the new copy either at a location specified in the command or at the
location following the object that was copied.
SYNTAX
referenceToObject
A reference to the object or objects to be duplicated.
Class: Reference
newLocation
RESULT
Exists
application command 4
An Exists command is a request to determine whether the object specified by a
reference exists.
SYNTAX
referenceToObject exists
exists referenceToObject
Command Definitions
99
C H A P T E R
Commands
PARAMETER
referenceToObject
A reference to the object or objects to find.
Class: Reference
RESULT
EXAMPLES
Get
100
Command Definitions
C H A P T E R
Commands
PARAMETERS
expression
className
referenceToObject
A reference to an object whose value is to be returned in the
result variable.
Class: Reference
RESULT
Command Definitions
101
C H A P T E R
Commands
EXAMPLE
NOTES
ERROR
102
Error
number
Error message
1728
Command Definitions
C H A P T E R
Commands
Launch
application command 4
If an application is not already running, sending it a Launch command
launches it without sending a Run command. (If the application is already
running, the Launch command has no effect.) This allows an application
to open without performing its usual startup procedures, such as opening a
new window or, in the case of a script application, running the script.
SYNTAX
launch [ referenceToApplication ]
PARAMETER
referenceToApplication
A reference of the form application nameString (see Notes).
This parameter is optional if the Launch command is used
within an appropriate Tell statement.
Class: Reference
RESULT
None
EXAMPLES
NOTES
Command Definitions
103
C H A P T E R
Commands
104
Command Definitions
C H A P T E R
Commands
Make
application command 4
A Make command is a request to create a new object. The command can
include values for properties of the object, for the data of the object, or both.
SYNTAX
[ with properties
PARAMETERS
className
referenceToLocation
The location at which to create the new object.
Class: Reference
propertyLabel
Command Definitions
105
C H A P T E R
Commands
RESULT
EXAMPLE
NOTES
If you use the Make command to create a new text object, check the application
dictionary to determine how the application handles delimiters. Some
applications, such as the Scriptable Text Editor, supply delimiters
automatically, so you dont have to include them in the value of the with
data parameter.
Move
application command 4
A Move command is a request to move an object or objects.
SYNTAX
PARAMETERS
referenceToObject
A reference to the object or objects to move.
Class: Reference
106
Command Definitions
C H A P T E R
Commands
referenceToLocation
A reference to the location to which to move the object or objects.
Class: Reference
RESULT
EXAMPLE
Open
application command 4
An Open command is a request to open a file or files.
SYNTAX
open referenceToFile
PARAMETER
referenceToFile
RESULT
None
Command Definitions
107
C H A P T E R
Commands
EXAMPLE
NOTES
To specify the name (nameString) of a file to open, use a string of the form
"Disk:Folder1:Folder2:...:Filename"; for details, see References to Files,
which begins on page 144. You can also specify a string with only a filename
("Filename"). In this case, the application attempts to find the file in the
current directory.
If the file or files specified by referenceToFile is already open, it remains open.
application command 4
A Print command is a request to print one or more objects.
SYNTAX
print referenceToObject
PARAMETER
referenceToObject
A reference to the object or objects to printtypically file(s),
document(s), or window(s).
Class: Reference or list of references
RESULT
None
108
Command Definitions
C H A P T E R
Commands
EXAMPLES
NOTES
To specify the name of a file to print, use the term file or alias followed by
a string of the form "Disk:Folder1:Folder2:...:Filename"; for details, see
References to Files, which begins on page 144. You can also specify a string
with only a filename ("Filename"). In this case, the application attempts to find
the file in the current directory.
Quit
application command 4
A Quit command is a request for an application to terminate. If no optional
parameters are specified, the Quit command has the same result as choosing
the Quit menu item in the application.
SYNTAX
Command Definitions
109
C H A P T E R
Commands
PARAMETERS
referenceToApplication
A reference of the form application nameString, where
nameString is a string that matches the name of the application
you want to quit as it is listed in the Application menu.
Class: Reference
saveOption
RESULT
None
EXAMPLES
Run
110
Command Definitions
C H A P T E R
Commands
on the application. Some applications are not affected; others, such as the
Scriptable Text Editor, repeat their startup procedures each time they receive
a Run command.
run [ scriptObjectVariable ]
run [ referenceToApplication ]
PARAMETERS
scriptObjectVariable
A variable identifier whose value is a script object. This
parameter is optional if the Run command is used within
an appropriate Tell statement.
Class: Script
referenceToApplication
A reference of the form application nameString (see Notes).
This parameter is optional if the Run command is used within
an appropriate Tell statement.
Class: Reference
RESULT
The AppleScript Run command returns the result, if any, returned by the
specified script objects Run handler.
The application Run command doesnt return a result.
EXAMPLES
Command Definitions
111
C H A P T E R
Commands
NOTES
Save
application command 4
A Save command is a request to save an object or objects.
SYNTAX
PARAMETERS
referenceToObject
A reference to the object or objects to be saved.
Class: Reference
112
Command Definitions
C H A P T E R
Commands
RESULT
None
EXAMPLE
NOTES
To specify the name (nameString) of a file in which to save the specified object or
objects, use a string of the form "Disk:Folder1:Folder2:...:Filename"; for
details, see References to Files, which begins on page 144. You can also specify
a string with only a filename ("Filename"). In this case, the application attempts
to find the file in the current directory.
If you use the form file nameString and the specified file is not present in the
specified location, the application creates a file with the specified name in that
location. If you use the form alias nameString and the specified file is not
present in the specified location, the script wont compile.
Set
Command Definitions
113
C H A P T E R
Commands
PARAMETERS
variablePattern The name of the variable in which to store the value, or a list of
variable patterns, or a record of variable patterns.
Class: Identifier, list, or record
expression
referencePattern
A reference to the location whose value is to be set, or a list of
reference patterns, or a record of reference patterns.
Class: Reference, list, or record
RESULT
114
Command Definitions
C H A P T E R
Commands
EXAMPLES
You can use the Set command to set a variable to any value:
set x to 5
set myList to { 1, 2, "four" }
tell application "Scriptable Text Editor"
set x to word 1 of front document
end tell
These two statements are equivalent:
set x to 3
3 returning x
Similarly, the following examples are equivalent:
tell front document of application "Scriptable Text Editor"
set x to word 1
end tell
tell front document of application "Scriptable Text Editor"
word 1 returning x
end tell
In addition to setting a variable to a single value, you can set patterns of
variables to patterns of values. For example, this script sets a list of two
variables to the position of the front window.
tell application "Scriptable Text Editor"
set {x, y} to position of front window
end tell
Since the Scriptable Text Editor returns position of front window as a
list of two integers, the preceding example sets x to the first item in the list and
y to the second item.
Command Definitions
115
C H A P T E R
Commands
Patterns set with the Set command can also be more complex. Here are
some examples:
set x to {8, 94133, {firstName:"John", lastName:"Chapman"}}
set {p, q, r} to x
(* now p, q, and r have these values:
p = 8
q = 94133
r = {firstName:"John", lastName:"Chapman"} *)
tell front document of application "Scriptable Text Editor"
set {word 1, word 2} to
{firstName of item 3 of x, lastName of item 3 of x}
end tell
--now word 1 = "John" and word 2 = "Chapman"
set {p, q, {lastName:r}} to x
(* now p, q, and r have these values: p = 8
q = 94133
r = "Chapman" *)
As the last example demonstrates, the properties of a record need not be given
in the same order and need not all be used when you set a pattern to a pattern,
as long as the patterns match.
The use of the Set command with patterns is similar to the use of patterned
parameters with subroutines, which is described in Subroutines With
Positional Parameters, beginning on page 235.
116
Command Definitions
C H A P T E R
Commands
NOTES
If you use the Set command to set a variable to a list, record, or script object, the
variable shares data with the original list, record, or script object. If you change
the data of the original, the value of the variable also changes. Heres an
example of how this works:
set myList to { 1, 2, 3 }
set yourList to myList
set item 1 of myList to 4
The result of these statements is that item 1 of both myList and yourList is 4.
Data sharing promotes efficiency when using large data structures. Rather than
making copies of shared data, the same data can belong to multiple structures.
When one structure is updated, the others are automatically updated.
IMPORTANT
Command Definitions
117
C H A P T E R
Figure 5-0
Listing 5-0
Table 5-0
Object class definitions describe what objects that belong to a particular class
have in common. This guide contains object class definitions for system objects
(in this chapter) and Scriptable Text Editor objects (in Appendix B). This section
describes the information contained in object class definitions.
119
C H A P T E R
Figure 5-1 shows a sample object class definition for a paragraph object. The
definition contains four types of information: properties, element classes,
commands handled, and default value class returned. The sections that follow
describe the kinds of information provided by an object class definition.
Properties
5
A property of an object is a characteristic that has a single value, such as the
name of a window or the font of a character. Properties are contained by objects
in much the same way that elements are. The main difference is that each of
an objects properties has only one value, whereas an object may have many
different elements of a single class. Properties of an object are distinguished
from each other by their unique labels.
The definitions for two properties (from a total of six) are visible in the object
class definition shown in Figure 5-1. These properties labels are Font and Size.
The definition also lists the class to which each property belongs. For example,
the class of the Font property is String, indicating that the value of the Font
property is a character string. Properties can belong to object or value classes.
Element Classes
Elements are objects contained within an object. The element classes listed in
an object class definition indicate what kinds of elements objects of that object
class can contain. An object can contain many elements or none, and the
number of elements of a particular class that it contains may change over time.
Most application and system objects can contain elements.
The definition in Figure 5-1 shows that a paragraph object can include word
elements. It is possible for a paragraph to have no words. At a later time, the
same paragraph might have many words.
Commands Handled
Objects that belong to the same class can respond to the same commands.
Object class definitions list the commands to which all objects of that
class respond.
120
C H A P T E R
Figure 5-1
The Scriptable Text Editors object class definition for paragraph objects
Paragraph
An object of class Paragraph is a text object thats delimited by return
characters or by the beginning or end of the container.
PROPERTIES
Font
Size
ELEMENT CLASSES
COMMAND HANDLED
Copy, Count, Cut, Data Size, Delete, Exists, Get, Make, Move, Select, Set
DEFAULT VALUE CLASS RETURNED
Styled Text
121
C H A P T E R
The definition in Figure 5-1 shows that all paragraph objects respond to
the Copy, Count, Cut, Data Size, Delete, Exists, Get, Make, Move, Select,
and Set commands.
Each object has a value. For example, the value of a paragraph object is a string
that includes style and font information. You can get the value of a system or
application object by sending it a Get command or simply referring to it in a
script. If the Get command doesnt specify a value class for the value returned,
the default value class is used. For example, according to the definition of a
paragraph in Figure 5-1 a Get command that specifies a paragraph without
specifying a value class returns styled text.
References
A reference is a phrase that specifies one or more objects. You use references to
identify objects within applications. An example of a reference is
word 5 of paragraph 10 of document "Work in Progress"
which specifies a word object in the document named Work in Progress.
A reference describes what type of object youre looking for, where to look for
the object, and how to distinguish the object from other objects of the same
type. These three types of informationthe class, or type; the container, or
location; and the reference form, or distinguishing informationallow you to
specify any object of an application.
In general, you list the class and distinguishing information at the beginning of
a reference, followed by the container. In the previous example, the class of the
object is word. The container is the phrase paragraph 10 of document
"Work in Progress". The distinguishing information (the reference form) is
the combination of the class, word, and an index value, 5, which together
indicate the fifth word.
122
References
C H A P T E R
References allow you to identify objects in a flexible and intuitive way. Just as
there might be several ways to identify an object on the desktop, AppleScript
has different reference forms that allow you to specify the same object in
different ways. For example, heres another way to specify the fifth word of
a document:
word after word 4 of document "Work in Progress"
To write effective scripts, you should be familiar with AppleScripts reference
forms and know how to use containers and reference forms to identify the
objects you want to manipulate. The sections that follow describe containers
and reference forms.
Containers
5
A container is an object that contains one or more objects or properties. In a
reference, the container specifies where to find an object or a property. To
specify a container, use the word of or in, as in
word 5 of paragraph 10
and
character 2 in word 12
where word 5 is contained in a paragraph object and character 2 is
contained in a word object.
A container can be an object or a series of objects. In a series, list the smallest
object first, followed by the larger objects that contain it. Use the word of or in
to separate each object from its larger, containing object. For example, in
word 5 of paragraph 10 of document "Report"
word 5 is contained by the larger object, paragraph 10; paragraph 10 is
contained by the larger object document "Report".
References
123
C H A P T E R
You can also use the possessive form ('s) to specify containers. If you use the
possessive form, list the container before the object it contains. For example, in
first window's name
the container is first window. The object it contains is a Name property.
All properties and elements have containers. The previous example
specified the Name property of a window, which is contained in a window
object. Similarly, the following example specifies the Style property, which
is contained in a character object.
style of first character
124
References
C H A P T E R
Similarly, the following Tell statement tells the Scriptable Text Editor to delete
the third word of the first paragraph of the front document.
tell paragraph 1 of front document of application
"Scriptable Text Editor"
delete word 3
end tell
Tell statements can contain other Tell statements, called nested Tell statements.
When AppleScript encounters a partial reference in a nested Tell statement, it
tries to complete the reference starting with the innermost Tell statement. If that
does not provide enough information, AppleScript uses the direct object of the
next Tell statement, and so on. For example, the following Tell statement is
equivalent to the previous example.
tell front document of application "Scriptable Text Editor"
tell paragraph 1
tell word 3
delete
end tell
end tell
end tell
Reference Forms
A reference form is the syntax, or rule, for writing a phrase that identifies an
object or group of objects. For example, the Index reference form allows you to
identify an object by its number, as in
word 5 of paragraph 10
AppleScript includes other reference forms for identifying objects in
applications. Table 5-1 summarizes the reference forms you can use to identify
objects. Each section that follows includes a brief explanation of the reference
form, a syntax summary, and examples of how to use the reference form to
specify application objects. The Filter reference form is described in more detail
in Using the Filter Reference Form, which begins on page 140.
Reference Forms
125
C H A P T E R
Table 5-1
Reference forms
Reference form
Purpose
Arbitrary Element
Every Element
Filter
ID
Index
Middle Element
Name
Property
Range
Relative
Arbitrary Element
The Arbitrary Element reference form specifies an arbitrary object in a
container. If the container is a value (such as a list), AppleScript chooses
an object at random (that is, it uses a random-number generator to choose
the object). If the container is an application object, it is up to the application
to choose an object. It can choose a random object or any object at all.
SYNTAX
some className
where
className is the class identifier for the desired object.
126
Reference Forms
C H A P T E R
EXAMPLES
Every Element
The Every Element reference form specifies every object of a particular class in
a container.
SYNTAX
every className
pluralClassName
where
className is a singular class name (such as word or paragraph).
pluralClassName is the plural form defined by AppleScript or an application
(such as words or paragraphs). The plural form of an object class name has
the same effect as the word every before an object class name. Plural forms are
listed in application dictionaries.
VALUE
The value of an Every Element reference is a list of the objects in the container.
If the container does not contain any objects of the specified class, the list is an
empty list. For example, the value of the expression
every paragraph of {1, 2, 3}
is the empty list:
{}
Reference Forms
127
C H A P T E R
EXAMPLES
The following example assigns a string to the variable myString, and then
uses the Every Element reference form to specify every word contained in
the string.
set myString to "That's all, folks"
every word of myString
The value of the reference every word of myString is a list with
three items:
{"That's", "all", "folks"}
The following reference specifies the same list:
words of myString
The following references specify a list of all the words in the first paragraph of
a document.
tell front document of application "Scriptable Text Editor"
every word of paragraph 1
words of paragraph 1
end tell
NOTES
128
Reference Forms
C H A P T E R
Filter
5
The Filter reference form specifies all objects in a container that match one or
more conditions specified in a Boolean expression. The Filter reference form
specifies application objects only. It cannot be used to specify values. (For
information about how to use the Filter reference form, refer to the next section,
Using the Filter Reference Form, which begins on page 140.)
SYNTAX
EXAMPLES
The following are some examples of references that use the Filter reference
form. For examples with explanations, see the next section, Using the Filter
Reference Form, which begins on page 140.
every paragraph whose first word = last word
first word whose style contains italic
paragraph whose first word = last word
words whose style contains italic
every word whose size > 12 and font = "Palatino"
paragraphs where (count of characters) > 10
every word where it contains "ly"
every word where it "the"
Reference Forms
129
C H A P T E R
NOTES
Except for the Every Element reference form, the application returns an error
if no objects pass the test or tests. For the Every Element reference form, the
application returns an empty list if no objects pass the test or tests.
To specify a container after a filter, you must enclose the filter and the
reference it applies to in parentheses. For example, the parentheses around
words 1 thru 5 whose first character = "M" in the following
reference are required because the container of paragraph 5 follows
the filter.
(words 1 thru 5 whose first character = "M") of paragraph 5
ID
5
The ID reference form specifies an object by the value of its ID property. You
can use this reference form only for objects that have an ID property.
SYNTAX
className id IDvalue
where
className is the class identifier for the specified object.
IDvalue is the value of the objects ID property.
EXAMPLES
document ID 9096
window id 777
NOTES
130
Reference Forms
C H A P T E R
Index
5
The Index reference form specifies an object or a location by describing its
position with respect to the beginning or end of a container.
SYNTAX
Reference Forms
131
C H A P T E R
EXAMPLES
The following references specify the second word from the beginning of the
third paragraph.
word 2 of paragraph 3
2nd word of paragraph 3
second word of paragraph 3
The following references specify the last word in the third paragraph.
word 1 of paragraph 3
last word of paragraph 3
The following reference specifies the next-to-last word in the third paragraph.
word 2 of paragraph 3
The following references refer to the first insertion point of the document called
Introduction.
beginning of document "Introduction"
front of document "Introduction"
132
Reference Forms
C H A P T E R
The following example contains two references. The first is a reference to the
tenth word of the document called Introduction. The second is a reference to
the last insertion point in the same document.
tell application "Scriptable Text Editor"
move word 10 of document "Introduction" to
end of document "Introduction"
end tell
Middle Element
The Middle Element reference form specifies the middle object of a particular
class in a container.
SYNTAX
middle className
where
className is the class identifier for the specified object.
EXAMPLES
NOTES
AppleScript calculates the middle object with the expression ((n + 1) div
2), where n is the number of objects and div is the integer division operator. If
there is an even number of objects in the container, the result is rounded down.
For example, the middle word of a paragraph containing twenty words is the
tenth word.
Reference Forms
133
C H A P T E R
Name
5
The Name reference form specifies an object by name. Most applications
determine this by examining an objects Name property.
SYNTAX
EXAMPLES
document "Report"
window named "Help"
application "Macintosh HD:Applications:Scriptable Text Editor"
NOTES
134
Reference Forms
C H A P T E R
Property
5
The Property reference form specifies a property of an application object, a
script object, a record, or a date.
SYNTAX
propertyLabel
where
propertyLabel is the label for the property.
EXAMPLES
NOTES
Reference Forms
135
C H A P T E R
Range
5
The Range reference form specifies a series of objects of the same class
in the same container. You can specify the objects with a pair of indexes
(such as words 12 thru 24) or with a pair of boundary objects (such as
words from paragraph 3 to paragraph 5).
SYNTAX
pluralclassName
where
className is a singular class ID (such as word or paragraph).
pluralclassName is the plural class identifier defined by AppleScript or an
application (such as words or paragraphs).
boundaryReference1 and boundaryReference2 are references to objects that bound
the range. The range includes the boundary objects. You can use the reserved
word beginning in place of boundaryReference1 to indicate the position before
the first object of the container. Similarly, you can use the reserved word end
in place of boundaryReference2 to indicate the position after the last object in
the container.
startIndex and stopIndex are the indexes of the first and last object of the range
(such as 1 and 10 in words 1 thru 10).
VALUE
The value of a Range reference is a list of the objects in the range. If the
specified container does not contain all of the objects specified in the range, an
error is returned. For example, the following reference results in an error.
paragraphs 1 thru 3 of {1, 2, 3}
--results in an error
136
Reference Forms
C H A P T E R
EXAMPLES
The following examples and results use the Scriptable Text Editor document
shown in Figure 5-2.
Figure 5-2
Reference Forms
137
C H A P T E R
To get the result, AppleScript first gets the value of the container, which is a list
of two paragraphs:
{"This is paragraph one.", "This is paragraph two."}
AppleScript then gets every word of the resulting list, which results in a list
of two lists:
{{"This", "is", "paragraph", "one"},
{"This", "is","paragraph", "two"}}
NOTES
138
Reference Forms
C H A P T E R
Relative
5
The Relative reference form specifies an object or a location by describing its
position in relation to another object, known as the base, in the same container.
SYNTAX
EXAMPLES
The following references specify the word immediately before the first figure.
word before figure 1
word in front of figure 1
The following examples specify the insertion point immediately before the
tenth paragraph.
before paragraph 10
in front of paragraph 10
Reference Forms
139
C H A P T E R
The following example contains three references. The first two are Index
references that specify the front document and the first word. The third
is a Relative reference that specifies the insertion point before the tenth
paragraph. The command moves the first word to the insertion point
before the tenth paragraph.
tell front document of application "Scriptable Text Editor"
move word 1 to before paragraph 10
end tell
NOTES
You can specify only a single object with the Relative form. You can use the
form to specify an object that is either before or after the base object.
If it is possible for the specified object to contain the base object (as in the
expression paragraph before word 99), the reference does not specify
the container but instead specifies the object immediately before or after the
container of the base object. For example, the expression paragraph before
word 99 specifies the paragraph immediately before the paragraph containing
the ninety-ninth word.
All applications allow you to specify a base object belonging to the same
class as the desired object (such as window in back of window "Big").
Not all allow you to specify a base of a different object class (such as word
before figure 1). The possible base classes for a particular class are up
to each application.
140
C H A P T E R
the word it refers to each paragraph in the document Product Intro. The
filter, contains "dynamo", is applied to each paragraph in the document,
resulting in a smaller container whose paragraphs all contain the string
"dynamo". The reference specifies the second paragraph of that smaller
container.
141
C H A P T E R
A Filter reference includes one or more tests. Each test is a Boolean expression
that compares a property or element of each object being tested, or the objects
themselves, with another object or value. Table 5-2 shows some Filter references,
the Boolean expressions they contain, and what is being tested in each reference.
Table 5-2
Filter reference
Boolean expression
length > 10
The length
property of
each word
The first
character of
each word
it contains "el"
The words
themselves
Note
142
C H A P T E R
Because each test is a Boolean expression, it can also include the Boolean
operator Not. For example, the reference
words whose length > 10 and not it contains "M"
refers to only those words containing more than ten characters and not
containing the letter M. The expression it contains "M" is a valid
Boolean expression, and applying the Boolean Not operator to it, as in
not (it contains "M")
inverts the value of the expression, so that a true value becomes false, and a
false value becomes true.
A more elegant way to apply the Boolean Not operator to the expression
it contains "M" is
it doesn't contain "M"
The expression it doesn't contain "M" is a synonym for the expression
not (it contains "M"). AppleScript supports synonyms for many of its
operators. Using a synonym doesnt change the meaning of an expression, but
it can make the expression easier to read. Operators and synonyms are listed in
Chapter 6, Expressions.
143
C H A P T E R
References to Files
144
C H A P T E R
145
C H A P T E R
References to Applications
146
C H A P T E R
You can specify an application on the local computer with a string of the form
"Disk:Folder1:Folder2:...:ApplicationName" that specifies the applications
exact location. If AppleScript cant find the application in that location, it
displays a directory dialog box asking where the application is located.
You can also specify an application on the local computer with only the
applications name ("ApplicationName"). In this case, AppleScript attempts to
find an application of that name among currently running applications. If the
application isnt running, AppleScript attempts to locate it in the current
directory. If the application isnt in the current directory, AppleScript displays a
directory dialog box asking where the application is located. If the name of the
application you select is different from the name specified in the script, the
name in the script changes to match the name of the application you select.
When you run a script on the same computer on which it was compiled (that is,
on which it was last run or saved, or had its syntax checked), AppleScript finds
the application you specified in the original script even if you have moved it or
changed its name. If the application has been removed, AppleScript searches
for another version of the same application.
As with aliases, it is often convenient to store a reference to an application in
a variable:
set x to application "Scriptable Text Editor"
x
tell x to quit
If you save this script as a script application or compiled script, move the
Scriptable Text Editor application to another location, change its name,
then open the script again, the name "Scriptable Text Editor" in
the script changes to reflect the applications new name, and the script still
works correctly.
147
C H A P T E R
148
C H A P T E R
Figure 6-0
Listing 6-0
Table 6-0
Expressions
An expression is any series of AppleScript words that has a value. You use
expressions to represent or derive values in scripts. When AppleScript
encounters an expression, it converts it into an equivalent value. This is
known as evaluation.
Chapter 3 describes and gives examples of the simplest kinds of expressions,
called literal expressions, which are representations of values in scripts. This
chapter begins by describing how to evaluate expressions. It then describes five
additional types of expressions:
variables and script properties, which are named containers for values
the AppleScript property Text Item Delimiters, which determines the text
item delimiters used by AppleScript in all scripts
reference expressions, which are expressions that derive the value of
an object
operations, which are expressions that derive values from other values
Results of Expressions
The result of any expression is its value.You can use the Script Editor to
display the result of an expression by typing an expression on a line by
itself and running the script. AppleScript returns the value of the expression.
Heres an example:
1. Open the Script Editor if it is not already open.
2. Type the following expression in the editor subwindow:
3 + 4
Results of Expressions
149
C H A P T E R
Expressions
Variables
6
A variable is a named container in which to store a value. When AppleScript
encounters a variable in a statement, it evaluates the variable by getting its
value. Variables are contained in a script, not in an application, and their values
are normally lost when you close the script that contains them. If you need to
keep track of variable values that are persistent even after you close a script or
shut down your computer, use properties instead of variables. See Script
Properties, which begins on page 156, for more information.
Unlike variables in many other programming languages, AppleScript variables
can hold values of any class. For example, you can use the following sequence
of assignment statements to set x to a string value, an integer value, and finally
a Boolean value:
set x to "Title"
set x to 12
set x to True
The name of a variable is a series of characters, called an identifier, that you
specify when you create the variable.
Creating Variables
To create a variable in AppleScript, assign it a value. There are two commands
for doing this:
150
Set
Copy
Variables
C H A P T E R
Expressions
With the Set command, list the variable name first, followed by the value you
want to assign:
set myName to "Pegi"
With the Copy command, list the value first, followed by the variable name:
copy "Pegi" to myName
Statements like these that assign values to variables are called assignment
statements.
The variable name is a series of characters called an identifier. AppleScript
identifiers are not case sensitivefor example, the variables myname, myName,
and MYNAME all represent the same value. The rules for specifying identifiers
are listed in Identifiers on page 27.
You can list an expression in place of a value in an assignment statement.
AppleScript evaluates the expression and assigns the resulting value to the
variable. For example, the following statement creates a variable called
myNumber whose value is the integer 17.
set myNumber to 5 + 12
You can also assign a reference as the value of a variable. In this case,
AppleScript gets the value of the object specified in the reference and assigns
it to the variable. For example, the following statement gets the value of
the first word of the document called Reporta stringand stores it in a
variable called myWord.
set myWord to word 1 of document "Report" of application
"Scriptable Text Editor"
You can do the same thing with the Copy command:
copy word 1 of document "Report" of application
"Scriptable Text Editor" to myWord
Variables
151
C H A P T E R
Expressions
The results of the two types of assignment statements are the same in all
cases except when the value being assigned is a list, record, or script object.
The Copy command makes a new copy of the list, record, or script object,
and the Set command creates a variable that shares data with the original list,
record, or script object. For more information, refer to Data Sharing on
page 154.
Using Variables
To use the value of a variable in a script, include the variable in a command or
expression. For example, the first statement in the following example creates a
variable, called myName, whose value is the string "Mitch". The second
statement uses the variable myName in place of a string as the default
answer parameter of the Display Dialog command.
set myName to "Mitch"
display dialog "What is your name?" default answer myName
If you assign a new value to a variable, it replaces the old value. The following
script shows what happens when you assign a new value. It uses the Display
Dialog command to display the values. Try running this script:
set myName to "Mitch"
display dialog ("The value of myName is now " & myName)
buttons "Sure Is" default button 1
set myName to "Warren"
display dialog ("The value of myName is now " & myName)
buttons "You Betcha" default button 1
The first Display Dialog command displays the value stored by the first
assignment statement (the string "Mitch"). The next Display Dialog
command displays the value after the second assignment statement (the
string "Warren").
152
Variables
C H A P T E R
Expressions
To create a variable whose value is a reference instead of the value of the object
specified by a reference, use the A Reference To operator. Heres an example:
set myDoc to a reference to document "Report"
of application "Scriptable Text Editor"
The value of the variable myDoc is the reference
document "Report" of application "Scriptable Text Editor"
After you create a variable whose value is a reference, you can use it in a script
anywhere a reference is required. When AppleScript executes the statement
containing the variable, it replaces the variable with the reference. For example,
when AppleScript executes the statement
tell myDoc
get word 1
end tell
it replaces the variable myDoc with the reference document "Report" of
application "Scriptable Text Editor".
The syntax for using the A Reference To operator is
[a] ( ref [to] | reference to ) reference
where reference is a reference to an object. As indicated in the syntax description,
there are many ways to shorten expressions containing A Reference To. For
example, all of these expressions are equivalent:
set myDoc to a reference to document "Report" of
application"Scriptable Text Editor"
set myDoc to reference to document "Report" of
application "Scriptable Text Editor"
set myDoc to a ref to document "Report" of application
"Scriptable Text Editor"
Variables
153
C H A P T E R
Expressions
Data Sharing
Data sharing allows you to create two or more variables that share the same
list, record, or script object data; it can be used to promote efficiency when
working with large data structures. Only data in lists, records, and script
objects can be shared; you cannot share other values. In addition, the shared
structures must all be on the same computer.
To create a variable that shares data with another variable whose value is a list,
record, or script object, use the Set command. For example, the second Set
command in the following example creates the variable yourList, which
shares data with the previously defined variable myList.
set myList to { 1, 2, 3 }
set yourList to myList --this command creates yourList,
--which shares data with myList
set item 1 of myList to 4
get yourList --result:{ 4, 2, 3}
If you update myList by setting the value of its first item to 4, then the value
of both myList and yourList is {4, 2, 3}. Rather than having multiple
copies of shared data, the same data belongs to multiple structures. When one
structure is updated, the other is automatically updated.
154
Variables
C H A P T E R
Expressions
To avoid data sharing for lists, records, and script objects, use the Copy
command instead of the Set command. The Copy command makes a
copy of the list, record, or script object. Changing the value of the original
changes does not change the value of the variable. Heres an example of
using Copy instead of Set to create the variable yourList.
set myList to { 1, 2, 3 }
copy myList to yourList --this command makes a copy of
--mylist
set item 1 of myList to 4
get yourList --result: { 1, 2, 3 }
If you update myList, the value of yourList is still {1, 2, 3}.
Scope of Variables
The scope of a variable determines where else in a script you may refer to the
same variable. The scope of a variable in turn depends on where you declare it
and whether you declare it as global or local.
After you define a global variable in a script, you can make subsequent
references to the same variable either at the top level of the script or in any
of the scripts subroutines. After you define a local variable, you can make
subsequent references to the same variable only at the same level of the script
at which you defined the variable.
AppleScript assumes that all variables defined at the top level of a script or
within its subroutines are local unless you explicitly declare them as global. For
more detailed information and examples of the use of variables in subroutines,
see Recursive Subroutines, which begins on page 225.
You can also declare variables within script objects. The scope of variables in a
script object is limited to that script object. For more information, see Scope of
Script Variables and Properties, which begins on page 252.
Variables
155
C H A P T E R
Expressions
Predefined Variables
Script Properties
Script properties are labeled containers for values that you can use in much the
same way you use variables. The value of a script property persists until you
recompile the script that contains it, and you can easily set the propertys initial
value without resetting it each time the script is run. You can accomplish the
same thing with a global variable, but it is usually more convenient to use a
property for this purpose.
This section describes how to define script properties.
Note
156
Script Properties
C H A P T E R
Expressions
To see how script properties work, try running the following script, which
contains a script property called theCount.
property theCount : 0
set theCount to theCount+1
display dialog "The value of theCount is: " & theCount
as string
The first time you run the script, the value of theCount is set to 0. The Set
command adds one to theCount, and the Display Dialog command displays
the value of theCount, which is 1.
Now run the script again. The Set command adds 1 to the value of theCount
(which is still one because it has not been reset), and the Display Dialog
command reports a value of 2. If you run the script a third time, the value of
theCount is 3, and so on.
Now save the script as a compiled script. Close the script, and then open and
run it without making any changes. The value of theCount is one more than it
was before you closed the script.
Script Properties
157
C H A P T E R
Expressions
Like the scope of a variable, the scope of a script property determines where
else in a script you may refer to the same property ID. The scope of a property
in turn depends on where you declare it.
You can declare a property at the top level of a script or at the top level of a
script object. If you declare it at the top level of a script, a property identifier is
visible throughout the script. If you declare it at the top level of a script object,
a property identifier is visible only within that script object. After declaring a
property, you can use the same identifier as a separate variable only if you first
declare it as a local variable.
For detailed information and examples of the use of properties in subroutines,
see Scope of Script Variables and Properties, which begins on page 252.
AppleScript Properties
You can use the global variable AppleScript to get properties of AppleScript
itself rather than properties of the current target. You can refer to this global
variable from any part of any script. Currently, the Text Item Delimiters
property is the only AppleScript property available.
The Text Item Delimiters property consists of a list of strings used as delimiters
by AppleScript when it coerces lists to strings or gets text items from strings.
You can get and set the current value of AppleScripts Text Item Delimiters.
Normally, AppleScript doesnt use any delimiters. For example, the script
{"bread", "milk", "butter", 10.45} as string
158
AppleScript Properties
C H A P T E R
Expressions
AppleScript Properties
159
C H A P T E R
Expressions
Reference Expressions
160
Reference Expressions
C H A P T E R
Expressions
When AppleScript executes the statement, it gets the value of the reference
word 1 of front document of application "Scriptable Text
Editor"a stringand then coerces it to an integer, if possible. (For
information about the Repeat statement, refer to Chapter 7, Control
Statements. For information about coercions, refer to Coercing Values
on page 68.)
Operations
Operations are expressions that use operators to derive values from other
values. AppleScript includes operators for performing arithmetic operations,
comparing values, performing Boolean evaluations, and coercing values.
The values from which operators derive values are called operands. Each
operator can handle operands of specific classes, which are defined in the
definition of the operator. For example, the operands for the addition (+)
operator must belong to the class Integer or Real, while the operand for the
Not operator must belong to class Boolean. Certain operators work with
operands from a variety of classes. For example, you can use the concatenation
operator (&) to join two strings, two lists, or two records.
The result of each operation is a value of a particular class. For many operators,
such as the equality operator (=) and the greater than operator (>), the class of
the result is always the samein these cases, Boolean. For other operators,
such as the concatenation operator (&), the class of the result depends on the
class of the operands. For example, the result of concatenating two strings is a
string, but the result of concatenating two integers is a list of integers.
If you use an operator with operands of the wrong classes, AppleScript
attempts to coerce the operands to the correct class, if possible. For example,
the concatenation operator (&) works with strings, lists, or records. When
AppleScript evaluates the following expression, it coerces the integer 66 to a
string before concatenating it with the string "Route".
"Route " & 66
--result: "Route 66"
Operations
161
C H A P T E R
Expressions
162
Operations
C H A P T E R
Expressions
Table 6-1
AppleScript operators
Operator
Description
and
or
&
=
is
equal
equals
[is] equal to
Operations
163
C H A P T E R
Expressions
Table 6-1
Operator
Description
(Optionequal sign)
is not
isn't
isn't equal [to]
is not equal [to]
doesn't equal
does not equal
>
[is] greater than
comes after
is not less than or equal [to]
isn't less than or equal [to]
<
[is] less than
comes before
is not greater than or equal
[to]
isn't greater than or equal
[to]
(Optiongreater-than sign)
>=
[is] greater than or equal [to]
is not less than
isn't less than
does not come before
doesn't come before
164
Operations
C H A P T E R
Expressions
Table 6-1
Operator
Description
(Optionless-than sign)
<=
[is] less than or equal [to]
is not greater than
isn't greater than
does not come after
doesn't come after
start[s] with
begin[s] with
end[s] with
contain[s]
Operations
165
C H A P T E R
Expressions
Table 6-1
Operator
Description
is in
is contained by
is not in
is not contained by
isn't contained by
166
Operations
C H A P T E R
Expressions
Table 6-1
Operator
Description
(Option-slash)
/
div
mod
as
Operations
167
C H A P T E R
Expressions
Table 6-1
Operator
Description
not
BOOLEAN EXPRESSION
168
Operations
C H A P T E R
Expressions
CLASS IDENTIFIER
Two class identifiers are equal if they are the same identifier. They are not equal
if they are different identifiers.
CONSTANT
Two constants are equal if they are the same. They are not equal if they
are different.
DATA
Two data values are equal if they are the same length in bytes and their bytes
are the same (AppleScript does a byte-wise comparison).
DATE
Two dates are equal if they both represent the same date, even if they are
expressed in different formats. For example, the following expression is true,
because date "12/5/92" and date "December 5th, 1992" represent
the same date.
date "12/5/92" = date "December 5th, 1992"
INTEGER
Two integers are equal if they are the same. They are not equal if they
are different.
LIST
Two lists are equal if each item in the list to the left of the operator is equal to
the item in the same position in the list to the right of the operator. They are not
equal if items in the same positions in the lists are not equal or if the lists have
different numbers of items. For example,
{ (1 + 1), (4 > 3) } = {2, true}
is true, because (1 + 1) evaluates to 2, and (4 > 3) evaluates to true.
Operations
169
C H A P T E R
Expressions
REAL
Two real numbers are equal if they both represent the same real number, even
if the formats in which they are expressed are different. For example, the
following expression is true.
0.01 is equal to 1e10-2
Two real numbers are not equal if they represent different real numbers.
RECORDS
Two records are equal if they both contain the same collection of properties and
if the values of properties with the same labels are equal. They are not equal if
the records contain different collections of properties, or if the values of
properties with the same labels are not equal. The order in which properties are
listed does not affect equality. For example, the following expression is true.
{ name:"Eric", mileage:"8000" } = { mileage:"8000",
name:"Eric"}
REFERENCE
Two references are equal if their classes, reference forms, and containers are
identical. They are not equal if their classes, reference forms, and containers are
not identical, even if they refer to the same object.
For example, the expression x = y in the following Tell statement is true,
because the classes (word), reference forms (Index), and containers
(paragraph 1 of document "Intro" of application
"Scriptable Text Editor") of the two references are identical.
tell document "Intro" of application
"Scriptable Text Editor"
set x to a reference to word 1 of paragraph 1
set y to a reference to word 1 of paragraph 1
x = y
end tell
--result:true
170
Operations
C H A P T E R
Expressions
STRING
Two strings are equal if they are both the same series of characters. They are
not equal if they are different series of characters. AppleScript compares strings
character by character. It does not distinguish uppercase from lowercase letters
unless you use a Considering statement to consider the case attribute. For
example, the following expression is true.
"DUMPtruck" is equal to "dumptruck"
AppleScript considers all characters and punctuation, including spaces, tabs,
return characters, diacritical marks, hyphens, periods, commas, question
marks, semicolons, colons, exclamation points, backslash characters, and single
and double quotation marks in string comparisons. AppleScript ignores style in
string comparisons.
Operations
171
C H A P T E R
Expressions
Note
The Greater Than and Less Than operators work with dates, integers, real
numbers, and strings.
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
STRING
A string is greater than (comes after) another string if it would appear after the
other string in an English-language dictionary. For example,
"zebra" comes after "aardvark"
and
172
Operations
C H A P T E R
Expressions
The Starts With and Ends With operators work with lists and strings.
LIST
A list starts with another list if the values of the items in the list to the right of
the operator are equal to the values of the items at the beginning of the list to
the left. A list ends with another list if the values of the items in the list to the
right of the operator are equal to the values of the items at the end of the list to
Operations
173
C H A P T E R
Expressions
the left. In both cases, the items in the two lists must be in the same order. Both
Starts With and Ends With work if the operand to the right of the operator is a
single value. For example,
{ "this", "is", 2, "cool" } ends with "cool"
and
{ "this", "is", 2, "cool" } starts with "this"
and
{ "this", "is", 2, "cool" } starts with { "this", "is" }
are all true.
STRING
A string starts with another string if the characters in the string to the right of
the operator are the same as the characters at the beginning of the string to the
left. For example,
"operand" starts with "opera"
is true.
A string ends with another string if the characters in the string to the right of
the operator are the same as the characters at the end of the string to the left.
For example,
"operand" ends with "and"
is true.
AppleScript compares strings character by character according to the rules for
the Equal operator.
174
Operations
C H A P T E R
Expressions
Contains, Is Contained By
LIST
A list contains another list if the list to the right of the operator is a sublist
of the list to the left of the operator. 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,
{ "this", "is", 1 + 1, "cool" } contains { "is", 2 }
is true, but
{ "this", "is", 2, "cool" } contains { 2, "is" }
is false.
A list is contained by another list if the list to the left of the operator is a sublist
of the list to the right of the operator. For example,
{ "is", 2} is contained by { "this", "is", 2, "cool" }
is true. Both Contains and Is Contained By work if the sublist is a single
value. For example,
{ "this", "is", 2, "cool" } contains 2
and
2 is contained by { "this", "is", 2, "cool" }
are true.
Operations
175
C H A P T E R
Expressions
RECORD
A record contains another record if all the properties in the record to the
right of the operator are included in the record to the left, and the values
of properties in the record to the right are equal to the values of the corresponding properties in the record to the left. A record is contained by another record
if all the properties in the record to the left of the operator are included in the
record to the right, and the values of the properties in the record to the left
are equal to the values of the corresponding properties in the record to the
right. The order in which the properties appear does not matter. For example,
{ name:"Eric", mileage:"8000", description:"fast"}
contains { description:"fast", name:"Eric" }
is true.
STRING
A string contains another string if the characters in the string to the right of the
operator are equal to any contiguous series of characters in the string to the left
of the operator. For example,
"operand" contains "era"
is true, but
"operand" contains "dna"
is false.
A string is contained by another string if the characters in the string to the left
of the operator are equal to any series of characters in the string to the right of
the operator. For example, this statement is true:
"era" is contained by "operand"
176
Operations
C H A P T E R
Expressions
Concatenation
STRING
The concatenation of two strings is a string that begins with the characters in
the string to the left of the operator, followed immediately by the characters
in the string to the right of the operator. AppleScript does not add spaces or
other characters between the two strings. For example,
"dump" & "truck"
returns the string "dumptruck".
If the operand to the left of the operator is a string, but the operand to the right
is not, AppleScript attempts to coerce the operand to the right to a string. For
example, when AppleScript evaluates the expression
"Route " & 66
it coerces the integer 66 to the string "66", and the result is
"Route 66"
RECORD
The concatenation of two records is a record that begins with the properties
of the record to the left of the operator, followed by the properties of the record
to the right of the operator. If both records contain properties with the same
name, the value of the property from the record to the left of the operator
appears in the result. For example, the result of the expression
{ name:"Eric", mileage:"8000" } &
{ name:"Mitch", framesize:58 }
is
{ name:"Eric", mileage:"8000", frameSize:58 }
Operations
177
C H A P T E R
Expressions
The concatenation of two operands that are not strings or records is a list
whose first item is the value of the operand to the left of the operator, and
whose second item is the value of the operand to the right of the operator.
If the operands to be concatenated are lists, then the result is a list containing
all the items in the list to the left of the operator, followed by all the items in
the list to the right of the operator. For example,
{ "This" } & { "and", "that" }
returns a list containing three items:
{ "This", "and", "that" }
Operator Precedence
178
Operations
C H A P T E R
Expressions
Table 6-2
Order
Operator precedence
Operators
Associativity
Type of operator
( )
Innermost to
outermost
Grouping
+
-
Unary
Right to left
Exponentiation
*
/
div
mod
Left to right
+
-
Left to right
as
Left to right
Coercion
<
>
None
Comparison
None
not
Unary
Logical negation
10
and
Left to right
11
or
Left to right
Operations
179
C H A P T E R
Expressions
Date-Time Arithmetic
AppleScript supports these operations with the + and - operators on date and
time difference values:
date + timeDifference
--result: date
date - date
--result: timeDifference
date - timeDifference
--result: date
where date is a date value and timeDifference is an integer value specifying a
time difference in seconds.
To simplify the notation of time differences, you can also use one or more of
these constants:
minutes
60
hours
60 * minutes
days
24 * hours
weeks
7 * days
Heres an example:
date "Apr 15, 1992" + 4 * days + 3 * hours + 2 * minutes
It is often useful to be able to specify a time difference between two dates;
for example:
set timeInvestment to current date - "May 16, 1992"
After running this script, the value of the timeInvestment variable is an
integer that specifies the number of seconds between the two dates. If you then
add this time difference to the starting date (May 16, 1992), AppleScript returns
a date value equal to the current date when the timeInvestment variable
was set.
180
Operations
C H A P T E R
Expressions
Operations
181
C H A P T E R
Figure 7-0
Listing 7-0
Table 7-0
Control Statements
Control statements are statements that control when and how other statements
are executed. Most control statements are compound statementsthat is,
statements that contain other statements.
By default, AppleScript executes the statements in a script in sequence, one
after the other. Control statements can change the order in which AppleScript
executes statements by causing AppleScript to repeat or skip statements or go
to a different statement.
This chapter describes the following control statements:
Tell, which defines the default target to which commands are sent if no
direct object is specified
If, which allows you to execute or skip statements based on the outcome of
one or more tests
183
C H A P T E R
Control Statements
Most control statements are compound statements that contain other statements. For example, the If statement
if today = last day of theMonth
set MonthlyReport to prepareReport(currentMonth)
print MonthlyReport
end if
is a compound statement that contains a Set command and a Print command.
Compound statements begin with one or more reserved words, such as if in
the example above, that identify the type of compound statement. The last line
of a compound statement is always end, which can optionally include the
word that begins the control statement.
Control statements can contain other control statements. For example, this Tell
statement contains the If statement of the previous example.
tell application "ReportWizard"
if today = last day of theMonth
set MonthlyReport to prepareReport(currentMonth)
print MonthlyReport
end if
end tell
Control statements that are contained within other control statements are
sometimes called nested control statements.
All control statements can be compound statements. In addition, some control
statements can be written as single statements. For example, the statement
if (x > y) then return x
is equivalent to
if (x > y) then
return x
end if
184
C H A P T E R
Control Statements
You can use a simple statement only when youre controlling the execution of a
single statement (such as return x in the previous example).
Tell Statements
Tell statements specify the default target, the object to which commands are
sent if they do not include a direct parameter. For example, in the following
Tell statement, the Close command does not include a direct parameter.
tell front window
close
end tell
As a result, the Close command is sent to the front window, the default target
specified in the Tell statement.
When AppleScript encounters a partial reference (a reference that does not
specify every container of an object), it uses the default target to complete it.
For example, in the following Tell statement, the reference word 3 does not
specify all of the containers of the word object, so AppleScript completes it with
the default target.
tell front document of application "Scriptable Text Editor"
delete word 3
end tell
The result is that the Delete command is sent to the third word of the front
document of the Scriptable Text Editor.
A Tell statement also indicates which dictionary AppleScript should use to
interpret words contained in the statement. For example, the previous Tell
statement tells AppleScript to use the Scriptable Text Editor dictionary, which
contains the definitions for the Delete command and the word object. If the
Tell statement had not specified the application, AppleScript would not have
understood the Delete command.
If you refer to another application within a Tell statement to an application,
AppleScript uses the dictionaries of both applications to interpret the words
in the statement. For example, in response to the following Tell statement,
Tell Statements
185
C H A P T E R
Control Statements
AppleScript uses the Microsoft Excel dictionary for definitions of the Copy
command and cell object, and the Scriptable Text Editor dictionary for the
definition of the word object.
tell application "Microsoft Excel"
copy word 5 of document "TestDocument" of application
"Scriptable Text Editor" to Cell "R1C1" of Document
"spreadsheet"
end tell
AppleScript defines two variables, it and me, that you can use in
Tell statements.
The variable it is the default target. The value of it is a reference, as in
tell document "Introduction" of application
"Scriptable Text Editor"
get name of it
end tell
The reference name of me refers to the name property of the current script.
The result of the Get command is the string "Script".
186
Tell Statements
C H A P T E R
Control Statements
AppleScript defines another word, my, that you can use instead of the phrase
of me. For example, the following script is equivalent to the previous example:
property name : "Script"
tell document "Introduction" of application
"Scriptable Text Editor"
get my name
end tell
--result: "Script"
If AppleScript cannot find the property in the dictionary of the default target of
the Tell statement, then it assumes you want the property of the current script.
For example, the result of the Get command in the following Tell statement is
1000000.
property x : 1000000
tell document "Introduction" of application
"Scriptable Text Editor"
get x
end tell
--result: 1000000
Tell Statements
187
C H A P T E R
Control Statements
Note
SYNTAX
EXAMPLE
NOTES
188
Tell Statements
C H A P T E R
Control Statements
SYNTAX
tell referenceToObject
[ statement ]...
end [ tell ]
where
referenceToObject is a reference to an application object, system object, or
script object.
statement is any AppleScript statement.
EXAMPLES
Tell Statements
189
C H A P T E R
Control Statements
NOTES
If Statements
190
If Statements
C H A P T E R
Control Statements
else
set myMessage to " is equal to "
end if
set myResult to (x as string) & myMessage & (y as string)
If the expression x > y is true, the value of the variable myMessage is set to
" is greater than " and the If statement is finished. Control passes to the
Set statement, which uses the value of the variable myMessage to set the value
of another variable, called myResult. The value of myResult is a string such
as "7 is greater than 5". If the first Boolean expression is false, the
next expression, x < y, is evaluated with similar results.
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. For example, suppose
the values of x and y in the previous example are both 112. The first two tests,
x > y and x < y, fail. The value of the variable myMessage is set to " is
equal to ", and the value of myResult is "112 is equal to 112".
If statements can be more elaborate, as in this example:
display dialog "How many dependents?" default answer ""
set dependents to (text returned of result) as integer
display dialog "Have you ever been audited?" buttons
{"No", "Yes"}
if button returned of result = "Yes" then
set audit to true
else
set audit to false
end if
if dependents < 9 and audit = false then
display dialog "No extra forms are required."
else if dependents < 9 and audit = true then
display dialog "You might need to file an extra form."
If Statements
191
C H A P T E R
Control Statements
If (Simple Statement)
A simple If statement contains one Boolean expression and a statement to be
executed if the value of the Boolean expression is true.
SYNTAX
192
If Statements
C H A P T E R
Control Statements
If (Compound Statement)
if Boolean [ then ]
[ statement ]...
[ else if Boolean [ then ]
[ statement ]...]...
[ else
[ statement ]...]
end [ if ]
where
Boolean is an expression whose value is true or false.
statement is any AppleScript statement.
EXAMPLE
If Statements
193
C H A P T E R
Control Statements
Repeat Statements
194
Repeat Statements
C H A P T E R
Control Statements
Repeat Statements
195
C H A P T E R
Control Statements
Note that two of the strings in the preceding statement include a return
character. These are valid strings even though the surrounding quotation
marks are on different lines within the statement. Running the preceding
statement results in the following text:
David Numberman's Top 10 Numbers for Lists
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
The line
repeat with n from 1 to 10
specifies n as the looping variable, a variable that controls the number
of iterations.
At the beginning of each iteration, AppleScript adds 1 to the value of n. When
the value of the looping variable reaches 10, AppleScript exits the loop.
The expression n as string coerces an integer into a string, while the &
(concatenation) operator joins two strings to make a single string. For more
information about operators and coercing values, see Chapter 6, Expressions.
196
Repeat Statements
C H A P T E R
Control Statements
Repeat (forever)
The Repeat (forever) form of the Repeat statement is an infinite loop. The only
way to exit the loop is by using an Exit statement.
SYNTAX
repeat
[ statement ]...
end [ repeat ]
where
statement is any AppleScript statement.
This is an infinite loop; you must use an Exit statement to exit the loop
(see page 204).
EXAMPLE
Repeat Statements
197
C H A P T E R
Control Statements
SYNTAX
EXAMPLE
The following example numbers the paragraphs of a document with the Repeat
(number) Times form of the Repeat statement.
tell document "List"
set numParagraphs to (count paragraphs)
set paragraphNum to 1
repeat numParagraphs times
set paragraph paragraphNum to (paragraphNum as string) & " "
& paragraph paragraphNum
set paragraphNum to paragraphNum + 1
end repeat
end tell
198
Repeat Statements
C H A P T E R
Control Statements
Repeat While
The Repeat While form of the Repeat statement repeats a group of statements as
long as a particular condition, specified in a Boolean expression, is met.
SYNTAX
EXAMPLE
The following example numbers the paragraphs of a document with the Repeat
While form of the Repeat statement.
tell document "List"
set numParagraphs to (count paragraphs)
set paragraphNum to 1
repeat while paragraphNum numParagraphs
set paragraph paragraphNum to (paragraphNum as string) & " "
& paragraph paragraphNum
set paragraphNum to paragraphNum + 1
end repeat
end tell
Repeat Statements
199
C H A P T E R
Control Statements
Repeat Until
7
The Repeat Until form of the Repeat statement repeats a group of statements
until a particular condition, specified in a Boolean expression, is met.
SYNTAX
EXAMPLE
This example numbers the paragraphs of a document with the Repeat Until
form of the Repeat statement.
tell document "List"
set numParagraphs to (count paragraphs)
set paragraphNum to 1
repeat until paragraphNum > numParagraphs
set paragraph paragraphNum to (paragraphNum as string) & " "
& paragraph paragraphNum
set paragraphNum to paragraphNum + 1
end repeat
end tell
200
Repeat Statements
C H A P T E R
Control Statements
SYNTAX
EXAMPLE
The following example numbers the paragraphs of a document with the Repeat
With (loopVariable) From (startValue) To (stopValue) form of the Repeat statement.
tell document "List"
repeat with n from 1 to (count paragraphs)
set paragraph n to (n as string) & " " & paragraph n
end repeat
end tell
Repeat Statements
201
C H A P T E R
Control Statements
NOTES
You can use an existing variable as the looping variable in a Repeat statement
or define a new one in the Repeat statement. You cannot change the value of
the looping variable in the loop body. The variable is undefined after the loop
has been executed, but you can redefine it outside the loop.
AppleScript evaluates startValue, stopValue, and stepValue when it begins
executing the loop and stores the values internally. If you change the values
in the body of the loop, it has no effect on the execution of the loop.
In the Repeat With (loopVariable) In (list) form of the Repeat statement, the
looping variable is a reference to an item in a list. The number of iterations is
equal to the number of items in the list. In the first iteration, the value of the
variable is item 1 of list (where list is the list you specified in the first line of
the statement), in the second iteration, its value is item 2 of list, and so on.
SYNTAX
EXAMPLE
The following example numbers the paragraphs of a document with the Repeat
With (loopVariable) In (list) form of the Repeat statement. The value of the
202
Repeat Statements
C H A P T E R
Control Statements
NOTES
You can use an existing variable as the looping variable in a Repeat statement
or define a new one in the Repeat statement. You cannot change the value of
the looping variable in the loop body. The variable is undefined after the loop
has been executed, but you can redefine it outside the loop.
AppleScript evaluates loopVariable in list as item 1 of list, item 2 of
list, item 3 of list, and so on until it reaches the last item in the list:
repeat with i in {1, 2, 3, 4}
set x to i
end repeat
--result: item 4 of {1, 2, 3, 4}
To get the value of an item in the list, you must use the contents of operator:
repeat with i in {1, 2, 3, 4}
set x to contents of i
end repeat
--result: 4
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}.
Repeat Statements
203
C H A P T E R
Control Statements
Exit
7
An Exit statement is used in a Repeat statement to exit the Repeat statement.
When AppleScript executes an Exit statement, it terminates loop execution and
resumes execution with the next statement following the Repeat statement. You
cannot use Exit statements outside of Repeat statements.
SYNTAX
exit
EXAMPLE
set i to 1
tell application "Scriptable Text Editor"
repeat
if i > (count windows)
exit
end
print window i
set i to i + 1
end repeat
end tell
Try Statements
Scripts dont always work perfectly. When a script is executed, errors can occur
in the Operating System (for example, when a specified file isnt found), in an
application (for example, when you specify an object that doesnt exist), and in
the script itself. When an error occurs, AppleScript sends a special message
known as an error message. An error message is a message that is returned by
an application, AppleScript, or the Operating System if an error occurs during
the handling of a command. An error message can include an error number,
204
Try Statements
C H A P T E R
Control Statements
Kinds of Errors
Try Statements
205
C H A P T E R
Control Statements
Script errors are error messages sent by a script using the Error command.
Scripts that define additional errors will often include descriptions of the
errors in their documentation.
Note
When an error occurs, AppleScript checks to see if the statement that caused
the error is contained in a Try statement. A Try statement is a two-part
compound statement that contains a series of AppleScript statements, followed
by an error handler to be invoked if any of those statements causes an error. If
the statement that caused the error is included in a Try statement, then
AppleScript passes control to the error handler in the Try statement. After the
error handler completes, control passes to the statement immediately following
the end of the Try statement.
If the error occurred within a subroutine and AppleScript does not find a Try
statement in that subroutine, AppleScript checks to see if the statement that
invoked the current subroutine is contained in a Try statement. If that
statement is not contained in a Try statement, AppleScript continues up the call
chain, going to the statement that invoked that subroutine, if any, and so on. If
none of the calls in the call chain is contained in a Try statement, AppleScript
stops execution of the script.
206
Try Statements
C H A P T E R
Control Statements
The error handler can include up to five parameter variables (also called
formal parameters) that represent the actual information sent in the error
message when the error occurs. When the error handler is called, the parameter
variables become local variables in the error handler.
Try
7
A Try statement is a compound statement consisting of a list of AppleScript
statements followed by an error handler to be executed if any of the statements
cause an error message.
SYNTAX
try
[ statement ]...
on error
[ errorMessageVariable ]
[ number errorNumberVariable ]
[ from offendingObjectVariable ]
[ partial result resultListVariable ]
[ to expectedTypeVariable ]
[ global variable [, variable ]...]
[ local variable [, variable ]...]
[ statement ]...
end [ error | try ]
where
statement is any AppleScript statement.
errorMessageVariable (an identifier) is a parameter variable for the expression,
usually a string, that describes the error. You use this parameter variable to
refer to the error expression within the error handler.
errorNumberVariable (an identifier) is a parameter variable for the error number
(an integer). You use this parameter variable to refer to the error number within
the error handler.
Try Statements
207
C H A P T E R
Control Statements
EXAMPLES
The following Try statement provides an error handler for the Choose File
command. (For a complete description of the Choose File command, see the
AppleScript Scripting Additions Guide.) The Choose File command returns an
error if the user clicks the Cancel button in the Choose File dialog box. The
error handler gives the user a chance to continue if an error occurs.
try
choose file
set fileName to result
208
Try Statements
C H A P T E R
Control Statements
Try Statements
209
C H A P T E R
Control Statements
Error
7
The Error command signals an error in a script.
SYNTAX
error
[ errorMessage ]
[ number errorNumber ]
[ from offendingObject ]
[ partial result resultList ]
[ to expectedType ]
where
errorMessage is an expression, usually a string, describing the error. Although
this parameter is not required, you should provide descriptive expressions
for errors wherever possible (a string is the best way to inform the user of an
error), and you should always provide an expression if you do not include a
number parameter. If you do not include an error expression, an empty string
("") is passed to the error handler.
errorNumber is the error number for the error. You do not have to include an
error number, but if you do, the number must not be any of the error numbers
listed in Appendix C, Error Messages. In general, positive numbers from 500
to 10,000 do not conflict with error numbers for AppleScript, the Operating
System, or Apple events. If you do not include a number parameter, the value
-2700 is passed to the error handler.
offendingObject is a reference to the object, if any, that caused the error. If you
provide a partial reference, AppleScript completes it using the value of the
default object.
210
Try Statements
C H A P T E R
Control Statements
resultList 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. If you do
not include a partial result parameter, an empty list ({}) is passed to the
error handler.
expectedType is a class identifier. 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 shows how to signal and provide a handler for an error.
The CentimeterConversion subroutine signals error number 750 if its
parameter is not a number. The error handler tests the error number, and if it
is equal to 750, returns a string indicating that the parameter must be a real
number or integer.
on CentimeterConversion from x
--make sure the parameter is a real number or an integer
try
if {integer, real} contains class of x then
return x * 2.54
else
error number 750
end if
on error number errorNumber
if errorNumber = 750 then
return "The parameter must be a real number or integer."
else
error errorNumber --unknown error, resignal
end if
end try
end CentimeterConversion
CentimeterConversion from "Cupertino"
--result: "The parameter must be a real number or integer."
Try Statements
211
C H A P T E R
Control Statements
You can use the Error command to resignal an error. For example, in the
following Try statement, the Error command in the error handler resignals
the error exactly as it was received.
try
word 5 of "one two three"
on error number errNum from badObj
--statements that handle the error
error number errNum from badObj
end try
In the following Try statement, the Error command in the error handler
resignals the error, but changes the error message and error number. The
new error number is 600.
try
word 5 of "one two three"
on error
--statements that determine the cause of the error
error "There are not enough words." number 600
end try
212
Try Statements
C H A P T E R
Control Statements
213
C H A P T E R
Control Statements
Considering/Ignoring
Considering and Ignoring statements cause AppleScript to consider or ignore
specific characteristics, called attributes, as it executes groups of statements.
SYNTAX
ATTRIBUTES
214
C H A P T E R
Control Statements
EXAMPLES
considering case
"a" comes before "b"
end considering
considering case and white space but ignoring diacriticals
"a" comes after "b"
end considering
215
C H A P T E R
Control Statements
ignoring punctuation
if "this !,:book" = "this book" then
(* additional statements *)
end if
end ignoring
NOTES
216
C H A P T E R
Control Statements
ignoring case
if "This or that" = "thisorthat" then beep 2 --false
ignoring white space
if "This or that" = "thisorthat" then beep 1 --true
end ignoring
end ignoring
217
C H A P T E R
Control Statements
With Timeout
With Timeout statements let you change how long AppleScript can wait before
stopping execution of application and scripting addition commands that are
sent to other applications.
SYNTAX
EXAMPLE
The following With Timeout statement gives the user five minutes, instead of
the usual one minute, to type in his or her name.
try
with timeout of 300 seconds
tell application "Scriptable Text Editor"
display dialog "What is your name?"
default answer ""
end tell
end timeout
on error
beep
end
218
C H A P T E R
Control Statements
With Transaction
219
C H A P T E R
Control Statements
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.
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"
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.
With Transaction statements only work with applications that explicitly
support them. 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
220
C H A P T E R
Figure 8-0
Listing 8-0
Table 8-0
Handlers
Using Subroutines
Using Subroutines
221
C H A P T E R
Handlers
222
Using Subroutines
C H A P T E R
Handlers
Types of Subroutines
There are two types of subroutines: those with labeled parameters and those
with positional parameters.
Labeled parameters are identified by their labels and can be listed in any
order. Subroutines with labeled parameters can also have a direct parameter.
The direct parameter, if present, must be listed first.
Positional parameters must be listed in a specific order, which is defined in
the subroutine definition.
Using Subroutines
223
C H A P T E R
Handlers
If you need to call a subroutine from within a Tell statement, you must use the
reserved words of me or my to indicate that the subroutine is part of the
scriptnot a command that should be sent to the object of the Tell statement.
For example, the minimumValue subroutine call in the following Tell
statement is unsuccessful, because AppleScript sends the minimumValue
command to the Scriptable Text Editor. (You get an error message saying
that the Scriptable Text Editor does not understand the minimumValue
command.)
tell application "Scriptable Text Editor"
minimumValue(12, 400)
copy result as string to word 15 of front document
end tell
(* result: the subroutine call is unsuccessful because
AppleScript sends the minimumValue command to the
Scriptable Text Editor *)
If you use the words of me in the subroutine call, as shown in the following
Tell statement, the subroutine call is successful, because AppleScript knows
that the subroutine is part of the script.
tell application "Scriptable Text Editor"
minimumValue(12, 400) of me
copy result as string to word 15 of front document
end tell
(* result: the subroutine call is successful because the
words "of me" tell AppleScript that the minimumValue
command is part of the script *)
The word my before the subroutine call is a synonym for the words of me after
the subroutine call. For example, the following two subroutine calls are
equivalent:
minimumValue(12, 400) of me
my minimumValue(12, 400)
224
Using Subroutines
C H A P T E R
Handlers
You cannot specify the class of a parameter in a subroutine definition. You can,
however, get the value of the Class property of a parameter and check it to
see if the parameter belongs to the correct class. If it doesnt, you may be able
to coerce it with the As operator, or failing that, you can return an error.
(For information about coercing values, see Chapter 6, Expressions. For
information about returning errors, see Try Statements, which begins on
page 204.)
Heres an example of a subroutine that checks to see if its parameter is a real
number or an integer:
on CentimeterConversion from x
--make sure the parameter is a real number or an integer
if class of x is contained by {integer, real}
return x * 2.54
else
error "The parameter must be a real number or an integer"
end if
end CentimeterConversion
Recursive Subroutines
Using Subroutines
225
C H A P T E R
Handlers
226
Using Subroutines
C H A P T E R
Handlers
Using Subroutines
227
C H A P T E R
Handlers
the example calls the factorial subroutine. (You must have a compiled
script called Numeric Operations in the specified location for this script to
work correctly.)
set NumberLib to (load script file "MacHD:Scripts:Numeric Operations")
tell NumberLib
factorial(10)
end tell
Note
You cannot nest subroutine definitions; that is, you cannot define a subroutine
within a subroutine definition.
The way you call a subroutine is determined by the way the subroutine
was defined:
The sections that follow describe how to define and call subroutines.
228
C H A P T E R
Handlers
This section describes the syntax for defining and calling subroutines with
labeled parameters. Examples of subroutines that use this syntax begin
on page 232.
The definition for a subroutine with labeled parameters lists the labels to use
when calling the subroutine and the statements to be executed when it is called.
SYNTAX
( on | to ) subroutineName
[ [ of | in ] directParameterVariable ]
[ subroutineParamLabel paramVariable ]...
[ given label:paramVariable [, label:paramVariable ]...]
[ global variable [, variable ]...]
[ local variable [, variable ]...]
[ statement ]...
end [ subroutineName ]
where
subroutineName (an identifier) is the subroutine name.
directParameterVariable (an identifier) is a parameter variable (also called a
formal parameter) that represents the actual value of the direct parameter. You
use this identifier to refer to the direct parameter in the body of the subroutine
definition. As with application commands, the direct parameter must be first.
Note
229
C H A P T E R
Handlers
NOTES
230
C H A P T E R
Handlers
SYNTAX
subroutineName
[ [ of | in ] directParameter ]
[ [ subroutineParamLabel parameterValue ]
| [ with labelForTrueParam [, labelForTrueParam ]...
[ ( and | or | , ) labelForTrueParam ] ]
| [ without labelForFalseParam [, labelForFalseParam ]...]
[ ( and | or | , ) labelForFalseParam ] ]
| [ given label:parameterValue
[, label:parameterValue ]...] ]...
where
subroutineName (an identifier) is the name of the subroutine.
directParameter is the direct parameter, if one is included in the subroutine
definition. It can be any valid expression. As in application commands, the
direct parameter must be first if it is included at all.
subroutineParamLabel is one of the following labels used in the definition of
the subroutine: above, against, apart from, around, aside from, at,
below, beneath, beside, between, by, for, from, instead of, into, on,
onto, out of, over, thru (or through), under.
parameterValue is the value of a parameter, which can be any valid expression.
labelForTrueParam is 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 of how
to use a With clause, see page 233.) If you use or or a comma instead of and
with the last parameter of a with clause, AppleScript changes the of or the
comma to and during compilation.
labelForFalseParam is 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. If you use
or or a comma instead of and with the last parameter of a without clause,
AppleScript changes the or or the comma to and during compilation.
label is any parameter label used in the definition of the subroutine that is not
among the labels for subroutineParamLabel. You must use the special label
given to specify these parameters. (For an example, see Examples later in
this section.)
231
C H A P T E R
Handlers
If you use or or a comma instead of and with the last parameter of a with
clause, AppleScript changes the or or the comma to and during compiling.
NOTES
A subroutine call must include all the parameters specified in the subroutine
definition. There is no way to specify optional parameters.
When calling a subroutine, you can list any parameter-value pairs except
the direct parameter after the label given, not just the parameters that were
specified that way in the subroutine definition. For example, the following
two calls to the searchFiles subroutine described in the next section are
interchangeable.
searchFiles of {"March Expenses", "April Expenses"} for
"Le Chateau"
searchFiles of {"March Expenses", "April Expenses"}
given for:"Le Chateau"
With the exception of the direct parameter, which must directly follow the
subroutine name, labeled parameters can appear in any order. This includes
parameters listed in Given, With, and Without clauses. Furthermore, you can
include any number of Given, With, and Without clauses in a subroutine call.
232
C H A P T E R
Handlers
233
C H A P T E R
Handlers
The following subroutine uses the special label given to define a parameter
with the label rounding. By using verb forms ending with ing as labels, you
can often make subroutine calls easier to read.
to findNumbers of numberList above minLimit
given rounding:roundBoolean
set resultList to {}
repeat with i from 1 to (count items of numberList)
set x to item i of numberList
if roundBoolean = true then
copy (x + 0.5) div 1 to x
end if
if x > minLimit then
copy resultList & x to resultList
end if
end repeat
return resultList
end findNumbers
--to call findNumbers:
findNumbers of myList above 3 given rounding:true
Another way to call the findNumbers subroutine is to use a With or Without
clause to specify the value of the rounding parameter. You can use With or
Without clauses to specify parameters whose values are true or false.
--this call is equivalent to the previous example
findNumbers of myList above 3 with rounding
The subroutine parameter labels that can be used without the special label
given allow you considerable flexibility in defining handlers that sound
English-like. For example, heres a routine that takes any parameter that
can be displayed as a string and displays it in a dialog box:
on rock around the clock
display dialog (clock as string)
end rock
234
C H A P T E R
Handlers
The statement
rock around the current date
later in the same script displays the current date in a dialog box.
Heres another example of the use of subroutine parameter labels:
to check for yourNumber from bottom thru top
if bottom yourNumber and yourNumber top then
display dialog "Congratulations! You scored."
end if
end check
The statement
check for 8 from 7 thru 10
later in the same script displays the specified dialog box.
The sections that follow describe the syntax for defining and calling
subroutines with positional parameters. Examples of subroutines that use this
syntax begin on page 238.
The definition for a subroutine with positional parameters lists the order in
which to list parameters when calling the subroutine and the statements to be
executed when the subroutine is called.
235
C H A P T E R
Handlers
SYNTAX
236
C H A P T E R
Handlers
SYNTAX
NOTES
A subroutine call must include all the parameters specified in the subroutine
definition. There is no way to specify optional parameters.
You can use a subroutine call as a parameter of another subroutine call. Heres
an example.
minimumValue(2, maximumValue(x, y))
The second parameter of the call to minimumValue is the value from the
subroutine call to maximumValue. (The minimumValue subroutine is defined
in the next section.)
A call to a subroutine with positional parameters can include parameters that
arent literals as long as they evaluate to a pattern defined for the subroutine.
Similarly, the properties of a record passed to a subroutine dont have to be
given in the same order they are given in the subroutines declaration, as long
as all the properties required to fit the defined pattern are present. The
examples that follow include subroutines with positional parameters that
define a pattern.
237
C H A P T E R
Handlers
238
C H A P T E R
Handlers
A parameter pattern can be much more complex than a single list. The handler
in the next example takes two numbers and a record whose properties include
a list of bounds and displays a dialog box summarizing some of that
information:
on hello(a, b, {length:l, bounds:{x, y, w, h}, name:n})
set q to a b
set response to "Hello " & n & ", you are " & l &
" inches tall and occupy position (" & x & ", " & y & ")."
display dialog response
end hello
set thing to {bounds:{1, 2, 4, 5}, name:"George", length:72}
hello (2, 3, thing)
As you can see from this example, a call to a subroutine with patterned parameters can include parameters that arent literals, as long as they evaluate to the
appropriate pattern. Similarly, the properties of a record passed to a subroutine
with patterned parameters dont have to be given in the same order in which
they are given in the subroutines definition, as long as all the properties
required to fit the pattern are present.
A Return statement allows you to stop execution of a handler before all its
statements are executed and to obtain a value. Many of the preceding examples
in this chapter use Return statements.
Return
8
A Return statement exits a handler and returns a value. When AppleScript
executes a Return statement, it stops handler execution and resumes execution
239
C H A P T E R
Handlers
at the place in the script where the handler was called, using the value returned
as the value of the handler.
SYNTAX
return expression
where
expression is an AppleScript expression. When AppleScript executes a Return
statement, it returns the value of the expression. Expressions are described in
Chapter 6, Expressions.
EXAMPLE
To return a value and exit a subroutine, include a Return statement in the body
of the subroutine. For example, the following statement returns the integer 2:
return 2
If you include a Return statement without an expression, AppleScript exits the
subroutine immediately and no value is returned.
NOTES
240
C H A P T E R
Handlers
Command Handlers
Command handlers are handlers for application commands. They are similar
to subroutine handlers, but instead of defining responses to user-defined
commands, they define responses to application commands, such as Open,
Print, or Move, sent to application objects.
You define command handlers in scripts, but they handle commands that are
sent to application objects. To be useful, scripts that contain command handlers
must be associated with the application objects that receive those commands.
This is called attaching a script to an application object.
Scripts that are attached to objects can change the way those objects respond to
particular commands. Each application determines which, if any, of its objects
can have attached scripts, and how you attach the scripts.
This section describes the syntax for command handler definitions. For
information about recursion in command handlers, see theRecursive
Subroutines, which begins on page 225. For information about the scope
of variables and properties in handlers, see Scope of Script Variables and
Properties, which begins on page 252.
Command Handlers
241
C H A P T E R
Handlers
SYNTAX
where
commandName (an identifier) is a command name.
directParameterVariable (an identifier) is a parameter variable for the actual
value of the direct parameter. You use this parameter variable to refer to the
direct parameter in the body of the subroutine. If it is included, directParameter
must be listed immediately after the command name. The word of before
directParameter is optional.
label is the parameter label for one of the parameters of the command being
handled. The label given is optional.
paramVariable (an identifier) is a parameter variable for the actual value of the
parameter. You use this identifier to refer to the parameter in the body of
the handler.
variable is an identifier for either a global or local variable that can be used in
the handler. The scope of a local variable is the handler. You cannot refer to a
local variable outside the handler. The scope of a global variable can extend to
any other part of the script, including other handlers and script objects. For
detailed information about the scope of local and global variables, see Scope
of Script Variables and Properties, which begins on page 252.
statement is any AppleScript statement.
NOTES
242
Command Handlers
C H A P T E R
Handlers
Getting Started With AppleScript describes how you can use the Script Editor to
save a script as a script application. A script application is a script that you can
run from the Finder much like any other application. If you save a script as a
stay-open application, it stays open after it runs; if you dont, it quits right after
it runs.
Every script application can respond to at least two commands: the Run
command and the Open command. Like any other application, a script
application receives a Run command whenever it is launched, and an Open
command whenever another icon is dragged and dropped over its icon.
Stay-open script applications can also receive and handle any other commands.
All stay-open applications receive periodic Idle commands whenever theyre
not responding to other events and Quit commands whenever the user quits
the application.
This section describes handlers for the Run, Open, Idle, and Quit commands. It
also describes how you can call a script application from another script.
Run Handlers
All applications that are compatible with System 7 can respond to the Run
command, even if they arent scriptable. The Finder sends a Run command to
an application whenever that application is not already running and one of the
following actions occurs:
The user selects the applications icon and chooses Open from the File menu.
The applications icon is in the Apple Menu Items folder and the user
chooses it from the Apple menu.
The applications icon is in the Startup Items folder and the user restarts
the computer.
If the application is already running when one of these actions occurs, the
application is activated but no commands are sent to it. If the application isnt
243
C H A P T E R
Handlers
running, the Finder launches the application and sends it a Run command. The
application responds by performing the actions the user expects when the
application first opens, such as opening an untitled document.
Like any other application, a script application receives a Run command
whenever one of the actions just listed occurs. You can provide a handler for
the Run command in a couple of ways. An implicit Run handler consists of all
statements at the top level of a script except for property declarations, script
object definitions, and other command handlers. An explicit Run handler, like
any other handler, is enclosed within an on...end statement.
For example, the script that follows consists a property declaration, an
increment command, a handler for the increment command, and a Tell
statement. For the Tell statement to work, you have a Scriptable Text Editor
document named Count Log open before you run the script. Each time you run
the script, the value of the property x increases by 1 and the increase is
recorded in the Count Log.
property x : 0
increment()
on increment()
set x to x + 1
display dialog "Count is now " & x & "."
end increment
tell document
"Count Log" of application "Scriptable Text Editor"
set selection to "Count is now " & x & "." & return
end tell
The implicit Run handler for this script consists of the statement increment()
and the Tell statement. If you store this script in a script application and then
double-click the script applications icon, the Finder sends a Run command
to the script, and the Run command invokes the two statements in the implicit
Run handler.
244
C H A P T E R
Handlers
The script in the preceding example behaves exactly the same way if you
rewrite it with an explicit Run handler, like this:
property x : 0
on run
increment()
tell document
"Count Log" of application "Scriptable Text Editor"
set selection to "Count is now " & x & "." & return
end tell
end run
on increment()
set x to x + 1
display dialog "Count is now " & x & "."
end increment
The Run handlers in the preceding examples respond the same way to a Run
command whether the script is saved as a script application or as a compiled
script. If the script is saved as a compiled script, you can invoke its Run
handler by clicking the Run button in the Script Editor.
Note
245
C H A P T E R
Handlers
By default, a startup screen appears before the script runs. The user must click
the startup screens Run button or press the Return key before the Finder
actually sends the Run command. This allows the user to read the description
of the script before running it. If the Never Show Startup Screen checkbox is
selected in the Script Editors Save As dialog box when the script application is
created, the script runs immediately without displaying the startup screen.
You can also send a Run command to a script application from within another
script. For information about how to do this, see Calling a Script Application
on page 251.
Open Handlers
All applications that are compatible with System 7 can respond to the Open
command, even if they arent scriptable. The Finder sends an Open command
to an application whenever the user drags file, folder, or disk icons over the
applications icon and releases the mouse button. The Open command is sent
even if the application is already running.
Like any other application, a script application receives an Open command
whenever the user drags file, folder, or disk icons over the applications icon. If
the script in the script application includes an Open handler, the statements
within the handler run when the application receives the Open command. The
Open handler takes a single parameter; when the handler is called, the value of
that parameter is a list of all the items whose icons were dropped on the script
applications icon. (Each item in the list is an alias; you can convert it to a
pathname by using as string.)
For example, this Open handler makes a list of the pathnames for all items
dropped on the script applications icon:
on open names
tell application "Scriptable Text Editor"
make new window
repeat with i in names
set iPath to (i as string)
set selection to iPath & return
end repeat
save front window in file "List of Files"
end tell
end open
246
C H A P T E R
Handlers
Files, folders, or disks are not moved, copied, or affected in any way when their
icons are dragged and dropped over a script applications icon. The Finder just
gets a list of their identities and sends that list to the script application as the
direct parameter of the Open event. Of course, the script in the script application could easily tell the Finder to move, copy, or otherwise manipulate them.
Note
247
C H A P T E R
Handlers
Idle Handlers
248
C H A P T E R
Handlers
Quit Handlers
WA R N I N G
249
C H A P T E R
Handlers
250
C H A P T E R
Handlers
251
C H A P T E R
Handlers
Similarly, to launch a non-stay-open application and run its Open Handler, use
a Launch command followed by an Open command, like this:
tell application "NonStayOpen"
launch
open {alias "HardDisk:MyFile",
alias "HardDisk:MyOtherFile"}
end tell
For example, if the Open handler on page 246 were saved as a script application
called NonStayOpen, the script in the preceding example would cause the
handler to create a list of the two specified pathnames.
252
C H A P T E R
Handlers
You can declare a property and set its initial value using a statement like this:
property x: 3
The scope of a property declaration can be either a script object or an entire
script. The value set by a property declaration is not reset each time the script
is run; instead, it persists until the script is recompiled.
A global declaration is much the same as a property declaration except that it
doesnt set an initial value:
global x
The scope of a global variable declaration can be limited to specific handlers or
script objects or can extend throughout an entire script. Like the value of a
property, the value of a global variable is not reset each time a script is run.
However, the value of a global variable must be set by other statements in
the script.
To set the value of any property or variable, use the Set command. (You can
also use the Copy command for this purpose.)
set x to 3
If the variable has not previously been declared, the Set or Copy command
declares it as a local variable. But in some cases it is also necessary to declare
a local variable explicitly.
local x
Like a global declaration, an explicit local declaration doesnt set an
initial value.
The preceding examples represent the four basic forms for declaring variables
and properties in AppleScript. The sections that follow describe how
AppleScript interprets these four forms of declarations within handlers, within
script objects, and at the top level of a script.
253
C H A P T E R
Handlers
Figure 8-1
Form of
declaration
property x: 3
global x
set x to 3
local x
Scope of
declaration
Where AppleScript
looks for x
Everywhere
in script
To
top level
of
script
Within Run
handler
only
Within Run
handler only
The scope of a property declaration at the top level of a script extends to any
subsequent statements anywhere in the script. Heres an example:
property theCount : 0
increment()
on increment()
set theCount to theCount + 1
display dialog "Count is now " & theCount & "."
end increment
When it encounters the identifier theCount at any level of this script,
AppleScript associates it with the theCount property declared at the top level.
The value of a property persists after the script in which the property is defined
has been run. Thus, the value of theCount in the previous example is 0
the first time the script is run, 1 the next time, and so on. The propertys
current value is saved with the script and is not reset to 0 until the script is
recompiledthat is, modified and then run again, saved, or checked for syntax.
Similarly, the scope of a global variable declaration at the top level of a script
extends to any subsequent statements anywhere in the script. The next
254
C H A P T E R
Handlers
example accomplishes the same thing as the previous example, except that it
uses a global variable instead of a property to keep track of the count.
global theCount
increment()
on increment()
try
set theCount to theCount + 1
display dialog "Count is now " & theCount & "."
on error
set theCount to 1
display dialog "Count is now 1."
end try
end increment
When it encounters the identifier theCount at any level of this script,
AppleScript associates it with the theCount variable declared as a global at
the top level of the script. However, because a global variable declaration
doesnt set the initial value of a property, the script must use a Try statement
to determine whether the value has been previously set. Thus, if you want
the value associated with an identifier to persist, it is often easier to declare
it as a property so that you can declare its initial value at the same time.
If you dont want the value associated with an identifier to persist after a script
is run but you want to use the same identifier throughout a script, declare a
global variable and use the Set command to set its value each time the script is
run. Heres an example:
global theCount
set theCount to 0
on increment()
set theCount to theCount + 1
end increment
increment() --result: 1
increment() --result: 2
255
C H A P T E R
Handlers
Each time the on increment handler is called within the script, the global
variable theCount increases by 1. However, when you run the entire script
again, theCount is reset to 1.
In the absence of a global variable declaration at the top level of a script, the
scope of a variable declaration using the Set command at the top level of a
script is normally restricted to the Run handler for the script. For example, this
script declares two separate theCount variables:
set theCount to 10
on increment()
set theCount to 5
end increment
increment() --result: 5
theCount --result: 10
The scope of the first theCount variables declaration, at the top level of the
script, is limited to the Run handler for the script. The scope of the second
theCount declaration, within the on increment handler, is limited to that
handler. AppleScript keeps track of each variable independently.
To associate a variable in a handler or a script object with the same variable
declared at the top level of a script with the Set command, you can use a global
declaration in the handler, as shown in the next example.
set theCount to 0
on increment()
global theCount
set theCount to theCount + 1
end increment
increment() --result: 1
theCount --result: 1
In this case, when AppleScript encounters the theCount variable within the
on increment handler, it looks for a previous mention of theCount not only
within the handler, but also at the top level of the script. However, references
256
C H A P T E R
Handlers
to theCount in any other handler in the script are local to that handler unless
the handler also explicitly declares theCount as a global. This kind of global
declaration is discussed in more detail in the sections that follow.
To restrict the context of a variable to a scripts Run handler regardless of
subsequent global declarations, you must declare it explicitly as a local
variable, as shown in this example:
local theCount
set theCount to 10
on increment()
global theCount
set theCount to theCount + 2
end increment
increment() --error: "The variable theCount is not defined"
theCount --result: 10
Because the theCount variable in this example is declared as local to the Run
handler, any subsequent attempt to use the same variable as a global results in
an error.
Note
257
C H A P T E R
Handlers
You should be familiar with Chapter 9, Script Objects, before you read
this section.
Figure 8-2 summarizes the scope of properties and variables declared at the top
level of a script object. Sample scripts using each form of declaration follow.
Figure 8-2
Form of
declaration
property x: 3
global x
set x to 3
local x
Scope of
declaration
Everywhere
in script object
Where AppleScript
looks for x
To top level of
script object
To top level of
script
Within script
object's Run
handler only
Within script
object's Run
handler only
The scope of a property declaration at the top level of a script object extends to
any subsequent statements in that script object. Heres an example.
script Joe
property theCount : 0
on increment()
set theCount to theCount + 1
return theCount
end increment
end script
tell Joe to increment() --result: 1
tell Joe to increment() --result: 2
When it encounters the identifier theCount at any level of the script object
Joe, AppleScript associates it with the same identifier declared at the top
level of the script object. The value of the property theCount persists until
you reinitialize the script object by running the script again.
258
C H A P T E R
Handlers
The scope of a property declaration at the top level of a script object doesnt
extend beyond the script object. Thus, it is possible to use the same identifier in
different parts of a script to refer to different properties, as this example
demonstrates:.
property theCount : 0
script Joe
property theCount : 0
on increment()
set theCount to theCount + 1
return theCount
end increment
end script
tell Joe to increment() --result: 1
tell Joe to increment() --result: 2
theCount --result: 0
AppleScript keeps track of the property theCount declared at the top level of
the script separately from the property theCount declared within the script
object Joe. Thus, the theCount property declared at the top level of the script
Joe is increased by 1 each time Joe is told to increment, but the theCount
property declared at the top level of the script is not affected.
Like the scope of a property declaration, the scope of a global variable declaration at the top level of a script object extends to any subsequent statements in
that script object. However, as the next example demonstrates, AppleScript also
associates a global variable with the same variable declared at the top level of
the entire script.
set theCount to 0
script Joe
global theCount
on increment()
set theCount to theCount + 1
return theCount
end increment
end script
tell Joe to increment() --result: 1
tell Joe to increment() --result: 2
259
C H A P T E R
Handlers
The preceding example first sets the value of theCount at the top level of the
script. When AppleScript encounters the theCount variable within the on
increment handler, it first looks for an earlier occurrence within the handler,
then at the top level of the script Joe. When AppleScript encounters the global
declaration for theCount at the top level of script object Joe, it continues
looking at the top level of the script until it finds the original declaration for
theCount. This cant be done with a property of a script object, because
AppleScript looks no further than the top level of a script object for that script
objects properties.
Like the value of a script objects property, the value of a script objects global
variable persists after the script object has been run, but not after the script
itself has been run. Thus, telling Joe to increment repeatedly in the preceding
example continues to increment the value of theCount, but running the whole
script again sets theCount to 0 again before incrementing it.
The next example demonstrates how you can use a global variable declaration
in a script object to associate a global variable with a property declared at the
top level of a script.
property theCount : 0
script Norah
property theCount : 20
script Joe
global theCount
on increment()
set theCount to theCount + 1
return theCount
end increment
end script
tell Joe to increment()
end script
260
C H A P T E R
Handlers
261
C H A P T E R
Handlers
The scope of a variable declaration using the Set command at the top level of a
script object is limited to the Run handler:
script Joe
set theCount to 10
on increment()
global theCount
set theCount to theCount + 2
end increment
return theCount
end script
tell Joe to increment()
--error: "The variable theCount is not defined."
run Joe--result: 10
In contrast to the way it treats such a declaration at the top level of a script,
AppleScript treats the theCount variable declared at the top level of the script
object Joe in the preceding example as local to the script objects Run handler.
Any subsequent attempt to use the same variable as a global results in an error.
Similarly, the scope of an explicit local variable declaration at the top level of a
script object is limited to that script objects Run handler, even if the same
identifier has been declared as a property at a higher level in the script:
property theCount : 0
script Joe
local theCount
set theCount to 5
on increment()
set theCount to theCount + 1
end increment
end script
run Joe --result: 5
tell Joe to increment() --result: 1
262
C H A P T E R
Handlers
Figure 8-3
Form of
declaration
global x
set x to 3
Within
handler
only
local x
Where AppleScript
looks for x
To top level of
script
Within
handler only
263
C H A P T E R
Handlers
The scope of a variable declaration using the Set command within a handler is
limited to that handler:
script Henry
set theCount to 10
on increment()
set theCount to 5
end increment
return theCount
end script
tell Henry to increment() --result: 5
run Henry --result: 10
The scope of the first declaration of the first theCount variable, at the top level
of the script object Henry, is limited to the Run handler for the script object.
The scope of the second theCount declaration, within the on increment
handler, is limited to that handler. AppleScript keeps track of each variable
independently.
The scope of a local variable declaration in a handler is limited to that handler,
even if the same identifier has been declared as a property at a higher level in
the script:
property theCount : 10
on increment()
local theCount
set theCount to 5
end increment
increment() --result: 5
theCount --result: 10
264
C H A P T E R
Figure 9-0
Listing 9-0
Table 9-0
Script Objects
Script objects are objects that you define and use in scripts. Like the application
and system objects described earlier in this manual, script objects have
properties and can respond to commands. Unlike application or system objects,
script objects are defined within scripts.
This chapter describes how to define and use script objects. It begins by describing a simple script object definition and demonstrating how you would send a
command to the resulting script object. Subsequent sections describe in more
detail how to define, send commands to, and initialize script objects.
You can define groups of script objects that share properties and handlers, and
you can extend the behavior of a handler in one script object by calling it from
another script object. The section Inheritance and Delegation describes how
this works. If you are familiar with object-oriented design, you may recognize
the techniques described in this section.
The last section, Using the Copy and Set Commands With Script Objects,
describes what to expect when you set a variable to a script object or copy a
script object to a variable and how to write a handler that creates copies
of script objects.
Script objects are user-defined objects that combine data (in the form of
properties) and potential actions (in the form of handlers). Script object
definitions are compound statements that can contain collections of properties,
handlers, and other AppleScript statements.
265
C H A P T E R
Script Objects
266
C H A P T E R
Script Objects
Each script object definition begins with the keyword script, followed by an
optional variable name, and ends with the keyword end (or end script).
The statements in between can be any combination of property definitions,
handler definitions, and other AppleScript statements.
The syntax of a script object definition is
script [ scriptObjectVariable ]
[( property | prop ) propertyLabel : initialValue ]...
[ handlerDefinition ]...
[ statement ]...
end [script]
where
scriptObjectVariable is a variable identifier. If you include scriptObjectVariable,
AppleScript stores the script object in a variable. You can use the variable
identifier to refer to the script object elsewhere in the script.
propertyLabel is an identifier for a property. Properties are characteristics that
are identified by unique labels. They are similar to instance variables in
object-oriented programming.
initialValue is the value that is assigned to the property each time the script
object is initialized. Script objects are initialized when the scripts or handlers
that contain them are run. initialValue is required in property definitions.
handlerDefinition is a handler for a user-defined or system command. The
handlers within a script object definition determine which commands the script
object can respond to. Script object definitions can include handlers for userdefined commands (subroutines) or for system or application commands.
Handlers in script objects are similar to methods in object-oriented programming. For a detailed description of the syntax of handler definitions, refer to
Chapter 8, Handlers.
statement is any AppleScript statement. Statements other than handler and
property definitions are treated as if they were part of a handler definition
for the Run command; they are executed when a script object receives the
Run command.
267
C H A P T E R
Script Objects
You use Tell statements to send commands to script objects. A Tell statement
sent to a script object is similar to a Tell statement sent to an application, except
that it uses a variable name, instead of a reference, to identify the script object.
For example,
tell John
sayHello to "Herb"
sayHello to "Grace"
end tell
sends two sayHello commands to the script object John. The parameters of
the commands in the Tell statement, if any, must match the parameters defined
in the handler definitions in the script object definition. For example, the
statement
tell John
sayHello ("Herb")
end tell
--results in an error
results in an error message because the handler definition for the sayHello
command (shown earlier in this chapter) defines a labeled parameter, not a
positional parameter.
For a script object to respond to a command within a Tell statement, either the
script object or its parent script object must have a handler for the command. A
parent script object is a script object from which a script object inherits handlers
and properties. (For more information about parent script objects, see
Inheritance and Delegation on page 271.)
The one command that any script object can handle, even without an explicitly
defined handler, is the Run command. A handler for the Run command can
consist of all statements at the top level of a script object definition other than
property and handler definitions. If the script object definition contains only
268
C H A P T E R
Script Objects
handler and property definitions, and does not include any additional top-level
statements, the definition may include an explicit Run handler that begins with
on run. If a script object definition includes neither an implicit Run handler
(in the form of top-level statements) nor an explicit Run handler, the Run
command doesnt do anything. (For more information about Run handlers, see
Command Handlers for Script Applications, which begins on page 243.)
For example, the Display Dialog command in the following script object
definition is executed only if you send a Run command to script object John.
script John
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
display dialog "John received the Run command"
end script
When you define a script object, you define a collection of handlers and
properties. When you run a script containing a script object definition,
AppleScript creates a script object with the properties and handlers listed
in the definition. This is called initializing a script object. A script object
must be initialized before it can respond to commands.
If you include a script object definition at the top level of a scriptthat is, as
part of the scripts Run handlerAppleScript initializes the script object each
time the scripts Run handler is executed. (For more information about Run
handlers, see page 243.)
Similarly, if you include a script definition in another handler within a script,
AppleScript initializes a script object each time the handler is called. The
parameter variables in the handler definition become local variables of the
269
C H A P T E R
Script Objects
script object. For example, the makePoint handler in the following script
contains a script object definition for the script object point:
on makePoint(x, y)
script point
property xCoordinate:x
property yCoordinate:y
end script
return point
end makePoint
set myPoint to makePoint(10,20)
get xCoordinate of myPoint
get yCoordinate of myPoint
AppleScript initializes the script object point when it executes the makePoint
command. The parameter variables in the makePoint handler, in this case, x
and y, become local variables of the script object point. The initial value of x is
10, and the initial value of y is 20, because those are the parameters of the
makePoint command that initialized the script object.
One way to use script object definitions in handlers is to define constructor
functions, that is, handlers that create script objects. The following script uses
a constructor function to create three script objects.
on makePoint(x, y)
script
property xCoordinate:x
property yCoordinate:y
end script
end makePoint
set PointA to makePoint(10,20)
set PointB to makePoint(100,200)
set PointC to makePoint(1,1)
As in the previous example, you can retrieve the coordinates of the three script
objects using the Get command.
270
C H A P T E R
Script Objects
Note
how to a define a script object that inherits properties and handlers from
another script object
how inheritance works
how to use the Continue statement to extend the behavior of an inherited
handler without completely replacing it
Defining Inheritance
You define inheritance with the Parent property. A script object that includes a
Parent property inherits the properties and handlers of the script object listed
in the Parent property.
The script object listed in a Parent property definition is called the parent
script object, or parent. A script object that includes a Parent property is
referred to as a child script object, or child. The Parent property is not required.
A script object can have many children, but a child script object can have only
one parent.
271
C H A P T E R
Script Objects
272
C H A P T E R
Script Objects
Figure 9-1
script John
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
end script
parent
script Simple
property parent : John
end script
Figure 9-2
script Simple
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
end script
script John
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
end script
parent
script Rebel
property parent : John
property HowManyTimes : 10
end script
script Rebel
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
property HowManyTimes : 10
end script
Drawing diagrams like Figure 9-1 and Figure 9-2 can help you understand more
complicated relationships between parent and child script objects. For example,
if you were to guess the result of the following script without sketching a
diagram, you might conclude that the result of the sayHello command is
273
C H A P T E R
Script Objects
"Hello Emily". However, the correct result is "Hello Andrew", as you can
see in Figure 9-3.
script X
on sayHello()
return "Hello, " & getName()
end sayHello
on getName()
return "Emily"
end getName
end script
script Y
property parent : X
on getName()
return "Andrew"
end getName
end script
tell Y to sayHello()
Figure 9-3
script X
on sayHello()
return "Hello, " & getName()
end sayHello
on getName()
return "Emily"
end getName
end script
parent
script Y
property parent : X
on getName()
return "Andrew"
end getName
end script
274
script Y
on sayHello()
return "Hello, " & getName()
end sayHello
on getName()
return "Emily"
end getName
on getName()
return "Andrew"
end getName
end script
C H A P T E R
Script Objects
Even though script X in Figure 9-3 sends itself the getName command, the
command is intercepted by the child script, which substitutes its own version
of the getName handler. AppleScript always maintains the first target of a
command as the self to which inherited commands are sent, redirecting to
the child any inherited commands the parent sends to itself.
The relationship between a parent script object and its child script objects is
dynamic. If the properties of the parent change, so do the inherited properties
of the children. For example, the script object Simple in the following script
inherits its Vegetable property from script object John.
script John
property Vegetable : "Spinach"
end script
script Simple
property parent : John
end script
set Vegetable of John to "Swiss chard"
Vegetable of Simple
--result: "Swiss chard"
When you change the Vegetable property of script object John with the Set
command, you also change the Vegetable property of the child script object
Simple. The result of the last line of the script is "Swiss chard".
Similarly, if a child changes one of its inherited properties, the value of the
parent property changes. For example, the script object JohnSon in the
following script inherits the Vegetable property from script object John.
script John
property Vegetable : "Spinach"
end script
script JohnSon
property parent : John
on changeVegetable()
set my Vegetable to "Zucchini"
end changeVegetable
end script
275
C H A P T E R
Script Objects
276
C H A P T E R
Script Objects
Normally, if a child script object and its parent both have handlers for the same
command, the child uses its own handler. However, the handler in a child
script object can handle a command first, and then use a Continue statement to
call the handler for the same command in the parent.
The use of a Continue statement to call a handler in a parent script object is
called delegation. By delegating commands to a parent script object, a child
can extend the behavior of a handler contained in the parent without having to
repeat the entire handler definition. After the parent handles the command,
AppleScript continues at the place in the child where the Continue statement
was called. Handlers in child script objects that contain Continue statements
are similar to wrapper methods in object-oriented programming.
The syntax of a Continue statement is
continue commandName parameterList
where
commandName is the name of the current command.
parameterList is the list of parameters to be passed with the command. 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 actual values or parameter variables. If you list actual values,
those values replace the parameter values that were specified in the original
command. If you list parameter variables, the Continue statement passes the
parameter values that were specified in the original command.
277
C H A P T E R
Script Objects
The following script includes two script object definitions similar to those
shown in Figure 9-1 on page 273. The first, Elizabeth, works just like the
script John in the figure. The second, ChildOfElizabeth, includes a handler
with a Continue statement that is not included in the child script object
(Simple) shown in the figure.
script Elizabeth
property HowManyTimes : 0
to sayHello to someone
set HowManyTimes to HowManyTimes + 1
return "Hello " & someone
end sayHello
end script
script ChildOfElizabeth
property parent : Elizabeth
on sayHello to someone
if my HowManyTimes > 3 then
return "No, I'm tired of saying hello."
else
continue sayHello to someone
end if
end sayHello
end script
In the preceding example, the handler defined by ChildOfElizabeth for the
sayHello command checks the value of the HowManyTimes property each
time the handler is run. If the value is greater than 3, ChildOfElizabeth
returns a message refusing to say hello. Otherwise, ChildOfElizabeth calls
the sayHello handler in the parent script object (Elizabeth), which returns
the standard hello message. The word someone in the Continue statement is a
parameter variable. It indicates that the parameter received with the original
sayHello command will be passed to the handler in the parent script.
278
C H A P T E R
Script Objects
Note
279
C H A P T E R
Script Objects
script Andrea
property parent : Hugh
on identify()
continue identify()
end identify
end script
tell Hugh to identify()
--result: <<script Hugh>>
tell Andrea to identify()
--result: <<script Andrea>>
280
C H A P T E R
Script Objects
The default parent property for any script that doesnt explicitly declare one is
the default target applicationusually, the application that is running the
script, such as the Script Editor. You can use the predefined variable current
application to refer to either the default target application or whatever
application is currently set as a scripts parent property.
281
C H A P T E R
Script Objects
You can make any application the current application for a script or script
object simply by declaring it as a parent property. Any subsequent command in
the script for which the script doesnt have a handler is passed to the
application you declare as the parent, and subsequent occurrences of the
constant current application refer to that application.
For example, this script declares the Scriptable Text Editor as its parent
property, then sends commands that close the Scriptable Text Editors
frontmost window and return the applications name:
property parent: application "Scriptable Text Editor"
close front window
tell current application to return my name
In this case, my refers to the current application (Scriptable Text Editor). The
Tell statement is optional; just return the name of me would produce the
same result, because AppleScript sends the command to the Scriptable Text
Editor. If you remove the property declaration from the script, the Script Editor
becomes the current application. When sent to the Script Editor, the Close
command and the Return statement produce errors because the Script Editor
doesnt understand them.
In the next example, the script Bilbo declares the Scriptable Text Editor as
its parent property and includes a handler that modifies the behavior of
the scripting addition command Display Dialog.
script Bilbo
property parent : application "Scriptable Text Editor"
on display dialog x
tell application "Script Editor" to display dialog
"Scriptable Text Editor has something to say"
continue display dialog x
end display dialog
end script
tell Bilbo to display dialog "Hello"
282
C H A P T E R
Script Objects
Because the script object Bilbo declares the Scriptable Text Editor as its parent
property, the on display dialog handler must use a Tell statement to send
a separate Display Dialog command to the Script Editor. The handler then uses
a Continue statement to pass the original Display Dialog command to the
Scriptable Text Editor, which becomes the frontmost application and uses the
Display Dialog addition to display Hello.
The Copy and Set commands both assign values to variables, but they have
different results when the value assigned is a script object. The Copy command
makes a new copy of the script object, and the Set command creates a variable
that shares data with the original script object.
To see how this works, consider the following example, which defines a script
object, called John, with a property called Vegetable.
script John
property Vegetable: "Spinach"
end script
set myScriptObject to John
set Vegetable of John to "Swiss chard"
get Vegetable of myScriptObject
--result: "Swiss chard"
The first Set command defines a variable, called myScriptObject, that shares
data with the original script object John. The second Set command changes the
value of the Vegetable property of script object John from "Spinach" to
"Swiss chard". Because myScriptObject shares data with John, it shares
the change to the Vegetable property of John. When you get the Vegetable
property of myScriptObject, the result is "Swiss chard".
283
C H A P T E R
Script Objects
Now consider the following example, which uses the Copy command to define
the variable myScriptObject.
script John
property Vegetable: "Spinach"
end script
copy John to myScriptObject
set Vegetable of John to "Swiss chard"
get Vegetable of myScriptObject
--result: "Spinach"
In this case, the Copy command creates a new script object. Setting the
Vegetable property of the original script object has no effect on the new script
object. The result of the Get command is "Spinach".
When you copy a child script object to a variable, the variable contains a
complete copy of both the child and its parent, including all the parents
properties and handlers. Each new copy, including its inherited properties
and handlers, is completely independent of both the original and any
other copies.
For example, if you copy a modified version of the JohnSon script in this
example to two different variables, you can set each variables Vegetable
property independently:
script John
property Vegetable : "Spinach"
end script
script JohnSon
property parent : John
on changeVegetable(x)
set my Vegetable to x
end changeVegetable
end script
284
C H A P T E R
Script Objects
copy JohnSon to J1
copy JohnSon to J2
tell J1 to changeVegetable("Zucchini")
tell J2 to changeVegetable("Swiss chard")
Vegetable of J1
--result: "Zucchini"
Vegetable of J2
--result: "Swiss chard"
Vegetable of John
--result: "Spinach"
You can create handlers that construct copies of script objects for use elsewhere
in a script. For example, the script that follows includes a handler that takes an
initial balance as a parameter and creates a copy of a script object that acts as
an independent account. Each copy includes several properties and an on
deposit handler that enables the script object to increment its own balance
when it receives a Deposit command.
on makeAccount(initialBalance)
script account
property StartDate : current date
property Balance : initialBalance
on deposit(amount)
set Balance to Balance + amount
end deposit
end script
end makeaccount
set a to makeAccount(3300)
set b to makeAccount(33)
285
C H A P T E R
Script Objects
tell a
deposit(30)
deposit(60)
end tell
{Balance of a, StartDate of a}
--result: {3390, date "Tuesday, July 6, 1993 2:38:11 PM"}
{Balance of b, StartDate of b}
--result: {33, date "Tuesday, July 6, 1993 2:38:12 PM"}
286
Appendixes
A P P E N D I X
Figure A-0
Listing A-0
Table A-0
Commands
A command is a request for action. In AppleScript, you can use application commands, which are defined in each applications dictionary;
AppleScript commands, which are defined and handled by AppleScript;
or scripting addition commands, which are defined and handled by
AppleScript extensions called scripting additions.
Table A-1 lists standard application commands and AppleScript commands.
(For information about scripting addition commands, see the AppleScript
Scripting Additions Guide.) The syntax shown for standard application
commands is the syntax supported by most applications. Individual applications can extend or change the way the standard application commands work.
For information about how a specific application handles a particular
application command, see the applications dictionary. For more detailed
descriptions of the commands listed here, see Chapter 4, Commands.
Commands
289
290
None
close referenceToObject
close
(application
command)
Commands
count
(application
command)
count
(AppleScript
command)
number of className
number of compoundValue
count compoundValue
( copy | put )
continued
Integer or
list of integers
Integer
Value copied
(none if no
parameters are
included)
copy
(application
command)
Value copied
copy
(AppleScript
command)
Result
Syntax
Command syntax
Command
Table A-1
A P P E N D I X
A
Integer or
list of integers
data size
(application
command)
Commands
get
(application
command)
get
(AppleScript
command)
exists referenceToObject
exists
(application
command)
get referenceToObject
get expression
referenceToObject exists
error
[ errorMessage ]
[ number errorNumber ]
[ from offendingObject ]
[ partial result resultList ]
[ to expectedType ]
error
(AppleScript
command)
Value of
reference
continued
Value of
expression
Boolean
Reference
duplicate referenceToObject
duplicate
(application
command)
duplicate referenceToObject to referenceToLocation
None
delete referenceToObject
delete
(application
command)
Result
Syntax
Command
Table A-1
A P P E N D I X
A
291
292
Commands
print
(application
command)
print referenceToObject
open listOfFiles
None
continued
None
open referenceToFile
open
(application
command)
Reference to the
moved object
Reference to the
new object
None
Result
move
(application
command)
make
(application
command)
launch
launch
(application
command)
launch referenceToApplication
Syntax
Command
Table A-1
A P P E N D I X
A
Commands
set
(application
command)
set
(AppleScript
command)
save
(application
command)
run
(application
command)
run
(AppleScript
command)
save referenceToObject
run referenceToApplication
run
run scriptObjectVariable
run
Value assigned
Value assigned
None
None
The value, if
any, returned by
the script object
None
quit referenceToApplication
quit
(application
command)
quit referenceToApplication saving saveOption
Result
Syntax
Command
Table A-1
A P P E N D I X
A
293
A P P E N D I X
References
Table A-2
Reference form
Syntax
Arbitrary Element
some className
Every Element
every className
pluralClassName
Filter
ID
className ID IDvalue
Index
className integer
className index integer
first className
second className
third className
fourth className
continued
294
References
A P P E N D I X
Table A-2
Reference form
Syntax
fifth className
sixth className
seventh className
eighth className
ninth className
tenth className
integer st className
integer nd className
integer rd className
integer th className
last className
front className
back className
Middle Element
middle className
Name
className string
className named string
Property
propertyLabel
Range
continued
References
295
A P P E N D I X
Table A-2
Reference form
Syntax
Relative
Table A-3
Container
notation
Syntax
in
reference in containerReference
of
reference of containerReference
's
containerReference's reference
Operators
Table A-4 summarizes the operators in the AppleScript English language
dialect. The first column lists the operators. The second column shows
the syntax for using the operators in expressions. The placeholders in the
syntax descriptions correspond to AppleScript value classes, which are
described briefly in the last section of this appendix, and in more detail in
Chapter 3, Values.
Synonyms are listed in groups. The table shows the syntax for the first
operator, but operators that are synonyms follow the same syntax rules.
296
Operators
A P P E N D I X
Table A-4
Operator
Operators
Syntax
Arithmetic operators
number * number
number + number
date + number
number - number
date - number
date date
number ( | / ) number
number ^ number
div
mod
Logical operators
and
not
not Boolean
or
Boolean or Boolean
Containment operators
start[s] with
begin[s] with
end[s] with
contains
Operators
297
A P P E N D I X
Table A-4
Operators (continued)
Operator
Syntax
is in
is contained by
list is in list
record is in record
string is in string
is not in
is not contained by
isn't contained by
=
equal
equals
equal to
is
is equal to
expression = expression
expression expression
<
comes before
is less than
is not greater than or equal [to]
isn't greater than or equal [to]
less than
>
comes after
greater than
is greater than
is not less than or equal [to]
isn't less than or equal [to]
continued
298
Operators
A P P E N D I X
Table A-4
Operators (continued)
Operator
Syntax
<=
does not come after
doesn't come after
is less than or equal [to]
is not greater than
isn't greater than
less than or equal [to]
date date
integer integer
real real
string string
>=
does not come before
doesn't come before
greater than or equal [to]
is greater than or equal [to]
is not less than
isn't less than
date date
integer integer
real real
string string
Miscellaneous operators
&
as
expression as className
a reference to
Control Statements
Control statements are statements that control when and how other statements
are executed. Table A-5 summarizes the control statements in the AppleScript
English dialect. For more information about control statements, see Chapter 7,
Control Statements.
Control Statements
299
A P P E N D I X
Table A-5
Control statements
Control
statement
Syntax
tell
if
repeat
repeat
[ statement ]...
end [ repeat ]
repeat integer [ times ]
[ statement ]...
end [ repeat ]
repeat while Boolean
[ statement ]...
end [ repeat ]
repeat until Boolean
[ statement ]...
end [ repeat ]
repeat with variable from integer to integer [ by integer ]
[ statement ]...
end [ repeat ]
repeat with variable in list
[ statement ]...
end [ repeat ]
exit
exit
continued
300
Control Statements
A P P E N D I X
Table A-5
Control
statement
Syntax
try
try
[ statement ]...
on error
[ errorMessageVariable]
[ number errorNumberVariable]
[ from offendingObjectVariable ]
[ partial result resultListVariable]
[ to expectedTypeVariable ]
[ global variable [, variable]...]
[ local variable [, variable]...]
[ statement ]...
end [ error | try ]
considering
ignoring
with timeout
with
transaction
Handlers
A
Handlers are collections of statements that are executed in response to
commands or error messages. Table A-6 summarizes handler definitions
and subroutine calls.
Handlers
301
302
Handlers
subroutineName
[ ( of | in ) directParameter ]
[ subroutineParamLabel parameterValue ]
| [ with labelForTrueParam [, labelForTrueParam ]...
[( and | or | , ) labelForTrueParam ] ]
| [ without labelForFalseParam [, labelForFalseParam ]...
[( and | or | , ) labelForFalseParam ] ]
| [ given label:parameterValue
[, label:parameterValue ]...]...
Subroutine definition
(positional parameters)
Subroutine call
(positional parameters)
Return statement
Command handler
definition
( on | to ) subroutineName
[ of | in directParameterVariable ]
[ subroutineParamLabel paramVariable ] ...
[ given label:paramVariable [, label:paramVariable ]...]
[ global variable [, variable ]...]
[ local variable [, variable ]...]
[ statement ]...
end [ subroutineName ]
Subroutine definition
(labeled parameters)
Syntax
Handler
Table A-6
A P P E N D I X
A
A P P E N D I X
Script Objects
Script objects are user-defined objects. Table A-7 summarizes the syntax for
defining script objects in AppleScript. For more information about script
objects, see Chapter 9, Script Objects.
Table A-7
Script objects
Syntax
Script object
definition
script [scriptObjectVariable]
[(property | prop) propertyLabel : expression]...
[ handlerDefinition ]...
[ statement ]...
end [ script ]
Continue statement
(to pass a command
to a handler in the
parent script object)
continue commandStatement
Table A-8 summarizes the syntax for assigning values to variables and script
properties and declaring local and global variables. For information about
variables and script properties, see Chapter 3, Values. For detailed
information about the scope of script variables and properties, see Scope of
Script Variables and Properties, which begins on page 252.
Script Objects
303
A P P E N D I X
Table A-8
Assignment or declaration
Syntax
Variable assignment
(and declaration if variable
has not previously been
declared)
The Text Item Delimiters property, which is the only property you can get and
set using the global variable AppleScript, consists of a list of the delimiters
used by AppleScript when coercing lists to strings and when getting text items
from strings. This property is declared by AppleScript and is available from
any script. You can get and set it using this syntax:
AppleScript's text item delimiters
text item delimiters of AppleScript
Currently, only the first delimiter in the list is used by AppleScript.
Predefined Variables
Table A-9 lists special variables that are defined by AppleScript. These variables
are global, that is, they are available anywhere in a script.
As with all other identifiers, predefined variables are not case sensitive. For
example, result, Result, and RESULT are all treated as the same variable.
304
Predefined Variables
A P P E N D I X
Table A-9
Predefined variables
Identifier
Class
Description
it
Reference
me
Reference
pi
Real
result
Any class
return
String
A return character.
space
String
A space character.
tab
String
A tab character.
Constants
Identifier
Meaning
application
responses
Constants
305
A P P E N D I X
Table A-10
Identifier
Meaning
case
diacriticals
expansion
hyphens
punctuation
white space
Text styles
all caps
All caps
all lowercase
All lowercase
bold
Boldface
condensed
Condensed
expanded
Expanded
hidden
Hidden
italic
Italic
outline
Outline
plain
Plain text
shadow
Shadow
small caps
Small caps
strikethrough
Strikethrough
subscript
Subscript
continued
306
Constants
A P P E N D I X
Table A-10
Identifier
Meaning
superscript
Superscript
underline
Underline
Save options
ask
no
yes
Alignment
center
Centered
full
Justified
left
Flush left
right
Flush right
Boolean constants
false
true
Miscellaneous
current
application
Placeholders
Placeholders
307
A P P E N D I X
Table A-11
Placeholder
Explanation
applicationName
attribute
Boolean
className
commandName
commandStatement
compoundValue
containerReference
dataValue
date
directParameter
directParameterVariable
errorMessage
errorMessageVariable
errorNumber
308
Placeholders
A P P E N D I X
Table A-11
Placeholder
Explanation
errorNumberVariable
expectedType
expectedTypeVariable
expression
handlerDefinition
IDvalue
integer
label
labelForFalseParam
labelForTrueParam
list
listOfFiles
nameString
number
offendingObject
offendingObjectVariable
parameterValue
Placeholders
309
A P P E N D I X
Table A-11
Placeholder
Explanation
paramVariable
pluralClassName
propertyLabel
propertyValue
real
record
reference
referencePattern
referenceToApplication
referenceToFile
referenceToLocation
referenceToObject
resultList
310
Placeholders
A P P E N D I X
Table A-11
Placeholder
Explanation
resultListVariable
saveOption
scriptObjectVariable
session
statement
An AppleScript statement.
string
subroutineName
subroutineParamLabel
timeDifference
variable
variablePattern
Placeholders
311
A P P E N D I X
Figure B-0
Listing B-0
Table B-0
This appendix defines the AppleScript terms understood by the Scriptable Text
Editor, the application used in examples throughout this book. These include
both the names of application objects in the Scriptable Text Editor or its
documents and the names of commands that specify actions that the Scriptable
Text Editor performs. The appendix contains these sections:
The Scriptable Text Editor deals mainly with text; therefore, most of its objects
are text objects. The Scriptable Text Editor defines five text object classes:
Character
Word
Paragraph
Text
Text Item
313
A P P E N D I X
Each of the text object classes can contain any of the other text object classes as
elements. For example, a word can also be a paragraph. A word object can
contain character, word, and text item elements.
Classes of text objects are distinguished from each other by the way their
boundaries, or delimiters, are defined. Because of this, the same text can be
viewed as a collection of character elements, word elements, paragraph
elements, or text item elements.
In addition to paragraph, word, character, and text item elements, all text
objects can contain elements that belong to the class Text. An object belonging
to class text is a series of contiguous characters. In any text object, the elements
of class text are all of the possible series of contiguous characters contained
within the object. The most common way to use an element of class Text is to
specify the contiguous characters in a range of text objects.
For example, the following reference specifies all the characters, including
spaces, from the beginning of the fifth word to the end of the twenty-fifth word.
text from word 5 to word 25
In contrast, the following reference specifies a list of words, with no information
about spaces or punctuation between words.
word 5 thru 25
Like most scriptable applications, the Scriptable Text Editor supports standard
groups, or suites, of AppleScript objects and commands. Different applications
of the same type have many of the same objects and commands in their
dictionaries. For example, most text-processing applications have paragraph
objects, word objects, character objects, text item objects, and objects of class
text. For the most part, these objects have the same properties in different
applications.
Sometimes scriptable applications add properties to standard objects that are
not included in the standard suites. In the Scriptable Text Editor, each of the
314
A P P E N D I X
Text Styles
B
The text styles of Scriptable Text Editor text objects are defined by two
properties: Style and Uniform Styles:
The Style property specifies the styles of the text object. If the styles vary
within the object, the Style property specifies the style of the first character
of the object.
The Uniform Styles property specifies the styles that are the same for all the
characters in the text object.
The value of a Style or Uniform Styles property is a record with two properties:
On Styles and Off Styles. The On Styles property specifies styles that are on,
that is, that apply to the text object. The Off Styles property specifies styles that
are off, that is, that do not apply to the text object. Both On Styles and Off
Styles are lists of constants that specify text styles. For the Scriptable Text
Editor, these constants are bold, italic, outline, underline, and shadow.
The following example shows the value of a Style property for a text object
whose characters are bold and underlined:
{On Styles:{bold, underline}, Off Styles:{italic, outline, shadow}}
The On Styles property lists the two styles (bold and underline) that apply
to the text object, while the Off Styles property lists the styles that do not apply
to the text object. Together, the On Styles and Off Styles properties of a Style
property include all of the text styles that the Scriptable Text Editor supports.
The Uniform Styles property specifies the styles that are uniform throughout a
text object, that is, that are the same for every character in a text object. The On
Styles property specifies the styles that apply to every character in the object.
The Off Styles property specifies styles that do not apply to any character in the
315
A P P E N D I X
text object. If any of the style constants (bold, italic, outline, underline,
and shadow) do not appear in either field, it is because the styles apply to
some, but not all, of the characters in the object.
The following example shows the value of a Uniform Styles property for a
text object in which every character is bold and no characters are outlined
or shadowed:
{On Styles:{bold}, Off Styles:{outline, shadow}}
The fact that the italic and underline constants do not appear in either
field means that at least one, but not all, of the characters in the object are
italicized and underlined. To find out which characters are italicized or
underlined, you must examine the Style properties of each character in the
text object.
To set the styles of a text object, use a Copy or Set command to set the Style
property of the text object to one of the following:
a two-part record like the one described earlier for the value of a
Style property
For example, here are four ways to use the Set command to set text styles:
set the style of word 1 to {On Styles:{italic},
Off Styles:{bold, shadow}}
set the style of word 1 to {On Styles:{italic, bold}}
set the style of word 1 to {bold, italic}
set the style of word 1 to italic
316
In the first example, the styles specified in the On Styles property are added
to the active styles of word 1. The styles specified in the Off Styles property
are removed from the active styles of word 1. Styles that are not specified in
either property remain the same. For example, if word 1 is originally
A P P E N D I X
underlined, shadowed, and bold, then after the Set command, word 1 is
underlined and italicized.
In the second example, the styles specified in the On Styles property are
added to the active styles of word 1. Styles that are not specified remain the
same. For example, if word 1 is originally underlined and shadowed, then
after the Set command, word 1 is italicized, underlined, shadowed, and bold.
In the third example, the styles specified in the list are added to the active
styles of word 1. Styles that are not specified remain the same. For example,
if word 1 is originally underlined and shadowed, then after the Set
command, word 1 is italicized, underlined, shadowed, and bold.
In the fourth example, the style specified in the command is added to the
active styles of word 1. All other styles remain the same. For example, if
word 1 is originally underlined, shadowed, and bold, then after the Set
command, word 1 is italicized, underlined, shadowed, and bold.
When you set the style of a text object, if you include the same style constant in
both the On Styles property and the Off Styles property, the Scriptable Text
Editor returns the error Bad data.
When setting text styles, you can use a special constantplainto specify
that the text object is to be plain, that is, have no text styles. If you include
constants other than plain in the On Styles property, the Scriptable Text Editor
ignores the other constants. If you include plain in the Off Styles property, the
Scriptable Text Editor returns the error Bad data.
A script system is a collection of system software facilities that allow for the
visual representation of a particular writing system. Script systems include
Roman, Japanese, Hebrew, Greek, and Thai. Each script system has a corresponding script code, a constant used, for example, to identify the script
system in which some text was prepared. AppleScript and the Scriptable Text
Editor can handle text prepared in a variety of script systems, provided the
appropriate software is installed on your computer.
A character in an AppleScript string or a Scriptable Text Editor document takes
up either 1 byte or 2 bytes, depending on the script system the character
belongs to. Thus, the size in bytes of a text object may differ from the number
of characters it contains.
317
A P P E N D I X
This section defines the application object classes to which Scriptable Text
Editor objects belong. For an introduction to application objects and references,
see Chapter 5, Objects and References.
Application
B
The Application object class defines the characteristics of the Scriptable Text
Editor application.
PROPERTIES
318
Clipboard
Frontmost
Name
A P P E N D I X
Selection
ELEMENT CLASSES
document
window
COMMANDS HANDLED
None
EXAMPLES
319
A P P E N D I X
NOTES
The AppleScript English language dialect supports the abbreviation app for
referring to objects of class application. For example, the following statements
are equivalent:
cut the selection of application "Scriptable Text Editor"
cut the selection of app "Scriptable Text Editor"
The window and document element classes can be used interchangeably. This
is because each open document has a window, whose elements and properties
are always the same as those of its document. For example, if the first open
document is named Giant, the first window is also named Giant. A Scriptable
Text Editor document and its window contain the same text elements, so
references to text elements in a document and its window can be used
interchangeably. For example, word 1 of document "Giant" and word
1 of window "Giant" refer to the same word.
Text item objects are series of contiguous characters that are separated from
each other by special characters called delimiters. The Text Item Delimiters
property of the Scriptable Text Editor application consists of a list of characters
that can be used to separate text item objects. At startup the default value of the
Scriptable Text Editors Text Item Delimiters property is a single-item list that
contains a comma: {","}. You can set this delimiter to a different value or add
additional delimiters, but the new values are lost when the user quits the
application. You may find it convenient to alter the Text Item Delimiters
property temporarily if you are dealing with multilingual text or text formatted
with other delimiters.
The Clipboard property is a list of objects of class Data, but you can use the
As operator to get the Clipboard as a string, reference, or styled text. The
Scriptable Text Editor coerces the data to the requested type, if possible.
tell application "Scriptable Text Editor"
cut word 1 of front document
get clipboard as string
end tell
--result: the first word of the document as a string
320
A P P E N D I X
Character
B
An object of class Character is a text character.
PROPERTIES
Font
Length
Offset
Size
Style
321
A P P E N D I X
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
the characters of the text object. Both properties are lists of
constants that specify text styles. If a style does not appear in
either list, the style applies to some but not all of the characters
in the object. See Elements of Text Objects on page 314 for
more information. The constants that can be used in Uniform
Styles property lists are bold, italic, outline, underline,
and shadow.
Modifiable? No
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
Text
Text Item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Duplicate, Exists, Get, Make, Move,
Select, Set
Styled Text
322
A P P E N D I X
EXAMPLES
Document/Window
PROPERTIES
Bounds
The rectangle that bounds the content region of the window (the
portion of the window that contains the text of the document;
the window framethe title bar and scroll barsare not part
of the content region).
Class: List of four integers. The first two integers specify the
coordinates of the upper-left corner of the window, and the last
two integers specify the coordinates of the lower-right corner of
the window. (For information about window coordinates, see
Notes later in this section.)
Modifiable? Yes
Closable
Contents
323
A P P E N D I X
324
Floating
Index
Modal
Modified
Name
Position
A P P E N D I X
Resizable
Selection
Titled
Visible
Zoomable
Zoomed
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
325
A P P E N D I X
Text
Text Item
Word
COMMANDS HANDLED
Close, Copy, Count, Delete, Duplicate, Exists, Get, Make, Move, Print, Revert,
Save, Select, Set
EXAMPLE
NOTES
The window and document object classes can be used interchangeably. This
is because each open document has a window, whose elements and properties
are always the same as those of its document. For example, if the first open
document is named Giant, the first window is also named Giant. A Scriptable
Text Editor document and its window contain the same text elements, so
references to text elements in a document and its window can be used
interchangeably. For example, word 1 of document "Giant" and word
1 of window "Giant" refer to the same word.
Both the Bounds and Position properties are specified in terms of points on the
display. The Position property contains a single point: the upper-left corner of
the windows content region (the portion of the window within the window
frame made up of the title bar and scroll bars). The Bounds property contains
two points: the upper-left corner of the content region followed by the
lower-right corner. In AppleScript, points are specified by pairs of integers
known as coordinates. The first coordinate in the pair, known as the
x-coordinate, specifies the distance from the left edge of the display to the
326
A P P E N D I X
point. The other coordinate, known as the y-coordinate, specifies the distance
from the top of the display to the point. (These distances are measured in
pixels, which are the picture elements that make up the display.) Figure B-1
illustrates the Bounds and Position properties of a sample window.
Figure B-1
(0,0)
(100,0)
(400,0)
(Pixels)
Position of document
"Introduction" {100,100}
(0,100)
(0,400)
(Pixels)
Bounds of document
"Introduction"
{100,100,400,400}
You specify points in AppleScript with lists. Figure B-1 shows that the point for
the Position property is specified by the list {100, 100}. The first item in this
list is the x-coordinate value of the point, and the second is the y-coordinate
value. The figure also shows that the Bounds property is specified by the list
{100, 100, 400, 400}. You specify the two points that define a rectangle
in a single list. In this list, {100, 100} are the coordinates of the upper-left
corner, and {400, 400} are the coordinates of the lower-right corner.
327
A P P E N D I X
Although the object class defined for the Bounds and Position properties is List,
the Scriptable Text Editor actually stores Bounds and Position property data in
a different form. To get Bounds or Position data as a List, you must copy the
data to AppleScript. For example,
copy (Bounds of front window) to x
get item 2 of x
returns the y-coordinate of the upper-left corner of the window, but
get item 2 of (Bounds of front window)
returns an error.
The Name property of a document is an object of class Text. You can change the
characters of the name of a document, but unlike other objects of class Text,
you cannot change its Font, Size, or Style properties.
File
B
An object of class File contains the data for a Scriptable Text Editor document.
When a file object is opened, a corresponding document object is created.
(Only open documents are Scriptable Text Editor document objects.) When
a document object is saved, the data for the document is saved in the
corresponding file object, which is represented by a Scriptable Text Editor
document icon on the desktop.
PROPERTIES
Name
ELEMENT CLASSES
None
328
A P P E N D I X
COMMANDS HANDLED
Open, Print
None
EXAMPLE
NOTES
Insertion Point
PROPERTIES
Font
329
A P P E N D I X
Length
Offset
Size
Style
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object. For insertion points, the Uniform Styles property
indicates which text styles are active at the insertion point. It
always has the same value as the Style property.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. See Elements of Text Objects on
page 314 for information about how styles are used. The
constants that can be used in Uniform Styles property lists are
bold, italic, outline, underline, and shadow.
Modifiable? No
ELEMENT CLASSES
None
330
A P P E N D I X
COMMANDS HANDLED
Reference
EXAMPLES
The following statement moves the first word of a document to the insertion
point after the tenth word.
tell document "Intro" of app "Scriptable Text Editor"
move word 1 to insertion point after word 10
end tell
The following statement does the same thing:
tell document "Intro" of app "Scriptable Text Editor"
move word 1 to after word 10
end tell
AppleScript allows you to leave out the words insertion point when
specifying locations with the Relative reference form. For more information
about the Relative reference form, see Relative on page 139.
Paragraph
B
An object of class Paragraph is a text object thats delimited by return
characters or by the beginning or end of the container.
331
A P P E N D I X
PROPERTIES
Font
Length
Offset
Size
Style
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
332
A P P E N D I X
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
Text
Text Item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Exists, Get, Make, Move, Select, Set
Styled Text
EXAMPLE
333
A P P E N D I X
Selection
B
An object of class Selection is text that is currently selected. A blinking insertion
point is a zero-length selection.
PROPERTIES
Contents
Font
Length
Offset
Size
Style
334
A P P E N D I X
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
the characters of the text object. Both properties are lists of
constants that specify text styles. If a style does not appear in
either list, the style applies to some but not all of the characters
in the object. See Elements of Text Objects on page 314 for
information about how styles are used. The constants that can
be used in Uniform Styles property lists are bold, italic,
outline, underline, and shadow.
Modifiable? No
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
Text
Text item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Duplicate, Exists, Get, Make, Move, Set
Reference
335
A P P E N D I X
EXAMPLES
NOTES
In the Scriptable Text Editor, the only objects of class selection are the Selection
properties of the application, document, and window objects.
Text
B
An object of class Text is a series of one or more contiguous characters.
PROPERTIES
336
Font
The name of the font of the text object. If the font varies
within the object, the Font property specifies the font of the
first character.
Class: String
Modifiable? Yes
Length
Offset
A P P E N D I X
Size
The size, in points, of the text object. If the size varies within the
object, the Size property specifies the size of the first character.
Class: Integer
Modifiable? Yes
Style
The text styles of a text object. If the text styles vary within the
object, the Style property specifies the styles of the first character.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to the text object. The Off Styles property
specifies the styles that do not apply to the text object. Both
properties are lists of constants that specify text styles. See
Elements of Text Objects on page 314 for information
about how styles are used. The constants that can be used in
Style property lists are bold, italic, outline, underline,
and shadow.
Modifiable? Yes
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
the characters of the text object. Both properties are lists of
constants that specify text styles. If a style does not appear in
either list, the style applies to some but not all of the characters
in the object. See Elements of Text Objects on page 314 for
information about how styles are used. The constants that can
be used in Uniform Styles property lists are bold, italic,
outline, underline, and shadow.
Modifiable? No
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
337
A P P E N D I X
Text
Text Item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Duplicate, Exists, Get, Make, Move,
Select, Set
Styled Text
EXAMPLE
NOTES
The Scriptable Text Editor does not allow you to refer to an object of class Text
with the Index reference form (such as text 5 of characters 1 thru
1024) because it does not make sense to number the many possible objects of
class Text in a text object.
Text is a plural class name. You cannot use it in places where AppleScript
expects a singular class name. For example, the following statement results
in a compilation error.
tell document "Intro" of app "Scriptable Text Editor"
get every text from paragraph 1 to paragraph 2
end tell
--causes an error because text is a plural class name
338
A P P E N D I X
Text Item
B
Objects of class Text Item are delimited by any of the characters specified by the
Scriptable Text Editors Text Item Delimiters property or by the beginning or
end of a container. You can modify the Text Item Delimiters property, but such
changes are lost when the user quits the application.
PROPERTIES
Font
The name of the font of the text item. If the font varies
within the text item, the Font property specifies the font
of the first character.
Class: String
Modifiable? Yes
Length
Offset
Size
The size, in points, of the text item. If the size varies within the
text item, the Size property specifies the size of the first character.
Class: Integer
Modifiable? Yes
Style
The text styles of a text object. If the text styles vary within
the text item, the Style property specifies the styles of the
first character.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to the text object. The Off Styles property
specifies the styles that do not apply to the text object. Both
properties are lists of constants that specify text styles. See
Elements of Text Objects on page 314 for information
about how styles are used. The constants that can be used in
Style property lists are bold, italic, outline, underline,
and shadow.
Modifiable? Yes
339
A P P E N D I X
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
the characters of the text object. Both properties are lists of
constants that specify text styles. If a style does not appear in
either list, the style applies to some but not all of the characters
in the object. See Elements of Text Objects on page 314 for
information about how styles are used. The constants that can
be used in Uniform Styles property lists are bold, italic,
outline, underline, and shadow.
Modifiable? No
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
Text
Text Item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Duplicate, Exists, Get, Make, Move,
Select, Set
Styled Text
340
A P P E N D I X
EXAMPLE
NOTE
The characters used to separate text item objects are specified in the Scriptable
Text Editors Text Item Delimiters property. At startup the default value of the
Scriptable Text Editors Text Item Delimiters property is a single-item list that
contains a comma: {","}. You can set this delimiter to a different value or add
additional delimiters, but the new values are lost when the user quits the
application.
An object of class Text Style Info specifies the styles of a text object. The Style
and Uniform Styles properties of text objects are text style info objects.
PROPERTIES
On Styles
Off Styles The styles that do not apply to the text object.
Class: List of constants (see Notes later in this section)
Modifiable? Yes
ELEMENT CLASSES
None
341
A P P E N D I X
COMMANDS HANDLED
EXAMPLES
NOTES
The constants that can be used in Style property lists are bold, italic,
outline, underline, and shadow. For a complete description of text
styles, see Elements of Text Objects on page 314.
Window
B
See the definition of the document object class on page 323.
Word
B
Generally speaking, words in English are text objects delimited by spaces,
return characters, or the beginning or end of a container. (For a more precise
definition, see page 61.) Words in other languages are defined by the script
system for each language if the appropriate script system is installed.
342
A P P E N D I X
PROPERTIES
Font
The name of the font of the word. If the font varies within the
word, the Font property specifies the font of the first character.
Class: String
Modifiable? Yes
Length
Offset
Size
The size, in points, of the word. If the size varies within the
word, the Size property specifies the size of the first character.
Class: Integer
Modifiable? Yes
Style
The text styles of a text object. If the text styles vary within the
word, the Style property specifies the styles of the first character.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to the text object. The Off Styles property
specifies the styles that do not apply to the text object. Both
properties are lists of constants that specify text styles. See
Elements of Text Objects on page 314 for information
about how styles are used. The constants that can be used in
Style property lists are bold, italic, outline, underline,
and shadow.
Modifiable? Yes
Uniform Styles
The text styles that are uniformly on or off for all characters
of a text object.
Class: Text Style Info. Objects of this class have two properties:
On Styles and Off Styles. The On Styles property specifies the
styles that apply to all the characters of the text object. The Off
Styles property specifies the styles that do not apply to any of
the characters of the text object. Both properties are lists of
constants that specify text styles. If a style does not appear in
either list, the style applies to some but not all of the characters
343
A P P E N D I X
ELEMENT CLASSES
See Elements of Text Objects on page 314 for a general discussion of these
element classes.
Character
Paragraph
text
Text Item
Word
COMMANDS HANDLED
Copy, Count, Cut, Data Size, Delete, Duplicate, Exists, Get, Make, Move,
Select, Set
Styled Text
EXAMPLES
344
A P P E N D I X
This section defines the commands that are understood by the Scriptable Text
Editor and its objects.
The Scriptable Text Editor supports most of the standard application commands
listed in Chapter 4, Commands. As is true for most scriptable applications,
the Scriptable Text Editors definitions for some of these commands differ
slightly from the standard definitions. Table B-1 summarizes the differences
between the defined behavior of the standard commands and the Scriptable Text
Editor behavior.
Table B-1
Standard
application command
Close
Copy
Behaves like the standard version defined on page 88, except that
the direct parameter must be a single object. The Scriptable Text
Editor cannot copy a range of objects.
Count
Data Size
Behaves like the standard version defined on page 97, except that
the Scriptable Text Editor returns the size of text objects as a data
class that includes writing code information. The writing code
information adds 4 bytes to the data size.
Delete
Duplicate
Behaves like the standard version defined on page 99, except that
the direct parameter must be a single object. The Scriptable Text
Editor cannot duplicate a range of objects.
Exists
Get
345
A P P E N D I X
Table B-1
Standard
application command
Make
Behaves like the standard version defined on page 105, with some
exceptions. The default location for new text objects is the current
selection; the default location for new document and window
objects is in front of other Scriptable Text Editor windows.
When you create text objects with the Make command, the
Scriptable Text Editor automatically adds the appropriate delimiters
before or after the new text objects, depending on the script code for
the new text, the script code for the surrounding text, and, in the
case of text items, the value of the Text Item Delimiters property. Do
not include delimiters in the with data parameter.
Move
Behaves like the standard version defined on page 106, except that
the direct parameter must be a single object. The Scriptable Text
Editor cannot move a range of objects.
Open
Behaves like the standard version defined on page 107, except that
the Scriptable Text Editor can only open text files or its own files.
If you use the Open command to open a file of type "TEXT", the
Scriptable Text Editor automatically converts the file to a Scriptable
Text Editor file and appends .s to the end of the filename.
Quit
Run
Save
Behaves like the standard version defined on page 112, except that it
has an optional parameter that allows you to save Scriptable Text
Editor files as text files.
The direct parameter of the Save command must be a single object.
The Scriptable Text Editor cannot save a range of objects.
Set
346
A P P E N D I X
Table B-2 summarizes the commands other than the standard application
commands that are supported by the Scriptable Text Editor.
Table B-2
Command
Description
Cut
Paste
Revert
Select
The sections that follow describe both the commands listed in Table B-1 that
differ from the standard versions and the commands listed in Table B-2.
Copy
B
The standard Copy command is defined on page 88. The Scriptable Text Editor
version of the Copy command behaves like the standard version, except the
direct parameter of the Scriptable Text Editor command cannot be a list; it must
be a reference to a single object. For example, the following statement results in
an error:
tell document "Intro" of app "Scriptable Text Editor"
copy words whose style contains bold to beginning
end
--result: error; Copy can handle single objects only
347
A P P E N D I X
Cut
B
The Cut command is a request to remove an object and put it on the Clipboard.
If the Cut command includes a direct parameter, it removes the object specified
in the direct parameter. If the command does not include a direct parameter, it
removes the object in the current selection.
The Cut command has the same result as choosing the Cut menu item in the
Scriptable Text Editor: the object that was cut replaces any objects that were
previously on the Clipboard.
SYNTAX
cut [ referenceToObject ]
PARAMETER
referenceToObject
A reference to the object to be cut.
Class: Reference
RESULT
None
EXAMPLE
348
A P P E N D I X
NOTES
If you do not specify a direct parameter and there is no selection to be cut, the
Scriptable Text Editor does not change the contents of the Clipboard.
If you specify a direct parameter, it must be a reference to a single object. The
Scriptable Text Editor cannot cut ranges of objects. For example, the following
statement results in an error.
tell application "Scriptable Text Editor"
cut words of paragraph 5 of front document
end tell
--result: error, because Cut can handle single objects only
Data Size
B
The standard Data Size command is defined on page 97. The Scriptable Text
Editor version of the Data Size command behaves like the standard version. It
returns the size of the data (a value) that would result from a Get command on
an object or objects.
By default, the Scriptable Text Editor returns text objects as class Styled Text,
including font and style information. The additional information adds a
variable number of bytes to the data size. As a result, the size of a text object
will be greater than the number of bytes contained in the corresponding text
without the font and style information. To get the data size of a text object
without font and style information, use the as className parameter to request
the size of the data as text; for example,
data size of word 1 of front document as text
Duplicate
B
The standard Duplicate command is defined on page 99. The Scriptable Text
Editor version of the Duplicate command behaves like the standard version
of the command, except the direct parameter cannot be a list; it must be a
349
A P P E N D I X
Make
B
The standard Make command is defined on page 105. The Scriptable Text
Editor version of the Make command behaves like the standard version except
that the referenceToLocation parameter, which is required in the standard version
of the command, is optional in the Scriptable Text Editor version:
make [ new ] className [ at referenceToLocation ]
[ with properties
{ propertyName:propertyValue [, propertyName:propertyValue]...}]
[ with data dataValue ]
In addition, the Scriptable Text Editor automatically adds delimiters as needed
around new text objects. When you create text objects with the Make command, do not include delimiters in the data.
When making a new text item, the Scriptable Text Editor uses the first delimiter
listed in its Text Item Delimiters property as the items delimiter.
Not all languages require delimiters between each word. When making new
words, the Scriptable Text Editor relies on both the script code of the text to
be inserted and the script code of the text into which it is being inserted to
determine whether to use delimiters and, if so, which delimiters to use and
where to place them.
Finally, the Scriptable Text Editor provides default values for the data and
properties of objects created with the Make command. If you do not specify
values for all the properties or data of a new object, the Scriptable Text Editor
provides the default values.
350
A P P E N D I X
Move
B
The standard Move command is defined on page 106. The Scriptable Text
Editor version of the Move command behaves like the standard version,
except that the direct parameter cannot be a list; it must be a reference to a
single object.
For example, the following statement results in an error:
tell document "Intro" of app "Scriptable Text Editor"
move words whose style contains bold to beginning
end
--result: error; Move can handle single objects only
Open
B
The standard Open command is defined on page 107. The Scriptable Editor can
open its own files and text files (files of type "TEXT"). If you use the Open
command to open a file of type "TEXT", the Scriptable Text Editor automatically converts the file to a Scriptable Text Editor file and appends .s to the
end of the filename.
Paste
B
The Paste command is a request to make a copy of the objects on the Clipboard
and replace the current selection with them. The Paste command has the
same effect as choosing the Paste command from the Scriptable Text Editors
Edit menu.
SYNTAX
paste
351
A P P E N D I X
PARAMETERS
None
RESULT
None
EXAMPLE
NOTES
The Paste command replaces the current selection with the contents of the
Clipboard. If the current selection is an insertion point, the Paste command
inserts the contents of the Clipboard at the insertion point.
Revert
B
The Revert command is a request to replace one or more documents with the
versions of the documents that were most recently saved.
SYNTAX
revert referenceToDocument
352
A P P E N D I X
PARAMETER
referenceToDocument
A reference to the document or documents to be replaced by
the versions of the documents that were most recently saved.
Because the Scriptable Text Editors document and window
objects are interchangeable, either document or window objects
can be specified.
Class: Reference
RESULT
None
EXAMPLE
Save
B
The standard Save command is defined on page 112. The Scriptable Text Editor
version behaves like the standard version, except that it has an extra optional
parameter (as text) that allows you to save Scriptable Text Editor files as text
files (files of type "TEXT"). Without this parameter, files are saved as Scriptable
Text Editor files.
save referenceToObject [in referenceToFile ] [as text]
In addition, the direct parameter of the Scriptable Text Editor version cannot be
a list; it must be a reference to a single object. For example, the following
statement results in an error:
tell application "Scriptable Text Editor"
save documents 1 thru 3
end tell
--result: error; Save can handle single objects only
353
A P P E N D I X
Select
B
A Select command is a request to select a text object or bring a Scriptable Text
Editor document or window to the front. Using the Select command to select a
text object is the same as highlighting the text object by double-clicking it or
dragging the cursor across it while holding down the mouse button.
SYNTAX
select referenceToObject
PARAMETER
referenceToObject
A reference to the text object, document, or window to select.
Class: Reference
RESULT
None
EXAMPLE
354
A P P E N D I X
This section lists error numbers and messages returned by the Scriptable Text
Editor. For information about writing handlers for these and other errors, see
Chapter 8, Handlers.
Error
number
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
Error message
355
A P P E N D I X
Figure C-0
Listing C-0
Table C-0
Error Messages
This appendix lists error numbers and error messages for the following types
of errors:
357
A P P E N D I X
Error Messages
Error message
No error.
34
35
37
38
39
42
43
44
45
46
47
48
49
50
Parameter error.
51
61
108
Out of memory.
120
124
128
User canceled.
192
600
601
602
358
A P P E N D I X
Error Messages
Error
number
Error message
605
606
Application is background-only.
607
608
609
Connection is invalid.
904
905
906
915
30720
359
A P P E N D I X
Error Messages
Error message
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
Invalid range.
1721
1723
1725
continued
360
A P P E N D I X
Error Messages
Error
number
Error message
1726
1727
Expected a reference.
1728
1729
1730
1731
1750
1751
1752
1753
Script error.
1754
1755
Invalid access.
1756
1757
No such dialect.
1758
1759
1760
Error message
10000
10001
10002
10003
10004
10005
361
A P P E N D I X
Error Messages
10006
10007
10008
10009
10010
10011
Couldn't handle this command because it wasn't part of the current transaction.
10012
10013
10014
10015
362
A P P E N D I X
Error Messages
AppleScript Errors
Error
number
Error message
2701
2702
2703
2704
2705
2706
Stack overflow.
2707
2708
2709
2720
2721
2729
2740
2741
2750
2751
2752
2753
2754
2755
2760
2761
2762
2763
AppleScript Errors
363
A P P E N D I X
Error Messages
364
AppleScript Errors
Glossary
Apple event A high-level message that
adheres to the interprocess messaging
protocol on which AppleScript is based.
AppleScript A scripting language defined
by Apple Computer, Inc., that allows you to
control Macintosh computers without using
the keyboard or mouse.
AppleScript command A command
handled by AppleScript. AppleScript
commands do not have to be included
in Tell statements.
application command A command
handled by an application or its objects.
An application command must either
be included in a Tell statement or include
the name of the application in its direct
parameter.
application object An object stored in an
application or its documents and managed
by the application.
Arbitrary Element reference form A
reference form that specifies an arbitrary
object in a container. If the container is a
value, AppleScript uses a random-number
generator to choose the object. If the
container is an application object, the
application chooses the object.
assignment statement A statement that
assigns a value to a variable. Assignment
statements begin with Set or Copy.
363
G L O S S A RY
364
G L O S S A RY
365
G L O S S A RY
366
G L O S S A RY
367
G L O S S A RY
368
G L O S S A RY
369
G L O S S A RY
370
Index
Symbols
" character 62
* operator 166
/ operator 167
operator 167
& operator 163, 177178
() in syntax descriptions xix
+ operator 166
<= operator 165
< operator 164
= operator 163
>= operator 164
> operator 164
[] in syntax descriptions xix
\ character 62
^ operator 167
{} 49
| in syntax descriptions xix
operator 164
operator 165
operator 164
25
8384
operator 167
A
adding values to lists 51
addition of date and number values 180181
addition operator 166
after reserved word 139
alias versus file 144145
And operator 163
371
I N D E X
B
back of reserved words 139
back reserved word 131, 132
backslash character in strings 62
"Bad Data" error message 317
before reserved word 139
beginning reserved word 132
Begins With operator 165
binary operator 21
Boolean expressions 190
Boolean value class 40
Bounds property 323, 327328
brackets xix
C
capitalization in AppleScript 28
case attribute 214
case sensitivity 28
cell object 186
Character object class 321323
characters
in different script systems 318
elements of a string 60
child script objects 271286
classes
of operands 161168
of parameters 78, 225
Class value class 41
Clipboard property 318
Closable property 323
Close command 8788
coercion
of parameters 81
of values 6770
coercion operator 167
Comes After operator 164
Comes Before operator 164
command definitions
AppleScript
Copy 8891
372
Count 9296
Error 210212
Get 100102
Run 110112
Set 113117
Scriptable Text Editor 345355
Copy 347
Cut 348
Data Size 349
Duplicate 349
Make 350
Move 351
Open 351
Paste 351
Revert 352
Save 353
Select 354
standard application commands
Close 8788
Copy 8891
Count 9296
Data Size 9798
Delete 98
Duplicate 99
Exists 99100
Get 100102
Launch 103104
Make 105106
Move 106107
Open 107108
Print 108109
Quit 109110
Save 112113
Set 113117
using 7780
command handlers 241252
in script applications 243252
in stay-open script applications 247250
commands 1718, 71117
AppleScript 7374, 84117
application 7273, 84117
defined 71
handlers for. See command handlers
objects that can respond to 122
I N D E X
commands (continued)
parameters of 7879
Scriptable Text Editor 345354
scripting addition 23, 7475
summarized 289293
syntax of 78
targets of 71
user-defined 76, 221240
waiting for completion of 215, 217
comments 2627
comparison operators 163165, 298
comparisons 213
compiling a script 30
complete reference 124
completion of commands 215, 217
composite values 33
compound statements 16
concatenation operator (&) 163, 177178
conditional statement. See If statements
Considering statements 213217
constants, listed 305
Constant value class 42
constructor functions 270, 285286
containers 123124, 296
containment operators 165166, 297
Contains operator 165, 175176
Contents property 58, 154, 323
continuation characters 25
Continue statements 277283
passing commands to applications
with 280283
control statements 183218
defined 183
listed 300
nested 184
Copy command
in assignment statements 22, 150
defined 8891
definition 347
with script objects 283286
Count command 50, 9296
current application reserved
words 281283
current directory 144
current script 76
customizing applications 7, 11
Cut command 348
D
data sharing 117, 154, 283
Data Size command 9798, 349
Data value class 43, 81
date-time arithmetic 180181
Date value class 4347
default object 185, 186
default target 18
delegation 277286
Delete command 98
diacriticals attribute 215
dialects
defined 24
introduced 5
dictionaries 1820
defined 19
Scriptable Text Editor 19, 185, 313355
direct parameter 72, 78
division operator () 167
div operator 167
Document object class 323328
Does Not Come After operator 165
Does Not Come Before operator 164
Does Not Contain operator 166
Does Not Equal operator 164
double-quote character 62
Duplicate command 99, 349
E
eighth reserved word 131
elements
of objects 120
of text objects 314
of values 37
Else clause 191
373
I N D E X
F
fifth reserved word 131
filename 329
374
G
Get command 100102
Getting Started With AppleScript xv, xviii
given parameter label 230234
global variables 155, 158
persistence of 255, 259260
scope of 252264
Greater Than operator 164, 172173
Greater Than Or Equal To operator 164
H
handlers 221264, 267
for application commands 241242
in script applications 243252
defined 221
for errors 204212
for Idle command 248
interrupting 250
for Open command 246247
for Quit command 249
for Run command 243246
scope of identifiers declared within 263264
for stay-open script applications 247250
syntax summary 302
for user-defined commands 221240
hyphens attribute 215
I N D E X
I, J, K
M
macro languages 10
Make command 105106, 350
merging lists 51
messages. See Apple events
methods 267
me variable 186188, 224, 279280
Middle Element reference form 133
middle reserved word 133
minus symbol () 167
Modal property 324
Modified property 324
mod operator 167
Move command 106107, 351
multiplication operator 166
my reserved word 186188, 224, 279280
375
I N D E X
N
named reserved word 134
Name property 187, 318, 324
Name reference form 134
nested control statements 184
networks
AppleTalk 146
zones of 148
ninth reserved word 131
non-English text 66
not operator 168
Number value class 5253
O
object class definitions
Scriptable Text Editor
Application 318320
Character 321323
Document 323328
File 328329
Insertion Point 329331
Paragraph 331333
Selection 334336
Text 336338
Text Item 339341
Text Style Info 341342
Window. See Document object class
Word 342344
using 119122
object-oriented design 265
objects 1718, 119148
in applications 119
commands that act on 122
default 185, 186
elements of 120
properties of 120
script
child 271286
initializing 269271
parent 268, 271286
sending commands to 268269
376
P
paragraph element of a string 60
Paragraph object class 331333
parameters 8082
for application commands 7879
coercion of 81
in Continue statements 277
defined 78
direct 72, 78
I N D E X
parameters (continued)
labeled 78, 223
location 80, 140
optional 79
patterned 238239
positional 223
raw data in 81
required 79
parameter variables 270, 277
parentheses xix
Parent property 271
and current application 281283
parent script objects 268, 271286
partial references 124, 185
partial result parameter 210
Paste command 351
patterned parameters 238239
persistence
of global variables 255, 259260
of script properties 254, 259260
placeholders xix, 307311
plural object names 127
plus symbol (+) 166
positional parameters 223
Position property 324, 327328
possessive object names 124
precedence
of attributes 216
of operations 178179
predefined variables
introduced 156
listed 305
Print command 108109
properties
of AppleScript 158160
of objects 120
scope of 252264
of script objects 267
of scripts 156158
of values 36
Property reference form 135
property reserved word 157
prop reserved word 157
punctuation attribute 215
Q
Quit command 109110
handlers for, in stay-open script
applications 249
R
Range reference form 136139
Real value class 5354
recordable applications 11
Record button 10
Record value class 5457
recursion 225226
reference forms 125143
Arbitrary Element 126127
defined 125
Every Element 127128
Filter 129143
ID 130131
Index 131133
Middle Element 133
Name 134
Property 135
Range 136139
Relative 139140
and values 38
reference reserved word. See A Reference To
operator
references 122148
complete 124
defined 122
as expressions 160161
to files and applications 143148
partial 124, 185
Reference value class 5759
ref reserved word. See A Reference To operator
Relative reference form 139140
remainder operator 167
Repeat statements 194204
Repeat (forever) 197
Repeat (number) Times 198
377
I N D E X
S
's notation 124, 296
sample application xvii
Save command 112113, 353
saving parameter 87, 109
scope, of variables and properties 252264
scriptable applications 11
Scriptable Text Editor
commands 345354
dictionary 19, 185, 313355
and non-Roman script systems 317318
object class definitions 318344
script applications 243252
calling 251252
interrupting handlers in 250
script codes, and AppleScript 317
378
Script Editor 5, 30
script errors 206
scripting additions 23
introduced 7475
in With Timeout statements 217
script objects 265286
child 271286
defined 265
initializing 266, 269271
introduced 23
parent 268, 271286
scope of identifiers declared within 258262
sending commands to 268269
script properties 156158, 304
persistence of 254, 259260
scope of 252262
script reserved word 267
scripts
defined 3
running 9
scope of identifiers declared at top level
of 254257
script systems and AppleScript 317318
second[s] reserved word 218
second reserved word 131
Select command 354
Selection object class 334336
Selection property 319, 325
Set command
in assignment statements 22, 150
defined 113117
scope of variables set with 252264
with script objects 283284
seventh reserved word 131
short-circuiting, during evaluation 163
simple statements 16
simple values 33
sixth reserved word 131
Size property 321
slash symbol (/) 167
some reserved word 126
special characters
in identifiers 28
in strings 62
I N D E X
T
Tab character in strings 62
target 71
targets 18
Tell statements 72, 185190
compound 189190
introduced 16
simple 188
U
unary operators 21
Uniform Styles property 315317, 322
uppercase letters 28, 214
user-defined commands 76, 221240
user-defined objects. See script objects
379
I N D E X
W, X, Y
380
Z
zones, AppleTalk 146
Zoomable property 325
Zoomed property 325
T H E
A P P L E
P U B L I S H I N G
Deborah Dennis
PRODUCTION EDITOR
Rex Wolf
Special thanks to William Cook and
Warren Harris.
Acknowledgments to Kathleen Carter,
Dan Clifford, Sue Dumont, Ron Karr,
Kazuhisa Ohta, Donald Olson, Jon Pugh,
Brett Sher, Peter Sparks, and the entire
AppleScript team.
S Y S T E M