Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
AppleScript
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Language== ===Typing=== Variables are not strictly typed, and do not need to be declared. Variables can take any data type (including scripts and functions). For example: <syntaxhighlight lang="AppleScript" line> -- create an integer variable called variable1 set variable1 to 1 -- create a text variable called variable2 set variable2 to "Hello" -- create a list variable called variable3 copy {17, "doubleday"} to variable3 -- copy the list items of variable3 into separate variables variable4 and variable5 set {variable4, variable5} to variable3 -- set a variable to an instance of a script set variable6 to script myScript </syntaxhighlight> ===Scoping=== A subroutines cannot be called directly from an application tell block. Use of <code>my</code> or <code>of me</code> is required. <syntaxhighlight lang="AppleScript"> tell application "Finder" set x to my myHandler() -- or set x to myHandler() of me end tell on myHandler() --commands end myHandler</syntaxhighlight> Using the same technique for scripting addition commands can reduce errors and improve performance. <syntaxhighlight lang="AppleScript"> tell application "Finder" set anyNumber to my (random number from 5 to 50) end tell </syntaxhighlight> ===Types and objects=== A script can define custom data types, or use one of the many built-in classes and objects which are provided by the language and tend to be recognized by scriptable applications. Notable built-in types and objects include: ; Basic objects * '''application''': used mostly as a specifier for tell statements (<code>tell application "Finder" …</code>) * '''script''': script objects are containers for scripts; every AppleScript creates a script object when run, and script objects may be created within AppleScripts * '''class''': meta-object that specifies the type of other objects * '''reference''': object that encapsulates an unevaluated object specifier that may or may not point to a valid object; can be evaluated on-demand by accessing its <code>contents</code> property ; Standard data objects * '''constant''': [[Constant (computer programming)|constant]] value; language-defined constants include <code>pi</code>, <code>tab</code> and <code>linefeed</code> * '''boolean''': [[Boolean data type|Boolean]] (true/false) value; [[Subclass (computer science)|subclass]] of <code>constant</code> * '''number''': [[Abstract type|abstract]] [[Superclass (computer science)|superclass]] of <code>integer</code> and <code>real</code>; rarely used directly * '''integer''': [[Integer (computer science)|integer]]; can be manipulated with built-in mathematical operators * '''real''': [[floating-point]] ([[Real number|real]]) number; can be manipulated with built-in mathematical operators * '''date''': date and time * '''text''': before AppleScript 2.0 (Mac OS X 10.4 and below) the <code>text</code> class was distinct from <code>string</code> and <code>Unicode text</code>, and the three behaved somewhat differently; in 2.0 (10.5) and later, they are all synonyms and all text is handled as [[UTF-16]]<ref name="as-rn-leopard">{{cite web |url=https://developer.apple.com/mac/library/releasenotes/AppleScript/RN-AppleScript/RN-10_5/RN-10_5.html |title=AppleScript Release Notes: 10.5 Changes |website=developer.apple.com |access-date=May 8, 2017}}</ref> ; Containers * '''list''': ordered list of objects; can contain any class, including other lists and classes defined by applications * '''record''': keyed list of objects; like a list, except structured as [[key–value pair]]s; runtime keyed access is unsupported; all keys must be compile-time constant identifiers ; File system * '''alias''': reference to an existing file system object (file or folder); maintains link to file system object if moved or renamed * '''file''': reference to a file system object; can can refer to an object that does not exist * '''POSIX file''': reference to a file system object, in plain text, using Unix ([[POSIX]])-style slash (/) notation; not a true data type, as AppleScript automatically converts a POSIX file to an ordinary file<ref>{{cite web|title=POSIX file — Class Reference — AppleScript Language Guide|url=https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_classes.html#//apple_ref/doc/uid/TP40000983-CH1g-SW15|website=developer.apple.com|access-date=January 8, 2018|language=en}}</ref> ; Miscellaneous * '''RGB color''': specifies an RGB triplet (in [[High color#16-bit high color|16-bit high color]] format), for use in commands and objects that work with colors * '''unit types''': converts between standard units; for instance, a value can be defined as <code>square yards</code>, then converted to <code>square feet</code> by casting between unit types using the <code>as</code> operator ===Block=== AppleScript supports compound statement code structure via either single or multiple line syntax. The multiple line syntax ends a [[code block]] with a phrase that like <code>end ''keyword''</code> where ''keyword'' is the statement keyword at the start of the block. For example: <syntaxhighlight lang="AppleScript"> -- Simple form tell application "Safari" to activate -- Compound tell application "MyApp" -- commands for app end tell </syntaxhighlight> ===Script=== A script object is full object {{endash}} encapsulating methods and data and inheriting data and behavior from a parent script. Script objects can use the same 'tell' constructs that are used for application objects and can be loaded from and saved to files. Runtime performance can be enhanced in some cases by using script objects. A script object is defined as: <syntaxhighlight lang="AppleScript">script scriptName -- commands and handlers specific to the script end script </syntaxhighlight> ===Loop=== The loop construct has multiple variations; all using the keyword '''repeat'''. The loop can be exited via '''exit repeat'''. ; Unconditional <syntaxhighlight lang="AppleScript">repeat -- commands to be repeated end repeat</syntaxhighlight> ; Repeat a number of times <syntaxhighlight lang="AppleScript">repeat 10 times -- commands to be repeated end repeat</syntaxhighlight> ; Conditional For '''repeat while''', the block is executed as long as a condition evaluates to true. The '''repeat until''' loop is the same except that the block is executed as long as the condition evaluates to false. <syntaxhighlight lang="AppleScript">set x to 5 repeat while x > 0 set x to x - 1 end repeat set x to 5 repeat until x ≤ 0 set x to x - 1 end repeat </syntaxhighlight> ; With a variable A variable is initialized to a value and after each execution of the block, the variable is incremented by the step value; 1 if not specified. <syntaxhighlight lang="AppleScript"> -- repeat the block 2000 times, i gets all values from 1 to 2000 repeat with i from 1 to 2000 -- commands to be repeated end repeat -- repeat the block 4 times, i gets values 100, 75, 50 and 25 repeat with i from 100 to 25 by -25 -- commands to be repeated end repeat </syntaxhighlight> ; Enumerate A variable has the value of each list item as the loop progresses. <syntaxhighlight lang="applescript">set total to 0 repeat with loopVariable in {1, 2, 3, 4, 5} set total to total + loopVariable end repeat </syntaxhighlight> ===Handler=== A '''handler''', a variation of the block structure defines a subroutine. ;Function handler <syntaxhighlight lang="AppleScript" line> on myFunction(parameters...) -- subroutine commands end myFunction </syntaxhighlight> ;Folder actions block <syntaxhighlight lang="AppleScript" line> on adding folder items to thisFolder after receiving theseItems -- commands to apply to the folder or items end adding folder items to </syntaxhighlight> ;Run handler <syntaxhighlight lang="AppleScript" line> on run -- commands end run </syntaxhighlight> Handlers can also be defined using "to" in place of "on" and can be written to accept labeled parameters, not enclosed in parens. ;Handler with labeled parameters <syntaxhighlight lang="AppleScript">on rock around the clock display dialog (clock as string) end rock -- called with: rock around the current date </syntaxhighlight> ;Handler using "to" and labeled parameters <syntaxhighlight lang="AppleScript"> to check for yourNumber from bottom thru top if bottom ≤ yourNumber and yourNumber ≤ top then display dialog "Congratulations! You scored." end if end check --called with: check for 8 from 7 thru 10 </syntaxhighlight> There are four types of predefined handlers in AppleScript—run, open, idle, and quit—each of which is created in the same way as the run handler shown above. ;Run handler: Defines the main code of the script, which is called when the script is run. Run handler blocks are optional, unless arguments are being passed to the script. If an explicit run handler block is omitted, then all code that is not contained inside handler blocks is executed as though it were in an implicit run handler. ;Open handler: Defined using "on open theItems". <syntaxhighlight lang="AppleScript">on open theItems repeat with thisItem in theItems tell application "Finder" to update thisItem end repeat end open</syntaxhighlight> When a script containing an "open handler' is saved as an applet, the applet becomes a droplet. A droplet can be identified in the Finder by its icon, which includes an arrow, indicating items can be dropped onto the icon. The droplet's open handler is executed when files or folders are dropped onto droplet's icon. References to the items dropped on the droplet's icon are passed to the droplet's script as the parameter of the open handler. A droplet can also be launched the same way as an ordinary applet, executing its run handler. ;Idle handler: A subroutine that is run periodically by the system when the application is idle. <syntaxhighlight lang="AppleScript">on idle --code to execute when the script's execution has completed return 60 -- number of seconds to pause before executing idle handler again end idle</syntaxhighlight> An idle handler can be used in applets or droplets saved as stay-open applets, and is useful for scripts that watch for particular data or events. The length of the idle time is 30 seconds by default,<ref>{{cite web |url=https://developer.apple.com/library/mac/#documentation/AppleScript/Conceptual/AppleScriptLangGuide/conceptual/ASLR_about_handlers.html#//apple_ref/doc/uid/TP40000983-CH206-SW14 |title=AppleScript Language Guide: Handlers in Script Applications |website=developer.apple.com |access-date=July 21, 2013}}</ref> but can be changed by including a 'return x' statement at the end of the subroutine, where x is the number of seconds the system should wait before running the handler again. ;Quit handler: A handler that is run when the applet receives a Quit request. This can be used to save data or do other ending tasks before quitting. <syntaxhighlight lang="AppleScript">on quit --commands to execute before the script quits continue quit -- required for the script to actually quit end quit</syntaxhighlight> ===Comment=== A [[Comment (computer programming)|comment]] can be formatted various ways. A line comment begins with <code>--</code> or alternatively in later versions (AppleScript 2.0, first released in [[Mac OS X Leopard]]) with {{code|#}}. The latter permits an AppleScript script to run as an executable if it begins with a [[shebang line]] <code>#!/usr/bin/osascript</code>. For example: <syntaxhighlight lang="AppleScript"> --This is a line comment # So is this! (in later versions) </syntaxhighlight> A block comment (can be multiple lines) is delimited by <code>(*</code> and <code>*)</code>. For example: <syntaxhighlight lang="AppleScript"> (* This is a multiple line comment *) </syntaxhighlight> ===User interaction=== AppleScript has several user interface options, including dialogs, alerts, and list of choices. (The character, produced by typing {{keypress|option|return}} in the Script Editor, denotes continuation of a single statement across multiple lines.) <syntaxhighlight lang="AppleScript"> -- Dialog set dialogReply to display dialog "Dialog Text" default answer "Text Answer" hidden answer false buttons {"Skip", "Okay", "Cancel"} default button "Okay" cancel button "Skip" with title "Dialog Window Title" with icon note giving up after 15 </syntaxhighlight> <syntaxhighlight lang="AppleScript"> -- Choose from list set chosenListItem to choose from list {"A", "B", "3"} with title "List Title" with prompt "Prompt Text" default items "B" OK button name "Looks Good!" cancel button name "Nope, try again" multiple selections allowed false with empty selection allowed </syntaxhighlight> <syntaxhighlight lang="AppleScript"> -- Alert set resultAlertReply to display alert "Alert Text" as warning buttons {"Skip", "Okay", "Cancel"} default button 2 cancel button 1 giving up after 2 </syntaxhighlight> Each user interaction method can return the values of buttons clicked, items chosen or text entered for further processing. For example: <syntaxhighlight lang="AppleScript"> display alert "Hello, world!" buttons {"Rudely decline", "Happily accept"} set theAnswer to button returned of the result if theAnswer is "Happily accept" then beep 5 else say "Piffle!" end if </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)