kids encyclopedia robot

AppleScript facts for kids

Kids Encyclopedia Facts
Quick facts for kids
AppleScript
Paradigm Natural language programming, Scripting
Developer Apple Inc.
First appeared 1993; 32 years ago (1993)
Stable release
2.8 / October 16, 2014; 10 years ago (2014-10-16)
Typing discipline Weak, dynamic
OS System 7, Mac OS 8, Mac OS 9, macOS
License Proprietary (parts available under APSL)
Filename extensions .scpt, .scptd, .applescript
Influenced by
Natural language, HyperTalk

AppleScript is a special scripting language made by Apple Inc.. It helps you control Mac apps automatically. Imagine telling your computer to do a series of tasks all by itself! AppleScript first appeared in System 7 and is now part of every macOS computer. It's one of the tools that helps your Mac do things on its own. The name "AppleScript" can mean the language itself, a script you write, or the system that makes it all work.

What is AppleScript?

AppleScript is mainly a language that lets different apps on your Mac "talk" to each other. This is called inter-application communication (IAC). It uses something called Apple events, which are like special messages apps send to each other. These messages help apps work together to do tasks automatically, especially repetitive ones.

AppleScript can also do some simple calculations and text changes on its own. You can even add new features to it using "scripting additions." But mostly, AppleScript relies on other apps to do the heavy lifting for complex jobs. It's a bit like a conductor telling an orchestra what to play. It tells different apps what to do, making them work together.

AppleScript uses a mix of different programming styles. It has parts that are like step-by-step instructions, parts that deal with "objects" (like files or windows), and parts that sound a lot like natural English. This mix makes it unique!

How AppleScript Started

In the late 1980s, Apple thought about using a language called HyperTalk (from a program called HyperCard) as a standard way for people to create their own programs. But engineers at Apple realized they could make a similar, but even better, language that would work with *any* app. That's how the AppleScript project began. It became a part of System 7.

AppleScript was officially released in October 1993. One of the first big programs to use it was QuarkXPress, which is used for publishing. This made AppleScript very popular in the publishing world, helping people automate complex tasks. This was a big reason why Macs stayed popular for publishing, even when other programs moved to Microsoft Windows.

Later, when Macs switched to Mac OS X (around 2002), AppleScript became even more useful. New tools made it easier for app developers to add AppleScript support to their apps. Also, because Mac OS X was built on a Unix system, AppleScript could now run Unix commands directly. This gave AppleScript much more control over the computer itself. Tools like AppleScript Studio and AppleScriptObjC even let people build full Mac apps using AppleScript!

In 2006, Macworld magazine listed AppleScript as one of Apple's 30 most important products, placing it at number 17. Even in 2013, experts said AppleScript was still the best tool for advanced Mac users who like to customize their computers.

In 2016, the person in charge of AppleScript at Apple left, which worried some people. But Apple said they would continue to support automation tools in macOS. Today, AppleScript is still an important part of macOS automation, working alongside tools like Automator and Shortcuts.

Basic Ideas

AppleScript was made so that regular users could easily control apps and change files. It uses Apple events, which are standard ways for the Mac operating system to send info to apps. Think of it like sending specific instructions to a program. Apple events let a script work with many apps at once, passing information between them. This means complex tasks can be done without you having to click anything!

For example, imagine you want to make a simple photo gallery for a website:

  • First, AppleScript could open a photo in a photo-editing app.
  • Then, it could tell the app to change the picture (like making it smaller or adding a border).
  • Next, it could tell the app to save the new picture in a different folder.
  • After that, it could send the new picture's location to a text editor.
  • It could then tell the text editor to write a link for the photo into an HTML file.
  • AppleScript could repeat all these steps for hundreds or thousands of photos!
  • Finally, it could upload the HTML file and all the new photos to a website.

Instead of you doing hundreds of steps, the script does it all. This saves a lot of time and prevents mistakes. You can use a script once for a big job or use it again and again for daily tasks.

Every app that works with AppleScript has a "Scripting Dictionary." You can look at this dictionary in a script editor to see what the app can do. Things in the dictionary are usually grouped into "suites." There are two main types of things in any suite: "classes" and "commands."

  • Classes are like the objects in an app. For example, a text editor might have classes for windows, documents, and text. These classes have "properties" (like window size or text font size) that you can change. They can also contain other classes (a window has documents, a document has text).
  • Commands are instructions you can give to these objects. The basic way to tell an app what to do in AppleScript is to use the "tell" command.

All scriptable apps share some basic commands and objects, like opening, closing, or saving files. Many apps have lots of suites that can do almost anything the app itself can do.

AppleScript was also designed so you could record your actions. If an app supports recording, you can click a "Record" button in the Script Editor. Then, as you use the app, AppleScript will write down the commands for what you're doing. You can save this script and run it again to repeat your actions, or change it to make it more useful.

How to Add Notes (Comments)

You can add notes in your AppleScript code to explain what it does. These notes are called comments, and the computer ignores them when it runs the script.

To add a one-line comment, start it with two hyphens (`--`). In newer versions of AppleScript, you can also use a number sign (`#`).

-- This is a one line comment
# So is this! (in Mac OS X Leopard or later)

For comments that take up many lines, use parentheses with asterisks inside:

(* This is a
multiple
line
comment *)

"Hello, World!" Example

In programming, it's common to show a simple "Hello, World!" program. In AppleScript, you can do this in a few ways:

display dialog "Hello, world!" -- shows a pop-up window with "OK" and "Cancel" buttons
-- or
display alert "Hello, world!" -- shows a pop-up window with just an "OK" button and an icon
-- or
say "Hello, world!" -- makes your computer speak the message out loud

AppleScript has different ways to show messages or ask for input. The character `¬` (made by typing `option` + `return` in Script Editor) means a single command continues on the next line.

Here are examples of different pop-up windows:

-- Dialog box
set dialogReply to display dialog "Dialog Text" ¬
        default answer "Text Answer" ¬
        hidden answer false ¬
        buttons {"Skip", "Okay", "Cancel"} ¬
        default button "Okay" ¬
        cancel button "Skip" ¬
        with title "Dialog Window Title" ¬
        with icon note ¬
        giving up after 15
-- List of choices
set chosenListItem to choose from list {"A", "B", "3"} ¬
        with title "List Title" ¬
        with prompt "Prompt Text" ¬
        default items "B" ¬
        OK button name "Looks Good!" ¬
        cancel button name "Nope, try again" ¬
        multiple selections allowed false ¬
        with empty selection allowed
 
-- Alert message
set resultAlertReply to display alert "Alert Text" ¬
        as warning ¬
        buttons {"Skip", "Okay", "Cancel"} ¬
        default button 2 ¬
        cancel button 1 ¬
        giving up after 2

You can get information back from these interactions. For example, which button was clicked:

display alert "Hello, world!" buttons {"Rudely decline", "Happily accept"}
set theAnswer to button returned of the result
if theAnswer is "Happily accept" then
        beep 5 -- makes a sound 5 times
else
        say "Piffle!" -- makes the computer say "Piffle!"
end if

Like Natural Language

AppleScript was designed to be easy for beginners to use. It tries to sound like natural English, just like how your computer's screen uses icons to look like a real desktop. A good AppleScript should be easy for anyone to read and understand. It's based on the HyperTalk language, but it can work with any document or app.

The main idea of AppleScript is to use words that act like nouns and verbs. For example, instead of different commands to print a page, a document, or a range of pages, AppleScript uses one "print" command. You just combine it with what you want to print:

print page 1

print document 2

print pages 1 thru 5 of document 2

AppleScript uses an app's "dictionary" to connect its special messages (Apple events) with words that humans can understand. This lets it translate between readable AppleScript and the computer's code. You can see these dictionaries in a script editor (usually under File → Open Dictionary).

To tell a specific app what to do, AppleScript uses a "tell" command:

tell application "Microsoft Word"
  quit
end tell

You can also write it on one line:

tell application "Microsoft Word" to quit

For common actions like "activate," "open," "close," "print," and "quit," you can sometimes just say:

quit application "Microsoft Word"

You can also tell apps to do things in a step-by-step way, like this:

tell application "QuarkXPress"
  tell document 1
    tell page 2
      tell text box 1
        set word 5 to "Apple"
      end tell
    end tell
  end tell
end tell

Or you can describe things using "of" or apostrophe 's':

pixel 7 of row 3 of TIFF image "my bitmap"
TIFF image "my bitmap"'s 3rd row's 7th pixel

AppleScript understands numbers written as words ("one," "first") or as digits ("1"). The word "the" can also be used anywhere to make the script easier to read, but it doesn't change how the script works.

Script Examples

Here's a calculator script that checks if you enter numbers:

tell application "Finder"
        -- Set variables (placeholders for information)
        set the1 to text returned of (display dialog "Enter the 1st number:" default answer "Number here" buttons {"Continue"} default button 1)
        set the2 to text returned of (display dialog "Enter the 2nd number:" default answer "Number here" buttons {"Continue"} default button 1)
        try
                set the1 to the1 as integer -- try to turn text into a whole number
                set the2 to the2 as integer
        on error -- if there's a mistake (like not entering a number)
                display dialog "You may only input numbers into a calculator." with title "ERROR" buttons {"OK"} default button 1
                return -- stop the script
        end try
        
        -- Ask to Add?
        if the button returned of (display dialog "Add?" buttons {"No", "Yes"} default button 2) is "Yes" then
                set ans to (the1 + the2)
                display dialog ans with title "Answer" buttons {"OK"} default button 1
                say ans -- speak the answer
        -- Ask to Subtract?     
        else if the button returned of (display dialog "Subtract?" buttons {"No", "Yes"} default button 2) is "Yes" then
                set ans to (the1 - the2)
                display dialog ans with title "Answer" buttons {"OK"} default button 1
                say ans
        -- Ask to Multiply?     
        else if the button returned of (display dialog "Multiply?" buttons {"No", "Yes"} default button 2) is "Yes" then
                set ans to (the1 * the2)
                display dialog ans with title "Answer" buttons {"OK"} default button 1
                say ans
        -- Ask to Divide?       
        else if the button returned of (display dialog "Divide?" buttons {"No", "Yes"} default button 2) is "Yes" then
                set ans to (the1 / the2)
                display dialog ans with title "Answer" buttons {"OK"} default button 1
                say ans
        else
                delay 1 -- wait 1 second
                say "You haven't selected a function. The operation has cancelled."
        end if
        
end tell

Here's a simple username and password check. The username is "John" and the password is "app123":

tell application "Finder"
        set passAns to "app123"
        set userAns to "John"
        if the text returned of (display dialog "Username" default answer "") is userAns then
                display dialog "Correct" buttons {"Continue"} default button 1
                if the text returned of (display dialog "Username : John" & return & "Password" default answer "" buttons {"Continue"} default button 1 with hidden answer) is passAns then
                        display dialog "Access granted" buttons {"OK"} default button 1
                else
                        display dialog "Incorrect password" buttons {"OK"} default button 1
                end if
        else
                display dialog "Incorrect username" buttons {"OK"} default button 1
        end if
end tell

Tools for Making Scripts

Script Editors

Script editors are programs where you write, check, run, and fix your AppleScripts. They also let you see the "dictionaries" of apps that can be scripted. You can save your scripts in different ways, and they often help you by highlighting code and providing ready-made code snippets.

From Apple

AppleScript Editor (Script Editor)
This is the main editor for AppleScript that comes with macOS. You write scripts in special windows, then you can run and test them. It also shows you info for fixing mistakes. You can find scripting dictionaries and code snippets in its menus. Since OS X Yosemite, you can also write JavaScript in it.
Xcode
This is a bigger set of tools for making apps. You can use it to edit AppleScripts or even build full apps using AppleScript.

From Other Companies

Script Debugger
This is a powerful, paid editor for AppleScript. It lets you "debug" scripts, meaning you can go through your code step-by-step, set stopping points, and watch what happens to your variables. It also has a great dictionary viewer that shows you how dictionary terms apply to real documents.
Smile and SmileLab
Smile is a free editor for AppleScript. SmileLab is a paid version with extra features for math, charts, and web work. These tools let you create complex user interfaces for your scripts.
ASObjC Explorer 4
This was a paid editor for AppleScript, especially for AppleScriptObjC. It helped with debugging and completing code. It's no longer updated.
FaceSpan
This was a paid editor for making AppleScript apps with graphical user interfaces, but it's no longer available.

Script Launchers

While you can run AppleScripts from an editor, it's often easier to run them directly. Here are some ways:

Applets
You can save your AppleScript as a small application called an "applet." If it can accept files by dragging and dropping, it's called a "droplet." You can run applets from your Dock, Finder windows, Spotlight, or other app launchers.
Folder actions
You can set up AppleScripts to run automatically when something changes in a folder (like adding or removing files). You can set this up by right-clicking a folder and choosing Folder Actions Setup....
Hotkey launchers
You can assign keyboard shortcuts to your AppleScripts. This lets you run a script just by pressing a key combination. Many third-party apps like Alfred or Keyboard Maestro can do this.
Script menu
This is a menu that appears in your macOS menu bar, no matter what app you're using. You can put your AppleScripts here for quick access. When you select a script, it runs. This menu can be turned on in the Script Editor's preferences. It often comes with example scripts that can help you learn.
Unix command line
You can run AppleScripts from the Unix command line (a text-based way to control your computer) using the `osascript` command. This is useful for scheduled tasks.

AppleScript Resources

AppleScript Libraries

These are reusable pieces of AppleScript code (like building blocks) that you can use in different scripts. They became available in OS X Mavericks. When saved in a special way, they can even have their own dictionaries, just like scripting additions.

AppleScript Studio

This was a tool that let you add graphical interfaces (like buttons and windows) to your AppleScript apps. It was part of Xcode but has been replaced by AppleScriptObjC.

AppleScriptObjC

This is a tool that lets AppleScripts use parts of Apple's Cocoa system directly. It's been part of Xcode since Mac OS X Snow Leopard. The table below shows when and where you can use AppleScriptObjC in different macOS versions:

Where AppleScriptObjC can be used in each macOS version
In Xcode In applets In AppleScript
Libraries
In Script Editor
10.6 Yes
10.7 Yes Yes
10.8 Yes Yes
10.9 Yes Yes Yes
10.10 Yes Yes Yes Yes

You can use AppleScriptObjC in all macOS versions after 10.10.

Automator

Automator is a visual tool where you build "workflows" by dragging and dropping "actions." It's designed to do many of the same things as AppleScript without needing to write code. Automator even has a special action that lets you run AppleScripts for tasks that are too complex for Automator's simpler system.

Scriptable Core System Applications

These are special background apps that come with macOS. They let AppleScript control features that wouldn't normally be scriptable. Some examples include:

  • VoiceOver: For controlling the screen reader.
  • System Events: For controlling apps that aren't usually scriptable and for basic system tasks.
  • Image Events: For basic image changes.

Scripting Additions (OSAX)

These are like plug-ins for AppleScript, made by Apple or other companies. They add new commands to AppleScript, making it more powerful and less dependent on other apps. macOS includes a set called "Standard Additions" that adds common features like showing pop-up windows, reading/writing files, and doing math. Without these, AppleScript couldn't do many basic things on its own.

Language Basics

Classes (Data Types)

Apps can define their own special types of data, but AppleScript also has many built-in data types. These are usually understood by all scriptable apps. Here are some common ones:

  • application: Represents an app, often used with the `tell` command (e.g., `tell application "Finder" …`).
  • script: Represents a script itself.
  • boolean: A true or false value.
  • integer: A whole number (like 1, 5, -10). You can do math with these.
  • real: A number with a decimal point (like 3.14, 0.5). You can do math with these.
  • date: A date and time.
  • text: A string of characters (like "Hello World").
  • list: An ordered collection of items. It can hold any type of data, even other lists.
  • record: A list of items that are paired with names (like `Template:Name:"John", age:15`).
  • alias: A link to a file or folder that still works even if the file is moved or renamed.
  • file: A direct reference to a file or folder.
  • POSIX file: A reference to a file or folder using Unix-style paths (like `/Users/YourName/Documents`).
  • RGB color: Specifies a color using red, green, and blue values.
  • unit types: Helps convert between different units (like converting square yards to square feet).

Language Structures

Many AppleScript tasks are handled by blocks of code. A block usually starts with a command and ends with an "end command" statement.

If-Then Statements (Conditionals)

AppleScript has two ways to make decisions:

-- Simple decision
if x < 1000 then set x to x + 1

-- More complex decision
if x is greater than 3 then
     -- commands to run if true
else
     -- commands to run if false
end if

Loops (Repeating Actions)

AppleScript's "repeat" loops let you do a set of commands many times. You can stop a loop early with `exit repeat`.

Repeat forever:

repeat
     -- commands to be repeated
end repeat

Repeat a certain number of times:

repeat 10 times
     -- commands to be repeated
end repeat

Repeat while a condition is true (or until it's false):

set x to 5
repeat while x > 0 -- keep repeating as long as x is greater than 0
     set x to x - 1
end repeat

set x to 5
repeat until x ≤ 0 -- keep repeating until x is less than or equal to 0
     set x to x - 1
end repeat

Loop with a changing number:

-- repeat 2000 times, 'i' goes from 1 to 2000
repeat with i from 1 to 2000
     -- commands to be repeated
end repeat

-- repeat 4 times, 'i' goes 100, then 75, then 50, then 25
repeat with i from 100 to 25 by -25
    -- commands to be repeated 
end repeat

Loop through a list of items:

set total to 0
repeat with loopVariable in {1, 2, 3, 4, 5}
        set total to total + loopVariable
end repeat
Telling an Application What to Do Handling Mistakes (Errors)
-- Simple way
tell application "Safari" to activate

-- More detailed way
tell application "MyApp"
     -- commands for this app
end tell
try
     -- commands to try running
on error
     -- commands to run if there's a mistake
end try

AppleScript also has "handlers," which are like mini-programs or functions inside your script. They start with `on functionName()` and end with `end functionName`. They only run when you "call" them from somewhere else in your script.

Function Handler Folder Actions Block Run Handler
on myFunction(parameters...)
     -- commands for this mini-program
end myFunction
on adding folder items to thisFolder after receiving theseItems
     -- commands to apply to the folder or items        
end adding folder items to
on run
     -- commands that run when the script starts
end run

There are four main types of handlers: `run`, `open`, `idle`, and `quit`.

Run handler
This is the main part of your script that runs when you start it. If you don't write an explicit `run` handler, all your code that's not in other handlers will run as if it were in one.
Open handler
This runs when you drag files or folders onto a script saved as an "applet" (which then becomes a "droplet").
on open theItems
     repeat with thisItem in theItems
         tell application "Finder" to update thisItem
     end repeat 
end open
Idle handler
This runs regularly when your script is not busy. It's useful for scripts that need to keep checking for something.
on idle
     -- code to run when the script is waiting
  return 60 -- wait 60 seconds before running again
end idle
Quit handler
This runs when your script is told to quit. You can use it to save data or do other cleanup tasks.
on quit
     -- commands to run before the script quits
  continue quit -- this is needed for the script to actually quit
end quit
Script objects
You can define special "script objects" within your script. They can contain their own commands and data.
script scriptName
     -- commands and handlers specific to this script
end script

Other Important Information

  • Variables (placeholders for data) in AppleScript don't need to be declared first. They can hold any type of data.
set variable1 to 1 -- creates a number variable
set variable2 to "Hello" -- creates a text variable
copy {17, "doubleday"} to variable3 -- creates a list variable
set {variable4, variable5} to variable3 -- copies items from variable3 into separate variables
set variable6 to script myScript -- sets a variable to a script object
  • Script objects are powerful; they can have their own functions and inherit from other scripts.
  • You can't call your own mini-programs (subroutines) directly from inside an `application tell` block. You need to use `my` or `of me`.
tell application "Finder"
    set x to my myHandler()
    -- or
    set x to myHandler() of me
end tell

on myHandler()
    --commands
end myHandler

Open Scripting Architecture

A key part of AppleScript is the Open Scripting Architecture (OSA). Apple made OSA so that other scripting languages and automation tools could work just as well as AppleScript. This means that different scripting tools can all use the same basic ways to load, save, and run scripts.

One cool feature of OSA is scripting additions, also called OSAX. These are like plug-ins that let programmers add new features to AppleScript. Commands from scripting additions work everywhere on your system and don't depend on a specific app.

JavaScript for Automation

In OS X Yosemite and later, JavaScript for Automation (JXA) is another important language that uses OSA, similar to AppleScript. While other languages like Perl and Python can also work with Apple events, JXA is a direct alternative within the OSA system.

JXA also lets you use Objective-C (a programming language) directly. Since JXA is based on WebKit's JavaScriptCore engine, its JavaScript features are similar to what you find in Safari.

See Also

Kids robot.svg In Spanish: AppleScript para niños

  • ARexx – a similar technology from 1987
kids search engine
AppleScript Facts for Kids. Kiddle Encyclopedia.