An Introduction to AppleScript on Mac OS X
12/11/2001Look out everyone--AppleScript is coming back and coming back big!
AppleScript has been one of the most overlooked, cool technologies lurking in the Mac OS since 7.1, but it's usually hidden in your Apple Extras folder waiting to be discovered. Now with Mac OS X, it has a new home in the Applications folder, indicating that Apple no longer considers it just an extra. AppleScript has a bright future, and there's no better time than now to take advantage of this amazing technology.
"Why," you might ask, "should we once again see what AppleScript has to offer?" I can give you three reasons: Cocoa, Unix, and AppleScript itself.
The Cocoa advantage
Creating a Scriptable Application has never been easier, and Cocoa is what brings this into reality. Cocoa is an object-oriented framework that holds information and the methods that access this information within objects. Cocoa applications are really just a collection of these objects working together to accomplish a task.
|
Related Reading
|
Each of these Cocoa objects and their methods can potentially be accessed through AppleScript, and many of the core scripting commands are gained "for free." Planning for scriptabilty with Cocoa leads naturally to good program design. Even better, if you have an existing program written using Cocoa, adding AppleScript support is probably easier than you think.
The Unix way
Unix is usually seen as an OS, but one of the strengths of Unix is the ability to combine together many small programs to build a larger program that does what you want, all from the command line.
So, you can have one program read the contents of a file, send it to a stream editor to replace one string with another, and then break it into fields and store those fields with formatting in another file. Typically, Unix does this with very small programs that have a very specific purpose (i.e., to read the contents of a file); however, most programs on Macs and Windows are more monolithic, taking care of many functions that are usually related to each other (browsing, sending email, word processing, transferring files, etc.).
Since Cocoa typically has objects as the basis of these functions, scripting will allow access to those objects and their methods and data individually. Now a user can combine them with functions from other apps, the OS, and AppleScript itself, making them work more like the Unix model and giving them great flexibility and power.
AppleScript X
AppleScript has matured along with the Mac OS, and AppleScript 1.7 found in Mac OS X 10.1 allows for new ways of doing things that are incredibly convenient.
Many applications that come with Mac OS X are already scriptable, including the Finder, iMovie, Internet Connect, iTunes, Mail, Print Center, QuickTime, Sherlock, and Terminal. Also, Mac OS X has made running scripts incredibly easy by adding Toolbar scripts and an optional Script Menu that lets you run AppleScripts, Perl scripts, and shell scripts from anywhere. With these additions, starting a work flow is as easy as navigating through your files and clicking a button or selecting a menu item.
Additionally, AppleScript can now access Web Services. These are XML-based services that use SOAP or XML-RPC to send information to your scripts over the Internet. This gives you access to updated information or live feeds of data, like stock quotes, temperatures, and currency conversions, among others.
If this isn't enough to reaffirm your belief in Apple's commitment to AppleScript, Apple has just released AppleScript Studio, which makes AppleScript a peer language with ObjC and Java for building Cocoa applications, including front ends built with Interface Builder. Clearly, AppleScript has never been better. If you'd like to see some of this for yourself, go to Apple's AppleScript Web site and take a look at the Seybold 2001 AppleScript demo. Very cool stuff.
AppleScript for everyone
|
| |
If you haven't used AppleScript before, you will be happy to hear that it compares very well with other scripting languages on other platforms. Windows uses Visual Basic (VBScript) as the basis of its scripting support, whereas Linux or other Unix OSes usually use shell scripts or Perl. While these are not the only options for these OSes, they are the most common ones. Each scripting system has its own advantages and disadvantages, but in my opinion, none are as accessible to the non-programmer as AppleScript.
AppleScript uses a nice, human, language-like syntax that is user-friendly and easy to read and understand. It even supports local dialects, so you can write scripts in English or French or German, for example, adopting that language's syntax and idioms.
An example script (from Apple) to hide all Finder windows looks like this:
tell application "Finder"
if the (count of windows) is not 0 then
set collapsed of every window to true
end if
end tell
AppleScript supports record-ability, where a user's actions can be captured as a script, automatically. AppleScript can work between Native and Classic applications on Mac OS X 10.1 and between different machines via the Internet. It has a gentle learning curve, but it can scale very well to accomplish advanced tasks. In all, this means that AppleScript has the potential to be used by not only hardcore Mac programmers, but by everyday users too. Add this ease of use to Cocoa's ability to access individual functions within programs, and you have the makings of something great.
Your first scriptable Cocoa application
Hopefully, you're now a believer in scripting and can't wait to add it to your applications. Just to show you how easy it really is, I'm going to show you how to build a scriptable application in four steps.
- Open Project Builder and create a new Cocoa application named "ScriptableApp".
- Build the project without modifying anything by clicking on the Build Active Target (Hammer) button.
- Open the Info.plist, available by opening the Products folder and then the ScriptableApp.app, and add the following to the end of current list of keys:
<key>NSAppleScriptEnabled</key> <string>YES</string>
Make sure it is formated like the other keys and comes before the closing</dict>tag.

Figure 1. Adding the NSAppleScriptEnabled key to ScriptableApp's info.plist
- Save and rebuild your application. That's it!
You have now added support for the Core Suite of AppleScript commands to this application.
You can verify this by opening up Script Editor inside your AppleScript folder in the Applications folder and selecting "Open Dictionary..." from the File menu.
Since the ScriptableApp has not been installed, it's still located inside your project's build folder. Click on the Browse button and navigate to the ScriptableApp's project folder and look for a build folder. Inside it you should find the ScriptableApp.app. Select it and you should see the ScriptableApp launch and a ScriptableApp Dictionary window come up with the Standard Suite and Text Suite on the left side of the window. Clicking on an item in the left-hand pane will bring up the syntax for that item and a brief description of how that item is used.

Figure 2. Opening ScriptableApp's Dictionary
Now, we haven't added any text objects to our application, so the Text Suite doesn't really do anything in this application. Also, some of the Standard Suite commands, like save, print, move, delete, make, duplicate, need to have more code added before they "do the right thing," but we can access many of the commands and set and get values for different elements right away.
I've written a script that shows off a few of these commands and some of the things we can do "for free." Download ScriptableApp.sit and open it in Script Editor. Run it and review some of the commands for yourself. You might also look through the dictionaries of some other applications, and review the example scripts that come with AppleScript and that are also available on Apple's AppleScript Web site.
Aim of this series
For the rest of this series, I'm going to focus on adding scripting capabilities to Cocoa applications written in ObjC first. I'll also delve into localization, creating GUI-less applications, and native scripting additions.
If you are unfamiliar with ObjC or Cocoa, please check out Mike Beam's excellent series on Cocoa programming. I won't be using advanced examples at first, but casual knowledge of both will be helpful.
Cocoa applications can also be written in Java and we will see how to add support for scripting in those applications. I'll also look at AppleScript Studio, available in the very latest version of the Mac OS X development tools, and see what it brings to the mix.
Next time
In the next article, we will talk about how Cocoa supports scripting at the object level and go into greater detail about the Core Suite and Text Suite we saw in our ScriptableApp example. We will also talk about how to best design programs that make adding scripting easy. See you then.
Brad Dominy is the head of Neoki, LLC, a small web design firm located in Chicago, IL.
Return to the Mac DevCenter.
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 12 of 12.
-
Terrible
2003-12-25 20:53:02 anonymous2 [Reply | View]
I don't know what it is about tutorial writers these days, but the purpose of tutorials, especially the FIRST tutorial, is to get people up to speed so that they can do simple cheesy applications and start exploring. For goodness sakes, look at a HelloWorld Java/C/or even Flash tutorial when writing tutorials.
-
Randomize Mail app signatures with AppleScript
2003-04-08 15:58:47 anonymous2 [Reply | View]
I think an example of how to extend Mail App with AppleScript to be able randomize signatures would be great. This would be useful as a tool and as an example. It seems Mail App's plist stores signatures as RichText and this makes it hard to do simple things with your sig files:(
-
Ready for next article.
2002-02-13 05:41:04 benatong [Reply | View]
I'm right in the middle of learning scripting, by creating a trivial test application. I'm and old NeXT programmer so the ObjC stuff is old hat, but AppleScript is completely new to me.
Trying to follow the developers scripting doc's is almost impossible, when you don't have a simple example to reference for the basic's
Thanks
chuck
-
comment on the next article for SETI
2002-02-08 17:02:57 psheldon [Reply | View]
Berkeley has a bandwidth cap which my be transcended by use of a high speed cache pass of data downloads from SETI. sl-doubleclick-7-0-0-t3.sprintlink.net (pretty sure about the last "nk.net") but DNS nameservers know it better as 144.232.246.2 might take the pass. They were stuck a moment ago so I couldn't get through the links to leave this message because my netscape stalled trying to load the ad graphics.
Evidentally, the ad community needs a t3... cool.
I'm a romantic hoping for something serendipitous here because that is what SETI is about and what the world vitally needs cf Davies, but I won't be more specific here and have gone through other channels on that one.
I suppose Berkeley is having experts work on this, but they may be embroiled without informal channels, as they say in "The Psychology of Computer Programming". All I'm gonna say are the magic words for someone wise, beware the tradgedy of the commons, the classical management failure or "let's roll". Little steps Elly, little steps... Contact anyone?
-
can it do GUIs for shell apps?
2002-01-29 19:17:07 frankie1969 [Reply | View]
Something I'd really like to do is make clickable (and possibly drag-droppable) front-ends for Unix shell tools. I know about Wilfredo's DropScript, but I also want the output to appear in a standard text window. Is this (trivial|workable|painful|inconceivable)?
-
Timeline
2002-01-22 08:34:41 salamon [Reply | View]
As a new Cocoa applications developer I'm definitely looking forward to your next article. Any idea when it will be ready?
I've used AppleScript for a number of projects myself, and I consider adding full appleScrpt support (including recording!) to my applications to be a very high priority.
Thanks for doing this series!
Andrew
-
Scripter morphing Programmer
2002-01-18 09:58:50 carpenter-b [Reply | View]
I am a conventional Applescripter. I got hired on as a audio/video specialist for a distribution company, put in front of a Mac and told to learn to make it work. Learning Applescript from tutorials and books for dummies like me, I was able to get an automated system for encoding audio, video, preping images for the web and getting all this into a kiosk as well. I have been able to learn Applescript in a classroom as well. I have no training in any computer language nor in the structure of programming.
What I want to learn to do with applescript is what applescript is made to do. Getting applications to work with each other and getting then to manipulate data into something that will be a finished product.
I saw the QT video presentation of Sal, using FileMaker Pro, imaging software and Quark to create a catalog for Real Estate. Wonderful! That is what I want to do as well. And I want to make an application out of all my work. But my enviroment variables are not conventional or standard by any means.
Java, SQL, AIX, JDBC, AS/400, WinNT, MQ series and IBM's DB2 have been brought to the table. Not to mention, Web servers, FTP, and all kinds of other servers. I need to find a way to get my enviroment involved. In other words, real programming. All my work is devalued because it is scripting.
OS X and Applescript Studio have to be my hero.
-
Wanted: AppleScript sans ObjC info
2001-12-21 10:47:09 reggoboy [Reply | View]
I'm a Mac owner since 1984. But I'm a professional programmer. However, though I've done lots of Windows and Unix programming, I've never done any on the Mac. I've always found it rather inaccessible, with strange development environments and the need to but a bookshelf of Inside Mac books even to write a Hello World program...
My hope with AppleScript and the new Studio is that it will allow me to make full apps without needing to know ObjC, especially since it has full access to Cocoa. I don't want to touch ObjC or Java. On Windows, VB is basically an environment with a bunch of widgets that you can script with a simple scripting language. That's what I want your article series to tell me how to do, presuming AS is capable of that. I want to know how to make apps from the ground up with AS, and that's it. Hello, World would be a nice place to start.
Thanks!
Dave
-
Beam
2001-12-17 17:25:38 suthercd [Reply | View]
Not usually this verbose, but followed the link to the Cocoa introduction by Mike Beam.. looks like what I was looking for.
C
-
First article
2001-12-17 17:02:22 suthercd [Reply | View]
Applescript is very familiar- Cocoa and C++ Object programming much less so. The initial book from O'Reilly on Cocoa was more of an overview and did not begin to describe the underpinnings.
The Studio mailing list that has been set up on the Apple boards shows by the messages sent that the people who are able to quickly use Studio have considerable experience outside of Applescript.
The exercise in the article was very helpful as well as the script to download. Looks like the learning curve is initially steep- hope you can provide a guide to learn to use Studio as quickly as practical
Craig Sutherland
-
Dear Santa,
2001-12-17 09:34:59 o1eal [Reply | View]
Looks like a great series you've got underway. Though I'm not sure it fits into the aim of the series as you've defined it, here's what I'd like to see:
1. As a self-taught AppleScript programmer, I hunger for insight on the most intelligent way to accomplish a given task. Too often in the world of AS, we're told we can do things "any way we want." This flexibility is great, but it's also great to hear the perspective of those who understand programming in a broader sense. i.e., what factors should I consider in *choosing* among the many options?
2. I'd like some clarification on your comment that Cocoa allows you to use only a small part of an application in a script. I thought that was what I'd been doing for a while...loading Outlook Express, getting a message from it, copying that message to a Filemaker database etc. How does Cocoa enhance this?
3. What can I do to move into Java or Cocoa programming most easily? What's the best approach for someone with a fair amount of AS experience, but no formal training in programming?
Thanks for what you're doing. Judging from the first article, this promises to be a most enlightening series...
-Pete







I run: OSX10.4.5 on a powerbook G4 - 1.5GHZ. What am I doing wrong? I can`t get anywhere... I have installed X-Code and really want to learn!
Please do advice me how to get by this problem!
Thank You!