| AppleScript | |
|---|---|
| Paradigm | Natural language programming,Scripting |
| Developer | Apple Inc. |
| First appeared | 1993; 33 years ago (1993)[1] |
| Stable release | |
| Typing discipline | Weak,dynamic |
| OS | System 7,Mac OS 8,Mac OS 9,macOS |
| License | Proprietary (parts available underAPSL) |
| Filename extensions | .scpt, .scptd, .applescript |
| Website | developer |
| Influenced by | |
| Natural language,HyperTalk | |
AppleScript is ascripting language created byApple Inc. that facilitatesautomated control ofMacapplications. First introduced inSystem 7, it is currently included inmacOS in a package of automation tools. The termAppleScript may refer to the scripting language, to a script written in the language, or to the macOSOpen Scripting Architecture that underlies the language.[4][5]
AppleScript is primarily a mechanism for drivingApple events – aninter-application communication (IAC) technology that exchanges data between and controls applications.[4][5] Additionally, AppleScript supports basic calculations and text processing, and is extensible viascripting additions that add functions to the language.
AppleScript is tightly bound to the Mac environment, similar to howWindows Script Host is bound to the Windows environment. In other words, AppleScript is not a general purpose scripting language likePython. One way that AppleScript is bound to the unique aspects of its environment is that it relies on applications to publishdictionaries of addressable objects and operations.
As is typical of a command language, AppleScript is not designed to directly perform intensive processing. For example, a script cannot efficiently perform intensive math operations or complicated text processing. However, AppleScript can be used in combination with other tools and technologies which allows it to leverage more efficient programming contexts.
The language has aspects ofstructured,procedural,object-oriented andnatural language programming, but does not strictly conform to any of theseparadigms.[5]: xxvi
In the late 1980s, Apple considered usingHyperCard'sHyperTalk scripting language as the standard language forend-user development across the company and within itsclassic Mac OS operating system, and forinterprocess communication between Apple and non-Apple products.[6] HyperTalk could be used by novices to program a HyperCard stack. Apple engineers recognized that a similar, but more object-oriented scripting language could be designed to be used with anyapplication, and the AppleScript project was born as a spin-off of a research effort to modernize the Macintosh as a whole and finally became part ofSystem 7.[1]
AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7).[1]QuarkXPress (ver. 3.2) was one of the first major software applications that supported AppleScript. This, in turn, led to AppleScript being widely adopted within the publishing and prepress world, often tying together complex workflows. This was a key factor in retaining the Macintosh's dominant position in publishing and prepress, even after QuarkXpress and other publishing applications were ported to Microsoft Windows.
After some uncertainty about the future of AppleScript on Apple's next generation OS, the move toMac OS X (around 2002) and itsCocoa frameworks greatly increased the usefulness and flexibility of AppleScript. Cocoa applications allow application developers to implement basic scriptability for their apps with minimal effort, broadening the number of applications that are directly scriptable. At the same time, the shift to the Unix underpinnings and AppleScript's ability to run Unix commands directly, with thedo shell script command,[7] allowed AppleScripts much greater control over the operating system itself.[5]: 863 AppleScript Studio, released withMac OS X 10.2 as part ofXcode, and laterAppleScriptObjC framework, released inMac OS X 10.6, allowed users to build Cocoa applications using AppleScript.[5]: 969
In a 2006 article,Macworld included AppleScript among its rankings of Apple's 30 most significant products to date, placing it at #17.[8]
In a 2013 article forMacworld, veteran Mac software developer and commentatorJohn Gruber concluded his reflection on "the unlikely persistence of AppleScript" by noting: "In theory, AppleScript could be much better; in practice, though, it's the best thing we have that works. It exemplifies the Mac's advantages overiOS for tinkerers and advanced users."[9]
In October 2016, longtime AppleScript product manager and automation evangelistSal Soghoian left Apple when his position was eliminated "for business reasons".[10] Veterans in the Mac community such asJohn Gruber andAndy Ihnatko generally responded with concern, questioning Apple's commitment to the developer community and pro users.[11] Apple senior vice president of software engineeringCraig Federighi responded in an email saying that "We have every intent to continue our support for the great automation technologies in macOS!", though Jeff Gamet atThe Mac Observer opined that it did little to assuage his doubt about the future of Apple automation in general and AppleScript in particular.[12] For the time being, AppleScript remains one component of macOS automation technologies, along withAutomator,Shortcuts,Services, andshell scripting.
AppleScript was designed to be used as an accessible end-user scripting language, offering users an intelligent mechanism to control applications, and to access and modify data and documents. AppleScript usesApple events, a set of standardized data formats that the Macintosh operating system uses to send information to applications, roughly analogous to sendingXPath queries overXML-RPC in the world ofweb services.[5]: xxvi Apple events allow a script to work with multiple applications simultaneously, passing data between them so that complex tasks can be accomplished without human interaction.[4] For example, an AppleScript to create a simple web gallery might do the following:
For the user, hundreds or thousands of steps in multiple applications have been reduced to the single act of running the script, and the task is accomplished in much less time and with no possibility of random human error. A large complex script could be developed to run only once, while other scripts are used again and again.
An application's scriptable elements are visible in the application's Scripting Dictionary (distributed as part of the application), which can be viewed in anyscript editor. Elements are generally grouped intosuites, according to loose functional relationships between them. There are two basic kinds of elements present in any suite: classes and commands.
All scriptable applications share a few basic commands and objects, usually called the Standard Suite—commands to open, close or save a file, to print something, to quit, to set data to variables—as well as a basicapplication object that gives the scriptable properties of the application itself. Many applications have numerous suites capable of performing any task the application itself can perform. In exceptional cases, applications may support plugins which include their own scripting dictionaries.
AppleScript was designed with the ability to build scripts intuitively by recording user actions. Such AppleScript recordability has to be engineered into the app—the app must support Apple events and AppleScript recording;[13] as Finder supports AppleScript recording, it can be useful for reference. WhenAppleScript Editor (Script Editor) is open and the Record button clicked, user actions for recordable apps are converted to their equivalent AppleScript commands and output to the Script Editor window. The resulting script can be saved and re-run to duplicate the original actions, or modified to be more generally useful.
Whereas Apple events are a way to send messages into applications, AppleScript is a particular language designed to send Apple events. In keeping with the objective of ease-of-use for beginners, the AppleScript language is designed on thenatural languagemetaphor, just as thegraphical user interface is designed on thedesktop metaphor. A well-written AppleScript should be clear enough to be read and understood by anyone, and easily edited. The language is based largely on HyperCard's HyperTalk language, extended to refer not only to the HyperCard world of cards and stacks, but also theoretically to any document. To this end, the AppleScript team introduced theAppleEvent Object Model (AEOM), which specifies the objects any particular application "knows".
The heart of the AppleScript language is the use of terms that act as nouns and verbs that can be combined. For example, rather than a different verb to print a page, document or range of pages (such as printPage, printDocument, printRange), AppleScript uses a single "print" verb which can be combined with an object, such as a page, a document or a range of pages.
printpage1printdocument2printpages1thru5ofdocument2
Generally, AEOM defines a number of objects—like "document" or "paragraph"—and corresponding actions—like "cut" and "close". The system also defines ways to refer to properties of objects, so one can refer to the "third paragraph of the document 'Good Day'", or the "color of the last word of the front window". AEOM uses an applicationdictionary to associate the Apple events with human-readable terms, allowing the translation back and forth between human-readable AppleScript andbytecode Apple events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In theXcode andScript Editor applications, this is underFile → Open Dictionary.)
To designate which application is meant to be the target of such a message, AppleScript uses a "tell" construct:
tellapplication"Microsoft Word"quitendtell
Alternatively, the tell may be expressed in one line by using aninfinitive:
tellapplication"Microsoft Word"toquit
For events in the "Core Suite" (activate, open, reopen, close, print, and quit), the application may be supplied as thedirect object to transitive commands:
quitapplication"Microsoft Word"
The concept of an objecthierarchy can be expressed using nested blocks:
tellapplication"QuarkXPress"telldocument1tellpage2telltextbox1setword5to"Apple"endtellendtellendtellendtell
The concept of an objecthierarchy can also be expressed using either nestedprepositional phrases or a series of possessives:
pixel7ofrow3ofTIFFimage"my bitmap"TIFFimage"my bitmap"'s3rdrow's7thpixel
which in anotherprogramming language might be expressed as sequentialmethod calls, like in thispseudocode:
getTIFF("my bitmap").getRow(3).getPixel(7);
AppleScript includes syntax for ordinal counting, "the first paragraph", as well as cardinal, "paragraph one". Likewise, the numbers themselves can be referred to as text or numerically, "five", "fifth" and "5" are all supported; they are synonyms in AppleScript. Also, the word "the" can legally be used anywhere in the script in order to enhance readability: it has no effect on the functionality of the script.
A"Hello, World!" program can be written as a single line. To show a modal window with "OK" and "Cancel" buttons:
display dialog"Hello, world!"
To show a modal window with an "OK" button and an alert icon:
display alert"Hello, world!"
To output audio using a synthesized voice:
say"Hello, world!"
tellapplication"Finder"-- Set variablessetthe1totext returnedof(display dialog"1st"defaultanswer"Number here"buttons{"Continue"}defaultbutton1)setthe2totext returnedof(display dialog"2nd"defaultanswer"Number here"buttons{"Continue"}defaultbutton1)trysetthe1tothe1asintegersetthe2tothe2asintegeronerrordisplay dialog"You may only input numbers into a calculator."withtitle"ERROR"buttons{"OK"}defaultbutton1returnendtry-- Add?ifthebutton returnedof(display dialog"Add?"buttons{"No","Yes"}defaultbutton2)is"Yes"thensetansto(the1+the2)display dialoganswithtitle"Answer"buttons{"OK"}defaultbutton1sayans-- Subtract?elseifthebutton returnedof(display dialog"Subtract?"buttons{"No","Yes"}defaultbutton2)is"Yes"thensetansto(the1-the2)display dialoganswithtitle"Answer"buttons{"OK"}defaultbutton1sayans-- Multiply?elseifthebutton returnedof(display dialog"Multiply?"buttons{"No","Yes"}defaultbutton2)is"Yes"thensetansto(the1*the2)display dialoganswithtitle"Answer"buttons{"OK"}defaultbutton1sayans-- Divide?elseifthebutton returnedof(display dialog"Divide?"buttons{"No","Yes"}defaultbutton2)is"Yes"thensetansto(the1/the2)display dialoganswithtitle"Answer"buttons{"OK"}defaultbutton1sayanselsedelay1say"You haven't selected a function. The operation has cancelled."endifendtell
This script controls the Finder application to login withusername "John" andpassword "app123":
tellapplication"Finder"setpassAnsto"app123"setuserAnsto"John"ifthetext returnedof(display dialog"Username"defaultanswer"")isuserAnsthendisplay dialog"Correct"buttons{"Continue"}defaultbutton1ifthetext returnedof(display dialog"Username : John"&return&"Password"defaultanswer""buttons{"Continue"}defaultbutton1withhiddenanswer)ispassAnsthendisplay dialog"Access granted"buttons{"OK"}defaultbutton1elsedisplay dialog"Incorrect password"buttons{"OK"}defaultbutton1endifelsedisplay dialog"Incorrect username"buttons{"OK"}defaultbutton1endifendtell
Thedevelopment tools below provide a programing environment for scripting with AppleScript – supporting composing, validating, compiling, running and debugging scripts. Some also provide for listing AppleScript dictionaries, saving scripts in a number of formats,syntax highlighting and inserting code snippets.
For development and ad hoc scenarios, a script can be run from a script editor, but to support automation a script must run without opening another application. There are a number of options for doing so:
Re-usable AppleScriptmodules (available sinceOS X Mavericks), written in AppleScript orAppleScriptObjC and saved as script files or bundles in certain locations,[28] that can be called from other scripts. When saved as a bundle, a library can include an AppleScript dictionary (sdef) file,[29] thus functioning like ascripting addition but written in AppleScript or AppleScriptObjC.
A framework for attaching Cocoa interfaces to AppleScript applications, part of the Xcode package in Mac OS X 10.4 and 10.5, now deprecated in favor of AppleScriptObjC.[30]: 438
ACocoa developmentsoftware framework, also called AppleScript/Objective-C or ASOC,[31] part of the Xcode package sinceMac OS X Snow Leopard.[32] AppleScriptObjC allows AppleScripts to use Cocoa classes and methods directly.[33] The following table shows the availability of AppleScriptObjC in various versions of macOS:[34]
| OS version | InXcode | In applets | InAppleScript Libraries | InScript Editor |
|---|---|---|---|---|
| 10.6 | ||||
| 10.7 | ||||
| 10.8 | ||||
| 10.9 | ||||
| 10.10 |
AppleScriptObjC can be used in all subsequent Mac OS X versions.
A graphical, modular editing environment in whichworkflows are built up fromactions. It is intended to duplicate many of the functions of AppleScript without the necessity for programming knowledge. Automator has an action specifically designed to contain and run AppleScripts, for tasks that are too complex for Automator's simplified framework.[35]
These background-only applications, packaged with macOS, are used to allow AppleScript to access features that would not normally be scriptable. As of Mac OS X 10.6.3 they include the scriptable applications for:
Plug-ins for AppleScript developed by Apple or third parties.[36] They are designed to extend the built-in command set, expanding AppleScript's features and making it somewhat less dependent on functionality provided by applications. macOS includes a collection of scripting additions referred to as Standard Additions (StandardAdditions.osax) that adds a set of commands and classes that are not part of AppleScript's core features, including user interaction dialogs, reading and writing files, file system commands, date functions, and text and mathematical operations; without this OSAX, AppleScript would have no capacity to perform many basic actions not directly provided by an application.
Variables are not strictly typed, and do not need to be declared. Variables can take any data type (including scripts and functions). For example:
-- create an integer variable called variable1setvariable1to1-- create a text variable called variable2setvariable2to"Hello"-- create a list variable called variable3copy{17,"doubleday"}tovariable3-- copy the list items of variable3 into separate variables variable4 and variable5set{variable4,variable5}tovariable3-- set a variable to an instance of a scriptsetvariable6toscriptmyScript
A subroutines cannot be called directly from an application tell block. Use ofmy orof me is required.
tellapplication"Finder"setxtomymyHandler()-- orsetxtomyHandler()ofmeendtellonmyHandler()--commandsendmyHandler
Using the same technique for scripting addition commands can reduce errors and improve performance.
tellapplication"Finder"setanyNumbertomy(random numberfrom5to50)endtell
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:
tell application "Finder" …)contents propertypi,tab andlinefeedconstantinteger andreal; rarely used directlytext class was distinct fromstring andUnicode text, and the three behaved somewhat differently; in 2.0 (10.5) and later, they are all synonyms and all text is handled asUTF-16[37]square yards, then converted tosquare feet by casting between unit types using theas operatorAppleScript supports compound statement code structure via either single or multiple line syntax. The multiple line syntax ends acode block with a phrase that likeendkeyword wherekeyword is the statement keyword at the start of the block. For example:
-- Simple formtellapplication"Safari"toactivate-- Compoundtellapplication"MyApp"-- commands for appendtell
A script object is full object – 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:
scriptscriptName-- commands and handlers specific to the scriptendscript
The loop construct has multiple variations, all using the keywordrepeat. The loop can be exited viaexit repeat.
repeat-- commands to be repeatedendrepeat
repeat10times-- commands to be repeatedendrepeat
Forrepeat while, the block is executed as long as a condition evaluates to true. Therepeat until loop is the same except that the block is executed as long as the condition evaluates to false.
setxto5repeatwhilex>0setxtox-1endrepeatsetxto5repeatuntilx≤0setxtox-1endrepeat
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.
-- repeat the block 2000 times, i gets all values from 1 to 2000repeatwithifrom1to2000-- commands to be repeatedendrepeat-- repeat the block 4 times, i gets values 100, 75, 50 and 25repeatwithifrom100to25by-25-- commands to be repeatedendrepeat
A variable has the value of each list item as the loop progresses.
settotalto0repeatwithloopVariablein{1,2,3,4,5}settotaltototal+loopVariableendrepeat
Ahandler, a variation of the block structure defines a subroutine.
onmyFunction(parameters...)-- subroutine commandsendmyFunction
onaddingfolderitemstothisFolderafterreceivingtheseItems-- commands to apply to the folder or itemsendaddingfolderitemsto
onrun-- commandsendrun
Handlers can also be defined using "to" in place of "on" and can be written to accept labeled parameters, not enclosed in parens.
onrockaroundtheclockdisplay dialog(clockasstring)endrock-- called with:rockaroundthecurrent date
tocheckforyourNumberfrombottomthrutopifbottom≤yourNumberandyourNumber≤topthendisplay dialog"Congratulations! You scored."endifendcheck--called with:checkfor8from7thru10
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.
onopentheItemsrepeatwiththisItemintheItemstellapplication"Finder"toupdatethisItemendrepeatendopen
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.
onidle--code to execute when the script's execution has completedreturn60-- number of seconds to pause before executing idle handler againendidle
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,[39] 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.
onquit--commands to execute before the script quitscontinuequit-- required for the script to actually quitendquit
Acomment can be formatted various ways. A line comment begins with-- or alternatively in later versions (AppleScript 2.0, first released inMac OS X Leopard) with#. The latter permits an AppleScript script to run as an executable if it begins with ashebang line#!/usr/bin/osascript. For example:
--This is a line comment# So is this! (in later versions)
A block comment (can be multiple lines) is delimited by(* and*). For example:
(* This is amultiplelinecomment *)
AppleScript has several user interface options, including dialogs, alerts, and list of choices. (The character, produced by typing⌥ Option+return in the Script Editor, denotes continuation of a single statement across multiple lines.)
-- DialogsetdialogReplytodisplay dialog"Dialog Text"defaultanswer"Text Answer"hiddenanswerfalsebuttons{"Skip","Okay","Cancel"}defaultbutton"Okay"cancelbutton"Skip"withtitle"Dialog Window Title"withiconnotegivingupafter15
-- Choose from listsetchosenListItemtochoose from list{"A","B","3"}withtitle"List Title"withprompt"Prompt Text"defaultitems"B"OKbuttonname"Looks Good!"cancelbuttonname"Nope, try again"multipleselectionsallowedfalsewithemptyselectionallowed
-- AlertsetresultAlertReplytodisplay alert"Alert Text"aswarningbuttons{"Skip","Okay","Cancel"}defaultbutton2cancelbutton1givingupafter2
Each user interaction method can return the values of buttons clicked, items chosen or text entered for further processing. For example:
display alert"Hello, world!"buttons{"Rudely decline","Happily accept"}settheAnswertobutton returnedoftheresultiftheAnsweris"Happily accept"thenbeep5elsesay"Piffle!"endif
Apple provides theOpen Scripting Architecture (OSA) for other scripting languages and third-party scripting/automation products (such as QuicKeys andUserLand Frontier) to function on an equal status with AppleScript. AppleScript is implemented as a component ofComponent Manager, and the basic specs for interfacing such components to the OSA are public, allowing other developers to add their own scripting components to the system. Public clientAPIs for loading, saving and compiling scripts work the same for all such components, which means that applets and droplets can hold scripts in any of those scripting languages.[40]
One feature of the OSA isscripting additions, or OSAX forOpen Scripting Architecture eXtension,[36] which were inspired byHyperCard's External Commands. Scripting additions arelibraries that allow programmers to extend the function of AppleScript. Commands included as scripting additions are available system-wide, and are not dependent on an application (see also§ AppleScript Libraries). The AppleScript Editor is also able to directly edit and run some of the OSA languages.
This sectionneeds expansion with: comparison of JXA and AppleScript scripting. You can help byadding missing information.(May 2017) |
UnderOS X Yosemite and later versions of macOS, theJavaScript for Automation (JXA) component remains the only serious OSA language alternative to AppleScript,[14] though the Macintosh versions ofPerl,Python,Ruby, andTcl all support native means of working with Apple events without being OSA components.[30]: 516
JXA also provides anObjective-C (and C language) foreign language interface.[14] Being an environment based on WebKit's JavaScriptCore engine, the JavaScript feature set is in sync with the system Safari browser engine. JXA provides a JavaScript module system and it is also possible to useCommonJS modules via browserify.[41]