Cover | Table of Contents | Colophon
1.4 in Mac OS 9
or 1.3.4 in Mac OS 8.5. If you do not understand
certain aspects of this script, Part II of the
book is a detailed AppleScript language reference.set ASversion to version as string -- initialize ASversion to a string set ASversion to (characters 1 thru 3 of ASversion as string) as real (* coerce ASversion to a real number like 1.4 *) if ASversion is greater than or equal to 1.4 then (* test whether the version value is ≥ 1.4 *) display dialog "Good, you're running at least AppleScript 1.4" (* give the user some feedback with a dialog box *) else display dialog "You're running AppleScript " & ASversion end if
string value (e.g.,
"1.4") and stores it in an
ASversion variable. The first three characters of
this variable (such as 1.3 if the version was
1.3.4) are then coerced to a
real type, as in 1.3. We had to
take just the first three characters of the string
because a string with two decimal points in it, as
in 1.3.7, cannot be coerced to a
MYVAR is the
same as myvar, or myfunc is
the same as MyFunc in terms of function
definitions. Script Editor will not let you define two functions with
the same name, even if their letters are different combinations of
upper- and lowercase characters. The numerous AppleScript constants
and reserved words (case, current
application, and other constants are covered in Chapter 6) cannot be reused as your own variable or
method names. A script can change the values of
predefined variables such as pi or
space; however, scripters are better off using
these predefined variables for the variables'
intended purpose and creating their own variable names. Script Editor
sees "pi" and
"PI" as the same thing
("PI" would be corrected to
"pi" when you compile the script).
Class and command names within applications, while mostly lowercase,
are corrected when you compile the script to the spelling that is
specified in the app's dictionary. (Chapter 2 explains an application's
dictionary.) For instance, if you typed the class name tcpip
v4
configuration into Script Editor,
inside of a tell app "Network Setup
Scripting" block, it would be corrected
to "TCPIP v4 configuration" when
the statement was compiled.
(* this variable will store the BBEdit text and is initialized to a string *)
set allCode to ""
(* this variable will store the path to the Desktop folder and is initialized
to a string *)
set deskPath to ""
tell application "BBEdit 5.0"
try
activate
set allCode to (window text of document 1)
on error errMessage
display dialog "Looks like BBEdit does not have any open windows" &¬
return & return & "Error: " & errMessage & return & return &¬
"Exiting applet"
return -- this return statement exits the applet's run handler
end try
end tell
(* ask the user for a new filename then create a Script Editor file on the
desktop *)
tell application "Finder"
set frontmost to true
display dialog¬
set newScript to (the text returned in the result) as string
make file at desktop with properties¬
{name:newScript, file type:"TEXT", creator type:"ToyS"}
set deskPath to (desktop as string)
end tell
(* Use the 'write' scripting addition to write the code to the Script Editor file *)
tell application "Script Editor"
activate
set script_file to (deskPath & newScript) as alias
open for access script_file with write permission
write allCode to script_file
close access script_file
open script_file
end telldate, integer,
string, real) or that an
AppleScript command or scripting addition returns (see Appendix A). The data type that a variable stores
determines what the script can do with it afterward, such as perform
a math operation on an integer type or find out
the length property (the number of characters) of
a string
type.
alias |
real |
boolean |
record |
class |
reference |
constant |
RGB color |
data |
string |
date |
styled Clipboard Text |
file specification |
styled Text |
integer |
text |
=, +,
-, *) are familiar to
programmers in other languages (such as Java and Perl), as well as
young math students. In the following AppleScript code fragment, the
* and the = characters are the
operators:2 * 10 = 20
* operator. Operators can also be
used to test two expressions for equality or to combine two strings
into one string, as in these two code fragments:Set eq to (56.5 >= 56) (* the eq variable is set to true; the >=
("greater than or equal to") operator is used to test two values for
equivalence *)
Set twostrings to ("two strings" & " are now one string.") (* using
the & string-concatenation operator *)
& |
As |
( ) |
Begins with |
* |
Contains |
+ |
Does not contain |
- |
Does not equal |
/ ÷ div |
Ends with |
< |
Is contained by |
<= ≤ |
Is not contained by |
every, thru,
whose) that you can use to identify or refer to
objects in your code.some, AppleScript code can grab a random object in a container. Here is an example:tell application "Finder"
(* get a random image file from a desktop folder *)
set randomImage to some file of folder "jpegs"
end tellsome.tell application "Finder"
set allFiles to every file in folder "today" (* returns a list
of file objects *)
end tellevery.where and
whose reserved words are used in Filter
references. See the whose section.id reserved word. See the id
section.telll application "Finder"
get file 1 of disk "backup"
get first file of disk "backup"
end tellfirst and
last.middle.variable scope and the special variables that you
can add to your script called properties. The
second part of this chapter is devoted to
AppleScript's predefined variables such as
pi and current
application (a constant). These AppleScript
variables are called constants because their
value is predefined, and you mostly cannot use the same words for
your own script variables. You could name one of your own variables
pi (a predefined variable) and get away with it,
but this would only confuse the readers of your code.set int to 20 -- one way to set a variable to an integer copy 20 to int -- another way
int variable in
the statement set int to 20. Along with
copy, the set reserved word is
used to set a variable name to a value, in this case an
integer. AppleScript variables can store any
value, including booleans, lists, numbers, records, strings, and
application-defined classes. AppleScript variables have to begin with
a letter or underscore ( _ ) character, but subsequent characters can
include numbers and underscores. You cannot include operators and
other symbols that AppleScript reserves for different uses (such as
*, &, ^, or +) or special characters (such as $, @, or #). An
exception to this rule in AppleScript allows the creation of
memorable variable names if you use vertical-bar characters (|) to
begin and end the identifier:
set |2$var*&^%#| to 2
myname, myName, and
MYNAME are all considered the same variable.
Variable names can be one to several characters long, depending on
your stylistic preferences.set int to 20 -- one way to set a variable to an integer copy 20 to int -- another way
int variable in
the statement set int to 20. Along with
copy, the set reserved word is
used to set a variable name to a value, in this case an
integer. AppleScript variables can store any
value, including booleans, lists, numbers, records, strings, and
application-defined classes. AppleScript variables have to begin with
a letter or underscore ( _ ) character, but subsequent characters can
include numbers and underscores. You cannot include operators and
other symbols that AppleScript reserves for different uses (such as
*, &, ^, or +) or special characters (such as $, @, or #). An
exception to this rule in AppleScript allows the creation of
memorable variable names if you use vertical-bar characters (|) to
begin and end the identifier:
set |2$var*&^%#| to 2
myname, myName, and
MYNAME are all considered the same variable.
Variable names can be one to several characters long, depending on
your stylistic preferences.set and copy keywords to
declare a variable and store a value in it:set l to {"a", "legal", "var"} as list (* a variable name can be one letter *)
set a_veryLong_but_legal30_variable500_name to "Too long in my opinion"
copy 500 to int (* using the copy keyword instead of set has the same effect on
integers *)
copy "A string" to str -- creating a string variable with copy
set $perl_string to "Can't imitate perl without pipe characters" (* this will
raise a compiler error *)
set |$perl_string| to "Recreate a perl scalar variable if you use pipe¬
characters"
set 2str#in/g to "You can't start a variable with a number or use¬
special symbols in it" (* another error, unless you enclose the characters in
pipe symbols *)true or false), date constants
(e.g., April, May), and
considering or ignoring constants (e.g.,
case, white space), among
others. Predefined variables, on the other hand, have a changeable
value. In other words, you can use code such as set pi to
5 and the pi predefined variable will no
longer have the value of about 3.14159 in your script! You cannot
change the value of the boolean constant false,
however (set false to 3 will not compile). The
constants are listed in Table 6-1, and the
Predefined Variables are listed in Table 6-2.
Certain date and time values (i.e., minutes,
hours, days,
weeks) are changeable in a script like predefined
values; however, they are grouped with other date constants for
convenience.
all caps
|
all lowercase
|
application responses
|
ask
|
bold
|
case
|
condensed
|
current application
|
date and time constants (e.g., January,
February) |
|
if conditional statements, which are very similar
to the syntax of Visual Basic, Perl, and other languages. These
statements execute code only if the tested conditions are
true. AppleScript handles loops in script code
with several variations of the repeat statement,
similar to the "for,"
"foreach," or "for
each" statements in other languages. The
repeat flow-control construct repeats the
execution of code a specified number of times or for each member of a
container, such as a list type. Or, it repeats a
code phrase a specified number of times:repeat 100 times...end repeat
try...end
try statement block. In addition, you have already seen
dozens of examples of the tell..end tell statement
in earlier chapters. These statements specify the objects, usually
application objects, that receive the commands or Apple events that
your script sends. You specify the targets of different script
commands by using these tell statements.end, optionally followed by the
statement identifier, such as tell or
repeat. An example is:tell app "Photoshop 5.5"...end tell
if and tell statements
allow "simple" rather than
"compound" usage, such as:if (current date) > date "1/1/2001" then display dialog "Welcome to 2001"
end reserved word. This code shows some nested
flow-control statements and simple statements:tell application "Finder"
set freeMemoryBlock to largest free block
(* Here's a simple statement; no 'end' is necessary *)
if freeMemoryBlock < 10000000 then display dialog¬
"Memory is getting low"
set listOfProcesses to name of processes
if "BBEdit 5.0" is not in listOfProcesses then (* compound 'if'
statement *)
tell application "BBEdit 5.0" to run -- simple 'tell' statement
end if
end tellon or to and a subroutine name
that does not clash with any of AppleScript's other
predefined names (such as anything or
pi), and then a set of parentheses that optionally
lists any parameters or values that should be passed to the
subroutine. The subroutine in Example 8-1 is called
myfunc.on myfunc(s1,s2) return (s1 & s2) end myfunc"
myfunc("one string ", "connected to another")|
idle handler
|
|
open handler |
on or
to are required in the subroutine definition,
followed by the name of the subroutine, and any parameters separated
by commas and contained in parentheses. You have to use empty
parentheses following the subroutine name if the subroutine will not
take any parameters. The subroutine's name must
comply with AppleScript's rules for identifiers. In
AppleScript, the names that you create for variables and subroutines
have to begin with a letter or underscore ( _ ) character, but
subsequent characters can include letters, numbers, and underscores.
Unless you begin and end the subroutine name with a vertical bar (|),
you cannot include AppleScript's reserved words and
operators such as *, &,
^, or +, or special characters
such as $, @, or #.
end keyword
is required to signal the end of the subroutine definition. You can
follow end with the subroutine name for the sake
of readability:On Squared(n1)...end Squared
if...then...end if
repeat...end repeat
Squared(7)
on or to are required
in the labeled-subroutine definition, followed by the name of the
subroutine, and optionally a nonlabeled parameter called a
direct parameter. If the subroutine has a direct
parameter (it does not have to), then the subroutine name has to be
followed by the keyword of or
in:
On Square of intOne...
on Square of intOne above intLimit given Intclass:theClass
if (intOne > intLimit) and (theClass is integer) then
return intOne ^ 2
else
return 0
end if
end Square
Square of myint above 0 given Intclass:(class of myint)on Square(intOne,intLimit,theClass)
if (intLimit > 0) and (theClass is integer) then
return intOne ^ 2
else
return 0
end if
end Squareabove intLimit:on Square of intOne above intLimit given Intclass:theClass
above, you can use the following
AppleScript reserved words: about,
against, apart from,
around, aside from,
at, below,
beneath, beside,
between, by,
for, from, instead
of, into, on,
ontoprop parent : MyParent
MyParent in this case is a variable that refers to
another script object.script MyScript (* define properties, methods, variables here *) end script
script...end script to define a script object
within another script. For example, a single script could involve its
own properties, subroutines, run handler, and
one or more script objects. Used in this manner, a script object can
be like a "type" that you define.
Example 9-2 defines a
Collection type within another script. A
Collection involves one to several property/value pairs and methods
that can return Collection values as well as add a new property/value
pair to the Collection. In this case, the Collection object or type
is defined at the top of the script and then demonstrated beneath the
script-object definition. The example Collection involves the names
of some planets followed by their diameters in
kilometers.
(* Apple Guide's 'open' command can take a file specification type for a parameter *) set filespec to¬ "macintosh hd:BBEdit 5.0:BBEdit 5.0:BBEdit Guide" as file specification tell application "Apple Guide" (* Use the 'string' labeled parameter and the 'ViewNumber' parameter that takes an integer type *) open database filespec string "grep" ViewNumber 4 end tell
tell app "Apple System Profiler" (* get the machine's IP address *) get TCPIP address end tell
set rep to "macintosh hd:desktop folder:ASP report" as alias tell application "Apple System Profiler" activate bring ASP to the front open rep end tell
ASPreportFile
displaying print dialog true as text.displaying print dialog (boolean) true/false value. If
it's true, it displays a dialog
for setting printing preferences prior to printing the ASP report._!Åm¿__-#8_ÁÎ>°CºE_$ëBj,/Z.·,©._fnB,"†VS'íu,>…£1Ë-_éΣI_{_ÇRôY] *oe}g_
Z2<Ú¯e)EifÍ3&bEa_Ü__E,â#@aÍ'ÌÌ·k_m].¿__'__AQHuè·Ë…e>>é¤>/
tell app "Desktop Printer Manager" (* Find out which installed drivers can work with desktop printers; a list of these drivers is stored in the drivers variable, if your computer has any supported drivers *) set drivers to supported drivers end tell