This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com AppleScript in a Nutshell By Bruce W Perry of • Table Contents • Index • Reviews • Examples • Reader Reviews • Errata Publisher: O'Reilly Pub Date: June 2001 ISBN: 1-56592-841-5 Pages: 526 Slots: 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 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 This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com AppleScript in a Nutshell By Bruce W Perry of • Table Contents • Index • Reviews • Examples • Reader Reviews • Errata Publisher: O'Reilly Pub Date: June 2001 ISBN: 1-56592-841-5 Pages: 526 Slots: Copyright Preface Organization of This Book Conventions Used in This Book How to Contact Us Acknowledgments Part I: Introduction to AppleScript Chapter AppleScript: An Introduction Section 1.1 How Is AppleScript Used? Section 1.2 Apple Events Section 1.3 Using Script Runner with OS X Section 1.4 Using OSA Menu with OS Section 1.5 Checking Your AppleScript Version Section 1.6 Diving In Chapter Using Script Editor with OS and OS X Section 2.1 Script Editor Controls/Commands Section 2.2 Scripting the Script Editor Part II: AppleScript Language Reference Chapter Data Types alias boolean class constant data date file specification integer international text list number real This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com record reference RGB color string Styled Clipboard Text Styled Text text Unicode Text Unit of Measurement Classes Chapter Operators & () * + / ÷ div < >= ^ [a] reference to and as begin[s] with contains does not contain does not equal ends with is contained by is not contained by m od not or Chapter Reference Forms after back before beginning first, second, third, fourth, etc every every from to id last middle name some whose Chapter Variables and Constants This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Chapter Variables and Constants Section 6.1 Variables Section 6.2 Constants and Predefined Variables Chapter Flow-Control Statements considering [but ignoring] end [considering] continue error exit [repeat] if simple statement if [then] [else if] [else] end [if] ignoring [but considering] end [ignoring] repeat end [repeat] repeat until end [repeat] repeat while end [repeat] repeat with {loop variable} from {integer} to {integer}[by stepVal] end [repeat] repeat with {loop variable} in {list} end [repeat] repeat {integer} times end [repeat] return [return value] tell simple statement tell end [tell] try [on error] [number | from | partial result | to] end[error | try] using terms from end [using terms from] with timeout [of] {integer} second[s] end [timeout] with transaction [session object] end [transaction] Chapter Subroutines Section 8.1 Subroutines with Positional Parameters Section 8.2 Subroutines with Labeled Parameters Chapter Script Objects and Libraries Script Objects Libraries Part III: Scripting Mac OS Applications Chapter 10 Apple Guide and Help Viewer Apple Guide Help Viewer Chapter 11 Apple System Profiler Apple System Profiler Chapter 12 Keychain Scripting and Apple Verifier Keychain Scripting Apple Verifier Chapter 13 Desktop Printer Manager Desktop Print Manager Chapter 14 Mac OS Finder Commands Section 14.1 Example Finder Scripts Chapter 15 Mac OS Finder Classes This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Finder Classes Chapter 16 Network Setup Scripting Network Setup Scripting Chapter 17 Scripting Sherlock Sherlock Chapter 18 URL Access Scripting URL Access Scripting Part IV: Scripting Mac OS Control Panels and Extensions Chapter 19 Appearance Control Panel Appearance Control Panel Chapter 20 Apple Data Detectors Extension Apple Data Detectors Chapter 21 Apple Menu Options Control Panel Apple Menu Options Chapter 22 Application Switcher Extension Application Switcher Chapter 23 ColorSync Extension ColorSync Chapter 24 File Exchange Control Panel File Exchange Chapter 25 File Sharing Control Panel File Sharing Chapter 26 Folder Actions Extension Folder Actions Chapter 27 FontSync Control Panel and Extension FontSync Control Panel FontSync Extension Chapter 28 Location Manager Control Panel Location Manager Chapter 29 Memory and Mouse Control Panels Memory Control Panel Mouse Control Panel Chapter 30 Speech Listener and SpeakableItems Extension Speech Listener Application SpeakableItems Extension Embedded Speech Commands Chapter 31 Web Sharing Control Panel This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Part V: Scripting the Mac OS X System Chapter 32 Scripting the OS X Desktop Section 32.1 Working with Files, Folders, Disks, and Windows in OS X Chapter 33 Scripting Mail Section 33.1 Setting Up an Email Message Section 33.2 Exploring the Mail Application Object Section 33.3 Getting Information about an Email Account Chapter 34 Executing Scripts with the Terminal App osacompile osalang osascript Chapter 35 Scripting TextEdit TextEdit Part VI: Appendixes Appendix A Standard Scripting Additions Standard Additions Standard Additions Appendix B AppleScript Resources Section B.1 Apple Computer AppleScript URLs Section B.2 AppleScript FAQs, Mailing Lists, and Tutorials Section B.3 Macintosh Scripting Sites Section B.4 Commercial AppleScript Development Environments Section B.5 Freeware AppleScript Development Environments Colophon Index This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Copyright © 2002 O'Reilly & Associates, Inc All rights reserved Printed in the United States of America Published by O'Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472 Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O'Reilly & Associates, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps The association of the image of a Boston terrier and the topic of AppleScript is a trademark of O'Reilly & Associates, Inc Apple Computer, Inc boldly combined open source technologies with its own programming efforts to create Mac OS X, one of the most versatile and stable operating systems now available In the same spirit, Apple has joined forces with O'Reilly & Associates to bring you an indispensable collection of technical publications The ADC logo indicates that the book has been technically reviewed by Apple engineers and is recommended by the Apple Developer Connection Apple, Macintosh, AppleScript, Mac OS, and Mac OS X are registered trademarks of Apple, Inc While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Preface AppleScript continues to evolve on Mac OS and Mac OS X as the ultimate scripting tool for the Macintosh AppleScript's power to automate the operating system and complex applications such as graphics, desktop-publishing, and database programs, as well as a friendly English language dialect that helps ambitious scripters get up to speed quickly with their own applets, is not matched by any other platform's programming language Yet, only a small percentage of Macintosh users are even aware that AppleScript is installed with their operating system Those who are aware of AppleScript's presence on their machine often not take full advantage of this tool to automate their daily computing activities, both on their local machine and over the Internet Who should and can use AppleScript? The following users come to mind right away: system administrators who are automating tasks with networks and applications; web and graphics professionals who want to control the development of web sites and publications; scientists, mathematicians, and engineers who require applets to make calculations and automate their own software tools, as well as day-to-day programmers and students who are designing and prototyping new programs Not to mention everday users who want to automate their own computing tasks, such as file and folder backups If you are on a Macintosh, then you should be putting AppleScript to work for you The purpose of this book is primarily three-fold: Describe AppleScript and its tools (Part I) and provide a core language reference (Part II) that all users can keep next to their computers as they write new scripts Provide detailed descriptions, examples, and reference information on how to script the numerous system-level programs on Mac OS ( Part III and Part IV) and Mac OS X (Part V), such as the Finder on both OS versions, Sherlock, and Network Setup Scripting Give scripters general insight on how to approach the scripting of several programs that can be automated by AppleScript, such as Adobe Illustrator and Photoshop, FileMaker Pro, QuarkXPress, SoundJam MP, and OutLook Express The mantra is, study the "application class" in the program's AppleScript dictionary and you'll be up and running with scripting that program before you know it (Chapter discusses the application class in general terms; while the application classes of all the various system components are described in detail throughout the book.) Hopefully, this book will help reveal AppleScript to more Macintosh users, thus providing them with another outlet for creativity and productivity This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Organization of This Book AppleScript in a Nutshell is structured in six parts Part I This section provides an overview of AppleScript and Script Editor, the free AppleScript development tool that installs with the Macintosh Quick studies and experienced programmers will probably be able to develop their first AppleScripts (if you have never used AppleScript before) based on a reading of this introductory section alone Chapter describes how AppleScript is primarily used and also describes the relevance to AppleScript of Apple events, an internal messaging system that the Macintosh operating system uses for interapplication communication The end of Chapter summarizes AppleScript's core language features (Part II provides a more comprehensive language reference) You can use Chapter as a helpful reference to Script Editor as you use this Apple Computer tool to develop your scripts Chapter This AppleScript overview includes a description of how AppleScript is primarily used, an Appleevent tutorial, and a compressed language reference for those who want to dive right into scripting Novice users should start here with the book, while very experienced AppleScripters may use this section as a review or skip over it Chapter This chapter describes all of Script Editor's primary menu commands and controls It also explains the various options for saving AppleScript files Part II If scripters need more information on specific language features, this is the place to look The core-language information is presented with syntax examples, code examples, and text descriptions Everything is arranged in alphabetical order to make things easy to locate This includes the various data types (i.e., how AppleScript stores data in memory), operators (such as the common Math operators and the string-concatenation operator "&"), and how to set AppleScript variables and create user-defined functions, as well as advanced features, such as creating object-oriented script objects (Chapter 9) Chapter This chapter describes the built-in AppleScript data types, including string , integer , real , list , and record Comparisons with programming languages are made where it is appropriate (e.g., a list is like an array, and a record is an associative array) Chapter Use this chapter as a reference to the built-in symbols (e.g., &, +, *, - ) that you can use in AppleScript expressions Chapter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com AppleScript provides several English-language terms to use when the script refers to objects on your computer system, such as files, folders, disks, and applications This chapter is an alphabetical reference to these terms (e.g., first , every , id , where ) Chapter AppleScript, like other languages, uses variables as placeholders that represent data (e.g., strings or numbers) This chapter describes the rules for naming and creating your own variables; it also provides a reference to AppleScript's constants and predefined variables (like pi ) Chapter This chapter is an alphabetical reference to AppleScript's flow-control statements, such as if , repeat , try , exit , and continue Chapter This chapter is a tutorial on creating user-defined subroutines, which are also called handlers, functions, or methods (in object-oriented parlance) The second part of this chapter describes five special handlers in AppleScript: idle, open, quit, reopen, and run Chapter AppleScripters can create script objects, which are user-defined types that can have their own attributes and methods This chapter also describes function libraries, which are script objects that give other external scripts the ability to load and/or call the object's own functions Part III This section is devoted to the scripting of system-level Mac OS programs, such as Apple System Profiler, Keychain Scripting, the Finder, Network Setup Scripting, and Sherlock The scriptable control panels and extensions are covered in the next section, Part IV The programs that are covered in this section for the most part have comprehensive AppleScript dictionaries and can be used to extend your computer's capabilities (particularly with AppleScript!); however; they are not control panels or extensions The exception to this scheme is Apple Guide, which is an extension but was included in this section so that the reader has access in a single chapter to a description of AppleScript and the help-related programs Each chapter describes the purpose of the application, then describes each dictionary command and class in a reference-style form Chapter 10 This chapter describes the dictionaries and includes scripting tips for Apple Guide, the traditional automated Apple-help program, and the newer browser-based Help Viewer tool Chapter 11 Accessible from the Apple menu, Apple System Profiler displays a wealth of information about the hardware and software on your system This chapter describes its commands and classes and includes numerous code examples This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] QuickTime application version, retrieving QuickTime version (ASP) quit command Quit command Appearance control panel Apple Guide quit command Apple Menu options AppleSync extension Application Switcher extension ASP DPM File Exchange color panel Finder OS Folder Actions extension FontSync control panel FontSync extension Quit command Help Viewer quit command Keychain Scripting Network Setup Scripting Sherlock quit handler quit statement QuitFront command (Apple Guide) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] RAM disk default values, setting to RAM disk settings class (Memory control panel) random number osax Range reference form raw syntax, data data type and read reference number osax real data type Record button (Script Editor) 2nd record data type recordability recording Apple events records adding to font searching searching for reference data type reference forms 2nd Registry Relative reference form remembers window size (ASP) Remote Access configurations 2nd class properties in Network Setup Scripting connecting to creating disconnecting from properties of, setting configurations, switching among Remote Access configuration class (Network Setup Scripting) properties Remote Access status class (Network Access Scripting) remove action from command (Folder Actions extension) remove command (Network Setup Scripting) remove reference to object command File Sharing control panel removing folder items from command (Folder Actions suite) removing folder items osax reopen command (File Exchange color panel) reopen handler repeat statements 2nd repeat until end statement report class (ASP) 2nd report contents class (ASP) report text class (ASP) report view format class (ASP) reports, ASP 2nd restart command (Finder OS 9) result constant Result window (Script Editor) data, displaying debugging with return constant return keyword, in positional parameters This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com return statement return values checking last one missing reveal reference to object command (Finder OS 9) RGB color data type right angle bracket (>) > >= operators 2nd round osax router address class (Network Access Scripting) routers, creating addresses to Run button (Script Editor) run command Run command Appearance control panel run command Apple Menu options AppleSync extension Application Switcher extension ASP DPM File Exchange color panel Folder Actions extension FontSync control panel FontSync extension Run command Help Viewer run command Network Setup Scripting Sherlock run handler run osax Run-Only option (Script Editor) running Apple Menu Options control panel AppleSync extension applications, retrieving list of classic applets in OS X File Exchange control panel Folder Actions extension FontSync control panel FontSync extension Network Setup Scripting processes scripts order of scripts with run osax Sherlock This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] Save dialog (Script Editor), OS save object reference command (AppleSync extension) save reference to report command (ASP) Save/Save As options (Script Editor) OS Run-Only option saving scripts in Script Editor as droplets as templates as text files CGI scripts on web servers compiled say osax 2nd 3rd scanners, synchronizing colors of scientific notation, + operator and Script Editor as target application applets commands and controls debugging in Event Log Result window dictionaries and font size/type, determining line continuation character (¬) in pop-up menus Record button saving scripts in as droplets uses for viewing list of applications and memory script objects 2nd child, creating defining libraries [See libraries] loading storing in files Script Runner adding scripts to Mac OS X scripting Apple events and components, retrieving as list email Finder OS Finder OS X keychains Script Editor Sherlock Startup Disk control panel scripting additions [See osaxen] Scripting Additions folder 2nd 3rd 4th 5th scripting components osax scripts This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com attached, opening child, calling parent from compiling with Terminal 2nd examples in Finder OS executing on folder movements by spoken command with Terminal application folders, attaching to loading names of, abbreviating parent, calling from child preventing the editing of processing, delaying quitting, with idle handler readability run-only running in Mac OS in Mac OS X order of on remote machines saving in Script Editor as templates as droplets as text files targets of 2nd termination of Scripts folder (Script Runner) SCSI address (DPM) SCSI devices, mounting Search command (Help Viewer) search command (Sherlock 2) search domain class (Network Access Scripting) search Internet command (Sherlock 2) searching for file extensions for lists/records/strings disks for file types files/folders help files Internet lists/records/strings web sites security Keychain Scripting dictionary classes dictionary commands networks Security folder 2nd Security Software Developers Kit (SDK) select reference to object command (Finder OS 9) select search sites command (Sherlock 2) selecting objects servers FTP, files/folders on logging onto AppleShare IP This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com securely web, creating set a file reference number osax set command Apple Menu options FontSync extension 2nd Network Setup Scripting Sherlock set keyword set the clipboard to osax set volume osax shadow constant sharable container class (Finder OS 9) properties shared item class (File Sharing control panel) sharing privileges class (Finder OS 9) Sherlock dictionary classes dictionary commands properties, setting tab property Show Event Results (Script Editor) Show Events checkbox (Script Editor) show privileges of command (File Sharing control panel) ShowPanel command (Apple Guide) shut down command (Finder OS 9) Shutdown Items folder shutdown items folder reference class (Finder OS 9) single quote (') sleep command Finder OS small caps constant Smile (AppleScript tool) some reserved word sort command (Finder OS 9) sorting files/folders sound file class (Finder OS 9) sound volume, adjusting source code for applets space constant SpeakableItems extension 2nd special folders class (Finder OS 9) Speech control panel Speech Listener speech recognition 2nd controlling sound of embedded speech commands Speech Recognition extension square brackets ([]), [a] reference to operator Standard Suite event classes and ids start log statement Start/Stop tab (File Sharing), setting access privileges Startup Disk control panel startup disk, System Folder Control Panels Scripting Additions folder startup info (ASP) startup items folder reference class (Finder OS 9) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Startup Items folder startup screen, preventing display of in Script Editor StartupDiskBus (ASP) StartupDiskLocation (ASP) StartupDiskName (ASP) StartupDiskName class (ASP) statements, termination of Stationery option (Script Editor), OS Stay Open checkbox Stay Open option (Script Editor) Stop button (Script Editor) stop log statement store script osax strikethrough constant string data type 2nd 3rd strings built-in elements comparing considering statements ignoring statement white space constant concatenating 2nd 3rd defining manipulating punctuation in return constant searching searching for space constant storing as text tab constant version constant Styled Clipboard Text data type Styled Text data type subroutines 2nd automating delay idle handler naming open handler parameters direct labeled positional quit handler reopen handler run handler values, returning subscript constant subtraction suitcase class (Finder OS 9) summarize osax summarize text osax superscript constant syntax checking in Script Editor datatypes system attribute osax (OS X) system folder volumes class (ASP) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com System Folder, Finder application icon System Folder\:Scripting Additions folder This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] tab constant target addresses TCP/IP access privileges, setting configurations 2nd creating properties of, setting switching among control panel information about, retrieving printing and user mode volumes, mounting TCPIP address (ASP) TCPIP gateway (ASP) TCPIP info (ASP) TCPIP installed (ASP) TCPIP netmask (ASP) TCPIP status (ASP) TCPIP v4 configuration class (Network Access Scripting) TCPIP v4 options class (Network Setup Scripting) tell statements 2nd 3rd subroutines, calling temporary items folder reference class (Finder OS 9) Terminal application commands text class (TextEdit) properties text data type TEXT file type text files attribute runs, retrieving creating saving scripts as summarizing TextEdit dictionary classes the clipboard osax themes counting TIFF images time to GMT osax time, Greenwich Mean Time to keyword in positional parameters in labeled parameters in positional parameters TogglePanel command (Apple Guide) Topics window (Apple Guide) transactions aborting beginning ending grouping translation mapping class (File Extension control panel) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com translation mappings transport options class (Network Setup Scripting) Trash emptying trash-object class (Finder OS 9) elements/properties true constant try statement 2nd This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] U.S Geographic Detectors underline constant underscore (_) _ operator in positional parameters in variable names unembed command (AppleSync extension) Unicode Unicode Text data type Uniform Resource Locators [See URLs]2nd [See URLs] unlock reference to keychain command (Keychain Scripting) update reference to object command (Finder OS 9) upload command (URL Access Scripting) upload osax URL Access Scripting dictionary commands URL Access Scripting osax URL class (Scripting Additions) URLs (Uniform Resource Locators) accessing choosing detecting IP addresses, using as mailto URL Access Scripting use default settings command, Memory control panel user class (File Sharing control panel) users adding to groups connected to machine deleting dialogs querying duplicating interacting with applets privileges, setting removing from groups speaking to using terms from end statement Utilities folder utilities, writing This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] values, setting from Apple Menu options variable scope variables casting to class types creating declaring 2nd global local names of case sensitivity naming property scope of [See variable scope] specifying data types of values of 2nd storing tracking verify command (Apple Verifier) version (ASP) version constant video memory size (ASP) video note (ASP) viewing applications and memory used in Script Editor dictionaries in Script Editor VM info (ASP) VM size (ASP) VM storage (ASP) volumes, mounting This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] web browser configurations, switching among opening web page class (Scripting Additions) web pages accessing downloading/uploading 2nd 3rd saving to disk 2nd Web Pages folder web servers CGI scripts on, saving in Script Editor creating directories on, downloading/uploading using Mac as web sharing (ASP) Web Sharing control panel dictionary permissions and testing web sharing using scripts with web sites about AppleScript logging onto searching lists, selecting weekday constant where reserved word white space constant window class ASP 2nd Finder OS Window class (Help Viewer) windows frontmost information about, retrieving opening size, setting with timeout statement with transaction statement word class (TextEdit) word processing words referring to spacing between, decreasing/increasing 2nd write osax writing to files utilities This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] yes constant This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [Y] ... is an Apple Computer-maintained database that maps all of the Apple events that the Mac OS standard software uses to a corresponding English-language command This means that the activate AppleScript... considered a near paragon of scriptability Attachable means that you can create a script and then attach it to a program, so that the script is added to the program's internal menus Applications usually... valuable and timesaving information This is an example of a warning, which alerts to a potential pitfall in the program Warnings can also refer to a procedure that might be dangerous if not carried