12
3/16/12 5:18 PM The Ultimate Beginner's Guide To AppleScript | Mac.AppStorm Page 1 of 12 http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/ The Ultimate Beginner’s Guide To AppleScript This is the first post in a new series that revisits some of our readers’ favorite posts from the past that still contain awesome and relevant information that you might find useful. This post was originally published on July 7, 2009. AppleScript is a powerful scripting language that comes built-in to OS X. The princi- pal use for AppleScript is the automation of tasks that are normally repetitious and time consuming. For instance, as a freelancer, I hate creating invoices every week for my various clients. To solve this problem I wrote an AppleScript that reads the hours that I log into iCal, creates an invoice in Microsoft Excel based on those hours, and emails the invoices to my clients. All with the click of a button! The best part about AppleScript is that you don’t have to be a genius programmer to use it. In fact, you don’t have to have any programming experience whatsoever. This article will show you how to write an AppleScript for nearly any application using the simple instructions that come hidden within each app’s framework. Intrigued? Read on! The Main Window Getting Started: The Tell Block To create an AppleScript, open the application “Script Editor” located inside the Ap-

The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

Embed Size (px)

Citation preview

Page 1: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 1 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

The Ultimate Beginner’s Guide To AppleScript

This is the first post in a new series that revisits some of our readers’ favorite postsfrom the past that still contain awesome and relevant information that you mightfind useful. This post was originally published on July 7, 2009.

AppleScript is a powerful scripting language that comes built-in to OS X. The princi-pal use for AppleScript is the automation of tasks that are normally repetitious andtime consuming. For instance, as a freelancer, I hate creating invoices every week formy various clients. To solve this problem I wrote an AppleScript that reads the hoursthat I log into iCal, creates an invoice in Microsoft Excel based on those hours, andemails the invoices to my clients. All with the click of a button!

The best part about AppleScript is that you don’t have to be a genius programmer touse it. In fact, you don’t have to have any programming experience whatsoever. Thisarticle will show you how to write an AppleScript for nearly any application usingthe simple instructions that come hidden within each app’s framework. Intrigued?Read on!

The Main Window

Getting Started: The Tell Block

To create an AppleScript, open the application “Script Editor” located inside the Ap-

Page 2: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 2 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

pleScript folder within the Applications folder. You should see a simple window con-taining a large text field with a strip of buttons along the top. Inside the text field typethe following code:

12345

tell application "Finder" display dialog "Hello World" end tell

AppleScript attempts to use plain English wherever possible to make coding ex-tremely simple. Most commands in AppleScript are located inside a “tell block”. It’scalled a “tell block” because you are “telling” a given application what you want it todo. For instance, the code above is telling the Finder to display a dialog window con-taining the words “Hello World”. After you are finished with a command or string ofcommands for a given application, you end the block with “end tell”.

Always remember to end your tell blocks correctly or the code will not compile!

After you are done entering the code above, click on the “Compile” hammer icon. Ifyour syntax is correct, your code will automatically format and colorize. If you havemade an error, Script Editor will highlight the problematic area and give you a mes-sage about what it thinks might have gone wrong. Here is a quick reference to thevarious colors you’ll see in your compiled code (found in Script Editor>Preferences).

Page 3: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 3 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

Color Guide

After your code has compiled, click on the “Run” button. You should see the follow-ing dialog:

Hello World

Now click the “OK” button and look at the bottom of your Script Editor window.When you run a script, Script Editor tells you what the result was, or what was “re-turned”. In this case it’s telling you that the “OK” button was clicked.

The OK Return

Declaring Variables

Variables are essentially the same in every programming language. They provide aneasy way to access and manipulate lots of information in a compact snippet of code.Creating or “declaring” variables is different for every language. In AppleScript youdeclare variables as follows:

1234567

set theString to "Hello World" tell application "Finder" display dialog theString end tell

There are several things to note about the previous example. First, notice that vari-ables are declared using the “set” and “to” commands. By doing this you are setting

Page 4: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 4 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

your variable name, in this case “theString”, to equal something, in this case the text“Hello World”. Many programming languages require that you state the type of vari-able you want in the declaration (integer, floating point, text, etc.). AppleScript how-ever, is intelligent enough to work with your variables without any instruction aboutthe format.

Also notice how I typed my variable name. You can’t have spaces in a variable nameso it’s good practice to use camel case (theString) or the underscore method(the_string). It doesn’t really matter which method you choose, just make sure you’reconsistent throughout your code. It’s also a good idea to give all your variables mean-ingful names. When you are looking another programmer’s code, it can be annoyingto see variable names like “myVariable” that don’t give any indication as to whatthey are or what they will be used for.

Finally, notice that now that I’ve placed the text “Hello World” inside a variable, Ican call that variable again and again throughout my code. Then if I later decide tochange the text “Hello World” to “Good Morning Dave”, I only have to change thetext on the line where I declared the variable.

Working with Variables

You can do all kinds of crazy things with variables, but since this is only meant to bea brief introduction to AppleScript, I’ll just show you a few. Type in the followingcode:

1234567891011121314151617

--Integer Variablesset theFirstNumber to 3set the theSecondNumber to 2 --Variable Operationsset theAnswer to (theFirstNumber + theSecondNumber)set theAnswer to (theAnswer + 1) --String Variablesset theString to "3+2+1=" --Display Dialogtell application "Finder" display dialog theString & theAnswer end tell

Page 5: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 5 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

You can compile your code quickly by pressing the “enter” key (not the return key).This is located on the ten key number pad on desktop computers and next to the“Command” key to the right of the space bar on laptops.

As your script becomes more complex, a bit of organization is in order. By typing twodashes “–” before a line of text, you can insert a comment. Use comments to separateand describe your sections of code for easy navigation. In this example I’ve created astring variable (text only) and a few integer variables. Notice that you can performmathematical operations on variables. Here I’ve set “theFirstNumber” to equal threeand “theSecondNumber” to equal two and then added them together in “theAn-swer”.

Also notice that you can change a variable after it is declared. Immediately after set-ting “theAnswer” to the sum of “theFirstNumber” and “theSecondNumber” (result-ing in 5), I changed the value of “theAnswer” by adding one to it (resulting in 6). Ifyou run this script you should see the following result:

Some Basic Math

Again, this only scratches the surface of the kinds of operations you can perform onvariables. For now you should just understand that a variable isn’t static. Much of thepower of behind any programming language is the ability to manipulate variables toperform a wide variety of tasks.

The Key to it All: AppleScript Dictionaries

Though AppleScript itself has a wide range of commands that can be applied to anyprogram or item in OS X, the developers of each application are tasked with addingfull AppleScript support to their apps. What this means is that developers must writesimple manuals for how to communicate with their applications through Apple-Script. These manuals are called “Dictionaries”. To view a dictionary, go toFile>Open Dictionary in Script Editor. Scroll down the list of applications, click onMail and hit “OK”. You should see the following window:

Page 6: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 6 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

The Mail Dictionary

The column on the left contains the available “Suites” of commands and items. Whenyou click on a suite, you’ll see everything contained in the suite displayed below. Youcan narrow this preview by clicking in the second column, then again in the third.Suites contain commands (C with a circle) and classes (C with a square), classes con-tain properties (P) and elements (E). To understand how all this works, let’s use thisdictionary to create a script.

Create an Algorithm for Our Script

First we need an algorithm, which is a fancy way to say that we need write down ex-actly what our script will do. We want to create a script to compose and send anemail. We’ll want to use variables to make it easy to change the message itself as well

Page 7: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 7 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

as who the message is sent to. As we write our algorithm, we need to keep in mindthe way AppleScript works. Here are the steps I came up with:

1. Create variables for the recipient, the recipient’s email address, the subject of theemail, and the text for the body of the email.

2. Create a variable that holds our new message along with its various properties3. Create the new message4. Send the new message

Creating Simple Variables

We already know how to create variables holding text so we don’t even need the dic-tionary for step one. Here’s what the code looks like:

12345

--Variablesset recipientName to "John Doe"set recipientAddress to "[email protected]"set theSubject to "AppleScript Automated Email"set theContent to "This email was created and sent using AppleScript!"

As you can see, we’ve just put placeholder text into the variables for the name andemail address of the recipient as well as the subject and content of our message. Youcan change these to anything you’d like. Be sure to put your own email address in therecipientAddress variable so you can ensure that the the script is working properlywhen you receive the email.

Creating the Message Variable with the Mail Dictionary

Since we have no idea how to tell Mail to create a new message, this is where weneed to refer to the AppleScript dictionary. If you click on “Standard Suite” you’ll seeseveral common commands that come standard in AppleScript. Knowing that wewant to “create” a new message, we just scroll through the options and find some-thing equivalent. You’ll see there is no “create” command but about half way downthere is a “make” command. That sounds perfect, so we now know to tell Apple-Script we want to “make” something.

Next click on the “Mail” suite. We’ve already got our command (make) so scrolldown past the commands (verbs) until you see the classes (nouns). The first class wecome across is “outgoing message”, which is great because that’s exactly what we

Page 8: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 8 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

want! Now click on the “outgoing message” class and look at the available propertiesdown below.

We need to plug in our variables for the recipient’s name, the recipient’s email ad-dress, the subject, and the contents of the message. In the list of properties there isn’tanything about the recipient but there are properties for subject and content. We nowknow the proper syntax to refer to these properties. Notice that the dictionary givesyou the format to define the properties. For instance for the subject, we’ll type theword “subject” followed by a colon followed by the text of the subject.

Subject Content

Also in this suite you’ll find a “send” command, which we can use to send the mes-sage by simply typing “send”. We still need to know the proper syntax for the recipi-ent’s name and email address. Since it’s not in this suite, click on the “Message” suite.

Page 9: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 9 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

About halfway down the list of classes we find “recipient”. Click on the recipientclass and we see that once again, we can use plain English to refer to the properties ofthe recipient. We’ll simply type “name” and “address”.

You can use the search feature to hunt down properties, classes, elements and com-mands quickly.

Now we are ready to create our message variable using the syntax we’ve just learned.Here’s what the code looks like:

12345678910111213

--Variablesset recipientName to "John Doe"set recipientAddress to "[email protected]"set theSubject to "AppleScript Automated Email"set theContent to "This email was created and sent using AppleScript!" --Mail Tell Blocktell application "Mail" --Create the messageset theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true} end tell

Notice I’ve created a tell block to enclose all the commands to the Mail application.Then I set a variable (theMessage) to “make” a new “outgoing message” with theproperties discussed above. Also notice that sets of properties are always containedin brackets { }.

The Final Step: Setting the Recipient and Sending the Message

Now that we’ve created our message variable, we need to call that variable and cre-ate a new message with the properties of theMessage. We also need to set the recipi-ents and send the message. To do this, we’ll use a tell block on our variable. Here’sour finished script.

12345

--Variablesset recipientName to "John Doe"set recipientAddress to "[email protected]"set theSubject to "AppleScript Automated Email"set theContent to "This email was created and sent using AppleScript!"

Page 10: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 10 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

56789101112131415161718192021

AppleScript!" --Mail Tell Blocktell application "Mail" --Create the message set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true} --Set a recipient tell theMessage make new to recipient with properties {name:recipientName, address:recipientAddress} --Send the Message send end tellend tell

First, we created a new copy of theMessage (which inherits all the properties we’veput into it) and set it “to recipient with properties”. This tells Mail that we want toadd a recipient with the following properties. Here we just used the syntax welearned before and the variables for the name and address of the recipient.

Finally, we invoked the “send” command to send our message. Notice that we havetwo tell blocks to close this time. Once you’ve compiled your code and fixed any er-rors hit the “Run”. Mail should automatically create and send the message. Tadaah!Check your sent folder to make sure everything worked.

Page 11: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 11 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

Mail Message

Congratulations, you’ve created your first AppleScript! You can save it as a simplescript that you can come back and edit or as an application that runs automaticallywhen you open it.

Conclusion: Keep Learning

I hope this beginner’s guide has you thinking about all kinds of processes and tasksyou’d like to automate. The syntax I’ve shown you along with the AppleScript Dictio-naries will get you a long way. However, if you’re really interested in implementingAppleScript in a number of useful ways, you’ve got more reading to do. Apple pro-vides lots of information all about AppleScript on their website. Here’s a good placeto start.

Another website I’ve picked up a great deal from is T&B. It offers some really in-depth explanations and tutorials for you to follow (a little dated, but thorough and

Page 12: The Ultimate Beginner's Guide to Apple Script | Mac.appstorm

3/16/12 5:18 PMThe Ultimate Beginner's Guide To AppleScript | Mac.AppStorm

Page 12 of 12http://mac.appstorm.net/how-to/applescript/the-ultimate-beginners-guide-to-applescript/

free). Please feel welcome to leave a comment and let us know if you found this tutor-ial helpful! What other AppleScript tips would you like to see covered in the future?