AppleScript Programming/Printable version
This is the print version of AppleScript Programming You won't see this message or any elements not part of the book's content when you print or preview this page. |
The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/AppleScript_Programming
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 | edit source]{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 | edit source]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:
activate
ASCII character
ASCII number
beep
choose application
choose color
choose file
choose file name
choose folder
choose from list
choose remote application
choose URL
clipboard info
close access
copy
count
current date
delay
display alert
display dialog
display notification
do shell script
get
get eof
get volume settings
info for
launch
list disks
list folder
load script
localized string
log
mount volume
offset
open for access
open location
path to (application)
path to (folder)
path to resource
random number
read
round
run
run script
say
scripting components
set
set eof
set the clipboard to
set volume
store script
summarize
system attribute
system info
the clipboard
time to GMT
write
Comments
[edit | edit source]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 | edit source]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.
![](http://upload.wikimedia.org/wikibooks/en/0/0e/Shortest_applescript.png)
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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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.
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 | edit source]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 | edit source]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 | edit source]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.
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 | edit source]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 | edit source]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
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 | edit source]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 | edit source]The osascript utility allows shell scripts to execute Applescript code in three different ways.
- Line by line from within a shell script using the
osascript -e
- Specify a plain text file or compiled script file using
osascript filename
. - 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:
Script Libraries
![]() |
This page or section is an undeveloped draft or outline. You can help to develop the work, or you can ask for assistance in the project room. |
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:
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 | edit source]![]() |
This page or section is an undeveloped draft or outline. You can help to develop the work, or you can ask for assistance in the project room. |
3rd Party Codes
![]() |
This page or section is an undeveloped draft or outline. You can help to develop the work, or you can ask for assistance in the project room. |
Sample Programs
Sample Programs
[edit | edit source]- Mail alert
- Archive selected mail
- Run QuickTime in full screen
- Converter for temperatures
- Letter Replacer
- Calculator
- Safari Quit Warning
- Create new Word doc and insert text and format text
- Create a unique email address
- Guess The Character Game