# AppleScript Programming/Printable version

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.

## Commands

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

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 (* *).

# 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

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

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:
This can be used to present information to a user or, as you will find out later, ask for it.

## Setting variables

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:
Now, if one wanted to show the user what the text stored in variable "theVariable" was, they could type:
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

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

## Exercises

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

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

Now let's use the three commands we know to write a simple number-based program. Try putting this into your Script Editor:
The result is a message box displaying the result (2).

## Strings

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:
The result is a message box displaying the result (Hello, User!).
Now put:
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

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.
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
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

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

## Basics of Records

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.
Which will return the string "jetson"
but not by index,
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".
For example, the following is an example an HFS path name
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.

## Converting between formats

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:
To convert a POSIX path to a standard Applescript alias (the inverse of the above command), use this command:

# 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:
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:
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.
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.
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

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.

# 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.
This will tell applescript to execute commands associated with the program System Events. For example, the command:
Will type the letter "e" into the current application.
Here's a simple program:
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.
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
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:
You can also use one line commands for keystrokes, such as:
Which will invoke Copy in most Mac applications.
It is possible to use combokeys in oneline like this:

# 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"

To run shell commands from Applescript:
The user would hear a sound.

## Shell command "osascript"

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:
The user would see:

# 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.
* Display Dialog
* Repeat
* Say
* tell
How To:
* Hide Application

# 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
# 3rd Party Codes

* Growl

# Sample Programs
## Sample Programs

* 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