# Applescript
> Scripting allows you to automate complex, repetitive, and time-consuming tasks by writing scripts that interact with apps, processes, and the operating system. A script consists of a series of stateme
---
# Mac Automation Scripting Guide: About Mac Scripting
## About Mac Scripting
Scripting allows you to automate complex, repetitive, and time-consuming tasks by writing scripts that interact with apps, processes, and the operating system. A script consists of a series of statements, each of which performs a specific operation. These statements work together to automate tasks. Through scripting, you can create powerful workflow solutions that enhance productivity, reduce errors, save time, and save money.
There are many different scripting languages. On the Mac, the primary ones used for automation areAppleScriptandJavaScript.
Note
OSÂ X also includes Automator, an app for building workflows that run prebuilt, configurable actions to perform tasks in apps and throughout the operating system. Automator doesnât require you to write any code, but can be extended through scripting. Because Automator uses preconceived actions and operates in a linear manner, itâs more limited in functionality than scripting. Automator is great for performing simple tasks involving a small number of sequential steps or apps. Scripting is a better choice for performing advanced, branching, or complex tasks.
Python and Perl are other examples of scripting languages.
### AppleScript
AppleScript is a mature scripting language developed by Apple. Itâs relatively easy to learn in relation to other scripting and programming languages, has been around since System 7.1, and has been widely adopted in both enterprise and personal workflows. While the AppleScript scripting language uses an English-like terminology which may appear simple, it is a rich, object-oriented language, capable of performing complicated programming tasks.
The core fundamentals of AppleScript are described inAppleScript Language Guide, as well as in numerous third-party books.
### JavaScript
JavaScript is a popular cross-platform scripting language. Historically, itâs been most commonly used to implement features on websites and in web-based apps that are accessed through browsers. However, some apps implement JavaScript-based scripting models for the purpose of automation. In OSÂ X 10.10, JavaScript became a peer to AppleScript in OSÂ X. There are many third-party websites and books that document the JavaScript language.
For fundamentals on JavaScript as a scripting language for automation in OSÂ X, seeJavaScript for Automation Release Notes. For information about the JavaScript language, seeMozillaâs official JavaScript documentation.
How Mac Scripting Works
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Working with XML
## Working with XML
The XML Suite of the System Events scripting dictionary defines several classes that make it quick and easy to read and parse XML data. TheXML fileclass represents any text file containing structured XML like the example data shown inListing 36-1.
-
-
- The Secret Lives of Cats
- Feline Press
-
-
At the top level, an XML file contains anXML dataobject thatâs comprised of nestedXML elementobjects. EachXML elementobject has anameand avalueproperty, and may also containXML attributeobjects that define additional metadata. The example code inListing 36-2demonstrates how to access these classes to read and parse the contents of an XML file on the Desktop that contains the XML data fromListing 36-1.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell XML file "~/Desktop/Book Data.xml"
- tell XML element "books"
- set theBookElements to every XML element whose name = "book"
- --> {XML element 1 of XML element 1 of contents of XML file "Macintosh HD:Users:YourUserName:Desktop:Book Data.xml" of application "System Events"}
- repeat with a from 1 to length of theBookElements
- set theCurrentBookElement to item a of theBookElements
- --> XML element 1 of XML element 1 of contents of XML file "Macintosh HD:Users:YourUserName:Desktop:Book Data.xml" of application "System Events"
- tell theCurrentBookElement
- name of theCurrentBookElement
- --> "book"
- name of every XML element
- --> {"name", "publisher"}
- name of every XML attribute
- --> {"country"}
- value of every XML attribute
- --> {"US"}
- set theBookName to value of XML element "name"
- --> "The Secret Lives of Cats"
- set thePublisher to value of XML element "publisher"
- --> "Feline Press"
- end tell
- end repeat
- end tell
- end tell
- end tell
Working with Property List Files
Automating the User Interface
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Removing HTML Markup from Text
## Removing HTML Markup from Text
When parsing HTML content, itâs often necessary to remove markup entirely. The handler inListing 34-1removes all HTML tags from the text provided, returning only the remaining textâthe contents of the tags.
APPLESCRIPT
Open in Script Editor
- on removeMarkupFromText(theText)
- set tagDetected to false
- set theCleanText to ""
- repeat with a from 1 to length of theText
- set theCurrentCharacter to character a of theText
- if theCurrentCharacter is "<" then
- set tagDetected to true
- else if theCurrentCharacter is ">" then
- set tagDetected to false
- else if tagDetected is false then
- set theCleanText to theCleanText & theCurrentCharacter as string
- end if
- end repeat
- return theCleanText
- end removeMarkupFromText
Listing 34-2shows how to call the handler inListing 34-1.
APPLESCRIPT
Open in Script Editor
- set theText to "This is a great time to own a Mac!"
- removeMarkupFromText(theText)
- --> Result: "This is a great time to own a Mac!"
Parsing HTML
Working with Property List Files
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Displaying Progress
## Displaying Progress
Many scripts perform large and time-consuming processing operations. All too often, they do this invisibly; they simply run and the user has no idea how long processing will take. A more user-friendly approach is to provide progress information during script operation. At a basic level, this can be done by displaying periodic dialogs or notifications. SeeDisplaying Dialogs and AlertsandDisplaying Notifications. At a complex level, this can be done by designing a fully-custom interface that provides processing feedback.
AppleScript and JavaScript can also report progress graphically and textually. For script apps, this progress reporting takes the form of a dialog window containing a progress bar, descriptive text, and a Stop button. SeeFigure 30-1.
For scripts running in Script Editor, this progress reporting appears at the bottom of the script window. SeeFigure 30-2.
For scripts running from the systemwide script menu, this progress reporting appears in the menu bar, beneath a temporarily displayed gear icon. SeeFigure 30-3.
AppleScript has several language-level properties and JavaScript has aProgressobject with properties that are used to produce this type of progress reporting. SeeTable 30-1.
AppleScript Property
JavaScript Property
Value Type
Description
progress total steps
Progress.totalUnitCount
Integer
Configures the total number of steps to be reported in the progress. For example, if the script will process 5 images, then the value forprogress total stepswould be5.
progress completed steps
Progress.completedUnitCount
Integer
Configures the number of steps completed so far. For example, if the script has processed 3 of 5 images, then the value ofprogress completed stepswould be3.
progress description
Progress.description
Integer
Text to display when reporting progress. Use this is an opportunity to let the user know whatâs happening. For example, it could indicate that images are being processed.
progress additional description
Progress.additionalDescription
Integer
Additional text to display when reporting progress. Use this is an opportunity to provide even more detailed information about whatâs happening. For example, it could indicate the specific task being performed, and how much more processing is remaining.
Listing 30-1andListing 30-2demonstrate how these properties can be used to provide progress information while processing a set of images.
APPLESCRIPT
Open in Script Editor
- set theImages to choose file with prompt "Please select some images to process:" of type {"public.image"} with multiple selections allowed
- -- Update the initial progress information
- set theImageCount to length of theImages
- set progress total steps to theImageCount
- set progress completed steps to 0
- set progress description to "Processing Images..."
- set progress additional description to "Preparing to process."
- repeat with a from 1 to length of theImages
- -- Update the progress detail
- set progress additional description to "Processing image " & a & " of " & theImageCount
- -- Process the image
- -- Increment the progress
- set progress completed steps to a
- -- Pause for demonstration purposes, so progress can be seen
- delay 1
- end repeat
- -- Reset the progress information
- set progress total steps to 0
- set progress completed steps to 0
- set progress description to ""
- set progress additional description to ""
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var images = app.chooseFile({
- withPrompt: "Please select some images to process:",
- ofType: ["public.image"],
- multipleSelectionsAllowed: true
- })
- // Update the initial progress information
- var imageCount = images.length
- Progress.totalUnitCount = imageCount
- Progress.completedUnitCount = 0
- Progress.description = "Processing Images..."
- Progress.additionalDescription = "Preparing to process."
- for (i = 0; i < imageCount; i++) {
- // Update the progress detail
- Progress.additionalDescription = "Processing image " + i + " of " + imageCount
- // Process the image
- // Increment the progress
- Progress.completedUnitCount = i
- // Pause for demonstration purposes, so progress can be seen
- delay(1)
- }
Clicking the Stop button in a progress dialog results in a user cancelled error.
For additional information, seeProgress ReportinginAppleScript Release NotesandProgressinJavaScript for Automation Release Notes.
Note
Thereâs no need to call a dedicated command to actually display progress information. The act of setting values for the progress properties mentioned above automatically results in progress information being displayed in a dialog, Script Editor, or the menu bar.
Prompting for a Color
Converting RGB to HTML Color
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Creating a Script
## Creating a Script
Generally, most scripts are written in Script Editor documents. Scripts can also be written in Xcode, but this is typically for scripts that require advanced user interfaces.
- Launch Script Editor in/Applications/Utilities/.
Launch Script Editor in/Applications/Utilities/.
- Press Command-N or select File > New.
Press Command-N or select File > New.
- If the script isnât configured for the correct language, choose the language in the navigation bar.TipIf you always use the same language, set it as the default language in the General pane of Script Editor preferences. SeeGeneral Preferences.
If the script isnât configured for the correct language, choose the language in the navigation bar.
If you always use the same language, set it as the default language in the General pane of Script Editor preferences. SeeGeneral Preferences.
- Write your script code in the editing area. Newly written code is uncompiled and formatted as new text.
Write your script code in the editing area. Newly written code is uncompiled and formatted as new text.
- Click the Compile button () to compile the script and check for syntax errors.If a syntax error occurs, an alert is displayed.If the script compiles, code formatting is applied at this time.
Click the Compile button () to compile the script and check for syntax errors.
If a syntax error occurs, an alert is displayed.
If the script compiles, code formatting is applied at this time.
You can change the formatting attributes, such as font and color, of uncompiled and compiled text in the Formatting pane of Script Editor preferences. SeeFormatting Preferences.
### Using an AppleScript Template
Script Editor includes a number of built-in templates for creating common types of AppleScripts, including droplets, Mail rule scripts, and Messages handler scripts.
Note
Script Editor does not include JavaScript templates at this time.
- Launch Script Editor in/Applications/Utilities/.
Launch Script Editor in/Applications/Utilities/.
- Choose File > New from Template.
Choose File > New from Template.
- Select a script template.A new Script Editor document window opens containing prewritten code and preconfigured settings. The following screenshot shows an example of a script created using a template.
Select a script template.
A new Script Editor document window opens containing prewritten code and preconfigured settings. The following screenshot shows an example of a script created using a template.
- Customize the script.
Customize the script.
Getting to Know Script Editor
Saving a Script
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Parsing HTML
## Parsing HTML
The process of reading an HTML file is no different than the process of reading a standard text fileâseeReading a Fileto learn how to do it. However, itâs often necessary to extract specific bits of information from HTML files, such as links, images, and table data, for further processing.
### Parsing an HTML File
The handler inListing 33-1extracts specific tags and their content from HTML text. Provide an HTML file to read, a closing and ending tag, and indicate whether to return only content between the tags, or the tags with their enclosed content. If no closing tag is provided, the handler extracts the opening tag data only. This feature could be used to extract image tags from HTML content, for example, which donât have a separate closing tag.
APPLESCRIPT
Open in Script Editor
- on parseHTMLFile(theFile, theOpeningTag, theClosingTag, returnContentsOnly)
- try
- set theFile to theFile as string
- set theFile to open for access file theFile
- set theCombinedResults to ""
- set theCurrentOpeningTag to ""
- repeat
- read theFile before "<"
- set theCurrentTag to read theFile until ">"
- if theCurrentTag does not start with "<" then set theCurrentTag to ("<" & theCurrentTag) as string
- if theCurrentTag begins with theOpeningTag then
- set theCurrentOpeningTag to theCurrentTag
- if theClosingTag is "" then
- if theCombinedResults is "" then
- set theCombinedResults to theCombinedResults & theCurrentOpeningTag
- else
- set theCombinedResults to theCombinedResults & return & theCurrentOpeningTag
- end if
- else
- set theTextBuffer to ""
- repeat
- set theTextBuffer to theTextBuffer & (read theFile before "<")
- set theTagBuffer to read theFile until ">"
- if theTagBuffer does not start with "<" then set theTagBuffer to ("<" & theTagBuffer)
- if theTagBuffer is theClosingTag then
- if returnContentsOnly is false then
- set theTextBuffer to theCurrentOpeningTag & theTextBuffer & theTagBuffer
- end if
- if theCombinedResults is "" then
- set theCombinedResults to theCombinedResults & theTextBuffer
- else
- set theCombinedResults to theCombinedResults & return & theTextBuffer
- end if
- exit repeat
- else
- set theTextBuffer to theTextBuffer & theTagBuffer
- end if
- end repeat
- end if
- end if
- end repeat
- close access theFile
- on error theErrorMessage number theErrorNumber
- try
- close access theFile
- end try
- if theErrorNumber is not -39 then return false
- end try
- return theCombinedResults
- end parseHTMLFile
Listing 33-2shows how to call the handler inListing 33-1to extract all hyperlinks within a chosen HTML file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file with prompt "Select an HTML file:"
- parseHTMLFile(theFile, "", false)
- --> Example of Result: "Click here to view fileA.
- Click here to view fileB."
Listing 33-3shows how to call the handler inListing 33-1to extract the destinations of all hyperlinks within a chosen HTML file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file with prompt "Select an HTML file:"
- parseHTMLFile(theFile, "", true)
- --> Example of Result: "Click here to view fileA.
- Click here to view fileB."
Listing 33-4shows how to call the handler inListing 33-1to extract all images within a chosen HTML file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file with prompt "Select an HTML file:"
- parseHTMLFile(theFile, "
Example of Result: "
-
-
"
Listing 33-5shows how to call the handler inListing 33-1to extract any tables within a file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file with prompt "Select an HTML file:"
- parseHTMLFile(theFile, "
", false)
- --> Example of Result:"
-
-
-
- |
-
-
"
### Parsing an HTML Tag
The handler inListing 33-6extracts the contentsâfirst instance of text contained within quotesâof an HTML tag.
APPLESCRIPT
Open in Script Editor
- on parseHTMLTag(theHTMLTag)
- set AppleScript's text item delimiters to "\""
- set theHTMLTagElements to text items of theHTMLTag
- set AppleScript's text item delimiters to ""
- if length of theHTMLTagElements is greater than 1 then return item 2 of theHTMLTagElements
- return ""
- end parseHTMLTag
Listing 33-7shows how to call the handler inListing 33-6to extract the destination of a hyperlink tag.
APPLESCRIPT
Open in Script Editor
- set theHTMLTag to "Click here to view fileA."
- parseHTMLTag(theHTMLTag)
- --> Result: "http://www.apple.com/fileA.html"
Encoding and Decoding Text
Removing HTML Markup from Text
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Running a Script
## Running a Script
Scripts can be opened and run in Script Editor and script applications can be run outside of Script Editor like any other OSÂ X application. Some apps and tools, such as Automator and the systemwide script menu, can also run scripts.
### Running a Script in Script Editor
To run a script in Script Editor, click the Run button () in the toolbar, press Command-R, or choose Script > Run, as shown inFigure 8-1.
As the script runs, the Accessory View pane shows events and results of the script. This information can be useful for troubleshooting. SeeViewing Script Events and Results.
### Running a Script Application
To run a script application, double-click the script in the Finder, just like you would do to launch any other application. The script opens and begins running.
Note
When running a script app outside of Script Editor, you canât view a list of the scriptâs events and results. To monitor this activity, open the app in Script Editor instead, run it, and check the Accessory View pane.
Saving a Script
Configuring Scripting Preferences
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Objective-C to AppleScript Quick Translation Guide
## Objective-C to AppleScript Quick Translation Guide
This appendix provides AppleScript equivalents for typical Objective-C features of a class. Below the table is a list of notes that correspond to the numbers in column 1.
Note
Objective-C
AppleScript
@interface MyClass : NSObject {
script MyClass
   property parent: class "NSObject"
   int myProperty;
   IBOutlet NSTextField *myField;
IBOutlet @property (retain) NSButton *myButton;
property myProperty: 0
property myField: missing value
property myButton: missing value
@end
@implementation MyClass
- (IBAction) myAction:(id) object {
-- Handler with interleaved parameters
   on myAction:object
-- or
-- Handler with positional parameters
   on myAction_(object)
// No Arguments
   [object method];
// One Argument
   [object method:parameterName];
// Multiple Argument
   [object methodWithArgument1:parameter1 Argument2:parameter2];
-- No Arguments
      object's methodName()
-- or
methodName() of object
-- or
tell object to methodName()
-- One Argument
object's methodName:parameterName
-- or
methodName_(parameterName) of object
-- or
tell object to methodName:parameterName
-- Multiple Arguments
object's methodWithArgument1:parameter1 Argument2:parameter2
-- or
methodWithArgument1_Argument2_(parameter1, parameter2) of object
-- or
tell object to methodWithArgument1:parameter1 Argument2:parameter2
   [object propertyName];
   object.propertyName;
      object's propertyName()
-- or
propertyName() of object
      object's propertyName
-- or
propertyName of object
@end
   end myAction_
end script
- An Objective-C class corresponds to an AppleScriptscriptobject. In AppleScript, inheritance is denoted using theparentproperty.
An Objective-C class corresponds to an AppleScriptscriptobject. In AppleScript, inheritance is denoted using theparentproperty.
- An instance variable or@propertyin Objective-C corresponds to apropertyin AppleScript.AppleScript doesnât require explicit tagging of Interface Builder outlet properties (IBOutlet). Interface Builder sees any property with a value ofmissing valueas a potential outlet.
An instance variable or@propertyin Objective-C corresponds to apropertyin AppleScript.
AppleScript doesnât require explicit tagging of Interface Builder outlet properties (IBOutlet). Interface Builder sees any property with a value ofmissing valueas a potential outlet.
- Objective-C divides class definitions into an@interfacesection containing properties and an@implementationsection containing method definitions. AppleScript has no such division. Properties and methods are all contained within the samescriptobject.
Objective-C divides class definitions into an@interfacesection containing properties and an@implementationsection containing method definitions. AppleScript has no such division. Properties and methods are all contained within the samescriptobject.
- An Objective-C method definition corresponds to an AppleScript handler that uses either an interleaved- or positional-style for parameter placement.Interleaved parameters are preceded by colons and separated by spaces, similar to Objective-C syntax. SeeHandlers with Interleaved ParametersinAppleScript Language Guide.A positional parameter hander name is the Objective-C selector name, with colons changed to underscores. This handler name is followed by parentheses enclosing comma-separated parameters. SeeHandlers with Positional ParametersinAppleScript Language Guide.AppleScript doesnât require explicit tagging of Interface Builder action methods (IBAction). Interface Builder sees any method with a single parameter as a potential action method.
An Objective-C method definition corresponds to an AppleScript handler that uses either an interleaved- or positional-style for parameter placement.
Interleaved parameters are preceded by colons and separated by spaces, similar to Objective-C syntax. SeeHandlers with Interleaved ParametersinAppleScript Language Guide.
A positional parameter hander name is the Objective-C selector name, with colons changed to underscores. This handler name is followed by parentheses enclosing comma-separated parameters. SeeHandlers with Positional ParametersinAppleScript Language Guide.
AppleScript doesnât require explicit tagging of Interface Builder action methods (IBAction). Interface Builder sees any method with a single parameter as a potential action method.
- A method call in Objective-C corresponds to an AppleScript handler call that uses either interleaved- or positional-style parameters. Regardless of style, parameters must always be provided in the order the method definition specifies.AppleScript has three equivalent syntaxes for addressing object handlers and properties:object's method,method of object, andtell object to method.
A method call in Objective-C corresponds to an AppleScript handler call that uses either interleaved- or positional-style parameters. Regardless of style, parameters must always be provided in the order the method definition specifies.
AppleScript has three equivalent syntaxes for addressing object handlers and properties:object's method,method of object, andtell object to method.
- An Objective-C method with no parameters, such as a property or constant, can be called using an explicit accessor method call or more concise dot syntax. Similarly in AppleScript, a method with no parameters can be called using a handler call with empty parentheses, or as a property without the parentheses.
An Objective-C method with no parameters, such as a property or constant, can be called using an explicit accessor method call or more concise dot syntax. Similarly in AppleScript, a method with no parameters can be called using a handler call with empty parentheses, or as a property without the parentheses.
- In AppleScript, handlers andscriptobjects are closed using theendsyntax.
In AppleScript, handlers andscriptobjects are closed using theendsyntax.
### Resolving Terminology Conflicts in AppleScriptObjC
AppleScript distinguishes betweenreserved words,application identifiers, anduser identifiers. Reserved words are terms defined by AppleScript itself. Application identifiers, also known asapplication keywords, are terms defined by an appâs scripting dictionary. User identifiers are variable or subroutine names defined by the script writer.
Identifiers passed to AppleScriptObjC, in particular, Cocoa method names, must be user identifiers. If an identifier conflicts with a reserved word or an application identifier, you can force it to be considered a user identifier by escaping itâenclosing it in vertical bars. For example, theNSColorclass has asetmethod for setting the current drawing color. However,setis a reserved AppleScript term for assigning variables. Calling thesetmethod without escaping it would produce a syntax error.Listing 43-1shows the correct usage.
APPLESCRIPT
Open in Script Editor
- myColor's |set|()
- -- OR
- |set|() of myColor
- -- OR
- tell myColor to |set|()
Similarly,NSWindowhas aboundsproperty, butboundsis an application-defined term. Therefore, any references to this property must also be escaped. SeeListing 43-2.
APPLESCRIPT
Open in Script Editor
- get myWindow's |bounds|
- -- OR
- get |bounds| of myWindow
- -- OR
- tell myColor to get |bounds|
When in doubt, add the vertical bars. If theyâre unnecessary, they are merely redundant and harmless.
### Importing Frameworks
To import a framework in AppleScript, use theusecommand, followed by the framework name. SeeListing 43-3.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- set theString to "Hello World"
- set theString to stringWithString_(theString) of NSString of current application
- set theString to (uppercaseString() of theString) as string
- --> Result: "HELLO WORLD"
### Accessing Scripting Additions
A normal AppleScript automatically loads and has access to terminology from scripting additions that are installed on the system. In AppleScriptObjC scripts, you must explicitly state that you want to use scripting addition terminology.Listing 43-4shows how to do this.
APPLESCRIPT
Open in Script Editor
- use scripting additions
- display dialog "Hello World" as string
### Classes and Constants
In AppleScriptObjC, Objective-C classes and constants are referred to in the context of thecurrent applicationconstantâa reference to the app thatâs running the script.
In this context, classes are referenced using theclassspecifier, followed by the class name, as shown inListing 43-5.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- class "NSView" of current application
Constants are referenced without a preceding identifier. SeeListing 43-6.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- current application's NSCalibratedRGBColorSpace
- -- OR
- NSCalibratedRGBColorSpace of current application
Listing 43-7demonstrates how to reference both Objective-C classes and constants.
APPLESCRIPT
Open in Script Editor
- script MyView
- property parent : class "NSView"
- on drawRect:rect
- set theWhiteColor to current application's class "NSColor"'s whiteColor()
- -- OR
- set theWhiteColor to whiteColor() of class "NSColor" of current application
- -- OR
- tell class "NSColor" of current application to set theWhiteColor to whiteColor()
- theWhiteColor's colorUsingColorSpaceName:(current application's NSCalibratedRGBColorSpace)
- -- OR
- colorUsingColorSpaceName_(NSCalibratedRGBColorSpace of current application) of theWhiteColor
- end drawRect:
- end script
In places wherecurrent applicationis the current context, such as the top level of a script,current applicationmay be shortened tomyorme. In the case of class specifiers, it may be omitted entirely. SeeListing 43-8.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- class "NSView"
- my NSCalibratedRGBColorSpace
- -- OR
- NSCalibratedRGBColorSpace of me
As a convenience technique to save typing, itâs good practice to define properties for classes at the top of your script. This way, you can refer to them by property name throughout your script.
APPLESCRIPT
Open in Script Editor
- script MyView
- property parent : class "NSView"
- property NSColor : class "NSColor"
- on drawRect:rect
- set theWhiteColor to NSColor's whiteColor()
- theWhiteColor's colorUsingColorSpaceName:NSCalibratedRGBColorSpace
- end drawRect:
- end script
### Resources
For additional information about AppleScriptObjC, seeAppleScriptObjC Release Notesand the third-party bookEveryDay AppleScriptObjC.
Using Dictation to Run Scripts
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Introduction to AppleScript Language Guide
This document is a guide to the AppleScript languageâits lexical conventions, syntax, keywords, and other elements. It is intended primarily for use with AppleScript 2.0 or later and macOS version 10.5 or later.
AppleScript 2.0 can use scripts developed for any version of AppleScript from 1.1 through 1.10.7, any scripting addition created for AppleScript 1.5 or later for macOS, and any scriptable application for Mac OS v7.1 or later. A script created with AppleScript 2.0 can be used by any version of AppleScript back to version 1.1, provided it does not use features of AppleScript, scripting additions, or scriptable applications that are unavailable in that version.
Important:Descriptions and examples for the terms in this document have been tested with AppleScript 2.0 in OS X v10.5 (Leopard). Except for terms that are noted as being new in Leopard, most descriptions and examples work with previous system versions, but have not been tested against all of them.
If you need detailed information about prior system and AppleScript versions, seeAppleScript Release Notes (OS X v10.4 and earlier).
## What Is AppleScript?
AppleScript is a scripting language created by Apple. It allows users to directly control scriptable Macintosh applications, as well as parts of macOS itself. You can create scriptsâsets of written instructionsâto automate repetitive tasks, combine features from multiple scriptable applications, and create complex workflows.
Note:Apple also provides the Automator application, which allows users to automate common tasks by hooking together ready-made actions in a graphical environment. For more information, seeAutomator Documentation.
A scriptable application is one that can be controlled by a script. For AppleScript, that means being responsive to interapplication messages, calledApple events, sent when a script command targets the application. (Apple events can also be sent directly from other applications and macOS.)
AppleScript itself provides a very small number of commands, but it provides a framework into which you can plug many task-specific commandsâthose provided by scriptable applications and scriptable parts of macOS.
Most script samples and script fragments in this guide use scriptable features of the Finder application, scriptable parts of macOS, or scriptable applications distributed with macOS, such as TextEdit (located in/Applications).
## Who Should Read This Document?
You should use this document if you write or modify AppleScript scripts, or if you create scriptable applications and need to know how scripts should work.
AppleScript Language Guideassumes you are familiar with the high-level information about AppleScript found inAppleScript Overview.
## Organization of This Document
This guide describes the AppleScript language in a series of chapters and appendixes.
The first five chapters introduce components of the language and basic concepts for using it, then provide additional overview on working with script objects and handler routines:
- AppleScript Lexical Conventionsdescribes the characters, symbols, keywords, and other language elements that make up statements in an AppleScript script.
AppleScript Lexical Conventionsdescribes the characters, symbols, keywords, and other language elements that make up statements in an AppleScript script.
- AppleScript Fundamentalsdescribes basic concepts that underly the terminology and rules covered in the rest of this guide.
AppleScript Fundamentalsdescribes basic concepts that underly the terminology and rules covered in the rest of this guide.
- Variables and Propertiesdescribes common issues in working with variables and properties, including how to declare them and how AppleScript interprets their scope.
Variables and Propertiesdescribes common issues in working with variables and properties, including how to declare them and how AppleScript interprets their scope.
- Script Objectsdescribes how to define, initialize, send commands to, and use inheritance with script objects.
Script Objectsdescribes how to define, initialize, send commands to, and use inheritance with script objects.
- About Handlersprovides information on using handlers (a type of function available in AppleScript) to factor and reuse code.
About Handlersprovides information on using handlers (a type of function available in AppleScript) to factor and reuse code.
The following chapters provide reference for the AppleScript Language:
- Class Referencedescribes the classes AppleScript defines for common objects used in scripts.
Class Referencedescribes the classes AppleScript defines for common objects used in scripts.
- Commands Referencedescribes the commands that are available to any script.
Commands Referencedescribes the commands that are available to any script.
- Reference Formsdescribes the syntax for specifying an object or group of objects in an application or other container.
Reference Formsdescribes the syntax for specifying an object or group of objects in an application or other container.
- Operators Referenceprovides a list of the operators AppleScript supports and the rules for using them, along with sections that provide additional detail for commonly used operators.
Operators Referenceprovides a list of the operators AppleScript supports and the rules for using them, along with sections that provide additional detail for commonly used operators.
- Control Statements Referencedescribes statements that control when and how other statements are executed. It covers standard conditional statements, as well as statements used in error handling and other operations.
Control Statements Referencedescribes statements that control when and how other statements are executed. It covers standard conditional statements, as well as statements used in error handling and other operations.
- Handler Referenceshows the syntax for defining and calling handlers and describes other statements you use with handlers.
Handler Referenceshows the syntax for defining and calling handlers and describes other statements you use with handlers.
The following chapter describes an AppleScript-related feature of macOS:
- Folder Actions Referencedescribes how you can write and attach script handlers to specific folders, such that the handlers are invoked when the folders are modified.
Folder Actions Referencedescribes how you can write and attach script handlers to specific folders, such that the handlers are invoked when the folders are modified.
The following appendixes provide additional information about the AppleScript language and how to work with errors in scripts:
- AppleScript Keywordslists the keywords of the AppleScript language, provides a brief description for each, and points to related information.
AppleScript Keywordslists the keywords of the AppleScript language, provides a brief description for each, and points to related information.
- Error Numbers and Error Messagesdescribes error numbers and error messages you may see in working with AppleScript scripts.
Error Numbers and Error Messagesdescribes error numbers and error messages you may see in working with AppleScript scripts.
- Working with Errorsprovides detailed examples of handling errors withtry Statementsanderror Statements.
Working with Errorsprovides detailed examples of handling errors withtry Statementsanderror Statements.
- Double Angle Bracketsdescribes when you are likely to see double angle brackets (or chevronsâ«») in scripts and how you can work with them.
Double Angle Bracketsdescribes when you are likely to see double angle brackets (or chevronsâ«») in scripts and how you can work with them.
- Libraries using Load Scriptdescribes how to save libraries of handlers and access them from other scripts.
Libraries using Load Scriptdescribes how to save libraries of handlers and access them from other scripts.
- Unsupported Termslists terms that are no longer supported in AppleScript.
Unsupported Termslists terms that are no longer supported in AppleScript.
## Conventions Used in This Guide
Glossary terms are shown inboldfacewhere they are defined.
Important:This document sometimes uses the continuation character (¬) for sample statements that donât fit on one line on a document page. It also uses the continuation character in some syntax statements to identify an item that, if included, must appear on the same line as the previous item. The continuation character itself is not a required part of the syntaxâit is merely a mechanism for including multiple lines in one statement.
The following conventions are used in syntax descriptions:
language element
Plain computer font indicates an element that you type exactly as shown. If there are special symbols (for example,+or&), you also type them exactly as shown.
placeholder
Italic text indicates a placeholder that you replace with an appropriate value.
[optional]
Brackets indicate that the enclosed language element or elements are optional.
(a group)
Parentheses group elements together.
However, the parentheses shown inHandler Syntax (Positional Parameters)are part of the syntax.
[optional]...
Three ellipsis points (...) after a group defined by brackets indicate that you can repeat the group of elements within brackets 0 or more times.
a | b | c
Vertical bars separate elements in a group from which you must choose a single element. The elements are often grouped within parentheses or brackets.
Filenames shown in scripts
Most filenames shown in examples in this document include extensions, such asrtffor a TextEdit document. Use of extensions in scripts is generally dependent on the âShow all file extensionsâ setting in the Advanced pane of Finder Preferences.
To work with the examples on your computer, you may need to modify either that setting or the filenames.
## See Also
These Apple documents provide additional information for working with AppleScript:
- SeeGetting Started with AppleScriptfor a guided quick start, useful to both scripters and developers.
SeeGetting Started with AppleScriptfor a guided quick start, useful to both scripters and developers.
- SeeAppleScript Overview, including the chapterScripting with AppleScript, for a high-level overview of AppleScript and its related technologies.
SeeAppleScript Overview, including the chapterScripting with AppleScript, for a high-level overview of AppleScript and its related technologies.
- SeeGetting Started With Scripting & Automationfor information on the universe of scripting technologies available in macOS.
SeeGetting Started With Scripting & Automationfor information on the universe of scripting technologies available in macOS.
- SeeAppleScript Terminology and Apple Event Codesfor a list of many of the scripting terms defined by Apple.
SeeAppleScript Terminology and Apple Event Codesfor a list of many of the scripting terms defined by Apple.
For additional information on working with the AppleScript language and creating scripts, see one of the comprehensive third-party documents available in bookstores and online.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Mac Automation Scripting Guide: How Mac Scripting Works
## How Mac Scripting Works
TheOpen Scripting Architecture (OSA)provides a standard and extensible mechanism for interapplication communication in OS X. This communication takes place through the exchange of Apple events. AnApple eventis a type of interprocess message that encapsulates commands and data.
Ascriptable applicationresponds to Apple events by performing operations or supplying data. Every scriptable app implements its own scripting features and exposes its own unique terminology through ascripting dictionary. While not all apps are consideredscriptable, any app with a graphical user interface responds to Apple Events at a minimal level. This is because OSÂ X uses Apple Events to instruct all apps to perform core tasks such as launching, quitting, opening a document, and printing. To learn about scripting terminology and dictionaries, seeAccessing Scripting Terminology.
The OSA provides the following capabilities in OS X:
- The ability for app developers to create scriptable apps and expose scripting terminology
The ability for app developers to create scriptable apps and expose scripting terminology
- The ability for users to write scripts in a variety of scripting languages
The ability for users to write scripts in a variety of scripting languages
- The ability to communicate between apps on the same computer or on different computers using Apple events
The ability to communicate between apps on the same computer or on different computers using Apple events
TheOpen Scripting frameworkdefines standard data structures, routines, and resources for creatingscripting components, which implement support for specific scripting languages. The AppleScript and JavaScript components (inSystem/Library/Components), for example, make it possible to control scriptable apps from AppleScript and JavaScript scripts. Through the frameworkâs standard interface, a scriptable app can interact with any scripting component, regardless of its language. The framework also provides API for compiling, executing, loading, and storing scriptsâfunctions provided by script editing apps.
TheApple Event Managersupplies the underlying support for creating scriptable apps and is implemented in the AE framework within the CoreServices framework. App developers can interact with the Apple Event Manager through the Apple Event APIs in the Foundation framework. SeeNSAppleEventManager Class ReferenceandNSAppleEventDescriptor Class Reference.
Figure 2-1shows how OSA elements work together in OSÂ X.
### Extending the Reach of Scripting
Every scriptable app expands the reach of scripting. Developers can also add new scripting capabilities through scripting additions and scriptable background apps.
Ascripting additionis a bundle that implements new scripting terminology. For example, the Standard Additions scripting addition that comes with OSÂ X (found in/System/Library/ScriptingAdditions/StandardAdditions.osax), includes commands for using the Clipboard, displaying alerts, speaking text, executing shell scripts, and more. Since scripting additions are loaded in a global context, commands provided by Standard Additions are available to all scripts.
Ascriptable background application(sometimes called anagent) runs with no visible user interface and provides scripts with access to useful features. System Events and Image Events are examples of scriptable background apps in OSÂ X. Scripts can target System Events to perform operations on property list files, adjust system preferences, and much more. Scripts can target Image Events to perform basic image manipulations, such as cropping, rotating, and resizing.
### Objective-C Bridging
Several technologies in OSÂ X make it possible for scripts to interact with Objective-C frameworks, and vice-versa.
AppleScriptObjCis a bridge between AppleScript and Objective-C, andJavaScriptObjCis a bridge between JavaScript for automation and Objective-C. These bridges enable you to write scripts that use scripting terminology to interact with Objective-C frameworks, such as Foundation and AppKit. The bridges also enable you to design user interfaces for scripts that have the same look and feel of any other Cocoa app. For information about the AppleScriptObjC bridge, seeObjective-C to AppleScript Quick Translation Guide. For information about JavaScriptObjC, seeObjective-C BridgeinJavaScript for Automation Release Notes.
TheScripting Bridgelets you control scriptable apps using standard Objective-C syntax. Instead of incorporating scripts in your Cocoa app or dealing with the complexities of sending and handling Apple events, you can simply send Objective-C messages to objects representing scriptable apps. Your Cocoa app can do anything a script can, but in Objective-C code thatâs more tightly integrated with the rest of your projectâs code. SeeScripting Bridge Programming GuideandScripting Bridge Framework Reference.
About Mac Scripting
Types of Scripts
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Opening a Scripting Dictionary
## Opening a Scripting Dictionary
Script Editor can open dictionaries and display their contents for you to consult while writing scripts.
Do one of the following:
- Drag an app or scripting addition onto Script Editor in the Dock or in the Finder.
Drag an app or scripting addition onto Script Editor in the Dock or in the Finder.
- Choose File > Open Dictionary (or press Shift-Command-O), and select a scriptable app or scripting addition.
Choose File > Open Dictionary (or press Shift-Command-O), and select a scriptable app or scripting addition.
- Double-click an app or scripting addition in the Library palette. If the Library palette isnât visible, choose Window > Library (or press Shift-Command-L) to display it. Click the Add button (+) in the Library palette to add a new app or scripting addition to the list for quick access in the future.
Double-click an app or scripting addition in the Library palette. If the Library palette isnât visible, choose Window > Library (or press Shift-Command-L) to display it. Click the Add button (+) in the Library palette to add a new app or scripting addition to the list for quick access in the future.
An error message is displayed if you attempt to open an app without scripting terminologyâa nonscriptable app.
About Scripting Terminology
Navigating a Scripting Dictionary
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Displaying Notifications
## Displaying Notifications
Notification Center offers another opportunity for providing feedback during script execution. Use the Standard Additions scripting additionâsdisplay notificationcommand to show notifications, such as status updates as files are processed. Notifications are shown as alerts or banners, depending on the userâs settings in System Preferences > Notifications. SeeFigure 24-1andFigure 24-2.
To show a notification, provide thedisplay notificationcommand with a string to display. Optionally, provide values for thewith title,subtitle, andsound nameparameters to provide additional information and an audible alert when the notification appears, as shown inListing 24-1andListing 24-2.
APPLESCRIPT
Open in Script Editor
- display notification "All graphics have been converted." with title "My Graphic Processing Script" subtitle "Processing is complete." sound name "Frog"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.displayNotification("All graphics have been converted.", {
- withTitle: "My Graphic Processing Script",
- subtitle: "Processing is complete.",
- soundName: "Frog"
- })
Note
After using a script to display a notification, the script or Script Editor (if the script is run from within Script Editor) is added to the list of notifying apps in System Preferences > Notifications. There, you can configure options, such as whether to display notifications as alerts or banners.
Clicking the Show button in an alert-style notification opens the app that displayed the notification. For a script app, the action of opening the app again triggers therunhandler of the script, potentially causing the script to begin processing a second time. Keep this in mind, and add code to your script to handle this scenario, if appropriate.
Prompting for Text
Speaking Text
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Prompting for a Choice from a List
## Prompting for a Choice from a List
Use the Standard Additions scripting additionâschoose from listcommand to prompt the user to select from a list of strings.Listing 28-1andListing 28-2ask the user to select a favorite fruit, as seen inFigure 28-1.
APPLESCRIPT
Open in Script Editor
- set theFruitChoices to {"Apple", "Banana", "Orange"}
- set theFavoriteFruit to choose from list theFruitChoices with prompt "Select your favorite fruit:" default items {"Apple"}
- theFavoriteFruit
- --> Result: {"Apple"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var fruitChoices = ["Apple", "Banana", "Orange"]
- var favoriteFruit = app.chooseFromList(fruitChoices, {
- withPrompt: "Select your favorite fruit:",
- defaultItems: ["Apple"]
- })
- favoriteFruit
- // Result: ["Apple"]
Thechoose from listcommand can optionally let the user choose multiple items by setting themultiple selections allowedparameter totrue. For this reason, the result of the command is always a list of selected strings. This list may be empty if theempty selection allowedparameter has been specified and the user dismissed the dialog without making a selection.
Prompting for a File Name
Prompting for a Color
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Processing Dropped Files and Folders
## Processing Dropped Files and Folders
Droplets are applets configured to process dropped files and folders. A droplet is distinguishable from a normal applet because its icon includes a downward pointing arrow, as shown inFigure 17-1.
To create an AppleScript droplet, include anopenevent handler in your script and save the script as an application. To create a JavaScript droplet, include anopenDocumentsfunction in your script and save the script as an application. The presence of this handler or function automatically renders the saved application as a droplet, allowing it to accept dropped files and folders in the Finder. Theopenhandler andopenDocumentsfunction accept a single parameterâa list of dropped files or foldersâwhich are passed to the handler when the script is activated by dropping something onto it. In AppleScript, these dropped files and folders arealiasobjects. In JavaScript, theyârePathobjects. For more information about these types of objects, seeReferencing Files and Folders.
An AppleScriptopenhandler is formatted as shown inListing 17-1.
APPLESCRIPT
Open in Script Editor
- on open theDroppedItems
- -- Process the dropped items here
- end open
A JavaScriptopenDocumentsfunction is formatted as shown inListing 17-2.
JAVASCRIPT
Open in Script Editor
- function openDocuments(droppedItems) {
- // Process the dropped items here
- }
Typically, a droplet loops through items dropped onto it, processing them individually, as inListing 17-3andListing 17-4.
APPLESCRIPT
Open in Script Editor
- on open theDroppedItems
- repeat with a from 1 to length of theDroppedItems
- set theCurrentDroppedItem to item a of theDroppedItems
- -- Process each dropped item here
- end repeat
- end open
JAVASCRIPT
Open in Script Editor
- function openDocuments(droppedItems) {
- for (var item of droppedItems) {
- // Process each dropped item here
- }
- }
To run a droplet, drop files or folders onto it in the Finder. To test a droplet in Script Editor, add the following line(s) of code to the root levelâtherunhandler portionâof the script.Listing 17-5andListing 17-6prompt you to select a file and then passes it to theopenhandler oropenDocumentsfunction.
APPLESCRIPT
Open in Script Editor
- open {choose file}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var file = app.chooseFile()
- openDocuments([file])
### Creating an AppleScript Droplet from a Script Editor Template
Script Editor includes several preconfigured AppleScript droplet templates, which solve the majority of droplet use cases.
Note
Script Editor does not include JavaScript templates at this time.
- Launch Script Editor from/Applications/Utilities/.
Launch Script Editor from/Applications/Utilities/.
- Select File > New from Template > Droplets.
Select File > New from Template > Droplets.
- Choose a droplet template.Options include:Droplet with Settable PropertiesâThis template processes dropped files based on file type, extension, or type identifier. It also demonstrates how to include a user-configurable setting, which affects the behavior of the script.Recursive File Processing DropletâThis template processes dropped files based on file type, extension, or type identifier. It is configured to detect files within dropped folders and their subfolders.Recursive Image File Processing DropletâThis template processes image files matching specific file types, extensions, or type identifiers. It is configured to detect images within dropped folders and their subfolders.All of these templates are designed to serve as starting points for creating a droplet, and can be customized, as needed.
Choose a droplet template.
Options include:
- Droplet with Settable PropertiesâThis template processes dropped files based on file type, extension, or type identifier. It also demonstrates how to include a user-configurable setting, which affects the behavior of the script.
Droplet with Settable PropertiesâThis template processes dropped files based on file type, extension, or type identifier. It also demonstrates how to include a user-configurable setting, which affects the behavior of the script.
- Recursive File Processing DropletâThis template processes dropped files based on file type, extension, or type identifier. It is configured to detect files within dropped folders and their subfolders.
Recursive File Processing DropletâThis template processes dropped files based on file type, extension, or type identifier. It is configured to detect files within dropped folders and their subfolders.
- Recursive Image File Processing DropletâThis template processes image files matching specific file types, extensions, or type identifiers. It is configured to detect images within dropped folders and their subfolders.
Recursive Image File Processing DropletâThis template processes image files matching specific file types, extensions, or type identifiers. It is configured to detect images within dropped folders and their subfolders.
All of these templates are designed to serve as starting points for creating a droplet, and can be customized, as needed.
### Creating a Droplet to Process Files
InListing 17-7andListing 17-8, theopenhandler andopenDocumentsfunction process dropped files based on file type, extension, or type identifier. The file types, extensions, and type identifiers supported by the handler are configurable in properties at the top of the script. If a dropped file matches the criteria you configure, then the file is passed to theprocessItem()handler, where you can add custom file processing code. These examples are not configured to process dropped folders.
APPLESCRIPT
Open in Script Editor
- property theFileTypesToProcess : {} -- For example: {"PICT", "JPEG", "TIFF", "GIFf"}
- property theExtensionsToProcess : {} -- For example: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
- property theTypeIdentifiersToProcess : {} -- For example: {"public.jpeg", "public.tiff", "public.png"}
- on open theDroppedItems
- repeat with a from 1 to count of theDroppedItems
- set theCurrentItem to item a of theDroppedItems
- tell application "System Events"
- set theExtension to name extension of theCurrentItem
- set theFileType to file type of theCurrentItem
- set theTypeIdentifier to type identifier of theCurrentItem
- end tell
- if ((theFileTypesToProcess contains theFileType) or (theExtensionsToProcess contains theExtension) or (theTypeIdentifiersToProcess contains theTypeIdentifier)) then
- processItem(theCurrentItem)
- end if
- end repeat
- end open
- on processItem(theItem)
- -- NOTE: The variable theItem is a file reference in AppleScript alias format
- -- Add item processing code here
- end processItem
JAVASCRIPT
Open in Script Editor
- var SystemEvents = Application("System Events")
- var fileTypesToProcess = [] // For example: {"PICT", "JPEG", "TIFF", "GIFf"}
- var extensionsToProcess = [] // For example: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
- var typeIdentifiersToProcess = [] // For example: {"public.jpeg", "public.tiff", "public.png"}
- function openDocuments(droppedItems) {
- for (var item of droppedItems) {
- var alias = SystemEvents.aliases.byName(item.toString())
- var extension = alias.nameExtension()
- var fileType = alias.fileType()
- var typeIdentifier = alias.typeIdentifier()
- if (fileTypesToProcess.includes(fileType) || extensionsToProcess.includes(extension) || typeIdentifiersToProcess.includes(typeIdentifier)) {
- processItem(item)
- }
- }
- }
- function processItem(item) {
- // NOTE: The variable item is an instance of the Path object
- // Add item processing code here
- }
### Creating a Droplet to Process Files and Folders
InListing 17-9andListing 17-10, theopenhandler andopenDocumentsfunction loop through any dropped files and folders.
For each dropped file, the script calls theprocessFile()handler, which determines whether the file matches specific file types, extensions, and type identifiers. The file types, extensions, and type identifiers supported by the handler are configurable in properties at the top of the script. If thereâs a match, then any custom file processing code you add runs.
The script passes each dropped folder to theprocessFolder(), which retrieves a list of files and subfolders within the dropped folder. TheprocessFolder()handler recursively calls itself to process any additional subfolders. It calls theprocessFile()handler to process any detected files. If necessary, you can add custom folder processing code to theprocessFolder()handler.
APPLESCRIPT
Open in Script Editor
- property theFileTypesToProcess : {} -- I.e. {"PICT", "JPEG", "TIFF", "GIFf"}
- property theExtensionsToProcess : {} -- I.e. {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
- property theTypeIdentifiersToProcess : {} -- I.e. {"public.jpeg", "public.tiff", "public.png"}
- on open theDroppedItems
- repeat with a from 1 to count of theDroppedItems
- set theCurrentItem to item a of theDroppedItems
- tell application "Finder"
- set isFolder to folder (theCurrentItem as string) exists
- end tell
- -- Process a dropped folder
- if isFolder = true then
- processFolder(theCurrentItem)
- -- Process a dropped file
- else
- processFile(theCurrentItem)
- end if
- end repeat
- end open
- on processFolder(theFolder)
- -- NOTE: The variable theFolder is a folder reference in AppleScript alias format
- -- Retrieve a list of any visible items in the folder
- set theFolderItems to list folder theFolder without invisibles
- -- Loop through the visible folder items
- repeat with a from 1 to count of theFolderItems
- set theCurrentItem to ((theFolder as string) & (item a of theFolderItems)) as alias
- open {theCurrentItem}
- end repeat
- -- Add additional folder processing code here
- end processFolder
- on processFile(theItem)
- -- NOTE: variable theItem is a file reference in AppleScript alias format
- tell application "System Events"
- set theExtension to name extension of theItem
- set theFileType to file type of theItem
- set theTypeIdentifier to type identifier of theItem
- end tell
- if ((theFileTypesToProcess contains theFileType) or (theExtensionsToProcess contains theExtension) or (theTypeIdentifiersToProcess contains theTypeIdentifier)) then
- -- Add file processing code here
- display dialog theItem as string
- end if
- end processFile
JAVASCRIPT
Open in Script Editor
- var SystemEvents = Application("System Events")
- var fileManager = $.NSFileManager.defaultManager
- var currentApp = Application.currentApplication()
- currentApp.includeStandardAdditions = true
- var fileTypesToProcess = [] // For example: {"PICT", "JPEG", "TIFF", "GIFf"}
- var extensionsToProcess = [] // For example: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
- var typeIdentifiersToProcess = [] // For example: {"public.jpeg", "public.tiff", "public.png"}
- function openDocuments(droppedItems) {
- for (var item of droppedItems) {
- var isDir = Ref()
- if (fileManager.fileExistsAtPathIsDirectory(item.toString(), isDir) && isDir[0]) {
- processFolder(item)
- }
- else {
- processFile(item)
- }
- }
- }
- function processFolder(folder) {
- // NOTE: The variable folder is an instance of the Path object
- var folderString = folder.toString()
- // Retrieve a list of any visible items in the folder
- var folderItems = currentApp.listFolder(folder, { invisibles: false })
- // Loop through the visible folder items
- for (var item of folderItems) {
- var currentItem = `${folderString}/${item}`
- openDocuments([currentItem])
- }
- // Add additional folder processing code here
- }
- function processFile(file) {
- // NOTE: The variable file is an instance of the Path object
- var fileString = file.toString()
- var alias = SystemEvents.aliases.byName(fileString)
- var extension = alias.nameExtension()
- var fileType = alias.fileType()
- var typeIdentifier = alias.typeIdentifier()
- if (fileTypesToProcess.includes(fileType) || extensionsToProcess.includes(extension) || typeIdentifiersToProcess.includes(typeIdentifier)) {
- // Add file processing code here
- }
- }
Reading and Writing Files
Watching Folders
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Manipulating Lists of Items
## Manipulating Lists of Items
In scripting, a listâtypically referred to as an array in JavaScriptâis a an ordered collection of values thatâs stored in a single object. A script can loop through the items of a list in order to process the items individually. There are many other tasks scripts commonly performed with lists, such as joining and sorting, which usually require custom scripting.
Note
For general information about working with lists in AppleScript, see thelistclass reference documentation inAppleScript Language Guide.
In JavaScript, theArrayobject provides a range of processing functions. Information about this object can be foundhere.
### Looping through a List
Listing 21-1andListing 21-2show how to incrementally loop through a list. In these examples, a variableâain AppleScript andiin JavaScriptârepresents an integer value from1through the number of items in the list. Each loop causes this variable value to increase, and you can use the increment variable to target a specific list item.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- repeat with a from 1 to length of theList
- set theCurrentListItem to item a of theList
- -- Process the current list item
- display dialog theCurrentListItem & " is item " & a & " in the list."
- end repeat
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var array = ["Sal", "Ben", "David", "Chris"]
- var arrayLength = array.length
- for (var i = 0; i < arrayLength; i++) {
- var currentArrayItem = array[i]
- // Process the current array item
- app.displayDialog(`${currentArrayItem} is item ${i + 1} in the array.`)
- }
A script can also loop through a list of items more directly by dynamically assigning a list item to a variable. InListing 21-3andListing 21-4, a variableâtheCurrentListItemin AppleScript andcurrentArrayItemin JavaScriptârepresents the item matching the current loop.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- repeat with theCurrentListItem in theList
- -- Process the current list item
- display dialog theCurrentListItem & " is an item in the list."
- end repeat
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var array = ["Sal", "Ben", "David", "Chris"]
- var arrayLength = array.length
- for (var currentArrayItem of array) {
- // Process the current array item
- app.displayDialog(`${currentArrayItem} is an item in the array.`)
- }
Note
For more information about looping through list items in AppleScript, seeControl Statements ReferenceinAppleScript Language Guide.
### Converting a List to a String
The handler inListing 21-5joins a list of strings together in AppleScript, separating them by a specific delimiter.
APPLESCRIPT
Open in Script Editor
- on convertListToString(theList, theDelimiter)
- set AppleScript's text item delimiters to theDelimiter
- set theString to theList as string
- set AppleScript's text item delimiters to ""
- return theString
- end convertListToString
Listing 21-6shows how to call the handler inListing 21-5.
APPLESCRIPT
Open in Script Editor
- set theList to {"The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."}
- convertListToString(theList, space)
- --> Result: "The quick brown fox jumps over a lazy dog."
In JavaScript, custom scripting isnât required to perform this operation. TheArrayobject has ajoin()method, which can be called to merge a list of items together, as shown inListing 21-7.
JAVASCRIPT
Open in Script Editor
- var array = ["The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."]
- var array.join(" ")
- // Result: "The quick brown fox jumps over a lazy dog."
Note
SeeSplitting Textto learn how to break text apart, based on a specific delimiter.
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSArrayclass to convert a list of strings into a single string. The handlers inListing 21-8andListing 21-9demonstrate how to do this.
APPLESCRIPT
Open in Script Editor
- on convertListToString(theList, theDelimiter)
- set theArray to arrayWithArray_(theList) of NSArray of current application
- set theString to componentsJoinedByString_(theDelimiter) of theArray
- return (theString as string)
- end convertListToString
JAVASCRIPT
Open in Script Editor
- function convertArrayToString(array, delimiter) {
- array = $(array)
- array = array.componentsJoinedByString(delimiter)
- return array.js
- }
### Counting the Items in a List
Listing 21-10andListing 21-11show how to get the number of items in a list.
APPLESCRIPT
Open in Script Editor
- set theList to {"Apple Watch", "iMac", "iPhone", "MacBook Pro"}
- length of theList
- --> Result: 4
JAVASCRIPT
Open in Script Editor
- var array = ["Apple Watch", "iMac", "iPhone", "MacBook Pro"]
- array.length
- // Result: 4
### Counting the Occurrences of an Item in a List
The handlers inListing 21-12andListing 21-13count how many times an item appears in a list.
APPLESCRIPT
Open in Script Editor
- on countInstancesOfItemInList(theList, theItem)
- set theCount to 0
- repeat with a from 1 to count of theList
- if item a of theList is theItem then
- set theCount to theCount + 1
- end if
- end repeat
- return theCount
- end countInstancesOfItemInList
JAVASCRIPT
Open in Script Editor
- function countInstancesOfItemInArray(array, item) {
- var count = 0
- for (var element of array) {
- if (element === item) {
- count++
- }
- }
- return count
- }
Listing 21-14andListing 21-15show how to call the handlers inListing 21-12andListing 21-13.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Jen", "Ben", "David", "Chris", "Jen"}
- countInstancesOfItemInList(theList, "Jen")
- --> Result: 2
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Jen", "Ben", "David", "Chris", "Jen"]
- countInstancesOfItemInArray(array, "Jen")
- // Result: 2
### Determining if a List Contains a Specific Item
Listing 21-16andListing 21-17return atrueorfalsevalue, indicating the presence of an item in a list.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- theList contains "Lizzie"
- --> false
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array.includes("Lizzie")
- // Result: false
Listing 21-18andListing 21-19demonstrate how to add an item to a list only if the list doesnât already contain the item.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- if theList does not contain "Jen" then
- set end of theList to "Jen"
- end if
- return theList
- --> Result: {"Sal", "Ben", "David", "Chris", "Jen"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- if (!array.includes("Jen")) {
- array.push("Jen")
- }
- array
- // Result: ["Sal", "Ben", "David", "Chris", "Jen"]
### Determining the Position of an Item in a List
The handler inListing 21-20determines the position of an item the first time it appears in a list.
APPLESCRIPT
Open in Script Editor
- on getPositionOfItemInList(theItem, theList)
- repeat with a from 1 to count of theList
- if item a of theList is theItem then return a
- end repeat
- return 0
- end getPositionOfItemInList
Listing 21-21shows how to call the handler inListing 21-20. In AppleScript, list item positions start at1âthe first item in a list has a position of1.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"}
- getPositionOfItemInList("Maddie", theList)
- --> Result: 7
In JavaScript, theindexOf()method of theArrayobject can be called to determine the position of an item in an array, as shown inListing 21-22. In JavaScript, array item positions start at0âthe first item in an array has an index of0.
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie]
- array.indexOf("Maddie")
- // Result: 6
ThegetPositionOfItemInList()AppleScript handler andindexOf()JavaScript method can be used to cross-reference data between corresponding lists. InListing 21-23andListing 21-24, a person is located in a list by name. Next, the personâs phone extension is located in a corresponding list.
APPLESCRIPT
Open in Script Editor
- set theNames to {"Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"}
- set theExtensions to {"x1111", "x2222", "x3333", "x4444", "x5555", "x6666", "x7777", "x8888"}}
- set thePerson to choose from list theNames with prompt "Choose a person:"
- if thePerson is false then error number -128
- set theExtension to item (getPositionOfItemInList((thePerson as string), theNames)) of theExtensions
- display dialog "The phone extension for " & thePerson & " is " & theExtension & "."
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var names = ["Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"]
- var extensions = ["x1111", "x2222", "x3333", "x4444", "x5555", "x6666", "x7777", "x8888"]
- var people = app.chooseFromList(names, {withPrompt: "Choose a person:"})
- if (!people) {
- throw new Error(-128)
- }
- var person = people[0]
- var index = names.indexOf(person)
- console.log(index)
- var extension = extensions[index]
- app.displayDialog(`The phone extension for ${person} is ${extension}.`)
### Determining Multiple Positions of an Item in a List
The handlers inListing 21-25andListing 21-26determine every position of an item in a list.
APPLESCRIPT
Open in Script Editor
- on getPositionsOfItemInList(theItem, theList, listFirstPositionOnly)
- set thePositions to {}
- repeat with a from 1 to length of theList
- if item a of theList is theItem then
- if listFirstPositionOnly = true then return a
- set end of thePositions to a
- end if
- end repeat
- if listFirstPositionOnly is true and thePositions = {} then return 0
- return thePositions
- end getPositionsOfItemInList
JAVASCRIPT
Open in Script Editor
- function getPositionsOfItemInArray(item, array, firstPositionOnly) {
- if (firstPositionOnly) {
- return array.indexOf(item)
- }
- var indexes = []
- for (var index = 0; index < array.length; index++) {
- var element = array[index]
- if (element === item) {
- indexes.push(index)
- }
- }
- return indexes
- }
Listing 21-27andListing 21-28show how to call the handlers inListing 21-25andListing 21-26.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "Jen", "David", "Chris", "Lizzie", "Maddie", "Jen", "Lillie"}
- getPositionsOfItemInList("Jen", theList, false)
- --> Result: {3, 8}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "Jen", "David", "Chris", "Lizzie", "Maddie", "Jen", "Lillie"]
- getPositionsOfItemInArray("Jen", array, false)
- // Result: [2, 7]
### Finding the Highest Numeric Value in a List
The handlers inListing 21-29andListing 21-30determine the highest numeric value in a list of items. The passed list can contain non-numeric data as well as lists within lists.
APPLESCRIPT
Open in Script Editor
- on getHighestNumberInList(theList)
- set theHighestNumber to false
- repeat with a from 1 to count of theList
- set theCurrentItem to item a of theList
- set theClass to class of theCurrentItem
- if theClass is in {integer, real} then
- if theHighestNumber is "" then
- set theHighestNumber to theCurrentItem
- else if theCurrentItem is greater than theHighestNumber then
- set theHighestNumber to item a of theList
- end if
- else if theClass is list then
- set theHighValue to getHighestNumberInList(theCurrentItem)
- if theHighValue is greater than theHighestNumber then
- set theHighestNumber to theHighValue
- end if
- end if
- end repeat
- return theHighestNumber
- end getHighestNumberInList
JAVASCRIPT
Open in Script Editor
- function getHighestNumberInList(list) {
- var highestNumber = undefined
- for (var item of list) {
- var number = undefined
- if (item.constructor === Number) {
- number = item
- }
- else if (item.constructor === Array) {
- number = getHighestNumberInList(item)
- }
- if (number != undefined && (highestNumber === undefined || number > highestNumber)) {
- highestNumber = number
- }
- }
- return highestNumber
- }
Listing 21-31andListing 21-32show how to call the handlers inListing 21-29andListing 21-30for a list containing a mixture of numbers and strings.
APPLESCRIPT
Open in Script Editor
- getHighestNumberInList({-3.25, 23, 2345, "sid", 3, 67})
- --> Result: 2345
JAVASCRIPT
Open in Script Editor
- getHighestNumberInList([-3.25, 23, 2345, "sid", 3, 67])
- // Result: 2345
Listing 21-33andListing 21-34show how to call the handlers inListing 21-29andListing 21-30for a list containing a mixture of numbers, strings, booleans, and lists.
APPLESCRIPT
Open in Script Editor
- getHighestNumberInList({-3.25, 23, {23, 78695, "bob"}, 2345, true, "sid", 3, 67})
- --> Result: 78695
JAVASCRIPT
Open in Script Editor
- getHighestNumberInList([-3.25, 23, [23, 78695, "bob"], 2345, true, "sid", 3, 67])
- // Result: 78695
Listing 21-35andListing 21-36show how to call the handlers inListing 21-29andListing 21-30for a list containing only strings.
APPLESCRIPT
Open in Script Editor
- getHighestNumberInList({"this", "list", "contains", "only", "text"})
- --> Result: false
JAVASCRIPT
Open in Script Editor
- getHighestNumberInList(["this", "list", "contains", "only", "text"])
- // Result: undefined
### Finding the Lowest Numeric Value in a List
The handlers inListing 21-37andListing 21-38determines the lowest numeric value in a list of items. The passed list can contain non-numeric data as well as lists within lists.
APPLESCRIPT
Open in Script Editor
- on getLowestNumberInList(theList)
- set theLowestNumber to false
- repeat with a from 1 to count of theList
- set theCurrentItem to item a of theList
- set theClass to class of theCurrentItem
- if theClass is in {integer, real} then
- if theLowestNumber is "" then
- set theLowestNumber to theCurrentItem
- else if theCurrentItem is less than theLowestNumber then
- set theLowestNumber to item a of theList
- end if
- else if theClass is list then
- set theLowValue to getLowestNumberInList(theCurrentItem)
- if theLowValue is less than theLowestNumber then
- set theLowestNumber to theLowValue
- end if
- end if
- end repeat
- return theLowestNumber
- end getLowestNumberInList
JAVASCRIPT
Open in Script Editor
- function getLowestNumberInList(list) {
- var lowestNumber = undefined
- for (var item of list) {
- var number = undefined
- if (item.constructor === Number) {
- number = item
- }
- else if (item.constructor === Array) {
- number = getLowestNumberInList(item)
- }
- if (number != undefined && (lowestNumber === undefined || number < lowestNumber)) {
- lowestNumber = number
- }
- }
- return lowestNumber
- }
Listing 21-39andListing 21-40show how to call the handlers inListing 21-37andListing 21-38for a list containing a mixture of numbers and strings.
APPLESCRIPT
Open in Script Editor
- getLowestNumberInList({-3.25, 23, 2345, "sid", 3, 67})
- --> Result: -3.25
JAVASCRIPT
Open in Script Editor
- getLowestNumberInList([-3.25, 23, 2345, "sid", 3, 67])
- // Result: -3.25
Listing 21-41andListing 21-42show how to call the handlers inListing 21-37andListing 21-38for a list containing a mixture of numbers, strings, booleans, and lists.
APPLESCRIPT
Open in Script Editor
- getLowestNumberInList({-3.25, 23, {-22, 78695, "Sal"}, 2345, true, "sid", 3, 67})
- --> Result: -22
JAVASCRIPT
Open in Script Editor
- getLowestNumberInList([-3.25, 23, [-22, 78695, "bob"], 2345, true, "sid", 3, 67])
- // Result: -22
Listing 21-43andListing 21-44show how to call the handlers inListing 21-37andListing 21-38for a list containing only strings.
APPLESCRIPT
Open in Script Editor
- getLowestNumberInList({"this", "list", "contains", "only", "text"})
- --> Result: false
JAVASCRIPT
Open in Script Editor
- getLowestNumberInList(["this", "list", "contains", "only", "text"])
- // Result: undefined
### Inserting Items into a List
The handlers inListing 21-45andListing 21-46insert an item into a list. Provide the item to insert, the list, and the position where the item should be inserted. Note that position can be specified in relation to the end of the list by using a negative number.
Note
In JavaScript, theArrayclass has built-in methodsâunshift(inserts at the beginning),splice(inserts at a specific position), andpush(inserts at the end)âfor inserting items into a list, requiring less custom scripting than is necessary in AppleScript.
APPLESCRIPT
Open in Script Editor
- on insertItemInList(theItem, theList, thePosition)
- set theListCount to length of theList
- if thePosition is 0 then
- return false
- else if thePosition is less than 0 then
- if (thePosition * -1) is greater than theListCount + 1 then return false
- else
- if thePosition is greater than theListCount + 1 then return false
- end if
- if thePosition is less than 0 then
- if (thePosition * -1) is theListCount + 1 then
- set beginning of theList to theItem
- else
- set theList to reverse of theList
- set thePosition to (thePosition * -1)
- if thePosition is 1 then
- set beginning of theList to theItem
- else if thePosition is (theListCount + 1) then
- set end of theList to theItem
- else
- set theList to (items 1 thru (thePosition - 1) of theList) & theItem & (items thePosition thru -1 of theList)
- end if
- set theList to reverse of theList
- end if
- else
- if thePosition is 1 then
- set beginning of theList to theItem
- else if thePosition is (theListCount + 1) then
- set end of theList to theItem
- else
- set theList to (items 1 thru (thePosition - 1) of theList) & theItem & (items thePosition thru -1 of theList)
- end if
- end if
- return theList
- end insertItemInList
JAVASCRIPT
Open in Script Editor
- function insertItemInArray(item, array, position) {
- var arrayCount = array.length
- if (Math.abs(position) > arrayCount) {
- return false
- }
- else if (position === 0) {
- array.unshift(item)
- }
- else if (position < arrayCount) {
- array.splice(position, 0, item)
- }
- else {
- array.push(item)
- }
- return array
- }
Listing 21-47andListing 21-48show how to call the handlers inListing 21-45andListing 21-46to insert a single item into a list at a specific position.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList("Jen", theList, 3)
- --> Result: {"Sal", "Ben", "Jen", "David", "Chris"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array = insertItemInArray("Jen", array, 2)
- // Result = ["Sal", "Ben", "Jen", "David", "Chris"]
Listing 21-49andListing 21-50show how to call the handlers inListing 21-45andListing 21-46to insert multiple items into a list at a specific position.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList({"Lizzie", "Maddie", "Lillie"}, theList, 3)
- --> Result: {"Sal", "Ben", "Lizzie", "Maddie", "Lillie", "David", "Chris"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- var items = ["Lizzie", "Maddie", "Lillie"]
- for (var item of items) {
- array = insertItemInArray(item, array, 2)
- }
- // Result = ["Sal", "Ben", "Lillie", "Maddie", "Lizzie", "David", "Chris"]
Listing 21-51andListing 21-52show how to call the handlers inListing 21-45andListing 21-46to insert a list into a list at a specific position.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList({{"Lizzie", "Maddie", "Lillie"}}, theList, 3)
- --> Result: {"Sal", "Ben", {"Lizzie", "Maddie", "Lillie"}, "David", "Chris"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array = insertItemInArray(["Lizzie", "Maddie", "Lillie"], array, 2)
- // Result = ["Sal", "Ben", ["Lizzie", "Maddie", "Lillie"], "David", "Chris"]
Listing 21-53andListing 21-54show how to call the handlers inListing 21-45andListing 21-46to insert a single item at the end of a list.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList("Jen", theList, -1)
- --> {"Sal", "Ben", "David", "Chris", "Jen"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array = insertItemInArray("Jen", array, array.length)
- // Result = ["Sal", "Ben", "David", "Chris", "Jen"]
Listing 21-55andListing 21-56show how to call the handlers inListing 21-45andListing 21-46to insert a single item at the second-to-last position in a list.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList("Wanda", theList, -2)
- --> {"Sal", "Sue", "Bob", "Wanda", "Carl"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array = insertItemInArray("Jen", array, -1)
- // Result = ["Sal", "Ben", "David", "Jen", "Chris"]
Listing 21-57andListing 21-58show how to call the handlers inListing 21-45andListing 21-46to insert a single item at a nonexistent position in a list.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- insertItemInList("Jen", theList, 15)
- --> Result: false
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array = insertItemInArray("Jen", array, 14)
- // Result = false
### Replacing Items in a List
You can replace an item in a list using the syntax shown inListing 21-59andListing 21-60if you know the position of the item you want to replace.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- set item 3 of theList to "Wanda"
- return theList
- --> Result: {"Sal", "Sue", "Wanda", "Carl"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array[2] = "Wanda"
- array
- // Result: ["Sal", "Ben", "Wanda", "Chris"]
The handlers inListing 21-61andListing 21-62can be used to replace an item in a list when you donât know its position. Provide the item you want to replace, the list, the replacement item, and specify whether to replace all instances of the item, or just the first one.
APPLESCRIPT
Open in Script Editor
- on replaceItemInList(theItem, theList, theReplacementItem, replaceAll)
- repeat with a from 1 to the count of theList
- set theCurrentItem to item a of theList
- if theCurrentItem is theItem then
- set item a of theList to theReplacementItem
- if replaceAll is false then return theList
- end if
- end repeat
- return theList
- end replaceItemInList
JAVASCRIPT
Open in Script Editor
- function replaceItemInArray(item, array, replacementItem, replaceAll) {
- var arrayLength = array.length
- for (var i = 0; i < arrayLength; i++) {
- var currentArrayItem = array[i]
- if (currentArrayItem === item) {
- array.splice(i, 1, replacementItem)
- if (!replaceAll) {
- break
- }
- }
- }
- return array
- }
Listing 21-63andListing 21-64show how to call the handlers inListing 21-61andListing 21-62.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Jen", "Ben", "David", "Chris", "Jen"}
- replaceItemInList("Jen", theList, "Lizzie", true)
- --> {"Sal", "Lizzie", "Ben", "David", "Chris", "Lizzie"}
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Jen", "Ben", "David", "Chris", "Jen"]
- replaceItemInArray("Jen", array, "Lizzie", true)
- // Result: ["Sal", "Lizzie", "Ben", "David", "Chris", "Lizzie"]
### Sorting a List
The handler inListing 21-65sorts a list of strings or numbers in AppleScript.
APPLESCRIPT
Open in Script Editor
- on sortList(theList)
- set theIndexList to {}
- set theSortedList to {}
- repeat (length of theList) times
- set theLowItem to ""
- repeat with a from 1 to (length of theList)
- if a is not in theIndexList then
- set theCurrentItem to item a of theList as text
- if theLowItem is "" then
- set theLowItem to theCurrentItem
- set theLowItemIndex to a
- else if theCurrentItem comes before theLowItem then
- set theLowItem to theCurrentItem
- set theLowItemIndex to a
- end if
- end if
- end repeat
- set end of theSortedList to theLowItem
- set end of theIndexList to theLowItemIndex
- end repeat
- return theSortedList
- end sortList
Listing 21-66shows how to call the handler inListing 21-65.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- sortList(theList)
- --> Result: {"Ben", "Chris", "David", "Sal"}
To perform a reverse (descending) sort, use the reverse command, as shown inListing 21-67.
APPLESCRIPT
Open in Script Editor
- set theList to {"Sal", "Ben", "David", "Chris"}
- reverse of sortList(theList)
- --> Result: {"Sal", "David", "Chris", "Ben"}
In JavaScript, theArrayobject has asortmethod, which sorts the arrayâs items. SeeListing 21-68.
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array.sort()
- // Result: ["Ben", "Chris", "David", "Sal"]
As in AppleScript, a sorted JavaScript array can be reversed, as shown inListing 21-69.
JAVASCRIPT
Open in Script Editor
- var array = ["Sal", "Ben", "David", "Chris"]
- array.sort()
- array.reverse()
- // Result: ["Sal", "David", "Chris", "Ben"]
Note
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSArrayclass to convert a list of strings into a single string. The handlers inListing 21-70andListing 21-71demonstrate how to do this.
APPLESCRIPT
Open in Script Editor
- on sortList(theList)
- set theArray to arrayWithArray_(theList) of NSArray of current application
- set theSortedList to sortedArrayUsingSelector_("localizedStandardCompare:") of theArray
- return (theSortedList as list)
- end sortList
JAVASCRIPT
Open in Script Editor
- function sortArray(array) {
- array = $(array)
- var sortedArray = array.sortedArrayUsingSelector("localizedStandardCompare:")
- return ObjC.deepUnwrap(sortedArray)
- }
Manipulating Numbers
Displaying Dialogs and Alerts
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Referencing Files and Folders
## Referencing Files and Folders
### Referencing Files and Folders in AppleScript
In AppleScript, file and folder paths are typically represented usingalias,file, andPOSIX fileobjects.
Note
Additional information about working with file and folder paths in AppleScript can be found inAliases and FilesinAppleScript Language Guide.
### Alias Objects
Analiasobject dynamically points to an existing item in the file system. Since an alias is dynamic, it continues pointing to the item even if the item is renamed or moved, the same way an alias file works when you manually create one in the Finder. With an AppleScript alias, the original item must exist at run time or an error will occur.
Analiasobject is displayed as a colon-delimited path preceded by analiasspecifier, in the format shown inListing 15-1.
APPLESCRIPT
Open in Script Editor
- alias "VolumeName:FolderName:SubfolderName:FileName"
Listing 15-2shows an example of analiasobject that references the Desktop folder.
APPLESCRIPT
Open in Script Editor
- alias "Macintosh HD:Users:yourUserName:Desktop:"
Listing 15-3is an example of analiasobject that references an existing file on the Desktop.
APPLESCRIPT
Open in Script Editor
- alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
To create an alias, add the alias specifier prefix to a colon-delimited path string, as shown inListing 15-4.
APPLESCRIPT
Open in Script Editor
- set thePath to alias "Macintosh HD:Users:yourUserName:Desktop:"
Many commands accept an alias as a parameter and/or return an alias as a result. InListing 15-5, thechoose filecommand accepts a folderaliasobject in itsdefault locationparameter. The command then returns analiasobject that points to the chosen file.
APPLESCRIPT
Open in Script Editor
- set theDefaultFolder to alias "Macintosh HD:Users:yourUserName:Desktop:"
- choose file default location theDefaultFolder
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
### File Objects
Afileobject is a static reference to an item at a specific location in the file system. Itâs not dynamic, and can even refer to an item that doesnât exist yet. For example, asavecommand may accept a file reference when saving to a new file.
Afileobject is displayed as a colon-delimited path preceded by afilespecifier, in the format shown inListing 15-6.
APPLESCRIPT
Open in Script Editor
- file "VolumeName:FolderName:SubfolderName:FileName"
Listing 15-7shows an example of afileobject that references a file that may or may not exist on the Desktop.
APPLESCRIPT
Open in Script Editor
- file "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
Unlike the way analiasobject works, you canât create afileobject simply by prefixing a path string with thefilespecifier. For example,Listing 15-7errors when run within a script.
APPLESCRIPT
Open in Script Editor
- set theFile to file "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
Instead, you must prefix the path with thefilespecifier at the time the file is targeted by a command, as shown inListing 15-8.
APPLESCRIPT
Open in Script Editor
- set theFile to "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- read file theFile
Note
Afileobject can refer to either a file or a folder, despite thefilespecifier prefix.
### POSIX File Objects
Some scriptable apps are designed to work with POSIX-style paths, rather than AppleScriptaliasandfileobjects. Like afileobject, aPOSIX fileobject is not dynamic and can also refer to an item that doesnât exist yet.
APOSIX fileobject is displayed as a slash-delimited path preceded by aPOSIX filespecifier, in the format shown inListing 15-10.
APPLESCRIPT
Open in Script Editor
- POSIX file "/FolderName/SubfolderName/FileName"
Listing 15-11is an example of aPOSIX fileobject that references a file that may or may not exist on the Desktop.
APPLESCRIPT
Open in Script Editor
- POSIX file "/Users/yourUserName/Desktop/My File.txt"
Note
APOSIX fileobject can refer to either a file or a folder, despite thePOSIX filespecifier prefix.
In a POSIX path, the startup diskâs name is omitted and represented by a leading slash. Other disks are referenced in relation to theVolumesdirectory of the startup disk, for example:/Volumes/DiskName/FolderName/SubFolderName/FileName.
### App-Specific References to Files and Folders
Some apps, such as the Finder and System Events, have their own syntax for referring to files and folders.Listing 15-12shows how a Finder file reference appears.
APPLESCRIPT
Open in Script Editor
- document file "My File.txt" of folder "Desktop" of folder "yourUserName" of folder "Users" of startup disk of application "Finder"
Listing 15-13shows how a System Events folder reference appears.
APPLESCRIPT
Open in Script Editor
- folder "Macintosh HD:Users:yourUserName:Desktop:" of application "System Events"
Since this terminology is app-specific, it doesnât work in other apps. For example, you canât write a script that tries to import a Finder reference to an audio file into iTunes because iTunes doesnât understand Finder file references. In this case, you must coerce the Finder file reference to something iTunes can understand, like an alias. SeeConverting Between Path Formatsbelow. In most cases, apps with their own path syntax also support standard AppleScript path types.
### Converting Between Path Formats
Since different situations may result in paths appearing in different formats, you may need to regularly convert one path format to another. Sometimes, this can be done by using theascoercion operator, as shown inListing 15-14,Listing 15-15,Listing 15-16, andListing 15-17.
APPLESCRIPT
Open in Script Editor
- set theFilePath to "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- set theFilePath to theFilePath as alias
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
APPLESCRIPT
Open in Script Editor
- set theFilePath to choose file
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- set theFilePath to theFilePath as string
- --> Result: "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
APPLESCRIPT
Open in Script Editor
- set theFilePath to POSIX file "/Users/yourUserName/Desktop/My File.txt"
- set theFilePath to theFilePath as alias
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
APPLESCRIPT
Open in Script Editor
- tell application "Finder"
- set theFilePath to file "My File.txt" of desktop
- end tell
- --> Result: document file "My File.txt" of folder "Desktop" of folder "yourUserName" of folder "Users" of startup disk of application "Finder"
- set theFilePath to theFilePath as alias
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
Converting from a string or alias to a POSIX path canât be done through coercion. Instead, you must access thePOSIX pathproperty of the path to convert, as shown inListing 15-18.
APPLESCRIPT
Open in Script Editor
- set theFilePath to choose file
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- set theFilePath to POSIX path of theFilePath
- --> Result: "/Users/yourUserName/Desktop/My File.txt"
### Using Conversion Handlers
Running paths through a conversion handler is a good way to ensure the format you expect.
### Converting a Path to an Aliases
The handler inListing 15-19converts strings,pathobjects,POSIX fileobjects, Finder paths, and System Events paths toaliasformat.
APPLESCRIPT
Open in Script Editor
- on convertPathToAlias(thePath)
- tell application "System Events"
- try
- return (path of disk item (thePath as string)) as alias
- on error
- return (path of disk item (path of thePath) as string) as alias
- end try
- end tell
- end convertPathToAlias
Listing 15-19shows how to call the handler inListing 15-19to convert a POSIX-style path string to an alias.
APPLESCRIPT
Open in Script Editor
- set thePath to "/Users/yourUserName/Desktop/My File.txt"
- set thePath to convertPathToAlias(thePath)
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
### Converting a Path to a String
The handler inListing 15-21converts a path to string format.
APPLESCRIPT
Open in Script Editor
- on convertPathToString(thePath)
- tell application "System Events"
- try
- return path of disk item (thePath as string)
- on error
- return path of thePath
- end try
- end tell
- end convertPathToString
Listing 15-22shows how to call the handler inListing 15-21to convert an alias to a path string.
APPLESCRIPT
Open in Script Editor
- set thePath to alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- set thePath to convertPathToString(thePath)
- --> Result: "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
### Converting a Path to a POSIX Path String
The handler inListing 15-23converts a path to POSIX path string format.
APPLESCRIPT
Open in Script Editor
- on convertPathToPOSIXString(thePath)
- tell application "System Events"
- try
- set thePath to path of disk item (thePath as string)
- on error
- set thePath to path of thePath
- end try
- end tell
- return POSIX path of thePath
- end convertPathToPOSIXString
Listing 15-24shows how to call the handler inListing 15-23to convert an alias to a path string.
APPLESCRIPT
Open in Script Editor
- set thePath to alias "Macintosh HD:Users:yourUserName:Desktop:My File.txt"
- set thePath to convertPathToPOSIXString(thePath)
- --> Result: "/Users/yourUserName/Desktop/My File.txt"
### Referencing Files and Folders in JavaScript
In JavaScript, file and folder paths are represented usingPathobjects.
To create a path, pass a POSIX-style string to thePathobject, as shown inListing 15-25.
JAVASCRIPT
- Path("/FolderName/SubfolderName/FileName")
To convert a path to a string, call thetoString()method on the path, as shown inListing 15-26.
JAVASCRIPT
Open in Script Editor
- var path = Path("/Users/yourUserName/Desktop/My File.txt")
- var string = path.toString()
- string
- // Result: "/Users/yourUserName/Desktop/My File.txt"
Using Script Libraries
Reading and Writing Files
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Manipulating Images
## Manipulating Images
Image Events is a scriptable background app in OSÂ X that can be used to automate the manipulation of images without the need for a fully-featured image editor. You can use Image Events to:
- Read image properties
Read image properties
- Flip and rotate images
Flip and rotate images
- Crop and add padding to images
Crop and add padding to images
- Resize images
Resize images
- Convert images from one type to another
Convert images from one type to another
The Image Events app is located in/System/Library/CoreServices/. You can access its dictionary from the Library palette in Script Editor. SeeOpening a Scripting Dictionary.
Note
Image Events can read and save most standard image formats, including.bmp,.jpg,.png,.psd, and.tif. Image Events can read.pdffiles, but cannot save them.
### The Image Events Workflow
To manipulate an image with Image Events, a script typically performs the following sequential steps:
- Open the Image Events app.
Open the Image Events app.
- Open an image file.
Open an image file.
- Access image properties or manipulate the image.
Access image properties or manipulate the image.
- Save the modified image as a new image file or overwriting the original image file.
Save the modified image as a new image file or overwriting the original image file.
- Close the image.
Close the image.
### Opening an Image
An image must be opened before Image Events can interact with it. To open an image, use theopencommand and provide the imageâs path, as shown inListing 38-1.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Launch Image Events and open the image
- tell application "Image Events"
- launch
- open theImageFile
- end tell
- --> Result: image "My Image.png" of application "Image Events"
The result of the open command is animageobject, the newly opened image. Since Image Events is a background app, opening an image produces no visible changes onscreenâyou wonât actuallyseethe opened image.
Note
When working with Image Events, use thelaunchcommand to make sure itâs running rather than theactivatecommand, which is reserved for apps with interfaces.
### Reading Image Properties
Like all scriptable objects, images have attributes that define them, such as dimensions, color space, and resolution. Theimageclass in the Image Events scripting dictionary contains a variety of properties for key attributes.Listing 38-2shows how to access some of these properties. First, it retrieves a record of available properties for a selected image. Next, it retrieves some individual properties.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- -- Read the image's properties
- tell theImage
- properties
- --> {color space:RGB, image file:file "Macintosh HD:Users:YourUserName:Desktop:My Image.png" of application "Image Events", bit depth:millions of colors, dimensions:{293, 252}, location:folder "Macintosh HD:Users:YourUserName:Desktop:" of application "Image Events", embedded profile:profile "Thunderbolt Display" of image "My Image.png" of application "Image Events", file type:PNG, class:image, name:"My Image.png", resolution:{72.0, 72.0}}
- -- Read the image's resolution
- resolution
- --> {72.0, 72.0}
- -- Read the image's type
- file type
- --> PNG
- -- Read the name of the image's embedded profile
- name of embedded profile
- --> "Thunderbolt Display"
- end tell
- end tell
### Flipping an Image
Theflipcommand reverses the axis of an image. It has two options for the required parameter:horizontalfor changing the axis of the image on a horizontal plane, andverticalfor changing the axis of the image on a vertical plane.Listing 38-3flips an image both horizontally and vertically.
Important
The script inListing 38-3saves a chosen image as a new file with a prefix oftemp-. If another file exists with this same name, it is overwritten.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Determine a save name for the image
- set theName to name
- set theSaveName to "temp-" & theName
- -- Flip the image horizontally
- flip with horizontal
- -- Flip the image vertically
- flip with vertical
- -- Save the image to the output folder, using the save name
- save as file type in (theOutputFolder & theSaveName)
- -- Close the image
- close
- end tell
- end tell
### Rotating an Image
Therotatecommand rotates an image around its center point. To rotate an image clockwise, provide the commandâsto angleparameter with an integer value between1to359(seeListing 38-4). To rotate an image counter-clockwise, provide a negative value, such as-90.
Important
The script inListing 38-4saves a chosen image as a new file with a prefix oftemp-. If another file exists with this same name, it is overwritten.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Determine a save name for the image
- set theName to name
- set theSaveName to "temp-" & theName
- -- Rotate an image 45 degrees
- rotate to angle 45
- -- Save the image to the output folder, using the save name
- save as file type in (theOutputFolder & theSaveName)
- -- Close the image
- close
- end tell
- end tell
### Scaling an Image
Scaling an image proportionally increases or decreases its dimensions. Thescalecommand can resize images in one of two ways:
- To scale an image by percentage, provide a decimal value for theby factorparameter. The value1is equivalent to 100%. The value.5is 50%. The value1.5is 150% and so on.Use the following formula to determine the scaling factor:«percentage» * .01
To scale an image by percentage, provide a decimal value for theby factorparameter. The value1is equivalent to 100%. The value.5is 50%. The value1.5is 150% and so on.
Use the following formula to determine the scaling factor:
«percentage» * .01
- To scale an image to a specific size, provide an integer value for theto sizeparameter. This value indicates the maximum number of pixels for the resized image on its longest side.
To scale an image to a specific size, provide an integer value for theto sizeparameter. This value indicates the maximum number of pixels for the resized image on its longest side.
Scaling doesnât change the resolution of an image. For example, a 72 dpi image that has been scaled to 50% of its original dimensions still has a resolution of 72 dpi.
Listing 38-5demonstrates how to resize an image. It can scale by percentage or pixels, depending on the value of a Boolean variable.
Important
The script inListing 38-5saves a chosen image as a new file with a prefix oftemp-. If another file exists with this same name, it is overwritten.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- To scale by percentage, set this value to true. To scale to a specific size, set it to false.
- set scaleByPercentage to true
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Determine a save name for the image
- set theName to name
- set theSaveName to "temp-" & theName
- -- Scale the image by 50%
- if scaleByPercentage = true then
- scale by factor 0.5
- -- Scale the image to 100px on its longese side
- else
- scale to size 100
- end if
- -- Save the image to the output folder, using the save name
- save as file type in (theOutputFolder & theSaveName)
- -- Close the image
- close
- end tell
- end tell
### Cropping an Image
Cropping an image removes pixels around all of its sides, centering the remaining area. Theto dimensionsrequired parameter takes a list of two integers: the new width and height, in pixels. InListing 38-6, an image is cropped to 100 by 100 pixels.
Important
The script inListing 38-6saves a chosen image as a new file with a prefix oftemp-. If another file exists with this same name, it is overwritten.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Determine a save name for the image
- set theName to name
- set theSaveName to "temp-" & theName
- -- Crop the image to 100px by 100px
- crop to dimensions {100, 100}
- -- Save the image to the output folder, using the save name
- save as file type in (theOutputFolder & theSaveName)
- -- Close the image
- close
- end tell
- end tell
### Padding an Image
Padding an image adds space around its sides. Itâs essentially the reverse of cropping an image, although negative padding an image produces cropping. Theto dimensionsrequired parameter takes a list of two integers: the new width and height, in pixels. The optionalwith pad colorparameter can be used to specify the color of the padding. InListing 38-7, 20 pixels of padding is added around an image.
Important
The script inListing 38-7saves a chosen image as a new file with a prefix oftemp-. If another file exists with this same name, it is overwritten.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Prompt for a color
- set theColor to choose color
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Determine a save name for the image
- set theName to name
- set theSaveName to "temp-" & theName
- -- Get the current dimensions of the image
- set {theWidth, theHeight} to dimensions
- -- Pad the image by 20 pixels on all sides
- pad to dimensions {theWidth + 20, theHeight + 20} with pad color theColor
- -- Save the image to the output folder, using the save name
- save as file type in (theOutputFolder & theSaveName)
- -- Close the image
- close
- end tell
- end tell
Note
Images containing transparency result in transparent padding, regardless of whether a color is specified.
### Converting an Image from One Type to Another
To convert an image from one type to another, open it and save it in another format.Listing 38-8saves a chosen image in.jpg,.psd, and.tifformat.
APPLESCRIPT
Open in Script Editor
- -- Prompt for an image
- set theImageFile to choose file of type "public.image" with prompt ""
- -- Locate an output folder
- set theOutputFolder to (path to desktop folder as string)
- -- Launch Image Events
- tell application "Image Events"
- launch
- -- Open the image
- set theImage to open theImageFile
- tell theImage
- -- Save the image as a .jpg
- save as JPEG in (theOutputFolder & "temp-conversion-output.jpg")
- -- Save the image as a .psd
- save as PSD in (theOutputFolder & "temp-conversion-output.psd")
- -- Save the image as a .tif
- save as TIFF in (theOutputFolder & "temp-conversion-output.tif")
- -- Close the image
- close
- end tell
- end tell
Automating the User Interface
Calling Command-Line Tools
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Navigating a Scripting Dictionary
## Navigating a Scripting Dictionary
A scripting dictionary window in Script Editor contains three primary areas. SeeFigure 12-1.
- Toolbar.Options for toggling between terminology views, setting the scripting language, entering search terms, and more.
Toolbar.Options for toggling between terminology views, setting the scripting language, entering search terms, and more.
- Navigation pane.Columns of scripting terminology.
Navigation pane.Columns of scripting terminology.
- Detail pane.Definitions for any terminology selected in the navigation pane.
Detail pane.Definitions for any terminology selected in the navigation pane.
### Types of Terminology
The navigation pane of a dictionary includes the types of terms described inTable 12-1.
Type
Icon
Description
Suite
Asuiteis a grouping of related commands and classes. Apps often have a Standard Suite, which includes terminology supported by most scriptable apps, such as anopencommand, aquitcommand, and anapplicationclass.
Command
Acommandis an instruction that can be sent to an app or object in order to initiate some action. For example,delete,make,printare commands that are found in many scriptable apps. Many commands haveparametersthat specify the target object and control the behavior of the command.
Class
Aclassis an object within an app, or an app itself. Mail, for example, has anapplicationclass, amessageclass, and asignatureclass, among others. Objects within an app sometimes contain other objects aselements. For example, in Mail, amailboxobjects can containmessageobjects as elements.
Property
Apropertyis an attribute of a class. For example, themessageclass in Mail has many properties, includingdate received,read status, andsubject. Some properties are read-only, while others are readable and writable.
### Key Concepts
Itâs important to understand the concepts ofinheritanceandcontainmentwhen navigating a scripting dictionary.
### Inheritance
In a scriptable app, different classes often implement the same properties. For example, in Finder, thefileandfolderclasses both havecreation date,modification date, andnameproperties. Rather than defining these same properties multiple times throughout the scripting dictionary, Finder implements a genericitemclass. Since files and folders are considered types of Finder items, these classes inherit the properties of theitemclass. In other words, any properties of theitemclass also apply to thefileandfolderclasses. There are many other items in Finder that also inherit these same properties, including thedisk,package, andalias fileclasses.
A class that inherits the properties of other classes can also implement its own properties. In Finder, thefileclass implements a number of file-specific properties, includingfile typeandversion. Thealias fileclass implements anoriginal itemproperty.
In some cases, a class inherits properties from multiple classes. In Finder, an alias is a type of file, which is a type of item. Therefore, thealias fileclass inherits the properties of both thefileanditemclasses, as shown inFigure 12-2.
### Containment
Classes of a scriptable app reside within a certain containment hierarchy. The application is at the top level, with other classes nested beneath. Finder, for example, contains disks, folders, files, and other objects. While files donât contain elements, folders and disks can contain other folders and files. SeeFigure 12-3. Mail is another exampleâthe application contains accounts, which can contain mailboxes, which can contain other mailboxes and messages.
When referencing a class, you must do so very specifically according to its containment hierarchy in order to provide the scripting system with context. To reference a file in Finder, you would specify where the file resides in the folder hierarchy. SeeListing 12-1andListing 12-2. To reference a message in Mail, you would specify where the message resides in the mailbox and account hierarchy.
APPLESCRIPT
Open in Script Editor
- tell application "Finder"
- modification date of file "My File.txt" of folder "Documents" of folder "YourUserName" of folder "Users" of startup disk
- end tell
- --> Result: date "Monday, September 28, 2015 at 10:10:17 AM"
JAVASCRIPT
Open in Script Editor
- var Finder = Application("Finder")
- Finder.startupDisk.folders["Users"].folders["YourUserName"].folders["Documents"].files["My File.txt"].modificationDate()
- // Result: Mon Sep 28 2015 17:10:17 GMT-0700 (PDT)
### Anatomy of a Command Definition
The definition of a command in a scripting dictionary is a recipe for using the command, as shown inFigure 12-4,Listing 12-3, andListing 12-4.
A command definition includes the following elements:
- Command name.The name of the command.
Command name.The name of the command.
- Direct parameter.An object to be targeted by the command. For themovecommand in Finder, this is the object to be moved. If a command definition doesnât specify a direct parameter, then the target object is the application. A direct parameter immediately follows the command.
Direct parameter.An object to be targeted by the command. For themovecommand in Finder, this is the object to be moved. If a command definition doesnât specify a direct parameter, then the target object is the application. A direct parameter immediately follows the command.
- Labeled parameters.Control some aspect of the commandâs behavior and are required or optional. Optional parameters are surrounded by brackets. Since these parameters are identified by label, they can be placed in any order when you write your script. The command definition denotes the value type for each labeled parameter. For example, the optionalreplacingparameter for themovecommand in Finder takes a boolean value.
Labeled parameters.Control some aspect of the commandâs behavior and are required or optional. Optional parameters are surrounded by brackets. Since these parameters are identified by label, they can be placed in any order when you write your script. The command definition denotes the value type for each labeled parameter. For example, the optionalreplacingparameter for themovecommand in Finder takes a boolean value.
- Result.The result of the command, if any. Often, this is a reference to a newly created or modified object. For themovecommand in Finder, itâs a reference to the moved object.
Result.The result of the command, if any. Often, this is a reference to a newly created or modified object. For themovecommand in Finder, itâs a reference to the moved object.
APPLESCRIPT
Open in Script Editor
- tell application "Finder"
- move folder someFolder to someOtherFolder replacing true
- end tell
JAVASCRIPT
Open in Script Editor
- var Finder = Application("Finder")
- Finder.move(someFolder, {
- to: someOtherFolder,
- replacing: true
- })
### Anatomy of a Class Definition
A class definition describes a class, as shown inFigure 12-5.
A class definition includes the following elements:
- Class name.The name of the class.
Class name.The name of the class.
- Inheritance details.A list of other classes from which properties are inherited, if any. Each class is a hyperlinkâclicking it takes you to the definition for the corresponding class.
Inheritance details.A list of other classes from which properties are inherited, if any. Each class is a hyperlinkâclicking it takes you to the definition for the corresponding class.
- Containment details.A list of contained classes, if any. May also list other classes containing the class, if any.
Containment details.A list of contained classes, if any. May also list other classes containing the class, if any.
- Properties.Any properties for the class, along with their data types. Read-only properties include anr/oindicator.
Properties.Any properties for the class, along with their data types. Read-only properties include anr/oindicator.
To view inherited properties, as well as containing classes in the Script Editor dictionary viewer, select Show inherited items in Preferences > General. SeeFigure 12-6.
Opening a Scripting Dictionary
Using Handlers/Functions
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Reading and Writing Files
## Reading and Writing Files
Scripts are often designed to write data to files such as logs or backups. The Standard Additions scripting addition contains a number of commands that make it possible to read and write files.
### Writing to a File
The handlers inListing 16-1andListing 16-2safely write data to disk, creating a new file if the targeted file doesnât already exist. Provide the text to write, a target file path, and indicate whether to overwrite existing content. If you choose not to overwrite existing content, then the text provided is appended to any existing content.
APPLESCRIPT
Open in Script Editor
- on writeTextToFile(theText, theFile, overwriteExistingContent)
- try
- -- Convert the file to a string
- set theFile to theFile as string
- -- Open the file for writing
- set theOpenedFile to open for access file theFile with write permission
- -- Clear the file if content should be overwritten
- if overwriteExistingContent is true then set eof of theOpenedFile to 0
- -- Write the new content to the file
- write theText to theOpenedFile starting at eof
- -- Close the file
- close access theOpenedFile
- -- Return a boolean indicating that writing was successful
- return true
- -- Handle a write error
- on error
- -- Close the file
- try
- close access file theFile
- end try
- -- Return a boolean indicating that writing failed
- return false
- end try
- end writeTextToFile
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function writeTextToFile(text, file, overwriteExistingContent) {
- try {
- // Convert the file to a string
- var fileString = file.toString()
- // Open the file for writing
- var openedFile = app.openForAccess(Path(fileString), { writePermission: true })
- // Clear the file if content should be overwritten
- if (overwriteExistingContent) {
- app.setEof(openedFile, { to: 0 })
- }
- // Write the new content to the file
- app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) })
- // Close the file
- app.closeAccess(openedFile)
- // Return a boolean indicating that writing was successful
- return true
- }
- catch(error) {
- try {
- // Close the file
- app.closeAccess(file)
- }
- catch(error) {
- // Report the error is closing failed
- console.log(`Couldn't close file: ${error}`)
- }
- // Return a boolean indicating that writing was successful
- return false
- }
- }
Listing 16-3andListing 16-4show how to call the handlers inListing 16-1andListing 16-2to write text content to a file on the Desktop, replacing any existing content in the file.
APPLESCRIPT
Open in Script Editor
- set this_story to "Once upon a time in Silicon Valley..."
- set theFile to (((path to desktop folder) as string) & "MY STORY.txt")
- writeTextToFile(this_story, theFile, true)
JAVASCRIPT
Open in Script Editor
- var story = "Once upon a time in Silicon Valley..."
- var desktopString = app.pathTo("desktop").toString()
- var file = `${desktopString}/MY STORY.txt`
- writeTextToFile(story, file, true)
Listing 16-5andListing 16-6show howListing 16-1andListing 16-2could be called to insert dated log entries into a log file.
APPLESCRIPT
Open in Script Editor
- set theText to ((current date) as string) & space & "STATUS OK" & return
- set theFile to (((path to desktop folder) as string) & "MY LOG FILE.log")
- writeTextToFile(theText, theFile, false)
JAVASCRIPT
Open in Script Editor
- var dateString = Date().toString()
- var desktopString = app.pathTo("desktop").toString()
- var text = `${dateString} STATUS OK\n\n`
- var file = `${desktopString}/MY LOG FILE.log`
- writeTextToFile(text, file, false)
In practice, this technique could be used to maintain a log when script errors occur.Listing 16-7andListing 16-8are try statements, which can be wrapped around custom script code in order to log any script errors to a file in the~/Library/Logs/folder of the current userâs home directory.
APPLESCRIPT
Open in Script Editor
- try
- -- Your custom script code goes here
- on error theErrorMessage number theErrorNumber
- set theError to "Error: " & theErrorNumber & ". " & theErrorMessage & return
- set theLogFile to ((path to library folder from user domain) as string) & "Logs:Script Error Log.log"
- my writeTextToFile(theError, theLogFile, false)
- end try
JAVASCRIPT
Open in Script Editor
- try {
- // Your custom script code goes here
- }
- catch (error) {
- var errorString = `Error: ${error.message}\n\n`
- var logFile = app.pathTo("library folder", { from: "user domain" }).toString() + "/Logs/Script Error Log.log"
- writeTextToFile(errorString, logFile, false)
- }
### Reading a File
The handlers inListing 16-9andListing 16-10read the contents of a specified file.
APPLESCRIPT
Open in Script Editor
- on readFile(theFile)
- -- Convert the file to a string
- set theFile to theFile as string
- -- Read the file and return its contents
- return read file theFile
- end readFile
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function readFile(file) {
- // Convert the file to a string
- var fileString = file.toString()
- // Read the file and return its contents
- return app.read(Path(fileString))
- }
Listing 16-11andListing 16-12show how to call the handlers inListing 16-9andListing 16-10to read a specified text file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file of type "txt" with prompt "Please select a text file to read:"
- readFile(theFile)
- --> Result: "Contents of the chosen file."
JAVASCRIPT
Open in Script Editor
- var file = app.chooseFile({
- ofType: "txt",
- withPrompt: "Please select a text file to read:"
- })
- readFile(file)
- // Result: "Contents of the chosen file."
### Reading and Splitting a File
The handlers inListing 16-13andListing 16-14read the contents of a specified text file, using a delimiter to split it into a list.
APPLESCRIPT
Open in Script Editor
- on readAndSplitFile(theFile, theDelimiter)
- -- Convert the file to a string
- set theFile to theFile as string
- -- Read the file using a specific delimiter and return the results
- return read file theFile using delimiter {theDelimiter}
- end readAndSplitFile
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function readAndSplitFile(file, delimiter) {
- // Convert the file to a string
- var fileString = file.toString()
- // Read the file using a specific delimiter and return the results
- return app.read(Path(fileString), { usingDelimiter: delimiter })
- }
Listing 16-15andListing 16-16shows how to call the handlers inListing 16-13andListing 16-14to read the paragraphs of a chosen log file.
APPLESCRIPT
Open in Script Editor
- set theFile to choose file of type "log" with prompt "Please select a log file:"
- readAndSplitFile(theFile, return)
- --> Result: {"Log entry 1", "Log entry 2", ... }
JAVASCRIPT
Open in Script Editor
- var file = app.chooseFile({
- ofType: "log",
- withPrompt: "Please select a log file:"
- })
- readAndSplitFile(file, "\n")
- // Result: ["Log entry 1", "Log entry 2", ...]
Referencing Files and Folders
Processing Dropped Files and Folders
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: About this Guide
## About this Guide
This guide provides high-level information about scripting on the Mac and isnât designed to serve as a language guide. Primarily, it introduces core concepts, highlights resources, and provides examples that demonstrate common scripting tasks.
This guide does not provide examples for every possible task that can be scripted in a given situation or app. For example, it doesnât cover automating every single scriptable text manipulation function. Instead, it covers automating a range of commonly encountered scenarios, such as changing the case of text, splitting text, and adding a prefix to text. These examples can be used for guidance when attempting to automate other scriptable tasks.
Many of the examples in this guide have been written modularly, allowing them to be copied and pasted into your own scripts, where they may be used as is or modified to meet your unique needs. Most examples are commented and relatively easy to follow, even with little or no prior scripting experience.
The majority of examples in this guide are provided in both AppleScript and JavaScript format. A language label precedes each example, making its language easily distinguishable at a glance. Some examples demonstrate using the scripting bridges, AppleScriptObjC and JavaScriptObjC, to interact with Objective-C classes. Additional examples are occasionally provided in notes to show alternative solutions.
Note
Some examples in this guide require OSÂ X 10.11 or later.
Some JavaScript examples in this guide use template stringsâstring literals which may include embedded expressions, such as the one shown inListing 4-1.
JAVASCRIPT
Open in Script Editor
- numberOfPeople = 12
- console.log(`There are ${numberOfPeople} people.`)
Template strings were introduced as a JavaScript standard in 2015, and are supported in OSÂ X 10.11 and later.
### Opening Examples in Script Editor
Links have been provided throughout this guide to open example code directly in Script Editor. To open an example, click the âOpen in Script Editorâ link above a code listing. Depending on the security settings on your Mac, you may be prompted to confirm you want to open the script in Script Editor. If you receive this prompt, click the New Script button to create a new document. SeeFigure 4-1andFigure 4-2.
Note
New Script Editor documents are set to use your default scripting language, as configured in the General pane of Script Editor preferences. SeeTargeting a Scripting Languageto learn how to configure an example script to target a different scripting language.
Types of Scripts
Getting to Know Script Editor
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Watching Folders
## Watching Folders
The ability to watch folders and take action on incoming items is a powerful automation technique that enables the creation of fully unattended workflows. A watched folder might be used, for example, to watermark incoming photos, convert them to PDF, and email them to clients for review. Many companies set up script serversâdedicated robot machines that watch folders and process detected items, allowing employees to offload tedious and repetitious work in order to focus on other important tasks.
In OSÂ X, there are two primary ways to set up scripting-based watched folders: folder actions and stay open script apps.
### Using Folder Actions to Watch Folders
Folder actions is a feature in OSÂ X that lets you connect scripts to folders on your Mac. A folder action script includes one or more event handlers that run in response to certain events, such as opening, closing, or adding items to the connected folder. With folder actions, you can create automated workflows that:
- Notify you when new files and folders arrive in a folder
Notify you when new files and folders arrive in a folder
- Notify you when existing files and folders are removed from a folder
Notify you when existing files and folders are removed from a folder
- Perform processing of newly detected files and folders
Perform processing of newly detected files and folders
- Initiate any automated task when a new file or folder is detected
Initiate any automated task when a new file or folder is detected
- Adjust or reset the view properties of a folderâs window when itâs opened, closed, or resized
Adjust or reset the view properties of a folderâs window when itâs opened, closed, or resized
### Write a Folder Action Script
The event handlers supported by folder actions are defined in the Standard Additions scripting addition that comes with OSÂ X. They are:
Folder event
Event handler
Parameters
Itemsâfiles or foldersâare added to the folder
adding folder items to
- Direct parameterâThe connected folder.
Direct parameterâThe connected folder.
- after receivingâA list of items added to the folder.
after receivingâA list of items added to the folder.
Items are removed from the folder
removing folder items from
- Direct parameterâThe connected folder.
Direct parameterâThe connected folder.
- after losingâA list of items removed from the folder. For items that were deleted, names of the removed items are provided.
after losingâA list of items removed from the folder. For items that were deleted, names of the removed items are provided.
The folder is opened in a new Finder window
opening folder
- Direct parameterâThe connected folder.
Direct parameterâThe connected folder.
The window of a folder is closed
closing folder window for
- Direct parameterâThe connected folder.
Direct parameterâThe connected folder.
The window of a folder is moved
moving folder window for
- Direct parameterâThe connected folder.
Direct parameterâThe connected folder.
- fromâThe coordinates of the folderâs window before it was moved.
fromâThe coordinates of the folderâs window before it was moved.
- Create a Script Editor document.
Create a Script Editor document.
- Add one or more folder action event handlers to the document.
Add one or more folder action event handlers to the document.
- Save the document as a compiled script to one of the following folders:/Library/Scripts/Folder Action Scripts/âThe script can be used by any user.~/Library/Scripts/Folder Action Scripts/âThe script can be used by the current user only.
Save the document as a compiled script to one of the following folders:
- /Library/Scripts/Folder Action Scripts/âThe script can be used by any user.
/Library/Scripts/Folder Action Scripts/âThe script can be used by any user.
- ~/Library/Scripts/Folder Action Scripts/âThe script can be used by the current user only.
~/Library/Scripts/Folder Action Scripts/âThe script can be used by the current user only.
The following examples demonstrate how to use different folder action event handlers.
APPLESCRIPT
Open in Script Editor
- on opening folder theAttachedFolder
- -- Get the name of the attached folder
- tell application "Finder"
- set theName to name of theAttachedFolder
- -- Display an alert indicating that the folder was opened
- activate
- display alert "Attention!" message "The folder " & (quoted form of theName) & " was opened."
- end tell
- end opening folder
APPLESCRIPT
Open in Script Editor
- on closing folder window for theAttachedFolder
- -- Get the name of the attached folder
- tell application "Finder"
- set theName to name of theAttachedFolder
- -- Display an alert indicating that the folder was closed
- activate
- display alert "Attention!" message "The folder " & (quoted form of theName) & " was closed."
- end tell
- end closing folder window for
APPLESCRIPT
Open in Script Editor
- on adding folder items to theAttachedFolder after receiving theNewItems
- -- Get the name of the attached folder
- tell application "Finder"
- set theName to name of theAttachedFolder
- -- Count the new items
- set theCount to length of theNewItems
- -- Display an alert indicating that the new items were received
- activate
- display alert "Attention!" message (theCount & " new items were detected in folder " & (quoted form of theName) & "." as string)
- -- Loop through the newly detected items
- repeat with anItem in theNewItems
- -- Process the current item
- -- Move the current item to another folder so it's not processed again in the future
- end repeat
- end tell
- end adding folder items to
APPLESCRIPT
Open in Script Editor
- on removing folder items from theAttachedFolder after losing theRemovedItems
- -- Get the name of the attached folder
- tell application "Finder"
- set theName to name of theAttachedFolder
- -- Count the removed items
- set theCount to length of theRemovedItems
- -- Display an alert indicating that items were removed
- activate
- display alert "Attention!" message (theCount & " items were removed from folder " & (quoted form of theName) & "." as string)
- -- Loop through the removed items, performing any additional tasks
- repeat with anItem in theRemovedItems
- -- Process the current item
- end repeat
- end tell
- end removing folder items from
### Attaching a Folder Action Script to a Folder
A folder action script must be connected to a folder in order to use it. This is done with Folder Actions Setup, an app thatâs launched from the Finderâs contextual menu.
- Control-click the folder in Finder.
Control-click the folder in Finder.
- Choose Folder Actions Setup from the contextual menu.The Folder Actions Setup app launches, the folder is automatically added to the Folders with Actions list, and youâre prompted to select a script.
Choose Folder Actions Setup from the contextual menu.
The Folder Actions Setup app launches, the folder is automatically added to the Folders with Actions list, and youâre prompted to select a script.
- Choose a script to connect to the folder and click Attach.
Choose a script to connect to the folder and click Attach.
- Make sure the Enable Folder Actions checkbox is selected, as well as the On checkboxes next to the folder.
Make sure the Enable Folder Actions checkbox is selected, as well as the On checkboxes next to the folder.
Once the script and folder are connected, the folder action event handlers in the script should run when the corresponding actions occur.
Note
Folder Actions Setup can also be used to disable or remove folder action scripts and watched folders.
The Folder Actions Setup app itself resides in/System/Library/CoreServices/.
### Watching Folders Using an Idle Loop and a Stay Open Script App
Although folder actions provide efficient folder watching capabilities, some scripters prefer to implement customized folder watching workflows that provide more control over the folder watching process. This is typically done by creating a stay-open script with anidlehandler that checks a folder at regular intervals for new items to process.Listing 18-5demonstrates anidlehandler-based script that watches an Input folder on the Desktop.
APPLESCRIPT
Open in Script Editor
- on idle
- -- Locate the folder to watch
- set theFolder to locateAndCreateFolder(path to desktop folder, "Input")
- -- Watch the folder
- watchFolder(theFolder)
- -- Delay 2 minutes before checking the folder again
- return 120
- end idle
- on watchFolder(theFolder)
- -- Check for files in the folder
- tell application "Finder"
- set theFilesToProcess to every file of theFolder
- end tell
- -- Stop if there are no files to process
- if theFilesToProcess = {} then return
- -- Locate an output folder
- set theOutputFolder to locateAndCreateFolder(path to desktop folder, "Output")
- repeat with aFile in theFilesToProcess
- -- Process the current file
- -- Move the current file to the output folder so it doesn't get processed again
- tell application "Finder"
- move aFile to theOutputFolder
- end tell
- end repeat
- end watchFolder
- -- Locate a folder, creating it if it doesn't exist
- on locateAndCreateFolder(theParentFolder, theFolderName)
- tell application "Finder"
- if ((folder theFolderName of theParentFolder) exists) = false then make new folder at theParentFolder with properties {name:theFolderName}
- return (folder theFolderName of theParentFolder) as alias
- end tell
- end locateAndCreateFolder
### Folder Watching Best Practices
Regardless of what method you use for folder watching, follow these best practices to produce an efficient and reliable workflow:
- Wait for items to finish writing to disk before processing them.
Wait for items to finish writing to disk before processing them.
- Move processed items to an output folder so the same items arenât detected and processed a second time.
Move processed items to an output folder so the same items arenât detected and processed a second time.
- Handle errors gracefully, such as by moving problematic items to an error folder so other processing can proceed.
Handle errors gracefully, such as by moving problematic items to an error folder so other processing can proceed.
- Bring dialogs and alerts to the front so theyâre visible and can be addressed.
Bring dialogs and alerts to the front so theyâre visible and can be addressed.
Processing Dropped Files and Folders
Manipulating Text
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Using Dictation to Run Scripts
## Using Dictation to Run Scripts
Dictation commands is a powerful accessibility feature in OS X that lets you control your Mac using your voice. With dictation commands enabled, simply speak a command and watch it execute. The system comes with dozens of built-in dictation commands for opening apps, selecting menus, and more. You can extend the capabilities of dictation even further by creating your own custom commands using scripting and Automator.
### Enabling Dictation Commands
You must enable dictation commands before you can use them.
- Launch System Preferences and open the Dictation & Speech preference pane.
Launch System Preferences and open the Dictation & Speech preference pane.
- Click the On radio button to enable dictation.
Click the On radio button to enable dictation.
- Click Use Enhanced Dictation.Enhanced dictation lets you perform dictation when your computer is offline, and is required to use dictation commands. Enabling this feature downloads some additional system content to your Mac.
Click Use Enhanced Dictation.
Enhanced dictation lets you perform dictation when your computer is offline, and is required to use dictation commands. Enabling this feature downloads some additional system content to your Mac.
- Open the Accessibility preference pane.
Open the Accessibility preference pane.
- In the list of accessibility features, click Dictation.
In the list of accessibility features, click Dictation.
- Click Dictation Commands.
Click Dictation Commands.
- Select theâEnabled advanced commandsâ checkbox.
Select theâEnabled advanced commandsâ checkbox.
### Creating a Dictation Command Script
Any script can serve as a dictation command. When the command is called, any code in the scriptâsrunhandler runs.
- Launch Script Editor and write a script that performs a task when run.
Launch Script Editor and write a script that performs a task when run.
- Save the script in script format to the~/Library/Speech/Speakable Items/folder in your Home directory.If you want the script to be available to other users on your Mac, save it to the/Library/Speech/Speakable Items/instead.
Save the script in script format to the~/Library/Speech/Speakable Items/folder in your Home directory.
If you want the script to be available to other users on your Mac, save it to the/Library/Speech/Speakable Items/instead.
- Launch System Preferences and open the Accessibility preference pane.
Launch System Preferences and open the Accessibility preference pane.
- In the list of accessibility features, click Dictation.
In the list of accessibility features, click Dictation.
- Click Dictation Commands.
Click Dictation Commands.
- Click + to adde a new dictation command.
Click + to adde a new dictation command.
- Enter a phrase to speak to invoke the script.
Enter a phrase to speak to invoke the script.
- Choose the application context for triggering the command, such as Any Application, Mail, or Safari.
Choose the application context for triggering the command, such as Any Application, Mail, or Safari.
- Choose Run Workflow > Other from the Perform pop-up menu.
Choose Run Workflow > Other from the Perform pop-up menu.
- Click Done.
Click Done.
### Running a Dictation Command Script
To run a dictation commandâscript or otherwiseâpress Fn key twice. When the dictation listener window (Figure 42-1) appears, say the name of the command you want to perform.
To make dictation even easier, select the âEnable the dictation keyword phraseâ checkbox and enter a phrase in System Preferences > Accessibility > Dictation. Once enabled, you donât need to press the Fn key twice anymore to trigger a command. Instead, just say the keyword phrase, followed by the name of the command. For example, if your keyword phrase isComputer, you might say âComputer, send my weekly status report.â
### Creating a Dictation Command Automator Workflow
Automator can also be used to create dictation commands.
- Launch Automator.
Launch Automator.
- Click Dictation Command in the template selection dialog.
Click Dictation Command in the template selection dialog.
- Add actions to the workflow.The Run AppleScript, Run JavaScript, and Run Shell Script actions can be used to initiate scripts from your workflow.
Add actions to the workflow.
The Run AppleScript, Run JavaScript, and Run Shell Script actions can be used to initiate scripts from your workflow.
- At the top of the workflow, enter a dictation command and select the Command Enabled checkbox.
At the top of the workflow, enter a dictation command and select the Command Enabled checkbox.
- Save the workflow and name it.
Save the workflow and name it.
Note
Automator dictation commands are automatically saved in the~/Library/Speech/Speakable Items/folder in your Home directory.
Using the Systemwide Script Menu
Objective-C to AppleScript Quick Translation Guide
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Making a Systemwide Service
## Making a Systemwide Service
In OSÂ X,serviceslet you access functionality in one app from within another app. An app that provides a service advertises the operations it can perform on a particular type of data. Services are triggered from the Application Name > Services menu, or from contextual menus that appear when you Control-click on text, files, and other kinds of data. When youâre manipulating a particular type of data, related services becomes available. For example, Mail provides a service that creates a new email from selected text.
### Making a Script Available as a Service
A script can be made available as a service by embedding it in an Automator service workflow.
- Launch Automator, found in/Applications/.
Launch Automator, found in/Applications/.
- Create a new Automator document.
Create a new Automator document.
- When prompted, choose a document type of Service and click Choose.
When prompted, choose a document type of Service and click Choose.
- At the top of the Automator document, configure the service.If the service will process a specific type of data, such as text, files, or images, select the appropriate type. Otherwise, select âno input.âIf the service will be available within the context of a specific app only, select the appropriate app. Otherwise, select âany application.âIf the service will replace selected text with processed text, select the âOutput replaces selected textâ checkbox.
At the top of the Automator document, configure the service.
If the service will process a specific type of data, such as text, files, or images, select the appropriate type. Otherwise, select âno input.â
If the service will be available within the context of a specific app only, select the appropriate app. Otherwise, select âany application.â
If the service will replace selected text with processed text, select the âOutput replaces selected textâ checkbox.
- Typerunin the search field above the action library pane to filter the action library.A list of actions for running AppleScripts, JavaScripts, UNIX shell scripts, and more are displayed.
Typerunin the search field above the action library pane to filter the action library.
A list of actions for running AppleScripts, JavaScripts, UNIX shell scripts, and more are displayed.
- Drag an action, such as Run AppleScript or Run JavaScript, to the workflow area.An interface for the action appears.
Drag an action, such as Run AppleScript or Run JavaScript, to the workflow area.
An interface for the action appears.
- Write the script code and add it to the action. If the action contains additional configuration options, adjust them as needed.For AppleScripts and JavaScripts, use the actionâs run handler template to process input data when the service runs, such as text or files. For workflows that replace selected text with processed text, be sure your workflow results in a text value. SeeExample Service Workflow Scripts.
Write the script code and add it to the action. If the action contains additional configuration options, adjust them as needed.
For AppleScripts and JavaScripts, use the actionâs run handler template to process input data when the service runs, such as text or files. For workflows that replace selected text with processed text, be sure your workflow results in a text value. SeeExample Service Workflow Scripts.
- Save the Automator document.When prompted, enter a name for the service.
Save the Automator document.
When prompted, enter a name for the service.
### Example Service Workflow Scripts
Listing 40-1andListing 40-2provide example code that can be pasted into the Run AppleScript and Run JavaScript Automator actions to convert selected text to uppercase.
APPLESCRIPT
Open in Script Editor
- on run {input, parameters}
- set input to changeCaseOfText(input as string, "upper")
- return input
- end run
- on changeCaseOfText(theText, theCaseToSwitchTo)
- if theCaseToSwitchTo contains "lower" then
- set theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"
- else if theCaseToSwitchTo contains "upper" then
- set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
- set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- else
- return theText
- end if
- set theAlteredText to ""
- repeat with aCharacter in theText
- set theOffset to offset of aCharacter in theComparisonCharacters
- if theOffset is not 0 then
- set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
- else
- set theAlteredText to (theAlteredText & aCharacter) as string
- end if
- end repeat
- return theAlteredText
- end changeCaseOfText
JAVASCRIPT
Open in Script Editor
- function run(input, parameters) {
- var selectedText = input[0]
- return selectedText.toUpperCase()
- }
### Triggering Service Workflows
Saved Automator service workflows automatically appear in services menus throughout the system at the appropriate time. For example, text processing workflows become available when you select text in an app. To run a service, select Application Name > Services > Service Workflow Name from the menu bar, or select Services > Service Workflow Name from a contextual menu.
Calling Command-Line Tools
Using the Systemwide Script Menu
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Prompting for Text
## Prompting for Text
Use thedisplay dialogcommandâs optionaldefault answerparameter to collect text, such as a username or email address, as your script runs. As demonstrated byFigure 23-1,Listing 23-1, andListing 23-2, the inclusion of thedefault answerparameter automatically adds a text entry field to the resulting dialog. Any string you provide for the parameter appears in the text field when the dialog displays. Providing an empty string ("") produces an empty text field. When the dialog dismisses, any text from the field is returned in atext returnedproperty of thedisplay dialogcommandâs result.
APPLESCRIPT
Open in Script Editor
- set theResponse to display dialog "What's your name?" default answer "" with icon note buttons {"Cancel", "Continue"} default button "Continue"
- --> {button returned:"Continue", text returned:"Jen"}
- display dialog "Hello, " & (text returned of theResponse) & "."
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var response = app.displayDialog("What's your name?", {
- defaultAnswer: "",
- withIcon: "note",
- buttons: ["Cancel", "Continue"],
- defaultButton: "Continue"
- })
- // Result: {"buttonReturned":"Continue", "textReturned":"Jen"}
- app.displayDialog("Hello, " + (response.textReturned) + ".")
Note
Additional information about thedisplay dialogcommand can be found inDisplaying Dialogs and Alerts. For complete information about the command and its parameters, launch Script Editor, open the Standard Additions scripting additionâs dictionary, and navigate to the commandâs definition.
### Prompting for Hidden Text
Protect potentially sensitive information from prying eyes by using thedisplay dialogcommandâsdefault answerparameter in conjunction with thehidden answerparameter to show bullets instead of plain text in the dialogâs text field. SeeFigure 23-2,Listing 23-3, andListing 23-4.
APPLESCRIPT
Open in Script Editor
- display dialog "Please enter a passphrase to use this script." default answer "" with icon stop buttons {"Cancel", "Continue"} default button "Continue" with hidden answer
- --> Result: {button returned:"Continue", text returned:"MySecretPassphrase"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.displayDialog("Please enter a passphrase to use this script.", {
- defaultAnswer: "",
- withIcon: "stop",
- buttons: ["Cancel", "Continue"],
- defaultButton: "Continue",
- hiddenAnswer: true
- })
- // Result: {"buttonReturned":"Continue", "textReturned":"MySecretPassphrase"}
Warning
Always be cautious when requesting sensitive data, such as passwords. Hidden text is returned by thedisplay dialogcommand as plain, unencrypted text, so this command offers limited security.
Displaying Dialogs and Alerts
Displaying Notifications
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Converting RGB to HTML Color
## Converting RGB to HTML Color
In HTML documents, colors are typically represented as hex values. The handlers inListing 31-1andListing 31-2show how to convert 8-bit or 256 color-based RGB values to hex values. Provide an RGB color represented by a list of three numbers, each with a value between0and65535.
APPLESCRIPT
Open in Script Editor
- on convertRGBColorToHexValue(theRGBValues)
- set theHexList to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
- set theHexValue to ""
- repeat with a from 1 to count of theRGBValues
- set theCurrentRGBValue to (item a of theRGBValues) div 256
- if theCurrentRGBValue is 256 then set theCurrentRGBValue to 255
- set theFirstItem to item ((theCurrentRGBValue div 16) + 1) of theHexList
- set theSecondItem to item (((theCurrentRGBValue / 16 mod 1) * 16) + 1) of theHexList
- set theHexValue to (theHexValue & theFirstItem & theSecondItem) as string
- end repeat
- return ("#" & theHexValue) as string
- end convertRGBColorToHexValue
JAVASCRIPT
Open in Script Editor
- function convertRGBColorToHexValue(rgbValues) {
- var r = parseInt(rgbValues[0], 10).toString(16).slice(-2)
- if (r.length == 1)
- r = "0" + r
- var g = parseInt(rgbValues[1], 10).toString(16).slice(-2)
- if (g.length == 1)
- g = "0" + g
- var b = parseInt(rgbValues[2], 10).toString(16).slice(-2)
- if (b.length == 1)
- b = "0" + b
- return ("#" + r + g + b)
- }
Listing 31-3shows how to call the handlers inListing 31-1to convert a specified RGB color to a hex value for use in HTML.
APPLESCRIPT
Open in Script Editor
- set theRGBValues to (choose color default color {65535, 0, 0})
- convertRGBColorToHexValue(theRGBValues)
- --> Result: "#FF0000"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var color = app.chooseColor({defaultColor: [1, 0, 0]})
- color = [Math.trunc(color[0] * 65535), Math.trunc(color[1] * 65535), Math.trunc(color[2] * 65535)]
- convertRGBColorToHexValue(color)
- // Result: "#FF0000"
Note
In AppleScript, thechoose colorcommand produces RGB values ranging from0through65535. In JavaScript, the RGB values range between0and1. These values must be converted to match the AppleScript values to be used.Listing 31-4demonstrates this conversion.
Displaying Progress
Encoding and Decoding Text
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Automating the User Interface
## Automating the User Interface
Unfortunately, not every Mac app has scripting support, and those that do may not always have scripting support for every task you want to automate. You can often work around such limitations, however, by writing a user interface script, commonly called a UI or GUI script. A user interface script simulates user interaction, such as mouse clicks and keystrokes, allowing the script to select menu items, push buttons, enter text into text fields, and more.
### Enabling User Interface Scripting
User interface scripting relies upon the OSÂ X accessibility frameworks that provide alternative methods of querying and controlling the interfaces of apps and the system. By default, accessibility control of apps is disabled. For security and privacy reasons, the user must manually enable it on an app-by-app (including script apps) basis.
- Launch System Preferences and click Security & Privacy.
Launch System Preferences and click Security & Privacy.
- Click the Privacy tab.
Click the Privacy tab.
- Click Accessibility.
Click Accessibility.
- Click the Add button (+).
Click the Add button (+).
- Choose an app and click Open.
Choose an app and click Open.
- Select the checkbox to the left of the app.
Select the checkbox to the left of the app.
When running an app that requires accessibility control for the first time, the system prompts you to enable it. SeeFigure 37-1.
Attempting to run an app that has not been given permission to use accessibility features results in an error. SeeFigure 37-2.
Note
To run a user interface script in Script Editor, you must enable accessibility for Script Editor.
Admin credentials are required to perform enable user interface scripting.
### Targeting an App
User interface scripting terminology is found in the Processes Suite of the System Events scripting dictionary. This suite includes terminology for interacting with most types of user interface elements, including windows, buttons, checkboxes, menus, radio buttons, text fields, and more. In System Events, theprocessclass represents a running app.Listing 37-1shows how to target an app using this class.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell process "Safari"
- -- Perform user interface scripting tasks
- end tell
- end tell
To control the user interface of an app, you must first inspect the app and determine its element hierarchy. This can be done by querying the app. For example,Listing 37-2asks Safari for a list of menus in the menu bar.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell process "Safari"
- name of every menu of menu bar 1
- end tell
- end tell
- --> Result: {"Apple", "Safari", "File", "Edit", "View", "History", "Bookmarks", "Develop", "Window", "Help"}
Accessibility Inspector (Figure 37-3) makes it even easier to identify user interface element information. This app is included with Xcode. To use it, open Xcode and select Xcode > Open Developer Tool > Accessibility Inspector.
Once you know how an element fits into an interface, you target it within that hierarchy. For example,button X of window Y of process Z.
### Clicking a Button
Use theclickcommand to click a button.Listing 37-3clicks a button in the Safari toolbar to toggle the sidebar between open and closed.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell process "Safari"
- tell toolbar of window 1
- click (first button where its accessibility description = "Sidebar")
- end tell
- end tell
- end tell
- --> Result: {button 1 of toolbar 1 of window "AppleScript: Graphic User Interface (GUI) Scripting" of application process "Safari" of application "System Events"}
### Choosing a Menu Item
Menu items can have a fairly deep hierarchy within the interface of an app. A menu item generally resides within a menu, which resides within a menu bar. In scripting, they must be addressed as such.Listing 37-4selects the Pin Tab menu item in the Window menu of Safari.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell process "Safari"
- set frontmost to true
- click menu item "Pin Tab" of menu "Window" of menu bar 1
- end tell
- end tell
- --> Result: menu item "Pin Tab" of menu "Window" of menu bar item "Window" of menu bar 1 of application process "Safari" of application "System Events"
Note
Scripting the user interface of an app can be tedious and repetitious. To streamline the process, consider creating handlers to perform common functions. For example,Listing 37-5shows a handler that can be used to choose any menu item of any menu in any running app.
APPLESCRIPT
Open in Script Editor
- on chooseMenuItem(theAppName, theMenuName, theMenuItemName)
- try
- -- Bring the target app to the front
- tell application theAppName
- activate
- end tell
- -- Target the app
- tell application "System Events"
- tell process theAppName
- -- Target the menu bar
- tell menu bar 1
- -- Target the menu by name
- tell menu bar item theMenuName
- tell menu theMenuName
- -- Click the menu item
- click menu item theMenuItemName
- end tell
- end tell
- end tell
- end tell
- end tell
- return true
- on error
- return false
- end try
- end chooseMenuItem
Listing 37-6calls the handler inListing 37-5to select the Pin Tab menu item in the Window menu of Safari.
APPLESCRIPT
Open in Script Editor
- chooseMenuItem("Safari", "Window", "Pin Tab")
### Choosing a Submenu Item
Some menus contain other menus. In these cases, it may be necessary to select a menu item in a submenu of a menu.Listing 37-7demonstrates how this would be done by selecting a submenu item in Safari.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- tell process "Safari"
- set frontmost to true
- click menu item "Email This Page" of menu of menu item "Share" of menu "File" of menu bar 1
- end tell
- end tell
- --> Result: {menu item "Email This Page" of menu "Share" of menu item "Share" of menu "File" of menu bar item "File" of menu bar 1 of application process "Safari" of application "System Events"}
Working with XML
Manipulating Images
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Manipulating Text
## Manipulating Text
Manipulating text is one of the most common tasks performed in scripts. AppleScript and JavaScript both possess some basic text manipulation functions and properties that allow you to concatenate text, get the length of a string, and more. Overall, JavaScript has a much wider-range of built-in language-level text manipulation functions. Custom scripting is usually required to manipulate text with AppleScript.
Note
For general information about working with text in AppleScript, see thetextclass reference documentation inAppleScript Language Guide.
In JavaScript, theStringobject provides a range of text processing functions. Information about this object can be foundhere. JavaScript also provides aRegExpconstructor, which can be used for pattern matching. Information about this constructor can be foundhere.
### Changing the Case of Text
The handlers inListing 19-1andListing 19-2convert text to uppercase or lowercase. To use these handlers, provide some source text and a case to applyâupperorlower.
APPLESCRIPT
Open in Script Editor
- on changeCaseOfText(theText, theCaseToSwitchTo)
- if theCaseToSwitchTo contains "lower" then
- set theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"
- else if theCaseToSwitchTo contains "upper" then
- set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
- set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- else
- return theText
- end if
- set theAlteredText to ""
- repeat with aCharacter in theText
- set theOffset to offset of aCharacter in theComparisonCharacters
- if theOffset is not 0 then
- set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
- else
- set theAlteredText to (theAlteredText & aCharacter) as string
- end if
- end repeat
- return theAlteredText
- end changeCaseOfText
JAVASCRIPT
Open in Script Editor
- function changeCaseOfText(text, caseToSwitchTo) {
- var alteredText = text
- if (caseToSwitchTo === "lower") {
- alteredText = alteredText.toLowerCase()
- }
- else if (caseToSwitchTo === "upper") {
- alteredText = alteredText.toUpperCase()
- }
- return alteredText
- }
Listing 19-3andListing 19-4show how to call the handlers inListing 19-1andListing 19-2to convert text to uppercase.
APPLESCRIPT
Open in Script Editor
- changeCaseOfText("scripting is awesome!", "upper")
- --> Result: "SCRIPTING IS AWESOME!"
JAVASCRIPT
Open in Script Editor
- changeCaseOfText("scripting is awesome!", "upper")
- // Result: "SCRIPTING IS AWESOME!"
Listing 19-5andListing 19-6show how to call the handlers inListing 19-1andListing 19-2to convert text to lowercase.
APPLESCRIPT
Open in Script Editor
- changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")
- --> Result: "doing repetitive work is boring"
JAVASCRIPT
Open in Script Editor
- changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")
- // Result: "doing repetitive work is boring"
Note
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSStringclass to change the case of text.Listing 19-7andListing 19-8demonstrate how to do this.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on changeCaseOfText(theText, theCase)
- -- Create an NSString object from the passed text
- set theText to stringWithString_(theText) of NSString of current application
- -- Apply the appropriate transformation to the NSString object
- if theCase contains "lower" then
- set theNewText to lowercaseString() of theText
- else if theCase contains "upper" then
- set theNewText to uppercaseString() of theText
- else
- set theNewText to capitalizedString() of theText
- end if
- -- Convert the NSString to an AppleScript string
- return (theNewText as string)
- end changeCaseOfText
JAVASCRIPT
Open in Script Editor
- function changeCaseOfText(text, caseToSwitchTo) {
- // Convert the passed text to an NSString object
- var alteredText = $(text)
- // Apply the appropriate transformation to the NSString object
- if (caseToSwitchTo === "lower") {
- alteredText = alteredText.lowercaseString
- }
- else if (caseToSwitchTo === "upper") {
- alteredText = alteredText.uppercaseString
- }
- // Convert the NSString to an AppleScript string
- return alteredText.js
- }
### Finding and Replacing Text in a String
The handler inListing 19-9can be used to find and replace text in a string. To use it, provide some source text, a string to find, and a replacement string. This handler replaces any found instances of the specified search string.
APPLESCRIPT
Open in Script Editor
- on findAndReplaceInText(theText, theSearchString, theReplacementString)
- set AppleScript's text item delimiters to theSearchString
- set theTextItems to every text item of theText
- set AppleScript's text item delimiters to theReplacementString
- set theText to theTextItems as string
- set AppleScript's text item delimiters to ""
- return theText
- end findAndReplaceInText
Listing 19-10shows how to call the handler inListing 19-9.
APPLESCRIPT
Open in Script Editor
- set theText to "On Tuesday, I told you to have the report ready by next Tuesday."
- set theText to findAndReplaceInText(theText, "Tuesday", "Friday")
- --> Result: "On Friday, I told you to have the report ready by next Friday."
In JavaScript, theStringobjectâsreplace()method is used to find and replace text in a string, as shown inListing 19-11. Unlike the previous AppleScript example, this function replaces only the first occurrence of the found text.
JAVASCRIPT
Open in Script Editor
- var text = "On Tuesday, I told you to have the report ready by next Tuesday."
- text = text.replace("Tuesday", "Friday")
- // Result: "On Friday, I told you to have the report ready by next Tuesday."
Thereplace()method can be combined with a regular expression to replace every occurrence of the found text, as shown inListing 19-12.
JAVASCRIPT
Open in Script Editor
- var text = "On Tuesday, I told you to have the report ready by next Tuesday."
- text = text.replace(/Tuesday/g, "Friday")
- // Result: "On Friday, I told you to have the report ready by next Friday."
Note
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSStringclass to perform a find and replace in text. The handlers inListing 19-13andListing 19-14demonstrate how to do this.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on findAndReplaceInText(theText, theSearchString, theReplacementString)
- -- Create an NSString object from the passed AppleScript string
- set theText to stringWithString_(theText) of NSString of current application
- -- Call an NSString replacement method on the newly created NSString object
- set theText to stringByReplacingOccurrencesOfString_withString_(theSearchString, theReplacementString) of theText
- -- Convert from an NSString to an AppleScript string
- return (theText as string)
- end findAndReplaceInText
JAVASCRIPT
Open in Script Editor
- function findAndReplaceInText(text, searchString, replacementString) {
- // Create an NSString object from the passed string
- var alteredText = $(text)
- // Call an NSString replacement method on the newly created NSString object
- alteredText = alteredText.stringByReplacingOccurrencesOfStringWithString(searchString, replacementString)
- // Convert from an NSString to a JavaScript string
- return alteredText.js
- }
### Getting the Characters of a String
Listing 19-15andListing 19-16show how to get a list of characters in a string.
APPLESCRIPT
Open in Script Editor
- set theText to "The quick brown fox jumps over a lazy dog."
- characters of theText
- --> Result: {"T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "a", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."}
JAVASCRIPT
Open in Script Editor
- var text = "The quick brown fox jumps over a lazy dog."
- text.split("")
- // Result: ["T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "a", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."]
### Getting the Length of String
Listing 19-17andListing 19-18show how to get the length ofâthe number of characters inâa string.
APPLESCRIPT
Open in Script Editor
- set theText to "The quick brown fox jumps over a lazy dog."
- length of theText
- --> Result: 42
JAVASCRIPT
Open in Script Editor
- var text = "The quick brown fox jumps over a lazy dog."
- text.length
- // Result: 42
### Getting the Paragraphs of a String
Listing 19-19andListing 19-20show how to get a list of paragraphs in a string.
APPLESCRIPT
Open in Script Editor
```applescript
set theText to "* Sal
* Ben
* Chris
* David"
paragraphs of theText
-- Result: {"* Sal", "* Ben", "* Chris", "* David"}
```
JAVASCRIPT
Open in Script Editor
```javascript
var text = `* Sal
* Ben
* Chris
* David`
text.split("\n")
// Result: ["* Sal", "* Ben", "* Chris", "* David"]
```
### Getting the Position of Text in a String
To determine the position of text within a string in AppleScript, request itsoffset, as shown inListing 19-21. This provides the character number where the first instance of the text begins.
APPLESCRIPT
Open in Script Editor
- set theText to "The quick brown fox jumps over a lazy dog."
- offset of "quick" in theText
- --> Result: 5
Note
In AppleScript, character positions start at1; the first character in a string has an offset of1. If the string doesnât include the text provided, then an offset of0is returned.
To determine the position of text within a string in JavaScript, call theindexOf()method of the text object, as shown inListing 19-22.
JAVASCRIPT
Open in Script Editor
- var text = "The quick brown fox jumps over a lazy dog."
- text.indexOf("quick")
- // Result: 4
Note
In JavaScript, character positions start at0; the first character in a string has an index of0. If the string doesnât include the text provided, then an offset of-1is returned.
### Splitting Text
The handler inListing 19-23splits text into a list, based on a specific delimiter.
APPLESCRIPT
Open in Script Editor
- on splitText(theText, theDelimiter)
- set AppleScript's text item delimiters to theDelimiter
- set theTextItems to every text item of theText
- set AppleScript's text item delimiters to ""
- return theTextItems
- end splitText
Listing 19-24shows how to call the handler inListing 19-23.
APPLESCRIPT
Open in Script Editor
- set theText to "The quick brown fox jumps over a lazy dog."
- splitText(theText, space)
- --> Result: {"The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."}
In JavaScript, theStringobjectâssplit()method is used to split text based on a delimiter, as shown inListing 19-25.
JAVASCRIPT
Open in Script Editor
- var text = "The quick brown fox jumps over a lazy dog."
- text.split(" ")
- // Result: ["The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."]
Note
SeeConverting a List to a Stringto learn how to merge strings back together.
### Trimming Text
The handlers inListing 19-26andListing 19-27trim text from the beginning or end of a string. To use these examples, provide some source text, characters to trim, and a trim directionâbeginning(trim from the beginning),end(trim from the end), orboth(trim from both the beginning and end).
APPLESCRIPT
Open in Script Editor
- on trimText(theText, theCharactersToTrim, theTrimDirection)
- set theTrimLength to length of theCharactersToTrim
- if theTrimDirection is in {"beginning", "both"} then
- repeat while theText begins with theCharactersToTrim
- try
- set theText to characters (theTrimLength + 1) thru -1 of theText as string
- on error
- -- text contains nothing but trim characters
- return ""
- end try
- end repeat
- end if
- if theTrimDirection is in {"end", "both"} then
- repeat while theText ends with theCharactersToTrim
- try
- set theText to characters 1 thru -(theTrimLength + 1) of theText as string
- on error
- -- text contains nothing but trim characters
- return ""
- end try
- end repeat
- end if
- return theText
- end trimText
JAVASCRIPT
Open in Script Editor
- function trimText(text, charsToTrim, direction) {
- var result = text
- var regexString = charsToTrim.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
- if (direction === "beginning" || direction === "both") {
- var regex = new RegExp(`^(?:${regexString})*`)
- result = result.replace(regex, "")
- }
- if (direction === "end" || direction === "both") {
- var regex = new RegExp(`(?:${regexString})*$`)
- result = result.replace(regex, "")
- }
- return result
- }
Listing 19-28andListing 19-29show how to call the handlers inListing 19-26andListing 19-27to trim text from the beginning of a string.
APPLESCRIPT
Open in Script Editor
- trimText("----1----", "-", "beginning")
- --> Result: "1----"
JAVASCRIPT
Open in Script Editor
- trimText("----1----", "-", "beginning")
- // Result: "1----"
Listing 19-30andListing 19-31show how to call the handlers inListing 19-26andListing 19-27to trim text from the end of a string.
APPLESCRIPT
Open in Script Editor
- trimText("12345.txt", ".txt", "end")
- --> Result: "12345"
JAVASCRIPT
Open in Script Editor
- trimText("12345.txt", ".txt", "end")
- // Result: "12345"
Listing 19-32andListing 19-33show how to call the handlers inListing 19-26andListing 19-27to trim text from the beginning and end of a string.
APPLESCRIPT
Open in Script Editor
- trimText("*-*-Ben*-*-", "*-", "both")
- --> Result: "Ben"
JAVASCRIPT
Open in Script Editor
- trimText("*-*-Ben*-*-", "*-", "both")
- // Result: "Ben"
Note
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSStringclass to remove whitespace around text. The handlers inListing 19-34andListing 19-35demonstrate how to do this.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on trimWhiteSpaceAroundString(theText)
- -- Create an NSString object from an AppleScript string
- set theText to stringWithString_(theText) of NSString of current application
- -- Trim white space around the NSString
- set theWhitespaceCharacterSet to whitespaceCharacterSet of NSCharacterSet of current application
- set theText to stringByTrimmingCharactersInSet_(theWhitespaceCharacterSet) of theText
- -- return result coerced to an AppleScript string
- return (theText as string)
- end trimWhiteSpaceAroundString
JAVASCRIPT
Open in Script Editor
- function trimWhiteSpaceAroundString(text) {
- // Create an NSString object from the text
- var alteredText = $(text)
- // Trim white space around the NSString and return the result
- var whitespace = $.NSCharacterSet.whitespaceCharacterSet
- return alteredText.stringByTrimmingCharactersInSet(whitespace).js
- }
### Trimming Paragraphs of Text
The handlers inListing 19-36andListing 19-37remove unwanted characters from multiple paragraphs.
Note
This handler calls thetrimText()handler. SeeListing 19-26.
APPLESCRIPT
Open in Script Editor
- on trimParagraphsOfText(theText, theCharactersToTrim, theTrimDirection)
- set theParagraphs to every paragraph of theText
- repeat with a from 1 to count of paragraphs of theText
- set theCurrentParagraph to item a of theParagraphs
- set item a of theParagraphs to trimText(theCurrentParagraph, theCharactersToTrim, theTrimDirection)
- end repeat
- set AppleScript's text item delimiters to return
- set theText to theParagraphs as string
- set AppleScript's text item delimiters to ""
- return theText
- end trimParagraphsOfText
JAVASCRIPT
Open in Script Editor
- function trimParagraphsOfText(text, charsToTrim, direction) {
- var paragraphs = text.split("\n")
- for (var i = 0; i < paragraphs.length; i++) {
- var currentParagraph = paragraphs[i]
- paragraphs[i] = trimText(currentParagraph, charsToTrim, direction)
- }
- return paragraphs.join("\n")
- }
Listing 19-38andListing 19-39show how to call the handlers inListing 19-36andListing 19-37.
APPLESCRIPT
Open in Script Editor
```applescript
set theText to "* Sal
* Ben
* Chris
* David"
trimParagraphsOfText(theText, "* ", "beginning")
-- Result:
(*
"Sal
Ben
Chris
David"
*)
```
JAVASCRIPT
Open in Script Editor
```javascript
var text = `* Sal
* Ben
* Chris
* David`
trimParagraphsOfText(text, "* ", "beginning")
// Result: "Sal\nBen\nChris\nDavid"
```
Note
In JavaScript,\nrepresents a newline character.
Watching Folders
Manipulating Numbers
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Saving a Script
## Saving a Script
After you write a script, you can save it for future reference or to be run outside of Script Editor.
### Saving a Script or Script Bundle
Scripts and script bundles open in Script Editor when double-clicked in the Finder.
- Choose File > Save (or press Command-S) to display the save dialog.
Choose File > Save (or press Command-S) to display the save dialog.
- Type a name for the script and choose an output folder.
Type a name for the script and choose an output folder.
- Choose Script or Script Bundle from the File Format popup menu.
Choose Script or Script Bundle from the File Format popup menu.
- Click Save.
Click Save.
### Saving a Script Application
Script applications, known as applets, work like other apps on your Mac. Double-click an applet to run it.
- Choose File > Save (or press Command-S) to display the save dialog.
Choose File > Save (or press Command-S) to display the save dialog.
- Type a name for the applet and choose an output folder.
Type a name for the applet and choose an output folder.
- Choose Application from the File Format popup menu.
Choose Application from the File Format popup menu.
- If you want the scriptâs descriptionâdefined in the Accessory View paneâto display when the applet launches, select the âShow startup screenâ checkbox.
If you want the scriptâs descriptionâdefined in the Accessory View paneâto display when the applet launches, select the âShow startup screenâ checkbox.
- If you want to create a stay-open applet, select the âStay open after run handlerâ checkbox.
If you want to create a stay-open applet, select the âStay open after run handlerâ checkbox.
- Click Save.
Click Save.
Note
To open a saved script applet or droplet for editing, drag it onto the Script Editor app or choose File > Open in Script Editor.
To convert a previously saved script or script bundle to an applet, choose File > Duplicate, press Shift-Command-S, or choose File > Export. Then, perform the steps above.
If an AppleScript applet contains anopenevent handler, or a JavaScript applet contains anopenDocumentsfunction, it automatically becomes a drag and drop application known as a droplet. Drag files and folders onto the droplet to process them, or double-click the droplet to run it. To learn about creating droplets, seeProcessing Dropped Files and Folders.
### Protecting a Scriptâs Source Code
If you plan to distribute your script, you may wish to protect is source code. This is done by exporting the script in run-only format.
- Choose File > Export to display the export dialog.
Choose File > Export to display the export dialog.
- Type a name for the applet and choose an output folder.
Type a name for the applet and choose an output folder.
- Choose a format from the File Format popup menu.
Choose a format from the File Format popup menu.
- If youâre saving in application format, choose whether you want a startup screen or a stay-open script.
If youâre saving in application format, choose whether you want a startup screen or a stay-open script.
- Select the Run-only checkbox.
Select the Run-only checkbox.
- Click Save.
Click Save.
Important
When saving a script in run-only format, make sure you retain a backup of your editable script.
### Code Signing a Script
By default, the security settings in OSÂ X only allow the launching of apps (including applets and droplets) that have been created by you, downloaded from the Mac App Store, or created by developers identified by Apple. If you plan to distribute your scripts to others, you should consider code signing your scripts with an Apple developer ID.
You obtain a Developer ID certificate fromCertificates, Identifiers & Profilesin your developer account and import it on your Mac. For detailed information about obtaining and importing a certificate, seeMaintaining Your Signing Identities and CertificatesinApp Distribution Guide.
- If the Bundle Contents pane isnât visible, choose View > Show Bundle, press Command-0, or click the bundle contents button () in the toolbar.
If the Bundle Contents pane isnât visible, choose View > Show Bundle, press Command-0, or click the bundle contents button () in the toolbar.
- Make sure the following highlighted fields are populated in the Bundle Contents pane.NameâThe name of your script.IdentifierâA uniform type identifier for your script. For information, seeUniform Type Identifiers Overview.Short VersionâThe version number for your script.CopyrightâThe copyright string for your script.
Make sure the following highlighted fields are populated in the Bundle Contents pane.
- NameâThe name of your script.
NameâThe name of your script.
- IdentifierâA uniform type identifier for your script. For information, seeUniform Type Identifiers Overview.
IdentifierâA uniform type identifier for your script. For information, seeUniform Type Identifiers Overview.
- Short VersionâThe version number for your script.
Short VersionâThe version number for your script.
- CopyrightâThe copyright string for your script.
CopyrightâThe copyright string for your script.
- Choose File > Export to display the export dialog.
Choose File > Export to display the export dialog.
- Type a name for the applet and choose an output folder.
Type a name for the applet and choose an output folder.
- Choose a format from the File Format popup menu.
Choose a format from the File Format popup menu.
- If youâre saving in application format, choose whether you want a startup screen or a stay-open script.
If youâre saving in application format, choose whether you want a startup screen or a stay-open script.
- Choose whether you want to save the script as run-only.
Choose whether you want to save the script as run-only.
- Choose your developer identity from the Code Sign popup menu.
Choose your developer identity from the Code Sign popup menu.
- Click Save.
Click Save.
Creating a Script
Running a Script
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Configuring Scripting Preferences
## Configuring Scripting Preferences
Script Editor preferences allows you to configure a variety of aspects of scripting behavior.
### General Preferences
In the General pane of Script Editor preferences (Figure 9-1), you can configure settings such as the following.
Default LanguageâThe default scripting language when you create new Script Editor documents.
Show âtellâ application menuâThis setting can be enabled to add a tell application menu to the navigation bar. Selecting an app in this menu allows you to direct script execution to the chosen app. InFigure 9-2, the tell application menu is set to the Finder. As a result, the script itself doesnât need to include atell application "Finder"statement. It automatically understands the Finderâs terminology and sends events to the Finder.
In addition, the current application objectâwhich refers to the application currently executing the scriptâreflects the selected application, rather than Script Editor. SeeListing 9-1andListing 9-2.
APPLESCRIPT
Open in Script Editor
- name of current application
- --> Result: "Finder"
JAVASCRIPT
Open in Script Editor
- Application.currentApplication().name()
- // Result: "Finder"
Show inherited itemsâThis setting can be enabled to display inherited object properties in the dictionary viewer. For example, in the Finder, afileobject inherits the attributes of anitemobject. Without this setting enabled, the dictionary entry forfilesimply provide a a pointer to theitementry to view theitemattributes. SeeFigure 9-3. With this option enabled, thefileentry in the Finderâs scripting dictionary includes the attributes of anitem. SeeFigure 9-4.
Script MenuâThese settings allow you to enable and configure a systemwide script menu (Figure 9-5). This menu can be used to organize your scripts and provide access to them in any app.
### Editing Preferences
In the Editing pane of Script Editor preferences, shown inFigure 9-6, you can configure settings such as the following.
Code completionâWhen this option is enabled, Script Editor suggest code completions as you type a script (Figure 9-7).
To accept and insert a code completion suggestion, press the F5 key or the Esc (Escape) key. If multiple code completion choices are available, a code completion dialog appears, allowing you to select a suggestion (seeFigure 9-8).
Tab width and line wrappingâAdjust how indentation and line wrapping occurs in the editor pane of Script Editor documents.
Escape tabs and line breaks in stringsâThis setting only affects AppleScripts. When this option is disabled, tabs and line breaks appear normally in a text string, as shown inFigure 9-9.
When this option is enabled, tabs and line breaks are replaced with escaped character equivalentsâ/tfor a tab, and/rfor a line break. SeeFigure 9-10.
### Formatting Preferences
In the Formatting pane of Script Editor window (Figure 9-11), you can configure the styleâfont, point size, and colorâof various script attributes, including new text, language keywords, comments, and variables. Formatting options are language-specific. Select a language from the Language popup menu to view that languageâs formatting settings.
### History Preferences
In the History pane of Script Editor preferences (Figure 9-12), you can enable or disable the log history, adjust the quantity of log history entries, and enable logging only when the log is visible.
### Plug-ins Preferences
The Plug-ins pane of Script Editor preferences (Figure 9-13) lists any installed Script Editor plug-ins.
Running a Script
About Scripting Terminology
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Manipulating Numbers
## Manipulating Numbers
Working with and manipulating numbers is an important and regular occurrence in scripting. Basic mathematic operationsâsuch as addition, subtraction, multiplication, and divisionâare language-level features, but some other commonly performed operations require custom scripting.
Note
AppleScriptâs language-level mathematical operators are listed inOperators ReferenceinAppleScript Language Guide.
JavaScriptâs language-level arithmetic operators can be foundhere. JavaScript also includes a built-inMathobject, which provides a variety of properties and methods for performing common mathematical operations. Information about this object can be foundhere. Several of the JavaScript examples in this chapter call theMath.abs()method to get the absolute value of a number. AppleScript does not have an equivalent method.
### Converting a Number to a String
Scripts often need to convert numbers to string format to display information to the user or populate a document. In AppleScript, this conversion can be accomplished most of the time simply by using the coercion operatoras, as shown inListing 20-1.
APPLESCRIPT
Open in Script Editor
- 12 as string
- --> Result: "12"
In JavaScript, the same conversion can be accomplished by calling thetoString()method, as shown inListing 20-2.
JAVASCRIPT
Open in Script Editor
- num = 12
- num.toString()
- // Result: "12"
### Converting a Long Number to a String
In AppleScript, long numeric values are displayed in scientific notation. For example,1234000000is displayed by a script as1.234E+9. When this value is coerced to a string, it becomes:"1.234E+9". The handler inListing 20-3converts a number, regardless of length, to a string of numeric characters instead of a numeric string in scientific notation.
APPLESCRIPT
Open in Script Editor
- on convertNumberToString(theNumber)
- set theNumberString to theNumber as string
- set theOffset to offset of "E" in theNumberString
- if theOffset = 0 then return theNumberString
- set thePrefix to text 1 thru (theOffset - 1) of theNumberString
- set theConvertedNumberPrefix to ""
- if thePrefix begins with "-" then
- set theConvertedNumberPrefix to "-"
- if thePrefix = "-" then
- set thePrefix to ""
- else
- set thePrefix to text 2 thru -1 of thePrefix
- end if
- end if
- set theDecimalAdjustment to (text (theOffset + 1) thru -1 of theNumberString) as number
- set isNegativeDecimalAdjustment to theDecimalAdjustment is less than 0
- if isNegativeDecimalAdjustment then
- set thePrefix to (reverse of (characters of thePrefix)) as string
- set theDecimalAdjustment to -theDecimalAdjustment
- end if
- set theDecimalOffset to offset of "." in thePrefix
- if theDecimalOffset = 0 then
- set theFirstPart to ""
- else
- set theFirstPart to text 1 thru (theDecimalOffset - 1) of thePrefix
- end if
- set theSecondPart to text (theDecimalOffset + 1) thru -1 of thePrefix
- set theConvertedNumber to theFirstPart
- set theRepeatCount to theDecimalAdjustment
- if (length of theSecondPart) is greater than theRepeatCount then set theRepeatCount to length of theSecondPart
- repeat with a from 1 to theRepeatCount
- try
- set theConvertedNumber to theConvertedNumber & character a of theSecondPart
- on error
- set theConvertedNumber to theConvertedNumber & "0"
- end try
- if a = theDecimalAdjustment and a is not equal to (length of theSecondPart) then set theConvertedNumber to theConvertedNumber & "."
- end repeat if theConvertedNumber ends with "." then set theConvertedNumber to theConvertedNumber & "0"
- if isNegativeDecimalAdjustment then set theConvertedNumber to (reverse of (characters of theConvertedNumber)) as string
- return theConvertedNumberPrefix & theConvertedNumber
- end convertNumberToString
Listing 20-3shows how to call the handler inListing 20-3.
APPLESCRIPT
Open in Script Editor
- convertNumberToString(8.72124243234E+11)
- --> Result: "872124243234"
### Adding a Descriptive Suffix to a Number
The handlersListing 20-5andListing 20-6convert a number to a string and appends a suffix of"st","nd","rd", or"th", resulting in strings such as"1st","2nd","3rd", and"4th".
APPLESCRIPT
Open in Script Editor
- on addDescriptiveSuffixToNumber(theNumber)
- -- Determine the suffix to add, based on the last two digits
- set theLastDigit to theNumber mod 10
- set theLastTwoDigits to theNumber mod 100
- set theSuffix to "th"
- if {1, -1} contains theLastDigit and {11, -11} does not contain theLastTwoDigits then
- set theSuffix to "st"
- else if {2, -2} contains theLastDigit and {12, -12} does not contain theLastTwoDigits then
- set theSuffix to "nd"
- else if {3, -3} contains theLastDigit and {13, -13} does not contain theLastTwoDigits then
- set theSuffix to "rd"
- end if
- -- Return the number and suffix
- return (theNumber as string) & theSuffix
- end addDescriptiveSuffixToNumber
JAVASCRIPT
Open in Script Editor
- function addDescriptiveSuffixToNumber(num) {
- // Convert the number to absolute value
- var integer = Math.abs(num)
- // Determine the suffix to add, based on the last two digits
- var suffix = "th"
- var lastDigit = integer % 10
- var lastTwoDigits = integer % 100
- if (lastDigit === 1 && lastTwoDigits !== 11) {
- suffix = "st"
- }
- else if (lastDigit === 2 && lastTwoDigits !== 12) {
- suffix = "nd"
- }
- else if (lastDigit === 3 && lastTwoDigits !== 13) {
- suffix = "rd"
- }
- // Return the number and suffix
- return num.toString() + suffix
- }
Listing 20-7andListing 20-8show how to test the handlers inListing 20-5andListing 20-6by looping through a range of positive and negative numbers.
APPLESCRIPT
Open in Script Editor
- set theTestResults to ""
- repeat with a from -10 to 10
- set theTestResults to theTestResults & addDescriptiveSuffixToNumber(a)
- if a is less than 10 then set theTestResults to theTestResults & ", "
- end repeat
- theTestResults
- --> Result: "-10th, -9th, -8th, -7th, -6th, -5th, -4th, -3rd, -2nd, -1st, 0, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th"
JAVASCRIPT
Open in Script Editor
- var testResults = ""
- for (var i = -10; i <= 10; i++) {
- testResults += addDescriptiveSuffixToNumber(i)
- if (i < 10) {
- testResults += ", "
- }
- }
- testResults
- // Result: "-10th, -9th, -8th, -7th, -6th, -5th, -4th, -3rd, -2nd, -1st, 0th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th"
Listing 20-9andListing 20-10show how to call the handlers inListing 20-5andListing 20-6to identify positions of items in a list.
APPLESCRIPT
Open in Script Editor
- set thePersonList to {"Sal", "Ben", "Chris", "David"}
- set theListLength to length of thePersonList
- repeat with a from 1 to theListLength
- set theSuffixedNumber to addDescriptiveSuffixToNumber(a)
- set thePerson to item a of thePersonList
- display dialog "The " & theSuffixedNumber & " person in list is " & thePerson & "."
- end repeat
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var personList = ["Sal", "Ben", "Chris", "David"]
- var listLength = personList.length
- for (var i = 0; i < listLength; i++) {
- var suffixedNum = addDescriptiveSuffixToNumber(i + 1)
- var person = personList[i]
- app.displayDialog(`The ${suffixedNum} person in list is ${person}.`)
- }
### Adding Leading Zeros to a Number
The handlers inListing 20-11andListing 20-12convert a number to a string and prepends it with leading zeros until it reaches a certain length. They accept two parametersâthe number to add leading zeros to and the maximum number of leading zeros to add. For example, if the maximum number of leading zeros is set to2, the results range from001to999. If the maximum number of leading zeros is3, the results range from0001to9999, and so on.
APPLESCRIPT
Open in Script Editor
- on addLeadingZerosToNumber(theNumber, theMaxLeadingZeroCount)
- -- Determine if the number is negative
- set isNegative to theNumber is less than 0
- -- Determine when the maximum number of digits will be reached
- set theThreshold to (10 ^ theMaxLeadingZeroCount) as integer
- -- If the number is shorter than the maximum number of digits
- if theNumber is less than theThreshold then
- -- If the number is negative, convert it to positive
- if isNegative = true then set theNumber to -theNumber
- -- Add the zeros to the number
- set theLeadingZeros to ""
- set theDigitCount to length of ((theNumber div 1) as string)
- set theCharacterCount to (theMaxLeadingZeroCount + 1) - theDigitCount
- repeat theCharacterCount times
- set theLeadingZeros to (theLeadingZeros & "0") as string
- end repeat
- -- Make the number negative, if it was previously negative
- if isNegative = true then set theLeadingZeros to "-" & theLeadingZeros
- -- Return the prefixed number
- return (theLeadingZeros & (theNumber as text)) as string
- -- If the number is greater than or equal to the maximum number of digits
- else
- -- Return the original number
- return theNumber as text
- end if
- end addLeadingZerosToNumber
JAVASCRIPT
Open in Script Editor
- function addLeadingZerosToNumber(num, maxLeadingZeroCount) {
- var leadingZeros = ""
- // Convert the number to absolute value
- var absNum = Math.abs(num)
- // Determine when the maximum number of digits will be reached
- var threshold = Math.pow(10, maxLeadingZeroCount)
- // If the number is shorter than the maximum number of digits
- if (absNum < threshold) {
- // Prepare a leading zeros string
- var digitCount = Math.trunc(absNum).toString().length
- var charCount = maxLeadingZeroCount + 1 - digitCount
- for (var i = 0 ; i < charCount; i++) {
- leadingZeros += "0"
- }
- }
- // Add the zeros to the number
- var result = `${leadingZeros}${absNum}`
- // Make the number negative, if it was previously negative
- if (num < 0) {
- result = `-${result}`
- }
- // Return the prefixed number
- return result
- }
Listing 20-13andListing 20-14show how to call the handlers inListing 20-11andListing 20-12.
APPLESCRIPT
Open in Script Editor
- addLeadingZerosToNumber(9, 3)
- --> Result: "0009"
JAVASCRIPT
Open in Script Editor
- addLeadingZerosToNumber(9, 3)
- // Result: "0009"
### Comma-Delimiting a Number
The handlersListing 20-15andListing 20-16comma-delimit a numeric value and converts it to a string.
Note
These handlers call theconvertNumberToString()handler. SeeListing 20-3.
APPLESCRIPT
Open in Script Editor
- on convertNumberToCommaDelimitedString(theNumber)
- -- Convert the number to a string
- set theNumber to convertNumberToString(theNumber)
- -- Determine the length of the number
- set theNumberLength to length of theNumber
- -- Reverse the number so a comma can be added every 3 digits
- set theNumber to (reverse of every character of theNumber) as string
- -- Loop through the number's digits, add commas, and put the numbers back in the correct order
- set theConvertedNumber to ""
- repeat with a from 1 to theNumberLength
- if a is theNumberLength or (a mod 3) is not 0 then
- set theConvertedNumber to (character a of theNumber & theConvertedNumber) as string
- else
- set theConvertedNumber to ("," & character a of theNumber & theConvertedNumber) as string
- end if
- end repeat
- -- Return the comma delimited number
- return theConvertedNumber
- end convertNumberToCommaDelimitedString
JAVASCRIPT
Open in Script Editor
- function convertNumberToCommaDelimitedString(num) {
- // Convert the number to a string
- var numString = num.toString()
- if (numString.indexOf("e") != - 1) {
- numString = convertNumberToString(numString)
- }
- // Reverse the number so a comma can be added every 3 digits
- numString = numString.split("").reverse().join("")
- var numStringWithCommas = ""
- // Determine the length of the number
- var numStringLength = numString.length
- // Loop through the number's digits, add commas, and put the numbers back in the correct order
- for (var i = 0; i < numStringLength; i++) {
- var toPrepend = numString[i]
- if (i != numStringLength - 1 && ((i + 1) % 3) == 0) {
- toPrepend = "," + toPrepend
- }
- numStringWithCommas = toPrepend + numStringWithCommas
- }
- // Return the comma delimited number
- return numStringWithCommas
- }
Listing 20-17andListing 20-18shows how to call the handlers inListing 20-15andListing 20-16.
APPLESCRIPT
Open in Script Editor
- convertNumberToCommaDelimitedString(872124243234)
- --> Result: "872,124,243,234"
JAVASCRIPT
Open in Script Editor
- convertNumberToCommaDelimitedString(872124243234)
- // Result: "872,124,243,234"
Note
When you use AppleScriptObjC or JavaScriptObjC, you can use methods of theNSNumberFormatterto format numbers in different ways.
The handlers inListing 20-19andListing 20-20convert a number to a string by returning a comma-delimited, rounded, localized decimal value. For example: (3.64525432506E+5at 0 places converts to"364525",3.64525432506E+5at 3 places converts to"364525.433", and0.2375at 2 places converts"0.24".
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on convertNumberToDecimalString(theNumber, theNumberOfDecimalPlaces)
- if theNumberOfDecimalPlaces is greater than 0 then
- set theDecimalIndicators to "."
- repeat theNumberOfDecimalPlaces times
- set theDecimalIndicators to theDecimalIndicators & "#"
- end repeat
- else
- set theDecimalIndicators to ""
- end if
- set theFormatter to init() of alloc() of NSNumberFormatter of current application
- setFormat_("0" & theDecimalIndicators) of theFormatter
- set theFormattedNumber to stringFromNumber_(theNumber) of theFormatter
- return (theFormattedNumber as string)
- end convertNumberToDecimalString
JAVASCRIPT
Open in Script Editor
- function convertNumberToDecimalString(number, numberOfDecimalPlaces) {
- var decimalIndicators = ""
- if (numberOfDecimalPlaces > 0) {
- decimalIndicators = "."
- for (var i = 0; i < numberOfDecimalPlaces; i++) {
- decimalIndicators += "#"
- }
- }
- var formatter = $.NSNumberFormatter.new
- formatter.format = `0${decimalIndicators}`
- var formattedNumber = formatter.stringFromNumber(number)
- return formattedNumber.js
- }
The handlers inListing 20-21andListing 20-22convert a number to a string by returning a comma-delimited, rounded, localized percentage value. For example:0.2345to"23%"or0.2375to"24%".
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on convertNumberToPercentageString(theNumber)
- set theStyle to NSNumberFormatterPercentStyle of current application
- set theFormattedNumber to localizedStringFromNumber_numberStyle_(theNumber, theStyle) of NSNumberFormatter of current application
- return (theFormattedNumber as string)
- end convertNumberToPercentageString
JAVASCRIPT
Open in Script Editor
- function convertNumberToPercentageString(number) {
- var style = $.NSNumberFormatterPercentStyle
- var formattedNumber = $.NSNumberFormatter.localizedStringFromNumberNumberStyle(number, style)
- return formattedNumber.js
- }
The handlers inListing 20-23andListing 20-24convert a number to a string by returning a comma-delimited, rounded, localized currency value. For example:9128to"$9,128.00"or9978.2485to"$9,978.25".
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on convertNumberToCurrencyString(theNumber)
- set theStyle to NSNumberFormatterCurrencyStyle of current application
- set theFormattedNumber to localizedStringFromNumber_numberStyle_(theNumber, theStyle) of NSNumberFormatter of current application
- return (theFormattedNumber as string)
- end convertNumberToCurrencyString
JAVASCRIPT
Open in Script Editor
- function convertNumberToCurrencyString(number) {
- var style = $.NSNumberFormatterCurrencyStyle
- var formattedNumber = $.NSNumberFormatter.localizedStringFromNumberNumberStyle(number, style)
- return formattedNumber.js
- }
The handlers inListing 20-25andListing 20-26convert a number to a string by returning a string of a numeric value in words. For example:23to âtwenty-three",23.75to"twenty-three point seven five".
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- on convertNumberToWords(theNumber)
- set theStyle to NSNumberFormatterSpellOutStyle of current application
- set theFormattedNumber to localizedStringFromNumber_numberStyle_(theNumber, theStyle) of NSNumberFormatter of current application
- return (theFormattedNumber as string)
- end convertNumberToWords
JAVASCRIPT
Open in Script Editor
- function convertNumberToWords(number) {
- var style = $.NSNumberFormatterSpellOutStyle
- var formattedNumber = $.NSNumberFormatter.localizedStringFromNumberNumberStyle(number, style)
- return formattedNumber.js
- }
In JavaScript,regular expressionscan also be used to convert a number to a comma-delimited string even more efficiently, as shown inListing 20-27.
JAVASCRIPT
Open in Script Editor
- function convertNumberToCommaDelimitedString(num) {
- var numPieces = num.toString().split(".")
- numPieces[0] = numPieces[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
- return numPieces.join(".")
- }
### Determining if a Number is an Odd Number
The handlers inListing 20-28andListing 20-29determine whether a whole number is even or odd. A returned value offalseindicates the passed number is even; a returned value oftrueindicates the passed number is odd.
APPLESCRIPT
Open in Script Editor
- on isNumberOdd(theNumber)
- if theNumber mod 2 is not 0 then
- return true
- else
- return false
- end if
- end isNumberOdd
JAVASCRIPT
Open in Script Editor
- function isNumberOdd(num) {
- return num % 2 !== 0
- }
Listing 20-30andListing 20-31show how to call the handlers inListing 20-28andListing 20-29.
APPLESCRIPT
Open in Script Editor
- isNumberOdd(3)
- --> Result: true
JAVASCRIPT
Open in Script Editor
- isNumberOdd(3)
- // Result: true
Listing 20-32andListing 20-33show how to call the handlers inListing 20-28andListing 20-29by prompting the user to enter an even number.
APPLESCRIPT
Open in Script Editor
- repeat
- display dialog "Enter an even integer:" default answer ""
- try
- if text returned of result is not "" then set theNumberProvided to text returned of result as integer
- if isNumberOdd(theNumberProvided) is false then exit repeat
- end try
- end repeat
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- while (true) {
- var result = app.displayDialog("Enter an even integer:", {defaultAnswer: ""})
- var text = result.textReturned
- if (text !== "") {
- var num = Number(text)
- if (!isNumberOdd(num)) {
- break
- }
- }
- }
### Rounding and Truncating a Number
The handlers inListing 20-34andListing 20-35round and truncate a numeric value, and convert it to a string. Provide a numeric value and indicate a number of decimal places.
Note
These handlers call theconvertNumberToString()handler. SeeListing 20-3.
APPLESCRIPT
Open in Script Editor
- on roundAndTruncateNumber(theNumber, numberOfDecimalPlaces)
- if numberOfDecimalPlaces is 0 then
- set theNumber to theNumber + 0.5
- return convertNumberToString(theNumber div 1)
- end if
- set theRoundingValue to "5"
- repeat numberOfDecimalPlaces times
- set theRoundingValue to "0" & theRoundingValue
- end repeat
- set theRoundingValue to ("." & theRoundingValue) as number
- set theNumber to theNumber + theRoundingValue
- set theModValue to "1"
- repeat numberOfDecimalPlaces - 1 times
- set theModValue to "0" & theModValue
- end repeat
- set theModValue to ("." & theModValue) as number
- set theSecondPart to (theNumber mod 1) div theModValue
- if length of (theSecondPart as text) is less than numberOfDecimalPlaces then
- repeat numberOfDecimalPlaces - (the length of (theSecondPart as text)) times
- set theSecondPart to ("0" & theSecondPart) as string
- end repeat
- end if
- set theFirstPart to theNumber div 1
- set theFirstPart to convertNumberToString(theFirstPart)
- set theNumber to (theFirstPart & "." & theSecondPart)
- return theNumber
- end roundAndTruncateNumber
JAVASCRIPT
Open in Script Editor
- function roundAndTruncateNumber(num, numDecimalPlaces) {
- if (numDecimalPlaces === 0) {
- num = num + 0.5
- return convertNumberToString(num / 1)
- }
- var roundingValue = "5"
- for (var i = 0; i < numDecimalPlaces; i++) {
- roundingValue = "0" + roundingValue
- }
- roundingValue = Number("0." + roundingValue)
- num += roundingValue
- var modValue = "1"
- for (var i = 0; i < numDecimalPlaces - 1; i++) {
- modValue = "0" + modValue
- }
- modValue = Number("0." + modValue)
- var secondPart = Math.floor((num % 1) / modValue)
- var secondPartStringLength = secondPart.toString().length
- if (secondPartStringLength < numDecimalPlaces) {
- var count = numDecimalPlaces - secondPartStringLength
- for (var i = 0; i < count; i++) {
- secondPart = "0" + secondPart
- }
- }
- var firstPart = Math.floor(num)
- firstPart = convertNumberToString(firstPart)
- return `${firstPart}.${secondPart}`
- }
Listing 20-36shows how to call the handler inListing 20-34.
APPLESCRIPT
Open in Script Editor
- roundAndTruncateNumber(1.04575, 3)
- --> Result: "1.046"
Manipulating Text
Manipulating Lists of Items
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Using Handlers/Functions
## Using Handlers/Functions
Collections of script statements that can be invoked by name are referred to ashandlersin AppleScript,functionsormethodsin JavaScript, andsubroutinesin some other languages. Throughout this document, these terms are used interchangeably.
Handlers are generally written to perform a task multiple times throughout a script, such as displaying an alert, writing text to a file, or creating an email message. Instead of inserting the same code over and over, you write it once and give it a name. You can name a handler whatever you like as long as the name contains no special characters, such as punctuation, or spaces, and isnât a reserved language term. You thencall, or evoke, a handler whenever necessary by referring to it by name. Each time you do, any code in the handler runs. Handlers can optionally be written to receive information as input for processing (parameters), and can return information as output (resultorreturn value).
Handlers provide a way to organize your code by breaking it up into smaller, manageable, modular chunks. This can be useful when troubleshooting; you can narrow in on a single handler to resolve a problem, rather than sorting through a long, complex script. It also makes future script updates easier, as you can change behavior in one place to affect an entire script.
Note
AppleScript handlers are generally placed at the end of a script, while in JavaScript, theyâre usually placed at the top.
### AppleScript Handlers
In AppleScript, a handler begins with the wordonorto, followed by the handler name and its parameters, if any. It ends with the wordend, followed by the handler name. AppleScript handlers can be written with positional, labeled, or interleaved parameters.
Listing 13-1shows a simple one-line script that displays a hypothetical error message, which you might want to display numerous times as a script runs.
APPLESCRIPT
Open in Script Editor
- display dialog "The script encountered a problem."
InListing 13-1, the code fromListing 13-1has been converted to a handler nameddisplayError, which has no parameters.
APPLESCRIPT
Open in Script Editor
- on displayError()
- display dialog "The script encountered a problem."
- end displayError
Listing 13-3shows a variation of the handler inListing 13-1, which uses thetoprefix instead ofon. Either syntax is acceptable.
APPLESCRIPT
Open in Script Editor
- to displayError()
- display dialog "The script encountered a problem."
- end displayError
You can now call thedisplayErrorhandler any time you want to display an error, as shown inListing 13-4.
APPLESCRIPT
Open in Script Editor
- try
- -- Do something
- on error
- -- Notify the user that there's a problem
- displayError()
- end try
- try
- -- Do something else
- on error
- -- Notify the user that there's a problem
- displayError()
- end try
For detailed information about AppleScript handlers, seeAbout HandlersandHandler ReferenceinAppleScript Language Guide.
Note
To call a handler from within atellstatement, you must use the reserved wordsof meormy, as shown inListing 13-5.
APPLESCRIPT
Open in Script Editor
- tell application "Finder"
- try
- -- Do something
- on error
- -- Notify the user that there's a problem
- displayError() of me
- end try
- end tell
- tell application "Finder"
- try
- -- Do something else
- on error
- -- Notify the user that there's a problem
- my displayError()
- end try
- end tell
### AppleScript Handlers with Positional Parameters
Positional parameters are a series of comma-separated variables, contained within parentheses, following the handler name. InListing 13-6, thedisplayErrorhandler fromListing 13-1has been updated to accept two positional parametersâan error message and a list of buttons to display.
APPLESCRIPT
Open in Script Editor
- on displayError(theErrorMessage, theButtons)
- display dialog theErrorMessage buttons theButtons
- end displayError
To call the handler, refer to it by name and provide a value for each positional parameter, as shown inListing 13-7. The order of these values should match the parameter positions in the handler definition.
APPLESCRIPT
Open in Script Editor
- displayError("There's not enough available space. Would you like to continue?", {"Don't Continue", "Continue"})
For additional information about this style of handler, seeHandlers with Positional ParametersinAppleScript Language Guide.
### AppleScript Handlers with Interleaved Parameters
Interleaved parameters are a variation of positional parameters, in which the parameter name is split into pieces and interleaved with parameters using colons and spaces.Listing 13-8shows how the handler fromListing 13-6can be represented using interleaved parameters.
APPLESCRIPT
Open in Script Editor
- tell me to displayError:"There's not enough available space. Would you like to continue?" withButtons:{"Don't Continue", "Continue"}
- on displayError:theErrorMessage withButtons:theButtons
- display dialog theErrorMessage buttons theButtons
- end displayError:withButtons:
Interleaved parameters resemble Objective-C syntax. Therefore, they are typically used to call Objective-C methods in AppleScriptObjC scripts.
Objective-C to AppleScript Quick Translation Guidediscusses interleaved parameter use in AppleScriptObjC scripts. For additional information about this style of handler, seeHandlers with Interleaved ParametersinAppleScript Language Guide.
### AppleScript Handlers with Labeled Parameters
AppleScript also supports labeled parameters, although this style is rarely used when defining custom handlers. Most often, itâs a style used for event handlers. SeeEvent Handlers.Listing 13-9shows how thedisplayErrorhandler might appear if it were written using the labeled parameter style.
APPLESCRIPT
Open in Script Editor
- display of "There's not enough available space. Would you like to continue?" over {"Don't Continue", "Continue"}
- to display of theErrorMessage over theButtons
- display dialog theErrorMessage buttons theButtons
- end display
For additional information about this style of handler, seeHandlers with Labeled ParametersinAppleScript Language Guide.
### JavaScript Functions
In JavaScript, a function name is preceded by the wordfunctionand followed by a list of parameters, if any. The functionâs contents are contained within curly braces ({ ... }).
Listing 13-10shows a simple script that displays a hypothetical error message.
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function displayError() {
- app.displayDialog("The script encountered a problem.")
- }
You can now call thedisplayErrorfunction any time you want to display an error, as shown inListing 13-11.
JAVASCRIPT
Open in Script Editor
- try {
- // Do something
- } catch (error) {
- // Notify the user that there's a problem
- displayError()
- }
- try {
- // Do something else
- } catch (error) {
- // Notify the user that there's a problem
- displayError()
- }
### Using Parameters
JavaScript functions are written with positional parameters, comma-separated variables, contained within parentheses, following the function name. InListing 13-12, thedisplayErrorfunction fromListing 13-10has been updated to accept two positional parametersâan error message and a list of buttons to display.
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function displayError(errorMessage, buttons) {
- app.displayDialog(errorMessage, {
- buttons: buttons
- })
- }
To call the function, refer to it by name and provide a value for each positional parameter, as shown inListing 13-13. The order of these values should match the parameter positions in the function definition.
JAVASCRIPT
Open in Script Editor
- displayError("There's not enough available space. Would you like to continue?", ["Don't Continue", "Continue"])
### Exiting Handlers and Returning a Result
Often, handlers are used to process information and produce a result for further processing. To enable this functionality, add thereturncommand, followed by a value to provide, to the handler. InListing 13-14andListing 13-15, thedisplayErrorhandler returns a Boolean value, indicating whether processing should continue after an error has occurred.
APPLESCRIPT
Open in Script Editor
- set shouldContinueProcessing to displayError("There's not enough available space. Would you like to continue?")
- if shouldContinueProcessing = true then
- -- Continue processing
- else
- -- Stop processing
- end if
- on displayError(theErrorMessage)
- set theResponse to display dialog theErrorMessage buttons {"Don't Continue", "Continue"} default button "Continue"
- set theButtonChoice to button returned of theResponse
- if theButtonChoice = "Continue" then
- return true
- else
- return false
- end if
- end displayError
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function displayError(errorMessage) {
- var response = app.displayDialog(errorMessage, {
- buttons: ["Don't Continue", "Continue"],
- defaultButton: "Continue"
- })
- var buttonChoice = response.buttonReturned
- if (buttonChoice == "Continue")
- return true
- else
- return false
- }
- var shouldContinueProcessing = displayError("There's not enough available space. Would you like to continue?")
- if (shouldContinueProcessing) {
- // Continue processing
- } else {
- // Stop processing
- }
Note
You can return a value at any time within a handler, not just at the end.
### Event Handlers
Some apps, including scripts themselves, can call handlers when certain events occur, such as when launched or quit. In Mail, you can set up a rule to look for incoming emails matching certain criteria. When a matching email is detected, Mail can call a handler in a specified script to process the email. Handlers like these are consideredevent handlersorcommand handlers.
Listing 13-16shows an example of a Mail rule event handler. It receives any detected messages as input, and can loop through them to process them.
APPLESCRIPT
Open in Script Editor
- using terms from application "Mail"
- on perform mail action with messages theDetectedMessages for rule theRule
- tell application "Mail"
- set theMessageCount to count of theDetectedMessages
- repeat with a from 1 to theMessageCount
- set theCurrentMessage to item a of theDetectedMessages
- -- Process the message
- end repeat
- end tell
- end perform mail action with messages
- end using terms from
### Script Event Handlers
As previously mentioned, scripts can contain event handlers too. These handlers run when certain events occur.
### Run Handlers
Therunevent handler is called when a script runs. By default, any executable code at the top level of a scriptâthat is, not contained within a handler orscriptobjectâis considered to be contained within an implicitrunhandler. SeeListing 13-17andListing 13-18.
APPLESCRIPT
Open in Script Editor
- display dialog "The script is running."
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.displayDialog("The script is running.")
Optionally, therunhandler can be explicitly defined.Listing 13-19andListing 13-20produce the exact same behavior asListing 13-17andListing 13-18.
APPLESCRIPT
Open in Script Editor
- on run
- display dialog "The script is running."
- end run
JAVASCRIPT
Open in Script Editor
- function run() {
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.displayDialog("The script is running.")
- }
### Quit Handlers
Thequitevent handler is optional, and is called when a script app quits. Use this as an opportunity to perform cleanup tasks, if necessary, such as removing temporary folders or logging progress.Listing 13-21andListing 13-22demonstrate the use of aquithandler.
APPLESCRIPT
Open in Script Editor
- on quit
- display dialog "The script is quitting."
- end quit
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function quit() {
- app.displayDialog("The script is quitting.")
- }
### Open Handlers
The inclusion of anopenhandler oropenDocumentsmethod in a script app automatically makes the app drag-and-droppable. When launched in this way, theopenhandler receives a dropped list of files or folders as a direct parameter, as shown inListing 13-23andListing 13-24.
APPLESCRIPT
Open in Script Editor
- on open theDroppedItems
- -- Process the dropped items here
- end open
JAVASCRIPT
Open in Script Editor
- function openDocuments(droppedItems) {
- // Process the dropped items here
- }
For detailed information about using theopenhandler to create drop scripts, seeProcessing Dropped Files and Folders.
### Idle Handlers
When saving a script, you can optionally save it as a stay-open application. SeeFigure 13-1. In a stay-open script app, the script stays open after therunhandler completes, and anidlehandler is called every 30 seconds. Use theidlehandler to perform periodic processing tasks, such as checking a watched folder for new files to process. To change the duration betweenidlecalls, return a new duration, in seconds, as the result of theidlehandler.Listing 13-25andListing 13-26demonstrate anidlehandler that delays for five seconds between executions.
APPLESCRIPT
Open in Script Editor
- on idle
- display dialog "The script is idling."
- return 5
- end idle
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- function idle() {
- app.displayDialog("The script is idling.")
- return 5
- }
For information about using theidlehandler for folder watching, seeWatching Folders.
Navigating a Scripting Dictionary
Using Script Libraries
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: About Scripting Terminology
## About Scripting Terminology
AppleScript and JavaScript possess core language commands, classes, and properties that make scripting possible. For AppleScript, core terminology is documented inAppleScript Language Guide. For JavaScript, seeJavaScript for Automation Release NotesandMozillaâs official JavaScript documentation.
Each scriptable app introduces additional terminology that extends the core language. For example, Mail introduces terminology for creating and sending email messages. iTunes introduces terminology for working with music and playlists. In order to write a script that controls an app, you need to familiarize yourself with that appâs terminology.
The terminology for an app is found in itsscripting dictionary, an.sdeffile stored in the app bundle. The dictionary describes the commands, classes, and properties an app supports. This information is used by the scripting components of the operating system, the app itself, and any other apps or scripts that interact with the app through scripting. It also serves as a reference, which you can consult in Script Editor for guidance as you write a script. SeeFigure 10-1.
Not every OSÂ X app supports scripting, but many apps do, including Mail, Address Book, Calendar, iTunes, and Messages. To determine if a particular app is scriptable, see if it has a scripting dictionary. SeeOpening a Scripting Dictionary.
Scripting terminology can vary extensively from app to app. While some apps may have extensive scripting support, others may have very limited scripting support. If an app doesnât meet your scripting needs, reach out to the app developer and request improved support in a future version. To request scripting enhancements for Apple apps, submit abug reportthat specifies the app and communicates your specific needs.
Also, keep in mind that scripting terminology can change from one version of an app or OSÂ X to the next. Always test essential scripts when upgrading to a new app or system version.
Note
OSÂ X also supports scripting additions, packages of terminology that extend the core AppleScript language. In fact, OSÂ X comes with Standard Additions, a scripting addition that implements a range of commonly performed functions, such as displaying alerts and dialogs, speaking text, and reading and writing files. Scripting additions are installed in/System/ScriptingAdditions/,/Library/ScriptingAdditions/, or~/Library/ScriptingAdditions/, and have dictionaries just like scriptable apps.
Configuring Scripting Preferences
Opening a Scripting Dictionary
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Prompting for a Color
## Prompting for a Color
Use the Standard Additions scripting additionâschoose colorcommand to ask the user to select a color from a color picker dialog like the one shown inFigure 29-1. The command accepts an optionaldefault colorparameter, and produces an RGB color value as its result.Listing 29-1andListing 29-2display a color picker, create a TextEdit document containing some text, and apply the chosen color to the text.
APPLESCRIPT
Open in Script Editor
- set theColor to choose color default color {0, 65535, 0}
- --> Result: {256, 40421, 398}
- tell application "TextEdit"
- set theDocument to make new document
- set text of document 1 to "Colored Text"
- set color of text of document 1 to theColor
- end tell
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var color = app.chooseColor({defaultColor: [0, 1, 0]})
- // Result: [0.003753719385713339, 0.7206835746765137, 0.005828946363180876]
- color = [Math.trunc(color[0] * 65535), Math.trunc(color[1] * 65535), Math.trunc(color[2] * 65535)]
- var textedit = Application("TextEdit")
- var document = textedit.make({new: "document"})
- document.text = "Colored Text"
- document.text.color = [256, 40421, 398]
Note
In AppleScript, thechoose colorcommand produces RGB values ranging from0through65535. In JavaScript, the RGB values range between0and1. These values must be converted to match the AppleScript values to be used.Listing 29-2demonstrates this conversion.
Prompting for a Choice from a List
Displaying Progress
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Using the Systemwide Script Menu
## Using the Systemwide Script Menu
The OSÂ X script menu provides quick access to your collection of scripts. Simply select a script in the menu at any time to run it instantly. Within the script menu, scripts can be organized into subfolders and by application. SeeFigure 41-1.
Note
The script menu can run compiled scripts, as well as scripts saved as apps. It can also run UNIX shell scripts and Automator workflows.
### Enabling the Script Menu
The script menu is disabled by default in OSÂ X.
- Launch Script Editor, located in/Applications/Utilities/.
Launch Script Editor, located in/Applications/Utilities/.
- Select Script Editor > Preferences, or press Command-Comma (,), to open the preferences window.
Select Script Editor > Preferences, or press Command-Comma (,), to open the preferences window.
- Click General in the toolbar.
Click General in the toolbar.
- Enable the âShow Script menu in menu barâ checkbox.
Enable the âShow Script menu in menu barâ checkbox.
- Choose whether application scriptsâscripts that appear only when a corresponding app is in the frontâshould appear at the top or bottom of the script menu.
Choose whether application scriptsâscripts that appear only when a corresponding app is in the frontâshould appear at the top or bottom of the script menu.
The script menu displays scripts in the~/Library/Scripts/folder of your user directory. To include scripts at the computer-level (in the/Library/Scripts/folder), enable the âShow Computer scriptsâ checkbox.
### Adding User-Level Scripts to the Script Menu
User-level scripts are scripts that only you can see and use. They arenât available to other users on your Mac.
To add user-level scripts to the script menu, save them into the~/Library/Scripts/folder of your user directory. For quick access to this folder, select Open Scripts Folder > Open User Scripts Folder from the script menu. When you do this, the folder is automatically created if it doesnât already exist.
### Adding Computer-Level Scripts to the Script Menu
Computer-level scripts are scripts that any user on your Mac can see and use.
To add computer-level scripts to the script menu, save them into the/Library/Scripts/folder on your Mac. For quick access to this folder, select Open Scripts Folder > Open Computer Scripts Folder from the script menu. When you do this, the folder is automatically created if it doesnât already exist.
### Adding Application-Specific Scripts to the Script Menu
Application-specific scripts are only visible in the script menu when a specific app is in the front.
To add application-specific scripts to the script menu, save them into the~/Library/Scripts/Applications/«ApplicationName»folder in your user directory or the/Library/Scripts/Applications/«ApplicationName»folder on your Mac. For quick access to this folder, bring the app to the front, then select Open Scripts Folder > Open «ApplicationName» Scripts Folder from the script menu. When you do this, a folder for the application is automatically created if it doesnât already exist.
### Running Scripts in the Script Menu
Select a script from the script menu to run it. If the script is an application, it launches and runs normally. If the script is a compiled script, a progress indicator appears in the menu bar. SeeFigure 41-2.
Note
To reveal a script in the script menu, select it in the menu while pressing the Shift key.
To open a script menu script in Script Editor, select it in the menu while pressing the Option key.
Making a Systemwide Service
Using Dictation to Run Scripts
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Getting to Know Script Editor
## Getting to Know Script Editor
Script Editor, found in/Applications/Utilities/, is an app for writing AppleScripts and JavaScripts. It provides the ability to edit, compile, and run scripts, browse scripting terminology, and save scripts in a variety of formats including compiled scripts, apps, and plain text.
Note
Xcode can also be used to write AppleScriptObjC and JavaScriptObjC apps.
### Navigating Script Editor Documents
A Script Editor document window includes the following main areas, as shown inFigure 5-1:
- ToolbarâUse this to compile, run, and stop your script. Buttons are also available for showing and hiding the accessory view pane and the bundle contents pane. Select View > Customize Toolbar, or Control-click on the toolbar and choose Customize Toolbar, to choose what buttons displayed in the toolbar.The toolbar also includes a Record button, which converts manual mouse clicks and keystrokes into script code. However, recording is not supported in JavaScript and few apps support AppleScript recording.
ToolbarâUse this to compile, run, and stop your script. Buttons are also available for showing and hiding the accessory view pane and the bundle contents pane. Select View > Customize Toolbar, or Control-click on the toolbar and choose Customize Toolbar, to choose what buttons displayed in the toolbar.
The toolbar also includes a Record button, which converts manual mouse clicks and keystrokes into script code. However, recording is not supported in JavaScript and few apps support AppleScript recording.
- Navigation barâUse this bar to select a scripting language, target an app, or navigate through the handlers in your script.The navigation bar currently only supports navigation of AppleScript handlers.
Navigation barâUse this bar to select a scripting language, target an app, or navigate through the handlers in your script.
The navigation bar currently only supports navigation of AppleScript handlers.
- Editor paneâWrite your script code here.
Editor paneâWrite your script code here.
- Accessory View paneâView and edit your scriptâs description here, or browse the result and events produced when your script runs.
Accessory View paneâView and edit your scriptâs description here, or browse the result and events produced when your script runs.
- Bundle Contents paneâ Edit the identifier, version, and copyright info for your script here. You can also use this pane to add, remove, or manage resources contained within the bundle. This pane is accessible only when your script is saved in script bundle or app format.
Bundle Contents paneâ Edit the identifier, version, and copyright info for your script here. You can also use this pane to add, remove, or manage resources contained within the bundle. This pane is accessible only when your script is saved in script bundle or app format.
### Targeting a Scripting Language
When you create a Script Editor document, select a scripting language in the navigation bar. SeeFigure 5-2.
If you always use the same language, set it as the default in the General pane of Script Editor preferences. SeeFigure 5-3.
### Viewing Script Events and Results
Script Editor can display the result of executing a script, as well as a log of events sent and received during execution.
Note
Aresultis a value generated when a script statement executes. For example, executing themakecommand to create a folder in the Finder produces the newly created folder object as its result. The result of a script is the result of the scriptâs last statement. If the scriptâs last statement doesnât produce a result, then the script has no result.
### Viewing the Script Result
The result of executing your scriptâif a result was producedâis found in the Accessory View pane. SeeFigure 5-4.
Do one of the following:
- Press Command-2.
Press Command-2.
- Choose View > Show Result.
Choose View > Show Result.
- Click the Show Result () button at the bottom of the Accessory View pane.
Click the Show Result () button at the bottom of the Accessory View pane.
### Viewing the Script Log
The Accessory View pane also contains a script log. SeeFigure 5-5.
The script log displays the following information.
- ResultâThe result of executing your script.
ResultâThe result of executing your script.
- MessagesâIncludes log messages generated as your script runs, as well as the scriptâs result.
MessagesâIncludes log messages generated as your script runs, as well as the scriptâs result.
- EventsâIncludes log messages, the scriptâs result, and eventsâcommandsâsent to applications.
EventsâIncludes log messages, the scriptâs result, and eventsâcommandsâsent to applications.
- RepliesâIncludes log messages, the scriptâs result, events sent to applications, and event replies.
RepliesâIncludes log messages, the scriptâs result, events sent to applications, and event replies.
Do one of the following:
- Press Command-3.
Press Command-3.
- Choose View > Show Log.
Choose View > Show Log.
- Click the Show Log () button at the bottom of the Accessory View pane.
Click the Show Log () button at the bottom of the Accessory View pane.
Note
In AppleScript, log messages are generated using thelogcommand. SeeListing 5-1.
APPLESCRIPT
Open in Script Editor
- log "My log entry."
Since thelogcommand targets the script itself, you must explicitly use themekeyword to direct it to the script when calling it within a tell statement. SeeListing 5-2.
APPLESCRIPT
Open in Script Editor
- tell app "Finder"
- tell me to log "My log entry."
- end tell
In JavaScript, log messages are generated by calling theconsole.log()method anywhere in your script. SeeListing 5-3.
JAVASCRIPT
Open in Script Editor
- console.log("My log entry.")
### Viewing the Log History
The result and script log areas in the Accessory View pane reset each time you run your script. However, you can view historical logs for an opened script in the Log History window. SeeFigure 5-6.
Do one of the following:
- Press Option-Command-L.
Press Option-Command-L.
- Choose View > Log History.
Choose View > Log History.
- Click the Log History button () in the top right of the Accessory View pane.
Click the Log History button () in the top right of the Accessory View pane.
About this Guide
Creating a Script
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Encoding and Decoding Text
## Encoding and Decoding Text
A standard practice when creating URL's is to encode spaces and special characters (high-level ASCII) to hexadecimal equivalents. For example, spaces in URL's are routinely converted to%20. The process of encoding and decoding URLs and other text in this manner can be accomplished through scripting.
### Encoding Characters
The handler inListing 32-1encodes a single character.
APPLESCRIPT
Open in Script Editor
- on encodeCharacter(theCharacter)
- set theASCIINumber to (the ASCII number theCharacter)
- set theHexList to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
- set theFirstItem to item ((theASCIINumber div 16) + 1) of theHexList
- set theSecondItem to item ((theASCIINumber mod 16) + 1) of theHexList
- return ("%" & theFirstItem & theSecondItem) as string
- end encodeCharacter
Listing 32-2shows how to call the handler inListing 32-1.
APPLESCRIPT
Open in Script Editor
- encodeCharacter("$")
- --> Result: "%24"
### Encoding Text
The handler inListing 32-3encodes an entire string. Provide a string and indicate whether to encode two levels of special characters. The first level includes commonly encoded special characters, such as$,%, and*. The second level includes extended special characters that arenât typically encodedâ.,-,_, and:. High-level ASCII characters, such as copyright symbols, trademark symbols, and spaces, are always encoded.
APPLESCRIPT
Open in Script Editor
- on encodeText(theText, encodeCommonSpecialCharacters, encodeExtendedSpecialCharacters)
- set theStandardCharacters to "abcdefghijklmnopqrstuvwxyz0123456789"
- set theCommonSpecialCharacterList to "$+!'/?;&@=#%><{}\"~`^\\|*"
- set theExtendedSpecialCharacterList to ".-_:"
- set theAcceptableCharacters to theStandardCharacters
- if encodeCommonSpecialCharacters is false then set theAcceptableCharacters to theAcceptableCharacters & theCommonSpecialCharacterList
- if encodeExtendedSpecialCharacters is false then set theAcceptableCharacters to theAcceptableCharacters & theExtendedSpecialCharacterList
- set theEncodedText to ""
- repeat with theCurrentCharacter in theText
- if theCurrentCharacter is in theAcceptableCharacters then
- set theEncodedText to (theEncodedText & theCurrentCharacter)
- else
- set theEncodedText to (theEncodedText & encodeCharacter(theCurrentCharacter)) as string
- end if
- end repeat
- return theEncodedText
- end encodeText
Note
This handler calls theencodeCharacter()handler. SeeListing 32-1.
Listing 32-4shows how to call the handler inListing 32-3to encode only high-level ASCII characters.
APPLESCRIPT
Open in Script Editor
- encodeText("*smith-wilson© report_23.txt", false, false)
- --> Result: "*smith-wilson%A9%20report_23.txt"
Listing 32-5shows how to call the handler inListing 32-3to encode high-level ASCII characters and all special characters.
APPLESCRIPT
Open in Script Editor
- encodeText("*smith-wilson© report_23.txt", true, true)
- --> Result: "%2Asmith%2Dwilson%A9%20report%5F23%2Etxt"
Listing 32-6shows how to call the handler inListing 32-3to encode high-level ASCII characters and special characters, excluding periods, hyphens, underscores, and colons.
APPLESCRIPT
Open in Script Editor
- encodeText("annual smith-wilson_report.txt", true, false)
- --> Result: "annual%20smith-wilson_report.txt"
Note
When you use AppleScriptObjC, you can use methods of theNSStringclass to encode text. The handler inListing 32-7demonstrates how to do this.
APPLESCRIPT
Open in Script Editor
- on encodeText(theText)
- set theString to stringWithString_(theText) of NSString of current application
- set theEncoding to NSUTF8StringEncoding of current application
- set theAdjustedString to stringByAddingPercentEscapesUsingEncoding_(theEncoding) of theString
- return (theAdjustedString as string)
- end encodeText
### Decoding Text
The handler inListing 32-8decodes an encoded character hex string.
APPLESCRIPT
Open in Script Editor
- on decodeCharacterHexString(theCharacters)
- copy theCharacters to {theIdentifyingCharacter, theMultiplierCharacter, theRemainderCharacter}
- set theHexList to "123456789ABCDEF"
- if theMultiplierCharacter is in "ABCDEF" then
- set theMultiplierAmount to offset of theMultiplierCharacter in theHexList
- else
- set theMultiplierAmount to theMultiplierCharacter as integer
- end if
- if theRemainderCharacter is in "ABCDEF" then
- set theRemainderAmount to offset of theRemainderCharacter in theHexList
- else
- set theRemainderAmount to theRemainderCharacter as integer
- end if
- set theASCIINumber to (theMultiplierAmount * 16) + theRemainderAmount
- return (ASCII character theASCIINumber)
- end decodeCharacterHexString
Listing 32-9shows how to call the handler inListing 32-8.
APPLESCRIPT
Open in Script Editor
- decodeCharacterHexString("%24")
- --> Result: "$"
The handler inListing 32-10decodes any encoded character hex strings in the specified text.
APPLESCRIPT
Open in Script Editor
- on decodeText(theText)
- set flagA to false
- set flagB to false
- set theTempCharacter to ""
- set theCharacterList to {}
- repeat with theCurrentCharacter in theText
- set theCurrentCharacter to contents of theCurrentCharacter
- if theCurrentCharacter is "%" then
- set flagA to true
- else if flagA is true then
- set theTempCharacter to theCurrentCharacter
- set flagA to false
- set flagB to true
- else if flagB is true then
- set end of theCharacterList to decodeCharacterHexString(("%" & theTempCharacter & theCurrentCharacter) as string)
- set theTempCharacter to ""
- set flagA to false
- set flagB to false
- else
- set end of theCharacterList to theCurrentCharacter
- end if
- end repeat
- return theCharacterList as string
- end decodeText
Note
This handler calls thedecodeCharacterHexString()handler. SeeListing 32-8.
Listing 32-11shows how to call the handler inListing 32-10.
APPLESCRIPT
Open in Script Editor
- decodeText("%2Asmith%2Dwilson%A9%20report%5F23%2Etxt")
- --> Result: "*smith-wilson© report_23.txt"
Note
When you use AppleScriptObjC, you can use methods of theNSStringclass to decode URL encoded text. The handler inListing 32-12demonstrates how to do this.
APPLESCRIPT
Open in Script Editor
- on decodeText(theText)
- set theString to stringWithString_(theText) of NSString of current application
- set theEncoding to NSUTF8StringEncoding of current application
- set theAdjustedString to stringByReplacingPercentEscapesUsingEncoding_(theEncoding) of theString
- return (theAdjustedString as string)
- end decodeText
Converting RGB to HTML Color
Parsing HTML
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Displaying Dialogs and Alerts
## Displaying Dialogs and Alerts
Dialogs and alerts are great ways to provide information about a scriptâs progress, report problems, and allow users to make decisions that affect script behavior.
### Displaying a Dialog
Use thedisplay dialogcommand, provided by the Standard Additions scripting addition to show a basic dialog message to the user, such as the one inFigure 22-1. This dialog was produced by the code inListing 22-1andListing 22-2. In these examples, a string is passed to thedisplay dialogcommand as a direct parameter. The result of the command is the button the user clicked in the dialog.
APPLESCRIPT
Open in Script Editor
- set theDialogText to "The curent date and time is " & (current date) & "."
- display dialog theDialogText
- --> Result: {button returned:"OK"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var dialogText = "The current date and time is " + (app.currentDate())
- app.displayDialog(dialogText)
- // Result: {"buttonReturned":"OK"}
Note
This chapter covers a portion of thedisplay dialogcommandâs capabilities. For example, thedisplay dialogcommand can also be used to collect text entered by the user. This is covered inPrompting for Text. For complete information about thedisplay dialogcommand and its parameters, launch Script Editor, open the Standard Additions scripting additionâs dictionary, and navigate to the commandâs definition.
### Customizing Dialog Buttons
By default, a dialog produced by thedisplay dialogcommand has two buttonsâCancel and OK (the default). However, the command also has numerous optional parameters, some of which can be used to customize the buttons.
Use thebuttonsparameter to provide a list of between one and three buttons. You can optionally use thedefault buttonparameter to configure one as the defaultâitâs highlighted and pressing the Return key activates it to close the dialog. You can also use thecancel buttonparameter to configure one as the cancel buttonâpressing Escape or Command-Period (.) activates it to close the dialog and produce a user cancelled error.
The dialog shown inFigure 22-2has been customized to include Donât Continue (the cancel button) and Continue (the default) buttons. This dialog was produced by the example code inListing 22-3andListing 22-4.
APPLESCRIPT
Open in Script Editor
- set theDialogText to "An error has occurred. Would you like to continue?"
- display dialog theDialogText buttons {"Don't Continue", "Continue"} default button "Continue" cancel button "Don't Continue"
- --> Result: {{button returned:"Continue"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var dialogText = "An error has occurred. Would you like to continue?"
- app.displayDialog(dialogText, {
- buttons: ["Don't Continue", "Continue"],
- defaultButton: "Continue",
- cancelButton: "Don't Continue"
- })
- // Result: {"buttonReturned":"Continue"}
### Adding an Icon to a Dialog
Dialogs can also include an icon, providing users with a visual clue to their importance. You can direct thedisplay dialogcommand to a specific icon by its file path, or resource name or ID if the icon is stored as a resource within your scriptâs bundle. You can also use the standard system iconsstop,note, andcaution.Listing 22-5andListing 22-6display a dialog that includes the system caution icon like the one shown inFigure 22-3.
APPLESCRIPT
Open in Script Editor
- set theDialogText to "The amount of available free space is dangerously low."
- display dialog theDialogText with icon caution
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var dialogText = "The amount of available free space is dangerously low."
- app.displayDialog(dialogText, {withIcon: "caution"})
### Automatically Dismissing a Dialog
Sometimes, you may want to continue with script execution if a dialog isnât dismissed by a user within a certain timeframe. In this case, you can specify an integer value for thedisplay dialogcommandâsgiving up afterparameter, causing the dialog togive upand close automatically after a specified period of inactivity.
Listing 22-7andListing 22-8display a dialog that automatically closes after five seconds of inactivity.
APPLESCRIPT
Open in Script Editor
- display dialog "Do, or do not. There is no try." giving up after 5
- --> Result: {button returned:"OK", gave up:true}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var dialogText = "Do, or do not. There is no try."
- app.displayDialog(dialogText, {givingUpAfter: 5})
- // Result: {"buttonReturned":"OK", "gaveUp":true}
When using thegiving up afterparameter, the result of thedisplay dialogcommand includes agaveUpproperty, a Boolean value indicating whether the dialog was auto-dismissed. This information is useful if you want the script to take a different course of action based on whether a dialog is manually or automatically dismissed.
### Displaying an Alert
Thedisplay alertcommand is also provided by the Standard Additions scripting addition. Itâs similar to thedisplay dialogcommand, but with slightly different parameters. One of thedisplay alertcommandâs optional parameters ismessage, which lets you provide additional text to display in a separate text field, below the bolded alert text.Listing 22-9andListing 22-10show how to display the alert inFigure 22-4, which contains bolded alert text, plain message text, and custom buttons.
APPLESCRIPT
Open in Script Editor
- set theAlertText to "An error has occurred."
- set theAlertMessage to "The amount of available free space is dangerously low. Would you like to continue?"
- display alert theAlertText message theAlertMessage as critical buttons {"Don't Continue", "Continue"} default button "Continue" cancel button "Don't Continue"
- --> Result: {button returned:"Continue"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var alertText = "An error has occurred."
- var alertMessage = "The amount of available free space is dangerously low. Would you like to continue?"
- app.displayAlert(alertText, {
- message: alertMessage,
- as: "critical",
- buttons: ["Don't Continue", "Continue"],
- defaultButton: "Continue",
- cancelButton: "Don't Continue"
- })
- // Result: {"buttonReturned":"OK"}
Note
This chapter covers a portion of thedisplay alertcommandâs capabilities. For complete information about thedisplay alertcommand and its parameters, launch Script Editor, open the Standard Additions scripting additionâs dictionary, and navigate to the commandâs definition.
Manipulating Lists of Items
Prompting for Text
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Prompting for a File Name
## Prompting for a File Name
Use the Standard Additions scripting additionâschoose file namecommand to display a save dialog that lets the user enter a file name and choose an output folder, such as the one produced byListing 27-1andListing 27-2, shown inFigure 27-1.
APPLESCRIPT
Open in Script Editor
- set theNewFilePath to choose file name with prompt "Save the document as:"
- --> Result: file "Macintosh HD:Users:yourUserName:Desktop:ImportantDocument"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var newFilePath = app.chooseFileName({
- withPrompt: "Save the document as:"
- })
- newFilePath
- // Result: Path("/Users/yourUserName/Desktop/ImportantDocument")
If the specified file name already exists in the output folder when the user clicks the Save button, the user is prompted to replace it, as shown inFigure 27-2.
The result of thechoose file namecommand is a path to a potential file. This file may or may not already exist. However, if it does exist, you can assume the user wants to replace it. Your script can now safely write or save a file to the path.
Listing 27-3andListing 27-4ask the user to type some text as a note and choose an file name and output folder, and then save the note in the specified file.
APPLESCRIPT
Open in Script Editor
- set theResponse to display dialog "Enter a note:" default answer ""
- set theNote to text returned of theResponse
- set theNewFilePath to choose file name with prompt "Save the document as:"
- writeTextToFile(theNote, theNewFilePath, true)
- on writeTextToFile(theText, theFile, overwriteExistingContent)
- try
- -- Convert file to a string
- set theFile to theFile as string
- -- Open file for writing
- set theOpenedFile to open for access file theFile with write permission
- -- Clear file if content should be overwritten
- if overwriteExistingContent is true then set eof of theOpenedFile to 0
- -- Write new content to file
- write theText to theOpenedFile starting at eof
- -- Close file
- close access theOpenedFile
- -- Return a boolean indicating that writing was successful
- return true
- -- Handle a write error
- on error
- -- Close file
- try
- close access file theFile
- end try
- -- Return a boolean indicating that writing failed
- return false
- end try
- end writeTextToFile
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var response = app.displayDialog("Enter a note:", {
- defaultAnswer: ""
- })
- var note = response.textReturned
- var newFilePath = app.chooseFileName({
- withPrompt: "Save document as:"
- })
- writeTextToFile(note, newFilePath, true)
- function writeTextToFile(text, file, overwriteExistingContent) {
- try {
- // Convert file to a string
- var fileString = file.toString()
- // Open file for writing
- var openedFile = app.openForAccess(Path(fileString), { writePermission: true })
- // Clear file if content should be overwritten
- if (overwriteExistingContent) {
- app.setEof(openedFile, { to: 0 })
- }
- // Write new content to file
- app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) })
- // Close file
- app.closeAccess(openedFile)
- // Return a boolean indicating that writing was successful
- return true
- }
- catch (error) {
- try {
- // Close file
- app.closeAccess(file)
- }
- catch(error) {
- // Report error is closing failed
- console.log(`Couldn't close file: ${error}`)
- }
- // Return a boolean indicating that writing was successful
- return false
- }
- }
Prompting for Files or Folders
Prompting for a Choice from a List
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Prompting for Files or Folders
## Prompting for Files or Folders
Itâs generally good practice to avoid hard-coding file and folder paths in a script. Prompting the user to select files and folders makes for a more dynamic script that wonât break when paths change.
### Prompting for a File
Use the Standard Additions scripting additionâschoose filecommand to prompt the user to select a file.Listing 26-1andListing 26-2demonstrate how to use this command to display the simple file selection dialog with a custom prompt shown inFigure 26-1.
APPLESCRIPT
Open in Script Editor
- set theDocument to choose file with prompt "Please select a document to process:"
- --> Result: alias "Macintosh HD:Users:yourUserName:Documents:ImportantDoc.pages"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var document = app.chooseFile({
- withPrompt: "Please select a document to process:"
- })
- document
- // Result: Path("/Users/yourUserName/Documents/ImportantDoc.pages")
### Prompting for a Specific Type of File
If your script requires specific types of files for processing, you can use thechoose filecommandâs optionalof typeparameter to provide a list of acceptable types. Types may be specified as extension strings without the leading period (such as"jpg"or"png") or as uniform type identifiers (such as"public.image"or"com.apple.iwork.pages.sffpages").Listing 26-3andListing 26-4show how to prompt for an image.
APPLESCRIPT
Open in Script Editor
- set theImage to choose file with prompt "Please select an image to process:" of type {"public.image"}
- --> Result: alias "Macintosh HD:Users:yourUserName:Pictures:IMG_0024.jpg"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var image = app.chooseFile({
- withPrompt: "Please select an image to process:",
- ofType: ["public.image"]
- })
- image
- // Result: Path("/Users/yourUserName/Pictures/IMG_0024.jpg")
### Prompting for Multiple Files
To let the user choose more than one file, include thechoose filecommandâs optionalmultiple selections allowedparameter.Listing 26-5andListing 26-6display a prompt asking for multiple images, as shown inFigure 26-2.
APPLESCRIPT
Open in Script Editor
- set theImages to choose file with prompt "Please select some images to process:" of type {"public.image"} with multiple selections allowed
- --> Result: {alias "Macintosh HD:Users:yourUserName:Pictures:IMG_0024.jpg", alias "Macintosh HD:Users:yourUserName:Pictures:IMG_0025.jpg", alias "Macintosh HD:Users:yourUserName:Pictures:IMG_0026.jpg"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var images = app.chooseFile({
- withPrompt: "Please select some images to process:",
- ofType: ["public.image"],
- multipleSelectionsAllowed: true
- })
- images
- // Result: [Path("/Users/yourUserName/Pictures/IMG_0024.jpg"), Path("/Users/yourUserName/Pictures/IMG_0025.jpg"), Path("/Users/yourUserName/Pictures/IMG_0026.jpg")]
### Prompting for a Folder
Use the Standard Additions scripting additionâschoose foldercommand to prompt the user to select a folder, such as an output folder or folder of images to process.Listing 26-7andListing 26-8demonstrate how to use this command to display the simple folder selection dialog with a custom prompt shown inFigure 26-3.
APPLESCRIPT
Open in Script Editor
- set theOutputFolder to choose folder with prompt "Please select an output folder:"
- --> Result: alias "Macintosh HD:Users:yourUserName:Desktop:"
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var outputFolder = app.chooseFolder({
- withPrompt: "Please select an output folder:"
- })
- outputFolder
- // Result: Path("/Users/yourUserName/Desktop")
### Prompting for Multiple Folders
To let the user choose more than one folder, include thechoose foldercommandâs optionalmultiple selections allowedparameter, as shown inListing 26-9andListing 26-10.
APPLESCRIPT
Open in Script Editor
- set theFoldersToProcess to choose folder with prompt "Please select the folders containing images to process:" with multiple selections allowed
- --> Result: {alias "Macintosh HD:Users:yourUserName:Desktop:", alias "Macintosh HD:Users:yourUserName:Documents:"}
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var foldersToProcess = app.chooseFolder({
- withPrompt: "Please select an output folder:",
- multipleSelectionsAllowed: true
- })
- foldersToProcess
- // Result: [Path("/Users/yourUserName/Desktop"), Path("/Users/yourUserName/Documents")]
Speaking Text
Prompting for a File Name
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Calling Command-Line Tools
## Calling Command-Line Tools
In AppleScript, thedo shell scriptcommand is used to execute command-line tools. This command is implemented by the Standard Additions scripting addition included with OSÂ X.
Note
The Terminal app in/Applications/Utilities/is scriptable and provides another way to execute command-line tools from scripts.
### Executing Commands
The direct parameter of thedo shell scriptcommand is a string containing the shell code you want to execute, as demonstrated inListing 39-1, which simply lists a directory.
APPLESCRIPT
Open in Script Editor
- do shell script "ls /Applications/"
- (*
- --> Result:
- "App Store.app
- Automator.app
- Calculator.app
- Calendar.app
- ..."
- *)
Since the direct parameter ofdo shell scriptis a string, you can concatenate it with other strings at run time.Listing 39-2, for example, concatenates a shell command to a previously defined parameter value.
APPLESCRIPT
Open in Script Editor
- set theHostName to "www.apple.com"
- do shell script "ping -c1 " & theHostName
### Quoting Strings
The shell uses space characters to separate parameters and gives special meaning to certain punctuation marks, such as$,(,), and*. To ensure that strings are treated as expectedâfor example, spaces arenât seen as delimitersâitâs best to wrap strings in quotes. This process is known asquoting. If your string contains quotes, they must also beescaped(preceded by a/character) so they are interpreted as part of the string.Listing 39-3shows an example of an error occurring as a result of a parameter that contains a space.
APPLESCRIPT
Open in Script Editor
- set thePath to "/Library/Application Support/"
- do shell script "ls " & thePath
- --> Result: error "ls: /Library/Application: No such file or directory\rls: Support: No such file or directory" number 1
The easiest way to quote a string is to use thequoted formproperty of the text class, as demonstrated inListing 39-4. This property returns the string in a form thatâs safe from further interpretation by the shell, regardless of its contents.
APPLESCRIPT
Open in Script Editor
- set thePath to quoted form of "/Library/Application Support/"
- --> Result: "'/Library/Application Support/'"
- do shell script "ls " & thePath
- (*
- --> Result:
- "App Store
- Apple
- ...
- "
- *)
### More Information
For more information about thedo shell scriptcommand, seeCommands ReferenceinAppleScript Language GuideandTechnical Note TN2065.
Manipulating Images
Making a Systemwide Service
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Speaking Text
## Speaking Text
Spoken text is another way to provide feedback to users during script execution; instead of reading a message visually, the user can listen to it audibly.Listing 25-1andListing 25-2show how the Standard Additions scripting additionâssaycommand can be used to speak a phrase.
APPLESCRIPT
Open in Script Editor
- say "Processing is complete."
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.say("Processing is complete.")
Thesaycommand has a number of optional parameters, some of which allow you to specify a voice and attributes such as speaking rate, pitch, and modulation. SeeListing 25-3andListing 25-4.
APPLESCRIPT
Open in Script Editor
- say "Just what do you think you're doing Dave?" using "Alex" speaking rate 140 pitch 42 modulation 60
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- app.say("Just what do you think you're doing Dave?", {
- using: "Alex",
- speakingRate: 140,
- pitch: 42,
- modulation: 60
- })
### Saving Text as an Audio File
Thesaycommandâssaving asparameter adds another level of power, enabling text to be converted to audio format and saved as an.aifffile for later listening. This technique could be used, for example, to save email messages in audio format, as demonstrated byListing 25-5andListing 25-6.
APPLESCRIPT
Open in Script Editor
- tell application "Mail"
- tell message 1 of inbox
- set theSubject to subject
- set theBody to content
- end tell
- end tell
- set theOutputFile to (path to desktop as string) & "message.aiff"
- set theAudio to "Message Subject: " & theSubject & return & "Body: " & theBody
- say theAudio saving to theOutputFile
JAVASCRIPT
Open in Script Editor
- var Mail = Application("Mail")
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- message = Mail.inbox.messages[0]
- subject = message.subject()
- body = message.content()
- outputFile = ((app.pathTo("desktop").toString()) + "/message.aiff")
- audio = "Message Subject: " + subject + "\nBody: " + body
- app.say(audio, {savingTo: outputFile})
### Speaking Text While Displaying a Dialog
Typically, a script executes a single command at a time, waiting for a command to complete before moving onto the next.Listing 25-7andListing 25-8demonstrate how to display a dialog message, while simultaneously using theNSTaskclass in the Foundation framework to read the message out loud.
APPLESCRIPT
Open in Script Editor
- use framework "Foundation"
- use scripting additions
- set theStatusText to "Processing is complete."
- set theTask to (current application's NSTask's launchedTaskWithLaunchPath:"/usr/bin/say" arguments:{theStatusText})
- try
- display dialog theStatusText
- theTask's terminate()
- on error
- try
- theTask's terminate()
- end try
- end try
JAVASCRIPT
Open in Script Editor
- var app = Application.currentApplication()
- app.includeStandardAdditions = true
- var statusText = "Processing is complete."
- var task = $.NSTask.launchedTaskWithLaunchPathArguments("/usr/bin/say", [statusText])
- try {
- app.displayDialog(statusText)
- task.terminate
- }
- catch(error){
- task.terminate
- }
Displaying Notifications
Prompting for Files or Folders
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Types of Scripts
## Types of Scripts
There are many different types of scripts on the Mac.
AppletsâA script thatâs been saved as an app. It behaves like other apps. Double-click it to launch and run it. When an applet is launched, any code in itsrunhandler executes. If a script doesnât contain an explicitrunhandler, then the top level of the script is treated as an implicitrunhandler and any code there executes.
DropletsâA script applet that has been configured to accept dropped files and folders. Double-click it to launch and run itâexecute itsrunhandler. Or, drag and drop files and folders onto it to process them. In a droplet, dropped files and folders are passed directly to an AppleScriptopenhandler or JavaScriptopenDocumentsfunction for processing.
ScriptsâA script document file. Double-click it to open it for editing. Some apps and processes can load and run scripts. For example, Mail rules can execute scripts to process messages matching specific criteria. Scripts are sometimes referred to ascompiled scripts.
Script bundlesâA script document thatâs been saved inbundleformat. A bundle is a directory with a standardized, hierarchical structure that holds executable code and the resources used by that code.
Stay-open scriptsâBy default, applets and droplets run and quit after launch. When configured as stay-open, however, they remain open until explicitly ordered to quit. Often, stay-open scripts include anidlehandler, which initiates periodic actions.
For detailed information aboutrun,open, andidlehandlers in AppleScript, seeHandlers in Script ApplicationsinAppleScript Language Guide. For information aboutrun,openDocuments, andidlefunctions in JavaScript, seeAppletsinJavaScript for Automation Release Notes. For information about bundles, seeBundle Programming Guide.
How Mac Scripting Works
About this Guide
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Document Revision History
## Document Revision History
This table describes the changes toMac Automation Scripting Guide.
Date
Notes
2018-06-07
New document that provides an introduction to using AppleScript and JavaScript to streamline workflows and increase productivity in OS X.
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Working with Property List Files
## Working with Property List Files
Many apps store settings in property list files (also called plists). Scripts can also store and retrieve data in plists. The terminology for interacting with plists is found in the Property List Suite of the System Events scripting dictionary (seeFigure 35-1).
### Creating a New Property List File
Listing 35-1demonstrates how to create a new property list file. First, an empty plist file (classproperty list file) is created. Next, individual property list items (classproperty list item) of varying type (Boolean, date, list, number, record, string) are added to the file.
APPLESCRIPT
Open in Script Editor
- tell application "System Events"
- -- Create an empty property list dictionary item
- set theParentDictionary to make new property list item with properties {kind:record}
- -- Create a new property list file using the empty dictionary list item as contents
- set thePropertyListFilePath to "~/Desktop/Example.plist"
- set thePropertyListFile to make new property list file with properties {contents:theParentDictionary, name:thePropertyListFilePath}
- -- Add a Boolean key
- tell property list items of thePropertyListFile
- make new property list item at end with properties {kind:boolean, name:"booleanKey", value:true}
- -- Add a date key
- make new property list item at end with properties {kind:date, name:"dateKey", value:current date}
- -- Add a list key
- make new property list item at end with properties {kind:list, name:"listKey"}
- -- Add a number key
- make new property list item at end with properties {kind:number, name:"numberKey", value:5}
- -- Add a record/dictionary key
- make new property list item at end with properties {kind:record, name:"recordKey"}
- -- Add a string key
- make new property list item at end with properties {kind:string, name:"stringKey", value:"string value"}
- end tell
- end tell
Listing 35-2shows the contents of a property list file created by the script inListing 35-1.
-
-
-
-
- booleanKey
-
- dateKey
- 2016-01-28T19:34:13Z
- listKey
-
- numberKey
- 5
- recordKey
-
- stringKey
- string value
-
-
### Reading a Property List Key Value
Listing 35-3shows how to read a value of a key in a property list file.
Open in Script Editor
- tell application "System Events"
- tell property list file thePropertyListFilePath
- return value of property list item "stringKey"
- end tell
- end tell
- --> Result: "string value"
### Changing a Property List Key Value
Listing 35-4shows how to change the value of a key in a property list file.
Open in Script Editor
- tell application "System Events"
- tell property list file thePropertyListFilePath
- set value of property list item "stringKey" to "new string value"
- end tell
- end tell
### Adding a New Property List Item
Listing 35-3shows how to add a new key and value to a property list file.
Open in Script Editor
- tell application "System Events"
- tell property list items of property list file thePropertyListFilePath
- make new property list item at end with properties {kind:string, name:"newStringKey", value:"new string value"}
- end tell
- end tell
Removing HTML Markup from Text
Working with XML
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# Mac Automation Scripting Guide: Using Script Libraries
## Using Script Libraries
A script library is a collection of handlers, which can be loaded and used by other scripts. For example, a scripter might compile a set of commonly-used text-processing handlers into a text library. This library could then be shared by multiple scripts that need to perform text processing operations.
### Writing Script Libraries
To write a script library, create a Script Editor document that contains one or more handlers, such as the one shown inListing 14-1andListing 14-2, and save it inscriptformat, as shown inFigure 14-1.
APPLESCRIPT
Open in Script Editor
- on changeCaseOfText(theText, theCaseToSwitchTo)
- if theCaseToSwitchTo contains "lower" then
- set theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"
- else if theCaseToSwitchTo contains "upper" then
- set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
- set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- else
- return theText
- end if
- set theAlteredText to ""
- repeat with aCharacter in theText
- set theOffset to offset of aCharacter in theComparisonCharacters
- if theOffset is not 0 then
- set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
- else
- set theAlteredText to (theAlteredText & aCharacter) as string
- end if
- end repeat
- return theAlteredText
- end changeCaseOfText
JAVASCRIPT
Open in Script Editor
- function changeCaseOfText(text, caseToSwitchTo) {
- var alteredText = text
- if (caseToSwitchTo === "lower") {
- alteredText = alteredText.toLowerCase()
- }
- else if (caseToSwitchTo === "upper") {
- alteredText = alteredText.toUpperCase()
- }
- return alteredText
- }
Move the saved script to one of the following folders on your Mac, creating the folder if it doesnât already exist:
- ~/Library/Script Libraries/
~/Library/Script Libraries/
- /Library/Script Libraries/
/Library/Script Libraries/
- /Resources/folder inside a script or app bundle.
/Resources/folder inside a script or app bundle.
For additional information about writing script libraries, seeCreating a LibraryinAppleScript Language GuideandLibrariesinJavaScript for Automation Release Notes.
### Using Script Libraries
Once a script library is installed, your other scripts can target its handlers at any time.
To target a script library in AppleScript, use atellstatement, as shown inListing 14-3.
APPLESCRIPT
Open in Script Editor
- tell script "My Text Processor"
- changeCaseOfText("scripting is awesome!", "upper")
- end tell
- --> Result: "SCRIPTING IS AWESOME!"
To target a script library in JavaScript, use theLibrarycommand to reference the library. Then, you can target handlers in the referenced library, as shown inListing 14-4.
JAVASCRIPT
Open in Script Editor
- textProcessor = Library("My Text Processor")
- textProcessor.changeCaseOfText("scripting is awesome!", "upper")
- // Result: "SCRIPTING IS AWESOME!"
Using Handlers/Functions
Referencing Files and Folders
Copyright © 2018 Apple Inc. All rights reserved.Terms of Use|Privacy Policy|Updated: 2016-06-13
---
# About Handlers
When script developers want to factor and re-use their code, they can turn to handlers. A handler is a collection of statements that can be invoked by name. Handlers are also known as functions, subroutines, or methods.
This chapter describes how to work with handlers, in the following sections:
- Handler Basics
Handler Basics
- Handlers in Script Applications
Handlers in Script Applications
For detailed reference information, seeHandler Reference.
## Handler Basics
Ahandleris a collection of statements that can be invoked by name. Handlers are useful in scripts that perform the same action in more than one place. You can package statements that perform a specific task as a handler, give it a descriptive name, and call it from anywhere in the script. This makes the script shorter and easier to maintain.
A script can contain one or more handlers. However, you can not nest a handler definition within another handler (although a script object defined in a handler can contain other handlers).
The definition for a handler specifies the parameters it uses, if any, and may specify a class or classes for the parameter and a default value.
When you call a handler, you must list its parameters according to how they are specified in its definition. Handlers may have labeled, positional, or interleaved parameters, described in subsequent sections. If a parameter has a specified class, AppleScript will coerce the actual value to that class as if using theasoperator. If a parameter has a default value, that parameter may be omitted.
A handler definition can contain variable declarations and statements. It may use areturnstatement (described in detail inreturn) to return a value and exit the handler.
The sections that follow provide additional information on working with handlers:
- Defining a Simple Handler
Defining a Simple Handler
- Handlers with Labeled Parameters
Handlers with Labeled Parameters
- Handlers with Positional Parameters
Handlers with Positional Parameters
- Handlers with Patterned Positional Parameters
Handlers with Patterned Positional Parameters
- Recursive Handlers
Recursive Handlers
- Errors in Handlers
Errors in Handlers
- Passing by Reference Versus Passing by Value
Passing by Reference Versus Passing by Value
- Calling Handlers in a tell Statement
Calling Handlers in a tell Statement
### Defining a Simple Handler
The following is a definition for a simple handler that takes any parameter value that can be displayed as text (presumably one representing a date) and displays it in a dialog box. The handler name isrock; its parameter isaround the clock, wherearoundis a parameter label andclockis the parameter name (theis an AppleScript filler for readability):
```
on rock around the clock```
```
display dialog (clock as text)```
```
end rock```
This handler allows an English-like calling statement:
```
rock around the current date -- call handler to display current date```
A handler can have no parameters. To indicate that a handler has no parameters, you include a pair of empty parentheses after the handler name in both the handler definition and the handler call. For example, the followinghelloWorldscript has no parameters.
```
on helloWorld()```
```
display dialog "Hello World"```
```
end```
```
```
```
helloWorld() -- Call the handler```
### Handlers with Labeled Parameters
To define a handler with labeled parameters, you list the labels to use when calling the handler and the statements to be executed when it is called. (The syntax is shown inHandler Syntax (Labeled Parameters).)
Handlers with labeled parameters can also have a direct parameter. With the exception of the direct parameter, which must directly follow the handler name, labeled parameters can appear in any order, with the labels from the handler definition identifying the parameter values. This includes parameters listed ingiven,with, andwithoutclauses (of which there can be any number).
ThefindNumbershandler in the following example uses the special labelgivento define a parameter with the labelgiven rounding.
```
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 then -- round the number```
```
-- Use copy so original list isnât modified.```
```
copy (round x) to x```
```
end if```
```
if x > minLimit then```
```
set end of resultList to x```
```
end if```
```
end repeat```
```
return resultList```
```
end findNumbers```
The next statements show how to callfindNumbersby passing a predefinedlistvariable:
```
set myList to {2, 5, 19.75, 99, 1}```
```
findNumbers of myList above 19 given rounding:true```
```
--result: {20, 99}```
```
findNumbers of myList above 19 given rounding:false```
```
--result: {19.75, 99}```
You can also specify the value of theroundingparameter by using awithorwithoutclause to indicatetrueorfalse. (In fact, when you compile the previous examples, AppleScript automatically convertsgiven rounding:truetowith roundingandgiven rounding:falsetowithout rounding.) These examples pass alistobject directly, rather than using alistvariable as in the previous case:
```
findNumbers of {5.1, 20.1, 20.5, 33} above 20 with rounding```
```
--result: {33}```
```
```
```
findNumbers of {5.1, 20.1, 20.5, 33.7} above 20 without rounding```
```
--result: {20.1, 20.5, 33.7}```
Here is another handler that uses parameter labels:
```
to check for yourNumber from startRange thru endRange```
```
if startRange ⤠yourNumber and yourNumber ⤠endRange then```
```
display dialog "Congratulations! Your number is included."```
```
end if```
```
end check```
The following statement calls the handler, causing it to display the"Congratulations!"message
```
check for 8 from 7 thru 10 -- call the handler```
### Handlers with Positional Parameters
The definition for a handler with positional parameters shows the order in which to list parameters when calling the handler and the statements to be executed when the handler is called. The definition must include parentheses, even if it doesnât include any parameters. The syntax is shown inHandler Syntax (Positional Parameters).
In the following example, theminimumValueroutine returns the smaller of two values:
```
on minimumValue(x, y)```
```
if x < y then```
```
return x```
```
else```
```
return y```
```
end if```
```
end minimumValue```
```
```
```
-- To call minimumValue:```
```
minimumValue(5, 105) --result: 5```
The first line of theminimumValuehandler specifies the parameters of the handler. To call a handler with positional parameters you list the parameters in the same order as they are specified in the handler definition.
If a handler call is part of an expression, AppleScript uses the value returned by the handler to evaluate the expression. For example, to evaluate the following expression, AppleScript first callsminimumValue, then evaluates the rest of the expression.
```
minimumValue(5, 105) + 50 --result: 55```
### Handlers with Patterned Positional Parameters
You can create a handler whose positional parameters define a pattern to match when calling the handler. For example, the following handler takes a single parameter whose pattern consists of two items in a list:
```
on displayPoint({x, y})```
```
display dialog ("x = " & x & ", y = " & y)```
```
end displayPoint```
```
```
```
-- Calling the handler:```
```
set testPoint to {3, 8}```
```
displayPoint(testPoint)```
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. The handler displays a dialog box summarizing some of the passed information.
```
on hello(a, b, {length:l, bounds:{x, y, w, h}, name:n})```
```
set q to a + b```
```
```
```
set response to "Hello " & n & ", you are " & l & ¬```
```
" inches tall and occupy position (" & x & ", " & y & ")."```
```
```
```
display dialog response```
```
```
```
end hello```
```
```
```
set thing to {bounds:{1, 2, 4, 5}, name:"George", length:72}```
```
hello (2, 3, thing)```
```
--result: A dialog displaying âHello George, you are 72 inches tall```
```
-- and occupy position (1,2).â```
The properties of a record passed to a handler with patterned parameters donât have to be given in the same order in which they are given in the handlerâs definition, as long as all the properties required to fit the pattern are present.
The following call tominimumValueuses the value from a handler call tomaximumValueas its second parameter. ThemaximumValuehandler (not shown) returns the larger of two passed numeric values.
```
minimumValue(20, maximumValue(1, 313)) --result: 20```
### Handlers with Interleaved Parameters
A handler with interleaved parameters is a special case of one with positional parameters. The definition shows the order in which to list parameters when calling the handler and the statements to be executed when the handler is called, but the name of the handler is broken into pieces and interleaved with the parameters, which can make it easier to read. Handlers with interleaved parameters may be used in any script, but are especially useful with bridged Objective-C methods, since they naturally resemble Objective-C syntax. The syntax is shown inHandler Syntax (Interleaved Parameters).
A handler with interleaved parameters may have only one parameter, as in this example:
```
on areaOfCircleWithRadius:radius```
```
return radius ^ 2 * pi```
```
end areaOfCircleWithRadius:```
Or more than one, as in this example:
```
on areaOfRectangleWithWidth:w height:h```
```
return w * h```
```
end areaOfRectangleWithWidth:height:```
To call a handler with interleaved parameters, list the parameters in the same order as they are specified in the handler definition. Despite the resemblance to labeled parameters, the parameters may not be reordered. Also, the call must be explicitly sent to an object, even if the target object is the default,it. For example:
```
its foo:5 bar:105 --this works```
```
tell it to foo:5 bar:105 --as does this```
```
foo:5 bar:105 --syntax error.```
Note:The actual name of an interleaved-parameter handler is all the name parts strung together with underscores, and is equivalent to a handler defined using that name with positional parameters. For example, these two handler declarations are equivalent:
on tableView:t objectValueForTableColumn:c row:ron tableView_objectValueForTableColumn_row_(t, c, r)Given a compiled script, AppleScript will automatically translate between the two forms depending on whether or not the current system version supports interleaved parameters.
```
on tableView:t objectValueForTableColumn:c row:r```
```
on tableView_objectValueForTableColumn_row_(t, c, r)```
### Parameter Specifications
Note:Parameter specifications are supported in OS X Yosemite v10.10 and later.
The parameter ânameâ in a handler definition may be a simple name, as shown above, or it may additionally specify a required class and, for labeled parameters, a default value. To specify a required class, follow the name withasclassoras {class,â¦}. For example, you could declare a parameter to be specifically an integer like this:
```
on factorial(x as integer)```
The effect is as if the handler began withset x to x as integer; if coercing the actual value to an integer fails, AppleScript throws an appropriate error, which may be caught with atryblock. The class may be a list of classes, as described inOperators Reference.
Labeled parameters may be declared with a default value by following the formal parameter name with:literal. Doing so makes the parameter optional when called. For example, this declares amakehandler with a default value for thewith dataparameter:
```
on make new theClass with data theData : missing value```
This handler can now be called without supplying awith dataparameter; the handler would seetheDataset to the specified defaultmissing value, which it could then test for and handle appropriately.
A parameter may use both a type specification and a default value. For example, this declares amakehandler with awith propertiesparameter that must be a record and has a default value of an empty record:
```
on make new theClass with properties theProperties as record : {}```
### Recursive Handlers
Arecursive handleris a handler that calls itself. For example, this recursive handler generates a factorial. (The factorial of a number is the product of all the positive integers from 1 to that number. For example, 4 factorial is equal to 1 * 2 * 3 * 4, or 24. The factorial of 0 is 1.)
```
on factorial(x)```
```
if x > 0 then```
```
return x * factorial(x - 1)```
```
else```
```
return 1```
```
end if```
```
end factorial```
```
```
```
-- To call factorial:```
```
factorial(10) --result: 3628800```
In the example above, the handlerfactorialis called once, passing the value10. The handler then calls itself recursively with a value ofx - 1, or9. Each time the handler calls itself, it makes another recursive call, until the value ofxis0. Whenxis equal to0, AppleScript skips to theelseclause and finishes executing all the partially executed handlers, including the originalfactorialcall.
When you call a recursive handler, AppleScript keeps track of the variables and pending statements in the original (partially executed) handler until the recursive handler has completed. Because each call uses some memory, the maximum number of pending handlers is limited by the available memory. As a result, a recursive handler may generate an error before the recursive calls complete.
In addition, a recursive handler may not be the most efficient solution to a problem. For example, the factorial handler shown above can be rewritten to use arepeatstatement instead of a recursive call, as shown in the example inrepeat with loopVariable (from startValue to stopValue).
### Errors in Handlers
As with any AppleScript statements that may encounter an error, you can use atrystatement to deal with possible errors in a handler. Atrystatement includes two collections of statements: one to be executed in the general case, and a second to be executed only if an error occurs.
By using one or moretrystatements with a handler, you can combine the advantages of reuse and error handling in one package. For a detailed example that demonstrates this approach, seeWorking with Errors.
### Passing by Reference Versus Passing by Value
Within a handler, each parameter is like a variable, providing access to passed information. AppleScript passes all parameters by reference, which means that a passed variable is shared between the handler and the caller, as if the handler had created a variable using thesetcommand. However, it is important to remember a point raised inUsing the copy and set Commands: only mutable objects can actually be changed.
As a result, a parameterâs class type determines whether information is effectively passed by value or by reference:
- For mutable objects (those whose class isdate,list,record, orscript), information is passedby reference:If a handler changes the value of a parameter of this type, the original object is changed.
For mutable objects (those whose class isdate,list,record, orscript), information is passedby reference:
If a handler changes the value of a parameter of this type, the original object is changed.
- For all other class types, information is effectively passedby value:Although AppleScript passes a reference to the original object, that object cannot be changed. If the handler assigns a new value to a parameter of this type, the original object is unchanged.
For all other class types, information is effectively passedby value:
Although AppleScript passes a reference to the original object, that object cannot be changed. If the handler assigns a new value to a parameter of this type, the original object is unchanged.
If youwantto pass by reference with a class type other thandate,list,record, orscript, you can pass areferenceobject that refers to the object in question. Although the handler will have access only to a copy of thereferenceobject, the specified object will be the same. Changes to the specified object in the handler will change the original object, although changes to thereferenceobject itself will not.
### Calling Handlers in a tell Statement
To call a handler from within atellstatement, you must use the reserved wordsof meormyto indicate that the handler is part of the script and not a command that should be sent to the target of thetellstatement.
For example, the following script calls theminimumValuehandler defined inHandlers with Positional Parametersfrom within atellstatement. If this call did not include the wordsof me, it would cause an error, because AppleScript would send theminimumValuecommand to TextEdit, which does not understand that message.
```
tell front document of application "TextEdit"```
```
minimumValue(12, 400) of me```
```
set paragraph 1 to result as text```
```
end tell```
```
--result: The handler call is successful.```
Instead of using the wordsof me, you could insert the wordmybefore the handler call:
```
my minimumValue(12, 400)```
## Handlers in Script Applications
Ascript applicationis an application whose only function is to run the script associated with it. Script applications contain handlers that allow them to respond to commands. For example, many script applications can respond to theruncommand and theopencommand. A script application receives aruncommand whenever it is launched and anopencommand whenever another icon is dropped on its icon in the Finder. It can also contain other handlers to respond to commands such asquitorprint.
When saving a script in Script Editor, you can create a script application by choosing either Application or Application Bundle from the File Format options. Saving as Application results in a simple format that is compatible with Mac OS 9.Saving as Application Bundle results in an application that uses the modern bundle format, with its specified directory structure, which is supported back to OS X v10.3.
When creating a script application, you can also specify whether astartup screen should appear before the application runs its script. Whatever you write in the Description pane of the script window in Script Editor is displayed in the startup screen.You can also specify in Script Editor whether a script application should stay open after running. The default is for the script to quit immediately after it is run.
You can run a script application from the Finder much like any other application. If it has a startup screen, the user must click the Run button or press the Return key before the script actually runs.
Consider the following simple script
```
tell application "Finder"```
```
close front window```
```
end tell```
What this script does as a script application depends on what you specify when you save it. If you donât specify a startup screen or tell it to stay open, it will automatically execute once, closing the front Finder window, and then quit.
If a script application modifies the value of a property, the changed value persists across launches of the application. For related information, seeScope of Variables and Properties.
For information about some common script application handlers, see the following sections:
- run Handlers
run Handlers
- open Handlers
open Handlers
- idle and quit Handlers for Stay-Open Applications
idle and quit Handlers for Stay-Open Applications
SeeHandler Referencefor syntax information.
### run Handlers
When you run a script or launch a script application, itsrunhandler is invoked. A scriptâsrunhandler is defined in one of two ways:
- As an implicitrunhandler, which consists of all statements declared outside any handler or nestedscriptobject in a script.Declarations for properties andglobalvariables are not considered statements in this contextâthat is, they are not considered to be part of an implicitrunhandler.
As an implicitrunhandler, which consists of all statements declared outside any handler or nestedscriptobject in a script.
Declarations for properties andglobalvariables are not considered statements in this contextâthat is, they are not considered to be part of an implicitrunhandler.
- As an explicitrunhandler, which is enclosed withinon runandendstatements, similar to other handlers.
As an explicitrunhandler, which is enclosed withinon runandendstatements, similar to other handlers.
Having both an implicit and an explicitrunhandler is not allowed, and causes a syntax error during compilation. If a script has no run handler (for example, a script that serves as a library of handlers, as described inParameter Specifications), executing the script does nothing. However, sending it an explicitruncommand causes an error.
The following script demonstrates an implicitrunhandler. The script consists of a statement that invokes thesayHellohandler, and the definition for the handler itself:
```
sayHello()```
```
```
```
on sayHello()```
```
display dialog "Hello"```
```
end sayHello```
The implicitrunhandler for this script consists of the statementsayHello(), which is the only statement outside the handler. If you save this script as a script application and then run the application, the script receives aruncommand, which causes it to execute the one statement in the implicitrunhandler.
You can rewrite the previous script to provide the exact same behavior with an explicitrunhandler:
```
on run```
```
sayHello()```
```
end run```
```
```
```
on sayHello()```
```
display dialog "Hello"```
```
end sayHello```
Whether a script is saved as a script application or as a compiled script, itsrunhandler is invoked when the script is run. You can also invoke arunhandler in a script application from another script. For information about how to do this, seeCalling a Script Application From a Script.
### open Handlers
Mac apps, including script applications, receive anopencommand whenever the user drops file, folder, or disk icons on the applicationâs Finder icon, even if the application is already running.
If the script in a script application includes anopenhandler, the handler is executed when the application receives theopencommand. Theopenhandler takes a single parameter which provides a list of all the items to be opened. Each item in the list is analiasobject.
For example, the followingopenhandler makes a list of the pathnames of all items dropped on the script applicationâs icon and saves them in the frontmost TextEdit document:
```
on open names```
```
set pathNamesString to "" -- Start with empty text string.```
```
repeat with i in names```
```
-- In this loop, you can perform operations on each dropped item.```
```
-- For now, just get the name and append a return character.```
```
set iPath to (i as text)```
```
set pathNamesString to pathNamesString & iPath & return```
```
end repeat```
```
-- Store list in open document, to verify what was dropped.```
```
tell application "TextEdit"```
```
set paragraph 1 of front document to pathNamesString```
```
end tell```
```
return```
```
end open```
Files, folders, or disks are not moved, copied, or affected in any way by merely dropping them on a script application. However, the script applicationâs handler can tell Finder to move, copy, or otherwise manipulate the items. For examples that work with Finder items, seeFolder Actions Reference.
You can also run anopenhandler by sending a script application theopencommand. For details, seeCalling a Script Application From a Script.
### idle and quit Handlers for Stay-Open Applications
By default, a script application that receives arunoropencommand handles that single command and then quits. In contrast, a stay-open script application (one saved as Stay Open in Script Editor) stays open after it is launched.
A stay-open script application can be useful for several reasons:
- Stay-open script applications can receive and handle other commands in addition torunandopen. This allows you to use a script application as a script server that, when it is running, provides a collection of handlers that can be invoked by any other script.
Stay-open script applications can receive and handle other commands in addition torunandopen. This allows you to use a script application as a script server that, when it is running, provides a collection of handlers that can be invoked by any other script.
- Stay-open script applications can perform periodic actions, even in the background, as long as the script application is running.
Stay-open script applications can perform periodic actions, even in the background, as long as the script application is running.
Two particular handlers that stay-open script applications often provide are anidlehandler and aquithandler.
#### idle Handlers
If a stay-open script application includes anidlehandler, AppleScript sends the script application periodicidlecommandsâby default, every 30 secondsâallowing it to perform background tasks when it is not performing other actions.
If anidlehandler returns a positive number, that number becomes the rate (in seconds) at which the handler is called. If the handler returns a non-numeric value, the rate is not changed. You can return 0 to maintain the default delay of 30 seconds.
For example, when saved as a stay-open application, the following script beeps every 5 seconds:
```
on idle```
```
beep```
```
return 5```
```
end idle```
The result returned from a handler is just the result of the last statement, even if it doesnât include the wordreturnexplicitly. (Seereturnfor more information.) For example, this handler gets called once a minute, because the value of the last statement is 60:
```
on idle```
```
set x to 10```
```
beep```
```
set x to x * 6 -- The handler returns the result (60).```
```
end idle```
#### quit Handlers
AppleScript sends a stay-open script application aquitcommand whenever the user chooses the Quit menu command or presses Command-Q while the application is active. If the script includes aquithandler, the statements in the handler are run before the application quits.
Aquithandler can be used to set script properties, tell another application to do something, display a dialog box, or perform almost any other task. If the handler includes acontinue quitstatement, the script applicationâs default quit behavior is invoked and it quits. If thequithandler returns before it encounters acontinue quitstatement, the application doesnât quit.
Note:Thecontinuestatement passes control back to the applicationâs defaultquithandler. For more information, seecontinue.
For example, this handler checks with the user before allowing the application to quit:
```
on quit```
```
display dialog "Really quit?" ¬```
```
buttons {"No", "Quit"} default button "Quit"```
```
if the button returned of the result is "Quit" then```
```
continue quit```
```
end if```
```
-- Without the continue statement, the application doesn't quit.```
```
end quit```
Warning:If AppleScript doesnât encounter acontinue quitstatement while executing anon quithandler, it may seem to be impossible to quit the application. For example, if the handler shown above gets an error before thecontinue quitstatement, the application wonât quit. If necessary, you can use Force Quit (Command-Option-Esc) to halt the application.
## Calling a Script Application From a Script
A script can send commands to a script application just as it can to other applications. To launch a non-stay-open application and run its script, use alaunchcommand followed by aruncommand, like this:
```
launch application "NonStayOpen"```
```
run application "NonStayOpen"```
Thelaunchcommand launches the script application without sending it an implicitruncommand. When theruncommand is sent to the script application, it processes the command, sends back a reply if necessary, and quits.
Similarly, to launch a non-stay-open application and run itsstringTesthandler (which takes atextobject as a parameter), use alaunchcommand followed by astringTestcommand, like this:
```
tell application "NonStayOpen"```
```
launch```
```
stringTest("Some example text.")```
```
end tell```
For information on how to create script applications, seeHandlers in Script Applications.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Folder Actions Reference
Folder Actions is a feature of macOS that lets you associate AppleScript scripts with folders. A Folder Action script is executed when the folder to which it is attached has items added or removed, or when its window is opened, closed, moved, or resized. The script provides a handler that matches the appropriate format for the action, as described in this chapter.
Folder Actions make it easy to create hot folders that respond to external actions to trigger a workflow. For example, you can use a Folder Action script to initiate automated processing of any photo dropped in a targeted folder. A well written Folder Action script leaves the hot folder empty. This avoids repeated application of the action to the same files, and allows Folder Actions to perform more efficiently.
You can Control-click a folder to access some Folder Action features with the contextual menu in the Finder. Or you can use the Folder Actions Setup application, located in/System/Library/CoreServices. This application lets you perform tasks such as the following:
- Enable or disable Folder Actions.
Enable or disable Folder Actions.
- View the folders that currently have associated scripts
View the folders that currently have associated scripts
- View and edit the script associated with a folder.
View and edit the script associated with a folder.
- Add folders to or remove folders from the list of folders.
Add folders to or remove folders from the list of folders.
- Associate one or more scripts with a folder.
Associate one or more scripts with a folder.
- Enable or disable all scripts associated with a folder.
Enable or disable all scripts associated with a folder.
- Enable or disable individual scripts associated with a folder.
Enable or disable individual scripts associated with a folder.
- Remove scripts associated with a folder.
Remove scripts associated with a folder.
Folder Actions Setup looks for scripts located in/Library/Scripts/Folder Action Scriptsand~/Library/Scripts/Folder Action Scripts. You can use the sample scripts located in/Library/Scripts/Folder Action Scriptsor any scripts you have added to these locations, or you can navigate to other scripts.
A Folder Action script provides a handler (seeHandler Reference) that is invoked when the specified action takes place. When working with Folder Action handlers, keep in mind that:
- You do not invoke Folder Actions directly. Instead, when a triggering action takes place on a folder, the associated handler is invoked automatically.
You do not invoke Folder Actions directly. Instead, when a triggering action takes place on a folder, the associated handler is invoked automatically.
- When a Folder Action handler is invoked, none of the parameters is optional.
When a Folder Action handler is invoked, none of the parameters is optional.
- A Folder Action handler does not return a value.
A Folder Action handler does not return a value.
Hereâs how you can use a Folder Action script to perform a specific action whenever an image file is dropped on a specific image folder:
- Create a script with Script Editor or another script application.
Create a script with Script Editor or another script application.
- In that script, write a handler that conforms to the syntax documented here for theadding folder items tofolder action. Your handler can use the aliases that are passed to it to access the image files dropped on the folder.
In that script, write a handler that conforms to the syntax documented here for theadding folder items tofolder action. Your handler can use the aliases that are passed to it to access the image files dropped on the folder.
- Save the script as a compiled script or script bundle.
Save the script as a compiled script or script bundle.
- Put a copy of the script in/Library/Scripts/Folder Action Scriptsor~/Library/Scripts/Folder Action Scripts.
Put a copy of the script in/Library/Scripts/Folder Action Scriptsor~/Library/Scripts/Folder Action Scripts.
- Use the Folder Actions Setup application, located in/Applications/AppleScript, to:Enable folder actions for your image folder.Add a script to that folder, choosing the script you created.
Use the Folder Actions Setup application, located in/Applications/AppleScript, to:
- Enable folder actions for your image folder.
Enable folder actions for your image folder.
- Add a script to that folder, choosing the script you created.
Add a script to that folder, choosing the script you created.
A script handler that is invoked after items are added to its associated folder.
##### Syntax
```
on adding folder items to alias after receiving listOfAlias [ statement ]...end [ adding folder items to ]```
##### Placeholders
Analiasthat identifies the folder that received the items.
List of aliases that identify the items added to the folder.
Any AppleScript statement.
##### Examples
The following Folder Action handler is triggered when items are added to the folder to which it is attached. It makes an archived copy, in ZIP format, of the individual items added to the attached folder. Archived files are placed in a folder namedDonewithin the attached folder.
```
```
```
on adding folder items to this_folder after receiving these_items```
```
tell application "Finder"```
```
if not (exists folder "Done" of this_folder) then```
```
make new folder at this_folder with properties {name:"Done"}```
```
end if```
```
set the destination_folder to folder "Done" of this_folder as alias```
```
set the destination_directory to POSIX path of the destination_folder```
```
end tell```
```
repeat with i from 1 to number of items in these_items```
```
set this_item to item i of these_items```
```
set the item_info to info for this_item```
```
if this_item is not the destination_folder and ¬```
```
the name extension of the item_info is not in {"zip", "sit"} then```
```
set the item_path to the quoted form of the POSIX path of this_item```
```
set the destination_path to the quoted form of ¬```
```
(destination_directory & (name of the item_info) & ".zip")```
```
do shell script ("/usr/bin/ditto -c -k -rsrc --keepParent " ¬```
```
& item_path & " " & destination_path)```
```
end if```
```
end repeat```
```
end adding folder items to```
A script handler that is invoked after a folderâs associated window is closed.
##### Syntax
```
on closing folder window for alias [ statement ]...end [ closing folder window for ]```
##### Placeholders
Analiasthat identifies the folder that was closed.
Any AppleScript statement.
##### Examples
The following Folder Action handler is triggered when the folder to which it is attached is closed. It closes any open windows of folders within the targeted folder.
```
-- This script is designed for use with OS X v10.2 and later.```
```
on closing folder window for this_folder```
```
tell application "Finder"```
```
repeat with EachFolder in (get every folder of folder this_folder)```
```
try```
```
close window of EachFolder```
```
end try```
```
end repeat```
```
end tell```
```
end closing folder window for```
A script handler that is invoked after a folderâs associated window is moved or resized. Not currently available.
##### Syntax
```
on moving folder window for alias from bounding rectangle [ statement ]...end [ moving folder window for ]```
##### Placeholders
Analiasthat identifies the folder that was moved or resized.
You can use this alias to obtain the folder windowâs new coordinates from the Finder.
The previous coordinates of the window of the folder that was moved or resized. The coordinates are provided as a list of four numbers, {left, top, right, bottom}; for example, {10, 50, 500, 300} for a window whose origin is near the top left of the screen (but below the menu bar, if present).
Any AppleScript statement.
##### Examples
```
on moving folder window for this_folder from original_coordinates```
```
tell application "Finder"```
```
set this_name to the name of this_folder```
```
set the bounds of the container window of this_folder ¬```
```
to the original_coordinates```
```
end tell```
```
display dialog "Window \"" & this_name & "\" has been returned to its original size and position." buttons {"OK"} default button 1```
```
end moving folder window for```
##### Special Considerations
Warning:In OS X v10.5, and possibly in previous OS versions, Folder Actions does not activate attachedmoving folder window forscripts when the folder is moved.
A script handler that is invoked when its associated folder is opened in a window.
##### Syntax
```
on opening folderalias [ statement ]...end [ opening folder ]```
##### Placeholders
Analiasthat identifies the folder that was opened.
Any AppleScript statement.
##### Examples
The following Folder Action handler is triggered when the folder it is attached to is opened. It displays any text from the Spotlight Comments field of the targeted folder. (Prior to OS X v10.4, this script displays text from the Comments field of the specified folder.)
```
-- This script is designed for use with OS X v10.2 and later.```
```
property dialog_timeout : 30 -- set the amount of time before dialogs auto-answer.```
```
```
```
on opening folder this_folder```
```
tell application "Finder"```
```
activate```
```
set the alert_message to the comment of this_folder```
```
if the alert_message is not "" then```
```
display dialog alert_message buttons {"Open Comments", "Clear Comments", "OK"} default button 3 giving up after dialog_timeout```
```
set the user_choice to the button returned of the result```
```
if the user_choice is "Clear Comments" then```
```
set comment of this_folder to ""```
```
else if the user_choice is "Open Comments" then```
```
open information window of this_folder```
```
end if```
```
end if```
```
end tell```
```
end opening folder```
##### Special Considerations
Spotlight was introduced in OS X v10.4. In prior versions of the Mac OS, the example script shown above works with the Comments field of the specified folder, rather than the Spotlight Comments field.
A script handler that is invoked after items have been removed from its associated folder.
##### Syntax
```
on removing folder items from alias after losinglistOfAliasOrText [ statement ]...end [ removing folder items from ]```
##### Placeholders
Analiasthat identifies the folder from which the items were removed.
List of aliases that identify the items lost (removed) from the folder. For permanently deleted items, only the names are provided (astextstrings).
Any AppleScript statement.
##### Examples
The following Folder Action handler is triggered when items are removed from the folder to which it is attached. It displays an alert containing the number of items removed.
```
on removing folder items from this_folder after losing these_items```
```
tell application "Finder"```
```
set this_name to the name of this_folder```
```
end tell```
```
set the item_count to the count of these_items```
```
display dialog (item_count as text) & " items have been removed " & "from folder \"" & this_name & "\"." buttons {"OK"} default button 1```
```
end removing folder items from```
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Class Reference
Aclassis a category for objects that share characteristics. AppleScript defines classes for common objects used in AppleScript scripts, such as aliases, Boolean values, integers, text, and so on.
Each object in a script is an instance of a specific class and has the same properties (including theclassproperty), can contain the same kinds of elements, and supports the same kinds of operations and coercions as other objects of that type. Objects that are instances of AppleScript types can be used anywhere in a scriptâthey donât need to be within atellblock that specifies an application.
Scriptable applications also define their own classes, such as windows and documents, which commonly contain properties and elements based on many of the basic AppleScript classes described in this chapter. Scripts obtain these objects in the context of the applications that define them. For more information on the class types applications typically support, see âStandard Classesâ in Technical Note TN2106,Scripting Interface Guidelines.
A persistent reference to an existing file, folder, or volume in the file system.
For related information, seefile,POSIX file, andAliases and Files.
##### Properties of alias objects
##### Coercions Supported
AppleScript supports coercion of analiasobject to atextobject or single-itemlist.
##### Examples
```
set zApp to choose application as alias -- (then choose Finder.app)```
```
--result: alias "Leopard:System:Library:CoreServices:Finder.app:"```
```
class of zApp --result: alias```
```
zApp as text --result: "Leopard:System:Library:CoreServices:Finder.app:"```
```
zApp as list --result: {alias "Leopard:System:Library:CoreServices:Finder.app:"}```
You can use thePOSIX pathproperty to obtain a POSIX-style path to the item referred to by an alias:
```
POSIX path of zApp --result: "/System/Library/CoreServices/Finder.app/"```
##### Discussion
You can only create an alias to a file or folder that already exists.
##### Special Considerations
AppleScript 2.0 attempts to resolve aliases only when you run a script. However, in earlier versions, AppleScript attempts to resolve aliases at compile time.
An application on a local machine or an available server.
An application object in a script has all of the properties described here, which are handled by AppleScript. It may have additional properties, depending on the specific application it refers to.
##### Properties of application objects
##### Coercions Supported
AppleScript supports coercion of anapplicationobject to a single-itemlist.
##### Examples
You can determine whether an application on the current computer is running without launching it (this wonât work if your target is on a remote computer):
```
tell application "iTunes" -- doesn't automatically launch app```
```
if it is running then```
```
pause```
```
end if```
```
end tell```
You can also use this format:
```
if application "iTunes" is running```
```
tell application "iTunes" to pause```
```
end if```
The following statements specify the TextEdit application by, respectively, its signature, its bundle id, and by a POSIX path to a specific version of TextEdit:
```
application id "ttxt"```
```
application id "com.apple.TextEdit"```
```
application "/Applications/TextEdit.app"```
You can target a remote application with atellstatement. For details, seeRemote Applications.
##### Special Considerations
Starting in OS X v10.5, there are several changes in application behavior:
- Applications launch hidden.AppleScript has always launched applications if it needed to in order to send them a command. However, they would always launch visibly, which could be visually disruptive. AppleScript now launches applications hidden by default. They will not be visible unless the script explicitly says otherwise usingactivate.
Applications launch hidden.
AppleScript has always launched applications if it needed to in order to send them a command. However, they would always launch visibly, which could be visually disruptive. AppleScript now launches applications hidden by default. They will not be visible unless the script explicitly says otherwise usingactivate.
- Applications are located lazily.When running a script, AppleScript will not attempt to locate an application until it needs to in order to send it a command. This means that a compiled script or script application may contain references to applications that do not exist on the userâs system, but AppleScript will not ask where the missing applications are until it encounters a relevanttellblock. Previous versions of AppleScript would attempt to locate every referenced application before running the script.When opening a script for editing, AppleScript will attempt to locate all the referenced applications in the entire script, which may mean asking where one is. Pressing the Cancel button only cancels the search for that application; the script will continue opening normally, though custom terminology for that application will display as raw codes. In older versions, pressing Cancel would cancel opening the script.
Applications are located lazily.
When running a script, AppleScript will not attempt to locate an application until it needs to in order to send it a command. This means that a compiled script or script application may contain references to applications that do not exist on the userâs system, but AppleScript will not ask where the missing applications are until it encounters a relevanttellblock. Previous versions of AppleScript would attempt to locate every referenced application before running the script.
When opening a script for editing, AppleScript will attempt to locate all the referenced applications in the entire script, which may mean asking where one is. Pressing the Cancel button only cancels the search for that application; the script will continue opening normally, though custom terminology for that application will display as raw codes. In older versions, pressing Cancel would cancel opening the script.
- Applications are located and re-located dynamically.Object specifiers that refer to applications, including those intellblocks, are evaluated every time a script runs. This alleviates problems with scripts getting âstuckâ to a particular copy of an application.
Applications are located and re-located dynamically.
Object specifiers that refer to applications, including those intellblocks, are evaluated every time a script runs. This alleviates problems with scripts getting âstuckâ to a particular copy of an application.
In prior versions of AppleScript, use of the new built-in application properties will fall back to sending an event to the application, but the application may not handle these properties in the same way, or handle them at all. (Most applications will handlename,version, andfrontmost;idandrunningare uncommon.) The other new features described above require AppleScript 2.0.
A logical truth value.
Abooleanobject evaluates to one of the AppleScript constantstrueorfalse. ABoolean expressioncontains one or morebooleanobjects and evaluates totrueorfalse.
##### Properties of boolean objects
##### Operators
The operators that takebooleanobjects as operands areand,or,not,&,=, andâ, as well as their text equivalents:is equal to,is not equal to,equals, and so on.
The=operator returnstrueif both operands evaluate to the same value (eithertrueorfalse); theâoperator returnstrueif the operands evaluate to different values.
The binary operatorsandandortakebooleanobjects as operands and return Boolean values. Anandoperation, such as(2 > 1) and (4 > 3), has the valuetrueif both its operands aretrue, andfalseotherwise. Anoroperation, such as(theString = "Yes") or (today = "Tuesday"), has the valuetrueif either of its operands istrue.
The unarynotoperator changes atruevalue tofalseor afalsevalue totrue.
The concatenation operator (&) creates a list containing the two boolean values on either side of it; for example:
```
true & false --result: {true, false}```
For additional information on these operators, seeOperators Reference.
##### Coercions Supported
AppleScript supports coercion of abooleanobject to a single-itemlist, atextobject, or aninteger.
##### Examples
The following are simple Boolean expressions:
```
true```
```
false```
```
paragraphCount > 2```
AppleScript supplies the Boolean constantstrueandfalseto serve as the result of evaluating a Boolean operation. But scripts rarely need to use these literals explicitly because a Boolean expression itself evaluates to a Boolean value. For example, consider the following two script snippets:
```
if companyName is equal to "Acme Baking" then```
```
return true```
```
else```
```
return false```
```
end if```
```
```
```
return companyName is equal to "Acme Baking"```
The second, simpler version, just returns the value of the Boolean comparisoncompanyName is equal to "Acme Baking", so it doesnât need to use a Boolean constant.
##### Discussion
When you pass a Boolean value as a parameter to a command, the form may change when you compile the command. For example, the following line
```
choose folder showing package contents true```
is converted to this when compiled by AppleScript:
```
choose folder with showing package contents```
It is standard for AppleScript to compile parameter expressions from the Boolean form (such asshowing package contents trueorinvisibles false) into thewithform (with showing package contentsorwithout invisibles, respectively).
Specifies the class of an object or value.
All classes have aclassproperty that specifies the class type. The value of theclassproperty is an identifier.
##### Properties of class objects
##### Operators
The operators that take class identifier values as operands are&,=,â, andas.
The coercion operatorastakes an object of one class type and coerces it to an object of a type specified by a class identifier. For example, the following statement coerces atextobject into a correspondingreal:
```
"1.5" as real --result: 1.5```
##### Coercions Supported
AppleScript supports coercion of a class identifier to a single-itemlistor atextobject.
##### Examples
Asking for the class of a type such asintegerresults in a value ofclass:
```
class of text --result: class```
```
class of integer --result: class```
Here is the class of a boolean literal:
```
class of true --result: boolean```
And here are some additional examples:
```
class of "Some text" --result: text```
```
class of {1, 2, "hello"} --result: list```
A word with a predefined value.
Constants are generally used for enumerated types. You cannot define constants in scripts; constants can be defined only by applications and by AppleScript. SeeGlobal Constants in AppleScriptfor more information.
##### Properties of constant objects
##### Operators
The operators that takeconstantobjects as operands are&,=,â, andas.
##### Coercions Supported
AppleScript supports coercion of aconstantobject to a single-itemlistor atextobject.
##### Examples
One place you use constants defined by AppleScript is in text comparisons performed withconsideringorignoringstatements (described inconsidering / ignoring (text comparison)). For example, in the following script statements,punctuation,hyphens, andwhite spaceare constants:
```
considering punctuation but ignoring hyphens and white space```
```
"bet-the farm," = "BetTheFarm," --result: true```
```
end considering```
```
class of hyphens --result: constant```
The final statement shows that the class ofhyphensisconstant.
##### Discussion
Constants are not text strings, and they must not be surrounded by quotation marks.
Literal constants are defined inLiterals and Constants.
In addition to the constants defined by AppleScript, applications often define enumerated types to be used for command parameters or property values. For example, the iTunessearchcommand defines these constants for specifying the search area:
```
albums```
```
all```
```
artists```
```
composers```
```
displayed```
```
songs```
Specifies the day of the week, the date (month, day of the month, and year), and the time (hours, minutes, and seconds).
To get the current date, use the commandcurrent date:
```
set theDate to current date```
```
--result: "Friday, November 9, 2007 11:35:50 AM"```
You can get and set the different parts of adateobject through the date and time properties described below.
When you compile a script, AppleScript displays date and time values according to the format specified in System Preferences.
##### Properties of date objects
##### Operators
The operators that takedateobject as operands are&,+,â,=,â,>,â¥,<,â¤,comes before,comes after, andas. In expressions containing>,â¥,<,â¤,comes before, orcomes after, a later time is greater than an earlier time.
AppleScript supports the following operations ondateobjects with the+andâoperators:
```
date + timeDifference```
```
--result: date```
```
date - date```
```
--result: timeDifference```
```
date - timeDifference```
```
--result: date```
wheretimeDifferenceis anintegervalue specifying a time difference in seconds. To simplify the notation of time differences, you can also use one or more of these of these constants:
```
minutes```
```
60```
```
hours```
```
60 * minutes```
```
days```
```
24 * hours```
```
weeks```
```
7 * days```
Hereâs an example:
```
date "Friday, November 9, 2007" + 4 * days + 3 * hours + 2 * minutes```
```
--result: date "Tuesday, November 13, 2007 3:02:00 AM"```
To express a time difference in more convenient form, divide the number of seconds by the appropriate constant:
```
31449600 / weeks --result: 52.0```
To get an integral number of hours, days, and so on, use thedivoperator:
```
151200 div days --result: 1```
To get the difference, in seconds, between the current time and Greenwich mean time, use thetime to GMTcommand.
##### Coercions Supported
AppleScript supports coercion of adateobject to a single-itemlistor atextobject.
##### Examples
The following expressions show some options for specifying a date, along with the results of compiling the statements. If you construct a date using only partial information, AppleScript fills in the missing pieces with default values. The actual format is based on the settings in System Preferences.
```
date "8/9/2007, 17:06"```
```
--result: date "Thursday, August 9, 2007 5:06:00 PM"```
```
date "7/16/70"```
```
--result: date "Wednesday, July 16, 2070 12:00:00 AM"```
```
date "12:06" -- specifies a time on the current date```
```
--result: date "Friday, November 9, 2007 12:06:00 PM"```
```
date "Sunday, December 12, 1954 12:06 pm"```
```
--result: date "Sunday, December 12, 1954 12:06:00 PM"```
The following statements access various date properties (results depend on the date the statements are executed):
```
set theDate to current date --using current date command```
```
--result: date "Friday, November 9, 2007 11:58:38 AM"```
```
weekday of theDate --result: Friday```
```
day of theDate --result: 9```
```
month of theDate --result: November```
```
year of theDate --result: 2007```
```
time of theDate --result: 43118 (seconds since 12:00:00 AM)```
```
time string of theDate --result: "11:58:38 AM"```
```
date string of theDate --result: "Friday, November 9, 2007"```
If you want to specify a time relative to a date, you can do so by usingof,relative to, orin, as shown in the following examples.
```
date "2:30 am" of date "Jan 1, 2008"```
```
--result: date "Tuesday, January 1, 2008 2:30:00 AM"```
```
date "2:30 am" of date "Sun Jan 27, 2008"```
```
--result: date "Sunday, January 27, 2008 2:30:00 AM"```
```
date "Nov 19, 2007" relative to date "3PM"```
```
--result: date "Monday, November 19, 2007 3:00:00 PM"```
```
date "1:30 pm" in date "April 1, 2008"```
```
--result: date "Tuesday, April 1, 2008 1:30:00 PM"```
##### Special Considerations
You can create adateobject using a string that follows the date format specified in the Formats pane in International preferences. For example, in US English:
```
set myDate to date "3/4/2008"```
When you compile this statement, it is converted to the following:
```
set myDate to date "Tuesday, March 4, 2008 12:00:00 AM"```
A reference to a file, folder, or volume in the file system. Afileobject has exactly the same attributes as analiasobject, with the addition that it can refer to an item that does not exist.
For related information, seealiasandPOSIX file. For a description of the format for a file path, seeAliases and Files.
##### Coercions Supported
AppleScript supports coercion of afileobject to atextobject or single-itemlist.
##### Examples
```
set fp to open for access file "Leopard:Users:myUser:NewFile"```
```
close access fp```
##### Discussion
You can create afileobject that refers to a file or folder that does not exist. For example, you can use thechoose file namecommand to obtain afileobject for a file that need not currently exist.
A number without a fractional part.
##### Properties of integer objects
##### Operators
The operators that can haveintegervalues as operands are+,-,*,÷(or/),div,mod,^,=,â,>,â¥,<, andâ¤.
Thedivoperator always returns anintegervalue as its result. The+,â,*,mod, and^operators return values of typeintegerorreal.
##### Coercions Supported
AppleScript supports coercion of anintegervalue to a single-itemlist, arealnumber, or atextobject.
Coercion of anintegerto anumberdoes nothing:
```
set myCount to 7 as number```
```
class of myCount --result: integer```
##### Examples
```
1```
```
set myResult to 3 - 2```
```
-1```
```
1000```
##### Discussion
The biggest value (positive or negative) that can be expressed as an integer in AppleScript is ±536870911, which is equal to ±(2^29 â 1). Larger integers are converted to real numbers, expressed in exponential notation, when scripts are compiled.
Note:The smallest possibleintegervalue is actually -536870912 (-2^29), but it can only be generated as a result of an expression. If you enter it directly into a script, it will be converted to a real when you compile.
An ordered collection of values. The values contained in a list are known as items. Each item can belong to any class.
A list appears in a script as a series of expressions contained within braces and separated by commas. An empty list is a list containing no items. It is represented by a pair of empty braces:{}.
##### Properties of list objects
##### Elements of list objects
A value contained in the list. Each value contained in a list is an item and an item may itself be another list. You can refer to values by their item numbers. For example,item 2 of {"soup", 2, "nuts"}is the integer2.
You can also refer to indexed list items by class. For example,integer 1 of {"oatmeal", 42, "new"}returns42.
##### Operators
The operators that can have list values as operands are&,=,â,starts with,ends with,contains, andis contained by.
For detailed explanations and examples of how AppleScript operators treat lists, seeOperators Reference.
##### Commands Handled
You can count the items in a list or the elements of a specific class in a list with thecountcommand. You can also use thelengthproperty of a list:
```
count {"a", "b", "c", 1, 2, 3} --result: 6```
```
length of {"a", "b", "c", 1, 2, 3} --result: 6```
##### Coercions Supported
AppleScript supports coercion of a single-item list to any class to which the item can be coerced if it is not part of a list.
AppleScript also supports coercion of an entire list to atextobject if each of the items in the list can be coerced to atextobject, as in the following example:
```
{5, "George", 11.43, "Bill"} as text --result: "5George11.43Bill"```
The resultingtextobject concatenates all the items, separated by the current value of the AppleScript propertytext item delimiters. This property defaults to an empty string, so the items are simply concatenated. For more information, seetext item delimiters.
Individual items in a list can be of any class, and AppleScript supports coercion of any value to a list that contains a single item.
##### Examples
The following statement defines a list that contains atextobject, an integer, and a Boolean value:
```
{ "it's", 2, true }```
Each list item can be any valid expression. The following list has the same value as the previous list:
```
{ "it" & "'s", 1 + 1, 4 > 3 }```
The following statements work with lists; note that the concatenation operator (&) joins two lists into a single list:
```
class of {"this", "is", "a", "list"} --result: list```
```
item 3 of {"this", "is", "a", "list"} --result: "a"```
```
items 2 thru 3 of {"soup", 2, "nuts"} --result: {2, "nuts"}```
```
{"This"} & {"is", "a", "list"} --result: {"This", "is", "a", "list"}```
For large lists, it is more efficient to use thea reference to operatorwhen inserting a large number of items into a list, rather than to access the list directly. For example, using direct access, the following script takes about 10 seconds to create a list of 10,000 integers (results will vary depending on the computer and other factors):
```
set bigList to {}```
```
set numItems to 10000```
```
set t to (time of (current date)) --Start timing operations```
```
repeat with n from 1 to numItems```
```
copy n to the end of bigList```
```
-- DON'T DO THE FOLLOWING--it's even slower!```
```
-- set bigList to bigList & n```
```
end```
```
set total to (time of (current date)) - t --End timing```
But the following script, which uses thea reference to operator, creates a list of 100,000 integers (ten times the size) in just a couple of seconds (again, results may vary):
```
set bigList to {}```
```
set bigListRef to a reference to bigList```
```
set numItems to 100000```
```
set t to (time of (current date)) --Start timing operations```
```
repeat with n from 1 to numItems```
```
copy n to the end of bigListRef```
```
end```
```
set total to (time of (current date)) - t --End timing```
Similarly, accessing the items in the previously created list is much faster usinga reference toâthe following takes just a few seconds:
```
set t to (time of (current date)) --Start timing```
```
repeat with n from 1 to numItems -- where numItems = 100,000```
```
item n of bigListRef```
```
end repeat```
```
set total to (time of (current date)) - t --End timing```
However, accessing the list directly, even for only 4,000 items, can take over a minute:
```
set numItems to 4000```
```
set t to (time of (current date)) --Start timing```
```
repeat with n from 1 to numItems```
```
item n of bigList```
```
end repeat```
```
set total to (time of (current date)) - t --End timing```
An abstract class that can represent anintegeror areal.
There is never an object whose class isnumber; the actual class of a "number" object is always one of the more specific types,integerorreal.
##### Properties of number objects
##### Operators
Because values identified as values of classnumberare really values of either classintegeror classreal, the operators available are the operators described in the definitions of theintegerorrealclasses.
##### Coercions Supported
Coercing an object tonumberresults in anintegerobject if the result of the coercion is aninteger, or arealobject if the result is a non-integer number.
##### Examples
Any valid literal expression for anintegeror arealvalue is also a valid literal expression for anumbervalue:
```
1```
```
2```
```
-1```
```
1000```
```
10.2579432```
```
1.0```
```
1.```
A pseudo-class equivalent to thefileclass.
There is never an object whose class isPOSIX file; the result of evaluating a POSIX file specifier is afileobject. The difference betweenfileandPOSIX fileobjects is in how they interpret name specifiers: aPOSIX fileobject interprets"name"as a POSIX path, while afileobject interprets it as an HFS path.
For related information, seealiasandfile. For a description of the format for a POSIX path, seeAliases and Files.
##### Properties of POSIX file objects
Seefile.
##### Coercions Supported
Seefile.
##### Examples
The following example asks the user to specify a file name, starting in the temporary directory/tmp, which is difficult to specify using a file specifier:
```
set fileName to choose file name default location (POSIX file "/tmp")```
```
-result: dialog starts in /tmp folder```
Numbers that can include a fractional part, such as 3.14159 and 1.0.
##### Properties of real objects
##### Operators
The operators that can haverealvalues as operands are+,-,*,÷(or/),div,mod,^,=,â,>,â¥,<, andâ¤.
The÷and/operators always returnrealvalues as their results. The+,-,*,mod, and^operators returnrealvalues if either of their operands is arealvalue.
##### Coercions Supported
AppleScript supports coercion of arealvalue to anintegervalue, rounding any fractional part.
AppleScript also supports coercion of arealvalue to a single-itemlistor atextobject. Coercion to text uses the decimal separator specified in Numbers in the Formats pane in International preferences.
##### Examples
```
10.2579432```
```
1.0```
```
1.```
As shown in the third example, a decimal point indicates a real number, even if there is no fractional part.
Real numbers can also be written using exponential notation. A lettereis preceded by a real number (without intervening spaces) and followed by an integer exponent (also without intervening spaces). The exponent can be either positive or negative. To obtain the value, therealnumber is multiplied by 10 to the power indicated by the exponent, as in these examples:
```
1.0e5 --equivalent to 1.0 * 10^5, or 100000```
```
1.0e+5 --same as 1.0e5```
```
1.0e-5 --equivalent to 1.0 * 10^-5, or .00001```
##### Discussion
Real numbers that are greater than or equal to 10,000.0 or less than or equal to 0.0001 are converted to exponential notation when scripts are compiled. The largest value that can be evaluated (positive or negative) is 1.797693e+308.
An unordered collection of labeled properties. The only AppleScript classes that support user-defined properties arerecordandscript.
A record appears in a script as a series of property definitions contained within braces and separated by commas. Each property definition consists of a label, a colon, and the value of the property. For example, this is a record with two properties:{product:"pen", price:2.34}.
Each property in a record has a unique label which distinguishes it from other properties in the collection. The values assigned to properties can belong to any class. You can change the class of a property simply by assigning a value belonging to another class.
##### Properties of record objects
##### Operators
The operators that can have records as operands are&,=,â,contains, andis contained by.
For detailed explanations and examples of how AppleScript operators treat records, seeOperators Reference.
##### Commands Handled
You can count the properties in a record with thecountcommand:
```
count {name:"Robin", mileage:400} --result: 2```
##### Coercions Supported
AppleScript supports coercion of records to lists; however, all labels are lost in the coercion and the resulting list cannot be coerced back to a record.
##### Examples
The following example shows how to change the value of a property in a record:
```
set myRecord to {product:"pen", price:2.34}```
```
product of myRecord -- result: "pen"```
```
```
```
set product of myRecord to "pencil"```
```
product of myRecord -- result: "pencil"```
AppleScript evaluates expressions in a record before using the record in other expressions. For example, the following two records are equivalent:
```
{ name:"Steve", height:76 - 1.5, weight:150 + 20 }```
```
{ name:"Steve", height:74.5, weight:170 }```
You cannot refer to properties in records by numeric index. For example, the following object specifier, which uses the index reference form on a record, is not valid.
```
item 2 of { name:"Rollie", IQ:186, city:"Unknown" } --result: error```
You can access thelengthproperty of a record to count the properties it contains:
```
length of {name:"Chris", mileage:1957, city:"Kalamazoo"} --result: 3```
You can get the same value with thecountcommand:
```
count {name:"Chris", mileage:1957, city:"Kalamazoo"} --result: 3```
##### Discussion
After you define a record, you cannot add additional properties to it. You can, however, concatenate records. For more information, see& (concatenation).
An object that encapsulates an object specifier.
The result of thea reference tooperator is areferenceobject, and object specifiers returned from application commands are implicitly turned intoreferenceobjects.
Areferenceobject âwrapsâ an object specifier. If you target areferenceobject with thegetcommand, the command returns thereferenceobject itself. If you ask areferenceobject for itscontentsproperty, it returns the enclosed object specifier. All other requests to areferenceobject are forwarded to its enclosed object specifier. For example, if you ask for theclassof areferenceobject, you get theclassof the object specified by its object specifier.
For related information, seeObject Specifiers.
##### Properties of reference objects
Other than thecontentsproperty, all other property requests are forwarded to the enclosed object specifier, so the reference object appears to have all the properties of the referenced object.
##### Operators
All operators are forwarded to the enclosed object specifier, so the reference object appears to support all the operators of referenced object.
Thea reference tooperator returns a reference object as its result.
##### Coercions Supported
All coercions are forwarded to the enclosed object specifier, so the reference object appears to support all the coercions of referenced object.
##### Examples
Reference objects are most often used to specify application objects. The following example creates a reference to a window within the TextEdit application:
```
set myWindow to a ref to window "top.rtf" of application "TextEdit"```
```
--result: window "top.rtf" of application "TextEdit"```
In subsequent script statements, you can use the variablemyWindowin place of the longer termwindow "top.rtf" of application "TextEdit".
Because all property requests other thancontents ofare forwarded to its enclosed specifier, thereferenceobject appears to have all the properties of the referenced object. For example, bothclass ofstatements in the following example returnwindow:
```
set myRef to a reference to window 1```
```
class of contents of myRef -- explicit dereference using "contents of"```
```
class of myRef -- implicit dereference```
For additional examples, see thea reference tooperator.
A type definition for a three-item list ofintegervalues, from 0 to 65535, that specify the red, green, and blue components of a color.
Otherwise, behaves exactly like alistobject.
##### Examples
```
set whiteColor to {65535, 65535, 65535} -- white```
```
set yellowColor to {65535, 65535, 0} -- yellow```
```
yellowColor as string --result: "65535655350"```
```
set redColor to {65535, 0, 0} -- red```
```
set userColor to choose color default color redColor```
A collection of AppleScript declarations and statements that can be executed as a group.
The syntax for ascriptobject is described inDefining Script Objects.
##### Properties of script objects
##### Commands Handled
You can copy ascriptobject with thecopycommand or create a reference to it with thesetcommand.
##### Coercions Supported
AppleScript supports coercion of ascriptobject to a single-itemlist.
##### Examples
The following example shows a simplescriptobject that displays a dialog. It is followed by a statement that shows how to run the script:
```
script helloScript```
```
display dialog "Hello."```
```
end script```
```
```
```
run helloScript -- invoke the script```
##### Discussion
Ascriptobject can contain otherscriptobjects, called child scripts, and can have a parent object. For additional information, including more detailed examples, seeScript Objects.
Thename,id, andversionproperties are automatically defined in OS X Mavericks v10.9 (AppleScript 2.3) and later, and are used to identify scripts used as libraries, as described inScript Objects.
An ordered series of Unicode characters.
Starting in AppleScript 2.0, AppleScript is entirely Unicode-based. There is no longer a distinction between Unicode and non-Unicode text. Comments and text constants in scripts may contain any Unicode characters, and all text processing is done in Unicode, so all characters are preserved correctly regardless of the userâs language preferences.
For example, the following script works correctly in AppleScript 2.0, where it would not have in previous versions:
```
set jp to "æ¥æ¬èª"```
```
set ru to "Ð ÑÑÑкий"```
```
jp & " and " & ru -- returns "æ¥æ¬èª and Ð ÑÑÑкий"```
For information on compatibility with previous AppleScript versions, including the use ofstringandUnicode textas synonyms fortext, see the Special Considerations section.
##### Properties of text objects
##### Elements of text objects
Atextobject can contain these elements (which may behave differently than similar elements used in applications):
One or more Unicode characters that make up the text.
Starting in AppleScript 2.0, elements oftextobject count a combining character cluster (also known as a Unicode grapheme cluster) as a single character. (This relates to a feature of Unicode that is unlikely to have an impact on most scripters: some âcharactersâ may be represented as either a single entity or as a base character plus a series of combining marks.
For example, âéâ may be encoded as either U+00E9 (LATIN SMALL LETTER E WITH ACUTE) or as U+0065 (LATIN SMALL LETTER E), U+0301 (COMBINING ACUTE ACCENT). Nonetheless, AppleScript 2.0 will count both as one character, where older versions counted the base character and combining mark separately.
A series of characters beginning immediately after either the first character after the end of the preceding paragraph or the beginning of the text and ending with either a carriage return character (\r), a linefeed character (\n), a return/linefeed pair (\r\n), or the end of the text. The Unicode "paragraph separator" character (U+2029) is not supported.
Becauseparagraphelements areseparatedby a carriage return, linefeed, or carriage return/linefeed pair, text ending with a paragraph break specifies a following (empty) paragraph. For example,"this\nthat\n"has three paragraphs, not two: "this", "that", and "" (the empty paragraph after the trailing linefeed).
Similarly, two paragraph breaks in a row specify an empty paragraph between them:
paragraphs of "this\n\nthat" --result: {"this", "", "that"}
All of the text contained in thetextobject, including spaces, tabs, and all other characters.
You can usetextto access contiguous characters (but see also the Discussion section below):
text 1 thru 5 of "Bring me the mouse." --result: "Bring"
A continuous series of characters, with word elements parsed according to the word-break rules set in the International preference pane.
Because the rules for parsing words are thus under user control, your scripts should not count on a deterministic text parsing of words.
##### Operators
The operators that can havetextobjects as operands are&,=,â,>,â¥,<,â¤,starts with,ends with,contains,is contained by, andas.
In text comparisons, you can specify whether white space should be considered or ignored. For more information, seeconsidering and ignoring Statements.
For detailed explanations and examples of how AppleScript operators treattextobjects, seeOperators Reference.
##### Special String Characters
The backslash (\) and double-quote (") characters have special meaning in text. AppleScript encloses text in double-quote characters and uses the backslash character to represent return (\r), tab (\t), and linefeed (\n) characters (described below). So if you want to include an actual backslash or double-quote character in atextobject, you must use the equivalent two-character sequence. As a convenience, AppleScript also provides the text constantquote, which has the value\".
Character
To insert in text
Backslash character (\)
Double quote (")
quote(text constant)
To declare atextobject that looks like this when displayed:
```
He said "Use the '\' character."```
you can use the following:
```
"He said \"Use the '\\' character.\""```
White space refers to text characters that display as vertical or horizontal space. AppleScript defines the white spaceconstantsreturn,linefeed,space, andtabto represent, respectively, a return character, a linefeed character, a space character, and a tab character. (Thelinefeedconstant became available in AppleScript 2.0.)
Although you effectively use these values as text constants, they are actually defined as properties of the global constantAppleScript.
Constant
Value
space
"\t"
return
"\r"
linefeed
"\nâ
To enter white space in a string, you can just type the characterâthat is, you can press the Space bar to insert a space, the Tab key to insert a tab character, or the Return key to insert a return. In the latter case, the string will appear on two lines in the script, like the following:
```
display dialog "Hello" & "```
```
" & "Goodbye"```
When you run this script, "Hello" appears above âGoodbyeâ in the dialog.
You can also enter a tab, return, or linefeed with the equivalent two-character sequences. When atextobject containing any of the two-character sequences is displayed to the user, the sequences are converted. For example, if you use the followingtextobject in adisplay dialogcommand:
```
display dialog "item 1\t1\ritem 2\t2"```
it is displayed like this (unless you enable âEscape tabs and line breaks in stringsâ in the Editing tab of the of Script Editor preferences):
```
item 1 1```
```
item 2 2```
To use the white space constants, you use the concatenation operator to join multipletextobjects together, as in the following example:
```
"Year" & tab & tab & "Units sold" & return & "2006" & tab ¬```
```
& tab & "300" & return & "2007" & tab & tab & "453"```
When passed todisplay dialog, this text is displayed as follows:
```
Year Units sold```
```
2006 300```
```
2007 453```
##### Coercions Supported
AppleScript supports coercion of antextobject to a single-itemlist. If atextobject represents an appropriate number, AppleScript supports coercion of thetextobject to an integer or a real number.
##### Examples
You can define atextobject in a script by surrounding text characters with quotation marks, as in these examples:
```
set theObject to "some text"```
```
set clientName to "Mr. Smith"```
```
display dialog "This is a text object."```
Suppose you use the following statement to obtain atextobject nameddocTextthat contains all the text extracted from a particular document:
```
set docText to text of document "MyFavoriteFish.rtf" of application "TextEdit"```
The following statements show various ways to work with thetextobjectdocText:
```
class of docText --result: text```
```
first character of docText --result: a character```
```
every paragraph of docText --result: a list containing all paragraphs```
```
paragraphs 2 thru 3 of docText --result: a list containing two paragraphs```
The next example prepares atextobject to use with thedisplay dialogcommand. It uses thequoteconstant to insert\"into the text. When this text is displayed in the dialog (above a text entry field), it looks like this:Enter the text in quotes ("text in quotes"):
```
set promptString to "Enter the text in quotes (" & quote ¬```
```
& "text in quotes" & quote & "): "```
```
display dialog promptString default answer ""```
The following example gets a POSIX path to a chosen folder and uses thequoted formproperty to ensure correct quoting of the resulting string for use with shell commands:
```
set folderName to quoted form of POSIX path of (choose folder)```
Suppose that you choose the folder namediWork '08in yourApplicationsfolder. The previous statement would return the following result, which properly handles the embedded single quote and space characters in the folder name:
```
"'/Applications/iWork '\\''08/'"```
##### Discussion
To get a contiguous range of characters within atextobject, use thetextelement. For example, the value of the following statement is thetextobject"y thi":
```
get text 3 thru 7 of "Try this at home"```
```
--result: "y thi"```
The result of a similar statement using the character element instead of the text element is a list:
```
get characters 3 thru 7 of "Try this at home"```
```
--result: {"y", " ", "t", "h", "i"}```
You cannot set the value of an element of atextobject. For example, if you attempt to change the value of the first character of the text objectmyNameas shown next, youâll get an error:
```
set myName to "Boris"```
```
set character 1 of myName to "D"```
```
--result: error: you cannot set the values of elements of text objects```
However, you can achieve the same result by getting the last four characters and concatenating them with "D":
```
set myName to "boris"```
```
set myName to "D" & (get text 2 through 5 of myName)```
```
--result: "Doris"```
This example doesnât actually modify the existingtextobjectâit sets the variablemyNameto refer to a newtextobject with a different value.
##### Special Considerations
For compatibility with versions prior to AppleScript 2.0,stringandUnicode textare still defined, but are considered synonyms fortext. For example, all three of these statements have the same effect:
```
someObject as text```
```
someObject as string```
```
someObject as Unicode text```
In addition,text,string, andUnicode textwill all compare as equal. For example,class of "foo" is stringistrue, even thoughclass of "foo"returnstext. However, it is still possible for applications to distinguish between the three different types, even though AppleScript itself does not.
Starting with AppleScript 2.0, there is no style information stored withtextobjects.
Because all text is Unicode text, scripts now always get the Unicode text behavior. This may be different from the formerstringbehavior for some locale-dependent operations, in particularwordelements. To get the same behavior with 2.0 and pre-2.0, add an explicitas Unicode textcoercion, for example,words of (someText as Unicode text).
Becausetext item delimiters(described intext item delimiters) respectconsideringandignoringattributes in AppleScript 2.0, delimiters are case-insensitive by default. Formerly, they were always case-sensitive. To enforce the previous behavior, add an explicitconsidering casestatement.
Because AppleScript 2.0 scripts store all text as Unicode, any text constants count as a use of the formerUnicode textclass, which will work with any version of AppleScript back to version 1.3. A script that contains Unicode-only characters such as Arabic or Thai will run, but will not be correctly editable using versions prior to AppleScript 2.0: the Unicode-only characters will be lost.
Used for working with measurements of length, area, cubic and liquid volume, mass, and temperature.
The unit type classes support simple objects that do not contain other values and have only a single property, theclassproperty.
##### Properties of unit type objects
##### Operators
None. You must explicitly coerce a unit type to a number type before you can perform operations with it.
##### Coercions Supported
You can coerce a unit type object tointeger, single-itemlist,real, ortext. You can also coerce between unit types in the same category, such asinchestokilometers(length) orgallonstoliters(liquid volume). As you would expect, there is no coercion between categories, such as fromgallonstodegrees Centigrade.
##### Examples
The following statements calculate the area of a circle with a radius of 7 yards, then coerce the area to square feet:
```
set circleArea to (pi * 7 * 7) as square yards --result: square yards 153.9380400259```
```
circleArea as square feet --result: square feet 1385.4423602331```
The following statements set a variable to a value of 5.0 square kilometers, then coerce it to various other units of area:
```
set theArea to 5.0 as square kilometers --result: square kilometers 5.0```
```
theArea as square miles --result: square miles 1.930510792712```
```
theArea as square meters --result: square meters 5.0E+6```
However, you cannot coerce an area measurement to a unit type in a different
category:
```
set theArea to 5.0 as square meters --result: square meters 5.0```
```
theArea as cubic meters --result: error```
```
theArea as degrees Celsius --result: error```
The following statements demonstrate coercion of a unit type to atextobject:
```
set myPounds to 2.2 as pounds --result: pounds 2.2```
```
set textValue to myPounds as text --result: "2.2"```
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Commands Reference
This chapter describes the commands available to perform actions in AppleScript scripts. For information on how commands work, seeCommands Overview.
The commands described in this chapter are available to any scriptâthey are either built into the AppleScript language or added to it through the standard scripting additions (described inScripting Additions).
Note:In the command descriptions below, if the first item in the Parameters list does not include a parameter name, it is the direct parameter of the command (described inDirect Parameter).
Table 7-1lists each command according to the suite (or related group) of commands to which it belongs and provides a brief description. Detailed command descriptions follow the table, in alphabetical order.
Command
Description
AppleScript suite
activate
Brings an application to the front, and opens it if it is on the local computer and not already running.
In Script Editor, displays a value in the Event Log History window or in the Event Log pane of a script window.
Clipboard Commands suite
clipboard info
Returns information about the clipboard.
set the clipboard to
Places data on the clipboard.
the clipboard
Returns the contents of the clipboard.
File Commands suite
info for
Returns information for a file or folder.
list disks
Returns a list of the currently mounted volumes.
DeprecatedUsetell application "System Events" to get the name of every disk.
list folder
Returns the contents of a specified folder.
DeprecatedUsetell application "System Events" to get the name of every disk item of ....
mount volume
Mounts the specified AppleShare volume.
path to (application)
Returns the full path to the specified application.
path to (folder)
Returns the full path to the specified folder.
path to resource
Returns the full path to the specified resource.
File Read/Write suite
close access
Closes a file that was opened for access.
get eof
Returns the length, in bytes, of a file.
open for access
Opens a disk file for thereadandwritecommands.
read
Reads data from a file that has been opened for access.
set eof
Sets the length, in bytes, of a file.
write
Writes data to a file that was opened for access with write permission.
Internet suite
open location
Opens a URL with the appropriate program.
Miscellaneous Commands suite
current date
Returns the current date and time.
do shell script
Executes a shell script using theshshell.
get volume settings
Returns the sound output and input volume settings.
random number
Generates a random number.
round
Rounds a number to an integer.
set volume
Sets the sound output and/or input volume.
system attribute
Gets environment variables or attributes of this computer.
system info
Returns information about the system.
time to GMT
Returns the difference between local time and GMT (Universal Time).
Scripting suite
load script
Returns ascriptobject loaded from a file.
run script
Runs a script or script file
scripting components
Returns a list of all scripting components.
store script
Stores ascriptobject into a file.
Standard suite
copy
Copies one or more values into variables.
count
Counts the number of elements in an object.
Returns the value of a script expression or an application object.
launch
Launches the specified application without sending it aruncommand.
For an application, launches it. For a script application, launches it and sends it theruncommand. For a script script object, executes itsrunhandler.
Assigns one or more values to one or more script variables or application objects.
String Commands suite
ASCII character
Converts a number to a character.
Deprecatedstarting in AppleScript 2.0. Use theidproperty of thetextclass instead.
ASCII number
Converts a character to its numeric value.
Deprecatedstarting in AppleScript 2.0. Use theidproperty of thetextclass instead.
localized string
Returns the localized string for the specified key.
offset
Finds one piece of text inside another.
summarize
Summarizes the specified text or text file.
User Interaction suite
beep
Beeps one or more times.
choose application
Allows the user to choose an application.
choose color
Allows the user to choose a color.
choose file
Allows the user to choose a file.
choose file name
Allows the user to specify a new file reference.
choose folder
Allows the user to choose a folder.
choose from list
Allows the user to choose one or more items from a list.
choose remote application
Allows the user to choose a running application on a remote machine.
choose URL
Allows the user to specify a URL.
delay
Pauses for a fixed amount of time.
display alert
Displays an alert.
display dialog
Displays a dialog box, optionally requesting user input.
display notification
Displays a notification.
Speaks the specified text.
Brings an application to the front, launching it if necessary.
##### Syntax
##### Parameters
The application to activate.
##### Result
None.
##### Examples
```
activate application "TextEdit"```
```
tell application "TextEdit" to activate```
##### Discussion
Theactivatecommand does not launch applications on remote machines. For examples of other ways to specify an application, see theapplicationclass andRemote Applications.
Returns the character for a specified number.
Important:This command is deprecated starting in AppleScript 2.0âuse theidproperty of thetextclass instead.
##### Syntax
##### Parameters
The character code, an integer between 0 and 255.
##### Result
Atextobject containing the character that corresponds to the specified number.
Signals an error ifintegeris out of range.
##### Examples
```
set theChar to ASCII character 65 --result: "A"```
```
set theChar to ASCII character 194 --result: "¬"```
```
set theChar to ASCII character 2040 --result: invalid range error```
##### Discussion
The name âASCIIâ is something of a misnomer.ASCII characteruses the primary text encoding, as determined by the userâs language preferences, to map between integers and characters. If the primary language is English, the encoding is Mac OS Roman, if it is Japanese, the encoding is MacJapanese, and so on. For integers below 128, this is generally the same as ASCII, but for integers from 128 to 255, the results vary considerably.
Because of this unpredictability,ASCII characterandASCII numberare deprecated starting in AppleScript 2.0. Use theidproperty of thetextclass instead, since it always uses the same encoding, namely Unicode.
Returns the number associated with a specified character.
Important:This command is deprecated starting in AppleScript 2.0âuse theidproperty of thetextclass instead.
##### Syntax
##### Parameters
Atextobject containing at least one character. If there is more than one character, only the first one is used.
##### Result
The character code of the specified character as an integer.
##### Examples
```
set codeValue to ASCII number "¬" --result: 194```
##### Discussion
The result ofASCII numberdepends on the userâs language preferences; see the Discussion section ofASCII characterfor details.
Plays the system alert sound one or more times.
##### Syntax
##### Parameters
Number of times to beep.
##### Result
None.
##### Examples
Audible alerts can be useful when no one is expected to be looking at the screen:
```
beep 3 --result: three beeps, to get attention```
```
display dialog "Something is amiss here!" -- to show message```
Allows the user to choose an application.
##### Syntax
##### Parameters
Title text for the dialog.
"Choose Application"
A prompt to be displayed in the dialog.
"Select an application:"
Allow multiple items to be selected? Iftrue, the results will be returned in a list, even if there is exactly one item.
false
Specifies the desired class of the result. If specified, the value must be one ofapplicationoralias.
application
##### Result
The selected application, as either anapplicationoraliasobject; for example,application "TextEdit". If multiple selections are allowed, returns a list containing one item for each selected application, if any.
Signals a âuser canceledâ error if the user cancels the dialog. For an example of how to handle such errors, seetry Statements.
##### Examples
```
choose application with prompt "Choose a web browser:"```
```
choose application with multiple selections allowed```
```
choose application as alias```
##### Discussion
Thechoose applicationdialog initially presents a list of all applications registered with the system. To choose an application not in that list, use the Browse button, which allows the user to choose an application anywhere in the file system.
Allows the user to choose a color from a color picker dialog.
##### Syntax
##### Parameters
The color to show when the color picker dialog is first opened.
{0, 0, 0}: black.
##### Result
The selected color, represented as a list of three integers from 0 to 65535 corresponding to the red, green, and blue components of a color; for example, {0, 65535, 0} represents green.
Signals a âuser canceledâ error if the user cancels thechoose colordialog. For an example of how to handle such errors, seetry Statements.
##### Examples
This example lets the user choose a color, then uses that color to set the background color in their home folder (when it is in icon view):
```
tell application "Finder"```
```
tell icon view options of window of home```
```
choose color default color (get background color)```
```
set background color to the result```
```
end tell```
```
end tell```
Allows the user to choose a file.
##### Syntax
##### Parameters
The prompt to be displayed in the dialog.
None; no prompt is displayed.
A list of Uniform Type Identifiers (UTIs); for example,{"public.html", "public.rtf"}. Only files of the specified types will be selectable. For a list of system-defined UTIs, seeUniform Type Identifiers Overview. To get the UTI for a particular file, useinfo for.
Note:Four-character file type codes, such as"PICT"or"MooV", are also supported, but are deprecated. To get the file type code for a particular file, useinfo for.
None; any file can be chosen.
The folder to begin browsing in.
Browsing begins in the last selected location, or, if this is the first invocation, in the userâsDocumentsfolder.
Show invisible files and folders?
true: This is only for historical compatibility reasons. Unless you have a specific need to choose invisible files, you should always useinvisibles false.
Allow multiple items to be selected? Iftrue, the results will be returned in a list, even if there is exactly one item.
false
Show the contents of packages? Iftrue, packages are treated as folders, so that the user can choose a file inside a package (such as an application).
false. Manipulating the contents of packages is discouraged unless you control the package format or the package itself.
##### Result
The selected file, as analias. If multiple selections are allowed, returns a list containing onealiasfor each selected file, if any.
Signals a âuser canceledâ error if the user cancels the dialog. For an example of how to handle such errors, seetry Statements.
##### Examples
```
set aFile to choose file with prompt "HTML or RTF:" ¬```
```
of type {"public.html", "public.rtf"} invisibles false```
A UTI can specify a general class of files, not just a specific format. The following script allows the user to choose any image file, whether its format isJPEG,PNG,GIF, or whatever. It also uses thedefault locationparameter combined withpath to (folder)to begin browsing in the userâsPicturesfolder:
```
set picturesFolder to path to pictures folder```
```
choose file of type "public.image" with prompt "Choose an image:" ¬```
```
default location picturesFolder invisibles false```
Allows the user to specify a new filename and location. This does not create a fileârather, it returns a file specifier that can be used to create a file.
##### Syntax
##### Parameters
The prompt to be displayed near the top of the dialog.
"Specify new file name and location"
The default file name.
"untitled"
The default file location. Seechoose filefor examples.
Browsing starts in the last location in which a search was made or, if this is the first invocation, in the userâsDocumentsfolder.
##### Result
The selected location, as afile. For example:
file "HD:Users:currentUser:Documents:untitled"
Signals a âuser canceledâ error if the user cancels the dialog. For an example of how to handle such errors, seetry Statements.
##### Examples
The following example supplies a non-default prompt and search location:
```
set fileName to choose file name with prompt "Save report as:" ¬```
```
default name "Quarterly Report" ¬```
```
default location (path to desktop folder)```
##### Discussion
If you choose the name of a file or folder that exists in the selected location,choose file nameoffers the choice of replacing the chosen item. However, choosing to replace does not actually replace the item.
Allows the user to choose a directory, such as a folder or a disk.
##### Syntax
##### Parameters
The prompt to be displayed in the dialog.
None; no prompt is displayed.
The folder to begin browsing in.
Browsing begins in the last selected location, or, if this is the first invocation, in the userâsDocumentsfolder.
Show invisible folders?
false
Allow multiple items to be selected? Iftrue, the results will be returned in a list, even if there is exactly one item.
false
Show the contents of packages? Iftrue, packages are treated as folders, so that the user can choose a package folder, such as an application, or a folder inside a package.
false. Manipulating the contents of packages is discouraged unless you control the package format or the package itself.
##### Result
The selected directory, as analias. If multiple selections are allowed, returns a list containing onealiasfor each selected directory, if any.
Signals a âuser canceledâ error if the user cancels thechoose folderdialog. For an example of how to handle such errors, seetry Statements.
##### Examples
The following example specifies a prompt and allows multiple selections:
```
set foldersList to choose folder ¬```
```
with prompt "Select as many folders as you like:" ¬```
```
with multiple selections allowed```
The following example gets a POSIX path to a chosen folder and uses thequoted formproperty (of thetextclass) to ensure correct quoting of the resulting string for use with shell commands:
```
set folderName to quoted form of POSIX path of (choose folder)```
Suppose that you choose the folder namediWork '08in yourApplicationsfolder. The previous statement would return the following result, which properly handles the embedded single quote and space characters in the folder name:
```
"'/Applications/iWork '\\''08/'"```
Allows the user to choose items from a list.
##### Syntax
##### Parameters
A list of numbers and/ortextobjects for the user to choose from.
Title text for the dialog.
None; no title is displayed.
The prompt to be displayed in the dialog.
"Please make your selection:"
A list of numbers and/ortextobjects to be initially selected. The list cannot include multiple items unless you also specifymultiple selections allowed true. If an item in the default items list is not in the list to choose from, it is ignored.
None; no items are selected.
The name of the OK button.
"OK"
The name of the Cancel button.
"Cancel"
Allow multiple items to be selected?
false
Allow the user to choose OK with no items selected? Iffalse, the OK button will not be enabled unless at least one item is selected.
false
##### Result
If the user clicks the OK button, returns alistof the chosennumberand/ortextitems; if empty selection is allowed and nothing is selected, returns an empty list ({}). If the user clicks the Cancel button, returnsfalse.
##### Examples
This script selects from a list of all the people in Address Book who have defined birthdays, and gets the birthday of the selected one. Notice theif the result is not falsetest (choose from listreturnsfalseif the user clicks Cancel) and theset aName to item 1 of the result(choose from listreturns a list, even if it contains only one item).
```
tell application "Address Book"```
```
set bDayList to name of every person whose birth date is not missing value```
```
choose from list bDayList with prompt "Whose birthday would you like?"```
```
if the result is not false then```
```
set aName to item 1 of the result```
```
set theBirthday to birth date of person named aName```
```
display dialog aName & "'s birthday is " & date string of theBirthday```
```
end if```
```
end tell```
##### Discussion
For historical reasons,choose from listis the only dialog command that returns a result (false) instead of signaling an error when the user presses the âCancelâ button.
Allows the user to choose a running application on a remote machine.
##### Syntax
##### Parameters
Title text for thechoose remote applicationdialog.
None; no title is displayed.
The prompt to be displayed in the dialog.
"Select an application:"
##### Result
The selected application, as anapplicationobject.
Signals a âuser canceledâ error if the user cancels the dialog. For an example of how to handle such errors, seetry Statements.
##### Examples
```
set myApp to choose remote application with prompt "Choose a remote web browser:"```
##### Discussion
The user may choose a remote machine usingBonjour or by entering a specific IP address. There is no way to limit the precise kind of application returned, so either limit your script to generic operations or validate the userâs choice. If you want your script to send application-specific commands to the resulting application, you will need a using terms from statement.
For information on targeting other machines, seeRemote Applications.
Allows the user to specify a URL.
##### Syntax
##### Parameters
A list that specifies the types of services to show, if available. The list can contain one or more of the following service types, or one or moretextobjects representing Bonjour service types (described below), or both:
- Web servers: showshttpandhttpsservices
Web servers: showshttpandhttpsservices
- FTP Servers: showsftpservices
FTP Servers: showsftpservices
- Telnet hosts: showstelnetservices
Telnet hosts: showstelnetservices
- File servers: showsafp,nfs, andsmbservices
File servers: showsafp,nfs, andsmbservices
- News servers: showsnntpservices
News servers: showsnntpservices
- Directory services: showsldapservices
Directory services: showsldapservices
- Media servers: showsrtspservices
Media servers: showsrtspservices
- Remote applications: showseppcservices
Remote applications: showseppcservices
Atextobject is interpreted as a Bonjour service typeâfor example,"_ftp._tcp"represents the file transfer protocol. These types are listed inTechnical Q&A 1312: Bonjour service types used in OS X.
File servers
Allow user to type in a URL? If you specifyeditable URL false, the text field in the dialog is inactive.
choose URLdoes not attempt to verify that the user-entered text is a valid URL. Your script should be prepared to verify the returned value.
true: the user can enter a text string. Iffalse, the user is restricted to choosing an item from the Bonjour-supplied list of services.
##### Result
The URL for the service, as atextobject. This result may be passed toopen locationor to any application that can handle the URL, such as a browser forhttpURLs.
Signals a âuser canceledâ error if the user cancels the dialog. For an example of how to handle such errors, seetry Statements.
##### Examples
The following script asks the user to choose an URL, either by typing in the text input field or choosing one of the Bonjour-located servers:
```
set myURL to choose URL```
```
tell application Finder to open location myURL```
Returns information about the current clipboard contents.
##### Syntax
##### Parameters
Restricts returned information to only this data type.
None; returns information for all types of data as a list of lists, where each list represents a scrap flavor.
##### Result
Alistcontaining one entry{class, size}for each type of data on the clipboard. To retrieve the actual data, use thethe clipboardcommand.
##### Examples
```
clipboard info```
```
clipboard info for Unicode text```
Closes a file opened with theopen for accesscommand.
##### Syntax
##### Parameters
The alias or file specifier or integer file descriptor of the file to close. A file descriptor must be obtained as the result of an earlieropen for accesscall.
##### Result
None.
Signals an error if the specified file is not open.
##### Examples
You should always close files that you open, being sure to account for possible errors while using the open file:
```
set aFile to choose file```
```
set fp to open for access aFile```
```
try```
```
--file reading and writing here```
```
on error e number n```
```
--deal with errors here and don't resignal```
```
end```
```
close access fp```
##### Discussion
Any files left open will be automatically closed when the application exits.
Copies one or more values, storing the result in one or more variables. This command only copies AppleScript values, not application-defined objects.
##### Syntax
##### Parameters
The expression whose value is to be copied.
The name of the variable or pattern of variables in which to store the value or pattern of values. Patterns may be lists or records.
##### Result
The new copy of the value.
##### Examples
As mentioned in the Discussion,copycreates an independent copy of the original value, and it creates a deep copy. For example:
```
set alpha to {1, 2, {"a", "b"}}```
```
copy alpha to beta```
```
set item 2 of item 3 of alpha to "change" --change the original list```
```
set item 1 of beta to 42 --change a different item in the copy```
```
{alpha, beta}```
```
--result: {{1, 2, {"a", "change"}}, {42, 2, {"a", "b"}}}```
Each variable reflects only the changes that were made directly to that variable. Compare this with the similar example inset.
See thesetcommand for examples of using variable patterns. The behavior is the same except that the values are copied.
##### Discussion
Thecopycommand may be used to assign new values to existing variables, or to define new variables. SeeDeclaring Variables with the copy Commandfor additional details.
Using thecopycommand creates a new value that is independent of the originalâa subsequent change to that value does not change the original value. The copy is a âdeepâ copy, so sub-objects, such as lists within lists, are also copied. Contrast this with the behavior of thesetcommand.
When usingcopywith an object specifier, the specifier itself is the value copied, not the object in the target application that it refers to.copytherefore copies the object specifier, but does not affect the application data at all. To copy the object in the target application, use the applicationâsduplicatecommand, if it has one.
##### Special Considerations
The syntaxputexpressionintovariablePatternis also supported, but is deprecated. It will be transformed into thecopyform when you compile the script.
Counts the number of elements in another object.
##### Syntax
##### Parameters
An expression that evaluates to an object with elements, such as alist,record, or application-defined container object.countwill count the contained elements.
##### Result
The number of elements, as aninteger.
##### Examples
In its simplest form,count, or the equivalent pseudo-propertynumber, counts theitemelements of a value. This may be an AppleScript value, such as a list:
```
set aList to {"Yes", "No", 4, 5, 6}```
```
count aList --result: 5```
```
number of aList --result: 5```
â¦or an application-defined object that hasitemelements:
```
tell application "Finder" to count disk 1 --result: 4```
If the value is an object specifier that evaluates to a list,countcounts the items of that list. This may be anEveryspecifier:
```
count every integer of aList --result: 3```
```
count words of "hello world" --result: 2```
```
tell application "Finder" to count folders of disk 1 --result: 4```
â¦or aFilterspecifier:
```
tell application "Finder"```
```
count folders of disk 1 whose name starts with "A" --result: 1```
```
end tell```
â¦or similar. For more on object specifiers, seeObject Specifiers.
Returns the current date and time.
##### Syntax
##### Result
The current date and time, as adateobject.
##### Examples
```
current date --result: date "Tuesday, November 13, 2007 11:13:29 AM"```
See thedateclass for information on how to access the properties of a date, such as the day of the week or month.
Waits for a specified number of seconds.
##### Syntax
##### Parameters
The number of seconds to delay. The number may be fractional, such as0.5to delay half a second.
##### Result
None.
##### Examples
```
set startTime to current date```
```
delay 3 --delay for three seconds```
```
set elapsedTime to ((current date) - startTime)```
```
display dialog ("Elapsed time: " & elapsedTime & " seconds")```
##### Discussion
delaydoes not make any guarantees about the actual length of the delay, and it cannot be more precise than 1/60th of a second.delayis not suitable for real-time tasks such as audio-video synchronization.
Displays a standardized alert containing a message, explanation, and from one to three buttons.
##### Syntax
##### Parameters
The alert text, which is displayed in emphasized system font.
An explanatory message, which is displayed in small system font, below the alert text.
The type of alert to show. You can specify one of the following alert types:
- informational: the standard alert dialog
informational: the standard alert dialog
- warning: the alert dialog dialog is badged with a warning icon
warning: the alert dialog dialog is badged with a warning icon
- critical: currently the same as the standard alert dialog
critical: currently the same as the standard alert dialog
informational
A list of up to three button names.
If you supply one name, a button with that name serves as the default and is displayed on the right side of the alert dialog. If you supply two names, two buttons are displayed on the right, with the second serving as the default button. If you supply three names, the first is displayed on the left, and the next two on the right, as in the case with two buttons.
{"OK"}: One button labeled âOKâ, which is the default button.
The name or number of the default button. This may be the same as the cancel button.
The rightmost button.
The name or number of the cancel button. See âResultâ below. This may be the same as the default button.
None; there is no cancel button.
The number of seconds to wait before automatically dismissing the alert.
None; the dialog will wait until the user clicks a button.
##### Result
If the user clicks a button that was not specified as the cancel button,display alertreturns a record that identifies the button that was clickedâfor example,{button returned: "OK"}. If the command specifies agiving up aftervalue, the record will also contain agave up:falseitem.
If thedisplay alertcommand specifies agiving up aftervalue, and the dialog is dismissed due to timing out before the user clicks a button, the command returns a record indicating that no button was returned and the command gave up:{button returned:"", gave up:true}
If the user clicks the specified cancel button, the command signals a âuser canceledâ error. For an example of how to handle such errors, seetry Statements.
##### Examples
```
set alertResult to display alert "Insert generic warning here." ¬```
```
buttons {"Cancel", "OK"} as warning ¬```
```
default button "Cancel" cancel button "Cancel" giving up after 5```
For an additional example, see the Examples section for thetrystatement.
Displays a dialog containing a message, one to three buttons, and optionally an icon and a ï¬eld in which the user can enter text.
##### Syntax
##### Parameters
The dialog text, which is displayed in emphasized system font.
The initial contents of an editable text field. This edit field is not present unless this parameter is present; to have the field present but blank, specify an empty string:default answer ""
None; there is no edit field.
If true, any text in the edit field is obscured as in a password dialog: each character is displayed as a bullet.
false: text in the edit field is shown in cleartext.
A list of up to three button names.
If you donât specify any buttons, by default, Cancel and OK buttons are shown, with the OK button set as the default button.
If you specify any buttons, there is no default or cancel button unless you use the following parameters to specify them.
The name or number of the default button. This button is highlighted, and will be pressed if the user presses the Return or Enter key.
If there are no buttons specified usingbuttons, the OK button. Otherwise, there is no default button.
The name or number of the cancel button. This button will be pressed if the user presses the Escape key or Command-period.
If there are no buttons specified usingbuttons, the Cancel button. Otherwise, there is no cancel button.
The dialog window title.
None; no title is displayed.
The resource name or ID of the icon to display.
The type of icon to show. You may specify one of the following constants:
- stop(or0): Shows a stop icon
stop(or0): Shows a stop icon
- note(or1): Shows the application icon
note(or1): Shows the application icon
- caution(or2): Shows a warning icon, badged with the application icon
caution(or2): Shows a warning icon, badged with the application icon
Analiasorfilespecifier that specifies a.icnsfile.
The number of seconds to wait before automatically dismissing the dialog.
None; the dialog will wait until the user presses a button.
##### Result
A record containing the button clicked and text entered, if any. For example:
{text returned:"Cupertino", button returned:"OK"}
If the dialog does not allow text input, there is notext returneditem in the returned record.
If the user clicks the specified cancel button, the command signals a âuser canceledâ error. For an example of how to handle such errors, seetry Statements.
If thedisplay dialogcommand specifies agiving up aftervalue, and the dialog is dismissed due to timing out before the user clicks a button, it returns a record indicating that no button was returned and the command gave up:{button returned:"", gave up:true}
##### Examples
The following example shows how to use many of the parameters to adisplay dialogcommand, how to process possible returned values, and one way to handle a user cancelled error. The dialog displays two buttons and prompts a user to enter a name, giving up if they do not make a response within fifteen seconds. It shows one way to handle the case where the user cancels the dialog, which results in AppleScript signaling an âerrorâ with the error number -128. The script uses additionaldisplay dialogcommands to show the flow of logic and indicate where you could add statements to handle particular outcomes.
```
set userCanceled to false```
```
try```
```
set dialogResult to display dialog ¬```
```
"What is your name?" buttons {"Cancel", "OK"} ¬```
```
default button "OK" cancel button "Cancel" ¬```
```
giving up after 15 ¬```
```
default answer (long user name of (system info))```
```
on error number -128```
```
set userCanceled to true```
```
end try```
```
```
```
if userCanceled then```
```
-- statements to execute when user cancels```
```
display dialog "User cancelled."```
```
else if gave up of dialogResult then```
```
-- statements to execute if dialog timed out without an answer```
```
display dialog "User timed out."```
```
else if button returned of dialogResult is "OK" then```
```
set userName to text returned of dialogResult```
```
-- statements to process user name```
```
display dialog "User name: " & userName```
```
end if```
```
end```
The following example displays a dialog that asks for a password. It supplies a default answer of"wrong", and specifies that the default answer, as well as any text entered by the user, is hidden (displayed as a series of bullets). It gives the user up to three chances to enter a correct password.
```
set prompt to "Please enter password:"```
```
repeat 3 times```
```
set dialogResult to display dialog prompt ¬```
```
buttons {"Cancel", "OK"} default button 2 ¬```
```
default answer "wrong" with icon 1 with hidden answer```
```
set thePassword to text returned of dialogResult```
```
if thePassword = "magic" then```
```
exit repeat```
```
end if```
```
end repeat```
```
if thePassword = "magic" or thePassword = "admin" then```
```
display dialog "User entered valid password."```
```
end if```
The password text is copied from the return valuedialogResult. The script doesnât check for a user cancelled error, so if the user cancels AppleScript stops execution of the script.
Posts a notification using the Notification Center, containing a title, subtitle, and explanation, and optionally playing a sound.
##### Syntax
##### Parameters
The body text of the notification. At least one of this and the title must be specified.
The title of the notification. At least one of this and the body text must be specified.
The subtitle of the notification.
The name of a sound to play when the notification appears. This may be the base name of any sound installed inLibrary/Sounds.
##### Result
None.
##### Examples
```
display notification "Encoding complete" subtitle "The encoded files are in the folder " & folderName```
##### Discussion
Exactly how the notification is presented is controlled by the âNotificationsâ preferences in System Preferences. Users may opt to display a reduced form of notification, turn off the sound, or even not display them at all.
Executes a shell script using theshshell.
##### Syntax
##### Parameters
The shell script to execute.
Specifies the desired type of the result. The raw bytes returned by the command will be interpreted as the specified class.
«class utf8»: UTF-8 text. If there is noasparameter and the output is not valid UTF-8, the output will be interpreted as text in the primary encoding.
Execute the command as the administrator? Once a script is correctly authenticated, it will not ask for authentication again for five minutes. The elevated privileges and the grace period do not extend to any other scripts or to the rest of the system. For security reasons, you may not tell another application todo shell script with administrator privileges. Put the command outside of anytellblock, or put it inside atell meblock.
false
The name of an administrator account. You can avoid a password dialog by specifying a name in this parameter and a password in thepasswordparameter. If you specify a user name, you must also specify a password.
An administrator password, typically used in conjunction with the administrator specified by theuser nameparameter. Ifuser nameis omitted, it is assumed to be the current user.
Should thedo shell scriptcommand change all line endings in the command output to Mac-style and trim a trailing one? For example, the result ofdo shell script "echo foo; echo bar"is"foo\rbar", not the"foo\nbar\n"that the shell script actually returned.
true
##### Result
The output of the shell script.
Signals an error if the shell script exits with a non-zero status. The error number will be the status, the error message will be the contents of stderr.
##### Examples
```
do shell script "uptime"```
##### Discussion
For additional documentation and examples of thedo shell scriptcommand, see Technical Note TN2065,do shell script in AppleScript.
Evaluates an object specifier and returns the result.
The command namegetis typically optionalâexpressions that appear as statements or operands are automatically evaluated as if they were preceded byget. However,getcan be used to force early evaluation of part of an object specifier.
##### Syntax
##### Parameters
An object specifier to be evaluated. If the specifier refers to an application-defined object, thegetcommand is sent to that application. Technically, all values respond toget, but for all values other than object specifiers,getis an identity operation: the result is the exact same value.
The desired class for the returned data. If the data is not of the desired type, AppleScript attempts to coerce it to that type.
None; no coercion is performed.
##### Result
The value of the evaluated expression. SeeReference Formsfor details on what the results of evaluating various object specifiers are.
##### Examples
getcan get properties or elements of AppleScript-defined objects, such as lists:
```
get item 1 of {"How", "are", "you?"} --result: "How"```
â¦or of application-defined objects:
```
tell application "Finder" to get name of home --result: "myname"```
As noted above, thegetis generally optional. For example, these statements are equivalent to the above two:
```
item 1 of {"How", "are", "you?"} --result: "How"```
```
tell application "Finder" to name of home --result: "myname"```
However, an explicitgetcan be useful for forcing early evaluation of part of an object specifier. Consider:
```
tell application "Finder" to get word 1 of name of home```
```
--Finder got an error: Canât get word 1 of name of folder "myname" of folder "Users" of startup disk.```
This fails because Finder does not know about elements oftext, such aswords. AppleScript does, however, so the script has to make Finder get only thename of ...part:
```
tell application "Finder" to get word 1 of (get name of home)```
```
--result: "myname"```
The explicitgetforces that part of the specifier to be evaluated; Finder returns atextresult, from which AppleScript can then getword 1.
For more information on specifiers, seeObject Specifiers.
Returns the length of a file, in bytes.
##### Syntax
##### Parameters
The file to obtain the length for, as an alias, a file specifier, or anintegerfile descriptor. A file descriptor must be obtained as the result of an earlieropen for accesscall.
##### Result
The logical size of the file, that is, the length of its contents in bytes.
##### Examples
This example obtains an alias to a desktop picture folder and usesget eofto obtain its length:
```
set desktopPicturesFolderPath to ¬```
```
(path to desktop pictures folder as text) & "Flow 1.jpg" as alias```
```
--result: alias "Leopard:Library:Desktop Pictures:Flow 1.jpg"```
```
get eof desktopPicturesFolderPath --result: 531486```
Returns the sound output and input volume settings.
##### Syntax
##### Result
A record containing the sound output and input volume settings. All the integer settings are between 0 (silent) and 100 (full volume):
The base output volume.
The input volume.
The alert volume. 100 for this setting means âas loud as the output volume.â
Is the output muted? If true, this overrides the output and alert volumes.
##### Examples
```
set volSettings to get volume settings```
```
--result: {output volume:43, input volume:35, alert volume:78, output muted:false}```
Return information for a file or folder.
##### Syntax
##### Parameters
An alias or file specifier for the file or folder.
Return the size of the file or folder? For a file, its âsizeâ is its length in bytes; for a folder, it is the sum of the sizes of all the files the folder contains.
true: Because getting the size of a folder requires getting the sizes of all the files inside it,size truemay take a long time for large folders such as/System. If you do not need the size, ask to not get it usingsize false. Alternatively, target the Finder or System Events applications to ask for the specific properties you want.
##### Result
A record containing information about the specified file or folder, with the following fields. Some fields are only present for certain kinds of items:
The itemâs full name, as it appears in the file system. This always includes the extension, if any. For example,"OmniOutliner Professional.app".
The itemâs name as it appears in Finder. This may be different than thenameif the extension is hidden or if the item has a localized name. For example,"OmniOutliner Professional".
The applicationâsCFBundleName, which is the name displayed in the menu bar when the application is active. This is often, but not always, the same as the displayed name. For example,"OmniOutliner Pro".
The extension part of the item name. For example, the name extension of the file âfoo.txtâ is"txt".
The packageâs bundle identifier. If the package is an application, this is the applicationâsid.
The itemâs type, as a Uniform Type Identifier (UTI). This is the preferred form for identifying item types, and may be used withchoose file.
The itemâs type, as displayed in Finder. This may be localized, and should only be used for display purposes.
The application that will open this item.
The date the item was created.
The date the item was last modified. Folder modification dates do not change when an item inside them changes, though they do change when an item is added or removed.
The itemâs type, as a four-character code. This is the classic equivalent of the type identifier, but less accurate and harder to interpret; usetype identifierif possible.
The itemâs four-character creator code. For applications, this is the classic equivalent of the bundle identifier, and will work for referencing an application by id. For files, this can be used to infer the default application, but not reliably; usedefault applicationif possible.
The itemâs short version string, as it appears in a Finder âGet Infoâ window. Any item may have this attribute, but typically only applications do.
The itemâs long version string, as it appears in a Finder âGet Infoâ window. Any item may have this attribute, but typically only applications do.
The itemâs size, in bytes. For more details, see thesizeparameter.
Is the item an alias file?
Is the item a folder? This is true for packages, such as application packages, as well as normal folders.
Is the item a package folder, such as an application? A package folder appears in Finder as if it is a file.
Is the itemâs name extension hidden?
Is the item visible? Typically, only special system files are invisible.
Is the item locked?
Is the item currently in use?
Iftrue, the item is reliably busy. Iffalse, the item may still be busy, because this status may not be supported by some applications or file systems.
The folderâs windowâs bounding rectangle, as list of four integers: {top, left, bottom, right}.
##### Examples
```
set downloadsFolder to path to downloads folder```
```
--result: alias "HD:Users:me:Downloads:"```
```
info for downloadsFolder```
```
--result: {name:"Downloads", folder:true, alias:false, ...}```
##### Special Considerations
Becauseinfo forreturns so much information, it can be slow, and because it only works on one file at a time, it can be difficult to use. The recommended technique is to use System Events or Finder to ask for the particular properties you want.
Launches an application, if it is not already running, but does not send it aruncommand.
If an application is already running, sending it alaunchcommand has no effect. That allows you to open an application without performing its usual startup procedures, such as opening a new window or, in the case of a script application, running its script. For example, you can use thelaunchcommand when you donât want an application to open and close visibly. This is less useful in AppleScript 2.0, which launches applications as hidden by default (even with theruncommand).
See theapplicationclass reference for information on how to use anapplicationobjectâsis runningproperty to determine if it is running without having to launch it.
##### Syntax
##### Parameters
The application to launch.
##### Result
None.
##### Examples
```
launch application "TextEdit"```
```
tell application "TextEdit" to launch```
##### Discussion
Thelaunchcommand does not launch applications on remote machines. For examples of other ways to specify an application, see theapplicationclass.
Many applications also support thereopencommand, which reactivates a running application or launches it if it isnât running. If the application is already running, this command has the same effect as double-clicking the application icon in the Finder. Each application determines how it will implement thereopencommandâsome may perform their usual startup procedures, such as opening a new window, while others perform no additional operations.
Returns the names of the currently mounted volumes.
Important:This command is deprecated; usetell application "System Events" to get the name of every disk.
##### Syntax
##### Result
Alistof text objects, one for each currently mounted volume.
Returns the names of the items in a specified folder.
Important:This command is deprecated; usetell application "System Events" to get the name of every disk item of ....
##### Syntax
##### Parameters
Specifies the folder to list.
Show invisible files and folders?
true
##### Result
Alistoftextobjects, one for each item in the specified folder.
Returns ascriptobject loaded from a specified file.
##### Syntax
##### Parameters
Analiasorfilespecifier that specifies ascriptobject. The file must be a compiled script (with extensionscpt) or script bundle (with extensionscptd).
##### Result
Thescriptobject. You can get this objectâs properties or call its handlers as if it were a localscriptobject.
##### Examples
For examples, seeParameter SpecificationsinAbout Handlers.
Returns the localized text for the specified key.
##### Syntax
##### Parameters
The key for which to obtain the localized text.
The name of the strings file excluding the.stringssuffix.
"Localizable"
Analiasorfilespecifier that specifies the strings file.
The current script bundle for a document-based script (ascptdbundle); otherwise, the current application.
##### Result
Atextobject containing the localized text, or the original key if there is no localized text for that key.
##### Examples
In order forlocalized stringto be useful, you must create localized string data for it to use:
- Save your script as an application bundle or script bundle.
Save your script as an application bundle or script bundle.
- Createlprojfolders in theResourcesdirectory of the bundle for each localization: for example,English.lproj,French.lproj. Create files namedLocalized.stringsin each one. When you are done, the folder structure should look like this:Figure 7-1Bundle structure with localized string data
Createlprojfolders in theResourcesdirectory of the bundle for each localization: for example,English.lproj,French.lproj. Create files namedLocalized.stringsin each one. When you are done, the folder structure should look like this:
- Add key/value pairs to each Localized.strings file. Each pair is a line of text"key" = "value";, for example:Figure 7-2Key/value pair for localized string data
Add key/value pairs to each Localized.strings file. Each pair is a line of text"key" = "value";, for example:
Nowlocalized stringwill return the appropriate values, as defined in your files. For example, when running in French:
```
localized string "hello" --result: "bonjour"```
In Script Editor, displays a value in the Event Log History window or in the Event Log pane of a script window.
##### Syntax
##### Parameters
The value to display. Expressions are evaluated but object specifiers are not resolved.
The displayed value is enclosed in block comment charactersâfor example,(*window 1*).
If you do not specify a value,logwill display just the comment characters:(**).
##### Result
None.
##### Examples
The following shows a simple use of logging:
```
set area to 7 * 43 as square feet```
```
log area -- result (in Event Log pane): (*square feet 301.0*)```
Log statements can be useful for tracking a scriptâs progress. For an example that shows how to log statements in a repeat loop, seeLogging.
Mounts the specified network volume.
##### Syntax
##### Parameters
The name or URL (for example,afp://server/volume/) of the volume to mount.
The server on which the volume resides; omit if URL path provided in direct parameter.
The AppleTalk zone in which the server resides; omit if URL path provided.
The user name with which to log in to the server; omit for guest access.
The password for the user name; omit for guest access.
##### Result
None.
##### Examples
```
mount volume "afp://myserver.com/" -- guest access```
```
mount volume "http://idisk.mac.com/myname/Public"```
```
mount volume "http://idisk.mac.com/somebody" ¬```
```
as user name "myname" with password "mypassword"```
##### Discussion
Themount volumecommand can connect to any file server that is supported by the Finder ÂConnect To... command, including Windows (smb), Samba, and FTP servers. On some kinds of servers, theas user nameandwith passwordparameters may not bypass the login dialog, but encoding the name and password in the URL (for example,smb://myname:passwd@server.domain.com/sharename) will mount it silently.
Finds one piece of text inside another.
##### Syntax
##### Parameters
The source text to find the position of.
The target text to search in.
##### Result
Anintegervalue indicating the position, in characters, of the source text in the target, or 0 if not found.
##### Examples
```
set myString to "Yours, mine, and ours"```
```
offset of "yours" in myString --result: 1, because case is ignored by default```
```
offset of "mine" in myString --result: 8```
```
offset of "theirs" in myString --result: 0, because "theirs" doesn't appear```
```
considering case```
```
offset of "yours" in myString -- result: 0, because case is now considered```
```
end considering```
##### Discussion
offsetcompares text as theequalsoperator does, includingconsideringandignoringconditions. The values returned are counted the same waycharacterelements oftextare countedâfor example,offset of "c" in "école"is always2, regardless of whether"école"is in Normalization Form C or D. The result of matching part of a character cluster is undefined.
Opens a file for reading and writing.
##### Syntax
##### Parameters
Analiasorfilespecifier that specifies the file to open. You can only use an alias if the file exists.
Should writing to the file be allowed?
false:writeandset eofcommands on this file will fail with an error.
##### Result
A file descriptor, as aninteger. This file descriptor may be used with any of the other file commands:read,write,get eof,set eof, andclose access.
##### Examples
The following example opens a file named "NewFile" in the specified locationpath to desktop, but does not ask for write access:
```
set theFile to (path to desktop as text) & "NewFile"```
```
set referenceNumber to open for access theFile```
To open the file with write access, you would substitute the following line:
```
set referenceNumber to open for access theFile with write permission```
##### Discussion
Opening a file usingopen for accessis not the same as opening a file using Finder. It is âopenâ only in the sense that AppleScript has access to read (and optionally write) its contents; it does not appear in one of the target applicationâs windows, and it does not even have to be one of the target applicationâs files.open for accessand the associated file commands (read,write,get eof,set eof) are typically used with text files. They can also read and write arbitrary binary data, but this is not recommended unless you create the file yourself or have detailed knowledge of the file format.
Callingopen for accesson a file returns an integer, termed afile descriptor, which represents an open communication channel to the fileâs data. This file descriptor remains open until the script callsclose accesson it (or on the same file). Each file descriptor maintains afile pointer, which marks the current position within the file and is initially set to the beginning of the file.readandwritecommands begin reading or writing at the file pointer, unless instructed otherwise using afromorstarting atparameter, and advance the file pointer by the number of bytes read or written, so the next operation will begin where the previous one left off.
A single file may be opened more than once, and therefore have several different file descriptors. Each file descriptor maintains its own file pointer, and each must be closed separately. If you open more than one channel at once with write permission, behavior is unspecified.
It is not strictly necessary to useopen for accessâall the other file commands can accept an alias; if the file is not open, they will open it, do the operation, and then close it. Explicitly opening and closing the file does have two potential advantages, however.
One is performance: if you are performing a number of operations on the same file, opening and closing it repeatedly could become expensive. It is cheaper to explicitly open the file, do the work, and then explicitly close it.
Two is ease of sequential read and write operations: because the file pointer tracks the progress through the file, reading or writing several pieces of data from the same file is a simple matter. Doing the same thing without using the file pointer requires calculating the data size yourself, which is not even possible in some cases.
Opens a URL with the appropriate program.
##### Syntax
##### Parameters
The URL to open.
This parameter exists only for historical reasons; it is no longer supported.
##### Result
None.
##### Examples
This example opens an Apple web page:
```
open location "http://www.apple.com"```
Returns the location of the specified application.
##### Syntax
##### Parameters
The application to locate. See theapplicationclass reference for possible ways to specify an application. You may also use one of the following identifiers:
The application executing the script, such as Script Editor.
The frontmost application.
The script itself. For script applications, this is the same ascurrent application, but for script documents, it is the location of the document.
Note:Some older applications may treatmeidentically tocurrent application.
The application of the current target.
The class of the returned location. If specified, must be one ofaliasortext.
alias
##### Result
The location of the specified application, as either analiasor atextobject containing the path.
##### Examples
```
path to application "TextEdit"```
```
--result: alias "Leopard:Applications:TextEdit.app:"```
```
path to --result: alias "Leopard:Applications:AppleScript:Script Editor.app:"```
```
path to me --result: same as above```
```
path to it --result: same as above```
```
path to frontmost application --result: same as above```
```
path to current application```
```
--result: same, but could be different for a script application```
Returns the location of the specified special folder.
##### Syntax
##### Parameters
The special folder for which to return the path. You may specify one of the following folders:
```
application support```
```
applications folder```
```
desktop```
```
desktop pictures folder```
```
documents folder```
```
downloads folder```
```
favorites folder```
```
Folder Action scripts```
```
fonts```
```
help```
```
home folder```
```
internet plugins```
```
keychain folder```
```
library folder```
```
modem scripts```
```
movies folder```
```
music folder```
```
pictures folder```
```
preferences```
```
printer descriptions```
```
public folder```
```
scripting additions```
```
scripts folder```
```
services folder```
```
shared documents```
```
shared libraries```
```
sites folder```
```
startup disk```
```
startup items```
```
system folder```
```
system preferences```
```
temporary items```
```
trash```
```
users folder```
```
utilities folder```
```
workflows folder```
The following folders are also defined, but are only meaningful when used withfrom Classic domain:
```
apple menu```
```
control panels```
```
control strip modules```
```
extensions```
```
launcher items folder```
```
printer drivers```
```
printmonitor```
```
shutdown folder```
```
speakable items```
```
stationery```
```
voices```
The domain in which to look for the specified folder. You may specify one of the following domains:
A folder in/System.
A folder in/Library.
A folder in/Network.
A folder in~, the userâs home folder.
A folder in the Classic Mac OS system folder. Only meaningful on systems that support Classic.
The default domain for the specified folder. This varies depending on the folder.
The class of the returned location.
alias
Create the folder if it doesnât exist? Your script may not have permission to create the folder (for example, asking to create something in the system domain), so your script should be prepared for that error.
true
##### Result
The location of the specified folder, as either analiasor atextobject containing the path.
##### Examples
```
path to desktop --result: alias "Leopard:Users:johndoe:Desktop:"```
```
path to desktop as string --result: "Leopard:Users:johndoe:Desktop:"```
Returns the location of the specified resource.
##### Syntax
##### Parameters
The name of the requested resource.
Analiasorfilespecifier that specifies the bundle containing the resource.
The current script bundle for a document-based script (ascptdbundle); otherwise, the current application.
The name of a subdirectory in the bundleâsResourcesdirectory.
##### Result
The location of the specified resource, as analias.
##### Examples
The following example shows how you can get the path to a.icnsfileâin this case, in the Finder application.
```
tell application "Finder"```
```
set gearIconPath to path to resource "Gear.icns"```
```
end```
```
--result: alias "HD:System:Library:CoreServices:Finder.app:Contents:Resources:Gear.icns"```
Returns a random number.
##### Syntax
##### Parameters
The lowest number to return. Can be negative.
The highest number to return. Can be negative.
An initial seed for the random number generator. Once called with any particular seed value,random numberwill always generate the same sequence of numbers. This can be useful when testing randomized algorithms: you can force it to behave the same way every time.
##### Result
A number between thefromandtolimits, including the limit values. Depending on the limit values, the result may be an integer or a real. If at least one limit is specified, and all specified limits are integers, the result is an integer. Otherwise, the result is a real, and may have a fractional part.
##### Examples
```
random number --result: 0.639215561057```
```
random number from 1 to 10 --result: 8```
##### Discussion
Random numbers are, by definition, random, which means that you may get the same number twice (or even more) in a row, especially if the range of possible numbers is small.
The numbers generated are only pseudo-random, and are not considered cryptographically secure.
If you need to select one of a set of objects in a relationship, usesomeobjectrather thanobject(random number from 1 to countobjects). See theArbitraryreference form for more details.
Reads data from a file.
##### Syntax
##### Parameters
The file to read from, as an alias, a file specifier, or anintegerfile descriptor. A file descriptor must be obtained as the result of an earlieropen for accesscall.
The byte position in the file to start reading from. The position is 1-based, so1is the first byte of the file,2the second, and so on. Negative integers count from the end of the file, so-1is the last byte,-2the second-to-last, and so on.
The current file pointer (seeopen for access) if the file is open, or the beginning of the file if not.
The number of bytes to read.
Read until the end of the file.
Stop reading at this byte position in the file; useeofto indicate the last byte. The position is 1-based, like thefromparameter.
A single character; read up to the next occurrence of that character. Thebeforecharacter is also read, but is not part of the result, so the nextreadwill start just after it.
A single character; read up to and including the next occurrence of that character.
A delimiter, such as a tab or return character, used to separate the data read into a list of text objects. The resulting items consist of the text between occurrences of the delimiter text. The delimiter is considered a separator, so a leading or trailing delimiter will produce an empty string on the other side. For example, the result of reading"axbxcx"using a delimiter of"x"would be{"a", "b", "c", ""}.
None;readreturns a single item.
Asusing delimiterabove, but all of the strings in the list count as delimiters.
Interpret the raw bytes read as this class. The most common ones control the use of three different text encodings:
The primary text encoding, as determined by the userâs language preferences set in the International preference panel. (For example, Mac OS Roman for English, MacJapanese for Japanese, and so on.)
UTF-16.
UTF-8. (SeeDouble Angle Bracketsfor information on chevron or ârawâ syntax.)
Any other class is possible, for exampledateorlist, but is typically only useful if the data was written using awritestatement specifying the same value for theasparameter.
text
##### Result
The data read from the file. If the file is open, the file pointer is advanced by the number of bytes read, so the nextreadcommand will start where the previous one left off.
##### Examples
The following example opens a file for read access, reads up to (and including) the first occurrence of".", closes the file, and displays the text it read. (See the Examples section for thewritecommand for how to create a similar file for reading.)
```
set fp to open for access file "Leopard:Users:myUser:NewFile"```
```
set myText to read fp until "."```
```
close access fp```
```
display dialog myText```
To read all the text in the file, replaceset myText to read fp until "."withset myText to read fp.
##### Discussion
At most one ofto,for,before, anduntilis allowed. Use ofbefore,until, orusing delimiter(s)will interpret the file first as text and then coerce the text to whatever is specified in theasparameter. Otherwise, it is treated as binary data (which may be interpreted as text if so specified.)
readcannot automatically detect the encoding used for a text file. If a file is not in the primary encoding, you must supply an appropriateasparameter.
When reading binary data,readalways uses big-endian byte order. This is only a concern if you are reading binary files produced by other applications.
Rounds a number to an integer.
##### Syntax
##### Parameters
The number to round.
The direction to round. You may specify one of the following rounding directions:
Rounds to the next largest integer. This is the same as the math âceilingâ function.
Rounds down to the next smallest integer. This is the same as the math âfloorâ function.
Rounds toward zero, discarding any fractional part. Also known as truncation.
Rounds to the nearest integer; .5 cases are rounded to the nearest even integer. For example, 1.5 rounds to 2, 0.5 rounds to 0. Also known as âunbiased roundingâ or âbankersâ rounding.â See Discussion for details.
Rounds to the nearest integer; .5 cases are rounded away from zero. This matches the rules commonly taught in elementary mathematics classes.
to nearest
##### Result
The rounded value, as anintegerif it is within the allowable range (±229), or as arealif not.
##### Examples
Rounding up or down is not the same as rounding away from or toward zero, though it may appear so for positive numbers. For example:
```
round 1.1 rounding down --result: 1```
```
round -1.1 rounding down --result: -2```
To round to the nearest multiple of something other than 1, divide by that number first, round, and then multiply. For example, to round a number to the nearest 0.01:
```
set x to 5.1234```
```
set quantum to 0.01```
```
(round x/quantum) * quantum --result: 5.12```
##### Discussion
The definition ofto nearestis more accurate thanas taught in school, but may be surprising if you have not seen it before. For example:
```
round 1.5 --result: 2```
```
round 0.5 --result: 0```
Rounding 1.5 to 2 should come as no surprise, butas taught in schoolwould have rounded 0.5 up to 1. The problem is that when dealing with large data sets or with many subsequent rounding operations, always rounding up introduces a slight upward skew in the results. The round-to-even rule used byto nearesttends to reduce the total rounding error, because on average an equal portion of numbers will round down as will round up.
Executes therunhandler of the specified target.
To run an application, it must be on a local or mounted volume. If the application is already running, the effect of theruncommand depends on the application. Some applications are not affected; others repeat their startup procedures each time they receive aruncommand.
Theruncommand launches an application as hidden; useactivateto bring the application to the front.
For ascriptobject, theruncommand causes either the explicit or the implicitrunhandler, if any, to be executed. For related information, seerun Handlers.
##### Syntax
##### Parameters
Ascriptorapplicationobject.
it(the current target)
##### Result
The result, if any, returned by the specified objectâsrunhandler.
##### Examples
```
run application "TextEdit"```
```
tell application "TextEdit" to run```
```
run myScript --where myScript is a script object```
For information about using theruncommand withscriptobjects, seeSending Commands to Script Objects.
##### Discussion
To specify an application to run, you can supply a string with only the application name, as shown in the Examples section. Or you can specify a location more precisely, using one of the forms described inAliases and Files. For examples of other ways to specify an application, see theapplicationclass.
It is not necessary to explicitly tell an application torunbefore sending it other commands; AppleScript will do that automatically. To launch an application without invoking its usual startup behavior, use thelaunchcommand. For further details, seeCalling a Script Application From a Script.
Runs a specified script or script file.
See alsostore script.
##### Syntax
##### Parameters
The script text, or analiasorfilespecifier that specifies the script file to run.
A list of parameter values to be passed to the script.
The scripting component to use.
"AppleScript"
##### Result
The result of the scriptâsrunhandler.
##### Examples
The following script targets the application Finder, escaping the double quotes around the application name with the backslash character (for more information on using the backslash, see the Special String Characters section in thetextclass description):
```
run script "get name of front window of app \"Finder\"" --result: a window name```
This example executes a script stored on disk:
```
set scriptAlias to "Leopard:Users:myUser:Documents:savedScript.scptd:" as alias```
```
run script scriptAlias --result: script is executed```
Speaks the specified text.
##### Syntax
##### Parameters
The text to speak.
The text to display in the feedback window, if different from the spoken text. This parameter is ignored unless Speech Recognition is turned on (in System Preferences).
The voice to speak withâfor example:"Zarvox".
You can use any of the voices from the System Voice pop-up on the Text to Speech tab in the Speech preferences pane.
The current System Voice (set in the Speech panel in System Preferences.
Should the command wait for speech to complete before returning? This parameter is ignored unless Speech Recognition is turned on (in System Preferences).
true
Analiasorfilespecifier to anAIFFfile (existing or not) to contain the sound output. You can only use analiasspecifier if the file exists. If this parameter is specified, the sound is not played audibly, only saved to the file.
None; the text is spoken out loud, and no file is saved.
##### Result
None.
##### Examples
```
say "You are not listening to me!" using "Bubbles" -- result: spoken in Bubbles```
The following example saves the spoken text into a sound file:
```
set soundFile to choose file name -- specify name ending in ".aiff"```
```
--result: a file URL```
```
say "I love oatmeal." using "Victoria" saving to soundFile```
```
--result: saved to specified sound file```
Returns a list of the names of all currently available scripting components, such as the AppleScript component.
##### Syntax
##### Result
Alistoftextitems, one for each installed scripting component.
##### Examples
```
scripting components --result: {"AppleScript"}```
##### Discussion
A scripting component is a software component, such as AppleScript, that conforms to the Open Scripting Architecture (OSA) interface. The OSA provides an abstract interface for applications to compile, execute, and manipulate scripts without needing to know the details of the particular scripting language. Each scripting language corresponds to a single scripting component.
Assigns one or more values to one or more variables.
##### Syntax
##### Parameters
The name of the variable or pattern of variables in which to store the value or pattern of values. Patterns can be lists or records.
The expression whose value is to be set. It can evaluate to any type of object or value.
##### Result
The value assigned.
##### Examples
setmay be used to create new variables:
```
set myWeight to 125```
...assign new values to existing variables:
```
set myWeight to myWeight + 23```
...change properties or elements of objects, such as lists:
```
set intList to {1, 2, 3}```
```
set item 3 of intList to 42```
...or application-defined objects:
```
tell application "Finder" to set name of startup disk to "Happy Fun Ball"```
As mentioned in the Discussion, setting one variable to another makes both variables refer to the exact same object. If the object is mutable, that is, it has writable properties or elements, changes to the object will appear in both variables:
```
set alpha to {1, 2, {"a", "b"}}```
```
set beta to alpha```
```
set item 2 of item 3 of alpha to "change" --change the original variable```
```
set item 1 of beta to 42 --change a different item in the new variable```
```
{alpha, beta}```
```
--result: {{42, 2, {"a", "change"}}, {42, 2, {"a", "change"}}}```
Both variables show the same changes, because they both refer to the same object. Compare this with the similar example incopy. Assigning a new object to a variable is not the same thing as changing the object itself, and does not affect any other variables that refer to the same object. For example:
```
set alpha to {1, 2, 3}```
```
set beta to alpha --result: beta refers to the same object as alpha```
```
set alpha to {4, 5, 6}```
```
--result: assigns a new object to alpha; this does not affect beta.```
```
{alpha, beta}```
```
--result: {{4, 5, 6}, {1, 2, 3}}```
setcan assign several variables at once using a pattern, which may be a list or a record. For example:
```
tell application "Finder" to set {x, y} to position of front window```
Sinceposition of front windowevaluates to a list of two integers, this setsxto the first item in the list andyto the second item.
You can think of pattern assignment as shorthand for a series of simple assignments, but that is not quite accurate, because the assignments are effectively simultaneous. That means that you can use pattern assignment to exchange two variables:
```
set {x, y} to {1, 2} --now x is 1, and y is 2.```
```
set {x, y} to {y, x} --now x is 2, and y is 1.```
To accomplish the second statement using only simple assignments, you would need a temporary third variable.
For more information on using the set command, including a more complex pattern example, seeDeclaring Variables with the set Command.
##### Discussion
Using thesetcommand to assign a value to a variable causes the variable to refer to the original value. In a sense, it creates a new name for the same object. If multiple variables refer to a mutable object (that is, one with writable properties or elements, such as a list orscriptobject), changes to the object are observable through any of the variables. If you want a separate copy, use thecopycommand. This sharing only applies to values in AppleScript itself; it does not apply to values in other applications. Changing the object a variable refers to is not the same as altering the object itself, and does not affect other variables that refer to the same object.
Sets the length of a file, in bytes.
##### Syntax
##### Parameters
The file to set the length of, as an alias, a file specifier, or as an integer file descriptor, which must be obtained as the result of an earlieropen for accesscall.
The new length of the file, in bytes. If the new length is shorter than the existing length of the file, any data beyond that position is lost. If the new length is longer, the contents of the new bytes are unspecified.
##### Result
None.
Signals a âwrite permissionâ error if the file was opened usingopen for accesswithout write permission.
##### Examples
If you want to completely replace the contents of an existing file, the first step must be to change its length to zero:
```
set theFile to choose file with prompt "Choose a file to clobber:"```
```
set eof theFile to 0```
Places data on the clipboard.
##### Syntax
##### Parameters
The data (of any type) to place on the clipboard.
##### Result
None.
##### Examples
The following script places text on the clipboard, then retrieves the text in TextEdit with athe clipboardcommand:
```
set the clipboard to "Important new text."```
```
tell application "TextEdit"```
```
activate --make sure TextEdit is running```
```
set clipText to the clipboard --result: "Important new text."```
```
--perform operations with retrieved text```
```
end tell```
##### Discussion
It is not necessary to use the clipboard to move data between scriptable applications. You can simplygetthe data from the first application into a variable andsetthe appropriate data in the second application.
Sets the sound output, input, and alert volumes.
##### Syntax
##### Parameters
The sound output volume, a real number from 0 to 7.
Important:This parameter is deprecated; if specified, all other parameters will be ignored.
The sound output volume, an integer from 0 to 100.
None; the output volume is not changed.
The sound input volume, an integer from 0 to 100.
None; the input volume is not changed.
The alert input volume, an integer from 0 to 100.
None; the alert volume is not changed.
Should the sound output be muted?
None; the output muting is not changed.
##### Result
None.
##### Examples
The following example saves the current volume settings, before increasing the output volume, saying some text, and restoring the original value:
```
set savedSettings to get volume settings```
```
-- {output volume:32, input volume:70, alert volume:78, output muted:false}```
```
set volume output volume 90```
```
say "This is pretty loud."```
```
set volume output volume (output volume of savedSettings)```
```
delay 1```
```
say "That's better."```
Stores ascriptobject into a file.
See alsorun script.
##### Syntax
##### Parameters
Thescriptobject to store.
Analiasorfilespecifier that specifies the file to store thescriptobject in.
None; a standard Save As dialog will be presented to allow the user to choose where to save thescriptobject.
Allow overwriting an existing file? You may specify one of the following constants:
Overwrite without asking.
Never overwrite; signal an error if the file exists.
Present a dialog asking the user what to do; the options are Replace (overwrite the file), Cancel (signal a âuser canceledâ error), or Save As (save to a different location).
##### Result
None.
##### Examples
This example stores a script on disk, using the Save As dialog to specify a location on the desktop and the namestoredScript. It then creates an alias to the stored script and runs it withrun script:
```
script test```
```
display dialog "Test"```
```
end script```
```
```
```
store script test --specify "Leopard:Users:myUser:Desktop:storedScript"```
```
```
```
set localScript to alias "Leopard:Users:myUser:Desktop:storedScript" run script localScript --result: displays dialog "Test"```
Thestore scriptcommand stores only the contents of the scriptâin this case, the one statement,display dialog "Test". It does not store the beginning and ending statements of the script definition.
Summarizes the specified text or text file.
##### Syntax
##### Parameters
Thetext, or analiasto a text file, to summarize.
The number of sentences desired in the summary.
##### Result
Atextobject containing a summarized version of the text or file.
##### Examples
This example summarizes Lincolnâs famous Gettysburg Address down to one sentenceâa tough job even for AppleScript:
```
set niceSpeech to "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.```
```
Now we are engaged in a great civil war, testing whether that nation, or any nation, so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.```
```
But, in a larger sense, we can not dedicateâwe can not consecrateâwe can not hallowâthis ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before usâthat from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotionâthat we here highly resolve that these dead shall not have died in vainâthat this nation, under God, shall have a new birth of freedomâand that government of the people, by the people, for the people, shall not perish from the earth."```
```
set greatSummary to summarize niceSpeech in 1```
```
display dialog greatSummary --result: displays one inspiring sentence```
Get environment variables or attributes of this computer.
##### Syntax
##### Parameters
The attribute to test: either a Gestalt value or a shell environment variable name. Gestalt values are described inGestalt Manager Reference.
If the attribute is omitted,system attributewill return a list of the names of all currently defined environment variables.
For Gestalt values, an integer mask that is bitwise-ANDed with the Gestalt response. If the result is non-zero,system attributereturnstrue, otherwisefalse.
For environment variables, this parameter is ignored.
None;system attributereturns the original Gestalt response code.
##### Result
If the attribute specified is a Gestalt selector, either the Gestalt response code ortrueorfalsedepending on thehasparameter.
If the attribute specified is an environment variable, the value of that variable, or an empty string ("") if it is not defined.
If no attribute is supplied, a list of all defined environment variables.
##### Examples
To get the current shell:
```
system attribute "SHELL" --result: "/bin/bash" (for example)```
To get a list of all defined environment variables:
```
system attribute```
```
(* result: (for example)```
```
{"PATH", "TMPDIR", "SHELL", "HOME", "USER", "LOGNAME", "DISPLAY", "SSH_AUTH_SOCK", "Apple_PubSub_Socket_Render", "__CF_USER_TEXT_ENCODING", "SECURITYSESSIONID", "COMMAND_MODE"}```
```
*)```
Gets information about the system.
##### Syntax
##### Result
A record containing various information about the system and the current user. This record contains the following fields:
The version number of AppleScript, for example,"2.0". This can be useful for testing for the existence of AppleScript features. When comparing version numbers, useconsidering numeric stringsto make them compare in numeric order, since standard lexicographic ordering would consider"1.9"to come after"1.10".
The version number of AppleScript Studio, for example,"1.5".
Note:AppleScript Studio is deprecated in OS X v10.6.
The version number of OS X, for example,"10.5.1".
The current userâs short name, for example,"hoser". This is set in the Advanced Options panel in the Accounts preference pane, or in the âShort Nameâ field when creating the account. This is also available from System Events usingname of current user.
The current userâs long name, for example,"Random J. Hoser". This is the âUser Nameâ field in the Accounts preference pane, or in the âNameâ field when creating the account. This is also available from System Events usingfull name of current user.
The current userâs user ID. This is set in the Advanced Options panel in the Accounts preference pane.
The current userâs locale code, for example"en_US".
The location of the current userâs home folder. This is also available from Finderâshomeproperty, or System Eventsâhome folderproperty.
The name of the boot volume, for example,"Macintosh HD". This is also available from Finder or System Events usingname of startup disk.
The computerâs name, for example"mymac". This is the âComputer Nameâ field in the Sharing preference pane.
The computerâs DNS name, for example"mymac.local".
The computerâs IPv4 address, for example"192.201.168.13".
The MAC address of the primary Ethernet interface, for example"00:1c:63:91:4e:db".
The CPU type, for example"Intel 80486".
The clock speed of the CPU in MHz, for example2400.
The amount of physical RAM installed in the computer, in megabytes (MB), for example2048.
##### Examples
```
system info --result: long record of information```
Returns the contents of the clipboard.
##### Syntax
##### Parameters
The type of data desired.the clipboardwill attempt to find that âflavorâ of data on the clipboard; if it is not found, it will attempt to coerce whatever flavor is there.
##### Result
The data from the clipboard, which can be of any type.
##### Examples
The following script places text on the clipboard, and then appends the clipboard contents to the frontmost TextEdit document:
```
```
```
set the clipboard to "Add this sentence at the end."```
```
tell application "TextEdit"```
```
activate --make sure TextEdit is running```
```
make new paragraph at end of document 1 with data (return & the clipboard)```
```
end tell```
##### Discussion
It is not necessary to use the clipboard to move data between scriptable applications. You can simplygetthe data from the first application into a variable andsetthe appropriate data in the second application.
Returns the difference between local time and GMT (Greenwich Mean Time) or Universal Time, in seconds.
##### Syntax
##### Result
Theintegernumber of seconds difference between the current time zone and Universal Time.
##### Examples
The following example computes the time difference between the current location and Cupertino:
```
set localOffset to time to GMT --local difference, in seconds```
```
set cupertinoOffset to -8.0 * hours```
```
--doesn't account for Daylight Savings; may actually be -7.0.```
```
set difference to (localOffset - cupertinoOffset) / hours```
```
display dialog ("Hours to Cupertino: " & difference)```
Writes data to a specified file.
##### Syntax
##### Parameters
The data to write to the file. This is typicallytext, but may be of any type. When reading the data back, thereadcommand must specify the same type, or the results are undefined.
The file to write to, as an alias, a file specifier, or anintegerfile descriptor. A file descriptor must be obtained as the result of an earlieropen for accesscall.
The byte position in the file to start reading from. The position is 1-based, so1is the first byte of the file,2the second, and so on. Negative integers count from the end of the file, so-1is the last byte,-2the second-to-last, and so on. The constanteofis the position just after the last byte; use this to append data to the file.
The current file pointer (seeopen for access) if the file is open, or the beginning of the file if not.
The number of bytes to write.
Write all the data provided.
Write the data as this class. The most common ones control the use of three different text encodings:
The primary text encoding, as determined by the userâs language preferences set in the International preference panel. (For example, Mac OS Roman for English, MacJapanese for Japanese, and so on.)
UTF-16.
UTF-8.
Any other class is possible, for exampledateorlist, but is typically only useful if the data will be read using areadstatement specifying the same value for theasparameter.
The class of the supplied data. See Special Considerations.
##### Result
None. If the file is open,writewill advance the file pointer by the number of bytes written, so the nextwritecommand will start writing where the last one ended.
Signals an error if the file is open without write permission, or if there is any other problem that prevents writing to the file, such as a lack of disk space.
##### Examples
The following example opens a file with write permission, creating it if it doesnât already exist, writes text to it, and closes it.
```
set fp to open for access file "HD:Users:myUser:NewFile" with write permission```
```
write "Some text. And some more text." to fp```
```
close access fp```
##### Special Considerations
As specified above,writewith noasparameter writes as the class of the supplied data, which means that in AppleScript 2.0writealways writestextdata using the primary encoding. Prior to 2.0,stringandUnicode textwere distinct types, which meant that it would use primary encoding forstringand UTF-16 forUnicode text. For reliable results when creating scripts that will run on both 2.0 and pre-2.0, always specify the encoding explicitly usingas textoras Unicode text, as appropriate.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Handler Reference
This chapter provides reference for handlers, which are defined and introduced inAbout Handlers. It describes the types of parameters you can use with handlers and how you invoke them. It also describes thecontinueandreturnstatements, which you use to control the flow of execution in handlers.
Acontinuestatement causes AppleScript to invoke the handler with the same name in the parent of the current handler. If there is no such handler in the parent, AppleScript looks up the parent chain, ending with the current application.
Acontinuestatement is like a handler call, in that after execution completes in the new location, it resumes with the statement after thecontinuestatement.
##### Syntax
```
continue handlerName [ parameterList ]```
##### Placeholders
A required identifier that specifies the name of the current handler (which is also the name of the handler in which to continue execution).
The list of parameters to be passed tohandlerName.
The list must follow the same format as the parameter definitions in the handler definition for the command. For handlers with labeled parameters, this means that the parameter labels must match those in the handler definition. For handlers with positional parameters, the parameters must appear in the correct order.
You can list the parameter variables that were specified in the original command (and thus the original values) or you can list values that may differ from those of the original variables.
##### Examples
You can write a handler that overrides an AppleScript command but uses acontinuestatement to pass control on to the AppleScript command if desired:
```
on beep numTimes```
```
set x to display dialog "Start beeping?" buttons {"Yes", "No"}```
```
if button returned of x is "Yes" then ¬```
```
continue beep numTimes -- Let AppleScript handle the beep.```
```
-- In this example, nothing to do after returning from the continue.```
```
end beep```
```
```
```
beep 3 --result: local beep handler invoked; shows dialog before beeping```
```
tell my parent to beep 3 -- result: AppleScript beep command invoked```
When AppleScript encounters the statementbeep 3, it invokes the localbeephandler, which displays a dialog. If the user clicks Yes, the handler uses acontinuestatement to pass thebeepcommand to the scriptâs parent (AppleScript), which handles the command by beeping. If the user clicks No, it does not continue thebeepcommand, and no sound is heard.
The final statement,tell my parent to beep 3, shows how to directly invoke the AppleScriptbeepcommand, rather than the local handler.
For an example that uses acontinuestatement to exit a script handler and return control to the applicationâs defaultquithandler, seequit Handlers.
For additional examples, seeUsing the continue Statement in Script Objects.
Areturnstatement exits a handler and optionally returns a specified value. Execution continues at the place in the script where the handler was called.
##### Syntax
```
return [ expression ]```
##### Placeholders
Represents the value to return.
##### Examples
The following statement, inserted in the body of a handler, returns the integer2:
```
return 2 -- returns integer value 2```
If you include areturnstatement without an expression, AppleScript exits the handler immediately and no value is returned:
```
return -- no value returned```
See other sections throughoutHandler Referencefor more examples of scripts that use thereturnstatement.
##### Discussion
If a handler does not include areturnstatement, AppleScript returns the value returned by the last statement. If the last statement doesnât return a value, AppleScript returns nothing.
When AppleScript has finished executing a handler (that is, when it executes areturnstatement or the last statement in the handler), it passes control to the place in the script immediately after the place where the handler was called. If a handler call is part of an expression, AppleScript uses the value returned by the handler to evaluate the expression.
It is often considered good programming practice to have just onereturnstatement and locate it at the end of a handler. Doing so can provide the following benefits:
- The script is easier to understand.
The script is easier to understand.
- The script is easier to debug.
The script is easier to debug.
- You can place cleanup code in one place and make sure it is executed.
You can place cleanup code in one place and make sure it is executed.
In some cases, however, it may make more sense to use multiplereturnstatements. For example, theminimumValuehandler inHandler Syntax (Positional Parameters)is a simple script that uses tworeturnstatements.
For related information, seeAppleScript Error Handling.
A handler is a collection of statements that can be invoked by name. This section describes the syntax for handlers that use labeled parameters.
Labeled parameters are identified by their labels and can be listed in any order.
##### Syntax
```
( on | to ) handlerName ¬ [ [ of | in ] directParamName ] ¬ [ ASLabel userParamName ]... ¬ [ given userLabel:userParamName [, userLabel:userParamName ]...] [ statement ]...end [ handlerName ]```
##### Placeholders
An identifier that names the handler.
An identifier for the direct parameter variable. If it is included,directParamNamemust be listed immediately after the command name. The wordoforinbeforedirectParamNameis required in user-defined handlers, but is optional in terminology-defined handlers (for example, those defined by applications).
If a user-defined handler includes a direct parameter, the handler must also include at least one variable parameter.
An AppleScript-defined label. The available labels are:about,above,against,apart from,around,aside from,at,below,beneath,beside,between,by,for,from,instead of,into,on,onto,out of,over,since,thru(orthrough),under. These are the only labels that can be used without the special labelgiven.Each label must be unique among the labels for the handler (that is, you cannot use the same label for more than one parameter).
An identifier for a user-defined label, associated with a user-defined parameter. Each label must be unique.
The firstuserLabel-userParamNamepair must follow the wordgiven; any additional pairs are separated by commas.
An identifier for a parameter variable.
Any AppleScript statement. These statements can include definitions ofscriptobjects, each of which, like anyscriptobject, can contain handlers and otherscriptobjects. However, you cannot declare another handler within a handler, except within ascriptobject.
Handlers often contain areturnstatement.
##### Examples
For examples and related conceptual information, seeHandlers with Labeled Parameters.
##### Discussion
A handler written to respond to an application command (like those inHandlers in Script Applications) need not include all of the possible parameters defined for that command. For example, an application might define a command with up to five possible parameters, but you could define a handler for that command with only two of the parameters.
If a script calls a handler with more parameters than are specified in the handler definition, the extra parameters are ignored.
This section describes the syntax for calling a handler with labeled parameters.
##### Syntax
```
handlerName ¬
[ [ of | in ] directParam ] ¬
[ [ ASLabel paramValue ...] ¬
| [ with labelForTrueParam [, labelForTrueParam ]... ¬
[ ( and | , ) labelForTrueParam ] ] ¬
| [ without labelForFalseParam [, labelForFalseParam ]...] ¬
[ ( and | , ) labelForFalseParam ] ] ¬
| [ given userLabel:paramValue [, userLabel:paramValue ]...]... ```
##### Placeholders
An identifier that names the handler.
Any valid expression. The expression for the direct parameter must be listed first if it is included at all.
One of the following AppleScript-defined labels used in the definition of the handler:about,above,against,apart from,around,aside from,at,below,beneath,beside,between,by,for,from,instead of,into,on,onto,out of,over,since,thru(orthrough),under.
The value of a parameter, which can be any valid expression.
The label for a Boolean parameter whose value istrue. You use this form inwithclauses. Because the valuetrueis implied by the wordwith, you provide only the label, not the value. For an example, see thefindNumbershandler inHandlers with Labeled Parameters.
The label for a Boolean parameter whose value isfalse. You use this form inwithoutclauses. Because the valuefalseis implied by the wordwithout, you provide only the label, not the value.
Any parameter label used in the definition of the handler that is not among the labels forASLabel. You must use the special labelgivento specify these parameters. For an example, see thefindNumbershandler below.
##### Examples
For examples, seeHandlers with Labeled Parameters.
##### Discussion
When you call a handler with labeled parameters, you supply the following:
- The handler name.
The handler name.
- A value for the direct parameter, if the handler has one. It must directly follow the handler name.
A value for the direct parameter, if the handler has one. It must directly follow the handler name.
- One label-value pair for each AppleScript-defined label and parameter defined for the handler.
One label-value pair for each AppleScript-defined label and parameter defined for the handler.
- One label-value pair for each user-defined label and parameter defined for the handler thatis nota boolean value.The first pair is preceded by the wordgiven; a comma precedes each additional pair. The order of the pairs does not have to match the order in the handler definition.
One label-value pair for each user-defined label and parameter defined for the handler thatis nota boolean value.
The first pair is preceded by the wordgiven; a comma precedes each additional pair. The order of the pairs does not have to match the order in the handler definition.
- For each user-defined label and parameter defined for the handler thatisa boolean value, you can either:Supply the label, followed by a boolean expression (as with non-boolean parameters); for example:given rounding:trueUse a combination ofwithandwithoutclauses, as shown in the following examples:with rounding, smoothing and curlingwith rounding without smoothing, curlingNote:AppleScript automatically converts between some forms when you compile. For example,given rounding:trueis converted towith rounding, andwith rounding, smoothingis converted towith rounding and smoothing.
For each user-defined label and parameter defined for the handler thatisa boolean value, you can either:
- Supply the label, followed by a boolean expression (as with non-boolean parameters); for example:given rounding:true
Supply the label, followed by a boolean expression (as with non-boolean parameters); for example:
```
given rounding:true```
- Use a combination ofwithandwithoutclauses, as shown in the following examples:with rounding, smoothing and curlingwith rounding without smoothing, curlingNote:AppleScript automatically converts between some forms when you compile. For example,given rounding:trueis converted towith rounding, andwith rounding, smoothingis converted towith rounding and smoothing.
Use a combination ofwithandwithoutclauses, as shown in the following examples:
```
with rounding, smoothing and curling```
```
with rounding without smoothing, curling```
Note:AppleScript automatically converts between some forms when you compile. For example,given rounding:trueis converted towith rounding, andwith rounding, smoothingis converted towith rounding and smoothing.
A handler is a collection of statements that can be invoked by name. This section describes the syntax for handlers that use positional parameters.
Important:The parentheses that surround the parameter list in the following definition are part of the syntax.
##### Syntax
```
on | to handlerName ( [ userParamName [, userParamName ]...] )
   [ statement ]...
end [ handlerName ] ```
##### Placeholders
An identifier that names the handler.
An identifier for a user-defined parameter variable.
Any AppleScript statement, including global or local variable declarations. For information about the scope of local and global variables, seeScope of Variables and Properties.
##### Examples
For examples and related conceptual information, seeHandlers with Positional Parameters.
A call for a handler with positional parameters must list the parameters in the same order as they are specified in the handler definition.
##### Syntax
```
handlerName( [ paramValue [, paramValue ]...] )```
##### Placeholders
An identifier that names the handler.
The value of a parameter, which can be any valid expression. If there are two or more parameters, they must be listed in the same order in which they were specified in the handler definition.
##### Examples
For examples, seeHandlers with Positional Parameters
##### Discussion
When you call a handler with positional parameters, you supply the following:
- The handler name.
The handler name.
- An opening and closing parenthesis.
An opening and closing parenthesis.
- If the handler has any parameters, then you also list, within the parentheses, the following:One value for each parameter defined for the handler. The value can be any valid expression.
If the handler has any parameters, then you also list, within the parentheses, the following:
One value for each parameter defined for the handler. The value can be any valid expression.
A handler is a collection of statements that can be invoked by name. This section describes the syntax for handlers that use interleaved parameters.
##### Syntax
```
on | tohandlerNamePart:userParamName [namePart:userParamName ]... )Â Â Â [ statement ]...end [ handlerName ] ```
##### Placeholders
An identifier that, combined with the other parts, forms the handler name.
An identifier for a user-defined parameter variable.
Any AppleScript statement, including global or local variable declarations. For information about the scope of local and global variables, seeScope of Variables and Properties.
##### Examples
For examples and related conceptual information, seeHandlers with Interleaved Parameters.
A call for a handler with interleaved parameters must list the parameters in the same order as they are specified in the handler definition.
##### Syntax
```
( tell scriptObject to | scriptObject's | my ) handlerNamePart:paramValue [ namePart:paramValue ]...] ```
##### Placeholders
A script object to direct the handler call to, which can be any valid expression.
An identifier that names the handler.
The value of a parameter, which can be any valid expression. If there are two or more parameters, they must be listed in the same order in which they were specified in the handler definition.
##### Examples
For examples, seeHandlers with Positional Parameters
##### Discussion
When you call a handler with positional parameters, you supply the following:
- A script object to direct the handler call to, either usingtellscriptto,script's, ormy, equivalent totell me to.
A script object to direct the handler call to, either usingtellscriptto,script's, ormy, equivalent totell me to.
- The first handler name part.
The first handler name part.
- A value for the first parameter.
A value for the first parameter.
- For each additional parameter, you also list the following:The next name part, followed by a colon and a value for that parameter. The value can be any valid expression.
For each additional parameter, you also list the following:
The next name part, followed by a colon and a value for that parameter. The value can be any valid expression.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Working with Errors
This appendix provides a detailed example of handling errors withtry Statementsanderror Statements. It shows how to use atrystatement to check for bad data and other errors, and anerrorstatement to pass on any error that canât be handled. It also shows how to check for just a particular error number that you are interested in.
## Catching Errors in a Handler
TheSumIntegerListhandler expects a list of integers. If any item in the passed list is not an integer,SumIntegerListsignalserror number 750and returns 0. The handler includes an error handler that displays a dialog if the error number is equal to 750; if the error number is not equal to 750, the handler resignals the error with anerrorstatement so that other statements in the call chain can handle the unknown error.If no statement handles the error, AppleScript displays an error dialog and execution stops.
```
on SumIntegerList from itemList```
```
try```
```
-- Initialize return value.```
```
set integerSum to 0```
```
-- Before doing sum, check that all items in list are integers.```
```
if ((count items in itemList) is not equal to ¬```
```
(count integers in itemList)) then```
```
-- If all items arenât integers, signal an error.```
```
error number 750```
```
end if```
```
-- Use a repeat statement to sum the integers in the list.```
```
repeat with currentItem in itemList```
```
set integerSum to integerSum + currentItem```
```
end repeat```
```
return integerSum -- Successful completion of handler.```
```
on error errStr number errorNumber```
```
-- If our own error number, warn about bad data.```
```
if the errorNumber is equal to 750 then```
```
display dialog "All items in the list must be integers."```
```
return integerSum -- Return the default value (0).```
```
else```
```
-- An unknown error occurred. Resignal, so the caller```
```
-- can handle it, or AppleScript can display the number.```
```
error errStr number errorNumber```
```
end if```
```
end try```
```
end SumIntegerList```
TheSumIntegerListhandler handles various error conditions. For example, the following call completes without error:
```
set sumList to {1, 3, 5}```
```
set listTotal to SumIntegerList from sumList --result: 9```
The following call passes bad dataâthe list contains an item that isnât an integer:
```
set sumList to {1, 3, 5, "A"}```
```
set listTotal to SumIntegerList from sumList```
```
if listTotal is equal to 0 then```
```
-- the handler didnât total the list;```
```
-- do something to handle the error (not shown)```
```
end if```
TheSumIntegerListroutine checks the list and signals an error 750 because the list contains at least one non-integer item. The routineâs error handler recognizes error number 750 and puts up a dialog to describe the problem. TheSumIntegerListroutine returns 0. The script checks the return value and, if it is equal to 0, does something to handle the error (not shown).
Suppose some unknown error occurs whileSumIntegerListis processing the integer list in the previous call. When the unknown error occurs, theSumIntegerListerror handler calls theerrorcommand to resignal the error. Since the caller doesnât handle it, AppleScript displays an error dialog and execution halts. TheSumIntegerListroutine does not return a value.
Finally, suppose the caller has its own error handler, so that if the handler passes on an error, the caller can handle it. Assume again that an unknown error occurs whileSumIntegerListis processing the integer list.
```
try```
```
set sumList to {1, 3, 5}```
```
set listTotal to SumIntegerList from sumList```
```
on error errMsg number errorNumber```
```
display dialog "An unknown error occurred: " & errorNumber as text```
```
end try```
In this case, when the unknown error occurs, theSumIntegerListerror handler calls theerrorcommand to resignal the error. Because the caller has an error handler, it is able to handle the error by displaying a dialog that includes the error number. Execution can continue if it is meaningful to do so.
## Simplified Error Checking
AppleScript provides a mechanism to streamline the way you can catch and handle individual errors. It is often necessary for a script to handle a particular error, but not others. It is possible to catch an error, check for the error number you are interested in, and use an error statement to resignal for other errors. For example:
```
try```
```
open for access file "MyFolder:AddressData" with write permission```
```
on error msg number n from f to t partial result p```
```
if n = -49 then -- File already open error```
```
display dialog "I'm sorry but the file is already open."```
```
else```
```
error msg number n from f to t partial result p```
```
end if```
```
end try```
This script tries to open a file with write permission, but if the file is already opened, it just displays a dialog. However, you can instead implement this more concisely as:
```
try```
```
open for access file "MyFolder:AddressData" with write permission```
```
on error number -49```
```
display dialog "I'm sorry but the file is already open."```
```
end try```
In this version, there is no need to list themessage,from,to, orpartial resultparameters, in order to pass them along. If the error is not -49 (file is already open), this error handler will not catch the error, and AppleScript will pass the error to the next handler in an outer scope.
One drawback to this approach is that you must use a literal constant for the error number in theon errorparameter list. You can't use global variable or property names because the number must be known when the script is compiled.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Operators Reference
This chapter describes AppleScript operators. Anoperatoris a symbol, word, or phrase that derives a value from another value or pair of values. Anoperationis the evaluation of an expression that contains an operator. Anoperandis an expression from which an operator derives a value.
AppleScript provides logical and mathematical operators, as well as operators for containment, concatenation, and obtaining a reference to an object. Operators that operate on two values are calledbinary operators, while operators that operate on a single value are known asunary operators.
The first part of this chapter contains two tables:Table 9-1summarizes all of the operators that AppleScript uses, andTable 9-2shows the order in which AppleScript evaluates operators within expressions. The rest of the chapter shows how AppleScript evaluates representative operators in script expressions.
AppleScript operator
Description
Logical conjunction.
A binary logical operator that combines two Boolean values. The result istrueonly if both operands evaluate totrue.
AppleScript checks the left-hand operand first and, if its isfalse, ignores the right-hand operand. (This behavior is calledshort-circuiting.)
Class of operands:boolean
Class of result:boolean
Logical disjunction.
A binary logical operator that combines two Boolean values. The result istrueif either operand evaluates totrue.
AppleScript checks the left-hand operand first and, if its istrue, ignores the right-hand operand. (This behavior is called short-circuiting.)
Class of operands:boolean
Class of result:boolean
Concatenation.
A binary operator that joins two values. If the left-hand operand is atextobject, the result is atextobject (and only in this case does AppleScript try to coerce the value of the right-hand operand to match that of the left).
If the operand to the left is a record, the result is a record. If the operand to the left belongs to any other class, the result is a list.
For more information, see& (concatenation).
Class of operands: any
Class of result:list,record,text
is equal
equals
[is] equal to
Equality.
A binary comparison operator that results intrueif both operands have the same value. The operands can be of any class.
For more information, seeequal, is not equal to.
Class of operands:boolean
Class of result:boolean
â (Option-equal sign on U.S. keyboard)
is not
isn't
isn't equal [to]
is not equal [to]
doesn't equal
does not equal
Inequality.
A binary comparison operator that results intrueif its two operands have different values. The operands can be of any class.
For more information, seeequal, is not equal to.
Class of operands:boolean
Class of result:boolean
[is] greater than
comes after
is not less than or equal [to]
isn't less than or equal [to]
Greater than.
A binary comparison operator that results intrueif the value of the left-hand operand is greater than the value of the right-hand operand.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the left-hand operand.
For more information, seegreater than, less than.
Class of operands:date,integer,real,text
Class of result:boolean
[is] less than
comes before
is not greater than or equal [to]
isn't greater than or equal [to]
Less than.
A binary comparison operator that results intrueif the value of the left-hand operand is less than the value of the right-hand operand.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
For more information, seegreater than, less than.
Class of operands:date,integer,real,text
Class of result:boolean
â¥(Option-period on U.S. keyboard)
[is] greater than or equal [to]
is not less than
isn't less than
does not come before
doesn't come before
Greater than or equal to.
A binary comparison operator that results intrueif the value of the left-hand operand is greater than or equal to the value of the right-hand operand.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
The method AppleScript uses to determine which value is greater depends on the class of the operands.
Class of operands:date,integer,real,text
Class of result:boolean
â¤(Option-comma on U.S. keyboard)
[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.
A binary comparison operator that results intrueif the value of the left-hand operand is less than or equal to the value of the right-hand operand.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
The method AppleScript uses to determine which value is greater depends on the class of the operands.
Class of operands:date,integer,real,text
Class of result:boolean
start[s] with
begin[s] with
Starts with.
A binary containment operator that results intrueif the list ortextobject to its right matches the beginning of the list ortextobject to its left.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
For more information, seestarts with, ends with.
Class of operands:list,text
Class of result:boolean
end[s] with
Ends with.
A binary containment operator that results intrueif the list ortextobject to its right matches the end of the list ortextobject to its left.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
For more information, seestarts with, ends with.
Class of operands:list,text
Class of result:boolean
contain[s]
Containment.
A binary containment operator that results intrueif the list, record, ortextobject to its right matches any part of the list, record, ortextobject to its left.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the operand to the left.
For more information, seecontains, is contained by.
Class of operands:list,record,text
Class of result:boolean
does not contain
doesn't contain
Non-containment.
A binary containment operator that results intrueif the list, record, ortextobject to its right does not match any part of the list, record, ortextobject to its left.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the right-hand operand to the class of the left-hand operand.
For more information, seecontains, is contained by.
Class of operands:list,record,text
Class of result:boolean
is in
is contained by
Containment.
A binary containment operator that results intrueif the list, record, ortextobject to its left matches any part of the list, record, ortextobject to its right.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the left-hand operand to the class of the right-hand operand.
For more information, seecontains, is contained by.
Class of operands:list,record,text
Class of result:boolean
is not in
is not contained by
isn't contained by
Non-containment.
A binary containment operator that results intrueif the list, record, ortextobject to its left does not match any part of the list, record, ortextobject to its right.
Both operands must evaluate to values of the same class. If they donât, AppleScript attempts to coerce the left-hand operand to the class of the right-hand operand.
For more information, seecontains, is contained by.
Class of operands:list,record,text
Class of result:boolean
Multiplication.
A binary arithmetic operator that multiplies the number to its left and the number to its right.
Class of operands:integer,real
Class of result:integer,real
Addition.
A binary arithmetic operator that adds the number or date to its left and the number or date to its right. Only integers can be added to dates. AppleScript interprets such an integer as a number of seconds.
As a unary operator,+has no effect and is removed on compile.
Class of operands:date,integer,real
Class of result:date,integer,real
Subtraction.
A 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 on U.S. keyboard)
Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands:integer,real
Class of result:real
Integral division.
A binary arithmetic operator that divides the number to its left by the number to its right and returns the integral part of the answer as its result.
Class of operands:integer,real
Class of result:integer
Remainder.
A binary arithmetic operator that divides the number to its left by the number to its right and returns the remainder as its result.
Class of operands:integer,real
Class of result:integer,real
Exponentiation.
A binary arithmetic operator that raises the number to its left to the power of the number to its right.
Class of operands:integer,real
Class of result:real
Coercion (orobject conversion).
A binary operator that converts the left-hand operand to the class listed to its right.
Not all values can be coerced to all classes. The coercions that AppleScript can perform are listed inCoercion (Object Conversion). The additional coercions, if any, that an application can perform is listed in its dictionary.
Class of operands: The right-hand operand must be a class identifier or list of class identifiers; the left-hand operand must be a value that can be converted to that class or one of the listed classes.
Class of result: The class specified by the class identifier to the right of the operator
Negation.
A unary logical operator that results intrueif the operand to its right isfalse, andfalseif the operand istrue.
Class of operand:boolean
Class of result:boolean
[a] (ref [to] | reference to)
A reference to.
A unary operator that causes AppleScript to return areferenceobject that specifies the location of the operand to its right. A reference is evaluated at run time, not at compile time.
Seea reference tofor more information.
Class of operand: any class type
Class of result:reference
When evaluating expressions, AppleScript uses operator precedence to determine which operations are evaluated first. In the following expression, for example, AppleScript does not simply perform operations from left to rightâit performs the multiplication operation2 * 5first, because multiplication has higher precedence than addition.
```
12 + 2 * 5 --result: 22```
Table 9-2shows the order in which AppleScript performs operations. The column labeled âAssociativityâ indicates the order in the case where there are two or more operands of the same precedence in an expression. The word âNoneâ in the Associativity column indicates that you cannot have multiple consecutive occurrences of the operation in an expression. For example, the expression3 = 3 = 3is not legal because the associativity for the equal operator is ânone.â
To evaluate expressions with multiple unary operators of the same order, AppleScript applies the operator closest to the operand first, then applies the next closest operator, and so on. For example, the expressionnot not not trueis evaluated asnot (not (not true)).
You can enforce the order in which AppleScript performs operations by grouping expressions in parentheses, which are evaluated first, starting with the innermost pair of parentheses.
Order
Operators
Associativity
Type of operator
Innermost to outermost
Grouping
Unary
Plus or minus sign for numbers
Right to left
Exponentiation
(note that this is different from standard math, in which exponentiation takes precedence over unary plus or minus)
Left to right
Multiplication and division
Left to right
Addition and subtraction
Left to right
Concatenation
Left to right
Coercion
None
Comparison
None
Equality and inequality
Unary
Logical negation
Left to right
Logical and
Left to right
Logical or
The following sections provide additional detail about how AppleScript evaluates operators in expressions:
- & (concatenation)
& (concatenation)
- a reference to
a reference to
- Para
Para
- contains, is contained by
contains, is contained by
- equal, is not equal to
equal, is not equal to
- greater than, less than
greater than, less than
- starts with, ends with
starts with, ends with
The concatenation operator (&) concatenatestextobjects, joinsrecordobjects into a record, and joins other objects into a list.
Table 9-1summarizes the use of use of this operator.
##### text
The concatenation of twotextobjects joins the characters from the left-handtextobject to the characters from the right-handtextobject, without intervening spaces. For example,"dump" & "truck"evaluates to thetextobject"dumptruck".
If the left-hand operand is atextobject, but the right-hand operand is not, AppleScript attempts to coerce the right-hand operand to atextobject. For example, when AppleScript evaluates the expression"Route " & 66it coerces the integer66to thetextobject"66", and the result is thetextobject"Route 66".
However, you get a different result if you reverse the order of the operands:
```
66 & "Route " --result: {66, "Route "} (a list)```
In the following example, the left-hand operand is atextobject and the right-hand operand is a list, so concatenation results in atextobject:
```
item 1 of {"This"} & {"and", "that"} -- "Thisandthat"```
##### record
The concatenation of two records joins the properties of the left-hand record to the properties of the right-hand record. If both records contain properties with the same name, the value of the property from the left-hand record appears in the result. For example, the result of the expression
```
{ name:"Matt", mileage:"8000" } & { name:"Steve", framesize:58 }```
```
{ name:"Matt", mileage:"8000", frameSize:58 }```
##### All Other Classes
Except for the cases described above fortextobjects andrecordobjects, the concatenation operator (&) joins lists. A non-list operand is considered to be a list containing that operand. The following example shows concatenation of two integers, a list and a text string, and a list and a record, respectively:
```
1 & 2 --result: {1, 2}```
```
{"this"} & "hello" --result: {"this", "hello"}```
```
{"this"} & {a:1, b:2} --result: {"this", 1, 2}```
If both the operands to be concatenated are lists, then the result is a list containing all the items in the left-hand list, followed by all the items in the right-hand list. For example:
```
{"This"} & {"and", "that"} --result: {"This", "and", "that"}```
```
{"This"} & item 1 of {"and", "that"} --result: {"This", "and"}```
To join two lists and create a list of lists, rather than a single list, you can enclose each list in two sets of brackets:
```
{{1, 2}} & {{3, 4}} --result: {{1, 2}, {3, 4}}```
For information on working efficiently with large lists, seelist.
Thea reference tooperator is a unary operator that returns areferenceobject. You can abbreviate this operator toa ref to, orref to, or even justref.
For related information, see thereferenceclass andObject Specifiers.
##### Examples
The following statement creates areferenceobject that contains an object specifier to the Finder startup disk:
```
tell app "Finder" to set diskRef to a ref to startup disk```
```
--result: startup disk of application "Finder"```
The following shows how to obtain a reference object that refers to an item in a list:
```
set itemRef to a reference to item 3 of {1, "hello", 755, 99}```
```
--result: item 3 of {1, "hello", 755, 99}```
```
set newTotal to itemRef + 45 --result: 800```
In the final line, AppleScript automatically resolves the object specifier contained in the referenceitemRefand obtains its value to use in the addition operation. To cause AppleScript to explicitly resolve areferenceobject, you can use itscontentsproperty:
```
contents of itemRef --result: 755```
The next examples demonstrate how using a reference object can result in a different outcome than accessing an object directly. The first example obtains a current track object from iTunes, gets the name, changes the track, then gets the name again:
```
tell application "iTunes"```
```
set curTrack to current track```
```
--result: file track id 2703 of user playlist id 2425```
```
-- of source id 46 of application "iTunes"```
```
display dialog (name of curTrack as string) -- "Shattered"```
```
next track -- play next song```
```
display dialog (name of curTrack as string) -- "Shattered"```
```
end tell```
BecausecurTrackis a specifictrackobject, its name doesnât change when the current track changes. But observe the result when using a reference to the current track:
```
tell application "iTunes"```
```
set trackRef to a reference to current track```
```
--result: current track of application "iTunes"```
```
display dialog (name of trackRef as string) -- "Shattered"```
```
next track -- play next song```
```
display dialog (name of trackRef as string) -- "Strange Days"```
```
end tell```
BecausetrackRefis areferenceobject containing an object specifier, the specifier identifies the new track when the current track changes.
Theasoperator converts, orcoerces, a value of one class to a value of another class. Not all values are coercible to all classes; seeCoercion (Object Conversion)for a list of allowed coercions.
The right-hand operand ofasmay be a single class, such astext, or a list of classes, such as{integer, text}.When given a list, theasoperator processes the list from the first type to the last, checking if the value is an instance of that type; if one matches, the result is the original value. If none match, then it again processes the list from the first type to the last, attempting to coerce the value to that type; the result is the result of the first successful coercion. If none succeed, it throws an error.
Note:Coercing to a list of classes is supported in OS X Yosemite v10.10 and later.
##### Examples
This expression returnsxas a number, suitable for use with a math operator. For example, ifxwas the text"1.5", it would return therealvalue1.5.
```
x as number```
This expression returnsxas either an integer or text, whichever succeeds first. For example, consider ifxwasdate "Wednesday, May 27, 2015 at 12:03:15 PM":dateobjects cannot be coerced to integers, but they can be coerced to text, so the result is the date as text:"Wednesday, May 27, 2015 at 12:03:15 PM".
```
x as {integer, text}```
The way lists of classes are processed means that the result ofascan depend on the order of the classes. For example, the result of1.5 as {integer, text}is2, but1.5 as {text, integer}is"1.5". It is also possible to have types that will never be reached. For example, in the expressionx as {number, integer}, theintegercoercion will never trigger, becausenumberwill always succeed first.
Thecontainsandis contained byoperators work with lists, records, andtextobjects.
Table 9-1summarizes the use of these operators and their synonyms.
##### list
A listcontainsanother list if the right-hand list is a sublist of the left-hand list. A sublist is a list whose items appear in the same order and have the same values as any series of items in the other list. For example, the following statement istruebecause1 + 1evaluates to2, so that all the items in the right-hand list appear, in the same order, in the left-hand list:
```
{ "this", "is", 1 + 1, "cool" } contains { "is", 2 }```
The following statement isfalsebecause the items in the right-hand list are not in the same order as the matching items in the left-hand list:
```
{ "this", "is", 2, "cool" } contains { 2, "is" }```
A listis contained byanother list if the left-hand list is a sublist of the right-hand list. For example, the following expression istrue:
```
{ "is", 2} is contained by { "this", "is", 2, "cool" }```
Bothcontainsandis contained bywork if the sublist is a single valueâas with the concatenation operator (&), single values are coerced to one-item lists. For example, both of the following expressions evaluate totrue:
```
{ "this", "is", 2, "cool" } contains 2```
```
2 is contained by { "this", "is", 2, "cool" }```
However, the following expressions, containing nested lists, both evaluate to false:
```
{"this", "is", {2}, "cool"} contains 2 -- false```
```
{"this", "is", {2}, "cool"} contains {2} -- false```
##### record
A record contains another record if all the properties in the right-hand record are included in the left-hand record, and the values of properties in the right-hand record are equal to the values of the corresponding properties in the left-hand record. A record is contained by another record if all the properties in the left-hand record are included in the right-hand record, and the values of the properties in the left-hand record are equal to the values of the corresponding properties in the right-hand record. The order in which the properties appear does not matter. For example, the following istrue:
```
{ name:"Matt", mileage:"8000", description:"fast"} ¬```
```
contains { description:"fast", name:"Matt" }```
##### text
Atextobject contains anothertextobject if the characters in the right-handtextobject are equal to any contiguous series of characters in the left-handtextobject. For example,
```
"operand" contains "era"```
istrue, but
```
"operand" contains "dna"```
isfalse.
Atextobject is contained by anothertextobject if the characters in the left-handtextobject are equal to any series of characters in the right-handtextobject. For example, this statement istrue:
```
"era" is contained by "operand"```
Text comparisons can be affected byconsideringandignoringstatements, as described in the Text section ofequal, is not equal to.
Theequalandis not equal tooperators can handle operands of any class. Two expressions of different classes are generally not equal, although for scalar operands, such as booleans, integers, and reals, two operands are the same if they have the same value.
Table 9-1summarizes the use of these operators and their synonyms.
##### list
Two lists are equal if they both contain the same number of items and if the value of an item in one list is identical to the value of the item at the corresponding position in the other list:
```
{ 7, 23, "Hello" } = {7, 23, "Goodbye"} --result: false```
##### record
Two records are equal if they both contain the same collection of properties and if the values of properties with the same label are equal. They are not equal if the records contain different collections of properties, or if the values of properties with the same label are not equal. The order in which properties are listed does not affect equality. For example, the following expression istrue:
```
{ name:"Matt", mileage:"8000" } = { mileage:"8000", name:"Matt"}```
##### text
Twotextobjects are equal if they are both the same series of characters. They are not equal if they are different series of characters. For related information, see thetextclass.
Text comparisons can be affected byconsideringandignoringstatements, which instruct AppleScript to selectively consider or ignore attributes of characters or types of characters. For example, unless you use anignoringstatement, AppleScript comparestextobjects by considering all characters and punctuation.
AppleScript does not distinguish uppercase from lowercase letters unless you use aconsideringstatement to consider thecaseattribute. For example:
```
"DUMPtruck" is equal to "dumptruck" --result: true```
```
considering case```
```
"DUMPtruck" is equal to "dumptruck" --result: false```
```
end considering```
When comparing twotextobjects, if the test is not enclosed in aconsideringorignoringstatement, then the comparison uses default values for considering and ignoring attributes (described inconsidering / ignoring (text comparison)).
Thegreater thanandless thanoperators work with dates, integers, real numbers, andtextobjects.
Table 9-1summarizes the use of these operators and their synonyms.
##### date
A date is greater than another date if it represents a later time. A date is less than another date if it represents an earlier time.
##### integer, real
An integer or a real number is greater than another integer or real number if it represents a larger number. It is less than another integer or real number if it represents a smaller number.
##### text
To determine the ordering of twotextobjects, AppleScript uses the collation order set in the Language pane of International preferences. Atextobject is greater than (comes after) anothertextobject based on the lexicographic ordering of the userâs language preference. With the preference set to English, the following two statements both evaluate totrue:
```
"zebra" comes after "aardvark"```
```
"zebra" > "aardvark"```
The following two statements also evaluate totrue:
```
"aardvark" comes before "zebra"```
```
"aardvark" < "zebra"```
Text comparisons can be affected byconsideringandignoringstatements, as described in the Text section ofequal, is not equal to.
Thestarts withandends withoperators work with lists andtextobjects.
Table 9-1summarizes the use of these operators and their synonyms.
##### list
A liststarts withthe items in a second list if all the items in the second list are found at the beginning of the first list. A listends withthe items in a second list if all the items in the second list are found at the end of the first list. For example, the following three expressions are alltrue:
```
{ "this", "is", 2, "cool" } ends with "cool"```
```
{ "this", "is", 2, "cool" } starts with "this"```
```
{ "this", "is", 2, "cool" } starts with { "this", "is" }```
##### text
Atextobjectstarts withthe text in a secondtextobject if all the characters in the second object are found at the beginning of the first object. Atextobjectends withthe text in a secondtextobject if all the characters in the second object are found at the end of the first object. For example, the following expression istrue:
```
"operand" starts with "opera"```
Atextobject ends with anothertextobject if the characters in the right-handtextobject are the same as the characters at the end of the left-handtextobject. For example, the following expression istrue:
```
"operand" ends with "and"```
Text comparisons can be affected byconsideringandignoringstatements, as described in the Text section ofequal, is not equal to.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Variables and Properties
Variables and properties are introduced in previous chapters in this document. You use them inscriptobjects to store and manipulate values.
Important:In reading this chapter, you should be familiar with the information on implicit and explicitrunhandlers inrun Handlers.
The following sections cover common issues in working with variables and properties, including how to declare them and how AppleScript interprets their scope in a script:
- Defining Properties
Defining Properties
- Declaring Variables
Declaring Variables
- Scope of Variables and Properties
Scope of Variables and Properties
## Defining Properties
Property labels follow the rules described inIdentifiers.
Property definitions use the following syntax:
propertypropertyLabel:expression
An identifier.
An AppleScript expression that sets the initial value for the property. Property definitions are evaluated before variable assignments, so property definitions cannot contain variables.
The following are examples of valid property definitions:
```
property windowCount : 0```
```
property defaultName : "Barry"```
```
property strangeValue : (pi * 7)^2```
After you define a property, you can change its value with thecopyorsetcommand.
The value set by a property definition is not reset each time the script is run; instead, it persists until the script is recompiled.
You cannot declare a property in a handler but a handler can access a property defined in its containingscriptobject.
## Declaring Variables
Variable names follow the rules described inIdentifiers.
To create a variable in AppleScript, you assign it a value using thecopyorsetcommand. For example, the following statements create and initialize two variables, one namedcircumferenceand one namedsavedResult:
```
set circumference to pi * 3.5 --result: 10.995574287564```
```
copy circumference to savedResult --result: 10.995574287564 (copy of 1st variable)```
As shown in this example, a variable assignment can make use of a previously defined variable. It can also make use of properties declared in the samescriptobject.
There are some obvious, and some more subtle, differences in usingcopyandsetto create a variableâseeUsing the copy and set Commandsfor more information.
If you assign a new value to a variable that is already in use, it replaces the old value. You can assign a simple value, an expression, or an object specifierâexpressions are evaluated and object specifiers are resolved to obtain the value to assign. To create a variable whose value is an object specifier itself, rather than the value of the object specified, use thea reference tooperator.
The next two sections describe how you can explicitly define alocalor aglobalvariable. These variable types differ primarily in their scope. Scope, which refers to where a variable is accessible within a script, is described in detail inScope of Variables and Properties.
### Local Variables
You can declare explicitlocalvariables using the following syntax:
localvariableName[,variableName]â¦
An identifier.
The following are examples of validlocalvariable declarations:
```
local windowCount -- defines one variable```
```
local agentName, agentNumber, agentHireDate -- defines three variables```
You cannot assign an initial value to alocalvariable in its declaration, nor can you declare a class for the variable. Instead, you use thecopyorsetcommand to initialize a variable and set its class. For example:
```
set windowCount to 0 -- initialize to zero; an integer```
```
set agentName to "James Smith" -- assign agent name; a text string```
```
set agentNumber to getAgentNumber(agentName) -- call handler; an integer```
```
copy current date to agentHireDate -- call current date command; a date```
### Global Variables
The syntax forglobalvariables is nearly identical to that forlocalvariables:
globalvariableName[,variableName]â¦
An identifier.
The following are examples of validglobalvariable declarations:
```
global gAgentCount```
```
global gStatementDate, gNextAgentNumber```
As withlocalvariables, you use thecopyorsetcommand to initializeglobalvariables and set their class types. For example:
```
set gAgentCount to getCurrentAgentCount() -- call handler to get count```
```
set gStatementDate to current date -- get date from current date command```
```
set gNextAgentNumber to getNextAvailNumber() -- call handler to get number```
### Using the copy and set Commands
As its name implies, when you use thecopycommand to create a variable, it always creates a separate copy (though note that a copy of an object specifier still specifies the same object). However, when you use thesetcommand to create a variable, the new variable always refers to the original object or value. You have essentially created another name for the same object.
When more than one variable refers to a changeable (or mutable) object, a change to the object is observable through any of the variables. The types of AppleScript objects that are mutable aredate,list,record, andscriptobjects.
For objects that cannot be modified (immutable objects), variables created with thesetcommand may seem like copiesâthereâs no way to change the object the variables point to, so they seem independent. This is demonstrated in the example in the next section that creates the variablesmyNameandyourName.
#### Declaring Variables with the set Command
You can use thesetcommand to set a variable to any type of object. If the variable doesnât exist, it is created; if it does exist, its current value is replaced:
```
set numClowns to 5 --result: 5```
```
set myList to { 1, 2, "four" } --result: {1, 2, "four"}```
```
tell application "TextEdit"```
```
set word1 to word 1 of front document --result: some word```
```
end tell```
The following example uses a mutable object. It creates two variables that refer to the same list, then modifies the list through one of the variables:
```
set myList to { 1, 2, 3 }```
```
set yourList to myList```
```
set item 1 of myList to 4```
After executing these statements, the statementsitem 1 of myListanditem 1 of yourListboth yield4, because both variables refer to the same list.
Now suppose youâre working with an immutable object, such as atextobject:
```
set myName to "Sheila"```
```
set yourName to myName```
Both variables refer to the sametextobject, buttextobjects are not mutable, so there is no way to change the the valuemyNamesuch that it affects the value ofyourName. (If you assign new text to one of the variables, you are just creating a new, separatetextobject.)
Thesetcommand can assign several variables at once using a pattern, which may be a list or record: a list or record of variables on one side, and a list or record of values on the other. Values are matched to variables based on their position for a list, or based on their keys for a record. Not having enough values is an error; if there are too many values, the extra ones are ignored. The order in which the values are evaluated and the variables are assigned is unspecified, but all values are evaluated before any assignments are made.
The Examples section of thesetcommand shows some simple pattern assignments. Here is an example with more complex patterns:
```
set x to {8, 94133, {firstName:"John", lastName:"Chapman"}}```
```
set {p, q, r} to x```
```
(* now p, q, and r have these values:```
```
p = 8```
```
q = 94133```
```
r = {firstName:"John", lastName:"Chapman"} *)```
```
set {p, q, {lastName:r}} to x```
```
(* now p, q, and r have these values: p = 8```
```
q = 94133```
```
r = "Chapman" *)```
In the final assignment statement above,{lastName:r}is a record that hasnât been used before in the script, and contains an item with labellastNameand valuer(a previously defined variable). The variablexhas previously been set to have a record that has an item with labellastNameand value"Chapman". During the assignment, the value of the item labeledlastNamein the new record is set to the value of the item labeledlastNameinxâhence it now has the value"Chapman".
As this example demonstrates, the properties of a record need not be given in the same order and need not all be used when you set a pattern to a pattern, as long as the patterns match. For details, see thesetcommand.
Note:Using patterns with thesetcommand is similar to using patterned parameters with handlers, which is described inHandlers with Patterned Positional Parameters.
#### Declaring Variables with the copy Command
You can use thecopycommand to set a variable to any type of object. If the variable doesnât exist, it is created; if it does exist, its current value is replaced. Thecopycommand creates a new copy that is independent of the originalâa subsequent change does not change the original value (though note that a copy of an object specifier still specifies the same object).
To copy within an application, you should use the applicationâsduplicatecommand, if it has one. To copy between applications, you can use thegetcommand to obtain information from one application and thesetcommand to set it in another.
Thecopycommand creates a deep copyâthat is, if you copy a nested data structure, such as a list that contains another list, the entire structure is copied, as shown in the following example. This example creates a record (alpha), then a list (beta), then a list that contains the first record and list (gamma), then finally a copy ofgamma(delta). It then changes a property in the original record,alpha. The result shows that the property is changed whereveralphaappears, except in the copy,delta:
```
set alpha to {property1:10, property2:20}```
```
set beta to {1, 2, "Hello"}```
```
set gamma to {alpha, beta, "Goodbye"}```
```
copy gamma to delta```
```
set property1 of alpha to 42```
```
```
```
{alpha, beta, gamma, delta} -- List variables to show contents```
```
(*result: {{property1:42, property2:20}, {1, 2, "Hello"}, {{property1:42, property2:20}, {1, 2, "Hello"}, "Goodbye"}, {{property1:10, property2:20}, {1, 2, "Hello"}, "Goodbye"}} *)```
If you make a copy of areferenceobject, it refers to the same object as the original (because both contain the same object specifier):
```
set windowRef to a reference to window 1 of application "Finder"```
```
name of windowRef --result: "Script testing folder"```
```
copy windowRef to currentWindowRef --result: a new object specifier```
```
name of currentWindowRef --result: "Script testing folder"```
## Scope of Variables and Properties
Thedeclarationof a variable or property identifier is the first valid occurrence of the identifier in ascriptobject. The form and location of the declaration determine how AppleScript treats the identifier in thatscriptobject.
Thescopeis the range over which AppleScript recognizes a declared identifier within ascriptobject. The scope of a variable depends on where you declare it and whether you declare it asglobalorlocal. The scope of a property extends to the entirescriptobject in which it is declared. After declaring a property, you can reuse the same identifier as a separate variable only if you first declare it as alocalvariable.
Lifetimerefers to the period of time over which a variable or property is in existence. Only the values of properties andglobalvariables can persist after a script is run.
In the discussions that follow, declarations and statements in ascriptobject that occur outside of any handlers or nestedscriptobjects are identified asoutside.
The following examples show the four basic forms for declaring variables and properties in AppleScript:
- property x: 3The scope of a property definition is thescriptobject in which it is declared, including any handlers or nestedscriptobjects. A property definition specifies an initial value. You cannot declare a property in a handler.The value set by a property definition is not reset each time the script is run; instead, it persists until the script is recompiled.
property x: 3
The scope of a property definition is thescriptobject in which it is declared, including any handlers or nestedscriptobjects. A property definition specifies an initial value. You cannot declare a property in a handler.
The value set by a property definition is not reset each time the script is run; instead, it persists until the script is recompiled.
- global xThe scope of aglobalvariable can be limited to specific handlers or containedscriptobjects or it can extend throughout a top-levelscriptobject. Aglobaldeclaration doesnât set an initial valueâit must be initialized by acopyorsetcommand before a script can access its value.The value of aglobalvariable is not reset each time a script is run, unless its initialization statement is executed.
global x
The scope of aglobalvariable can be limited to specific handlers or containedscriptobjects or it can extend throughout a top-levelscriptobject. Aglobaldeclaration doesnât set an initial valueâit must be initialized by acopyorsetcommand before a script can access its value.
The value of aglobalvariable is not reset each time a script is run, unless its initialization statement is executed.
- local xThe scope of alocalvariable can be limited to specific handlers or containedscriptobjects or it can extend throughout a top-levelscriptobject. Alocaldeclaration doesnât set an initial valueâit must be initialized by acopyorsetcommand before a script can access its value.The value of alocalvariable is reset each time the handler is run (either therunhandler for the script, or the specific handler in which the variable is declared).
local x
The scope of alocalvariable can be limited to specific handlers or containedscriptobjects or it can extend throughout a top-levelscriptobject. Alocaldeclaration doesnât set an initial valueâit must be initialized by acopyorsetcommand before a script can access its value.
The value of alocalvariable is reset each time the handler is run (either therunhandler for the script, or the specific handler in which the variable is declared).
- set x to 3In the absence of aglobalvariable declaration, the scope of a variable declared with thecopyorsetcommand is normally restricted to therunhandler for the script, making it implicitly local to that run handler. However, a handler or nested script object can declare the same variable with aglobaldeclaration to gain access to it.The value of a variable declared with thecopyorsetcommand is reset each time a script is run.
set x to 3
In the absence of aglobalvariable declaration, the scope of a variable declared with thecopyorsetcommand is normally restricted to therunhandler for the script, making it implicitly local to that run handler. However, a handler or nested script object can declare the same variable with aglobaldeclaration to gain access to it.
The value of a variable declared with thecopyorsetcommand is reset each time a script is run.
If you want to use the same identifier in several different places in a script, you should either declare it as a property or as aglobalvariable.
It is often convenient to limit the scope of a particular identifier to a single handler or nestedscriptobject, which you can do by defining it as alocalvariable in the handler orscriptobject. Outside, the identifier has no value associated with it and can be reused elsewhere in the script. When used this way, alocalvariable is said toshadow(or block access to) aglobalvariable or property with the same name, making the global version inaccessible in the scope of the handler orscriptobject where thelocalvariable is declared.
Note:If you save a script as a script application, then run the application on read-only media, the value of a modified property orglobalvariable is not saved.
The following sections provide additional information about scope:
- Scope of Properties and Variables Declared in a Script Object
Scope of Properties and Variables Declared in a Script Object
- Scope of Variables Declared in a Handler
Scope of Variables Declared in a Handler
### Scope of Properties and Variables Declared in a Script Object
Table 3-1shows the scope and lifetime for variables and properties that are declared at the top level in ascriptobject (outside any handlers or nestedscriptobjects).
Declaration type
Scope (visibility)
Lifetime
property x: 3
Everywhere in script
Reset when script is recompiled
global x
Everywhere in script
Reset when reinitialized in script or when script is recompiled
local x
Withinrunhandler only
Reset when script is run
set x to 3
Withinrunhandler only
Reset when script is run
The scope of a property in ascriptobject extends to any subsequent statements anywhere in the script. Consider the following example:
```
property currentCount : 0```
```
increment()```
```
```
```
on increment()```
```
set currentCount to currentCount + 1```
```
display dialog "Count is now " & currentCount & "."```
```
end increment```
When it encounters the identifiercurrentCountanywhere in this script, AppleScript associates it with thecurrentCountproperty.
The value of a property persists after the script in which the property is defined has been run. Thus, the value ofcurrentCountis 0 the first time this script is run, 1 the next time it is run, and so on. The propertyâs current value is saved with thescriptobject and is not reset to 0 until the script is recompiledâthat is, modified and then run again, saved, or checked for syntax.
The value of aglobalvariable also persists after the script in which it is defined has been run. However, depending on how it is initialized, aglobalvariable may be reset each time the script is run again. The next example shows how to initialize aglobalvariable so that it is initialized only the first time a script is run, and thus produces the same result as using a property in the previous example:
```
global currentCount```
```
increment()```
```
```
```
on increment()```
```
try```
```
set currentCount to currentCount + 1```
```
on error```
```
set currentCount to 1```
```
end try```
```
display dialog "Count is now " & currentCount & "."```
```
end increment```
The first time the script is run, the statementset currentCount to currentCount + 1generates an error because theglobalvariablecurrentCounthas not been initialized. When the error occurs, theon errorblock initializescurrentCount. When the script is run again, the variable has already been initialized, so the error branch is not executed, and the variable keeps its previous value. Persistence is accomplished, but not as simply as in the previous example.
If you donât want the value associated with an identifier to persist after a script is run but you want to use the same identifier throughout a script, declare aglobalvariable and use thesetcommand to set its value each time the script is run:
```
global currentCount```
```
set currentCount to 0```
```
on increment()```
```
set currentCount to currentCount + 1```
```
end increment```
```
```
```
increment() --result: 1```
```
increment() --result: 2```
Each time theon incrementhandler is called within the script, theglobalvariablecurrentCountincreases by 1. However, when you run the entire script again,currentCountis reset to 0.
In the absence of aglobalvariable declaration, the scope of a variable declaration using thesetcommand is normally restricted to therunhandler for the script. For example, this script declares two separatecurrentCountvariables:
```
set currentCount to 10```
```
on increment()```
```
set currentCount to 5```
```
end increment```
```
```
```
increment() --result: 5```
```
currentCount --result: 10```
The scope of the firstcurrentCountvariableâs declaration is limited to therunhandler for the script. Because this script has no explicitrunhandler, outside statements are part of its implicitrunhandler, as described inrun Handlers. The scope of the secondcurrentCountdeclaration, within theon incrementhandler, is limited to that handler. AppleScript keeps track of each variable independently.
To associate a variable in a handler with the same variable declared with thesetcommand outside the handler, you can use aglobaldeclaration in the handler, as shown in the next example. (This approach also works to associate a variable in a nestedscriptobject.)
```
set currentCount to 0```
```
on increment()```
```
global currentCount```
```
set currentCount to currentCount + 1```
```
end increment```
```
```
```
increment() --result: 1```
```
currentCount --result: 1```
To restrict the context of a variable to a scriptâsrunhandler regardless of subsequentglobaldeclarations, you must declare it explicitly as alocalvariable, as shown in this example:
```
local currentCount```
```
set currentCount to 10```
```
on increment()```
```
global currentCount```
```
set currentCount to currentCount + 2```
```
end increment```
```
```
```
increment() --error: "The variable currentCount is not defined"```
Because thecurrentCountvariable in this example is declared as local to the script, and hence to its implicitrunhandler, any subsequent attempt to declare the same variable asglobalresults in an error.
If you declare an outside variable with thesetcommand and then declare the same identifier as a property, the declaration with thesetcommand overrides the property definition. For example, the following script returns 10, not 5. This occurs because AppleScript evaluates property definitions before it evaluatessetcommand declarations:
```
set numClowns to 10 -- evaluated after property definition```
```
property numClowns: 5 -- evaluated first```
```
numClowns --result: 10```
The next example, shows how to use aglobalvariable declaration in ascriptobject to associate aglobalvariable with an outside property:
```
property currentCount : 0```
```
script Paula```
```
property currentCount : 20```
```
script Joe```
```
global currentCount```
```
on increment()```
```
set currentCount to currentCount + 1```
```
return currentCount```
```
end increment```
```
end script```
```
tell Joe to increment()```
```
end script```
```
run Paula --result: 1```
```
run Paula --result: 2```
```
currentCount --result: 2```
```
currentCount of Paula --result: 20```
This script declares two separatecurrentCountproperties: one outside any handlers (andscriptobjects) in the main script and one in thescriptobjectPaulabut outside of any handlers orscriptobjects withinPaula. Because the scriptJoedeclares theglobalvariablecurrentCount, AppleScript looks forcurrentCountat the top level of the script, thus treating JoeâscurrentCountandcurrentCountat the top level of the script as the same variable.
### Scope of Variables Declared in a Handler
A handler canât declare a property, although it can refer to a property that is declared outside any handler in thescriptobject. (A handler can contain script objects, but it canât contain another handler, except in a contained script object.)
Table 3-2summarizes the scope of variables declared in a handler. Examples of each form of declaration follow.
Declaration type
Scope (visibility)
Lifetime
global x
Within handler only
Reset when script is recompiled; if initialized in handler, then reset when handler is run
local x
Within handler only
Reset when handler is run
set x to 3
Within handler only
Reset when handler is run
The scope of aglobalvariable declared in a handler is limited to that handler, although AppleScript looks beyond the handler when it tries to locate an earlier occurrence of the same variable. Hereâs an example:
```
set currentCount to 10```
```
on increment()```
```
global currentCount```
```
set currentCount to currentCount + 2```
```
end increment```
```
```
```
increment() --result: 12```
```
currentCount --result: 12```
When AppleScript encounters thecurrentCountvariable within theon incrementhandler, it doesnât restrict its search for a previous occurrence to that handler but keeps looking until it finds the declaration outside any handler. However, the use ofcurrentCountin any subsequent handler in the script is local to that handler unless the handler also explicitly declarescurrentCountas aglobalvariable.
The scope of alocalvariable declaration in a handler is limited to that handler, even if the same identifier has been declared as a property outside the handler:
```
property currentCount : 10```
```
on increment()```
```
local currentCount```
```
set currentCount to 5```
```
end increment```
```
```
```
increment() --result: 5```
```
currentCount --result: 10```
The scope of a variable declaration using thesetcommand in a handler is limited to that handler:
```
script Henry```
```
set currentCount to 10 -- implicit local variable in script object```
```
on increment()```
```
set currentCount to 5-- implicit local variable in handler```
```
end increment```
```
return currentCount```
```
end script```
```
```
```
tell Henry to increment() --result: 5```
```
run Henry --result: 10```
The scope of the first declaration of the firstcurrentCountvariable in thescriptobjectHenryis limited to therunhandler for thescriptobject (in this case, an implicitrunhandler, consisting of the last two statements in the script). The scope of the secondcurrentCountdeclaration, within theon incrementhandler, is limited to that handler. The two instances ofcurrentCountare independent variables.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Reference Forms
This chapter describes AppleScript reference forms.Areference formspecifies the syntax for identifying an object or group of objects in an application or other containerâthat is, the syntax for constructing an object specifier (described inObject Specifiers).
For example, the following object specifier (from a script targeting the Finder) uses several index reference forms, which identify an object by its number within a container:
```
item 1 of second folder of disk 1```
Important:When you use a reference form, you specify the container in which the referenced object or objects reside. This takes the formreferenceFormofcontainerObject. You can also enclose a reference form in atellstatement, which then serves to specify the outer container. For more information, seeAbsolute and Relative Object Specifiers.
Some of the examples of reference forms shown in this chapter will not compile as shown. To compile them, you may need to add an enclosingtellstatement, targeting the Finder or the word processing application TextEdit.
Specifies an arbitrary object in a container. This form is useful whenever randomness is desired.
Because an arbitrary item is, by its nature, random, this form is not useful for operations such as processing each item in a group of files, words, or other objects.
##### Syntax
```
some class```
##### Placeholders
The class for an arbitrary object.
##### Examples
The following creates a new Mail message with a random signature (and depends on the user having at least one signature):
```
tell application "Mail"```
```
activate```
```
set randomSignature to some signature```
```
set newMessage to make new outgoing message ¬```
```
at end of outgoing messages with properties ¬```
```
{subject:"Guess who?", content:"Welcome aboard.", visible:true}```
```
set message signature of newMessage to randomSignature```
```
end tell```
The following simply gets a random word from a TextEdit document:
```
tell application "TextEdit"```
```
some word of document 1 -- any word from the first document```
```
end tell```
Specifies every object of a particular class in a container.
##### Syntax
```
every class
pluralClass```
##### Placeholders
A singular class (such aswordorparagraph).
The plural form for a class (such aswordsorparagraphs).
##### Value
The value of aneveryobject specifier is a list of the objects from the container. If the container does not contain any objects of the specified class, the list is an empty list: {}. For example, the value of the expressionevery word of {1, 2, 3}is the empty list{}.
##### Examples
The following example uses aneveryobject specifier to specify every word contained in a text string:
```
set myText to "That's all, folks"```
```
every word of myText --result: {"That's", "all", "folks"} (a list of three words)```
The following object specifier specifies the same list:
```
words of myText```
The following example specifies a list of all the items in the Users folder of the startup disk (boot partition):
```
tell application "Finder"```
```
every item of folder "Users" of startup disk```
```
end tell```
The following specifies the same list as the previous example:
```
tell application "Finder"```
```
items of folder "Users" of startup disk```
```
end tell```
##### Discussion
Use of theeveryreference form implies the existence of anindexproperty for the specified objects.
If you specify aneveryobject specifier as the container from which to obtain a property or object, the result is a list containing the specified property or object for each object of the container. The number of items in the list is the same as the number of objects in the container.
Specifies all objects in a container that match a condition, or test, specified by a Boolean expression.
The filter form specifies application objects only. It cannot be used to filter the AppleScript objectslist,record, ortext. A term that uses the filter form is also known as awhoseclause.
Note:You can use the wordswhereorthatassynonyms forwhose.
A filter reference form can often be replaced by arepeatstatement, or vice versa. For example, the following script closes every TextEdit window that isnât named"Old Report.rtf":
```
tell application "TextEdit"```
```
close every window whose name is not "Old Report.rtf"```
```
end tell```
You could instead obtain a list of open windows and set up arepeatstatement that checks the name of each window and closes the window if it isnât named"Old Report.rtf". However, awhoseclause is often the fastest way to obtain the desired information.
The following is an abbreviated form of the previous script:
```
windows of application "TextEdit" whose name is not "Old Report.rtf"```
For related information, seerepeat Statements.
##### Syntax
```
objectSpecifier ( whose | where ) booleanTest ```
##### Placeholders
Specifies the container in which to look for objects that match the Boolean test.
These words have the same meaning, and refer to all of the objects in the specified container that match the conditions in the specified Boolean expression.
Any Boolean expression (see thebooleanclass definition).
##### Value
The value of a filter reference form is a list of the objects that pass the test. If no objects pass the test, the list is an empty list: {}.
##### Examples
The following example shows an object specifier for all open Finder windows that do not have the name"AppleScript Language Guide".
```
tell application "Finder"```
```
every window whose name is not "AppleScript Language Guide"```
```
end tell```
##### Discussion
In effect, a filter reduces the number of objects in a container. Instead of specifyingeveryFinder window, the following object specifier specifies just the windows that are currently zoomed:
```
every window whose zoomed is true```
To specify a container after a filter, you must enclose the filter and the object specifier it applies to in parentheses, as in this example:
```
tell application "Finder"```
```
(files whose file type is not "APPL") in folder "HD:SomeFolder:"```
```
end tell```
Within a test in a filter reference, the direct object is the object being tested. Though it isnât generally needed, this implicit target can be specified explicitly using the keywordit, which is described inThe it and me Keywords.
The following example shows several equivalent ways of constructing a filter reference to find all the files in a folder that whose name contains the word âAppleScriptâ. While the termitrefers to the Finder application outside of the filter statements, within themof itrefers to the current file being tested. The result of each filter test is the same and is not changed by including or omitting the termof it:
```
tell application "Finder"```
```
it --result: application "Finder" (target of tell statement)```
```
set myFolder to path to home folder```
```
--result: alias "Leopard:Users:myUser:"```
```
files in myFolder --result: a list of Finder document files```
```
files in myFolder where name of it contains "AppleScript"```
```
(* result: document file "AppleScriptLG.pdf" of folder "myUser"```
```
of folder "Users" of startup disk of application "Finder"}*)```
```
files in myFolder where name contains "AppleScript" -- same result```
```
every file in myFolder whose name contains "AppleScript" -- same result```
```
every file in myFolder where name of it contains "AppleScript"```
```
-- same result```
```
end tell```
A filter reference form 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 8-1shows some filter references, the Boolean expressions they contain, and what is being tested in each reference.
Filter reference form
Boolean expression
What is being tested
windows whose zoomed is true
zoomed is true
Thezoomedproperty of each window
windows whose name isnât "Hard Disk"
name isnât "Hard Disk"
Thenameproperty of each window
files whose creator type is "OMGR"
creator type is "OMGR"
Thecreator typeproperty of each file
A test can be any Boolean expression. You can link multiple tests, as in the following statement:
```
windows whose zoomed is true and floating is false```
Specifies an object by the value of itsidproperty.
You can use the ID reference form only with application objects that have an ID property.
##### Syntax
```
class id expression```
##### Placeholders
The id value.
##### Examples
The following examples use the ID reference form to specify anapplicationby ID and adiskobject by ID.
```
tell application id "com.apple.finder"```
```
-- specifies an application (Finder) by its ID```
```
disk id -100 -- specifies a Finder disk object by ID```
```
name of disk id -100 --result: "Leopard_GM" (gets name from ID specifier)```
```
end tell```
##### Discussion
Use of theidreference form implies the existence of aidproperty for the specified objects.
Althoughidproperties are most often integers, anidproperty can belong to any class. An application that supportsidproperties for its scriptable objects must guarantee that the IDs are unique within a container. Some applications may also provide additional guarantees, such as ensuring the uniqueness of an ID among all objects.
The value of anidproperty is not typically 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. In some scripts you may wish to refer to an object by its ID, rather than by a property such as its name, which may change. Similarly, you could keep track of an item by its index, but indexes can change when items in a container are added, deleted, or even renamed.
Note:A good way to keep track of files and folders is to use analias.
Starting in AppleScript 2.0, objects of classapplicationhave anidproperty, which represents the applicationâs bundle identifier (the default) or its four-character signature code.
Also starting in AppleScript 2.0, objects of classtexthave anidproperty, representing the Unicode code point or points for the character or characters in the object. Because atextobjectâs ID is based on the characters it contains, these IDs are not guaranteed to be unique, and in fact will be identical for twotextobjects that store the same characters. And in fact, there is no way to tell two such objects apart by inspection.
Specifies an object by describing its position with respect to the beginning or end of a container.
For related information, seeRelative.
##### Syntax
```
class [ index ] integer
integer (st | nd | rd | th ) class
( first | second | third | fourth | fifth | sixth | seventh | eighth | ninth | tenth ) class
( last | front | back ) class```
##### Placeholders
The class of the indexed object to obtain.
An integer that describes the position of the object in relation to the beginning of the container (if integer is a positive integer) or the end of the container (if integer is a negative integer).
Appended to the appropriate integer to form an index. For example,1st,2nd,3rd.
Specify one of the ordinal indexes.
The formsfirst,second, and so on are equivalent to the corresponding integer forms (for example,second wordis equivalent to2nd word). For objects whose index is greater than 10, you can use the forms12th,23rd,101st, and so on. (Note that any integer followed by any of the suffixes listed is valid; for example, you can use11rdto refer to the eleventh object.)
Thefrontform (for example,front window) is equivalent toclass 1(window 1) orfirst class(first window). Thelastandbackforms (for example,last wordandback window) refer to the last object in a container. They are equivalent toclass -1(for example,window -1).
##### Examples
Each of the following object specifiers specifies the first item on the startup disk:
```
item 1 of the startup disk```
```
item index 1 of the startup disk -- "index" is usually omitted```
```
the first item of the startup disk```
The following object specifiers specify the second word from the beginning of the third paragraph:
```
word 2 of paragraph 3```
```
2nd word of paragraph 3```
```
second word of paragraph 3```
The following object specifiers specify the last word in the third paragraph:
```
word â1 of paragraph 3```
```
last word of paragraph 3```
The following object specifiers specify the next-to-last word in the third paragraph.
```
word â2 of paragraph 3```
```
-2th word of paragraph 3```
##### Discussion
Indexes are volatile. Changing some other property of the object may change its index, as well as the index of other like objects. For example, after deletingword 4from a paragraph, the word no longer exists. But there may still be aword 4âthe word that was formerlyword 5. Afterword 4is deleted, any words with an index higher than 4 will also have a new index. So the object an index specifies can change.
For a unique, persistent object specifier, you can use theidreference form (seeID), if the application supports it for the class of object you are working with. And for keeping track of a file, you can use analiasobject.
Specifies the middle object of a particular class in a container. This form is rarely used.
##### Syntax
```
middle class ```
##### Placeholders
The class of the middle object to obtain.
##### Examples
```
tell application "TextEdit"```
```
middle paragraph of front document```
```
end tell```
```
middle item of {1, "doughnut", 33} --result: "doughnut"```
```
middle item of {1, "doughnut", 22, 33} --result: "doughnut"```
```
middle item of {1, "doughnut", 11, 22, 33} --result: 11```
##### Discussion
Themiddlereference form generally works only when theindexform also works.
AppleScript calculates the middle object by taking half the count, then rounding up. For example, the middle word of a paragraph containing ten words is the fifth word; the middle of eleven words is the sixth.
Specifies an object by name.
##### Syntax
```
class [ named ] nameText ```
##### Placeholders
The class for the specified object.
The value of the objectâs name property.
##### Examples
The following statements identify objects by name:
```
document "Report.rtf"```
```
window named "logs"```
##### Discussion
Use of thenamereference form implies the existence of anameproperty for the specified objects.
In some applications, it is possible to have multiple objects of the same class in the same container with the same name. For example, if there are two drives named âHard Diskâ, the following statement is ambiguous (at least to the reader):
```
tell application "Finder"```
```
item 1 of disk "Hard Disk"```
```
end tell```
In such cases, it is up to the application to determine which object is specified by anamereference.
Specifies a property of an object.
##### Syntax
```
propertyLabel```
##### Placeholders
The label for the property.
##### Examples
The following example is an object specifier to a property of a Finder window. It lists the label for the windowâs property (zoomed) and its container (front window).zoomedis a Boolean property.
```
zoomed of front window -- e.g., false, if the window isn't zoomed```
For many objects, you can obtain a list of properties:
```
tell app "Finder"```
```
properties of window 1 --result: a list of properties and their values```
```
end tell```
The following example is an object specifier to theUnitPriceproperty of arecordobject. The label of the property isUnitPriceand the container is therecordobject.
```
UnitPrice of {Product:"Super Snack", UnitPrice:0.85, Quantity:10} --result: 0.85```
##### Discussion
Property labels are listed in class definitions in application dictionaries. Because a propertyâs label is unique among the properties of an object, the label is all you need to specify the propertyâthere is no need to specify the class of the property.
Specifies a series of objects of the same class in the same container. You can specify the objects with a pair of indexes (such aswords 12 thru 24) or with a pair of boundary objects (integers from integer 1 to integer 3).
##### Syntax
```
every class from boundarySpecifier1 to boundarySpecifier2
pluralClass from boundarySpecifier1 to boundarySpecifier2
class startIndex ( thru | through ) stopIndex
pluralClass startIndex ( thru | through ) stopIndex```
##### Placeholders
A singular class (such aswindoworword).
A plural class (such aswindowsorwords).
Specifiers to objects that bound the range. The range includes the boundary objects. You can use the reserved wordbeginningin place ofboundarySpecifier1to indicate the position before the first object of the container. Similarly, you can use the reserved wordendin place ofboundarySpecifier2to indicate the position after the last object in the container.
The indexes of the first and last object of the range (such as1and10inwords 1 thru 10).
Though integer indexes are the most common class, the start and stop indexes can be of any class. An application determines which index classes are meaningful to it.
##### Value
The value of a range reference form is a list of the objects in the range. If the specified container does not contain objects of the specified class, or if the range is out of bounds, an error is returned. For example, the following range specifier results in an error because there are no words in the list:
```
words 1 thru 3 of {1, 2, 3} --result: an error```
##### Examples
The following example shows the boundary object form of a range specifier. When you compile this statement, Script Editor convertsfrom integer 1 to integer 2to the formintegers 1 thru 2.
```
set intList to integers from integer 1 to integer 2 of {17, 33, 24}```
```
--result: {17, 33}```
In the next example, the phrasefolders 3 thru 4is a range specifier that specifies a list of two folders in the containerstartup disk:
```
tell application "Finder"```
```
folders 3 thru 4 of startup disk```
```
end tell```
```
--result: a list of folders (depends on contents of startup disk)```
##### Discussion
If you specify a range specifier as the container for a property or object, as in
```
name of folders 2 thru 3 of startup disk```
the result is a list containing the specified property or object for each object of the container. The number of items in the list is the same as the number of objects in the container.
To obtain a contiguous series of charactersâinstead of a listâfrom atextobject, use thetextclass:
```
text from word 1 to word 4 of "We're all in this together"```
```
--result: "We're all in this"```
```
words 1 thru 4 of "We're all in this together"```
```
--result: {"We're", "all", "in", "this"}```
Specifies an object or an insertion point in a container by describing a position in relation to another object, known as the base, in the same container.
##### Syntax
```
[ class ] ( before | [in] front of ) baseSpecifier
[ class ] ( after | [in] back of | behind ) baseSpecifier```
##### Placeholders
The class identifier of the specified object. If you omit this parameter, the specifier refers to an insertion point.
A specifier for the object.
These forms are equivalent, and refer to the object immediately preceding the base object.
These forms are equivalent, and refer to the object immediately after the base.
These forms are equivalent, and refer to the first insertion point of the container (insertion point 1).
These forms are equivalent, and refer to the last insertion point of the container (insertion point -1).
Although terms such asbeginningandendsound like absolute positions, they are relative to the existing contents of a container (that is, before or after the existing contents).
##### Examples
The two relative specifiers in the followingtellblock specify the same file by identifying its position relative to another file on a disk:
```
tell application "Finder"```
```
item before item 3 of startup disk --result: e.g., a specifier```
```
item after item 1 of startup disk --result: e.g., a specifier```
```
end tell```
The following example shows how to use various relative specifiers in a word processing document:
```
tell first document of application "TextEdit"```
```
copy word 1 to before paragraph 3```
```
copy word 3 to in back of paragraph 4```
```
copy word 1 of the last paragraph to behind the third paragraph```
```
end tell```
##### Discussion
Therelativereference form generally works only when theindexform also works.
You can specify only a single object with a relative specifierâan object that is either before or after the base object.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# AppleScript Lexical Conventions
This chapter provides an overview of the vocabulary and conventions of the AppleScript Language. It starts with the character set and introduces elements of increasing complexity.
After reading this chapter, you should have an understanding of the basic language components used to construct AppleScript expressions and statements.
AppleScript Lexical Conventions contains the following sections:
- Character Set
Character Set
- Identifiers
Identifiers
- Keywords
Keywords
- Comments
Comments
- The Continuation Character
The Continuation Character
- Literals and Constants
Literals and Constants
- Operators
Operators
- Variables
Variables
- Expressions
Expressions
- Statements
Statements
- Commands
Commands
- Results
Results
- Raw Codes
Raw Codes
## Character Set
Starting in OS X v10.5 (AppleScript 2.0),the character set for AppleScript is Unicode. AppleScript preserves all characters correctly worldwide, and comments and text constants in scripts may contain any Unicode characters.
AppleScript syntax uses several non-ASCII characters, which can be typed using special key combinations. For information on characters that AppleScript treats specially, see the sectionsIdentifiers,Comments,Text,The Continuation Character, andRaw Codesin this chapter, as well asTable 9-1inOperators Reference.
## Identifiers
An AppleScriptidentifieris a series of characters that identifies a class name, variable, or other language element, such as labels for properties and handlers.
An identifier must begin with a letter and can contain any of these characters:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_```
Identifiers are not case sensitive. For example, the identifiersmyvariableandMyVariableare equivalent.
AppleScript remembers and enforces the first capitalization it comes across for an identifier. So if it first encounters an identifier asmyAccount, it will later, during compilation, change versions such asMyAccountandmyaccounttomyAccount.
The following are examples of valid identifiers:areaOfCircle,Agent007,axis_of_rotation.
The following are not valid identifiers:C-,back&forth,999,Why^Not.
AppleScript provides a loophole to the preceding rules: identifiers whose first and last characters are vertical bars (|) can contain any characters. The leading and trailing vertical bars are not considered part of the identifier.
Important:This use of vertical bars can make scripts difficult to read, and is not recommended.
The following are legal identifiers:|back&forth|,|Right*Now!|.
An identifier can contain additional vertical bars preceded by a backslash (\) character, as in the identifier|This\|Or\|That|. Use of the backslash character is described further in the Special String Characters section of thetextclass.
## Keywords
Akeywordis a reserved word in the AppleScript language. Keywords consist of lower-case, alphabetic characters:abcdefghijklmnopqrstuvwxyz. In a few cases, such asaside from, they come in pairs.
Important:You should not attempt to reuse keywords in your scripts for variable names or other purposes. Developers should not re-define keywords in the terminology for their scriptable applications.
Table 1-1lists the keywords reserved in AppleScript 2.0 (which are the same as those used in AppleScript 1.x). For additional information, seeTable A-1, which provides a brief description for each keyword and points to related information, where available.
about
above
after
against
apart from
around
aside from
back
before
beginning
behind
below
beneath
beside
between
considering
contain
contains
contains
continue
copy
does
eighth
else
equal
equals
error
every
exit
false
fifth
first
fourth
from
front
given
global
ignoring
instead of
into
last
local
middle
ninth
onto
out of
over
prop
property
reference
repeat
return
returning
script
second
seventh
since
sixth
some
tell
tenth
that
then
third
through
thru
timeout
times
transaction
true
until
where
while
whose
with
without
## Comments
Acommentis text that is ignored by AppleScript when a script is executed. You can use comments to describe what is happening in the script or make other kinds of notes. There are three kinds of comments:
- A block comment begins with the characters(*and ends with the characters*). Block comments must be placed between other statements. That means they can be placed on the same line at the beginning or end of a statement, but cannot be embedded within a simple (one-line) statement.
A block comment begins with the characters(*and ends with the characters*). Block comments must be placed between other statements. That means they can be placed on the same line at the beginning or end of a statement, but cannot be embedded within a simple (one-line) statement.
- An end-of-line comment begins with the characters--(two hyphens) and ends with the end of the line:--end-of-line comments extend to the end of the line
An end-of-line comment begins with the characters--(two hyphens) and ends with the end of the line:
```
--end-of-line comments extend to the end of the line```
- Starting in version 2.0, AppleScript also supports use of the # symbol as an end-of-line comment. This allows you to make a plain AppleScript script into aUnix executable by beginning it with the following line and giving it execute permission:#!/usr/bin/osascriptCompiled scripts that use#will run normally on pre-2.0 systems, and if edited will display using--. Executable text scripts using#!/usr/bin/osascriptwill not run on pre-2.0 systems, since the#will be considered a syntax error.
Starting in version 2.0, AppleScript also supports use of the # symbol as an end-of-line comment. This allows you to make a plain AppleScript script into aUnix executable by beginning it with the following line and giving it execute permission:
```
#!/usr/bin/osascript```
Compiled scripts that use#will run normally on pre-2.0 systems, and if edited will display using--. Executable text scripts using#!/usr/bin/osascriptwill not run on pre-2.0 systems, since the#will be considered a syntax error.
You can nest commentsâthat is, comments can contain other comments, as in this example:
```
(* Here are some```
```
--nested comments```
```
(* another comment within a comment *)```
```
*)```
## The Continuation Character
A simple AppleScript statement must normally be entered on a single line. You can extend a statement to the next line by ending it with thecontinuation character, ¬. With a U.S. keyboard, you can enter this character by typing Option-l (lower-case L). In Script Editor, you can type Option-Return, which inserts the continuation character and moves the insertion point to the next line.
Here is a single statement displayed on two lines:
```
display dialog "This is just a test." buttons {"Great", "OK"} ¬```
```
default button "OK" giving up after 3```
A continuation character within a quoted text string is treated like any other character.
## Literals and Constants
Aliteralis a value that evaluates to itselfâthat is, it is interpreted just as it is written. In AppleScript, for example,"Hello"is a text literal. Aconstantis a word with a predefined value. For example, AppleScript defines a number of enumerated constants for use with thepath to (folder)command, each of which specifies a location for which to obtain the path.
### Boolean
AppleScript defines theBoolean valuestrueandfalseand supplies thebooleanclass.
### Constant
Global Constants in AppleScriptdescribes constants that can be used throughout your scripts. For related information, see theconstantclass.
### List
A list defines an ordered collection of values, known as items, of any class. As depicted in a script, a list consists of a series of expressions contained within braces and separated by commas, such as the following:
```
{1, 7, "Beethoven", 4.5}```
A list can contain other lists. An empty list (containing no items) is represented by a pair of empty braces:{}.
AppleScript provides thelistclass for working with lists.
### Number
Anumeric literal is a sequence of digits, possibly including other characters, such as a unary minus sign, period (in reals), or"E+"(in exponential notation). The following are some numeric literals:
```
-94596```
```
3.1415```
```
9.9999999999E+10```
AppleScript defines classes for working withrealandintegervalues, as well as thenumberclass, which serves as a synonym for eitherrealorinteger.
### Record
A record is an unordered collection of labeled properties. A record appears in a script as a series of property definitions contained within braces and separated by commas. Each property definition consists of a unique label, a colon, and a value for the property. For example, the following is a record with two properties:
```
{product:"pen", price:2.34}```
### Text
Atextliteral consists of a series of Unicode characters enclosed in a pair of double quote marks, as in the following example:
```
"A basic string."```
AppleScripttextobjects are instances of thetextclass, which provides mechanisms for working with text. The Special String Characters section of that class describes how to use white space, backslash characters, and double quotes in text.
## Operators
Anoperatoris a symbol, word, or phrase that derives a value from another value or pair of values. For example, the multiplication operator (*) multiplies two numeric operands, while the concatenation operator (&) joins two objects (such as text strings). Theis equaloperator performs a test on two Boolean values.
For detailed information on AppleScriptâs operators, seeOperators Reference.
## Variables
Avariableis a named container in which to store a value. Its name, which you specify when you create the variable, follows the rules described inIdentifiers. You can declare and initialize a variable at the same time with acopyorsetcommand. For example:
```
set myName to "John"```
```
copy 33 to myAge```
Statements that assign values to variables are known asassignment statements.
When AppleScript encounters a variable, it evaluates the variable by getting its value. A variable is contained in a script and its value is normally lost when you close the script that contains it.
AppleScript variables can hold values of any class. For example, you can assign the integer value17to a variable, then later assign the Boolean valuetrueto the same variable.
For more information, seeVariables and Properties.
## Expressions
Anexpressionis any series of lexical elements that has a value. Expressions are used in scripts to represent or derive values. The simplest kinds of expressions, called literal expressions, are representations of values in scripts. More complex expressions typically combine literals, variables, operators, and object specifiers.
When you run a script, AppleScript converts its expressions into values. This process is known asevaluation. For example, when the following simple expression is evaluated, the result is 21:
```
3 * 7 --result: 21```
An object specifierspecifies some or all of the information needed to find another object. For example, the following object specifier specifies a named document:
```
document named "FavoritesList"```
For more information, seeObject Specifiers.
## Statements
Astatementis a series of lexical elements that follows a particular AppleScript syntax. Statements can include keywords, variables, operators, constants, expressions, and so on.
Every script consists of statements. When AppleScript executes a script, it reads the statements in order and carries out their instructions.
Acontrol statementis a statement that determines when and how other statements are executed. AppleScript defines standard control statements such asif,repeat, andwhilestatements, which are described in detail inControl Statements Reference.
Asimple statementis one that can be written on a single line:
```
set averageTemp to 63 as degrees Fahrenheit```
Note:You can use a continuation character (¬) to extend a simple statement onto a second line.
Acompound statementis written on more than one line, can contain other statements, and has the wordend(followed, optionally, by the first word of the statement) in its last line. For example the following is a compoundtellstatement:
```
tell application "Finder"```
```
set savedName to name of front window```
```
close window savedName```
```
end tell```
A compound statement can contain other compound statements.
## Commands
Acommandis a word or series of words used in an AppleScript statement to request an action. Every command is directed at atarget, which is the object that responds to the command. The target is usually an application object or an object in macOS, but it can also be ascriptobject or a value in the current script.
The following statement uses AppleScriptâsgetcommand to obtain the name of a window; the target is the front window of the Finder application:
```
get name of front window of application "Finder"```
For more information on command types, parameters, and targets, seeCommands Overview.
## Results
Theresultof a statement is the value generated, if any, when the statement is executed. For example, executing the statement3 + 4results in the value7. The result of the statementset myText to "keyboard"is the text object"keyboard". A result can be of any class. AppleScript stores the result in the globally available propertyresult, described inAppleScript Constant.
## Raw Codes
When you open, compile, edit, or run scripts with a script editor, you may occasionally see terms enclosed in double angle brackets, or chevrons(«»), in a script window or in another window. These terms are calledraw formatorraw codes, because they represent the underlying Apple event codesthat AppleScript uses to represent scripting terms.
For compatibility with Asian national encodings, âãâ and âãâ are allowed as synonyms for â«â and â»â ( (Option- \ and Option-Shift- \, respectively, on a U.S. keyboard), since the latter do not exist in some Asian encodings.
For more information on raw codes, seeDouble Angle Brackets.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# AppleScript Fundamentals
This chapter describes basic concepts that underlie the terminology and rules covered in the rest of this guide.
- Script Editor Application
Script Editor Application
- AppleScript and Objects
AppleScript and Objects
- Object Specifiers
Object Specifiers
- Coercion (Object Conversion)
Coercion (Object Conversion)
- Scripting Additions
Scripting Additions
- Commands Overview
Commands Overview
- AppleScript Error Handling
AppleScript Error Handling
- Global Constants in AppleScript
Global Constants in AppleScript
- The it and me Keywords
The it and me Keywords
- Aliases and Files
Aliases and Files
- Remote Applications
Remote Applications
- Debugging AppleScript Scripts
Debugging AppleScript Scripts
## Script Editor Application
The Script Editor application is located in/Applications/Utilities. It provides the ability to edit, compile, and execute scripts, display application scripting terminologies, and save scripts in a variety of formats, such as compiled scripts, applications, and plain text.
Script Editor can display the result of executing an AppleScript script and can display a log of the Apple events that are sent during execution of a script. In the Script Editor Preferences, you can also choose to keep a history of recent results or event logs.
Script Editor has text formatting preferences for various types of script text, such as language keywords, comments, and so on. You can also turn on or off the Script Assistant, a code completion tool that can suggest and fill in scripting terms as you type. In addition, Script Editor provides a contextual menu to insert many types of boilerplate script statements, such as conditionals, comments, and error handlers.
Adictionaryis the part of a scriptable application that specifies the scripting terms it understands. You can choose File > Open Dictionary in Script Editor to display the dictionaryof a scriptable application or scripting addition on your computer. Or you can drag an application icon to the Script Editor icon to display its dictionary (if it has one).
To display a list that includes just the scriptable applications and scripting additions provided by macOS, choose Window > Library. Double-click an item in the list to display its dictionary.Figure 2-1shows the dictionary for the Finder application in OS X v10.5. The dictionary is labeled as âFinder.sdefâ. The sdef format, along with other terminology formats, is described in âSpecifying Scripting Terminologyâ inAppleScript Overview.
There are also third-party editors for AppleScript.
## AppleScript and Objects
AppleScript is an object-oriented language. When you write, compile, and execute scripts, everything you work with is an object. Anobjectis an instantiation of a class definition, which can include properties and actions. AppleScript defines classes for the objects you most commonly work with, starting with the top-levelscriptobject, which is the overall script you are working in.
Within in ascriptobject, you work with other objects, including:
- AppleScript objects:AppleScript defines classes for boolean values, scripts, text, numbers, and other kinds of objects for working in scripts; for a complete list, seeClass Reference.
AppleScript objects:
AppleScript defines classes for boolean values, scripts, text, numbers, and other kinds of objects for working in scripts; for a complete list, seeClass Reference.
- macOS objects:Scriptable parts of macOS and applications distributed with it, such as Finder, System Events, and Database Events (located in/System/Library/CoreServices), define many useful classes.
macOS objects:
Scriptable parts of macOS and applications distributed with it, such as Finder, System Events, and Database Events (located in/System/Library/CoreServices), define many useful classes.
- Application objects:Third-party scriptable applications define classes that support a wide variety of features.
Application objects:
Third-party scriptable applications define classes that support a wide variety of features.
The following sections provide more detail about objects:
- What Is in a Script Object
What Is in a Script Object
- Properties
Properties
- Elements
Elements
### What Is in a Script Object
When you enter AppleScript statements in script window in Script Editor, you are working in a top-levelscriptobject. Allscriptobject definitions follow the same syntax, except that a top-levelscriptobject does not have statements marking its beginning and end.
Ascriptobject can contain the following:
- Property definitions (optional):A property is a labeled container in which to store a value.
Property definitions (optional):
A property is a labeled container in which to store a value.
- An explicitrunhandler (optional):Arunhandler contains statements AppleScript executes when the script is run. (For more information, seerun Handlers.)
An explicitrunhandler (optional):
Arunhandler contains statements AppleScript executes when the script is run. (For more information, seerun Handlers.)
- An implicitrunhandler (optional):An implicitrunhandler consists of any statements outside of any contained handlers orscriptobjects.
An implicitrunhandler (optional):
An implicitrunhandler consists of any statements outside of any contained handlers orscriptobjects.
- Additional handlers (optional):A handler is the equivalent of a subroutine. (For details, seeAbout Handlers.)
Additional handlers (optional):
A handler is the equivalent of a subroutine. (For details, seeAbout Handlers.)
- Additionalscriptobjects (optional):Ascriptobject can contain nestedscriptobjects, each of which is defined just like a top-levelscriptobject, except that a nestedscriptobject is bracketed with statements that mark its beginning and end. (For details, seeScript Objects.)
Additionalscriptobjects (optional):
Ascriptobject can contain nestedscriptobjects, each of which is defined just like a top-levelscriptobject, except that a nestedscriptobject is bracketed with statements that mark its beginning and end. (For details, seeScript Objects.)
Here is an example of a simple script with one property, one handler, one nestedscriptobject, and an implicitrunhandler with two statements:
```
property defaultClientName : "Mary Smith"```
```
```
```
on greetClient(nameOfClient)```
```
display dialog ("Hello " & nameOfClient & "!")```
```
end greetClient```
```
```
```
script testGreet```
```
greetClient(defaultClientName)```
```
end script```
```
```
```
run testGreet --result: "Hello Mary Smith!"```
```
greetClient("Joe Jones") --result: "Hello Joe Jones!"```
The first statement in therunhandler isrun testGreet, which runs the nestedscriptobjecttestGreet. Thatscriptobject calls the handlergreetClient(), passing the propertydefaultClientName. The handler displays a dialog, greeting the default client, Mary Smith.
The second statement in therunhandler callsgreetClient()directly, passing the string"Joe Jones".
### Properties
Apropertyof an object is a characteristic that has a single value and a label, such as thenameproperty of a window or themonthproperty of a date. The definition for any AppleScript class includes the name and class for each of its properties. Property names must be unique within a class. Property values can be read/write or read only.
The AppleScriptdateclass, for example, defines both read/write and read only properties. These include theweekdayproperty, which is read only, and themonth,day, andyearproperties, which are read/write. Thatâs because the value of theweekdayproperty depends on the other propertiesâyou canât set an arbitrary weekday for an actual date.
The class of a property can be a simple class such asbooleanorinteger, a composite class such as apointclass (made up of two integers), or a more complex class.
Most classes only support predefined properties. However, for thescriptclass, AppleScript lets you to define additional properties. For information on how to do this, seeDefining Properties. You can also define properties forrecordobjects.
### Elements
Anelementis an object contained within another object. The definition for any AppleScript class includes the element types it can contain. An object can typically contain zero or more of each of its elements.
For a given element type, an object can contain many elements or none, and the number of elements that it contains may change over time. For example, it is possible for alistobject to contain no items (it can be an empty list). At a later time, the same list might contain many items.
Whether you can add elements to or remove elements from an object depends on the class and the element. For example, atextobject is immutableâyou cannot add or remove text once the object is created. For alistobject, you cannot remove items, but you can use thesetcommand to add an item to the beginning or end:
```
set myList to {1, "what", 3} --result: {1, "what", 3}```
```
set beginning of myList to 0```
```
set end of myList to "four"```
```
myList --result: {0, 1, "what", 3, "four"}```
## Object Specifiers
Anobject specifierspecifies the information needed to find another object in terms of the objects in which it is contained. An object specifier can refer to an application object, such as a window or file, or to an AppleScript object, such as an item in a list or a property in a record.
An object specifier is fully evaluated (or resolved) only when a script is run, not when it is compiled. A script can contain a valid object specifier (such asthird document of application "TextEdit"that causes an error when the script is executed (because, for example, there may be less than three documents open).
Applications typically return object specifiers in response to commands. For example, if you ask the Finder for a window, it returns information that specifies the window object your script asked for (if it exists). The top-level container in an object specifier is typically the application itself.
You create an object specifier every time your script uses a phrase that describes the path to an object or property, such asname of window 1 of application "Finder". When you use thea reference tooperator, it creates areferenceobject that wraps an object specifier.
The difference between an object specifier and the object it refers to is like the difference between a building address and the building itself. The address is a series of words and numbers, such as â2121 Oak Street, San Francisco, CAâ that identifies a location (on a street, in a city, in a state). It is distinct from the building itself. If the building at that location is torn down and replaced with a new building, the address remains the same.
### What Is in an Object Specifier
An object specifier describes an object type, a location, and how to distinguish the object from other objects of the same type in that location. These three types of informationâthe type, or class; the location, or container; and the distinguishing information, or reference formâallow you to specify any object.
In the following example, the class of the object isparagraph. The container is the phraseof document 1. Because this phrase is inside atellstatement, thetellstatement provides the top-level container,of application "TextEdit". The distinguishing information (the reference form) is the combination of the class,paragraph, and an index value,1, which together indicate the first paragraph.
```
tell application "TextEdit"```
```
paragraph 1 of document 1```
```
end tell```
Note:If you examine the dictionary for the TextEdit application, you might think this script should sayparagraph 1 of text of document 1. However, where the meaning is unambiguous, some applications make life easier for scripters by allowing them to omit a container from an object specifier. TextEdit uses this feature in supplying animplicitly specified subcontainerfor the text in a document. That is, if an object specifier identifies an object, such as a word or paragraph, that is contained in a documentâs text, TextEdit automatically supplies theof textpart of the object specifier.
In addition to the index reference form, you can specify objects in a container by name, by range, by ID, and by the other forms described inReference Forms.
### Containers
A container is an object that contains one or more objects or properties. In an object specifier, a container specifies where to find an object or a property. To specify a container, use the wordoforin, as in the following statement (from a Findertellblock):
```
folder "Applications" of startup disk```
A container can be an object or a series of objects, listed from the innermost to the outermost containing object, as in the following:
```
tell application "Finder"```
```
first item of first folder of first disk```
```
end tell```
You can also use the possessive form ('s) to specify containers. In the following example, the innermost container isfirst windowand the object it contains is anameproperty:
```
tell application "TextEdit"```
```
first window's name```
```
end tell```
In this example, the target of thetellstatement ("TextEdit") is the outer container for the object specifier.
### Absolute and Relative Object Specifiers
Anabsolute object specifierhas enough information to identify an object or objects uniquely. It can be used unambiguously anywhere in a script. For a reference to an application object to be absolute, its outermost container must be the application itself, as in:
```
version of application "Finder" --result: "10.5.1"```
In contrast,arelative object specifierdoes not specify enough information to identify an object or objects uniquely; for example:
```
name of item 1 of disk 2```
When AppleScript encounters a relative object specifier in atellstatement, it attempts to use the default target specified by the statement to complete the object specifier. Though it isnât generally needed, this implicit target can be specified explicitly using the keywordit, which is described inThe it and me Keywords.
The default target of atellstatement is the object that receives commands if no other object is specified. For example, the followingtellstatement tells the Finder to get a name using the previous relative object specifier.
```
tell application "Finder"```
```
name of item 1 of disk 2```
```
end tell```
When AppleScript encounters a relative object specifier outside anytellstatement, it tries to complete the object specifier by looking up the inheritance chain described inInheritance in Script Objects.
### Object Specifiers in Reference Objects
When you can create areferenceobject with thea reference tooperator, it contains an object specifier. For example:
```
tell application "TextEdit"```
```
set docRef to a reference to the first document```
```
--result: document 1 of application "TextEdit"```
```
-- an object specifier```
```
name of docRef --result: "New Report.rtf"```
```
-- name of the specified object```
```
end tell```
In this script, the variabledocRefis a reference whose object specifier refers to the first document of the application TextEditâwhich happens to be named âNew Report.rtfâ in this case. However, the object thatdocRefrefers to can change. If you open a second TextEdit document called âSecond Report.rtfâ so that its window is in front of the previous document, then run this script again, it will return the name of the now-frontmost document, âSecond Report.rtfâ.
You could instead create a reference with a more specific object specifier:
```
tell application "TextEdit"```
```
set docRef to a reference to document "New Report.rtf"```
```
--result: document "New Report.rtf" of application "TextEdit"```
```
name of docRef --result: "New Report.rtf"```
```
end tell```
If you run this script after opening a second document, it will still return the name of the original document, âNew Report.rtfâ, if the document exists.
After you create areferenceobject with thea reference tooperator, you can use thecontentsproperty to get the value of the object that it refers to. That is, using thecontentsproperty causes the referenceâs object specifier to be evaluated. In the following script, for example, the content of the variablemyWindowis the window reference itself.
```
set myWindow to a ref to window "Q1.rtf" of application "TextEdit"```
```
myWindow```
```
-- result: window "Q1.rtf" of application "TextEdit" (object specifier)```
```
contents of myWindow```
```
--result: window id 283 of application "TextEdit" (an evaluated window)```
```
get myWindow```
```
-- result: window "Q1.rtf" of application "TextEdit" (object specifier)```
Note that the result of thegetcommand is to return the referenceâs object specifier, not to resolve the specifier to the object it specifies.
When it can, AppleScript will implicitly dereference a reference object (without use of thecontentsproperty), as in the following example:
```
set myWindow to a ref to window 1 of application "TextEdit"```
```
name of myWindow --result: "Q1.rtf" (if that is the first window's name)```
For related information, see the Discussion section for thereferenceclass.
## Coercion (Object Conversion)
Coercion(also known asobject conversion) is the process of converting objects from one class to another. AppleScript converts an object to a different class in either of these circumstances:
- in response to theasoperator
in response to theasoperator
- automatically, when an object is of a different class than was expected for a particular command or operation
automatically, when an object is of a different class than was expected for a particular command or operation
Not all classes can be coerced to all other class types.Table 2-1summarizes the coercions that AppleScript supports for commonly used classes. For more information about each coercion, see the corresponding class definition inClass Reference.
AppleScript provides many coercions, either as a built-in part of the language or through the Standard Additions scripting addition. You can use these coercions outside of atellblock in your script. However, coercion of application class types may be dependent on the application and require atellblock that targets the application.
Theasoperator specifies a specific coercion or set of coercions. For example, the following statement coerces the integer2into the text"2"before storing it in the variablemyText:
```
set myText to 2 as text```
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. If the conversion canât be performed, AppleScript reports an error.
When coercingtextstrings to values of classinteger,number, orreal, or vice versa, AppleScript uses the current Numbers settings in the Formats pane in International preferences to determine what separators to use in the string. When coercing strings to values of classdateor vice versa, AppleScript uses the current Dates settings in the Formats pane.
Convert from class
To class
Notes
alias
list(single-item)
text
application
list(single-item)
This is both an AppleScript class and an application class.
boolean
integer
list(single-item)
text
class
list(single-item)
text
constant
list(single-item)
text
date
list(single-item)
text
file
list(single-item)
text
integer
list(single-item)
real
text
Coercing anintegerto anumberdoes not change its class.
list(single-item)
any class to which the item can be coerced if it is not part of a list
list(multiple-item)
text, if each of the items in the list can be coerced to atextobject
number
integer
list(single-item)
real
text
Values identified as values of classnumberare really values of either classintegeror classreal.
POSIX file
seefile
POSIX fileis a pseudo-class equivalent to thefileclass.
real
integer
list(single-item)
In coercing tointeger, any fractional part is rounded.
Coercing arealto anumberdoes not change its class.
record
list
All labels are lost in the coercion and the resulting list cannot be coerced back to a record.
reference
any class to which the referenced object can be coerced
script
list(single-item)
text
integer
list(single-item)
real
Can coerce tointegerorrealonly if thetextobject represents an appropriate number.
unit types
integer
list(single-item)
real
text
Can coerce between unit types in the same category, such asinchestokilometers(length) orgallonstoliters(liquid volume).
## Scripting Additions
Ascripting additionis a file or bundle that provides handlers you can use in scripts to perform commands and coercions.
Many of the commands described in this guide are defined in the Standard Additions scripting addition in macOS. These commands are stored in the fileStandardAdditions.osaxin/System/Library/ScriptingAdditions, and are available to any script. You can examine the terminology for the Standard Additions by opening this file in Script Editor.
Note:A script can obtain the location of the Standard Additions with this script statement, which uses thepath to (folder)command:
path to scripting additions as text--result: "Hard_Disk:System:Library:ScriptingAdditions:"
```
path to scripting additions as text```
```
--result: "Hard_Disk:System:Library:ScriptingAdditions:"```
Scripting additions can be embedded within bundled script applets by placing them in a folder namedScripting Additions(note the space between âScriptingâ and âAdditionsâ) inside the bundleâÂsContents/Resources/folder. Note that Script Editor does not look for embedded scripting additions when editing bundled applets. During script development, any required scripting additions must be properly installed in/System/ScriptingAdditions,/Library/ScriptingAdditions, or~/Library/ScriptingAdditionsso that Script Editor can find them.
Developers can create their own scripting additions, as described in Technical Note TN1164,Scripting Additions for Mac OS X. For related conceptual information, seeAppleScript Overview, particularly the section âExtending AppleScript with Coercions, Scripting Additions, and Faceless Background Applicationsâ in the chapterOpen Scripting Architecture.
## Commands Overview
Acommandis a word or a series of words used in AppleScript statements to request an action. Every command is directed at atarget, which is the object that responds to the command. The target is often anapplication object(one that is stored in an application or its documents and managed by the application, such as a window or document) or an object in macOS. However, it can also be ascriptobject or a value in the current script.
Commands often return results. For example, thedisplay dialogcommand returns a record that may contain text, a button name, and other information. Your script can examine this record to determine what to do next. You can assign the result of a command to a variable you define, or access it through the predefined AppleScriptresultvariable.
### Types of Commands
Scripts can make use of the following kinds of commands:
- AnAppleScript commandis one that is built into the AppleScript language. There currently are five such commands:get,set,count,copy, andrun. Except forcopy, each of these commands can also be implemented by applications. That is, there is an AppleScript version of the command that works on AppleScript objects, but an application can define its own version that works on the object types it defines.
AnAppleScript commandis one that is built into the AppleScript language. There currently are five such commands:get,set,count,copy, andrun. Except forcopy, each of these commands can also be implemented by applications. That is, there is an AppleScript version of the command that works on AppleScript objects, but an application can define its own version that works on the object types it defines.
- Ascripting addition commandis one that is implemented through the mechanism described inScripting Additions). Although anyone can create a scripting addition (see Technical Note TN1164,Scripting Additions for Mac OS X), this guide documents only the scripting addition commands from the Standard Additions, supplied by Apple as part of macOS. These commands are available to all scripts.
Ascripting addition commandis one that is implemented through the mechanism described inScripting Additions). Although anyone can create a scripting addition (see Technical Note TN1164,Scripting Additions for Mac OS X), this guide documents only the scripting addition commands from the Standard Additions, supplied by Apple as part of macOS. These commands are available to all scripts.
- Auser-defined commandis one that is implemented by a handler defined in ascriptobject. To invoke a user-defined command outside of atellstatement, simply use its name and supply values for any parameters it requires. The command will use the current script as its target.To invoke a user-defined command inside atellstatement, seeCalling Handlers in a tell Statement.
Auser-defined commandis one that is implemented by a handler defined in ascriptobject. To invoke a user-defined command outside of atellstatement, simply use its name and supply values for any parameters it requires. The command will use the current script as its target.
To invoke a user-defined command inside atellstatement, seeCalling Handlers in a tell Statement.
- Anapplication commandis one that is defined by scriptable application to provide access to a scriptable feature. They are typically enclosed in atellstatement that targets the application. You can determine which commands an application supports by examining its dictionary in Script Editor.Scriptable applications that ship with macOS, such as the Finder and System Events applications (located in/System/Library/CoreServices), provide many useful scripting commands.Third-party scriptable applications also provide commands you can use in scripts. Many support all or a subset of the Standard commands, described in Technical Note TN2106,Scripting Interface Guidelines. These include commands such asdelete,duplicate,exists, andmove, as well as application implementations of AppleScript commands, such asgetandset.
Anapplication commandis one that is defined by scriptable application to provide access to a scriptable feature. They are typically enclosed in atellstatement that targets the application. You can determine which commands an application supports by examining its dictionary in Script Editor.
Scriptable applications that ship with macOS, such as the Finder and System Events applications (located in/System/Library/CoreServices), provide many useful scripting commands.
Third-party scriptable applications also provide commands you can use in scripts. Many support all or a subset of the Standard commands, described in Technical Note TN2106,Scripting Interface Guidelines. These include commands such asdelete,duplicate,exists, andmove, as well as application implementations of AppleScript commands, such asgetandset.
### Target
There are two ways to explicitly specify an object as the target of a command: by supplying it as the direct parameter of the command (described in the next section) or by specifying it as the target of atellstatement that contains the command. If a script doesnât explicitly specify the target with atellstatement, and it isnât handled by a handler in the script or by AppleScript itself, it is sent to the next object in the inheritance chain (seeThe AppleScript Inheritance Chain).
In the following script, the target of thegetcommand is the object specifiername of first window. Because the enclosingtellstatement specifies the Finder application, the full specifier isname of first window of application "Finder", and it is the Finder application which obtains and returns the requested information.
```
tell application "Finder"```
```
get name of first window```
```
end tell```
When a command targets an application, the result may be an application object. If so, subsequent statements that target the result object are sent to the application.
A script may also implicitly specify a target by using an application command imported using aNotestatement. For example, theextract addresscommand in the following script targets the Mail application because the command was imported from Mail:
```
use application "Mail"```
```
extract address from "John Doe "```
### Direct Parameter
Thedirect parameteris a value, usually an object specifier, that appears immediately next to a command and specifies the target of the command. Not all commands have a direct parameter. If a command can have a direct parameter, it is noted in the commandâs definition.
In the following statement, the object specifierlast file of window 1 of application "Finder"is the direct parameter of theduplicatecommand:
```
duplicate last file of window 1 of application "Finder"```
The direct parameter usually appears immediately after the command, but may also appear immediately before it. This can be easier to read for some commands, such asexistsin this example:
```
if file "semaphore" of application "Finder" exists then```
```
-- continue processing...```
```
end if```
Atellstatement specifies a default target for all commands contained within it, so the direct parameter is optional. The following example has the same result as the previous example:
```
tell last file of window 1 of application "Finder"```
```
duplicate```
```
end tell```
### Parameters That Specify Locations
Many commands have parameters that specify locations. A location can be either an insertion point or another object. Aninsertion pointis a location where an object can be added.
In the following example, thetoparameter specifies the location to which to move the first paragraph. The value of thetoparameter of theduplicatecommand is the relative object specifierbefore paragraph 4, which is an insertion point. AppleScript completes the specifier with the target of thetellstatement,front document of application "TextEdit".
```
tell front document of application "TextEdit"```
```
duplicate paragraph 1 to before paragraph 4```
```
end tell```
The phrasesparagraph 1andbefore paragraph 4are called index and relative references, respectively. For more information, seeReference Forms.
## AppleScript Error Handling
During script execution, errors may occur due to interaction with macOS, problems encountered in an application script command, or problems caused by statements in the script itself. When an error occurs, AppleScript stops execution at the current location, signals an error, and looks up the calling chain for script statements that can handle the error. That is, it looks for the nearest error-handling code block that surrounds the location where the error occurred.
Scripts can handle errors by enclosing statements that may encounter an error within atrystatement. Thetrystatement includes anon errorsection that is invoked if an error occurs. AppleScript passes information about the error, including an error number and an error message, to theon errorsection. This allows scripts to examine the error number and to display information about it.
If the error occurs within a handler that does not provide atrystatement, AppleScript looks for an enclosingtrystatement where the handler was invoked. If none of the calls in the call chain is contained in atrystatement, AppleScript stops execution of the script and displays an error message (for any error number other than -128, described below).
A script can use anerrorstatement to signal an error directly. Doing so invokes the AppleScript error handling mechanism, which looks for an enclosingtrystatement to handle the error.
Some âerrorsâ are the result of the normal operation of a command. For example, commands such asdisplay dialogandchoose filesignalerror â128(User canceled), if the user clicks the Cancel button. Scripts routinely handle the user canceled error to ensure normal operation. For an example of how to do this, see the Examples section for thedisplay dialogcommand. If notrystatement in a script handles the -128 error, AppleScript halts execution of the script without displaying any error message.
For related information, seeResults,error Statements,try Statements,Error Numbers and Error Messages, andWorking with Errors.
## Global Constants in AppleScript
AppleScript defines a number of global constants that you can use anywhere in a script.
### AppleScript Constant
The global constantAppleScriptprovides access to properties you can use throughout your scripts.
You can use theAppleScriptidentifier itself to distinguish an AppleScript property from a property of the current target with the same name, as shown in the sectionversion.
The following sections describe additional properties ofAppleScript.
#### pi
Thismathematicalvalue represents the ratio of a circle's circumference to its diameter. It is defined as a real number with the value 3.14159265359.
For example, the following statement computes the area of a circle with radius 7:
```
set circleArea to pi * 7 * 7 --result: 153.9380400259```
#### result
When a statement is executed, AppleScript stores the resulting value, if any, in the predefined propertyresult. The value remains there until another statement is executed that generates a value. Until a statement that yields a result is executed, the value ofresultis undefined. You can examine the result in Script Editor by looking in the Result pane of the script window.
Note:When an error occurs during script execution, AppleScript signals an error. It doesnât return error information in theresultproperty. For more information, seeAppleScript Error Handling.
#### Text Constants
AppleScript defines the text propertiesspace,tab,return,linefeed, andquote. You effectively use these properties as text constants to represent white space or a double quote (") character. They are described in the Special String Characters section of thetextclass.
#### text item delimiters
AppleScript provides thetext item delimitersproperty for use in processing text. This property consists of a list of strings used as delimiters by AppleScript when it coerces a list to text or gets text items from text strings. When gettingtext itemsof text, all of the strings are used as separators. When coercing a list to text, the first item is used as a separator.
Note:Prior to OS X Snow Leopard v10.6, AppleScript only used the first delimiter in the list when gettingtext items.
Becausetext item delimitersrespectconsideringandignoringattributes in AppleScript 2.0, delimiters are case-insensitive by default. Formerly, they were always case-sensitive. To enforce the previous behavior, add an explicitconsidering casestatement.
You can get and set the current value of thetext item delimitersproperty. Normally, AppleScript doesnât use any delimiters. For example, if the text delimiters have not been explicitly changed, the statement
```
{"bread", "milk", "butter", 10.45} as string```
returns the following:
```
"breadmilkbutter10.45"```
For printing or display purposes, it is usually preferable to settext item delimitersto 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.45"```
Thetext item delimitersproperty can be used to extract individual names from a pathname. For example, the script
```
set AppleScript's text item delimiters to {":"}```
```
get last text item of "Hard Disk:CD Contents:Release Notes"```
returns the result"Release Notes".
If you change thetext item delimitersproperty in Script Editor, it remains changed until you restore its previous value or until you quit Script Editor and launch it again. If you changetext item delimitersin a script application, it remains changed in that application until you restore its previous value or until the script application quits; however, the delimiters are not changed in Script Editor or in other script applications you run.
Scripts commonly use an error handler to reset thetext item delimitersproperty to its former value if an error occurs (for more on dealing with errors, seeAppleScript Error Handling):
```
set savedDelimiters to AppleScript's text item delimiters```
```
try```
```
set AppleScript's text item delimiters to {"**"}```
```
--other script statements...```
```
--now reset the text item delimiters:```
```
set AppleScript's text item delimiters to savedDelimiters```
```
on error m number n```
```
--also reset text item delimiters in case of an error:```
```
set AppleScript's text item delimiters to savedDelimiters```
```
--and resignal the error:```
```
error m number n```
```
end try```
#### version
This property provides the current version of AppleScript. The following script shows how to check for a version greater than or equal to version 1.9. Theifstatement is wrapped in aconsidering numeric stringsstatement so that an AppleScript version such as1.10.6compares as larger than, say, version1.9.
```
considering numeric strings```
```
if version of AppleScript as string ⥠"1.9" then```
```
-- Perform operations that depend on version 1.9 or greater```
```
else```
```
-- Handle case where version is not high enough```
```
end if```
```
end considering```
Applications can have their ownversionproperty, so to access the AppleScript version explicitly, you use the phraseversion of AppleScript. This will work inside atellblock that targets another application, such as the following:
```
tell application "Finder"```
```
version --result: "10.5.1"```
```
version of AppleScript --result: "2.0"```
```
end tell```
### current application Constant
Thecurrent applicationconstant refers to the application that is executing the current AppleScript script (for example, Script Editor). Because the current application is the parent of AppleScript(seeThe AppleScript Inheritance Chain), it gets a chance to handle commands that arenât handled by the current script or by AppleScript.
Thecurrent applicationconstant is an object specifierâif you ask AppleScript for its value, the result is the object specifier:
```
get current application --result: current application```
However, if you ask forname of current application, AppleScript resolves the object specifier and returns the current applicationâs name:
```
name of current application --result: "Script Editor"```
### missing value Constant
Themissing valueconstant is a placeholder for missing or uninitialized information.
For example, the following statements use themissing valueconstant to determine if a variable has changed:
```
set myVariable to missing value```
```
-- perform operations that might change the value of myVariable```
```
if myVariable is equal to missing value then```
```
-- the value of the variable never changed```
```
else```
```
-- the value of the variable did change```
```
end if```
### true, false Constants
AppleScript defines theBoolean constantstrueandfalse. These constants are described with thebooleanclass.
## The it and me Keywords
AppleScript defines the keywordmeto refer to the current script and the keyworditto refer to the current target. (Thecurrent scriptis the one that is currently being executed; thecurrent targetis the object that is the current default target for commands.) It also definesmyas a synonym forof meanditsas a synonym forof it.
If a script hasnât targeted anything,itandmerefer to the same thingâthe scriptâas shown in the following example:
```
-- At the top-level of the script:```
```
me --result: «script» (the top-level script object)```
```
it --result: «script» (same as it, since no target set yet)```
Atellstatement specifies a default target. In the following example, the default target is the Finder application:
```
-- Within a tell block:```
```
tell application "Finder" -- sets target```
```
me --result: «script» (still the top-level script object)```
```
it --result: application "Finder" (target of the tell statement)```
```
end tell```
You can use the wordsof meormyto indicate that the target of a command is the current script and not the target of thetellstatement. In the following example, the wordmyindicates thatminimumValue()handler is defined by the script, not by Finder:
```
tell application "Finder"```
```
set fileCount to count files in front window```
```
set myCount to my minimumValue(fileCount, 100)```
```
--do something with up to the first 100 filesâ¦```
```
end tell```
You can also useof meormyto distinguish script properties from object properties. Suppose there is a TextEdit document open named âSimple.rtfâ:
```
tell document 1 of application "TextEdit"```
```
name --result: "Simple.rtf" (implicitly uses target of tell)```
```
name of it --result: "Simple.rtf" (specifies target of tell)```
```
me --result: «script» (top-level script object, not target of tell)```
```
end tell```
The following example shows how to specify differentversionproperties in a Findertellstatement. The Finder is the default target, but usingversion of me,my version, orversion of AppleScriptallows you to specify the version of the top-levelscriptobject. (The top-levelscriptobject returns the AppleScript version, because it inherits from AppleScript, as described inThe AppleScript Inheritance Chain.)
```
tell application "Finder"```
```
version --result: "10.5.1" (Finder version is the default in tell block)```
```
its version --result: "10.5.1" (specifically asks for Finder version)```
```
version of me --result: "2.0" (AppleScript version)```
```
my version --result: "2.0" (AppleScript version)```
```
version of AppleScript --result: "2.0" (AppleScript version)```
```
end tell```
For information on usingitin a filter reference, see the Discussion section for theFilterreference form.
## Aliases and Files
To refer to items and locations in the macOS file system, you usealiasobjects andfileobjects.
Analiasobject is a dynamic reference to an existing file system object. Because it is dynamic, it can maintain the link to its designated file system object even if that object is moved or renamed.
Afileobject represents a specific file at a specific location in the file system. It can refer to an item that does not currently exist, such as the name and location for a file that is to be created. Afileobject is not dynamic, and always refers to the same location, even if a different item is moved into that place. ThePOSIX filepseudo-class is roughly synonymous with file:POSIX filespecifiers evaluate to afileobject, but they use different semantics for the name, as described inSpecifying Paths.
The following is the recommended usage for these types:
- Use analiasobject to refer to existing file system objects.
Use analiasobject to refer to existing file system objects.
- Use afileobject to refer to a file that does not yet exist.
Use afileobject to refer to a file that does not yet exist.
- Use aPOSIX filespecifier if you want to specify the file using a POSIX path.
Use aPOSIX filespecifier if you want to specify the file using a POSIX path.
The following sections describe how to specify file system objects by path and how to work with them in your scripts.
### Specifying Paths
You can createaliasobjects andfileobjects by supplying a name specifier, where the name is the path to an item in the file system.
For alias and file specifiers, the path is an HFS path, which takes the form"disk:item:subitem:subsubitem:...:item". For example,"Hard_Disk:Applications:Mail.app"is the HFS path to the Mail application, assuming your boot drive is named"Hard_Disk".
HFS paths with a leading colon, such as":folder:file", are resolved relative to the HFS working directory. However, their use is discouraged, because the location of the HFS working directory is unspecified, and there is no way to control it from AppleScript.
For POSIX file specifiers, the path is a POSIX path, which takes the form"/item/subitem/subsubitem/.../item". The disk name is not required for the boot disk. For example,"/Applications/Mail.app"is the POSIX path to the Mail application. You can see the POSIX path of an item in Finder in the "Where" field of its Get Info window. Despite the name, POSIX file specifiers may refer to folders or disks. Use of"~"to specify a home directory is not supported.
POSIX paths without a leading slash, such as"folder/file", are resolved relative to the POSIX working directory. This is supported, but only is useful for scripts run from the shellâthe working directory is the current directory in the shell. The location of the POSIX working directory for applications is unspecified.
### Working With Aliases
AppleScript defines thealiasclass to represent aliases. An alias can be stored in a variable and used throughout a script.
The following script first creates an alias to an existing file in the variablenotesAlias, then uses the variable in atellstatement that opens the file. It uses atrystatement to check for existence of the alias before creating it, so that the alias is only created once, even if the script is run repeatedly.
```
try```
```
notesAlias -- see if we've created the alias yet```
```
on error```
```
-- if not, create it in the error branch```
```
set notesAlias to alias "Hard_Disk:Users:myUser:Feb_Notes.rtf"```
```
end try```
```
-- now open the file from the alias:```
```
tell application "TextEdit" to open notesAlias```
Finding the object an alias refers to is calledresolvingan alias. AppleScript 2.0 attempts to resolve aliases only when you run a script. However, in earlier versions, AppleScript attempts to resolve aliases at compile time.
Once you run the previous example, creating the alias, the script will be able to find the original file when you run it again, even if the fileâs name or location changes. (However, if you run the script again after recompiling it, it will create a new alias.)
You can get the HFS path from an alias by coercing it to text:
```
notesAlias as text --result: "Hard_Disk:Users:myUser:Feb_Notes.rtf"```
You can use thePOSIX pathproperty to obtain a POSIX-style path to the item referred to by an alias:
```
POSIX path of notesAlias --result: "/Feb_Notes.rtf"```
If an alias doesnât refer to an existing file system object then it is broken. You canât create an alias to an object that doesnât exist, such as a file you plan to create. For that you use afileobject, described in the next section.
For a sample script that shows how a script application can process a list of aliases it receives when a user drops one or more file icons on it, seeopen Handlers.
### Working With Files
AppleScript usesfileobjects to represent files in scripts. Afileobject can be stored in a variable and used throughout a script. The following script first creates afileobject for an existing file in the variablenotesFile, then uses the variable in atellstatement that opens the file:
```
set notesFile to POSIX file "/Users/myUser/Feb_Meeting_Notes.rtf"```
```
tell application "TextEdit" to open notesFile```
You can use afileobject to specify a name and location for a file that may not exist:
```
set newFile to POSIX file "/Users/myUser/BrandNewFile.rtf"```
Similarly, you can let a user specify a new file with thechoose file namecommand, then use the returnedfileobject to create the file. In the following example, if the user cancels thechoose file namedialog, the rest of the script is not executed. If the user does supply a file name, the script opens the file, creating it if necessary, then uses atrystatement to make sure it closes the file when it is finished writing to it.
```
set theFile to choose file name```
```
set referenceNumber to open for access theFile with write permission```
```
try```
```
-- statements to write to the file```
```
on error```
```
close access referenceNumber```
```
end try```
```
close access referenceNumber```
Typically, when you pass afileobject to a command that uses it to operate on a new or existing item in the file system, the components of the path must exist for the command to succeed.
## Remote Applications
A script can target an application on a remote computer if remote applications are enabled on that computer, and if the script specifies the computer with an eppc-style specifier.
### Enabling Remote Applications
For a script to send commands to a remote application, the following conditions must be satisfied:
- The computer that contains the application and the computer on which the script is run must be connected to each other through a network.
The computer that contains the application and the computer on which the script is run must be connected to each other through a network.
- Remote Apple Events (set in the Sharing preferences pane) must be enabled on the remote computer and user access must be provided (you can allow access for all users or for specified users only).
Remote Apple Events (set in the Sharing preferences pane) must be enabled on the remote computer and user access must be provided (you can allow access for all users or for specified users only).
- If the specified remote application is not running, you must run it.
If the specified remote application is not running, you must run it.
- You must authenticate as admin when you compile or run the script.
You must authenticate as admin when you compile or run the script.
### eppc-Style Specifiers
An eppc-style specifier takes the following format:
```
eppc://[user[:password]@]IP_address```
Either a numeric IP address in dotted decimal form (four numbers, from 0 to 255, separated by periods; for example,123.23.23.123) or a hostname. A hostname can be a Bonjour name.
The following are examples of valid eppc-style specifiers. If you supply the user name and password, no authentication is required. If you do not supply it, authentication may be required.
```
"eppc://myCoolMac.local" -- hostname, no user or pwd```
```
"eppc://myUserName:pwd@myCoolMac.local" -- user, pwd, and hostname```
```
"eppc://123.23.23.123" -- IP address, no user or pwd```
```
"eppc://myUserName:pwd@123.23.23.123" -- user, pwd, and IP address```
```
"eppc://myUserName@server.company.com" -- server address, user```
Important:If a part of the eppc-style specifier contains non-UTF-8 characters or white space, it must be URL-encoded: for example, here is a user name that contains a space:
  ÂJohn%20Smith.
### Targeting Remote Applications
You can target an application that is running on a remote machine and you can launch applications on remote machines that are not currently running.
The following example uses an eppc-style specifier to target the Finder on a remote computer. It includes a user name and password, so no authentication is required.
```
set remoteMachine to "eppc://userName:pwd@MacName.local"```
```
tell app "Finder" of machine remoteMachine to close front window```
Important:If you compile an erroneous eppc-style address, you will have to quit and relaunch Script Editor for changes to that address to take effect.
In some cases, youâll need to use ausing terms fromstatement to tell AppleScript to compile against the local version of an application. The following example uses that technique in telling the remote Finder application to open the TextEdit application:
```
set remoteFinder to application "Finder" of machine ¬```
```
"eppc://myUserName:pwd@123.23.23.123"```
```
```
```
using terms from application "Finder"```
```
tell remoteFinder```
```
open application file id "com.apple.TextEdit"```
```
end tell```
```
end using terms from```
If you omit the password (pwd) in the previous script, you will have to authenticate when you run the script.
## Debugging AppleScript Scripts
AppleScript does not include a built-in debugger, but it does provide several simple mechanisms to help you debug your scripts or just observe how they are working.
### Feedback From Your Script
You can insert various statements into a script to indicate the current location and other information. In the simplest case, you can insert a beep command in a location of interest:
```
beep 3 -- three beeps; a very important part of the script!```
Adisplay dialogcommand can display information about whatâs happening in a script and, like a breakpoint, it halts execution until you dismiss it (or until it times out, depending on the parameters you pass). The following example displays the current script location and the value of a variable:
```
display dialog "In factorial routine; x = " & (x as string)```
Thesaycommand can get your attention by speaking the specified text. In the following example,currentClientis atextobject that stores a client name:
```
say "I'm in the clientName handler. The client is " & currentClient```
### Logging
Script Editor can display a log of the Apple events that are sent during execution of a script. In the Script Editor Preferences, you can also choose to keep a history of recent results or event logs.
In addition, you can insertlogstatements into a script. Log output is shown in the Event Log pane of a script window, and also in theEvent Log History window, if it is open.
The following simple example logs the current word in arepeat with loopVariable (in list)statement:
```
set wordList to words in "Where is the hammer?"```
```
repeat with currentWord in wordList```
```
log currentWord```
```
if contents of currentWord is equal to "hammer" then```
```
display dialog "I found the hammer!"```
```
end if```
```
end repeat```
The following shows how the words appear in the log when the script is run:
```
(*Where*)```
```
(*is*)```
```
(*the*)```
```
(*hammer*)```
### Third Party Debuggers
If you need full-featured debugging capabilities, there are powerful, third-party AppleScript debuggers available.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Script Objects
This chapter describes thescriptobject, which is used to implement all AppleScript scripts. Before reading this chapter, you should be familiar with the information inAppleScript and Objects.
Ascript objectis a user-defined object that can combine data (in the form of properties) and actions (in the form of handlers and additionalscriptobjects). Script objects support inheritance, allowing you to define a hierarchy of objects that share properties and handlers. You can also extend or modify the behavior of a handler in onescriptobject when calling it from anotherscriptobject.
The top-levelscriptobject is the one that implements the overall script you are working on. Anyscriptobject can contain nestedscriptobjects, each of which is defined just like a top-levelscriptobject, except that a nestedscriptobject is bracketed with statements that mark its beginning and end.
This chapter describesscriptobjects in the following sections:
- Defining Script Objectsshows the syntax for definingscriptobjects and includes a simple example .
Defining Script Objectsshows the syntax for definingscriptobjects and includes a simple example .
- Initializing Script Objectsdescribes how AppleScript creates ascriptobject with the properties and handlers you have defined.
Initializing Script Objectsdescribes how AppleScript creates ascriptobject with the properties and handlers you have defined.
- Sending Commands to Script Objectsdescribes how you usetellstatements to send commands toscriptobjects.
Sending Commands to Script Objectsdescribes how you usetellstatements to send commands toscriptobjects.
- Script Librariesdescribes script libraries and how to use them from other scripts.
Script Librariesdescribes script libraries and how to use them from other scripts.
- Inheritance in Script Objectsdescribes inheritance works and how you can use it to share functionality in thescriptobjects you define.
Inheritance in Script Objectsdescribes inheritance works and how you can use it to share functionality in thescriptobjects you define.
## Defining Script Objects
Eachscriptobject definition (except for the top-levelscriptobject) begins with the keywordscript, followed by a variable name, and ends with the keywordend(orend script). The statements in between can be any combination of property definitions, handler definitions, nestedscriptobject definitions, and other AppleScript statements.
The syntax of ascriptobject definition is as follows:
scriptvariableName
    [ (property|prop)parent :parentSpecifier]
    [ (property|prop)propertyLabel:initialValue]...
    [handlerDefinition]...
    [statement]...
end[script]
A variable identifier for the script. You can refer to a script object by this name elsewhere in a script.
Specifies the parent of thescriptobject, typically anotherscriptobject.
For more information, seeInheritance in Script Objects.
An identifier, unique within thescriptobject, that specifies a characteristic of the object; equivalent to an instance variable.
The value that is assigned to the property each time thescriptobject is initialized.scriptobjects are initialized when compiled.initialValueis required in property definitions.
A handler for a command thescriptobject can respond to; equivalent to a method. For more information, seeAbout HandlersandHandler Reference.
Any AppleScript statement. Statements other than handler and property definitions are treated as if they were part of an implicit handler definition for theruncommand; they are executed when ascriptobject receives theruncommand.
Here is a simplescriptobject definition:
```
script John```
```
property HowManyTimes : 0```
```
```
```
to sayHello to someone```
```
set HowManyTimes to HowManyTimes + 1```
```
return "Hello " & someone```
```
end sayHello```
```
```
```
end script```
It defines ascriptobject that can handle thesayHellocommand. It assigns thescriptobject to the variableJohn. The definition includes a handler for thesayHellocommand. It also includes a property, calledHowManyTimes, that indicates how many times thesayHellocommand has been called.
A handler within ascriptobject definition follows the same syntax rules as any other handler.
You can use atellstatement to send commands to ascriptobject. For example, the following statement sends thesayHellocommand thescriptobject defined above.
```
tell John to sayHello to "Herb" --result: "Hello Herb"```
You can manipulate the properties ofscriptobjects by using thegetcommand to get the value of a property and thesetorcopycommand to change the value. The value of a property is persistentâit gets reset every time you compile the script, but not when you run it.
## Initializing Script Objects
When you define ascriptobject, it can contain properties, handlers, and nestedscriptobject definitions. When you execute the script containing it, AppleScript creates ascriptobject with the defined properties, handlers, and nestedscriptobjects. The process of creating an instance of ascriptobject from its definition is called initialization. Ascriptobject must be initialized before it can respond to commands.
A top-levelscriptobject is initialized each time the scriptâsrunhandler is executed. Similarly, if you define a script within a handler, AppleScript initializes ascriptobject each time the handler is called. The parameter variables in the handler definition become local variables of thescriptobject.
For example, themakePointhandler in the following script contains ascriptobject definition for thescriptobjectthePoint:
```
on makePoint(x, y)```
```
script thePoint```
```
property xCoordinate:x```
```
property yCoordinate:y```
```
end script```
```
return thePoint```
```
end makePoint```
```
```
```
set myPoint to makePoint(10,20)```
```
get xCoordinate of myPoint --result: 10```
```
get yCoordinate of myPoint --result: 20```
AppleScript initializes thescriptobjectthePointwhen it executes themakePointcommand. After the call tomakePoint, the variablemyPointrefers to thisscriptobject. The parameter variables in themakePointhandler, in this case,xandy, become local variables of thescriptobject. The initial value ofxis 10, and the initial value ofyis 20, because those are the parameters passed to themakePointhandler that initialized thescriptobject.
If you added the following line to the end of the previous script and ran it, the variablemyOtherPointwould refer to a second instance of thescriptobjectthePoint, with different property values:
```
set myOtherPoint to makePoint(30,50)```
ThemakePointscript is a kind of constructor function that createsscriptobjects representing points.
## Sending Commands to Script Objects
You can usetellstatements to send commands toscriptobjects. For example, the followingtellstatement sends twosayHellocommands to thescriptobjectJohn(defined below):
```
tell John```
```
sayHello to "Herb"```
```
sayHello to "Grace"```
```
end tell```
For ascriptobject to respond to a command within atellstatement, either thescriptobject or its parent object must have a handler for the command. For more information about parent objects, seeInheritance in Script Objects.
Ascriptobject definition may include an implicitrunhandler, consisting of all executable statements that are outside of any handler or nestedscriptobject, or it may include an explicitrunhandler that begins withon run, but it may not contain bothâsuch a script will not compile. If a script has no run handler (for example, a script that serves as a library of handlers, as described inParameter Specifications), executing the script does nothing. However, sending it an explicitruncommand causes an error. For more information, seerun Handlers.
Thedisplay dialogcommand in the followingscriptobject definition is the only executable statement at the top level, so it constitutes thescriptobjectâs implicitrunhandler and is executed when the script sends aruncommand toscriptobjectJohn, with the statementtell John to run.
```
script John```
```
property HowManyTimes : 0```
```
to sayHello to someone```
```
set HowManyTimes to HowManyTimes + 1```
```
return "Hello " & someone```
```
end sayHello```
```
display dialog "John received the run command"```
```
end script```
```
```
```
tell John to run```
You can also use the possessive to send a command to ascriptobject. For example, either of the following two forms send thesayHellocommand to scriptJohn(the first version compiles into the second):
```
John's sayHello to "Jake" --result: "Hello Jake"```
```
sayHello of John to "Jake" --result: "Hello Jake"```
## Script Libraries
A top-levelscriptobject saved in a Script Libraries folder becomes ascript libraryusable by other scripts. Libraries let you share and reuse handlers, reorganize large scripts into a set of smaller libraries that are easier to manage, and build richer, higher-level functionality out of simpler libraries.
Note:Libraries are supported in OS X Mavericks v10.9 (AppleScript 2.3) and later. To share properties and handlers between scripts in prior OS versions, use theload scriptcommand as described inLibraries using Load Script.
### Creating a Library
The basic requirement for a script to be a script library is its location: it must be a script document in a âScript Librariesâ folder in one of the following folders. When searching for a library, the locations are searched in the order listed, and the first matching script is used:
- If the script that references the library is a bundle, the scriptâs bundleResourcesdirectory. This means that scripts may be packaged and distributed with the libraries they use.
If the script that references the library is a bundle, the scriptâs bundleResourcesdirectory. This means that scripts may be packaged and distributed with the libraries they use.
- If the application running the script is a bundle, the applicationâs bundleResourcesdirectory. This means that script applications (âappletsâ and âdropletsâ) may be packaged and distributed with the libraries they use. It also enables applications that run scripts to provide libraries for use by those scripts.
If the application running the script is a bundle, the applicationâs bundleResourcesdirectory. This means that script applications (âappletsâ and âdropletsâ) may be packaged and distributed with the libraries they use. It also enables applications that run scripts to provide libraries for use by those scripts.
- Any folders specified in the environment variableOSA_LIBRARY_PATH. This allows using a library without installing it in one of the usual locations. The value of this variable is a colon-separated list of paths, such as/opt/local/Script Libraries:/usr/local/Script Libraries. Unlike the other library locations, paths specified inOSA_LIBRARY_PATHare used exactly as-is, without appending âScript Librariesâ.Supported in OS X v10.11 and later.
Any folders specified in the environment variableOSA_LIBRARY_PATH. This allows using a library without installing it in one of the usual locations. The value of this variable is a colon-separated list of paths, such as/opt/local/Script Libraries:/usr/local/Script Libraries. Unlike the other library locations, paths specified inOSA_LIBRARY_PATHare used exactly as-is, without appending âScript Librariesâ.Supported in OS X v10.11 and later.
- The Library folder in the userâs home directory,~/Library. This is the location to install libraries for use by a single user, and is the recommended location during library development.
The Library folder in the userâs home directory,~/Library. This is the location to install libraries for use by a single user, and is the recommended location during library development.
- The computer Library folder,/Library. Libraries located here are available to all users of the computer.
The computer Library folder,/Library. Libraries located here are available to all users of the computer.
- The network Library folder,/Network/Library. Libraries located here are available to multiple computers on a network.
The network Library folder,/Network/Library. Libraries located here are available to multiple computers on a network.
- The system Library folder,/System/Library. These are libraries provided by macOS.
The system Library folder,/System/Library. These are libraries provided by macOS.
- Any installed application bundle, in the applicationâs bundleLibrarydirectory. This allows distributing libraries that are associated with an application, or creating applications that exist solely to distribute libraries.Supported in OS X v10.11 and later.
Any installed application bundle, in the applicationâs bundleLibrarydirectory. This allows distributing libraries that are associated with an application, or creating applications that exist solely to distribute libraries.Supported in OS X v10.11 and later.
Script libraries also havename,id, andversionproperties. It is recommended that you define all three, especially for libraries you plan to distribute publicly: doing so allows clients to unambiguously identify particular versions of libraries that have the functionality they need. These properties may be defined either aspropertydefinitions within the script itself, or, for script bundles, in the Info.plist file, which can be edited using the Bundle Contents drawer in Script Editor. For details, see thescriptclass reference.
A script library may be a single-file (scpt) or bundle format (scptd). If a library is a bundle, it may define its own terminology.
#### Defining Scripting Terminology
Libraries may define scripting terminology, including commands, properties and enumerated values, by supplying a Scripting Definition (sdef) file in their bundle. Like applications, this terminology is available to client scripts when they target the library withtelloruse, and to the library script itself.
To define terminology, create an sdef file as described in theCocoa Scripting GuideunderPreparing a Scripting Definition File. Then, copy the file to the bundleâs Resources directory and set the Info.plist keyOSAScriptingDefinitionto the base name of the sdef file (that is, the file name without the â.sdefâ extension). Script Editorâs Bundle Contents drawer can do this for you: drag the file into the âResourcesâ list to copy the file into the bundle, and enter the base name of the sdef file in the âScripting Definitionâ field.
### Using a Library
A script library defines a script object, which a client script may then reference and then send commands to, as described inSending Commands to Script Objects. Libraries are identified by name:
```
script "My Library"```
AppleScript will search the various Script Library folders, as described above inCreating a Library, and create an instance of the library script. Unlike the result fromload script, this instance is shared and persists for at least the lifetime of the client script, so you do not have to save it in a variable, and state will be preserved while the client script is running. For example, given this library script:
```
property name : "Counter"```
```
property nextNumberProperty : 0```
```
on nextNumber()```
```
set my nextNumberProperty to my nextNumberProperty + 1```
```
return my nextNumberProperty```
```
end nextNumber```
This client script, despite referencing the library in full both times, will log â1â and then â2â:
```
tell script "Counter" to log its nextNumber() -- logs "1"```
```
tell script "Counter" to log its nextNumber() -- logs "2"```
Note:Library script instances are unique to, and persistent for the lifetime of, the AppleScript interpreter that loads them. Script Editor, Script Menu, and Folder Actions all run their scripts using a separate interpreter for each script; applets and AppleScriptObjC applications use a single interpreter for the entire application; and other applications may do either. If you are designing a library, try to not rely on persistent state in the library script itself, since its lifetime will vary depending on how the client script is run.
## Inheritance in Script Objects
You can use the AppleScript inheritance mechanism to define relatedscriptobjects in terms of one another. This allows you to share property and handler definitions among manyscriptobjects without repeating the shared definitions. Inheritance is described in the following sections:
- The AppleScript Inheritance Chain
The AppleScript Inheritance Chain
- Defining Inheritance Through the parent Property
Defining Inheritance Through the parent Property
- Some Examples of Inheritance
Some Examples of Inheritance
- Using the continue Statement in Script Objects
Using the continue Statement in Script Objects
### The AppleScript Inheritance Chain
The top-levelscriptobject is the parent of all otherscriptobjects, although anyscriptobject can specify a different parent object. The top-levelscriptobject also has a parentâAppleScript itself (the AppleScript component). And even AppleScript has a parentâthe current application. The name of that application (which is typically Script Editor) can be obtained through the global constantcurrent application. This hierarchy defines theinheritance chainthat AppleScript searches to find the target for a command or the definition of a term.
Everyscriptobject has access to the properties, handlers, and script objects it defines, as well as to those defined by its parent, and those of any other object in the inheritance chain, including AppleScript. Thatâs why the constants and properties described inGlobal Constants in AppleScriptare available to any script.
Note:There is an exception to the previous claim. An explicitlocalvariable canshadow(or block access to) aglobalvariable or property with the same name, making the global version inaccessible in the scope of the handler orscriptobject. For related information, seeScope of Variables and Properties.
### Defining Inheritance Through the parent Property
When working withscriptobjects,inheritanceis the ability of a childscriptobject to take on the properties and handlers of a parent object. You specify inheritance with theparentproperty.
The object listed in aparentproperty definition is called theparent object, or parent. Ascriptobject that includes aparentproperty is referred to as achild script object, or child. Theparentproperty is not required, though if one is not specified, every script is a child of the top-level script, as described inThe AppleScript Inheritance Chain. Ascriptobject can have many children, but a childscriptobject can have only one parent. The parent object may be any object, such as alistor anapplicationobject, but it is typically anotherscriptobject.
The syntax for defining a parent object is
(property|prop)parent :variable
An identifier for a variable that refers to the parent object.
Ascriptobject must be initialized before it can be assigned as a parent of anotherscriptobject. This means that the definition of a parentscriptobject (or a command that calls a function that creates a parentscriptobject) must come before the definition of the child in the same script.
### Some Examples of Inheritance
The inheritance relationship betweenscriptobjects should be familiar to those who are acquainted with C++ or other object-oriented programming languages. A childscriptobject that inherits the handlers and properties defined in its parent is like a C++ class that inherits methods and instance variables from its parent class. If the child does not have its own definition of a property or handler, it uses the inherited property or handler. If the child has its own definition of a particular property or handler, then it ignores (or overrides) the inherited property or handler.
Listing 4-1shows the definitions of a parentscriptobject calledAlexand a childscriptobject calledAlexJunior.
Listing 4-1A pair of script objects with a simple parent-child relationship
```
script Alex```
```
on sayHello()```
```
return "Hello, " & getName()```
```
end sayHello```
```
on getName()```
```
return "Alex"```
```
end getName```
```
end script```
```
```
```
script AlexJunior```
```
property parent : Alex```
```
on getName()```
```
return "Alex Jr"```
```
end getName```
```
end script```
```
```
```
-- Sample calls to handlers in the script objects:```
```
tell Alex to sayHello() --result: "Hello, Alex"```
```
tell AlexJunior to sayHello() --result: "Hello, Alex Jr."```
```
```
```
tell Alex to getName() --result: "Alex"```
```
tell AlexJunior to getName() --result: "Alex Jr"```
Eachscriptobject defines agetName()handler to return its name. ThescriptobjectAlexalso defines thesayHello()handler. BecauseAlexJuniordeclares Alex to be its parent object, it inherits thesayHello()handler.
Using atellstatement to invoke thesayHello()handler ofscriptobjectAlexreturns"Hello, Alex". Invoking the same handler ofscriptobjectAlexJuniorreturns"Hello, Alex Jr"âalthough the samesayHello()handler inAlexis executed, when that handler callsgetName(), itâs thegetName()inAlexJuniorthat is executed.
The relationship between a parentscriptobject and its childscriptobjects is dynamic. If the properties of the parent change, so do the inherited properties of the children. For example, thescriptobjectJohnSonin the following script inherits itsvegetableproperty fromscriptobjectJohn.
```
script John```
```
property vegetable : "Spinach"```
```
end script```
```
script JohnSon```
```
property parent : John```
```
end script```
```
set vegetable of John to "Swiss chard"```
```
vegetable of JohnSon```
```
--result: "Swiss chard"```
When you change thevegetableproperty ofscriptobjectJohnwith thesetcommand, you also change thevegetableproperty of the childscriptobjectSimple. The result of the last line of the script is"Swiss chard".
Similarly, if a child changes one of its inherited properties, the value in the parent object also changes. For example, thescriptobjectJohnSonin the following script inherits thevegetableproperty fromscriptobjectJohn.
```
script John```
```
property vegetable : "Spinach"```
```
end script```
```
script JohnSon```
```
property parent : John```
```
on changeVegetable()```
```
set my vegetable to "Zucchini"```
```
end changeVegetable```
```
end script```
```
tell JohnSon to changeVegetable()```
```
vegetable of John```
```
--result: "Zucchini"```
When you change thevegetableproperty ofscriptobjectJohnSonto"Zucchini"with thechangeVegetablecommand, thevegetableproperty ofscriptobjectJohnalso changes.
The previous example demonstrates an important point about inherited properties: to refer to an inherited property from within a childscriptobject, you must use the reserved wordmyorof meto indicate that the value to which youâre referring is a property of the currentscriptobject. (You can also use the wordsof parentto indicate that the value is a property of the parentscriptobject.) If you donât, AppleScript assumes the value is a local variable.
For example, if you refer tovegetableinstead ofmy vegetablein thechangeVegetablehandler in the previous example, the result is"Spinach". For related information, seeThe it and me Keywords.
### Using the continue Statement in Script Objects
In a childscriptobject, you can define a handler with the same name as a handler defined in its parent object. In implementing the child handler, you have several options:
- The handler in the childscriptobject can be independent of the one in its parent. This allows you to call either handler, as you wish.
The handler in the childscriptobject can be independent of the one in its parent. This allows you to call either handler, as you wish.
- The handler in the child can simply invoke the handler in its parent. This allows the child object to take advantage of the parentâs implementation (as shown in thescriptobjects below that contain aon identifyhandler).
The handler in the child can simply invoke the handler in its parent. This allows the child object to take advantage of the parentâs implementation (as shown in thescriptobjects below that contain aon identifyhandler).
- The handler in the child can invoke the handler in its parent, changing the values passed to it or executing additional statements before or after invoking the parent handler. This allows the child object to modify or add to the behavior of its parent, but still take advantage of the parentâs implementation.
The handler in the child can invoke the handler in its parent, changing the values passed to it or executing additional statements before or after invoking the parent handler. This allows the child object to modify or add to the behavior of its parent, but still take advantage of the parentâs implementation.
Normally, if a childscriptobject and its parent both have handlers for the same command, the child uses its own handler. However, the handler in a childscriptobject can handle a command first, and then use acontinuestatement to call the handler for the same command in the parent.
This handing off of control to another object is calleddelegation. By delegating commands to a parentscriptobject, a child can extend the behavior of a handler contained in the parent without having to repeat the entire handler definition. After the parent handles the command, AppleScript continues at the place in the child where thecontinuestatement was executed.
The syntax for acontinuestatement is shown incontinue.
The following script includes twoscriptobject definitions,ElizabethandChildOfElizabeth.
```
script Elizabeth```
```
property HowManyTimes : 0```
```
to sayHello to someone```
```
set HowManyTimes to HowManyTimes + 1```
```
return "Hello " & someone```
```
end sayHello```
```
end script```
```
```
```
script ChildOfElizabeth```
```
property parent : Elizabeth```
```
on sayHello to someone```
```
if my HowManyTimes > 3 then```
```
return "No, I'm tired of saying hello."```
```
else```
```
continue sayHello to someone```
```
end if```
```
end sayHello```
```
end script```
```
tell Elizabeth to sayHello to "Matt"```
```
--result: "Hello Matt", no matter how often the tell is executed```
```
tell ChildOfElizabeth to sayHello to "Bob"```
```
--result: "Hello Bob", the first four times the tell is executed;```
```
-- after the fourth time: "No, Iâm tired of saying hello."```
In this example, the handler defined byChildOfElizabethfor thesayHellocommand checks the value of theHowManyTimesproperty each time the handler is run. If the value is greater than 3,ChildOfElizabethreturns a message refusing to say hello. Otherwise,ChildOfElizabethcalls thesayHellohandler in the parentscriptobject (Elizabeth), which returns the standard hello message. The wordsomeonein thecontinuestatement is a parameter variable. It indicates that the parameter received with the originalsayHellocommand will be passed to the handler in the parent script.
Note:The reserved wordmyin the statementifmy HowManyTimes > 10in this example is required to indicate thatHowManyTimesis a property of thescriptobject. Without the wordmy, AppleScript assumes thatHowManyTimesis an undefined local variable.
Acontinuestatement can change the parameters of a command before delegating it. For example, suppose the followingscriptobject is defined in the same script as the preceding example. The firstcontinuestatement changes the direct parameter of thesayHellocommand from"Bill"to"William". It does this by specifying the value"William"instead of the parameter variablesomeone.
```
script AnotherChildOfElizabeth```
```
property parent : Elizabeth```
```
on sayHello to someone```
```
if someone = "Bill" then```
```
continue sayHello to "William"```
```
else```
```
continue sayHello to someone```
```
end if```
```
end sayHello```
```
end script```
```
```
```
tell AnotherChildOfElizabeth to sayHello to "Matt"```
```
--result: "Hello Matt"```
```
```
```
tell AnotherChildOfElizabeth to sayHello to "Bill"```
```
--result: "Hello William"```
If you override a parentâs handler in this manner, the reserved wordsmeandmyin the parentâs handler no longer refer to the parent, as demonstrated in the example that follows.
```
script Hugh```
```
on identify()```
```
me```
```
end identify```
```
end script```
```
script Andrea```
```
property parent : Hugh```
```
on identify()```
```
continue identify()```
```
end identify```
```
end script```
```
```
```
tell Hugh to identify()```
```
--result: «script Hugh»```
```
```
```
tell Andrea to identify()```
```
--result: «script Andrea»```
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Control Statements Reference
This chapter describes AppleScript control statements. Acontrol statementis a statement that determines when and how other statements are executed or how expressions are evaluated. For example, a control statement may cause AppleScript to skip or repeat certain statements.
Simple statementscan be written on one line, whilecompound statementscan contain other statements, including multiple clauses with nested and multi-line statements. A compound statement is known as astatement block.
Compound statements begin with one or more reserved words, such astell, that identify the type of control statement. The last line of a compound statement always starts withend, and can optionally include the word that begins the control statement (such asend tell).
### considering and ignoring Statements
Theconsideringandignoringstatements cause AppleScript to consider or ignore specific characteristics as it executes groups of statements. There are two kinds ofconsideringandignoringstatements:
- Those that specify attributes to be considered or ignored in performing text comparisons.
Those that specify attributes to be considered or ignored in performing text comparisons.
- Those that specify whether AppleScript should consider or ignore responses from an application.
Those that specify whether AppleScript should consider or ignore responses from an application.
Specify how AppleScript should treats attributes, such as case, in performing text comparisons.
##### Syntax
```
considering attribute [, attribute ... and attribute ] ¬
   [ but ignoring attribute [, attribute ... and attribute ] ]
      [ statement ]...
end considering
ignoring attribute [, attribute ... and attribute ] ¬
   [ but considering attribute [, attribute ... and attribute ] ]
      [ statement ]...
end ignoring```
##### Placeholders
A characteristic of the text:
If this attribute is ignored, uppercase letters are not distinguished from lowercase letters. See Special Considerations below for related information. See alsogreater than, less thanfor a description of how AppleScript sorts letters, punctuation, and other symbols.
If this attribute is ignored,textobjects are compared as if no diacritical marks (such as ´, `, Ë, ¨, and Ë) are present; for example,"résumé"is equal to"resume".
If this attribute is ignored,textobjects are compared as if no hyphens are present; for example"anti-war"is equal to"antiwar".
By default, this attribute is ignored, and text strings are compared according to their character values. For example, if this attribute is considered,"1.10.1" > "1.9.4"evaluates astrue; otherwise it evaluates asfalse. This can be useful in comparing version strings.
If this attribute is ignored,textobjects are compared as if no punctuation marks (such as. , ? : ; ! ' ") are present; for example"What? he inquired."is equal to"what he inquired".
If this attribute is ignored, thetextobjects are compared as if spaces, tab characters, and return characters were not present; for example"Brick house"would be considered equal to"Brickhouse".
Any AppleScript statement.
##### Examples
The following examples show howconsideringandignoringstatements for various attributes can change the value of text comparisons.
```
"Hello Bob" = "HelloBob" --result: false```
```
ignoring white space```
```
"Hello Bob" = "HelloBob" --result: true```
```
end ignoring```
```
```
```
"BOB" = "bob" --result: true```
```
considering case```
```
"BOB" = "bob" --result: false```
```
end considering```
```
```
```
"a" = "á" --result: false```
```
ignoring diacriticals```
```
"a" = "á" --result: true```
```
end considering```
```
```
```
"Babs" = "bábs" --result: false```
```
```
```
ignoring case```
```
"Babs" = "bábs" --result: false```
```
end ignoring```
```
```
```
ignoring case and diacriticals```
```
"Babs" = "bábs" --result: true```
```
end ignoring```
##### Discussion
You can nestconsideringandignoringstatements. If the same attribute appears in both an outer and inner statement, the attribute specified in the inner statement takes precedence.When attributes in an innerconsideringorignoringstatement are different from those in outer statements, they are added to the attributes to be considered and ignored.
##### Special Considerations
Becausetext item delimiters(described inversion) respectconsideringandignoringattributes in AppleScript 2.0, delimiters are case-insensitive by default. Formerly, they were always case-sensitive. To enforce the previous behavior, add an explicitconsidering casestatement.
consideringandignoringare fully Unicode-aware. For example, withignoring case, âÐоÑбаÑâ is equal to âÐÐÐ ÐÐЧâ. Also, the characters ignored by diacriticals, hyphens, punctuation, and white space are defined by Unicode character classes:
- ignoring punctuationignores category P*, which includes left- and right-quotation marks such asâ â « ».
ignoring punctuationignores category P*, which includes left- and right-quotation marks such asâ â « ».
- ignoring hyphensignores category Pd, which includes em- and en-dashes.
ignoring hyphensignores category Pd, which includes em- and en-dashes.
- ignoring whitespaceignores category Z*, plus tab (\t), return (\r), and linefeed (\n), which includes em-, en-, and non-breaking spaces.
ignoring whitespaceignores category Z*, plus tab (\t), return (\r), and linefeed (\n), which includes em-, en-, and non-breaking spaces.
Para
Permits a script to continue without waiting for an application to respond to commands that target it.
##### Syntax
```
considering | ignoring application responses   [ statement ]...end [ considering | ignoring ]```
##### Placeholders
Any AppleScript statement.
##### Examples
The following example shows how to use an ignoring statement so that a script neednât wait while Finder is performing a potentially lengthy task:
```
tell application "Finder"```
```
ignoring application responses```
```
empty the trash```
```
end ignoring```
```
end tell```
Your script may want to ignore most responses from an application, but wait for a response to a particular statement. You can do so by nestingconsideringandignoringstatements:
```
tell application "Finder"```
```
ignoring application responses```
```
empty the trash```
```
-- other statements that ignore application responses```
```
considering application responses```
```
set itemName to name of first item of startup disk```
```
end considering```
```
-- other statements that ignore application responses```
```
end ignoring```
```
end tell```
##### Discussion
A response to an application command indicates whether the command completed successfully, and also returns results and error messages, if there are any. When you use anignoring application responsesblock, you forego this information.
Results and error messages from AppleScript commands, scripting additions, and expressions are not affected by theapplication responsesattribute.
### error Statements
During script execution, errors can occur in the operating system (for example, when a specified file isnât found), in an application (for example, when the script specifies an object that doesnât exist), and in the script itself. Anerror messageis a message that is supplied by an application, AppleScript, or macOS when an error occurs during the handling of a command. An error message can include anerror number, which is an integer that identifies the error; anerror expression, which is an expression, usually atextobject, that describes the error; and other information.
A script can signal an errorâwhich can then be handled by an error handlerâwith theerrorstatement. This allows scripts to supply their own messages for errors that occur within the script. For example, a script can prepare to handle anticipated errors by using atrystatement. In theon errorbranch of atrystatement, a script may be able to recover gracefully from the error. If not, it can use anerrorstatement to resignal the error message it receives, modifying the message as needed to supply information specific to the script.
Signals an error in a script.
##### Syntax
```
error [ errorMessage ] [ number errorNumber ] ¬   [ partial resultresultList ] ¬   [ from offendingObject ] [ to expectedType ]```
##### Placeholders
Atextobject describing the error. Although this parameter is optional, you should provide descriptions for errors wherever possible. If you do not include an error description, an emptytextobject ("") is passed to the error handler.
The error number for the error. This is an optional parameter. If you do not include a number parameter, the value -2700 (unknown error) is passed to the error handler.
If the error you are signaling is a close match for one that already has an AppleScript error constant, you can use that constant. If you need to create a new number for the error, avoid using one that conflicts with error numbers defined by AppleScript, macOS, and the Apple Event Manager. In general, you should use positive numbers from 500 to 10,000. For more information, seeError Numbers and Error Messages.
A list of objects. Applies only to commands that return results for multiple objects. If results for some, but not all, of the objects specified in the command are available, you can include them in the partial result parameter. This is rarely supported by applications.
A reference to the object, if any, that caused the error.
A class. If a parameter specified in the command was not of the expected class, and AppleScript was unable to coerce it to the expected class, then you can include the expected class in thetoparameter.
##### Examples
The following example uses atrystatement to handle a simple error, and demonstrates how you can use anerrorstatement to catch an error, then resignal the error exactly as it was received, causing AppleScript to display an error dialog (and halt execution):
```
try```
```
word 5 of "one two three"```
```
on error eStr number eNum partial result rList from badObj to expectedType```
```
-- statements that take action based on the error```
```
display dialog "Doing some preliminary handling..."```
```
-- then resignal the error```
```
error eStr number eNum partial result rList from badObj to expectedType```
```
end try```
In the next example, anerrorstatement resignals an error, but omits any original error information and supplies its own message to appear in the error dialog:
```
try```
```
word 5 of "one two three"```
```
on error```
```
-- statements to execute in case of error```
```
error "There are not enough words."```
```
end try```
For more comprehensive examples, seeWorking with Errors.
### if Statements
Anifstatement allows you to define statements or groups of statements that are executed only in specific circumstances, based on the evaluation of one or more Boolean expressions.
Anifstatement is also called a conditional statement. Boolean expressions inifstatements are also called tests.
Executes a statement if a Boolean expression evaluates totrue.
##### Syntax
```
if boolean then statement ```
##### Placeholders
A Boolean expression.
Any AppleScript statement.
##### Examples
This script displays a dialog if the value of the Boolean expressionageOfCat > 1istrue. (The variableageOfCatis set previously.)
```
if ageOfCat > 1 then display dialog "This is not a kitten."```
Executes a group (or groups) of statements if a Boolean expression (or expressions) evaluates totrue.
##### Syntax
```
if boolean [ then ] [ statement ]...
[else if boolean [ then ] [ statement ]...]...
[else [ statement ]...]
end [ if ]```
##### Placeholders
A Boolean expression.
Any AppleScript statement.
##### Examples
The following example uses a compoundifstatement, with a finalelseclause, to display a statement based on the current temperature (obtained separately):
```
if currentTemp < 60 then```
```
set response to "It's a little chilly today."```
```
else if currentTemp > 80 then```
```
set response to "It's getting hotter today."```
```
else```
```
set response to "It's a nice day today."```
```
end if```
```
display dialog response```
##### Discussion
Anifstatement can contain any number ofelse ifclauses; AppleScript looks for the first Boolean expression contained in aniforelse ifclause that istrue, executes the statements contained in its block (the statements between oneelse ifand the followingelse iforelseclause), and then exits theifstatement.
Anifstatement can also include a finalelseclause. The statements in its block are executed if no other test in theifstatement passes.
### repeat Statements
You use arepeatstatement to create loops or execute groups of repeated statements in scripts.
There are a number of types ofrepeatstatement, each differing in the way it terminates the loop. Each of the options, from repeating a loop a specific number of times, to looping over the items in a list, to looping until a condition is met, and so on, lends itself to particular kinds of tasks.
For information on testing and debuggingrepeatstatements, seeDebugging AppleScript Scripts.
Terminates arepeatloop and resumes execution with the statement that follows therepeatstatement.
You can only use anexitstatement inside arepeatstatement. Though most commonly used with therepeat (forever)form, you can also use anexitstatement with other types ofrepeatstatement.
##### Syntax
```
exit [ repeat ]```
##### Examples
See the example inrepeat (forever).
Repeats a statement (or statements) until anexitstatement is encountered.
Important:Arepeat(forever) statement will never complete unless you cause it to do so.
To terminate arepeat(forever) statement, you can:
- Use anexitstatement and design the logic so that it eventually encounters theexitstatement.
Use anexitstatement and design the logic so that it eventually encounters theexitstatement.
- Use areturnstatement, which exits the handler or script that contains the loop, and therefore the loop as well.
Use areturnstatement, which exits the handler or script that contains the loop, and therefore the loop as well.
- Use atrystatement and rely on an error condition to exit the loop.
Use atrystatement and rely on an error condition to exit the loop.
##### Syntax
```
repeat
   [ statement ]...
end [ repeat ]```
##### Placeholders
Any AppleScript statement.
##### Examples
This form of therepeatstatement is similar to therepeat untilform, except that instead of putting a test in therepeatstatement itself, you determine within the loop when it is time to exit. You might use this form, for example, to wait for a lengthy or indeterminate operation to complete:
```
repeat```
```
-- perform operations```
```
if someBooleanTest then```
```
exit repeat```
```
end if```
```
end repeat```
In a script application that stays open, you can use anidlehandler to perform periodic tasks, such as checking for an operation to complete. Seeidle Handlersfor more information.
Repeats a statement (or statements) a specified number of times.
##### Syntax
```
repeat integer [ times ]
   [ statement ]...
end [ repeat ]```
##### Placeholders
Specifies the number of times to repeat the statements in the body of the loop.
Instead of an integer, you can specify any value that can be coerced to an integer.
If the value is less than one, the body of therepeatstatement is not executed.
Any AppleScript statement.
##### Examples
The following handler uses therepeat (number) timesform of therepeatstatement to raise a passed number to the passed power:
```
on raiseToTheNth(x, power)```
```
set returnVal to x```
```
repeat power - 1 times```
```
set returnVal to returnVal * x```
```
end repeat```
```
return returnVal```
```
end raiseToTheNth```
Repeats a statement (or statements) until a condition is met. Tests the condition before executing any statements.
##### Syntax
```
repeat until boolean
   [ statement ]...
end [ repeat ]```
##### Placeholders
A Boolean expression. If it has the valuetruewhen entering the loop, the statements in the loop are not executed.
Any AppleScript statement.
##### Examples
The following example uses therepeat untilform of therepeatstatement to allow a user to enter database records. The handlerenterDataRecord(), which is not shown, returnstrueif the user is done entering records:
```
set userDone to false```
```
repeat until userDone```
```
set userDone to enterDataRecord()```
```
end repeat```
Repeats a statement (or statements) as long as a condition is met. Tests the condition before executing any statements. Similar to therepeat untilform, except that it continueswhilea condition istrue, instead ofuntilit istrue.
##### Syntax
```
repeat while boolean
   [ statement ]...
end [ repeat ]```
##### Placeholders
A Boolean expression. If it has the valuefalsewhen entering the loop, the statements in the loop are not executed.
Any AppleScript statement.
##### Examples
The following example uses therepeat whileform of therepeatstatement to allow a user to enter database records. In this case, weâve just reversed the logic shown in therepeat untilexample. Here, the handlerenterDataRecord(), which is not shown, returnstrueif the user isnotdone entering records:
```
set userNotDone to true```
```
repeat while userNotDone```
```
set userNotDone to enterDataRecord()```
```
end repeat```
Repeats a statement (or statements) until the value of the controlling loop variable exceeds the value of the predefined stop value.
##### Syntax
```
repeat with loopVariable from startValue to stopValue [ by stepValue ]
   [ statement ]...
end [ repeat ]```
##### Placeholders
Controls the number of iterations. It can be a previously defined variable or a new variable you define in therepeatstatement.
Specifies a value that is assigned toloopVariablewhen the loop is entered.
You can specify an integer or any value that can be coerced to an integer.
Specifies an value. When that value is exceeded by the value ofloopVariable, iteration ends. IfstopValueis less thanstartValue, the body is not executed.
You can specify an integer or any value that can be coerced to an integer.
Specifies a value that is added toloopVariableafter each iteration of the loop. You can assign anintegeror arealvalue; arealvalue is rounded to aninteger.
Any AppleScript statement.
##### Examples
The following handler uses therepeat with loopVariable (from startValue to stopValue)form of therepeatstatement to compute a factorial value (the factorial of a number is the product of all the positive integers from 1 to that number):
```
on factorial(x)```
```
set returnVal to 1```
```
repeat with n from 2 to x```
```
set returnVal to returnVal * n```
```
end repeat```
```
return returnVal```
```
end factorial```
##### Discussion
You can use an existing variable as the loop variable in arepeat with loopVariable (from startValue to stopValue)statement or define a new one in the statement. In either case, the loop variable is defined outside the loop. You can change the value of the loop variable inside the loop body but it will get reset to the next loop value the next time through the loop. After the loop completes, the loop variable retains its last value.
AppleScript evaluatesstartValue,stopValue, andstepValuewhen it begins executing the loop and stores the values internally. As a result, if you change the values in the body of the loop, it doesnât change the execution of the loop.
Loops through the items in a specified list.
The number of iterations is equal to the number of items in the list. In the first iteration, the value of the variable is a reference to the first item inlist, in the second iteration, it is a reference to the second item inlist, and so on.
##### Syntax
```
repeat with loopVariable in list
   [ statement ]...
end [ repeat ]```
##### Placeholders
Any previously defined variable or a new variable you define in therepeatstatement (see Discussion).
A list or a object specifier (such aswords 1 thru 5) whose value is a list.
listcan also be a record; AppleScript coerces the record to a list (see Discussion).
Any AppleScript statement.
##### Examples
The following script uses therepeat with loopVariable (in list)form of therepeatstatement to loop through a list of first names, displaying a greeting for each.
```
set peopleList to {"Chris", "David", "Sal", "Ben"}```
```
repeat with aPerson in peopleList```
```
display dialog "Hello " & aPerson & "!"```
```
end repeat```
##### Discussion
You can use an existing variable as the loop variable in arepeat with loopVariable (in list)statement or define a new one in therepeat withâ¦statement. In either case, the loop variable is assigned a new valueâthe current item in the loopâat the start of each loop. After the loop completes, the loop variable retains its last value.
This example uses an existing variable as the loop variable:
```
set currentIncrement to 0```
```
-- The loop variable is an existing variable, defined above```
```
repeat with currentIncrement in {1, 2, 3, 4}```
```
-- Do something```
```
end repeat```
```
currentIncrement```
```
--result: item 4 of {1, 2, 3, 4} --result: the last value of the loop variable```
This example defines a new variable as the loop variable:
```
-- The loop variable is a new variable, defined in the repeat statement```
```
repeat with currentIncrement in {1, 2, 3, 4}```
```
-- Do something```
```
end repeat```
```
currentIncrement```
```
--result: item 4 of {1, 2, 3, 4} --result: the last value of the loop variable```
You can change the value of the loop variable inside the loop body, but it gets reset to the next loop value the next time through the loop. Again, after the loop completes, the loop variable retains its last value.
```
repeat with currentIncrement in {1, 2, 3, 4}```
```
display dialog currentIncrement```
```
set currentIncrement to 0```
```
end repeat```
```
currentIncrement```
```
--result: 0```
AppleScript evaluatesloopVariableinlistas an object specifierâa reference to the current item in the listâthat takes on the value ofitem 1 of list,item 2 of list,item 3 of list, and so on until it reaches the last item in the list. For example:
```
repeat with i in {1, 2, 3, 4}```
```
set listItem to i```
```
end repeat```
```
--result: item 4 of {1, 2, 3, 4} --result: an object specifier```
To access the actual value of an item in the list, rather than a reference to the item, use thecontents ofproperty:
```
repeat with i in {1, 2, 3, 4}```
```
set listItem to contents of i```
```
end repeat```
```
--result: 4```
This technique is especially important when performing a comparison, as you typically want to test whether thevalueof a list item matches another value. The following script examines a list of words, displaying a dialog if it finds the word âhammerâ in the list. To perform a proper comparison, the test statement (if (contents of currentWord) is equal to "hammer" then) compares thecontentsof the current list item, rather than the object specifier itself.
```
set wordList to words in "Where is the hammer?"```
```
repeat with currentWord in wordList```
```
log currentWord```
```
if (contents of currentWord) is equal to "hammer" then```
```
display dialog "I found the hammer!"```
```
end if```
```
end repeat```
Note:In the previous example, the statementlog currentWordlogs the current list item to Script Editorâs log pane. For more information about logging, seeDebugging AppleScript Scripts.
You can also use list variables directly in expressions, which may result in an implicit coercion from an object reference to a specific data type. In the following example, the loop variableiis implicitly coerced to an integer (equivalent to explicitly retrieving thecontents of i) by using the+operator to add it to a variable containing an integer.
```
set total to 0```
```
repeat with i in {1, 2, 3, 4}```
```
set total to total + i```
```
end repeat```
```
--result: 10```
### tell Statements
Atellstatement specifies the default targetâthat is, the object to which commands are sent if they do not include a direct parameter. Statements within atellstatement that use terminology from the targeted object are compiled against that objectâs dictionary.
The object of atellstatement is typically a reference to an application object or ascriptobject. For example, the followingtellstatement targets the Finder application:
```
tell application "Finder"```
```
set frontWindowName to name of front window```
```
-- any number of additional statements can appear here```
```
end tell```
You can nesttellstatements inside othertellstatements, as long as you follow the syntax and rules described intell (compound).
When you need to call a handler from within atellstatement, there are special terms you use to indicate that the handler is part of the script and not a command that should be sent to the object of thetellstatement. These terms are described inThe it and me Keywordsand inCalling Handlers in a tell Statement.
Atellstatement that targets a local application doesnât cause it to launch, if it is not already running. For example, a script can examine therunningproperty of the targetedapplicationobject to determine if the application is running before attempting to send it any commands. If it is not running it wonât be launched.
If atellstatement targets a local application and executes any statements that require a response from the application, then AppleScript will launch the application if it is not already running. The application is launched as hidden, but the script can send it anactivatecommand to bring it to the front, if needed.
Atellstatement that targets a remote application will not cause it to launchâin fact, it will not compile or run unless the application is already running. Nor is it possible to access therunningproperty of an application on a remote computer.
Specifies a target object and a command to send to it.
##### Syntax
```
tell referenceToObject to statement ```
##### Placeholders
Any object. Typically an object specifier or areferenceobject (which contains an object specifier).
Any AppleScript statement.
##### Examples
This simpletellstatement closes the front Finder window:
```
tell front window of application "Finder" to close```
For more information on how to specify an application object, see theapplicationclass.
Specifies a target object and one or more commands to send to it. A compoundtellstatement is different from a simpletellstatement in that it always includes anendstatement.
##### Syntax
```
tell referenceToObject    [ statement ]... end [ tell ]```
##### Placeholders
Any object. Typically an object specifier or areferenceobject (which contains an object specifier).
Any AppleScript statement, including anothertellstatement.
##### Examples
The following statements show how to close a window using first a compoundtellstatement, then with two variations of a simpletellstatement:
```
tell application "Finder"```
```
close front window```
```
end tell```
```
```
```
tell front window of application "Finder" to close```
```
tell application "Finder" to close front window```
The following example shows a nestedtellstatement:
```
tell application "Finder"```
```
tell document 1 of application "TextEdit"```
```
set newName to word 1 -- handled by TextEdit```
```
end tell```
```
set len to count characters in newName -- handled by AppleScript```
```
if (len > 2) and (len < 15) then -- comparisons handled by AppleScript```
```
set name of first item of disk "HD" to newName -- handled by Finder```
```
end if```
```
end tell```
This example works because in each case the terminology understood by a particular application is used within atellblock targeting that application. However, it would not compile if you asked the Finder forword 1of a document, or told TextEdit toset nameof the first item on a disk, because those applications do not support those terms.
### try Statements
Atrystatement provides the means for scripts to handle potential errors. It attempts to execute one or more statements and, if an error occurs, executes a separate set of statements to deal with the error condition. If an error occurs and there is notrystatement in the calling chain to handle it, AppleScript displays an error and script execution stops.
For related information, seeerror StatementsandAppleScript Error Handling.
Attempts to execute a list of AppleScript statements, calling an error handler if any of the statements results in an error.
Atrystatement is a two-part compound statement that contains a series of AppleScript statements, followed by an error handler to be invoked if any of those statements causes an error. If the statement that caused the error is included in atrystatement, then AppleScript passes control to the error handler. After the error handler completes, control passes to the statement immediately following the end of thetrystatement.
##### Syntax
```
try
   [ statement ]...
[ on error [ errorMessage ] [ number errorNumber ] [ from offendingObject ] ¬
   [ partial result resultList ] [ to expectedType ]
      [ statement ]... ]
end [ error | try ]```
##### Placeholders
Any AppleScript statement.
Atextobject, that describes the error.
The error number, an integer. For possible values, seeError Numbers and Error Messages.
A reference to the object, if any, that caused the error.
A list that provides partial results for objects that were handled before the error occurred. The list can contain values of any class. This parameter applies only to commands that return results for multiple objects. This is rarely supported by applications.
The expected class. If the error was caused by a coercion failure, the value of this variable is the class of the coercion that failed. (The second example below shows how this works in a case where AppleScript is unable to coerce atextobject into aninteger.)
Either a global variable or a local variable that can be used in the handler. A variable can contain any class of value. The scope of a local variable is the handler. The scope of a global variable extends to any other part of the script, including other handlers andscriptobjects. For related information about local and global variables, seeversion.
##### Examples
The following example shows how you can use atrystatement to handle the âCancelâ button for adisplay alertcommand. Canceling returns an error number of -128, but is not really an error. This test handler just displays a dialog to indicate when the user cancels or when some other error occurs.
```
try```
```
display alert "Hello" buttons {"Cancel", "Yes", "No"} cancel button 1```
```
on error errText number errNum```
```
if (errNum is equal to -128) then```
```
-- User cancelled.```
```
display dialog "User cancelled."```
```
else```
```
display dialog "Some other error: " & errNum & return & errText```
```
end if```
```
end try```
You can also use a simplified version of thetrystatement that checks for just a single error number. In the following example, only error -128 is handled. Any other error number is ignored by thistrystatement, but is automatically passed up the calling chain, where it may be handled by othertrystatements.
```
try```
```
display alert "Hello" buttons {"Cancel", "Yes", "No"} cancel button 1```
```
on error number -128```
```
-- Either do something special to handle Cancel, or just ignore it.```
```
end try```
The following example demonstrates the use of thetokeyword to capture additional information about an error that occurs during a coercion failure:
```
try```
```
repeat with i from 1 to "Toronto"```
```
-- do something that depends on variable "i"```
```
end repeat```
```
on error from obj to newClass```
```
log {obj, newClass} -- Display from and to info in log pane.```
```
end try```
Thisrepeatstatement fails because thetextobject"Toronto"cannot be coerced to aninteger. The error handler simply writes the values ofobj(the offending value,"Toronto") andnewClass(the class of the coercion that failed,integer) to Script Editorâs Event Log History window (and to the script windowâs Event Log pane). The result is â(*Toronto, integer*)â, indicating the error occurred while trying to coerce âTorontoâ to an integer.
For additional examples, seeWorking with Errors.
### use Statements
Ausestatement declares a required resource for a scriptâan application, script library, framework, or version of AppleScript itselfâand can optionallyimportterminology from the resource for use elsewhere in the script. The effects and syntax ofusevary slightly depending on the used resource; the different cases are described below.
Note:usestatements are supported in OS X Mavericks v10.9 (AppleScript 2.3) and later.
The basic function ofuseis to require that a resource be present before the script begins executing. If the requirement cannot be met, the script will fail to run. Ausestatement can also specify a minimum version for the required resource, such as a minimum compatible version of an application. In this example, AppleScript will ensure that Safari version 7.0 or later is available:
```
use application "Safari" version "7.0"```
usestatements can also import terminology from the used resource, making the terms available throughout the script without requiring the use oftellorusing terms from. AppleScript tracks where terms were imported from, and sends events that use those terms to that target. Ordinarily, commands are sent to the current target (it) as described inTarget, but imported terminology overrides this. Ifâ¦
- the event identifier is imported
the event identifier is imported
- the direct parameter is an imported class or enumeration identifier
the direct parameter is an imported class or enumeration identifier
- the direct parameter is an object specifier ending with an imported term
the direct parameter is an object specifier ending with an imported term
â¦then the command is sent to the import source instead. This happens even if the command is inside atellblock for a different target. For example, this script uses a command from Safari:
```
use application "Safari"```
```
search the web for "AppleScript"```
Importing happens by default, but can be suppressed using thewithout importingparameter, if applicable. You can use this to add requirements to existing scripts without changing anything else about the script:
```
use application "Safari" version "7.0" without importing```
Because Safari's terms are not imported, the script will still need to usetellto send it events.
Declares a required minimum version of AppleScript, and that the script expects a newer behavior for how scripting additions are handled, described inuse (scripting additions).
##### Syntax
```
use AppleScript [ version versionText ] ```
##### Placeholders
The required minimum version of AppleScript, as a version string such as"2.3.2". If omitted, its default value is 2.3, the version in whichusewas introduced. This value is always text, not a number, and is compared as ifconsidering numeric stringsis in effect. For example,"2.10"is greater than"2.3", because 10 is greater than 3.
##### Examples
In its simplest form,usecan be used to declare that the script uses AppleScript:
```
use AppleScript```
This also implicitly means that the script uses AppleScript version 2.3 or later, whenusewas first introduced, and that the script expects a newer behavior for how scripting additions are handled, described inuse (scripting additions).
Ausecommand can also explicitly specify a minimum required version of AppleScript:
```
use AppleScript version "2.3.2"```
Declares that a script uses scripting additions.
##### Syntax
```
use scripting additions ¬    [ with importing | without importing | importing boolean ]```
##### Placeholders
A boolean value,trueorfalse. AppleScript will recompile this towith importingorwithout importing. The default iswith importing.
##### Examples
Useuse scripting additionsto explicitly declare that the script uses scripting addition commands:
```
use scripting additions```
##### Discussion
Scripting addition commands are handled differently if a script hasusecommands. If a script has one or moreusecommands of any kind, scripting addition commands arenotavailable by default. You must explicitly indicate that you wish to use scripting additions, either with auseorusing terms fromcommand.
```
use scripting additions```
```
display dialog "hello world"```
```
using terms from scripting additions```
```
display dialog "hello world"```
```
end using terms from```
If a script usesuse scripting additions, AppleScript may optimize scripting addition commands, sending them to the current application instead of the current target (it) when it does not change the meaning to do so. For example,random numberdoes not need to be sent to another application to work correctly, and will always be sent to the current application when imported withuse. Without ause scripting additionscommand, AppleScript must use a less efficient dispatching scheme, so explicitly declaring them is recommended.
Declares a required application or script library, and may import its terms for use later in the script.
##### Syntax
```
use [ identifier : ] ( script | application ) specifier ¬   [ version versionText ] ¬   [ with importing | without importing | importing boolean ]```
##### Placeholders
The required minimum version of the resource as a version number, such as"2.3.2". This value is always text, not a number, and is compared as ifconsidering numeric stringsis in effect. For example,"2.10"is greater than"2.3", because 10 is greater than 3.
An optional identifier for the resource.
Specifier data for the resource. This is typically a name, as inuse application "Finder"oruse script "My Library", but may be any valid specifier form, such as by ID, as inuse application id "com.apple.mail".
A boolean value,trueorfalse. AppleScript will recompile this towith importingorwithout importing. The default iswith importing.
##### Examples
Ausecommand may refer to an application:
```
use application "Finder"```
â¦or a script library:
```
use script "Happy Fun Ball"```
If an optional identifier is given, it defines a property whose value is the required resource. This can make it more convenient to refer to the resource, as in this example: thegetstatement uses the identifierSafariinstead of the full specifierapplication "Safari".
```
use Safari : application "Safari"```
```
get the name of Safari's front window```
By usingusewith multiple applications, you can combine terms from different sources in ways impossible usingtell, becausetellonly makes one terminology source available at a time. For example, the following script, in one statement, uses Mail and Safari to search the web for the sender of the currently selected mail message. Thegetevent is sent to Mail because it definesmessage viewer, while thesearch the webevent is sent to Safari.
```
use application "Mail"```
```
use application "Safari"```
```
```
```
search the web for the sender of the first item of ¬```
```
```
```
(get selected messages of the front message viewer)```
Declares a required framework for use with the AppleScript/Objective-C bridge.
##### Syntax
```
use framework specifier```
##### Placeholders
Specifier data for the resource. This may be a base name ("AppKit"), a full name ("AppKit.framework"), or a POSIX path ("/System/Library/Frameworks/AppKit.framework").
##### Examples
Most scripts that use the AppleScript/Objective-C bridge should have at least one of these twousestatements:
```
use framework "Foundation"```
```
use framework "AppKit"```
You can also use other frameworks, such as WebKit:
```
use framework "WebKit"```
##### Discussion
When you declare a required framework, AppleScript ensures the framework is loaded before running your script. To ensure that your AppleScript/Objective-C script libraries work correctly in any application, declare all needed frameworks explicitly; otherwise, there is no guarantee that a given framework will be available, and your script may fail.
Theversionparameter is not supported for frameworks; to check whether or not a framework supports a certain feature, useNSClassFromStringor-respondsToSelector:.
Note:OS X Yosemite v10.10 and later allow using Objective-C frameworks from any script. OS X Mavericks v10.9 only allows using Objective-C frameworks from a script library.
### using terms from Statements
Ausing terms fromstatement lets you specify which terminology AppleScript should use in compiling the statements in a script. Whereas atellstatement specifies the default target (often an application) to which commands are sentandthe terminology to use, ausing terms fromstatement specifies only the terminology.
Ausing terms fromstatement can be useful in writing application event handler scripts, such as Mail rules.
Another use for this type of statement is with a script that targets an application on a remote computer that may not be available when you compile the script (or the application may not be running). Or, you might be developing locally and only want to test with the remote application at a later time. In either case, you can use ausing terms fromstatement to specify a local application (presumably with a terminology that matches the one on the remote computer) to compile against.
Even if a statement contained within ausing terms fromstatement compiles, the script may fail when run because the target applicationâs terminology may differ from that used in compiling.
You can nestusing terms fromstatements. When you do so, each script statement is compiled against the terminology of the application named in the innermost enclosingusing terms fromstatement.
Instructs AppleScript to use the terminology from the specified source in compiling the enclosed statements.
##### Syntax
```
using terms from ( application | script | scripting additions) Â Â Â [ statement ]... end [ using terms from ]```
##### Placeholders
A specifier for an application object.
A specifier for a script library.
Any AppleScript statement.
##### Examples
The following example shows how to use ausing terms fromstatement in writing a Mail rule action script. These scripts take the following form:
```
using terms from application "Mail"```
```
on perform mail action with messages theMessages for rule theRule```
```
tell application "Mail"```
```
-- statements to process each message in theMessages```
```
end tell```
```
end perform mail action with messages```
```
end using terms from```
To use the script, you open Preferences for the Mail application, create or edit a rule, and assign the script as the action for the rule.
For an example that works with an application on a remote machine, seeTargeting Remote Applications.
As discussed inuse Statements, a script with anyusestatements does not make scripting addition terms visible by default. You can enable scripting addition terms for specific parts of a script withusing terms fromas in this example:
```
use AppleScript```
```
-- scripting addition commands such as "display dialog" will not compile here...```
```
using terms from scripting additions -- ...but will compile within this block.```
```
display dialog "Hello world!"```
```
end using terms from```
##### Discussion
using terms fromdoes not import terms asusedoes, and is subject to the same limits on terminology use astell.using terms from scripting additionsdoes not enable optimization of scripting addition commands asuse scripting additionsdoes.
### with timeout Statements
You can use awith timeoutstatement to control how long AppleScript waits for a command to execute before timing out. By default,when an application fails to respond to a command, AppleScript waits for two minutes before reporting an error and halting execution.
Specifies how long AppleScript waits for a response to a command that is sent to another application.
##### Syntax
```
with timeout [ of ] integerExpression second[s] Â Â Â [ statement ]... end [ timeout ] ```
##### Placeholders
The amount of time, in seconds, AppleScript should wait before timing out (and interrupting the command).
Any AppleScript statement.
##### Examples
The following script tells TextEdit to close its first document; if the document has been modified, it asks the user if the document should be saved. It includes the statementwith timeout of 20 seconds, so that if the user doesnât complete thecloseoperation within 20 seconds, the operation times out.
```
tell application "TextEdit"```
```
with timeout of 20 seconds```
```
close document 1 saving ask```
```
end timeout```
```
end tell```
##### Discussion
When a command fails to complete in the allotted time (whether the default of two minutes, or a time set by awith timeoutstatement), AppleScript stops running the script and returns the error"event timed out".AppleScript does not cancel the operationâit merely stops execution of the script. If you want the script to continue, you can wrap the statements in atrystatement. However, whether your script can send a command to cancel an offending lengthy operation after a timeout is dependent on the application that is performing the command.
Awith timeoutstatement applies only to commands sent to application objects, not to commands sent to the application that is running the script.
In some situations, you may want to use anignoring application responsesstatement (instead of awith timeoutstatement) so that your script neednât wait for application commands to complete. For more information, seeconsidering and ignoring Statements.
### with transaction Statements
When you execute a script, AppleScript may send one or more Apple events to targeted applications. A transaction is a set of operations that are applied as a single unitâeither all of the changes are applied or none are. This mechanism works only with applications that support it.
Associates a single transaction ID with any events sent to a target application as a result of executing commands in the body of the statement.
##### Syntax
```
with transaction [ session ]
   [ statement ]...
end [ transaction ]```
##### Placeholders
An object that identifies a specific session.
Any AppleScript statement.
##### Examples
This example uses awith transactionstatement to ensure that a record can be modified by one user without being modified by another user at the same time. (In the following examples, âSmall DBâ and âSuper DBâ are representative database applications.)
```
tell application "Small DB"```
```
with transaction```
```
set oldName to Field "Name"```
```
set oldAddress to Field "Address"```
```
set newName to display dialog ¬```
```
"Please type a new name" ¬```
```
default answer oldName```
```
set newAddress to display dialog ¬```
```
"Please type the new address" ¬```
```
default answer oldAddress```
```
set Field "Name" to newName```
```
set Field "Address" to newAddress```
```
end transaction```
```
end tell```
Thesetstatements obtain the current values of the Name and Address fields and invite the user to change them. Enclosing thesesetstatements in a singlewith transactionstatement informs the application that other users should not be allowed to access the same record at the same time.
Awith transactionstatement works only with applications that explicitly support it. Some applications only supportwith transactionstatements (like the one in the previous example) that do not take a session object as a parameter. Other applications support bothwith transactionstatements that have no parameter andwith transactionstatements that take a session parameter.
The following example demonstrates how to specify a session for awith transactionstatement:
```
tell application "Super DB"```
```
set mySession to make session with data {user: "Bob", password: "Secret"}```
```
with transaction mySession```
```
...```
```
end transaction```
```
end tell```
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Double Angle Brackets
When you type English language script statements in a Script Editor script window, AppleScript is able to compile the script because the English terms are described either in the terminology built into the AppleScript language or in the dictionary of an available scriptable application or scripting addition. When AppleScript compiles your script, it converts it into an internal executable format, then reformats the text to conform to settings in Script Editorâs Formatting preferences.
When you open, compile, edit, or run scripts with Script Editor, you may occasionally see terms enclosed in double angle brackets, or chevrons(«»). For example, you might see the term«event sysodlog»as part of a scriptâthis is the event code representation for adisplay dialogcommand. The event code representation is also known asraw format.
For compatibility with Asian national encodings, âãâ and âãâ are allowed as synonyms for â«â and â»â ( (Option- \ and Option-Shift- \, respectively, on a U.S. keyboard), since the latter do not exist in some Asian encodings.
The following sections provide more information about when chevrons appear in scripts.
## When a Dictionary Is Not Available
AppleScript uses double angle brackets in a Script Editor script window when it canât identify a term. That happens when it encounters a term that isnât part of the AppleScript language and isnât defined in an application or scripting addition dictionary that is available when the script is opened or compiled.
For example, if a script is compiled on one machine and later opened on another, the dictionary may not be available, or may be from an older version of the application or scripting addition that does not support the term.
This can also happen if the fileStandardAdditions.osaxis not present in/System/ScriptingAdditions. Then, scripting addition commands such asdisplay dialogwill not be present and will be replaced with chevron notation («event sysodlog») when you compile or run the script.
## When AppleScript Displays Data in Raw Format
Double angle brackets can also occur in results. For example, if the value of a variable is ascriptobject namedJoe, AppleScript represents thescriptobject as shown in this script:
```
script Joe```
```
property theCount : 0```
```
end script```
```
```
```
set scriptObjectJoe to Joe```
```
scriptObjectJoe```
```
--result: «script Joe»```
Similarly, if Script Editor canât display a variableâs data directly in its native format, it uses double angle brackets to enclose both the worddataand a sequence of numerical values that represent the data. Although this may not visually resemble the original data, the dataâs original format is preserved.
This may occur because an application command returns a value that does not belong to any of the normal AppleScript classes. You can store such data in variables and send them as parameters to other commands, but Script Editor cannot display the data in its native format.
## Entering Script Information in Raw Format
You can enter double angle brackets, or chevrons («»), directly into a script by typing Option-Backslash and Shift-Option-Backslash. You might want to do this if youâre working on a script that needs to use terminology that isnât available on your current machineâfor example, if youâre working at home and donât have the latest dictionary for a scriptable application you are developing, but you know the codes for a supported term.
You can also use AppleScript to display the underlying codes for a script, using the following steps:
- Create a script using standard terms compiled against an available application or scripting addition.
Create a script using standard terms compiled against an available application or scripting addition.
- Save the script as text and quit Script Editor.
Save the script as text and quit Script Editor.
- Remove the application or scripting addition from the computer.
Remove the application or scripting addition from the computer.
- Open the script again and compile it.
Open the script again and compile it.
- When AppleScript asks you to locate the application or scripting addition, cancel the dialog.
When AppleScript asks you to locate the application or scripting addition, cancel the dialog.
Script Editor can compile the script, but displays chevron format for any terms that rely on a missing dictionary.
## Sending Raw Apple Events From a Script
The term«event sysodlog»is actually the raw form for an Apple event with event class'syso'and event ID'dlog'(thedisplay dialogcommand). For a list of many of the four-character codes and their related terminology used by Apple, seeAppleScript Terminology and Apple Event Codes Reference.
You can use raw syntax to enter and execute events (even complex events with numerous parameters) when there is no dictionary to support them. However, providing detailed documentation for how to do so is beyond the scope of this guide.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Error Numbers and Error Messages
This appendix describes error numbers and error messages provided by AppleScript and macOS.
## AppleScript Errors
An AppleScript error is an error that occurs when AppleScript processes script statements. Nearly all of these are of interest to users. For errors returned by an application, see the documentation for that application.
Error number
Error message
-2700
Unknown error.
-2701
Canât divide by zero.
-2702
The result of a numeric operation was too large.
-2703
can't be launched because it is not an application.
-2704
isn't scriptable.
-2705
The application has a corrupted dictionary.
-2706
Stack overflow.
-2707
Internal table overflow.
-2708
Attempt to create a value larger than the allowable size.
-2709
Can't get the event dictionary.
-2720
Can't both consider and ignore .
-2721
Can't perform operation on text longer than 32K bytes.
-2729
Message size too large for the 7.0 Finder.
-2740
A can't go after this .
-2741
Expected but found .
-2750
The parameter is specified more than once.
-2751
The property is specified more than once.
-2752
The handler is specified more than once.
-2753
The variable is not defined.
-2754
Can't declare as both a local and global variable.
-2755
Exit statement was not in a repeat loop.
-2760
Tell statements are nested too deeply.
-2761
is illegal as a formal parameter.
-2762
is not a parameter name for the event .
-2763
No result was returned for some argument of this expression.
## Operating System Errors
An operating system error is an error that occurs when AppleScript or an application requests services from the Mac OS. They are rare, and often there is nothing you can do about them in a script, other than report them. A few, such as"User canceled", make sense for scripts to handleâas shown, for an example, in the Examples section for thedisplay dialogcommand.
Error number
Error message
No error.
Disk full.
Disk wasnât found.
Bad name for file
File wasnât open.
End of file error.
Too many files open.
File wasnât found.
Disk is write protected.
File is locked.
Disk is locked.
File is busy.
Duplicate file name.
File is already open.
Parameter error.
File reference number error.
File not open with write permission.
-108
Out of memory.
-120
Folder wasnât found.
-124
Disk is disconnected.
-128
User cancelled.
-192
A resource wasnât found.
-600
Application isnât running
-601
Not enough room to launch application with special requirements.
-602
Application is not 32-bit clean.
-605
More memory needed than is specified in the size resource.
-606
Application is background-only.
-607
Buffer is too small.
-608
No outstanding high-level event.
-609
Connection is invalid.
-904
Not enough system memory to connect to remote application.
-905
Remote access is not allowed.
-906
isnât running or program linking isnât enabled.
-915
Canât find remote machine.
-30720
Invalid date and time .
## Apple Event Errors
An Apple event error may occur when an app attempts to process an event sent by a script or a script attempts to process the reply.
Error number
Error message
-1700
Bad parameter data was detected or there was a failure while performing a coercion.
-1701
An Apple event description was not found.
-1702
Corrupt data was detected.
-1703
The wrong data type was detected.
-1704
An invalid Apple event description was detected.
-1705
The specified list item doesnât exist.
-1706
A newer version of Apple Event Manager is required to perform this operation.
-1707
The event isnât an Apple event.
-1708
The script doesnât understand the message. The event was not handled.
-1709
An invalid reply parameter was received byAEResetTimer.
-1710
An invalid sending mode (something other thanNoReply,WaitReply, orQueueReply) was detected or interaction level is unknown.
-1711
The user canceled while waiting for an event reply.
-1712
The Apple event has timed out.
-1713
User interaction is not allowed.
-1714
There is no special function for this keyword.
-1715
A required parameter is missing.
-1716
The target address type of an Apple event is unknown.
-1717
Unable to find a matching event or coercion handler.
-1718
Unable to access the contents of an event reply because the reply hasnât been received yet.
-1719
The specified index is invalid or out of range.
-1720
The specified range is invalid, such as3rdto2ndor1sttoall.
-1721
The wrong number of arguments was detected.
-1723
The accessor was not found.
-1725
There is no such Boolean operator.
-1726
An invalid comparison was made or an invalid logical descriptor was detected.
-1727
AEResolvewas given a non-object parameter.
-1728
The referenced object doesnât exist. This is a run-time resolution error, such as when attempting to reference a third object when only two objects exist.
-1729
An object counting procedure returned a negative value.
-1730
Attempted to pass an empty list to an accessor.
-1731
An unknown type of object was detected.
-10000
The Apple event handler failed.
-10001
A type mismatch has occurred.
-10002
Invalid key form was detected.
-10003
The specified object cannot be modified.
-10004
A privilege error has occurred.
-10005
The read operation was denied.
-10006
The write operation was denied.
-10007
The object index is too large.
-10008
The specified object is not an element.
-10009
Unable to provide the requested type.
-10010
The Apple event handler doesnât support the specified class.
-10011
The event is not part of the current transaction.
-10012
There is no such transaction.
-10013
Nothing is selected by the user.
-10014
The Apple event handler only handles single objects.
-10015
The previous action canât be undone.
-10016
The Apple event handler does not handle remote events.
-10023
The specified constant value is invalid for this property.
-10024
The specified class canât be an element of the specified container, such as when attempting to make or duplicate an object.
-10025
An invalid combination of properties was provided, such as for theset,make, orduplicatecommand.
## Open Scripting Architecture Errors
An Open Scripting Architecture error may occur when the scripting system itself encounters an error.
Error number
Error message
-1750
A scripting component error has occurred.
-1751
An invalid script ID was detected.
-1752
The script isnât a supported type.
-1753
A script error has occurred.
-1754
A bad selector was detected.
-1756
The source is not available.
-1757
There is no matching dialect.
-1758
The data format is obsolete.
-1759
The data format is too new.
-1761
There is a component mismatchâparameters are from two different components.
-1762
Unable to connect to the scripting system matching the specified ID.
-1763
Unable to store memory pointers in a saved script.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Open Scripting Architecture
TheOpen Scripting Architecture (OSA)provides a standard and extensible mechanism for interapplication communication in OS X. Communication takes place through the exchange of Apple events, a type of message designed to encapsulate commands and data of any complexity.
Apple events provide an event dispatching and data transport mechanism that can be used within a single application, between applications on the same computer, and between applications on different computers. The OSA defines data structures, a set of common terms, and a library of functions, so that applications can more easily create and send Apple events, as well as receive them and extract data from them.
Note:Apple events are not always the most efficient or appropriate mechanism for communicating between processes. OS X offers other mechanisms, including distributed objects, notifications, sockets, ports, streams, shared memory, and Mach messaging. These mechanisms are described in âIPC and Notification Mechanismsâ inKernel and Device Drivers LayerinMac Technology Overview.
The OSA supports several powerful features in OS X:
- the ability to create scriptable applications (described inScriptable Applications)
the ability to create scriptable applications (described inScriptable Applications)
- the ability for users to write scripts that combine operations from multiple scriptable applications
the ability for users to write scripts that combine operations from multiple scriptable applications
- the ability to communicate between applications with Apple events
the ability to communicate between applications with Apple events
## The Parts of the Open Scripting Architecture
Applications that need full access to the Open Scripting Architecture can get it by linking with the Carbon framework. Some applications that work with Apple events (especially those with minimal user interface requirements) may be able to obtain all the services they need by linking to the Core Services framework.
Note:Aframeworkis a type of bundle (or directory in the file system) that packages software with the resources that software requires, including the headers that define its interface. Frameworks are typically located in/System/Library/Frameworks, though they may be nested inside other frameworks.
The Open Scripting Architecture is made up of the following parts:
- TheApple Event Managerprovides an API for sending and receiving Apple events and working with the information they contain. It supplies the underlying support for creating scriptable applications. It is implemented inAE.framework, a subframework ofCoreServices.framework. (Prior to OS X version 10.5, theAE.frameworkwas a subframework ofApplicationServices.framework.)This framework also defines constants that developers can use to support a standard vocabulary for Apple events among different applications.For API documentation, seeApple Event Manager Reference. For conceptual documentation and code samples, seeApple Events Programming Guide.
TheApple Event Managerprovides an API for sending and receiving Apple events and working with the information they contain. It supplies the underlying support for creating scriptable applications. It is implemented inAE.framework, a subframework ofCoreServices.framework. (Prior to OS X version 10.5, theAE.frameworkwas a subframework ofApplicationServices.framework.)
This framework also defines constants that developers can use to support a standard vocabulary for Apple events among different applications.
For API documentation, seeApple Event Manager Reference. For conceptual documentation and code samples, seeApple Events Programming Guide.
- TheCarbon umbrella frameworkincludes the HIToolbox framework, which in turn defines certain functions used in processing and sending Apple events (for example, in the header fileInteraction.h).
TheCarbon umbrella frameworkincludes the HIToolbox framework, which in turn defines certain functions used in processing and sending Apple events (for example, in the header fileInteraction.h).
- TheOpen Scripting frameworkdefines standard data structures, routines, and resources for creating scripting components, which support scripting languages. Because of its standard interface, applications can interact with any scripting component, regardless of its language. This framework provides API for compiling, executing, loading, and storing scripts. It is implemented inOpenScripting.framework, a subframework ofCarbon.framework.For documentation, seeOpen Scripting Architecture Reference.
TheOpen Scripting frameworkdefines standard data structures, routines, and resources for creating scripting components, which support scripting languages. Because of its standard interface, applications can interact with any scripting component, regardless of its language. This framework provides API for compiling, executing, loading, and storing scripts. It is implemented inOpenScripting.framework, a subframework ofCarbon.framework.
For documentation, seeOpen Scripting Architecture Reference.
- The AppleScript component (inSystem/Library/Components) implements the AppleScript language, which provides a way for scripts to control scriptable applications.The AppleScript language is described inAppleScript Language Guide, as well as in a number of third-party books.
The AppleScript component (inSystem/Library/Components) implements the AppleScript language, which provides a way for scripts to control scriptable applications.
The AppleScript language is described inAppleScript Language Guide, as well as in a number of third-party books.
## Apple Events
The Apple event is the basic message for interprocess communication in the Open Scripting Architecture. With Apple events, you can gather all the data necessary to accomplish a high level task into a single package that can be passed across process boundaries, evaluated, and returned with results.
An Apple event consists of a series of nested data structures, each identified by one or more four-character codes (also referred to as Apple event codes). These data structures, as well as the codes and the header files in which they are defined, are described inApple Events Programming Guide. That document also provides conceptual information about Apple events and programming examples that work with them. For a list of four-character codes and their related terminology used by Apple, seeAppleScript Terminology and Apple Event Codes Reference. Your application can reuse these terms and codes whenever it performs an equivalent function.
## Apple Events Sent by the Mac OS
The Mac OS takes advantage of Apple events to communicate with applications, such as to notify an application that it has been launched or should open or print a list of documents. Applications that present a graphical user interface must be able to respond to whichever of these events make sense for the application. For example, all such applications can be launched and quit, but some may not be able to open or print documents.
For detailed information on the events sent by the Mac OS and how to respond to them, see:
- For Carbon applications: âHandling Events Sent by the Mac OSâ inResponding to Apple EventsinApple Events Programming Guide.
For Carbon applications: âHandling Events Sent by the Mac OSâ inResponding to Apple EventsinApple Events Programming Guide.
- For Cocoa applications:How Cocoa Applications Handle Apple EventsinCocoa Scripting Guide.
For Cocoa applications:How Cocoa Applications Handle Apple EventsinCocoa Scripting Guide.
## Script Execution in the Open Scripting Architecture
The Open Scripting Architecture allows users to control multiple applications with scripts written in a variety of scripting languages. Each scripting language has a corresponding scripting component. The AppleScript component supports the AppleScript language. When a scripting component executes a script, statements in the script may result in Apple events being sent to applications.
Although AppleScript is the most widely used language (and the only one provided by Apple), developers are free to use the Open Scripting Architecture to create scripting components for other scripting languages. Depending on the implementation, scripts written in these languages may be able to communicate with scriptable applications.
Figure 1shows what happens when theScript Editorapplication executes an AppleScript script that targets the Mail application. Script Editor calls functions in the Open Scripting framework. The Open Scripting framework communicates through the AppleScript component, which in turn uses the Apple Event Manager to send any required Apple events to the Mail application. If a reply is requested, the Mail application returns information in a reply Apple event.
Applications can also call Apple Event Manager functions directly to send Apple events to other applications and get replies from them (not shown inFigure 1).
## Extending AppleScript with Coercions, Scripting Additions, and Faceless Background Applications
Developers can extend AppleScript by creating bundles that provide command handlers and coercion handlers. The bundles can be applications or scripting additions. However, in many cases the best solution for extending AppleScript is to provide features through a faceless background applicationâthat is, a sort of invisible server application.
### Coercions
Coercionis the process of converting the information in an Apple event from one type to another. Acoercion handleris a function that provides coercion between two (or possibly more) data types. OS X provides default coercion between many standard types. For a complete listing, seeDefault Coercion HandlersinApple Events Programming Guide.
Coercion is available to both scripts and applications. In a script, for example, the following statement coerces the numeric value 1234 to the string value â1234â.
```applescript
set myString to 1234 as text
```
A scriptable application can specify a type when it uses an Apple Event Manager function to extract data from an Apple event. If the data is not already in the specified type, the Apple Event Manager will attempt to coerce it to that type. An application can provide coercion handlers for its own data types, as described inWriting and Installing Coercion HandlersinApple Events Programming Guide.
### Scripting Additions
Ascripting additionis a file or bundle that provides AppleScript commands or coercions. A single scripting addition can contain multiple handlers. For example, the Standard Additions scripting addition in OS X (filenameStandardAdditions.osax), includes commands for using the Clipboard, obtaining the path to a file, speaking text, executing shell scripts, and more. The commands provided by the Standard Additions are available to all scripts. To see what terminology a scripting addition provides, you can examine its dictionary, as described inDisplaying Scripting Dictionaries.
Terms introduced by scripting additions exist in the same name space as AppleScript terms and application-defined terms. While this has the advantage of making a service globally available, it also means that terms from scripting additions can conflict with other terms, polluting the global name space. Debugging scripting additions can also be difficult. Because you can not simply set breakpoints in your own code, you may need to use sampling, profiling, and various other tools to determine where a problem lies. (SeeFaceless Background Applicationsfor an approach that avoids these problems.)
A scripting addition provides its services by installing event handlers (for commands) or coercion handlers (for coercions) in an applicationâs system dispatch tables. The handlers for the Standard Additions (and for any other scripting additions installed by the Mac OS in/System/Library/ScriptingAdditions) get installed if the application calls API in the Open Scripting framework, or if the application specifically loads a scripting addition. An application can also specifically load other scripting additions from other locations.
For information on writing scripting additions, see Technical Note TN1164,Native Scripting Additions. For information on loading scripting additions, see Technical Q&A QA1070,Loading Scripting Additions Without Initializing Apple Script in OS X.
### Faceless Background Applications
A faceless background application (now more commonly referred to as an agent), is one that, as its name implies, runs in the background and has no visible user interface. By creating a scriptable agent, you can provide services without some of the disadvantages of scripting additions. For example, you can develop and debug in a standard application environment, and any terminology you provide does not pollute the global name spaceâit is available only within a scriptâstellstatement that targets the agent.
You can install your agent directly, but if it is intended for use with another application, you can put it in theResourcesfolder of the application it supports. That promotes ease of use by allowing a drag-and-drop installation process, and will minimize users stumbling across the agent and asking âWhat is this for?â The agent will be launched whenever it is referenced in atellstatement. It can be told to quit, and you can also set it up to time out, so it can get unloaded when it is no longer in use.
Apple provides a number of scriptable services through agents, as described inSystem Events and GUI Scripting,Image Events, andDatabase Events. For example, scripts can use the System Events application to perform operations on property list files.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Libraries using Load Script
OS X Mavericks v10.9 (AppleScript 2.3) introduces built-in support for script libraries, which are scripts containing handlers that may be shared among many scripts. Scripts that must run on older versions of the OS can share handlers between scripts usingload script, as described here.
## Saving and Loading Libraries of Handlers
In addition to defining and calling handlers within a script, you can access handlers from other scripts. To make a handler available to another script, save it as a compiled script, then use theload scriptcommand to load it in any script that needs to call the handler. You can use this technique to create libraries containing many handlers.
Note:Theload scriptcommand loads the compiled script as ascriptobject; for more information, seeScript Objects.
For example, the following script contains two handlers:areaOfCircleandfactorial:
```applescript
-- This handler computes the area of a circle from its radius.
```
```applescript
-- (The area of a circle is equal to pi times its radius squared.)
```
```applescript
on areaOfCircle from radius
```
```applescript
-- Make sure the parameter is a real number or an integer.
```
```applescript
if class of radius is contained by {integer, real}
```
```applescript
return radius * radius * pi -- pi is predefined by AppleScript.
```
```applescript
else
```
```applescript
error "The parameter must be a real number or an integer"
```
```applescript
end if
```
```applescript
end areaOfCircle
```
```applescript
```
```applescript
```
```applescript
-- This handler returns the factorial of a number.
```
```applescript
on factorial(x)
```
```applescript
set returnVal to 1
```
```applescript
if x > 1 then
```
```applescript
repeat with n from 2 to x
```
```applescript
set returnVal to returnVal * n
```
```applescript
end repeat
```
```applescript
end if
```
```applescript
return returnVal
```
```applescript
end factorial
```
In Script Editor, save the script as a compiled Script (which has extensionscpt) or Script Bundle (extensionscptd) and name it âNumberLibâ.
After saving the script as a compiled script, other scripts can use theload scriptcommand to load it. For example, the following script loads the compiled scriptNumberLib.scpt, storing the resultingscriptobject in the variablenumberLib. It then makes handler calls within atellstatement that targets thescriptobject. The compiled script must exist in the specified location for this script to work.
```applescript
set numberLibrary to (load script file "NumberLib.scpt")
```
```applescript
```
```applescript
tell numberLibrary
```
```applescript
factorial(10) --result: 3628800
```
```applescript
areaOfCircle from 12 --result: 452.38934211693
```
```applescript
end tell
```
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# AppleScript Keywords
This appendix lists AppleScript keywords (orreserved words), provides a brief description for each, and points to related information, where available. (See alsoKeywordsinAppleScript Lexical Conventions.)
The keywords inTable A-1are part of the AppleScript language. You should not attempt to reuse them in your scripts for variable names or other purposes. Developers should not re-define keywords in the terminology for their scriptable applications. You can view many additional scripting terms defined by Apple, but not part of the AppleScript language, inAppleScript Terminology and Apple Event Codes.
about
handler parameter labelâseeHandler Syntax (Labeled Parameters)
above
handler parameter labelâseeHandler Syntax (Labeled Parameters)
after
used to describe position in theRelativereference form; used as part of operator (comes after,does not come after) with classes such asdate,integer, andtext
against
handler parameter labelâseeHandler Syntax (Labeled Parameters)
logicalandoperatorâseeTable 9-1
apart from
handler parameter labelâseeHandler Syntax (Labeled Parameters)
around
handler parameter labelâseeHandler Syntax (Labeled Parameters)
coercion operatorâseeTable 9-1
aside from
handler parameter labelâseeHandler Syntax (Labeled Parameters)
handler parameter labelâseeHandler Syntax (Labeled Parameters)
back
used withIndexandRelativereference forms;in back ofis synonymous withafterandbehind
before
used to describe position in theRelativereference form; used as an operator (comes before,does not come before) with classes such asdate,integer, andtext; synonymous within front of
beginning
specifies an insertion location at the beginning of a containerâsee the boundary specifier descriptions for theRangereference form
behind
synonymous withafterandin back of
below
handler parameter labelâseeHandler Syntax (Labeled Parameters)
beneath
handler parameter labelâseeHandler Syntax (Labeled Parameters)
beside
handler parameter labelâseeHandler Syntax (Labeled Parameters)
between
handler parameter labelâseeHandler Syntax (Labeled Parameters)
used inconsidering and ignoring Statements
used with binary containment operatorcontains, is contained by; also used as handler parameter labelâseeHandler Syntax (Labeled Parameters)
considering
a control statementâseeconsidering and ignoring Statements
contain, contains
binary containment operatorâseecontains, is contained by
continue
changes the flow of executionâseecontinue
copy
an AppleScript commandâseecopy
division operatorâseeTable 9-1
does
used with operators such asdoes not equal,does not come before, anddoes not containâseeTable 9-1
eighth
specifies a position in a containerâseeIndexreference form
else
used withifcontrol statementâseeif Statements
marks the end of a script or handler definition, or of a compound statement, such as atellorrepeatstatement; also specifies an insertion location at the end of a containerâsee the boundary specifier descriptions for theRangereference form
equal, equals
binary comparison operatorâseeequal, is not equal to
error
errorcontrol statement; also used withtrystatement
every
specifies every object in a containerâseeEveryreference form
exit
terminates arepeatloopâseeexit
false
a Boolean literalâseeBoolean
fifth
specifies a position in a containerâseeIndexreference form
first
specifies a position in a containerâseeIndexreference form
handler parameter labelâseeHandler Syntax (Labeled Parameters)
fourth
specifies a position in a containerâseeIndexreference form
from
used in specifying a range of objects in a containerâseeRangereference form; also used as handler parameter labelâseeHandler Syntax (Labeled Parameters)
front
in front ofis used to describe position in theRelativereference form; synonymous withbefore
an AppleScript commandâseeget
given
a special handler parameter labelâseeHandler Syntax (Labeled Parameters)
global
specifies the scope for a variable (see alsolocal)âseeGlobal Variables
a control statementâseeif Statements
ignoring
a control statementâseeconsidering and ignoring Statements
used in construction object specifiersâseeContainers; also used with theRelativereference formâfor examplein front ofandin back of
instead of
handler parameter labelâseeHandler Syntax (Labeled Parameters)
into
put intois a deprecated synonym for thecopycommand; also used as handler parameter labelâseeHandler Syntax (Labeled Parameters)
used with various comparison operatorsâseeTable 9-1
refers to the current target (of it)âseeThe it and me Keywords
synonym forof itâseeThe it and me Keywords
last
specifies a position in a containerâseeIndexreference form
local
specifies the scope for a variable (see alsoglobal)âseeLocal Variables
refers to the current script (of me)âseeThe it and me Keywords
middle
specifies a position in a containerâseeIndexreference form
remainder operatorâseeTable 9-1
synonym forof meâseeThe it and me Keywords
ninth
specifies a position in a containerâseeMiddlereference form
logical negation operatorâseeTable 9-1
used in construction object specifiersâseeContainers; used with or as part of many other terms, includingof me,in front of, and so on
handler parameter labelâseeHandler Syntax (Labeled Parameters)
onto
handler parameter labelâseeHandler Syntax (Labeled Parameters)
logicaloroperatorâseeTable 9-1
out of
handler parameter labelâseeHandler Syntax (Labeled Parameters)
over
handler parameter labelâseeHandler Syntax (Labeled Parameters)
prop, property
propis an abbreviation forpropertyâseeThe it and me Keywords
put intois a deprecated synonym for thecopycommand
ref/reference
refis an abbreviation forreferenceâseereference
repeat
a control statementâseerepeat Statements
return
exits from a handlerâseereturn
returning
deprecated
script
used to declare a script object; also the class of a script objectâsee thescriptclass andScript Objects
second
specifies a position in a containerâseeIndexreference form
an AppleScript commandâseeset
seventh
specifies a position in a containerâseeIndexreference form
since
handler parameter labelâseeHandler Syntax (Labeled Parameters)
sixth
specifies an index position in a containerâseeIndexreference form
some
specifies an object in a containerâseeArbitraryreference form
tell
a control statementâseetell Statements
tenth
specifies a position in a containerâseeIndexreference form
that
synonym forwhose
syntactic no-op, used to make script statements look more like natural language
then
used withifcontrol statementâseeif Statements
third
specifies a position in a containerâseeIndexreference form
through, thru
used in specifying a range of objects in a containerâseeRangereference form
timeout
used withwith timeoutcontrol statementâseewith timeout
times
used withrepeatcontrol statementâseerepeat (number) times
used in many places, includingcopyandsetcommands; in theRangereference form; by operators such asis equal toanda reference to; with the control statementrepeat with loopVariable (from startValue to stopValue); with the partial result parameter intry Statements
transaction
used withwith transactioncontrol statementâseewith transaction
true
a Boolean literalâseeBoolean
an error-handling statementâseetry Statements
until
used withrepeatcontrol statementâseerepeat until
a requirement statementâseeuse Statements
where
used with theFilterreference form to specify a Boolean test expression (synonymous withwhose)
while
used withrepeatcontrol statementâseerepeat while
whose
used with theFilterreference form to specify a Boolean test expression (synonymous withwhere)
with
used in commands to specify various kinds of parameters, includingtruefor some Boolean for parametersâsee, for example, thewith promptandmultiple selections allowedparameters to thechoose from listcommand; also used with applicationmakecommands to specify properties (with properties)
without
used in commands to specifyfalsefor a Boolean for a parameterâsee, for example, themultiple selections allowedparameter to thechoose from listcommand
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Scripting with AppleScript
The following is a brief introduction to AppleScript scripts, tools for working with them, and information on using AppleScript scripts together with other scripting systems. For related documents, see the learning paths inGetting Started with AppleScript.
## Script Editor and AppleScript Scripts
An AppleScript script consists of one or more statements, written in a syntax described inAppleScript Language Guide(and in a number of third-party books). AppleScript defines some scripting terms, while scriptable applications and parts of the Mac OS specify additional terms for scriptable features they support. Scripting terminologies generally use common English words, resulting in scripts that are easier to read. For example, the following is a valid script statement:
```applescript
display dialog "Welcome to AppleScript."
```
Users can compile and execute scripts with theScript Editorapplication and can save them in various executable formats, including as stand-alone applications.
### A Simple AppleScript Script
Listing 1shows an AppleScript script that simply returns the number of files in theApplicationsfolder on the current system disk (denoted bystartup disk, a term understood by the Finder). If the folder cannot be found, the script returns a count of zero. This script counts just files in the specified folder, not folders or the files they might contain.
Listing 1A script that counts the files in the Applications folder
```applescript
tell application "Finder"
```
```applescript
if folder "Applications" of startup disk exists then
```
```applescript
return count files in folder "Applications" of startup disk
```
```applescript
else
```
```applescript
return 0
```
```applescript
end if
```
```applescript
end tell
```
When a script is compiled and executed, some statements perform basic operations, such as assigning a variable or returning a value. A statement that targets a scriptable application results in an Apple event being sent to that application. The application can return information to the script in a reply Apple event.
The script inListing 1causes an Apple event to be sent to the Finder, which locates the Applications folder on the startup disk, counts the files in it, and returns that value. Theif...then...elsestructure is one of several standard programming language features that AppleScript supports.
### Script Editor
The Script Editor application is located in/Applications/AppleScript. It provides the ability to edit, compile, and execute scripts, display application scripting terminologies, and save scripts in a variety of formats, such as compiled scripts, applications, bundled applications, and plain text.
Script Editor can display the result of executing an AppleScript script and can display a log of the Apple events that are sent during execution of a script. In the Script Editor Preferences, you can also choose to keep a history of recent results or event logs.
Script Editor has text formatting preferences for various types of script text, such as language keywords, comments, and so on. You can also turn on or off the Script Assistant, a code completion tool that can suggest and fill in scripting terms as you type. In addition, Script Editor provides a contextual menu to insert many types of boilerplate script statements, such as conditionals, comments, and error handlers.
#### Displaying Scripting Dictionaries
You can choose File > Open Dictionary in Script Editor to examine the scripting dictionary of a scriptable application or scripting addition on your computer. Or you can drag an application icon to the Script Editor icon to display its dictionary (if it has one). You can also open scripting dictionaries in Xcode.
To display a list that includes just the scriptable applications and scripting additions provided by the Mac OS, choose Window > Library. Double-click an item in the list to display its dictionary.Figure 1shows the dictionary for the Finder application in OS X version 10.5. The dictionary is labeled as âFinder.sdefâ. The sdef format, along with other terminology formats, is described inSpecifying Scripting Terminology.
#### Debugging and Third Party Products
Script Editor supports only simple debugging strategies, such as logging event output and insertingspeakordisplay dialogstatements within scripts. However, there are a number of third-party products for working with AppleScript, some of them quite powerful. For example, there are script editors and tools for monitoring and debugging scripts, Apple events, and scriptable applications. Some of these third-party products are listed at theAppleScript Resourcesweb page.
For information on debugging scriptable applications and Apple events, see the documentsCocoa Scripting GuideandApple Events Programming Guide.
### Interacting with the User in Scripts
AppleScript provides little direct support for interacting with the user in scripts. However, the Standard Additions scripting addition provides terminology for obtaining various choices from the user. For example, it includes commands for letting the user choose an application, a color, a file, a filename, and so on. It also provides thedisplay dialogcommand, which allows you to display a dialog with various options for text labels, buttons, and text input. Scripting Additions are described inExtending AppleScript with Coercions, Scripting Additions, and Faceless Background Applications.
## What You Can Control with Scripts
Many applications from Apple are scriptable and you can also script some parts of the Mac OS. For example, the Finder, iTunes, QuickTime Player, and Mail are highly scriptable. For a complete list, see theScriptable Applicationsweb page at theAppleScriptwebsite. For more information on scriptability provided by Apple, seeAppleScript Utilities and Applications.
Note:You can also control many Apple technologies and applications withAutomator, which is available starting in OS X version 10.4.
Many third-party applications are scriptableâtheir advertising and packaging usually mention if they are scriptable. The documentation for a scriptable application typically lists the AppleScript terminology that the application understands. You can also determine if an application is scriptable by attempting to examine its dictionary with the Script Editor application, as described inDisplaying Scripting Dictionaries.
Note:For a list of scriptable applications from all parties, see âScriptable Applicationsâ at theMacScripterwebsite.
## Using AppleScript with Web Services
XML-RPC and SOAP are remote procedure call protocols that support exchanging commands and information over the Internet. Starting with OS X version 10.1, AppleScript and the Apple Event Manager provide XML-RPC and SOAP support such that:
- Scripters can make XML-RPC calls and SOAP requests from scripts.
Scripters can make XML-RPC calls and SOAP requests from scripts.
- Developers can make XML-RPC calls and SOAP requests from applications or other code by sending Apple events.
Developers can make XML-RPC calls and SOAP requests from applications or other code by sending Apple events.
For documentation on using AppleScript with web services, seeXML-RPC and SOAP Programming Guide(some examples may be out of date). For additional sources and examples, seeWeb Services. For information on developing web content and applications for the web in OS X, seeGetting Started with Internet and Web.
## Using AppleScript with Other Scripting Systems
OS X supports a UNIX-like shell environment that is familiar to many developers. That support includes the Terminal application, located in/Applications/Utilities, which you can use to open shell windows and execute shell scripts. AppleScript provides two convenient mechanisms to interact with a shell environment: you can execute shell commands from within AppleScript scripts and you can execute AppleScript scripts as shell commands.
### Executing Shell Commands From AppleScript Scripts
AppleScript provides thedo shell scriptcommand to support executing a shell command as part of an AppleScript script. For example, the following script statement uses ado shell scriptcommand to change the directory to the current userâs home directory and obtain a list of the files found there. The list information is stored in the AppleScript variablefileInfo:
```applescript
set fileInfo to do shell script "cd ~; ls"
```
Thedo shell scriptcommand is primarily of use to scripters. Although applications can execute AppleScript scripts that use thedo shell scriptcommand, they have more efficient options for executing shell commands, as described inSupport for Carbon ApplicationsandSupport for Cocoa Applications. For more information on thedo shell scriptcommand, see Technical Note TN2065,do shell script in AppleScript.
### Executing AppleScript Scripts as Shell Commands
To execute AppleScript scripts as shell commands in a Terminal window or shell script file, you can use theosacompilecommand and theosascriptcommand (located in/usr/bin). The former compiles an AppleScript script, while the latter executes a plain text or a compiled AppleScript script. Man pages provide documentation for these commands. For example, typeman osascriptin a Terminal window to get information on theosascriptcommand.
Starting in OS X version 10.5, there is a command-line tool to display compiled scripts as text,osadecompile. Again, see the man page for details.
Also starting in Mac OX X v10.5, AppleScript allows use of the # symbol as a comment-to-end-of-line token (the traditional double hyphen (--) is also still supported). This means that you can make a plain AppleScript script into a Unix executable by beginning it with the following line and giving it execute permission.
```applescript
#!/usr/bin/osascript
```
### Scripting the Terminal Application
The Terminal application is itself scriptable. For example, you can use thedo scriptcommand to execute text as a shell script or command. To see the operations Terminal supports, you can examine its scripting dictionary with Script Editor.
### Using Other Scripting Languages
For those who have experience with various scripting languages and environments, the previous sections have probably already provided an urge to start experimenting. And you do have a lot of options for combining features from the scripting tools, languages, and environments that are most appropriate for specific kinds of tasks. For example, the following one-line shell script statement combines Perl, AppleScript, and various tools to find duplicate entries in the Address Book application.
```applescript
osascript -e 'tell app "Address Book" to get the name of every person' | perl -pe 's/, /\n/g' | sort | uniq -d
```
This statement usesosascriptto execute an inline AppleScript script ('tell app "Address Book" to get the name of every person') that returns the names of every address entry from the Address Book application. It pipes the output of this script through theperltool, and with a series of other commands and pipes, obtains and formats a (possibly empty) list of duplicate names.
For additional information about working with AppleScript from languages such as Ruby and Python, seeScripting Bridge.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Scriptable Applications
Ascriptable applicationis one that goes beyond the basics of responding to Apple events sent by the Mac OS to make its most important data and operations available to AppleScript scripts or to other applications. To do this, the application must provide both a terminology for scripters to use and the underlying Apple event code to support it. Both Carbon and Cocoa applications can be scriptable, and the Cocoa framework contains built-in support that minimizes the amount of code you have to write.
## Specifying Scripting Terminology
Scriptable applications describe the scripting terminology they support by supplying a scripting dictionary. A dictionary specifies the commands and objects an application supports, as well as other information that is used by AppleScript or the application itself, and possibly by other applications or scripts that want to take advantage of the applicationâs scriptability. For information on designing a scripting terminology, see Technical Note TN2106,Scripting Interface Guidelines.
Users typically examine a dictionary for information on how to control an application in their scripts. You can display the dictionary for a scriptable application or scripting addition with Script Editor, as described inDisplaying Scripting Dictionaries.
There are currently three dictionary formats:
- sdef:âsdefâ is short for âscripting definition.â This XML-based format is a superset of the two formats described next and supports new and improved features. Although prior to OS X version 10.4, you could not use an sdef directly in your application, you could convert an sdef into either of the other formats with thesdptool. Starting in OS X v10.4, Cocoa applications can work natively with the sdef format, as described inPreparing a Scripting Definition Fileand other chapters inCocoa Scripting Guide.In OS X v10.5 (Leopard), itâs possible to create applications that provide dictionary information solely in sdef format, both for Carbon and Cocoa applications. You can read about additional refinements to sdef usage in Cocoa applications for Leopard in the Scripting section ofFoundation Release Notes for macOS 10.13 and iOS 11.For documentation on the sdef format, including a change history, see thesdef(5) man page.Scripting Interface Guidelinesalso includes information on working with sdefs. For documentation on thesdptool, see the man page forsdp(1), as well asEvolution of Cocoa Scriptability InformationinCocoa Scripting Guide. For an example of how to use an sdef file, see the Sketch sample application. For other examples, see the sample code projects listed inSupport for Cocoa Applications.
sdef:âsdefâ is short for âscripting definition.â This XML-based format is a superset of the two formats described next and supports new and improved features. Although prior to OS X version 10.4, you could not use an sdef directly in your application, you could convert an sdef into either of the other formats with thesdptool. Starting in OS X v10.4, Cocoa applications can work natively with the sdef format, as described inPreparing a Scripting Definition Fileand other chapters inCocoa Scripting Guide.
In OS X v10.5 (Leopard), itâs possible to create applications that provide dictionary information solely in sdef format, both for Carbon and Cocoa applications. You can read about additional refinements to sdef usage in Cocoa applications for Leopard in the Scripting section ofFoundation Release Notes for macOS 10.13 and iOS 11.
For documentation on the sdef format, including a change history, see thesdef(5) man page.Scripting Interface Guidelinesalso includes information on working with sdefs. For documentation on thesdptool, see the man page forsdp(1), as well asEvolution of Cocoa Scriptability InformationinCocoa Scripting Guide. For an example of how to use an sdef file, see the Sketch sample application. For other examples, see the sample code projects listed inSupport for Cocoa Applications.
- script suite:This is the original format used by Cocoa applications and it is still supported for backward compatibility. A script suite contains a pair of information property list (plist) files that provide both AppleScript information and information used by the application. An application can contain multiple script suites.For documentation, seeScript Suite and Script Terminology FilesinCocoa Scripting Guide.
script suite:This is the original format used by Cocoa applications and it is still supported for backward compatibility. A script suite contains a pair of information property list (plist) files that provide both AppleScript information and information used by the application. An application can contain multiple script suites.
For documentation, seeScript Suite and Script Terminology FilesinCocoa Scripting Guide.
- aete:This is the original dictionary format, and is still used in Carbon applications. The name comes from the Resource Manager resource type in which the information is stored ('aete'). An aete is useful in 10.4 and earlier, in both Carbon and Cocoa applications, to provide a dictionary that scripting languages can use without launching the application.
aete:This is the original dictionary format, and is still used in Carbon applications. The name comes from the Resource Manager resource type in which the information is stored ('aete'). An aete is useful in 10.4 and earlier, in both Carbon and Cocoa applications, to provide a dictionary that scripting languages can use without launching the application.
## Determining What to Make Scriptable
In designing a scriptable application, itâs a good idea to provide access to all of the applicationâs main features, though it may make sense to start with just a key subset. You donât typically make your applicationâs user interface directly scriptable. A good design allows users to script your applicationâs model objects (which represent data and basic behaviors) rather than its user interface (which presents information to the user).
For example, the scripting support for a drawing application might allow a script to rotate an image, but not to perform the user interface operation of clicking a Rotate button. Some applications provide additional capabilities through their scripting interface that arenât otherwise available.
For design information, see âLearning How to Make an Application Scriptableâ inGetting Started with AppleScriptand Technical Note TN2106,Scripting Interface Guidelines.
For information on how to support printing in a scriptable application, seeThe Enhanced Print Apple Event.
## Registering to Receive Apple Events
A scriptable application typically responds to a set of common commands, such asget data,set data,delete, andsave, as well as to other commands that support operations specific to the application. Commands are represented in Apple events by constants defined in framework or application headers. To support a command, an application registers an event handler routine with the Apple Event Manager to handle Apple events it receives that specify that command. The Apple Event Manager dispatches received events to the handlers registered for them.
Note:For Cocoa applications, commands are registered automatically, so that developers rarely need to register apple event handlers directly.
For more information on creating and registering event handlers, seeApple Event DispatchingandResponding to Apple EventsinApple Events Programming Guide.
## Resolving Objects in the Application
Apple events often specify items in the application. For example, aget dataevent might ask for the text of a paragraph in an open document. A distinct item in an application that can be specified in an Apple event is known as anApple event object. (The term object does not imply that the items must be represented internally as objects in an object-oriented programming language.) All such objects are considered to be contained in other objects, with the application itself serving as the ultimate container. For a given application, theAppleScript object model(also called the Apple event object model) specifies the classes of objects a scripter can work with in scripts, the accessible properties of those objects, and the inheritance and containment relationships for those objects.
The structures within an Apple event that identify objects are referred to asobject specifiers. Finding the Apple event objects they specify is known as resolving the object specifiers. To resolve object specifiers, an application must include functions that are able to find objects within their containers. The application registers these functions with the Apple Event Manager, and works with the Apple Event Manager to call them at the appropriate time to obtain the objects they specify.
For Cocoa applications, Cocoa scripting support does much of the work of resolving object specifiers, but a scriptable application must still supply methods that can locate an object within its object model containment hierarchy.
For an example of an AppleScript object model, seeOverview of Cocoa Support for Scriptable Applications; for information on how Cocoa applications resolve objects, seeObject Specifiers; both are inCocoa Scripting Guide.
## Recording
A recordable application is one that sends Apple events to itself when a user performs actions with the application. If the user has turned on recording in the Script Editor application (with Script > Record), actions that generate Apple events are recorded into an AppleScript script.
Applications that support recording typically:
- Factor code that implements the user interface from code that actually performs operations (a standard approach for applications that follow the model-view-controller design paradigm).
Factor code that implements the user interface from code that actually performs operations (a standard approach for applications that follow the model-view-controller design paradigm).
- Send Apple events within the application to connect those two parts of the application. The Apple Event Manager provides a mechanism for doing this with a minimum of overhead, described in âAddressing an Apple Event for Direct Dispatchingâ inCreating and Sending Apple EventsinApple Events Programming Guide.
Send Apple events within the application to connect those two parts of the application. The Apple Event Manager provides a mechanism for doing this with a minimum of overhead, described in âAddressing an Apple Event for Direct Dispatchingâ inCreating and Sending Apple EventsinApple Events Programming Guide.
- Make sure that any significant action or series of related actions within the application generates an Apple event.
Make sure that any significant action or series of related actions within the application generates an Apple event.
The Finder application in OS X is recordable. Starting in OS X version 10.5, theAutomatorapplication has a separate Record mechanism that lets users record actions into an Automator workflow.
## Creating and Sending Apple Events
An application can create and send Apple events directly. This is usually done either to send internal Apple events, as described inRecording, to obtain services from a scriptable application, or to communicate directly with another application. The Open Scripting Architecture provides various mechanisms for creating and sending Apple events.
Starting in OS X version 10.5, applications can useScripting Bridgeto obtain services from scriptable applications. Scripting Bridge lets you work efficiently in a high-level language (Objective-C) without having to handle the details of sending and receiving Apple events. (See alsoSupport for Cocoa Applicationsfor related information.)
When you really do need to send an Apple event directly, seeBuilding an Apple EventandCreating and Sending Apple EventsinApple Events Programming Guide.
## Executing Scripts
To execute scripts, an application establishes a connection with the AppleScript scripting component. It can then:
- Use the standard scripting component routines to manipulate scripts associated with any part of the application or its documents.
Use the standard scripting component routines to manipulate scripts associated with any part of the application or its documents.
- Let users record and edit scripts.
Let users record and edit scripts.
- Compile and execute scripts.
Compile and execute scripts.
Note:Starting in OS X version 10.5, applications can useScripting Bridgeto obtain services from scriptable applications. This can be much more efficient than manipulating scripts.
An application can store and execute scripts regardless of whether it is scriptable or recordable. If an application is scriptable, however, it can execute scripts that control its own behavior, thus acting as both the client application and the server application for the corresponding Apple events. For more information, seeOpen Scripting Architecture Reference.
In Cocoa, theNSAppleScriptclass, described inNSAppleScript Class Reference, provides a high-level wrapper for executing AppleScript scripts from applications. For more information, seeSupport for Cocoa Applications.
## Summary of Operations in a Scriptable Application
The following list summarizes how scriptable applications interact with the Open Scripting Architecture to make their features available to scripters.
- The Apple Event Manager defines data structures that are used to construct Apple events.
The Apple Event Manager defines data structures that are used to construct Apple events.
- The Open Scripting Architecture (OSA) provides a data transport and event dispatching mechanism for Apple events, built on top of lower level protocols.
The Open Scripting Architecture (OSA) provides a data transport and event dispatching mechanism for Apple events, built on top of lower level protocols.
- AppleScript defines a scripting language, described inAppleScript Language Guide(and third-party books) and implemented by the AppleScript component in OS X.
AppleScript defines a scripting language, described inAppleScript Language Guide(and third-party books) and implemented by the AppleScript component in OS X.
- There is a small set of Apple events sent by the Mac OS, such asopen application,quit, andopen documentsthat all applications should be able to respond to. A scriptable application responds to additional common events, such asget dataandset data, as well as to its own specific commands.
There is a small set of Apple events sent by the Mac OS, such asopen application,quit, andopen documentsthat all applications should be able to respond to. A scriptable application responds to additional common events, such asget dataandset data, as well as to its own specific commands.
- A scriptable application provides a scripting terminology (or dictionary) for the operations it supports. The application can reuse some event constants defined by the OSA or use its own for custom events. (Constants defined by Apple, many of which you can reuse in your applications, are described inAppleScript Terminology and Apple Event Codes Reference.)The sdef file format provides a mechanism for creating one terminology definition that can be converted for use in different environments.
A scriptable application provides a scripting terminology (or dictionary) for the operations it supports. The application can reuse some event constants defined by the OSA or use its own for custom events. (Constants defined by Apple, many of which you can reuse in your applications, are described inAppleScript Terminology and Apple Event Codes Reference.)
The sdef file format provides a mechanism for creating one terminology definition that can be converted for use in different environments.
- Developers design their applications so that key operations can be invoked in response to received Apple events.
Developers design their applications so that key operations can be invoked in response to received Apple events.
- A scriptable application works with the Apple Event Manager to:Register handlers for Apple events it can process.Extract information from received Apple events, then perform requested operations or return requested data.Construct Apple events for replies or other purposes.Scriptable Carbon applications work with the Apple Event Manager directly, but for scriptable Cocoa applications, much of this work is handled automatically.
A scriptable application works with the Apple Event Manager to:
- Register handlers for Apple events it can process.
Register handlers for Apple events it can process.
- Extract information from received Apple events, then perform requested operations or return requested data.
Extract information from received Apple events, then perform requested operations or return requested data.
- Construct Apple events for replies or other purposes.
Construct Apple events for replies or other purposes.
Scriptable Carbon applications work with the Apple Event Manager directly, but for scriptable Cocoa applications, much of this work is handled automatically.
- Scripters write AppleScript scripts that specify scriptable applications and the operations to perform.
Scripters write AppleScript scripts that specify scriptable applications and the operations to perform.
- When a script is executed, script statements that target applications are translated by the AppleScript component into Apple events that are sent to those applications.Applications can also send Apple events directly to other applications.
When a script is executed, script statements that target applications are translated by the AppleScript component into Apple events that are sent to those applications.
Applications can also send Apple events directly to other applications.
- An application responds to the Apple events it receives by performing operations, returning data, or both.
An application responds to the Apple events it receives by performing operations, returning data, or both.
## OS X Support for Creating Scriptable Applications
OS X supplies a number of resources that applications can use to work with Apple events and to support scriptability, including the API provided in the following frameworks:
- The underlying support in OS X for creating scriptable applications and working with Apple events is provided by the Open Scripting Architecture, and is described inThe Parts of the Open Scripting Architecture.
The underlying support in OS X for creating scriptable applications and working with Apple events is provided by the Open Scripting Architecture, and is described inThe Parts of the Open Scripting Architecture.
- TheCocoa framework(Cocoa.framework) includes the Application Kit and Foundation frameworks, which together provide the building blocks for sophisticated Mac apps. The Cocoa framework includes a great deal of support for creating scriptable applications.For specific Cocoa scripting documentation, seeCocoa Scripting Guide.
TheCocoa framework(Cocoa.framework) includes the Application Kit and Foundation frameworks, which together provide the building blocks for sophisticated Mac apps. The Cocoa framework includes a great deal of support for creating scriptable applications.
For specific Cocoa scripting documentation, seeCocoa Scripting Guide.
- Java applications are not typically scriptable, though they can be made AppleScript-aware using the mechanisms described inOS X Integration for JavainJava Development Guide for Mac.
Java applications are not typically scriptable, though they can be made AppleScript-aware using the mechanisms described inOS X Integration for JavainJava Development Guide for Mac.
### Support for Carbon Applications
Carbon applications have traditionally worked directly with the Apple Event Manager to create, send, receive, and interpret Apple events. These topics are described in detail inApple Events Programming Guide.
For information on making your Carbon application scriptable, see previous sections in this chapter, as well as the learning paths inGetting Started with AppleScript.
Carbon applications can use functions such asOSACompileandOSAExecutefromOpenScripting.frameworkto compile and execute scripts. Keep in mind, however, that if you are executing a script merely to send a simple command to another application, it is more efficient to create and send an Apple event directly.
If the purpose for executing a script is just to perform ado shell scriptcommand, Carbon applications can do so more efficiently using one of the BSD callssystem(3),popen(3), orexec(3), which you can read about at their respective man pages.
### Support for Cocoa Applications
The Foundation and Application Kit frameworks provide Cocoa applications with automated handling for certain Apple events. This includes events that may be sent by the Mac OS, such as theopen application,open documents,print documents, andquitApple events.
In addition, Cocoa provides substantial support for creating scriptable applications. To take advantage of it, applications provide scriptability information in one of the formats described inSpecifying Scripting Terminology. They also create KVC-compliant accessors for scriptable properties in their scriptable classes. (Key-value coding, or KVC, is described inKey-Value Coding Programming Guide.) Though creating a fully scriptable application is a non-trivial task, an application can support many standard AppleScript commands, such as those for getting and setting properties of application objects, with a relatively small number of additional steps.
Cocoa applications can also use any of the Open Scripting Architecture APIs available to Carbon applications, and in fact, Cocoa links with the Carbon framework. For example, a Cocoa Application might call an Apple Event Manager function to send an Apple event directly (there currently is no Cocoa API to do that).
Starting in OS X version 10.5, theScripting Bridgetechnology provides an efficient way for Cocoa applications to interact with scriptable applications at a high levelâthat is, without having to construct or parse individual Apple events.
Cocoa provides theNSAppleScriptclass for tasks such as compiling and executing scripts. This gives applications another mechanism to control scriptable applications and take advantage of services they provide. However, you should not useNSAppleScriptto execute a script merely to result in sending an Apple event, because it is far more expensive than using Scripting Bridge or creating and sending an Apple event directly. And if the purpose for executing a script is to perform ado shell scriptcommand, Cocoa applications can execute shell commands more efficiently usingNSTask.
The Cocoa framework also includes classes such asNSAppleEventDescriptor, for working with underlying Apple event data structures, andNSAppleEventManager, for accessing certain Apple Event Manager functions.
Cocoa support for handling Apple events and creating scriptable applications is documented inCocoa Scripting Guide. For related information, see âFramework and Language Supportâ inAbout Apple EventsinApple Events Programming Guide. For introductory sample code, seeSimpleScripting,SimpleScriptingProperties,SimpleScriptingObjects, andSimpleScriptingVerbs. For a more complex example, see the Sketch sample application.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# About AppleScript
AppleScriptis a scripting language that provides direct control of scriptable applications and scriptable parts of the Mac OS. Ascriptable applicationis one that can respond to a variety of Apple events by performing operations or supplying data. AnApple eventis a type of interprocess message that can encapsulate commands and data of arbitrary complexity. By providing an API that supports these mechanisms, theOpen Scripting Architecturemakes possible one of the most powerful features in OS Xâthe ability to write scripts that automate operations with multiple applications.
You can use AppleScript scripts to perform repetitive tasks, automate complex workflows, control applications on local or remote computers, and access web services. Because script writers (or scripters) can access features in any scriptable application, they can combine features from many applications. For example, a script might make remote procedure calls to a web service to get stock quotes, add the current stock prices to a database, then graph information from the database in a spreadsheet application. From controlling an image-processing workflow to performing quality assurance testing for a suite of applications, AppleScript makes automation possible.
While the AppleScript scripting language (described inAppleScript Language Guide, and in a number of detailed third-party books) uses an English-like terminology which may appear simple, it is a rich, object-oriented language, capable of performing complicated programming tasks. However, its real strength comes from providing access to the features available in scriptable applications. If you make your application scriptable, it will help scripters get their work done, and quite likely become indispensable to their work process.
TheAutomatorapplication, available starting in OS X version 10.4, lets users work in a graphical interface to put together complex, automated workflows. Workflows consist of one or more actions, which are provided by Apple, by developers, and by scripters, and can be written in AppleScript and in other languages, including Objective-C. Starting in OS X v10.5, developers can incorporate workflows directly in their applications, providing another mechanism for accessing features of other applications and the Mac OS.
Scripting Bridge, available starting in OS X version 10.5, provides an automated process for creating an Objective-C interface to scriptable applications. This allows Cocoa applications and other Objective-C code to efficiently access features of scriptable applications, using native Objective-C syntax. Some other scripting languages, such as Ruby and Python, can use Scripting Bridge, but also have their own software bridges to access features of scriptable applicationsâfor more information, seeGetting Started With Scripting & Automation.
AppleScript has several other new or improved features in OS X v10.5, including full support for Unicode text, additional support for identifying and working with application objects in scripts, 64-bit support, more accurate and useful error messages, and additional scriptability in Apple technologies such as iChat and the Dock. For more information, seeAppleScript Features.
## When to Use AppleScript
The following are common scenarios in which you might use AppleScript or related technologies in your development work.
- Youâre creating or updating an application for OS X and you want it to be scriptable. As a scriptable application, users can invoke it in their AppleScript scripts and you can write scripts to perform automated testing during development. You can also make the application accessible to Automator users, or access it through Appleâs Scripting Bridge, or through open source bridge technologies, using languages such as Objective-C, Ruby, and Python.For information on these technologies, seeScriptable Applications,Scripting Bridge, andAutomatorin this document and the related learning paths inGetting Started With Scripting & AutomationandGetting Started with AppleScript.âFramework and Language Support,â inAbout Apple EventsinApple Events Programming Guide, describes trade-offs involved in developing scriptable applications in procedural and object-oriented languages, and in using support provided by the Carbon APIs or the Cocoa application framework.
Youâre creating or updating an application for OS X and you want it to be scriptable. As a scriptable application, users can invoke it in their AppleScript scripts and you can write scripts to perform automated testing during development. You can also make the application accessible to Automator users, or access it through Appleâs Scripting Bridge, or through open source bridge technologies, using languages such as Objective-C, Ruby, and Python.
For information on these technologies, seeScriptable Applications,Scripting Bridge, andAutomatorin this document and the related learning paths inGetting Started With Scripting & AutomationandGetting Started with AppleScript.
âFramework and Language Support,â inAbout Apple EventsinApple Events Programming Guide, describes trade-offs involved in developing scriptable applications in procedural and object-oriented languages, and in using support provided by the Carbon APIs or the Cocoa application framework.
- Youâre interested in automating repetitive operations, whether in development or in other work, using scripts orAutomatorworkflows.For information on working with scripts, seeScripting with AppleScriptin this document, as well the learning paths inGetting Started with AppleScript.To learn about applications and technologies that extend AppleScript and help it work with graphic images, XML, property lists, databases, and other technologies, seeAppleScript Utilities and Applications.
Youâre interested in automating repetitive operations, whether in development or in other work, using scripts orAutomatorworkflows.
For information on working with scripts, seeScripting with AppleScriptin this document, as well the learning paths inGetting Started with AppleScript.
To learn about applications and technologies that extend AppleScript and help it work with graphic images, XML, property lists, databases, and other technologies, seeAppleScript Utilities and Applications.
## Limitations of AppleScript
The AppleScript scripting language excels in its ability to call on multiple applications, but was not designed to perform task-specific functions itself. So, for example, you cannot use AppleScript to efficiently perform intensive math operations or lengthy text processing. However, you can use AppleScript in combination with shell scripts, Perl scripts, and other scripting languages. This allows you to work with the most efficient language for the task at hand. For related information, seeUsing AppleScript with Other Scripting Systems.
AppleScript relies on developers to build scriptability into their applications. However, a mechanism called GUI scripting, introduced with OS X version 10.3, does allow some scripting of applications that do not contain code for responding to Apple events. For more information, seeSystem Events and GUI Scripting.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# AppleScript Utilities and Applications
Apple provides a number of utilities and applications in OS X to enhance the features of AppleScript and your scripts. You can get additional information on some items described in this section by searching in Mac Help in the Finder or by going to theAppleScriptwebsite.
## AppleScript Utility
AppleScript Utility, located in/Applications/AppleScript, is an application that first became available in OS X version 10.4. Starting in OS X version 10.5, this utility is itself scriptable.
AppleScript Utility helps you manage several AppleScript-related features in OS X that were formerly available separately. For example, AppleScript Utility provides an interface to:
- Select a default script editor (to be launched when you double-click a script file.
Select a default script editor (to be launched when you double-click a script file.
- Enable or disable GUI scripting (described inSystem Events and GUI Scripting).Prior to OS X v10.4, GUI scripting was enabled through the âEnable access for assistive devicesâ checkbox in the Universal Access preference pane in System Preferences.
Enable or disable GUI scripting (described inSystem Events and GUI Scripting).
Prior to OS X v10.4, GUI scripting was enabled through the âEnable access for assistive devicesâ checkbox in the Universal Access preference pane in System Preferences.
- Launch the Folder Actions Setup application (described inFolder Actions Setup).
Launch the Folder Actions Setup application (described inFolder Actions Setup).
- Specify settings for the Script menu.The Script menu provides access to scripts for performing tasks such as the following:Opening AppleScript related folders.Working with Apple applications such as Address Book, Mail, and Script Editor.Working with parts of the OS, such as ColorSync, Finder, and Folder Actions.Working with features such as internet services, printing, and URLs.In OS X version 10.3, you install and remove the Script menu with utility applications located in/Applications/AppleScript.
Specify settings for the Script menu.
The Script menu provides access to scripts for performing tasks such as the following:
- Opening AppleScript related folders.
Opening AppleScript related folders.
- Working with Apple applications such as Address Book, Mail, and Script Editor.
Working with Apple applications such as Address Book, Mail, and Script Editor.
- Working with parts of the OS, such as ColorSync, Finder, and Folder Actions.
Working with parts of the OS, such as ColorSync, Finder, and Folder Actions.
- Working with features such as internet services, printing, and URLs.
Working with features such as internet services, printing, and URLs.
In OS X version 10.3, you install and remove the Script menu with utility applications located in/Applications/AppleScript.
## Folder Actions Setup
Folder Actions is a feature that lets you associate scripts with folders. A script is executed when the folder to which it is attached is opened or closed, moved or resized, or has items added or removed.
Folder Actions Setup, located in/Applications/AppleScript, is an application that first became available in OS X version 10.3. Starting in OS X version 10.5, Folder Actions Setup is itself scriptable.
This utility helps you perform tasks related to Folder Actions, including the following:
- Enable or disable Folder Actions.
Enable or disable Folder Actions.
- View the folders that currently have scripts attached and view the attached scripts.
View the folders that currently have scripts attached and view the attached scripts.
- Add folders to or remove folders from the list of folders.
Add folders to or remove folders from the list of folders.
- Attach one or more scripts to a folder.
Attach one or more scripts to a folder.
- Remove attached scripts from a folder.
Remove attached scripts from a folder.
- Enable or disable scripts attached to a folder.
Enable or disable scripts attached to a folder.
## System Events and GUI Scripting
System Events is an agent (or faceless background application) that supplies the terminology for using a number of features in AppleScript scripts. Among these features is GUI scripting, which allows your scripts to perform some actions in applications that have no built-in scripting support. System Events, which is located in/System/Library/CoreServices, has been part of OS X since version 10.1 (Puma), though its features have evolved since that release.
The following are some of the terminology suites supplied by System Events in OS X version 10.4 (and where noted, in version 10.5). For more information, display the application dictionary, as described inDisplaying Scripting Dictionaries. You can also get information on many of the features supported by System Events in Mac Help (from the Help menu in OS X) and at the AppleScriptGUI Scriptingweb page at theAppleScript in OS Xwebsite.
- Accounts suite and Login Items suiteSystem Events supports scripting of the System Preferences Accounts pane through the terminology in these two suites.
Accounts suite and Login Items suite
System Events supports scripting of the System Preferences Accounts pane through the terminology in these two suites.
- Audio File suite and Movie File suiteAvailable starting in OS X version 10.5, these suites provide terminology for accessing audio files and movie files, and the data they contain.
Audio File suite and Movie File suite
Available starting in OS X version 10.5, these suites provide terminology for accessing audio files and movie files, and the data they contain.
- Desktop suiteAvailable starting in OS X version 10.5, this suite provides access to Desktop preferences, such as the current desktop picture or pictures folder, and the interval for changing the desktop picture.
Desktop suite
Available starting in OS X version 10.5, this suite provides access to Desktop preferences, such as the current desktop picture or pictures folder, and the interval for changing the desktop picture.
- Disk-Folder-File suiteProvides terminology to access disks, files, and folders without targeting the Finder. This can be more efficient than using the Finder, and can prevent certain kinds of conflicts.
Disk-Folder-File suite
Provides terminology to access disks, files, and folders without targeting the Finder. This can be more efficient than using the Finder, and can prevent certain kinds of conflicts.
- Dock Preferences suite and Expose Preferences suiteAvailable starting in OS X version 10.5, these suites provide terminology for accessing Dock preferences, as well as Exposé (including Spaces) and Dashboard mouse and key preferences.
Dock Preferences suite and Expose Preferences suite
Available starting in OS X version 10.5, these suites provide terminology for accessing Dock preferences, as well as Exposé (including Spaces) and Dashboard mouse and key preferences.
- Folder Actions suiteStarting with AppleScript 1.9.0 in Mac OS version 10.2, System Events supports the Folder Actions feature, described inFolder Actions Setup.
Folder Actions suite
Starting with AppleScript 1.9.0 in Mac OS version 10.2, System Events supports the Folder Actions feature, described inFolder Actions Setup.
- Network Preferences suiteAvailable starting in OS X version 10.5, this suite provides terminology for working with items such as connections and disconnections, network locations, and network services.
Network Preferences suite
Available starting in OS X version 10.5, this suite provides terminology for working with items such as connections and disconnections, network locations, and network services.
- Power suiteProvides commands for sleeping, logging out, shutting down, or restarting your computer.
Power suite
Provides commands for sleeping, logging out, shutting down, or restarting your computer.
- Property List suiteProvides terminology for reading and writing the information in property list files.
Property List suite
Provides terminology for reading and writing the information in property list files.
- Processes suiteProvides classes and commands for GUI Scripting, a feature available starting in OS X version 10.3 that allows scripters to control applications that are either not scriptable or only partially scriptable. With GUI Scripting, AppleScript scripts can select menu items, push buttons, and perform other tasks to control the interfaces of most non-Classic applications. However, as the name implies, GUI scripting works by scripting the user interface, and so tends to result in fragile scripts. For example, items in an applicationâs user interface may change in various ways between releases, or even between launches of the application, depending on preference settings and other factors.This suite is called the Processes suite because in GUI scripting, the root for any script must be a process (represented by an instance of theapplication process class). The GUI Scripting architecture is based on the accessibility support in OS X, which must be enabled, in OS X v10.4, through the AppleScript Utility. Prior to OS X v10.4, GUI scripting was enabled through the âEnable access for assistive devicesâ checkbox in the Universal Access preference pane in System Preferences.For more information, see theGUI Scriptingweb page.
Processes suite
Provides classes and commands for GUI Scripting, a feature available starting in OS X version 10.3 that allows scripters to control applications that are either not scriptable or only partially scriptable. With GUI Scripting, AppleScript scripts can select menu items, push buttons, and perform other tasks to control the interfaces of most non-Classic applications. However, as the name implies, GUI scripting works by scripting the user interface, and so tends to result in fragile scripts. For example, items in an applicationâs user interface may change in various ways between releases, or even between launches of the application, depending on preference settings and other factors.
This suite is called the Processes suite because in GUI scripting, the root for any script must be a process (represented by an instance of theapplication process class). The GUI Scripting architecture is based on the accessibility support in OS X, which must be enabled, in OS X v10.4, through the AppleScript Utility. Prior to OS X v10.4, GUI scripting was enabled through the âEnable access for assistive devicesâ checkbox in the Universal Access preference pane in System Preferences.
For more information, see theGUI Scriptingweb page.
- QuickTime File suiteAvailable starting in OS X version 10.5, this suite provides terminology for working with QuickTime files, including data, annotations, and tracks.
QuickTime File suite
Available starting in OS X version 10.5, this suite provides terminology for working with QuickTime files, including data, annotations, and tracks.
- Security suiteAvailable starting in OS X version 10.5, this suite provides access to Security preferences, such as automatic login and password requirements.
Security suite
Available starting in OS X version 10.5, this suite provides access to Security preferences, such as automatic login and password requirements.
- System Events suiteThis suite provides a great deal of terminology for working with parts of the OS. That includes properties for accessing certain folders (preferences folder, favorites folder, desktop pictures folder, and so on), the startup disk, and other useful items.
System Events suite
This suite provides a great deal of terminology for working with parts of the OS. That includes properties for accessing certain folders (preferences folder, favorites folder, desktop pictures folder, and so on), the startup disk, and other useful items.
- XML suiteProvides terminology for working with information in XML files.
XML suite
Provides terminology for working with information in XML files.
## Image Events
Like System Events, Image Events is an agent (or faceless background application) that is located in/System/Library/CoreServices. Image Events supports the manipulation, from scripts, of images and image-related data through operations such as cropping, embedding, matching, padding, profiling, rotating, and scaling. These operations are typically used in print, web, and media publishing.
Image Events has been part of OS X since version 10.4 and provides access to the built-in service called SIPS (Scriptable Image Processing Server) that became available in that OS release.
You can find more information on Image Events in Mac Help (from the OS X Help menu) or at theImage Eventsweb page. You can also examine the Image Events dictionary with Script Editor, as described inDisplaying Scripting Dictionaries. SIPS is described inTechnical Note TN2035 ColorSync on OS X. You can also get some information about SIPS by typingsips --helpin a Terminal window.
## Database Events
Database Events is a simple, scratchpad database implementation for use in AppleScript scripts. It allows any script applet to create and edit its own database.
You can use Database Events to create a new database with a file associated with it or to open a database file to access its database. Databases contain records, records contain fields, and fields contain a name and a value. The assignment of names and values is free form, as the scripter defines it. Databases persist in the file system, across executions of Database Events.
Database Events has been part of OS X since version 10.4. Like System Events, Database Events is an agent (or faceless background application) that is located in/System/Library/CoreServices.
You can examine the Database Events dictionary with Script Editor, as described inDisplaying Scripting Dictionaries.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Default Coercion Handlers
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This appendix lists the type conversions performed by the default coercion handlers provided by the Mac OS. These handlers may be implemented by the Apple Event Manager, the Open Scripting framework, or other frameworks.
Support for the following coercions was added in Mac OS X version 10.4:
- Between these types:typeStyledText,typeUnicodeText,typeUTF8Text, andtypeUTF16ExternalRepresentationand these types:typeType,typeEnumerated, and the numeric typestypeSInt16,typeSInt32,typeUInt32,typeSInt64,typeIEEE32BitFloatingPoint,typeIEEE64BitFloatingPoint, andtypeExtended.Important:See the description for thetypePixelMapenum inApple Event Manager Referencefor important information about restrictions on coercions involving typeStyledText.See tableTable C-1for a mapping between the preferred and non-preferred numeric constant names.
Between these types:
typeStyledText,typeUnicodeText,typeUTF8Text, andtypeUTF16ExternalRepresentation
and these types:
typeType,typeEnumerated, and the numeric typestypeSInt16,typeSInt32,typeUInt32,typeSInt64,typeIEEE32BitFloatingPoint,typeIEEE64BitFloatingPoint, andtypeExtended.
Important:See the description for thetypePixelMapenum inApple Event Manager Referencefor important information about restrictions on coercions involving typeStyledText.
See tableTable C-1for a mapping between the preferred and non-preferred numeric constant names.
- FromtypeChartotypeStyledText.Note:Starting in Mac OS X version 10.3,typeCharis deprecated in favor of one of the Unicode string types. For details, see the descriptions fortypeCharand for the Unicode string types (typeUnicodeText) inApple Event Manager Reference.
FromtypeChartotypeStyledText.
Note:Starting in Mac OS X version 10.3,typeCharis deprecated in favor of one of the Unicode string types. For details, see the descriptions fortypeCharand for the Unicode string types (typeUnicodeText) inApple Event Manager Reference.
## Coercion Handler Tables
Table C-1shows some older, non-preferred numeric constant names and their preferred equivalents. To find available coercions for a non-preferred name fromTable C-1, look up its equivalent preferred name inTable C-2.
Non-preferred numeric constant name
Preferred numeric constant name
typeSMInt,typeShortInteger
typeSInt16
typeInteger,typeLongInteger
typeSInt32
typeMagnitude
typeUInt32
typeComp
typeSInt64
typeSMFloat,typeShortFloat
typeIEEE32BitFloatingPoint
typeFloat,typeLongFloat
typeIEEE64BitFloatingPoint
Table C-2lists the default coercions handled by the Apple Event Manager.
Coerce from descriptor type
To descriptor type
Comment
typeChar
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
typeSInt16
typeSInt32
typeSInt64
typeIEEE32BitFloatingPoint
typeIEEE64BitFloatingPoint
typeExtended
Any string that is a valid representation of a number can be coerced into an equivalent numeric value.
typeSInt16
typeSInt32
typeSInt64
typeIEEE32BitFloatingPoint
typeIEEE64BitFloatingPoint
typeExtended
typeChar
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
Any numeric descriptor type can be coerced into the equivalent text string.
typeSInt16
typeSInt32
typeSInt64
typeIEEE32BitFloatingPoint
typeIEEE64BitFloatingPoint
typeExtended
typeSInt16
typeSInt32
typeSInt64
typeIEEE32BitFloatingPoint
typeIEEE64BitFloatingPoint
typeExtended
Any numeric descriptor type can be coerced into any other numeric descriptor type.
typeChar
typeIntlText
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
typeChar
typeIntlText
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
If the destination encoding cannot represent a character in the source text, the result is undefined.
typeChar
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
typeType
typeEnumerated
typeKeyword
typeProperty
Any four-character string can be coerced to one of these descriptor types.
typeEnumerated
typeKeyword
typeProperty
typeType
typeChar
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
Any of these descriptor types can be coerced to the equivalent text string.
typeIntlText
typeChar
typeStyledText
typeUnicodeText
typeUTF8Text
typeUTF16ExternalRepresentation
The result contains text only, without the script code or language code from the original descriptor.
typeTrue
typeBoolean
The result is the Boolean valuetrue.
typeFalse
typeBoolean
The result is the Boolean valuefalse.
typeEnumerated
typeBoolean
The enumerated value'true'becomes the Boolean value true. The enumerated value'fals'becomes the Boolean value false.
typeBoolean
typeEnumerated
The Boolean valuefalsebecomes the enumerated value'fals'. The Boolean valuetruebecomes the enumerated value'true'.
typeSInt16
typeBoolean
A value of 1 becomes the Boolean valuetrue. A value of 0 becomes the Boolean valuefalse.
typeBoolean
typeSInt16
A value offalsebecomes 0. A value oftruebecomes 1.
typeAlias
typeFSS
An alias is coerced into a file system specification. Not recommendedâusetypeFSRefinstead.
typeAlias
typeFSRef
An alias is coerced into a file system reference.
typeAppleEvent
typeAppParameters
An Apple event is coerced into a list of application parameters for theLaunchParamBlockRecparameter block.
any descriptor type
typeAEList
A descriptor is coerced into a descriptor list containing a single item.
typeAEList
type of list item
A descriptor list containing a single descriptor is coerced into a descriptor.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Introduction to Apple Events Programming Guide
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Apple Events Programming Guideprovides conceptual information and programming examples for working with Apple events.
AnApple eventis a type of interprocess message that can specify complex operations and data. Apple events allow you to gather all the data necessary to accomplish a high level task into a single package that can be passed across process boundaries, evaluated, and returned with results. The Mac OS uses Apple events to communicate with applications. Apple events are also an essential part of the AppleScript scripting system, which allows users to automate actions usingscriptable applicationsâapplications that can respond to a variety of Apple events by performing operations or supplying data.
Note:Mac OS X offers other mechanisms for communicating between processes. These mechanisms are described in âIPC and Notification Mechanismsâ in "Darwin and Core Technologiesâ inMac Technology Overview.
Apple Events Programming Guideassumes that you are familiar with the information inAppleScript Overview.
The information in this document applies primarily to Carbon applications. While Cocoa applications can take advantage of most of the described features, in many cases they wonât need to. For more information, seeFramework and Language Support.
## Who Should Read This Document
You should read this document if you want to:
- Make your Carbon application respond to the Apple events sent by the Mac OS (for launching and quitting applications, opening documents, and so on).
Make your Carbon application respond to the Apple events sent by the Mac OS (for launching and quitting applications, opening documents, and so on).
- Work with Apple events as part of writing a scriptable Carbon application.
Work with Apple events as part of writing a scriptable Carbon application.
- Use Apple events to communicate with other applications.
Use Apple events to communicate with other applications.
- Gain background information about Apple events for your work with scriptable Cocoa applications, AppleScript Studio applications, Automator workflows, or AppleScript scripts.
Gain background information about Apple events for your work with scriptable Cocoa applications, AppleScript Studio applications, Automator workflows, or AppleScript scripts.
Important:An Apple event can contain object specifiers that identify objects within the application that receives the event. Object specifiers are mentioned only briefly in this document. For information on how to work with object specifiers, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
Do not rely on the API descriptions inInterapplication CommunicationâOpen Scripting Architecture ReferenceandApple Event Manager Referenceprovide the current API documentation.
## Organization of This Document
This document is organized into the following chapters:
- About Apple Eventsdefines Apple events, explains when theyâre useful, and provides a quick overview of common tasks for working with them. It also provides a brief description of the framework and language support available in Mac OS X and provides links to additional information inApple Events Programming Guideand in other documents.
About Apple Eventsdefines Apple events, explains when theyâre useful, and provides a quick overview of common tasks for working with them. It also provides a brief description of the framework and language support available in Mac OS X and provides links to additional information inApple Events Programming Guideand in other documents.
- Building an Apple Eventprovides an overview of Apple event data structures and describes how to build an Apple event.
Building an Apple Eventprovides an overview of Apple event data structures and describes how to build an Apple event.
- Apple Event Dispatchingshows how your application works with the Apple Event Manager to register the Apple events it can handle and dispatch those events to the code that should handle them.
Apple Event Dispatchingshows how your application works with the Apple Event Manager to register the Apple events it can handle and dispatch those events to the code that should handle them.
- Working With the Data in an Apple Eventdescribes how to extract data from Apple events and the data structures that comprise them.
Working With the Data in an Apple Eventdescribes how to extract data from Apple events and the data structures that comprise them.
- Responding to Apple Eventsdescribes how to respond to an Apple event by examining the event, performing the requested action, interacting with the user (if necessary), and returning a reply event. It also provides an overview of how to respond to Apple events sent by the Mac OS.
Responding to Apple Eventsdescribes how to respond to an Apple event by examining the event, performing the requested action, interacting with the user (if necessary), and returning a reply event. It also provides an overview of how to respond to Apple events sent by the Mac OS.
- Creating and Sending Apple Eventsprovides information and sample code that will help you create and send Apple events and respond to reply Apple events.
Creating and Sending Apple Eventsprovides information and sample code that will help you create and send Apple events and respond to reply Apple events.
- Writing and Installing Coercion Handlersdescribes how to write coercion handlers that convert between various types of data and how to install them so that they are available to your application.
Writing and Installing Coercion Handlersdescribes how to write coercion handlers that convert between various types of data and how to install them so that they are available to your application.
- Testing and Debugging Apple Event Codeprovides tips for displaying and debugging Apple events in your application.
Testing and Debugging Apple Event Codeprovides tips for displaying and debugging Apple events in your application.
- Selected Apple Event Manager Functionsprovides information about some commonly used functions.
Selected Apple Event Manager Functionsprovides information about some commonly used functions.
- Selected Apple Event Constantsprovides information about some commonly used constants.
Selected Apple Event Constantsprovides information about some commonly used constants.
- Default Coercion Handlerslists the type conversions performed by the default coercion handlers provided by the Mac OS.
Default Coercion Handlerslists the type conversions performed by the default coercion handlers provided by the Mac OS.
## See Also
The following documents provide related information.
- AppleScript Overviewprovides information that is useful for working with AppleScript and Apple events, including a description of the Open Scripting Architecture, on which both rely.
AppleScript Overviewprovides information that is useful for working with AppleScript and Apple events, including a description of the Open Scripting Architecture, on which both rely.
- Apple Event Manager Referencedescribes the API for sending and receiving Apple events and working with the information they contain.
Apple Event Manager Referencedescribes the API for sending and receiving Apple events and working with the information they contain.
- Technical Note TN2106,Scripting Interface Guidelines, describes how to design the scripting interface for a scriptable application.
Technical Note TN2106,Scripting Interface Guidelines, describes how to design the scripting interface for a scriptable application.
- AppleScript Language Guidedescribes the features and terminology of the AppleScript scripting language.
AppleScript Language Guidedescribes the features and terminology of the AppleScript scripting language.
- For information on sending Apple events to web services, seeXML-RPC and SOAP Programming Guide.
For information on sending Apple events to web services, seeXML-RPC and SOAP Programming Guide.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Responding to Apple Events
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Your application must be able to respond to certain Apple events sent by the Mac OS, such as theopen applicationandquitevents. If your application has defined additional Apple events that it supports, either to supply services to other applications or to make itself scriptable, it must be ready to respond to those events as well.
This chapter describes how you write handlers to respond to the Apple events your application receives. It also provides an overview of how Carbon applications work with Apple events sent by the Mac OS.
## About Apple Event Handlers
To respond to Apple events, your application registers handler functions with the Apple Event Manager for the events it can handle, as described inApple Event Dispatching. Your application will only receive Apple events that target itâthat is, events that specify your application in their target address descriptor. These include the events described inHandling Apple Events Sent by the Mac OS. Should your application receive an Apple event it is not expecting, the Apple Event Manager will not find it in your dispatch table, so the event will not be dispatched to one of your handlers, unless you have installed a wildcard handler.
Note:One exception is the case where an event handler is installed automatically for your application. For example,Processing Apple Events With the Carbon Event Modeldescribes a case in which a systemquitevent handler is installed automatically.
As a result, your event handlers should generally be called only for events they understand. If a problem occurs, it is most commonly due to an error in constructing the event that was sent to your application. Because of this possibility, you may want to test the error handling in your Apple event code by intentionally sending your application Apple events containing unexpected information.
### Definition of an Apple Event Handler
When you declare an Apple event handler, the syntax must match theAEEventHandlerProcPtrdata type, which is described in detail inApple Event Manager Reference.Listing 5-1shows the declaration for a function that handles theopen documentsApple eventâall your handler declarations use a similar declaration.
Listing 5-1Definition for an Apple event handler
```applescript
static pascal OSErr HandleOpenDocAE (// 1
```
```applescript
const AppleEvent * theAppleEvent,// 2
```
```applescript
AppleEvent * reply,// 3
```
```applescript
SInt32 handlerRefcon);// 4
```
Hereâs a description of this function declaration:
- Thepascalkeyword ensures proper ordering of parameters on the stack.
Thepascalkeyword ensures proper ordering of parameters on the stack.
- The Apple event for the function to handle. Youâll often extract information from it to help you process the Apple event.
The Apple event for the function to handle. Youâll often extract information from it to help you process the Apple event.
- The default reply (provided by the Apple Event Manager). It contains no parameters. If no reply is requested, the reply event is a null descriptor.
The default reply (provided by the Apple Event Manager). It contains no parameters. If no reply is requested, the reply event is a null descriptor.
- The 32-bit reference constant you supplied for the handler when you first registered it by callingAEInstallEventHandler. You can use the reference constant to provide information about the Apple event, or for any other purpose you want.For example, you can install, for multiple Apple events, dispatch table entries that specify the same handler but different reference constants. Your handler can then use the reference constant to distinguish between the different Apple events it receives.
The 32-bit reference constant you supplied for the handler when you first registered it by callingAEInstallEventHandler. You can use the reference constant to provide information about the Apple event, or for any other purpose you want.
For example, you can install, for multiple Apple events, dispatch table entries that specify the same handler but different reference constants. Your handler can then use the reference constant to distinguish between the different Apple events it receives.
### Interacting With the User
When your application handles an Apple event, it may need to interact with the user. For example, your handler for theprint documentsevent may need to display a print dialog before printing. Your application should not just assume it is okay to interact with the user in response to an Apple event. It should always call theAEInteractWithUserfunction to make sure it is in the foreground before it interacts with the user.
IfAEInteractWithUserreturns the valuenoErr, then your application is currently in front and is free to interact with the user. IfAEInteractWithUserreturns the valueerrAENoUserInteraction, your application should not attempt to interact with the user.
You can specify flags to theAESetInteractionAllowedfunction to allow the following types of interaction with your application:
- Only when your application is sending an Apple event to itself.
Only when your application is sending an Apple event to itself.
- Only when the client application is on the same computer as your application.
Only when the client application is on the same computer as your application.
- For any event sent by any client application on any computer.
For any event sent by any client application on any computer.
Both client and server applications specify their preferences for user interaction: the client specifies whether the server should be allowed to interact with the user, and the server (your application) specifies when it allows user interaction while processing an Apple event. For interaction to take place, these two conditions must be met:
- The client application must set flags in thesendModeparameter of theAESendfunction indicating that user interaction is allowed.
The client application must set flags in thesendModeparameter of theAESendfunction indicating that user interaction is allowed.
- The server application must either set no user interaction preferences, in which case it is assumed that only interaction with a client on the local computer is allowed; or it must use theAESetInteractionAllowedfunction to indicate that user interaction is allowed.
The server application must either set no user interaction preferences, in which case it is assumed that only interaction with a client on the local computer is allowed; or it must use theAESetInteractionAllowedfunction to indicate that user interaction is allowed.
If these two conditions are met and ifAEInteractWithUserdetermines that both the client and server applications allow user interaction under the current circumstances,AEInteractWithUserbrings your application to the foreground if it isnât already in the foreground. Your application can then display a dialog or otherwise interact with the user. TheAEInteractWithUserfunction brings your server application to the front either directly or after the user responds to a notification request.
Important:CallingAEInteractWithUserensures that your application will get correct notification in terms of being activated. There is no guarantee that other applications are setting an interaction level, but if they are, your application can respect it.
Interaction is not currently guaranteed to work correctly in the context of fast user switching. For example, your application could ask the user whether it should present UI, but the user might never respond because your application has been switched out.
To track when your Carbon or Cocoa application has been switched in or out, you can sign up for notification of thekEventSystemUserSessionActivatedandkEventSystemUserSessionDeactivatedevents, as described inUser Switch NotificationsinMultiple User Environment Programming Topics.
To determine whether your application is currently running in the active user session, you can use theCGSessionCopyCurrentDictionaryfunction, together with thekCGSessionOnConsoleKey, as described inSupporting Fast User SwitchinginMultiple User Environment Programming Topics.
For more information on working with user interaction, seeSpecifying Send and Reply Optionsin this document, as well as the following inApple Event Manager Reference:
- The section "User Interaction Level Constants.â
The section "User Interaction Level Constants.â
- The constants listed under âAESendMode.â
The constants listed under âAESendMode.â
- The functionsAEInteractWithUser,AESetInteractionAllowed,AEGetInteractionAllowed, andAESend.
The functionsAEInteractWithUser,AESetInteractionAllowed,AEGetInteractionAllowed, andAESend.
## Writing an Apple Event Handler
Your Apple event handler typically performs the following operations:
- It extracts information from the received Apple event.
It extracts information from the received Apple event.
- It performs any requested actions, checking that interaction is allowed before attempting to interact with a user.
It performs any requested actions, checking that interaction is allowed before attempting to interact with a user.
- It adds information to the reply Apple event if appropriate.
It adds information to the reply Apple event if appropriate.
- It returns a result code. If an error occurs in extracting information from the event or if an error occurs in any other operation:It may add error information to the reply Apple event.It returns an appropriate error code.
It returns a result code. If an error occurs in extracting information from the event or if an error occurs in any other operation:
- It may add error information to the reply Apple event.
It may add error information to the reply Apple event.
- It returns an appropriate error code.
It returns an appropriate error code.
### Extracting Information From the Apple Event
For nearly all standard Apple events, your handler extracts data from the event to help determine how to process the event. The following are some kinds of information you are likely to extract:
- The event class and/or the event ID. For example, if you registered your handler with one or more wildcards, you may need to get the event class or event ID to determine which kind of event you actually received. You can obtain this information by calling a function such asAEGetAttributePtr, and passingkeyEventClassAttrorkeyEventIDAttrfor the parameter that specifies the keyword of the attribute to access.
The event class and/or the event ID. For example, if you registered your handler with one or more wildcards, you may need to get the event class or event ID to determine which kind of event you actually received. You can obtain this information by calling a function such asAEGetAttributePtr, and passingkeyEventClassAttrorkeyEventIDAttrfor the parameter that specifies the keyword of the attribute to access.
- The direct parameter, which usually specifies the data to be acted upon.Listing 4-5shows how to get a parameter that contains a list of files from anopen documentsApple event.
The direct parameter, which usually specifies the data to be acted upon.Listing 4-5shows how to get a parameter that contains a list of files from anopen documentsApple event.
- Additional parameters. These can be any kind of data stored in an Apple event. They might include object specifiers, which identify objects within your application on which the Apple event operates. For information on how to work with object specifiers, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
Additional parameters. These can be any kind of data stored in an Apple event. They might include object specifiers, which identify objects within your application on which the Apple event operates. For information on how to work with object specifiers, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
Working With the Data in an Apple Eventprovides additional information and examples of how you extract data from an Apple event.
### Performing the Requested Action
When your application responds to an Apple event, it should perform the standard action requested by that event. For example, your application should respond to theprint documentsevent by printing the specified documents.
Many Apple events can ask your application to return data. For instance, if your application is a spelling checker, the client application might expect your application to return data in the form of a list of misspelled words.
### Adding Information to a Reply Apple Event
If the application that sent the Apple event requested a reply, the Apple Event Manager passes a default reply Apple event to your handler. The reply event has event classkCoreEventClassand event IDkAEAnswer. If the client application does not request a reply, the Apple Event Manager passes a null descriptor insteadâthat is, a descriptor of typetypeNullwhose data handle has the valueNULL.
The default reply Apple event has no parameters, but your handler can add parameters or attributes to it. If your application is a spelling checker, for example, you can return a list of misspelled words in a parameter. However, your handler should check whether the reply Apple event exists before attempting to add to it. Attempting to add to a null descriptor generates an error.
Your handler may need to add error information to the reply event, as described in subsequent sections.
### Returning a Result Code
When your handler finishes processing an Apple event, it should dispose of any Apple event descriptors or other data it has acquired. It should then return a result code to the Apple Event Manager. Your handler should returnnoErrif it successfully handles the Apple event or a nonzero result code if an error occurs.
If an error occurs because your application cannot understand the event, it should returnerrAEEventNotHandled. This allows the Apple Event Manager to look for a handler in the system dispatch table that might be able to handle the event. If the error occurs because the event is impossible to handle as specified, return the result code returned by whatever function caused the failure, or whatever other result code is appropriate.
For example, suppose your application receives aget dataevent requesting the name of the current printer, but it cannot handle such an event. In this situation, you can returnerrAEEventNotHandledin case another available handler can handle theget dataevent. However, this strategy is only useful if your application has installed such a system handler, or the event is one of the few for which a system handler may be installed automatically. (For information on handlers that are installed automatically, seeHandling Apple Events Sent by the Mac OS.)
However, if your application cannot handle aget dataevent that requests the fifth paragraph in a document because the document contains only four paragraphs, you should return some other nonzero error, because further attempts to handle the event are pointless.
In addition to returning a result code, your handler can also return an error string by adding akeyErrorStringparameter to the reply Apple event. The client can use this string in an error message to the user. For more information, seeReturning Error Information.
For scriptable applications, the client is often the Script Editor, or some other application, executing a script. When you return an error code that the Apple Event Manager understands, the Script Editor automatically displays an appropriate error message to the user. You can find tables of error codes documented inApple Event Manager ReferenceandOpen Scripting Architecture Reference.
### Returning Error Information
If your handler returns a nonzero result code, the Apple Event Manager adds akeyErrorNumberparameter to the reply Apple event (unless you have already added akeyErrorNumberparameter). This parameter contains the result code that your handler returns. This can be useful because it associates the error number directly with the return event, which the client application may pass around without the result code.
Rather than just returning an error code, your handler itself can add error information to the reply Apple event. It can add both an error number and an error string. As noted previously, in many cases returning an Apple Event Manager error code will result in an appropriate error message. You should only add your own error text in cases where you can provide information the Apple Event Manager cannot, such as information specific to the operation of your application.
Note:Handlers can return several additional types of error information. For details, see theOSAScriptErrorfunction and the constant section âOSAScriptError Selectorsâ inOpen Scripting Architecture Reference.
To directly add an error number parameter to a reply Apple event, your handler can call a function like the one inListing 5-2.
Listing 5-2A function to add an error number to a reply Apple event
```applescript
static void AddErrNumberToEvent(OSStatus err, AppleEvent* reply)// 1
```
```applescript
{
```
```applescript
OSStatus returnVal = errAEEventFailed;// 2
```
```applescript
```
```applescript
if (reply->descriptorType != typeNull)// 3
```
```applescript
{
```
```applescript
returnVal = AESizeOfParam(reply, keyErrorNumber, NULL, NULL);
```
```applescript
if (returnVal != noErr))// 4
```
```applescript
{
```
```applescript
AEPutParamPtr(reply, keyErrorNumber,
```
```applescript
typeSInt32, &err, sizeof(err));// 5
```
```applescript
}
```
```applescript
}
```
```applescript
return returnVal;
```
```applescript
}
```
Hereâs a description of how this function works:
- It receives an error number and a pointer to the reply Apple event to modify.
It receives an error number and a pointer to the reply Apple event to modify.
- It declares a variable for the return value and sets it to the Apple Event Manager error constant for âApple event handler failed.â If the function is successful, this value is changed.
It declares a variable for the return value and sets it to the Apple Event Manager error constant for âApple event handler failed.â If the function is successful, this value is changed.
- It checks the descriptor type of the reply Apple event to make sure it is not a null event.
It checks the descriptor type of the reply Apple event to make sure it is not a null event.
- It verifies that the event doesnât already contain an error number parameter (AESizeOfParamreturns an error if it doesnât find the parameter).
It verifies that the event doesnât already contain an error number parameter (AESizeOfParamreturns an error if it doesnât find the parameter).
- It callsAEPutParamPtrto add an error number parameter to the reply event:keyErrorNumberspecifies the keyword for the added parameter.typeSInt32specifies the descriptor type for the added parameter.errspecifies the error number to store in the added parameter.
It callsAEPutParamPtrto add an error number parameter to the reply event:
- keyErrorNumberspecifies the keyword for the added parameter.
keyErrorNumberspecifies the keyword for the added parameter.
- typeSInt32specifies the descriptor type for the added parameter.
typeSInt32specifies the descriptor type for the added parameter.
- errspecifies the error number to store in the added parameter.
errspecifies the error number to store in the added parameter.
In addition to returning a result code, your handler can return an error string in thekeyErrorStringparameter of the reply Apple event. Your handler should provide meaningful text in thekeyErrorStringparameter, so that the client can display this string to the user if desired.
Listing 5-3shows a function that adds a parameter, from a string reference that refers to Unicode text, to a passed descriptor. You pass the desired keyword to identify the parameter to add. TheAEPutParamStringfunction callsAEPutParamPtr, which adds a parameter to an Apple event record or an Apple event, so those are the types of descriptors you should pass to it. (Descriptors, Descriptor Lists, and Apple Eventsdescribes the inheritance relationship between common Apple event data types.)
Listing 5-3A function that adds a string parameter to a descriptor
```applescript
OSErr AEPutParamString(AppleEvent *event,
```
```applescript
AEKeyword keyword, CFStringRef stringRef)// 1
```
```applescript
{
```
```applescript
UInt8 *textBuf;
```
```applescript
CFIndex length, maxBytes, actualBytes;
```
```applescript
```
```applescript
length = CFStringGetLength(stringRef);// 2
```
```applescript
```
```applescript
maxBytes = CFStringGetMaximumSizeForEncoding(length,
```
```applescript
kCFStringEncodingUTF8);// 3
```
```applescript
textBuf = malloc(maxBytes);// 4
```
```applescript
if (textBuf)
```
```applescript
{
```
```applescript
CFStringGetBytes(stringRef, CFRangeMake(0, length),
```
```applescript
kCFStringEncodingUTF8, 0, true,
```
```applescript
(UInt8 *) textBuf, maxBytes, &actualBytes);// 5
```
```applescript
```
```applescript
OSErr err = AEPutParamPtr(event, keyword,
```
```applescript
typeUTF8Text, textBuf, actualBytes);// 6
```
```applescript
```
```applescript
free(textBuf);// 7
```
```applescript
return err;
```
```applescript
}
```
```applescript
else
```
```applescript
return memFullErr;
```
```applescript
}
```
Hereâs a description of how this function works:
- It receives a pointer to a descriptor to add a parameter to, a key word to identify the parameter, and a string reference from which to obtain the text for the parameter.
It receives a pointer to a descriptor to add a parameter to, a key word to identify the parameter, and a string reference from which to obtain the text for the parameter.
- It gets the length of the string from the passed reference.
It gets the length of the string from the passed reference.
- It determines the maximum number of bytes needed to store the text, based on its encoding.
It determines the maximum number of bytes needed to store the text, based on its encoding.
- It allocates a buffer of that size.
It allocates a buffer of that size.
- It gets the text from the string reference.
It gets the text from the string reference.
- It adds the text as a parameter to the passed descriptor. (If called with the keywordkeyErrorString, for example, it adds an error string parameter.)
It adds the text as a parameter to the passed descriptor. (If called with the keywordkeyErrorString, for example, it adds an error string parameter.)
- It frees its local buffer.
It frees its local buffer.
Listing 5-4shows how you could callAEPutParamStringto add an error string to a reply Apple event.
Listing 5-4Adding an error string to an Apple event with AEPutParamString
```applescript
CFStringRef errStringRef = getLocalizedErrMsgForErrNumber(err);
```
```applescript
OSErr anErr = AEPutParamString(reply, keyErrorString, errStringRef);
```
Hereâs a description of how this code snippet works:
- It calls an application-defined function to obtain a localized error message as a string reference, based on a passed error number. (For information on localized strings, seeWorking With Localized StringsinBundle Programming Guide.)
It calls an application-defined function to obtain a localized error message as a string reference, based on a passed error number. (For information on localized strings, seeWorking With Localized StringsinBundle Programming Guide.)
- It callsAEPutParamString, passing the event (obtained previously) to add the error text to, the error string keyword, and the string reference for the error message text.
It callsAEPutParamString, passing the event (obtained previously) to add the error text to, the error string keyword, and the string reference for the error message text.
### A Handler for the Open Documents Apple Event
Listing 5-5shows a handler that responds to theopen documentsApple event.
Listing 5-5An Apple event handler for the open documents event
```applescript
static pascal OSErrOpenDocumentsAE(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
```
```applescript
{
```
```applescript
AEDescList docList;
```
```applescript
FSRef theFSRef;
```
```applescript
long index;
```
```applescript
long count = 0;
```
```applescript
OSErr err = AEGetParamDesc(theAppleEvent,
```
```applescript
keyDirectObject, typeAEList, &docList);// 1
```
```applescript
require_noerr(err, CantGetDocList);// 2
```
```applescript
```
```applescript
err = AECountItems(&docList, &count);// 3
```
```applescript
require_noerr(err, CantGetCount);
```
```applescript
```
```applescript
for(index = 1; index <= count; index++)// 4
```
```applescript
{
```
```applescript
err = AEGetNthPtr(&docList, index, typeFSRef,
```
```applescript
NULL, NULL, &theFSRef, sizeof(FSRef), NULL);// 5
```
```applescript
require_noerr(err, CantGetDocDescPtr);
```
```applescript
```
```applescript
err = OpenDocument(&theFSRef);// 6
```
```applescript
}
```
```applescript
AEDisposeDesc(&docList);// 7
```
```applescript
```
```applescript
CantGetDocList:
```
```applescript
CantGetCount:
```
```applescript
CantGetDocDescPtr:
```
```applescript
if (err != noErr)// 8
```
```applescript
{
```
```applescript
// For handlers that expect a reply, add error information here.
```
```applescript
}
```
```applescript
return(err);// 9
```
```applescript
}
```
Hereâs a description of how thisopen documentshandler works:
- It calls an Apple Event Manager function (AEGetParamDesc) to obtain a descriptor list from the direct object of the received Apple event. This is a list of file aliases, one for each document to open.
It calls an Apple Event Manager function (AEGetParamDesc) to obtain a descriptor list from the direct object of the received Apple event. This is a list of file aliases, one for each document to open.
- It uses therequire_noerrmacro (defined inAssertMacros.h) to jump to a labeled location as a simple form of error handling.
It uses therequire_noerrmacro (defined inAssertMacros.h) to jump to a labeled location as a simple form of error handling.
- It calls an Apple Event Manager function (AECountItems) to obtain the number of items in the descriptor list.
It calls an Apple Event Manager function (AECountItems) to obtain the number of items in the descriptor list.
- It sets up a loop over the items in the descriptor list.
It sets up a loop over the items in the descriptor list.
- It calls an Apple Event Manager function (AEGetNthPtr) to get an item from the list, by index, asking for a type oftypeFSRef. This causes the function to coerce the retrieved item (a file alias) to the requested type.
It calls an Apple Event Manager function (AEGetNthPtr) to get an item from the list, by index, asking for a type oftypeFSRef. This causes the function to coerce the retrieved item (a file alias) to the requested type.
- It calls a function you have written (OpenDocument) to open the current document from the list.Aprint documentsevent handler would be very similar to this one, but in this step could call yourPrintDocumentfunction.
It calls a function you have written (OpenDocument) to open the current document from the list.
Aprint documentsevent handler would be very similar to this one, but in this step could call yourPrintDocumentfunction.
- It disposes of the document list descriptor.
It disposes of the document list descriptor.
- Theopen documentsevent sent by the Mac OS doesnât expect a reply, so thereplyparameter is a null event. For event handlers that expect a reply, this is where you can use the techniques described earlier in this chapter to add an error number or an error string. Some examples of events that expect a reply (and thus supply a non-null reply event) includeget dataevents andquitevents.
Theopen documentsevent sent by the Mac OS doesnât expect a reply, so thereplyparameter is a null event. For event handlers that expect a reply, this is where you can use the techniques described earlier in this chapter to add an error number or an error string. Some examples of events that expect a reply (and thus supply a non-null reply event) includeget dataevents andquitevents.
- It returns an error code (noErrif no error has occurred).
It returns an error code (noErrif no error has occurred).
As an alternative to code shown in this handler, you might use an approach that extracts the document list in the event handler, then passes it to a separate function,OpenDocuments, to iterate over the items in the list. This has the advantage that you can also call theOpenDocumentsfunction with the document list obtained fromNavDialogGetReplywhen you are working with Navigation Services. Theselectionfield of the returnedNavReplyRecordis a descriptor list like the one described above.
## Handling Apple Events Sent by the Mac OS
Mac OS X sends Apple events to communicate with applications in certain common situations, such as when launching the application or asking it to open a list of documents. These events are sometimes referred to as the ârequiredâ events, although applications are not required to support all of them. For example, if your application isnât document-based, it wonât support theopen documentsorprint documentsevents. However, any application that presents a graphical user interface through the Human Interface Toolbox or the Cocoa application framework should respond to as many of these events as it makes sense for that application to support.
Carbon applications typically install Apple event handlers to handle these events, though in some cases a default handler may be installed automatically (as described inCommon Apple Events Sent by the Mac OS).
For Cocoa applications, most of the work of responding to events sent by the Mac OS happens automatically, though in some cases applications may want to step in and modify the default behavior. For more details, including some information of general interest, seeHow Cocoa Applications Handle Apple EventsinCocoa Scripting Guide.
### Common Apple Events Sent by the Mac OS
The following are Apple events your application is likely to receive from the Mac OS. For information on the constants associated with these events, seeEvent ID Constants for Apple Events Sent by the Mac OS.
- open application(orlaunch)Received when your application is launched. The application should perform any tasks required when a user launches it without opening or printing any existing documents, though it may of course open a new, untitled document.Starting in Mac OS X version 10.4, anopen applicationApple event may contain information about whether the application was launched as a login item or as a service item. For details on working with this kind of information, see âLaunch Apple Event Constantsâ in âApple Event Manager Constantsâ inApple Event Manager Reference.
open application(orlaunch)
Received when your application is launched. The application should perform any tasks required when a user launches it without opening or printing any existing documents, though it may of course open a new, untitled document.
Starting in Mac OS X version 10.4, anopen applicationApple event may contain information about whether the application was launched as a login item or as a service item. For details on working with this kind of information, see âLaunch Apple Event Constantsâ in âApple Event Manager Constantsâ inApple Event Manager Reference.
- reopen applicationReceived when the application is reopenedâfor example, when the application is open but not frontmost, and the user clicks its icon in the Dock. The application should perform appropriate tasksâfor example, it might create a new document if none is open.
reopen application
Received when the application is reopenedâfor example, when the application is open but not frontmost, and the user clicks its icon in the Dock. The application should perform appropriate tasksâfor example, it might create a new document if none is open.
- open documentsReceived with a list of documents for the application to open.Listing 5-5shows a complete Apple event handler for this event.Starting in Mac OS X version 10.4, theopen documentsApple event may contain an optional parameter identified by the keykeyAESearchText. If present, the parameter contains the search text from the Spotlight search that identified the documents to be opened. The application should make a reasonable effort to display an occurrence of the search text in each opened documentâfor example by scrolling text into view that contains all or part of the search text.
open documents
Received with a list of documents for the application to open.Listing 5-5shows a complete Apple event handler for this event.
Starting in Mac OS X version 10.4, theopen documentsApple event may contain an optional parameter identified by the keykeyAESearchText. If present, the parameter contains the search text from the Spotlight search that identified the documents to be opened. The application should make a reasonable effort to display an occurrence of the search text in each opened documentâfor example by scrolling text into view that contains all or part of the search text.
- print documentsReceived with a list of documents for the application to print. You can obtain file system references to the items in the list using code like that you use when handling anopen documentsevent. SeeInteracting With the Userfor information on when it is appropriate to display a dialog or perform other interaction.Starting in Mac OS X version 10.3, the print documents event was extended to include an optionalprint settingsparameter that defines the settings for the print job or jobs, and an optionalprint dialogparameter that specifies whether the application should display the Print dialog. By default, the application should not show the Print dialog if the caller doesn't specify a print dialog parameter. For details, see Technical Note TN2082,The Enhanced Print Apple Event.
print documents
Received with a list of documents for the application to print. You can obtain file system references to the items in the list using code like that you use when handling anopen documentsevent. SeeInteracting With the Userfor information on when it is appropriate to display a dialog or perform other interaction.
Starting in Mac OS X version 10.3, the print documents event was extended to include an optionalprint settingsparameter that defines the settings for the print job or jobs, and an optionalprint dialogparameter that specifies whether the application should display the Print dialog. By default, the application should not show the Print dialog if the caller doesn't specify a print dialog parameter. For details, see Technical Note TN2082,The Enhanced Print Apple Event.
- open contentsAvailable starting in Mac OS X version 10.4. Received when content, such as text or an image, is dropped on the application iconâfor example, when a dragged image is dropped on the icon in the Dock.The structure of this event is very similar to theopen documentsevent. The direct object parameter consists of a list of content data items to be opened. ThedescriptorTypefor each item in the list indicates the type of the content ('PICT','TIFF','utf8', and so on).The application should use the content in an appropriate wayâfor example, if a document is open, it might insert the content at the current insertion point; if no document is open, it might open a new document and insert the provided text or image.If your Carbon application provides a service that can accept the type of data in anopen contentsApple event it receives, you can handle the event without even installing an event handler for itâa default handler will be installed, if one isnât present, and invoked automatically. As a result, your service provider will receive a{kEventClassService, kEventServicePerform}Carbon event.Because there is no way to return data from anopen contentsApple event, the default handler only invokes a service that accepts the given data type but returns nothing.If your application doesnât support services, or if you want to provide special handling for theopen contentsApple event, your application can install a handler for the event.For information on working with services, seeSetting Up Your Carbon Application to Use the Services Menu.
open contents
Available starting in Mac OS X version 10.4. Received when content, such as text or an image, is dropped on the application iconâfor example, when a dragged image is dropped on the icon in the Dock.
The structure of this event is very similar to theopen documentsevent. The direct object parameter consists of a list of content data items to be opened. ThedescriptorTypefor each item in the list indicates the type of the content ('PICT','TIFF','utf8', and so on).
The application should use the content in an appropriate wayâfor example, if a document is open, it might insert the content at the current insertion point; if no document is open, it might open a new document and insert the provided text or image.
If your Carbon application provides a service that can accept the type of data in anopen contentsApple event it receives, you can handle the event without even installing an event handler for itâa default handler will be installed, if one isnât present, and invoked automatically. As a result, your service provider will receive a{kEventClassService, kEventServicePerform}Carbon event.
Because there is no way to return data from anopen contentsApple event, the default handler only invokes a service that accepts the given data type but returns nothing.
If your application doesnât support services, or if you want to provide special handling for theopen contentsApple event, your application can install a handler for the event.
For information on working with services, seeSetting Up Your Carbon Application to Use the Services Menu.
- quit applicationReceived when the application should quit. The application can perform any special operations required at that time.If your application callsRunApplicationEventLoop, a simplequithandler is installed automatically. If you install your own handler, it can perform any required operations, then returnerrAEEventNotHandledso that the default handler continues quitting the application. If you return another error value, the application will not quit. However, yourquithandler can callQuitApplicationEventLoop, which causesRunApplicationEventLoopto quit and return back tomain(). In that case you can returnnoErrfrom your handler instead oferrAEEventNotHandled.If your application does not callRunApplicationEventLoop, you should supply your ownquithandler.You should not terminate your application from within aquitevent handler. Instead, you should set a flag that you check outside the handler.
quit application
Received when the application should quit. The application can perform any special operations required at that time.
If your application callsRunApplicationEventLoop, a simplequithandler is installed automatically. If you install your own handler, it can perform any required operations, then returnerrAEEventNotHandledso that the default handler continues quitting the application. If you return another error value, the application will not quit. However, yourquithandler can callQuitApplicationEventLoop, which causesRunApplicationEventLoopto quit and return back tomain(). In that case you can returnnoErrfrom your handler instead oferrAEEventNotHandled.
If your application does not callRunApplicationEventLoop, you should supply your ownquithandler.
You should not terminate your application from within aquitevent handler. Instead, you should set a flag that you check outside the handler.
- show preferencesReceived when the user chooses the Preferences menu item. Carbon applications that handle the Preferences command can install an Apple event handler for this event, but they more commonly install a Carbon event handler forkEventCommandProcessand check for thekHICommandPreferencescommand ID.
show preferences
Received when the user chooses the Preferences menu item. Carbon applications that handle the Preferences command can install an Apple event handler for this event, but they more commonly install a Carbon event handler forkEventCommandProcessand check for thekHICommandPreferencescommand ID.
- application diedReceived by an application that launched another application when the launched application quits or terminates. Your application can respond to the information that the other application is no longer running.
application died
Received by an application that launched another application when the launched application quits or terminates. Your application can respond to the information that the other application is no longer running.
### Installing Handlers for Apple Events Sent by the Mac OS
Listing 5-6shows how your application installs handlers for various Apple events that are sent by the Mac OS. The listing assumes that you have defined the functionsOpenApplicationAE,ReopenApplicationAE,OpenDocumentsAE, andPrintDocumentsAEto handle the Apple eventsopen application,reopen,open documents, andprint documents, respectively.
This function doesnât install handlers for theopen contentsandquitApple events, so the application will rely on the default handlers for those events (described previously inCommon Apple Events Sent by the Mac OS).
Listing 5-6Installing event handlers for Apple events from the Mac OS
```applescript
static OSErr InstallMacOSEventHandlers(void)
```
```applescript
{
```
```applescript
OSErr err;
```
```applescript
```
```applescript
err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
```
```applescript
NewAEEventHandlerUPP(OpenApplicationAE), 0, false);
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
err = AEInstallEventHandler(kCoreEventClass, kAEReopenApplication,
```
```applescript
NewAEEventHandlerUPP(ReopenApplicationAE), 0, false);
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
```
```applescript
NewAEEventHandlerUPP(OpenDocumentsAE), 0, false);
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
```
```applescript
NewAEEventHandlerUPP(PrintDocumentsAE), 0, false);
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
```
```applescript
CantInstallAppleEventHandler:
```
```applescript
return err;
```
```applescript
}
```
For a description of the parameters you pass to theAEInstallEventHandlerfunction, seeInstalling Apple Event Handlers.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Writing and Installing Coercion Handlers
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Coercionis the process of converting a descriptor and the data it contains from one type to another. When coercing between types, by definition the descriptor type is changed to the new type. However, if the underlying data representation is the same, data conversion is not required.
Functions that perform coercions are referred to ascoercion handlers. The Mac OS provides default coercion handlers to convert between many different descriptor types. Default handlers can, for example, convert aliases to file system specifications, integers to Boolean data types, and characters to numeric data types. These handlers may be implemented by the Apple Event Manager, the Open Scripting framework, or other frameworks.Table C-2lists descriptor types and the available default coercions.
You can also provide your own coercion handlers to perform coercions that the default handlers donât support. This chapter describes how to write coercion handlers and how to install them so that they are available to your application.
For many of the Apple Event Manager functions that your application uses to extract data from an Apple event, you can specify a desired descriptor type for the returned data. If the original data is of a different type, the Apple Event Manager attempts to coerce the data to the requested descriptor type. For more information on functions that let you specify a desired descriptor type, seeCoercing Data From an Apple Event.
## How Coercion Handlers are Installed and Dispatched
Coercion handling works by a process that is similar to the one described previously for dispatching Apple events to Apple event handlers:
- You write coercion handler functions to coerce data between types that your application works with but that are not handled by a default coercion handler.
You write coercion handler functions to coerce data between types that your application works with but that are not handled by a default coercion handler.
- Your application registers coercion handlers with the Apple Event Manager for all the descriptor data types it can convert between. A handler may handle just one type of coercion or multiple types. To specify multiple types, you use the constanttypeWildCard.
Your application registers coercion handlers with the Apple Event Manager for all the descriptor data types it can convert between. A handler may handle just one type of coercion or multiple types. To specify multiple types, you use the constanttypeWildCard.
- The Apple Event Manager creates an application coercion handler dispatch table for your application. The dispatch table maps the descriptor types your application can coerce to the coercion handlers it provides.The Apple Event Manager also creates a system coercion dispatch handler, described below, for the default coercion handlers.
The Apple Event Manager creates an application coercion handler dispatch table for your application. The dispatch table maps the descriptor types your application can coerce to the coercion handlers it provides.
The Apple Event Manager also creates a system coercion dispatch handler, described below, for the default coercion handlers.
- When the Apple Event Manager needs to perform a coercion in your application, it goes through these steps until the coercion is handled:It looks for a coercion handler in your application coercion dispatch table.It looks for a coercion handler in your system coercion dispatch table, which includes the default coercions described inTable C-2.Note:Default coercion handlers may be installed lazily, as they are needed.If it canât find an appropriate coercion handler, it returns the result codeerrAECoercionFail.
When the Apple Event Manager needs to perform a coercion in your application, it goes through these steps until the coercion is handled:
- It looks for a coercion handler in your application coercion dispatch table.
It looks for a coercion handler in your application coercion dispatch table.
- It looks for a coercion handler in your system coercion dispatch table, which includes the default coercions described inTable C-2.Note:Default coercion handlers may be installed lazily, as they are needed.
It looks for a coercion handler in your system coercion dispatch table, which includes the default coercions described inTable C-2.
Note:Default coercion handlers may be installed lazily, as they are needed.
- If it canât find an appropriate coercion handler, it returns the result codeerrAECoercionFail.
If it canât find an appropriate coercion handler, it returns the result codeerrAECoercionFail.
Although your application can have both a system coercion dispatch table and an application dispatch table, you should generally install all coercion handlers in the application coercion dispatch table. For Carbon applications running in Mac OS 8 or Mac OS 9, a handler in the system coercion dispatch table could reside in the system heap, where it would be available to other applications. However, your application should not install a handler in a system coercion dispatch table with the goal that the handler will get called when other applications perform coercionsâthis wonât necessarily work in Mac OS 8 or Mac OS 9 and will not work in Mac OS X.
## Writing a Coercion Handler
When you write a coercion handler, it must do the following things:
- Validate the information passed to it so that it has a reasonable chance of success.
Validate the information passed to it so that it has a reasonable chance of success.
- Gain access to the information to be coerced.
Gain access to the information to be coerced.
- Convert the information to the specified type.
Convert the information to the specified type.
- Create a new descriptor of the specified type.
Create a new descriptor of the specified type.
Warning:This coercion handler usestypeChar, which should be avoided starting in Mac OS X version 10.3, as noted inDefault Coercion Handlers.
There are two types of coercion handlers. The first, which matches the format defined for theAECoerceDescProcPtrdata type, expects the caller to pass a descriptor containing the data to be coerced. The second, which matches the format defined for theAECoercePtrProcPtrdata type, expects the caller to pass a a pointer to the data to be coerced. These data types are described inApple Event Manager Reference.
The examples in this chapter show how to work with a coercion handler that uses descriptors. However the differences in working with the pointer-based type are fairly straight-forward.
To write a a coercion handler namedCoerceApplesToOranges, based on theAECoerceDescProcPtrdata type, you would declare the handler as shown inListing 7-1.
Listing 7-1Declaring a coercion handler
```applescript
OSErr CoerceApplesToOranges (
```
```applescript
const AEDesc * fromDesc,// 1
```
```applescript
DescType toType,// 2
```
```applescript
long handlerRefcon,// 3
```
```applescript
AEDesc * toDesc// 4
```
```applescript
);
```
The following are descriptions of the numbered parameters:
- A pointer to the descriptor to be coerced.
A pointer to the descriptor to be coerced.
- The type to coerce to.
The type to coerce to.
- A reference variable that will be passed to your handlerâyou can use it for any purpose.
A reference variable that will be passed to your handlerâyou can use it for any purpose.
- A descriptor pointer where the handler will store the coerced descriptor.This routine creates a new descriptor, so it is up to the calling routine to dispose of the descriptor.
A descriptor pointer where the handler will store the coerced descriptor.
This routine creates a new descriptor, so it is up to the calling routine to dispose of the descriptor.
Suppose that you want to write a coercion handler to convert text strings into your internal âbarâ data type. ThetypeBartype is defined as shown inListing 7-2.
Listing 7-2An application-defined data type
```applescript
enum {
```
```applescript
typeBar = 'bar!'
```
```applescript
};
```
Listing 7-3provides a slightly simplified version of the handler you might write.
Listing 7-3A simple coercion handler
```applescript
static OSErr TextToBarCoercionHandler(const AEDesc* fromDesc, DescType toType, long handlerRefcon, AEDesc* toDesc)
```
```applescript
{
```
```applescript
require_noerr((fromDesc->descriptorType != typeChar),CoercionFailed);// 1
```
```applescript
require_noerr((toType != typeBar), CoercionFailed);
```
```applescript
require_noerr((handlerRefcon != 1234), CoercionFailed);// 2
```
```applescript
```
```applescript
long dataSize = AEGetDescDataSize(fromDesc);// 3
```
```applescript
char dataPtr[dataSize];
```
```applescript
OSErr err = AEGetDescData(fromDesc, dataPtr, dataSize);
```
```applescript
require_noerr(err, CoercionFailed);
```
```applescript
```
```applescript
long result = 0;
```
```applescript
const char* pChar = (const char*) dataPtr;
```
```applescript
while (dataSize-- > 0)// 4
```
```applescript
result += *pChar++;
```
```applescript
```
```applescript
err = AECreateDesc(typeBar, &result, sizeof(result), toDesc);// 5
```
```applescript
```
```applescript
if (err != noErr)// 6
```
```applescript
err = errAECoercionFail;
```
```applescript
```
```applescript
CoercionFailed:// 7
```
```applescript
return err;
```
```applescript
}
```
Hereâs what the code inTextToBarCoercionHandlerdoes:
- Checks the passed parameters to validate that it can handle the requested coercion, using the macrorequire_noerr, which jumps to the error labelCoercionFailedif a value isnât supported.Coercion handlers that support multiple types will have additional work to do here.
Checks the passed parameters to validate that it can handle the requested coercion, using the macrorequire_noerr, which jumps to the error labelCoercionFailedif a value isnât supported.
Coercion handlers that support multiple types will have additional work to do here.
- Checks that the passed reference constant matches the expected value. You previously set the reference constant when you installed the coercion handler (shown inInstalling a Coercion Handler).
Checks that the passed reference constant matches the expected value. You previously set the reference constant when you installed the coercion handler (shown inInstalling a Coercion Handler).
- Gets the size of the data in the descriptor to be coerced and uses it to get the actual data from the descriptor.
Gets the size of the data in the descriptor to be coerced and uses it to get the actual data from the descriptor.
- In a while loop, converts the data from type text to type bar (by summing the bytes).
In a while loop, converts the data from type text to type bar (by summing the bytes).
- Creates a new descriptor of type bar, using the coerced data.
Creates a new descriptor of type bar, using the coerced data.
- If it was unable to create the coerced descriptor, returns an error indicating the coercion failed.
If it was unable to create the coerced descriptor, returns an error indicating the coercion failed.
- Whether it jumped to the error label or fell through on success, returns an error code indicating whether the coercion succeeded or failed.
Whether it jumped to the error label or fell through on success, returns an error code indicating whether the coercion succeeded or failed.
These are the main differences if you want to write a coercion handler based on theAECoercePtrProcPtrdata type, which works with a pointer to data:
- The coercion handler has two additional parameters: one specifies the descriptor type of the data the pointer parameter points to; the other specifies the size of the data.
The coercion handler has two additional parameters: one specifies the descriptor type of the data the pointer parameter points to; the other specifies the size of the data.
- When obtaining the data to convert, you use the size and type information to extract the data from the pointer, rather than getting the type and the data from a passed descriptor.
When obtaining the data to convert, you use the size and type information to extract the data from the pointer, rather than getting the type and the data from a passed descriptor.
## Installing a Coercion Handler
To install a coercion handler, you use theAEInstallCoercionHandlerfunction, which is declared as shown inListing 7-4.
Listing 7-4Declaration of AEInstallCoercionHandler
```applescript
OSErr AEInstallCoercionHandler (
```
```applescript
DescType fromType,// 1
```
```applescript
DescType toType,// 2
```
```applescript
AECoercionHandlerUPP handler,// 3
```
```applescript
long handlerRefcon,// 4
```
```applescript
Boolean fromTypeIsDesc,// 5
```
```applescript
Boolean isSysHandler// 6
```
```applescript
);
```
You specify as parameters to this function:
- The descriptor type of the data coerced by the handler. You can passtypeWildCardto accept all types.
The descriptor type of the data coerced by the handler. You can passtypeWildCardto accept all types.
- The descriptor type of the resulting data. You can passtypeWildCardto accept all types.
The descriptor type of the resulting data. You can passtypeWildCardto accept all types.
- The address of the coercion handler for this descriptor type; the handler is declared as described inWriting a Coercion Handler.
The address of the coercion handler for this descriptor type; the handler is declared as described inWriting a Coercion Handler.
- A reference constant to pass to the handler when it is called. You can use the reference constant for any purpose you want.
A reference constant to pass to the handler when it is called. You can use the reference constant for any purpose you want.
- A Boolean value that indicates whether your coercion handler expects the data to be specified as a descriptor or as a pointer to the actual data.
A Boolean value that indicates whether your coercion handler expects the data to be specified as a descriptor or as a pointer to the actual data.
- A Boolean value that indicates whether your coercion handler should be added to your applicationâs coercion dispatch table or the system coercion dispatch table.
A Boolean value that indicates whether your coercion handler should be added to your applicationâs coercion dispatch table or the system coercion dispatch table.
To call theTextToBarCoercionHandlerhandler defined inListing 7-3, you can use code like that shown inListing 7-5.
Listing 7-5Installing a coercion handler
```applescript
OSErr err = AEInstallCoercionHandler(
```
```applescript
typeChar, // Coerce from this type
```
```applescript
typeBar, // to this type,
```
```applescript
TextToBarCoercionHandler, //using this handler,
```
```applescript
1234, // passing this reference constant.
```
```applescript
true, // The handler operates on descriptors,
```
```applescript
false); // and resides in the application table.
```
Hereâs what the parameters in this call specify:
- Coerce from type'TEXT'.
Coerce from type'TEXT'.
- Coerce to typetypeBar.
Coerce to typetypeBar.
- Use the handlerTextToBarCoercionHandlerto perform the coercion.
Use the handlerTextToBarCoercionHandlerto perform the coercion.
- Pass the reference constant 1234.
Pass the reference constant 1234.
- The handler operates on descriptors.
The handler operates on descriptors.
- The handler resides in the applicationâs coercion dispatch table.
The handler resides in the applicationâs coercion dispatch table.
## Testing a Coercion Handler
You can use code like that shown inListing 7-6to test theTextToBarCoercionHandlerhandler defined inListing 7-3.
Listing 7-6Testing a coercion handler
```applescript
AEDesc textDesc;
```
```applescript
const char* kText = "1234";
```
```applescript
OSErr err = AECreateDesc(typeChar, kText, strlen(kText), &textDesc);// 1
```
```applescript
```
```applescript
AEDesc barDesc;
```
```applescript
err = AECoerceDesc(&textDesc, typeBar, &barDesc);// 2
```
```applescript
if (err == noErr)
```
```applescript
{
```
```applescript
// Use the descriptor as needed.
```
```applescript
```
```applescript
// Dispose of the descriptor when finished with it.
```
```applescript
err = AEDisposeDesc(&barDesc);// 3
```
```applescript
}
```
```applescript
err = AEDisposeDesc(&textDesc);// 4
```
Here is what the code in this snippet does:
- Creates a descriptor containing the text string â1234â.
Creates a descriptor containing the text string â1234â.
- Calls the Apple Event Manager functionAECoerceDesc, passing the text descriptor, the desired type (type bar), and the address of a descriptor in which to store the coerced descriptor.
Calls the Apple Event Manager functionAECoerceDesc, passing the text descriptor, the desired type (type bar), and the address of a descriptor in which to store the coerced descriptor.
- If the coercion is successful, disposes of the coerced descriptor. Because a coercion returns a new descriptor, your application must dispose of the descriptor when it is finished with it. (This code snippet does not include full error handling.)
If the coercion is successful, disposes of the coerced descriptor. Because a coercion returns a new descriptor, your application must dispose of the descriptor when it is finished with it. (This code snippet does not include full error handling.)
- Disposes of the text descriptor.
Disposes of the text descriptor.
If the coercion fails, you can set a breakpoint in your coercion handler to determine if it is ever called. Possible problems include:
- You didnât install the coercion handler.
You didnât install the coercion handler.
- The type you passed toAECoerceDescwas different than the type you registered for your coercion handler.
The type you passed toAECoerceDescwas different than the type you registered for your coercion handler.
- The text descriptor you created has a different descriptor type than you registered for your coercion handler.
The text descriptor you created has a different descriptor type than you registered for your coercion handler.
You can install a single coercion handler that specifies the constanttypeWildCardfor both the to and from types. Then any time the Apple Event Manager attempts to dispatch a coercion to the application, it will invoke that handler. This provides a convenient bottleneck for debugging.
Using wildcards can also be convenient as a general way to handle coercions, with one or a small number of handlers converting between supported types and the applicationâs private data types.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Unsupported Terms
This appendix lists scripting terms that are not supported by AppleScript. Though you may see these terms in a dictionary, script, or scripting addition, you should not count on their behavior.
## List of Unsupported Terms
This command is not supported.
An Internet or intranet address for the TCP/IP protocol. Only used for compatibility with WebSTAR AppleScript CGI scripts, this term is not supported by AppleScript itself.
An HTML page. This class is not supported.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# Introduction to XML-RPC and SOAP Programming Guide
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Note:This document was previously titled âXML-RPC and SOAP Support.â
XML-RPC and SOAP Programming Guidedescribes how to use Apple Script and the Apple Event Manager in OS X to make remote procedure calls using the XML-RPC and SOAP (Simple Object Access Protocol) protocols.
XML-RPCis a protocol for using XML and HTTP to make remote procedure calls over the Internet.SOAP (Simple Object Access Protocol)is a remote procedure call protocol designed for exchanging information in a distributed environment, where a server may consist of a hierarchy of objects.
This book describes only how to send XML-RPC and SOAP requests, not how to serve them.
Note:Web service protocols such as XML-RPC and SOAP are evolving, as is the support for them in OS X. The scripts and code samples in this document depend on third-party web services that are also subject to change. Though the samples have been tested as published, your experience may vary.
The sample code in this book can be adapted for Carbon applications, Cocoa applications, simple tools, or other code. However, there is no specific Cocoa class support provided.
## Who Should Read This Document
To take full advantage of this document, you should be familiar with AppleScript, either through writing AppleScript scripts or creating scriptable applications. You can learn more about these topics inAppleScript Documentation. In particular, seeAppleScript OverviewandApple Events Programming Guide.
You should also be familiar with the XML-RPC and SOAP protocols. You can find information on these protocols at third-party websites. For example, the XML-RPC specification is currently described athttp://www.xmlrpc.com/specand the SOAP specification athttp://www.w3.org/TR/.
## Organization of This Document
This document is organized into the following chapters:
- About AppleScriptâs Support for XML-RPC and SOAPprovides a brief introduction to the XML-RPC and SOAP protocols, then describes the scripting support in OS X version 10.1 (and later) for these protocols, including the syntax for script statements and the APIs for making remote procedure calls from applications or other code.
About AppleScriptâs Support for XML-RPC and SOAPprovides a brief introduction to the XML-RPC and SOAP protocols, then describes the scripting support in OS X version 10.1 (and later) for these protocols, including the syntax for script statements and the APIs for making remote procedure calls from applications or other code.
- Making Remote Procedure Calls From Scriptsprovides sample scripts and step by step descriptions for making XML-RPC and SOAP requests from scripts.
Making Remote Procedure Calls From Scriptsprovides sample scripts and step by step descriptions for making XML-RPC and SOAP requests from scripts.
- Making Remote Procedure Calls From Applicationsprovides sample code and step by step descriptions for making XML-RPC and SOAP requests from applications and other code.
Making Remote Procedure Calls From Applicationsprovides sample code and step by step descriptions for making XML-RPC and SOAP requests from applications and other code.
- Document Revision Historydescribes the history of this book.
Document Revision Historydescribes the history of this book.
Copyright © 2001, 2014 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2014-07-15
---
# Automator
Automator is a workflow automation application, first available in OS X version 10.4. Automator, which is located in/Applications, lets you create complex workflows using a graphical interface that does not require any knowledge of scripting languages. A workflow consists of one or more actions, executed sequentially, with each action typically taking the output of the previous action as its input. An action performs a distinct operation, such as copying a file, cropping a photo, or sending an email message. You can run a workflow in Automator or save it as a standalone application.
Starting in OS X version 10.5, you can also embed and execute Automator workflows in your application.
Automator includes actions for many Apple applications, including Finder, Mail, Safari, Xcode, iPhoto, iTunes, and QuickTime Player, and you can write actions that make features of your applications available in Automator. You use Xcode and Interface Builder to put together actions, using the Action project template (also available starting in OS X v10.4). Actions are implemented as plug-ins and you can write them using AppleScript (for scriptable applications) or Objective-C.
Note:If your application is scriptable, other developers and users can write actions for it. However, by supplying actions yourself, you can be sure to make your application look its best in Automator.
For information on using the Automator application, choose Help in Automator or Help > Mac Help in the Finder and search for âAutomatorâ. For information on creating actions, seeAutomator Programming GuideandAutomator Framework Reference. For information on using workflows in your application, seeAutomation Release Notes for OS X v10.7, as well as the class descriptions forAMWorkflow,AMWorkflowView, andAMWorkflowControllerinAutomator Framework Reference
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Scripting Bridge
Scripting Bridge, introduced in OS X version 10.5, provides an automated process for creating an Objective-C interface to scriptable applications. This allows Cocoa applications and other Objective-C code to efficiently access features of scriptable applications, using native Objective-C syntax. Some other scripting languages, such as Ruby and Python, can use also Scripting Bridge (they also have open-source software bridges to scriptable applicationsâRubyOSA and py-appscript). For more information, seeRuby and Python Programming Topics for Mac.
To use Scripting Bridge, you add the Scripting Bridge framework to your application project and use command-line tools to generate the interface files for the scriptable application you want to target. Then in your application code, you obtain a reference to an application object for the targeted scriptable application and send Objective-C messages to it.
For details, seeScripting Bridge Programming GuideandScripting Bridge Framework Reference. For related sample code, seeScriptingBridgeFinder.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Creating and Sending Apple Events
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This chapter provides information and sample code that will help you create and send Apple events and handle Apple events you receive in response to those you send. Before reading this chapter, you should be familiar with the information inBuilding an Apple Event.
Applications most commonly create and send Apple events for one of the reasons described inWhen Applications Use Apple Events: to communicate directly with other applications or to support recording in a scriptable application. And as described inTwo Approaches to Creating an Apple Event, you can create an Apple event in one step with theAEBuildAppleEventfunction, or you can create a possibly incomplete Apple event withAECreateAppleEvent, then add attributes and parameters to complete the event.
Note:Two Approaches to Creating an Apple Eventalso briefly describes a third approach, using stream-oriented calling conventions, and points to documentation for that approach.
## Functions for Creating Apple Event Data Structures
In addition to theAEBuildAppleEventandAECreateAppleEventfunctions for creating Apple events, you use the following functions for creating other data structures you use with Apple events:
- For creating descriptor records and lists and adding items to lists:AEBuildDesc,AECreateDesc,AECreateList,AEPutPtr,AEPutDesc
For creating descriptor records and lists and adding items to lists:
AEBuildDesc,AECreateDesc,AECreateList,AEPutPtr,AEPutDesc
- For adding attributes and parameters to Apple events and Apple event records:AEBuildParameters,AEPutParameter,AEPutParamDesc,AEPutAttributePtr,AEPutAttributeDesc
For adding attributes and parameters to Apple events and Apple event records:
AEBuildParameters,AEPutParameter,AEPutParamDesc,AEPutAttributePtr,AEPutAttributeDesc
Table A-1lists these and other Apple Event Manager functions. For complete function descriptions, seeApple Event Manager Reference.
## Specifying a Target Address
When you create an Apple event, you must specify the address of the target. Thetarget addressidentifies the particular application or process to send the Apple event to. You can send Apple events to applications on the local computer or on remote computers on the network. You specify a target address with atarget address descriptor.
The preferred descriptor types for identifying the address in an address descriptor are shown inAddress Descriptor Type Constants.You can also use another type if your application provides a coercion handler that coerces that type into one of the address types that the Apple Event Manager recognizes. SeeWriting and Installing Coercion Handlersfor more information on coercion handlers.
To address an Apple event to a target on a remote computer on the network, you generally usetypeApplicationURLfor the address descriptor type. To address an Apple event to a target on the local computer you can use any of the address types.
The fastest way for your application to send an Apple event to itself is to use a target address with a process serial number ofkCurrentProcess. For more information, seeAddressing an Apple Event for Direct Dispatching.
### Creating a Target Address Descriptor
If you want to create an Apple event with theAECreateAppleEventfunction, you need to create a target address descriptor to pass to the function. You can do so by calling theAECreateDescfunction.Listing 6-1shows how to create an address descriptor for a process serial number (typeProcessSerialNumber). Other target address descriptor types are shown inAddress Descriptor Type Constants.
Listing 6-1Creating an address descriptor using a process serial number
```applescript
OSErr err;
```
```applescript
ProcessSerialNumber thePSN;
```
```applescript
AEAddressDesc addressDesc;
```
```applescript
```
```applescript
err = GetProcessNumber(&thePSN);// 1
```
```applescript
if (err == noErr)
```
```applescript
{
```
```applescript
err = AECreateDesc(typeProcessSerialNumber,
```
```applescript
&thePSN, sizeof(thePSN), &addressDesc);// 2
```
```applescript
}
```
Hereâs a description of how this code snippet works:
- It calls an application-defined function,GetProcessNumber, to obtain the process serial number of another process.To create a target address descriptor for the current process, seeListing 6-2.
It calls an application-defined function,GetProcessNumber, to obtain the process serial number of another process.
To create a target address descriptor for the current process, seeListing 6-2.
- It callsAECreateDescto create a target address based on the specified process serial number.Your application should callAEDisposeDescto dispose of the address descriptor when it is finished with it.
It callsAECreateDescto create a target address based on the specified process serial number.
Your application should callAEDisposeDescto dispose of the address descriptor when it is finished with it.
When you create an Apple event with theAEBuildAppleEventfunction, it uses information from the following three parameters to create a target address descriptor:
The address type for the address information described in the next two parameters: for example,typeProcessSerialNumberortypeKernelProcessID.
A pointer to the address information.
The number of bytes pointed to by theaddressDataparameter.
For a code example that usesAEBuildAppleEvent, seeListing 6-4.
### Addressing an Apple Event for Direct Dispatching
Applications typically send Apple events to themselves to support recordability, discussed briefly inWhen Applications Use Apple Events. The best way for your application to send Apple events to itself is to use an address descriptor oftypeProcessSerialNumberwith thelowLongOfPSNfield set tokCurrentProcessand thehighLongOfPSNfield set to 0.Listing 6-2shows how to do this.
When you send an Apple event with this type of target address descriptor, the Apple Event Manager jumps directly to the appropriate Apple event handler without going through the normal event-processing sequence. This is not only more efficient, it avoids the situation in which an Apple event sent in response to a user action arrives in the event queue after some other event that really occurred later than the user action. For example, suppose a user chooses Cut from the Edit menu and then clicks in another window. If thecutApple event arrives in the queue after the window activate event, a selection in the wrong window might be cut.
Listing 6-2Creating an address descriptor that specifies the current application
```applescript
AEAddressDesc addressDesc;
```
```applescript
ProcessSerialNumber selfPSN = { 0, kCurrentProcess };// 1
```
```applescript
```
```applescript
OSErr err = AECreateDesc(typeProcessSerialNumber, &selfPSN,
```
```applescript
sizeof(selfPSN), &addressDesc);// 2
```
Hereâs a description of how this code snippet works:
- Sets up a process serial number for the current process, as described above.
Sets up a process serial number for the current process, as described above.
- CallsAECreateDescto create a target address that specifies the current application by its process serial number.Your application should callAEDisposeDescto dispose of the address descriptor when it is finished with it.
CallsAECreateDescto create a target address that specifies the current application by its process serial number.
Your application should callAEDisposeDescto dispose of the address descriptor when it is finished with it.
Your application can send events to itself using other forms of target addressing. However, this can lead to the event dispatching sequence problems just described.
Important:When Apple event recording has been turned on, the Apple Event Manager records every event that your application sends to itself unless you specify thekAEDontRecordflag in thesendModeparameter of theAESendorAESendMessagefunction.
### Obtaining the Addresses of Remote Processes
You can useAECreateRemoteProcessResolverand related functions to obtain the addresses of other processes on the network. To do so you follow these steps:
- CallAECreateRemoteProcessResolverto get a process resolver.
CallAECreateRemoteProcessResolverto get a process resolver.
- CallAERemoteProcessResolverGetProcessesto obtain a dictionary containing, for each remote application, the URL of the application and its human readable name (and possibly other information).
CallAERemoteProcessResolverGetProcessesto obtain a dictionary containing, for each remote application, the URL of the application and its human readable name (and possibly other information).
- CallAEDisposeRemoteProcessResolverto dispose of the process resolver.
CallAEDisposeRemoteProcessResolverto dispose of the process resolver.
- Create a target address descriptor based on a specified URL.Extract the URL from the dictionary entry as aCFURLRef.Convert it to aCFStringRef(for example, withCFURLGetString).Extract a text string in UTF-8 encoding. (For an example of code that extracts unicode text from aCFStringRef, seeListing 5-3.)Put the text into an address descriptor using the typetypeApplicationURL. The format of the URL associated with this type is described in the Discussion section of âDescriptor Type Constantsâ inApple Event Manager Reference.
Create a target address descriptor based on a specified URL.
- Extract the URL from the dictionary entry as aCFURLRef.
Extract the URL from the dictionary entry as aCFURLRef.
- Convert it to aCFStringRef(for example, withCFURLGetString).
Convert it to aCFStringRef(for example, withCFURLGetString).
- Extract a text string in UTF-8 encoding. (For an example of code that extracts unicode text from aCFStringRef, seeListing 5-3.)
Extract a text string in UTF-8 encoding. (For an example of code that extracts unicode text from aCFStringRef, seeListing 5-3.)
- Put the text into an address descriptor using the typetypeApplicationURL. The format of the URL associated with this type is described in the Discussion section of âDescriptor Type Constantsâ inApple Event Manager Reference.
Put the text into an address descriptor using the typetypeApplicationURL. The format of the URL associated with this type is described in the Discussion section of âDescriptor Type Constantsâ inApple Event Manager Reference.
- Alternatively, if the dictionary entry contains a process ID for the remote process, you can create an address descriptor based on the typetypeKernelProcessID.
Alternatively, if the dictionary entry contains a process ID for the remote process, you can create an address descriptor based on the typetypeKernelProcessID.
You can use the remote process resolver technology, for example, to present an interface to allow a user to select a remote application. For more information on these functions, see the section âLocating Processes on Remote Computersâ inApple Event Manager Reference.
## Creating an Apple Event
This section provides examples of how to create an Apple event withAECreateAppleEventand withAEBuildAppleEvent. These functions are introduced inTwo Approaches to Creating an Apple Event.
### Creating an Apple Event With AEBuildAppleEvent
TheAEBuildAppleEventfunction provides a mechanism for converting a specially formatted string into a complete Apple event. This function is similar toAECreateAppleEvent, but contains additional parameters it uses in creating the Apple event and constructing parameters for it.
TheAEBuildAppleEventfunction is similar to theprintffamily of routines in the standard C library. The syntax for the format string defines an Apple event as a sequence of name-value pairs, with optional parameters preceded with a tilde (~) character. For details, see Technical Note TN2106,AEBuild*, AEPrint*, and Friends.
The next two code listings show how you might useAEBuildAppleEventto create an Apple event that tells the Finder to reveal the startup disk (make it visible on the desktop).
Listing 6-3Constants used in creating a reveal Apple event for the Finder
```applescript
const CFStringRef startupDiskPath = CFSTR("/");// 1
```
```applescript
const OSType finderSignature = 'MACS';// 2
```
Hereâs a description of these constants, which are defined inAERegistry.hand used by the Finder in its Apple event support:
- Defines a string reference for the POSIX-style path of the startup disk.
Defines a string reference for the POSIX-style path of the startup disk.
- Defines the application signature for the Mac OS Finder application.Because the Finder is always running in Mac OS X, it is generally safe to send it an Apple event without first making sure it has been launched.
Defines the application signature for the Mac OS Finder application.
Because the Finder is always running in Mac OS X, it is generally safe to send it an Apple event without first making sure it has been launched.
Listing 6-4shows a function that creates an Apple event to reveal the startup disk in the Finder.
Listing 6-4Creating a reveal Apple event with AEBuildAppleEvent
```applescript
OSErr BuildRevealStartupDiskAE (AppleEvent * revealEvent)// 1
```
```applescript
{
```
```applescript
FSRef startupDiskFSRef;
```
```applescript
AliasHandle startupDiskAlias;
```
```applescript
OSErr err = noErr;
```
```applescript
```
```applescript
CFURLRef startupURLRef =
```
```applescript
CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
```
```applescript
startupDiskPath, kCFURLPOSIXPathStyle, true);// 2
```
```applescript
```
```applescript
if (CFURLGetFSRef(startupURLRef, &startupDiskFSRef))// 3
```
```applescript
{
```
```applescript
err = FSNewAlias(NULL, &startupDiskFSRef, &startupDiskAlias);// 4
```
```applescript
if (err == noErr)
```
```applescript
{
```
```applescript
err = AEBuildAppleEvent(// 5
```
```applescript
kAEMiscStandards,// 6
```
```applescript
kAEMakeObjectsVisible,// 7
```
```applescript
typeApplSignature,// 8
```
```applescript
&finderSignature,// 9
```
```applescript
sizeof(finderSignature),// 10
```
```applescript
kAutoGenerateReturnID, // 11
```
```applescript
kAnyTransactionID,// 12
```
```applescript
revealEvent,// 13
```
```applescript
NULL,// 14
```
```applescript
"'----':[alis(@@)]",// 15
```
```applescript
startupDiskAlias);// 16
```
```applescript
}
```
```applescript
}
```
```applescript
else
```
```applescript
err = memFullErr;// 17
```
```applescript
```
```applescript
return err;// 18
```
```applescript
}
```
Hereâs a description of how theBuildRevealStartupDiskAEfunction works:
- It is passed a pointer to an Apple event data structure for the event to be created.
It is passed a pointer to an Apple event data structure for the event to be created.
- It callsCFURLCreateWithFileSystemPathto create aCFURLReffor the path to the startup disk, passing the constantstartupDiskPathdeclared inListing 6-3.
It callsCFURLCreateWithFileSystemPathto create aCFURLReffor the path to the startup disk, passing the constantstartupDiskPathdeclared inListing 6-3.
- It callsCFURLGetFSRefto get anFSReffile reference to the startup disk from theCFURLRef.
It callsCFURLGetFSRefto get anFSReffile reference to the startup disk from theCFURLRef.
- It callsFSNewAliasto convert theFSRefto an alias handle for the startup disk, to use in creating the Apple event.
It callsFSNewAliasto convert theFSRefto an alias handle for the startup disk, to use in creating the Apple event.
- It callsAEBuildAppleEventto create the Apple event. The next several items describe the parameters you pass to that function.
It callsAEBuildAppleEventto create the Apple event. The next several items describe the parameters you pass to that function.
- SpecifieskAEMiscStandards, a constant defined inAERegistry.h, for the event class.
SpecifieskAEMiscStandards, a constant defined inAERegistry.h, for the event class.
- SpecifieskAEMakeObjectsVisible, also defined inAERegistry.h, for the event ID.
SpecifieskAEMakeObjectsVisible, also defined inAERegistry.h, for the event ID.
- PassestypeApplSignatureto specify a target address type.
PassestypeApplSignatureto specify a target address type.
- PassesfinderSignature, defined inListing 6-3, to specify the application signature for the Finder.
PassesfinderSignature, defined inListing 6-3, to specify the application signature for the Finder.
- Passes the size of the application signature.
Passes the size of the application signature.
- Passes the Apple Event Manager constantkAutoGenerateReturnID, indicating the Apple Event Manager should set a return ID for the event. Your application can specify its own return ID, if needed.
Passes the Apple Event Manager constantkAutoGenerateReturnID, indicating the Apple Event Manager should set a return ID for the event. Your application can specify its own return ID, if needed.
- Passes the Apple Event Manager constantkAnyTransactionID, indicating the event is not part of a series of interdependent transactions.
Passes the Apple Event Manager constantkAnyTransactionID, indicating the event is not part of a series of interdependent transactions.
- Passes a pointer to the Apple event to be built.
Passes a pointer to the Apple event to be built.
- Passes a value ofNULL, indicating no error information is required.See Technical Note TN2106,AEBuild*, AEPrint*, and Friendsfor information on working with error information when usingAEBuildAppleEvent.
Passes a value ofNULL, indicating no error information is required.
See Technical Note TN2106,AEBuild*, AEPrint*, and Friendsfor information on working with error information when usingAEBuildAppleEvent.
- Passes a format string containing information for any attributes and parameters to add to the Apple event. In this case, there is just one parameter, an alias ('----').The identifier for the direct parameter in an Apple event is specified by the constantkeyDirectObject('----'). The minus sign has special meaning in AEBuild strings, so it should always be enclosed in single quotes when it is used to identify the direct parameter for an Apple event.
Passes a format string containing information for any attributes and parameters to add to the Apple event. In this case, there is just one parameter, an alias ('----').
The identifier for the direct parameter in an Apple event is specified by the constantkeyDirectObject('----'). The minus sign has special meaning in AEBuild strings, so it should always be enclosed in single quotes when it is used to identify the direct parameter for an Apple event.
- Passes the previously created alias handle as the data corresponding to the entry in the format string.
Passes the previously created alias handle as the data corresponding to the entry in the format string.
- In the case where the function could not create anFSRef, it sets a return error value.
In the case where the function could not create anFSRef, it sets a return error value.
- It returns a value indicating whether an error occurred.
It returns a value indicating whether an error occurred.
To see how theBuildRevealStartupDiskAEfunction is called, and how you can send the resulting Apple event, seeListing 6-7.
### Creating an Apple Event With AECreateAppleEvent
To create an Apple event withAECreateAppleEvent, you perform these steps:
- Prepare a target address descriptor, as described inCreating a Target Address Descriptor.
Prepare a target address descriptor, as described inCreating a Target Address Descriptor.
- CallAECreateAppleEventto create the Apple event, passing the event class, event ID, and other information.
CallAECreateAppleEventto create the Apple event, passing the event class, event ID, and other information.
- If necessary, call other Apple Event Manager functions to add additional information to the event, until it contains all the information required for the task you want to perform.
If necessary, call other Apple Event Manager functions to add additional information to the event, until it contains all the information required for the task you want to perform.
For example, suppose your application wants to send aquitApple event to another application. It might do this to terminate an application it launched previously, or perhaps to make sure an application is not running so it can perform an update.Listing 6-5shows how to create aquitapplication Apple event.
Listing 6-5Creating a quit Apple event with AECreateAppleEvent
```applescript
AppleEvent someAE;
```
```applescript
```
```applescript
err = AECreateAppleEvent(// 1
```
```applescript
kCoreEventClass,// 2
```
```applescript
kAEQuitApplication,// 3
```
```applescript
&theTarget,// 4
```
```applescript
kAutoGenerateReturnID,// 5
```
```applescript
kAnyTransactionID,// 6
```
```applescript
&someAE);// 7
```
Hereâs how the code inListing 6-5works:
- It callsAECreateAppleEventto create the Apple event. The following items describe the parameters you pass to that function.
It callsAECreateAppleEventto create the Apple event. The following items describe the parameters you pass to that function.
- SpecifieskCoreEventClass, a constant defined inAppleEvents.h, for the event class.
SpecifieskCoreEventClass, a constant defined inAppleEvents.h, for the event class.
- SpecifieskAEQuitApplication, also defined inAppleEvents.h, for the event ID.
SpecifieskAEQuitApplication, also defined inAppleEvents.h, for the event ID.
- Passes the address of the previously constructed target address descriptor, which identifies the application to send thequitevent to.
Passes the address of the previously constructed target address descriptor, which identifies the application to send thequitevent to.
- Passes the Apple Event Manager constantkAutoGenerateReturnID, indicating the Apple Event Manager should set a return ID for the event. Your application can specify its own return ID, if needed.
Passes the Apple Event Manager constantkAutoGenerateReturnID, indicating the Apple Event Manager should set a return ID for the event. Your application can specify its own return ID, if needed.
- Passes the Apple Event Manager constantkAnyTransactionID, indicating the event is not part of a series of interdependent transactions.
Passes the Apple Event Manager constantkAnyTransactionID, indicating the event is not part of a series of interdependent transactions.
- It passes the address of an Apple event data structure for the event to be created.
It passes the address of an Apple event data structure for the event to be created.
Thatâs all you need to do to create aquitApple event. However, to create a more complicated Apple event, you typically need to add attributes or parameters to the event. For example, your application might receive aget dataApple event for which it returns some specified text as the direct parameter of the reply Apple event.Listing 6-6shows how to add such a direct parameter, using a previously defined function.
Listing 6-6Adding a direct parameter to an Apple event
```applescript
OSErr anErr = AEPutParamString(// 1
```
```applescript
reply,// 2
```
```applescript
keyDirectObject,// 3
```
```applescript
textStringRef);// 4
```
Hereâs how the code inListing 6-6works:
- It calls the application-defined functionAEPutParamString, shown inListing 5-3. The following items describe the parameters you pass to add a direct parameter to the Apple event.
It calls the application-defined functionAEPutParamString, shown inListing 5-3. The following items describe the parameters you pass to add a direct parameter to the Apple event.
- A pointer to the Apple event to add the parameter to.
A pointer to the Apple event to add the parameter to.
- An Apple Event Manager keyword constant specifying that the parameter is to be added as the direct parameter of the Apple event.
An Apple Event Manager keyword constant specifying that the parameter is to be added as the direct parameter of the Apple event.
- ACFStringRef, obtained prior to the call, that specifies the text for the direct parameter.
ACFStringRef, obtained prior to the call, that specifies the text for the direct parameter.
You can also use theAEBuildParametersfunction, introduced inTwo Approaches to Creating an Apple Event, to add more complicated attributes or parameters to an existing Apple event.
### Disposing of Apple Events You Create
Regardless of how you create an Apple event, your application is responsible for disposing of it with theAEDisposeDescfunction when you are finished with it. Your application must also dispose of all the descriptor records it creates when adding parameters and attributes to an Apple eventâremember, many Apple Event Manager functions make copies of descriptors and of their associated data, as noted inDisposing of Apple Event Data Structures.
You normally dispose of your Apple event and its reply, if any, after you send the event and receive a result (either fromAESendorAESendMessage). You should dispose of the data structures you created even if the sending function returns an error. If you are sending the event asynchronously, you need not wait for the reply Apple event before disposing of the sent Apple event.
## Sending an Apple Event
Once you have created an Apple event, the Apple Event Manager provides two choices for sending it. TheAESendfunction provides more options but higher overhead, while theAESendMessagefunction provides fewer options but less overhead.
### When to Use AESend
TheAESendfunction has parameters for specifying how to handle timeouts, idle processing, and event filtering. It requires your application to link with the entire Carbon framework, which brings in the HIToolbox framework and requires a connection to the window server.
UsingAESendis appropriate only for applications that require the use of idle processing and event filtering. This type of processing is not generally needed, or recommended, for applications that handle events with Carbon event handlers. Therefore, only Carbon applications that use older style event handling are likely to need to useAESend.
Note:If you callAESendand passNULLfor the filter and idle functions,AESendwill call through to the less expensiveAESendMessagefunction.
TheAESendfunction provides these parameters that are not available toAESendMessage:
This parameter is deprecated in Mac OS X.
A universal procedure pointer to a function that handles events (such as update, operating-system, activate, and null events) that your application receives while waiting for a reply. Your idle function can also perform other tasks (such as displaying a delay cursor) while waiting for a reply or a return receipt.
If your application specifies thekAEWaitReplyflag in thesendModeparameter and you wish your application to get periodic time while waiting for the reply to return, you must provide an idle function. Otherwise, you can pass a value ofNULLfor this parameter.
For advice on whether to use idle functions, seeSpecifying Send and Reply Options.
A universal procedure pointer to a function that determines which incoming Apple events should be received while the handler waits for a reply or a return receipt. If your application doesnât need to filter Apple events, you can pass a value ofNULLfor this parameter. If you do so, no application-oriented Apple events are processed while waiting.
### When to Use AESendMessage
TheAESendMessagefunction requires less overhead than theAESendfunction. It also allows you to send Apple events by linking with just the Application Services framework, and not the entire Carbon framework (and window server), as required byAESend.
Using theAESendMessagefunction is appropriate for applications that donât require idle processing and event filtering (most modern Carbon applications), and where any of the following applies:
- Efficiency is a key concern.
Efficiency is a key concern.
- The application has no user interface.
The application has no user interface.
- The application should not link with Carbon.
The application should not link with Carbon.
### Specifying Send and Reply Options
Regardless of which function you use to send Apple events, youâll need to specify certain options, such as how to interact with the user, whether you want a reply Apple event, and if so, how to receive it. You do this by setting flags in thesendModeparameter, present in bothAESendandAESendMessage. Hereâs a brief description of that parameter:
Specifies options for how the server application should handle the Apple event. To obtain a value for this parameter, you add together constants to set bits that specify the reply mode, the interaction level, and possibly flags for other options.
You can read a full description of all the constants for setting send mode flags in the constant section "AESendModeâ inApple Event Manager Reference. But here are some of the more common choices you might make for these flags.
#### Specifying a Reply in the Send Mode Parameter
If you do not want a reply to the Apple event you are sending, you specify thekAENoReplyflag in thesendModeparameter.
If youâre willing to wait a certain amount of time for a reply, specifykAEWaitReplyâthe function does not return until the timeout specified by thetimeoutInTicksparameter expires or the server application returns a reply. When the server application returns a reply, thereplyparameter contains the reply Apple event.
If you specify thekAEWaitReplyflag toAESend, you should provide an idle function to process any non-high-level events that occur while your application is waiting for a reply. You supply a pointer to your idle function as a parameter to theAESendfunction. So that your application can process other Apple events while it is waiting for a reply, you can also specify an optional filter function.
You don't provide an idle function or a filter function when you call theAESendMessagefunction because it doesnât provide parameters for them. If you specifykAEWaitReplytoAESendMessage, it executes in such a way that any timers or event sources added to your run loop are not called while insideAESendMessage.
Rather than wait for a reply, you can send Apple events asynchronously and receive reply events when theyâre ready through normal event processing. To do this, you specify thekAEQueueReplyflag and register a handler for reply events with the event classkCoreEventClassand event IDkAEAnswer. Your application processes reply events in the same way it does other Apple events. This approach is recommended because it is far more efficient than waiting in an idle routine. In addition, it avoids the possibility of getting into odd states, such as loops within loops while waiting for replies as the idle routine processes events.
If you specifykAEWaitReplyorkAEQueueReply, the Apple Event Manager automatically passes a default reply Apple event to the server. The Apple Event Manager returns any nonzero result code from the serverâs handler in thekeyErrorNumberparameter of the reply Apple event. The server can return an error string in thekeyErrorStringparameter of the reply Apple event. The server can also use the reply Apple event to return any data you requestedâfor example, the results of a numeric calculation or a list of misspelled words.
If you specify thekAENoReplyflag, the reply Apple event passed to the server application consists of a null descriptor record.
#### Specifying User Interaction in the Send Mode Parameter
If your Apple event may require the user to interact with the server application (for example, to specify print or file options), you can communicate your user interaction preferences to the server by specifying additional flags in thesendModeparameter. These flags specify the conditions, if any, under which the server application can interact with the user and, if interaction is allowed, whether the server should come directly to the foreground or post a notification request.
The server application specifies its own preferences for user interaction by specifying flags to theAESetInteractionAllowedfunction, as described inInteracting With the User.
### Sending an Apple Event With AESend
Listing 6-7shows how you can build an Apple event withAEBuildAppleEventand send the event withAESend.
Listing 6-7Sending an Apple event with the AESend function
```applescript
OSErr err = noErr;
```
```applescript
AppleEvent revealEvent;
```
```applescript
```
```applescript
err = BuildRevealStartupDiskAE(&revealEvent);// 1
```
```applescript
```
```applescript
if (err == noErr)
```
```applescript
{
```
```applescript
err = AESend(&revealEvent,// 2
```
```applescript
NULL, // No reply event needed.// 3
```
```applescript
kAENoReply | kAECanInteract,// 4
```
```applescript
kAENormalPriority,// Normal priority.// 5
```
```applescript
kAEDefaultTimeout,// Let AE Mgr decide on timeout.// 6
```
```applescript
NULL, // No idle function.// 7
```
```applescript
NULL); // No filter function.// 8
```
```applescript
```
```applescript
err = AEDisposeDesc(&revealEvent);// 9
```
```applescript
}
```
Hereâs how the code inListing 6-7works:
- Calls the application-defined functionBuildRevealStartupDiskAE, shown inListing 6-4, to build an Apple event that tells the Finder to reveal the startup disk.
Calls the application-defined functionBuildRevealStartupDiskAE, shown inListing 6-4, to build an Apple event that tells the Finder to reveal the startup disk.
- Calls the functionAESend, passing the Apple event obtained by the previous function call. The next several items describe the remaining parameters you pass to theAESendfunction.
Calls the functionAESend, passing the Apple event obtained by the previous function call. The next several items describe the remaining parameters you pass to theAESendfunction.
- PassesNULLfor the reply event because no reply is expected.
PassesNULLfor the reply event because no reply is expected.
- Passes a logical combination of constants indicating that no reply is expected and that interaction with the user is allowed (although none is likely for this event).In the case where your application wants an asynchronous reply and does not allow interaction, you would passkAEQueueReply | kAENeverInteract.
Passes a logical combination of constants indicating that no reply is expected and that interaction with the user is allowed (although none is likely for this event).
In the case where your application wants an asynchronous reply and does not allow interaction, you would passkAEQueueReply | kAENeverInteract.
- Passes a constant indicating the event should have normal priority. However, priority is ignored on Mac OS X.
Passes a constant indicating the event should have normal priority. However, priority is ignored on Mac OS X.
- Passes a constant indicating the Apple Event Manager should use the default timeout length (usually about thirty seconds). You can, instead, pass a specific value for the number of ticks (sixtieths of a second) to delay.
Passes a constant indicating the Apple Event Manager should use the default timeout length (usually about thirty seconds). You can, instead, pass a specific value for the number of ticks (sixtieths of a second) to delay.
- PassesNULL, indicating it will not use an idle function (needed only in specific cases where your application waits for a reply).
PassesNULL, indicating it will not use an idle function (needed only in specific cases where your application waits for a reply).
- PassesNULL, indicating it will not use a filter function (needed, in conjunction with an idle function, only in specific cases where your application waits for a reply).
PassesNULL, indicating it will not use a filter function (needed, in conjunction with an idle function, only in specific cases where your application waits for a reply).
- CallsAEDisposeDescto dispose of the Apple event.In cases where you expect a reply Apple event, your application should dispose of that event as well, once it is finished with it. If the reply is handled asynchronously, dispose of the reply event in the reply handler.
CallsAEDisposeDescto dispose of the Apple event.
In cases where you expect a reply Apple event, your application should dispose of that event as well, once it is finished with it. If the reply is handled asynchronously, dispose of the reply event in the reply handler.
In this example, the call toAESenddoes not supply an idle function or a filter function. As a result,AESendwill fall through and call theAESendMessagefunction, which has less overhead. When you donât require idle and filter functions, you can, of course, callAESendMessagedirectly, as described in the next section.
As noted inSpecifying a Reply in the Send Mode Parameter, even in the case where your application expects a delayed reply to an Apple event it sends, the most efficient mechanism is to ask for queued replies and register a handler to receive them.
### Sending an Apple Event With AESendMessage
Listing 6-8shows how you can send an Apple event withAESendMessage.
Listing 6-8Sending an Apple event with the AESendMessage function
```applescript
OSErr err = noErr;
```
```applescript
AppleEvent revealEvent;
```
```applescript
```
```applescript
err = BuildRevealStartupDiskAE(&revealEvent);// 1
```
```applescript
```
```applescript
if (err == noErr)
```
```applescript
{
```
```applescript
err = AESendMessage(&revealEvent,// 2
```
```applescript
NULL,// 3
```
```applescript
kAENoReply | kAENeverInteract,// 4
```
```applescript
kAEDefaultTimeout);// 5
```
```applescript
```
```applescript
err = AEDisposeDesc(&revealEvent);// 6
```
```applescript
}
```
Hereâs how the code inListing 6-7works:
- Calls the application-defined functionBuildRevealStartupDiskAE, shown inListing 6-4, to build an Apple event that tells the Finder to reveal the startup disk.
Calls the application-defined functionBuildRevealStartupDiskAE, shown inListing 6-4, to build an Apple event that tells the Finder to reveal the startup disk.
- Calls the functionAESendMessage, passing the Apple event obtained by the previous function call. The next several items describe the remaining parameters you pass to theAESendMessagefunction.
Calls the functionAESendMessage, passing the Apple event obtained by the previous function call. The next several items describe the remaining parameters you pass to theAESendMessagefunction.
- PassesNULLfor the reply event because no reply is expected.
PassesNULLfor the reply event because no reply is expected.
- Passes a logical combination of constants indicating that no reply is expected and that interaction with the user is not allowed.
Passes a logical combination of constants indicating that no reply is expected and that interaction with the user is not allowed.
- Passes a constant indicating the Apple Event Manager should use the default timeout length (usually about thirty seconds). You can, instead, pass a specific value for the number of ticks (sixtieths of a second) to delay.
Passes a constant indicating the Apple Event Manager should use the default timeout length (usually about thirty seconds). You can, instead, pass a specific value for the number of ticks (sixtieths of a second) to delay.
- CallsAEDisposeDescto dispose of the Apple event.
CallsAEDisposeDescto dispose of the Apple event.
## Handling a Reply Apple Event
When your application receives a reply event, either as a return parameter from the sending routine or in a return event handler, it uses Apple Event Manager functions to extract the information it needs from the event. This process is the same as the one described inResponding to Apple Events.
Whenever a server application provides an error string parameter in a reply event, it should also provide an error number. However, you canât count on all server applications to do so. A client application should therefore check for both thekeyErrorNumber(for example, seeListing 5-2) andkeyErrorStringparameters before assuming that no error has occurred.
When your application has finished using the reply Apple event, it should dispose of it by calling theAEDisposeDescfunction. The Apple Event Manager takes care of disposing of both the Apple event and the reply Apple event after a server applicationâs handler returns, but the server is responsible for disposing of any data structures it creates while extracting data from the event.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Building an Apple Event
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This chapter provides an overview of Apple event data structures and describes how to build an Apple event.
An Apple event is capable of describing complex commands and the data necessary to carry them out. For example, an Apple event might request that a database application return data from records that meet certain criteria. An event sent by the Mac OS might request that the receiving application print a specified list of documents. The Apple Event Manager provides a relatively small number of Apple event data structures that together can be used to represent commands of great complexity.
Your application typically works with Apple events and the data they contain when:
- It receives an Apple event and must extract information to figure out what to do with the event.
It receives an Apple event and must extract information to figure out what to do with the event.
- In response to a received Apple event, it must add information to a reply event to return to the sender.
In response to a received Apple event, it must add information to a reply event to return to the sender.
- It creates an Apple event from scratch for internal communication or to request data or services from another application.
It creates an Apple event from scratch for internal communication or to request data or services from another application.
Working effectively with Apple events in these cases requires some knowledge of the data structures and organization of an Apple event, as well as familiarity with the Apple Event Manager functions you use to create Apple events and manipulate their data.
## About Apple Event Data Structures
Understanding a few key concepts can help things go smoothly in creating an Apple event or working with its data:
- Each piece of information in an Apple event is associated with a four-character code (or in some cases, two such codes).
Each piece of information in an Apple event is associated with a four-character code (or in some cases, two such codes).
- A descriptor is a data structure that stores data and an accompanying four-character code. All the information you work with in an Apple event is stored in descriptors and lists of descriptors.
A descriptor is a data structure that stores data and an accompanying four-character code. All the information you work with in an Apple event is stored in descriptors and lists of descriptors.
- The content of an Apple event is conceptually divided into two kinds of items, both constructed from descriptors:Attributes identify characteristics of the task to be performed by the Apple event.Parameters provide additional data to be used in performing the task.
The content of an Apple event is conceptually divided into two kinds of items, both constructed from descriptors:
- Attributes identify characteristics of the task to be performed by the Apple event.
Attributes identify characteristics of the task to be performed by the Apple event.
- Parameters provide additional data to be used in performing the task.
Parameters provide additional data to be used in performing the task.
- To create an Apple event, extract data from an event, or add data to an event, an application calls Apple Event Manager functions and passes the appropriate four-character codes and other information.
To create an Apple event, extract data from an event, or add data to an event, an application calls Apple Event Manager functions and passes the appropriate four-character codes and other information.
- To operate effectively with Apple events, you just need to find the right function for the task at hand.
To operate effectively with Apple events, you just need to find the right function for the task at hand.
## Apple Event Building Blocks
This section describes the constants and data structures used to construct an Apple event.
### Apple Event Constants
The Apple Event Manager uses four-character codes (also referred to as Apple event codes) to identify the data within an Apple event. A four-character code is just four bytes of data that can be expressed as a string of four characters in the Mac OS Roman encoding. For example,'capp'is the four-character code that specifies an application.
The Apple Event Manager defines four-character-code constants for many common commands (or verbs) and data objects (or nouns) that can be used in Apple events. These constants are defined primarily in the header filesAppleEvents.handAERegistry.hin the AE framework. They are documented inApple Event Manager Reference. A subset of these constants is described inSelected Apple Event Constantsin this document.
Listing 2-1shows some constants fromAERegistry.h. Each constant definition includes a comment showing the actual numeric value as a hex number.
Listing 2-1Some four-character codes from AERegistry.h
```applescript
enum {
```
```applescript
cApplication = 'capp', /* 0x63617070 */
```
```applescript
cArc = 'carc', /* 0x63617263 */
```
```applescript
cBoolean = 'bool', /* 0x626f6f6c */
```
```applescript
cCell = 'ccel', /* 0x6363656c */
```
```applescript
cChar = 'cha ', /* 0x63686120 */
```
```applescript
cDocument = 'docu', /* 0x646f6375 */
```
```applescript
cGraphicLine = 'glin', /* 0x676c696e */
```
```applescript
...
```
```applescript
};
```
For the Apple event support in your application, you should use existing constants wherever they make sense, rather than defining new constants. For example, if your application supports an Apple event to get the name of a document, you can use the constantcDocumentto denote a document.
Apple reserves all values that consist entirely of lowercase letters and spaces. You can generally avoid conflicts with Apple-defined constants by including at least one uppercase letter when defining a four-character code.
### Event Class and Event ID
An Apple event is uniquely identified by itsevent classandevent IDattributes, each of which is an arbitrary four-character code (described inApple Event Constants). The Apple Event Manager uses these values in dispatching Apple events to code in your application (described inApple Event Dispatching).
Apple defines event class and event ID values for standard Apple events, including those that it sends. For example, adeleteApple event has an event class value of'core'(represented by the constantkAECoreSuite) and an event ID value of'delo'(kAEDelete). For examples and descriptions of Apple-defined event class and event ID values, seeEvent Class Constants,Event ID Constants for Apple Events Sent by the Mac OS, andEvent ID Constants for Standard AppleScript Commands.
You define the event class and event ID values for application-specific Apple events your application supports. While these values are arbitrary, you should follow the simple guidelines described inApple Event Constantsin choosing values.
You can use a common event class for multiple Apple events as a way to group related events that your application supports. For example, many Apple-defined Apple events share a common event class. This can be useful in organizing the name space for your Apple events and may simplify your coding, but it doesnât result in any special treatment by the Apple Event Manager.
If you want other applications to be able to send Apple events to your application, you must publish event class and event ID values for those events. You should also describe the contents your application expects to find in each type of Apple event.
Similarly, if you want to send Apple events to other applications, you are dependent on those applications to provide the event class, event ID, and any other information you need to construct an Apple event the application can understand. One exception is that most applications, including yours, should be able to handle the Apple events described inCommon Apple Events Sent by the Mac OS. So, for example, you might construct aquitApple event that targets almost any Mac OS X application, and expect the application to handle it.
### Descriptors, Descriptor Lists, and Apple Events
Descriptors and descriptor lists are the basic structural elements used in Apple events. Adescriptorstores data and an accompanying descriptor type to form the basic building block of all Apple Events. Thedescriptor typeis a four-character code that identifies the type of data associated with the descriptor.Table B-4lists constants for some of the main descriptor typesâfor a complete list, seeApple Event Manager Reference.Figure 2-1shows the format of a descriptor.
The data field of a descriptor is opaqueâyou should not attempt to access it directly.Table A-1lists functions provided by the Apple Event Manager for accessing the data in a descriptor (and related data types).
Figure 2-2shows a descriptor with a descriptor type oftypeUTF8Text, which specifies that the descriptorâs data is text in UTF-8 encodingâin this case, the text is âSummary of Salesâ.
Akeywordis a four-character code used by the Apple Event Manager to identify a specific descriptor within an Apple event. Akeyword-specified descriptorcombines a keyword with a descriptor. This is the basic type used to specify attributes and parameters, which are described in detail inApple Event Attributes and Parameters.Figure 2-3shows the format of a keyword-specified descriptor.
Anaddress descriptoris a descriptor that specifies a target address for an Apple eventâthat is, it specifies the application or other process to send the event to. The descriptor type can be specified by one of the constants shown inTable B-5.
Adescriptor listis a descriptor whose data consists of a list of zero or more descriptors (it can be an empty list). A descriptor list can contain other lists, which allows for the construction of complex descriptors, and hence complex Apple events.Figure 2-4shows the format of a descriptor list.
AnApple event recordis a descriptor list whose data is a set of keyword-specified descriptors that describe Apple event parameters.
AnApple eventis an Apple event record whose contents are conceptually divided into two parts, one for attributes and one for parameters, as shown inFigure 2-6.
Figure 2-5shows the inheritance for descriptors and related data structures, with the corresponding data types shown in parentheses.
An Apple Event Manager function that operates on one of these data structures can also operate on any type that inherits from it. For example, Apple events inherit from Apple event records, which inherit from descriptor lists. As a result, you can pass an Apple event to any Apple Event Manager function that expects an Apple event record or a descriptor list. Similarly, you can pass Apple events and Apple event records, as well as descriptor lists and descriptors, to any Apple Event Manager function that expects a descriptor. SeeTable A-1for a list of functions for working with the various data types.
### Apple Event Attributes and Parameters
Every Apple event consists of attributes and, often, parameters, as shown inFigure 2-6. Taken together, the attributes of an Apple event denote the task to be performed, while the parameters provide additional information to be used in performing the task.
You use Apple Event Manager functions to create an Apple event, to add attributes or parameters to an Apple event, and to extract and examine the attributes or parameters from an Apple event.
#### Apple Event Attributes
AnApple event attributeis a keyword-specified descriptor that identifies a characteristic of an Apple event. For example, every Apple event must include attributes for event class, event ID, and target address:
- The event classand event IDattributes provide a pair of arbitrary four-character codes that together uniquely identify an Apple event. For more information, seeEvent Class and Event ID.
The event classand event IDattributes provide a pair of arbitrary four-character codes that together uniquely identify an Apple event. For more information, seeEvent Class and Event ID.
- Thetarget address attributespecifies the process to send the Apple event to.
Thetarget address attributespecifies the process to send the Apple event to.
Apple events can include other kinds of attributesâseeTable B-6for a list of keyword constants for Apple event attributes.
#### Apple Event Parameters
AnApple event parameteris a keyword-specified descriptor that contains additional data for the command. Keywords for common Apple event parameters are shown inTable B-7.
As with attributes, there are various kinds of Apple event parameters. Adirect parameterusually specifies the data to be acted upon by the target application. For example,Figure 2-7shows the main Apple event attributes and the direct parameter for anopen documentsevent that targets the AppleWorks application. The direct parameter specifies a descriptor list containing file aliases to the documents to open. An Apple event has at most one direct parameter.
Apple event parameters can contain standard data types, such as text strings, integers of various lengths, Boolean values, and others, listed inTable B-4.
An Apple event can include other parameters, in addition to the direct parameter. For example, an Apple event that represents an arithmetic operation might contain a direct parameter that specifies a pair of values to operate on, as well as an additional parameter that specifies the operator. A reply Apple event may contain an error number parameter and an error string parameter, added by your application when an error occurs, as described inReturning Error Information.
#### Accessing Attributes and Parameters
Your application cannot examine the attributes and parameters of an assembled Apple event directly. Instead, it calls Apple Event Manager functions such asAEGetAttributeDescandAEGetParamDescto request an attribute or parameter by keyword. Because attributes and parameters are descriptors, you can also operate on them by index, using the functionsAEGetNthDescorAEGetNthPtr. However, that only makes sense if, for example, you are iterating over every descriptorâyou should not assume that the parameters or attributes in an Apple event are in any particular order.
Apple event parameters often contain descriptions of Apple event objects within the target application. For example, aget dataApple event contains a parameter that describes the Apple event object that contains the requested data. Thus, an event might request, for example, the first paragraph of text from a named document. Apple event objects are described inâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
For more information on accessing attributes and parameters in an Apple event, seeWorking With the Data in an Apple Event.
#### Optional Parameters
An Apple event may be defined so that it has optional parameters. Anoptional parameteris one that the sending application may or may not include. A target application must be prepared to handle the event whether or not the optional parameter is present. However, it can choose to ignore an optional parameter, even if present. This allows optional parameters to be added to an Apple event retroactively, without breaking existing code.
If an optional parameter is not present, or if your application chooses to ignore it, you should provide the default behavior for the Apple event. To determine if an optional parameter is present, you call a function such asAEGetParamDesc, specifying the keyword for the parameter. If the function returns successfully, you can extract information from the parameter and respond accordingly. If the function returns an error, you can assume the parameter is not present and provide the default behavior.
## Two Approaches to Creating an Apple Event
How do you put together the data structures described in this chapter to create an Apple event? The Apple Event Manager provides functions that lend themselves to two main approaches, which you can combine as needed:
- You can create an Apple event with one call, passing all the information needed for a complete Apple event.Related functions allow you to create a complex descriptor, attribute, or parameter and add it to an existing Apple event in one step.
You can create an Apple event with one call, passing all the information needed for a complete Apple event.
Related functions allow you to create a complex descriptor, attribute, or parameter and add it to an existing Apple event in one step.
- You can create an Apple event sequentially, by first creating a potentially incomplete event, then adding information to it with subsequent calls.With this approach, you build descriptors into more complex data structures from the bottom up.
You can create an Apple event sequentially, by first creating a potentially incomplete event, then adding information to it with subsequent calls.
With this approach, you build descriptors into more complex data structures from the bottom up.
In either case, your application relies on the Apple Event Manager to construct Apple event data structures based on the arguments you pass.
Note:There is a third way, not shown in this document, to create Apple event records and Apple event descriptors using stream-oriented calling conventions. The stream APIs are documented inApple Event Manager Reference, while Technical Note 2046AEStream and Friendsprovides conceptual overview and examples. You can use the stream functions independently, or combine them with the other mechanisms.
### Creating an Apple Event in One Step
You can call theAEBuildAppleEventfunction to create an Apple event in one step. To do so, you pass event class, event ID, and other information that is used to create the Apple eventâs attributes. TheAEBuildAppleEventfunction includes parameters for specifying the target addressâyou donât have to separately create an address descriptor. You may need to prepare data youâll pass toAEBuildAppleEventâfor example, you may need to create aliases to files you will insert into the Apple event as a descriptor list.
Note:In this discussion, the word âparameterâ is overloaded. When you callAEBuildAppleEvent, you pass information infunction parametersto specify how to createApple event parameters(and attributes), which are just Apple event data structures.
In addition, you provide a specially formatted string, similar to the string you might pass to aprintffunction, along with parameters that specify the data that corresponds to items in the format string. As a result,AEBuildAppleEventcan also create the parameters for your Apple event, resulting in a full-fledged Apple event.
The Apple Event Manager also provides theAEBuildDescfunction as a one-step mechanism for adding potentially complex descriptors to an existing Apple event, and theAEBuildParametersfunction for adding parameters or attributes.
The one-step functions are most useful in situations where your application knows in advance all the information needed to create an Apple event or other data structure. They also make it easier to do parameterized substitution of values. For an example of this approach, seeCreating an Apple Event With AEBuildAppleEvent.
### Creating an Apple Event Sequentially
You can create the basic structure for an Apple event by calling theAECreateAppleEventfunction. You pass information specifying event class, event ID, target address, return ID, and transaction ID; the function creates an Apple event containing the corresponding attributes. However, before you can callAECreateAppleEvent, you have to create a target address descriptor to pass to it, using a function such asAECreateDesc.
After callingAECreateAppleEvent, the resulting Apple event contains attributes for the event but no parameters. To add parameters to the event, you can use theAEBuildDescandAEBuildParametersfunctions described in the previous section, or you can continue to work sequentially. For example, if the direct object of the event you are creating is a list of file aliases, you could create it sequentially by performing the following steps:
- CallAECreateDesconce for each file alias to create a descriptor for it.
CallAECreateDesconce for each file alias to create a descriptor for it.
- CallAECreateListto create a descriptor list.
CallAECreateListto create a descriptor list.
- CallAEPutDesconce for each descriptor to add it to the descriptor list.
CallAEPutDesconce for each descriptor to add it to the descriptor list.
- CallAEPutParamDescto add the descriptor list to the Apple event as a parameter.
CallAEPutParamDescto add the descriptor list to the Apple event as a parameter.
This sequential approach is most useful for creating simple Apple events, or in situations where your application must factor the creation of an Apple event across several layers of codeâfor example, where you create an event, then pass it to various subsystems to add data to it.
For an example of how to create an Apple event step by step, seeCreating an Apple Event With AECreateAppleEvent.
### The Completed Apple Event
Figure 2-8shows the main data structures of a complete Apple event, containing a list of keyword-specified descriptors that specify the attributes and parameters of anopen documentsApple event. Although this is an event sent to your application by the Mac OS, events you create have a similar structure.
The figure includes attributes for the event class, event ID, and target address. It also shows the direct parameterâa keyword-specified descriptor with the keywordkeyDirectObject. The entire figure corresponds to theopen documentsevent shown inFigure 2-7.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# About Apple Events
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This chapter provides an overview of when and how applications use Apple events, with links to more detailed information on those topics. It also provides a brief description of the framework and language support available for working with Apple events in Mac OS X.
AnApple eventis a type of interprocess message that can encapsulate commands and data of arbitrary complexity. Apple events provide a data transport and event dispatching mechanism that can be used within a single application, between applications on the same computer, and between applications on different computers connected to a network. The Mac OS uses Apple events to communicate with applications.
Apple events are part of theOpen Scripting Architecture (OSA), which provides a standard and extensible mechanism for interapplication communication in Mac OS X. The OSA is described inAppleScript Overview.
Note:Apple events are not always the most efficient or appropriate method for communicating between processes. Mac OS X offers other mechanisms, including distributed objects, notifications, sockets, ports, streams, shared memory, and Mach messaging. These mechanisms are described in âInterprocess Communicationâ inSystem-Level TechnologiesinMac Technology Overview.
## A Quick Look at Working With Apple Events
Apple events are designed to provide a flexible mechanism for interprocess communication. An Apple event specifies a target application (or other process) and provides a detailed description of an operation to perform. The operating system locates the target, delivers the event and, if necessary, delivers a reply Apple event back to the sender. While simple in concept, this mechanism provides a basis for powerful interaction between processes and for automating tasks that use multiple applications.
### When Applications Use Apple Events
An application is most likely to work with Apple events for the following reasons:
- To respond to Apple events received from the Mac OS.For applications that present a graphical user interface, Mac OS X sends Apple events to initiate certain operations, such as launching or quitting the application.For Cocoa applications, most of the work of responding to these events happens automatically. Carbon applications need to provide more of their own implementationâfor details, seeHandling Apple Events Sent by the Mac OS.
To respond to Apple events received from the Mac OS.
For applications that present a graphical user interface, Mac OS X sends Apple events to initiate certain operations, such as launching or quitting the application.
For Cocoa applications, most of the work of responding to these events happens automatically. Carbon applications need to provide more of their own implementationâfor details, seeHandling Apple Events Sent by the Mac OS.
- To make its services or data available to other processes.Most applications that provide services through Apple events are scriptable applicationsâthey provide a scripting terminology that lets users write AppleScript scripts to access the applicationâs operations and data. When a script is executed, some of its statements result in Apple events being sent to the application. Other applications can also send Apple events directly to scriptable applications.Scriptable applications make it possible for users to automate their work. And starting in Mac OS X version 10.4, your scriptable application can also provide users with Automator actions. (Automator is an application that lets users work in a graphical interface to put together complex, automated workflows, made up of actions that perform discrete operations.)Scriptable Carbon applications can use the techniques for working with Apple events that are described throughout this document. For information on scriptable Cocoa applications, seeFramework and Language Support.For information on designing and creating scriptable applications, and on creating Automator actions, see the learning paths inGetting Started with AppleScript.
To make its services or data available to other processes.
Most applications that provide services through Apple events are scriptable applicationsâthey provide a scripting terminology that lets users write AppleScript scripts to access the applicationâs operations and data. When a script is executed, some of its statements result in Apple events being sent to the application. Other applications can also send Apple events directly to scriptable applications.
Scriptable applications make it possible for users to automate their work. And starting in Mac OS X version 10.4, your scriptable application can also provide users with Automator actions. (Automator is an application that lets users work in a graphical interface to put together complex, automated workflows, made up of actions that perform discrete operations.)
Scriptable Carbon applications can use the techniques for working with Apple events that are described throughout this document. For information on scriptable Cocoa applications, seeFramework and Language Support.
For information on designing and creating scriptable applications, and on creating Automator actions, see the learning paths inGetting Started with AppleScript.
- To communicate directly with other applications.An application can send an Apple event to ask another application to perform an operation or return data. For example, you might create a scriptable server application, running locally or remotely. Your other applications create Apple events and send them to the scriptable server to access its services. This is, in effect, another way to factor your code, with the shared functionality made available through Apple events.
To communicate directly with other applications.
An application can send an Apple event to ask another application to perform an operation or return data. For example, you might create a scriptable server application, running locally or remotely. Your other applications create Apple events and send them to the scriptable server to access its services. This is, in effect, another way to factor your code, with the shared functionality made available through Apple events.
- To support recording in a scriptable application.Recordingrefers to the assemblingof Apple events that represent a userâs actions into a script. Users can turn on recording in the Script Editor application, then perform actions with scriptable applications that support recording. Any Apple events generated by those actions are recorded into an AppleScript script. To support recording as fully as possible, you can take these steps:Factor code that implements the user interface in your application from code that actually performs operationsâthis is a standard approach for applications that follow the model-view-controller design paradigm.Send Apple events within the application to connect these two parts of your application. The Apple Event Manager provides a mechanism for doing this with a minimum of overhead, described inAddressing an Apple Event for Direct Dispatching.Make sure that any significant action within your application generates an Apple event that can be recorded in a script.Recording is beyond the scope of this document, but you can read more about it in the sectionsâRecordable ApplicationsâandâMaking Your Application RecordableâinInside Macintosh: Interapplication Communication.
To support recording in a scriptable application.
Recordingrefers to the assemblingof Apple events that represent a userâs actions into a script. Users can turn on recording in the Script Editor application, then perform actions with scriptable applications that support recording. Any Apple events generated by those actions are recorded into an AppleScript script. To support recording as fully as possible, you can take these steps:
- Factor code that implements the user interface in your application from code that actually performs operationsâthis is a standard approach for applications that follow the model-view-controller design paradigm.
Factor code that implements the user interface in your application from code that actually performs operationsâthis is a standard approach for applications that follow the model-view-controller design paradigm.
- Send Apple events within the application to connect these two parts of your application. The Apple Event Manager provides a mechanism for doing this with a minimum of overhead, described inAddressing an Apple Event for Direct Dispatching.
Send Apple events within the application to connect these two parts of your application. The Apple Event Manager provides a mechanism for doing this with a minimum of overhead, described inAddressing an Apple Event for Direct Dispatching.
- Make sure that any significant action within your application generates an Apple event that can be recorded in a script.
Make sure that any significant action within your application generates an Apple event that can be recorded in a script.
Recording is beyond the scope of this document, but you can read more about it in the sectionsâRecordable ApplicationsâandâMaking Your Application RecordableâinInside Macintosh: Interapplication Communication.
### Apple Event Terminology
A scriptable application specifies the terminology that can be used in scripts that target the application. There are currently three formats for this information:
- aete:This is the original dictionary format and is still used in Carbon applications. The name comes from the Resource Manager resource type in which the information is stored ('aete').
aete:This is the original dictionary format and is still used in Carbon applications. The name comes from the Resource Manager resource type in which the information is stored ('aete').
- script suite:This is the original format used by Cocoa applications. A script suite contains a pair of information property list (plist) files.
script suite:This is the original format used by Cocoa applications. A script suite contains a pair of information property list (plist) files.
- sdef:âsdefâ is short for âscripting definition.â This XML-based format is a superset of the other two formats and supports additional features.
sdef:âsdefâ is short for âscripting definition.â This XML-based format is a superset of the other two formats and supports additional features.
For more information on these formats, including pointers to additional documentation, see "Scriptable Applications" inOpen Scripting ArchitectureinAppleScript Overview.
### Sending and Receiving Apple Events
Applications typically use Apple events to request services and information from other applications or to provide services and information in response to such requests. In client-server terms, theclient applicationsends an Apple event to request a service or information from theserver application. The recipient of an Apple event is also known as thetarget applicationbecause it is the target of the event. A client application must know which kinds of Apple events the server supports.
Figure 1-1shows two applications communicating with Apple events. The client uses Apple Event Manager functions to create and send an Apple event to the server, the FileMaker Pro database application. The event might, for example, request employee information from a payroll database. FileMaker Pro uses other Apple Event Manager functions to extract information from the event and identify the requested operation. Depending on the event, FileMaker Pro may need to add a record, delete a record, or return specified information in a reply Apple event.
The most common Apple event client is a script editor application executing an AppleScript script. Statements in a script that target an application may result in Apple events being sent to the application. Another common client is the Mac OS, which sends Apple events to applications to open documents and perform other operations.
The most common servers are scriptable applications and scriptable parts of the Mac OS, such as the Finder and the System Events application (located in/System/Library/CoreServices). You can read more about script editors and scriptable applications inAppleScript Overview.
### Responding to Apple Events
Your application should be prepared to respond to Apple events sent by the Mac OS, as well as to other Apple events the application supports. An Apple event typically contains information that specifies the target application, the action to perform, and optionally the objects on which to operate. For example,Figure 1-2shows anopen documentsApple event sent by Mac OS X to the AppleWorks application. This type of Apple event provides a list of files for the target application to open.
For an application to handle a specific Apple event such as theopen documentsevent, it must register with the Apple Event Manager a function that handles events of that type. The Apple Event Manager dispatches a received Apple event to the handler registered for it. AnApple event handleris an application-defined function that extracts pertinent data from an Apple event, performs the requested action, and if necessary, returns a result.
## How to Use Apple Events
The steps your application takes in working with Apple events will differ, depending on whether it is responding to Apple events or creating and sending them.
### Steps for Responding to Apple Events
To respond to Apple events in your application, you perform steps like the following:
- Determine which Apple events your application will support.
Determine which Apple events your application will support.
- Make sure your application can receive Apple events and dispatch them to a function that can handle them.Write functions that handle the Apple events you support.Register the functions with the Apple Event Manager so it can dispatch events to them.
Make sure your application can receive Apple events and dispatch them to a function that can handle them.
- Write functions that handle the Apple events you support.
Write functions that handle the Apple events you support.
- Register the functions with the Apple Event Manager so it can dispatch events to them.
Register the functions with the Apple Event Manager so it can dispatch events to them.
- Call Apple Event Manager functions to extract information from received Apple events and locate specified items in your application.Note:Locating objects in your application is not covered in this documentâfor details, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
Call Apple Event Manager functions to extract information from received Apple events and locate specified items in your application.
Note:Locating objects in your application is not covered in this documentâfor details, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
- Perform the actions specified by received Apple events.
Perform the actions specified by received Apple events.
- If necessary, add information to a reply Apple event (sent to you as part of a received Apple event).If an error occurs, return an error code; you can also add error information to the reply event.
If necessary, add information to a reply Apple event (sent to you as part of a received Apple event).
If an error occurs, return an error code; you can also add error information to the reply event.
For guidelines and sample code for performing these steps, seeApple Event DispatchingandResponding to Apple Events.
### Steps for Creating and Sending Apple Events
To create and send Apple events in your application, you perform steps like the following:
- Create an Apple event.The Apple Event Manager provides functions for building an Apple event in one step and for creating an Apple event and adding information to it as a sequence of steps.
Create an Apple event.
The Apple Event Manager provides functions for building an Apple event in one step and for creating an Apple event and adding information to it as a sequence of steps.
- Send the Apple event.The Apple Event Manager provides functions for sending an event with more options and more overhead, or with less options and less overhead.You will have to specify information such asthe target application to send the Apple event tohow to handle a timeout (in case the target doesnât respond)whether to allow interaction with the user (for example, if the Apple event might result in showing a dialog)
Send the Apple event.
The Apple Event Manager provides functions for sending an event with more options and more overhead, or with less options and less overhead.
You will have to specify information such as
- the target application to send the Apple event to
the target application to send the Apple event to
- how to handle a timeout (in case the target doesnât respond)
how to handle a timeout (in case the target doesnât respond)
- whether to allow interaction with the user (for example, if the Apple event might result in showing a dialog)
whether to allow interaction with the user (for example, if the Apple event might result in showing a dialog)
For guidelines and sample code for performing these steps, seeTwo Approaches to Creating an Apple EventandCreating and Sending Apple Events.
## Framework and Language Support
You work with Apple events primarily through the API defined by the Apple Event Manager, which is documented inApple Event Manager Reference. This API is implemented by the AE framework, a subframework of the Application Services framework, and is made available through headers written in the C programming language.
Note:The Apple Event Manager is part of the Open Scripting Architecture. Some Apple-event related functions and constants are not defined in the AE frameworkâthey are defined in other frameworks, as described inOpen Scripting Architectureâ inAppleScript Overview.
Carbon applications that work with Apple events, whether written in C or C++, typically call Apple Event Manager functions directly. Apple also provides C sample code, such asMoreOSL, to help in the implementation of scriptable Carbon applications.
Cocoa applications are written in Objective-C or Java. The Cocoa application framework provides built-in support for AppleScript scripting that allows many applications to be scriptable without working directly with Apple Event Manager functions. The Cocoa application framework also includes classes such asNSAppleEventDescriptor, for working with underlying Apple event data structures, andNSAppleEventManager, for accessing certain Apple Event Manager functions.
However, because Objective-C is a super set of the C language, Cocoa applications written in Objective-C can call Apple Event Manager functions directly and use any of the mechanisms described in this document. For example, a Cocoa application might use Apple Event Manager functions to perform operations that are not currently supported by the Cocoa framework, such as directly sending an Apple event. For details on writing a scriptable Cocoa application, seeCocoa Scripting Guide.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Apple Event Dispatching
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This chapter shows how your application works with the Apple Event Manager to register the Apple events it supports and dispatch those events to the appropriate Apple event handlers. AnApple event handleris an application-defined function that extracts pertinent data from an Apple event, performs the requested action, returns a result code, and if necessary, returns information in a reply Apple event.
Note:For information on how Apple events are dispatched in Cocoa applications, seeHow Cocoa Applications Handle Apple EventsinCocoa Scripting Guide.
## How Apple Event Dispatching Works
Apple event dispatching works by a simple process:
- Your application registers Apple event handler functions with the Apple Event Manager for all the types of Apple events it can work with. A handler may handle just one type of Apple event or multiple types.
Your application registers Apple event handler functions with the Apple Event Manager for all the types of Apple events it can work with. A handler may handle just one type of Apple event or multiple types.
- The Apple Event Manager creates an Apple event dispatch table for your application. Adispatch tablemaps the Apple events your application supports to the Apple event handlers it provides.
The Apple Event Manager creates an Apple event dispatch table for your application. Adispatch tablemaps the Apple events your application supports to the Apple event handlers it provides.
- When your application receives an Apple event, it calls an Apple Event Manager function to process the event. If your dispatch table contains an entry for the event, the Apple Event Manager calls the associated handler.
When your application receives an Apple event, it calls an Apple Event Manager function to process the event. If your dispatch table contains an entry for the event, the Apple Event Manager calls the associated handler.
Note:For your application to respond to Apple events sent from remote computers, a user must open System Preferences, go to Sharing preferences, and select Remote Apple Events in the Services pane.
### Dispatch Tables
You build an Apple event dispatch table by making calls to the functionAEInstallEventHandlerto register (or install) the events your application can handle and the functions that handle them. An Apple event is uniquely identified by the four-character codes specified by its event class and event ID attributes (described inEvent Class and Event ID). These codes are the values your application uses to register event handler functions with the Apple Event Manager, and they are the values stored in the dispatch table. For example, adeleteApple event has an event class value of'core'(represented by the constantkAECoreSuite) and an event ID value of'delo'(kAEDelete).
When you install a handler function for an Apple event, you provide the following information:
- The event class and event ID of the Apple event; you can also specify wildcard values to register a handler for more than one event class or event ID.
The event class and event ID of the Apple event; you can also specify wildcard values to register a handler for more than one event class or event ID.
- The address of the Apple event handlerfor the Apple event.
The address of the Apple event handlerfor the Apple event.
- An optional reference constant for passing additional information to the event handler.
An optional reference constant for passing additional information to the event handler.
- A Boolean value indicating whether the handler should be installed in the application dispatch table or the system dispatch table (you typically install handlers in the application dispatch table).
A Boolean value indicating whether the handler should be installed in the application dispatch table or the system dispatch table (you typically install handlers in the application dispatch table).
If you install a handler and there is already an entry in the dispatch table for the same event class and event ID, the entry is replaced. You can also specifically remove a handler with the functionAERemoveEventHandleror get a handler (if it is present) with the functionAEGetEventHandler.
An Apple event handler should return the valueerrAEEventNotHandledif it does not handle an event that is dispatched to it but wants to allow the event to be redispatched to another handler, if one is available.
You have several options in how you install event handlers:
- You can individually register, by event class and event ID, each of the Apple events that your application supports.If you provide a separate event handler for each event, each handler will always knows exactly which type of event was dispatched to it.If you provide the same handler for more than one event, a handler will need to do some work to determine which event it has received.For example, you might supply a different refcon value for each registered event type so that the event handler can examine its refcon parameter to determine how to respond.Or you might have your handler examine the event ID attribute of the passed Apple event (which requires an additional call to an Apple Event Manager function).
You can individually register, by event class and event ID, each of the Apple events that your application supports.
- If you provide a separate event handler for each event, each handler will always knows exactly which type of event was dispatched to it.
If you provide a separate event handler for each event, each handler will always knows exactly which type of event was dispatched to it.
- If you provide the same handler for more than one event, a handler will need to do some work to determine which event it has received.For example, you might supply a different refcon value for each registered event type so that the event handler can examine its refcon parameter to determine how to respond.Or you might have your handler examine the event ID attribute of the passed Apple event (which requires an additional call to an Apple Event Manager function).
If you provide the same handler for more than one event, a handler will need to do some work to determine which event it has received.
For example, you might supply a different refcon value for each registered event type so that the event handler can examine its refcon parameter to determine how to respond.
Or you might have your handler examine the event ID attribute of the passed Apple event (which requires an additional call to an Apple Event Manager function).
- You can use thetypeWildCardconstantfor either the event class or the event ID (or for both), allowing multiple Apple events to be dispatched to a single handler, while minimizing the number of calls toAEInstallEventHandler. A handler can then examine the actual event class or event ID attribute of a received event to determine how to respond.
You can use thetypeWildCardconstantfor either the event class or the event ID (or for both), allowing multiple Apple events to be dispatched to a single handler, while minimizing the number of calls toAEInstallEventHandler. A handler can then examine the actual event class or event ID attribute of a received event to determine how to respond.
There are several reasons why you might choose to use a wildcard handler. For example, early in the development process, you may want to combine many events in one handler, then add (and register) more specific handlers at a later time. Or your application may support operations on a large number of objects that are nearly identicalârather than install many handlers that duplicate some of their code, you may prefer to install a wildcard handler.
If an Apple event dispatch table contains one entry for an event class and a specific event ID, and another that is identical except that it specifies a wildcard value for the event class or event ID, the Apple Event Manager dispatches to the more specific entry. For example, suppose the dispatch table includes one entry with event classkAECoreSuiteand event IDkAEDelete, and another with event classkAECoreSuiteand event IDtypeWildCard. If the application receives adeleteApple event, it is dispatched to the handler function associated with the event IDkAEDelete.
### The System Dispatch Table
When you callAEInstallEventHandler, you have the option of installing an Apple event handler in the application dispatch table or in the system dispatch table. When an event is dispatched, the Apple Event Manager checks first for a matching handler in the application dispatch table, then in the system dispatch table.
In Mac OS X, you should generally install all handlers in the application dispatch table. For Carbon applications running in Mac OS 8 or Mac OS 9, a handler in the system dispatch table could reside in the system heap, where it would be available to other applications. However, this wonât work in Mac OS X.
Warning:If your application installs a handler in the system heap in Mac OS 8 or Mac OS 9, then quits or crashes without uninstalling the handler, the system is likely to crash the next time another application tries to call that handler.
## Dispatching Apple Events in Your Application
To dispatch Apple events in your application, you perform the following steps:
- Determine which Apple events your application will respond to and write event handler functions for those events.
Determine which Apple events your application will respond to and write event handler functions for those events.
- Call the Apple Event Manager functionAEInstallEventHandlerto install your handlers.
Call the Apple Event Manager functionAEInstallEventHandlerto install your handlers.
- Make sure your application processes Apple events correctly so that they are dispatched to the appropriate handler.The process for this step varies depending on how your application handles events in general.
Make sure your application processes Apple events correctly so that they are dispatched to the appropriate handler.
The process for this step varies depending on how your application handles events in general.
These steps are described in the following sections.
### Determining Which Apple Events to Respond To
All applications that present a graphical user interface through the Human Interface Toolbox should respond to certain events sent by the Mac OS, such as theopen application,open documents, andquitevents. These are described inHandling Apple Events Sent by the Mac OS. These events can also be sent by other applications.
Your application also responds to any Apple events it has specified for working with its commands and data. To handle Apple events that your application defines, it registers handlers for the event class and event ID values you have chosen for those events. As noted, you can register wildcard values to dispatch multiple events to one or more common handlers.
### Installing Apple Event Handlers
Listing 3-1shows how your application callsAEInstallEventHandlerto install an Apple event handler function. The listing assumes that you have defined the functionInstallMacOSEventHandlersto install handlers for Apple events that are sent by the Mac OSâthat function is shown inListing 5-6.
Listing 3-1also assumes you have defined the functionsHandleGraphicAEandHandleSpecialGraphicAEto handle Apple events that operate on graphic objects used by your application. That function is not shown, but other event handlers are described inResponding to Apple Events.
Listing 3-1Installing event handlers for various Apple events
```applescript
static OSErr InstallAppleEventHandlers(void)
```
```applescript
{
```
```applescript
OSErr err;
```
```applescript
```
```applescript
err = InstallMacOSEventHandlers();
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
err = AEInstallEventHandler(kMyGraphicEventClass, kSpecialID,
```
```applescript
NewAEEventHandlerUPP(HandleSpecialGraphicAE), 0, false);// 1
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
err = AEInstallEventHandler(kMyGraphicEventClass, typeWildCard,
```
```applescript
NewAEEventHandlerUPP(HandleGraphicAE), 0, false);// 2
```
```applescript
require_noerr(err, CantInstallAppleEventHandler);
```
```applescript
```
```applescript
CantInstallAppleEventHandler:
```
```applescript
return err;
```
```applescript
}
```
InListing 3-1, the application-defined functionInstallAppleEventHandlersuses the macrorequire_noerr(defined inAssertMacros.h) to check the return value of each function. If an error occurs, it jumps to an error label. The function always returns an error value, which can benoErrif no error occurred.
The following descriptions apply to the numbered lines inListing 3-1:
- The application-defined functionHandleSpecialGraphicAEhandles Apple events that deal with one specific type of graphic object supported by the application, identified by the event classkMyGraphicEventClassand event IDkSpecialID.
The application-defined functionHandleSpecialGraphicAEhandles Apple events that deal with one specific type of graphic object supported by the application, identified by the event classkMyGraphicEventClassand event IDkSpecialID.
- The application-defined functionHandleGraphicAEhandles Apple events that deal with the applicationâs other graphic objects. It is installed with an event ID oftypeWildCard, an Apple Event Manager constant that matches any event ID. As a result, theHandleGraphicAEfunction will be called to handle any received Apple event with event classkMyGraphicEventClass, except those with the event IDkSpecialID.
The application-defined functionHandleGraphicAEhandles Apple events that deal with the applicationâs other graphic objects. It is installed with an event ID oftypeWildCard, an Apple Event Manager constant that matches any event ID. As a result, theHandleGraphicAEfunction will be called to handle any received Apple event with event classkMyGraphicEventClass, except those with the event IDkSpecialID.
Both of the numbered calls toAEInstallEventHandlerprovide the event class, event ID, and address of an Apple event handler. TheNewAEEventHandlerUPPfunction creates a universal procedure pointer to a handler function. The value of0passed for the reference constant indicates the application does not need to pass additional information to the event handler function.
Each call toAEInstallEventHandleralso passes a Boolean value offalse, indicating the handler should be installed in the application dispatch table, not the system dispatch table.
### Processing Apple Events
How your application processes Apple events depends on how it processes events in generalâwhether it uses the modern Carbon event model (described inCarbon Event Manager Programming Guide), or relies on the olderWaitNextEventfunction. In either case, your application receives events from the operating system, some of which represent Apple events. The application dispatches these events to its Apple event handlers by calling the Apple Event Manager functionAEProcessAppleEvent.
Figure 3-1provides a conceptual view of the dispatching mechanism. It shows the flow of control between the AppleWorks application and the Apple Event Manager when the application receives anopen documentsevent and callsAEProcessAppleEvent.
TheAEProcessAppleEventfunction takes an event of typeEventRecordand looks up the Apple event it refers to in the applicationâs dispatch table. If it finds a handler function for the Apple event, it calls the function, passing the Apple event.
The following sections describe in detail how an application calls theAEProcessAppleEventfunction.
#### Processing Apple Events With the Carbon Event Model
An application that uses the Carbon event modelreceives each Apple event as a Carbon event of type{kEventClassAppleEvent, kEventAppleEvent}. For applications that call theRunApplicationEventLoopfunction to process Carbon events, theAEProcessAppleEventfunction is called automatically, and dispatches received Apple events as shown inFigure 3-1.
Applications that use the Carbon event model but do not callRunApplicationEventLoopmust install a Carbon event handler to process Apple events.Listing 3-2shows how you might install such a handlerâin this case, namedAEHandler.
Listing 3-2Installing a Carbon event handler to handle Apple events
```applescript
const EventTypeSpec kEvents[] = {{kEventClassAppleEvent, kEventAppleEvent}};
```
```applescript
```
```applescript
InstallApplicationEventHandler(NewEventHandlerUPP(AEHandler),
```
```applescript
GetEventTypeCount(kEvents), kEvents, 0, NULL);
```
Your Carbon event handler for Apple events must perform these steps:
- Remove the Carbon event of type{kEventClassAppleEvent, kEventAppleEvent}from the event queue before dispatching the Apple Event inside it.The process of removing the event from the queue triggers a synchronization with the Apple Event Manager that allows the next call toAEProcessAppleEventto dispatch the Apple event properly. If the handler doesnât remove the Carbon event from the queue, the application will end up dispatching the wrong Apple event.
Remove the Carbon event of type{kEventClassAppleEvent, kEventAppleEvent}from the event queue before dispatching the Apple Event inside it.
The process of removing the event from the queue triggers a synchronization with the Apple Event Manager that allows the next call toAEProcessAppleEventto dispatch the Apple event properly. If the handler doesnât remove the Carbon event from the queue, the application will end up dispatching the wrong Apple event.
- CallConvertEventRefToEventRecordto get anEventRecordto pass toAEProcessAppleEvent.
CallConvertEventRefToEventRecordto get anEventRecordto pass toAEProcessAppleEvent.
- CallAEProcessAppleEvent.
CallAEProcessAppleEvent.
- ReturnnoErrto indicate the Carbon event has been handled (which does not depend on whether the dispatched Apple event is handled by the application).
ReturnnoErrto indicate the Carbon event has been handled (which does not depend on whether the dispatched Apple event is handled by the application).
Listing 3-3shows a version of theAEHandlerfunction.
Listing 3-3A handler for a Carbon event that represents an Apple event
```applescript
OSStatus AEHandler(EventHandlerCallRef inCaller, EventRef inEvent, void* inRefcon)
```
```applescript
{
```
```applescript
Boolean release = false;
```
```applescript
EventRecord eventRecord;
```
```applescript
OSErr ignoreErrForThisSample;
```
```applescript
```
```applescript
// Events of type kEventAppleEvent must be removed from the queue
```
```applescript
// before being passed to AEProcessAppleEvent.
```
```applescript
if (IsEventInQueue(GetMainEventQueue(), inEvent))
```
```applescript
{
```
```applescript
// RemoveEventFromQueue will release the event, which will
```
```applescript
// destroy it if we don't retain it first.
```
```applescript
RetainEvent(inEvent);
```
```applescript
release = true;
```
```applescript
RemoveEventFromQueue(GetMainEventQueue(), inEvent);
```
```applescript
}
```
```applescript
```
```applescript
// Convert the event ref to the type AEProcessAppleEvent expects.
```
```applescript
ConvertEventRefToEventRecord(inEvent, &eventRecord);
```
```applescript
ignoreErrForThisSample = AEProcessAppleEvent(&eventRecord);
```
```applescript
```
```applescript
if (release)
```
```applescript
ReleaseEvent(inEvent);
```
```applescript
```
```applescript
// This Carbon event has been handled, even if no AppleEvent handlers
```
```applescript
// were installed for the Apple event.
```
```applescript
return noErr;
```
```applescript
}
```
If your application has not installed a handler for a received Apple event, the event may be handled by a handler installed by the system. For example, if your application callsRunApplicationEventLoop, a simplequit applicationhandler is installed automatically. But if you callAEProcessAppleEventfor an event for which there is no handler installed, the event is ignored.
#### Processing Apple Events With WaitNextEvent
A Carbon application that uses theWaitNextEventfunction, rather than the Carbon event model, receives an Apple event in its event loop as a standard event record (typeEventRecord), identified by the constantkHighLevelEvent. The application passes these events toAEProcessAppleEvent, as shown in the following code listings.
Listing 3-4shows a simplified main event loop function which continually loops, getting events and calling theHandleEventfunction (inListing 3-5) to process them.
Listing 3-4A main event loop
```applescript
static void MainEventLoop()
```
```applescript
{
```
```applescript
RgnHandle cursorRgn;
```
```applescript
Boolean gotEvent;
```
```applescript
EventRecord event;
```
```applescript
```
```applescript
cursorRgn = NULL;
```
```applescript
while(!gQuit)
```
```applescript
{
```
```applescript
gotEvent = WaitNextEvent(everyEvent, &event, 32767L, cursorRgn);
```
```applescript
```
```applescript
if (gotEvent)
```
```applescript
{
```
```applescript
HandleEvent(&event);
```
```applescript
}
```
```applescript
}
```
```applescript
}
```
Listing 3-5shows a standard approach for processing event records. When the value in thewhatfield of the event record iskHighLevelEvent, the function callsAEProcessAppleEvent, which dispatches the event as shown inFigure 3-1.
Listing 3-5A function that processes Apple events
```applescript
static void HandleEvent(EventRecord *event)
```
```applescript
{
```
```applescript
switch (event->what)
```
```applescript
{
```
```applescript
case mouseDown:
```
```applescript
HandleMouseDown(event);
```
```applescript
break;
```
```applescript
```
```applescript
case keyDown:
```
```applescript
case autoKey:
```
```applescript
HandleKeyPress(event);
```
```applescript
break;
```
```applescript
```
```applescript
case kHighLevelEvent:
```
```applescript
AEProcessAppleEvent(event);
```
```applescript
break;
```
```applescript
}
```
```applescript
}
```
Listing 3-4andListing 3-5are based on functions in the Xcode projectAppearanceSample, located in/Developer/Examples/Carbon.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Introduction to AppleScript Overview
Important:This document is no longer being updated. For the latest information about Apple SDKs, visit thedocumentation website.
AppleScript Overviewprovides a high-level overview of AppleScript and its related technologies to help you determine where you can use them in your work.
Note:For information on the universe of scripting technologies available on OS X, seeGetting Started With Scripting & Automation.
AppleScript is a scripting language that makes possible direct control of scriptable applications and of many parts of the Mac OS. A scriptable application is one that makes its operations and data available in response to AppleScript messages, called Apple events.
With scriptable applications, users can write scripts to automate operations, while developers can use AppleScript as an aid to rapid prototyping and automated testing. Developers can also use technologies including Apple events, AppleScript, Automator, and Scripting Bridge, to take advantage of services provided by other applications and by the Mac OS.
AppleScript and Apple events are based on the Open Scripting Architecture, which is implemented by several OS X frameworks. Apple provides a number of additional applications and technologies that enhance AppleScript or take advantage of its features.
## Who Should Read This Document
You should readAppleScript Overviewto get a broad understanding of AppleScript and related automation technologies, and to determine where they fit into your development process.
This document may also be of interest if you write AppleScript scripts and would like to know more about the technology behind them.
AppleScript Overviewis intended for a general developer audience, but experience with some kind of scripting language is helpful. If you are starting from scratch, seeGetting Started with AppleScript.
## Organization of This Document
This document contains the following:
- About AppleScriptintroduces AppleScript, describes when you might use it, and notes some limitations.
About AppleScriptintroduces AppleScript, describes when you might use it, and notes some limitations.
- Open Scripting Architecturedescribes the underlying technology used to implement AppleScript and Apple events. It also describes how to extend AppleScript.
Open Scripting Architecturedescribes the underlying technology used to implement AppleScript and Apple events. It also describes how to extend AppleScript.
- Scripting with AppleScriptprovides a brief description of how you work with AppleScript scripts. It also describes options for combining AppleScript scripting with other kinds of scripting.
Scripting with AppleScriptprovides a brief description of how you work with AppleScript scripts. It also describes options for combining AppleScript scripting with other kinds of scripting.
- Scriptable Applicationsexplains how scriptable applications work, including how they specify their scripting terminology, and describes the programming resources available for creating scriptable applications.
Scriptable Applicationsexplains how scriptable applications work, including how they specify their scripting terminology, and describes the programming resources available for creating scriptable applications.
- Scripting Bridgedescribes a technology available starting in OS X version 10.5 that generates Objective-C API for accessing scriptable applications.
Scripting Bridgedescribes a technology available starting in OS X version 10.5 that generates Objective-C API for accessing scriptable applications.
- Automatordescribes Appleâs graphical automation program and how developers can take advantage of it.
Automatordescribes Appleâs graphical automation program and how developers can take advantage of it.
- AppleScript Utilities and Applicationsdescribes utilities and applications that work with AppleScript or provide additional features you can use in AppleScript scripts.
AppleScript Utilities and Applicationsdescribes utilities and applications that work with AppleScript or provide additional features you can use in AppleScript scripts.
## See Also
You can find additional introductory information on AppleScript and related technologies inGetting Started with AppleScript.
There are also links to related documentation throughoutAppleScript Overview.
Copyright © 2002, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Document Revision History
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This table describes the changes toXML-RPC and SOAP Programming Guide.
Moved to Retired Documents Library.
Made minor changes to first two chapters. Changed title from "XML-RPC and SOAP Support."
InMaking Remote Procedure Calls From Scripts, added warning that the script samples may not work because the web services they rely on may no longer be available. Also provided the location of some additional sample scripts.
First version.
Copyright © 2001, 2014 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2014-07-15
---
# Selected Apple Event Constants
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This appendix describes some commonly used Apple event constants. For more complete documentation, seeApple Event Manager Reference.
## Event Class Constants
Table B-1lists several event class constants. For related information, seeEvent Class and Event ID.
Event class
Value
Description
kCoreEventClass
'aevt'
An Apple event sent by the Mac OS that your application should support if appropriate (sometimes called ârequiredâ events)
kAECoreSuite
'core'
A core Apple event; events with this type or with thekCoreEventClasstype make up the âstandardâ eventsâbasic events that scriptable applications should support if applicable
kAEFinderSuite
'fndr'
An event that the Finder accepts
kAEFinderEvents
'FNDR'
Deprecated constant for Finder event
kAERPCClass
'rpc '
Remote procedure call event
kAETextSuite
'TEXT'
Text suite event
kFASuiteCode
'faco'
Folder actions event
kAEInternetSuite
'gurl'
Internet suite event
kAETableSuite
'tbls'
Table suite event
## Event ID Constants for Apple Events Sent by the Mac OS
Table B-2shows event IDs for various Apple events that may be sent to your application by the Mac OS. For more information, seeHandling Apple Events Sent by the Mac OS. These events are sometimes referred to as the ârequiredâ events, and have the event class value'aevt', defined by the constantkCoreEventClass. For related information, seeEvent Class and Event ID.
Event ID
Value
Description
kAEOpenApplication
'oapp'
Sent when a user opens your application without opening or printing any documents.
kAEReopenApplication
'rapp'
Sent when the application is reopened.
kAEOpenDocuments
'odoc'
Sent with a list of documents to be opened.
kAEPrintDocuments
'pdoc'
Sent with a list of documents to be printed.
kAEOpenContents
'ocon'
Sent with content to be displayed (such as when dragged content is dropped on an application icon in the Dock).
kAEQuitApplication
'quit'
Sent when the application is quitting.
kAEShowPreferences
'pref'
Sent when the user chooses the Preferences menu item.
kAEApplicationDied
'obit'
Sent to an application that launched another application when the launched application quits or terminates.
## Event ID Constants for Standard AppleScript Commands
Table B-3shows event IDs for Apple events that represent various standard AppleScript commands. Each scriptable application should support as many of these commands as make sense for that particular application. These events are sometimes referred to as "standard" or "core" events, and have the event class value'core', defined by the constantkAECoreSuite. For related information, seeEvent Class and Event ID.
Event ID
Value
Description
kAEClone
'clon'
Duplicate the specified AppleScript object or objects.
kAEClose
'clos'
Close the specified object or objects, usually consisting of windows or documents.
kAECountElements
'cnte'
Return the number of objects of a particular class contained by the specified object or objects.
kAECreateElement
'crel'
Create a new object.
kAEDelete
'delo'
Delete the specified object or objects.
kAEDoObjectsExist
'doex'
Return a boolean value indicating whether the specified object or objects exist.
kAEGetData
'getd'
Return the specified data from an object or set of objects.
kAEMove
'move'
Move an object or set of objects.
kAESave
'save'
Save an object or objects, often consisting of windows or documents.
kAESetData
'setd'
Set the data of an object or objects.
## Descriptor Type Constants
In a descriptor, thedescriptorTypestructure member stores a value that is a four-character code.Table B-4lists constants for some of the main descriptor types, along with their four-character code values and a description of the kinds of data they identify. For a complete list of the basic descriptor types, seeApple Event Manager Reference.
Descriptor type
Value
Description of data
typeBoolean
'bool'
1-byte Boolean value
typeSInt32
'long'
32-bit integer
typeUTF8Text
'utf8'
Unicode text (UTF-8 encoding)
typeUTF16ExternalRepresentation
'ut16'
Unicode text (UTF-16 encoding)
typeSInt16
'shor'
16-bit integer
typeAEList
'list'
List of descriptors
typeAERecord
'reco'
List of keyword-specified descriptors
typeAppleEvent
'aevt'
Apple event
typeEnumerated
'enum'
Enumerated data
typeType
'type'
Four-character code
typeFSRef
'fsrf'
File-system reference
typeNull
'null'
Nonexistent data
## Address Descriptor Type Constants
The descriptor type in an address descriptor can be specified by one of the type constants shown inTable B-5(or by any type you define for which you provide a coercion to one of these types):
Descriptor type
Value
Description
typeApplSignature
'sign'
Application signature
typeTargetID
'targ'
Deprecated; do not use in Mac OS X
typeProcessSerialNumber
'psn '
Process serial number
typeKernelProcessID
'kpid'
Kernel process ID
typeApplicationBundleID
'bund'
Application bundle ID (Mac OS X version 10.3 and later)
typeApplicationURL
'aprl'
Application URL, possibly for a remote application (Mac OS X version 10.1 and later)
typeMachPort
'port'
Mach port.
For information on how to create a target descriptor, seeSpecifying a Target Address.
## Attribute Keyword Constants
Your application cannot examine the attributes and parameters of an assembled Apple event directly. Instead, it calls Apple Event Manager functions to request an attribute or parameter by keyword. Keywords are arbitrary values used to keep track of various descriptors.
See âKeyword Parameter Constantsâ inApple Event Manager Referencefor descriptions of keyword constants for additional Apple event parameters.
Table B-6lists keyword constants for Apple event attributes:
Attribute keyword
Value
Description
keyAddressAttr
'addr'
Address of target or client application
keyEventClassAttr
'evcl'
Event class of Apple event
keyEventIDAttr
'evid'
Event ID of Apple event
keyEventSourceAttr
'esrc'
Nature of the source application
keyInteractLevelAttr
'inte'
Settings for whether to allow bringing a server application to the foreground, if necessary, to interact with the user
keyOriginalAddressAttr
'from'
Address of original source of Apple event if the event has been forwarded
keyReturnIDAttr
'rtid'
Return ID for reply Apple event
keyTimeoutAttr
'timo'
Length of time, in ticks, that the client will wait for a reply or a result from the server
keyTransactionIDAttr
'tran'
Transaction ID identifying a series of Apple events
## Parameter Keyword Constants
Table B-7lists keyword constants for commonly used Apple event parameters:
Parameter keyword
Value
Description
keyDirectObject
'----'
Direct parameter
keyErrorNumber
'errn'
Error number parameter (used only in reply events)
keyErrorString
'errs'
Error string parameter (used only in reply events)
keyProcessSerialNumber
'psn '
Process serial number
keyPreDispatch
'phac'
Dispatch event to predispatch handler
keyAEVersion
'vers'
AppleScript version
See âKeyword Parameter Constantsâ inApple Event Manager Referencefor descriptions of keyword constants for additional Apple event parameters.
## Event Source Constants
You use the constants inTable B-8to check the value of thekeyEventSourceAttrattribute, which specifies the source of an Apple event.Listing 4-3shows how to obtain that attribute from an Apple event.
Constant
Meaning
kAEUnknownSource
Source of Apple event unknown
kAEDirectCall
A direct call that bypassed the PPC Toolbox
kAESameProcess
Target application is also the source application
kAELocalProcess
Source application is another process on the same computer as the target application
kAERemoteProcess
Source application is a process on a remote computer on the network
## Send Mode Constants for the AESend Function
When you send an Apple event withAESend, you use one of the constants inTable B-9in thesendModeparameter to specify how to deal with replies.
Flag
Description
kAENoReply
Your application does not want a reply Apple event.
kAEQueueReply
Your application wants a reply Apple event; the reply appears in your event queue as soon as the server has the opportunity to process and respond to your Apple event.
kAEWaitReply
Your application wants a reply Apple event and is willing to give up the processor while waiting for the reply; for example, if the server application is on the same computer as your application, your application yields the processor to allow the server to respond to your Apple event.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Working With the Data in an Apple Event
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This chapter describes how your application gets various kinds of data from Apple events and the data structures that comprise them.
Your application responds to Apple events in the Apple event handlers it registers, or in routines your handlers call. Within a handler, you know that the passed Apple event matches the expected event class and event ID, although there can be some variation if the handler is registered with one or more wildcards. In either case, your handler has at least a general idea of what information the Apple event should contain. In the case of a wildcard handler, it can obtain information from the Apple event to identify the type more closely.
## About Extracting Data From an Apple Event
The parameters and attributes of an Apple event, as well as the data within an individual descriptor, are stored in a format that is opaque to your application. You use Apple Event Manager functions to extract the data you need from a received Apple event. To obtain data in a format your application can use, you typically follow a common series of steps:
- You call a function that returns the descriptor for a high-level data structure you are interested in, such as an Apple event attribute or parameter. For example, you can call theAEGetAttributeDescfunction to obtain the descriptor for an attribute, specifying the attribute by its keyword.
You call a function that returns the descriptor for a high-level data structure you are interested in, such as an Apple event attribute or parameter. For example, you can call theAEGetAttributeDescfunction to obtain the descriptor for an attribute, specifying the attribute by its keyword.
- If the returned descriptor is a list, you use another function to iterate over the items in the list. For example, you can useAEGetNthDescto get descriptors from a list by index.
If the returned descriptor is a list, you use another function to iterate over the items in the list. For example, you can useAEGetNthDescto get descriptors from a list by index.
- Once you have obtained an individual descriptor, you use other functions to extract its data. For example, you can callAEGetDescDataSizeto determine the size of the data in a descriptor andAEGetDescDatato get the data.
Once you have obtained an individual descriptor, you use other functions to extract its data. For example, you can callAEGetDescDataSizeto determine the size of the data in a descriptor andAEGetDescDatato get the data.
Many of the functions for getting data from an Apple event are available in two forms:
- One that returns a copy of the descriptor for the data.
One that returns a copy of the descriptor for the data.
- One that returns a copy of the data in a buffer you have supplied.
One that returns a copy of the data in a buffer you have supplied.
For example,AEGetParamDescreturns a copy of the descriptor for a parameter, whileAEGetParamPtrreturns the data from an Apple event parameter in a specified buffer. You typically use the buffer form to extract data of fixed length or known maximum length, such as a result code. You use the descriptor form to extract data of variable length, such as a list of unknown length.
You can also use Apple Event Manager functions to get data from descriptors, descriptor lists, and Apple events. For example, you can use theAESizeOfAttributefunction to get the size and descriptor type of an Apple event attribute from an Apple event. And you can use theAESizeOfParamfunction to get the size and descriptor type of an Apple event parameter from an Apple event or an Apple event record (typeAERecord).
Where performance is critical, you can useAECreateDescFromExternalPtrto efficiently create a descriptor containing large amounts of data, and callAEGetDescDataRangeto efficiently get data from a descriptor.
Other functions allow you to count the number of items in a descriptor list (AECountItems) or iterate through those descriptors (AEGetNthPtrorAEGetNthDesc).
This chapter provides examples of how to work with some of these functions, whileFunctions for Working With Apple Event Data Structureslists these and other Apple Event Manager functions. For complete reference, seeApple Event Manager Reference.
## Coercing Data From an Apple Event
Coercionis the process of converting a descriptor and, if necessary, the data it contains, from one type to another. When your handler receives an Apple event, you typically use one or more of the functionsAEGetParamPtr,AEGetAttributePtr,AEGetParamDesc,AEGetAttributeDesc,AEGetNthPtr, andAEGetNthDescto get data from the Apple event. Each of these Apple Event Manager functions allows your application to specify a desired descriptor type for the resulting data. If the original data is of a different type, the Apple Event Manager attempts to coerce the data to the requested descriptor type. To prevent coercion and ensure that the descriptor type of the result is of the same type as the original, you specifytypeWildCardfor the desired type.
The following code snippet shows how to specify a desired descriptor type when calling the functionAEGetParamPtr.
Listing 4-1Getting and coercing an Apple event parameter
```applescript
DescType returnedType;
```
```applescript
long multResult;
```
```applescript
Size actualSize;
```
```applescript
OSErr err;
```
```applescript
```
```applescript
err = AEGetParamPtr(
```
```applescript
theAppleEvent,// 1
```
```applescript
keyMultResult,// 2
```
```applescript
typeSInt32,// 3
```
```applescript
&returnedType,// 4
```
```applescript
&multResult,// 5
```
```applescript
sizeof(multResult),// 6
```
```applescript
&actualSize);// 7
```
Hereâs a description of the parameters used in this call:
- A pointer to the Apple event to get the parameter data from.
A pointer to the Apple event to get the parameter data from.
- A keyword constant specifying the parameter to get the data from. In this example, the keyword is defined by the application and indicates a parameter containing the result of a multiplication operation.
A keyword constant specifying the parameter to get the data from. In this example, the keyword is defined by the application and indicates a parameter containing the result of a multiplication operation.
- A constant specifying the type to coerce the returned value to (if it isnât already that type).
A constant specifying the type to coerce the returned value to (if it isnât already that type).
- The address of a variable in which the function stores the actual type of the returned value, which may not match the requested type.
The address of a variable in which the function stores the actual type of the returned value, which may not match the requested type.
- The address of a variable in which the function stores the returned data.
The address of a variable in which the function stores the returned data.
- The maximum size of the returned data. TheAEGetParamPtrfunction wonât return more data than you specify in this parameter.
The maximum size of the returned data. TheAEGetParamPtrfunction wonât return more data than you specify in this parameter.
- The address of a variable in which the function stores the actual size of the requested data. If the returned value is greater than the amount your application allocated to store the returned data, you can increase the size of your buffer to this amount and call the function again. You can also choose to use theAEGetParamDescfunction when your application doesnât know the size of the data.
The address of a variable in which the function stores the actual size of the requested data. If the returned value is greater than the amount your application allocated to store the returned data, you can increase the size of your buffer to this amount and call the function again. You can also choose to use theAEGetParamDescfunction when your application doesnât know the size of the data.
If the coercion fails, theAEGetParamPtrfunction returns the result codeerrAECoercionFail.
By default, the Apple Event Manager can coerce between many different data types, listed inTable C-2. To perform other coercions, such as those involving data types you have defined, you can provide your own coercion handlers. SeeWriting and Installing Coercion Handlersfor more information on working with coercion handlers.
## Getting Data From an Apple Event Parameter
Apple event parameters are keyword-specified descriptors. You can use theAEGetParamDescfunction to get the descriptor for a parameter or to extract the descriptor list from a parameter; you can useAEGetParamPtrto get the data from the descriptor for a parameter. In general, use the former to extract data of variable length, and the latter to extract data of fixed length or known maximum length.
Listing 4-2shows how to callAEGetParamDescto extract a parameter descriptor from an Apple event such as anopen documentsevent.
Listing 4-2Getting a parameter as a descriptor
```applescript
AEDescList docList;
```
```applescript
OSErr myErr;
```
```applescript
```
```applescript
myErr = AEGetParamDesc( theAppleEvent,// 1
```
```applescript
keyDirectObject,// 2
```
```applescript
typeAEList,// 3
```
```applescript
&docList);// 4
```
```applescript
```
```applescript
// Check the returned value from AEGetParamDesc for any error.
```
```applescript
// (Not shown.)
```
Hereâs a description of the parameters used in this call:
- A pointer to the Apple event to get the parameter descriptor from (obtained previously).
A pointer to the Apple event to get the parameter descriptor from (obtained previously).
- A constant specifying that the function should get the descriptor for the direct parameter.
A constant specifying that the function should get the descriptor for the direct parameter.
- A constant specifying that the descriptor should be returned as a descriptor list, coercing it if necessary. If the coercion fails, the function returns the result codeerrAECoercionFail.
A constant specifying that the descriptor should be returned as a descriptor list, coercing it if necessary. If the coercion fails, the function returns the result codeerrAECoercionFail.
- The address of a variable in which the function stores the returned descriptor list.
The address of a variable in which the function stores the returned descriptor list.
SeeGetting Data From a Descriptor Listfor details on working with a descriptor list.
TheAEGetParamDescfunction supplies a copy of the descriptor for the parameter, so you must dispose of it when youâre finished with it by calling theAEDisposeDescfunction. For an example, seeListing 4-6.
If an Apple event parameter contains an object specifier, your handler should use theAEResolvefunction, other Apple Event Manager functions, and your own application-defined functions to resolve the object specifierâthat is, to locate the Apple event object in your application that the specifier describes. For more information, seeâResolving and Creating Object Specifier RecordsâinInside Macintosh: Interapplication Communication.
## Getting Data From an Apple Event Attribute
To get the descriptor for an attribute or to get the data from an attribute you use routines that are similar to those you use with parameters: theAEGetAttributePtrandAEGetAttributeDescfunctions.
For example,Listing 4-3shows how to useAEGetAttributePtrto get the data from thekeyEventSourceAttrattribute of an Apple event.
Listing 4-3Getting a value from an attribute
```applescript
DescType returnedType;
```
```applescript
AEEventSource sourceOfAE;
```
```applescript
Size actualSize;
```
```applescript
OSErr myErr;
```
```applescript
```
```applescript
myErr = AEGetAttributePtr( theAppleEvent,// 1
```
```applescript
keyEventSourceAttr,// 2
```
```applescript
typeShortInteger,// 3
```
```applescript
&returnedType,// 4
```
```applescript
(void *) &sourceOfAE,// 5
```
```applescript
sizeof (sourceOfAE),// 6
```
```applescript
&actualSize);// 7
```
```applescript
```
```applescript
// Check the returned value from AEGetParamDesc for any error.
```
```applescript
// (Not shown.)
```
Hereâs a description of the parameters used in this call:
- A pointer to the Apple event to get the attribute data from (obtained previously).
A pointer to the Apple event to get the attribute data from (obtained previously).
- A constant specifying the attribute from which to get the data.
A constant specifying the attribute from which to get the data.
- A constant specifying that the data should be returned as a short integer.
A constant specifying that the data should be returned as a short integer.
- The address of a variable in which the function stores the type of the actual descriptor returned.
The address of a variable in which the function stores the type of the actual descriptor returned.
- The address of a variable in which the function stores the requested data. If the data is not already a short integer, the Apple Event Manager coerces it as necessary. The value should equal one of the event source constant values described inEvent Source Constants.If you allocate a buffer for this parameter, itâs up to you to free it when you are finished with it.
The address of a variable in which the function stores the requested data. If the data is not already a short integer, the Apple Event Manager coerces it as necessary. The value should equal one of the event source constant values described inEvent Source Constants.
If you allocate a buffer for this parameter, itâs up to you to free it when you are finished with it.
- The size of the return buffer.
The size of the return buffer.
- The address of a variable in which the function stores the actual size of the returned data after coercion has taken place. You can check this value to make sure you got all the data.
The address of a variable in which the function stores the actual size of the returned data after coercion has taken place. You can check this value to make sure you got all the data.
## Getting Data From a Descriptor
Because the data within a descriptor is opaque, you use Apple Event Manager functions to extract it. In some cases, such as the example shown inListing 4-3, the data is of known type and size, or can be coerced to a known type, and you can store it in a variable of that type.
It is common, however, for a descriptor to contain data, such as text or an image, of unknown size. In situations of that type, you can call theAEGetDescDataSizefunction to find out how much memory you will need to store the data, allocate a buffer of that size, then callAEGetDescDatato get the actual data from the descriptor. The code snippet inListing 4-4shows how you might use these functions to get data into a buffer.
Listing 4-4Determining the size, then obtaining descriptor data
```applescript
Size dataSize = AEGetDescDataSize(desc);// 1
```
```applescript
UInt8* buffer = malloc(dataSize);// 2
```
```applescript
if (buffer)
```
```applescript
{
```
```applescript
OSErr err = AEGetDescData(desc, buffer, dataSize);// 3
```
```applescript
```
```applescript
// If no error, use the data.// 4
```
```applescript
```
```applescript
free(buffer);// 5
```
```applescript
}
```
Hereâs a description of what this code does:
- Calls an Apple Event Manager function to get the data size for the descriptor.
Calls an Apple Event Manager function to get the data size for the descriptor.
- Creates a buffer of that size.
Creates a buffer of that size.
- Calls an Apple Event Manager function to get the data from the descriptor into the buffer.
Calls an Apple Event Manager function to get the data from the descriptor into the buffer.
- If no error occurred in getting the data, your application can use it as needed.
If no error occurred in getting the data, your application can use it as needed.
- Frees the allocated buffer.
Frees the allocated buffer.
Alternatively, you can do the following:
- Call theAEGetParamPtrfunction (shown inListing 4-1), passing a size of zero for the maximum size (line 6 in the listing).
Call theAEGetParamPtrfunction (shown inListing 4-1), passing a size of zero for the maximum size (line 6 in the listing).
- Get the actual size value returned byAEGetParamPtr.
Get the actual size value returned byAEGetParamPtr.
- Allocate a buffer of that size.
Allocate a buffer of that size.
- CallAEGetParamPtragain to get the data into the buffer.
CallAEGetParamPtragain to get the data into the buffer.
- If you allocated memory for the buffer, free it when you are finished with it.
If you allocated memory for the buffer, free it when you are finished with it.
## Getting Data From a Descriptor List
To get descriptors and their data from a descriptor list, you can call theAECountItemsfunction to get the number of descriptors in the list, then set up a loop that callsAEGetNthDescorAEGetNthPtrto get the data from each descriptor.
For example, anopen documentsevent contains a direct parameter that specifies a list of documents to open. The parameter contains a descriptor list in which each descriptor specifies an alias to a file to open.Listing 4-5shows how you can extract the descriptor list from the parameter, determine the number of items it contains, and extract each descriptor from the list.
Listing 4-5Getting a descriptor list and its items
```applescript
AEDescList docList;
```
```applescript
FSRef theFSRef;
```
```applescript
long index;
```
```applescript
long count = 0;
```
```applescript
OSErr err;
```
```applescript
```
```applescript
err = AEGetParamDesc(theAppleEvent, keyDirectObject,
```
```applescript
typeAEList, &docList);// 1
```
```applescript
```
```applescript
err = AECountItems(&docList, &count);// 2
```
```applescript
```
```applescript
for(index = 1; index <= count; index++)// 3
```
```applescript
{
```
```applescript
err = AEGetNthPtr(&docList, index, typeFSRef,
```
```applescript
NULL, NULL, &theFSRef,
```
```applescript
sizeof(theFSRef), NULL);// 4
```
```applescript
```
```applescript
// Call routine to open document with current reference.// 5
```
```applescript
}
```
Hereâs a description of what this code does:
- CallsAEGetParamDescto obtain, in the variabledocList, a copy of the descriptor list from the direct parameter of the Apple event. Passes the constantkeyDirectObjectto identify the direct parameter and the constanttypeAEListto indicate the desired descriptor type. (theAppleEventis a pointer to the Apple event, obtained previously, to get the parameter descriptor from).
CallsAEGetParamDescto obtain, in the variabledocList, a copy of the descriptor list from the direct parameter of the Apple event. Passes the constantkeyDirectObjectto identify the direct parameter and the constanttypeAEListto indicate the desired descriptor type. (theAppleEventis a pointer to the Apple event, obtained previously, to get the parameter descriptor from).
- CallsAECountItems, passing the previously obtained descriptor list, to get the number of items in the list.
CallsAECountItems, passing the previously obtained descriptor list, to get the number of items in the list.
- Sets up a loop based on the count.
Sets up a loop based on the count.
- CallsAEGetNthPtrto obtain the indexed descriptor from the list. PassestypeFSRefto indicate the descriptor should be coerced to a file system reference, if necessary (otherwise the returned value will be a file alias). Passes the address of the variabletheFSRefas a buffer to store the reference.PassesNULLfor the fourth and fifth parameters, indicating the keyword and descriptor type of the returned item arenât needed.Also passesNULLfor the last parameter, indicating the actual size of the returned data isnât required. (If the returned size is larger than the size of the buffer you provided, you know that you didnât get all of the data for the descriptor.)
CallsAEGetNthPtrto obtain the indexed descriptor from the list. PassestypeFSRefto indicate the descriptor should be coerced to a file system reference, if necessary (otherwise the returned value will be a file alias). Passes the address of the variabletheFSRefas a buffer to store the reference.
PassesNULLfor the fourth and fifth parameters, indicating the keyword and descriptor type of the returned item arenât needed.
Also passesNULLfor the last parameter, indicating the actual size of the returned data isnât required. (If the returned size is larger than the size of the buffer you provided, you know that you didnât get all of the data for the descriptor.)
- Here you would call your own routine to open a document specified by the extracted file system reference.
Here you would call your own routine to open a document specified by the extracted file system reference.
For a more complete version of this code, including simple error handling, seeListing 5-5.
## Disposing of Apple Event Data Structures
If you create a descriptor, you must dispose of it when you are finished with it to prevent memory leaks. For example, when you extract a descriptor using theAEGetParamDesc,AEGetAttributeDesc,AEGetNthDesc, orAEGetKeyDescfunction, you get a copy of the descriptor. You call theAEDisposeDescfunction to dispose of your copy, thereby deallocating the memory used by its data.
Listing 4-6shows how to dispose of a descriptor list returned byAEGetParamDesc.
Listing 4-6Disposing of a descriptor list obtained from the direct object of an Apple event
```applescript
AEDescList docList;
```
```applescript
OSErr err;
```
```applescript
err = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
```
```applescript
```
```applescript
// Check for error, then perform operations on the descriptor list here.
```
```applescript
```
```applescript
AEDisposeDesc(&docList);
```
You can safely callAEDisposeDescon a null descriptor (but not on a null pointer!) Anull descriptoris one that has been initialized as shown in the following code snippet.
```applescript
AEDesc someDesc = { typeNull, 0L };
```
```applescript
```
```applescript
// Code to obtain a descriptor, which may fail.
```
```applescript
```
```applescript
// Safe to dispose, whether or not previous code succeeded.
```
```applescript
AEDisposeDesc(&someDesc);
```
You can perform the same initialization using theAEInitializeDescfunction, as shown in this code snippet.
```applescript
AEDesc someDesc;
```
```applescript
```
```applescript
AEInitializeDesc(&someDesc);
```
When you obtain a copy of a descriptor with one of the buffer-based functions, such asAEGetAttributePtrorAEGetNthPtr, the data is copied into a buffer provided by your application. You must then free any allocated memory when finished with the buffer.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Testing and Debugging Apple Event Code
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
To test and debug your Apple event code you can generally use the same techniques and tools you use with any code. For example, Xcode contains a full-featured source-level debugger that lets you set breakpoints and step through your code line by line. For C, C++, and Objective-C code, Xcode uses GDB, the debugger from theGNU Project. You can use Xcodeâs graphical interface to GDB or you can enter commands directly into the GDB console. For more information, see âDebuggingâ in Xcode Help andDebugging With GDB.
The remainder of this chapter provides tips that are specific to debugging code that works with Apple events.
## Determining If an Application Is Receiving Apple Events
The easiest way to determine if your application is receiving a particular event is to set a breakpoint in the event handler for that event, then send an event of that type to your application. There are several ways to send Apple events to your application:
- You can create and send events that target your application from within the application itself or from a test application. For more information, seeCreating and Sending Apple Events. This approach can be useful if youâre setting up a test suite and want to thoroughly test how your application responds to a variety of events.
You can create and send events that target your application from within the application itself or from a test application. For more information, seeCreating and Sending Apple Events. This approach can be useful if youâre setting up a test suite and want to thoroughly test how your application responds to a variety of events.
- You can use Script Editor to send Apple events to your application.For example, you can execute this one-line script to send your application aquitevent:Listing 8-1A simple script to quit an applicationtell app "MyApplication" to quitIf your application is scriptable, you may prefer to set up a test suite of scripts to thoroughly exercise the events you support, rather than perform the same task in a test application.For additional information on sending Apple events with Script Editor, seeScript Editor is an Apple Event Test Tool.
You can use Script Editor to send Apple events to your application.
For example, you can execute this one-line script to send your application aquitevent:
Listing 8-1A simple script to quit an application
```applescript
tell app "MyApplication" to quit
```
If your application is scriptable, you may prefer to set up a test suite of scripts to thoroughly exercise the events you support, rather than perform the same task in a test application.
For additional information on sending Apple events with Script Editor, seeScript Editor is an Apple Event Test Tool.
- You can use the Mac OS to send Apple events to your application.For example, you can select an application document in the Finder and double-click it to send anopen documentsevent to the application. SeeHandling Apple Events Sent by the Mac OSfor a list of the events the Mac OS sends to applications.
You can use the Mac OS to send Apple events to your application.
For example, you can select an application document in the Finder and double-click it to send anopen documentsevent to the application. SeeHandling Apple Events Sent by the Mac OSfor a list of the events the Mac OS sends to applications.
What if youâre sending events to your application, but the debugger never reaches the breakpoints you set in your Apple event code? One simple approach is to install a single Apple event handler with the event type and event class set totypeWildCard. Any Apple event your application receives will be dispatched to this handler, so a breakpoint in the handler should allow you to verify whether the application is actually receiving events.
Once you know your application is receiving events, you can take a closer look at the events using the information provided inExamining Apple Events. That information is also useful if you never hit the breakpoint in your wildcard handler. For example, you can examine the test events you are sending to see if they correctly target your application.
## Script Editor is an Apple Event Test Tool
The Script Editor application, located in/Applications/AppleScript, is a useful tool for working with Apple events. If your application is scriptable, you can use Script Editor to write and execute scripts that target your application, resulting in Apple events being sent to the application.
Even if your application is not fully scriptable, you can use Script Editor to send it events such as theopen applicationandquitevents that your application usually receives from the Mac OS.Listing 8-1shows an example of this.
In addition, you can use Script Editor to construct and send Apple events using raw format, in which you enclose actual four-character codes in special characters to specify an event. For example,Listing 8-2shows how to use the raw format to send anopen locationcommand to the Safari application and open the specified web page.
Listing 8-2Sending a raw event to open an URL
```applescript
tell application "Safari"
```
```applescript
«event GURLGURL» "http://www.apple.com/"
```
```applescript
end tell
```
When you compile this script, Script Editor examines Safariâs scripting dictionary and converts the second line to this:
```applescript
open location "http://www.apple.com/"
```
However, for an application that doesnât have a scripting dictionary, the raw code is not replaced by an equivalent term, but the Apple event can still be sent and understood (if the application supports it).
You enter the special characters that surround the raw code (called double angle brackets or guillemets) by typing Option-\ and Option-Shift-\. For additional information, seeDouble Angle Brackets in Results and ScriptsinAppleScript Language Guide.
Turning on Apple Event Loggingshows how you can examine the Apple events Script Editor sends and receives.
Note:The following features can also be useful in debugging your Apple event code:
You can execute AppleScript scripts from shell scripts and shell scripts from AppleScript scripts, which may come in handy for automating your testing. For more information, see âUsing AppleScript With Other Scripting Systemsâ inAppleScript Overview.
In addition, Xcode provides a build phase in which you can execute AppleScript scripts, and Xcode itself is scriptable. For additional information, see Xcode Help.
## Examining Apple Events
There are several available mechanisms for examining the contents of Apple events that your application sends and receives.
### Turning on Apple Event Logging
You can set environment variables in a Terminal window so that any Apple events sent or received by an application launched in that window are logged to the window in a human-readable format.Listing 8-4shows how you would do this if youâre working with the C shell.
Listing 8-3Turning on logging for sent and received Apple events in the C shell
```applescript
%setenv AEDebugSends 1; setenv AEDebugReceives 1
```
If you are using thebashshell you, you can use the form shown inListing 8-4.
Listing 8-4Turning on Apple event logging in the Bash shell
```applescript
%export AEDebugSends=1; export AEDebugReceives=1
```
To see which Apple events an application sends and receives, you set these environment variables, then launch the application in a Terminal window. For example, to see what events the Script Editor application sends, you can execute the line inListing 8-5. Once the Script Editor launches, you can compile and execute scripts and examine, in the Terminal window, the Apple events that are generated.
Listing 8-5Launching Script Editor in Terminal
```applescript
% /Applications/AppleScript/Script\ Editor.app/Contents/MacOS/Script\ Editor
```
Important:To launch an application in Terminal, you provide the full path to its executable, which is typically located inside the application bundle, rather than the path to the application itself.
Listing 8-6shows how to perform the same task with the Finder, a scriptable application that may send Apple events to your application.
Listing 8-6Launching Finder in Terminal
```applescript
% /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder
```
This technique for examining Apple events works for both Carbon and Cocoa applications. For example,Listing 8-7shows the output for areopenApple event sent to a Carbon application when you click on its icon in the Dock.
Listing 8-7Output of a reopen Apple event in Terminal
```applescript
AE2000 (968): Received an event:
```
```applescript
------oo start of event oo------
```
```applescript
{ 1 } 'aevt': aevt/rapp (ppc ){
```
```applescript
return id: 22609967 (0x159002f)
```
```applescript
transaction id: 0 (0x0)
```
```applescript
interaction level: 112 (0x70)
```
```applescript
reply required: 0 (0x0)
```
```applescript
remote: 0 (0x0)
```
```applescript
target:
```
```applescript
{ 1 } 'psn ': 8 bytes {
```
```applescript
{ 0x0, 0x60001 } (Dock)
```
```applescript
}
```
```applescript
optional attributes:
```
```applescript
{ 1 } 'reco': - 1 items {
```
```applescript
key 'optk' -
```
```applescript
{ 1 } 'list': - 1 elements {
```
```applescript
{ 1 } 'keyw': 4 bytes {
```
```applescript
'frnt'
```
```applescript
}
```
```applescript
}
```
```applescript
}
```
```applescript
```
```applescript
event data:
```
```applescript
{ 1 } 'aevt': - 1 items {
```
```applescript
key 'frnt' -
```
```applescript
{ 1 } 'bool': 1 bytes {
```
```applescript
false
```
```applescript
}
```
```applescript
}
```
```applescript
}
```
```applescript
------oo end of event oo------
```
From the formatted output inListing 8-7, you can identify various information in the Apple event. For example,aevt/rappis the event class/event ID pair for the event. You can look up these values in the Apple Event Manager headers and see that'rapp'is the value of the constantkAEReopenApplication, defined inAERegistry.h. For this event, no reply is required (reply required: 0), but if a reply were required, the target would be the Dock (target: { 1 } 'psn ': 8 bytes { { 0x0, 0x60001 } (Dock) }), which sent the Apple event.
Although Apple event log information can be somewhat cryptic, you can see that the event contains an optional attribute containing boolean data with the value false and the key'frnt'. This indicates that the application was not frontmost at the time thereopenevent was sent (when you clicked the application icon in the Dock). If the application is in front, the event data will contain the valuefalse.
Note:For Cocoa applications, you can display additional formatted output for Apple events using the mechanism described in âTurn On Debugging Output for Scriptingâ inKey Steps for Creating Scriptable ApplicationsinCocoa Scripting Guide.
### Observing Apple Events for Multiple Applications
You can open multiple Terminal windows, turn on debugging output in each, and debug your own application and other applications that it sends Apple events to or receives Apple events from at the same time.
### Setting Breakpoints and Printing Apple Events in GDB
The GDB debugger provides acallcommand that you can use to call routines such as Apple Event Manager functions. The sectionâUsing AEPrint* with GDBâin Technical Note TN2106,AEBuild*, AEPrint*, and Friends, shows how you can set breakpoints in GDB and print out the contents of Apple events in a readable format. While this approach is a little more complex, it provides a good example of setting breakpoints on Apple Event Manager routines and examining Apple events.
### Third Party Options
There are a number of third-party tools, some of them quite powerful, for monitoring and debugging Apple events and scriptable applications. You can find some of them listed atAppleScript Resources.
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Selected Apple Event Manager Functions
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
This appendix provides a table of functions that you use to work with the data in Apple event data structures. For complete descriptions of these functions (and the underlying data types), seeApple Event Manager Reference.
## Functions for Working With Apple Event Data Structures
Figure A-1shows the hierarchy for key Apple event data structures. An Apple Event Manager function that operates on one of these data structures can also operate on any type that inherits from it. For example, the same function that works on a descriptor (AEDesc) also works on a descriptor list (AEDescList).
However, if there is a specific function for working with a data type, you should use that function. For example, becauseAppleEventinherits fromAEDesc, it is theoretically possible to create an Apple event with theAECreateDescfunction (assuming you have access to the raw data for the Apple event). However, you should instead use theAEBuildfunction or theAECreateAppleEventfunction, which are designed specifically for creating Apple events. For information on using these functions, seeTwo Approaches to Creating an Apple Event.
Table A-1shows some of the functions the Apple Event Manager provides for working with Apple event data structures. Functions listed for structure types higher in the table also work for types lower in the table, though as noted, you should generally use the most specific function available for a type. For structures that are stored by key value (such as Apple event attributes and parameters), you typically use a function that accesses data by key, rather than by index.
Some functions have both a pointer and a descriptor version (for example,AECoerceDescandAECoercePtr). The pointer version works with data in a pointed to buffer, while the descriptor version works with data that is in a descriptor.
Data type
Operation
Function
Descriptor
(AEdesc)
create
AECreateDesc,AEBuildDesc
dispose of
AEDisposeDesc
get data
AEGetDescData,AEGetDescDataSize,
AEGetDescDataRange(valid forAEDesctypes only)
set data
AEReplaceDescData
coerce
AECoerceDesc,AECoercePtr
Descriptor list
(AEDescList)
create
AECreateList
count
AECountItems
get by index (base 1)
AEGetNthDesc,AEGetNthPtr
delete by index (base 1)
AEDeleteItem
AEPutDesc,AEPutPtr,AEBuildDesc
Apple event record
(AERecord)
get by key
AEGetKeyDesc,AEGetKeyPtr
delete by key
AEDeleteKeyDesc
put by key
AEPutKeyDesc,AEPutKeyPtr
Apple event
(AppleEvent)
create
AECreateAppleEvent,
AEBuildAppleEvent
get by parameter
AEGetParamDesc,AEGetParamPtr
get by attribute
AEGetAttributeDesc,AEGetAttributePtr
delete by parameter
AEDeleteParam
put by parameter
AEPutParamDesc,AEPutParamPtr,AEBuildParameters
put by attribute
AEPutAttributeDesc,AEPutAttributePtr,AEBuildParameters
For the following functions, you can specify the descriptor type of the resulting data; if the actual descriptor type of the attribute or parameter is different from the specified type, the Apple Event Manager attempts to coerce it to the specified type:
- AEGetParamPtr
AEGetParamPtr
- AEGetParamDesc
AEGetParamDesc
- AEGetAttributePtr
AEGetAttributePtr
- AEGetAttributeDesc
AEGetAttributeDesc
- AEGetNthPtr
AEGetNthPtr
- AEGetNthDesc
AEGetNthDesc
Copyright © 2005, 2007 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2007-10-31
---
# Making Remote Procedure Calls From Applications
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Starting with OS X version 10.1, the Apple Event Manager provides support for using the XML-RPC and SOAP protocols to make remote procedure calls from AppleScript scripts and from applications. This chapter provides sample code that show how to make remote procedure calls from applications or other code.
This chapter assumes you are familiar with the conceptual material inIntroduction to XML-RPC and SOAP Programming Guide. To test any of the sample code shown in this book, you must have an Internet connection.
## Making an XML-RPC Call
To make an XML-RPC call from an application or other code, you create an Apple event that describes the remote procedure call, use theAESendfunction to send it, and extract any returned information from the reply Apple event. This process, along with the Apple Event Manager API you use, is described inRemote Procedure Calls From Applications.
This section provides sample code you can use from an application, tool, or other code to send an XML-RPC request to a server. The sample code calls an Internet server that returns the state name for the passed state index. That is, for an index value of 1 it returns Alabama, for 2 it returns Alaska, for 50 it returns Wyoming, and so on.
### Setting Up a Project
You can use the sample code in this section in a number of ways. The following steps show one approach: creating a C++ tool with Project Builder:
- Launch Project Builder.
Launch Project Builder.
- Choose New Project from the File menu.
Choose New Project from the File menu.
- Choose the C++ tool template.
Choose the C++ tool template.
- Replace the code in the automatically generated main.cpp file with the sample code inListing 4-1,Listing 4-2, andListing 4-3, in that order.
Replace the code in the automatically generated main.cpp file with the sample code inListing 4-1,Listing 4-2, andListing 4-3, in that order.
- Use Add Frameworks from the Project menu to addCarbon.frameworkto the project.
Use Add Frameworks from the Project menu to addCarbon.frameworkto the project.
Once youâve built the tool, you can run it in Project Builder and examine its output in the Console pane, or run it in a Terminal window.
You can also build this code directly in a Terminal window with the following compile line:
```applescript
cc -g -o xmlrpc xmlrpc.cp -framework Carbon
```
If you want to compile with a C compiler, rather than a C++ compiler, youâll have to modify the code so that all variables are declared at the beginning of functions, rather than where they are used.
### Includes, Constants, and Declarations
Listing 4-1shows include statements, constants, and declarations to place at the beginning of your code file. This code
- includesCarbon.hto gain access to the scripting API it needs
includesCarbon.hto gain access to the scripting API it needs
- defines a simple error macro that usesfprintfto show an error number and line number, then exits the application
defines a simple error macro that usesfprintfto show an error number and line number, then exits the application
- defines constants that specify the server and method name to call to get state name information
defines constants that specify the server and method name to call to get state name information
- declares a debug function that is defined later
declares a debug function that is defined later
Listing 3-1Includes, constants, and declarations for making an XML-RPC call.
```applescript
#include
```
```applescript
```
```applescript
// Define a simple error macro that just shows the error and line number
```
```applescript
#define checkErr(err) \
```
```applescript
while (err != noErr) \
```
```applescript
{ fprintf(stderr, "Failed at line %d, error %d\n", __LINE__, err);\
```
```applescript
exit(-1); }
```
```applescript
```
```applescript
// Define constants for the XML-RPC server and method.
```
```applescript
static const char* serverURL = "http://betty.userland.com/RPC2";
```
```applescript
static const char* methodName = "examples.getStateName";
```
```applescript
```
```applescript
// Declare our debug function.
```
```applescript
static void dumpDebug(const char* msg, const AppleEvent* replyEvent,
```
```applescript
OSType debugDataKey);
```
### A Main Function That Makes an XML-RPC Call
Listing 4-2shows amainfunction that prepares an XML-RPC Apple event, sends it, and displays information from the reply Apple event. To do so, it performs the following steps:
- It callsAECreateDescto create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server). It uses the constantserverURLdefined previously to specify the desired Internet server.
It callsAECreateDescto create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server). It uses the constantserverURLdefined previously to specify the desired Internet server.
- It callsAECreateAppleEventto create an Apple event with event classkAERPCClass, event IDKAEXMLRPCScheme, and with the target address descriptor from step 1.
It callsAECreateAppleEventto create an Apple event with event classkAERPCClass, event IDKAEXMLRPCScheme, and with the target address descriptor from step 1.
- It callsAECreateListto create the direct object for the Apple event.
It callsAECreateListto create the direct object for the Apple event.
- It callsAEPutParamPtrto insert the method name, using the keykeyRPCMethodNameand the constantmethodNamedefined previously.
It callsAEPutParamPtrto insert the method name, using the keykeyRPCMethodNameand the constantmethodNamedefined previously.
- It callsAECreateListto create a list descriptor for the remote procedure call parameters.
It callsAECreateListto create a list descriptor for the remote procedure call parameters.
- It callsAEPutPtrto insert the only parameter for theexamples.getStateNamefunction, the state index, into the parameter list. It passestypeSInt32for the type code and an index value of 41. The index number was chosen randomly from the legal values of 1 to 50 (the fifty states).
It callsAEPutPtrto insert the only parameter for theexamples.getStateNamefunction, the state index, into the parameter list. It passestypeSInt32for the type code and an index value of 41. The index number was chosen randomly from the legal values of 1 to 50 (the fifty states).
- It callsAEPutParamDescto add the parameter list to the Apple eventâs direct object.
It callsAEPutParamDescto add the parameter list to the Apple eventâs direct object.
- It callsAEPutParamDescto insert the direct object into the Apple event.
It callsAEPutParamDescto insert the direct object into the Apple event.
- It callsAEPutAttributePtrto turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttrand the valuekAEDebugXMLDebugAll. This step is optional.
It callsAEPutAttributePtrto turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttrand the valuekAEDebugXMLDebugAll. This step is optional.
- It initializes a reply Apple event.
It initializes a reply Apple event.
- It callsAESendto send the Apple event, passingkAEWaitReplyto indicate it will wait for a reply.
It callsAESendto send the Apple event, passingkAEWaitReplyto indicate it will wait for a reply.
- If the previous call succeeds, it callsAEGetParamPtrwith keykeyDirectObjectand desired type oftypeCharto extract the direct object of the reply Apple event. For a successful call with state index 41, the returned value is the string âSouth Dakotaâ.It callsfprintfto display the state name. For exampleState is South Dakota!Note:Starting in OS X version 10.3,typeCharis deprecated in favor of one of the Unicode string types. For details, see the descriptions fortypeCharand for the Unicode string types inApple Event Manager Reference.
If the previous call succeeds, it callsAEGetParamPtrwith keykeyDirectObjectand desired type oftypeCharto extract the direct object of the reply Apple event. For a successful call with state index 41, the returned value is the string âSouth Dakotaâ.
It callsfprintfto display the state name. For example
```applescript
State is South Dakota!
```
Note:Starting in OS X version 10.3,typeCharis deprecated in favor of one of the Unicode string types. For details, see the descriptions fortypeCharand for the Unicode string types inApple Event Manager Reference.
- The main function then calls the functiondumpDebug, shown inListing 4-3, once each to display the header and data for the original XML-RPC request and for the reply from the server.Listing 4-4shows the possible result of these calls.
The main function then calls the functiondumpDebug, shown inListing 4-3, once each to display the header and data for the original XML-RPC request and for the reply from the server.Listing 4-4shows the possible result of these calls.
Listing 3-2main function to send an XML-RPC Apple event.
```applescript
//------------------------- main ----------------------------------
```
```applescript
// Builds and sends an XML-RPC Apple event.
```
```applescript
// Sends the Apple event to a server that returns the state
```
```applescript
// name corresponding to the passed number; e.g., the number
```
```applescript
// 5 corresponds to the state California.
```
```applescript
// Prints the returned state name, then calls function
```
```applescript
// to dump debug information from reply
```
```applescript
int main()
```
```applescript
{
```
```applescript
OSErr err;
```
```applescript
AEDesc targetAddress;
```
```applescript
```
```applescript
// Create the target address.
```
```applescript
// Using type typeApplicationURL makes it a remote procedure call event.
```
```applescript
err = AECreateDesc(typeApplicationURL, serverURL, strlen(serverURL), &targetAddress);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Create an XML-RPC Apple event
```
```applescript
AppleEvent xmlrpcEvent;
```
```applescript
err = AECreateAppleEvent(kAERPCClass, kAEXMLRPCScheme, &targetAddress,
```
```applescript
kAutoGenerateReturnID, kAnyTransactionID, &xmlrpcEvent);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(&targetAddress);
```
```applescript
```
```applescript
// Create the parameters for the event - the direct object is a record
```
```applescript
// that contains the method name, and a list of parameters
```
```applescript
AEDesc directObject;
```
```applescript
err = AECreateList(NULL, 0, true, &directObject);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Insert the method name
```
```applescript
err = AEPutParamPtr(&directObject, keyRPCMethodName, typeChar,
```
```applescript
methodName, strlen(methodName));
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Create the list for the actual parameters
```
```applescript
AEDesc paramList;
```
```applescript
err = AECreateList(NULL, 0, false, ¶mList);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Put the state index into the parameter array
```
```applescript
SInt32 stateIndex = 41; // Should correspond to South Dakota
```
```applescript
err = AEPutPtr(¶mList, 0, typeSInt32, &stateIndex,
```
```applescript
sizeof(stateIndex));
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Put the parameter list into the direct object
```
```applescript
err = AEPutParamDesc(&directObject, keyRPCMethodParam, ¶mList);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(¶mList);
```
```applescript
```
```applescript
// Put the direct object into the event
```
```applescript
err = AEPutParamDesc(&xmlrpcEvent, keyDirectObject, &directObject);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(&directObject);
```
```applescript
```
```applescript
// Request all available debugging information. That will include
```
```applescript
// the header and body for both the XML-RPC request and the reply
```
```applescript
// from the server.
```
```applescript
SInt32 debugAttr = kAEDebugXMLDebugAll;
```
```applescript
err = AEPutAttributePtr(&xmlrpcEvent, keyXMLDebuggingAttr, typeSInt32,
```
```applescript
&debugAttr, sizeof(debugAttr));
```
```applescript
```
```applescript
// Send the event
```
```applescript
AppleEvent replyEvent;
```
```applescript
AEInitializeDescInline(&replyEvent);
```
```applescript
err = AESend(&xmlrpcEvent, &replyEvent, kAEWaitReply, kAENormalPriority,
```
```applescript
kAEDefaultTimeout, NULL, NULL);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// The direct object of the reply Apple event contains
```
```applescript
// our result (the name of the state)
```
```applescript
char buffer[255];
```
```applescript
Size actualSize;
```
```applescript
err = AEGetParamPtr(&replyEvent, keyDirectObject, typeChar, NULL,
```
```applescript
buffer, sizeof(buffer), &actualSize);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
fprintf(stderr, "State is %.*s!\n", actualSize, buffer);
```
```applescript
```
```applescript
// Dump debug information
```
```applescript
dumpDebug("HTTP POST header", &replyEvent, keyAEPOSTHeaderData);
```
```applescript
dumpDebug("XML Request", &replyEvent, keyAEXMLRequestData);
```
```applescript
dumpDebug("HTTP Reply header", &replyEvent, keyAEReplyHeaderData);
```
```applescript
dumpDebug("XML Reply", &replyEvent, keyAEXMLReplyData);
```
```applescript
```
```applescript
return 0;
```
```applescript
}
```
### Displaying XML-RPC Debug Information
Listing 4-3shows a function that extracts debug information from a passed Apple event and displays it withfprintf. The information displayed depends on the key passed in thedebugDataKeyparameter. To display debug data, this function:
- CallsAEGetParamDesc, passing the key specified by thedebugDataKeyparameter and the desired typetypeChar, to extract character data for that debug key.The possible debug keys are shown inApple Event Manager API for Remote Procedure Calls.
CallsAEGetParamDesc, passing the key specified by thedebugDataKeyparameter and the desired typetypeChar, to extract character data for that debug key.
The possible debug keys are shown inApple Event Manager API for Remote Procedure Calls.
- If step 1 fails, it usesfprintfto display an error message.Otherwise, it formats the retrieved character data to show tabs, carriage returns, and line feeds, and displays it withfprintf.
If step 1 fails, it usesfprintfto display an error message.
Otherwise, it formats the retrieved character data to show tabs, carriage returns, and line feeds, and displays it withfprintf.
Listing 3-3A function to display debug information from an XML-RPC reply Apple event.
```applescript
// ------------------------- dumpDebug ----------------------------------
```
```applescript
// Extract and display debug information from a reply Apple event.
```
```applescript
```
```applescript
static void dumpDebug(const char* msg, const AppleEvent* replyEvent,
```
```applescript
OSType debugDataKey)
```
```applescript
{
```
```applescript
fprintf(stderr, "%s:\n", msg);
```
```applescript
```
```applescript
AEDesc paramDesc;
```
```applescript
OSErr err = AEGetParamDesc(replyEvent, debugDataKey,
```
```applescript
typeChar, ¶mDesc);
```
```applescript
if (err != noErr)
```
```applescript
fprintf(stderr, "\tCan't get debug data %4.4s - %d returned\n",
```
```applescript
&debugDataKey, err);
```
```applescript
else
```
```applescript
{
```
```applescript
int len = AEGetDescDataSize(¶mDesc);
```
```applescript
char* buffer = new char[len];
```
```applescript
AEGetDescData(¶mDesc, buffer, len);
```
```applescript
```
```applescript
char* p = buffer;
```
```applescript
char* pEnd = buffer + len;
```
```applescript
```
```applescript
while (p < pEnd)
```
```applescript
{
```
```applescript
char* pNext = strpbrk(p, "\r\n");
```
```applescript
if (pNext == NULL)
```
```applescript
pNext = pEnd;
```
```applescript
else
```
```applescript
{
```
```applescript
while (pNext < pEnd && (*pNext == '\r' || *pNext == '\n'))
```
```applescript
{
```
```applescript
*pNext++ = '\0';
```
```applescript
}
```
```applescript
}
```
```applescript
fprintf(stderr, "\t%.*s\n", pNext - p, p);
```
```applescript
p = pNext;
```
```applescript
}
```
```applescript
```
```applescript
AEDisposeDesc(¶mDesc);
```
```applescript
delete[] buffer;
```
```applescript
}
```
```applescript
fprintf(stderr, "\n\n");
```
```applescript
}
```
The following listing shows sample output from thedumpDebugfunction for an XML-RPC Apple event.
Listing 3-4Sample header and data from an XML-RPC post and the reply.
```applescript
HTTP POST header:
```
```applescript
POST /RPC2 HTTP/1.0
```
```applescript
User-Agent: OS X; AEServer (1.0)
```
```applescript
Host: betty.userland.com
```
```applescript
Content-Type: text/xml
```
```applescript
Content-length: 216
```
```applescript
```
```applescript
```
```applescript
XML Request:
```
```applescript
```
```applescript
```
```applescript
examples.getStateName
```
```applescript
```
```applescript
```
```applescript
```
```applescript
41
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
HTTP Reply header:
```
```applescript
HTTP/1.1 200 OK
```
```applescript
Connection: close
```
```applescript
Content-Length: 141
```
```applescript
Content-Type: text/xml
```
```applescript
Date: Mon, 13 Aug 2001 03:56:34 GMT
```
```applescript
Server: UserLand Frontier/7.0.1-WinNT
```
```applescript
```
```applescript
```
```applescript
XML Reply:
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
South Dakota
```
```applescript
```
```applescript
```
```applescript
```
## Making a SOAP Request
To make a SOAP request from an application or other code, you create an Apple event that describes the request, use theAESendfunction to send it, and extract any returned information from the reply Apple event. This process, along with the Apple Event Manager API you use, is described inRemote Procedure Calls From Applications.
This section provides sample code for sending a SOAP request to a server. Like the sample code inMaking an XML-RPC Call, it makes a request to an Internet server that returns the state name for the passed state index. That is, for an index value of 1 it returns Alabama, for 2 it returns Alaska, and so on. In this case, however, the sample code calls thegetStateNamemethod, a SOAP method on an entirely different server.
You can use the sample code in this task in a number of ways. The following steps show how to create a C++ tool with Project Builder:
- Launch Project Builder.
Launch Project Builder.
- Choose New Project from the File menu.
Choose New Project from the File menu.
- Choose the C++ tool template.
Choose the C++ tool template.
- Replace the code in the automatically generated main.cpp file with the sample code inListing 4-5,Listing 4-6,Listing 4-7, andListing 4-3, in that order.
Replace the code in the automatically generated main.cpp file with the sample code inListing 4-5,Listing 4-6,Listing 4-7, andListing 4-3, in that order.
- Use Add Frameworks from the Project menu to addCarbon.frameworkto the project.
Use Add Frameworks from the Project menu to addCarbon.frameworkto the project.
Once youâve built the tool, you can run it in Project Builder and examine its output in the Console pane, or run it in a Terminal window.
You can also build this code directly in a Terminal window with the following compile line:
```applescript
cc -g -o soap soap.cp -framework Carbon
```
If you want to compile with a C compiler, rather than a C++ compiler, youâll have to modify the code so that all variables are declared at the beginning of functions, rather than where they are used.
Listing 4-5shows include statements, constants, and declarations to place at the beginning of your code file. This code
- includes Carbon.h to gain access to the scripting API it needs
includes Carbon.h to gain access to the scripting API it needs
- defines a simple error macro that usesfprintfto show an error number and line number, then exits the application
defines a simple error macro that usesfprintfto show an error number and line number, then exits the application
- defines constants that specify the server and method name to call to get state name information
defines constants that specify the server and method name to call to get state name information
- declares a function (defined later) that creates a parameter list record
declares a function (defined later) that creates a parameter list record
- declares a debug function that is defined later
declares a debug function that is defined later
Listing 3-5Includes, constants, and declarations for making a SOAP request.
```applescript
#include
```
```applescript
```
```applescript
#define checkErr(err) \
```
```applescript
while (err != noErr) \
```
```applescript
{ fprintf(stderr, "Failed at line %d, error %d\n", __LINE__, err); \
```
```applescript
exit(-1); }
```
```applescript
```
```applescript
static const char* serverURL = "http://www.soapware.org/examples";
```
```applescript
static const char* methodName = "getStateName";
```
```applescript
static const char* methodNameSpaceURI = "http://www.soapware.org/";
```
```applescript
```
```applescript
static OSStatus createUserRecord(AEDesc* desc, const char* paramName,
```
```applescript
OSType dataType, const void* data, UInt32 dataSize);
```
```applescript
static void dumpDebug(const char* msg, const AppleEvent* reply,
```
```applescript
OSType debugDataKey);
```
### A Main Function That Makes a SOAP Request
Listing 4-2shows amainfunction that prepares a SOAP request Apple event, sends it, and displays information from the reply Apple event. To do so, it performs the following steps:
- It callsAECreateDescto create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server). It uses the constantserverURLdefined previously to specify the desired Internet server.
It callsAECreateDescto create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server). It uses the constantserverURLdefined previously to specify the desired Internet server.
- It callsAECreateAppleEventto create an Apple event with event classkAERPCClass, event IDkAESOAPScheme, and with the target address descriptor from step 1.
It callsAECreateAppleEventto create an Apple event with event classkAERPCClass, event IDkAESOAPScheme, and with the target address descriptor from step 1.
- It callsAECreateListto create the direct object for the Apple event.
It callsAECreateListto create the direct object for the Apple event.
- It callsAEPutParamPtrto insert the method name, using the keykeyRPCMethodNameand the constantmethodNamedefined previously.
It callsAEPutParamPtrto insert the method name, using the keykeyRPCMethodNameand the constantmethodNamedefined previously.
- It calls the functioncreateUserRecord, shown inListing 4-7, to create anAEDescrecord that stores the parameter name and value for a method that has one of each.
It calls the functioncreateUserRecord, shown inListing 4-7, to create anAEDescrecord that stores the parameter name and value for a method that has one of each.
- It callsAEPutParamDescto add the parameter record to the Apple eventâs direct object.
It callsAEPutParamDescto add the parameter record to the Apple eventâs direct object.
- It callsAEPutParamPtrto insert the method namespace URI, using the keykeySOAPMethodNameSpaceURIand the constantmethodNameSpaceURIdefined previously.
It callsAEPutParamPtrto insert the method namespace URI, using the keykeySOAPMethodNameSpaceURIand the constantmethodNameSpaceURIdefined previously.
- It callsAEPutParamDescto insert the direct object into the Apple event.
It callsAEPutParamDescto insert the direct object into the Apple event.
- It callsAEPutAttributePtrto turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttrand the valuekAEDebugXMLDebugAll. This step is optional.
It callsAEPutAttributePtrto turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttrand the valuekAEDebugXMLDebugAll. This step is optional.
- It initializes a reply Apple event.
It initializes a reply Apple event.
- It callsAESendto send the Apple event, passingkAEWaitReplyto indicate it will wait for a reply.
It callsAESendto send the Apple event, passingkAEWaitReplyto indicate it will wait for a reply.
- If the previous call succeeds, it callsAEGetParamPtrwith keykeyDirectObjectand desired type oftypeCharto extract the direct object of the reply Apple event. For a successful call with state index 41, the returned value is the string âSouth Dakotaâ.It callsfprintfto display the state name. For exampleState is South Dakota!
If the previous call succeeds, it callsAEGetParamPtrwith keykeyDirectObjectand desired type oftypeCharto extract the direct object of the reply Apple event. For a successful call with state index 41, the returned value is the string âSouth Dakotaâ.
It callsfprintfto display the state name. For example
```applescript
State is South Dakota!
```
- The main function then calls the functiondumpDebug, shown inListing 4-3, once each to display the header and data for the original XML-RPC request and for the reply from the server.Listing 4-8shows the possible result of these calls.
The main function then calls the functiondumpDebug, shown inListing 4-3, once each to display the header and data for the original XML-RPC request and for the reply from the server.Listing 4-8shows the possible result of these calls.
Listing 3-6main function to send a SOAP Apple event.
```applescript
//------------------------- main ----------------------------------
```
```applescript
// Builds and sends a SOAP request Apple event.
```
```applescript
// Sends the Apple event to a server that returns the state
```
```applescript
// name corresponding to the passed number; e.g., the number
```
```applescript
// 5 corresponds to the state California.
```
```applescript
// Prints the returned state name, then calls function
```
```applescript
// to dump debug information from reply
```
```applescript
int main()
```
```applescript
{
```
```applescript
OSErr err;
```
```applescript
AEDesc targetAddress;
```
```applescript
```
```applescript
// Create the target address
```
```applescript
// Using type typeApplicationURL makes it a remote procedure
```
```applescript
// call event.
```
```applescript
err = AECreateDesc(typeApplicationURL, serverURL, strlen(serverURL),
```
```applescript
&targetAddress);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Create a SOAP request Apple event
```
```applescript
AppleEvent event;
```
```applescript
err = AECreateAppleEvent(kAERPCClass, kAESOAPScheme, &targetAddress,
```
```applescript
kAutoGenerateReturnID, kAnyTransactionID, &event);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(&targetAddress);
```
```applescript
```
```applescript
// Create the parameters for the event - the direct object is a
```
```applescript
// record that contains the method name, and a list of parameters
```
```applescript
```
```applescript
AEDesc directObject;
```
```applescript
err = AECreateList(NULL, 0, true, &directObject);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Put the method name
```
```applescript
err = AEPutParamPtr(&directObject, keyRPCMethodName, typeChar,
```
```applescript
methodName, strlen(methodName));
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// The parameters for a SOAP request are a record. We use the
```
```applescript
// "AppleScript" format for records that contain user readable
```
```applescript
// names, and call a helper routine to construct this record.
```
```applescript
AEDesc paramRecord;
```
```applescript
SInt32 stateIndex = 41;
```
```applescript
err = createUserRecord(¶mRecord, "statenum", typeSInt32,
```
```applescript
&stateIndex, sizeof(stateIndex));
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Put the parameter record into the direct object
```
```applescript
err = AEPutParamDesc(&directObject, keyRPCMethodParam,
```
```applescript
¶mRecord);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(¶mRecord);
```
```applescript
```
```applescript
// Additional pieces for soap are the SOAP schema, method
```
```applescript
// namespaceURI and SOAPAction.
```
```applescript
// If the SOAP schema is not explicitly specified, it defaults
```
```applescript
// to kSOAP1999Schema for the 1999 schema
```
```applescript
// (corresponding to the 1.1 specification).
```
```applescript
// If the SOAPAction is not explicitly specified, it will be
```
```applescript
// the path part of the URL (in this case, "/examples")
```
```applescript
```
```applescript
err = AEPutParamPtr(&directObject, keySOAPMethodNameSpaceURI,
```
```applescript
typeChar, methodNameSpaceURI, strlen(methodNameSpaceURI));
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// Put the direct object into the event
```
```applescript
err = AEPutParamDesc(&event, keyDirectObject, &directObject);
```
```applescript
checkErr(err);
```
```applescript
AEDisposeDesc(&directObject);
```
```applescript
```
```applescript
// Request debugging information
```
```applescript
SInt32 debugAttr = kAEDebugXMLDebugAll;
```
```applescript
err = AEPutAttributePtr(&event, keyXMLDebuggingAttr, typeSInt32,
```
```applescript
&debugAttr, sizeof(debugAttr));
```
```applescript
```
```applescript
// Send the event
```
```applescript
AppleEvent reply;
```
```applescript
AEInitializeDescInline(&reply);
```
```applescript
err = AESend(&event, &reply, kAEWaitReply, kAENormalPriority,
```
```applescript
kAEDefaultTimeout, NULL, NULL);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
// The direct object contains our result (the name of the state)
```
```applescript
char buffer[255];
```
```applescript
Size actualSize;
```
```applescript
err = AEGetParamPtr(&reply, keyDirectObject, typeChar, NULL,
```
```applescript
buffer, sizeof(buffer), &actualSize);
```
```applescript
checkErr(err);
```
```applescript
```
```applescript
fprintf(stderr, "State is %.*s!\n", actualSize, buffer);
```
```applescript
```
```applescript
// Dump debug information
```
```applescript
dumpDebug("HTTP POST header", &reply, keyAEPOSTHeaderData);
```
```applescript
dumpDebug("XML Request", &reply, keyAEXMLRequestData);
```
```applescript
dumpDebug("HTTP Reply header", &reply, keyAEReplyHeaderData);
```
```applescript
dumpDebug("XML Reply", &reply, keyAEXMLReplyData);
```
```applescript
```
```applescript
return 0;
```
```applescript
}
```
### Creating Parameter List Records
Listing 4-7shows a function that creates a record containing the parameter name and value for a SOAP method with one parameter.
To prepare a parameter list record, this function performs the following steps:
- It callsAECreateListto create a list descriptor record for the SOAP request parameters.
It callsAECreateListto create a list descriptor record for the SOAP request parameters.
- It callsAECreateListagain to create a list descriptor for the parameter name and value.
It callsAECreateListagain to create a list descriptor for the parameter name and value.
- CallsAEPutPtrto insert the passed parameter name in the parameter name and value list, with the typetypeChar.
CallsAEPutPtrto insert the passed parameter name in the parameter name and value list, with the typetypeChar.
- CallsAEPutPtragain to insert the passed parameter data in the parameter name and value list, with the type specified the passed type.
CallsAEPutPtragain to insert the passed parameter data in the parameter name and value list, with the type specified the passed type.
- It callsAEPutParamDescto add the parameter name and value list to the parameter list record.
It callsAEPutParamDescto add the parameter name and value list to the parameter list record.
If you need to create a parameter list record for a SOAP request with multiple parameters, you can define a function with a variable length argument list. The function can iterate over the arguments, performing steps 3 and 4 (adding the name and data) for each pair of parameter arguments.
Listing 3-7A function to create a parameter list record for a SOAP request Apple event.
```applescript
// -------------------- createUserRecord -----------------------------
```
```applescript
// Creates a record containing the parameters for a SOAP request.
```
```applescript
// Uses the "AppleScript" format for records that contain user readable
```
```applescript
// names.
```
```applescript
```
```applescript
static OSStatus createUserRecord(AEDesc* desc, const char* paramName,
```
```applescript
OSType dataType, const void* data, UInt32 dataSize)
```
```applescript
{
```
```applescript
OSErr err = AECreateList(0, NULL, true, desc);
```
```applescript
if (err == noErr) {
```
```applescript
AEDesc termsList;
```
```applescript
err = AECreateList(0, NULL, false, &termsList);
```
```applescript
```
```applescript
if (err == noErr)
```
```applescript
err = AEPutPtr(&termsList, 0, typeChar,
```
```applescript
paramName, strlen(paramName));
```
```applescript
if (err == noErr)
```
```applescript
err = AEPutPtr(&termsList, 0, dataType,
```
```applescript
data, dataSize);
```
```applescript
```
```applescript
if (err == noErr)
```
```applescript
err = AEPutParamDesc(desc, keyASUserRecordFields,
```
```applescript
&termsList);
```
```applescript
```
```applescript
AEDisposeDesc(&termsList);
```
```applescript
}
```
```applescript
return err;
```
```applescript
}
```
### Displaying SOAP Request Debug Information
The sample code to display debug information from a SOAP request Apple event uses the samedumpDebugfunction as the sample code for making an XML-RPC call. That code is shown inListing 4-3. However, because the XML-RPC and SOAP protocols are different, the requests, the Apple events that represent them, and the debug output are all different. ListingListing 4-8shows sample output from thedumpDebugfunction for a SOAP request Apple event.
Listing 3-8Sample header and data from a SOAP post and the reply.
```applescript
HTTP POST header:
```
```applescript
POST /examples HTTP/1.0
```
```applescript
Host: www.soapware.org
```
```applescript
SOAPAction: "/examples"
```
```applescript
User-Agent: OS X; AEServer (1.0)
```
```applescript
Content-Type: text/xml
```
```applescript
Content-length: 538
```
```applescript
```
```applescript
```
```applescript
XML Request:
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
41
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
HTTP Reply header:
```
```applescript
HTTP/1.1 200 OK
```
```applescript
Connection: close
```
```applescript
Content-Length: 499
```
```applescript
Content-Type: text/xml; charset="us-ascii"
```
```applescript
Date: Mon, 13 Aug 2001 05:07:46 GMT
```
```applescript
Server: UserLand Frontier/7.0.1-WinNT
```
```applescript
```
```applescript
```
```applescript
XML Reply:
```
```applescript
```
```applescript
```
```applescript
```
```applescript
```
```applescript
South Dakota
```
```applescript
```
```applescript
```
```applescript
```
Copyright © 2001, 2014 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2014-07-15
---
# Glossary
- absolute object specifierAn object specifier that has enough information to identify an object or objects uniquely. For an object specifier to an application object to be complete, its outermost container must be the application itself. Seerelative object specifier.
An object specifier that has enough information to identify an object or objects uniquely. For an object specifier to an application object to be complete, its outermost container must be the application itself. Seerelative object specifier.
- Apple eventAn interprocess message that encapsulates a command in a form that can be passed across process boundaries, performed, and responded to with a reply event. When an AppleScript script is executed, a statement that targets a scriptable application may result in an Apple event being sent to that application.
An interprocess message that encapsulates a command in a form that can be passed across process boundaries, performed, and responded to with a reply event. When an AppleScript script is executed, a statement that targets a scriptable application may result in an Apple event being sent to that application.
- AppleScriptA scripting language that makes possible direct control of scriptable applications and scriptable parts of macOS.
A scripting language that makes possible direct control of scriptable applications and scriptable parts of macOS.
- AppleScript commandA script command provided by AppleScript. AppleScript commands do not have to be included intellstatements.
A script command provided by AppleScript. AppleScript commands do not have to be included intellstatements.
- application commandA command that is defined by scriptable application to provide access to a scriptable feature. An application command must either be included in atellstatement or include the name of the application in its direct parameter.
A command that is defined by scriptable application to provide access to a scriptable feature. An application command must either be included in atellstatement or include the name of the application in its direct parameter.
- application objectAn object stored in an application or its documents and managed by the application.
An object stored in an application or its documents and managed by the application.
- arbitrary reference formA reference form that specifies an arbitrary object in a container.
A reference form that specifies an arbitrary object in a container.
- assignment statementA statement that assigns a value to a variable. Assignment statements use thecopyorsetcommands.
A statement that assigns a value to a variable. Assignment statements use thecopyorsetcommands.
- attributeA characteristic that can be considered or ignored in aconsideringorignoringstatement.
A characteristic that can be considered or ignored in aconsideringorignoringstatement.
- binary operatorAn operator that derives a new value from a pair of values.
An operator that derives a new value from a pair of values.
- booleanA logical truth value; see thebooleanclass.
A logical truth value; see thebooleanclass.
- Boolean expressionAn expression whose value can be either true or false.
An expression whose value can be either true or false.
- chevronsSeedouble angle brackets.
Seedouble angle brackets.
- child script objectAscriptobject that inherits properties and handlers from another object, called the parent.
Ascriptobject that inherits properties and handlers from another object, called the parent.
- class(1) A category for objects that share characteristics such as properties and elements and respond to the same commands. (2) The label for the AppleScriptclasspropertyâa reserved word that specifies the class to which an object belongs.
(1) A category for objects that share characteristics such as properties and elements and respond to the same commands. (2) The label for the AppleScriptclasspropertyâa reserved word that specifies the class to which an object belongs.
- coercionThe process of converting an object from one class to another. For example, an integer value can be coerced into a real value. Also, the software that performs such a conversion. Also known as object conversion.
The process of converting an object from one class to another. For example, an integer value can be coerced into a real value. Also, the software that performs such a conversion. Also known as object conversion.
- commandA word or series of words that requests an action. See alsohandler.
A word or series of words that requests an action. See alsohandler.
- commentText that remains in a script after compilation but is ignored by AppleScript when the script is executed.
Text that remains in a script after compilation but is ignored by AppleScript when the script is executed.
- compileIn AppleScript, to convert a script from the form typed into a script editor to a form that can be used by AppleScript. The process of compiling a script includes syntax and vocabulary checks. A script is compiled when you first run it and again when you modify it and then run it again, save it, or check its syntax.
In AppleScript, to convert a script from the form typed into a script editor to a form that can be used by AppleScript. The process of compiling a script includes syntax and vocabulary checks. A script is compiled when you first run it and again when you modify it and then run it again, save it, or check its syntax.
- compiled scriptThe form to which a script is converted when you compile it.
The form to which a script is converted when you compile it.
- composite valueA value that contains other values. Lists, records, and strings are examples of composite values.
A value that contains other values. Lists, records, and strings are examples of composite values.
- compound statementA statement that occupies more than one line and contains other statements. A compound statement begins with a reserved word indicating its function and ends with the wordend. See alsosimple statement.
A statement that occupies more than one line and contains other statements. A compound statement begins with a reserved word indicating its function and ends with the wordend. See alsosimple statement.
- conditional statementSeeif statement.
Seeif statement.
- considering statementA control statement that lists a specific set of attributes to be considered when AppleScript performs operations on strings or sends commands to applications.
A control statement that lists a specific set of attributes to be considered when AppleScript performs operations on strings or sends commands to applications.
- constantA reserved word with a predefined value; see theconstantclass.
A reserved word with a predefined value; see theconstantclass.
- containerAn object that contains one or more other objects, known as elements. You specify containers with the reserved wordsoforin.
An object that contains one or more other objects, known as elements. You specify containers with the reserved wordsoforin.
- continuation characterA character used in Script Editor to extend a statement to the next line. With a U.S. keyboard, you can enter this character by typing Option-l (lower-case L).
A character used in Script Editor to extend a statement to the next line. With a U.S. keyboard, you can enter this character by typing Option-l (lower-case L).
- continue statementA statement that controls when and how other statements are executed. AppleScript defines standard control statements such asif,repeat, andwhile.
A statement that controls when and how other statements are executed. AppleScript defines standard control statements such asif,repeat, andwhile.
- control statementA statement that causes AppleScript to exit the current handler and transfer execution to the handler with the same name in the parent. Acontinuestatement can also be used to invoke an inherited handler in the local context.
A statement that causes AppleScript to exit the current handler and transfer execution to the handler with the same name in the parent. Acontinuestatement can also be used to invoke an inherited handler in the local context.
- current applicationThe application that is using the AppleScript component to compile and execute scripts (typically, Script Editor).
The application that is using the AppleScript component to compile and execute scripts (typically, Script Editor).
- current scriptThe script currently being executed.
The script currently being executed.
- current targetThe object that is the current default target for commands.
The object that is the current default target for commands.
- dataA class used for data that do not belong to any of the other AppleScript classes; see thedataclass.
A class used for data that do not belong to any of the other AppleScript classes; see thedataclass.
- dateA class that specifies a time, day of the month, month, and year; see thedateclass.
A class that specifies a time, day of the month, month, and year; see thedateclass.
- declarationThe first occurrence of a variable or property identifier in a script. The form and location of the declaration determine how AppleScript treats the identifier in that scriptâfor example, as a property, global variable, or local variable.
The first occurrence of a variable or property identifier in a script. The form and location of the declaration determine how AppleScript treats the identifier in that scriptâfor example, as a property, global variable, or local variable.
- default targetThe object that receives a command if no object is specified or if the object is incompletely specified in the command. Default (or implicit) targets are specified intellstatements.
The object that receives a command if no object is specified or if the object is incompletely specified in the command. Default (or implicit) targets are specified intellstatements.
- delegationThe handing off of control to another object. In AppleScript, the use of acontinuestatement to call a handler in a parent object or the current application.
The handing off of control to another object. In AppleScript, the use of acontinuestatement to call a handler in a parent object or the current application.
- dialectA version of the AppleScript language that resembles a specific human language or programming language. As of AppleScript 1.3, English is the only dialect supported.
A version of the AppleScript language that resembles a specific human language or programming language. As of AppleScript 1.3, English is the only dialect supported.
- dictionaryThe set of commands, objects, and other terminology that is understood by an application or other scriptable entity. You can display an applicationâs dictionary with Script Editor.
The set of commands, objects, and other terminology that is understood by an application or other scriptable entity. You can display an applicationâs dictionary with Script Editor.
- direct parameterThe parameter immediately following a command, which typically specifies the object to which the command is sent.
The parameter immediately following a command, which typically specifies the object to which the command is sent.
- double angle bracketsCharacters («») typically used by AppleScript to enclose raw data. With a U.S. keyboard, you can enter double angle brackets (also known as chevrons) by typing Option-Backslash and Shift-Option-Backslash.
Characters («») typically used by AppleScript to enclose raw data. With a U.S. keyboard, you can enter double angle brackets (also known as chevrons) by typing Option-Backslash and Shift-Option-Backslash.
- elementAn object contained within another object. An object can typically contain zero or more of each of its elements.
An object contained within another object. An object can typically contain zero or more of each of its elements.
- empty listA list containing no items. See thelistclass.
A list containing no items. See thelistclass.
- error expressionAn expression, usually atextobject, that describes an error.
An expression, usually atextobject, that describes an error.
- error handlerA collection of statements that are executed in response to an error message. See thetrystatement.
A collection of statements that are executed in response to an error message. See thetrystatement.
- error messageA message that is supplied by an application, by AppleScript, or by macOS when an error occurs during the handling of a command.
A message that is supplied by an application, by AppleScript, or by macOS when an error occurs during the handling of a command.
- error numberAn integer that identifies an error.
An integer that identifies an error.
- evaluationThe conversion of an expression to a value.
The conversion of an expression to a value.
- every reference formA reference form that specifies every object of a particular type in a container.
A reference form that specifies every object of a particular type in a container.
- exit statementA statement used in the body of arepeatstatement to exit the Repeat statement.
A statement used in the body of arepeatstatement to exit the Repeat statement.
- explicit run handlerA handler at the top level of ascriptobject that begins withon runand ends withend. A singlescriptobject can include an explicitrunhandler or an implicitrunhandler, but not both.
A handler at the top level of ascriptobject that begins withon runand ends withend. A singlescriptobject can include an explicitrunhandler or an implicitrunhandler, but not both.
- expressionIn AppleScript, any series of words that has a value.
In AppleScript, any series of words that has a value.
- filterA phrase, added to a reference to a system or application object, that specifies elements in a container that match one or more conditions.
A phrase, added to a reference to a system or application object, that specifies elements in a container that match one or more conditions.
- filter reference formA reference form that specifies all objects in a container that match a condition specified by a Boolean expression.
A reference form that specifies all objects in a container that match a condition specified by a Boolean expression.
- formal parameterSeeparameter variable.
Seeparameter variable.
- global variableA variable that is available anywhere in the script in which it is defined.
A variable that is available anywhere in the script in which it is defined.
- handlerA collection of statements that can be invoked by name. See alsocommand.
A collection of statements that can be invoked by name. See alsocommand.
- identifierA series of characters that identifies a value or handler in AppleScript. Identifiers are used to name variables, handlers, parameters, properties, and commands.
A series of characters that identifies a value or handler in AppleScript. Identifiers are used to name variables, handlers, parameters, properties, and commands.
- ID reference formA reference form that specifies an object by the value of its ID property.
A reference form that specifies an object by the value of its ID property.
- if statementA control statement that contains one or more Boolean expressions whose results determine whether to execute other statements within theifstatement.
A control statement that contains one or more Boolean expressions whose results determine whether to execute other statements within theifstatement.
- ignoring statementA control statement that lists a specific set of attributes to be ignored when AppleScript performs operations on text strings or sends commands to applications.
A control statement that lists a specific set of attributes to be ignored when AppleScript performs operations on text strings or sends commands to applications.
- implicit run handlerAll the statements at the top level of a script except for property definitions,scriptobject definitions, and other handlers. A singlescriptobject can include an explicitrunhandler or an implicitrunhandler, but not both.
All the statements at the top level of a script except for property definitions,scriptobject definitions, and other handlers. A singlescriptobject can include an explicitrunhandler or an implicitrunhandler, but not both.
- index reference formA reference form that specifies an object by describing its position with respect to the beginning or end of a container.
A reference form that specifies an object by describing its position with respect to the beginning or end of a container.
- inheritanceThe ability of a childscriptobject to take on the properties and handlers of a parent object.
The ability of a childscriptobject to take on the properties and handlers of a parent object.
- inheritance chainThe hierarchy of objects that AppleScript searches to find the target for a command or the definition of a term.
The hierarchy of objects that AppleScript searches to find the target for a command or the definition of a term.
- initializing a script objectThe process of creating ascriptobject from the properties and handlers listed in ascriptobject definition. AppleScript creates ascriptobject when it runs a script or handler that contains ascriptobject definition.
The process of creating ascriptobject from the properties and handlers listed in ascriptobject definition. AppleScript creates ascriptobject when it runs a script or handler that contains ascriptobject definition.
- insertion pointA location where another object or objects can be added.
A location where another object or objects can be added.
- integerA positive or negative number without a fractional part; see theintegerclass.
A positive or negative number without a fractional part; see theintegerclass.
- itemA value in a list or record. An item can be specified by its offset from the beginning or end of the list or record.
A value in a list or record. An item can be specified by its offset from the beginning or end of the list or record.
- keywordA word that is part of the AppleScript language. Synonymous withreserved word.
A word that is part of the AppleScript language. Synonymous withreserved word.
- labeled parameterA parameter that is identified by a label. See alsopositional parameter.
A parameter that is identified by a label. See alsopositional parameter.
- lifetimeThe period of time over which a variable or property is in existence.
The period of time over which a variable or property is in existence.
- listAn ordered collection of values; see thelistclass.
An ordered collection of values; see thelistclass.
- literalA value that evaluates to itself.
A value that evaluates to itself.
- local variableA variable that is available only in the handler in which it is defined. Variables that are defined within handlers are local unless they are explicitly declared as global variables.
A variable that is available only in the handler in which it is defined. Variables that are defined within handlers are local unless they are explicitly declared as global variables.
- log statementA script statement that reports the value of one or more variables to the Event Log pane of a script window, and to the Event Log History window, if it is open.
A script statement that reports the value of one or more variables to the Event Log pane of a script window, and to the Event Log History window, if it is open.
- loopA series of statements that is repeated.
A series of statements that is repeated.
- loop variableA variable whose value controls the number of times the statements in arepeatstatement are executed.
A variable whose value controls the number of times the statements in arepeatstatement are executed.
- middle reference formA reference form that specifies the middle object of a particular class in a container. (This form is rarely used.)
A reference form that specifies the middle object of a particular class in a container. (This form is rarely used.)
- name reference formA reference form that specifies an object by nameâthat is, by the value of itsnameproperty.
A reference form that specifies an object by nameâthat is, by the value of itsnameproperty.
- nested control statementA control statement that is contained within another control statement.
A control statement that is contained within another control statement.
- numberA synonym for the AppleScript classesintegerandreal.
A synonym for the AppleScript classesintegerandreal.
- objectAn instantiation of a class definition, which can include properties and actions.
An instantiation of a class definition, which can include properties and actions.
- object conversionSeecoercion.
Seecoercion.
- object specifierA phrase specifies the information needed to find another object in terms of the objects in which it is contained. See alsoabsolute object specifier,relative object specifier, andreference form.
A phrase specifies the information needed to find another object in terms of the objects in which it is contained. See alsoabsolute object specifier,relative object specifier, andreference form.
- operandAn expression from which an operator derives a value.
An expression from which an operator derives a value.
- operationThe evaluation of an expression that contains an operator.
The evaluation of an expression that contains an operator.
- operatorA symbol, word, or phrase that derives a value from another value or pair of values.
A symbol, word, or phrase that derives a value from another value or pair of values.
- optional parameterA parameter that need not be included for a command to be successful.
A parameter that need not be included for a command to be successful.
- outside property, variable, or statementA property, variable, or statement in ascriptobject but occurs outside of any handlers or nestedscriptobjects.
A property, variable, or statement in ascriptobject but occurs outside of any handlers or nestedscriptobjects.
- parameter variableAn identifier in a handler definition that represents the actual value of a parameter when the handler is called. Also called aformal parameter.
An identifier in a handler definition that represents the actual value of a parameter when the handler is called. Also called aformal parameter.
- parent objectAn object from which anotherscriptobject, called the child, inherits properties and handlers. A parent object may be any object, such as alistor anapplicationobject, but it is typically anotherscriptobject.
An object from which anotherscriptobject, called the child, inherits properties and handlers. A parent object may be any object, such as alistor anapplicationobject, but it is typically anotherscriptobject.
- positional parameterA handler parameter that is identified by the order in which it is listed. In a handler call, positional parameters are enclosed in parentheses and separated by commas. They must be listed in the order in which they appear in the corresponding handler definition.
A handler parameter that is identified by the order in which it is listed. In a handler call, positional parameters are enclosed in parentheses and separated by commas. They must be listed in the order in which they appear in the corresponding handler definition.
- propertyA labeled container in which to store a value. Properties can specify characteristics of objects.
A labeled container in which to store a value. Properties can specify characteristics of objects.
- property reference formA reference form that specifies a property of anapplicationobject,recordorscriptobject.
A reference form that specifies a property of anapplicationobject,recordorscriptobject.
- range reference formA reference form that specifies a series of objects of the same class in the same container.
A reference form that specifies a series of objects of the same class in the same container.
- raw formatAppleScript terms enclosed in double angle brackets, or chevrons («»). AppleScript uses raw format because it cannot find a script term in any available dictionary, or cannot display data in its native format.
AppleScript terms enclosed in double angle brackets, or chevrons («»). AppleScript uses raw format because it cannot find a script term in any available dictionary, or cannot display data in its native format.
- realA number that can include a decimal fraction; see therealclass.
A number that can include a decimal fraction; see therealclass.
- recordAn unordered collection of properties, identified by unique labels; see therecordclass.
An unordered collection of properties, identified by unique labels; see therecordclass.
- recordable applicationAn application that uses Apple events to report user actions for recording purposes. When recording is turned on, Script Editor creates statements corresponding to any significant actions you perform in a recordable application.
An application that uses Apple events to report user actions for recording purposes. When recording is turned on, Script Editor creates statements corresponding to any significant actions you perform in a recordable application.
- recursive handlerA handler that calls itself.
A handler that calls itself.
- referenceAn object that encapsulates an object specifier.
An object that encapsulates an object specifier.
- reference formThe syntax for identifying an object or group of objects in an application or other containerâthat is, the syntax for constructing an object specifier. AppleScript defines reference forms for arbitrary, every, filter, ID, index, middle, name, property, range, and relative.
The syntax for identifying an object or group of objects in an application or other containerâthat is, the syntax for constructing an object specifier. AppleScript defines reference forms for arbitrary, every, filter, ID, index, middle, name, property, range, and relative.
- relative object specifierAn object specifier that does not include enough information to identify an object or objects uniquely. When AppleScript encounters a partial object specifier, it uses the default object specified in the enclosingtellstatement to complete the reference. Seeabsolute object specifier.
An object specifier that does not include enough information to identify an object or objects uniquely. When AppleScript encounters a partial object specifier, it uses the default object specified in the enclosingtellstatement to complete the reference. Seeabsolute object specifier.
- relative reference formA reference form that specifies an object or location by describing its position in relation to another object, known as the base, in the same container.
A reference form that specifies an object or location by describing its position in relation to another object, known as the base, in the same container.
- repeat statementA control statement that contains a series of statements to be repeated and, in most cases, instructions that specify when the repetition stops.
A control statement that contains a series of statements to be repeated and, in most cases, instructions that specify when the repetition stops.
- required parameterA parameter that must be included for a command to be successful.
A parameter that must be included for a command to be successful.
- reserved wordA word that is part of the AppleScript language. Synonymous withkeyword.
A word that is part of the AppleScript language. Synonymous withkeyword.
- resultA value generated when a command is executed or an expression evaluated.
A value generated when a command is executed or an expression evaluated.
- return statementA statement that exits a handler and optionally returns a specified value.
A statement that exits a handler and optionally returns a specified value.
- scopeThe range over which AppleScript recognizes a variable or property, which determines where else in a script you may refer to that variable or property.
The range over which AppleScript recognizes a variable or property, which determines where else in a script you may refer to that variable or property.
- scriptA series of written instructions that, when executed, cause actions in applications or macOS.
A series of written instructions that, when executed, cause actions in applications or macOS.
- scriptable applicationAn application that can be controlled by a script. For AppleScript, that means being responsive to interapplication messages, called Apple events, sent when a script command targets the application.
An application that can be controlled by a script. For AppleScript, that means being responsive to interapplication messages, called Apple events, sent when a script command targets the application.
- script applicationAn application whose only function is to run the script associated with it.
An application whose only function is to run the script associated with it.
- script editorAn application used to create and modify scripts.
An application used to create and modify scripts.
- Script EditorThe script-editing application distributed with AppleScript.
The script-editing application distributed with AppleScript.
- scripting additionA file that provides additional commands or coercions you can use in scripts. If a scripting addition is located in the Scripting Additions folder, its terminology is available for use by any script.
A file that provides additional commands or coercions you can use in scripts. If a scripting addition is located in the Scripting Additions folder, its terminology is available for use by any script.
- scripting addition commandA command that is implemented as a scripting addition.
A command that is implemented as a scripting addition.
- script libraryA script saved in a Script Libraries folder so it can be used by other scripts.
A script saved in a Script Libraries folder so it can be used by other scripts.
- script objectA user-defined object that can combine data (in the form of properties) and actions (in the form of handlers and additionalscriptobjects).
A user-defined object that can combine data (in the form of properties) and actions (in the form of handlers and additionalscriptobjects).
- script object definitionA compound statement that contains a collection of properties, handlers, and other AppleScript statements.
A compound statement that contains a collection of properties, handlers, and other AppleScript statements.
- simple statementOne that can be written on a single line. See alsocompound statement.
One that can be written on a single line. See alsocompound statement.
- simple valueA value, such as an integer or a constant, that does not contain other values.
A value, such as an integer or a constant, that does not contain other values.
- Standard suiteA set of standard AppleScript terminology that a scriptable application should support if possible. The Standard suite contains commands such ascount,delete,duplicate, andmake, and classes such asapplication,document, andwindow.
A set of standard AppleScript terminology that a scriptable application should support if possible. The Standard suite contains commands such ascount,delete,duplicate, andmake, and classes such asapplication,document, andwindow.
- statementA series of lexical elements that follows a particular AppleScript syntax. Statements can include keywords, variables, operators, constants, expressions, and so on. See alsocompound statement,simple statement.
A series of lexical elements that follows a particular AppleScript syntax. Statements can include keywords, variables, operators, constants, expressions, and so on. See alsocompound statement,simple statement.
- statement blockOne or more statements enclosed in a compound statement and having anendstatement.
One or more statements enclosed in a compound statement and having anendstatement.
- stringA synonym for thetextclass.
A synonym for thetextclass.
- styled textText that may include style and font information. Not supported in AppleScript 2.0.
Text that may include style and font information. Not supported in AppleScript 2.0.
- suiteWithin an application's scriptability information, a grouping of terms associated with related operations.
Within an application's scriptability information, a grouping of terms associated with related operations.
- synonymAn AppleScript word, phrase, or language element that has the same meaning as another AppleScript word, phrase, or language element. For example, the operatordoes not equalis a synonym forâ.
An AppleScript word, phrase, or language element that has the same meaning as another AppleScript word, phrase, or language element. For example, the operatordoes not equalis a synonym forâ.
- syntaxThe arrangement of words in an AppleScript statement.
The arrangement of words in an AppleScript statement.
- syntax descriptionThe rules for constructing a valid AppleScript statement of a particular type.
The rules for constructing a valid AppleScript statement of a particular type.
- system objectAn object that is part of a scriptable element of macOS.
An object that is part of a scriptable element of macOS.
- targetThe recipient of a command. Potential targets includeapplicationobjects,scriptobjects (including the current script), and the current application.
The recipient of a command. Potential targets includeapplicationobjects,scriptobjects (including the current script), and the current application.
- tell statementA control statement that specifies the default target for the statements it contains.
A control statement that specifies the default target for the statements it contains.
- testA Boolean expression that specifies the conditions of a filter or anifstatement.
A Boolean expression that specifies the conditions of a filter or anifstatement.
- textAn ordered series of characters (a text string); see thetextclass.
An ordered series of characters (a text string); see thetextclass.
- try statementA two-part compound statement that contains a series of AppleScript statements, followed by an error handler to be invoked if any of those statements cause an error.
A two-part compound statement that contains a series of AppleScript statements, followed by an error handler to be invoked if any of those statements cause an error.
- unary operatorAn operator that derives a new value from a single value.
An operator that derives a new value from a single value.
- UnicodeAn international standard that uses a 16-bit encoding to uniquely specify the characters and symbols for all commonly used languages.
An international standard that uses a 16-bit encoding to uniquely specify the characters and symbols for all commonly used languages.
- Unicode code pointA unique number that represents a character and allows it to be represented in an abstract way, independent of how it is rendered.
A unique number that represents a character and allows it to be represented in an abstract way, independent of how it is rendered.
- Unicode textA class that represents an ordered series of two-byte Unicode characters.
A class that represents an ordered series of two-byte Unicode characters.
- use statementA control statement that declares a required resource for a script and may import terminology from that resource.
A control statement that declares a required resource for a script and may import terminology from that resource.
- user-defined commandA command that is implemented by a handler defined in ascriptobject.
A command that is implemented by a handler defined in ascriptobject.
- using terms from statementA control statement that instructs AppleScript to use the terminology from the specified application in compiling the enclosed statements.
A control statement that instructs AppleScript to use the terminology from the specified application in compiling the enclosed statements.
- variableA named container in which to store a value.
A named container in which to store a value.
- with timeout statementA control statement that specifies the amount of time AppleScript waits for application commands to complete before stopping execution of the script.
A control statement that specifies the amount of time AppleScript waits for application commands to complete before stopping execution of the script.
- with transaction statementA control statement that allows you to take advantage of applications that support the notion of a transactionâa sequence of related events that should be performed as if they were a single operation, such that either all of the changes are applied or none are.
A control statement that allows you to take advantage of applications that support the notion of a transactionâa sequence of related events that should be performed as if they were a single operation, such that either all of the changes are applied or none are.
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25
---
# About AppleScriptâs Support for XML-RPC and SOAP
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Starting with OS X version 10.1, AppleScript and the Apple Event Manager provide XML-RPC and SOAP support such that:
- Scripters can make XML-RPC calls and SOAP requests from scripts.
Scripters can make XML-RPC calls and SOAP requests from scripts.
- Developers can make XML-RPC calls and SOAP requests from applications or other code by sending Apple events.
Developers can make XML-RPC calls and SOAP requests from applications or other code by sending Apple events.
## The XML-RPC and SOAP Protocols
Aremote procedure callis a request to a server application at another location to perform operations and return information.XML-RPCis a simple protocol that allows software running in different environments to make remote procedure calls over the Internet. XML-RPC uses two industry standards: XML (extensible markup language) for encoding messages, and HTTP (hypertext transfer protocol) for transporting them. A properly formatted XML-RPC message is an HTTP POST request whose body is in XML. The specified remote server executes the requested call and returns any requested data in XML format.
XML-RPC recognizes procedure parameters by position. Parameters and return values can be simple types such as numbers, strings, and dates, or more complex types such as structures and arrays. To learn more about XML-RPC messages, see the XML-RPC specification athttp://www.xmlrpc.com/spec.
SOAP (Simple Object Access Protocol)is an RPC protocol designed for a distributed environment, where a server may consist of a hierarchy of objects whose methods can be called over the Internet. A goal of SOAP is to establish a standard protocol that will serve both web service providers and service users. As with other remote procedure call protocols, SOAP uses XML to encode messages and HTTP to transport them. A SOAP request contains a header and an envelope; the envelope in turn contains the body of the request.
One key difference between the SOAP and XML-RPC protocols is that with SOAP, parameters are notational (a request must encode the method parameter names within its XML), rather than positional (recognized by position). To learn more about SOAP messages, see the SOAP specification athttp://www.w3.org/TR/.
Remote procedure calls provide a powerful tool for accessing services over the Internet. For example, there are already a variety of web-based servers that can check spelling, translate text between languages, provide stock prices, supply weather and traffic information, and more. You can find available services at sites such as XMethods athttp://www.xmethods.net/. There you can also find information youâll need to make remote procedure calls to these services.
## AppleScript Support for Remote Procedure Calls
This section describes how to make XML-RPC and SOAP requests from scripts and from applications or other code. Using this support, both scripters and developers can take advantage of the growing number of XML-RPC and SOAP servers available on the Internet.
With OS X version 10.1, the Apple Event Manager is able to process Apple events that encapsulate remote procedure calls, whether the events originate from scripts or applications.Figure 2-1shows a simplified view of this process.
The Apple Event Manager recognizes a remote procedure call Apple event by its address descriptor, which uses the descriptor typetypeApplicationURL. To process a remote procedure call Apple event (assuming the event and the XML it contains are properly formatted), the Apple Event Manager performs these basic steps:
- It uses information from the Apple event to build the XML that represents the remote procedure call.
It uses information from the Apple event to build the XML that represents the remote procedure call.
- It opens a connection to the specified server.
It opens a connection to the specified server.
- It sends the XML via HTTP POST request.
It sends the XML via HTTP POST request.
- It waits for a response.
It waits for a response.
- It parses the XML of the response.
It parses the XML of the response.
- It constructs a reply Apple event.
It constructs a reply Apple event.
- It returns the reply.
It returns the reply.
Scripters can take advantage of this capability by adding statements to their scripts that specify XML-RPC or SOAP requests. Application developers can create and send Apple events directly to invoke XML-RPC or SOAP requests.
### Remote Procedure Calls From Scripts
When you compile and execute a script, the AppleScript component works with the Apple Event Manager to convert script statements into Apple events that are sent to the specified applications. The following sections describe the terminology and syntax for making XML-RPC calls and SOAP requests from scripts.
#### AppleScript Terminology for Remote Procedure Calls
AppleScript 1.7 for OS X version 10.1 can specify Internet applications as targets of Tell statements or within Using Terms From blocks. When you specify an XML-RPC server or a SOAP server in one of these statements, the Apple Event Manager generates a dictionary that makes the terminology for remote procedure calls available to your script. That terminology includes the following terms that specify XML-RPC and SOAP requests:
- call xmlrpc
call xmlrpc
- call soap
call soap
The next sections describe how to use AppleScriptâs remote procedure call terminology.
#### XML-RPC Script Statements
To make an XML-RPC request from a script, you must specify an XML-RPC server as the target application for the request. To do so, you use a statement like the following, which specifies an XML-RPC server that provides spell-checking services over the Internet:
```applescript
tell application "http://www.stuffeddog.com/speller/speller-rpc.cgi"
```
In this statement, the XML-RPC server application isspeller-rpc.cgiand the remote location is specified by the URLhttp://www.stuffeddog.com/speller/. You can also use the following alternate syntax (where the symbol¬(Option-l) denotes a continuation of one script statement onto more than one line), but this form is converted to the above form when the script is compiled:
```applescript
tell application "speller-rpc.cgi" of machine ¬
```
```applescript
"http://www.stuffeddog.com/speller"
```
Once you have specified an XML-RPC server, you can make remote procedure calls within a script block (such as a Tell statement) that specifies that server:
```applescript
tell application "http://www.stuffeddog.com/speller/speller-rpc.cgi"
```
```applescript
-- remote procedure calls here
```
```applescript
end tell
```
To specify a name and parameters for the remote procedure call, you use script statements like the following:
```applescript
set returnValue to¬
```
```applescript
call xmlrpc {method name:"someMethod",¬
```
```applescript
parameters: {parameter1, parameter2} }
```
This statement specifies a remote procedure call with two parameters. (You use the same terminology,method name:, whether specifying a function or method.) The parameters are represented as a list. The returned information is stored in the variablereturnValue. Because XML-RPC parameter syntax is positional, you donât need to provide the parameter names for a given procedure call. An XML-RPC server returns an error if the passed XML is not properly formatted.
The following example combines a Tell block with a remote procedure call to the spell-checking server specified earlier.
```applescript
set myText to "My frst naem is John"
```
```applescript
tell application "http://www.stuffeddog.com/speller/speller-rpc.cgi"
```
```applescript
set returnValue to call xmlrpc {method name:"speller.spellCheck",¬
```
```applescript
parameters: {myText} }
```
```applescript
end tell
```
This sample shows how easy it can be to set up a remote procedure call from a script. The first line sets a local variable to a text string to be checked. Then the Tell statement specifies an Internet spell-checking server. The single statement in the Tell block calls thespeller.spellCheckfunction, passing the local string variable as the single parameter (the text to be checked) and storing the result in a second local variable. This particular remote procedure returns a list that contains, for each misspelled word, a list of suggested corrections, the location of the word in the text, and the misspelled word itself.Listing 2-1shows an example of such a list.
Listing 1-1Sample list of misspelled words returned by spellCheck remote procedure call.
```applescript
{{suggestions:{"fast", "fest", "first", "fist", "Forst",
```
```applescript
"frat", "fret", "frist", "frit", "frost", "frot", "fust"},
```
```applescript
location:4, |word|:"frst"}, {suggestions:{"haem", "na em",
```
```applescript
"na-em", "naam", "nae", "nae m", "nae-m", "nael", "Naim",
```
```applescript
"nam", "name", "neem"}, location:9, |word|:"naem"}}
```
Note that this is not the raw data returned from the remote procedure call. When you execute the script shown above, the AppleScript component calls on the Apple Event Manager to convert thecall xmlrpcstatement to an Apple event and send the event to the specified server. The Apple Event Manager recognizes the event and processes it by formatting the remote procedure call into proper XML, opening a connection, sending the message, waiting for a reply, formatting the returned XML into an Apple event, and returning the event.
For a complete script that uses remote procedure calls to check spelling, seeScripting an XML-RPC Call.
#### SOAP Script Statements
The process for making SOAP requests in AppleScript scripts is very similar to the process for XML-RPC, though it uses the termcall soaprather thancall xmlrpc. To specify a SOAP server as the target application for a SOAP request, you use a statement like the following:
```applescript
tell application "http://services.xmethods.net:80/perl/soaplite.cgi"
```
In this statement, the SOAP server application issoaplite.cgi, a server that can perform English to French translation, and the remote location is specified by the URLhttp://services.xmethods.net:80/perl/. Once you have specified a SOAP server on a remote machine, you can make SOAP requests within a script block that specifies that server:
```applescript
tell application "http://services.xmethods.net:80/perl/soaplite.cgi"
```
```applescript
-- SOAP requests here
```
```applescript
end tell
```
To specify a method name and parameters for the SOAP request, you use script statements like the following (where the symbol¬(Option-l) denotes a continuation of one script statement onto more than one line):
```applescript
set returnValue to call soap {method name:"BabelFish", ¬
```
```applescript
method namespace uri:"urn:xmethodsBabelFish", ¬
```
```applescript
parameters:{translationmode:direction as string, ¬
```
```applescript
sourcedata:theText as string}, ¬
```
```applescript
SOAPAction:"urn:xmethodsBabelFish#BabelFish"}
```
This statement specifies a SOAP request to a method namedBabelFishwith two parameters,translationmode(such as English to French) andsourcedata(the text to be translated). The returned information (translated text) is stored in the variablereturnValue. Unlike the case with XML-RPC calls, for a SOAP request you must specify the names of the parameters for the specified method. While an XML-RPC call represents parameters as a list, a SOAP request represents them as a record. The server will return an error if the passed XML is not properly formatted.
The following example combines a Tell block with a SOAP request to the translation server specified earlier.
```applescript
set theText to "The spirit is willing but the flesh is weak."
```
```applescript
set direction to "en_fr"
```
```applescript
tell application "http://services.xmethods.net:80/perl/soaplite.cgi"
```
```applescript
set resultText to call soap {method name:"BabelFish", ¬
```
```applescript
method namespace uri:"urn:xmethodsBabelFish", ¬
```
```applescript
parameters:{translationmode:direction as string, ¬
```
```applescript
sourcedata:theText as string}, ¬
```
```applescript
SOAPAction:"urn:xmethodsBabelFish#BabelFish"}
```
```applescript
end tell
```
The first two lines set local variables for the text to be translated and the direction of translation (from English to French). The Tell statement specifies an Internet language translation server. Thecall soapstatement in the Tell block calls theBabelFishfunction, specifying two parameters by name (translationmodeandsourcedata), and passing the local variables as the parameter values. All the terms shown in thecall soapstatement in this example are required exceptparameters:(because a SOAP method may have no parameters). The resulting translated text is stored in another local variable.
You obtain values for themethod namespace uri:andSOAPAction:terms from the services themselves. For example, many SOAP services publish the information needed to use their services at sites such as XMethods athttp://www.xmethods.net/. You can learn more about SOAP name spaces and SOAPAction in the SOAP specification athttp://www.w3.org/TR/.
When you execute this script, AppleScript and the Apple Event Manager take care of formatting the SOAP request into proper XML, opening a connection, sending the message, waiting for a reply, formatting the returned XML into an Apple event, and returning the event.
For a complete script that uses SOAP requests to translate English text to French, seeScripting a SOAP Request.
### Remote Procedure Calls From Applications
As described earlier, the Apple Event Manager is now able (in OS X version 10.1) to process Apple events that encapsulate remote procedure calls, whether the events originate from scripts or applications. Assuming the Apple event and the XML it contains are properly formatted, the Apple Event Manager extracts the XML, establishes a connection to the specified server, sends the request via HTTP, waits for a response, parses the XML of the response, constructs a reply Apple event, and returns the reply.
To take advantage of this support, applications and other code can create Apple events to send either XML-RPC or Soap requests. The process includes the following steps:
- Link withCarbon.framework.
Link withCarbon.framework.
- Prepare any necessary Apple event descriptors, including an address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
Prepare any necessary Apple event descriptors, including an address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
- Create an Apple event with event classkAERPCClassand event typekAEXMLRPCScheme(for XML-RPC) orkAESOAPScheme(for SOAP), and with the target address descriptor created previously.
Create an Apple event with event classkAERPCClassand event typekAEXMLRPCScheme(for XML-RPC) orkAESOAPScheme(for SOAP), and with the target address descriptor created previously.
- Create the direct object for the Apple event and insert parameters for the method name, method parameter list, and any other required information for the remote procedure call.
Create the direct object for the Apple event and insert parameters for the method name, method parameter list, and any other required information for the remote procedure call.
- Insert the direct object into the Apple event.
Insert the direct object into the Apple event.
- Send the Apple event withAESend.
Send the Apple event withAESend.
- Process the reply Apple event to extract any needed information.
Process the reply Apple event to extract any needed information.
More detailed steps for sending an XML-RPC Apple event are shown inSending an XML-RPC Apple Eventand for a SOAP request inSending a SOAP Apple Event. For examples with sample code, seeMaking Remote Procedure Calls From Applications.
There is some overhead in creating Apple events to send remote procedure calls and in extracting information from the reply Apple event, but you gain the advantage of having the Apple Event Manager build the required XML for you. If, however, you already have code that, for example, automatically generates XML for remote procedure calls, it may be more efficient for you to write your own code to make the remote procedure calls as well.
#### Apple Event Manager API for Remote Procedure Calls
This section describes some of the key constants used to construct remote procedure call Apple events. These constants are defined inAEDataModel.h(inAE.framework, a subframework ofApplicationServices.framework). For step-by-step instructions that show how to create Apple events using these constants, seeMaking Remote Procedure Calls From Applications.
The Apple Event Manager defines one event class constant and two event ID constants for remote procedure call Apple events. These constants are shown inListing 2-2. You use the constantkAERPCClassas the event class for both XML-RPC and SOAP requests. To specify the request type, you use eitherkAEXMLRPCSchemeorkAESOAPSchemefor the event ID.
Listing 1-2Event class and event ID constants for remote procedure call Apple events.
```applescript
kAERPCClass = 'rpc ', /* for outgoing XML events */
```
```applescript
kAEXMLRPCScheme = 'RPC2', /* event ID: send to XMLRPC endpoint */
```
```applescript
kAESOAPScheme = 'SOAP', /* event ID: send to SOAP endpoint */
```
Listing 2-3shows the constanttypeApplicationURL. An Apple event for a remote procedure call must have an address descriptor of this type that specifies the target for the request. The Apple Event Manager recognizes this type as a remote procedure call and processes it appropriately.
Listing 1-3Address descriptor type for remote procedure call Apple events.
```applescript
enum {
```
```applescript
//...some constants not shown
```
```applescript
typeApplicationURL = 'aprl',
```
```applescript
//...
```
```applescript
};
```
The SOAP specification defines a schema for encoding (or serializing) information. The Apple Event Manager can work with both the 1999 (or SOAP specification version 1.1) and 2001 (SOAP specification version 1.2) schemas.Listing 2-4shows the constants for specifying the SOAP schema used to format the SOAP request in a remote procedure call Apple event.
You can specify a serialization schema by adding a parameter of typetypeTypeand keykeySOAPSchemaVersionto the direct object of a SOAP request Apple event. If you do not specify a schema, the default iskSOAP1999Schema.
Listing 1-4Constants for specifying a SOAP schema.
```applescript
enum {
```
```applescript
kSOAP1999Schema = 'ss99',
```
```applescript
kSOAP2001Schema = 'ss01',
```
```applescript
//...
```
```applescript
keySOAPSchemaVersion = 'ssch'
```
```applescript
};
```
Listing 2-5shows some of the constants you use to identify the components of an XML-RPC or SOAP request. When you create a remote procedure call Apple event, you use these constants to add various information about the request to the direct object of the Apple event:
- You use the keykeyRPCMethodNameto add an Apple event parameter that specifies the procedure or method name for the request.
You use the keykeyRPCMethodNameto add an Apple event parameter that specifies the procedure or method name for the request.
- After you build a descriptor list that describes the parameters for a remote procedure call, you insert it into the direct object for the Apple event using the keykeyRPCMethodParam.
After you build a descriptor list that describes the parameters for a remote procedure call, you insert it into the direct object for the Apple event using the keykeyRPCMethodParam.
- For a SOAP request, you add the required SOAPAction header to the direct object using the keykeySOAPAction.
For a SOAP request, you add the required SOAPAction header to the direct object using the keykeySOAPAction.
- For a SOAP request, you add the required SOAP name space URI to the direct object using the keykeySOAPMethodNameSpaceURI.
For a SOAP request, you add the required SOAP name space URI to the direct object using the keykeySOAPMethodNameSpaceURI.
Listing 1-5Constants used in constructing an XML-RPC or SOAP request in a remote procedure call Apple event.
```applescript
keyRPCMethodName = 'meth', /* name of the method to call */
```
```applescript
keyRPCMethodParam = 'parm', /* the list (or structure) of parameters*/
```
```applescript
keySOAPAction = 'sact', /* the SOAPAction header */
```
```applescript
keySOAPMethodNameSpaceURI= 'mspu',/* Required namespace URI */
```
Listing 2-6shows constants you can specify in an attribute to a remote procedure call Apple event to turn on Apple Event Manager debugging. Depending on which debug information you specify with these constants, the reply Apple event from an XML-RPC or SOAP request can supply the header or the body of the outgoing request, or of the reply.
Listing 1-6Constants for turning on the Apple Event Managerâs remote procedure call debugging.
```applescript
enum {
```
```applescript
kAEDebugPOSTHeader = (1 << 0), /* headers of the HTTP post - typeChar */
```
```applescript
kAEDebugReplyHeader = (1 << 1), /* headers returned by the server */
```
```applescript
kAEDebugXMLRequest = (1 << 2), /* the XML request we sent */
```
```applescript
kAEDebugXMLResponse = (1 << 3), /* the XML reply from the server */
```
```applescript
kAEDebugXMLDebugAll = 0xffffffff/* everything! */
```
```applescript
};
```
Depending on which debugging flags you specify with the constants shown inListing 2-6, one or more attributes is added to the Apple event. You can extract those attributes using the keys shown inListing 2-7.
Listing 1-7Key constants for remote procedure call debugging attributes.
```applescript
keyAEPOSTHeaderData = 'phed', /* header of request to the server */
```
```applescript
keyAEReplyHeaderData = 'rhed', /* header of server reply */
```
```applescript
keyAEXMLRequestData = 'xreq', /* body of request to the server */
```
```applescript
keyAEXMLReplyData = 'xrep', /* body of server reply */
```
#### Sending an XML-RPC Apple Event
To make an XML-RPC request from your application or other code, youâll need to create an Apple event that encapsulates the procedure call and callAESendto send it. This section describes the steps you need to follow. To see those steps implemented in code, seeMaking an XML-RPC Call.
To use an Apple event to execute an XML-RPC request, you do the following:
- Link withCarbon.framework.
Link withCarbon.framework.
- Create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
Create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
- Create an Apple event with event classkAERPCClass, event IDKAEXMLRPCScheme, and with the target address descriptor created in a previous step.
Create an Apple event with event classkAERPCClass, event IDKAEXMLRPCScheme, and with the target address descriptor created in a previous step.
- Create the direct object for the Apple event.
Create the direct object for the Apple event.
- Insert the method name, using the keykeyRPCMethodName.
Insert the method name, using the keykeyRPCMethodName.
- Create a list descriptor for the remote procedure call parameters and insert each parameter (using the keykeyRPCMethodParam).
Create a list descriptor for the remote procedure call parameters and insert each parameter (using the keykeyRPCMethodParam).
- Add the parameter list to the direct object.
Add the parameter list to the direct object.
- Insert the direct object into the Apple event.
Insert the direct object into the Apple event.
- Optionally turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttr.
Optionally turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttr.
- Send the Apple event withAESend.
Send the Apple event withAESend.
- Process the reply Apple event to extract any needed information. If you turned on debugging, you can extract debugging information, according to which of the debugging constants (described above) you specified. For example, you can examine the header or the body of the posted message, or of the reply.
Process the reply Apple event to extract any needed information. If you turned on debugging, you can extract debugging information, according to which of the debugging constants (described above) you specified. For example, you can examine the header or the body of the posted message, or of the reply.
#### Sending a SOAP Apple Event
To make a SOAP request from your application or other code, youâll need to create an Apple event that encapsulates the request and callAESendto send it. This section describes the steps you need to follow. To see those steps implemented in code, seeMaking a SOAP Request.
To use an Apple event to execute a SOAP request, you do the following:
- Link withCarbon.framework.
Link withCarbon.framework.
- Create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
Create a target address descriptor of typetypeApplicationURLthat specifies the target for the request (a remote server).
- Create an Apple event with event classkAERPCClass, event IDkAESOAPScheme, and with the target address descriptor created in a previous step.
Create an Apple event with event classkAERPCClass, event IDkAESOAPScheme, and with the target address descriptor created in a previous step.
- Create the direct object for the Apple event.
Create the direct object for the Apple event.
- Insert the method name, using the keykeyRPCMethodName.
Insert the method name, using the keykeyRPCMethodName.
- Create a list descriptor for the SOAP method parameters and insert each parameter as character data.
Create a list descriptor for the SOAP method parameters and insert each parameter as character data.
- Add the parameter list to the direct object, using the keykeyRPCMethodParam.
Add the parameter list to the direct object, using the keykeyRPCMethodParam.
- Add the SOAP name space URI to the direct object, using the keykeySOAPMethodNameSpaceURI.
Add the SOAP name space URI to the direct object, using the keykeySOAPMethodNameSpaceURI.
- Insert the direct object into the Apple event.
Insert the direct object into the Apple event.
- Optionally turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttr.
Optionally turn on debugging by adding an attribute to the event with keykeyXMLDebuggingAttr.
- Send the Apple event withAESend.
Send the Apple event withAESend.
- Process the reply Apple event to extract any needed information. If you turned on debugging, you can extract debugging information, according to which of the constants described above you specified. For example, you may be able to examine the header or the body of the posted message, or of the reply.
Process the reply Apple event to extract any needed information. If you turned on debugging, you can extract debugging information, according to which of the constants described above you specified. For example, you may be able to examine the header or the body of the posted message, or of the reply.
Copyright © 2001, 2014 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2014-07-15
---
# Making Remote Procedure Calls From Scripts
# Retired Document
Important:This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Starting with OS X version 10.1, the Apple Event Manager provides support for using the XML-RPC and SOAP protocols to make remote procedure calls from AppleScript scripts and from applications. This chapter provides sample scripts that show how to make remote procedure calls from scripts.
This chapter assumes you are familiar with the material inIntroduction to XML-RPC and SOAP Programming Guide. To test any of the scripts shown in this chapter, you must have an Internet connection.
Warning:The script examples in this chapter may not work because the web services they rely on may no longer be available. You can find additional script samples that make use of web services at/Library/Scripts/Internet Services. For example, theStock Quotescript uses a web service to look up the price for a stock specified by its symbol, while theCurrent Temperature by Zipcodescript looks up the temperature for a specified Zip code.
## Scripting an XML-RPC Call
To make an XML-RPC request from a script, you use the AppleScript termcall xmlrpc. The syntax for this term is described inXML-RPC Script Statements. You can find available XML-RPC services at sites such as XMethods athttp://www.xmethods.net/. There you can also find information about the parameters and return values for remote procedure calls to these services.
Listing 3-1shows a script that prompts a user for text, makes an XML-RPC request to an Internet server to check the spelling for that text, prompts the user to correct any words that may have been misspelled, and displays the final text.
Listing 2-1A script that makes an XML-RPC request to check the spelling of a text phrase.
```applescript
---- Main script ----------------------------------------
```
```applescript
-- Supply default text to spell check.
```
```applescript
set spellCheckText to "My frst naem is John"
```
```applescript
```
```applescript
----Query user for different text to check.
```
```applescript
set dialogResult to display dialog ¬
```
```applescript
"Enter a phrase to spell check:" default answer spellCheckText
```
```applescript
```
```applescript
if button returned of dialogResult is "OK" then
```
```applescript
set spellCheckText to text returned of dialogResult
```
```applescript
-- Call spellCheck handler.
```
```applescript
set resultList to spellCheck(spellCheckText)
```
```applescript
(*
```
```applescript
The returned data looks something like this:
```
```applescript
{{suggestions:{"fast", "fest", "first", "fist", "Forst",
```
```applescript
"frat", "fret", "frist", "frit", "frost", "frot", "fust"},
```
```applescript
location:4, |word|:"frst"}, {suggestions:{"haem", "na em",
```
```applescript
"na-em", "naam", "nae", "nae m", "nae-m", "nael", "Naim",
```
```applescript
"nam", "name", "neem"}, location:9, |word|:"naem"}}
```
```applescript
*)
```
```applescript
-- Make list of words to spellcheck.
```
```applescript
set wordList to every word of spellCheckText
```
```applescript
```
```applescript
-- Give user chance to correct each misspelled word.
```
```applescript
repeat with eachItem in resultList
```
```applescript
set newWord to choose from list suggestions of eachItem ¬
```
```applescript
with prompt "You misspelled \"" & |word| of eachItem & ¬
```
```applescript
"\"" without multiple selections allowed
```
```applescript
```
```applescript
-- If user selected a corrected word, insert it into list
```
```applescript
if (newWord as string) is not equal to "false" then
```
```applescript
set wordIndex to ¬
```
```applescript
findIt(every word of spellCheckText, location of eachItem)
```
```applescript
copy newWord to item wordIndex of wordList
```
```applescript
end if
```
```applescript
end repeat
```
```applescript
```
```applescript
-- Display corrected text.
```
```applescript
set spellCheckText to ""
```
```applescript
repeat with oneWord in wordList
```
```applescript
set spellCheckText to spellCheckText & oneWord & " "
```
```applescript
end repeat
```
```applescript
```
```applescript
display dialog "Corrected text: " & spellCheckText
```
```applescript
end if
```
```applescript
```
```applescript
-- spellCheck handler ------------------------------------------
```
```applescript
-- This handler makes the remote procedure call.
```
```applescript
on spellCheck(sentence)
```
```applescript
tell application "http://www.stuffeddog.com/speller/speller-rpc.cgi"
```
```applescript
return call xmlrpc {method name:"speller.spellCheck", ¬
```
```applescript
parameters:sentence}
```
```applescript
end tell
```
```applescript
end spellCheck
```
```applescript
```
```applescript
```
```applescript
-- findIt handler ------------------------------------
```
```applescript
-- The "textList" parameter is a list of the words in the original text.
```
```applescript
-- The "index" parameter is the character index of a misspelled word.
```
```applescript
-- This handler returns the word at that index.
```
```applescript
-- For example, the misspelled word at character index four is "frst".
```
```applescript
-- Its word index is 2 (the 2nd word in the original text).
```
```applescript
on findIt(textList, index)
```
```applescript
set curLength to 0
```
```applescript
set ixWord to 1
```
```applescript
```
```applescript
repeat with oneWord in textList
```
```applescript
set curLength to curLength + (length of oneWord) + 1
```
```applescript
if curLength ⥠index then
```
```applescript
exit repeat
```
```applescript
end if
```
```applescript
set ixWord to ixWord + 1
```
```applescript
end repeat
```
```applescript
log ixWord
```
```applescript
return ixWord
```
```applescript
end findIt
```
This script has a main section and two handlers. In the main section, it performs the following actions:
- It sets a default text string to be checked.
It sets a default text string to be checked.
- It displays a dialog that prompts the user to enter different text.
It displays a dialog that prompts the user to enter different text.
- If the user accepts the dialog, it calls thespellCheckhandler to check the spelling. That handler, described below, contains the only script statements needed to make a remote procedure call to a spell-checking server.The handler returns a list that contains, for each misspelled word, a list of suggested corrections, the character location of the word in the text, and the misspelled word itself. The returned list looks something like this:The returned data looks something like this:{{suggestions:{"fast", "fest", "first", "fist", "Forst","frat", "fret", "frist", "frit", "frost", "frot", "fust"},location:4, |word|:"frst"}, {suggestions:{"haem", "na em","na-em", "naam", "nae", "nae m", "nae-m", "nael", "Naim","nam", "name", "neem"}, location:9, |word|:"naem"}}Note that this is not the raw data returned from the remote procedure call. Rather, the Apple Event Manager has interpreted the XML returned by the procedure call and built an Apple event to encapsulate it. This list of records is the result. Becausewordis a reserved word in AppleScript, it is enclosed in vertical bars (|word|) when used as an identifier (in this case as a label in a record).
If the user accepts the dialog, it calls thespellCheckhandler to check the spelling. That handler, described below, contains the only script statements needed to make a remote procedure call to a spell-checking server.
The handler returns a list that contains, for each misspelled word, a list of suggested corrections, the character location of the word in the text, and the misspelled word itself. The returned list looks something like this:
```applescript
The returned data looks something like this:
```
```applescript
{{suggestions:{"fast", "fest", "first", "fist", "Forst",
```
```applescript
"frat", "fret", "frist", "frit", "frost", "frot", "fust"},
```
```applescript
location:4, |word|:"frst"}, {suggestions:{"haem", "na em",
```
```applescript
"na-em", "naam", "nae", "nae m", "nae-m", "nael", "Naim",
```
```applescript
"nam", "name", "neem"}, location:9, |word|:"naem"}}
```
Note that this is not the raw data returned from the remote procedure call. Rather, the Apple Event Manager has interpreted the XML returned by the procedure call and built an Apple event to encapsulate it. This list of records is the result. Becausewordis a reserved word in AppleScript, it is enclosed in vertical bars (|word|) when used as an identifier (in this case as a label in a record).
- For each word (if any) in the returned list of misspelled words, it lets the user choose a correction (using the standard scripting additionchoose from list).It then calls thefindIthandler to find the location of the misspelled word in the text phrase and replaces it with the user choice.
For each word (if any) in the returned list of misspelled words, it lets the user choose a correction (using the standard scripting additionchoose from list).
It then calls thefindIthandler to find the location of the misspelled word in the text phrase and replaces it with the user choice.
- It displays the corrected text (possibly the same as the original text, if no corrections were made).
It displays the corrected text (possibly the same as the original text, if no corrections were made).
ThespellCheckhandler contains the one and only statement in the script that makes a remote procedure call. It performs the following operations:
- It uses a Tell statement to identify the location of the remote XML-RPC server (http://www.stuffeddog.com/speller/speller-rpc.cgi).
It uses a Tell statement to identify the location of the remote XML-RPC server (http://www.stuffeddog.com/speller/speller-rpc.cgi).
- It uses the AppleScript termcall xmlrpcto make the remote procedure call, specifying the method name (speller.spellCheck) and passing the specified text for the single parameter.
It uses the AppleScript termcall xmlrpcto make the remote procedure call, specifying the method name (speller.spellCheck) and passing the specified text for the single parameter.
- It returns the result of the remote procedure call. That consists of a list that contains, for each misspelled word, a list of suggested corrections, the location of the word in the text, and the misspelled word itself.
It returns the result of the remote procedure call. That consists of a list that contains, for each misspelled word, a list of suggested corrections, the location of the word in the text, and the misspelled word itself.
Note that AppleScript, working through the Apple Event Manager, did all the work of formatting thecall xmlrpcscript statement into proper XML, opening a connection to the specified server, sending the message, waiting for a reply, formatting the returned XML into an Apple event, and returning the event.
ThefindIthandler merely returns the word position in the original text of the word that corresponds to the passed character index of a misspelled word (returned by the remote procedure handler). For example, the character index of the first misspelled word (frst) is 4. That word is the second word in the original text, sofinditwould return the value 2.
For a script that shows a more flexible type of handler and includes error handling, seeListing 3-3.
## Scripting a SOAP Request
To make a SOAP request from a script, you use the AppleScript termcall soap. The syntax for these calls is described inSOAP Script Statements. You can find available SOAP services at sites such as XMethods athttp://www.xmethods.net/. There you can also find information about the parameters and return values for SOAP requests to these services.
### A Simple Translation Script
Listing 3-2shows a script that prompts a user for text, makes a SOAP request to an Internet server to translate that text to French, and displays the translated text.
Listing 2-2A simple script that calls a SOAP translation server.
```applescript
---- Main script ----------------------------------------
```
```applescript
-- Supply default text to translate.
```
```applescript
set defaultText to "The spirit is willing but the mind is weak"
```
```applescript
```
```applescript
--Display dialog and let user type different text to translate.
```
```applescript
display dialog "Enter the text to translate into French:" ¬
```
```applescript
default answer defaultText
```
```applescript
set this_text to the text returned of the result
```
```applescript
```
```applescript
-- Call translation handler
```
```applescript
set the new_text to translate("en_fr", this_text)
```
```applescript
```
```applescript
--Show translated text and allow user to copy it to Clipboard.
```
```applescript
display dialog new_text buttons {"Clipboard", "OK"} default button 2
```
```applescript
if the button returned of the result is "Clipboard" then
```
```applescript
set the clipboard to new_text
```
```applescript
end if
```
```applescript
```
```applescript
-- translate handler ------------------------------------------
```
```applescript
-- This handler makes the SOAP request.
```
```applescript
on translate(direction, theText)
```
```applescript
tell application "http://services.xmethods.net:80/perl/soaplite.cgi"
```
```applescript
return call soap {method name:"BabelFish", ¬
```
```applescript
method namespace uri:"urn:xmethodsBabelFish", ¬
```
```applescript
parameters:{translationmode:direction as string, ¬
```
```applescript
sourcedata:theText as string}, ¬
```
```applescript
SOAPAction:"urn:xmethodsBabelFish#BabelFish"}
```
```applescript
end tell
```
```applescript
end translate
```
This script starts has a main section and one handler to make the translation SOAP request. In the main section, it performs the following actions:
- It sets a default text string to be translated from English to French.
It sets a default text string to be translated from English to French.
- It displays a dialog that prompts the user to enter different text.
It displays a dialog that prompts the user to enter different text.
- It calls thetranslatehandler to translate the text. That handler, described below, contains the only script statements needed to make a SOAP request to a translation server.The handler returns the translated text.
It calls thetranslatehandler to translate the text. That handler, described below, contains the only script statements needed to make a SOAP request to a translation server.
The handler returns the translated text.
- It displays the translated text and allows the user to copy it to the Clipboard.
It displays the translated text and allows the user to copy it to the Clipboard.
Thetranslatehandler contains the one and only statement in the script that makes a SOAP request. It performs the following operations:
- It uses a Tell statement to identify the location of the remote SOAP server (http://services.xmethods.net:80/perl/soaplite.cgi).
It uses a Tell statement to identify the location of the remote SOAP server (http://services.xmethods.net:80/perl/soaplite.cgi).
- It uses the AppleScript termcall soapto make the SOAP request. You can obtain certain values you need to make a SOAP request from the service itself. In this example, the call includes the following:method name:"BabelFish"specifies the required method namemethod namespace uri:"urn:xmethodsBabelFish"specifies the required method namespace URIparameters:{translationmode:direction as string, sourcedata:theText as string}specifies the parameter names and the values to pass for those parameters; a method may have no parametersSOAPAction:"urn:xmethodsBabelFish#BabelFish"specifies the required SOAPAction value
It uses the AppleScript termcall soapto make the SOAP request. You can obtain certain values you need to make a SOAP request from the service itself. In this example, the call includes the following:
- method name:"BabelFish"specifies the required method name
method name:"BabelFish"specifies the required method name
- method namespace uri:"urn:xmethodsBabelFish"specifies the required method namespace URI
method namespace uri:"urn:xmethodsBabelFish"specifies the required method namespace URI
- parameters:{translationmode:direction as string, sourcedata:theText as string}specifies the parameter names and the values to pass for those parameters; a method may have no parameters
parameters:{translationmode:direction as string, sourcedata:theText as string}specifies the parameter names and the values to pass for those parameters; a method may have no parameters
- SOAPAction:"urn:xmethodsBabelFish#BabelFish"specifies the required SOAPAction value
SOAPAction:"urn:xmethodsBabelFish#BabelFish"specifies the required SOAPAction value
- It returns the result of the SOAP request. That consists of a text string that contains the translated text.
It returns the result of the SOAP request. That consists of a text string that contains the translated text.
Note that AppleScript, working through the Apple Event Manager, did all the work of formatting thecall soapscript statement into proper XML, opening a connection to the specified server, sending the message, waiting for a reply, formatting the returned XML into an Apple event, and returning the event.
### A More Complex Translation Script
The script inListing 3-3performs the same task as the script inListing 3-2, translating an English phrase to French. However, it is more flexible and sophisticated in several ways:
- It turns the translation handler into a flexible SOAP request routine that can call different SOAP servers and different methods depending on the parameters passed to it.
It turns the translation handler into a flexible SOAP request routine that can call different SOAP servers and different methods depending on the parameters passed to it.
- It uses error handling in the SOAP request handler and sets a boolean parameter value so that the caller can check for success. The main script checks that parameter and displays an error message if the SOAP request was unsuccessful.
It uses error handling in the SOAP request handler and sets a boolean parameter value so that the caller can check for success. The main script checks that parameter and displays an error message if the SOAP request was unsuccessful.
- The main script also shows how to use atryblock to handle errors. In this case, it checks for errors while displaying a dialog: for any returned error number except -128 (the user cancelled), it beeps.
The main script also shows how to use atryblock to handle errors. In this case, it checks for errors while displaying a dialog: for any returned error number except -128 (the user cancelled), it beeps.
- It defines property values to make the script more readable and easier to modify.
It defines property values to make the script more readable and easier to modify.
Listing 2-3A more detailed script that calls a SOAP translation server.
```applescript
-- Use properties to store default values.
```
```applescript
property SOAP_app : "http://services.xmethods.net:80/perl/soaplite.cgi"
```
```applescript
property method_name : "BabelFish"
```
```applescript
property method_namespace_URI : "urn:xmethodsBabelFish"
```
```applescript
property SOAP_action : "urn:xmethodsBabelFish#BabelFish"
```
```applescript
property English_to_French : "en_fr"
```
```applescript
```
```applescript
---- Main script ----------------------------------------
```
```applescript
--Query user for text to translate.
```
```applescript
set this_text to "Hello my friend!"
```
```applescript
repeat
```
```applescript
try
```
```applescript
display dialog ¬
```
```applescript
"Enter the text to translate into French:" ¬
```
```applescript
default answer this_text
```
```applescript
set this_text to the text returned of the result
```
```applescript
if this_text is not "" then
```
```applescript
set this_text to this_text as string
```
```applescript
exit repeat
```
```applescript
end if
```
```applescript
on error number error_number
```
```applescript
-- Don't show error if user just cancelled.
```
```applescript
if the error_number is -128 then error number -128
```
```applescript
beep
```
```applescript
end try
```
```applescript
end repeat
```
```applescript
```
```applescript
-- Create the parameter record.
```
```applescript
set the method_parameters to {translationmode:English_to_French, ¬
```
```applescript
sourcedata:this_text}
```
```applescript
```
```applescript
-- Call the SOAP handler.
```
```applescript
copy my SOAP_call(SOAP_app, method_name, ¬
```
```applescript
method_namespace_URI, method_parameters, SOAP_action) ¬
```
```applescript
to {call_indicator, call_result}
```
```applescript
```
```applescript
-- Check for error return from SOAP handler.
```
```applescript
if the call_indicator is false then
```
```applescript
beep
```
```applescript
display dialog "An error occurred." & return & return ¬
```
```applescript
& call_result buttons {"Cancel"} default button 1
```
```applescript
else
```
```applescript
--Show translated text and allow user to copy it to Clipboard.
```
```applescript
display dialog call_result buttons {"Clipboard", "OK"} ¬
```
```applescript
default button 2
```
```applescript
if the button returned of the result is "Clipboard" then
```
```applescript
set the clipboard to the call_result
```
```applescript
end if
```
```applescript
end if
```
```applescript
```
```applescript
-- SOAP translation handler ------------------------------
```
```applescript
on SOAP_call(SOAP_app, method_name, ¬
```
```applescript
method_namespace_URI, method_parameters, SOAP_action)
```
```applescript
try
```
```applescript
using terms from application "http://www.apple.com/placebo"
```
```applescript
tell application SOAP_app
```
```applescript
set this_result to call soap ¬
```
```applescript
{method name:method_name ¬
```
```applescript
, method namespace uri:method_namespace_URI ¬
```
```applescript
, parameters:method_parameters ¬
```
```applescript
, SOAPAction:SOAP_action}
```
```applescript
end tell
```
```applescript
end using terms from
```
```applescript
return {true, this_result}
```
```applescript
on error error_message
```
```applescript
return {false, error_message}
```
```applescript
end try
```
```applescript
end SOAP_call
```
Copyright © 2001, 2014 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2014-07-15
---
# Index
SymbolsABCDEFGHIKLMNOPQRSTUVWY
Copyright © 2016 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2016-01-25