Previous Page
Next Page

21.4. Standard Scripting Addition Commands

The scripting addition commands present in a standard installation of Tiger (Mac OS X 10.4) are all implemented by the StandardAdditions scripting addition. You can consult the StandardAdditions dictionary to learn what commands it contains and to get the full details on their syntax, and it would be a waste of trees for me to repeat the information you'll find there. However, I'll list all the commands and provide some basic explanations and comments (and examples) that go beyond what the dictionary tells you. For most of these commands, where I or the dictionary might say "string," you should understand "or Unicode text," since StandardAdditions has been generally revised to be Unicode-savvy.

(For load script, store script, and run script, see "Compiled Script Files as Script Objects" in Chapter 8. For the POSIX file class, see "File and Alias" in Chapter 13 and "File Coercions" in Chapter 14. For do shell script, see Chapter 25. For digital hub scripting, folder actions, and CGI events, see Chapter 27.)

21.4.1. Dialogs

These scripting addition commands put up dialogs, thus providing a modicum of user interaction. The dialog will appear in whatever application is being targeted at the moment, or in the host application if no application is being targeted. They should not be used in an environment where no user interaction is allowed (for example, in a Unix osascript command). Recall (from "Errors" in Chapter 19) that the -128 ("User canceled") error thrown when the user clicks the Cancel button in one of these dialogs, if it percolates all the way up to AppleScript, does not normally result in an error dialog (though it will cause the script to terminate prematurely).

display dialog

general informational, text entry, and button-choice dialog

general informational, text entry, and button-choice dialog

A remarkably flexible little command. You can put up an information dialog. It can have an icon and a title. It can include a user text entry field; optionally, the user's text can appear as bullets (for password entry and so forth). You can dictate the names of up to three buttons, specify which is the OK button (which responds to Return) and which is the Cancel button (which responds to Esc or Command-Period, generates error -128), and learn which one the user pressed. The dialog can be set to time out if the user does not respond, and you can learn that this is what happened. By default, the buttons are "Cancel" and "OK"; a button called "Cancel" is the Cancel button by default. Returns a record.

Examples

set r to display dialog "Quick! Pick a Pep Boy!" buttons {"Mannie", "Moe", "Jack"} ¬
    with icon caution giving up after 3
set favoritePepBoy to button returned of r
if favoritePepBoy is "" and gave up of r then set notFastEnough to true
set whoIsIt to text returned of (display dialog "What is your name?" ¬
    default answer "" buttons {"OK"} default button "OK")

display alert

informational dialog

informational dialog

Syntactically, a simpler version of display dialog; there is no user text entry. Has a more Cocoa-like appearance than display, dialog; there can be title text and smaller message text, and the icon has the proper look for the host application. The default is a single button ("OK"), and there is always a default button (the rightmost, by default). A button named "Cancel" is not automatically the Cancel button. The third (leftmost) button is gapped away from the others. Returns a record. (New in Tiger.)

Example

tell application "Finder"
    display alert "Pep Alert" message "Mannie, Moe, and Jack welcome you."
end tell

choose from list

listbox selection dialog

listbox selection dialog

Puts up a scrolling list of strings or numbers for the user to choose from. Returns a list of chosen strings or numbers, or false (not an error!) if the user cancels. There are two buttons, and you can set their titles; you can add a prompt and a window title. You can specify whether to permit multiple selections and/or an empty selection.

Example

set p to choose from list {"Mannie", "Moe", "Jack"} with prompt "Pick a Pep Boy:"

choose file

file selection dialog

file selection dialog

Puts up a standard Open File dialog, with title "Choose File" and default button "Choose." You can add a prompt; you can set the initial folder displayed. You can specify whether invisible files should be shown, whether packages should be treated as folders, and what types of file to display (can be a list of either four-letter file type codes or UTIssee http://developer.apple.com/macosx/uniformtypeidentifiers.htmlbut not both). Returns an alias.

Example

set f to choose file of type {"public.text"} without invisibles

choose folder

folder selection dialog

folder selection dialog

Puts up a standard Choose Folder dialog, with title "Choose a Folder." The user can also create a new folder. Your options are similar to choose file. Returns an alias.

Example

set f to choose folder with prompt "Pick a folder:"

choose file name

file save dialog

file save dialog

Puts up a standard Save File dialog (default button "Save"), with title "Choose File Name" and default prompt "Specify new file name and location." The user can also create a new folder. If the user specifies an existing file, goes through the usual "Replace?" rigmarole. You can set the initial folder, the initial filename, and the prompt. Returns a file URL (which appears as a file specifier). Does not actually save anything.

Example

set f to choose file name with prompt "Where shall I save this stuff?"

choose application

application selection dialog

application selection dialog

Puts up a standard Choose Application dialog, listing all applications, with title "Choose Application" and default prompt "Select an application." The user can switch to browsing in a standard Open File dialog. You can specify the window title and prompt. Returns an application specifier, or optionally an alias, or a list if multiple selections are allowed.

Example

set theApp to choose application as alias
tell application "Finder"
    set isScriptable to has scripting terminology of theApp
end tell
if isScriptable then display dialog "It's scriptable!"

choose URL

URL selection dialog

URL selection dialog

Puts up a standard Choose URL dialog (with a Connect button); this is rather like the Finder's Connect to Server dialog, useful for finding servers on the local network, with an option to let the user choose various categories of server. The user can also just type a URL unless you prevent it; this can be basically any string at all. Does not actually connect! Returns a string.

Example

choose URL showing File servers -- "afp://duck.local."

choose remote application

remote application selection dialog

remote application selection dialog

Puts up a dialog with title "Choose Remote Application" and two panes, one for selecting a local machine or entering an IP number, the other with default prompt "Select an application." The target machine must have Remote Apple Events turned on in the Sharing system preferences. I have not been able to get the local-machine choice to work (where the Bonjour names of local machines are listed automatically) but using the IP number works, and a Bonjour name can be entered manually. You can supply the title and prompt. Returns an eppc URL string suitable for targeting the application remotely; see Chapter 23. (New in Tiger.)

Examples

choose remote application
-- application "Finder" of machine "eppc://192.168.0.4/?uid=501&pid=178"
using terms from application "Finder"
    set ap to choose remote application -- I choose Finder on remote machine
    -- username/password dialog appears, I fill it out
    tell ap
        get name of window 1 -- Desktop
    end tell
end using terms from

choose color

color selection dialog

color selection dialog

Puts up a standard Color Picker dialog, where the user may choose a color. You can specify the initially selected color. Returns a color. A color is expressed as an rgb color, which is a list of three integers representing the red, green, and blue components.

Example

choose color default color {9000, 10000, 50000} -- {50000, 9000, 10000}

21.4.2. Noises

These commands produce sounds and modify sound settings.

beep

beep

beep

Plays the system beep sound. Optionally takes an integer saying how many times to beep.

Example

beep

get volume settings

sound loudness report

sound loudness report

Reports the loudness of sound output, input, and alert volume, as a record.

Example

alert volume of (get volume settings) -- 75

set volume

sound loudness setting

sound loudness setting

Sets the loudness of sound output, input, and alert volume.

Example

set volume output volume 100 alert volume 100
beep

say

text-to-speech

text-to-speech

Reads text aloud, either in real time or saving the synthesized speech as a sound file. Can also be used in conjunction with speech recognition to determine what text appears below the microphone window .

Example

tell application "SpeechRecognitionServer"
    set s to listen for {"yes", "no"} with prompt "Would you like me to beep?" ¬
        giving up after 10
end tell
if s is "yes" then
    say "Okay, I will beep now." displaying "Okay."
    beep
else
    say "Okay, then I won't." displaying "Okay."
end if

21.4.3. File and Machine Information

The following commands provide information about a file or the system.

system info

system information

system information

Returns a record of basic system information, such as the computer name , CPU speed and type, Ethernet address, and so forth (new in Tiger). If the desired information is not part of this record, use the more general (but harder to use) system attribute command.

Example

set v to system version of (system info)
display dialog "You are running system " & v & "!"

system attribute

gestalt and environment variables

gestalt and environment variables

Returns the value of gestalt selectors (see http://developer.apple.com/documentation/Carbon/Reference/Gestalt_Manager/index.html ).

Example

set n to system attribute "sysv"
set s to "print sprintf \"%lx\", " & n
set v to do shell script "perl -e " & quoted form of s
set L to characters of v
set v to "." & item -1 of L
set v to "." & item -2 of L & v
set v to ((items 1 thru -3 of L) as string) & v
display dialog "You are running system " & v & "!"

Also returns the value of user environment variables (see Chapter 25 for an example ). To find out what they are, issue the system attribute command with no parameters.

Example

system attribute "SHELL" -- "/bin/bash"

path to

standard folder location

standard folder location

Locates various standard folders, such as the system folder. If the designated folder is legal but doesn't exist, the path to command silently creates it unless you specify without folder creation, in which case an error is returned if the folder doesn't exist. If a standard folder isn't listed as an enumerator, you can use its four-letter code (see http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/index.html ). Returns an alias, or a string, if desired (or Unicode textthe dictionary fails to document this fact).

Example

path to desktop -- alias "feathers:Users:mattneub:Desktop:"
path to "cmnu" -- alias "feathers:Library:Contextual Menu Items:"

path to

application and script file location

application and script file location

Locates an application by name, including the current application (the host application). Launches the application if it uses Cocoa scripting (I regard this as a bug). The special phrase path to me is supposed to give the alias of the current compiled script file, but in the past this has been unreliable; it is somewhat better in Tiger, though it can still go wrong depending on the script runner environment and the script file format (script bundles are problematic), and it doesn't work in Script Editor (works fine in Script Debugger).

Example

path to application "Finder"
-- alias "feathers:System:Library:CoreServices:Finder.app:"

path to resource

bundle resource location

bundle resource location

Locates a file in the Resources folder of a bundle. Intended primarily for script bundles and applet bundles (and AppleScript Studio applications), so they can see inside themselves; doesn't work in Script Editor, but works fine in Script Debugger. You can optionally designate any bundle to look in (such as an application), and a subfolder within the bundle.

Examples

display dialog ((path to resource "description.rtfd") as string)
-- feathers:Users:mattneub:Library:Scripts:myScriptBundle.scptd:Contents:
    Resources:description.rtfd
set f to path to resource "app.icns" in bundle ¬
    alias "feathers:Applications:Mail.app:"
display dialog "Time to check your mail!" with icon f

list disks

volume names

volume names

Gets the names of all mounted volumes. Returns a list of strings (meaning Unicode text).

Example

list disks -- {"feathers", "gromit", "Network"}

list folder

folder contents

folder contents

Gets the names of all items within a folder. Includes invisible files and folders if you don't prevent it. Returns a list of strings (meaning Unicode text).

Example

list folder (path to home folder)
-- {".bash_history", ".CFUserTextEncoding", ".DS_Store", ".ssh", ...}

info for

file/folder information

file/folder information

Gets information about an item on disk. Returns a file information record packed with useful stuff. If you ask for the info for a folder, the script may take some time to run, in order to sum the sizes of all the files within it; you can prevent this by saying without size.

Example

set uf to (path to home folder as string)
set L to list folder uf
set s to {}
repeat with f in L -- collect sizes of all items
    set end of s to size of (info for file (uf & f))
end repeat
set maxItem to 0
set maxVal to 0
repeat with i from 1 to (count s) -- find biggest size
    if item i of s > maxVal then
        set maxItem to i
        set maxVal to item i of s
    end if
end repeat
display dialog "The biggest thing in your home folder is: " & item maxItem of L

21.4.4. File Data

These commands perform sequential read and write of file data. ("Sequential" means that each read or write will start, by default, just after the last character read or written in the same session.)

open for access

open file

open file

Opens a file for read accessoptionally, for write accesscreating the file as a text file if it doesn't exist (it does this even if you're opening for read access only; I regard this as a bug). Returns a file reference number that can be used with the other commands.

Example

set f to (path to desktop as string) & "newfile.txt"
set ff to open for access file f
close access ff

read

read data

read data

Reads data from a file, optionally treating it as a specified datatype (for an example, see "Forming Unicode Text" in Chapter 13); the default is string (not Unicode text). There are options for where to start (character position values start at 1), how many characters to read, and where to stop. The using delimiter parameter is poorly documented: this is a list of one-character strings, any of which will be used to break the data into a single-level list of strings (which will lack all the delimiter characters). The until and before parameters fail when reading as string if they are out of the basic ASCII range (over 128), but they work using Unicode text.

Example

set f to (path to desktop as string) & "someUTF16file.txt"
set ff to open for access file f
set d1 to read ff as Unicode text
d1 -- "Mannie¬Moe¬Jack"
-- testingdelimiter parameter
set notsign to "¬" as Unicode text
set L to read ff from 1 as Unicode text using delimiter notsign
L -- {"Mannie", "Moe", "Jack"}
-- testingbefore parameter
set d2 to read ff from 1 as Unicode text before notsign
close access ff
d2 -- "Mannie"

write

write data

write data

Writes data to a file, optionally treating it as a specified datatype; thus you can store any kind of data in a text file and retrieve it later (it will be read correctly if you specify the same class when writing and when reading). There are options for where to start and how much data to write; writing at the end of a file appends, but writing in the middle of the file overwrites existing data (it doesn't insert).

Example

set f to a reference to file ((path to desktop as string) & "justTesting")
open for access f with write permission
write {"Mannie", "Moe", "Jack"} as list to f
close access f
open for access f
set L to read f as list
close access f
L -- {"Mannie", "Moe", "Jack"}

get eof

get file end position

get file end position

Returns the index of the last character of a file (which is also the size of the file). Because character position values start at 1, and because the eof is the position of the last character, if you want to append to a file you must start writing at a position one greater than the eof (and that is the largest position at which you are permitted to start writing).

Example

write "Howdy" to f
set ourEof to get eof of f
write "Doody" to f starting at ourEof + 1

set eof

set file end position

set file end position

Sets a file's size, truncating its data or filling the new excess with zeros. To replace an existing file's data, set its eof to 0 before writing to it.

close access

close file

close file

Closes a file. Always close a file you have opened for access!

The file data commands let you describe the file you want to operate on as either a file reference number returned by open for access, or a file specifier or alias. In the read example earlier, I capture a file reference number and use it throughout; in the write example, I start with a file specifier and use that instead. The open for access command will also take a pathname string, but other commands will not. So, this works:

set f to open for access ((path to desktop as string) & "testing")
close access f

And so does this:

set f to ((path to desktop as string) & "testing")
open for access f
close access alias f

But this doesn't:

set f to ((path to desktop as string) & "testing")
open for access f
close access f
-- error: Can't make "feathers:Users:mattneub:Desktop:testing" into type file

You should ensure sufficient error handling so as not to leave a file open (unlike all the examples thus far!). If you do accidentally leave a file open, you might have to quit the current application, such as the Script Editor, in order to close it. Script Debugger helps you here; it notifies you if you've left a file open, and permits you to close it without quitting.

In this example, we use AppleScript to construct a miniature "database." We have some strings; taking advantage of the write command's starting at parameter, we write each string into a 32-character "field." Notice the cautious error handling:

set pep to {"Mannie", "Moe", "Jack"}
set f to (path to current user folder as string) & "testFile"
try
    set fNum to open for access file f with write permission
on error
    close access file f
    return
end try
try
    set eof fNum to 0 -- erase if exists
    set eof fNum to (count pep) * 32
    repeat with i from 1 to (count pep)
        write item i of pep to fNum starting at (i - 1) * 32
    end repeat
    close access fNum
on error
    close access fNum
end try

Now we'll fetch the data from the "database." We take advantage of the fact that all data that isn't part of a string is null.

set f to choose file of type "TEXT"
try
    set fNum to open for access f
on error
    close access f
    return
end try
set L to {}
try
    set ct to (get eof fNum) / 32
    repeat with i from 1 to ct
        set end of L to read fNum from (i - 1) * 32 ¬
            before ASCII character 0 --  read up to but not including null
    end repeat
    close access fNum
on error
    close access fNum
end try
L -- {"Mannie", "Moe", "Jack"} 

21.4.5. String and Clipboard

These commands give string-related information or work with the Clipboard.

ASCII character

number to character

number to character

Converts an ASCII numeric value to a one-character (MacRoman) string.

Example

ASCII character 82 -- "R"

ASCII number

character to number

character to number

Converts the first character of a (MacRoman) string to an ASCII numeric value.

Example

ASCII number "Ribbit" -- 82

offset

substring position

substring position

Reports the position of a substring within a target string. Character position values start at 1. Returns 0 if the substring isn't found. Formerly considered case and ignored diacriticals, which is backwards from AppleScript's own defaults; staring in Panther, this is fixed, and string considerations are obeyed (see "String Considerations" in Chapter 19).

Example

offset of "bb" in "Ribbit" -- 3

summarize

summary of content

summary of content

Summarizes the content of a string or textfile, like the Summarize Service.

set the clipboard to

set clipboard

set clipboard

Puts data onto the clipboard.

clipboard info

describe clipboard

describe clipboard

Describes the contents of the clipboard as a list of class-size pairs.

Example

-- user has copied a file's icon in the Finder
clipboard info
-- {{string, 20}, {«class ut16», 44}, {«class hfs », 80}, {«class
 utf8», 20}, {Unicode text, 42}, {picture, 2616}, {«class icns», 43336},
{«class furl», 62}}

the clipboard

get clipboard

get clipboard

Gets the clipboard text, or you can specify some other class. A common trick is to specify as record; in the resulting record, the names of the items are their classes, and the values are their values.

-- user has copied a file's icon in the Finder
set r to the clipboard as record
-- {string:"Hawaii Itinerary.pdf", «class ut16»:"Hawaii Itinerary.pdf",
«class hfs »:«data hfs 0000...0000», «class utf8»:"Hawaii
Itinerary.pdf", Unicode text:"Hawaii Itinerary.pdf", picture:«data PICT0A38...000FF»,
 «class icns»:«data icns6963...0000», «class furl»:file
"feathers:Users:mattneub:Desktop:Hawaii Itinerary.pdf"}
type identifier of (info for «class furl» of r) -- "com.adobe.pdf"
the clipboard as «class furl» -- works too

21.4.6. Numbers and Dates

These commands add some extra arithmetic and date-time powers to AppleScript.

round

round

round

Rounds a real to an integer, in various ways (one of which is called rounding as taught in school, showing that AppleScript has a sense of humor).

Example

round 1.3 -- 1

random number

generate random number

generate random number

Generates a random number. By default, this is a real between 0 and 1, but you can specify a different upper bound or both bounds. If every number you specify is an integer, the result is an integer, which could be either of the bounds; otherwise it is a real. You can seed the generator to get it started; this is useful for generating a fixed pseudo-random sequence.

Example

random number
set L to {}
repeat 10 times
    if (random number 1) as boolean then
        set end of L to "heads"
    else
        set end of L to "tails"
    end if
end repeat
L -- {"heads", "tails", "heads", "heads", "heads",
     "tails", "heads", "heads", "heads", "heads"}

current date

now

now

Generates a date object corresponding to the current date and time.

Example

time string of (current date) -- "10:41:13 AM"

time to GMT

time zone

time zone

Reports the time zone that has been set via the Date & Time preference pane, as an offset from Greenwich Mean Time, in seconds.

Example

(time to GMT) / hours -- -7.0

21.4.7. Miscellaneous

These are scripting addition commands I couldn't categorize.

delay

wait

wait

Pauses for a specified number of seconds. Starting with Panther, this number can be a real.

Example

delay 1
beep

mount volume

AppleShare

AppleShare

Mounts an AppleShare volume (a machine where Personal File Sharing is turned on). The machine is specified as an afp URL string, such as is returned from the choose URL command. To avoid the dialog for choosing a particular volume, add the volume name as a second path element. To avoid the dialog asking for username and password, supply them as parameters or as part of the URL. A Windows server can be mounted using an smb URL. Returns a file URL (but no result if the volume is already mounted). If the syntax of the mount volume command is insufficiently flexible, consider using do shell script to call mount_afp.

Examples

-- this first one lets user choose, presents the "Select volumes to mount" dialog
set s to choose URL showing File servers
mount volume s as user name "mattneub" with password "teehee"
-- these next ones present no dialogs
mount volume "afp://matt%20neuburg:teehee@duck.local/OmniumGatherum"
mount volume "afp://duck.local/OmniumGatherum" ¬
    as user name "matt neuburg" with password "teehee"
-- this one presents username/password dialog and volume dialog
mount volume "afp://duck.local"

scripting components

list OSA components

list OSA components

Returns a list of strings giving the names of the installed OSA scripting components. One of these will be "AppleScript".

open location

open a URL

open a URL

Given a URL string, opens the URL with the appropriate helper application. For an example, see "Reduction" in Chapter 1.


Previous Page
Next Page