No part of this publication or the
software described in it may be
reproduced, stored in a retrieval
system, or transmitted, in any form
or by any means, mechanical,
electronic, photocopying, recording,
or otherwise, without prior written
permission of Apple Computer, Inc.
Printed in the United States
of America.
The Apple logo is a trademark of
Apple Computer, Inc. Use of the
“keyboard” Apple logo (OptionShift-K) for commercial purposes
without the prior written consent of
Apple may constitute trademark
infringement and unfair competition
in violation of federal and state laws.
No licenses, express or implied, are
granted with respect to any of the
technology described in this book.
Apple retains all intellectual
property rights associated with the
technology described in this book.
This book is intended to assist
application developers to develop
applications only for Apple
Macintosh computers.
Apple Computer, Inc.
20525 Mariani Avenue
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, AppleTalk,
HyperCard, HyperTalk, LaserWriter,
and Macintosh are trademarks of
Apple Computer, Inc., registered
in the United States and other
countries.
AppleScript, Finder, Geneva
and System 7 are trademarks of
Apple Computer, Inc.
Adobe Illustrator and PostScript are
trademarks of Adobe Systems
Incorporated, which may be
registered in certain jurisdictions.
FrameMaker is a registered
trademark of Frame Technology
Corporation.
Helvetica and Palatino are registered
trademarks of Linotype Company.
FileMaker is a registered trademark
of Claris Corporation.
ITC Zapf Dingbats is a registered
trademark of International Typeface
Corporation.
Microsoft is a registered trademark
of Microsoft Corporation.
Simultaneously published in the
United States and Canada.
LIMITED WARRANTY ON MEDIA
AND REPLACEMENT
If you discover physical defects in the
manuals distributed with an Apple
product, Apple will replace the manuals
at no charge to you, provided you return
the item to be replaced with proof of
purchase to Apple or an authorized
Apple dealer during the 90-day period
after you purchased the software. In
addition, Apple will replace damaged
manuals for as long as the software is
included in Apple’s Media Exchange
program. See your authorized Apple
dealer for program coverage and details.
In some countries the replacement
period may be different; check with
your authorized Apple dealer.
ALL IMPLIED WARRANTIES ON
THIS MANUAL, INCLUDING
IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A
PART ICULAR PURPOSE, ARE
LIMITED IN DURATION TO NINETY
(90) DAYS FROM THE DATE OF THE
ORIGINAL RETAIL PURCHASE OF
THIS PRODUCT.
Even though Apple has reviewed this
manual, APPLE MAKES NO
WARRANTY OR REPRESENTATION,
EITHER EXPRESS OR IMPLIED, WITH
RESPECT TO THIS MANUAL, ITS
QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS
MANUAL IS SOLD “AS IS,” AND
YOU, THE PURCHASER, ARE
ASSUMING THE ENTIRE RISK AS TO
ITS QUALITY AND ACCURACY.
IN NO EVENT WILL APPLE BE
LIABLE FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES
RESULTING FROM ANY DEFECT OR
INACCURACY IN THIS MANUAL,
even if advised of the possibility of such
damages.
THE WARRANTY AND REMEDIES
SET FORTH ABOVE ARE EXCLUSIVE
AND IN LIEU OF ALL OTHERS, ORAL
OR WRITTEN, EXPRESS OR IMPLIED.
No Apple dealer, agent, or employee is
authorized to make any modification,
extension, or addition to this warranty.
Some states do not allow the exclusion
or limitation of implied warranties or
liability for incidental or consequential
damages, so the above limitation or
exclusion may not apply to you. This
warranty gives you specific legal rights,
and you may also have other rights
which vary from state to state.
Contents
Figures and Tablesxiii
PrefaceAbout This Guide
Audiencexv
Organization of This Guidexvi
Sample Applications and Scriptsxvii
For More Informationxviii
Getting Startedxviii
Scripting Additionsxviii
Other AppleScript Dialectsxviii
Scriptable Applicationsxviii
Conventions Used in This Guide xix
Part 1Introducing AppleScript
xv
1
Chapter 1AppleScript, Scripts, and Scriptable Applications
What Is AppleScript?3
What Can You Do With Scripts?5
Automating Activities5
Integrating Applications 7
Customizing Applications 7
Who Runs Scripts, and Who Writes Them?9
Special Features of AppleScript10
What Applications Are Scriptable?11
3
iii
Chapter 2Overview of AppleScript
How Does AppleScript Work?14
Statements14
Commands and Objects 17
Dictionaries18
Values20
Expressions 21
Operations21
Variables22
Script Objects23
Scripting Additions23
Dialects24
Other Features and Language Elements24
If (Simple Statement) 192
If (Compound Statement)193
Repeat Statements 194
Repeat (forever)197
Repeat (number) Times198
Repeat While199
Repeat Until200
Repeat With (loopVariable) From (startValue) To (stopValue)201
Repeat With (loopVariable) In (list)202
Exit204
Try Statements 204
Kinds of Errors205
How Errors Are Handled206
Writing a Try Statement206
Try207
Signaling Errors in Scripts210
Error210
Considering and Ignoring Statements 213
Considering/Ignoring214
With Timeout Statements 217
With Timeout218
With Transaction Statements219
With Transaction219
183
Chapter 8Handlers
Using Subroutines 221
Types of Subroutines223
Scope of Subroutine Calls in Tell Statements224
Checking the Classes of Subroutine Parameters 225
viii
221
Recursive Subroutines225
Saving and Loading Libraries of Subroutines226
Subroutine Definitions and Calls228
Subroutines With Labeled Parameters229
Subroutine Definition, Labeled Parameters229
Subroutine Call, Labeled Parameters230
Examples of Subroutines With Labeled Parameters232
Subroutines With Positional Parameters235
Subroutine Definition, Positional Parameters235
Subroutine Call, Positional Parameters236
Examples of Subroutines With Positional Parameters238
The Return Statement239
Return 240
Command Handlers 241
Command Handler Definition241
Command Handlers for Script Applications243
Run Handlers243
Open Handlers246
Handlers for Stay-Open Script Applications247
Idle Handlers248
Quit Handlers249
Interrupting a Script Application’s Handlers250
Calling a Script Application251
Scope of Script Variables and Properties 252
Scope of Properties and Variables Declared at the Top Level
of a Script254
Scope of Properties and Variables Declared in a Script Object258
Scope of Variables Declared in a Handler263
Chapter 9Script Objects
About Script Objects265
Defining Script Objects267
Sending Commands to Script Objects268
Initializing Script Objects 269
Inheritance and Delegation 271
265
ix
Defining Inheritance271
How Inheritance Works272
The Continue Statement277
Using Continue Statements to Pass Commands to Applications280
The Parent Property and the Current Application281
Using the Copy and Set Commands With Script Objects283
Appendix A The Language at a Glance
Commands289
References294
Operators296
Control Statements299
Handlers301
Script Objects303
Variable and Property Assignments and Declarations303
Predefined Variables304
Constants305
Placeholders307
289
Appendix B Scriptable Text Editor Dictionary
About Text Objects 313
Elements of Text Objects 314
Special Properties of Scriptable Text Editor Text Objects314
Text Styles 315
AppleScript and Non-Roman Script Systems317
Scriptable Text Editor Object Class Definitions318
Application 318
Character 321
Document/Window 323
File 328
Insertion Point 329
Paragraph 331
Selection 334
Text336
313
x
Text Item 339
Text Style Info 341
Window 342
Word 342
Scriptable Text Editor Commands 345
Copy347
Cut 348
Data Size349
Duplicate349
Make 350
Move 351
Open 351
Paste 351
Revert 352
Save 353
Select 354
Scriptable Text Editor Errors355
Appendix C Error Messages
Operating System Errors 358
Apple Event Errors 359
Apple Event Registry Errors 361
AppleScript Errors 362
Glossary
Index
363
371
357
xi
Figures and Tables
Chapter 1
Chapter 2
Chapter 3
Chapter 4
AppleScript, Scripts, and Scriptable Applications
Figure 1-1Changing text style with the mouse and with a script4
Figure 1-2A script that performs a repetitive action6
Figure 1-3A script that copies information from one application to another8
Figure 1-4Different ways to run a script9
Overview of AppleScript
Figure 2-1How AppleScript works15
Figure 2-2How AppleScript gets the Scriptable Text Editor dictionary20
13
3
Values33
Figure 3-1Value class definition for lists34
Figure 3-2Coercions supported by AppleScript69
Table 3-1AppleScript value class identifiers 39
Commands
Figure 4-1Command definition for the Move command77
Figure 4-2The Scriptable Text Editor document “simple”95
71
Chapter 5
Table 4-1Standard application commands defined in this chapter 85
Table 4-2AppleScript commands defined in this chapter86
Objects and References
Figure 5-1The Scriptable Text Editor’s object class definition for
paragraph objects121
Figure 5-2The Scriptable Text Editor document “simple”137
Table 5-1Reference forms126
Table 5-2Boolean expressions and tests in Filter references142
Figure 8-1Scope of property and variable declarations at the top level
Figure 8-2Scope of property and variable declarations at the top level
Figure 8-3Scope of variable declarations within a handler263
Script Objects
Figure 9-1Relationship between a simple child script and its parent273
Figure 9-2Another child-parent relationship273
Figure 9-3A more complicated child-parent relationship274
The Language at a Glance
Table A-1Command syntax290
Table A-2Reference form syntax294
Table A-3Container notation in references296
Table A-4Operators297
Table A-5Control statements300
Table A-6Handler definitions and calls302
Table A-7Script objects303
Table A-8Assignments and declarations304
Table A-9Predefined variables 305
Table A-10Constants defined by AppleScript305
Table A-11Placeholders used in syntax descriptions308
221
of a script254
of a script object258
265
289
Appendix B
xiv
Scriptable Text Editor Dictionary
Figure B-1Bounds and Position properties of a Scriptable Text Editor
window327
Table B-1Variations from standard behavior in Scriptable Text Editor versions
of standard application commands345
Table B-2Other Scriptable Text Editor commands347
313
P R E F A C E
About This Guide
The AppleScript Language Guide: English Dialect is a complete guide to the
English dialect of the AppleScript language. AppleScript allows you to create
sets of written instructions—known as scripts—to automate and customize
your applications.
Audience0
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:
■
another scripting language (such as HyperTalk, the scripting language for
HyperCard, or a scripting language for a specific application)
■
a computer programming language (such as BASIC, Pascal, or C)
■
a macro language (such as a language used to manipulate spreadsheets)
If you’re 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 programming—including books
specifically about AppleScript—in 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
Organization of This Guide0
This guide is divided into two parts:
■
Part 1, “Introducing AppleScript,” provides an overview of the AppleScript
language and the tasks you can perform with it.
■ Part 2, “AppleScript Language Reference,” provides reference descriptions
of all of the features of the AppleScript language.
Part 1 contains these chapters:
■ Chapter 1, “AppleScript, Scripts, and Scriptable Applications,” introduces
AppleScript and its capabilities.
■ Chapter 2, “Overview of AppleScript,” provides an overview of the
elements of the AppleScript language.
Part 2 contains the following chapters:
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
■ Chapter 7, “Control Statements,” describes statements that control when and
how other statements are executed. It includes information about Tell, If,
and Repeat statements.
handlers, and the scope of variables and properties in handlers and
elsewhere in a script. It includes the syntax for defining and calling
subroutines and error handlers.
■ Chapter 9, “Script Objects,” describes how to define and use script objects. It
includes information about object-oriented programming techniques such as
using inheritance and delegation to define groups of related objects.
At the end of the guide are three appendixes, a glossary of AppleScript terms,
and an index.
■ Appendix A, “The Language at a Glance,” is a collection of tables that
summarize the features of the AppleScript language. It is especially useful
for experienced programmers who want a quick overview of the language.
■ Appendix B, “Scriptable Text Editor Dictionary,” defines the words in the
AppleScript language that are understood by the Scriptable Text Editor
sample application.
■ Appendix C, “Error Messages,” lists the error messages returned
by AppleScript.
Sample Applications and Scripts0
A sample application, the Scriptable Text Editor, is included with AppleScript.
The Scriptable Text Editor is scriptable; that is, it understands scripts written in
the AppleScript language. It also supports recording of scripts: when you use
the Record button in the Script Editor (the application you use to write and
modify scripts), the actions you perform in the Scriptable Text Editor generate
AppleScript statements for performing those actions. Scripts for performing
tasks in the Scriptable Text Editor are used as examples throughout this guide.
xvii
P R E F A C E
For More Information0
Getting Started0
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 Additions0
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.
xviii
Other AppleScript Dialects0
A dialect is a version of the AppleScript language that resembles a particular
language. This guide describes the English dialect of AppleScript (also
called AppleScript English). This dialect uses words taken from the English
language and has an English-like syntax. Other dialects can use words from
other human languages, such as Japanese, and have a syntax that resembles
a specific human language or programming language.
For information about a specific dialect, see the version of the AppleScriptLanguage Guide for that dialect.
Scriptable Applications0
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.
P R E F A C E
Conventions Used in This Guide 0
Words and sample scripts in monospaced font are AppleScript language
elements that must be typed exactly as shown. Terms are shown in boldface
where they are defined. You can also find these definitions in the glossary.
Here are some additional conventions used in syntax descriptions:
language element
Plain computer font indicates an element that you
must type exactly as shown. If there are special symbols
(for example, + or &), you must also type them exactly
as shown.
placeholderItalic text indicates a placeholder that you must replace
with an appropriate value. (In some programming
languages, placeholders are called nonterminals.)
[optional]Brackets indicate that the enclosed language element or
elements are optional.
(a group)Parentheses group together elements. If parentheses are
part of the syntax, they are shown in bold.
[optional]...Three ellipsis points (. . .) after a group defined by
brackets indicate that you can repeat the group of
elements within brackets 0 or more times.
(a group). . .Three ellipsis points (. . .) after a group defined by
parentheses indicate that you can repeat the group
of elements within parentheses one or more times.
a|b|cVertical bars separate elements in a group from which
you must choose a single element. The elements are
often grouped within parentheses or brackets.
xix
P A R T ONE
Introducing AppleScript1
CHAPTER 1
Figure 1-0
Listing 1-0
Table 1-0
AppleScript, Scripts, and
Scriptable Applications1
This chapter introduces the AppleScript scripting language. It answers
these questions:
■ What is AppleScript?
■ What are scripts?
■ Who runs scripts, and who writes them?
■ How is AppleScript different from other scripting mechanisms?
■ What can you do with scripts?
■ What applications are scriptable?
What Is AppleScript?1
AppleScript is a scripting language that allows you to control Macintosh
computers without using the keyboard or mouse. AppleScript lets you use
series of written instructions, known as scripts, to control applications and the
desktop. Figure 1-1 shows the difference between changing the text style of a
paragraph with the mouse and performing the same task with a script.
What Is AppleScript?3
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
Figure 1-1Changing text style with the mouse and with a script
Changing the style of text with the mouse
Changing the style of text with a script
4What Is AppleScript?
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
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
Programmer’s 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 you’ve used any of these languages, you’ll 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.
What Can You Do With Scripts?1
AppleScript lets you automate, integrate, and customize applications. The
following sections provide examples.
Automating Activities1
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.
What Can You Do With Scripts?5
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
Figure 1-2A script that performs a repetitive action
Introduction before running script
Make AppleScript Bold script
Introduction after running script
6What Can You Do With Scripts?
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
Integrating Applications 1
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 1
Scripts can add new features to applications. To customize an application, you
add a script that is triggered by a particular action within the application, such
as choosing a menu item or clicking a button. Whether you can add scripts to
applications is up to each application, as are the ways you associate scripts
with specific actions.
What Can You Do With Scripts?7
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
Figure 1-3A script that copies information from one application to another
8What Can You Do With Scripts?
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
Who Runs Scripts, and Who Writes Them?1
To run a script is to cause the actions the script describes to be performed.
Everyone who uses a Macintosh computer can run scripts. Figure 1-4 illustrates
two ways to run a script.
Figure 1-4Different ways to run a script
Double-clicking a script application’s icon
Clicking the Run button
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.
Who Runs Scripts, and Who Writes Them?9
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
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.
Special Features of AppleScript1
AppleScript has a number of features that set it apart from both macro
programs and scripting languages that control a single program:
■ AppleScript makes it easy to refer to data within applications. Scripts can
use familiar names to refer to familiar objects. For example, a script can refer
to paragraph, word, and character objects in a word-processing document
and to row, column, and cell objects in a spreadsheet.
■ You can control several applications from a single script. Although many
applications include built-in scripting or macro languages, most of these
languages work for only one application. In contrast, you can use AppleScript
to control any of the applications that support it. You don’t have to learn a
new language for each application.
■ You can write scripts that control applications on more than one computer. A
single script can control any number of applications, and the applications
can be on any computer on a given network.
■ You can create scripts by recording. The Script Editor application includes a
recording mechanism that takes much of the work out of creating scripts.
When recording is turned on, you can perform actions in a recordable
application and the Script Editor creates corresponding instructions in the
AppleScript language. To learn how to turn recording on and off, refer to
Getting Started With AppleScript.
■ AppleScript supports multiple dialects, or representations of the AppleScript
language that resemble various human languages and programming
languages. This guide describes the AppleScript English dialect. You can use
Script Editor to convert a script from one dialect to another without
changing what happens when you run the script.
10Special Features of AppleScript
CHAPTER 1
AppleScript, Scripts, and Scriptable Applications
What Applications Are Scriptable?1
Applications that understand one or more AppleScript commands are called
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.
Some scriptable applications are also recordable. For every significant action
you can perform in a recordable application, the Script Editor can record a
series of corresponding instructions in the AppleScript language. With
recordable applications, you can create a script simply by performing actions
in the application.
Finally, some scriptable applications are also attachable. An attachable applica-tion is one that can be customized by attaching scripts to specific objects in the
application, such as buttons and menu items. These scripts are triggered by
specific user actions, such as choosing a menu item or clicking a button.
What Applications Are Scriptable?11
CHAPTER 2
Figure 2-0
Listing 2-0
Table 2-0
Overview of AppleScript2
AppleScript is a dynamic, object-oriented script language. At its heart is the
ability to send commands to objects in many different applications. These
objects, which are familiar items such as words or paragraphs in a text-editing
application or shapes in a drawing application, respond to commands by
performing actions. AppleScript determines dynamically—that is, whenever
necessary—which objects and commands an application recognizes based on
information it obtains from each scriptable application.
In addition to manipulating objects in other applications, AppleScript can store
and manipulate its own data, called values. Values are simple data structures,
such as character strings and real numbers, that can be represented in scripts
and manipulated with operators. Values can be obtained from applications or
created in scripts.
The building blocks of scripts are statements. When you write a script, you
compose statements that describe the actions you want to perform. AppleScript
includes several kinds of statements that allow you to control when and how
statements are executed. These include If statements for conditional execution,
Repeat statements for statements that are repeated, and handler definitions for
creating user-defined commands.
This chapter provides an overview of AppleScript. It includes a summary of
how AppleScript works and brief descriptions of the AppleScript language
elements. Part 2 of this book, “AppleScript Language Reference,” describes the
elements of the AppleScript language in more detail.
13
CHAPTER 2
Overview of AppleScript
How Does AppleScript Work?2
AppleScript works by sending messages, called Apple events, to applications.
When you write a script, you write one or more groups of instructions called
statements. When you run the script, the Script Editor sends these statements
to the AppleScript extension, which interprets the statements and sends Apple
events to the appropriate applications. Figure 2-1 shows the relationship
between the Script Editor, the AppleScript extension, and the application.
The parts that you use—the Script Editor and the application—are shown to
the left of the dotted line in Figure 2-1. The parts that work behind the scenes—
the AppleScript extension and Apple events—are shown to the right of the
dotted line.
Applications respond to Apple events by performing actions, such as changing
a text style, getting a value, or opening a document. Applications can also
send Apple events back to the AppleScript extension to report results. The
AppleScript extension sends the final results to the Script Editor, where they
are displayed in the result window.
When you write scripts, you needn’t be concerned about Apple events or the
AppleScript extension. All you need to know is how to use the AppleScript
language to request the actions or results that you want.
Statements2
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.
14How Does AppleScript Work?
CHAPTER 2
Overview of AppleScript
Figure 2-1How AppleScript works
Script Editor
Writes, records, and runs scripts
Application
• Responds to Apple events by performing actions
• Sends Apple events to AppleScript extension
1
4
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)
Statements15
CHAPTER 2
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
Notice that this example contains the statement print
front window instead of print the front window.
AppleScript allows you to add or remove the word the
anywhere in a script without changing the meaning of the
script. You can use the word the to make your statements
more English-like and therefore more readable. ◆
16Statements
CHAPTER 2
Overview of AppleScript
Here’s another example of a compound statement:
if the number of windows is greater than 0 then
print front window
end if
Statements contained in a compound statement can themselves be compound
statements. Here’s an example:
tell application "Scriptable Text Editor"
if the number of windows is greater than 0 then
print front window
end if
end tell
Commands and Objects 2
Commands are the words or phrases you use in AppleScript statements to
request actions or results. Every command is directed at a target, which is
the object that responds to the command. The target of a command is usually
an application object. Application objects are objects that belong to an
application, such as windows, or objects in documents, such as the words
and paragraphs in a text document. Each application object has specific
information associated with it and can respond to specific commands.
For example, in the Scriptable Text Editor, window objects understand the Print
command. The following example shows how to use the Print command to
request that the Scriptable Text Editor print the front window.
tell application "Scriptable Text Editor"
print front window
end tell
The Print command is contained within a Tell statement. Tell statements
specify default targets for the commands they contain. The default target is the
object that receives commands if no other object is specified or if the object is
Commands and Objects17
CHAPTER 2
Overview of AppleScript
specified incompletely in the command. In this case, the statement containing
the Print statement does not contain enough information to uniquely identify
the window object, so AppleScript uses the application name listed in the Tell
statement to determine which object receives the Print command.
In AppleScript, you use references to identify objects. A reference is a
compound name, similar to a pathname or address, that specifies an object.
For example, the following phrase is a reference:
front window of application "Scriptable Text Editor"
This phrase specifies a window object that belongs to a specific application.
(The application itself is also an object.) AppleScript has different types of
references that allow you to specify objects in many different ways. You’ll learn
more about references in Chapter 5, “Objects and References.”
Objects can contain other objects, called elements. In the previous example, the
front window is an element of the Scriptable Text Editor application object.
Similarly, in the next example, a word element is contained in a specific
paragraph element, which is contained in a specific document.
word 1 of paragraph 3 of document "Try This"
Every object belongs to an object class, which is simply a name for objects with
similar characteristics. Among the characteristics that are the same for the
objects in a class are the commands that can act on the objects and the elements
they can contain. An example of an object class is the Document object class in
the Scriptable Text Editor. Every document created by the Script Editor belongs
to the Document object class. The Script Editor’s definition of the document
object class determines which classes of elements, such as paragraphs and
words, a document object can contain. The definition also determines which
commands, such as the Close command, a document object can respond to.
Dictionaries2
To examine a definition of an object class, a command, or some other word
supported by an application, you can open that application’s 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,
18Dictionaries
CHAPTER 2
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 application’s 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 application’s 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 application’s 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
Dictionaries19
CHAPTER 2
Overview of AppleScript
the application. Figure 2-2 shows how AppleScript gets the words in the
Scriptable Text Editor ’s dictionary.
Figure 2-2How AppleScript gets the Scriptable Text Editor dictionary
Scriptable Text Editor
application
Dictionary
resource
AppleScript
extension
Commands:
cut
make
print
...
Objects:
character
paragraph
window
...
Dictionary of
commands
and objects
In addition to the terms defined in application dictionaries, the AppleScript
English dialect includes its own standard terms. Unlike the terms in application dictionaries, the standard AppleScript terms are always available. You can
use these terms (such as If, Tell, and First) anywhere in a script. This manual
describes the standard terms provided by the AppleScript English dialect.
The words in system and application dictionaries are known as reservedwords. When defining new words for your script—such as identifiers for
variables—you cannot use reserved words.
Values2
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.
20Values
CHAPTER 2
Overview of AppleScript
Values are an important means of exchanging data in AppleScript. When you
request information about application objects, it is usually returned in the form
of values. Similarly, when you provide information with commands, you
typically supply it in the form of values.
A fixed number of specific types of values are recognized by AppleScript. You
cannot define additional types of values, nor can you change the way values
are represented. The different types of AppleScript values, called value classes,
are described in Chapter 3, “Values.”
Expressions 2
An expression is a series of AppleScript words that corresponds to a value.
Expressions are used in scripts to represent or derive values. When you run a
script, AppleScript converts its expressions into values. This process is known
as evaluation.
Two common types of expressions are operations and variables. An operation
is an expression that derives a new value from one or two other values. A
variable is a named container in which a value is stored. The following sections
introduce operations and variables. For more information about these and
other types of expressions, see Chapter 6, “Expressions.”
Operations2
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
(12 > 4) AND (12 = 4)--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.
Expressions21
CHAPTER 2
Overview of AppleScript
You can use operations within AppleScript statements, such as:
tell application "Scriptable Text Editor"
delete word 3 + 4 of document "Test"
end tell
When you run this script, AppleScript evaluates the expression 3 + 4 and
uses the result to determine which word to delete.
Variables2
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 data—the 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
22Expressions
CHAPTER 2
Overview of AppleScript
AppleScript does not distinguish uppercase letters from lowercase variables in
variable names; the variables myName, myname, and MYNAME all represent the
same value.
Script Objects2
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 Additions2
Scripting additions are files that provide additional commands or coercions
you can use in scripts. A scripting addition file must be located in the Scripting
Additions folder (located in the Extensions folder of the System Folder) for
AppleScript to recognize the additional commands it provides.
Unlike other commands used in AppleScript, scripting addition commands
work the same way regardless of the target you specify. For example, the Beep
command, which is provided by the General Commands scripting addition,
triggers the alert sound no matter which application the command is sent to.
A single scripting addition file can contain several commands. For example, the
File Commands scripting addition includes the commands Path To, List Folder,
List Disks, and Info For. The scripting additions provided by Apple Computer,
Inc., are described in the book AppleScript Scripting Additions Guide. Scripting
additions are also sold commercially, included with applications, and
distributed through electronic bulletin boards and user groups.
Script Objects23
CHAPTER 2
Overview of AppleScript
Dialects2
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.
Other Features and Language Elements2
So far, you’ve 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, you’ll need to know about a few additional elements
and features of the AppleScript scripting language that are not described in
the reference:
■ continuation characters
■ comments
■ identifiers
■ case sensitivity
■ abbreviations
■ compiling scripts
24Dialects
CHAPTER 2
Overview of AppleScript
Continuation Characters 2
A simple AppleScript statement must normally be on a single line. If a statement
is longer than will fit on one line, you can extend it by including a continuationcharacter, ¬ (Option-L or Option-Return), at the end of one line and continuing
the statement on the next. For example, the statement
delete word 1 of paragraph 3 of document "Learning AppleScript"
can appear on two lines:
delete word 1 of paragraph 3 of document ¬
"Learning AppleScript"
The only place a continuation character does not work is within a string. For
example, the following statement causes an error, because AppleScript interprets
the two lines as separate statements.
--this statement causes an error:
delete word 1 of paragraph 3 of document "Fundamentals ¬
of Programming"
Note
The characters -- in the example indicate that the first line
is a comment. A comment is text that is ignored by
AppleScript when a script is run. Comments are added to
help you understand scripts. They are explained in the
next section, “Comments.” ◆
If a string extends beyond the end of the line, you can continue typing without
pressing Return (the text never wraps to the next line), or you can break the
string into two or more strings and use the concatenation operator (&) to
join them:
delete word 1 of paragraph 3 of document "Fundamentals " ¬
& "of Programming"
For more information about the concatenation operator, see Chapter 6,
“Expressions.”
Other Features and Language Elements25
CHAPTER 2
Overview of AppleScript
Comments2
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
26Other Features and Language Elements
CHAPTER 2
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 aren’t yet finished.
Here’s an example of “commenting out” an unfinished handler:
(*
on finish()
--under construction
end
*)
If you later remove (* and *), the handler is once again available.
Identifiers2
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. You’ll learn
about these uses later in this guide.
An identifier must begin with a letter and can contain uppercase letters,
lowercase letters, numerals (0–9), 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
Other Features and Language Elements27
CHAPTER 2
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 words—that 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 Sensitivity2
AppleScript is not case sensitive; when it interprets statements in a script, it
does not distinguish uppercase from lowercase letters. This is true for all
elements of the language.
The one exception to this rule is string comparisons. Normally, AppleScript
does not distinguish uppercase from lowercase letters when comparing strings,
but if you want AppleScript to consider case, you can use a special statement
called a Considering statement. For more information, see “Considering and
Ignoring Statements” on page 213.
Most of the examples in this chapter and throughout this guide are in lowercase letters. Sometimes words are capitalized to improve readability. For
example, in the following variable assignment, the “N” in myName is capitalized
to make it easier to see that two words have been combined to form the name of
the variable.
set myName to "Pegi"
28Other Features and Language Elements
CHAPTER 2
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.
Abbreviations2
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
Other Features and Language Elements29
CHAPTER 2
Overview of AppleScript
Compiling Scripts With the Script Editor2
When you create or modify a script and then attempt to run or save it as a
compiled script or script application, the Script Editor asks AppleScript to
compile the script first. To compile a script, AppleScript converts the script
from the form typed into a Script Editor window (or any script-editing
window) to a form that AppleScript can execute. AppleScript also attempts to
compile the script when you click the Script Editor’s Check Syntax button.
If AppleScript compiles the script successfully, the Check Syntax button is
dimmed and the Script Editor reformats the text of the script according to the
preferences set with the AppleScript Formatting command (in the Edit menu).
This may cause indentation and spacing to change, but it doesn’t affect the
meaning of the script. If AppleScript can’t compile the script because of syntax
errors or other problems, the Script Editor displays a dialog box describing the
error or, if you are trying to save the script, allowing you to save the script as a
text file only.
30Other Features and Language Elements
P A R T TWO
AppleScript Language
Reference2
CHAPTER 3
Figure 3-0
Listing 3-0
Table 3-0
Values3
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.
Using Value Class Definitions3
Value class definitions contain information about values that belong to a
particular class. All value classes fall into one of two categories: simple values,
such as integers and real numbers, which do not contain other values, or
composite values, such as lists and records, which do. Value class definitions
for composite values contain more types of information than definitions for
simple values.
Figure 3-1 shows the definition for the List value class, a composite value. The
figure shows seven types of information: examples, properties, elements,
operators, commands handled, reference forms, and coercions supported. The
sections following the figure explain each type of information. Some definitions
end with notes (not shown in Figure 3-1) that provide additional information.
Using Value Class Definitions33
CHAPTER 3
Values
Figure 3-1Value class definition for lists
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
A list appears in a script as a series of expressions contained within braces
and separated by commas. For example,
{ "it's", 2, TRUE }
is a list containing a string, an integer, and a Boolean.
PROPERTIES
Class
Length
Rest
Reverse
The class identifier for the value. This property is read-only,
and its value is always list.
An integer containing the number of items in the list. This
property is read-only.
A list containing all items in the list except the first item.
A list containing all items in the list, but in the opposite order.
ELEMENTS
Item
A value contained in the list. Each value contained in a list is
an item. You can refer to values by their item numbers. For
example, item 2 of {"soup", 2, "nuts"} is
integer 2. To specify items of a list, use the reference forms
listed in "Reference Forms" later in this definition.
OPERATORS
The operators that can have lists as operands are &, =, , Starts With, Ends
With, Contains, Is Contained By.
34Using Value Class Definitions
the
CHAPTER 3
Values
Figure 3-1Value class definition for lists (continued)
Using Value Class Definitions35
CHAPTER 3
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
AppleScript supports coercion of a single-item list to any value class
to which the item can be coerced if it is not part of a list.
AppleScript also supports coercion of an entire list to a string if all
items in the list can be coerced to a string. The resulting string
concatenates all the items:
{5, "George", 11.43, "Bill"} as string
--result: "5George11.43Bill"
36Using Value Class Definitions
CHAPTER 3
Values
Literal Expressions3
A literal expression is an expression that evaluates to itself. The “Literal
Expressions” section of a value class definition shows examples of how values
of a particular class are represented in AppleScript—that is, typical literal
expressions for values of that class. For example, in AppleScript and many
other programming languages, the literal expression for a string is a series of
characters enclosed in quotation marks. The quotation marks are not part of the
string value; they are a notation that indicates where the string begins and
ends. The actual string value is a data structure stored in AppleScript.
The sample value class definition in Figure 3-1 shows literal expressions for list
values. As with the quotation marks in a string literal expression, the braces
that enclose a list and the commas that separate its items are not part of the
actual list value; they are notations that represent the grouping and items of
the list.
Properties3
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.
Using Value Class Definitions37
CHAPTER 3
Values
Elements3
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:
item 3 of {"To", "be", "great", "is", "to", "be", "misunderstood"}
--result: "great"
The “Reference Forms” section of a composite value class definition lists the
reference forms you can use to specify elements of composite values.
Operators3
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 Handled3
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.
38Using Value Class Definitions
CHAPTER 3
Values
Reference Forms3
A reference is a compound name for an object or a value. You can use
references to specify values within composite values or properties of simple
values. You cannot use references to refer to simple values.
The “Reference Forms” section is included in composite value class definitions
only. It lists the reference forms you can use to specify elements of a composite
value. For complete descriptions of the AppleScript reference forms, see
Chapter 5, “Objects and References.”
Coercions Supported3
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.
Value Class Definitions3
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.
Value Class Definitions39
CHAPTER 3
Values
Table 3-1AppleScript value class identifiers
Value class
identifierDescription of corresponding value
BooleanA logical truth value
ClassA class identifier
ConstantA reserved word defined by an application or AppleScript
DataRaw data that cannot be represented in AppleScript, but can
be stored in a variable
DateA string that specifies a day of the week, day of the month,
month, year, and time
IntegerA positive or negative number without a fractional part
ListAn ordered collection of values
NumberSynonym for class Integer or class Real; a positive or negative
number that can be either of class Integer or of class Real
RealA positive or negative number that can have a fractional part
RecordA collection of properties
ReferenceA reference to an object
StringAn ordered series of characters
Styled TextSynonym for a special string that includes style and font
information
TextSynonym for class string
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.
40Value Class Definitions
CHAPTER 3
Values
Boolean3
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
ClassThe 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
AppleScript supports coercion of a Boolean value to a single-item list.
Value Class Definitions41
CHAPTER 3
Values
Class3
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
ClassThe 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
AppleScript supports coercion of a class identifier to a single-item list.
42Value Class Definitions
CHAPTER 3
Values
Constant3
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
ClassThe class identifier for the object. This property is read-only,
and its value is always constant.
ELEMENTS
None
OPERATORS
The operators that take values of class Constant as operands are &, =, , and As.
COERCIONS HANDLED
AppleScript supports coercion of a constant to a single-item list.
NOTES
Constants are not strings, and they must not be surrounded by
quotation marks.
You cannot define your own constants; constants can be defined only
by applications and AppleScript.
Value Class Definitions43
CHAPTER 3
Values
Data3
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
ClassThe class identifier for the object. This property is read-only,
and its value varies depending on the application.
ELEMENTS
None
OPERATORS
The operators that can take values of class Data as operands are = and .
COERCIONS SUPPORTED
AppleScript supports coercion of a Data value to a single-item list.
Date3
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.
44Value Class Definitions
CHAPTER 3
Values
LITERAL EXPRESSIONS
date "12/5/54, 12:06 PM"
date "12/05/53, 12:06"
date "12/05/54"
date "12:06"
date "Sunday, December 5, 1954 12:06 pm"
PROPERTIES
ClassThe class identifier for the object. This property is read-only, and
WeekdayOne of the constants Monday, Tuesday, Wednesday,
MonthOne of the constants January, February, March, April, May,
YearAn integer specifying the year; for example, 1993.
TimeAn integer that specifies the number of seconds since midnight
DateA string that consists of the date portion of the date value; for
June, July, August, September, October, November,
December or Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec.
of the date value; for example, 2700 is equivalent to 12:45
AM.
example, "June 3, 1993".
ELEMENTS
None
Value Class Definitions45
OPERATORS
CHAPTER 3
Values
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:
minutes60
hours60 * minutes
days24 * hours
weeks7 * days
Here’s 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.
46Value Class Definitions
CHAPTER 3
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
AppleScript supports coercion of a Date value to a single-item list or a string.
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 don’t specify a complete date, day, and time when typing a Date value,
AppleScript fills in information as needed. If you don’t specify the date
information, AppleScript uses the date when the script is compiled. If you
Value Class Definitions47
CHAPTER 3
Values
don’t 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.
Integer3
A value of class Integer is a positive or negative number without a
fractional part.
LITERAL EXPRESSIONS
1
2
-1
1000
PROPERTY
ClassThe class identifier for the object. This property is read-only, and
its value is always integer.
ELEMENTS
None
48Value Class Definitions
CHAPTER 3
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
AppleScript supports coercion of an Integer value to a single-item list, a real
number, or a string.
You can also coerce an integer using the synonym Number, but the class of the
resulting value remains unchanged:
set x to 7 as number
class of x --result: integer
NOTES
The largest value that can be expressed as an integer in AppleScript is
536870909, which is equal to (229– 3). Larger integers (positive or negative)
are converted to real numbers (expressed in exponential notation) when
scripts are compiled.
List3
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
A list appears in a script as a series of expressions contained within braces and
separated by commas. For example,
{ "it's", 2, true }
is a list containing a string, an integer, and a Boolean.
Value Class Definitions49
PROPERTIES
CHAPTER 3
Values
Each list item can be any valid expression. For example,
{ "it" & "'s", 1 + 1, 4 > 3 }
has the same value as the list in the previous example, because each of the
expressions it contains has the same value as the corresponding expression
in the previous example.
An empty list is a list containing no items. It is represented by a pair of
empty braces:
{}
ClassThe class identifier for the value. This property is read-only, and
its value is always list.
LengthAn integer containing the number of items in the list. This
property is read-only.
RestA list containing all items in the list except the first item.
ReverseA list containing all items in the list, but in the opposite order.
ELEMENT
ItemA value contained in the list. Each value contained in a list
is an item. You can refer to values by their item numbers.
For example, item 2 of { "soup", 2, "nuts" } is the
integer 2. To specify items of a list, use the reference forms listed
in “Reference Forms” later in this definition.
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.
50Value Class Definitions
CHAPTER 3
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:
■ Property. For example, class of {"this", "is", "a", "list"}
■ Index. For example, item 3 of {"this", "is", "a", "list"}
■ Middle. For example, middle item of {"this", "is", "a",
■ Arbitrary. For example, some item of {"soup", 2, "nuts"} might
■ Every Element. For example, every item of {"soup", 2, "nuts"}
■ Range. For example, items 2 thru 3 of {"soup", 2, "nuts"}
Value Class Definitions51
specifies list.
specifies "a".
"list"} specifies "is".
specify any of the items in the list.
specifies {"soup", 2, "nuts"}.
specifies {2, "nuts"}.
CHAPTER 3
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
AppleScript supports coercion of a single-item list to any value class to which
the item can be coerced if it is not part of a list.
AppleScript also supports coercion of an entire list to a string if all items in the
list can be coerced to a string. The resulting string concatenates all the items:
{5, "George", 11.43, "Bill"} as string
--result: "5George11.43Bill"
Individual items in a list can be of any value class, and AppleScript supports
coercion of any value to a list that contains a single item. Concatenated values
of any class can also be coerced to a list:
5 & "George" & 11.43 & "Bill" as list
--result: {5, "George", 11.43, "Bill"}
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.
52Value Class Definitions
CHAPTER 3
Values
Number3
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
ELEMENTS
OPERATORS
ClassThe class identifier for the object. This property is read-only, and
its value is always either integer or real.
None
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.
Value Class Definitions53
CHAPTER 3
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
Real3
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
ClassThe class identifier for the object. This property is read-only, and
its value is always real.
54Value Class Definitions
CHAPTER 3
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
AppleScript supports coercion of a Real value to a single-item list or a
string. AppleScript supports coercion of a Real value to an Integer value
only if the Real value has no fractional part.
AppleScript also supports coercion of a Real value using the synonym Number,
but the class of the resulting value remains unchanged:
set x to 1.5 as number
class of x --result: real
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.
Record3
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.
Value Class Definitions55
CHAPTER 3
Values
LITERAL EXPRESSIONS
Records appear in scripts as series of properties contained within braces and
separated by commas. Each property has a label. Following the label is a colon,
and following the colon, the value of the property. For example, the record
{ name:"Mitchell", height:70.5, weight:165 }
contains three properties: Name (a string), Height (a real number), and Weight
(an integer). The values assigned to properties can belong to any class.
AppleScript evaluates expressions in a record before using the record in other
expressions. For example, the record
In addition to the properties that are specific to each record, two properties are
common to all records:
ClassThe 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}, ¬
LengthAn integer containing the number of properties in the record.
This property is read-only.
If you define a Class property explicitly in a record, the value you define
replaces the implicit Class property record described above.
56Value Class Definitions
Off Styles:{ Italic, Outline, Shadow}}
CHAPTER 3
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
AppleScript supports coercion of records to lists; however, all property labels
are lost in the coercion and the resulting list cannot be coerced back to a record.
Value Class Definitions57
CHAPTER 3
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.
Reference3
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 word 1 of front window of app ¬
"Scriptable Text Editor"
--result: word 1 of window 1 of application ¬
"Scriptable Text Editor"
58Value Class Definitions
CHAPTER 3
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
word 1 of document "Report"
window "Graph"
PROPERTIES
ClassThe class identifier for the object. This property is read-only, and
ContentsThe value of the object to which the reference refers. The class
its value is always reference.
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
OPERATORS
None
The A Reference To operator returns a reference as its result.
Value Class Definitions59
CHAPTER 3
Values
COERCIONS SUPPORTED
The application to which an object specified by a reference belongs determines
whether the value of the object can be coerced to a desired class.
NOTES
A reference can function as a reference to an object or as an expression whose
value is the value of the object specified in the reference. When a reference is
the direct parameter of a command, it usually functions as a reference to an
object, indicating to which object the command should be sent. In most other
cases, references function as expressions, which AppleScript evaluates by
getting their values.
For example, the reference in the following example functions as a reference to
an object. It identifies the object to which the Copy command is sent.
copy word 1 of front document of application "Scriptable Text Editor"
On the other hand, the reference in the following example functions as a
reference expression:
repeat (word 1 of front document of application
"Scriptable Text Editor") times
display dialog "Hello"
end repeat
When AppleScript executes the statement, it gets the value of the reference
word 1 of front document of application "Scriptable Text
Editor"—a string—and then coerces it to an integer, if possible. (For
information about the Repeat statement, see “Repeat Statements,” which
begins on page 194. For information about coercions, see “Coercing Values” on
page 68.)
60Value Class Definitions
CHAPTER 3
Values
String3
A value of class String is a character string (an ordered series of characters)
in AppleScript.
LITERAL EXPRESSIONS
Strings in scripts are always surrounded by quotation marks, as in these
examples:
"string"
"Rolling along, stringing a song"
"Pennsylvania 68000"
To include quotation marks in a string, you must use the equivalent twocharacter sequence, \". For more information, see “Special Characters in
Strings” later in this section.
PROPERTIES
ELEMENTS
ClassThe class identifier for the object. This property is read-only, and
its value is always string.
LengthThe number of characters in the string.
Strings can have character, word, paragraph, and text elements.
The elements of a string may be different from the character, word, paragraph,
and text objects of applications.
CharacterA single character contained in the string.
Paragraph A series of characters ending with either (1) a return character
or (2) the end of the string and beginning immediately after
either (1) the first character after the end of the preceding
paragraph or (2) the beginning of the string.
Text A continuous series of characters, including spaces, tabs, and
all other characters, within a string (see “Notes” later in
this section).
Value Class Definitions61
CHAPTER 3
Values
WordA continuous series of characters that contains only the
following types of characters:
letters (including letters with diacritical marks)
digits
nonbreaking spaces
dollar signs, cent signs, English pound symbols, or yen symbols
percent signs
commas between digits
periods before digits
apostrophes between letters or digits
hyphens (but not minus signs [Option-hyphen] or dashes
[Option-Shift-hyphen]).
Here are some examples of words:
non-functional
he's
v1.0
$99.99
12c-d
Note that this definition applies to English text in the Roman
script system. Words in other languages are defined by the
script system for each language if the appropriate script system
is installed. (For more information about script systems, see
page 317.)
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.
62Value Class Definitions
CHAPTER 3
Values
REFERENCE FORMS
You can use the following reference forms to refer to elements of strings:
■ Property. For example, class of "This is a string" specifies string.
■ Index. For example, word 3 of "This is a string" specifies "a".
■ Middle. For example, middle word of "This is a string"
specifies "is".
■ Arbitrary. For example, some word of "This is a string" might
specify any of the words in the string.
■ Every Element. For example, every word of "This is a string"
specifies {"This", "is", "a", "string"}.
■ Range. For example, words 2 thru 3 of "This is a string"
specifies {"is", "a"}.
You cannot use the Relative, Name, ID, or Filter reference forms.
SPECIAL CHARACTERS IN STRINGS
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
When a string containing any of the two-character sequences is displayed to
the user (as, for example, in a dialog box), the sequences are converted. For
example, the string
"item 1\t1\ritem 2\t2"
Value Class Definitions63
CHAPTER 3
Values
is displayed in a dialog box as
item 11
item 22
STRING CONSTANTS
AppleScript defines three constants for string values:
ConstantValue
space" "
tab"\t"
return"\r"
COERCIONS SUPPORTED
If a string consists of an appropriate number, AppleScript supports coercion of
the string to an integer, a number, or a real number. Similarly, any integer,
number, or real number can be coerced to a string. AppleScript also supports
coercion of a string to a single-item list and coercion of a list whose items are all
strings to a single concatenated string.
NOTES
There is no limit on the length of strings except the memory available in
the computer.
To get a contiguous range of characters within a string, use the text element.
For example, the value of the following statement is the string "y thi".
get text of characters 3 thru 7 of "Try this at home"
--result: "y thi"
The result of the same statement without the text element is a list.
get characters 3 thru 7 of "Try this at home"
--result: {"y", " ", "t", "h", "i"}
64Value Class Definitions
CHAPTER 3
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, you’ll 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 Text3
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
ELEMENTS
ClassThe class identifier for the object. This property is read-only, and
its value is always string.
LengthThe number of characters in the string.
Styled text has the same character, word, paragraph, and text elements as
a string.
Value Class Definitions65
CHAPTER 3
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.
SPECIAL CHARACTERS AND STRING CONSTANTS
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.
66Value Class Definitions
NOTES
CHAPTER 3
Values
You can’t 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 don’t 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.
Text3
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
Value Class Definitions67
CHAPTER 3
Values
However, the class of a string is always string:
class of "A string" as text
--result: string
Unlike the class identifier Number (which is a synonym for either Real or
Integer) or Styled Text (which denotes a string that includes font and style
information), the class identifier Text is precisely equivalent to a single class
identifier—String.
Coercing Values3
AppleScript coerces values in two ways:
■ in response to the As operator
■ automatically, when a value is of a different class than was expected for a
particular command or operation
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.
68Coercing Values
CHAPTER 3
Values
If you provide a command parameter or operand of the wrong class, AppleScript
automatically coerces the operand or parameter to the expected class, if possible.
For example, when AppleScript executes this statement,
repeat ( word 2 of document "Big" of application
"Scriptable Text Editor") times
display dialog "Hello"
end repeat
it expects the number of times to be an integer. To coerce word 2 of
document "Big" of application "Scriptable Text Editor" to an integer, AppleScript gets the value of word 2 of document "Big"
of application "Scriptable Text Editor"—a string—and then
coerces it to an integer, if possible.
Not all values can be coerced to all other classes of values. Figure 3-2 summarizes
the coercions that AppleScript supports. To use the figure, find the class of the
value to be coerced in the column at the left. Search across the table to the column
labeled with the class to which you want to coerce the value. If there is a square
at the intersection, then AppleScript supports the coercion.
Reference values are not included in the table because applications determine
whether the value of an object specified by a reference value can be coerced to a
desired class.
For more information about each coercion, see the corresponding value class
definitions in this chapter.
Note
When coercing strings to values of class Integer, Number,
or Real or vice versa, AppleScript uses the current settings
in the Numbers control panel for decimal and thousands
to determine what separators to use in the string.
When coercing strings to values of class date or vice versa,
AppleScript uses the current settings in the Date & Time
control panel for date and time format. ◆
Coercing Values69
CHAPTER 3
Values
Figure 3-2Coercions supported by AppleScript
Coerce to
Boolean
Class
Constant
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.
Data
Date
Integer
‡
Single-item list
Multi-item list
Number
Real
Record
String or text
Styled text*
†
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
70Coercing Values
CHAPTER 3
Values
set x to 4 as number
class of x
--result: integer
set x to "Hello" as text
class of x
--result: string
Coercing Values71
CHAPTER 3
Values
72Coercing Values
CHAPTER 4
Figure 4-0
Listing 4-0
Table 4-0
Commands4
A command is a word or series of words used in AppleScript statements to
request an action. Every command is directed at a target, which is the object
that responds to the command. The target is usually an application object,
but it can also be a script object or a user-defined subroutine or value in the
current script.
Not all commands can be used with all types of targets. When you use a
command to request an action, you must choose a command that works with
the target you want to manipulate. You must also be sure to specify the target
correctly. Several factors, including the direct parameter you provide with a
command and whether or not the command is included in a Tell statement, can
determine the target of a command.
This chapter begins by describing types of commands and targets of commands.
It summarizes which types of commands work with which types of targets.
Next, it describes the details of using commands and command definitions,
including specifying parameters and using results of commands. The chapter
ends with definitions of standard commands.
Types of Commands4
You can use four types of commands in AppleScript to request actions:
application commands, AppleScript commands, scripting additions, and
user-defined commands.
Each time you use a command, you specify the target, or recipient, of the
command. Potential targets include application objects, script objects, the
current script, and the current application. In some cases you specify the
target explicitly by including it in a Tell statement or supplying a direct
parameter. In other cases you specify the target implicitly.
Ty pes of Commands71
CHAPTER 4
Commands
The sections that follow describe the different types of commands and
their targets.
Application Commands4
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 application’s 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
command’s 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
72Ty pes of Commands
CHAPTER 4
Commands
Similarly, if you specify a reference incompletely in the command line,
AppleScript uses the default target specified in the enclosing Tell statement
to complete the reference. For example, the following statement is equivalent
to both of the previous examples:
tell front document of app "Scriptable Text Editor"
delete word 1
end tell
For information about sending application commands to script objects, see
Chapter 9, “Script Objects,” which begins on page 265.
AppleScript Commands4
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):
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.
Ty pes of Commands73
CHAPTER 4
Commands
For more examples of how to use Copy, Count, Get, Run, and Set, see the
command definitions later in this chapter.
Scripting Addition Commands4
Scripting additions are files that provide additional commands or coercions
you can use in scripts. Each scripting addition can contain one or more
command handlers. If a scripting addition is located in the Scripting Additions
folder (in the Extensions folder of the System Folder), the command handlers it
provides are available for use by any script whose target is an application on
that computer.
Like the target of an application command, the target of a scripting addition
command is always an application object or a script object. If the script doesn’t
explicitly specify the target with a Tell statement, AppleScript sends the
command to the default target application, which is usually the application
running the script (for example, the Script Editor).
A scripting addition command performs its action only after the command has
been received by a target application. Unlike application commands, scripting
addition commands always work the same way regardless of the application to
which they are sent.
For example, the scripting addition command Display Dialog displays a dialog
box that can include text, one or more buttons, an icon, and a field in which the
user can type text. In the script that follows, the target of the Display Dialog
command is the Scriptable Text Editor application. When the script runs, the
Scriptable Text Editor becomes the frontmost application (that is, its menus
become visible and its windows become the frontmost windows on the screen)
and passes the command to the scripting addition’s handler for the Display
Dialog command, which displays the dialog box.
tell application "Scriptable Text Editor"
display dialog "What’s your name?" default answer ""
end tell
In the next example, the Display Dialog command is not enclosed in a Tell
statement, nor does it have a direct parameter, so its target is the Script Editor
(or whatever application runs the script). When you run the script, the Script
Editor passes the command to the scripting addition’s handler for the Display
74Ty pes of Commands
CHAPTER 4
Commands
Dialog command, which displays the dialog box in the Script Editor’s 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 words—including the command names, parameter
labels, and in some cases object names—used 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, you’ll 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.
Ty pes of Commands75
CHAPTER 4
Commands
User-Defined Commands4
User-defined commands are commands that trigger the execution of collections
of statements, called subroutines, elsewhere in the same script. The target of a
user-defined command is the current script, that is, the script from which the
command is executed.
There are two ways to specify the current script as the target of a user-defined
command. Outside of a Tell statement, simply use the command to specify the
current script as its target. For example, suppose that minimumValue is a
command defined by the user in the current script. The handler for the
minimumValue command is a subroutine that returns the smaller of two
values. The target of the minimumValue command in the following example is
the current script:
set theCount to minimumValue(12,105)
Inside a Tell statement, use the words of me or my to indicate that the target
of the command is the current script and not the default target of the Tell
statement. For example, the following sample script shows how to call the
minimumValue subroutine from within a Tell statement:
tell application "Scriptable Text Editor"
set theCount to my minimumValue(12,105)
get word theCount of front document
end tell
Without the word my before the minimumValue command, AppleScript
sends the minimumValue command to the Scriptable Text Editor, resulting
in an error.
Chapter 8, “Handlers,” describes the syntax for defining and invoking
subroutines such as minimumValue in more detail.
Note
You can also define subroutines in script objects. The target
of a user-defined command whose subroutine is defined in
a script object is the script object. For information about
defining and invoking subroutines in script objects, see
Chapter 9, “Script Objects.” ◆
76Ty pes of Commands
CHAPTER 4
Commands
Using Command Definitions4
Command definitions contain information about what commands do and how
to use them in scripts. Figure 4-1 shows the definition for the Move command,
an application command. The definition contains four types of information:
syntax, parameters, results, and examples. Some definitions include information
about errors as well. The sections following the figure explain the information
conveyed by each part of the definition.
Figure 4-1Command definition for the Move command
Move
A Move command is a request to move an object or objects.
SYNTAX
move referenceToObject to referenceToLocation
PARAMETERS
referenceToObject
referenceToLocation
RESULT
A reference to the object that was moved.
Class: Reference
EXAMPLE
tell document 1 of app "Scriptable Text Editor"
move word 10 to before paragraph 11
end tell
application command
A reference to the object or objects to move.
Class: Reference
A reference to the location to which to move the object
or objects.
Class: Reference
Using Command Definitions77
CHAPTER 4
Commands
Syntax4
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.
Parameters4
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
78Using Command Definitions
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.