AppleScript

From Wikipedia, the free encyclopedia
  (Redirected from Applescript)
Jump to: navigation, search
AppleScript
AppleScript Editor Logo.png
Paradigm Natural language, Scripting
Appeared in 1993
Developer Apple Inc.
Stable release 2.1.1 (November 9, 2009; 8 months ago (2009-11-09))
Typing discipline weak, dynamic
Influenced by Natural language, HyperCard
OS System 7, Mac OS 8, Mac OS 9, Mac OS X
License Apple EULA (parts available under APSL)
Usual file extensions .scpt .applescript
Website developer.apple.com/applescript/

AppleScript is a scripting language created by Apple Inc. and built into Macintosh operating systems since system 7. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language.

Applescript is primarily an inter-application processing system, designed to exchange data between and control other applications in order to automate repetitive tasks. AppleScript has some limited processing abilities of its own - basic calculation abilities, and some more intricate text processing tools - and is extensible, allowing the addition of scripting additions which add new functions to the language itself. Mainly, however, AppleScript relies on the built-in functionalities of other applications and processes to handle complex tasks.

Applescript has some elements of object-oriented programming, particularly in the construction of script objects, and some lisp-like natural language processing tendencies, but fails to conform to either category properly.

Contents

[edit] History

The AppleScript project was an outgrowth of the (now discontinued) HyperCard project. HyperCard contained an English language-based scripting language called HyperTalk, which could be used to program a HyperCard stack. Apple engineers recognized that a similar scripting language could be designed to be used with any application, and the AppleScript project was born as part of System 7.

AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7). 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 to Mac OS X (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 allowed AppleScripts much greater control over the operating system itself. AppleScript Studio, released with Mac OS X 10.2 as part of XCode, and later AppleScriptObjC framework, released in Mac OS X 10.6, allows users to build native Cocoa applications using AppleScript.

AppleScript is one component of Mac OS X Automation technologies along with Services and Automator.

[edit] 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 can be used to create automated workflows which can reduce the time and repetitiveness of various tasks, minimize the opportunity for human error, provide consistent output, and facilitate a manageable production system. AppleScript leverages Apple Events: a set of standardized data formats that the Macintosh operating system uses to send information to applications. 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:

  1. Open a photo in a photo-editing application (by sending that application an Open File Apple Event).
  2. Tell the photo-editing application to manipulate the image (e.g. reduce its resolution, add a border, add a photo credit)
  3. Tell the photo-editing application to save the changed image in a file in some different folder (by sending that application an Save and/or Close Apple Events).
  4. Send the new file path (via another Apple Event) to a text editor or web editor application
  5. Tell that editor application to write a link for the photo into an HTML file.
  6. Repeat the above steps for an entire folder of images (hundreds or even thousands of photos).
  7. Upload the HTML file and folder of revised photos to a website, by sending Apple Events to an FTP 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 AppleScript 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 commands that can be given to scriptable objects. The general format for block of AppleScript is to tell a scriptable object run a command.

All scriptable applications share a few of 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 built scripts intuitively by recording user actions. When the AppleScript Editor is open and the Record button clicked, any user actions on the computer - in any application that supports AppleEvents and AppleScript recording - are converted to their equivalent AppleScript commands and placed in 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.

[edit] Hello World!

In AppleScript, the traditional Hello World! program can be written is a couple of different forms:

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
-- or
say "Hello World!" -- an audio message using a synthesized computer voice

AppleScript dialogs are rudimentary but can be customized to a limited extent, and return the values of buttons and text for further processing. For example:

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

[edit] 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 Mac OS tradition of ease-of-use, the AppleScript language is designed on the natural language metaphor, just as the graphical user interface is designed on the desktop 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 the AppleEvent 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 (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 Apple Events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In the Xcode 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:

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 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 phrases:

pixel 7 of row 3 of TIFF image "my bitmap"

which in another programming language might be expressed as sequential method calls:

getTIFF("my bitmap").getPixel(3,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 called synonyms. Also, to add to the English-likeness, 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.

[edit] AppleScript development tools

[edit] 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 application, saving scripts in a number of formats (compiled script files, application packages, script bundles, and plain text files), and usually provide bells and whistles such as syntax highlighting and prewritten code snippets.

AppleScript Editor (called Script Editor in versions of OS X prior to 10.6 Snow Leopard)
The editor for AppleScript packaged with Mac OS X. 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.
Smile and SmileLab, available from (Satimage)
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.
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, breakpoints, 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, 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.
FaceSpan, from Late Night Software
a third-party commercial IDE for creating AppleScript applications with Graphic User Interfaces. Development of FaceSpan has been suspended.

[edit] 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:

Script Menu
This system-wide menu provides access to AppleScripts from the Mac OS X menu bar, visible no matter what application is running. Selecting a script in the script menu launches it. In 10.6.x, the script menu is activated from the preferences of the AppleScript Editor; in prior versions of OS X, it was activated from the AppleScript Utility application. When first activated, 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.

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.

Hotkey Launchers
Keyboard shortcuts can be assigned to AppleScripts in the script menu using the System Preferences "Keyboard & Mouse Settings". Various third-party utilities are available - QuickKeys, Spark - which can run AppleScripts on demand using key combinations.
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 10.6.x from earlier versions. This same action can be achieved with third-party utilities such as Hazel.
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.

[edit] Related Scripting Issues

Automator
Automator is 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 OS X, are used to allow AppleScript to access features that would not normally be scriptable. As of 10.6.3 they include the scriptable applications for VoiceOver (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), and AppleScript Utility (for scripting a few AppleScript related preferences), as well as a few utility applications used by the system.
AppleScriptObjC
Part of the XCode package, a cocoa development environment, which is available on the Mac OS X install CD but not installed by default. AppleScriptObjC allows AppleScripts to call Cocoa commands directly.
AppleScript Studio
Part of the XCode package in 10.4 and 10.5, now deprecated. A framework for attaching Cocoa interfaces to AppleScript applications.
Scripting Additions (OSAX)
Scripting additions are 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 in somewhat less dependent on functionality provided by applications. For instance, Apple's Standard Addition.osax scripting addition adds a set of commands and classes that that are not part of AppleScript's core features - without this osax, AppleScript would have no capacity to display dialogs or use navigation services.

[edit] AppleScript language essentials

[edit] Classes (data types)

Applescript has a number of built-in classes (or data types), though of course an application can and most likely will define extra data types for its own purposes. The basic data classes that should be universally recognized are as follows:

[edit] 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: for instance:

Looping Conditionals Application Targeting Error Handling
Repeat with i from 1 to 2000
     -- commands to be repeated
end repeat
if x is greater than 3 then
     -- commands
else
     -- other commands
end if
tell application "MyApp"
     -- commands for app
end tell
try
     -- commands to be tested
on error
     -- error commands 
end try

One important variation on this are on - end ... structures that are used to define handlers (function-like subroutines) and specify certain conditions Subroutines - called handlers are structured similarly, starting with on functionName() and ending with end functionName

Function handler Folder actions block Run handler
on myFunction(parameters...)
     -- subroutine commands 
end myfunction
on adding folder items to thisFolder after receiving theseItems
     -- commands to apply to the folder or items 	
end adding folder items to
on run
     --  commands	
end run

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 handlers are optional, unless arguments are being passed to the script.
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 hander 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 one second by default, but can be changes by including a 'return x' statement at the end of the subroutine, where x is he 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 quites
  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.

[edit] Miscellaneous info

set variable1 to 1 -- create an integer variable called variable1
set variable2 to "Hello" -- create an text variable called variable2
copy {17, "doubleday"} to variable3 -- create a list variable called variable3
set {variable4 , variable5} 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
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

[edit] Open Scripting Architecture

An important aspect of the AppleScript implementation is the Open Scripting Architecture (OSA).[1] Apple provides OSA for 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, 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 APIs 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.

Under Mac OS X, the JavaScript OSA component remains the only serious OSA language alternative to AppleScript, though the Macintosh versions of Perl, Python, Ruby, and Tcl all support native means of working with AppleEvents without being OSA components. The MacRuby development roadmap shows that OSA conformance is planned in version 0.6.[2]

One of the most interesting features of the OSA are "scripting additions", or OSAX for Open Scripting Architecture eXtension, which were based on Hypercard's External Commands. Scripting Additions allow programmers to extend the function of AppleScript. Commands included as Scripting Additions are available system wide, and are not dependent on an application. Mac OS X includes a collection of scripting additions referred to as Standard Additions, which extends the function of AppleScript with a variety of new commands, including user interaction dialogs, reading and writing files, file system commands, date functions, text and math operations.

[edit] References

[edit] Further reading

[edit] External links

Personal tools
Namespaces
Variants
Actions
Navigation
Interaction
Toolbox
Print/export
Languages