AppleScript in a Nutshell

Overview

AppleScript in a Nutshell is the first complete reference to AppleScript, the popular programming language that gives both power users and sophisticated enterprise customers the important ability to automate repetitive tasks and customize applications. As the Macintosh continues to expand and solidify its base in the multimedia and publishing industries, AppleScript is the tool of choice on this platform for creating sophisticated time- and money-saving workflow applications (applets). These applets automate the ...

See more details below
Paperback (1ST)
$27.76
BN.com price
(Save 20%)$34.99 List Price
Other sellers (Paperback)
  • All (31) from $1.99   
  • New (3) from $25.14   
  • Used (28) from $1.99   
AppleScript in a Nutshell

Available on NOOK devices and apps  
  • NOOK Devices
  • NOOK HD/HD+ Tablet
  • NOOK
  • NOOK Color
  • NOOK Tablet
  • Tablet/Phone
  • NOOK for Windows 8 Tablet
  • NOOK for iOS
  • NOOK for Android
  • NOOK Kids for iPad
  • PC/Mac
  • NOOK for Windows 8
  • NOOK for PC
  • NOOK for Mac
  • NOOK Study
  • NOOK for Web

Want a NOOK? Explore Now

NOOK Book (eBook)
$15.49
BN.com price
(Save 44%)$27.99 List Price

Overview

AppleScript in a Nutshell is the first complete reference to AppleScript, the popular programming language that gives both power users and sophisticated enterprise customers the important ability to automate repetitive tasks and customize applications. As the Macintosh continues to expand and solidify its base in the multimedia and publishing industries, AppleScript is the tool of choice on this platform for creating sophisticated time- and money-saving workflow applications (applets). These applets automate the processing and management of digital video, imaging, print, and web-based material. AppleScript is also gaining a foothold in scientific programming, as technical organizations adopt G4 CPU-based systems for advanced computing and scientific analysis. Finally, "power users" and script novices will find that AppleScript is a great everyday Mac programming tool, similar to Perl on Windows NT or Unix.

In this well-organized and concise reference, AppleScript programmers will find:

  • Detailed coverage of AppleScript Version 1.4 and beyond on Mac OS 9 and Mac OS X.
  • Complete descriptions of AppleScript language features, such as data types, flow-control statements, functions, object-oriented features (script objects and libraries), and other syntactical elements.
  • Descriptions and hundreds of code samples on programming the various "scriptable" system components, such as the Finder, File Sharing, File Exchange, Network scripting, Web scripting, Apple System Profiler, the ColorSync program, and the numerous powerful language extensions called "osax" or scripting additions.
    Most other AppleScript books are hopelessly out of date. AppleScript in a Nutshell covers the latest updates and improvements with practical, easy to understand tips, including:
  • Using AppleScript as a tool for distributed computing, an exciting development that Apple Computer calls "program linking over IP." Programmers can now do distributed computing with Macs over TCP/IP networks, including controlling remote applications with AppleScript and calling AppleScript methods on code libraries that are located on other machines.
  • Using the Sherlock find application to automate web and network searching.
  • Insights on scripting new Apple technologies such as Apple Data Detectors, Folder Actions, Keychain Access, and Apple Verifier.
    AppleScript in a Nutshell is a high-end handbook at a low-end price—an essential desktop reference that puts the full power of this user-friendly programming language into every AppleScript user's hands.
Read More Show Less

Product Details

  • ISBN-13: 9781565928411
  • Publisher: O'Reilly Media, Incorporated
  • Publication date: 6/29/2001
  • Series: In a Nutshell (O'Reilly) Series
  • Edition description: 1ST
  • Edition number: 1
  • Pages: 528
  • Product dimensions: 6.04 (w) x 9.02 (h) x 0.99 (d)

Meet the Author

Bruce W. Perry is an independent software developer and writer, and the author of O'Reilly's Java Servlet & JSP Cookbook and Ajax Hacks. Since 1996, he has developed web applications and databases for various nonprofits, design and marketing firms, as well as publishers. In his spare time, Perry is an active age-group triathlete and has cycled extensively in the Swiss Alps. He splits his time between Warren, Vermont and the Newburyport, Massachusetts area with his wife Stacy LeBaron, daughter Rachel, and son Scott.

Read More Show Less

Read an Excerpt

Chapter 7: Flow-Control Statements

The flow-control statements in AppleScript orchestrate the "flow" or the order in which the code statements execute in your scripts. Programmers will be familiar with AppleScript's 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

You will be pleased to know that AppleScript has more than adequate error-trapping capabilities. This is accomplished by enclosing the statements that may raise errors in a 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.

You can nest flow-control statements within other flow-control statements. Most of these statements end, appropriately, with the reserved word end, optionally followed by the statement identifier, such as tell or repeat. An example is:


tell app "Photoshop 5.5"...end tell

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

These simple statements appear on one line, they do not contain other code statements, and they do not need to be completed with the 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 tell

Suffice it to say, flow-control statements are how AppleScript derives much of its power and complexity. You will develop very few scripts that do not use at least one flow-control statement. Table 7-1 lists the statements that this chapter describes.

Table 7-1: Flow-Control Statements

considering

repeat with loop variable

continue

repeat integer times

error

return

exit

tell simple statement

if simple statement

tell compound statement

if compound statement

try

ignoring

using terms from

repeat

with timeout

repeat until

with transaction

repeat while

 

considering [but ignoring] end [considering]

Syntax


Considering case
 
  "animal" is equal to "AniMal" -- returns false

end considering

Description

Use considering statements to specify the elements that should be considered during string comparisons and communications with other applications. The statements that constitute the comparison are enclosed in the considering...end considering block. This statement block affects how each of its enclosed statements is processed. The considering statement can also alter AppleScript's default behavior for the code that is executed prior to the end of the considering statement (signaled by an end or end considering phrase). For example, if you wanted to compare two strings and take upper- or lowercase characters into account, but ignore any white space in the strings, then you would use the statement: considering case but ignoring white space...end considering. AppleScript's default behavior is to consider elements such as case, white space, and punctuation when it compares strings for equality. The following constants can also be used in the considering statement (Chapter 6, Variables and Constants, discusses AppleScript's constants):

  • application responses
  • case
  • diacriticals
  • expansion
  • hyphens
  • punctuation (i.e., . , ? : ; ! \ ' " `)
  • white space

AppleScript considers by default an application's responses to any Apple events that your script sends them. You can use the ignoring statement to ignore responses from an application, as in considering case but ignoring application responses.

There are a few instances when ignoring application responses might make sense, such as when you are sending quit commands to several running processes. If one of the processes responds to the command with an error, then the script ignores its response (as well as any other application response) and thus prevents it from disrupting the execution of the rest of the script. See "ignoring" in this chapter for more details.

Examples

This code shows how to use this statement with a fairly complex string comparison:


tell application "Finder"
 
  considering case but ignoring punctuation, white space and hyphens
 
     set theTruth to ("voracious appetite" is equal to "voracious, 
¬
 
     appetite") --returns true
 
  end considering

end tell

The example tells AppleScript which elements to consider and ignore when executing the string comparison within the considering statement block. Since white space, hyphens, and punctuation should be ignored in the comparison, the two strings turn out the same. Therefore, the theTruth variable is set to true. If you are wondering why you would ever ignore these elements in a string comparison, programs often deal with a lot of junk characters and tokens, such as markup-language elements, which are returned from applications or web pages. The considering statement allows you, in a minimal way, to filter out elements that you do not want to include in string comparisons (unfortunately, you will have to write custom functions or use an HTML-parsing osax to filter out the common < > characters in hypertext markup language [HTML], as AppleScript does not consider them to be "punctuation").

continue

Syntax


On parMethod(int )
 
  If somethingTrue then
 
     (* code statements here *)
 
  else
 
     continue parMethod(int) -- call parent script's parMethod version
 
  end if

end parMethod

Description

The continue statement is used to call a parent script's method from a child script. In AppleScript, a child script can inherit properties and methods from a parent script. This topic is covered in Chapter 9, Script Objects and Libraries. The child script specifies its parent (if it has one) by declaring a parent property at the top of the script:


property parent : 
NameOfScript

The NameOfScript part can be either the name of a script object or an application, such as:


application "Finder"

A child script inherits the methods of a parent; it does not have to define these methods. However, the child script can "override" the parent method(s) by redefining them in the body of the script. Within these redefined methods, it can use the continue statement to call the parent method. The following example constitutes a child script that calls its parent's version of the parMethod function based on the magnitude of the numerical argument passed to the method. The child object handles real numbers and the parent handles integers.

Examples


On parMethod(int )
 
  If (class of int is real) then
 
     Return (int * 2)
 
  Else
 
     continue parMethod(int) (* it's an integer so call the parent 
 
     parMethod *)
 
  end if

end parMethod

error

Syntax


error myErrText number 9000 -- myErrText contains the error description

Description

The error statement allows you to raise an error based on certain script conditions. Why would you ever want to raise an error? You may want to catch an error in a function but handle the error in the part of the code that called the function, higher up in the call chain. So you would use the error statement to pass the error up to the calling function, such as in the following example. This is similar to "throwing" an exception in Java.

Examples

This example uses a getNumber method to get a number from the user, but it does not bother (for the sake of demonstration) to check the entry to ensure that the user has entered a valid number. If the user enters data that is not a number then the statement:


return (theNum as number)

causes an error, because AppleScript cannot coerce non-numeric characters to a number. To be specific, this is AppleScript error number -1700. The getNumber method catches the error and uses an error statement to pass the original error's error message and number back to the calling handler (in this case the script's run handler), which then catches the "re-raised" error and displays a message:


on run
 
  try
 
     display dialog "Your number is: " & (getNumber(  ) as text)
 
  on error errmesg number errn
 
     display dialog errmesg & return & return & "error number: " & ¬ 
 
        (errn as text)
 
  end try

end run

on getNumber(  )
 
  set theNum to (text returned of (display dialog ¬
 
  "Please enter a  number:" default answer ""))
 
  try
 
     return (theNum as number)
 
     on error errmesg number errnumber
 
     error errmesg number errnumber
 
  end try

end getNumber

The error statement also gives the scripter more control on how program errors are handled. For example, you can catch an error in a script with a try block (see "try" later in this chapter), examine the nature of the error, then re-raise the error with the error statement providing a more lucid error message to the user. This is best illustrated with the following code, which catches an error caused by coercing a non-numeric string to a real data type:


(* use the display-dialog scripting addition to ask the user to enter a number *)

set aNum to the text returned of (display dialog "Enter a number" ¬

default  answer "")

try
 
  set aNum to aNum as real (* non-numeric string like "10ab" will raise an error *)

on error number errNumber
 
  set myErrText to "Can't coerce the supplied text to a real: " & ¬
 
  return & "The AS error number is " & errNumber
 
  error myErrText number 9000 -- add your own error number

end try

The code first asks the user to enter a number, using the display dialog scripting addition. This produces a dialog box with a text-entry field. If the user enters some text that cannot be coerced to a number, such as 10ab (the included letters ab cause the coercion to fail), the expression:


set aNum to aNum as real

causes the script to raise an error. The try block catches the error, and then processes the statements following the on error code. These statements include:


error myErrText number 9000

which produces an AppleScript error-dialog box and adds the scripter's custom message (stored in the variable myErrText). It also provides a custom error number of 9000. You can create your own groups of error numbers or variables for certain error conditions, which your script can then identify and respond to with more accuracy and clarity than if the scripter only relied on AppleScript's error numbers.

The next two examples illustrate the setup and usage of custom error variables. The first example is a script that contains several user-defined error variables for some common errors that occur in AppleScripts. This script is loaded into the current script using the load script scripting addition (Appendix A, Standard Scripting Additions, discusses scripting additions, or osaxen). The example only contains three constants, but it could define dozens of them to accommodate most or all of the possible script errors that could occur. The constants are set to the actual values that AppleScript assigns to the errors that represent, for example, the failure to coerce data from one type to another (i.e., error number -1700):


set FAILED_COERCION to -1700
 

set MISSING_PARAMETER to -1701
 

set TIMEDOUT_APPLEEVENT to -1712

You can then test for certain errors and, if you discover them, display more informative messages or take some other appropriate action. For example, the script in the following code sets the variable objErrors to the script object defined in the prior example. It then uses the FAILED_COERCION and TIMEDOUT_APPLEEVENT constants from that object to test for these error conditions. In other words, the TIMEDOUT_APPLEEVENT variable contains AppleScript's actual error number for Apple events that time out (-1712), but it is easier to remember if it is stored in a variable with a coherent name. If either of these errors is detected, the error statement is used to produce a dialog box with your own error message:


set objErrors to (load script file "HFSA2gig:nutshell

 book:demo 
¬ scripts:scr_0504")(* this
  script object contains


the user-defined error variables *)
set userReply to the text returned of (display dialog ¬ "Please enter a number" default answer "") try set aNum to userReply as real (* if the user doesn't provide a number this statement will fail and the try block will catch the error *) on error errM number errNumber if errNumber is equal to (objErrors's FAILED_COERCION) then (* FAILED_COERCION is a property of the script object stored in objError *) error "The number you provided was not a valid integer or real." else if errNumber is equal to (objErrors's TIMEDOUT_APPLEEVENT) then error "For some reason AppleScript timed out." else -- default error message for all other errors set defMessage to "Sorry, AppleScript error number: " & errNumber & ¬ "occurred in the script. Here's
AppleScript's error description: " & errM error defMessage
end if end try

The error statement includes a number of optional parameters. It is important to remember that you supply the values for these parameters (if you want to use them). With try blocks and on error statements, AppleScript itself will fill these parameters with values (see "try" later in this chapter):

  • A non-labeled parameter that contains the text describing the error, as in error "The Apple event timed out".
  • A labeled parameter that identifies the error number, such as error "The Apple event timed out" number 9000. You use the keyword number followed by the integer. If you do not include an error number, AppleScript gives this parameter a default value of -2700.
  • A labeled parameter that identifies the object that caused the error, as in error "The Apple event timed out" number 9000 from userReply. You use the keyword from followed by a reference to the object, in this case the variable that caused the coercion error.
  • A labeled parameter that involves the reserved words partial result followed by a value of type list. If the command that caused the error involved the receipt of return values from multiple objects (e.g., a command sent to several database files to get some data), then the list value contains any of the values that were successfully received before the error halted the operation. AppleScript gives this parameter a default value of the empty list ({ }).
  • A to keyword or label followed by a word that identifies a class type, such as boolean, string, or integer. If the command that caused the error received the wrong type of parameter value, then the to labeled parameter will identify the correct data type that the parameter expected.

The following example demonstrates how to pass the information about an AppleScript error to an error statement. The script intentionally raises an error by using a string instead of a boolean expression in an if statement. Then it passes the error data as a long string to an error statement:


try
 
  if "not a boolean" then (* this causes an error, caught in the try block *)
 
     beep 2
 
  end if

on error errMessage number errNum from errSource partial result ¬ 

errList  to class_constant -- various variables store information about the error
 
  set bigmessage to "The error is: " & errMessage & return & ¬
 
  "The number is: " & errNum & return & "The source is: " & errSource
 
  error bigmessage -- error statement displays dialog box to user

end try

exit [repeat]

Syntax


repeat 2 times
 
  exit repeat

end repeat

Description

The exit statement causes the flow of script execution to leave the exit statement's repeat loop. The execution then resumes with the script code following the repeat loop. exit can only be used inside of a repeat loop, regardless of the repeat-loop variation. Using exit is the conventional way to exit a repeat loop that has no conditional statement associated with it, as shown in this example. In other words, this form of repeat is an infinite loop:


repeat
 
  set userReply to the text returned of (display dialog "Want to get 
¬
 
  out of this endless loop?" default answer "")
 
  if userReply is "yes" then exit repeat

end repeat

This endless loop can also be exited by clicking the Cancel button on the dialog produced by display dialog, which terminates the execution of the script.

if simple statement

Syntax


If theBool is true then exit repeat

Description

AppleScript supports the simple if statement that is similar to Perl's. You can use a statement such as the following...

Read More Show Less

Table of Contents

Preface;
Organization of This Book;
Conventions Used in This Book;
How to Contact Us;
Acknowledgments;
Introduction to AppleScript;
Chapter 1: AppleScript: An Introduction;
1.1 How Is AppleScript Used?;
1.2 Apple Events;
1.3 Using Script Runner with OS X;
1.4 Using OSA Menu with OS 9;
1.5 Checking Your AppleScript Version;
1.6 Diving In;
Chapter 2: Using Script Editor with OS 9 and OS X;
2.1 Script Editor Controls/Commands;
2.2 Scripting the Script Editor;
AppleScript Language Reference;
Chapter 3: Data Types;
Chapter 4: Operators;
Chapter 5: Reference Forms;
Chapter 6: Variables and Constants;
6.1 Variables;
6.2 Constants and Predefined Variables;
Chapter 7: Flow-Control Statements;
Chapter 8: Subroutines;
8.1 Subroutines with Positional Parameters;
8.2 Subroutines with Labeled Parameters;
Chapter 9: Script Objects and Libraries;
Scripting Mac OS 9 Applications;
Chapter 10: Apple Guide and Help Viewer;
Chapter 11: Apple System Profiler;
Chapter 12: Keychain Scripting and Apple Verifier;
Chapter 13: Desktop Printer Manager;
Chapter 14: Mac OS 9 Finder Commands;
14.1 Example Finder Scripts;
Chapter 15: Mac OS 9 Finder Classes;
Chapter 16: Network Setup Scripting;
Chapter 17: Scripting Sherlock 2;
Chapter 18: URL Access Scripting;
Scripting Mac OS 9 Control Panels and Extensions;
Chapter 19: Appearance Control Panel;
Chapter 20: Apple Data Detectors Extension;
Chapter 21: Apple Menu Options Control Panel;
Chapter 22: Application Switcher Extension;
Chapter 23: ColorSync Extension;
Chapter 24: File Exchange Control Panel;
Chapter 25: File Sharing Control Panel;
Chapter 26: Folder Actions Extension;
Chapter 27: FontSync Control Panel and Extension;
Chapter 28: Location Manager Control Panel;
Chapter 29: Memory and Mouse Control Panels;
Chapter 30: Speech Listener and SpeakableItems Extension;
Chapter 31: Web Sharing Control Panel;
Scripting the Mac OS X System;
Chapter 32: Scripting the OS X Desktop;
32.1 Working with Files, Folders, Disks, and Windows in OS X;
Chapter 33: Scripting Mail;
33.1 Setting Up an Email Message;
33.2 Exploring the Mail Application Object;
33.3 Getting Information about an Email Account;
Chapter 34: Executing Scripts with the Terminal App;
Chapter 35: Scripting TextEdit;
Appendixes;
Standard Scripting Additions;
AppleScript Resources;
Apple Computer AppleScript URLs;
AppleScript FAQs, Mailing Lists, and Tutorials;
Macintosh Scripting Sites;
Commercial AppleScript Development Environments;
Freeware AppleScript Development Environments;
Colophon;

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)