AppleScript Programming/Printable version


AppleScript Programming

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/AppleScript_Programming

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Introduction

AppleScript is an object-oriented scripting language, spesifically designed to work with inter-application communication facilitating Apple Events. An object is an instance of a predefined class with shared characteristics.

The objects one may work with using the AppleScript language may be defined within three different sources: Within the AppleScript Language itself, within macOS scriptable applications, or within third party applications. All classes and commands from these sources should be documented in the Scripting dictionaries available from the menu of the Script Editor application.

Classes of AppleScript

edit
{alias, application, boolean, class, constant, date, file, integer, list, number, POSIX file, real, record, reference, RGB color, script, text, string, Unicode text}
{centimeters, feet, inches, kilometers, meters, miles, yards, square feet, square kilometers, square meters, square miles, square yards, cubic centimeters, cubic feet, cubic inches, cubic meters, cubic meters, cubic yards, gallons, liters, liters, quarts, grams, kilograms, ounces, pounds, degrees Celsius, degrees Fahrenheit, degrees Kelvin}

Commands

edit

Working with AppleScript one might come across AppleScript commands, scripting addition commands, user-defined commands and application commands.

The standard additions to AppleScript contains a range of commands available to all scripts. The commands are:

Comments

edit

To document comments a programmer usually writes some comments along the way. Single line comments are written after # or --. Multi line comments are wrapped in (* *).

#  This is a single line comment
-- This is a single line comment
(* This is a 
   multi line 
   comment *)


Basic commands

AppleScript is a programming language that is somewhat similar to English making it easier to understand than some programming languages. The commands in AppleScript are written in a syntax similar to English. This allows users more easily understand the code.

A first script

edit

Alright, let's write our first program! Launch your Script Editor application (in /Applications/Applescript [pre OSX 10.5] or /Applications/Utilities [OSX 10.5 or later]) and type this into your new document:

beep

Then hit the run button.

 

Your Mac should now play its default beep sound. You have just learned your first AppleScript command: beep. The above script is the shortest script in AppleScript, or at least the shortest that does something.

Dialog boxes

edit

But if you're going to write a tool for scripting programs or even a small AppleScript program, you're going to need to learn to do more than to make the computer beep. The next command we will explore is "display dialog". A display dialog command is written like this:

display dialog "the text to display goes here"

This can be used to present information to a user or, as you will find out later, ask for it.

Setting variables

edit

Another vital command you should learn is the "set" command. The "set" command sets variables to strings, lists, records, and other variable types. Here is a set command in action:

set theVariable to "Support Wikibooks!"

Now, if one wanted to show the user what the text stored in variable "theVariable" was, they could type:

display dialog theVariable

A dialog box would appear with the text "Support Wikibooks!"

Now you know three vital commands and were briefly introduced to strings. More information on strings is in the next module.

Using variables with strings

edit

You can use a variable and a string in the same display dialog line. They are combined with &

set project to "Wikibooks"
display dialog "Support " & project

Exercises

edit

Create a program says "Hello [your name]" with [your name] in a variable.

(Answers)


Numbers and strings

Variables, Numbers, and Strings: In the last section, the "set" command was used to set a variable, in this case "theVariable" to the string "Support Wikibooks!". In this chapter, you will learn about variables, numbers, and strings.

Variables

edit

Variables, if you are unfamiliar to programming or algebra, are words that represent some function. For example, in Algebra, the variable x in the equation x-5=1 must equal 6. Variables in AppleScript can be most single letters or any word that is not a command. However, since many normal words are commands in AppleScript, the easiest way to pick a sure-fire variable is to use CamelCase, or to have capitalization insideTheSentence likeThis. Variables are always set using the set command or copy command.

Numbers

edit

Now let's use the three commands we know to write a simple number-based program. Try putting this into your Script Editor:

set firstVariable to 5
set secondVariable to 3
display dialog firstVariable - secondVariable

The result is a message box displaying the result (2).

Strings

edit

Numbers are very useful for mathematical computations by nature. However, what if you want a script to tell you text? This is where strings come in. A string is a type of data stored by a variable that contains a simple line or lines of text.

By putting this in your Script Editor, you can say, you're working with String Variables:

set firstString to "Hello, "
set secondString to "User!"
display dialog firstString & secondString

The result is a message box displaying the result (Hello, User!).

Now put:

set firstString to "Hello, "
set secondString to "User!"
display dialog firstString & secondString default answer "3"

Now the user can define the variable.

Next Page: Lists and records | Previous Page: Basic commands
Home: AppleScript Programming


Lists and records

For the best results, you should have Script Editor open, so you can test the code and results as you read.

Basics of Lists

edit

Applescript has two separate classes of data structure that are used to represent a collection of items: the list class, and the record class. A list is an ordered collection of objects, which can be any value or data structure that AppleScript understands. To say that the contents of a list is ordered means that every item in the list occupies a numbered position. This number is termed the item's index, which can be used to retrieve a specific item from a list.

List creation is simple, anything that you put between a { and a } is a list.

set myList to {} -- make a new list
set myList to myList & {1, "two", {7}, {fred:"barney", wilma:"betty", foo:"bar"}, 5} -- add a bunch of items to the list
set k to {6, "three", {8}, {george:"jetson", elroy:"jetson", judy:"jetson"}, 0}

In the example above we create two lists. The first list l contains 5 items, the number 1, a string "two", a list containing the number 7, a record containing three properties, fred, wilma, and foo with string values, and the number 5.

We can access these items in several ways. The statements

item 3 of myList
third item of myList
myList's third item
myList's item 3

Will all return the same value, {7}, that is, a list containing the number 7.

Looping Through a String As If It Were a List

edit

This works a character at a time. (Strings are sequences of characters and behave accordingly.)

 
set my_string to "freedom is not freedom fries"
repeat with counter_variable_name from 1 to count of my_string
	set current_character to item counter_variable_name of my_string
end repeat

Basics of Records

edit

A record is a list of properties. You can retrieve items from a record by name, but not by index. For example, to retrieve the elroy of the property list {scooby:"doo", elroy:"jetson",grape:"ape"}, I can retrieve it by name.

elroy of {scooby:"doo", elroy:"jetson", grape:"ape"}

Which will return the string "jetson"

but not by index,

item 2 of {scooby:"doo", elroy:"jetson", grape:"ape"}

Which returns an error.

Next Page: Aliases and paths | Previous Page: Numbers and strings
Home: AppleScript Programming


Aliases and paths

Paths can appear in the following format in AppleScript which is a carryover from Classic Mac OS. This type of path name is called HFS which is short for "Hierarchical File System".

<Volume Name>:<Directory Name>:...:<Directory Name>:<Filename>

For example, the following is an example an HFS path name

Macintosh HD:Applications:Safari.app

HFS paths are different than the current OS X standard, called w:POSIX paths. The POSIX style comes from OS X's Unix heritage. Notice that in HFS path names, a colon ":", is used as a separator, and in POSIX path names, a forward slash "/" is used as a separator. The other major difference is that in HFS path names, the path name begins with the name of the volume and in POSIX path names, the startup volume doesn't need to be named, only other volumes need to be named.

Because of the history of OS X with both a Classic Mac OS history and a Unix history both HFS paths and POSIX paths are still useful and in AppleScript you sometimes have to convert from one standard to the other, depending upon which kind of path name is needed.

The following example of a POSIX path specifies the application Safari.app which is contained by the Applications folder on the start up disk.

/Applications/Safari.app

Converting between formats

edit

Assuming oldPath would be an alias or record of a finder item, use the following command to set a standard Applescript alias to a POSIX path:

 set thisPOSIXPath to (the POSIX path of oldPath)
 -- input: "Macintosh HD:Applications:Safari.app"
 -- output: "/Applications/Safari.app"


To convert a POSIX path to a standard Applescript alias (the inverse of the above command), use this command:

 set newerPath to POSIX file newPath as alias -- omit 'as alias' to get a file object
 -- input: "/Applications/Safari.app"
 -- output: "Macintosh HD:Applications:Safari.app"


Scripting other applications

AppleScript can be used with other applications using the "tell" command. The tell command means to send a message to an application.

Anything written under that will be executed in the application Safari. So if we wanted to tell Safari to activate, we'd type:

tell application "Safari"
   activate
end tell

The "end tell" command will let AppleScript know that it has reached the end of the command. Also, make sure that the name of the application is in "quotes".

You can also shorten the command above to simply this:

tell application "Safari" to activate

Of course what Safari is for is getting content off of the web. The following example code activates Safari and has it open a particular web page.

tell application "Safari"
	activate
	open location "http://learnbymac.com"
end tell

Or instead of telling Safari to open a location, we could tell the Finder to and instead of our script specifying that Safari be run, the Finder would pick the default web browser and run that instead.

tell application "Finder"
	open location "http://learnbymac.com"
end tell

Notice that in the example above, we did not tell the Finder to activate. This means that the Finder didn't need to become the frontmost application. It just needed to be running, which is always is, and open the default web browser, which could be Firefox.app which doesn't even support AppleEvents. The Finder processed the tell-message and did the required action.

One thing that AppleScript is good at—why it was developed—is to combine the functionality of different Mac applications and let the user make new software without "reinventing the wheel"

Application Numbers

edit

In the script below a range of cell values are read from the variable myTable which contains a reference to a table in an active document. It reads the values horizontally within the range, according to the reading direction of the language.

tell application "Numbers"

   tell myTable
      return value of every cell of range "A1:B10"
   end tell

end tell
Next Page: System Events | Previous Page: Aliases and paths
Home: AppleScript Programming


System Events

One of the many things that can be used with Applescript, is System Events. To use the System Event application, you must first give it a "tell" command.

 tell application "System Events"
   -- add code here.
 end tell

This will tell applescript to execute commands associated with the program System Events. For example, the command:

 keystroke "e"

Will type the letter "e" into the current application.

Here's a simple program:

tell application "TextEdit"
	activate
	make new document
end tell
tell application "System Events"
	keystroke "Support Wikibooks!"
end tell

It will open the application TextEdit, start a new document, and type the phrase "Support Wikibooks!"

You can also use keystroke tab (note that there are no quotes) to type a tab, and keystroke return to enter a new line.

tell application "TextEdit"
	activate
	make new document
end tell
tell application "System Events"
	keystroke "Support Wikibooks!"
	keystroke return
	keystroke "by donating!"
end tell

Which will create a new document with Support Wikibooks! and by donating, on another line.

Now you may be wondering, How do I perform key combinations like command+q (Works with other modifier keys, like option, and control)

Key combos is a three line code consisting of

key down {command}
keystroke "q"
key up {command}

You can also hold down many keys at a time using the augment of key down and key up but separating keys using commas

Here is a program that will open text edit and then quit it using command+q:

tell application "TextEdit"
	activate
end tell

delay 3.0

tell application "System Events"
	key down {command}
	keystroke "q"
	key up {command}
end tell

You can also use one line commands for keystrokes, such as:

tell application "System Events" to keystroke "c" using command down

Which will invoke Copy in most Mac applications.

It is possible to use combokeys in oneline like this:

keystroke "h" using {command down, shift down}


Shell Programming

AppleScript can interact with UNIX shell scripts in a couple of ways. AppleScript can call UNIX shell scripts and utilities using the "do shell script" command. UNIX shell scripts can call the "osascript" utility to execute AppleScript code.

AppleScript command "do shell script"

edit

To run shell commands from Applescript:

do shell script "afplay /System/Library/Sounds/Glass.aiff"

The user would hear a sound.

Shell command "osascript"

edit

The osascript utility allows shell scripts to execute Applescript code in three different ways.

  1. Line by line from within a shell script using the osascript -e
  2. Specify a plain text file or compiled script file using osascript filename.
  3. Through the standard input.

For example, the following command in a shell script or at a prompt, will open a Mac OS X dialog box and wait for the user to respond:

osascript -e 'tell app "System Events" to activate' -e 'tell app "System Events" to display dialog "Hello, world!"'

The user would see:

 

Next Page: Script Libraries | Previous Page: System Events
Home: AppleScript Programming


Script Libraries

Next Page: Advanced Code List | Previous Page: Shell Programming
Home: AppleScript Programming


Advanced Code List

Here is list of commands that also contains detailed examples how to use said command. Also, this list aims to include only code that comes with OS X, ignoring any possible "plugins" (and their commands) that do not follow any standard OS X Install.

List attempts to be in alphabetical order.

How To:

Next Page: Standard Additions | Previous Page: Script Libraries
Home: AppleScript Programming


Standard Additions

Standard Additions is a hidden application used exclusively in AppleScript. It contains all of the miscellaneous commands necessary for scripting, but are not attached to any other application.

List of Commands

edit
Next Page: 3rd Party Codes | Previous Page: Advanced Code List
Home: AppleScript Programming


3rd Party Codes

  1. Growl
Next Page: Sample Programs | Previous Page: Standard Additions
Home: AppleScript Programming


Sample Programs

Sample Programs

edit
Next Page: AppleScript Programming | Previous Page: 3rd Party Codes
Home: AppleScript Programming