AppleScript Handbook
Basic
Identifier
A normal identifier must begins with a underline _ or letter and then involves letters, numbers or underlines.
1 | set age to 100 |
Of course, Apple provides a special way that can declare any Unicode chars between two | as a identifier, expect the char | itself.
1 | set |名字| to "CSL" |
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 | -- Good |
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
Anintegernumber doesn’t have a fraction part.
1 | set age to 18 |
real
Arealnumber actually is a float number.
1 | set weight to 180.5 |
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 | set myName to "SSBun" |
| 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 | set now to current date |
| 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 | set my_file to choose file |
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 | set my_file to choose file name |
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 | set whiteColor to {65535, 65535, 65535} --white |
Operators
Coercion Type Convert
The operator as can convert a object to another type.
1 | set a to "100" |
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 |
| ---- | ||
=equalsis equal[is] equal to |
compares whether two objects are equal. | 1 is equal to 2 = false |
| ---- | ||
!=is notisn'tisn't equal [to]is not equal [to]doesn't equaldoes not equal |
compares whether two objects aren’t equal. | 1 is not 2 = true |
| ---- | ||
>[is] greater thancomes afteris 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 equalis not less thanisn't lesson thandoes not come beforedoesn't come before |
2 is greater than or equal to 2 == true |
|
| ---- | support types: integer, real, date, text | |
<[is] less thancomes beforeis 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 equalis not greater thanisn't greater thandoes not come afterdoesn't come after |
2 is less than or equal to 2 == true |
|
| ---- | ||
start[s] withbegin[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 containdoes not contain |
supports text, record and list | {1, 2, 3} doesn't contain 4 = true |
| ---- | ||
is inis contained by |
supports text, record and list | 1 is in {1, 2, 3} = true |
| ---- | ||
is not inis not contained byisn'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 istext, maybe occur errors. - The left operand is
record, the result isrecord, maybe occur errors. - The left operand is other type, the result is
list, maybe occur errors.
1 | "text" & 1 --"text1" |
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"returnsaword 2 of "hello world"returnsworldcharacters 3 through 5 of "American"returnseriwords 2 through 3 of "What's your name?"returns{your, name}
The first index is 1, not zero. You can abbreviate the keyword
throughtothru.
Get all files form a folder
1 | tell application "Finder" |
Uses whose or where its to filter result.
1 | tell application "Finder" |
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 | set message to "hello world" |
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 | global message |
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 | global message |
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 | property runTimes: 0 |
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 | if boolean1 then |
Loop
AppleScript provides least six ways to loop values.
- Infinite loop
1 | repeat |
The loop will never stop, you must use exit or return to break it.
- Limited loop
1 | repeat 10 times |
The loop body will execute ten time.
- Until loop
1 | repeat until boolean |
The loop body would repeatedly execute until the boolean become true.
- While loop
1 | repeat while boolean |
Opposites to the until loop, the loop body would execute repeatedly until the boolean become false.
- Range loop
1 | repeat with loopVariable from startValue to stopValue by stepValue |
You can ignore the by stepValue, the default value is 1.
- List loop
AppleScript provides a convenience approach to enumerate a list object quickly.
1 | set people to {"a", "b", "c", "d"} |
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 personto get real item of the list and modify its value.
1 | set people to {"a", "b", "c", "d"} |
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 | considering attribute1 but ignoring attribute2 |
The AppleScript supports multiple comparing attributes:
casecapital or small lettersdiacriticalshyphens: the hyphen-numeric strings: used to compare two version string."1.10.1" > "1.9.4"punctuationwhite 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 | try |
Catches the specific error message and error code.
1 | 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 | with timeout of x seconds -- x must be integer |
1 | with timeout of 5 seconds |
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 | on sayHelloWorld() |
Handler with positional parameters
We can pass parameters into a handler.
1 | on sayMsg(msg, n) |
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 | on warn to somebody about something |
Return
Of course, a method could return a result. Like other languages, We can use return to return a value.
1 | on createUser(userName) |
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 | on open selectedFiles |
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 | on 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 | on 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 | property description: "I'm a person" |
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 | tell 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 | set personPath to ((path to desktop) as text) & "person.scpt" |
Modify Outer Scripts Properties in the Current Script
We can not only load outer script files but can also modify their properties.
1 | set personPath to ((path to desktop) as text) & "person.scpt" |
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.scptfile 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.