AppleScript Handbook

Basic

Identifier

A normal identifier must begins with a underline _ or letter and then involves letters, numbers or underlines.

1
2
set age to 100
set _name to "CSL"

Of course, Apple provides a special way that can declare any Unicode chars between two | as a identifier, expect the char | itself.

1
2
set |名字| to "CSL"
set |年龄| to 100

Comments

Uses -- to declare a single line comment.
Uses (* and *) to declare a multiple-line comment.

Basic Types

boolean

The boolean only contains two values: true and false, it isn’t case-sensitive, but I suggest you use the lowercase.

1
2
3
4
5
6
-- Good
set a to true
set b to false
-- Bad
set c to True
set d to False

number

The number is an abstract class that can presents an integer or a real. There is no one object whose class is number. The actual class of a number object is always one of the integer or real.

  • integer
    An integer number doesn’t have a fraction part.
1
2
3
set age to 18
log class of age
--integer
  • real
    A real number actually is a float number.
1
2
3
set weight to 180.5
log class of weight
--real

Operators: +,-,*,÷ (or /), div, mod, ^, =, , >, , <, and .

text/string

The text and string are the same type in AppleScript. A text object represents a ordered serial of Unicode characters.

1
2
3
set myName to "SSBun"
log class of myName
--text
property type explanation
class class The text object’s type, always be text.
id integer or [integer] The Unicode number of every characters in the text.
length integer The number of characters in the text.
quoted form text The quoted form of abc is 'abc'.

constant

A word with a predefined value. You can’t define constants in scripts. constants can be defined only by applications and by AppleScript. eg: pi, the pi is a mathematic value representing 3.1416926.

Operators: &, =, !=andas.

list

An ordered collection of any values. {1, 2, 3}, {}

property type explanation
class class The value is list.
length integer The number of items in the list.
rest list A list containing all items in the list expect the first item.
reverse list A list containing all items in the list, but in the opposite order.

record

A hash map, dictionary. {name: "csl", age: 100}

property type explanation
class class The value is record
length integer The number of properties in the record.

reference

A reference is a pointer that points to a value. When you modify the reference’s value, the pointed value also will change. In AppleScript, set x to y, the x is just a copy of the y.

date

Specifies the date of the week, the date (month, day of month, and year), and the time (hours, minutes, and seconds).

1
2
set now to current date
--date Friday, December 24, 2021 at 10:57:12 AM
property type explanation
class class The value is date
day integer The day of the month.
weekday integer The day of the week.
month integer The month of the year.
year integer The year of the date.
time integer The number of seconds since midnight of a date.
date string text A string that specifies the date portion of a date.
time string text A string that specifies the time portion of a date.

Operators: &, +, , =, , >, , <, , comes before, comes after, and as.

alias

A persistent reference to an exist file, folder or volume in the file system.

property type explanation
class class The value is alias
POSIX path text
1
2
set my_file to choose file
--alias Macintosh HD:Users:csl:Documents:test.txt

file

A file object has exactly the same attributes as a alias object, with a addition that it can refer to a path that doesn’t exist.

1
2
set my_file to choose file name
--file Macintosh HD:Users:csl:Documents:untitled

POSIX file

A pseudo-class equivalent to the file class.

The only difference between file and POSIX file is that a POSIX file object interprets “name” as a POSIX, while a file object interprets “name” as a HFS path.

RGB color

A type definition for a three-item list of integer values, form 0 to 65535, that specify the red, green and blue components of a color.

1
2
set whiteColor to {65535, 65535, 65535} --white
set userColor to choose color default color whiteColor

Operators

Coercion Type Convert

The operator as can convert a object to another type.

1
2
3
4
5
6
7
8
9
set a to "100"
a as number --100

"1.99" as real --1.99
"1.99" as integer --2
"1" as real --1.0
"text" as list --{"text"}
1.99 as list --{1.99}
{a:1, b:2} as list --{1, 2}

Common Operators

operator explanation example
+ addition 1 + 1 = 2
- subtraction 1 - 1 = 0
* multiplication 2 * 3 = 6
÷ or / division 3 / 2 = 1.5
^ exponent 3^2 = 9
div aliquot 3 div 2 = 1
mod mod 5 mod 3 = 2
----
=
equals
is equal
[is] equal to
compares whether two objects are equal. 1 is equal to 2 = false
----
!=
is not
isn't
isn't equal [to]
is not equal [to]
doesn't equal
does not equal
compares whether two objects aren’t equal. 1 is not 2 = true
----
>
[is] greater than
comes after
is not less than or equal [to]
isn't less than or equal [to]
2 is greater than 2 = false
---- support types: integer, real, date, text
>=
[is] greater than or equal
is not less than
isn't lesson than
does not come before
doesn't come before
2 is greater than or equal to 2 == true
---- support types: integer, real, date, text
<
[is] less than
comes before
is not greater than or equal [to]
isn't greater than or equal [to]
2 is less than 2 = false
---- support types: integer, real, date, text
<=
[is] less than or equal
is not greater than
isn't greater than
does not come after
doesn't come after
2 is less than or equal to 2 == true
----
start[s] with
begin[s] with
supports text and list a stars with "abc" = true
----
end[s] with supports text and list a ends with "abc" = false
----
contain[s] supports text, record and list {10, 20} contains 20 = true
----
doesn't contain
does not contain
supports text, record and list {1, 2, 3} doesn't contain 4 = true
----
is in
is contained by
supports text, record and list 1 is in {1, 2, 3} = true
----
is not in
is not contained by
isn't contained by
supports text, record and list 1 is not in {1, 2, 3} = false

Logic Operators

and,or and not

Operator &

The operator & is used to combine two object to one.

The operator & has three combine rules.

  • The left operand is text, the result is text, maybe occur errors.
  • The left operand is record, the result is record, maybe occur errors.
  • The left operand is other type, the result is list, maybe occur errors.
1
2
3
4
5
6
7
"text" & 1 --"text1"
1 & "text" --{1, "text"}
{age: 100} & "weight" --{age:100, «class ktxt»:weight}
"weight" & {age: 100} --{"weight": 100}
{1, 2, 3} & {4, 5, 6} --{1, 2, 3, 4, 5, 6}
{1, 2, 3} & 4 & 5 & 6 --{1, 2, 3, 4, 5, 6}
{a: 10, b: 20} & {c: 30} --{a: 10, b: 20, c: 30}

Get Elements From an Object

Extracts words or characters from a text

  • every character of "abc" returns {a, b, c}
  • characters of "abc" returns {a, b, c}
  • words of "hello world" returns {hello, world}
  • eery word of "hello world" returns {hello, world}
  • character 1 of "abc" returns a
  • word 2 of "hello world" returns world
  • characters 3 through 5 of "American" returns eri
  • words 2 through 3 of "What's your name?" returns {your, name}

The first index is 1, not zero. You can abbreviate the keyword through to thru.

Get all files form a folder

1
2
3
4
5
6
7
8
9
tell application "Finder"
every file of desktop -- Gets all files on the desktop.
files of desktop

every folder of desktop -- Gets all folders on the desktop.
folders of desktop

name of every files of desktop --Lists all file names on the desktop.
end tell

Uses whose or where its to filter result.

1
2
3
4
tell application "Finder"
every file of desktop whose name ends with "png"
every file of desktop where its name ends with "png"
end tell

Variables and Properties

Variables

1
set myWeight to 80 as real

Uses as real to convert the value 80 from default integer type to real type, you can ignore it.

In AppleScript, all variables are local at default. The variables defined in script files that you can not access in in a handler(method) or script(object) internal. We will write more detail about handlers and scripts in next chapter. This time you can think of the handler is the method and the script is the object.

1
2
3
4
5
6
7
set message to "hello world"

on logMessage()
log message
end

logMessage()

The code above will throw an error when executing it. The error message is execution error: the variable message is not defined. If you want to access the variable message, you can add the code global message above the assignment code.

1
2
3
4
5
6
7
8
9
10
global message
set message to "hello world"

on logMessage()
log message
end

logMessage()

--hello world

In other word, if we want to define a local variable in a handler, but the variable has already been defined in outer, you can use local message to covert the global variable message to local variable.

1
2
3
4
5
6
7
8
9
10
11
global message
set message to "hello world"

on logMessage()
local message
set message to "good"
log message
end

logMessage() --good
log message --hello world

Properties

All variables we told above are saved in the memory, that means all values would be emptied once the script is done. If we want to keep some data we can access in the next running, we can declare a variable as a property.

1
2
3
property runTimes: 0

set runTimes to runTimes + 1

Executing the code above, you would find the runTimes value increases one every running. Do not rebuild the code, the property runTimes will be reset. Actually, the property’s value is saved to the script file.

Control

Switch

Simple format: if boolean then statement
Complex format:

1
2
3
4
5
6
7
8
if boolean1 then
else if boolean2 then
statement
else if boolean3 then
statement
else
statement
end if

Loop

AppleScript provides least six ways to loop values.

  1. Infinite loop
1
2
3
repeat
statement
end repeat

The loop will never stop, you must use exit or return to break it.

  1. Limited loop
1
2
3
repeat 10 times
statement
end repeat

The loop body will execute ten time.

  1. Until loop
1
2
3
repeat until boolean
statement
end repeat

The loop body would repeatedly execute until the boolean become true.

  1. While loop
1
2
3
repeat while boolean
statement
end repeat

Opposites to the until loop, the loop body would execute repeatedly until the boolean become false.

  1. Range loop
1
2
3
repeat with loopVariable from startValue to stopValue by stepValue
statement
end repeat

You can ignore the by stepValue, the default value is 1.

  1. List loop
    AppleScript provides a convenience approach to enumerate a list object quickly.
1
2
3
4
5
set people to {"a", "b", "c", "d"}

repeat with person in people
log person
end

Modifying the person’s value, the original people list will keep old value. If you want to modify the list, you need to use contents of person to get real item of the list and modify its value.

1
2
3
4
5
6
set people to {"a", "b", "c", "d"}

repeat with person in people
contents of person = "*"
end
--*, *, *, *

Considering/Ignoring Syntax

When we compare two text object, the AppleScript think of the text “abc” is equal to “ABC”, because the AppleScript is case-ignore. If you don’t want ignoring the case, you can use considering to add comparing rules.

1
2
3
considering attribute1 but ignoring attribute2
--compare texts
end considering

The AppleScript supports multiple comparing attributes:

  • case capital or small letters
  • diacriticals
  • hyphens: the hyphen -
  • numeric strings: used to compare two version string. "1.10.1" > "1.9.4"
  • punctuation
  • white space

Exception handling

Every programing languages provide the exception handling, the AppleScript is no exception.
All errors occurring in try scope will be caught.

Try

1
2
3
try
100 / 0 -- 100 cannot be divided by 0.
end try

Catches the specific error message and error code.

1
2
3
4
5
6
try
100 / 0
on error errText number errNum
log errText
log errNum
end try

You can ignore number errNum if you don’t want to get the error number.

Custom Errors

Throws a custom error represents that your code get an exception situation.

1
error "error message" number 404

Timeout

The AppleScript usually needs interact with users or other programs, if the script cannot receive a response after waiting a period of time, it will throw a timeout error.(The system default timeout duration is 120 seconds)

The AppleScript provides a way that we can customize the timeout duration for our specific situations.

1
2
3
with timeout of x seconds -- x must be integer
--do something
end timeout
1
2
3
with timeout of 5 seconds
display dialog "Click the button in 5 seconds"
end timeout

Executing this code will display a dialog, the script will throw an error if you don’t click the sure button in 5 seconds.

Handler

Handlers in AppleScript are same as methods or functions in other programing languages.

Simple handler

1
2
3
4
5
on sayHelloWorld()
display dialog "Hello, world"
end sayHelloWorld

sayHelloWorld()

Handler with positional parameters

We can pass parameters into a handler.

1
2
3
4
5
6
7
on sayMsg(msg, n)
repeat n times
display dialog msg
end repeat
end sayMsg

sayMsg("Hello, world")

Handler with labeled parameters

The labeled parameters can make the handler invoking like saying English sentences and it don’t have order so can be written at whatever position you want.

1
2
3
4
5
on warn to somebody about something
display dialog "Warning: " & somebody & "[" & something & "]"
end warn

warn to "csl" about "It's too late."

Return

Of course, a method could return a result. Like other languages, We can use return to return a value.

1
2
3
on createUser(userName)
return {name: userName}
end createUser

System Default Handlers

run

run is the default event handler in AppleScript, it is the entrance of a script, like the main method in C.

open

open is a powerful handler that you can use it to implement the Drag & Drop app. Write a script, save it as an application, select the keep open mark and then run the application, drag a file to the application’s icon. The open handler will be invoked with the dragged files as its parameters.

1
2
3
4
5
6
7
on open selectedFiles
set nameStr to ""
repeat with i in selectedFiles
set nameStr to nameStr & "/" & (i as text)
end repeat
display dialog nameStr
end open

idle

When the script keeps running and doesn’t perform any events, the idle handler will be invoked regularly, the default duration is 30 seconds but we can return an integer value to modify the duration.

1
2
3
4
on idle
display dialog "The program is running." giving up after 1
return 10
end idle

quit

If user want to exit applications manually, the quit handler will be invoked, then you can invoke continue quit to quit the application. Remember to invoke the continue quit, otherwise the application will not exit.

1
2
3
4
5
6
on quit
display dialog "Are you want to exit?" buttons {"sure", "cancel"}
if button returned of result = "sure" then
continue quit
end if
end quit

Script

The AppleScript is an OOP(Object-oriented programming) language. The script is the object, you can think of it as classes in other languages.

Keyword me

The keyword me in AppleScript is like the self in Ruby or the this in JavaScript.

path to me returns the script’s path.

Declares a Script

1
2
3
4
5
6
7
8
9
property description: "I'm a person"

script Person
display dialog description

on eat(food)
display dialog "I'm eating " & food giving up after 2
end eat
end script

run Person will execute the script’s body, displaying a dialog with content “I’m a person”, but the eat method won’t be invoked.

Executing eat("apple") of Person will invoke the eat handler, there have a more recommend approach to invoke handlers in scripts.

1
2
3
4
tell Person
run
eat("apple")
end Person

Invoke Outer Scripts

We might separate our script into several different files if its too complex. So the AppleScript provides a way to load outer file’s scripts.

Assuming that we save the Person script we written above to the person.scpt file at desktop.

1
2
3
4
5
6
set personPath to ((path to desktop) as text) & "person.scpt"
set personScript to load script file personPath

run Person of personScript

eat("apple") of Person of personScript

Modify Outer Scripts Properties in the Current Script

We can not only load outer script files but can also modify their properties.

1
2
3
4
5
6
7
set personPath to ((path to desktop) as text) & "person.scpt"
set personScript to load script file personPath

set message of personScript to "I'm a dog" --Modifies the property message.
run Person of personScript --The dialog's content will be replaced with "I'm a dog"

eat("apple") of Person of personScript

When loading outer scripts, the AppleScript just copy them into the current script file, so modifying the properties value just influences the memory data. If we execute the person.scpt file again, the property’s value is still old.

The AppleScript provides a command store script to save the changes really.

1
store script personScript in file personPath with replacing

If you ignore the with replacing, the AppleScript will ask you whether replacing the old script file. So the with replacing is actually a force and dangerous command, be careful when using it.

References

Dash for Mac
The Dash provides many detail documents about the AppleScript, it lists all of the classes and commands that you can read through the document to dive into more detail.