AppleScript Introduction

Since 1994, when System 7.5 was introduced, the Mac OS has included a scripting system known as AppleScript. This mechanism, more precisely known as Apple’s Open Scripting Architecture (OSA), lets you send instructions to the Finder and any other scriptable applications.

To use AppleScript, you must first create a script in a script-editing application, such as Apple’s Script Editor. When you run such a script it executes a sequence of operations, working in the same way as a macro created in macro applications such as QuicKeys or KeyQuencer.

  Scripting Languages

Script Editor can be used with any OSA-compliant language, although AppleScript is the easiest to understand. Other languages include MacPerl, which is a form of Perl (Practical extraction and report language), and Tool Command Language (TCL), both used on Unix and Mac OS X platforms.

Those used to scripting on the Web are accommodated by Late Night Software’s OSA-compliant version of JavaScript. In addition, UserLand offers Frontier, a free package with support for the AppleScript language, as well UserTalk, an OSA-compliant language similar to C or Pascal.

Advantages of AppleScript

AppleScript uses software that already exists in the system, which avoids problems introduced by third-party software in the Classic Mac OS. In addition, AppleScript instructions can be sent directly to to the Finder, ensuring that items shown on the desktop are immediately updated.Best of all, you can create numerous customised scripts, but only if you’re willing to explore the world of programming. If you are, you’ll find the experience both frustrating and rewarding.

Disadvantages

The operation of a script depends on the responses given by each application, the Finder and each scripting addition (see below). If these aren’t the same as when the script was first created you’ll have problems. This means that you must always check the version numbers of your software to see if it needs updating. Failing this, you may have modify or trash some of your scripts.

AppleScript’s original user interfaces are primitive, providing a standard dialogue box (with up to 256 characters, three buttons, an icon and optional fixed-size data-entry box), an Open dialogue (with a customised prompt message but fixed button names) and a Choose Folder dialogue. Sadly, you can’t choose files and folders in a single dialogue and you can’t select more than one item, although there are several third-party additions and packages that alleviate these limitations.

AppleScript in Mac OS X

Mac OS X incorporates a improved version of the AppleScript mechanism, allowing you to use many of the scripts you may have previously created in the Classic Mac OS, as well as more advanced scripts produced in the newer system. However, there are a few significant differences in the AppleScript language of the two operating systems, which may cause some older scripts to fail. And those scripts that refer to obsolete system components are doomed to go horribly wrong.

  The ScriptingAdditions Folder

This folder is inside the Library folder in your computer’s System folder. It contains special files, not surprisingly known as scripting additions. These usually provide extra AppleScript features, such as additional commands.

  Scripts Folders

Scripts for Mac OS X are normally kept in at least two places: /Library/Scripts and ~/Library/Scripts. All of these scripts can be launched from the menubar using Apple’s Script Menu (see below). However, some applications have their own script-launching system, with the related scripts often kept in a separate Scripts folder with the application.

Ideally, the scripts in the Scripts folder of your home directory should be organised by means of subfolders according to their function or related application. For example, those suitable for use with any program are best put in a folder called Universal Scripts whilst those that implement ‘folder actions’ should be placed in a folder named Folder Actions Scripts. And if, for example, you have scripts for BBEdit and GraphicConverter, you should put these in a BBEdit Scripts folder and GraphicConverter Scripts folder respectively, again inside the Scripts folder.

AppleScript in the Classic Mac OS

Assuming that you’ve installed AppleScript using the Mac OS Installer, you should find the AppleScript extension in the Extensions folder, which is inside the System Folder. If it’s missing, just run the Installer again and use Custom Install to add the AppleScript package.

  The Scripting Additions Folder

To use AppleScript you must also have the Scripting Additions folder, complete with scripting addition files, in the System Folder. These files are essential, as they’re used by most scripts.

  The Scripts Folder

The Scripts folder in the Classic Mac OS usually resides in the System Folder. However, applications with their own script-launching mechanisms often have their scripts in a separate Scripts folder along with the application.

As with Mac OS X, the Scripts folder should be organised in an application-by-application basis, so as to suit script-launching utilities such as OSA Menu (see below). The folder can look like this:-

although only the Folder Action Scripts folder is present when you first install AppleScript. Scripts in the other folders are only available in OSA Menu when the appropriate application is at the front, while scripts in the Universal Scripts folder can be used at any time.

  Using Script Editor

The Mac OS comes with Script Editor, a simple editor that works with any OSA-compliant language. Although perfectly adequate, it lacks a Find command, doesn’t support ‘drag and drop’ and, in older versions, allows no more than 32 KB of text. Other editors include Script Debugger (Late Night Software), Scripter (Main Event Software) and the Frontier editor.

Script Editor presents two panes, a Description window containing information about the script and a lower window containing the script itself, as shown below:-

This particular script, which has the same effect as selecting About This Computer under the Apple menu in the Classic Mac OS, was entered manually. However, you can also create a script by clicking on the Record button, performing a series of operations and then clicking on Stop. Unfortunately, this only works in the Finder or in applications that are scriptable and recordable. If in doubt, check the documentation supplied with your applications.

Having recorded a script, press Run to test it and then modify as necessary. When you click on Check Syntax the script is verified against the AppleScript terminologies stored in the relevant applications and scripting additions. If your script passes this test the text changes into compiled form, where certain keywords appear in bold, as shown in the above example. The preferred font for a category of keyword can be changed under Edit ➡ AppleScript Formatting.

Your final script can be saved as a text file, as a compiled script or as a self-contained application. When you do this, Script Editor tries to compile the script, if it’s not already done so, and offers you the chance to save it as a text file if it fails.

Compilation

As mentioned above, clicking on Check Syntax forces AppleScript to compile a script, checking as it does your instructions to the applications and scripting additions that it employs. The workings described here refer specifically to the Classic Mac OS, although OS X uses a similar system.

If a scriptable application has already been used AppleScript gets the necessary terminologies from a cache, which is cleared whenever you stop using your chosen script-editing application. If a terminology isn’t in the cache, AppleScript goes to the scsz resource in each scriptable application. If this has a flag saying Always send me a GetAETE event the appropriate application is launched and is sent a GetAETE event. This, by the way, explains why some applications are automatically launched whenever you try to open their dictionary (see below), whilst others stay inactive

If the application doesn’t respond to the GetAETE event, AppleScript simply extracts the terminology from the aete resource in the application and moves on. Those applications that respond to the event, such as BBEdit and QuarkXPress, usually send extra information to the editor, such as the terminologies for plug-ins or other extensions. AppleScript then takes the various tokens and organises them into a script resource and finally returns both this and the styled text to the editor.

Following compilation, the text in your script may alter. Sometimes this dramatic, particularly if you’re editing a script that was originally created on a machine with a different version of AppleScript. You can also get incoherent strings of characters should a necessary scripting addition be missing or where an application doesn’t support a specific instruction.

Dictionaries

The terminology used in an application or scripting addition is described in a dictionary. In Mac OS X this can be contained in a separate dictionary file, which is identified by a filename extension of .asdictionary, whilst in the Classic Mac OS it’s stored as an aete resource. You can check the commands that are available within a particular software component by selecting File ➡ Open Dictionary in Script Editor and then choosing the file of the required application or addition.

If you regularly need to open the dictionary of an application you can use a script of the form:-

tell application "Script Editor"

  launch

  activate

  open (path to application "application_name" as alias)

end tell

where application_name should be replaced by the name of your chosen application. This particular script also launches Script Editor if it’s not already running. If the location of the application file isn’t already known you’ll have to find the file manually when you first run the script.

  Using Scripting Additions

A scripting addition contains resources that add features to the AppleScript language. Some add instructions whilst others add coercions for converting one kind of AppleScript value to another. A few, such as Akua Sweets (AKUA Interactive Media AG), have both. If you’re unsure about coercions, just remove any third-party additions and try the script again.

Each addition is known as an Open Scripting Architecture eXtension (osax), whilst a collection of such files are known as osaxen, a term devised by Jon Pugh and Donald Olson. To quote Jon Pugh: “osaxen are not limited to scripting. If you have AppleScript installed and any program sends an event or uses a coercion defined in an osax, it will get called. Their use is not limited to AppleScript. However, AppleScript must be present for them to get loaded and used.”

Problems

Sometimes a script created using the Record feature doesn’t run. The answer, according to Mark Alldritt, is to open it in Script Editor and and re-compile the script by making a small change, such as adding a space to the end of a line and then clicking on the Check Syntax. Having done this, you can save the script and it should work normally.

A similar problem occurs when a script can’t locate an application that’s to be controlled. This causes a dialogue to appear, asking you to find the application’s file. If a script persists in doing this you should open it in Script Editor, select Run, go through the entire process and then select Save. Having done this, the problem shouldn’t return.

Stopping scripts that have gone horribly wrong can be difficult. If the script is running in Script Editor, just click on Stop and it should grinds to a halt. Similarly, you can halt a droplet by pressing -., or an applet with Stay Open selected by pressing -Shift-Q. Unfortunately, when running a compiled script from OSA Menu or OtherMenu (see below) it isn’t easy to stop, apart from forcing the Finder to quit or by waiting until the script ‘times out’, usually after three minutes.

Troubleshooting

Despite your best efforts, some scripts will fail. Usually, this is due to a simple (or sometimes difficult) scripting error, although it can also be caused by one of the files that script uses. For example, a single script can send instructions to the Finder and to several applications and scripting additions. If any one of these responds unexpectedly the script fails.

The following groups of scripts can go wrong:-

Scripts that send commands to applications:

Check that your applications are the versions required by the script. If they are, launch Script Editor and open the suspect script. Now choose File ➡ Open Dictionary. Assuming each application appears in the dialogue (which usually indicates that they’re scriptable) you should be able to select them in turn and check the available instructions.

Scripts that use scripting additions:

Check that your scripting additions are the same version required by the script and that they’re present and in the correct location. Now choose File ➡ Open Dictionary. Assuming the required additions appear in the dialogue (which usually indicates that they provides instructions, not just coercions) you should be able to select each one in turn and check the available instructions.

Scripts that use the Finder

Problems in Mac OS 7.x can indicate that the Finder Scripting Extension isn’t present. You should run the System Installer and try using Custom Install to reinstall AppleScript.

Scripts that don’t use applications or scripting additions:

Try replicating the action of the script manually. If the same thing happens your Mac OS may be faulty or an additional extension or control panel may be causing problems. If all is well you should double-check that the offending script really doesn’t use a specific application or scripting addition.

Scripts of every kind:

If all your scripts don’t work there’s something wrong with your machine. In the Classic Mac OS, try running the Mac OS Installer and use Custom Install to reinstall AppleScript.

Non-scriptable Applications

Some applications don’t support AppleScript or lack the required instructions, in which case you may have to ruse a macro application. Examples include QuicKeys (CE Software) and KeyQuencer for the Classic Mac OS (Binary Software), both of which can be controlled via AppleScript.

Other Classic options include Menu Events (Ross Brown), which controls application menus, or Akua Sweets (AKUA Interactive Media AG), an addition that gets to an application’s user interface. Last, but not least, there’s AutoType (James Davis), a scripting addition that simulates key presses, although this doesn’t work with OSA Menu or OtherMenu (see below).

Script Files

A script that you’ve created in Script Editor can be saved in any of the following forms:-

  Text

This kind of file contains just the script as plain text and can only be run from within Script Editor or another editing application, or launched from the (Script) menu of an application that supports scripts in this form. Fortunately, this format is ideal for storing partly-completed scripts or scripts that can’t be compiled at the present time, perhaps because of a missing application or scripting addition.

  Compiled Script

Most scripts come in this kind of file, which can be run from within an editor such as Script Editor or launched from a (Script) menu, either in an application that supports compiled scripts or by using additional software (see below).

Unlike a text file, the contents of a compiled script can’t be viewed in the scripting language until the necessary applications and scripting additions are available. Should an application be absent, you’ll be asked to locate its file. If you’re desperate open a script and don’t have the correct application you can choose another program, although this can be unpredictable and you certainly shouldn’t run the script.

Depending on a script’s origins of a script or the version of Script Editor used to create or modify the document, a compiled script can be stored as a bundle, in the data fork of a script file or in the resource fork of a script file, as described below.

Script Bundle (Mac OS X only)

This preferred form of script, which works in Mac OS X but not in the Classic Mac OS, is really a disguised folder containing various files, including a separate document for the Description text. Scripts of this kind can be created using Script Editor in Mac OS X 10.3 or higher, although older resource-fork files can also be produced with this particular system.

Script in Data Fork (Mac OS X and Mac OS 9)

An iterim form of compiled script, as produced by Script Editor in Mac OS X and in some versions of the Classic Mac OS. In these documents, the compiled script is kept in the data fork of the file, allowing the script to be used over the Internet. However, the Description text is stored as old-fashioned styl and TEXT resources, which means that this information is lost in such a transfer. Fortunately, this isn’t really a problem since the text can also be included in the body of the script.

Script in Resource Fork (Mac OS X and Mac OS 9)

This form of compiled script is usually generated in the Classic Mac OS, with the script itself stored as a scpt resource in the file, whilst the Description text is in styl and TEXT resources. Unfortunately, all of these resources prevent the information in the document from being sent directly over the Internet.

  Applet

An applet is, in effect, a stand-alone application. Typically, this kind of file is used for simple operations that don’t interact with other files. For example, you can create an applet that puts up a dialogue saying Do you want to Shut Down? and then shuts down your Mac if you click OK.

Applets produced by different versions of the Mac OS come in three types, as described below. Together with variations in supported AppleScript commands this can prevent some applets from working.

Application Bundle (Mac OS X only)

This preferred form of applet, which works in Mac OS X but not in the Classic Mac OS, is really a disguised folder containing modern Cocoa-based code, complete with a separate file for the Description text. Scripts of this kind can be created using Script Editor in Mac OS X 10.3 or higher, although, at the time of writing, older non-Cocoa applet files can also be produced.

Application (Mac OS X and Mac OS 9)

This kind of applet, produced by Script Editor in recent versions of Mac OS X and some versions of the Classic Mac OS, contains Carbon code in the data fork, for running under Mac OS X, sometimes with 680x0 code in the resource fork, for running under the Classic Mac OS. The lack of carb, spsh and WPos resources, as found in older applets, doesn’t seem to be a problem.

Application (Mac OS 9 only)

This type of applet, produced by Script Editor in older versions of the Classic Mac OS only has 680x0 code in the resource fork, forcing it to operate under the Classic environment in Mac OS X.

  Droplet

This is a special applet that can process a collection of files or folders that are dropped onto it. It can also be scripted to work as a standard application, in which case the items for processing can be selected via a standard Open dialogue.

Running Scripts

With suitable software you can launch scripts from any application, although a script’s behaviour depends on whether it activates another application or needs an open document in that application. For example, whilst using Tex-Edit you can run a script to operate in AppleWorks, which should activate the latter, bringing any open documents to the front.

Mac OS X

To take full advantage of scripting in Mac OS X you must install Apple’s Script Menu by locating the item called Script Menu.menu and double-clicking it or dragging it onto the menubar. A new (Scripts) menu should then appear towards the right-hand end of the bar, allowing you to open your Scripts folder or run any of the scripts that it contains.

Classic Mac OS

Scripts can be launched in the Classic Mac OS using one of the following four methods:-

  1. OSA Menu

OSA Menu (Leonard Rosenthol) is an extension that lets you run compiled scripts from a (Scripts) menu in the menubar, employing the Scripts folder in the System Folder, as described above. Scripts with special filename endings can also be launched by pressing keys. For example, a script ending in \H appears with -H in the menu and is triggered by this key combination.

  2. OtherMenu

OtherMenu (James W Walker) is an extension that also provides an extra menu at the right-hand end of the menubar. This includes all the features found in the standard Apple menu but with the ability to open compiled scripts, FKEY resources and other items through a hierarchical menu.

The menu provided by OtherMenu doesn’t normally change when you switch between applications, although it can be configured to do so. You can even use the menu whilst a dialogue is waiting for you to make a response. Unfortunately, OtherMenu doesn’t employ the backslash naming system for setting keyboard commands, although it can be controlled in conjunction with KeyQuencer.

  3. CMScript

CMScript (Michael Schürig) is a contextual menu module for Mac OS 8.x or higher that lets you run compiled scripts from contextual menus. It uses a Contextual Menu Scripts folder, inside the Contextual Menu Items folder within the System Folder. This contains a Finder Scripts folder for scripts used in the Finder and a Universal Scripts folder for scripts used in all applications.

As with OSA Menu, you can add extra folders (or aliases of folders) for each application, such as AppleWorks Scripts or Tex-Edit Scripts. You can also keep your scripts in another folder, create an alias of it called Contextual Menu Scripts and place that in the Contextual Menu Items folder.

  4. Applications

Some applications include have their own (Scripts) menu in the menubar, so you can launch scripts from within the application, although this is usually less flexible than OSA Menu or OtherMenu. The scripts go in a special folder, often in the same folder as the application itself. In some instances you may have to relaunch the application before the menu appears.

Running Finder Scripts from Menus

Some scripts can be used to process the files or folders that are highlighted in the Finder. However, this kind of script should be used with care. For example, if you select the startup disk and run your Trash Selected Items script while in AppleWorks you could put all your files in the Trash.

To be on the safe side, don’t make such scripts available from application menus. Also, with Script Menu or OSA Menu, they should be put in the Finder Scripts folder. Alternatively, you can modify each script so as not to activate the Finder or to process any selected items while you’re in another application. Or you can change such scripts to give a warning.

References

MacScripting FAQ, Fred Terry

©Ray White 2004.