Apple Script Language Guide v.1.3.7
Apple Script Language Guide v.1.3.7
Technical Publications
1999 Apple Computer, Inc.
AppleScript Language Guide
For AppleScript 1.3.7
5/5/99
Apple Computer, Inc.
Apple Computer, Inc.
1993-99 Apple Computer, Inc.
All rights reserved.
No part of this publication 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.,
except to make a backup copy of any
documentation provided on
CD-ROM.
The Apple logo is a trademark of
Apple Computer, Inc.
Use of the keyboard Apple logo
(Option-Shift-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-labeled
or Apple-licensed computers.
Every effort has been made to ensure
that the information in this manual is
accurate. Apple is not responsible for
typographical errors.
Apple Computer, Inc.
1 Innite Loop
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, AppleScript,
AppleTalk, AppleWorks, Finder,
LaserWriter, Mac, Macintosh, and
PowerBook are trademarks of Apple
Computer, Inc., registered in the
United States and other countries.
Adobe is a trademark of Adobe
Systems Incorporated or its
subsidiaries and may be registered in
certain jurisdictions.
FileMaker is a trademark of
FileMaker, Inc., registered in the U.S.
and other countries.
Helvetica and Palatino are registered
trademarks of Linotype-Hell AG
and/or its subsidiaries.
ITC Zapf Dingbats is a registered
trademark of International Typeface
Corporation.
Simultaneously published in the
United States and Canada.
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 modication,
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 specic legal rights,
and you may also have other rights
which vary from state to state.
3
5/5/99
Apple Computer, Inc.
Contents
Figures and Tables 13
Chapter 1
Introduction
17
Chapter 2
Overview of AppleScript
19
Conventions Used in This Guide 20
What Is AppleScript? 21
What Makes AppleScript Special? 23
Who Runs Scripts and Who Writes Them? 23
What Applications Are Scriptable? 24
What Can You Do With Scripts? 25
Automating Activities 25
Integrating Applications 27
Customizing Applications and Automating Workows 29
How AppleScript Works 29
Statements 31
Commands and Objects 32
Dictionaries 34
Values and Constants 36
Expressions 37
Operations 38
Variables 38
Script Objects 39
Scripting Additions 40
Dialects 40
Other Features and Language Elements 41
Continuation Characters 41
Comments 43
Identiers 44
Case Sensitivity 45
4
5/5/99
Apple Computer, Inc.
Abbreviations 46
Compiling Scripts With the Script Editor 47
Debugging Scripts 47
Chapter 3
Values and Constants
51
Using Value Class Denitions 52
Literal Expressions 52
Properties 53
Elements 54
Operators 54
Commands Handled 55
Reference Forms 55
Coercions Supported 55
Common Value Class Denitions 56
Boolean 58
Class 59
Constant 60
Data 61
Date 62
Integer 66
List 67
Number 71
Real 72
Record 74
Reference 77
String 80
Styled Text 84
Text 87
Unicode Text and International Text 87
Unit Type Value Classes 91
AppleScript Unit Types by Category 92
Working With Unit Type Value Classes 93
Other Value Classes 94
File Specication 95
RGB Color 96
Styled Clipboard Text 96
5
5/5/99
Apple Computer, Inc.
Coercing Values 97
Constants 100
Arithmetic Constants 101
Boolean Constants 101
Considering and Ignoring Attributes 101
Date and Time Constants 102
Miscellaneous Script Constants 103
Save Option Constants 105
String Constants 105
Text Style Constants 106
Version Constant 106
Chapter 4
Commands
109
Types of Commands 110
Application Commands 110
AppleScript Commands 112
Scripting Addition Commands 112
Target 113
Name Conicts 114
User-Dened Commands 114
Using Command Denitions 115
Syntax 116
Parameters 116
Result 117
Examples 117
Errors 118
Using Parameters 118
Coercion of Parameters 118
Parameters That Specify Locations 119
Raw Data in Parameters 120
Using Results 121
Viewing a Result in the Script Editors Result Window 121
Using the Predened Result Variable 122
Double Angle Brackets in Results and Scripts 123
When a Dictionary Is Not Available 123
When AppleScript Displays Data in Raw Format 125
6
5/5/99
Apple Computer, Inc.
Entering Script Information in Raw Format 125
Sending Raw Apple Events From a Script 127
Command Denitions 127
Close 130
Copy 132
Count 134
Delete 137
Duplicate 138
Exists 139
Get 141
Launch 143
Make 146
Move 148
Open 149
Print 150
Quit 151
Reopen 152
Run 154
Save 156
Set 157
Chapter 5
Objects and References
161
Object Class Denitions 162
Properties 164
Element Classes 165
Default Value Class Returned 165
References 165
Containers 167
Complete and Partial References 168
Reference Forms 169
Arbitrary Element 170
Every Element 171
Filter 173
ID 174
Index 177
Middle Element 179
7
5/5/99
Apple Computer, Inc.
Name 180
Property 182
Range 183
Relative 185
Using the Filter Reference Form 187
References to Files and Applications 190
References to Files 191
Specifying a File by Name or Pathname 191
Specifying a File by Reference 192
Specifying a File by Alias 193
Differences Between Files and Aliases 193
Specifying a File by File Specication 194
References to Applications 194
References to Local Applications 195
References to Remote Applications 196
Chapter 6
Expressions
199
Results of Expressions 200
Variables 200
Creating Variables 201
Using Variables 202
The A Reference To Operator 203
Data Sharing 206
Scope of Variables 207
Predened Variables 207
Script Properties 208
Dening Script Properties 208
Using Script Properties 209
Scope of Script Properties 210
AppleScript Properties 210
Reference Expressions 212
Operations 213
Operators That Handle Operands of Various Classes 220
Equal, Is Not Equal To 221
Greater Than, Less Than 224
Starts With, Ends With 226
8
5/5/99
Apple Computer, Inc.
Contains, Is Contained By 227
Concatenation 229
Operator Precedence 231
Date-Time Arithmetic 233
Working With Dates at Century Boundaries 235
Chapter 7
Control Statements
237
Characteristics of Control Statements 238
Debugging Control Statements 239
Tell Statements 240
Nested Tell Statements 241
Using
it
,
me
, and
my
in Tell Statements 242
Tell (Simple Statement) 243
Tell (Compound Statement) 244
If Statements 245
If (Simple Statement) 248
If (Compound Statement) 248
Repeat Statements 249
Repeat (forever) 250
Repeat (number) Times 251
Repeat While 252
Repeat Until 253
Repeat With (loopVariable) From (startValue) To (stopValue) 254
Repeat With (loopVariable) In (list) 256
Exit 258
Try Statements 259
Kinds of Errors 259
How Errors Are Handled 260
Writing a Try Statement 261
Try 261
Signaling Errors in Scripts 264
Error 264
Considering and Ignoring Statements 268
Considering/Ignoring 269
With Timeout Statements 272
With Timeout 273
9
5/5/99
Apple Computer, Inc.
With Transaction Statements 275
With Transaction 275
Chapter 8
Handlers
279
Script Applications 279
About Subroutines 280
The Return Statement 281
A Sample Subroutine 282
Types of Subroutines 283
Scope of Subroutine Calls in Tell Statements 284
Checking the Classes of Subroutine Parameters 285
Recursive Subroutines 286
Saving and Loading Libraries of Subroutines 287
Dening and Calling Subroutines 289
Subroutines With Labeled Parameters 290
Dening a Subroutine With Labeled Parameters 290
Calling a Subroutine With Labeled Parameters 291
Examples of Subroutines With Labeled Parameters 293
Subroutines With Positional Parameters 296
Dening a Subroutine With Positional Parameters 297
Calling a Subroutine With Positional Parameters 297
Examples of Subroutines With Positional Parameters 298
Command Handlers 300
Command Handler Syntax 300
Command Handlers for Application Objects 302
Command Handlers for Script Applications 302
Run Handlers 303
Open Handlers 305
Handlers for Stay-Open Script Applications 306
Idle Handlers 307
Quit Handlers 308
Interrupting a Script Applications Handlers 309
Calling a Script Application From a Script 310
Scope of Script Variables and Properties 311
Declaring Variables and Properties 312
10
5/5/99
Apple Computer, Inc.
Scope of Properties and Variables Declared at the Top Level of a
Script 313
Scope of Properties and Variables Declared in a Script Object 316
Scope of Variables Declared in a Handler 321
Chapter 9
Script Objects
325
About Script Objects 326
Dening Script Objects 327
Sending Commands to Script Objects 328
Initializing Script Objects 329
Inheritance and Delegation 331
Dening Inheritance 331
How Inheritance Works 332
The Continue Statement 336
Using Continue Statements to Pass Commands to Applications 339
The Parent Property and the Current Application 341
Using the Copy and Set Commands With Script Objects 342
Appendix A
The Language at a Glance
349
Common Scripting Tasks 350
Constants 354
Predened Variables 358
Commands 359
Coercions 363
References 365
Operators 367
Control Statements 373
Handlers 376
Script Objects 378
Variable and Property Assignments and Declarations 378
Placeholders 380
Error Numbers and Error Messages 384
Operating System Errors 384
Apple Event Errors 385
11
5/5/99
Apple Computer, Inc.
Application Scripting Errors 387
AppleScript Errors 388
Appendix B
Document Revision History
391
Glossary
395
Index
405
13
5/5/99
Apple Computer, Inc.
Figures and Tables
Chapter 2
Overview of AppleScript
19
Figure 2-1
Closing a window with the mouse and with a script 22
Figure 2-2
Different ways to run a script 24
Figure 2-3
A script that automates a frequently performed set of steps 27
Figure 2-4
A script that copies information from one application to
another 28
Figure 2-5
How AppleScript works 30
Figure 2-6
The Finders dictionary, with Item class displayed 35
Figure 2-7
How the Script Editor accesses the Finders dictionary 36
Chapter 3
Values and Constants
51
Figure 3-1
Formats for the String (or Text), Unicode Text, and International Text
value classes 88
Figure 3-2
How the Script Editor displays String, Unicode Text, and International
Text data 89
Figure 3-3
Coercions supported by AppleScript 99
Table 3-1
Common AppleScript value class identiers 56
Chapter 4
Commands
109
Figure 4-1
The AppleWorks document Simple 142
Table 4-1
Standard application-only commands 129
Table 4-2
AppleScript and application commands 130
Chapter 5
Objects and References
161
Table 5-1
Window class denition from the Finder dictionary 163
Table 5-2
Window class denition from the AppleWorks dictionary 164
Table 5-3
Reference forms 169
Table 5-4
Boolean expressions and tests in Filter references 189
14
5/5/99
Apple Computer, Inc.
Chapter 6
Expressions
199
Figure 6-1
Two-digit dates at century boundaries 235
Table 6-1
AppleScript operators 215
Table 6-2
Operator precedence 232
Chapter 8
Handlers
279
Figure 8-1
Scope of property and variable declarations at the top level of a
script 313
Figure 8-2
Scope of property and variable declarations at the top level of a script
object 317
Figure 8-3
Scope of variable declarations within a handler 321
Chapter 9
Script Objects
325
Figure 9-1
Relationship between a simple child script and its parent 333
Figure 9-2
Another child-parent relationship 333
Figure 9-3
A more complicated child-parent relationship 334
Appendix A
The Language at a Glance
349
Figure A-1
Coercions supported by AppleScript 364
Table A-1
Links to sample scripts and other useful information 350
Table A-2
Constants dened by AppleScript 355
Table A-3
Predened variables 358
Table A-4
Command syntax 360
Table A-5
Reference form syntax 365
Table A-6
Container notation in references 367
Table A-7
Operators 368
Table A-8
Operator precedence 372
Table A-9
Control statements 373
Table A-10
Handler denitions and calls 376
Table A-11
Script objects 378
Table A-12
Assignments and declarations 379
Table A-13
Placeholders used in syntax descriptions 380
15
5/5/99
Apple Computer, Inc.
Appendix B
Document Revision History
391
Table B-1
AppleScript Language Guide
document revision history 391
17
5/5/99
Apple Computer, Inc.
C H A P T E R 1
Introduction 1
Figure 1-0
Listing 1-0
Table 1-0
AppleScript is a scripting system that allows you to directly control Macintosh
applications, including the Mac OS itself. Instead of using a mouse, keyboard,
or other input device to manipulate menus, buttons, and other interface items,
you can create sets of written instructionsknown as scriptsto automate
repetitive tasks, customize applications, and even control complex workows.
This document is a complete guide to the AppleScript language. It is intended
for use with AppleScript version 1.3.4 or later and Mac OS 8.5.1 or later,
although some descriptions and examples may work with earlier versions.
This version of the AppleScript Language Guide has been revised to cover new
features in AppleScript, to include examples from the Mac OS and the Finder, to
improve formatting for online viewing, and to correct errors. For a detailed
listing of the changes, see Document Revision History (page 391).
This guide should be useful to anyone who wants to write new AppleScript
scripts or modify existing scripts. If you are new to AppleScript, however, you
might want to start by reading the AppleScript section of the Mac OS Help
Center, or by reviewing the introductory materials at the AppleScript website:
<http://www.apple.com/applescript/
>
You can also nd introductory books on AppleScript at many bookstores and
online sites. Macintosh software developers who want to create scriptable
applications should refer to
Inside Macintosh: Interapplication Communication
, and
to related information available at the Apple Developer website:
<http://www.apple.com/developer/>
This guide describes the AppleScript language in the following chapters:
I
Overview of AppleScript (page 19) introduces AppleScript and its
capabilities and provides an overview of the elements of the AppleScript
language.
C H A P T E R 1
Introduction
18
5/5/99
Apple Computer, Inc.
I
Values and Constants (page 51) describes AppleScripts value classes,
predened constants, and coercions for converting between value classes.
I
Commands (page 109) describes the commands available in AppleScript.
I
Objects and References (page 161) describes objects and their
characteristics and explains how to refer to objects in scripts.
I
Expressions (page 199) describes AppleScript expressions, the operators
they use, and how theyre evaluated.
I
Control Statements (page 237) describes statements that control when and
how other statements are executed.
I
Handlers (page 279) describes subroutines, command handlers, error
handlers, and the scope of variables and properties in handlers and
elsewhere in a script.
I
Script Objects (page 325) describes how to dene and use script objects.
I
The Language at a Glance (page 349) provides a quick overview of the
AppleScript language. It includes a table with links to examples of common
scripting tasks.
I
Document Revision History (page 391) provides a history of changes to
this document.
Most sample scripts in this guide demonstrate scriptable features of the Finder,
the Mac OS, or applications distributed with the Mac OS, such as the Apple
System Proler. Some examples use AppleWorks, an application suite available
from Apple Computer, Inc.
19
5/5/99
Apple Computer, Inc.
C H A P T E R 2
Overview of AppleScript 2
Figure 2-0
Listing 2-0
Table 2-0
AppleScript is a dynamic, object-oriented scripting language. Its key feature is
the ability to send commands to objects in many different applications,
including the Mac OS itself. An
object
is an item, such as a le or folder in a
Finder window, a word or paragraph in a text-editing application, or a shape in
a drawing application, that can respond to commands by performing actions.
AppleScript determines dynamicallythat is, whenever necessarywhich
objects and commands an application recognizes based on information stored
in 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
provides 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 denitions for
creating user-dened commands.
This chapter provides an overview of AppleScript in the following sections:
I
Conventions Used in This Guide (page 20) describes conventions you
should be familiar with before reading the rest of this guide.
I
What Is AppleScript? (page 21) provides a brief introduction to
AppleScript by answering some frequently asked questions.
I
How AppleScript Works (page 29) describes the basic mechanisms
AppleScript provides to create, compile, and run scripts, and to communicate
with and control scriptable applications.
C H A P T E R 2
Overview of AppleScript
20
Conventions Used in This Guide
5/5/99
Apple Computer, Inc.
I
Statements (page 31) provides an overview of the kinds of statements you
use to write scripts.
I
Commands and Objects (page 32) describes the words and phrases you
use in AppleScript statements to request actions or results. It also describes
the kinds of objects that serve as targets for commands.
I
Dictionaries (page 34) describes how AppleScript works with applications
to determine the words an application understands.
I
Values and Constants (page 36) describes the types of values and
predened constants AppleScript supports.
I
Expressions (page 37) describes AppleScript expressions, which are made
up of operations and variables.
I
Script Objects (page 39) describes an advanced feature of AppleScript that
lets you dene and use objects in scripts.
I
Scripting Additions (page 40) describes a mechanism for providing
AppleScript with additional commands.
I
Dialects (page 40) describes AppleScripts ability to work with scripts in
different representations, though only an English dialect is currently
supported.
I
Other Features and Language Elements (page 41) describes features of the
AppleScript scripting language used throughout this guide.
Conventions Used in This Guide 2
Script samples and script fragments in this guide are accurate as they appear,
but you should freely experiment with them and modify them to perform
similar tasks or work with different applications.
Glossary terms are shown in
boldface
where they are rst dened.
C H A P T E R 2
Overview of AppleScript
What Is AppleScript?
21
5/5/99
Apple Computer, Inc.
The following conventions are used in syntax descriptions:
What Is AppleScript? 2
AppleScript is a scripting language that allows you to control Macintosh
computers without using the keyboard or mouse. With AppleScript, you can
use a series of English-like instructions, known as a script, to control
applications, the Finder (or desktop), and many parts of the operating system.
For example, Figure 2-1 shows the difference between closing an application
window with the mouse and performing the same task with a script.
This guide describes how you can use AppleScript to write scripts. AppleScript
shares many features with other scripting, programming, and macro languages.
If youve used any of these languages, youll nd AppleScripts English-like
terminology easy to learn and use. AppleScript provides the Script Editor
application to help you create, compile, test, and modify scripts. You can easily
create scripts that run as stand-alone applications, as described in Compiling
Scripts With the Script Editor (page 47). You can also use the Script Editor to
language element Plain computer font indicates an element that you type
exactly as shown. If there are special symbols (for
example, + or &), you also type them exactly as shown.
placeholder Italic text indicates a placeholder that you replace with an
appropriate value. (In some programming languages,
placeholders are called nonterminals.)
[optional] Brackets indicate that the enclosed language element or
elements are optional.
(a group) Parentheses group elements together. If parentheses are
part of the syntax, they are shown in bold.
[optional]... Three ellipsis points (...) after a group dened 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 dened by
parentheses indicate that you can repeat the group of
elements within parentheses one or more times.
a|b|c Vertical bars separate elements in a group from which
you must choose a single element. The elements are often
grouped within parentheses or brackets.
C H A P T E R 2
Overview of AppleScript
22 What Is AppleScript?
5/5/99 Apple Computer, Inc.
examine the scriptable operations and objects an application supports, as
described in Dictionaries (page 34). For some applications, you can even
record operations into a script to examine how the application implements
scriptable features.
Figure 2-1 Closing a window with the mouse and with a script
C H A P T E R 2
Overview of AppleScript
What Is AppleScript? 23
5/5/99 Apple Computer, Inc.
The following sections provide a brief introduction to the AppleScript scripting
language by answering frequently asked questions:
I What Makes AppleScript Special? (page 23)
I Who Runs Scripts and Who Writes Them? (page 23)
I What Applications Are Scriptable? (page 24)
I What Can You Do With Scripts? (page 25)
What Makes AppleScript Special? 2
AppleScript has a number of features that set it apart from both macro
programs and scripting languages that control a single program:
I AppleScript uses an English-like terminology that makes it easy for
nontechnical users to write scripts. For more experienced users, it is far easier
to write powerful scripts with AppleScript and to understand and maintain
scripts written by others than it is with a standard programming language.
I You can easily save a script as a stand-alone script applicationan
application whose only function is to run the script associated with it.
I 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
le, disk, and window objects in the Mac OS Finder, or to row, column, and
cell objects in a spreadsheet.
I You can control multiple 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 dont have
to learn a new language for each application.
I 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.
Who Runs Scripts and Who Writes Them? 2
Anyone who uses a Macintosh computer can run scripts. When you run a
script, it performs the operations specied by its statements. Figure 2-2
C H A P T E R 2
Overview of AppleScript
24 What Is AppleScript?
5/5/99 Apple Computer, Inc.
illustrates two ways to run a script: by double-clicking a script applications
icon on the desktop, or by clicking the Run button in the Script Editor window.
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, a scripting specialist in a publishing
business can write scripts for everyone in the business to use. Scripts are also
sold commercially, included with applications, and distributed over the
Internet.
Figure 2-2 Different ways to run a script
What Applications Are Scriptable? 2
An application that can respond to one or more AppleScript commands is
called a scriptable application. Not all applications are scriptable, and some
applications support only a minimal number of basic commands, such as Open
C H A P T E R 2
Overview of AppleScript
What Is AppleScript? 25
5/5/99 Apple Computer, Inc.
and Quit. 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. You can also determine if
an application is scriptable by attempting to examine its dictionary with the
Script Editor application, as described in Dictionaries (page 34). Or, for a list
of scriptable applications, see the AppleScript website at
<http://www.apple.com/applescript/>
Some scriptable applications are also recordable. As you perform actions in a
recordable application, the Script Editor can record a series of corresponding
instructions in the AppleScript language. To learn how to turn recording on and
off, refer to the AppleScript section of the Mac OS Help Center.
Finally, some scriptable applications are also attachable. An attachable
application is one that can be customized by attaching scripts to specic objects
in the application, such as buttons and menu items. The scripts are then
triggered by specic user actions, such as choosing the menu item or clicking
the button. To determine if an application is attachable, refer to the
documentation for the application. For example, the Finder is an attachable
application, as described in Customizing Applications and Automating
Workows (page 29).
What Can You Do With Scripts? 2
AppleScript allows you to directly control Macintosh applications, including
the Mac OS itself. Instead of using a mouse or other input device to manipulate
menus, buttons, and other interface items, you can create sets of written
instructionsknown as scriptsto automate repetitive tasks, customize
applications, and even control complex workows.
See the following sections for information on
I Automating Activities (page 25)
I Integrating Applications (page 27)
I Customizing Applications and Automating Workows (page 29)
Automating Activities 2
Scripts make it easy to perform repetitive tasks. For example, suppose you are
revising a document such as the AppleScript Language Guide. Every time you
C H A P T E R 2
Overview of AppleScript
26 What Is AppleScript?
5/5/99 Apple Computer, Inc.
sit down to work on the Language Guide, you need to open the following
documents:
I the FrameMaker le Language Guide book le, which contains the
Language Guide text documents
I the Script Editor script latest test script, which contains sample scripts to
test
I the AppleWorks document AppleWorks test doc, which you use for testing
scripts that open and close documents and windows and work with words
and paragraphs
I the FileMaker Pro document Mac OS 8.5 Registry (distributed on the
AppleScript SDK for developers), which provides information about the
scripting terminology available for AppleScript and for scriptable parts of the
Mac OS
Instead of individually opening each of these documents, you can put an alias
to each document in a folder, then write a simple script that opens the les for
you. Figure 2-3 shows the folder containing aliases to your documents and a
script that opens them.
C H A P T E R 2
Overview of AppleScript
What Is AppleScript? 27
5/5/99 Apple Computer, Inc.
Figure 2-3 A script that automates a frequently performed set of steps
Integrating Applications 2
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 2-4 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. This script is also shown in Repeat Until (page 253).
Aliases to files used while revising the AppleScript
Language Guide
Script that opens work files and applications
C H A P T E R 2
Overview of AppleScript
28 What Is AppleScript?
5/5/99 Apple Computer, Inc.
Figure 2-4 A script that copies information from one application to another
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.
C H A P T E R 2
Overview of AppleScript
How AppleScript Works 29
5/5/99 Apple Computer, Inc.
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 and Automating Workows 2
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. For example, you can customize
the Finder by attaching folder action scripts to folders. An attached folder action
script is triggered automatically when you open or close a folder, add or
remove items from an open folder, or move or resize a folder window.
You can use folder action scripts to perform simple tasks, such as automatically
copying les to a backup folder, or more complex tasks, such as automating a
workow that uses multiple applications to perform operations on a graphics
le dropped in a folder. For more information on folder actions, see the
AppleScript section of the Mac OS Help Center.
Not all applications support adding scripts. The ones that do are responsible for
specifying the ways you associate scripts with specic actions.
How AppleScript Works 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-5 shows the relationship
between the Script Editor, the AppleScript extension, and the application.
Applications respond to Apple events by performing actions, such as inserting
text, 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 nal results to the Script Editor, where they are typically
displayed in the result window. (You can use the Show Result command to
open the result window.)
C H A P T E R 2
Overview of AppleScript
30 How AppleScript Works
5/5/99 Apple Computer, Inc.
Figure 2-5 How AppleScript works
Script Editor
Compiles and runs scripts
Displays results
AppleScript extension
Application
Responds to Apple events by performing actions
Sends Apple events to AppleScript extension
1
4
3
2
1. Interprets statements from the
Script Editor
2. Sends corresponding Apple events
to the application
3. Receives and interprets Apple event
responses from the application
4. Sends results back to the Script Editor
(some results can be displayed in the
result window)
C H A P T E R 2
Overview of AppleScript
Statements 31
5/5/99 Apple Computer, Inc.
Most scripters dont need to be concerned about Apple events or the
AppleScript extension. You just use the AppleScript language to request the
actions or results that you want. To nd out what scriptable actions an
application provides, see Dictionaries (page 34).
Statements 2
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.
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 "Finder" to close 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 rst word of the statement) as their last line.
The simple statement above is equivalent to the following compound
statement.
tell application "Finder"
close the front window
end tell
The compound Tell statement includes the lines tell application "Finder" and
end tell, and all statements between those two lines.
A compound statement can contain any number of statements. For example,
here is a Tell statement that contains two statements:
C H A P T E R 2
Overview of AppleScript
32 Commands and Objects
5/5/99 Apple Computer, Inc.
tell application "Finder"
set windowName to name of 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.
Notice that the previous example contains the statement close front window
instead of close 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.
Heres another example of a compound statement:
if the name of the front window is "Fred" then
close front window
end if
Statements contained in a compound statement can themselves be compound
statements. Heres an example:
tell application "Finder"
if the name of the front window is "Fred" then
close 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. Commands can also be targeted at system objects, which
specify objects that belong to the Mac OS, such as a desktop printer, a user or
C H A P T E R 2
Overview of AppleScript
Commands and Objects 33
5/5/99 Apple Computer, Inc.
group object from the Users & Groups control panel, or a theme object from the
Appearance control panel.
Each application or system object has specic information associated with it
and can respond to specic commands.
For example, in the Finder, window objects understand the Close command.
The following example shows how to use the Close command to request that
the Finder close the front window.
tell application "Finder"
close the front window
end tell
The Close 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 specied or if the object is
specied incompletely in the command. In this case, the statement containing
the Close 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 Close command.
In AppleScript, you use references to identify objects. A reference is a
compound name, similar to a pathname or address, that species an object. For
example, the following phrase is a reference:
front window of application "Finder"
This phrase species a window object that belongs to a specic application.
(The application itself is also an object.) AppleScript has different types of
references that allow you to specify objects in many different ways. Youll 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 Finder application object. Similarly, in the
next example, a le element is contained in a specic folder element, which is
contained in a specic disk. You can read more about references to Finder
objects in Chapter 5, Objects and References.
file 1 of folder 1 of startup disk
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
C H A P T E R 2
Overview of AppleScript
34 Dictionaries
5/5/99 Apple Computer, Inc.
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 Folder object class in the
Finder. Every folder visible in the Finder belongs to the Folder object class. The
Finders denition of the Folder object class determines which classes of
elements, such as les and folders, a folder object can contain. The denition
also determines which commands, such as the Close command, a folder object
can respond to.
Dictionaries 2
To examine a denition of an object class, a command, or some other word
supported by an application, you can open that applications dictionary from
the Script Editor. A dictionary is a set of denitions for words that are
understood by a particular application. Unlike other scripting languages,
AppleScript does not have a single xed set of denitions for use with all
applications. Instead, when you write scripts in AppleScript, you use both
denitions provided by AppleScript and denitions 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. You can view an applications
dictionary by dropping the applications icon on the Script Editors icon, or by
opening the application with the Script Editors Open Dictionary command.
Figure 2-6 shows the Finders dictionary, with the Item class displayed. For
more information on using the Script Editor, refer to the AppleScript section of
the Mac OS Help Center.
To use the words from an applications dictionary in a script, you must indicate
which application you want to manipulate. You can do this with a Tell
statement that lists the name of the application:
tell application "Finder"
clean up the front window
end tell
C H A P T E R 2
Overview of AppleScript
Dictionaries 35
5/5/99 Apple Computer, Inc.
Figure 2-6 The Finders dictionary, with Item class displayed
When it encounters a Tell statement, AppleScript reads the words in the
specied applications dictionary and uses them to interpret the statements in
the Tell block. For example, AppleScript uses the words in the Finder dictionary
to interpret the Clean Up command in the previous script sample.
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 (of resource type 'aete')
that denes the commands, objects, and other words script writers can use in
scripts to control the application. Figure 2-7 shows how AppleScript gets the
words in the Finders dictionary.
C H A P T E R 2
Overview of AppleScript
36 Values and Constants
5/5/99 Apple Computer, Inc.
Figure 2-7 How the Script Editor accesses the Finders dictionary
In addition to the terms dened in application dictionaries, AppleScript
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 guide describes the
standard terms provided by AppleScript.
The words in system and application dictionaries are known as reserved words.
When dening new words for your scriptsuch as identiers for variables
you cannot use reserved words.
Values and Constants 2
A value is a simple data structure that can be represented, stored, and
manipulated within AppleScript. AppleScript recognizes many types of values,
including character strings, real numbers, integers, lists, and dates. Values are
fundamentally different from application objects, which can be manipulated
Finder application AppleScript
extension
Script Editor application
Commands and objects
in the dictionary resource
Commands:
Objects:
...
clean up
eject
empty
...
...
disk
file
folder
...
window
...
C H A P T E R 2
Overview of AppleScript
Expressions 37
5/5/99 Apple Computer, Inc.
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.
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 xed number of specic types of values are recognized by AppleScript. You
cannot dene 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 and Constants.
A constant is a reserved word with a predened value. AppleScript provides
constants to help your scripts perform a variety of tasks, such as retrieving
information about an objects properties, performing comparisons, and
performing arithmetic operations. Chapter 3, Values and Constants, describes
AppleScripts constants.
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.
I Operations (page 38)
I Variables (page 38)
For more information about these and other types of expressions, see Chapter 6,
Expressions.
C H A P T E R 2
Overview of AppleScript
38 Expressions
5/5/99 Apple Computer, Inc.
Operations 2
The following are examples of AppleScript operations and their values. The
value of each operation is listed following the comment characters (--).
3 + 4 --value: 7
(12 > 4) and (12 = 4) --value: false
Each operation contains an operator. The plus sign (+) in the rst 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.
You can use operations within AppleScript statements, such as:
tell application "Finder"
open folder (3 + 2) of startup disk
end tell
When you run this script, AppleScript evaluates the expression (3 + 2) and
uses the result to tell the Finder which folder to open.
Variables 2
When AppleScript encounters a variable in a script, it evaluates the variable by
getting its value. To create a variable, simply assign it a value:
copy "Mark" to myName
The Copy command takes the datathe string "Mark"and puts it in the
variable myName. You can accomplish the same thing with the Set command:
set myName to "Mark"
Statements that assign values to variables are known as assignment statements.
C H A P T E R 2
Overview of AppleScript
Script Objects 39
5/5/99 Apple Computer, Inc.
You can retrieve the value in a variable with a Get command. Run the following
script and then display the result in the Script Editors result window. (You can
use the Show Result command to open the result window.)
set myName to "Mark"
get myName
The result window shows that the value in myName is "Mark", 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 "Robin".
set myName to "Mark"
set myName to "Robin"
get myName
AppleScript does not distinguish uppercase letters from lowercase variables in
variable names; the variables myName, myname, and MYNAME all represent the same
value. For related information, see Case Sensitivity (page 45).
Script Objects 2
Script objects are objects you dene and use in scripts. Like application objects,
script objects respond to commands and have specic information associated
with them. Unlike application objects, script objects are dened in scripts.
Script objects are an advanced feature of AppleScript. They allow you to use
object-oriented programming techniques to dene new objects and commands.
Information contained in script objects can be saved and used by other scripts.
For information about dening 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.
C H A P T E R 2
Overview of AppleScript
40 Scripting Additions
5/5/99 Apple Computer, Inc.
Scripting Additions 2
Scripting additions are les that provide additional commands or coercions
you can use in scripts. A scripting addition le must be located in the Scripting
Additions folder (in the System Folder) for AppleScript to recognize the
additional commands it provides.
A single scripting addition le can contain several commands. For example, the
Standard Additions scripting addition distributed with AppleScript, includes
commands for using the Clipboard, obtaining the path to a le, speaking and
summarizing text, and more.
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 part of the standard additions, triggers an alert sound no
matter which application you send the command to.
A coercion is software that converts a value from one class to another, such as
from an integer value to a real value. Many standard coercions are built in to
AppleScript.
For information about the standard additions distributed with AppleScript, see
the AppleScript section of the Mac OS Help Center, or see the AppleScript
website at
<http://www.apple.com/applescript/>
Dialects 2
AppleScript is designed so that scripts can be displayed in several different
dialects, which are representations of AppleScript that resemble human
languages or programming languages. However, the English dialect is currently
the only dialect supported. The English Dialect le is stored in the Dialects
folder, a folder in the Scripting Additions folder in the System Folder.
C H A P T E R 2
Overview of AppleScript
Other Features and Language Elements 41
5/5/99 Apple Computer, Inc.
IMPORTANT
For versions 1.3.7 and earlier of AppleScript, if you move or
delete the dialect le or a folder that includes it,
AppleScript will not work. L
There is currently no plan to support dialects other than English.
Other Features and Language Elements 2
Previous sections have introduced the key elements of the AppleScript
language, including statements, objects, commands, expressions, and script
objects. Later chapters in this guide discuss these elements in more detail and
describes how to use them in scripts. Before you continue, however, youll need
to know about a few additional elements and features of the AppleScript
scripting language that are described in the following sections:
I Continuation Characters (page 41)
I Comments (page 43)
I Identiers (page 44)
I Case Sensitivity (page 45)
I Abbreviations (page 46)
I Compiling Scripts With the Script Editor (page 47)
I Debugging Scripts (page 47)
Continuation Characters 2
A simple AppleScript statement must normally be on a single line. If a
statement is longer than will t on one line, you can extend it by including a
continuation character, , at the end of one line and continuing the statement
on the next. You can enter this character in most text-editing applications by
typing Option-L. In the Script Editor, you can also type Option-Return, which
inserts the continuation character and moves the insertion point to the next line.
The following statement
open the second file of the first folder of the startup disk
C H A P T E R 2
Overview of AppleScript
42 Other Features and Language Elements
5/5/99 Apple Computer, Inc.
can appear on two lines:
open the second file of the first folder
of the startup disk
IMPORTANT
This document frequently uses the continuation character
for sample statements that dont t on one line on a
document page. It also uses the continuation character in
some syntax statements to identify an item that, if included,
must appear on the same line as the previous item. The
continuation character itself is not a required part of the
syntaxit is merely a mechanism for including multiple
lines in one statement. L
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:
open the second file of the first folder of disk "Hard
Disk"
The two dashes (--) in the previous example indicate that the rst line is a
comment. A comment is text that is ignored by AppleScript when a script is
run. You add comments to help explain your scripts. For more information, see
Comments (page 43).
To use a very long string, you can either continue typing without pressing
Return, or you can break the string into two or more strings and use the
concatenation operator (&) to join them, as in the following example:
open the second file of the first folder of disk "Hard"
& "Disk"
For more information about the concatenation operator, see Chapter 6,
Expressions.
Note that to compile any of the statements in this section, you must enclose
them in a Tell block, such as the following:
C H A P T E R 2
Overview of AppleScript
Other Features and Language Elements 43
5/5/99 Apple Computer, Inc.
tell application "Finder"
open the second file of the first folder of the startup disk
end tell
Comments 2
You add comments to a script to explain what the script does.
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:
I 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.
I 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 AppleWorks word processing 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.
C H A P T E R 2
Overview of AppleScript
44 Other Features and Language Elements
5/5/99 Apple Computer, Inc.
--the following block comment is illegal
tell application "Finder"
get (* name of *) file 1 of startup disk
end tell
Because comments are not executed, you can prevent parts of scripts from being
executed by putting them between comment characters. You can use this trick,
known as commenting out, to isolate problems when debugging scripts or
temporarily block execution of any parts of a script that arent yet nished.
Heres an example of commenting out an unnished handler:
(*
on finish()
--under construction
end
*)
If you later remove (* and *), the handler is once again available. Handlers
are described in Handlers (page 279).
Identiers 2
An identier is a series of characters that identies a value or other language
element. For example, variable names are identiers. The following statement
sets the value of the variable myName to "Fred".
set myName to "Fred"
Identiers are also used as labels for properties and handlers. Youll learn about
these uses later in this guide.
An identier must begin with a letter and can contain uppercase letters,
lowercase letters, numerals (09), and the underscore character (_). Here are
some examples of valid identiers:
Yes
Agent99
Just_Do_It
The following are not valid identiers:
C H A P T E R 2
Overview of AppleScript
Other Features and Language Elements 45
5/5/99 Apple Computer, Inc.
C--
Back&Forth
999
Why^Not
Identiers whose rst and last characters are vertical bars (|) can contain any
characters. For example, the following are legal identiers:
|Back and Forth|
|Right*Now!|
Identiers whose rst and last characters are vertical bars can contain
additional vertical bars if the vertical bars are preceded by backslash (\)
characters, as in the identier |This\|Or\|That|. A backslash character in an
identier must be preceded by a backslash character, as in the identier |/
\\ Up \\/ Down|.
AppleScript identiers are not case sensitive. For example, the variable
identiers myvariable and MyVariable are equivalent.
Identiers cannot be the same as any reserved wordsthat is, words in the
AppleScript language or words in the dictionary of an application named in a
Tell statement. For example, you cannot create a variable whose identier is
file within a Tell statement to the Finder, because file is an object class in the
Finder dictionary. In this case, AppleScript returns a syntax error if you use file
as a variable identier.
Case Sensitivity 2
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 (page 268).
Most of the examples in this chapter and throughout this guide are in
lower-case letters. Sometimes words are capitalized to improve readability. For
example, in the following variable assignment, the N in myName is capitalized
C H A P T E R 2
Overview of AppleScript
46 Other Features and Language Elements
5/5/99 Apple Computer, Inc.
to make it easier to see that two words have been combined to form the name of
the variable.
set myName to "Robin"
After you create the variable myName, you can refer to it by any of these names:
MYNAME
myname
MyName
mYName
However, when you rst compile a script that capitalizes a variable name in
different ways, AppleScript will convert the capitalization of all occurrences of
the variable to match the capitalization of the rst occurrence.
Although this guide uses variable names that start with a lower case letter and
have initial upper case letters for subsequent words in the name (myFileName),
some scripters prefer the form my_file_name.
When interpreting strings, such as "Robin", AppleScript preserves the case of
the letters in the string, but does not use it in comparisons unless directed to do
so by a Considering statement. For example, the value of the variable myName
dened earlier is "Robin", but the value of the expression myName = "ROBIN" is
true.
Abbreviations 2
The AppleScript language is designed to be intuitive and easy to understand. To
this end, it 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 "AppleWorks"
print the front window
end tell
C H A P T E R 2
Overview of AppleScript
Other Features and Language Elements 47
5/5/99 Apple Computer, Inc.
tell app "AppleWorks"
print the front window
end tell
Compiling Scripts With the Script Editor 2
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 rst. To compile a script, AppleScript converts the script
from the form typed into a Script Editor window (or any script-editing
window) to an internal form that AppleScript can execute. The Script Editor
also attempts to compile the script when you click the Check Syntax button.
If the script compiles successfully, the Script Editor dims the Check Syntax
button and reformats the text of the script according to the preferences set with
the Formatting command (in the Edit menu). This may cause indentation and
spacing to change, and in some cases may even change the text, but it doesnt
affect the meaning of the script. If AppleScript cant 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 le only.
For additional information on compiling, see Double Angle Brackets in Results
and Scripts (page 123).
Debugging Scripts 2
This section describes several simple techniques you can use to help test and
debug scripts. If you write large or complicated scripts, however, you should
investigate a commercial script-debugging application from an independent
software developer. For information on script debuggers, see the AppleScript
website at
<http://www.apple.com/applescript/>
For debugging less complex scripts, try the following techniques:
I Examine the result window to see if the script is producing the desired result.
For more information, see Using Results (page 121).
I Comment out certain lines in the script until the rest of the script is working
correctly. For more information, see Comments (page 43).
C H A P T E R 2
Overview of AppleScript
48 Other Features and Language Elements
5/5/99 Apple Computer, Inc.
I Insert Say scripting addition commands to narrate the progress of a script.
The Say command speaks the specied text.
say "Starting to empty the trash."
tell application "Finder"
empty trash
end tell
say "Finished emptying the trash."
if fileName is not equal to "Expected FileName" then
say "Unexpected file name."
end if
I Insert a Display Dialog command (another scripting addition command) to
display information at a certain point in a script. For an example, see
Version Constant (page 106).
I Open the Script Editors Event Log window to display diagnostic
information while a script is running. The following paragraphs describe
how to use the Event Log.
The Event Log helps you discover and correct errors by showing the results of a
scripts actions. You open the Script Editors Event Log window from the
Controls menu or by typing Command-E. The window contains two
checkboxes. If you check Show Events, all Apple events are logged to the
window. If you also check Show Event Results, the value returned from an
Apple event is also displayed. (Results will not be returned unless both
checkboxes are checked.)
In addition to simply opening the Event Log to view the results of actions taken
by your script, you can insert log statements at strategic locations in your script.
A log statement reports the value of one or more variables to the Event Log
window.
Suppose you run the following script:
tell application "Finder"
set myFolder to first folder of startup disk
log (myFolder) --result: (*Claris Emailer Folder*)
end tell
C H A P T E R 2
Overview of AppleScript
Other Features and Language Elements 49
5/5/99 Apple Computer, Inc.
With no checkboxes checked, the Event Log window contains just the result of
the log (myFolder) statement:
(*Claris Emailer Folder*)
With just the Show Events checkbox checked, the Event Log window contains
tell application "Finder"
get folder 1 of startup disk
(*Claris Emailer Folder*)
end tell
Finally, with both checkboxes checked, the Event Log window contains
tell application "Finder"
get folder 1 of startup disk
--> folder "Claris Emailer Folder" of startup disk
(*Claris Emailer Folder*)
end tell
In this case, the log statement isnt really needed because it returns the same
information displayed by checking the Show Event Results checkbox.
You can use start log and stop log statements to exert ner control over event
logging. When the Show Events checkbox is checked, the log level count is set
to 1. Whenever the log level is greater than 0, the Event Log window shows
events. A start log statement increments the log level. A stop log statement
decrements it. If the Show Events checkbox is checked, the following script
turns off logging before getting the name of the rst folder and turns it on again
afterwards:
tell application "Finder"
stop log
set nameOne to name of first folder of startup disk
start log
set nameTwo to name of second folder of startup disk
end tell
Log statements can be especially useful when testing a Repeat loop or other
control statement. In the following script, the statement log currentWord causes
the current word to be displayed in the Script Editors Event Log window each
C H A P T E R 2
Overview of AppleScript
50 Other Features and Language Elements
5/5/99 Apple Computer, Inc.
time through the loop. Once the loop is working correctly, you can comment out
or delete the log statement.
set wordList to words in "Where is the hammer?"
--result: {"Where", "is", "the", "hammer"}
repeat with currentWord in wordList
log currentWord
if currentWord as text is equal to "hammer" then
display dialog "I found the hammer!"
end if
end repeat
This script examines a list of words with the Repeat With (loopVariable) In (list)
form of the Repeat statement, displaying a dialog if it nds the word hammer
in the list. For more information, see Repeat With (loopVariable) In (list)
(page 256).
For more information on the Script Editors Event Log window, see the
AppleScript section of the Mac OS Help Center.
51
5/5/99 Apple Computer, Inc.
C H A P T E R 3
Values and Constants 3
Figure 3-0
Listing 3-0
Table 3-0
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. Objects are described in Objects and
References (page 161).
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 nd out
how to represent a particular value, or which operators it responds to, check its
value class denition. 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 denitions, discusses the
common characteristics of all value classes, and presents denitions of many
value classes supported in AppleScript. It also describes how to coerce values
and describes various types of constant values you can use in scripts.
Value classes and coercions are described in the following sections:
I Common Value Class Denitions (page 56) provides detailed denitions
for a set of commonly used AppleScript value classes. Each class is described
in a separate section. The sections follow the format described in Using
Value Class Denitions (page 52).
I Unicode Text and International Text (page 87) describes two string value
classes that you use mainly to transfer data between applications.
I Unit Type Value Classes (page 91) provides an overview of the value
classes you use to work with measurements of length, area, cubic and liquid
volume, mass, and temperature.
I Coercing Values (page 97) describes how AppleScript coerces values. It
provides a table that shows the available coercions for common value classes.
C H A P T E R 3
Values and Constants
52 Using Value Class Denitions
5/5/99 Apple Computer, Inc.
A constant is a reserved word with a predened value. You can use constants to
supply values in scripts. Constants are described in the following sections:
I Constant (page 60) describes the value class Constant.
I Constants (page 100) describes the different kinds of constants used with
AppleScript.
Using Value Class Denitions 3
Value class denitions 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. Each of the value class
denitions in this chapter provides information in one or more of the following
categories:
I Literal Expressions (page 52)
I Properties (page 53)
I Elements (page 54)
I Operators (page 54)
I Commands Handled (page 55)
I Reference Forms (page 55)
I Coercions Supported (page 55)
In addition, some value class denitions end with notes that provide additional
information. For an example of a denition that includes each of these
categories, see List (page 67).
Literal Expressions 3
A literal expression is an expression that evaluates to itself. The Literal
Expressions section of a value class denition provides examples of how
values of a particular class are represented in AppleScriptthat 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
C H A P T E R 3
Values and Constants
Using Value Class Denitions 53
5/5/99 Apple Computer, Inc.
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 following example, from the denition for the List value class, shows a
literal expression for a list value, which is a composite-value type.
{ "it's", 2, true }
As with the quotation marks in a string literal expression, the braces that
enclose the 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.
The list class is described fully in List (page 67).
Properties 3
A property of a value class is a characteristic that is identied by a unique label
and has a single value. The Properties section of a value class denition
describes the property or properties of the class. Simple values have only one
property, called Class, which identies the class of the value. Composite values
have both a Class property and at least one additional property, such as Length
or Contents.
For example, the value class Boolean, described in Boolean (page 58), is a
simple class with just one property, the read-only Class property.
class of boolean --result: class
However, the class Date, described in Date (page 62), is a composite value
class that has additional properties. The following example uses the standard
scripting addition command Current Date to get the current date, then gets
various properties of the date.
set theDate to current date
--result: date "Wednesday, March 3, 1999 3:01:44 PM"
weekday of theDate --result: Wednesday
day of theDate --result: 3 (the day of the month)
The following example species the Length property of a simple list.
C H A P T E R 3
Values and Constants
54 Using Value Class Denitions
5/5/99 Apple Computer, Inc.
length of {"This", "list", "has", 5, "items"} --result: 5
You can optionally use the Get command to get the value of a specied
property. For example:
get class of boolean --result: class
In most cases, you can also use the Set command to set the additional properties
listed in the denitions of composite values. If a property cannot be set with the
Set command, its denition species that it is read-only.
Elements 3
Elements of values are values contained within other values. Composite values
have elements; simple values do not. For example, the List value class
denition, shown in List (page 67), contains one element, called an item.
You use references to refer to elements of composite values. For example, the
following reference species 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 denition lists the
reference forms you can use to specify elements of composite values.
Operators 3
You use operators, such as the addition operator (+), the concatenation operator
(&), and the equality operator (=), to manipulate values. Values that belong to
the same class can be manipulated by the same operators. The Operators
section of a value class denition 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 (page 213).
C H A P T E R 3
Values and Constants
Using Value Class Denitions 55
5/5/99 Apple Computer, Inc.
Commands Handled 3
Commands are the words or phrases you use in AppleScript statements to
request actions or results. 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 denition includes a Commands Handled section
that lists commands to which values of that class can respond.
Reference Forms 3
A reference is a compound name, similar to a pathname or address, that
species 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 denitions
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
Objects and References (page 161)
Coercions Supported 3
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 denition
describes the classes to which values of that class can be coerced. For example,
the coercions section for the value class List, described in List (page 67), notes
that any value can be added to a list or coerced to a single-value list.
For more information about coercions, see Coercing Values (page 97). For a
summary of the coercions supported for commonly used value classes, see
Figure 3-3 (page 99).
C H A P T E R 3
Values and Constants
56 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
Common Value Class Denitions 3
Table 3-1 summarizes common AppleScript value classes and provides links to
sections that describe them in detail.
Table 3-1 Common AppleScript value class identiers
Value class identier Description of corresponding value
Boolean (page 58) A logical truth value
Class (page 59) A class identier
Constant (page 60) A reserved word dened by an application or
AppleScript
Data (page 61) Raw data that cannot be represented in
AppleScript, but can be stored in a variable
Date (page 62) A string that species a day of the week, day of
the month, month, year, and time
File Specication
(page 95)
A collection of data that species the name and
location on disk of a le that may not yet exist
Integer (page 66) A positive or negative number without a fractional
part
International Text Character data in the form of international text;
see Unicode Text and International Text
(page 87)
List (page 67) An ordered collection of values
Number (page 71) Synonym for either class Integer or class Real
Real (page 72) A positive or negative number that can have a
fractional part
Record (page 74) A collection of properties
Reference (page 77) A reference to an object
C H A P T E R 3
Values and Constants
Common Value Class Denitions 57
5/5/99 Apple Computer, Inc.
Three identiers 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.
For example, you can use the class identier Text to coerce a date to a string.
set x to date "May 14, 1993" as text
class of x
--result: string
Although denitions for value class synonyms are provided, they do not
correspond to separate value classes. For more information about coercing
values using synonyms, see Coercing Values (page 97).
RGB Color (page 96) A collection of three integer values that specify the
red, green, and blue components of a color
String (page 80) An ordered series of 1-byte characters
Styled Clipboard
Text (page 96)
Special text data, retrieved from the Clipboard,
that includes style and font information
Styled Text (page 84) Synonym for a special string that includes style
and font information
Text (page 87) Synonym for class String
Unicode Text Character data in the form of Unicode (2-byte)
text; see Unicode Text and International Text
(page 87)
Unit Type Value
Classes (page 91)
Classes for working with measurements of length,
area, cubic and liquid volume, mass, and
temperature
Table 3-1 Common AppleScript value class identiers (continued)
Value class identier Description of corresponding value
C H A P T E R 3
Values and Constants
58 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
Boolean 3
A value of class Boolean is a logical truth value. The most common Boolean
values are the results of comparisons, such as 4 > 3 and WordCount = 5. The
two possible Boolean values are true and false.
LITERAL EXPRESSIONS
true
false
PROPERTY
Class The class identier 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.
For additional information on these operators, see Operations (page 213).
C H A P T E R 3
Values and Constants
Common Value Class Denitions 59
5/5/99 Apple Computer, Inc.
COERCIONS SUPPORTED
AppleScript supports coercion of a Boolean value to a single-item list.
Class 3
A value of class Class is a class identier. A class identier is a reserved word
that species the class to which an object or value belongs. The Class property
of an object contains a class identier value.
LITERAL EXPRESSIONS
string
integer
real
boolean
class
PROPERTY
Class The class identier for the object. This property is read-only, and
its value is always class.
ELEMENTS
None
OPERATORS
The operators that take class identier values as operands are &, =, , and As.
The operator As takes a value of one class and coerces it to a value of a class
specied by a class identier. For example, the following statement coerces a
string into the corresponding real number, 1.5:
"1.5" as real --result: 1.5
For more information about coercing values, see Expressions (page 199).
C H A P T E R 3
Values and Constants
60 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
COERCIONS SUPPORTED
AppleScript supports coercion of a class identier to a single-item list.
Constant 3
A value of class Constant is a reserved word dened by AppleScript or an
application in its dictionary. Applications dene 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, where saving no means do not save any changes, saving yes means save
without asking, and saving ask means ask the user whether to save.
For more information on the use of constants in AppleScript, see Constants
(page 100).
LITERAL EXPRESSIONS
yes
no
ask
plain
bold
italic
For a complete listing of the constants AppleScript provides, see Table A-3
(page 358) and Table A-2 (page 355).
PROPERTY
Class The class identier for the object. This property is read-only, and
its value is always constant.
ELEMENTS
None
C H A P T E R 3
Values and Constants
Common Value Class Denitions 61
5/5/99 Apple Computer, Inc.
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.
Starting in version 1.3.7, AppleScript supports coercion of a constant to a string.
NOTES
Constants are not strings, and they must not be surrounded by quotation
marks.
You cannot dene your own constants; constants can be dened only by
applications and AppleScript.
Data 3
A value of class Data is data returned by an application (in response to a
command) that does not belong to any of the other value classes dened in this
chapter. A value of class Data is raw data that can only be stored in a variable.
For more information on raw data, see Raw Data in Parameters (page 120).
PROPERTY
Class The class identier 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 .
C H A P T E R 3
Values and Constants
62 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
COERCIONS SUPPORTED
AppleScript supports coercion of a Data value to a single-item list.
Date 3
A complete Date value species 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 lls 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.
When you compile a script, AppleScript displays date and time values
according to the format specied in the Date & Time control panel.
For more information on arithmetic operations you can perform on dates and
times, see Date-Time Arithmetic (page 233). For a description of how
AppleScript handles centurys end dates such as the year 2000, see Working
With Dates at Century Boundaries (page 235).
LITERAL EXPRESSIONS
The following expressions show several options for specifying a date.
date "7/25/53, 12:06 PM"
date "8/9/50, 12:06"
date "8/9/50, 17:06"
date "7/16/70"
date "12:06"
date "Sunday, December 12, 1954 12:06 pm"
C H A P T E R 3
Values and Constants
Common Value Class Denitions 63
5/5/99 Apple Computer, Inc.
PROPERTIES
Class The class identier for the object. This property is read-only, and
its value is always date.
Day An integer that species the day of the month of a date value.
Weekday One of the constants Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, Sunday or Mon, Tue, Wed, Thu, Fri, Sat, Sun.
Month One of the constants January, February, March, April, May, June,
July, August, September, October, November, December or Jan, Feb,
Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec.
Year An integer specifying the year; for example, 1993.
Time An integer that species the number of seconds since midnight
of the date value; for example, 2700 is equivalent to 12:45 AM
(2700 = 45 minutes times 60 seconds).
Date String A string that consists of the date portion of the date value; for
example, "Saturday, February 27, 1999".
Time String A string that consists of the time portion of the date value; for
example, "3:20:24 PM".
ELEMENTS
None
OPERATORS
The operators that take Date values as operands are &, +, , =, , >, , <, ,
Comes Before, Comes After, and As. In expressions containing >, , <, , Comes
Before, or Comes After, a later time is greater than an earlier time. The following
operations on Date values with the + and operators are supported:
date + timeDifference
--result: date
date - date
--result: timeDifference
date - timeDifference
--result: date
C H A P T E R 3
Values and Constants
64 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
where date is a Date value and timeDifference is an Integer value specifying a time
difference in seconds. To simplify the notation of time differences, you can also
use one or more of these of these constants:
minutes 60
hours 60 * minutes
days 24 * hours
weeks 7 * days
Heres an example:
date "September 13, 1998" + 4 * days + 3 * hours + 2 * minutes
--result: date "Thursday, September 17, 1998 3:02:00 AM"
For more information about the way AppleScript operators treat Date values,
see Date-Time Arithmetic (page 233).
REFERENCE FORMS
You can refer to properties of a Date value using the Property reference form.
When you compile a script, AppleScript displays date and time values
according to the format specied in the Date & Time control panel. The
following statements access various date properties:
set theDate to current date --using scripting addition command
--result: date "Saturday, February 27, 1999 3:37:50 PM"
weekday of theDate --result: Saturday
day of theDate --result: 27
month of theDate --result: February
year of theDate --result: 1999
time of theDate --result: 56270 (seconds since 12:00:00 AM)
time string of theDate --result: "3:37:50 PM"
date string of theDate --result: "Saturday, February 27, 1999"
For more information on compiling dates, see the Notes section below.
If you want to specify a time relative to a date, you can do so by using of,
relative to, or in, as shown in the following examples.
date "2:30 am" of date "March 3, 1999"
--result: date "Wednesday, March 3, 1999 2:30:00 AM"
C H A P T E R 3
Values and Constants
Common Value Class Denitions 65
5/5/99 Apple Computer, Inc.
date "Nov. 19, 1999" relative to date "3PM"
--result: date "Friday, November 19, 1999 3:00:00 PM"
date "1:30 pm" in date "March 3, 1999"
--result: date "Wednesday, March 3, 1999 1:30:00 PM"
If you set the Day property of a date to a value that does not t into the month,
the date rolls over to the next month:
set myDate to date "Thursday, February 4, 1999 12:00:00 AM"
set day of myDate to 37
myDate --result: date "Tuesday, March 9, 1999 12:00:00 AM"
COERCIONS SUPPORTED
AppleScript supports coercion of a Date value to a single-item list or a string.
NOTES
When you compile a script, AppleScript displays Date values in a format
similar to the one shown in the following example, regardless of the format you
use when you type the date. The compiled version includes the full name of the
day of the week and month and no leading zeros for the date. The actual format
is based on the settings in the Date & Time control panel. The following notes
and examples assume the Date & Time control panel is set for 12-hour time, not
24-hour time.
date "Friday, January 3, 1992 12:05:00 PM"
If you dont specify a complete date, day, and time when typing a Date value,
AppleScript lls in information as needed. If you dont specify the date
information, AppleScript uses the date when the script is compiled. If you dont
specify the time information, 12:00 AM (midnight) is the default. If you omit
AM or PM, AM is the default; however, if you specify 12:00 without AM or PM,
12:00 PM is the default. If you specify a time using 24-hour time, AppleScript
converts it to the equivalent time using AM or PM (when the Date & Time
control panel is set for 12-hour time); for example, 17:00 is equivalent to 5:00
PM.
The following example shows how AppleScript lls in a default time property
when the specied date doesnt include the time:
C H A P T E R 3
Values and Constants
66 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
time string of date "March 3, 1999"
--result: "12:00:00 AM"
To get the current date, use the scripting addition command Current Date:
set theDate to current date
if (weekday of theDate) = Saturday then
display dialog "I shouldnt be working today!"
end if
For more information about the Current Date and Display Dialog commands,
and about the other standard scripting addition commands distributed with
AppleScript, see the following website:
<http://www.apple.com/applescript/>
Integer 3
A value of class Integer is a positive or negative number without a fractional
part.
LITERAL EXPRESSIONS
1
2
-1
1000
PROPERTY
Class The class identier for the object. This property is read-only, and
its value is always integer.
ELEMENTS
None
C H A P T E R 3
Values and Constants
Common Value Class Denitions 67
5/5/99 Apple Computer, Inc.
OPERATORS
The Div operator always returns an Integer value as its result. The +, , *, Mod,
and ^ operators return values of type Integer or Real.
The operators that can have Integer values 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 (2
29
3). Larger integers (positive or negative)
are converted to real numbers (expressed in exponential notation) when scripts
are compiled.
List 3
A value of class List is an ordered collection of values. The values contained in
a list are known as items. Each item can belong to any class.
LITERAL EXPRESSIONS
A list appears in a script as a series of expressions contained within braces and
separated by commas. For example, the following statement denes a list that
contains a string, an integer, and a Boolean:
{ "it's", 2, true }
C H A P T E R 3
Values and Constants
68 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
Each list item can be any valid expression. The following list 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:
{ "it" & "'s", 1 + 1, 4 > 3 }
An empty list is a list containing no items. It is represented by a pair of empty
braces:
{}
PROPERTIES
Class The class identier for the value. This property is read-only, and
its value is always list.
Length An integer containing the number of items in the list. This
property is read-only.
Rest A list containing all items in the list except the rst item.
Reverse A list containing all items in the list, but in the opposite order.
ELEMENT
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 the integer 2. To
specify items of a list, use the reference forms listed in
Reference Forms later in this denition.
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 (page 220).
C H A P T E R 3
Values and Constants
Common Value Class Denitions 69
5/5/99 Apple Computer, Inc.
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 specic 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:
I Property. For example, class of {"this", "is", "a", "list"} species list.
I Index. For example, item 3 of {"this", "is", "a", "list"} species "a".
I Middle. For example, middle item of {"this", "is", "a", "list"} species
"is".
I Arbitrary. For example, some item of {"soup", 2, "nuts"} might specify any
of the items in the list.
I Every Element. For example, every item of {"soup", 2, "nuts"} species
{"soup", 2, "nuts"}.
I Range. For example, items 2 thru 3 of {"soup", 2, "nuts"} species {2,
"nuts"}.
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.
C H A P T E R 3
Values and Constants
70 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
the items in {"this", "is", "a", "list"} whose first
character is "t"
--result: not a valid reference
For more information on the Filter reference form, see Filter (page 173).
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,
separated by the current value of the AppleScript property Text Item Delimiters.
This property defaults to an empty string, so the items are simply concatenated.
For more information on Text Item Delimiters, see AppleScript Properties
(page 210).
{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
You can use the concatenation operator (&) to merge or add values to lists,. For
example:
{"This"} & {"is", "a", "list"} --result: {"This", "is", "a", "list"}
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.
For large lists, it may be more efcient to use the Copy or Set command to insert
an item directly into a list. The following script creates a list of 10,000 integers in
C H A P T E R 3
Values and Constants
Common Value Class Denitions 71
5/5/99 Apple Computer, Inc.
about a second (the required time will vary depending on the speed of the
computer used and may vary depending on the version of AppleScript):
set bigList to {}
set bigListRef to a reference to bigList
set numItems to 10000
set t to (time of (current date)) --Start timing operations.
repeat with n from 1 to numItems
copy n to the end of bigListRef
end
set total to (time of (current date)) - t --End timing.
total --result: 1 second
For more information on working efciently with large lists, see the example
section in The A Reference To Operator (page 203).
Number 3
The class identier 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.
C H A P T E R 3
Values and Constants
72 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
PROPERTY
Class The class identier for the object. This property is read-only, and
its value is always either integer or real.
ELEMENTS
None
OPERATORS
Because values identied as values of class Number are really values of either
class Integer or class Real, the operators available are the operators described in
the denitions of the Integer (page 66) or Real (page 72) value classes.
COERCIONS SUPPORTED
You can use the class identier Number to coerce any value that can be coerced
to a Real value or an Integer value. However, the resulting value class is always
either Integer or Real:
set x to 1.5 as number
class of x --result: real
Real 3
Values that belong to the class Real are positive or negative numbers that can
include a decimal fraction, such as 3.14159 and 1.0.
LITERAL EXPRESSIONS
10.2579432
1.0
1.
As shown in the third example, a decimal point indicates a real number, even if
there is no fractional part.
C H A P T E R 3
Values and Constants
Common Value Class Denitions 73
5/5/99 Apple Computer, Inc.
Real numbers can also be written using exponential notation. A letter e is
preceded by a real number (without intervening spaces) and followed by an
integer exponent (also without intervening spaces). The exponent can be either
positive or negative. To obtain the value, the real number is multiplied by 10 to
the power indicated by the exponent, as in these examples:
1.0e5 --equivalent to 1.0 * 10^5, or 100000
1.0e+5 --same as 1.0e5
1.0e-5 --equivalent to 1.0 * 10^-5, or .00001
PROPERTY
Class The class identier for the object. This property is read-only, and
its value is always real.
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
C H A P T E R 3
Values and Constants
74 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
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.797693e+308.
Record 3
A value of class Record is an unordered collection of properties. Like the
properties of application objects, each property has a label, and the properties of
a record are distinguished from each other by their label. There can be only one
property with a particular label in any record.
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:"Steve", height:74.5, weight:175 }
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 following record is equivalent to the previous
one.
{ name:"Steve", height:76 - 1.5, weight:150 + 25 }
PROPERTIES
In addition to the properties that are specic to each record, two properties are
common to all records:
Class The class identier for the object. For most records, the value of
the Class property is record.
C H A P T E R 3
Values and Constants
Common Value Class Denitions 75
5/5/99 Apple Computer, Inc.
The Class property of a record can be modiedit is not
read-only. For example, an application that edits text could
dene a special record to specify the styles (such as bold and
underline) of text objects. The value of the Class property for
these records, as illustrated in the following example, is the class
identier Text Style Info.
tell application "AppleWorks"
-- Get text style from open document.
style of text body of document 1
end tell
Running the previous script produces the following result:
{class:text style info, on styles:{plain}, off styles:{italic, underline,
outline, shadow, condensed, expanded, strikethrough, superscript,
subscript, superior, inferior, double underline}}
Length An integer containing the number of properties in the record.
This property is read-only.
If you dene a Class property explicitly in a record, the value you dene
replaces the implicit Class property record described above.
OPERATORS
The operators that can have records as operands are &, =, , Contains, and Is
Contained By.
For detailed explanations and examples of how AppleScript operators treat
records, see Operators That Handle Operands of Various Classes (page 220).
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 {name:"Robin", mileage:4000}
--result: 2
C H A P T E R 3
Values and Constants
76 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
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:"Robin", 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 species the Mileage property of a
record.
mileage of {name:"Robin", 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:"Robin", 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.
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:"Steve", height:70.5, weight:165 } to writer
you can then get the value of the Name property with the expression
name of writer --result: "Steve"
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.
C H A P T E R 3
Values and Constants
Common Value Class Denitions 77
5/5/99 Apple Computer, Inc.
After you dene a record, you cannot add additional properties to it. You can,
however, concatenate records. For more information, see Concatenation
(page 229).
Reference 3
A value of class Reference is a reference to an object. A reference can refer to an
application object such as a window or le, or to an AppleScript object such as
an item in a list or a property in a record. 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 docNameRef in the following script
refers to a name object (name of document 1 of application "AppleWorks")
whose value is a string (such as "April Report").
tell application "AppleWorks"
set docNameRef to a reference to the name of the first document
--result: name of document 1 of application "AppleWorks"
docNameRef as string --result: "April Report"
end tell
If you change the name of the report to Revised April Report and run this
script again, the result of the reference will be the same (name of document 1 of
application "AppleWorks"), but the value will change ("Revised April Report").
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
identies the location of the building. It is distinct from the building itself. If the
building is replaced with a new building at the same location, the address
remains the same.
A value of class Reference created with the A Reference To operator is a
structure within AppleScript that refers to (or points to) a specic object.
C H A P T E R 3
Values and Constants
78 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
tell application "AppleWorks"
set docRef to a reference to the first document
--result: document 1 of application "AppleWorks"
name of docRef --result: "New Report"
end tell
In this script, the reference docRef refers to the rst document of the application
AppleWorks, which happens to be named New Report. However, the object
that docRef points to can change. If you open a second AppleWorks document
called Second Report and run this script again, it will return the name of the
newly opened document, Second Report.
You can instead create a direct reference to the document New Report:
tell application "AppleWorks"
set docRef to a reference to document "New Report"
--result: document "New Report" of application "AppleWorks"
name of docRef --result: "New Report"
end tell
If you run this script after opening a second document, it will still return the
name of the original document, New Report. You can also use the alias form
to refer to a le whose name or location may change. For more information, see
References to Files (page 191).
Values of class Reference are similar to pointers in other programming
languages, but unlike pointers, references can refer only to objects. Using a
reference can sometimes be much more efcient than using an object directly, as
shown in the example in the Notes section in List (page 67). For related
information about using values of class Reference, see The A Reference To
Operator (page 203).
LITERAL EXPRESSIONS
set itemRef to a reference to item 3 of {1, "hello", 755, 99}
--result: item 3 of {1, "hello", 755, 99}
set newTotal to itemRef + 45 --result: 800
a reference to the name of the first report
C H A P T E R 3
Values and Constants
Common Value Class Denitions 79
5/5/99 Apple Computer, Inc.
PROPERTIES
Class The class identier for the object. This property is read-only, and
its value is always reference.
Contents The value of the object to which the reference refers. The class of
the value depends on the reference. For information about how
to use the Contents property, see The A Reference To Operator
(page 203).
ELEMENTS
None
OPERATORS
The A Reference To operator returns a reference as its result. This operator is
described in The A Reference To Operator (page 203).
COERCIONS SUPPORTED
The application to which an object specied 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 specied 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.
The reference front window of application "Apple System Profiler" in the
following example functions as a reference to an object. It identies the object to
which the Close command is sent.
close front window of application "Apple System Profiler"
C H A P T E R 3
Values and Constants
80 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
On the other hand, the reference name of the first report in the following
example functions as a reference expression:
tell application "Apple System Profiler"
set reportNameString to name of the first report
end tell
When AppleScript executes this script, it gets the value of the reference
name of the first reporta stringand then stores it in the variable
reportNameString.
The following script shows an AppleWorks application command, the Make
command, which returns a reference:
tell application "AppleWorks"
-- Create a new document and get a reference to it.
set docRef to (make new document at beginning
with properties {name:"New Report"})
--result: document "New Report" of application "AppleWorks"
end tell
String 3
A value of class String is a character string (an ordered series of characters) in
AppleScript. For information on additional string value class types, see
Unicode Text and International Text (page 87).
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 two-character
sequence, \". For more information, see Special Characters in Strings later in
this section.
C H A P T E R 3
Values and Constants
Common Value Class Denitions 81
5/5/99 Apple Computer, Inc.
PROPERTIES
Class The class identier for the object. This property is read-only, and
its value is always string.
Length The number of characters in the string.
ELEMENTS
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.
Character A single character contained in the string.
Paragraph A series of characters beginning immediately after either the
rst character after the end of the preceding paragraph or the
beginning of the string and ending with either a return character
or the end 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).
Word A 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:
read-only
he's
v1.0
$99.99
12c-d
C H A P T E R 3
Values and Constants
82 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
This denition of a word applies to English text in the Roman
script system. Words in other languages are dened by the
script system for each language if the appropriate script system
is installed.
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 (page 220).
REFERENCE FORMS
You can use the following reference forms to refer to elements of strings:
I Property. For example, class of "This is a string" species string.
I Index. For example, word 3 of "This is a string" species "a".
I Middle. For example, middle word of "This is a string" species "is".
I Arbitrary. For example, some word of "This is a string" might specify any
of the words in the string.
I Every Element. For example, every word of "This is a string" species
{"This", "is", "a", "string"}.
I Range. For example, words 2 thru 3 of "This is a string" species {"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 \"
C H A P T E R 3
Values and Constants
Common Value Class Denitions 83
5/5/99 Apple Computer, Inc.
The tab and return characters can be included in strings, or they can be
represented by equivalent two-character sequences:
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"
is displayed in a dialog box as
item 1 1
item 2 2
STRING CONSTANTS
AppleScript denes three constants for string values:
COERCIONS SUPPORTED
If a string represents 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 can all
be coerced to strings to a single concatenated string. Starting with version 1.3.7,
AppleScript supports coercion of a constant, such as Monday or January, to a
string.
Tab character
\t
Return character
\r
Constant Value
space " "
tab "\t"
return "\r"
C H A P T E R 3
Values and Constants
84 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
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 3 thru 7 of "Try this at home"
--result: "y thi"
The result of a similar statement using the character element instead of the text
element is a list.
get characters 3 thru 7 of "Try this at home"
--result: {"y", " ", "t", "h", "i"}
You cannot set the value of an element of a string. For example, if you attempt
to change the value of the rst character of the string "Boris" as shown in the
following example, youll get an error.
set myName to "Boris"
set character 1 of myName to "D"
--results in an error, because you cannot set the values of
--elements of strings
However, you can modify the name by getting the last four characters and
concatenating them with "D":
set myName to "boris"
set myName to "D" & (get text 2 through 5 of myName)
--result: "Doris"
Styled Text 3
The class identier Styled Text is a synonym for a string that includes style and
font information.
C H A P T E R 3
Values and Constants
Common Value Class Denitions 85
5/5/99 Apple Computer, Inc.
LITERAL EXPRESSIONS
The only difference between a value of class String and a value of class Styled
Text is that the latter can include (but is not required to include) style and font
information. Thus any valid literal expression of class String is also valid as
class Styled Text.
PROPERTIES
Class The class identier for the object. This property is read-only, and
its value is always string.
Length The number of characters in the string.
ELEMENTS
Styled text has the same character, word, paragraph, and text elements as a
string.
OPERATORS
Because values identied as Styled Text values are really values of class String,
the operators available are the operators described in the denition 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 (page 220).
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 String (page 80).
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 String (page 80). Note that
literal string constants do not include style and font information; in other
words, they are not styled text.
C H A P T E R 3
Values and Constants
86 Common Value Class Denitions
5/5/99 Apple Computer, Inc.
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 identier Styled Text to coerce any string to styled text.
However, the resulting value is always of class String.
NOTES
AppleScript itself provides no commands for directly manipulating styled text.
To change the style or font information for a styled text value, you must work
with an application that knows how to manipulate styled text. However,
AppleScript does preserve style and font information when copying text objects
from applications to scripts and vice versa.
For example, you can use a script like this to obtain styled text, manipulate it,
and copy it back into an AppleWorks document:
tell application "AppleWorks"
-- Get text from open document.
set myText to text body of document "Report"
-- Add some information at the end.
set myText to myText & return & "The End."
-- Select all the current text in the document and replace it.
select text body of document "Report"
set selection of document "Report" to myText
close document "Report" saving ask
end tell
Because AppleWorks returns styled text when it returns the text from a
document, you dont need to coerce the returned text to styled text. The style
and font of the text are preserved both when it is copied to the variable myText
and when it is concatenated with a return character and the string "The End."
The modied text that is inserted back into the document consists of the
original text with its original style and font, a return character to move to a new
line, and the unstyled text, "The End.", which appears in the style and font of
the text 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
C H A P T E R 3
Values and Constants
Unicode Text and International Text 87
5/5/99 Apple Computer, Inc.
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. For related
information, see Unicode Text and International Text (page 87).
Text 3
You can use the class identier Text as a synonym for the identier Stringfor
example, in coercions:
"A string" as string = "A string" as text --result: true
However, the class of a string is always string:
set myThing to "A string"
class of myThing --result: string
set otherThing to myThing as text
class of otherThing --result: string
Unlike the class identier 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 identier Text is precisely equivalent to a single class
identierString.
Unicode Text and International Text 3
In addition to the string value classes described in String (page 80), Styled
Text (page 84), and Text (page 87), AppleScript provides partial support for
the following string types:
I Unicode Text: An ordered series of 2-byte Unicode characters. (Unicode is an
international standard that uses a 16-bit encoding to uniquely specify the
characters and symbols for all commonly used languages.)
I International Text: An ordered series of bytes, beginning with a 4-byte
language code and a 4-byte script code that together determine the format of
the bytes that follow. (International text can be obtained only from a
Macintosh computer that has a language kit installed.)
C H A P T E R 3
Values and Constants
88 Unicode Text and International Text
5/5/99 Apple Computer, Inc.
You can use the Unicode Text, International Text, and String classes in any script
and they do not need to be enclosed in a Tell block. These classes all represent
text data, though in different formats, as shown in Figure 3-1. You typically use
the Unicode Text and International Text classes to get information from and
send information to applications that work with these types of text.
Because the different string value classes store data in different formats, the size
in bytes of a string can vary from the number of characters it contains.
Comparisons between Unicode Text, International Text, and String values are
not likely to be useful. You cannot determine the Length property of a value
stored as Unicode Text, or access its Character, Word, or Paragraph elements (as
you can with other string types, including International Text).
Figure 3-1 Formats for the String (or Text), Unicode Text, and International Text
value classes
AppleScript provides limited options for displaying Unicode Text and
International Text:
I The Script Editor can display Unicode Text only as raw data, as shown in
Figure 3-2. For more information on raw data, see Raw Data in Parameters
(page 120).
1 byte
2 bytes
String and Text
International Text
Unicode Text
4-byte
language code
4-byte
script code
1-byte or 2-byte text data
depending on language
code and script code
C H A P T E R 3
Values and Constants
Unicode Text and International Text 89
5/5/99 Apple Computer, Inc.
I The Script Editor displays International Text according to the language and
script of the text and depending on whether a language kit is installed. For
example, the Script Editor can display International Text in the English
language and Roman script as a simple string, as shown in Figure 3-2.
However, it cannot display simplied Chinese characters unless you have
installed the appropriate language kit.
Figure 3-2 How the Script Editor displays String, Unicode Text, and International
Text data
1 byte
2 bytes
String and Text
International Text (English
language, Roman script)
Result
Unicode Text Result
Character
Value
Character
Value
Character
Value
4-byte
language code
for English
4-byte
script code
for Roman
1-byte text data
h e l l o
h e l l o
h e l l o
00
68
00 00 00 00 00 00 00 00 68 65 6C 6C 6F
65 6C 6C 6F
68 00 65 00 6C 00 6C 00 6F
Result
C H A P T E R 3
Values and Constants
90 Unicode Text and International Text
5/5/99 Apple Computer, Inc.
AppleScript provides coercions among the Unicode Text, International Text, and
String (or Text) classes. For example, if your script gets a value of type Unicode
Text from an application that supports Unicode, you can coerce the value to
String to see it in a readable format. However, because the String, Unicode Text,
and International Text classes store data differently, as shown in Figure 3-1
(page 88), and because there are differences in the text data each can represent,
information may be lost in some coercions. As shown in Figure 3-3 (page 99),
coercions from Unicode Text to International Text or String, and from
International Text to String, may result in lost information. For example, the
String class cannot represent 2-byte Chinese characters (from either
International Text or Unicode Text values) in its 1-byte character format.
For an overview of AppleScript coercion, see Coercing Values (page 97).
The following script statements demonstrate how to initialize a string as
Unicode Text and then coerce it to a standard String value:
set myString to "hello" as Unicode text
--result: data utxt00680065006C006C006F
myString as string
--result: "hello"
The following script retrieves text data from an open AppleWorks word
processing document, adds to it, and replaces the existing text with the
combined text. Because the original text is stored as Chinese characters (entered
with the Chinese Language Kit), AppleWorks returns the text as International
Text, so the script doesnt need to coerce it to International Text. After the script
completes, the document contains the original Chinese characters, followed by
The End. in the current language and script (English Roman). If the
appropriate language kit installed, AppleScript can display Chinese characters
in its result window.
tell application "AppleWorks"
-- Get text (Chinese characters) from open document.
set myText to text body of document "Chinese Text"
-- Add some information at the end in English.
set myText to myText & return & "The End."
-- Select all the current text in the document and replace it.
select text body of document "Chinese Text"
set selection of document "Chinese Text" to myText
end tell
C H A P T E R 3
Values and Constants
Unit Type Value Classes 91
5/5/99 Apple Computer, Inc.
If you use the & operator to combine two values of Unicode Text, the result is a
list, not a string:
set greetingString to "Hello" as Unicode text
--result: data utxt00480065006C006C006F
set nameString to " Bob" as Unicode text
--result: data utxt00200042006F0062
set combinedString to greetingString & nameString
--result:
-- {data utxt00480065006C006C006F, data utxt00200042006F0062}
set combinedString to (greetingString as string)
& (nameString as string)
--result: "Hello Bob"
Unit Type Value Classes 3
AppleScript provides Unit Type value classes for working with measurements
of length, area, cubic and liquid volume, mass, and temperature. Unit Type
classes are simple values that do not contain other values and have only a single
property, the Class property. You can use the Unit Type classes in any script and
they do not need to be enclosed in a Tell block.
AppleScript provides coercions from Unit Type to String and Number (Real or
Integer) and from String, Real, or Integer to Unit Type. You can also coerce
between Unit Types in the same category, such as inches to kilometers (length)
or gallons to liters (liquid volume). As you would expect, there is no coercion
between categories, such as from gallons to degrees Centigrade.
Note that AppleScript did not implement the quarts and degrees Kelvin Unit
Types or support coercions from miles to other types until version 1.3.7.
For an overview of value coercion in AppleScript, see Coercing Values
(page 97).
C H A P T E R 3
Values and Constants
92 Unit Type Value Classes
5/5/99 Apple Computer, Inc.
AppleScript Unit Types by Category 3
This section lists the Unit Type value classes AppleScript provides.
Length
centimetres
centimeters
feet
inches
kilometres
kilometers
metres
meters
miles
yards
Area
square feet
square kilometres
square kilometers
square metres
square meters
square miles
square yards
Cubic Volume
cubic centimetres
cubic centimeters
cubic feet
cubic inches
cubic metres
cubic meters
cubic yards
C H A P T E R 3
Values and Constants
Unit Type Value Classes 93
5/5/99 Apple Computer, Inc.
Working With Unit Type Value Classes 3
This section provides sample script statements for working with Unit Type
value classes.
The following statements calculate the area of a circle with a radius of 7 yards,
then coerce the area to square feet (pi is an AppleScript-dened constant).
set circleArea to (pi * 7) as square yards
--result: square yards 21.991148575129
circleArea as square feet
--result: square feet 197.920337176157
The following statements set a variable to a value of 5.0 square kilometers, then
coerce it to various other units of area:
set theArea to square kilometers 5.0
--result: square kilometers 5.0
theArea as square miles
Liquid Volume
gallons
litres
liters
quarts
Weight
grams
kilograms
ounces
pounds
Temperature
degrees Celsius
degrees Fahrenheit
degrees Kelvin
C H A P T E R 3
Values and Constants
94 Other Value Classes
5/5/99 Apple Computer, Inc.
--result: square miles 1.930510798581
theArea as square meters
--result: square meters 5.0E+6
You can also coerce a value from square meters to a real number or an integer:
set theArea to square meters 5.0
--result: square meters 5.0
theArea as real
--result: 5.0
theArea as integer
--result: 5
However, you cannot coerce an area measurement to a Unit Type in a different
category:
set theArea to square meters 5.0
--result: square meters 5.0
theArea as cubic meters
--result: error
theArea as degrees Celsius
--result: error
The following statements demonstrate coercion of a Unit Type to a String, and
from a String to a Unit Type:
set myValue to pounds 2.2 --result: pounds 2.2
myValue as string --result: "2.2"
"2.2" as kilograms --result: kilograms 2.2
Other Value Classes 3
AppleScript denes the following value classes to provide basic support for
some common data types. While AppleScript provides little built-in support for
coercing these classes or manipulating them directly, the classes are useful for
working with applications and the Clipboard.
I File Specication (page 95)
C H A P T E R 3
Values and Constants
Other Value Classes 95
5/5/99 Apple Computer, Inc.
I RGB Color (page 96)
I Styled Clipboard Text (page 96)
File Specication 3
The File Specication class species the name and location on disk of a le that
may not yet exist. You can obtain a le specication from the New File scripting
addition command distributed with AppleScript, or from an application
command that returns a le specication. The following statements use the
New File command, which displays a standard system dialog to obtain a
lename and location from the user.
set fileSpec to new file default name "New Report"
class of fileSpec --result: file specification
The default name displayed is New Report and the default directory is the
current directory. (The current directory is typically the directory where the
application was launched, the directory where the application last opened or
saved a previous document, or another directory specied by the application.
The current directory may be affected by settings in the General Controls
control panel.)
The user can specify any lename and location. This statement stores the
returned le specication, which describes the name and location specied by
the user, in the variable fileSpec. Depending on what the user species, the
result in the Script Editors result window is something like the following:
file "Hard Disk:Desktop Folder:New Report"
You can coerce a le specication to a string, which results in a string
containing the full path name to the le:
fileSpec as string --result: "Hard Disk:Desktop Folder:New Report"
Beyond coercing the pathname to a string, you cannot use AppleScript to
directly access or manipulate the information in a le specication. However,
you can obtain a le specication from, or pass a le specication to, a scripting
addition or application that knows how to work with a le specication. For a
full example that obtains a le specication and passes it to an application, see
Specifying a File by File Specication (page 194).
C H A P T E R 3
Values and Constants
96 Other Value Classes
5/5/99 Apple Computer, Inc.
RGB Color 3
The RGB Color value class represents a collection of three integer values that
specify the red, green, and blue components of a color. You can coerce a list of
three integer values into an RGB color if each of the values is from 0 to 65535. In
fact, AppleScript reports the class of an RGB Color value as List:
set myGreenRGB to {0, 65535, 0} as RGB color --result: {0, 65535, 0}
class of myGreenRGB --result: list
You can get or set individual values in an RGB color by accessing the items as
you would those in any list:
set myRGB to {500,25000,500} as RGB color --result: {500, 25000, 500}
set myGreenValue to second item of myRGB --result: 25000
set item 3 of myRGB to 12000
myRGB --result: {500, 25000, 12000}
You can use the RGB Color value class to obtain RGB colors from, or supply
RGB colors to, applications that work with RGB colors. For example, a graphic
object in an AppleWorks drawing document has Fill Color and Pen Color
properties that are RGB colors.
Styled Clipboard Text 3
The Styled Clipboard Text value class represents text data from the Clipboard
that includes style and font information. Although you cant coerce this value
class to any other class or display it in its native format, you can use it to pass
styled text between applications that work with styled text.
The following script copies all of the text, consisting of the one word Hello in
outline font, from the document "Hello with style" to the Clipboard. It then
gets the contents of the clipboard and displays the class of those contents.
tell application "AppleWorks"
set myText to text body of document "Hello with style"
activate -- Required for Clipboard commands.
-- Next two lines use scripting addition commands.
set the clipboard to myText
set myClipboardText to the clipboard as scrap styles
C H A P T E R 3
Values and Constants
Coercing Values 97
5/5/99 Apple Computer, Inc.
--result: data styl000100000000000F000A001008A0000C000000000000
class of myClipboardText --result: styled Clipboard text
end tell
As shown in the script, getting styled text from the Clipboard results in a value
of type Styled Clipboard Text, which AppleScript can only display as raw data
enclosed in chevrons (double-angle brackets). Although you cannot coerce
styled clipboard text to styled text or to a string, you can store it in a variable
and pass it to applications that work with styled text.
For more information on raw data, see Double Angle Brackets in Results and
Scripts (page 123).
Coercing Values 3
This section describes how you coerce values from one class to another. For
specic information on coercing Unit Type values, see Unit Type Value
Classes (page 91). For information on coercing Unicode Text and International
Text values, see Unicode Text and International Text (page 87). For
information on coercing additional classes, see Other Value Classes (page 94).
Coercing is the process of converting a value from one class to another.
AppleScript coerces values in one of two ways:
I in response to the As operator
I automatically, when a value is of a different class than was expected for a
particular command or operation
The ability to coerce a value from one class to another is either a built-in
function of AppleScript or a capability provided by a scripting addition
command. All of the coercions described in this section are built into
AppleScript, so you can use them in any script and they do not need to be
enclosed in a Tell block.
The As operator species 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, the following statement coerces the integer 2 into the
string "2" before storing it in the variable myString:
set myString to 2 as string
C H A P T E R 3
Values and Constants
98 Coercing Values
5/5/99 Apple Computer, Inc.
Similarly, this statement coerces the string "2" to the integer 2, so that it can be
added to the other operand, 8:
"2" as integer + 8
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 the following repeat
statement, it expects an integer for the number of times to repeat the enclosed
display dialog command (a scripting addition command).
repeat "2" times
display dialog "Hello"
end repeat
If you pass a string, as in this example, AppleScript attempts to coerce the string
to an integer. If you pass a string that AppleScript cant coerce to an integer,
such as "many", it reports an error.
Not all values can be coerced to all other classes of values. Figure 3-3
summarizes the coercions that AppleScript supports for commonly used value
classes. To use the gure, nd 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 the contents of the
reference determine whether the value specied by a reference can be coerced
to a desired class.
For more information about each coercion, see the corresponding value class
denitions 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. N
C H A P T E R 3
Values and Constants
Coercing Values 99
5/5/99 Apple Computer, Inc.
Figure 3-3 Coercions supported by AppleScript
Three of the identiers mentioned at the top of Figure 3-3 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:
B
o
o
l
e
a
n
C
l
a
s
s
C
o
n
s
t
a
n
t
I
n
t
e
g
e
r
Coerce from
Boolean
Class
Constant
Data
Date
Integer
International Text
Single-item list
Multi-item list
Real
Record
String
Unicode Text
D
a
t
a
D
a
t
e
div
mod
Left to right Multiplication and division
5 +
-
Left to right Addition and subtraction
6 & Left to right Concatenation
7 as Left to right Coercion
8 <
>
None Comparison
9 =
/
number ( | / ) number
^ number ^ number
div number div number
mod number mod number
Logical operators
and Boolean and Boolean
not not Boolean
or Boolean or Boolean
Containment operators
A P P E N D I X A
The Language at a Glance
Operators 369
5/5/99 Apple Computer, Inc.
start[s] with
begin[s] with
list starts with list
string starts with string
end[s] with list ends with list
string ends with string
contains list contains list
record contains record
string contains string
does not contain
doesn't contain
list does not contain list
record does not contain record
string does not contain string
is in
is contained by
list is in list
record is in record
string is in string
is not in
is not contained by
isn't contained by
list is not in list
record is not in record
string is not in string
Comparison operators (equality and inequality)
=
equal
equals
equal to
is
is equal to
expression = expression
Table A-7 Operators (continued)
Operator Syntax
A P P E N D I X A
The Language at a Glance
370 Operators
5/5/99 Apple Computer, Inc.
<=
does not come after
doesn't come after
is less than or equal [to]
is not greater than
isn't greater than
less than or equal [to]
date date
integer integer
real real
string string
Table A-7 Operators (continued)
Operator Syntax
A P P E N D I X A
The Language at a Glance
Operators 371
5/5/99 Apple Computer, Inc.
Table A-8 shows the order in which AppleScript performs operations. The
column labeled Associativity indicates the order in which AppleScript
performs operations if there are two or more operations of the same precedence
in an expression. The word none in the Associativity column indicates that
you cannot have multiple consecutive occurrences of the operation in an
expression. For example, the expression 3 = 3 = 3 is not legal because the
associativity for the equal operator (=) is none. The word unary indicates
that the operator is a unary operator. To evaluate expressions with multiple
unary operators of the same order, AppleScript applies the operator closest to
>=
does not come before
doesn't come before
greater than or equal [to]
is greater than or equal [to]
is not less than
isn't less than
date date
integer integer
real real
string string
Miscellaneous operators
& (concatenation) expression & expression
as expression as className
a reference to [a] ( ref [to] | reference to )
reference
Table A-7 Operators (continued)
Operator Syntax
A P P E N D I X A
The Language at a Glance
372 Operators
5/5/99 Apple Computer, Inc.
the operand rst, then applies the next closest operator, and so on. For example,
the expression not not not true is evaluated as not (not (not true)).
Table A-8 Operator precedence
Order Operators Associativity Type of operator
1
( )
Innermost to
outermost
Grouping
2
+
-
Unary Plus or minus sign for numbers
3
^
Right to left Exponentiation
4
*
/
div
mod
Left to right Multiplication and division
5
+
-
Left to right Addition and subtraction
6
&
Left to right Concatenation
7
as
Left to right Coercion
8
<
>
None Comparison
9
=