Dictionary commands
- adding folder items to
alias
This is a Folder Action command covered in
Section of Chapter 26.
- ASCII character integer
This command returns the ASCII character associated with the number
provided as a parameter. For example, ASCII character 80 returns the
string "P."
- ASCII number integer
You can find the ASCII number of a character by using code, such as
ASCII number "P"
(this returns an integer of 80).
- beep integer
This makes the beep sound integer number of times,
or once if a parameter is not included.
- choose application
This command opens the choose application dialog box, which only
lists the programs running at the moment. Figure A-3 shows this dialog. Figure A-4 shows what this dialog looks like in the OS X
release. The following example lists the running applications, then
opens the user's choice. Note that choose
application also displays faceless background applications
that the user cannot interact with (they can quit some of these apps,
however).
try -- capture error if they choose a 'background only' app
tell (choose application application label "Choose one program"¬
with prompt "Here are the running applications") to activate
on error errmesg
display dialog errmesg
end try
- application label string
This string appears at the top of the application
list.
- with prompt string
This string appears at the top of the dialog box.
|
Mac OS 9.1 adds two parameters to the
choose application scripting addition:
multiple selections allowed and as class
type (these are described elsewhere in this note). The Mac
OS X Standard Additions dictionary alters the choose
application osax to remove the application
label parameter and add three new optional parameters:
with title, multiple selections
allowed, and as type.
with title lets you specify the title for the
dialog window, as in:
choose application with title "Choose your favorite Apps"
multiple selections allowed is a
boolean value that if true,
allows the user to choose more than one application. as
type is designed to let the scripter get the
choose application return values as application,
alias, or file types. However, in AppleScript 1.6, this return value
was only available as an application type.
|
|
- choose file
This
osax opens a dialog box, allowing the user to choose a file to open,
which can then be stored in an alias variable, as
in:
set f to (choose file with prompt "Choose a file on the local disk")
If the user presses the Cancel button on the choose
file dialog instead, then an error is raised, and the
script terminates. You can catch this error (error number -128) with
a try block and thus allow the script to resume,
as in the following example (Figure A-5 shows the
choose file window):
try
c_file( ) (* call the scripts c_file subroutine which uses the choose file
osax *)
on error number ern
if ern = -128 then (* the user clicked the cancel button on the dialog box *)
display dialog "User cancelled"
else
display dialog "An unknown error occurred with file choosing."
end if
end try
on c_file( ) -- define the subroutine
set f to choose file
display dialog (f as text) -- display the file path as text
end c_file
- with prompt string
This optional labeled parameter allows you to include a message or
prompt with the dialog box:
choose file with prompt "Choose a file on the local disk"
- of type list
You can restrict the file types listed in the choose
file dialog with this labeled parameter, as in:
choose file of type {"TEXT"}
- choose file name
This Mac OS X osax replaces the new file osax of
AppleScript in Mac OS 9.0.4. choose file name is
also available in Mac OS 9.1. This scripting addition displays a
dialog box to the user. The user can then create a filename and a
location for a file that does not yet exist (a file
specification object is created and returned from this
command). The return value in Mac OS X looks like:
file "Mac OS X:users:bruceper:library:desktop:mydbfile"
In effect, a file specification is like a template
for a file that you will create in the future. Figure A-6 shows what the choose file name
dialog box looks like.
- with prompt string
This prompt or message appears on the dialog box, as in
choose file name with prompt "Please
choose the location and name for a new file" default name
mydbfile.
- default name string
If you want the choose file name dialog box to
be displayed with a default file name already
entered in the "Save As:" text box,
use this parameter.
- choose folder
Use this command if you want to interact with the user and get them
to choose a directory or folder. For example:
choose folder with prompt "Choose a folder to save your files
in"
- with prompt string
This optional labeled parameter adds a message to your dialog box so
the user knows why your applet is producing the dialog box in the
first place. See the choose folder example.
- choose from list
list
Lots of AppleScript commands return lists as data types. This handy
scripting addition allows you to show the user a
list of items in the form of a dialog box. Figure A-7 shows this window. The user can then choose
one or more items from the list (depending on
whether multiple selections are allowed). When the
dialog box is dismissed, the script receives a
list of the selected items as a return value:
set fruitList to (choose from list allFruits)
- with prompt string
Use this optional labeled parameter to add a message to the top of
the dialog box.
- default items list
If you included this optional parameter, then the
list of strings will be initially selected in the
dialog box (if firstFruits was a variable that
contained a list of strings):
choose from list allFruits default items firstFruits
- OK button name string
You can give the OK button your own label, as in:
set fruitList to (choose from list allFruits OK button name "Submit fruits")
- cancel button name string
You can give the Cancel button on the dialog box your own label, as
in:
set fruitList to (choose from list allFruits cancel button name "Not now")
- multiple selections allowed boolean
If you want to give the user the option to make more than one choice
in the dialog box's list, then set this labeled
parameter to true.
- empty selection allowed boolean
If set to true, this labeled parameter allows the
user to click the OK button without any list items
selected and not raise an error.
- choose URL
This command opens up the Network Browser and allows the user to
choose a URL involving any of the network services (as constants)
identified in the first labeled parameter.
- showing list of constants
This parameter can be one or more of the following constants:
Directory services |
News servers |
File servers |
Remote applications |
FTP Servers |
Telnet hosts |
Media servers |
Web servers |
The return value is a string URL, as in
http://my.yahoo.com. For example:
choose URL showing {Web servers,File servers} editable URL false
- editable URL boolean
Set this parameter to true if you want to allow
the user to enter a URL.
- clipboard info
This command returns a list of lists. Each
list contains two values separated by a comma: the
data type and size of the item on the clipboard. For example, if you
select and copy an image to the clipboard, then clipboard
info would return a value such as {{picture, 14368}}. The
second number is the size of the picture in bytes. If you selected
and copied the word "HI", then this
command would return {{string, 2}}, which is a string two bytes long.
If you copied some styled text, for instance (i.e., text that has a
certain font), then the clipboard information return value would
involve more than one list inside the outer
list, such as {{string, 65}, {styled Clipboard
text, 42}.}
- for class
Use this optional labeled parameter if you only want to see clipboard
information of a certain data type:
clipboard info for string
Use the keyword for followed by the name of the
class.
- close access
(file reference number, alias, or file specification)
Use this command to close access to a file you are reading from and
writing to.
- closing folder window for
alias
This is a Folder Action command covered in Section of Chapter 26.
- current date
This command returns a date object of the form:
date "Wednesday, May 24, 2000 8:50:06 AM"
You will use this scripting addition all the time! Since the return
value is a date object, you can get the various
date-related properties from it, such as the time
string ("8:50:06 AM"),
day, month, and year. See Chapter 3,and the description of the date data
type. The following example shows how to display various attributes
of the current date:
set theDate to current date (* osax returns a date object and stores it in
theDate *)
(* get various date properties *)
set d to day of theDate
set m to month of theDate
set y to year of theDate
set ts to time string of theDate
set mesg to "Here's info about today:" & return &¬
"time: " & ts & return &¬
"day: " & d & return &¬
"month: " & m & return &¬
"year: " & y & return
display dialog mesg
- delay
integer
This useful osax delays the script processing for
integer number of seconds, as in delay
5. It is similar to the sleep function
in Perl. There are many reasons to delay a script for a few moments,
such as dealing with the unpredictable download time of web
documents. You might want to pause a script as a browser attempts to
download a page before the script reports an error in the download.
By the way, use the download scripting addition
to download web pages using AppleScript.
download is covered in Chapter 18.
- display dialog
This is one of the principal ways an applet can interact with the
user, either by displaying a message or any script-processing
results, or by requesting them to enter text in an edit field.
display dialog may end up at the very top of
your "indispensable scripting
addition" list. This command can optionally add an
edit field for receiving text entries from the user by including the
default answer "" parameter (passing an empty
string to this labeled parameter displays an edit field with no text
in it). display dialog has five optional
parameters. For example, you can automatically make the dialog go
away with code, such as:
display dialog "I disappear after five sec." giving up after 5
display dialog returns a dialog
reply object, which is just like a
record data type. Chapter 3
describes the record type. See the
dialog reply class description
in this chapter.
- default answer string
Include an empty string (as in default answer
"") to display an empty edit field
to the user, or include a non-empty string as a
default value for the edit field. The string can
be up to 255 characters long. If you do not include this parameter,
then the dialog box does not have an edit field.
- buttons list
You can add up to three of your own button labels to the dialog:
display dialog "Enter one of your names" buttons¬
{"first","last","middle"} default answer ""
The first button in the list is the dialog button on the left, and
the next listed buttons are displayed left to right. If you do not
include this parameter, then the dialog box has two buttons: Cancel
and OK. You can detect which button dismissed the dialog by testing
the button returned property of
the reply, which looks like:
{text returned:"bruce", button returned:"first"}
In other words, the return value of display
dialog is like a record data type,
which gives you access to the returned text and button.
- default button number or string
You can specify a default button that will have a dark border around
it signifying it can also be activated by pressing the return key. If
you do not include this parameter, then the dialog box has two
buttons: Cancel and OK. Identify the default button by its
string or order in the buttons list. In the
following example, Keep It is the default button:
display dialog "how much of a reimbursement do you want?"¬ buttons
{"Send It","Keep It"} default button 2
- with icon number, string, or the constants stop, note, or caution
You can display one of the standard Apple dialog icons with this
parameter. The dialogs are Stop (number 0), Note (1), and Caution
(2). (See Figure A-8.) As an alternative, if you
specify the name or number of an icon (as in with icon
9) stored as a resource in the script file or current
application, then AppleScript displays that icon in the dialog box.
AppleScript searches the script file, the current application (i.e.,
the one identified in a tell statement), and the
System file, in that order, for the icon resource.
- giving up after
integer
This command usually displays a modal dialog, meaning that it is the
frontmost window, and the user has to dismiss it to access any other
windows. Since the scripter is never sure about the context of script
execution (what if the applet is executed over a network and the
machine happens to be unused at the moment?), it is often a good idea
to make the dialog box disappear automatically after a reasonable
period, such as several seconds. For example:
display dialog "Are you there?" default answer "Yes" giving up¬ after 10.
- get eof
This command returns the length in bytes of a file's
contents, as in:
get eof (alias "macintosh hd:desktop folder:myfile.txt")
The return value is an integer. get
eof does not return the size of the file on disk, just the
number of bytes of data that can be read from the file using the
read osax. See the info for
scripting addition for getting the actual disk size of the file, as
in:
(size of (info for theFile))
See the open for access command for a
description of reading and writing to files with AppleScript.
Due to Mac OS
X's Unix origins, only the applications that can
execute AppleScripts, such as Script Editor, Script Runner, and the
applications that have a built-in Scripts menu, will load and
recognize the commands and properties of scripting additions that
require user interaction. This means that, according to Apple
Computer, an application such as TextEdit will not display a dialog
if you use a display dialog command inside a
TextEdit tell block:
tell app "TextEdit"
activate
display dialog "Hi" -- this code will fail to display a dialog
end tell
Apple Computer suggests two strategies to deal with this Mac OS X
issue:
Execute scripts with Script Runner. Chapter 1,
describes the Script Runner. Script Runner is designed to execute the
scripts saved as compiled script files (as opposed to Mac OS X
applets). To work around this user-interaction problem with Mac OS X,
you do not need to change a script that already runs under Mac OS 9.1
as long as it is saved as a compiled script and is executed by Script
Runner.
Alter scripts to bring the script applet to the foreground when using
display dialog. The script applet will display
the dialog, then the script can return any other applications, such
as TextEdit, to the foreground. Here is a simple example that does
not do anything special with TextEdit but offers a solution to the
user-interaction problem described by this sidebar:
tell app "TextEdit"
activate
set userName to my showDialog( ) (* call the script's showDialog handler *)
end tell
on showDialog( )
tell me to activate (* bring the applet itself to the foreground *)
set theResult to (the text returned of (display dialog¬
"Enter your name please" default answer ""))
tell app "TextEdit" to activate
return theResult
end showDialog
This applet temporarily leaves the TextEdit application context to
call a user-defined handler, which displays a dialog and gets some
user input. Then the applet activates TextEdit again.
|
- handle CGI request
string
If you are using the Mac as a web server, you can use AppleScript and
the handle CGI request scripting addition to
process Common Gateway Interface (CGI) scripts. In older
implementations of Mac Web CGI programs, you had to define a handler
using raw syntax such as <<on event
WWW?sdoc>>... but this has changed with the new
Standard Additions. CGI scripts are used in web applications that
process HTML form data, among other web-related tasks. When the web
user submits the form to the web server, the CGI script intercepts
the form and processes its data. The string
parameter contains the path of the CGI program on the server, which
might look something like /cgi-bin/myCGI.acgi.
The following example shows what the structure of a handle
CGI request CGI looks like. The web server generates most
of these parameter values, and you will not have to look at them in
your CGI program. They are the equivalent of what Unix CGI
programmers call environment variables, which are data the web server
generates reflecting information about the web page request.
on handle CGI request the_path¬
searching for query_string¬
with posted data post_string¬
of content type mime_string¬
using access method acc_string¬
from address ip_string¬
from user user_string¬
using password passw_string¬
with user info info_string¬
from server serv_string¬
via port port_string¬
executing by path_string¬
referred by ref_string¬
from browser agent_string¬
using action cgi_string¬
of action type typ_string¬
from client IP address ipc_address¬
with full request req_string¬
with connection ID id_integer
end handle CGI request
searching for string
This is the data that follows the
"?" character in the URL when the
HTTP GET method is used. For example, the entire URL for sending form
data might look like:
http://www.formcorp.com/cgi-bin/myCGI?first=Bruce&last=Perry.
searching for would contain the string
"first=Bruce&last=Perry."
- with posted data string
This contains the data sent with the POST HTTP method. This string
could look like
"first=Bruce&last=Perry."
- of content type string
This is the Multipurpose Internet Mail Extensions (MIME) type for the
data sent to the CGI program. For example, the MIME type for a web
page is "text/html." The MIME type
for form data sent with an POST HTTP method is
"application/x-www-form-urlencoded."
- using access method string
This string is either
"GET" or
"POST."
- from address string
This labeled parameter contains the IP address of the entity making
an HTTP request to the web server. For example, if the person sending
the form data to the CGI program has an IP address of
"24.169.24.11," then the
from address string contains
this value.
- from user string
If the user is being authenticated on the web server for security
reasons, then this string contains the username.
- using password string
If the user is being authenticated on the web server for security
reasons, then this string contains the password of
the user.
- with user info string
This string may contain additional user
information such as an email address.
- from server string
This is the name of the server application sending the request.
- via port string
This string is the TCP/IP port number of the
server, such as "80."
- executing by string
This string is the path to the CGI script, as in
/cgi-bin/mycgi.acgi.
- referred by string
This is the URL from which the user linked to the CGI program. For
example, this could be the web form the user filled out before they
submitted the form to the CGI program, as in
http://www.formcorp.com/form.html.
- from browser string
This string contains the name of the user agent or
browser the web user is using.
- using action string
This string also contains the path to the CGI
program, as in
"/cgi-bin/mycgi.acgi."
- of action type string
This string returns one of these values:
PREPROCESSOR, POSTPROCESSOR, CGI, or ACGI.
- from client IP address string
If the client has his own IP address (for instance, if he is a client
on a Local Area Network), then this string
contains that address. An example is 192.168.0.5.
- with full request string
This is the full request sent to the server. It might look like
http://www.formcorp.com/cgi-bin/mycgi.acgi?first=Bruce&last=Perry.
- with connection ID integer
This integer parameter represents the
server-to-client connection.
- info for
alias, file specification , or string path to the file or folder
You can grab a bunch of information on a file or folder, as long as
you know its directory path, which you can pass to this osax as a
string. For example:
info for "macintosh hd:desktop folder:"
The return value is a record that looks like this:
{name:"Desktop Folder", creation date:date "Thursday, December 07,
1995 10:48:10 AM", modification date:date "Thursday, May 25, 2000 9:36:22 AM",
icon position:{-1, -1}, visible:true, size:311307, folder:true, alias:false,
folder window:{0, 20, 1024, 768}}.
You can use the path to scripting addition to
fill out the details of an unknown file path.
|
In AppleScript 1.5 and later,
info for now returns the size of a file or
folder as a real data type (e.g., even
"0.0" is given as the size of an
empty folder using info for), rather than an
integer, in order to accommodate the files or
folders that are greater than two gigabytes in size.
|
|
For instance, if you know a file called cgi.txt
is on your desktop, then the following code returns information about
that file, such as its creation date and size:
info for ((path to desktop as text) &
"cgi.txt")
The full pathname of this file might be macintosh
hd:desktop folder:cgi.txt, but the path to osax saved you
some writing. The info for scripting addition
returns the following type of record value:
{name:"cgi.txt", creation date:date "Thursday, May 25, 2000
9:36:22 AM", modification date:date "Thursday, May 25, 2000 10:03:19 AM", icon
position:{832, 92}, visible:true, size:2807, folder:false, alias:false,
locked:false, busy status:false, file creator:"R*ch", file type:"TEXT", short
version:"", long version:"", default application:alias "Macintosh HD:BBEdit
5.0:BBEdit 5.0:BBEdit 5.1"}.
- list disks
This scripting addition returns a list of disk
names mounted on your desktop. An example return value is:
{"Macintosh HD1", "H2gig", "HF2gig", "scratch"}.
- list folder
alias, file specification, or string path
This command lists the items in a folder, as in:
list folder "macintosh hd:myfolder"
The return value is a list of strings. The
following example lists the contents of the desktop folder (it also
uses the path to osax):
list folder (path to desktop) (* returns folders and files as a list of string
names *)
- load script
alias
This command loads a script object into the script that contains the
load script statement. The loading script can
then use that script object's properties and methods
as though the loaded script was a locally defined script. Chapter 9 describes script objects.
The following example loads a script object called
DateLib and stores the object in a variable,
dlib. It then calls that script
object's parseDate method by
using the statement dlib's parseDate (i.e., the
parseDate method of the DateLib
object, a reference to which is stored in the dlib
variable). This method takes a date object and
boolean variable as parameters and returns a
reformatted date string that looks like
"05/25/2000." If the
boolean parameter is false,
then the date string does not include leading
zeros (the latter string would be
"5/25/2000"). The following example
includes the definition of parseDate so readers
can examine the parseDate definition, but this
method is already available from DateLib via the
dlib variable:
(* use the path to osax to get a reference to a file on the desktop *)
set dlib to load script (path to desktop as text) & "DateLib"
dlib's parseDate(current date, true) (* returns a date string such as
"05/25/2000" *)
(* parseDate definition *)
on parseDate(theDate, leadingZeros)
local mydate
local new_date_str
try -- return "0" if the theDate or boolean parameter is invalid
set mydate to theDate
set month_part to my getMonthInt((month of mydate),¬
leadingZeros) as string
-- getMonthInt method is defined in the DateLib script
set day_part to (day of mydate) as string
set year_part to (year of mydate) as string
if leadingZeros then
if (day_part as integer) < 10 then
set new_date_str to (month_part & "/0" & day_part & "/"¬
& year_part) as string
else
set new_date_str to (month_part & "/" & day_part & "/" ¬
& year_part) as string
end if
else
set new_date_str to (month_part & "/" & day_part & "/" &¬
year_part) as string
end if
return new_date_str
on error
return "0"
end try
end parseDate
- mount volume
string
Use this osax to mount a volume on your desktop from a remote
computer.The on server labeled parameter is the
only required parameter when using the AppleTalk form of mount volume
(see the upcoming note on the TCP/IP form of mount volume). You have
to add the Apple Filing Protocol (AFP) prefix
("afp://") if you are connecting
with the volume via TCP/IP.
- on server string
Specify the file server name with a string, as in
on server
"StacyMac". This parameter is required.
- in AppleTalk zone string
Specify an AppleTalk zone with a string:
mount volume "macintosh hd" on server "StacyMac" in AppleTalk¬ Zone
"graphics_dep" as user name "powerpc1" with password¬ "#go9$4r"
- as user name string
If the user has to be authenticated with a username and password
before mounting a remote volume, these parameters can be included
with the mount volume osax. Pass the username as
a string:
as user name "powerpc1"
- with password string
Include a password as a string for the user
identified in the as user name parameter, or omit
this parameter for guest access.
|
The mount volume
command takes the following form when mounting a volume over a TCP/IP
network:
mount volume "afp://user:password@192.168.0.2/MacHD"
The command uses the Apple Filing Protocol
("afp://"), followed by the user name and password
separated by a colon, the @ sign, the IP address of the server, and
the name of the volume you want to mount. In Mac OS 9.1, mount volume
will look in the Keychain for the user name and password information
if you have left this information out of the mount volume URL, as in
mount volume "afp://192.168.0.3/Mac HD".
|
|
- moving folder window for
alias
This is a Folder Action command covered in Section of Chapter 26.
- new file
new file allows you to request a file
specification from the user and then use that file spec to
save a web page downloaded with the download
osax (see Chapter 18). This osax displays a common
Save As dialog box that allows the user to navigate to a directory
and save a file. A file specification reserves a
path and name for a file, even though the file does not yet exist.
The following example gets a file spec from a user then downloads a
web page to it:
|
AppleScript 1.5.5 on Mac OS 9 altered
this osax and changed the name to choose file
name. See the choose file name
description.
|
|
set fspec to (new file default name "home_URL.html")
tell application "URL Access Scripting" to¬
download "http://www.parkerriver.com" to fspec with progress
- with prompt string
You can add a message to the dialog box with this command.
- default name string
Give the file specification a default name (the
user can change this):
set fileSpec to (new file default name "myfile").
- offset
This handy string-manipulation command finds the first occurrence of
one string inside of another and returns the
1-based position of the interior string as an
integer. It returns
if the string is not located inside the outer
string. For example, offset of "a" in
"and" returns 1, because the
"a" inhabits position 1 in the word
"and." The following example shows
how to use the offset osax in a function that
checks to see if a string begins with
"<," ends with
">," and has at least one
character that is not a space character inside these tags (An actual
HTML or XML tag-validation function would have to do much more than
this demo subroutine!):
checkTag("<html>") -- call the function with a string parameter
(* function definition *)
on checkTag(str)
(* initialize booleans and string length variable *)
set openTag to false
set closeTag to false
set notEmpty to false
set len to length of str
if (character 1 of str) = "<" then set openTag to true
repeat with c in (characters of str) (* examines each character in the
string *)
set offs to (offset of c in str) (* what position does the char have in
the string ? *)
if offs = len then exit repeat (* we check the last string char after the
repeat loop, so exit here *)
(* if the character is not the first or last character and not a space
then the tags do not just surround a space character *)
if (offs > 1 and offs < len) and (ASCII number c) 32 then
set notEmpty to true
end repeat
if character len of str = ">" then set closeTag to true (* check last
string character *)
if openTag and closeTag and notEmpty then¬
display dialog "It's not empty and has opening and closing tags."
end checkTag
- of string
Specify the string you are looking for with the
of keyword, as in:
offset of "a" in
"animal"
- in string
Use the in keyword to identify the outer
string you are searching for the inner
string with, as in:
offset of "a" in "animal"
- opening folder
alias
This is a Folder Action command covered in Section of Chapter 26.
- open for access
alias
Use this osax to open a file and read and/or write to it. If the
open for access parameter is a file
specification for a file that does not yet exist, then a
new file is created. This is a primary scripting addition for file
input and output so you are likely to use it often. This scripting
addition is closely related to the read,
write, and close access
scripting additions. You should close access to a file when you
finish with it so you do not block any other operations that need
access to that file. The following example reads a chunk of text from
a file, then closes access to the file. open for
access returns a file-reference number, which can be used
with close access and other commands:
(* this script uses the path to, open for access, get eof, read, and close
access scripting additions *)
set theFile to alias ((path to desktop as string) & "write.txt")
set fref to (open for access theFile)
set tsize to (get eof theFile)
read fref as string from 1 to tsize
close access fref
- write permission boolean
If you want to write to the file, use the write permission
true parameter. Otherwise, you get an error that write
permission is not allowed. In other words, write
permission is false by default.
- open location
string
This osax opens the URL, such as a web page
(http://my.yahoo.com) or FTP site
(ftp://park:.......@12.16.160.221/ ) in the
application you have selected in the Internet control panel or in the
Internet Config application. For example, if Netscape 6 is your
default browser then open location
"http://my.yahoo.com" opens that page in the
Netscape browser.
- error reporting boolean
If you include the error reporting true parameter,
a dialog box reporting errors is displayed.
- path to
constant or application
path to returns the path to folders or
applications, depending on the parameter you use. You can use one of
the following constants to get the path as either an
alias or string to a common
location such as the desktop folder:
At Ease applications |
At Ease documents |
apple menu |
application support |
control panels |
control strip modules |
desktop Preferences |
modem scripts |
editors |
desktop pictures folder |
Folder Action scripts |
extensions |
fonts |
frontmost application |
internet plugins |
Help |
launcher items folder |
keychain folder |
plugins |
modem scripts |
printer drivers |
printer descriptions |
scripts |
printmonitor |
shared libraries folder |
scripting additions folder |
stationery folder |
speakable items |
trash folder |
shutdown items |
temporary items folder |
startup items |
voices folder |
users folder |
Or, you can get the path to a running program by specifying the
application, as in:
path to application "BBEdit 5.1" as string
You can get the path as an alias (which is the
default—you do not have to specify as alias)
or a string.
- as alias or as string
Since an alias return value is the default,
path to desktop returns an
alias path, as in:
alias "macintosh hd:desktop folder:"
and:
path to desktop as string
returns a string type, as in:
"macintosh hd:desktop folder:"
|
The OS
X Standard Additions file added a from...domain
optional parameter to the path to scripting
addition. For instance, using this parameter, path to
provides the location to the desktop folder based on the
domain you specify. The from parameter can take
any one of the four constants: System
domain, local domain, network
domain,or user
domain. For example:
set dpath to (path to desktop from user domain)
The latter code phrase returns a value that looks like:
alias "Mac OS X:Users:bruceper:Library:Desktop:"
Whereas if you used the local domain parameter,
the return value might be:
alias "Mac OS X:Library:Desktop:"
|
|
- random number
number
You can generate a random number with this osax, optionally including
an upper-limit number, as in:
set num to (random number 100)
If the upper-limit value is a real number, as in
random number 100.0, then the random result will
be a real type. A real number
type has a fractional part or decimal point, whereas an
integer type does not. (see the description of the
real data type in Chapter 3).
If the upper-limit number is an integer or whole
number, then the result will be an integer.
Finally, if the upper-limit number is omitted, as in:
set num to random number
then you will get a real number between
and 1 that looks like 0.408063409023. The result will have a scale of
12, meaning that there will be 12 digits on the right side of the
decimal point. The following example chooses a random number that
could help pick a card in a playing-card game by generating a random
number between 1 and 52:
cardNumber( ) -- call the method defined below
on cardNumber( )
set cd to (random number 100000) mod 52 + 1
return cd
end cardNumber
- from number integer or real
You can produce a random integer or
real within a range of numbers, such as:
random number from 100.1 to 500.3
If you include this from number parameter, you
have to use the to number
parameter as well. The latter code returns a number such as
319.675894353425. If you included two integers, then the return value
will also be an integer. If either one of these
numbers is a real, the result will be a
real. For example:
random number from 100 to 200.5
returns a number with a decimal point and
fractional part (i.e., a real number).
- to integer or real
Specify the upper level of a range with the to
keyword followed by an integer or
real. If you use the from
parameter with random number then you have to use
this to parameter. If the number used with this
parameter is a real then the random result will be
a real data type.
- with seed number
Use this parameter if you want to produce a random number that
steadily increases in value. The following example shows the random
numbers generated by using a seed that increases by one each time the
random number statement is executed:
on ranNumber( )
set counter to 0
repeat 5 times
set counter to counter + 1
set num to random number with seed counter
log num
end repeat
end ranNumber
(* results from Script Editor's event log *)
random number with seed 1
--> 0.293460940421
random number with seed 2
--> 0.500003913185
random number with seed 3
--> 0.603275399567
random number with seed 4
--> 0.706546885948
random number with seed 5
--> 0.758182629139
- read
reference number, alias, or file specification for a disk file
Use this command to read bytes from a file. Use the keyword
read followed by the file reference, such as an
alias or the number returned by the open
for access command. Generally, you get the amount of
readable data from the file first with the get
eof command, as in:
set theSize to (get eof theFile)
This command returns an integer number of bytes.
Then you can read the first half of a file, say, with the code:
read theFile from 1 to (theSize div 2)
Close the file after you have finished reading it with:
close access theFile
- using delimiter anything
This optional labeled parameter specifies the value you can use to
separate the chunks of read bytes or text. For instance:
read theFile using delimiter return as text
uses a return character as the delimiter. This
code returns a list in which each line of the text
file is a list member, as in:
{"Hi readers this is a short bit of text.", "Separated by a line."}
You could use this parameter to read from a tab- or comma-delimited
file, for instance, and then transfer the values into a
database-management system. The as class (e.g.,
as text) parameter is required if you use
using delimiter.
- using delimiters list
You can use more than one delimiter to generate a list of read-in
values, as in:
read theFile using delimiters {",",";"} as text
This reads in values separated by either a comma or a semi-colon and
returns these values as the members of a list. The
list does not contain the delimiters; they are
just used to separate or delimit each value. The as
class (e.g., as text) parameter is
required if you use using delimiters. This
parameter is optional.
- as class
Use this optional parameter to specify the data type of the return
value. Use as text or as string
unless you are reading in a series of numbers, dates, or other valid
alternative data types. The following example reads three lines of
numbers separated by tabs and stores them as integers in a
list. You could take those numbers and use
AppleScript to put them in a database. The code uses the
before return labeled parameter to prevent
AppleScript from reading in a return character and
trying to convert it to an integer, which would
raise an error:
set theFile to (open for access (path to desktop as text) &¬ "write.txt")
(* we know there are three lines in the data file; you could find out how many
lines there are first by reading in the text and counting the return
characters *)
repeat 3 times
read theFile using delimiter tab before return as integer
end repeat
close access theFile
(* return values look like:
{233,244}
{265,234}
{10,9}
*)
- for integer
Use this to specify the number of bytes to read from the disk
(for 20, for instance). This
code reads 20 bytes from the file. If you omit this labeled
parameter, then read reads to the end of the
file. You get an error of type "End of file
error" if the integer parameter
exceeds the number of bytes in the file. For example, read
theFile for 50 would return an error if the file has only
40 bytes of data. If you use read in a
repeat statement, then the read
statement sequentially reads through the file and does not just read
the same line over and again.
- before string
If you want to read up to but not including a character (such as a
period "." or
return character), use code, such as:
read theFile before return or read theFile before "."
If you know how many lines are in a file (pretty easy to find out in
a programmer's editor such as BBEdit or HomeSite),
you can use code, such as the read theFile before
return in a repeat number_of_file_lines
times statement, and AppleScript will neatly read the file
line by line. This parameter is optional.
- until string
Unlike before string, until
string reads up to and includes the
string character, as in:
read theFile until string "."
This code returns the "." with the
other file values.
- from integer
You can specify the number of bytes the read should start from, as in:
read theFile from 20
(which starts reading from and including the 20th byte). If you omit
this labeled parameter, AppleScript starts reading from the beginning
of the file or from the byte after the last-read byte. Use the
from integer parameter with the to
integer parameter to read a range of bytes from the disk
file. This parameter is optional.
- to integer
Stop the read at this byte position, as in:
read thefile to 100
This code reads the first 100 bytes of the disk file. Use this
parameter with the from integer
parameter to read a range of bytes, as in:
read theFile from 50 to 100
- removing folder items from
alias
This is a Folder Action command covered in Section of Chapter 26.
- round real
This osax rounds a
real number (such as 45.65) to an
integer and, of course, returns the
integer. For example, round
45.65 returns 46, because by default
round rounds to the nearest
integer (i.e., round 45.45
returns 45).
- rounding up/down/toward zero/to nearest
You might want to specify rounding up,
down, or toward zero instead of
accepting the default of rounding to nearest. For
example:
round 45.65 rounding down
returns 45 rather than the default of 46. rounding
down and rounding toward zero are
different for negative numbers. For example:
round -0.1 rounding toward zero
returns 0, but:
round -0.1 rounding down
returns -1. In other words, for positive numbers, rounding
down is the same as rounding toward
zero. For negative numbers, rounding up
is the same as rounding toward
zero.
|
The Mac
OS 9.1 and OS X version of round adds the
as taught in school
parameter to the other four parameters. as taught
in school always rounds 0.5 away from 0.
For example:
round 2.5 rounding as taught in school
returns 3. But:
round 2.5
(using the default parameter of rounding to
nearest) returns 2, because rounding to
nearest rounds .5 numbers to the nearest even number.
However:
round -46.5 rounding as taught in school
will return -47, rounding the real number argument 0.5 away from 0.
|
|
- run
script alias
You can call a script outside of the running script (i.e., the script
that uses the run script command) by passing
run script an alias to the
external script file. For example:
- run script (alias ((path to desktop as text) & "scr_2914"))
This code runs a script named
"scr_2914" on the desktop. For the
run script parameter, you can also use a string
file path, in other words, without the alias reserved word. Actually
run script calls the implicit or explicit
run handler of the script file (see the
"Run handler" section of Chapter 8). All scripts have an implicit
run handler (on run...end
run) that encompasses all statements except for property
definitions, function definitions, and script objects. run
script returns the result (if any) of calling the
script's run handler. The
following example defines a run handler that
takes two numerical arguments. The first parameter is rounded then a
dialog displays whether the result is even or odd; the second
parameter is simply returned to the calling script. The code used to
call this script is identified in comment characters at the top of
this example:
(*
run script (alias ((path to desktop as text) & "scr_2914"))
with parameters {345.45, 45.6}
*)
on run {num, num2}
if (class of num is real) then
if ((round num) mod 2) = 0 then
display dialog "A real number rounded to even integer."
else
display dialog "A real number rounded to odd integer."
end if
end if
return num2
end run
- with parameters list
You can optionally pass parameters to the script you want to call. If
the run handler takes two or more parameters,
you can specify them in the form of:
run script scriptAlias with parameters {345.5,233.4}
But if the run handler only takes one argument,
a line such as:
run script scriptAlias with parameters {345.5}
will pass the list type as a parameter as opposed
to the single numerical argument (at least under AppleScript 1.4).
You can work around this condition by making sure the
run handler takes its single argument and
handles it as a list.
- in string
You can specify the scripting component to use, such as in
"JavaScript" (if you have installed
the JavaScript OSA component from Late Night Software) if you want to
use a component other than the default component. The default
component I use in Script Editor is none other than AppleScript.
- say
anything
This command says the text parameter to the say
osax in the voice that is configured in the Speech control panel. You
have to install the Speech Manager extension in the startup
disk:System Folder:Extensions folder for this osax to
work. Once it is working, you can even use it for debugging by saying
the value of certain variables. The following example uses this osax
to say the value of a variable each time it completes an iteration in
a repeat loop:
checkVars( ) -- call the method defined below
on checkVars( )
set v1 to 1234567
repeat with n from 1 to 5
(* This will say something like "5 times around the value is 3" *)
say (n & " times around the value is " & (v1 mod n) as text)
end repeat
end checkVars
- displaying string
This parameter displays text in the SpeakableItems feedback window if
you have the SpeakableItems extension installed.
- using string
You can specify the voice you want to use, such as
"Deranged" or
"Hysterical," as in:
say "This project is disintegrating!" using "Hysterical"
- waiting until completion boolean
The default is waiting until completion true,
which does not return from the call to say until
the speech has been uttered. This is important when you are using
say in a repeat loop, since
you do not want to move on to the next loop of
repeat until the speaking voice has finished its
speech. Chapter 7, describes the
repeat loop.
- scripting components
This command returns the scripting components installed on your
machine as a list of strings.
An example return value is
{"JavaScript","AppleScript
"}.
- set eof
file reference number
You can add or truncate the bytes in a file opened with the
open for access osax (see open for
access). The following example reduces a file to only its
first 15 bytes. A file has to be open with write permission or this
osax returns an error.
set theFile to (open for access (path to desktop as text) & "write.¬ txt"
with write permission)
set eof theFile to 15
read theFile
close access theFile
- to anything
This required parameter sets the new length of the file, as in:
set eof theFile to 10000
This file's length is set to 10000 bytes. You can
enlarge or shrink a file with this command.
- set the clipboard to
anything
Use this osax inside of a tell statement to paste
a program's data onto the clipboard. You have to
activate the program before you use set the clipboard
to. For example, you could activate BBEdit 5.1 then use
the code:
set the clipboard to (contents of document 1)
- set volume
number
Use this osax to set the sound output volume to a number between
(silent) and 7 (full volume).
- store script
This osax stores a script object in a file, so you can then run that
script using the run script osax (Chapter 9 explains script objects). They are essentially
AppleScript statements such as property definitions and subroutines
enclosed in a script script_name...end script
block with similar behavior to object-oriented classes the programmer
creates. The following example defines a script that resets the
computer's volume. The example asks the user where
to save the file, using the store script osax:
store script volume_setter in (new file with prompt¬
"Pick a new file for the volume script.")
script volume_setter
set vol to (the text returned of (display dialog¬
"enter a volume number from 0 to 7" default answer ""))
if vol > 0 and vol < 8 then
set volume vol -- set the new volume
beep 2 -- test the sound output
end if
end script
- in file specification
You can have the user create a file specification
object (a space that the operating system reserves for the new file)
by using the new file scripting addition. This
is a required parameter.
- replacing ask/yes/no
If there is a chance that the store script
scripting addition will replace another script, specify the saving
behavior with this labeled parameter. ask displays
a dialog asking the user whether to overwrite the existing script
file, yes saves the script file (over the original
if there is one), and no does not replace an
existing file.
- summarize
text or an alias or file specification of a text file
This scripting addition attempts to summarize in an optionally
specified number of sentences the text or text file you feed it. For
example:
summarize alias ((path to desktop as text) & "thyroid1.txt") in 10
Summarize returns a string summary.
- in integer
Specify a pithy summary, as in:
summarize alias ((path to desktop as text) & "thyroid1.txt")¬
in 1
This code attempts a one-sentence summary.
- the clipboard
This command returns the contents of a program's
clipboard, but you have to couch the osax in a
tell block targeting the application. After
activating the app with the activate command,
you can use code such as:
return the Clipboard
This scripting addition returns a list type.
- as class
You can optionally specify the return value of this command to a
certain data type, as in:
the clipboard as text
- time to GMT
This command returns the difference in seconds between local time and
Greenwich Mean Time. You can convert this to minutes using:
time to GMT / 60
A negative number means that your local time is earlier than GMT
(e.g.,-14400 is four hours earlier than GMT).
- write
anything
Use this scripting addition to write data to a file opened with the
open for access command.
- for integer
You can restrict the write to a certain number of bytes (for
instance, if the script was reading from one file and writing to
another, and you were not sure of the number of bytes that were
read). For example
write theText to theFile for 100 -- write a 100-byte chunk
If you do not use this parameter, then all the data in
theText will be written to the file.
- starting at integer
Use this labeled parameter to specify a position in the file to do
the write, as in:
write "More text" to theFile starting at 100 (* start writing at the 100-byte
point in the file *)
This parameter is optional.
- to anything
This required parameter specifies the reference number
(open for access returns a file reference
number), alias, or file
specification of the file to write to. The following
example uses the new file osax to let the user
choose the file for writing with the write
scripting addition:
set filespec to (new file with prompt "Pick the new file to¬ write to")
(* use "choose file name" osax with OS X and OS 9.1 *)
set theFile to (open for access filespec with write permission)
write "Welcome to the beginning of this file." to theFile
close access theFile
- as class
You can optionally specify the writing of the data as
text, a list, a
real number, or some other data type. For example:
write 292.345 as real to filespec.
|