AppleScript Language Guide English Dialect
Apple Computer, Inc. © 1996 Apple Computer, Inc. All rights reserved. No part of this publication or the software described in it may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Computer, Inc. Printed in the United States of America. The Apple logo is a trademark of Apple Computer, Inc.
Contents Figures and Tables Preface About This Guide xiii xv Audience xv Organization of This Guide xvi Sample Applications and Scripts xvii For More Information xviii Getting Started xviii Scripting Additions xviii Other AppleScript Dialects xviii Scriptable Applications xviii Conventions Used in This Guide xix Part 1 Introducing AppleScript Chapter 1 AppleScript, Scripts, and Scriptable Applications 1 What Is AppleScript? 3 What Can You Do With Scripts? 5 Automating Activities 5 Integrating Appl
Chapter 2 Overview of AppleScript 13 How Does AppleScript Work? 14 Statements 14 Commands and Objects 17 Dictionaries 18 Values 20 Expressions 21 Operations 21 Variables 22 Script Objects 23 Scripting Additions 23 Dialects 24 Other Features and Language Elements 24 Continuation Characters 25 Comments 26 Identifiers 27 Case Sensitivity 28 Abbreviations 29 Compiling Scripts With the Script Editor 30 Part 2 AppleScript Language Reference Chapter 3 Values 33 Using Value Class Definitions Literal Expres
Value Class Definitions Boolean 40 Class 41 Constant 42 Data 43 Date 43 Integer 47 List 48 Number 52 Real 53 Record 54 Reference 57 String 60 Styled Text 64 Text 66 Coercing Values 67 Chapter 4 Commands 38 71 Types of Commands 71 Application Commands 72 AppleScript Commands 73 Scripting Addition Commands 74 User-Defined Commands 76 Using Command Definitions 77 Syntax 78 Parameters 78 Result 79 Examples 79 Errors 79 Using Parameters 80 Parameters That Specify Locations 80 Coercion of Parameters 81 Raw D
Command Definitions Close 87 Copy 88 Count 92 Data Size 97 Delete 98 Duplicate 99 Exists 99 Get 100 Launch 103 Make 105 Move 106 Open 107 Print 108 Quit 109 Run 110 Save 112 Set 113 Chapter 5 84 Objects and References 119 Using Object Class Definitions 119 Properties 120 Element Classes 120 Commands Handled 120 Default Value Class Returned 122 References 122 Containers 123 Complete and Partial References 124 Reference Forms 125 Arbitrary Element 126 Every Element 127 Filter 129 ID 130 Index 131 Middle
Name 134 Property 135 Range 136 Relative 139 Using the Filter Reference Form 140 References to Files and Applications 143 References to Files 144 References to Applications 146 References to Local Applications 147 References to Remote Applications 148 Chapter 6 Expressions 149 Results of Expressions 149 Variables 150 Creating Variables 150 Using Variables 152 The “A Reference To” Operator 153 Data Sharing 154 Scope of Variables 155 Predefined Variables 156 Script Properties 156 Defining Script Propertie
Chapter 7 Control Statements 183 Characteristics of Control Statements 184 Tell Statements 185 Tell (Simple Statement) 188 Tell (Compound Statement) 189 If Statements 190 If (Simple Statement) 192 If (Compound Statement) 193 Repeat Statements 194 Repeat (forever) 197 Repeat (number) Times 198 Repeat While 199 Repeat Until 200 Repeat With (loopVariable) From (startValue) To (stopValue) Repeat With (loopVariable) In (list) 202 Exit 204 Try Statements 204 Kinds of Errors 205 How Errors Are Handled 206 Writi
Recursive Subroutines 225 Saving and Loading Libraries of Subroutines 226 Subroutine Definitions and Calls 228 Subroutines With Labeled Parameters 229 Subroutine Definition, Labeled Parameters 229 Subroutine Call, Labeled Parameters 230 Examples of Subroutines With Labeled Parameters 232 Subroutines With Positional Parameters 235 Subroutine Definition, Positional Parameters 235 Subroutine Call, Positional Parameters 236 Examples of Subroutines With Positional Parameters 238 The Return Statement 239 Return 2
Defining Inheritance 271 How Inheritance Works 272 The Continue Statement 277 Using Continue Statements to Pass Commands to Applications The Parent Property and the Current Application 281 Using the Copy and Set Commands With Script Objects 283 Appendix A The Language at a Glance 289 Commands 289 References 294 Operators 296 Control Statements 299 Handlers 301 Script Objects 303 Variable and Property Assignments and Declarations Predefined Variables 304 Constants 305 Placeholders 307 Appendix B Scriptab
Text Item 339 Text Style Info 341 Window 342 Word 342 Scriptable Text Editor Commands Copy 347 Cut 348 Data Size 349 Duplicate 349 Make 350 Move 351 Open 351 Paste 351 Revert 352 Save 353 Select 354 Scriptable Text Editor Errors 355 Appendix C Error Messages 345 357 Operating System Errors 358 Apple Event Errors 359 Apple Event Registry Errors 361 AppleScript Errors 362 Glossary Index 363 371 xi
Figures and Tables Chapter 1 AppleScript, Scripts, and Scriptable Applications Figure 1-1 Figure 1-2 Figure 1-3 Figure 1-4 Chapter 2 Changing text style with the mouse and with a script 4 A script that performs a repetitive action 6 A script that copies information from one application to another Different ways to run a script 9 Overview of AppleScript Figure 2-1 Figure 2-2 Chapter 3 Chapter 4 Chapter 5 Values 3 13 How AppleScript works 15 How AppleScript gets the Scriptable Text Editor dictionar
Chapter 6 Chapter 8 Expressions 149 Table 6-1 Table 6-2 AppleScript operators Operator precedence Handlers 221 Figure 8-1 Figure 8-2 Figure 8-3 Chapter 9 Script Objects Figure 9-1 Figure 9-2 Figure 9-3 Appendix A Appendix B 265 Relationship between a simple child script and its parent Another child-parent relationship 273 A more complicated child-parent relationship 274 273 289 Command syntax 290 Reference form syntax 294 Container notation in references 296 Operators 297 Control statements
P R E F A C E About This Guide The AppleScript Language Guide: English Dialect is a complete guide to the English dialect of the AppleScript language. AppleScript allows you to create sets of written instructions—known as scripts—to automate and customize your applications. Audience 0 This guide is for anyone who wants to write new scripts or modify existing scripts.
P R E F A C E Organization of This Guide This guide is divided into two parts: ■ ■ Part 1, “Introducing AppleScript,” provides an overview of the AppleScript language and the tasks you can perform with it. Part 2, “AppleScript Language Reference,” provides reference descriptions of all of the features of the AppleScript language. Part 1 contains these chapters: ■ ■ Chapter 1, “AppleScript, Scripts, and Scriptable Applications,” introduces AppleScript and its capabilities.
P R E F A C E ■ ■ ■ Chapter 7, “Control Statements,” describes statements that control when and how other statements are executed. It includes information about Tell, If, and Repeat statements. Chapter 8, “Handlers,” describes subroutines, command handlers, error handlers, and the scope of variables and properties in handlers and elsewhere in a script. It includes the syntax for defining and calling subroutines and error handlers.
P R E F A C E For More Information 0 Getting Started 0 See the companion book Getting Started With AppleScript to learn what hardware and software you need to use AppleScript; how to install AppleScript; and how to run, record, and edit scripts. Scripting Additions 0 Scripting additions are files that provide additional commands you can use in scripts. A standard set of scripting additions comes with AppleScript.
P R E F A C E Conventions Used in This Guide 0 Words and sample scripts in monospaced font are AppleScript language elements that must be typed exactly as shown. Terms are shown in boldface where they are defined. You can also find these definitions in the glossary. Here are some additional conventions used in syntax descriptions: language element Plain computer font indicates an element that you must type exactly as shown.
P A R T O N E Introducing AppleScript 1
C H A P T E R Figure 1-0 Listing 1-0 Table 1-0 1 AppleScript, Scripts, and Scriptable Applications 1 This chapter introduces the AppleScript scripting language.
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Figure 1-1 Changing text style with the mouse and with a script Changing the style of text with the mouse Changing the style of text with a script 4 What Is AppleScript?
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications The script shown at the bottom of Figure 1-1 is written in AppleScript English, which is a dialect of the AppleScript scripting language that resembles English. This guide describes AppleScript English and how you can use it to write scripts. Other dialects, such as AppleScript Japanese and AppleScript French, are designed to resemble other human languages.
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Figure 1-2 A script that performs a repetitive action Introduction before running script Make AppleScript Bold script Introduction after running script 6 What Can You Do With Scripts?
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Integrating Applications 1 Scripts are ideal for performing tasks that involve more than one application. A script can send instructions to one application, get the resulting data, and then pass the data on to one or more additional applications. For example, a script can collect information from a database application and copy it to a spreadsheet application.
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Figure 1-3 8 A script that copies information from one application to another What Can You Do With Scripts?
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Who Runs Scripts, and Who Writes Them? 1 To run a script is to cause the actions the script describes to be performed. Everyone who uses a Macintosh computer can run scripts. Figure 1-4 illustrates two ways to run a script. Figure 1-4 Different ways to run a script Double-clicking a script application’s icon Clicking the Run button If the script is a script application on the desktop, you can run it by doubleclicking its icon.
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications Although everyone can run scripts, not everyone needs to write them. One person who is familiar with a scripting language can create sophisticated scripts that many people can use. For example, management information specialists in a business can write scripts for everyone in the business to use. Scripts are also sold commercially, included with applications, and distributed through electronic bulletin boards and user groups.
C H A P T E R 1 AppleScript, Scripts, and Scriptable Applications What Applications Are Scriptable? 1 Applications that understand one or more AppleScript commands are called scriptable applications. Not all applications are scriptable. The advertising and packaging for an application usually mention if it is scriptable. The documentation for a scriptable application typically lists the AppleScript words that the application understands. Some scriptable applications are also recordable.
C H A P T E R Figure 2-0 Listing 2-0 Table 2-0 2 Overview of AppleScript 2 AppleScript is a dynamic, object-oriented script language. At its heart is the ability to send commands to objects in many different applications. These objects, which are familiar items such as words or paragraphs in a text-editing application or shapes in a drawing application, respond to commands by performing actions.
C H A P T E R 2 Overview of AppleScript How Does AppleScript Work? 2 AppleScript works by sending messages, called Apple events, to applications. When you write a script, you write one or more groups of instructions called statements. When you run the script, the Script Editor sends these statements to the AppleScript extension, which interprets the statements and sends Apple events to the appropriate applications.
C H A P T E R 2 Overview of AppleScript Figure 2-1 How AppleScript works Script Editor Writes, records, and runs scripts 1 4 Application • Responds to Apple events by performing actions • Sends Apple events to AppleScript extension AppleScript statements (results) AppleScript extension • Interprets script statements and sends corresponding Apple events • Interprets Apple events and sends results back to the Script Editor 3 Apple events (results) 2 Apple events (requests for action) Statements
C H A P T E R 2 Overview of AppleScript All statements, including control statements, fall into one of two categories: simple statements or compound statements. Simple statements are statements such as the following that are written on a single line. tell application "Scriptable Text Editor" to print the front window Compound statements are statements that are written on more than one line and contain other statements.
C H A P T E R 2 Overview of AppleScript Here’s another example of a compound statement: if the number of windows is greater than 0 then print front window end if Statements contained in a compound statement can themselves be compound statements.
C H A P T E R 2 Overview of AppleScript specified incompletely in the command. In this case, the statement containing the Print statement does not contain enough information to uniquely identify the window object, so AppleScript uses the application name listed in the Tell statement to determine which object receives the Print command. In AppleScript, you use references to identify objects. A reference is a compound name, similar to a pathname or address, that specifies an object.
C H A P T E R 2 Overview of AppleScript AppleScript does not have a single fixed set of definitions for use with all applications. Instead, when you write scripts in AppleScript, you use both definitions provided by AppleScript and definitions provided by individual applications to suit their capabilities. Dictionaries tell you which objects are available in a particular application and which commands you can use to control them.
C H A P T E R 2 Overview of AppleScript the application. Figure 2-2 shows how AppleScript gets the words in the Scriptable Text Editor’s dictionary. Figure 2-2 How AppleScript gets the Scriptable Text Editor dictionary Scriptable Text Editor application Dictionary resource AppleScript extension Commands: cut make print ... Objects: character paragraph window ...
C H A P T E R 2 Overview of AppleScript Values are an important means of exchanging data in AppleScript. When you request information about application objects, it is usually returned in the form of values. Similarly, when you provide information with commands, you typically supply it in the form of values. A fixed number of specific types of values are recognized by AppleScript. You cannot define additional types of values, nor can you change the way values are represented.
C H A P T E R 2 Overview of AppleScript You can use operations within AppleScript statements, such as: tell application "Scriptable Text Editor" delete word 3 + 4 of document "Test" end tell When you run this script, AppleScript evaluates the expression 3 + 4 and uses the result to determine which word to delete. Variables 2 When AppleScript encounters a variable in a script, it evaluates the variable by getting its value.
C H A P T E R 2 Overview of AppleScript AppleScript does not distinguish uppercase letters from lowercase variables in variable names; the variables myName, myname, and MYNAME all represent the same value. Script Objects 2 Script objects are objects you define and use in scripts. Like application objects, script objects respond to commands and have specific information associated with them. Unlike application objects, script objects are defined in scripts.
C H A P T E R 2 Overview of AppleScript Dialects 2 AppleScript scripts can be displayed in several different dialects, or representations of AppleScript that resemble human languages or programming languages. The dialects available on a given computer are determined by the Dialects folder, a folder in the Scripting Additions folder (which in turn is located in the Extensions folder of the System Folder) that contains one dialect file for each AppleScript dialect installed on your computer.
C H A P T E R 2 Overview of AppleScript Continuation Characters 2 A simple AppleScript statement must normally be on a single line. If a statement is longer than will fit on one line, you can extend it by including a continuation character, ¬ (Option-L or Option-Return), at the end of one line and continuing the statement on the next.
C H A P T E R 2 Overview of AppleScript Comments 2 To explain what a script does, you add comments. A comment is text that remains in a script after compilation but is ignored by AppleScript when the script is executed. There are two kinds of comments: ■ ■ A block comment begins with the characters (* and ends with the characters *). Block comments must be placed between other statements. They cannot be embedded in simple statements.
C H A P T E R 2 Overview of AppleScript Because comments are not executed, you can prevent parts of scripts from being executed by putting them within comments. You can use this trick, known as “commenting out,” to isolate problems when debugging scripts or temporarily block execution of any parts of script that aren’t yet finished. Here’s an example of “commenting out” an unfinished handler: (* on finish() --under construction end *) If you later remove (* and *), the handler is once again available.
C H A P T E R 2 Overview of AppleScript Identifiers whose first and last characters are vertical bars (|) can contain any characters. For example, the following are legal identifiers: |Back and Forth| |Right*Now!| Identifiers whose first and last characters are vertical bars can contain additional vertical bars if the vertical bars are preceded by backslash (\) characters, as in the identifier |This\|Or\|That|.
C H A P T E R 2 Overview of AppleScript After you create the variable myName, you can refer to it by any of these names: MYNAME myname MyName mYName When interpreting strings, such as "Pegi", AppleScript preserves the case of the letters in the string, but does not use it in comparisons. For example, the value of the variable myName defined earlier is always "Pegi", but the value of the expression myName = "PEGI" is true.
C H A P T E R 2 Overview of AppleScript Compiling Scripts With the Script Editor When you create or modify a script and then attempt to run or save it as a compiled script or script application, the Script Editor asks AppleScript to compile the script first. To compile a script, AppleScript converts the script from the form typed into a Script Editor window (or any script-editing window) to a form that AppleScript can execute.
P A R T T W O AppleScript Language Reference 2
C H A P T E R Figure 3-0 Listing 3-0 Table 3-0 3 Values 3 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.
C H A P T E R 3 Values Figure 3-1 Value class definition for lists List A value of class List is an ordered collection of values. The values contained in a list are known as items. Each item can belong to any class. LITERAL EXPRESSIONS A list appears in a script as a series of expressions contained within braces and separated by commas. For example, { "it's", 2, TRUE } is a list containing a string, an integer, and a Boolean. PROPERTIES Class The class identifier for the value.
C H A P T E R 3 Values Figure 3-1 Value class definition for lists (continued) Using Value Class Definitions 35
C H A P T E R 3 Values COMMANDS HANDLED You can count the items in a list with the Count command. For example, the value of the following statement is 6. count {"a", "b", "c", 1, 2, 3} --result: 6 You can also count elements of a specific class in a list. For example, the value of the following statement is 3.
C H A P T E R 3 Values Literal Expressions 3 A literal expression is an expression that evaluates to itself. The “Literal Expressions” section of a value class definition shows examples of how values of a particular class are represented in AppleScript—that is, typical literal expressions for values of that class. For example, in AppleScript and many other programming languages, the literal expression for a string is a series of characters enclosed in quotation marks.
C H A P T E R 3 Values Elements 3 Elements of values are values contained within other values. Composite values have elements; simple values do not. The sample value class definition in Figure 3-1 shows one element, called an item. Use references to refer to elements of composite values.
C H A P T E R 3 Values Reference Forms 3 A reference is a compound name for an object or a value. You can use references to specify values within composite values or properties of simple values. You cannot use references to refer to simple values. The “Reference Forms” section is included in composite value class definitions only. It lists the reference forms you can use to specify elements of a composite value.
C H A P T E R 3 Values Table 3-1 AppleScript value class identifiers Value class identifier Description of corresponding value Boolean A logical truth value Class A class identifier Constant A reserved word defined by an application or AppleScript Data Raw data that cannot be represented in AppleScript, but can be stored in a variable Date A string that specifies a day of the week, day of the month, month, year, and time Integer A positive or negative number without a fractional part List
C H A P T E R 3 Values Boolean 3 A value of class Boolean is a logical truth value. The most common Boolean values are the results of comparisons, such as 4 > 3 and WordCount = 5. The two possible Boolean values are true and false. LITERAL EXPRESSIONS true false PROPERTY Class The class identifier for the object. This property is read-only, and its value is always boolean. ELEMENTS None OPERATORS The operators that take Boolean values as operands are And, Or, Not, &, =, and .
C H A P T E R 3 Values Class 3 A value of class Class is a class identifier. A class identifier is a reserved word that specifies the class to which an object or value belongs. The Class property of an object contains a class identifier value. LITERAL EXPRESSIONS string integer real boolean class PROPERTY Class The class identifier for the object. This property is read-only, and its value is always class.
C H A P T E R 3 Values Constant 3 A value of class Constant is a reserved word defined by AppleScript or an application in its dictionary. Applications define sets of values that can be used for parameters of a particular command; for example, the value of the saving parameter of a Close command must be one of the three constants yes, no, and ask. LITERAL EXPRESSIONS yes no ask PROPERTY Class The class identifier for the object. This property is read-only, and its value is always constant.
C H A P T E R 3 Values Data 3 A value of class Data is data returned by an application (in response to a command) that does not belong to any of the other value classes defined in this section. A value of class Data is raw data that can only be stored in a variable. PROPERTY Class The class identifier for the object. This property is read-only, and its value varies depending on the application. ELEMENTS None OPERATORS The operators that can take values of class Data as operands are = and .
C H A P T E R 3 Values LITERAL EXPRESSIONS date "12/5/54, 12:06 PM" date "12/05/53, 12:06" date "12/05/54" date "12:06" date "Sunday, December 5, 1954 12:06 pm" PROPERTIES Class The class identifier for the object. This property is read-only, and its value is always date. Weekday One of the constants Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday or Mon, Tue, Wed, Thu, Fri, Sat, Sun.
C H A P T E R 3 Values OPERATORS The operators that take Date values as operands are &, +, –, =, , >, , <, , Comes Before, Comes After, and As. In expressions containing >, , <, , Comes Before, or Comes After, a later time is greater than an earlier time.
C H A P T E R 3 Values REFERENCE FORMS You can refer to properties of a Date value using the Property reference form. weekday of date "May 3, 1993" --result: Monday time of date "May 3, 1993" --result: "12:00 AM" Note that AppleScript fills in a default time property for the date specified in the second example. If you want to specify a time relative to a date, you can do so as follows: date "2:30 am" of date "May 3, 1993" --result: date "May 3, 1993 2:30 AM" date "Sept.
C H A P T E R 3 Values don’t specify the time information, 12:00 AM (midnight) is the default. If you omit AM or PM, AM is the default; however, if you specify 12:00 without AM or PM, 12:00 PM is the default. If you specify the time using 24-hour time, AppleScript converts it to the equivalent time using AM or PM; for example, 17:00 is equivalent to 5:00 PM. To get the current date, use the scripting addition command Current Date.
C H A P T E R 3 Values OPERATORS The Div operator always returns an integer as its result. The +, –, *, Mod, and ^ operators return integers or real numbers. The operators that can have integers as operands are +, -, *, (or /), Div, Mod, ^, =, , >, , <, and . COERCIONS SUPPORTED AppleScript supports coercion of an Integer value to a single-item list, a real number, or a string.
C H A P T E R 3 Values Each list item can be any valid expression. For example, { "it" & "'s", 1 + 1, 4 > 3 } has the same value as the list in the previous example, because each of the expressions it contains has the same value as the corresponding expression in the previous example. An empty list is a list containing no items. It is represented by a pair of empty braces: {} PROPERTIES Class The class identifier for the value. This property is read-only, and its value is always list.
C H A P T E R 3 Values COMMANDS HANDLED You can count the items in a list with the Count command. For example, the value of the following statement is 6. count {"a", "b", "c", 1, 2, 3} --result: 6 You can also count elements of a specific class in a list. For example, the value of the following statement is 3.
C H A P T E R 3 Values You cannot use the Relative, Name, ID, or Filter reference forms. For example, the following reference, which uses the Filter reference form on a list, is not valid. the items in {"this", "is", "a", "list"} whose first character is "t" --result: not a valid reference COERCIONS SUPPORTED AppleScript supports coercion of a single-item list to any value class to which the item can be coerced if it is not part of a list.
C H A P T E R 3 Values Number 3 The class identifier Number is a synonym for Integer or Real; it describes a positive or negative number that can be either of class Integer or of class Real. LITERAL EXPRESSIONS 1 2 -1 1000 10.2579432 1.0 1. Any valid literal expression for an Integer or a Real value is also a valid literal expression for a Number value. PROPERTY Class The class identifier for the object. This property is read-only, and its value is always either integer or real.
C H A P T E R 3 Values COERCIONS SUPPORTED You can use the class identifier Number to coerce any value that can be coerced to a Real value or an Integer value. However, the resulting value class is always either Integer or Real: set x to 1.5 as number class of x --result: real 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.
C H A P T E R 3 Values ELEMENTS None OPERATORS The and / operators always return Real values as their results. The +, -, *, Mod, and ^ operators return Real values if either of their operands is a Real value. The operators that can have Real values as operands are +, -, *, (or /), Div, Mod, ^, =, , >, , <, and . COERCIONS SUPPORTED AppleScript supports coercion of a Real value to a single-item list or a string.
C H A P T E R 3 Values LITERAL EXPRESSIONS Records appear in scripts as series of properties contained within braces and separated by commas. Each property has a label. Following the label is a colon, and following the colon, the value of the property. For example, the record { name:"Mitchell", height:70.5, weight:165 } contains three properties: Name (a string), Height (a real number), and Weight (an integer). The values assigned to properties can belong to any class.
C H A P T E R 3 Values OPERATORS The operators that can have records as operands are &, =, , Starts With, Ends With, Contains, and Is Contained By. For detailed explanations and examples of how AppleScript operators treat records, see “Operators That Handle Operands of Various Classes,” which begins on page 168. COMMANDS HANDLED You can count the properties in a record with the Count command. For example, the value of the following statement is 2.
C H A P T E R 3 Values NOTES To specify a particular property of a record, you give its name. For example, if you assign the record to a variable, as in copy { name:"Mitchell", height:70.5, weight:165 } to writer you can then get the value of the Name property with the expression name of writer A property of a record can contain a value of any class. You can change the class of a property simply by assigning a value belonging to another class.
C H A P T E R 3 Values The difference between a value of class Reference and the object it refers to is analogous to the difference between an address and the building it refers to. The address is a series of words and numbers, such as “1414 Maple Street,” that identifies the building. It is distinct from the building itself. Values of class Reference are similar to pointers in other programming languages, but unlike pointers, references can refer only to objects.
C H A P T E R 3 Values COERCIONS SUPPORTED The application to which an object specified by a reference belongs determines whether the value of the object can be coerced to a desired class. NOTES A reference can function as a reference to an object or as an expression whose value is the value of the object specified in the reference. When a reference is the direct parameter of a command, it usually functions as a reference to an object, indicating to which object the command should be sent.
C H A P T E R 3 Values String 3 A value of class String is a character string (an ordered series of characters) in AppleScript. LITERAL EXPRESSIONS Strings in scripts are always surrounded by quotation marks, as in these examples: "string" "Rolling along, stringing a song" "Pennsylvania 68000" To include quotation marks in a string, you must use the equivalent twocharacter sequence, \". For more information, see “Special Characters in Strings” later in this section.
C H A P T E R 3 Values 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: non-functional he's v1.0 $99.
C H A P T E R 3 Values REFERENCE FORMS You can use the following reference forms to refer to elements of strings: ■ Property. For example, class of "This is a string" specifies string. ■ Index. For example, word 3 of "This is a string" specifies "a". ■ ■ ■ ■ Middle. For example, middle word of "This is a string" specifies "is". Arbitrary. For example, some word of "This is a string" might specify any of the words in the string. Every Element.
C H A P T E R 3 Values is displayed in a dialog box as item 1 item 2 1 2 STRING CONSTANTS AppleScript defines three constants for string values: Constant Value space " " tab "\t" return "\r" COERCIONS SUPPORTED If a string consists of an appropriate number, AppleScript supports coercion of the string to an integer, a number, or a real number. Similarly, any integer, number, or real number can be coerced to a string.
C H A P T E R 3 Values You cannot set the value of an element of a string. For example, if you attempt to change the value of the first character of the string "boris" as shown in the following example, you’ll get an error. set myName to "boris" set character 1 of myName to "D" --results in an error, because you cannot set the values of --elements of strings Styled Text 3 The class identifier Styled Text is a synonym for a string that includes style and font information.
C H A P T E R 3 Values OPERATORS Because values identified as Styled Text values are really values of class String, the operators available are the operators described in the definition of class String: &, =, , >, , <, , Starts With, Ends With, Contains, Is Contained By, and As. For detailed explanations and examples of how AppleScript operators treat strings, see “Operators That Handle Operands of Various Classes,” which begins on page 168.
C H A P T E R 3 Values NOTES You can’t change the style or font information from a script, but you can use styled text to preserve style and font information when copying text objects from applications to scripts.
C H A P T E R 3 Values However, the class of a string is always string: class of "A string" as text --result: string Unlike the class identifier Number (which is a synonym for either Real or Integer) or Styled Text (which denotes a string that includes font and style information), the class identifier Text is precisely equivalent to a single class identifier—String.
C H A P T E R 3 Values If you provide a command parameter or operand of the wrong class, AppleScript automatically coerces the operand or parameter to the expected class, if possible. For example, when AppleScript executes this statement, repeat ( word 2 of document "Big" of application "Scriptable Text Editor") times display dialog "Hello" end repeat it expects the number of times to be an integer.
C H A P T E R 3 Values Figure 3-2 Coercions supported by AppleScript Bo ole Cl an as s Co ns Da tant ta Da te Int eg Si er ng l Mu e-ite lti- m l Nu item ist mb lis t Re er al Re co St rd rin go St yle r te d t xt ex t* Coerce to Coerce from Boolean Class Constant Data Date Integer Single-item list † Multi-item list Real ‡ Record String * Only values that include style and font information can be coerced to styled text.
C H A P T E R 3 Values set x to 4 as number class of x --result: integer set x to "Hello" as text class of x --result: string Coercing Values 71
C H A P T E R 3 Values 72 Coercing Values
C H A P T E R Figure 4-0 Listing 4-0 Table 4-0 4 Commands 4 A command is a word or series of words used in AppleScript statements to request an action. Every command is directed at a target, which is the object that responds to the command. The target is usually an application object, but it can also be a script object or a user-defined subroutine or value in the current script. Not all commands can be used with all types of targets.
C H A P T E R 4 Commands The sections that follow describe the different types of commands and their targets. Application Commands Application commands are commands that cause actions in scriptable applications. The target of an application command is an application object or a script object. Different application objects respond to different commands. To determine which commands a particular object can respond to, see the definitions provided by the application’s documentation.
C H A P T E R 4 Commands Similarly, if you specify a reference incompletely in the command line, AppleScript uses the default target specified in the enclosing Tell statement to complete the reference. For example, the following statement is equivalent to both of the previous examples: tell front document of app "Scriptable Text Editor" delete word 1 end tell For information about sending application commands to script objects, see Chapter 9, “Script Objects,” which begins on page 265.
C H A P T E R 4 Commands For more examples of how to use Copy, Count, Get, Run, and Set, see the command definitions later in this chapter. Scripting Addition Commands 4 Scripting additions are files that provide additional commands or coercions you can use in scripts. Each scripting addition can contain one or more command handlers.
C H A P T E R 4 Commands Dialog command, which displays the dialog box in the Script Editor’s layer (that is, in front of any other Script Editor windows that may be open), while the Script Editor is still the active application. set theCount to number of words in front document of app "Scriptable Text Editor" if theCount > 500 then display dialog "You have exceeded your word limit.
C H A P T E R 4 Commands User-Defined Commands 4 User-defined commands are commands that trigger the execution of collections of statements, called subroutines, elsewhere in the same script. The target of a user-defined command is the current script, that is, the script from which the command is executed. There are two ways to specify the current script as the target of a user-defined command. Outside of a Tell statement, simply use the command to specify the current script as its target.
C H A P T E R 4 Commands Using Command Definitions 4 Command definitions contain information about what commands do and how to use them in scripts. Figure 4-1 shows the definition for the Move command, an application command. The definition contains four types of information: syntax, parameters, results, and examples. Some definitions include information about errors as well. The sections following the figure explain the information conveyed by each part of the definition.
C H A P T E R 4 Commands Syntax 4 Each command definition begins with a syntax description, which is a template for using the command in a statement.
C H A P T E R 4 Commands parameters, the description in the “Parameters” section specifies a default value that is used if you don’t include the parameter. For more information about direct parameters, see “Application Commands” on page 72. For more information about using parameters, see “Using Parameters” on page 80. Result 4 Many, but not all, commands return results. The result of a command is the value generated when the command is executed.
C H A P T E R 4 Commands the Cancel button in the dialog box, AppleScript returns error number –128 and the error string "User canceled". Your script must handle this error for script execution to continue. For a complete description of handling errors that occur during script execution, see Chapter 8, “Handlers.
C H A P T E R 4 Commands Phrases such as before paragraph 10 and word 1 are called relative references and index references, respectively. These kinds of references specify locations. For more information about these kinds of references, see “Index” on page 131 and “Relative” on page 139. Coercion of Parameters 4 If a parameter doesn’t belong to the right class, it may be possible to coerce it, that is, to change it into a value of another class.
C H A P T E R 4 Commands two different applications to edit a graphic, the data value returned by one Edit Graphic command can be sent as the direct parameter of another Edit Graphic command. If an application returns values of class Data, its documentation should say so. Using Results 4 The result of a command is the value generated when the command is executed. You can display the result of a command in the Script Editor.
C H A P T E R 4 Commands commands show how to use the result variable to set the value of numWords to the value returned by the Count command: count words in paragraph 3 set numWords to result When a direct parameter specifies more than one object, the result is a list that contains a value for each object that was handled. Here is an example of a command whose result is a list: get paragraphs 1 thru 3 of first document The result is a list of strings similar to the following.
C H A P T E R 4 Commands different computer when the Display Dialog scripting addition is not present in the Scripting Additions folder, AppleScript replaces the words display dialog in the script with «event sysodlog». In this case you should drop the icon for the Display Dialog scripting addition into the Scripting Additions folder before attempting to run the script. Double angle brackets can also occur in results.
C H A P T E R 4 Commands The application commands defined in this chapter are standard application commands supported by most applications. The definitions in this chapter describe how these commands work in most applications. Individual applications can extend or change the way the standard application commands work. Application dictionaries list application commands under two categories, the Required suite and the Standard suite. All applications support the commands in the Required suite.
C H A P T E R 4 Commands Table 4-1 Standard application commands defined in this chapter (continued) Command Summary Duplicate Copies an object or objects to a new location. Exists Determines if an object exists. Get Returns the value of an object. Launch* Launches an application without invoking its standard startup procedures. Make Creates a new object. Move Moves an object or objects. Save Saves an object to a file. Set Assigns a value to an object.
C H A P T E R 4 Commands Close application command 4 A Close command is a request to close one or more objects. SYNTAX close referenceToObject [ saving in referenceToFile ] [ saving saveOption ] PARAMETERS referenceToObject A reference to the object or objects to close. Class: Reference referenceToFile A reference of the form file nameString or alias nameString (see “Notes”). Class: Reference Default value: The file in which the object was last saved.
C H A P T E R 4 Commands EXAMPLES tell application "Scriptable Text Editor" close window "Tremendous" saving Yes end tell tell application "Scriptable Text Editor" close saving in file "Macintosh HD:Documents:Report" end tell NOTES To specify the name (nameString) of a file in which to save the object, use a string of the form "Disk:Folder1:Folder2:...:Filename"; for details, see “References to Files,” which begins on page 144. You can also specify a string with only a filename ("Filename").
C H A P T E R 4 Commands APPLESCRIPT COMMAND SYNTAX ( copy | put ) expression ( to | into) variablePattern APPLICATION COMMAND SYNTAX ( copy | put ) expression ( to | into) referencePattern ( copy | put ) [ referenceToObject ] PARAMETERS expression variablePattern The expression whose value is to be assigned. If expression is a reference or a list or record of references, AppleScript gets the values of the objects specified by the references.
C H A P T E R 4 Commands is a reference to the copied object; however, if the command does not include parameters, there is no result.
C H A P T E R 4 Commands Since the Scriptable Text Editor returns position of front window as a list of two integers, the preceding example copies the first item in the list to x and the second item in the list to y. Patterns copied with the Copy command can also be more complex.
C H A P T E R 4 Commands Count AppleScript command, application command4 The Count command can function as an AppleScript command or an application command. The AppleScript command counts the number of elements of a particular class in a list, record, or string. The application command counts the number of elements of a particular class in an object or objects.
C H A P T E R 4 Commands pluralClassName The plural class name of the elements to be counted. The elements of lists, records, and strings are listed in the value class definitions in Chapter 3, “Values.” Class: Class identifier Default value: Item for lists, records, and application objects; Character for strings (see “Notes”) referenceToObject A reference to the object or objects whose elements are to be counted.
C H A P T E R 4 Commands This example shows another way to count the integers in the list: count each integer in {"Yes", "No", "Maybe", 4, 5, 6} --result: 3 In the following example, every word of document "simple" consists of a list of words. The Scriptable Text Editor counts the words in the list.
C H A P T E R 4 Commands The result of the Count command depends on how you specify the range of objects to be counted.
C H A P T E R 4 Commands The counting in this example requires several steps, beginning with the reference to the outermost container. The reference paragraphs 2 thru 3 specifies a list of two items, each of which is a paragraph: {"This is paragraph two.", "This is paragraph three."} On the basis of this list, the Scriptable Text Editor evaluates the reference words of paragraphs 2 thru 3 as a list of two items, each of which is a list of the words in one paragraph: {{"This", "is", "paragraph", "two.
C H A P T E R 4 Commands Data Size application command 4 A Data Size command is a request for the size, in bytes, of the data of one or more objects. The value returned is the size of the data (a value) that would result from a Get command on the same object or objects. SYNTAX data size of referenceToObject [ as className ] PARAMETERS referenceToObject A reference to the object or objects whose data size is to be returned.
C H A P T E R 4 Commands EXAMPLE set theSize to the data size of paragraph 1 through 10 NOTES As described in the definition of the Get command, the data of some application objects can be returned as values of different classes. Because the size of the data returned as different classes can be different, the Data Size command includes an optional class parameter that allows you to specify the class of the data.
C H A P T E R 4 Commands Duplicate application command 4 A Duplicate command is a request to make a copy of an object or objects and insert the new copy either at a location specified in the command or at the location following the object that was copied. SYNTAX duplicate referenceToObject [ to newLocation ] PARAMETERS referenceToObject A reference to the object or objects to be duplicated. Class: Reference newLocation The new location for the object.
C H A P T E R 4 Commands PARAMETER referenceToObject A reference to the object or objects to find. Class: Reference RESULT If true, all of the objects referred to by referenceToObject exist. If false, one or more of the objects referred to by referenceToObject do not exist.
C H A P T E R 4 Commands APPLESCRIPT COMMAND SYNTAX [ get ] expression [ as className ] APPLICATION COMMAND SYNTAX [ get ] referenceToObject [ as className ] PARAMETERS expression An expression whose value is to be returned in the result variable. Class: Any AppleScript expression className A class identifier that specifies the desired value class for the returned data.
C H A P T E R 4 Commands EXAMPLE tell application "Scriptable Text Editor" get paragraph 3 --gets the value copy result to item 2 of x --puts the result end tell NOTES The word get in the Get command is optional because AppleScript automatically gets the value of expressions and references when they appear in scripts.
C H A P T E R 4 Commands Launch application command 4 If an application is not already running, sending it a Launch command launches it without sending a Run command. (If the application is already running, the Launch command has no effect.) This allows an application to open without performing its usual startup procedures, such as opening a new window or, in the case of a script application, running the script.
C H A P T E R 4 Commands AppleScript sends an implicit Run command whenever it begins to execute a Tell statement whose target is an application that is not already open. This can cause problems with applications such as the Scriptable Text Editor that normally perform specific tasks on startup, such as opening a new window.
C H A P T E R 4 Commands Make application command 4 A Make command is a request to create a new object. The command can include values for properties of the object, for the data of the object, or both. SYNTAX make [new] className at referenceToLocation ¬ [ with properties ¬ { propertyLabel:propertyValue [, propertyLabel:propertyValue ]...}] ¬ [ with data dataValue ] PARAMETERS className The class of the object to be created.
C H A P T E R 4 Commands RESULT A reference to the newly created object. Class: Reference EXAMPLE tell application "Scriptable Text Editor" make window at beginning with properties {bounds:{400, 300, 500, 600}, contents:"This window is narrow."} end tell NOTES If you use the Make command to create a new text object, check the application dictionary to determine how the application handles delimiters.
C H A P T E R 4 Commands referenceToLocation A reference to the location to which to move the object or objects. Class: Reference RESULT A reference to the object that was moved. Class: Reference EXAMPLE tell front document of app "Scriptable Text Editor" move word 10 to before paragraph 11 end tell Open application command 4 An Open command is a request to open a file or files.
C H A P T E R 4 Commands EXAMPLE tell app "Scriptable Text Editor" open file "Macintosh HD:New Products:Mammoth:Product Intro" end tell tell app "Scriptable Text Editor" open { file "HD:Letters:Offer", file "HD:Letters:Acceptance"} end tell NOTES To specify the name (nameString) of a file to open, use a string of the form "Disk:Folder1:Folder2:...:Filename"; for details, see “References to Files,” which begins on page 144. You can also specify a string with only a filename ("Filename").
C H A P T E R 4 Commands EXAMPLES tell application "Scriptable Text Editor" print document "Introduction" end tell tell application "Scriptable Text Editor" print windows 1 thru 5 end tell tell application "Scriptable Text Editor" print { file "HD:Letters:Zoning Department", file "HD:Letters:Mayor"} end tell NOTES To specify the name of a file to print, use the term file or alias followed by a string of the form "Disk:Folder1:Folder2:...
C H A P T E R 4 Commands PARAMETERS referenceToApplication A reference of the form application nameString, where nameString is a string that matches the name of the application you want to quit as it is listed in the Application menu. Class: Reference saveOption A constant that specifies whether to save documents that have been modified before quitting. The possible values are yes, no, and ask. The value yes specifies to save the documents. The value no specifies not to save the documents.
C H A P T E R 4 Commands on the application. Some applications are not affected; others, such as the Scriptable Text Editor, repeat their startup procedures each time they receive a Run command. APPLESCRIPT COMMAND SYNTAX run [ scriptObjectVariable ] APPLICATION COMMAND SYNTAX run [ referenceToApplication ] PARAMETERS scriptObjectVariable A variable identifier whose value is a script object. This parameter is optional if the Run command is used within an appropriate Tell statement.
C H A P T E R 4 Commands NOTES To specify the name (nameString) of an application to run, use a string of the form "Disk:Folder1:Folder2:...:ApplicationName"; for details, see “References to Applications,” which begins on page 146. You can also specify a string with only an application name ("ApplicationName"). In this case, if the application is not already running, AppleScript attempts to find the application in the current directory.
C H A P T E R 4 Commands referenceToFile A reference of the form file nameString or alias nameString that specifies the file in which to save the objects (see “Notes”). Class: Reference Default value: The file in which the object was last saved. If the object has not been saved before, the application creates a new file.
C H A P T E R 4 Commands APPLESCRIPT COMMAND SYNTAX set variablePattern to expression expression returning variablePattern APPLICATION COMMAND SYNTAX set referencePattern to expression expression returning referencePattern PARAMETERS variablePattern The name of the variable in which to store the value, or a list of variable patterns, or a record of variable patterns. Class: Identifier, list, or record expression The expression whose value or values are to be assigned.
C H A P T E R 4 Commands EXAMPLES You can use the Set command to set a variable to any value: set x to 5 set myList to { 1, 2, "four" } tell application "Scriptable Text Editor" set x to word 1 of front document end tell These two statements are equivalent: set x to 3 3 returning x Similarly, the following examples are equivalent: tell front document of application "Scriptable Text Editor" set x to word 1 end tell tell front document of application "Scriptable Text Editor" word 1 returning x end tell In
C H A P T E R 4 Commands Patterns set with the Set command can also be more complex.
C H A P T E R 4 Commands NOTES If you use the Set command to set a variable to a list, record, or script object, the variable shares data with the original list, record, or script object. If you change the data of the original, the value of the variable also changes. Here’s an example of how this works: set myList to { 1, 2, 3 } set yourList to myList set item 1 of myList to 4 The result of these statements is that item 1 of both myList and yourList is 4.
C H A P T E R Figure 5-0 Listing 5-0 Table 5-0 5 Objects and References 5 Objects are the things in applications, the Operating System, or AppleScript that can respond to commands. For example, application objects are objects stored in applications and their documents. Usually, they are identifiable items that users can manipulate in applications, such as windows, words, characters, and paragraphs in a text-editing application.
C H A P T E R 5 Objects and References Figure 5-1 shows a sample object class definition for a paragraph object. The definition contains four types of information: properties, element classes, commands handled, and default value class returned. The sections that follow describe the kinds of information provided by an object class definition. Properties 5 A property of an object is a characteristic that has a single value, such as the name of a window or the font of a character.
C H A P T E R 5 Objects and References Figure 5-1 The Scriptable Text Editor’s object class definition for paragraph objects Paragraph An object of class Paragraph is a text object that‘s delimited by return characters or by the beginning or end of the container. PROPERTIES Font The name of the font of the characters of the paragraph. If the font varies within the paragraph, the Font property specifies the font of the first character.
C H A P T E R 5 Objects and References The definition in Figure 5-1 shows that all paragraph objects respond to the Copy, Count, Cut, Data Size, Delete, Exists, Get, Make, Move, Select, and Set commands. Default Value Class Returned 5 Each object has a value. For example, the value of a paragraph object is a string that includes style and font information. You can get the value of a system or application object by sending it a Get command or simply referring to it in a script.
C H A P T E R 5 Objects and References References allow you to identify objects in a flexible and intuitive way. Just as there might be several ways to identify an object on the desktop, AppleScript has different reference forms that allow you to specify the same object in different ways.
C H A P T E R 5 Objects and References You can also use the possessive form ('s) to specify containers. If you use the possessive form, list the container before the object it contains. For example, in first window's name the container is first window. The object it contains is a Name property. All properties and elements have containers. The previous example specified the Name property of a window, which is contained in a window object.
C H A P T E R 5 Objects and References Similarly, the following Tell statement tells the Scriptable Text Editor to delete the third word of the first paragraph of the front document. tell paragraph 1 of front document of application "Scriptable Text Editor" delete word 3 end tell Tell statements can contain other Tell statements, called nested Tell statements.
C H A P T E R 5 Objects and References Table 5-1 Reference forms Reference form Purpose Arbitrary Element Specifies an arbitrary object in a container Every Element Specifies every object of a particular class in a container Filter Specifies every object in a particular container that matches conditions defined in a Boolean expression ID Specifies an object by its ID property Index Specifies the position of an object with respect to the beginning or end of a container Middle Element Specif
C H A P T E R 5 Objects and References EXAMPLES some word of paragraph 5 some word whose style contains outline Every Element 5 The Every Element reference form specifies every object of a particular class in a container. SYNTAX every className pluralClassName where className is a singular class name (such as word or paragraph). pluralClassName is the plural form defined by AppleScript or an application (such as words or paragraphs).
C H A P T E R 5 Objects and References EXAMPLES The following example assigns a string to the variable myString, and then uses the Every Element reference form to specify every word contained in the string.
C H A P T E R 5 Objects and References Filter 5 The Filter reference form specifies all objects in a container that match one or more conditions specified in a Boolean expression. The Filter reference form specifies application objects only. It cannot be used to specify values. (For information about how to use the Filter reference form, refer to the next section, “Using the Filter Reference Form,” which begins on page 140.
C H A P T E R 5 Objects and References NOTES Except for the Every Element reference form, the application returns an error if no objects pass the test or tests. For the Every Element reference form, the application returns an empty list if no objects pass the test or tests. To specify a container after a filter, you must enclose the filter and the reference it applies to in parentheses.
C H A P T E R 5 Objects and References additional guarantees, such as ensuring the uniqueness of an ID among all objects. The value of an ID property is not modifiable. It does not change even if the object is moved within the container. This allows you to save an object’s ID and use it to refer to the object for as long as the object exists. Applications are not required to support ID properties. To find out if or how an application uses ID properties, see the documentation for the application.
C H A P T E R 5 Objects and References The front form (for example, front window) is equivalent to className 1 or first className. The last and back forms (for example, last word and back window) refer to the last object in a container. They are equivalent to className -1. The following forms refer to insertion points and are used to specify locations: beginning | front end | back The beginning and front forms are equivalent and refer to the first insertion point of the container (insertion point 1).
C H A P T E R 5 Objects and References The following example contains two references. The first is a reference to the tenth word of the document called Introduction. The second is a reference to the last insertion point in the same document. tell application "Scriptable Text Editor" move word 10 of document "Introduction" to end of document "Introduction" end tell Middle Element 5 The Middle Element reference form specifies the middle object of a particular class in a container.
C H A P T E R 5 Objects and References Name 5 The Name reference form specifies an object by name. Most applications determine this by examining an object’s Name property. SYNTAX className [ named ] nameString where className is the class identifier for the specified object. nameString is the value of the object’s Name property (see “Notes”).
C H A P T E R 5 Objects and References Property 5 The Property reference form specifies a property of an application object, a script object, a record, or a date. SYNTAX propertyLabel where propertyLabel is the label for the property. EXAMPLES The following example is a reference to the Name property of the front window. It lists the label for the property (name) and its container (front window). name of front window The following example is a reference to the UnitPrice property of a record.
C H A P T E R 5 Objects and References Range 5 The Range reference form specifies a series of objects of the same class in the same container. You can specify the objects with a pair of indexes (such as words 12 thru 24) or with a pair of boundary objects (such as words from paragraph 3 to paragraph 5).
C H A P T E R 5 Objects and References EXAMPLES The following examples and results use the Scriptable Text Editor document shown in Figure 5-2. Figure 5-2 The Scriptable Text Editor document “simple” In the following example, the phrase words from paragraph 1 to paragraph 2 is a range reference that specifies the list of the words in the first and second paragraphs.
C H A P T E R 5 Objects and References To get the result, AppleScript first gets the value of the container, which is a list of two paragraphs: {"This is paragraph one.", "This is paragraph two.
C H A P T E R 5 Objects and References text of words 1 thru 4 of "We're all in this together" --result: "We're all in this" Relative 5 The Relative reference form specifies an object or a location by describing its position in relation to another object, known as the base, in the same container. SYNTAX [ className ] ( before | [in] front of ) baseReference [ className ] ( after | [in] back of | behind ) baseReference where className is the class identifier of the specified object.
C H A P T E R 5 Objects and References The following example contains three references. The first two are Index references that specify the front document and the first word. The third is a Relative reference that specifies the insertion point before the tenth paragraph. The command moves the first word to the insertion point before the tenth paragraph.
C H A P T E R 5 Objects and References For example, compare this reference without a filter every word of paragraph 5 to the same reference with a filter: every word of paragraph 5 where character 1 = "M" The first reference specifies all the words in the fifth paragraph. The second reference, which includes the filter where character 1 = "M", specifies all the words in the same container whose first character is “M”. Words that do not pass this test are filtered out.
C H A P T E R 5 Objects and References A Filter reference includes one or more tests. Each test is a Boolean expression that compares a property or element of each object being tested, or the objects themselves, with another object or value. Table 5-2 shows some Filter references, the Boolean expressions they contain, and what is being tested in each reference.
C H A P T E R 5 Objects and References Because each test is a Boolean expression, it can also include the Boolean operator Not. For example, the reference words whose length > 10 and not it contains "M" refers to only those words containing more than ten characters and not containing the letter “M.
C H A P T E R 5 Objects and References References to Files 5 You can use either of these forms to refer to any file: file nameString alias nameString where nameString is a string of the form "Disk:Folder1:Folder2:...:Filename" that specifies exactly where the file is stored or a string that consists of the file’s name only. Disk specifies the disk on the local computer on which the application is stored, Folder1:Folder2:...
C H A P T E R 5 Objects and References set fileRef to a reference to file "Hard Disk:June Sales" tell application "Scriptable Text Editor" open fileRef end If you use a reference of the form alias nameString, AppleScript creates an alias for the file—that is, a representation of the file, much like an alias icon on the desktop, that identifies the file no matter where it is located.
C H A P T E R 5 Objects and References References to Applications 5 You can use this form to refer to any application: application applicationNameString ¬ [ of machine computerName [ of zone AppleTalkZoneName ] ] where applicationNameString is either a string of the form "Disk:Folder1:Folder2: ...:ApplicationName" that specifies where the application is stored on the local computer or a string that consists of the name of the application.
C H A P T E R 5 Objects and References the definition in the application’s dictionary to determine the characteristics of the object, such as its properties and the commands it can handle. For the Scriptable Text Editor’s definition of an application, see page 318. References to Local Applications 5 You can specify an application on the local computer with a string of the form "Disk:Folder1:Folder2:...:ApplicationName" that specifies the application’s exact location.
C H A P T E R 5 Objects and References References to Remote Applications 5 If the application is on a remote computer, you must specify its name as it would be listed in the Application menu, the name of the computer, and if necessary the name of the zone in which the computer is located: quit application "Scriptable Text Editor" of machine "Mr.Science" of zone "Far Side" The specified remote application must be running. AppleScript doesn’t open applications on remote computers.
C H A P T E R Figure 6-0 Listing 6-0 Table 6-0 6 Expressions 6 An expression is any series of AppleScript words that has a value. You use expressions to represent or derive values in scripts. When AppleScript encounters an expression, it converts it into an equivalent value. This is known as evaluation. Chapter 3 describes and gives examples of the simplest kinds of expressions, called literal expressions, which are representations of values in scripts.
C H A P T E R 6 Expressions 3. Click the Run button in the Script Editor window. This causes AppleScript to evaluate the expression. 4. Choose Show Result from the Controls menu. The result window displays the result of the evaluation, 7. Variables 6 A variable is a named container in which to store a value. When AppleScript encounters a variable in a statement, it evaluates the variable by getting its value.
C H A P T E R 6 Expressions With the Set command, list the variable name first, followed by the value you want to assign: set myName to "Pegi" With the Copy command, list the value first, followed by the variable name: copy "Pegi" to myName Statements like these that assign values to variables are called assignment statements. The variable name is a series of characters called an identifier.
C H A P T E R 6 Expressions The results of the two types of assignment statements are the same in all cases except when the value being assigned is a list, record, or script object. The Copy command makes a new copy of the list, record, or script object, and the Set command creates a variable that shares data with the original list, record, or script object. For more information, refer to “Data Sharing” on page 154.
C H A P T E R 6 Expressions The “A Reference To” Operator 6 To create a variable whose value is a reference instead of the value of the object specified by a reference, use the A Reference To operator.
C H A P T E R 6 Expressions set myDoc to ref to document "Report" of application "Scriptable Text Editor" set myDoc to ref document "Report" of application "Scriptable Text Editor" After you create a reference with the A Reference To operator, you can use the Contents property to get the value of the object that it refers to. The Contents property is the value of the object specified by a reference.
C H A P T E R 6 Expressions To avoid data sharing for lists, records, and script objects, use the Copy command instead of the Set command. The Copy command makes a copy of the list, record, or script object. Changing the value of the original changes does not change the value of the variable. Here’s an example of using Copy instead of Set to create the variable yourList.
C H A P T E R 6 Expressions Predefined Variables 6 Predefined variables are variables whose values are supplied by AppleScript. You can use them in scripts without setting their values. Predefined variables are global—that is, you can use them anywhere in a script. For a summary of the predefined variables in the AppleScript English language dialect, refer to Appendix A, “The Language at a Glance.
C H A P T E R 6 Expressions Defining Script Properties 6 The syntax for defining a script property is ( prop | property ) propertyLabel : initialValue where propertyLabel is an identifier. The rules for specifying identifiers are listed in “Identifiers” on page 27. initialValue is the value that is assigned to the property when you first run the script that contains the property or when you save it or check its syntax.
C H A P T E R 6 Expressions Finally, recompile the script. (You can do this by making an insignificant change, such as adding a space at the end of a line, and clicking the Check Syntax button.) The value of theCount is set to the initial value in the property definition. The Display Dialog command reports a value of 1. Scope of Script Properties 6 Like the scope of a variable, the scope of a script property determines where else in a script you may refer to the same property ID.
C H A P T E R 6 Expressions returns this result if AppleScript’s text delimiters have not been explicitly changed: "breadmilkbutter10.45" For printing or display purposes, it is usually preferable to set the text delimiters to something that’s easier to read. For example, the script set AppleScript's text item delimiters to {", "} {"bread", "milk", "butter", 10.45} as string returns this result: "bread, milk, butter, 10.
C H A P T E R 6 Expressions on error m number n from f to t partial result p --also reset text item delimiters in case of an error: set AppleScript's text item delimiters to ¬ savedTextItemDelimiters --and resignal the error: error m number n from f to t partial result p end try Reference Expressions 6 References are compound names that refer to objects in applications, the system, or AppleScript. Because each object has a value, a reference can be used to represent a value in a script.
C H A P T E R 6 Expressions When AppleScript executes the statement, it gets the value of the reference word 1 of front document of application "Scriptable Text Editor"—a string—and then coerces it to an integer, if possible. (For information about the Repeat statement, refer to Chapter 7, “Control Statements.” For information about coercions, refer to “Coercing Values” on page 68.) Operations 6 Operations are expressions that use operators to derive values from other values.
C H A P T E R 6 Expressions When evaluating expressions containing operators, AppleScript checks the leftmost operand first. If the operand does not belong to one of the legal classes for the operator, AppleScript coerces it if possible. After coercing the leftmost operand or verifying that it belongs to a legal class, AppleScript checks the rightmost operand and coerces it (if necessary and possible) to be compatible with the leftmost operand.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators Operator Description and And. Binary logical operator that results in true if both the operand to its left and the operand to its right are true. Both of the operands must evaluate to Boolean values. When evaluating expressions containing the And operator, AppleScript checks the leftmost operand first. If its value is false, AppleScript does not evaluate the rightmost operand, because it already knows the expression is false.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators (continued) Operator Description (Option–equal sign) is not isn't isn't equal [to] is not equal [to] doesn't equal does not equal Not equal. Binary comparison operator that results in true if the operand to its left and the operand to its right have different values. The operands can be of any class. The method AppleScript uses to determine equality depends on the class of the operands.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators (continued) Operator Description (Option–less-than sign) <= [is] less than or equal [to] is not greater than isn't greater than does not come after doesn't come after Less than or equal to. Binary comparison operator that results in true if the value of the operand to its left is less than or equal to the value of the operand to its right. Both operands must evaluate to values of the same class.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators (continued) Operator Description does not contain doesn't contain Does not contain. Binary containment operator that results in true if the list, record, or string to its right does not match any part of the list, record, or string to its left. Both operands must evaluate to values of the same class. If they don’t, AppleScript attempts to coerce the operand to the right of the operator to the class of the operand to the left.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators (continued) Operator Description - Minus. Binary or unary arithmetic operator. The binary operator subtracts the number to its right from the number or date to its left. The unary operator makes the number to its right negative. Only integers can be subtracted from dates. AppleScript interprets such an integer as a number of seconds. Class of operands: Date, Integer, Real Class of result: Date, Integer, Real (Option-slash) / Division.
C H A P T E R 6 Expressions Table 6-1 AppleScript operators (continued) Operator Description not Not. Unary logical operator that results in true if the operand to its right is false, and false if the operand to its right is true. Class of operand: Boolean Class of result: Boolean [a] ( ref [to] | reference to ) A Reference To. Unary operator that causes AppleScript to interpret the value to its right as a reference instead of getting its value.
C H A P T E R 6 Expressions CLASS IDENTIFIER Two class identifiers are equal if they are the same identifier. They are not equal if they are different identifiers. CONSTANT Two constants are equal if they are the same. They are not equal if they are different. DATA Two data values are equal if they are the same length in bytes and their bytes are the same (AppleScript does a byte-wise comparison).
C H A P T E R 6 Expressions REAL Two real numbers are equal if they both represent the same real number, even if the formats in which they are expressed are different. For example, the following expression is true. 0.01 is equal to 1e10-2 Two real numbers are not equal if they represent different real numbers. RECORDS Two records are equal if they both contain the same collection of properties and if the values of properties with the same labels are equal.
C H A P T E R 6 Expressions The expression x = y in the following statement is false, because the containers are different. tell document "Intro" of application "Scriptable Text Editor" set x to a reference to word 1 of paragraph 1 set y to a reference to word 1 x = y end tell --result:false When you use references in expressions without the A Reference To operator, the values of the objects specified in the references are used to evaluate the expressions.
C H A P T E R 6 Expressions Note All string comparisons can be affected by Considering and Ignoring statements, which allow you to selectively consider or ignore the case of characters, as well as specific types of characters. For more information, see “Considering and Ignoring Statements” on page 213. ◆ Greater Than, Less Than 6 The Greater Than and Less Than operators work with dates, integers, real numbers, and strings. DATE A date is greater than another date if it represents a later time.
C H A P T E R 6 Expressions "zebra" > "aardvark" are true. A string is less than (comes before) another string if it would appear in a dictionary before the other string. For example, "aardvark" comes before "zebra" and "aardvark" < "zebra" are true. AppleScript uses the ASCII collating sequence to determine a word’s position in an English-language dictionary. The order of the ASCII collating sequence is space!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU VWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
C H A P T E R 6 Expressions the left. In both cases, the items in the two lists must be in the same order. Both Starts With and Ends With work if the operand to the right of the operator is a single value. For example, { "this", "is", 2, "cool" } ends with "cool" and { "this", "is", 2, "cool" } starts with "this" and { "this", "is", 2, "cool" } starts with { "this", "is" } are all true.
C H A P T E R 6 Expressions Contains, Is Contained By 6 The Contains and Is Contained By operators work with lists, records, and strings. LIST A list contains another list if the list to the right of the operator is a sublist of the list to the left of the operator. A sublist is a list whose items appear in the same order and have the same values as any series of items in the other list.
C H A P T E R 6 Expressions RECORD A record contains another record if all the properties in the record to the right of the operator are included in the record to the left, and the values of properties in the record to the right are equal to the values of the corresponding properties in the record to the left.
C H A P T E R 6 Expressions Concatenation 6 The concatenation operator (&) can handle operands of any class. STRING The concatenation of two strings is a string that begins with the characters in the string to the left of the operator, followed immediately by the characters in the string to the right of the operator. AppleScript does not add spaces or other characters between the two strings. For example, "dump" & "truck" returns the string "dumptruck".
C H A P T E R 6 Expressions ALL OTHER CLASSES The concatenation of two operands that are not strings or records is a list whose first item is the value of the operand to the left of the operator, and whose second item is the value of the operand to the right of the operator. If the operands to be concatenated are lists, then the result is a list containing all the items in the list to the left of the operator, followed by all the items in the list to the right of the operator.
C H A P T E R 6 Expressions Table 6-2 Order Operator precedence 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 as Left to right Coercion 7 < > None Comparison 8 = None Equality and inequality 9 not Unary Logical negation 10 and Left to right Logic
C H A P T E R 6 Expressions Date-Time Arithmetic 6 AppleScript supports these operations with the + and - operators on date and time difference values: date + timeDifference --result: date date - date --result: timeDifference date - timeDifference --result: date where date is a date value and timeDifference is an integer value specifying a time difference in seconds.
C H A P T E R 6 Expressions To express a time difference in more convenient form, divide the number of seconds by the appropriate constant: 31449600 / years --result: 1 151200 / days --result: 1.75 To get an integral number of hours, days, and so on, use the div operator: 151200 div days --result: 1 To get the difference, in seconds, between the current time and Greenwich mean time, use the scripting addition command Time to GMT.
C H A P T E R Figure 7-0 Listing 7-0 Table 7-0 7 Control Statements 7 Control statements are statements that control when and how other statements are executed. Most control statements are compound statements—that is, statements that contain other statements. By default, AppleScript executes the statements in a script in sequence, one after the other.
C H A P T E R 7 Control Statements Characteristics of Control Statements 7 Most control statements are compound statements that contain other statements. For example, the If statement if today = last day of theMonth set MonthlyReport to prepareReport(currentMonth) print MonthlyReport end if is a compound statement that contains a Set command and a Print command. Compound statements begin with one or more reserved words, such as if in the example above, that identify the type of compound statement.
C H A P T E R 7 Control Statements You can use a simple statement only when you’re controlling the execution of a single statement (such as return x in the previous example). Tell Statements 7 Tell statements specify the default target, the object to which commands are sent if they do not include a direct parameter. For example, in the following Tell statement, the Close command does not include a direct parameter.
C H A P T E R 7 Control Statements AppleScript uses the Microsoft Excel dictionary for definitions of the Copy command and cell object, and the Scriptable Text Editor dictionary for the definition of the word object. tell application "Microsoft Excel" copy word 5 of document "TestDocument" of application ¬ "Scriptable Text Editor" to Cell "R1C1" of Document ¬ "spreadsheet" end tell AppleScript defines two variables, it and me, that you can use in Tell statements. The variable it is the default target.
C H A P T E R 7 Control Statements AppleScript defines another word, my, that you can use instead of the phrase of me. For example, the following script is equivalent to the previous example: property name : "Script" tell document "Introduction" of application "Scriptable Text Editor" get my name end tell --result: "Script" ¬ If you refer to a property in a Tell statement without using either it or me, AppleScript assumes that you want the property of the default target of the Tell statement.
C H A P T E R 7 Control Statements Note Within tests in Filter references, the direct object is the object being tested, so the variable it refers to the object currently being tested. See “Using the Filter Reference Form” on page 140 for information about the use of it in tests. ◆ Tell (Simple Statement) A simple Tell statement specifies the object to which to send a command.
C H A P T E R 7 Control Statements Tell (Compound Statement) 7 A compound Tell statement specifies the default target of the commands it contains. SYNTAX tell referenceToObject [ statement ]... end [ tell ] where referenceToObject is a reference to an application object, system object, or script object. statement is any AppleScript statement.
C H A P T E R 7 Control Statements NOTES If referenceToObject specifies an application on a remote computer, additional conditions must be met. These conditions are described in “References to Applications,” which begins on page 146. If referenceToObject specifies an application on the same computer that is not running, AppleScript launches the application. If Statements 7 If statements allow you to define statements or groups of statements that are executed only in specific circumstances.
C H A P T E R 7 Control Statements else set myMessage to " is equal to " end if set myResult to (x as string) & myMessage & (y as string) If the expression x > y is true, the value of the variable myMessage is set to " is greater than " and the If statement is finished. Control passes to the Set statement, which uses the value of the variable myMessage to set the value of another variable, called myResult. The value of myResult is a string such as "7 is greater than 5".
C H A P T E R 7 Control Statements else --anything greater than 9 display dialog "You will need to file an extra form." end if The example shows how you can create a more complex Boolean expression with the help of Boolean operators, such as the And operator. The expression dependents < 9 and audit = false has two Boolean expressions as operands (dependents < 9, audit = false). If both expressions are true, the value of the entire expression is true.
C H A P T E R 7 Control Statements If (Compound Statement) 7 A compound If statement contains one or more Boolean expressions and groups of statements to be executed if the value of the corresponding Boolean expression is true. SYNTAX if Boolean [ then ] [ statement ]... [ else if Boolean [ then ] [ statement ]...]... [ else [ statement ]...] end [ if ] where Boolean is an expression whose value is true or false. statement is any AppleScript statement.
C H A P T E R 7 Control Statements Repeat Statements 7 Repeat statements are used to create loops, or groups of repeated statements, in scripts. There are several types of Repeat statements, which differ in the way they specify when the repetition stops.
C H A P T E R 7 Control Statements Here’s an example of a Repeat statement with an Exit statement: tell application "Scriptable Text Editor" set numberOfWindows to (count windows) set i to 1 repeat if i > numberOfWindows then exit end if print window i set i to i + 1 end repeat end tell More elaborate forms of the Repeat statement use looping variables that you can refer to in the body of the loop.
C H A P T E R 7 Control Statements Note that two of the strings in the preceding statement include a return character. These are valid strings even though the surrounding quotation marks are on different lines within the statement. Running the preceding statement results in the following text: David Numberman's Top 10 Numbers for Lists 1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 10.
C H A P T E R 7 Control Statements Repeat (forever) 7 The Repeat (forever) form of the Repeat statement is an infinite loop. The only way to exit the loop is by using an Exit statement. SYNTAX repeat [ statement ]... end [ repeat ] where statement is any AppleScript statement. This is an infinite loop; you must use an Exit statement to exit the loop (see page 204). EXAMPLE The following example numbers the paragraphs of a document.
C H A P T E R 7 Control Statements Repeat (number) Times The Repeat (number) Times form of the Repeat statement repeats a group of statements a specified number of times. SYNTAX repeat integer [ times ] [ statement ]... end [ repeat ] where integer is an integer that specifies the number of times to repeat the statements in the body of the loop. The word times after integer is optional. statement is any AppleScript statement.
C H A P T E R 7 Control Statements Repeat While 7 The Repeat While form of the Repeat statement repeats a group of statements as long as a particular condition, specified in a Boolean expression, is met. SYNTAX repeat while Boolean [ statement ]... end [ repeat ] where Boolean is an expression whose value is true or false. The statements in the loop are repeated until Boolean becomes false. If Boolean is false when entering the loop, the statements in the loop are not executed.
C H A P T E R 7 Control Statements Repeat Until 7 The Repeat Until form of the Repeat statement repeats a group of statements until a particular condition, specified in a Boolean expression, is met. SYNTAX repeat until Boolean [ statement ]... end [ repeat ] where Boolean is an expression whose value is true or false. The statements in the loop are repeated until Boolean becomes true. If Boolean is true when entering the loop, the statements in the loop are not executed.
C H A P T E R 7 Control Statements Repeat With (loopVariable) From (startValue) To (stopValue) 7 In the Repeat With (loopVariable) From (startValue) To (stopValue) form of the Repeat statement, the looping variable is an integer that is increased by a specified value after each iteration of the loop. The loop terminates when the value of the variable is greater than a predefined stop value. SYNTAX repeat with loopVariable from startValue to stopValue [ by stepValue ] [ statement ]...
C H A P T E R 7 Control Statements NOTES You can use an existing variable as the looping variable in a Repeat statement or define a new one in the Repeat statement. You cannot change the value of the looping variable in the loop body. The variable is undefined after the loop has been executed, but you can redefine it outside the loop. AppleScript evaluates startValue, stopValue, and stepValue when it begins executing the loop and stores the values internally.
C H A P T E R 7 Control Statements reference paragraphs (the paragraphs of document "List") is a list of the paragraphs in the document. tell document "List" set paragraphNum to 1 repeat with n in paragraphs set paragraph paragraphNum to (paragraphNum as string) & " " & contents of n set paragraphNum to paragraphNum + 1 end repeat end tell NOTES You can use an existing variable as the looping variable in a Repeat statement or define a new one in the Repeat statement.
C H A P T E R 7 Control Statements Exit 7 An Exit statement is used in a Repeat statement to exit the Repeat statement. When AppleScript executes an Exit statement, it terminates loop execution and resumes execution with the next statement following the Repeat statement. You cannot use Exit statements outside of Repeat statements.
C H A P T E R 7 Control Statements which is an integer that identifies the error, an error expression, which is an expression, usually a string, that describes the error, and other information. To handle error messages, scripts can include error handlers. Error handlers are contained in compound statements, called Try statements, that define the scope of the error handlers they contain. If an error message occurs and there is no handler for it, script execution stops.
C H A P T E R 7 Control Statements ■ Script errors are error messages sent by a script using the Error command. Scripts that define additional errors will often include descriptions of the errors in their documentation. Note Many “errors” are the result of the normal operation of a command. For example, the Choose File command returns error –128 if the user presses the Cancel button in the resulting dialog box. Scripts must routinely handle such errors to ensure normal operation.
C H A P T E R 7 Control Statements The error handler can include up to five parameter variables (also called formal parameters) that represent the actual information sent in the error message when the error occurs. When the error handler is called, the parameter variables become local variables in the error handler. Try 7 A Try statement is a compound statement consisting of a list of AppleScript statements followed by an error handler to be executed if any of the statements cause an error message.
C H A P T E R 7 Control Statements offendingObjectVariable (an identifier) is a parameter variable for the reference to the application or object that caused the error (a reference). You use this parameter variable to refer to the object that caused the error within the error handler. resultListVariable (an identifier) is a parameter variable for the results for objects that were handled before the error occurred. Its value is a list that can contain values of any class.
C H A P T E R 7 Control Statements on error errText number errNum display dialog "An error has occurred: " & errText & "\rDo you want to continue " & "using the default file?" buttons {"Cancel", "Continue"} default button 1 if button returned of result = "Cancel" error number -128 --quit silently else display dialog "The script will continue " & "using the default file.
C H A P T E R 7 Control Statements Signaling Errors in Scripts 7 A script can signal an error—which can then be handled by an error handler— with the Error command. This allows scripts to define their own messages for errors that occur within the script. Error 7 The Error command signals an error in a script.
C H A P T E R 7 Control Statements resultList applies only to commands that return results for multiple objects. If results for some, but not all, of the objects specified in the command are available, you can include them in the partial result parameter. If you do not include a partial result parameter, an empty list ({}) is passed to the error handler. expectedType is a class identifier.
C H A P T E R 7 Control Statements You can use the Error command to resignal an error. For example, in the following Try statement, the Error command in the error handler resignals the error exactly as it was received. try word 5 of "one two three" on error number errNum from badObj --statements that handle the error error number errNum from badObj end try In the following Try statement, the Error command in the error handler resignals the error, but changes the error message and error number.
C H A P T E R 7 Control Statements Considering and Ignoring Statements 7 Considering statements allow you to control the way AppleScript executes operations and commands by listing specific characteristics, called attributes, to be taken into account as the operations and commands are executed. Ignoring statements work the same way, except that you list specific attributes to be ignored.
C H A P T E R 7 Control Statements Considering/Ignoring Considering and Ignoring statements cause AppleScript to consider or ignore specific characteristics, called attributes, as it executes groups of statements. SYNTAX considering attribute [, attribute ... and attribute ] [ but ignoring attribute [, attribute ... and attribute ] ] [ statement ]... end considering ignoring attribute [, attribute ... and attribute ] [ but considering attribute [, attribute ... and attribute ] ] [ statement ]...
C H A P T E R 7 Control Statements diacriticals: Diacritical marks (such as ´, `, ˆ, ¨, and ˜) are considered in string comparisons. If this attribute is ignored, "résumé" is considered equal to "resume", and so on. hyphens: In string comparisons, hyphenated words are considered different from their nonhyphenated counterparts. If this attribute is ignored, the strings are compared as if any hyphens were not present; for example "anti-war" would be considered equal to "antiwar".
C H A P T E R 7 Control Statements ignoring punctuation if "this !,:book" = "this book" then (* additional statements *) end if end ignoring NOTES The case, white space, diacriticals, hyphens, expansion, and punctuation considerations apply only to comparisons performed by AppleScript.
C H A P T E R 7 Control Statements ignoring case if "This or that" = "thisorthat" then beep 2 --false ignoring white space if "This or that" = "thisorthat" then beep 1 --true end ignoring end ignoring With Timeout Statements 7 When AppleScript sends a command to an application, it normally waits for the command to complete execution before continuing with the rest of the script.
C H A P T E R 7 Control Statements With Timeout With Timeout statements let you change how long AppleScript can wait before stopping execution of application and scripting addition commands that are sent to other applications. SYNTAX with timeout [ of ] integer second[s] [ statement ]...
C H A P T E R 7 Control Statements With Transaction Statements 7 Some applications, such as databases, support the notion of a transaction— that is, a sequence of related events that should be performed as if they were a single operation. The With Transaction statement allows you to specify transactions for such applications.
C H A P T E R 7 Control Statements EXAMPLES This example uses a With Transaction statement to ensure that a record can be modified by one user without being modified by another user at the same time.
C H A P T E R Figure 8-0 Listing 8-0 Table 8-0 8 Handlers 8 Handlers are collections of statements that are executed in response to commands or error messages.
C H A P T E R 8 Handlers Here’s a subroutine, called minimumValue, that returns the smaller of two values: --minimumValue subroutine: on minimumValue(x, y) if x y then return x else return y end if end minimumValue --how to call minimumValue: minimumValue(5, 105) The first line of the minimumValue subroutine specifies the parameters of the subroutine.
C H A P T E R 8 Handlers Types of Subroutines 8 There are two types of subroutines: those with labeled parameters and those with positional parameters. ■ ■ Labeled parameters are identified by their labels and can be listed in any order. Subroutines with labeled parameters can also have a direct parameter. The direct parameter, if present, must be listed first. Positional parameters must be listed in a specific order, which is defined in the subroutine definition.
C H A P T E R 8 Handlers Scope of Subroutine Calls in Tell Statements 8 If you need to call a subroutine from within a Tell statement, you must use the reserved words of me or my to indicate that the subroutine is part of the script—not a command that should be sent to the object of the Tell statement. For example, the minimumValue subroutine call in the following Tell statement is unsuccessful, because AppleScript sends the minimumValue command to the Scriptable Text Editor.
C H A P T E R 8 Handlers Checking the Classes of Subroutine Parameters 8 You cannot specify the class of a parameter in a subroutine definition. You can, however, get the value of the Class property of a parameter and check it to see if the parameter belongs to the correct class. If it doesn’t, you may be able to coerce it with the As operator, or failing that, you can return an error. (For information about coercing values, see Chapter 6, “Expressions.
C H A P T E R 8 Handlers To generate 10 factorial, the subroutine factorial is called once from the top level of the script, and then calls itself ten more times, until the value of x is 0. When x is equal to 0, AppleScript skips to the Else clause and finishes executing all the partially executed subroutines, including the original factorial subroutine call.
C H A P T E R 8 Handlers --the factorial() subroutine returns the factorial of a number on factorial(x) if x > 0 then return x * (factorial(x - 1)) else return 1 end if end factorial --the min() subroutine returns the smallest number in a list on min(numberList) if class of numberList list or numberList = {} then return numberList if length of numberList = 1 then return item 1 of numberList copy item 1 of numberList to frontNumber copy length of numberList to listLength copy min(items 2 thru listLeng
C H A P T E R 8 Handlers the example calls the factorial subroutine. (You must have a compiled script called Numeric Operations in the specified location for this script to work correctly.) set NumberLib to (load script file "MacHD:Scripts:Numeric Operations") tell NumberLib factorial(10) end tell Note The Load Script scripting addition command loads the compiled script as a script object. For a definition of Load Script, see the AppleScript Scripting Additions Guide.
C H A P T E R 8 Handlers Subroutines With Labeled Parameters 8 This section describes the syntax for defining and calling subroutines with labeled parameters. Examples of subroutines that use this syntax begin on page 232. Subroutine Definition, Labeled Parameters 8 The definition for a subroutine with labeled parameters lists the labels to use when calling the subroutine and the statements to be executed when it is called.
C H A P T E R 8 Handlers subroutineParamLabel is one of the following labels: above, against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto, out of, over, thru (or through), under. These labels are the only labels that can be used without the special label given. As in other commands, each label must be unique among the labels for the subroutine (that is, you cannot use the same label for more than one parameter).
C H A P T E R 8 Handlers SYNTAX subroutineName [ [ of | in ] directParameter ] [ [ subroutineParamLabel parameterValue ] | [ with labelForTrueParam [, labelForTrueParam ]... [ ( and | or | , ) labelForTrueParam ] ] | [ without labelForFalseParam [, labelForFalseParam ]...] [ ( and | or | , ) labelForFalseParam ] ] | [ given label:parameterValue [, label:parameterValue ]...] ]... ¬ ¬ ¬ ¬ ¬ ¬ ¬ ¬ where subroutineName (an identifier) is the name of the subroutine.
C H A P T E R 8 Handlers If you use or or a comma instead of and with the last parameter of a with clause, AppleScript changes the or or the comma to and during compiling. NOTES A subroutine call must include all the parameters specified in the subroutine definition. There is no way to specify optional parameters.
C H A P T E R 8 Handlers The following subroutine converts inches to centimeters: on CentimeterConversion from x --make sure the parameter is a real number or an integer if class of x is contained by {integer, real} return x * 2.54 else error "The parameter must be a real number or an integer" end if end CentimeterConversion --to call CentimeterConversion: CentimeterConversion of 36 The following subroutine searches for a specific string in a list of files.
C H A P T E R 8 Handlers The following subroutine uses the special label given to define a parameter with the label rounding. By using verb forms ending with “ing” as labels, you can often make subroutine calls easier to read. to findNumbers of numberList above minLimit given rounding:roundBoolean set resultList to {} repeat with i from 1 to (count items of numberList) set x to item i of numberList if roundBoolean = true then copy (x + 0.
C H A P T E R 8 Handlers The statement rock around the current date later in the same script displays the current date in a dialog box. Here’s another example of the use of subroutine parameter labels: to check for yourNumber from bottom thru top if bottom yourNumber and yourNumber top then display dialog "Congratulations! You scored." end if end check The statement check for 8 from 7 thru 10 later in the same script displays the specified dialog box.
C H A P T E R 8 Handlers SYNTAX ( on | to ) subroutineName ( [ paramVariable [, paramVariable ]...] ) [ global variable [, variable ]...] [ local variable [, variable ]...] [ statement ]... end [ subroutineName ] where subroutineName (an identifier) is the name of the subroutine. paramVariable (an identifier) is a parameter variable for the actual value of the parameter. You use this identifier to specify the parameter in the body of the subroutine.
C H A P T E R 8 Handlers SYNTAX subroutineName ( [ parameterValue [, parameterValue ]...] ) where subroutineName (an identifier) is the name of the subroutine. parameterValue is the value of a parameter, which can be any valid expression. If there are two or more parameters, they must be listed in the same order in which they were specified in the subroutine definition. The parentheses that enclose the series of positional parameters are a required part of the language.
C H A P T E R 8 Handlers Examples of Subroutines With Positional Parameters 8 Here is a subroutine that returns the minimum value of a pair of values followed by an example of how to call the subroutine. on minimumValue(x, y) if x y then return x else return y end if end minimumValue minimumValue(21, 40000) You can also define a subroutine whose positional parameters define a pattern to match when calling the subroutine.
C H A P T E R 8 Handlers A parameter pattern can be much more complex than a single list. The handler in the next example takes two numbers and a record whose properties include a list of bounds and displays a dialog box summarizing some of that information: on hello(a, b, {length:l, bounds:{x, y, w, h}, name:n}) set q to a b set response to "Hello " & n & ", you are " & l & ¬ " inches tall and occupy position (" & x & ", " & y & ").
C H A P T E R 8 Handlers at the place in the script where the handler was called, using the value returned as the value of the handler. SYNTAX return expression where expression is an AppleScript expression. When AppleScript executes a Return statement, it returns the value of the expression. Expressions are described in Chapter 6, “Expressions.” EXAMPLE To return a value and exit a subroutine, include a Return statement in the body of the subroutine.
C H A P T E R 8 Handlers Command Handlers 8 Command handlers are handlers for application commands. They are similar to subroutine handlers, but instead of defining responses to user-defined commands, they define responses to application commands, such as Open, Print, or Move, sent to application objects. You define command handlers in scripts, but they handle commands that are sent to application objects.
C H A P T E R 8 Handlers SYNTAX The syntax for a command handler definition is ( on | to ) commandName [ [ of ] directParameterVariable ] [ given label:paramVariable [, label:paramVariable ]...] [ global variable [, variable ]...] [ local variable [, variable ]...] [ statement ]... end [ commandName ] ¬ ¬ where commandName (an identifier) is a command name. directParameterVariable (an identifier) is a parameter variable for the actual value of the direct parameter.
C H A P T E R 8 Handlers Command Handlers for Script Applications 8 Getting Started With AppleScript describes how you can use the Script Editor to save a script as a script application. A script application is a script that you can run from the Finder much like any other application. If you save a script as a stay-open application, it stays open after it runs; if you don’t, it quits right after it runs.
C H A P T E R 8 Handlers running, the Finder launches the application and sends it a Run command. The application responds by performing the actions the user expects when the application first opens, such as opening an untitled document. Like any other application, a script application receives a Run command whenever one of the actions just listed occurs. You can provide a handler for the Run command in a couple of ways.
C H A P T E R 8 Handlers The script in the preceding example behaves exactly the same way if you rewrite it with an explicit Run handler, like this: property x : 0 on run increment() tell document ¬ "Count Log" of application "Scriptable Text Editor" set selection to "Count is now " & x & "." & return end tell end run on increment() set x to x + 1 display dialog "Count is now " & x & ".
C H A P T E R 8 Handlers By default, a startup screen appears before the script runs. The user must click the startup screen’s Run button or press the Return key before the Finder actually sends the Run command. This allows the user to read the description of the script before running it. If the Never Show Startup Screen checkbox is selected in the Script Editor’s Save As dialog box when the script application is created, the script runs immediately without displaying the startup screen.
C H A P T E R 8 Handlers Files, folders, or disks are not moved, copied, or affected in any way when their icons are dragged and dropped over a script application’s icon. The Finder just gets a list of their identities and sends that list to the script application as the direct parameter of the Open event. Of course, the script in the script application could easily tell the Finder to move, copy, or otherwise manipulate them.
C H A P T E R 8 Handlers Idle Handlers 8 If a stay-open script application includes an Idle handler, AppleScript sends the script application periodic Idle commands whenever it’s not responding to incoming events. The statements in the handler run periodically (every 30 seconds, by default).
C H A P T E R 8 Handlers Quit Handlers 8 AppleScript sends a stay-open script application a Quit command whenever the user chooses the Quit menu command or presses Command-Q while the application is active. If the script includes a Quit handler, the statements in the handler are run before the application quits. A Quit handler can be used to set script properties, tell another application to do something, display a dialog box, or perform almost any other task.
C H A P T E R 8 Handlers Interrupting a Script Application’s Handlers 8 A stay-open script application handles incoming commands even if it is already running a handler in response to a previous command. This means that execution of a handler can be interrupted while another handler is run. Because script applications are not multitasking, execution of the first handler halts until the second one finishes.
C H A P T E R 8 Handlers Calling a Script Application 8 As previously mentioned, any script can send commands to a script application just as it can to any other application. However, script applications, like other applications, sometimes respond to the Run command in ways that you might not expect.
C H A P T E R 8 Handlers Similarly, to launch a non-stay-open application and run its Open Handler, use a Launch command followed by an Open command, like this: tell application "NonStayOpen" launch open {alias "HardDisk:MyFile", ¬ alias "HardDisk:MyOtherFile"} end tell For example, if the Open handler on page 246 were saved as a script application called “NonStayOpen,” the script in the preceding example would cause the handler to create a list of the two specified pathnames.
C H A P T E R 8 Handlers You can declare a property and set its initial value using a statement like this: property x: 3 The scope of a property declaration can be either a script object or an entire script. The value set by a property declaration is not reset each time the script is run; instead, it persists until the script is recompiled.
C H A P T E R 8 Handlers Scope of Properties and Variables Declared at the Top Level of a Script 8 Figure 8-1 summarizes the scope of properties and variables declared at the top level of a script. Sample scripts using each form of declaration follow.
C H A P T E R 8 Handlers example accomplishes the same thing as the previous example, except that it uses a global variable instead of a property to keep track of the count. global theCount increment() on increment() try set theCount to theCount + 1 display dialog "Count is now " & theCount & "." on error set theCount to 1 display dialog "Count is now 1.
C H A P T E R 8 Handlers Each time the on increment handler is called within the script, the global variable theCount increases by 1. However, when you run the entire script again, theCount is reset to 1. In the absence of a global variable declaration at the top level of a script, the scope of a variable declaration using the Set command at the top level of a script is normally restricted to the Run handler for the script.
C H A P T E R 8 Handlers to theCount in any other handler in the script are local to that handler unless the handler also explicitly declares theCount as a global. This kind of global declaration is discussed in more detail in the sections that follow.
C H A P T E R 8 Handlers Scope of Properties and Variables Declared in a Script Object 8 You should be familiar with Chapter 9, “Script Objects,” before you read this section. Figure 8-2 summarizes the scope of properties and variables declared at the top level of a script object. Sample scripts using each form of declaration follow.
C H A P T E R 8 Handlers The scope of a property declaration at the top level of a script object doesn’t extend beyond the script object. Thus, it is possible to use the same identifier in different parts of a script to refer to different properties, as this example demonstrates:.
C H A P T E R 8 Handlers The preceding example first sets the value of theCount at the top level of the script. When AppleScript encounters the theCount variable within the on increment handler, it first looks for an earlier occurrence within the handler, then at the top level of the script Joe. When AppleScript encounters the global declaration for theCount at the top level of script object Joe, it continues looking at the top level of the script until it finds the original declaration for theCount.
C H A P T E R 8 Handlers run Norah --result: 1 run Norah --result: 2 theCount --result: 2 theCount of Norah --result: 20 This script declares two separate theCount properties: one at the top level of the script and one at the top level of the script object Norah. Because the script Joe declares the global variable theCount, AppleScript looks for theCount at the top level of the script, thus treating Joe’s theCount and theCount at the top level of the script as the same variable.
C H A P T E R 8 Handlers The scope of a variable declaration using the Set command at the top level of a script object is limited to the Run handler: script Joe set theCount to 10 on increment() global theCount set theCount to theCount + 2 end increment return theCount end script tell Joe to increment() --error: "The variable theCount is not defined.
C H A P T E R 8 Handlers Scope of Variables Declared in a Handler 8 You can’t declare a property in a handler, although you can refer to a property declared at the top level of the script or script object to which the handler belongs. Figure 8-3 summarizes the scope of variables declared in a handler. Examples of each form of declaration follow.
C H A P T E R 8 Handlers The scope of a variable declaration using the Set command within a handler is limited to that handler: script Henry set theCount to 10 on increment() set theCount to 5 end increment return theCount end script tell Henry to increment() --result: 5 run Henry --result: 10 The scope of the first declaration of the first theCount variable, at the top level of the script object Henry, is limited to the Run handler for the script object.
C H A P T E R Figure 9-0 Listing 9-0 Table 9-0 9 Script Objects 9 Script objects are objects that you define and use in scripts. Like the application and system objects described earlier in this manual, script objects have properties and can respond to commands. Unlike application or system objects, script objects are defined within scripts. This chapter describes how to define and use script objects.
C H A P T E R 9 Script Objects Here is a simple script object definition: script John property HowManyTimes : 0 to sayHello to someone set HowManyTimes to HowManyTimes + 1 return "Hello " & someone end sayHello end script It defines a script object that can handle the sayHello command. It assigns the script object to the variable John. The definition includes a handler for the sayHello command.
C H A P T E R 9 Script Objects Defining Script Objects 9 Each script object definition begins with the keyword script, followed by an optional variable name, and ends with the keyword end (or end script). The statements in between can be any combination of property definitions, handler definitions, and other AppleScript statements. The syntax of a script object definition is script [ scriptObjectVariable ] [( property | prop ) propertyLabel : initialValue ]... [ handlerDefinition ]... [ statement ]...
C H A P T E R 9 Script Objects Sending Commands to Script Objects 9 You use Tell statements to send commands to script objects. A Tell statement sent to a script object is similar to a Tell statement sent to an application, except that it uses a variable name, instead of a reference, to identify the script object. For example, tell John sayHello to "Herb" sayHello to "Grace" end tell sends two sayHello commands to the script object John.
C H A P T E R 9 Script Objects handler and property definitions, and does not include any additional top-level statements, the definition may include an explicit Run handler that begins with on run. If a script object definition includes neither an implicit Run handler (in the form of top-level statements) nor an explicit Run handler, the Run command doesn’t do anything. (For more information about Run handlers, see “Command Handlers for Script Applications,” which begins on page 243.
C H A P T E R 9 Script Objects script object. For example, the makePoint handler in the following script contains a script object definition for the script object point: on makePoint(x, y) script point property xCoordinate:x property yCoordinate:y end script return point end makePoint set myPoint to makePoint(10,20) get xCoordinate of myPoint get yCoordinate of myPoint AppleScript initializes the script object point when it executes the makePoint command.
C H A P T E R 9 Script Objects Note The distinction between defining a script object and initializing a script object is similar to the distinction between a class and an instance in object-oriented design. When you define a script object, you define a class of objects that respond to the same commands. When AppleScript initializes a script object, it creates an instance of the class.
C H A P T E R 9 Script Objects The syntax for defining a parent script object is ( property | prop ) parent : variable where variable is a variable that contains the parent script object. A script object must be initialized before it can be assigned as a parent of another script object. This means that the definition of the parent script object (or a command that calls a function that creates the parent script object) must come before the definition of the child in the same script.
C H A P T E R 9 Script Objects Figure 9-1 Relationship between a simple child script and its parent script John property HowManyTimes : 0 to sayHello to someone set HowManyTimes to HowManyTimes + 1 return "Hello " & someone end sayHello end script parent script Simple property parent : John end script Figure 9-2 script Simple property HowManyTimes : 0 to sayHello to someone set HowManyTimes to HowManyTimes + 1 return "Hello " & someone end sayHello end script Another child-parent relationship scrip
C H A P T E R 9 Script Objects "Hello Emily". However, the correct result is "Hello Andrew", as you can see in Figure 9-3.
C H A P T E R 9 Script Objects Even though script X in Figure 9-3 sends itself the getName command, the command is intercepted by the child script, which substitutes its own version of the getName handler. AppleScript always maintains the first target of a command as the “self” to which inherited commands are sent, redirecting to the child any inherited commands the parent sends to itself. The relationship between a parent script object and its child script objects is dynamic.
C H A P T E R 9 Script Objects tell JohnSon to changeVegetable() Vegetable of John --result: "Zucchini" When you change the Vegetable property of script object JohnSon to "Zucchini" with the changeVegetable command, the Vegetable property of script object John also changes.
C H A P T E R 9 Script Objects The Continue Statement 9 Normally, if a child script object and its parent both have handlers for the same command, the child uses its own handler. However, the handler in a child script object can handle a command first, and then use a Continue statement to call the handler for the same command in the parent. The use of a Continue statement to call a handler in a parent script object is called delegation.
C H A P T E R 9 Script Objects The following script includes two script object definitions similar to those shown in Figure 9-1 on page 273. The first, Elizabeth, works just like the script John in the figure. The second, ChildOfElizabeth, includes a handler with a Continue statement that is not included in the child script object (Simple) shown in the figure.
C H A P T E R 9 Script Objects Note The reserved word my in the statement if my HowManyTimes > 10 in the previous example is required to indicate that HowManyTimes is a property of the script object. Without the word my, AppleScript assumes that HowManyTimes is an undefined local variable. ◆ A Continue statement can change the parameters of a command before delegating it. For example, suppose the following script object is defined in the same script as the preceding example.
C H A P T E R 9 Script Objects script Andrea property parent : Hugh on identify() continue identify() end identify end script tell Hugh to identify() --result: <