AppleScript is for Macintosh automation; so scripts you write can automate tasks you would otherwise have to perform with the mouse and keyboard.
So what would you want to automate? The answer to this question falls under two broad categories: small tasks and big tasks.
The main difference between small scripts and big scripts is the amount of though and planning involved.
- When writing small scripts, you start out by … writing the script. As the scope progresses, you add more functions, you add more lines, and you go back to fix and debug until the script works.
- Big scripts require planning. You have to carefully consider the users, the environment, and the different triggers for tasks the system will perform. You have to deal with where the data for the script comes from, small graphical user interfaces, and return on investment for your script or script project — all the issues that can kill your efforts just as you start to get excited.
Automating Small Tasks
Small scripts are the way one usually starts to become familiar with AppleScript. AppleScript lest you easily create a script, test it, save it as an application, and start using it. This quick turnaround for truly useful utilities is part of the winning recipe that makes AppleScript so great.
tell applicatio "QuarkXPress 4.01" tell every page of document 1 set width of (every line box whose width < 0.25) to 0.25 end tell end tell
Automating Big Tasks
Although AppleScript doesn’t sweat the small stuff, it can be the base for large-scale custom integrated system. As far as what to automate, you could automate any task that has repeatable logic, and if the cost of automation is less than the amount of money you save — and it usually is — the task is worth automating. Repeatable logic is logic that can be applied successfully to similar, but not identical, subjects and that produces a predictable outcome, based on the uniqueness of the subject.
For example, here is a process that is not so suitable for automation:
Here is a better candidate for automation:
When you get a job from a client, you search for the client in the database to locate the job information. If the job is marked “urgent,” you e-mail the imaging room to expect it within ten minutes. You open the Adobe InDesign document and verify that all the fonts were provided. You make sure the document contains the number of pages indicated in the electronic job ticket; if it doesn’t, you make a note in the database and e-mail the client. When done, you make a copy of the “job” folder in the “archive” folder on the server, and you send another copy to the “in” folder on the production server. You repeat these steps for all jobs that arrived last night.
Now this is a process for which AppleScript is perfect. Besides having programmatic elements such as a repeat loop for applying the process to all jobs and some branching, the process itself s clear, is logical, and can be applied to any client job that arrives.
If you look more closely at the previous process, you can see that quite a few of the steps happen in software applications. The operator has to know ho to use FileMaker Pro for searching and entering data; how to use InDesign for checking fonts, pages, and so on; and how to use the Finder or moving folders. Controlling these and many other applications is one of AppleScript’s main strengths. AppleScript can give applications commands and get information from applications, such as retrieving the data in a FileMaker Pro record or the number of pages in an InDesign document.
AppleScript is also ideal for performing repetitive tasks. For instance, how would you like to show up at work one morning and realize that your job for the day is go through 200 TIFF images in a folder, add a black frame to each one, and export each as JPEG? Then, you must create a PDF file containing all the images, with four-up (which means having four impressions of similar size on a single printed sheet) and with the image name under each image. Does this sound like hard work? Your reward for a job Weill done just might be another folder with 200 TIFF images the next day …
Although not sophisticated, this process is repetitive. A script can do it for you while you take a walk to the cafeteria.
Where Is AppleScript?
From more than ten years now, every Mac that shipped with system 7.1.1 (also known as System 7 Pro) and all the following operating systems had everything it needed to use AppleScript — you didn’t have to do any special installs, you add hardly any configuration issues from Mac to Mac, and you received a basic array of scriptable applications that grew rapidly (and still does).
What’s truly remarkable about AppleScript is that most of the language’s power comes from the applications you automate. For better or worst, the level to which applications can be automated, and the ease in which you can include them in an automated solution, is largely up to the software vendor. It is up to the development team of every application to implement scriptability for any feature they imagining someone would want to automate.
As it stands, the very existence of AppleScript depends on the applications that support it. For commercial-software developers, making an application scriptable doesn’t mean simply checking a Make Scriptable check box in a Compile dialog box; rather, they have to spend hours of programming to make it happen and to do it well.
To make an application scriptable, the developer has to create a special terminology for each feature they want to make scriptable and one up with an object model for the application. That can add up to many hours and can’t be done as an afterthought. However, difficult, software developers see good return on their investment when the companies integrate their applications into automated solutions. This alone ties that application to the client and lowers the changes the client will dump their application for a competing product.
How do you write Scripts?
You can’t write and run AppleScripts from any text editor. To write Scripts, you need to sue a special script editor, which will allow you to write the script, check the syntax, compile the script, run it, and save it as an applet.
Note: An applet means the AppleScript code is wrapped with the minimal executable shell that allows it to run in a stand-alone form, just like any other application.
To start, you may want to use Apple’s own free tool, Script Editor. Script Editor is a little application that comes preinstalled in the
AppleScript folder in the
Applications folder and is ready to use with every Mac system. Script Editor has always been a bare-bones AppleScript editor, which makes It rather easy to figure out and leaves few places to get lost. Besides Script Editor, a few other AppleScript editors are available with enhance editing and debugging features.
As you’re writing a script, you can compile and run it right from the Script Editor. Even if you save it as a droplet or an applet, you can reopen, change, recompile, and run it right from the script window. This makes you scripts (and other people’s scripts, for that matter) easy to look at and try.
Where Do Scripts Reside, and How Do They Run?
Scripts can be saved anywhere! It is up to you where you want to save the scripts you create. This flexibility allows you to create your own super-organized script storage system-and, of course, it allows you to create a holy mess.
Some applications provide special folders, usually called
Scripts to place your scripts in so they will appear in that application’ special Script menu.
More and more software vendors realize that providing a special menu for scripts their applications, or at least paling some scripts in a
Library/Scripts folder (which will appear I the operating system’s Scripts menu) is more than just letting users create their own scripts; it also allows them to quickly add “features” to their applications that otherwise would take timely programming resources.
AppleScript File Formats
You can save scripts in several file formats, including as compiled scripts, text files, applets, and variations o these. Scripts are usually saved as compiled scripts, with the
.scpt extension. This format can be edited using AppleScript editors only. Although you write scripts using text and you can usually see the text when you reopen a saved script, the script is actually saved as special tokens that re interpreted by the operating system’s AppleScript component when the script runs.
You usually won’t notice this “what-you-see-is-not-what-you-saved” situation unless the script has some version issue or an application or scripting addition issue. What you have to remember is that the scripts you write, as discussed earlier, will be composed largely of terminology defined by scriptable application. An application can defined hundreds of keypad that you can include in your scripts. Some of these keywords are the names of commands and classes defined by the application; others are the names of command parameters and object properties , and so on.
For a script to compile properly, it needs the applications that are referenced in ti to be present, and in some cases it also needs the applications to be open. In fact, if an application referenced in your script isn’t present when you try to open the script, you will either have to give up until you install it or trick AppleScript into thinking some other application is the missing one. If you do trick AppleScript, you will have a hard time changing the application-specific terms you used in your script, since they will appear in their raw from inside double angle brackets instead of the easy-to-read English-like AppleScript text you’re used to seeing.
- For instance, a script that used the
copycommand in InDesign CS2 will show the following code when the application isn’t available:
So how can all that affect you and your script? The main reason why you won’t be able to see your code properly is that the application, scripting addition, or application’s AppleScript plug-in isn’t available.
Some applications, mainly from Adobe, don’t incorporate their scripting terminology into the actual application but rather have a plug-in manage all the AppleScript-related activity. This will be a noticeable issue only if the application doesn’t ship with AppleScript but rather leaves you to activate it. Otherwise, it makes no difference.
Rest assured, however, that the actual script is fine. The next time you open it with the target application available, it will return to its old self and display properly.
As mentioned, when you save a script, you can specify its file format. Three main kids of script files exist: regular compiled scripts, which are the native AppleScript file format; plain-text files; and applets. On top of that, OS X has a new option for saving compiled scripts and script applets as bundles. Bundles are folders that appear and behave as files, which is great when you want you script to appear as a single unit but actually conceal related files as part of it. You can read more about bundles in Chapter 22.
For most purposes, you script will start as text entered in Script Editor but will be most likely saved as a compile script file. At any point you can save the script as an applet and place it any where for use. You can use a script in its AppleScript format state (nonapplet files are saved with the
.scpt extension) in one of the following ways:
- If the script is loaded into another script, you an use it in an application’s Script menu where available (InDesing, BBEdit, the Fidner, and so on);
- You can execute it fro the Unix command line using the
osascriptcommand; or you can simply run it from Script Editor; or
- You can simply run it from Script Editor.
Also, two similar application-based formats exist: apple and droplet.
- A regular applet runs the script when you double-click it, and unless it’s saved as “stay-open” applet, it quits after the script is done.
- A droplet can respond to files being dropped on it. This is useful for a script that processes files or folders. Chapter 22 discusses all these variations in detail.
When saving a script as an applet, you can’t specify whether you want it to be a droplet or a normal application. Instead, AppletScript determines this based on the contents of your script. Basically, if you tell AppleScript what to do in case some files are dropped on it, It will become a droplet; otherwise, it will be a normal application.
So, why then would you ever save a script as text? Well, you might do this for a few reasons. First, saving and opening scripts as text doesn’t require that the script be compiled. This is useful when something stops you from compiling the script, namely, an error in your AppleScript text. Second, when you send scripts t one used on other Macs, you should try to send them both as compiled scripts and in the text format. Getting the script’s text allow the other person to open the text version of the script in the Script Editor and compile it on the Mac on which the script will eventually run. This gives the script a chance to see where all applications are located on the new Mac.
Another format-related option you have is to save a run-only version of the script. This will allow the script to run, but no-one will be able to read it. Distributing a script as a run-only version is useful when you want to protect the rights to your proprietary code.
The Golden Triangle: AppleScript Language, Application Scriptability, and the Scripts You Write
You learned abut the role of other applications’ scriptability earlier. Now how does that scriptability work with the AppleScript language and with the actual scripts you write?
All this is very much like any other spoken language, say English. The base language has verbs, nouns, adjectives, and some rules. You can use English to talk, but what you say has to have some context in order to be interesting and for you to relate to others. This is where different subjects come in, and I mean big subjects — subjects that have their own lingo.
It’s the same with AppleScript: you can use the
make command along with the
document class which defined by most applications, but simply writing
make document has no meaning unless point it to an application that knows what to do with it. And this application will lave its own way of dealing with that command, which is different from the way another application was told to deal with it.
Of all these features, perhaps the most exciting task you can perform is to define your own commands and objects. You define commands by writing handlers, and you define objects by bundling those handlers along with some properties in script objects.
Let’s see whether you can get into the spirit of procreation. What if your script’s purpose is to automate the creation of a catalog? Say you have a sequence of commands, and starting at the top and going down, they tell different applications what to do. First you have some database commands for gathering information, and then you use some AppleScript commands to clean and format the text, add some dollar signs to numbers, and so on. Next, you have some repeat loops and conditional statements (
if, then) that dump all the text into the page-layout program.
OK, that’s not fair. When you start, you just want to get things done, and you don’t care really how. Although writing scripts that way is good for shorter scripts and certainly OK when you’re just starting, you should have an idea of how you should be writing scripts once you get over the initial euphoria that overcomes you every time your computer does something for you and you have to run to get a cup of coffee just so you can tell everyone that “the script did that by itself while I … while I … was getting a cup of coffee!”
Teaching the Script New Commands
So how would you make the orderly chain of commands different, and why? The second question has a few answers. For one, short scripts should remain as a collection of statements, without the use of handlers. Once you start working with longer scripts, scripts containing handle res are better organized, are easier to understand and debug, and are more flexible. They’re easier to change, and making a change can mean improving the way multiple scripts run. Also, your code bees more reusable, which is a major part of being a profitable scripter.
And how are better scripts written? Although an entire chapter is dedicated to healthy scriptwriting practices later in the book (Chapter 23), this section touches upon the ‘better script” model in general terms.
Let’s start with redundant code. Redundant code is code that performs nearly identical operations in many places in the script. For instance, in the catalog automation script, you may have some code that goes to the database and gets some information from a field, say the price of an item. Then the script adds a dollar sign to the number and inserts it in a named text frame in the page-layout application. These operations strung together take up, say, thirty lines of code, and they repeat in about five places in your script.
You can make the script much better by defining your own commands to handle each of these tasks! How about a few commands that go by the names
This command you write yourself is called a handler (or a subroutine). It is placed in a special wrapper right inside your script (for the most part) , and its functionality is available from anywhere in the script.
Calling handlers is similar to asking someone for a cup of coffee; with a short sentence, you asked them to perform about 20 separate operations.
When you’re just starting to script, creating subroutines can be added complication for which you may not be quite ready. Late, however, writing and calling subroutines can become some of the most important tasks you will do. Organizing your scripts with subroutines makes them easy to read and edit. It allows you to write special code that can be later reused in other scripts.