Why, when people were trying to get me to switch from Windows to a Mac, did no one tell me about AppleScript?
Sure, a stable OS with Unix shell access and a sophisticated UI are nice. But a scripting language that lets me automate tedious tasks and hike my creativity-to-boredom ratio? How come I never heard about that?
“It’s the hidden secret,” said Sal Soghoian, co-author of Apple Training Series: AppleScript 1-2-3 and Apple’s product manager for automation technology. He added that it rarely gets talked about.
AppleScript’s appeal is that it can control both your operating system and your applications, easily passing information among them. Soghoian estimates that four out of five “top-tier” Apple customers use AppleScript for serious automation — his examples include The New York Times generating daily stock charts and software developers testing applications.
Even Microsoft uses it, he says (for work on developing Office for Macintosh).
But AppleScript is also well suited for the desktop. You can use it to set your system to boot up with certain apps open in a particular way, right down to the size, location and content of each window. You can batch process files, rename and resize multiple images, or fetch Web pages and manipulate the results. You can connect to network servers and even create a simple database.
After a few months on a Mac, I wrote a script that copies data from a weekly report I get as a PDF, and formats it for insertion into a spreadsheet. This saves a boatload of tedious cutting and pasting. Another script pulls data out of our Web analytics tool and formats it for our home page “popular right now” box. Another one reads a text document and inserts the article information into proper fields of our content management system, saving more cut-and-paste operations.
It’s also extremely easy to share AppleScripts with colleagues who use Macs — a bit more elegant than, say, trying to share Perl scripts with Windows users who don’t have Perl (and the required add-on modules) already installed.
While other languages offer some similar capabilities to AppleScript, “there’s simply nothing like it in Windows,” declares David Pogue in his book Switching to the Mac: The Missing Manual, Leopard Edition. “It’s a programming language that’s both very simple and very powerful, because it lets Mac programs send instructions or data to each other.” And it does so using commands that are closer to plain English than most other scripting options.
A few caveats
AppleScript’s use of (relatively) natural language for its commands is a mixed blessing. While it’s popular among non-IT power users, even Soghoian admits that the syntax can frustrate those who regularly work in a language like Perl or Java. I lost count of how many errors I got because I’d write something like “x = 4” instead of the AppleScript-approved “set x to 4.” And I don’t program full time.
Although I’ve become an AppleScript enthusiast, I will caution that “natural language” doesn’t always mean “intuitive and easy.” While there are usually multiple ways to express something in AppleScript, quite a number of other syntaxes that might make sense won’t work in a script. The “nouns” and “verbs” to script specific applications can be hard to ferret out and apply properly, even after perusing the appropriate app “dictionary” (a listing of that application’s scriptable objects and methods). So some patience (and checking out others’ code) is needed.
Fortunately, though, some highly scriptable applications allow you to record activities in the AppleScript editor, very much like a macro recorder which translates your actions into (editable) AppleScript commands. This was very handy when I couldn’t figure out on my own the proper AppleScript for TextWrangler’s search and replace. For example, I use this AppleScript snippet to delete all percentages in a report that are formatted with a space followed by one or two digits followed by a period followed by one digit followed by a percent sign — as in 5.3% or 23.8%:
tell application “TextWrangler” to replace “\\s\\d{1,2}\\.\\d\\%” using “” searching in text 1 of text document 1 options {search mode:grep, starting at top:true, wrap around:false, backwards:false, case sensitive:false, match words:false, extend selection:false}
A final warning: AppleScript is not particularly well suited for a lot of text manipulation. There’s no built-in support for regular expressions; there’s not even a simple search-and-replace function as part of core AppleScript.
The good news here is that you can get some decent support for regular expressions by installing a free add-on from Satimage or, for smaller amounts of text, dumping it into an app like TextWrangler, which has such support. AppleScript can also incorporate more powerful commands from Perl, Ruby, Unix or anything else that can be accessed via a shell script, and then assign the results to a variable. For more on that, check out Apple’s technical note called “do shell script in AppleScript.”
Despite its drawbacks — and what language doesn’t have any? — I’ve found AppleScript to be a great tool for parsing drudgework out of my workday.
And now, without further ado, here’s a sampling of cool AppleScripts out there that just might make you love your Mac even more.
Search for any term in your clipboard on Computerworld or elsewhere
This is one of my faves: Take any term you’ve copied into your clipboard (command-C), regardless of the app you’re in, and Safari displays search results on that term from Computerworld.com.
To use:
- Copy the code.
- Open your script editor (you’ll find it in your Applications/AppleScript folder).
- Paste the code into the larger top portion of your script editor.
- Save the file as a script in your Library/Scripts folder. (Note: If you open the AppleScript utility in the Applications/AppleScript folder, you can have your script menu display in the top menu bar.)
Code
set url2 to “&x=0&y=0&cof=FORID%3A9#1214″tell application “System Events”
set myquery to the clipboard
end tell
— changes space to plus using function at end of file
set thequery to SaR(myquery, ” “, “+”)
tell application “Safari”
activate
tell application “System Events”
tell process “Safari”
click menu item “New Tab” of menu “File” of menu bar 1
end tell
end tell
set theURL to url1 & thequery & url2
set URL of document 1 to theURL
end tell
— handler (function) for search and replace
— (posted by James Nierodzik at macscripter.net)
on SaR(sourceText, findText, replaceText)
set {atid, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, findText}
set tempText to text items of sourceText
set AppleScript’s text item delimiters to replaceText
set sourceText to tempText as string
set AppleScript’s text item delimiters to atid
return sourceText
end SaR
If you want scripts that will search for terms in your clipboard at other sites, MacScripter has AppleScript versions posted for searching highlighted text on Google and Wikipedia (within Safari only). Download and install in your Scripts folder.
Targeted backups
Although Time Machine will do automated backups for those with modern versions of OS X, some readers might want an easy way to, say, keep all files related to a critical project together for an additional “in case of catastrophe” backup, or perhaps for something that could be easily downloaded to a USB drive.
It’s pretty intuitive to select files to back up by name or date. For example, take this line of AppleScript:
tell application “Finder” to duplicate (every item in folder “Documents” of home whose modification date comes after (current date) – 7 * days) to folder “backup_docs” of disk “Backups” with replacing
It copies all items in your Documents folder that were modified in the last week to the backup folder on your “Backups” disk; modify the folder locations and dates as needed (note that yesterday would be current date – 1 * days [not day]). “With replacing” tells the script to overwrite any existing files with the same name.
The same “whose” construction can be used to find other things, such as these two statements that can be used for all types of script or image files:
whose name contains “script”
or
whose kind ends with “image” .
Since I prefer to select files to back up based on “everything changed since I last ran this script,” here’s a quick modification created with Sal Soghoian’s help:
Code
activate
— Configure source and destination folders
set source_folder to folder “Documents” of home
set destination_folder to folder “docs” of disk “BackupDisk”– Create a config file 1st time script runs to keep track of latest time run
if not (exists file “backup_script_config.txt” in source_folder) then
make new document file at source_folder with properties {name:”backup_script_config.txt”}
duplicate every item in source_folder to destination_folder with replacing
else
set last_run to modification date of file “backup_script_config.txt” in source_folder
duplicate (every item in source_folder whose modification date comes after last_run) to destination_folder with replacing– Update config file modification date
set the open_file to open for access file ((document file “backup_script_config.txt” of source_folder) as string) with write permission
set eof of the open_file to 0
write last_run to the open_file starting at eof
close access the open_file
end if
end tell
Immediate backup on import
This script is designed for tasks like saving photographic images, where (conscientious) users might want to immediately back up files as soon as they’re imported. Apple offers a sample script for download, which you set up after you enter source and destination folders; it then continues to run in the background.
I encountered a bit of a performance lag when I played with it, but for some, the security of assured immediate backup is worth a bit of sluggishness.
Check your IP address
A simple IP utility from ScriptBuilders (accessible from the Scriptbuilders site) lets you quickly check your external IP address and copy it to your clipboard for tasks such as setting up a VPN or supporting a remote access connection.
Add lyrics to iTunes
There are hundreds of iTunes AppleScripts out there on sites such as Doug’s AppleScripts for iTunes. For example, you can make tracks “bookmarkable” so they resume playing wherever they left off or pick items on an iPod so they’re copied into an iTunes folder.
One of the more amusing is a script that automatically searches a database on the Web and adds a text version of a song’s lyrics into iTunes. Not all songs work properly, but when a match is found, you get to see full lyrics downloaded into iTunes.
iTunes volume fade-in and fade-out
For audiophiles who prefer that their music fade in when starting up and fade out when a tune is paused or restarted manually in mid-play, O’Reilly’s MacDevCenter site offers several iTunes scripts that do just that, either with or without dialog boxes.
Quick image manipulation
I’d wager that a fair number of AppleScript users would be surprised to learn that they don’t need an app like Photoshop in order to script things like rotating or resizing an image.
The following script from the book Apple Training Series: AppleScript 1-2-3 resizes an image to 50% of the original.
Code
try
tell application “Image Events”
— start the Image Events application
launch
— open the image file
set this_image to open this_file
— perform action
scale this_image by factor 0.5
— save the changes
save this_image with icon
— purge the open image data
close this_image
end tell
on error error_message
display dialog error_message
end try
Of course, Photoshop gives you much more control over how images are sized, so this isn’t a great technique to size images for printing or publication. However, for a quick e-mail attachment, it should be fine. There are also versions on the same Web page to size for maximum width or height, with user input setting the parameters.
Code
set the target_length to 640
repeat
display dialog “Enter the target length ” & “and choose the dimension of the ” & “image to scale to the target length:” default answer target_length buttons {“Cancel”, “Height”, “Width”}
copy the result as list to {target_length, target_dimension}
try
set the target_length to the target_length as number
if the target_length is greater than 0 then
exit repeat
else
error
end if
on error
beep
end try
end repeat
try
tell application “Image Events”
— start the Image Events application
launch
— open the image file
set this_image to open this_file
— get dimensions of the image
copy dimensions of this_image to {W, H}
— determine scale length
if the target_dimension is “Height” then
if W is less than H then
set the scale_length to the target_length
else
set the scale_length to (W * target_length) / H
set the scale_length to
round scale_length rounding as taught in school
end if
else — target dimension is Width
if W is less than H then
set the scale_length to (H * target_length) / W
set the scale_length to
round scale_length rounding as taught in school
else
set the scale_length to the target_length
end if
end if
— perform action
scale this_image to size scale_length
— save the changes
save this_image with icon
— purge the open image data
close this_image
end tell
on error error_message
display dialog error_message
end try
AppleScript resources
Interested in getting started with AppleScript — or delving deeper to write more sophisticated scripts? These resources will help beginners learn the basics, and will help experienced scripters improve their knowledge.
Web
You can find more image scripts and explanation of code from AppleScript 1-2-3 posted on Apple’s main AppleScript site.
Macscripter.net. A community focused specifically on AppleScript and other Apple automation tasks, Macscripter features a very helpful series of AppleScript tutorials as well as links to downloadable scripts and other resources. Members are helpful in answering questions; and I’ve found several solutions to scripting questions just by searching the forums.
Apple’s site features a section on learning AppleScript, including sample code, essential subroutines and some text and video tutorials.
Mactopia – from Microsoft of all places – has a site specifically for those interested in scripting Office for the Mac, including a VBA to AppleScript migration guide.
Books
AppleScript 1-2-3: A self-paced guide to learning ApppleScript, by Sal Soghoian and Bill Cheeseman (Peachpit Press). At 800+ pages, this isn’t meant to be read cover to cover; the first seven chapters are the instructions and the rest is reference. As a reference guide alone, this is a worthwhile book for anyone who wants to get even moderately serious about AppleScript.
AppleScript: The Comprehensive Guide to Scripting and Automation on Mac OS X, Second Edition by Hanaan Rosenthal (Apress). A couple of years old now, but I saw plenty of still-useful info during a quick browse of this one, including a lot of details on calling shell scripts.
Free books or book excerpts
There are two AppleScript 1-2-3 chapters available free online at apple.com: The First Step and Image Events.
You can download the first chapter of AppleScript for Dummies, A Cannonball Dive into the Scripting Pool, from the “For Dummies” store (PDF format).
AppleScript for Absolute Starters is available as a free PDF download.
Add-ons
Satimage osax 3.4.0. This free download offers additional capabilities to native AppleScript, including regular expressions, finding and replacing literal search terms, and some mathematical functions like absolute values, sines, cosines and square roots. The Satimage osax 3.4.0 dictionary details all the new functionality.
Using AppleScript in other languages
appscript is a “high-level, user-friendly Apple event bridge that allows you to control scriptable Mac OS X applications from Python, Ruby and Objective-C. Appscript makes these languages serious alternatives to Apple’s own AppleScript language for automating your Mac,” according to its open-source project page.
I’ve tried only the Ruby version, which worked fine in my limited testing. There are several explainers online to help you get started installing and using rb-appscript, including articles at the Macdeveloper and O’Reilly Web sites.
Mac::AppleScript::Glue is a CPAN module that “allows you to write Perl code in object-oriented syntax to control Mac applications,” by translating Perl to AppleScript. I haven’t tried this one yet and it’s fairly old (2002), but if you’re comfortable in Perl and would like to add AppleScript capabilities to your code without learning the syntax, this is probably worth a try.