JavaScript for Automation
   HOME

TheInfoList



OR:

AppleScript is a
scripting language A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled. A scripting ...
created by
Apple Inc. Apple Inc. is an American multinational technology company headquartered in Cupertino, California, United States. Apple is the largest technology company by revenue (totaling in 2021) and, as of June 2022, is the world's biggest company ...
that facilitates automated control over scriptable Mac
applications Application may refer to: Mathematics and computing * Application software, computer software designed to help the user to perform specific tasks ** Application layer, an abstraction layer that specifies protocols and interface methods used in a c ...
. First introduced in
System 7 System 7, codenamed "Big Bang", and also known as Mac OS 7, is a graphical user interface-based operating system for Macintosh computers and is part of the classic Mac OS series of operating systems. It was introduced on May 13, 1991, by Apple C ...
, it is currently included in all versions of
macOS macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
as part of a package of system automation tools. The term "AppleScript" may refer to the language itself, to an individual script written in the language, or, informally, to the macOS Open Scripting Architecture that underlies the language.


Overview

AppleScript is primarily a scripting language developed by Apple to do inter-application communication (IAC) using Apple events. AppleScript is related to, but different from, Apple events. Apple events are designed to exchange data between and control other applications in order to automate repetitive tasks. AppleScript has some processing abilities of its own, in addition to sending and receiving Apple events to applications. AppleScript can do basic calculations and text processing, and is extensible, allowing the use of scripting additions that add new functions to the language. Mainly, however, AppleScript relies on the functionality of applications and processes to handle complex tasks. As a
structured Structuring, also known as smurfing in banking jargon, is the practice of executing financial transactions such as making bank deposits in a specific pattern, calculated to avoid triggering financial institutions to file reports required by law ...
command language, AppleScript can be compared to
Unix shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating syste ...
s, the
Microsoft Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washin ...
Windows Script Host The Microsoft Windows Script Host (WSH) (formerly named Windows Scripting Host) is an automation technology for Microsoft Windows operating systems that provides scripting abilities comparable to batch files, but with a wider range of supported fe ...
, or IBM REXX but it is distinct from all three. Essential to its functionality is the fact that Macintosh applications publish "dictionaries" of addressable objects and operations. AppleScript has some elements of
procedural programming Procedural programming is a programming paradigm, derived from imperative programming, based on the concept of the '' procedure call''. Procedures (a type of routine or subroutine) simply contain a series of computational steps to be carrie ...
,
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
(particularly in the construction of script objects), and
natural language programming Natural-language programming (NLP) is an ontology-assisted way of programming in terms of natural-language sentences, e.g. English. A structured document with Content, sections and subsections for explanations of sentences forms a NLP docume ...
tendencies in its syntax, but does not strictly conform to any of these
programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, suc ...
s.


History

In the late 1980s Apple considered using
HyperCard HyperCard is a software application and development kit for Apple Macintosh and Apple IIGS computers. It is among the first successful hypermedia systems predating the World Wide Web. HyperCard combines a flat-file database with a graphical, f ...
's
HyperTalk HyperTalk is a discontinued high-level, procedural programming language created in 1987 by Dan Winkler and used in conjunction with Apple Computer's HyperCard hypermedia program by Bill Atkinson. Because the main target audience of HyperTalk ...
scripting language A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled. A scripting ...
as the standard language for end-user development across the company and within its classic Mac OS operating system, and for
interprocess communication In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categoriz ...
between Apple and non-Apple products. 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 any application, 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 of
System 7 System 7, codenamed "Big Bang", and also known as Mac OS 7, is a graphical user interface-based operating system for Macintosh computers and is part of the classic Mac OS series of operating systems. It was introduced on May 13, 1991, by Apple C ...
. AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7).
QuarkXPress QuarkXPress is a desktop publishing software for creating and editing complex page layouts in a WYSIWYG (What You See Is What You Get) environment. It runs on macOS and Windows. It was first released by Quark, Inc. in 1987 and is still owned and ...
(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 to
Mac OS X macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and la ...
(around 2002) and its Cocoa 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 the do shell script command, allowed AppleScripts much greater control over the operating system itself.
AppleScript Studio AppleScript is a scripting language created by Apple Inc. that facilitates automated control over scriptable Mac applications. First introduced in System 7, it is currently included in all versions of macOS as part of a package of system autom ...
, released with Mac OS X 10.2 as part of
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
, and later AppleScriptObjC framework, released in Mac OS X 10.6, allowed users to build Cocoa applications using AppleScript. In a 2006 article, '' Macworld'' included AppleScript among its rankings of Apple's 30 most significant products to date, placing it at #17. In a 2013 article for ''Macworld'', veteran Mac software developer and commentator
John Gruber John Gruber (born 1973) is a technology blogger, UI designer, and one of the inventors of the Markdown markup language. History Gruber is from Philadelphia, Pennsylvania. He received his Bachelor of Science in computer science from Drexel Univ ...
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 over
iOS iOS (formerly iPhone OS) is a mobile operating system created and developed by Apple Inc. exclusively for its hardware. It is the operating system that powers many of the company's mobile devices, including the iPhone; the term also include ...
for tinkerers and advanced users." In October 2016, longtime AppleScript product manager and automation evangelist Sal Soghoian left Apple when his position was eliminated "for business reasons". Veterans in the Mac community such as
John Gruber John Gruber (born 1973) is a technology blogger, UI designer, and one of the inventors of the Markdown markup language. History Gruber is from Philadelphia, Pennsylvania. He received his Bachelor of Science in computer science from Drexel Univ ...
and
Andy Ihnatko Andy Ihnatko (born November 18, 1967) is a tech author and former technology journalist for the ''Chicago Sun-Times'',. He currently resides in Massachusetts. He is a co-host on the Material podcast, on Relay FM's network. He also appears on Le ...
generally responded with concern, questioning Apple's commitment to the developer community and pro users. Apple senior vice president of software engineering
Craig Federighi Craig Federighi (born May 27, 1969) is an American engineer and business executive who is the senior vice president (SVP) of software engineering at Apple Inc. He oversees the development of iOS, iPadOS, macOS and Apple's common operating syste ...
responded in an email saying that "We have every intent to continue our support for the great automation technologies in macOS!", though Jeff Gamet at ''The Mac Observer'' opined that it did little to assuage his doubt about the future of Apple automation in general and AppleScript in particular. For the time being, AppleScript remains one component of macOS automation technologies, along with Automator, Shortcuts,
Services Service may refer to: Activities * Administrative service, a required part of the workload of university faculty * Civil service, the body of employees of a government * Community service, volunteer service for the benefit of a community or a p ...
, and shell scripting.


Basic concepts

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 uses Apple events, a set of standardized data formats that the Macintosh operating system uses to send information to applications, roughly analogous to sending
XPath XPath (XML Path Language) is an expression language designed to support the query or transformation of XML documents. It was defined by the World Wide Web Consortium (W3C) and can be used to compute values (e.g., strings, numbers, or Boolean v ...
queries over
XML-RPC XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism.Simon St. Laurent, Joe Johnston, Edd Dumbill. (June 2001) ''Programming Web Services with XML-RPC.'' O'Reilly. First Edit ...
in the world of web services. 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. For example, an AppleScript to create a simple web gallery might do the following: # Open a photo in a photo-editing application (by sending that application an ''Open File'' Apple event). # Tell the photo-editing application to manipulate the image (e.g. reduce its resolution, add a border, add a photo credit) # Tell the photo-editing application to save the changed image in a file in some different folder (by sending that application a ''Save'' and/or ''Close'' Apple event). # Send the new file path (via another Apple event) to a text editor or web editor application # Tell that editor application to write a link for the photo into an HTML file. # Repeat the above steps for an entire folder of images (hundreds or even thousands of photos). # Upload the HTML file and folder of revised photos to a website, by sending Apple events to a graphical
FTP The File Transfer Protocol (FTP) is a standard communication protocol used for the transfer of computer files from a server to a client on a computer network. FTP is built on a client–server model architecture using separate control and data ...
client, by using built-in AppleScript commands, or by sending Apple events to Unix FTP utilities. 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 any script editor. Elements are generally grouped into ''suites,'' according to loose functional relationships between them. There are two basic kinds of elements present in any suite: classes and commands. * ''Classes'' are scriptable objects—for example, a text editing application will almost certainly have classes for windows, documents, and texts—and these classes will have properties that can be changed (window size, document background color, text font size, etc.), and may contain other classes (a window will contain one or more documents, a document will contain text, a text object will contain paragraphs and words and characters). * ''Commands'', by contrast, are instructions that can be given to scriptable objects. The general format for a block of AppleScript is to ''tell'' a scriptable object to run a command. 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 basic ''application'' 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; as Finder supports AppleScript recording, it can be useful for reference. When
AppleScript Editor Script Editor (called AppleScript Editor from 2009 to 2014) is a code editor for the AppleScript and Javascript for Automation scripting languages, included in classic Mac OS and macOS. AppleScript Editor provides basic debugging capabili ...
(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.


Comments

Comments can be made multiple ways. A one-line comment can begin with 2 hyphens (). In AppleScript 2.0, first released in
Mac OS X Leopard Mac OS X Leopard (version 10.5) is the sixth software versioning, major release of macOS, Apple Inc., Apple's desktop and server operating system for Macintosh computers. Leopard was released on October 26, 2007 as the successor of Mac OS X Tig ...
, it may also begin with a number sign (#). This permits a self-contained AppleScript script to be stored as an executable text file beginning with the shebang line #!/usr/bin/osascript Example: --This is a one line comment # So is this! (in Mac OS X Leopard or later) For comments that take up multiple lines, AppleScript uses parentheses with asterisks inside. Example: (* This is a multiple line comment *)


Hello, world!

In AppleScript, the traditional
"Hello, World!" program A "Hello, World!" program is generally a computer program that ignores any input and outputs or displays a message similar to "Hello, World!". A small piece of code in most general-purpose programming languages, this program is used to illustr ...
could be written in many different forms, including: display dialog "Hello, world!" -- a modal window with "OK" and "Cancel" buttons -- or display alert "Hello, world!" -- a modal window with a single "OK" button and an icon representing the app displaying the alert -- or say "Hello, world!" -- an audio message using a synthesized computer voice AppleScript has several user interface options, including dialogs, alerts, and list of choices. (The character ¬, produced by typing in the Script Editor, denotes continuation of a single statement across multiple lines.) -- Dialog set dialogReply to display dialog "Dialog Text" ¬ default answer "Text Answer" ¬ hidden answer false ¬ buttons ¬ default button "Okay" ¬ cancel button "Skip" ¬ with title "Dialog Window Title" ¬ with icon note ¬ giving up after 15 -- Choose from list set chosenListItem to choose from list ¬ 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 -- Alert set resultAlertReply to display alert "Alert Text" ¬ as warning ¬ buttons ¬ default button 2 ¬ cancel button 1 ¬ giving up after 2 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 set theAnswer to button returned of the result if theAnswer is "Happily accept" then beep 5 else say "Piffle!" end if


Natural language metaphor

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 the natural language
metaphor A metaphor is a figure of speech that, for rhetorical effect, directly refers to one thing by mentioning another. It may provide (or obscure) clarity or identify hidden similarities between two different ideas. Metaphors are often compared wi ...
, just as the
graphical user interface The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inst ...
is designed on the
desktop metaphor In computing, the desktop metaphor is an interface metaphor which is a set of unifying concepts used by graphical user interfaces to help users interact more easily with the computer. The desktop metaphor treats the computer monitor as if it is ...
. 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 the
AppleEvent Object Model Apple events are the message-based interprocess communication mechanism in Mac OS, first making an appearance in System 7 and supported by every version of the classic Mac OS since then and by macOS. Apple events describe "high-level" events suc ...
(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. print page 1 print document 2 print pages 1 thru 5 of document 2 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 application ''dictionary'' to associate the Apple events with human-readable terms, allowing the translation back and forth between human-readable AppleScript and
bytecode Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (norma ...
Apple events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In the
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
and Script Editor applications, this is under ''File → Open Dictionary''.) To designate which application is meant to be the target of such a message, AppleScript uses a "tell" construct: tell application "Microsoft Word" quit end tell Alternatively, the tell may be expressed in one line by using an
infinitive Infinitive (abbreviated ) is a linguistics term for certain verb forms existing in many languages, most often used as non-finite verbs. As with many linguistic concepts, there is not a single definition applicable to all languages. The word is deri ...
: tell application "Microsoft Word" to quit For events in the "Core Suite" (activate, open, reopen, close, print, and quit), the application may be supplied as the
direct object In linguistics, an object is any of several types of arguments. In subject-prominent, nominative-accusative languages such as English, a transitive verb typically distinguishes between its subject and any of its objects, which can include but ...
to transitive commands: quit application "Microsoft Word" The concept of an object hierarchy can be expressed using nested blocks: tell application "QuarkXPress" tell document 1 tell page 2 tell text box 1 set word 5 to "Apple" end tell end tell end tell end tell The concept of an object hierarchy can also be expressed using nested
prepositional phrase An adpositional phrase, in linguistics, is a syntactic category that includes ''prepositional phrases'', ''postpositional phrases'', and ''circumpositional phrases''. Adpositional phrases contain an adposition (preposition, postposition, or ci ...
s: pixel 7 of row 3 of TIFF image "my bitmap" which in another
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
might be expressed as sequential method calls, like in this pseudocode: 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.


Examples of scripts

A failsafe calculator: tell application "Finder" -- Set variables set the1 to text returned of (display dialog "1st" default answer "Number here" buttons default button 1) set the2 to text returned of (display dialog "2nd" default answer "Number here" buttons default button 1) try set the1 to the1 as integer set the2 to the2 as integer on error display dialog "You may only input numbers into a calculator." with title "ERROR" buttons default button 1 return end try -- Add? if the button returned of (display dialog "Add?" buttons default button 2) is "Yes" then set ans to (the1 + the2) display dialog ans with title "Answer" buttons default button 1 say ans -- Subtract? else if the button returned of (display dialog "Subtract?" buttons default button 2) is "Yes" then set ans to (the1 - the2) display dialog ans with title "Answer" buttons default button 1 say ans -- Multiply? else if the button returned of (display dialog "Multiply?" buttons default button 2) is "Yes" then set ans to (the1 * the2) display dialog ans with title "Answer" buttons default button 1 say ans -- Divide? else if the button returned of (display dialog "Divide?" buttons default button 2) is "Yes" then set ans to (the1 / the2) display dialog ans with title "Answer" buttons default button 1 say ans else delay 1 say "You haven't selected a function. The operation has cancelled." end if end tell A simple
username A user is a person who utilizes a computer or network service. A user often has a user account and is identified to the system by a username (or user name). Other terms for username include login name, screenname (or screen name), accoun ...
and
password A password, sometimes called a passcode (for example in Apple devices), is secret data, typically a string of characters, usually used to confirm a user's identity. Traditionally, passwords were expected to be memorized, but the large number of ...
dialog box sequence. Here, the username is John and password is app123: tell application "Finder" set passAns to "app123" set userAns to "John" if the text returned of (display dialog "Username" default answer "") is userAns then display dialog "Correct" buttons default button 1 if the text returned of (display dialog "Username : John" & return & "Password" default answer "" buttons default button 1 with hidden answer) is passAns then display dialog "Access granted" buttons default button 1 else display dialog "Incorrect password" buttons default button 1 end if else display dialog "Incorrect username" buttons default button 1 end if end tell


Development tools


Script editors

Script editors provide a unified programing environment for AppleScripts, including tools for composing, validating, compiling, running, and debugging scripts. They also provide mechanisms for opening and viewing AppleScript dictionaries from scriptable applications, saving scripts in a number of formats (compiled script files, application packages, script bundles, and plain text files), and usually provide features such as
syntax highlighting Syntax highlighting is a feature of text editors that are used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms ...
and prewritten code snippets.


From Apple

;
AppleScript Editor Script Editor (called AppleScript Editor from 2009 to 2014) is a code editor for the AppleScript and Javascript for Automation scripting languages, included in classic Mac OS and macOS. AppleScript Editor provides basic debugging capabili ...
(Script Editor): The editor for AppleScript packaged with macOS, called ''AppleScript Editor'' in
Mac OS X Snow Leopard Mac OS X Snow Leopard (version 10.6) is the seventh major release of macOS, Apple's desktop and server operating system for Macintosh computers. Snow Leopard was publicly unveiled on June 8, 2009 at Apple’s Worldwide Developers Conference. ...
(10.6) through
OS X Mavericks OS X Mavericks (version 10.9) is the 10th major release of macOS, Apple Inc.'s desktop and server operating system for Macintosh computers. OS X Mavericks was announced on June 10, 2013, at WWDC 2013, and was released on October 22, 2013, wo ...
(10.9) and ''Script Editor'' in all earlier and later versions of macOS. Scripts are written in document editing windows where they can be compiled and run, and these windows contain various panes in which logged information, execution results, and other information is available for debugging purposes. Access to scripting dictionaries and prewritten code snippets is available through the application menus. Since
OS X Yosemite OS X Yosemite ( ; version 10.10) is the eleventh major release of macOS, Apple Inc.'s desktop and server operating system for Macintosh computers. OS X Yosemite was announced and released to developers on June 2, 2014, at WWDC 2014 and rel ...
(10.10), Script Editor includes the ability to write in both AppleScript and
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
. ;
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
: A suite of tools for developing applications with features for editing AppleScripts or creating full-fledged applications written with AppleScript.


From third parties

; Script Debugger, from Late Night Software: A third-party commercial IDE for AppleScript. Script Debugger is a more advanced AppleScript environment that allows the script writer to debug AppleScripts via single stepping,
breakpoint In software development, a breakpoint is an intentional stopping or pausing place in a program, put in place for debugging purposes. It is also sometimes simply referred to as a pause. More generally, a breakpoint is a means of acquiring know ...
s, stepping in and out of functions/subroutines, variable tracking, etc. Script Debugger also contains an advanced dictionary browser that allows the user to see the dictionary in action in real world situations. That is, rather than just a listing of what the dictionary covers, one can open a document in
Pages Page most commonly refers to: * Page (paper), one side of a leaf of paper, as in a book Page, PAGE, pages, or paging may also refer to: Roles * Page (assistance occupation), a professional occupation * Page (servant), traditionally a young mal ...
, for example, and see how the dictionary's terms apply to that document, making it easier to determine which parts of the dictionary to use. Script Debugger is not designed to create scripts with a GUI, other than basic alerts and dialogs, but is focused more on the coding and debugging of scripts. ;
Smile A smile is a facial expression formed primarily by flexing the muscles at the sides of the mouth. Some smiles include a contraction of the muscles at the corner of the eyes, an action known as a Duchenne smile. Among humans, a smile expresses ...
and SmileLab: A third-party freeware/commercial IDE for AppleScript, itself written entirely in AppleScript. Smile is free, and primarily designed for AppleScript development. SmileLab is commercial software with extensive additions for numerical analysis, graphing, machine automation and web production. Smile and SmileLab use an assortment of different windows—AppleScript windows for running and saving full scripts, AppleScript terminals for testing code line-by-line, unicode windows for working with text and XML. Users can create complex interfaces—called dialogs—for situations where the built-in dialogs in AppleScript are insufficient. ;ASObjC Explorer 4, from Shane Stanley: A discontinued third-party commercial IDE for AppleScript, especially for AppleScriptObjC. The main feature is Cocoa-object/event logging, debugging and code-completion. Users can read Cocoa events and objects like other scriptable applications. This tool was originally built for AppleScript Libraries (available in
OS X Mavericks OS X Mavericks (version 10.9) is the 10th major release of macOS, Apple Inc.'s desktop and server operating system for Macintosh computers. OS X Mavericks was announced on June 10, 2013, at WWDC 2013, and was released on October 22, 2013, wo ...
). AppleScript Libraries aims for re-usable AppleScript components and supports built-in AppleScript dictionary (sdef). ASObjC Explorer 4 can be an external Xcode script editor, too. ;FaceSpan, from Late Night Software: A discontinued third-party commercial IDE for creating AppleScript applications with graphic user interfaces.


Script launchers

AppleScripts can be run from a script editor, but it is usually more convenient to run scripts directly, without opening a script editor application. There are a number of options for doing so: ;Applets: AppleScripts can be saved from a script editor as applications (called ''applets'', or ''droplets'' when they accept input via
drag and drop In computer graphical user interfaces, drag and drop is a pointing device gesture in which the user selects a virtual object by "grabbing" it and dragging it to a different location or onto another virtual object. In general, it can be used to ...
). Applets can be run from the Dock, from the toolbar of Finder windows, from
Spotlight Spotlight or spot light may refer to: Lighting * Spot lights, automotive auxiliary lamps * Spotlight (theatre lighting) * Spotlight, a searchlight * Stage lighting instrument, stage lighting instruments, of several types Art, entertainment, an ...
, from third-party
application launcher An application launcher is a computer program that helps a user to locate and start other computer programs. An application launcher provides shortcuts to computer programs, and stores the shortcuts in one place so they are easier to find. In th ...
s, or from any other place where applications can be run. ;Folder actions: Using AppleScript folder actions, scripts can be launched when specific changes occur in folders (such as adding or removing files). Folder actions can be assigned by clicking on a folder and choosing ''Folder Actions Setup...'' from the contextual menu; the location of this command differs slightly in Mac OS X 10.6.x from earlier versions. This same action can be achieved with third-party utilities such as Hazel. ;Hotkey launchers:
Keyboard shortcut computing, a keyboard shortcut also known as hotkey is a series of one or several keys to quickly invoke a software program or perform a preprogrammed action. This action may be part of the standard functionality of the operating system or ...
s can be assigned to AppleScripts in the script menu using the ''Keyboard & Mouse Settings'' Preference Pane in System Preferences. In addition, various third-party utilities are available— Alfred, FastScripts,
Keyboard Maestro Keyboard Maestro is a closed-source commercial macOS-based application that allows automation of routine functions, such as navigating running applications, opening documents, typing text, expanding abbreviations, and controlling web application ...
, QuicKeys, Quicksilver, TextExpander—which can run AppleScripts on demand using key combinations. ;Script menu: This system-wide menu provides access to AppleScripts from the macOS menu bar, visible no matter what application is running. (In addition, many Apple applications, some third-party applications, and some add-ons provide their own script menus. These may be activated in different ways, but all function in essentially the same manner.) Selecting a script in the script menu launches it. Since Mac OS X 10.6.x, the system-wide script menu can be enabled from the preferences of Script Editor; in prior versions of Mac OS X, it could be enabled from the AppleScript Utility application. When first enabled, the script menu displays a default library of fairly generic, functional AppleScripts, which can also be opened in Script Editor and used as examples for learning AppleScript. Scripts can be organized so that they only appear in the menu when particular applications are in the foreground. ;Unix command line and launchd: AppleScripts can be run from the Unix command line, or from launchd for scheduled tasks, by using the osascript command line tool. The osascript tool can run compiled scripts (.scpt files) and plain text files (.applescript files—these are compiled by the tool at runtime). Script applications can be run using the Unix open command.


AppleScript resources


AppleScript Libraries

Re-usable AppleScript
module Module, modular and modularity may refer to the concept of modularity. They may also refer to: Computing and engineering * Modular design, the engineering discipline of designing complex devices using separately designed sub-components * Mo ...
s (available since
OS X Mavericks OS X Mavericks (version 10.9) is the 10th major release of macOS, Apple Inc.'s desktop and server operating system for Macintosh computers. OS X Mavericks was announced on June 10, 2013, at WWDC 2013, and was released on October 22, 2013, wo ...
), written in AppleScript or AppleScriptObjC and saved as script files or bundles in certain locations, that can be called from other scripts. When saved as a bundle, a library can include an AppleScript dictionary (sdef) file, thus functioning like a scripting addition but written in AppleScript or AppleScriptObjC.


AppleScript Studio

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.


AppleScriptObjC

A Cocoa development software framework, also called AppleScript/Objective-C or ASOC, part of the Xcode package since
Mac OS X Snow Leopard Mac OS X Snow Leopard (version 10.6) is the seventh major release of macOS, Apple's desktop and server operating system for Macintosh computers. Snow Leopard was publicly unveiled on June 8, 2009 at Apple’s Worldwide Developers Conference. ...
. AppleScriptObjC allows AppleScripts to use Cocoa classes and methods directly. The following table shows the availability of AppleScriptObjC in various versions of macOS: AppleScriptObjC can be used in all subsequent Mac OS X verisions.


Automator

A graphical, modular editing environment in which ''workflows'' are built up from ''actions''. 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.


Scriptable core system applications

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: :*
VoiceOver Voice-over (also known as off-camera or off-stage commentary) is a production technique where a voice—that is not part of the narrative (non- diegetic)—is used in a radio, television production, filmmaking, theatre, or other presentations. ...
(scriptable auditory and braille screen reader package) :* System Events (control of non-scriptable applications and access to certain system functions and basic file operations) :* Printer Setup Utility (scriptable utility for handling print jobs) :* Image Events (core image manipulation) :* HelpViewer (scriptable utility for showing help displays) :* Database Events (minimal SQLite3 database interface) :* AppleScript Utility (for scripting a few AppleScript related preferences)


Scripting Additions (OSAX)

Plug-ins for AppleScript developed by Apple or third parties. 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.


Language essentials


Classes (data types)

While applications can define specialized classes (or data types), AppleScript also has a number of built-in classes. These basic data classes are directly supported by the language and tend to be universally recognized by scriptable applications. The most common ones are as follows: * Basic objects ** application: an application object, used mostly as a specifier for tell statements (tell application "Finder" …). ** script: a script object. Script objects are containers for scripts. Every AppleScript creates a script object when run, and script objects may be created within AppleScripts. ** class: a meta-object that specifies the type of other objects. ** reference: an 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 contents property. * Standard data objects ** constant: a constant value. There are a number of language-defined constants, such as pi, tab, and linefeed. ** boolean: a Boolean true/false value. Actually a subclass of constant. ** number: a rarely used abstract superclass of integer and real. ** integer: an
integer An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
. Can be manipulated with built-in mathematical operators. ** real: a floating-point (
real Real may refer to: Currencies * Brazilian real (R$) * Central American Republic real * Mexican real * Portuguese real * Spanish real * Spanish colonial real Music Albums * ''Real'' (L'Arc-en-Ciel album) (2000) * ''Real'' (Bright album) (2010) ...
) number. Can be manipulated with built-in mathematical operators. ** date: a date and time. ** text: text. In versions of AppleScript before 2.0 (Mac OS X 10.4 and below) the text class was distinct from string and Unicode text, and the three behaved somewhat differently; in 2.0 (10.5) and later, they are all synonyms and all text is handled as being
UTF-16 UTF-16 (16-bit Unicode Transformation Format) is a character encoding capable of encoding all 1,112,064 valid code points of Unicode (in fact this number of code points is dictated by the design of UTF-16). The encoding is variable-length, as cod ...
(“
Unicode Unicode, formally The Unicode Standard,The formal version reference is is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems. The standard, wh ...
”)-encoded. * Containers ** list: an ordered list of objects. Can contain any class, including other lists and classes defined by applications. ** record: a keyed list of objects. Like a list, except structured as key–value pairs. Runtime keyed access is unsupported; all keys must be compile-time constant identifiers. * File system ** alias: a reference to a file system object (file or folder). The alias will maintain its link to the object if the object is moved or renamed. ** file: a reference to a file system object (file or folder). This is a static reference, and can point to an object that does not currently exist. ** POSIX file: a reference to a file system object (file or folder), in plain text, using Unix (
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming inter ...
)-style slash (/) notation. Not a true data type, as AppleScript automatically converts POSIX files to ordinary files whenever they are used. * Miscellaneous ** RGB color: specifies an RGB triplet (in 16-bit high color format), for use in commands and objects that work with colors. ** unit types: class that converts between standard units. For instance, a value can be defined as square yards, then converted to square feet by casting between unit types (using the as operator).


Language structures

Many AppleScript processes are managed by blocks of code, where a block begins with a command ''command'' and ends with an ''end command'' statement. The most important structures are described below.


Conditionals

AppleScript offers two kinds of conditionals. -- Simple conditional if x < 1000 then set x to x + 1 -- Compound conditional if x is greater than 3 then -- commands else -- other commands end if


Loops

The repeat loop of AppleScript comes in several slightly different flavors. They all execute the block between repeat and end repeat lines a number of times. The looping can be prematurely stopped with command exit repeat. Repeat forever. repeat -- commands to be repeated end repeat Repeat a given number of times. repeat 10 times -- commands to be repeated end repeat Conditional loops. The block inside repeat while loop executes as long as the condition evaluates to true. The condition is re-evaluated after each execution of the block. The repeat until loop is otherwise identical, but the block is executed as long as the condition evaluates to false. 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 Loop with a variable. When starting the loop, the variable is assigned to the start value. After each execution of the block, the optional step value is added to the variable. Step value defaults to 1. -- 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 Enumerate a list. On each iteration set the loopVariable to a new item in the given list set total to 0 repeat with loopVariable in set total to total + loopVariable end repeat One important variation on this block structure is in the form of on —end ... blocks that are used to define ''handlers'' (function-like subroutines). Handlers begin with ''on functionName()'' and ending with ''end functionName'', and are not executed as part of the normal script flow unless called from somewhere in the script. Handlers can also be defined using "to" in place of "on" and can be written to accept labeled parameters, not enclosed in parens. 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". on open theItems repeat with thisItem in theItems tell application "Finder" to update thisItem end repeat end open 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. 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 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, 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. on quit --commands to execute before the script quits continue quit -- required for the script to actually quit end quit ;Script objects: Script objects may be defined explicitly using the syntax: script scriptName -- commands and handlers specific to the script end script Script objects can use the same 'tell' structures that are used for application objects, and can be loaded from and saved to files. Runtime execution time can be reduced in some cases by using script objects.


Miscellaneous information

* Variables are not strictly typed, and do not need to be declared. Variables can take any data type (including scripts and functions). The following commands are examples of the creation of variables:set variable1 to 1 -- create an integer variable called variable1 set variable2 to "Hello" -- create a text variable called variable2 copy to variable3 -- create a list variable called variable3 set to variable3 -- copy the list items of variable3 into separate variables variable4 and variable5 set variable6 to script myScript -- set a variable to an instance of a script * Script objects are full objects—they can encapsulate methods and data and inherit data and behavior from a parent script. * Subroutines cannot be called directly from application tell blocks. Use the 'my' or 'of me' keywords to do so. tell application "Finder" set x to my myHandler() -- or set x to myHandler() of me end tell on myHandler() --commands end myHandler Using the same technique for scripting addition commands can reduce errors and improve performance. tell application "Finder" set anyNumber to my (random number from 5 to 50) end tell


Open Scripting Architecture

An important aspect of the AppleScript implementation is the Open Scripting Architecture (OSA). Apple provides OSA for other scripting languages and third-party scripting/automation products such as QuicKeys and UserLand Frontier, to function on an equal status with AppleScript. AppleScript was implemented as a scripting
component Circuit Component may refer to: •Are devices that perform functions when they are connected in a circuit.   In engineering, science, and technology Generic systems * System components, an entity with discrete structure, such as an assem ...
, and the basic specs for interfacing such components to the OSA were public, allowing other developers to add their own scripting components to the system. Public client
API An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how ...
s for loading, saving and compiling scripts would work the same for all such components, which also meant that applets and droplets could hold scripts in any of those scripting languages. One feature of the OSA is scripting additions, or OSAX for ''Open Scripting Architecture eXtension'', which were inspired by
HyperCard HyperCard is a software application and development kit for Apple Macintosh and Apple IIGS computers. It is among the first successful hypermedia systems predating the World Wide Web. HyperCard combines a flat-file database with a graphical, f ...
's External Commands. Scripting additions are
libraries A library is a collection of Document, materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or electronic media, digital access (soft copies) materials, and may be a ...
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 ). The AppleScript Editor is also able to directly edit and run some of the OSA languages.


JavaScript for Automation

Under
OS X Yosemite OS X Yosemite ( ; version 10.10) is the eleventh major release of macOS, Apple Inc.'s desktop and server operating system for Macintosh computers. OS X Yosemite was announced and released to developers on June 2, 2014, at WWDC 2014 and rel ...
and later versions of macOS, the JavaScript for Automation (JXA) component remains the only serious OSA language alternative to AppleScript, though the Macintosh versions of
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
, and
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited ...
all support native means of working with Apple events without being OSA components. JXA also provides an
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
(and C language) foreign language interface. 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 use
CommonJS CommonJS is a project with the goal to establish conventions on the module ecosystem for JavaScript outside of the web browser. The primary reason for its creation was a major lack of commonly accepted forms of JavaScript module units which could ...
modules via browserify.


See also

*
BBEdit BBEdit is a proprietary text editor made by Bare Bones Software, originally developed for Macintosh System Software 6, and currently supporting macOS. History The first version of BBEdit was created as a "bare bones" text editor to serve as a "p ...
— a highly scriptable text editor *
ARexx ARexx is an implementation of the Rexx language for the Amiga, written in 1987 by William S. Hawes, with a number of Amiga-specific features beyond standard REXX facilities. Like most REXX implementations, ARexx is an interpreted language. Program ...
— competitive technology of 1987


References


Further reading

* * * * * * * * *


External links

* * * * * {{DEFAULTSORT:Applescript Macintosh operating systems development MacOS development Proprietary software Scripting languages Programming languages High-level programming languages Programming languages created in 1993 1993 software Dynamic programming languages Dynamically typed programming languages