Free AppleScript Code Examples

Apple iMac Conceptual
Apple iMac Conceptual

How to Write AppleScript Code without any Prior Knowledge

AppleScript, with tutorial emphasis to benefit those new to scripting. Free example scripts of general utility. This site is dedicated to those who want to learn about the mechanics of the AppleScript language.

Note that I approach things as a step-by-step progression, therefore, starting at the top for the more basic scripts, continue to scroll toward the bottom of the page for more advanced scripts. For an explanation of some common terms with examples, check out: AppleScript Explained

For more advanced scripts go to: More AppleScript Code.

Getting Started with AppleScript Dialogs

A Basic Notification Dialog

This is a very simple dialog script to notify the user of the result of some action.

Note in the script below, that you could substitute 'note' or 'caution' for 'stop' to indicate varying degrees of importance or urgence:

display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"}
The resulting dialog from the script above
The resulting dialog from the script above

Taking the above script a step further, you could include 'giving up after 5 (or 15, 20, 60 etc) so that a dialog will automatically close itself after the indicated interval of time:

display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"} giving up after 5

You can also have multiple button choices (up to 3). take special note of the formatting required for multiple buttons:

display dialog "Your text here" with icon note buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30

Note in the above example, if you click on 'cancel' or strike the enter or return keys, it will generate an error message. To avoid this, and to get your dialog to close 'silently', the above must be enclosed within a 'try clause' such as:

try
	display dialog "Your text here" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30
end try

I hope that those of you who are new to AppleScripting will find these sample dialog scripts useful as you begin to explore the magic of AppleScript. If you don't understand how these scripts work, copy and paste them into your Script Editor and run them - this should clear up any questions you may have.

If you want a more detailed script on dialogs like this with an action attached to it, see 'Using AppleScript Dialogs to Invoke Actions' below.

Syntax Options for Dialogs

This article is closely connected with the previous one. Take a look at this simple dialog script and the table which follows.

Using a script statement from the previous article:

display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"}

This could actually be expressed more simply, like this (see the table below):

display dialog "Your text here" with icon 0 buttons "OK" default button 1
Icon Type
Icon Name
Numerical Value
Notification
note
1
Caution
caution
2
Warning
stop
0
Dialog Icons and optional numerical values for use in scripts

Note: In the example above the table, I used icon 0. This is equivalent to saying icon stop. In addition, I used the expression default button 1, which highlights the "OK" button (makes it blue) so that it can be activated by pressing the enter key.

Also, notice that I omitted the curly brackets {"OK"} surrounding the button name "OK". The brackets are optional, if you have only one button. If, however, I had two buttons, the brackets would be required and a comma inserted between the button names like this:

display dialog "Delete current document ?" with icon 0 buttons {"Cancel", "OK"} default button 1
Dialog resulting from script statement above
Dialog resulting from script statement above

Finally, notice that default button 1 highlights the "Cancel" button in this case. If I wanted to highlight (make default) the "OK" button, I would say default button 2.

There are actually a few additional optional parameters possible to customize your dialogs (also referred to as sheets) that I will go into as part of another article. In the meantime, have fun.

Using AppleScript Dialogs to Invoke Actions

Attaching an Action to User Interaction Dialog

In my last article, we ended up with this dialog which had to be encompassed by a 'TRY CLAUSE' to prevent an error message from being generated by activating the 'Cancel' button. In this article, I will begin by modifying the script below to show you how you can use data returned from a dialog to invoke an action from AppleScript.

try
	display dialog "Your text here" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30
end try

Taking our original script I will make a few additions:

try
	set theAction to button returned of (display dialog "Quit application AppleWorks 6 ?" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30)
	if theAction = "OK" then tell application "AppleWorks 6" to quit
end try

You can see above, that I have set the variable theAction to take on the value of the name of the button chosen (note parentheses). As before, if the user clicks on the 'Cancel' button the script halts without any action being taken. If, however the 'OK' button is chosen, then AppleScript sends the quit message to AppleWorks 6.

Now suppose we wanted a dialog that quits an application, but we want to be able to enter in the name of a specific application ahead of time.

try
	set dialogResult to (display dialog "Enter name of application to quit:" default answer "" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30)
	set appToQuit to (text returned of dialogResult)
	if (button returned of dialogResult) = "OK" then tell application appToQuit to quit
end try

There are a few changes to be noted here, but it's really not complicated at all.

First, I have enclosed the dialog part of the script in parentheses and before that I have inserted 'set dialogResult to'. This tells AppleScript to give the variable dialogResult the values that will be derived from executing the dialog part of the script.

The text default answer "", inserted into the dialog section tells AppleScript to give us a blank text field where the name of the app to quit will be entered. The variable dialogResult will contain both the text entered and the name of the button clicked.

Next, the variable appToQuit extracts the text part of dialogResult (the application name)

The next line determines if the 'OK' button was activated and, if so, quits the application supplied by the variable appToQuit, otherwise the script ends with no further action.

I hope you're having a little bit of fun now and seeing just how powerful the AppleScript language can be.

Getting Results of Dialogs

Once you get down the basics of writing a simple dialog for interaction with the user, the next step is to be able to use the returned data to its fullest extent to invoke other actions based upon the actions of the user.

If you read through the script below, you will see the kinds of information returned to AppleScript from a dialog and how it can be useful to save that data to variables for further processing. First a dialog that directly assigns the text result to a variable:

set returnedText to text returned of (display dialog "Enter some text:" default answer "" with icon note) -->"some text"

In this example, the variable: returnedText is set after the dialog has been invoked:

display dialog "Enter some text:" default answer "" with icon note
set returnedText to text returned of the result -->"some text"

In this final example, all of the result data is stored in a list with a variable assigned for each. Note here that I include the giving up after parameter which returns the 'true or false' of whether or not the user responded to the dialog or 'gave up' within the specified time:

display dialog "Enter some text:" default answer "" with icon note giving up after 15
set {returnedText, returnedButton, gaveupBoolean} to the result as list
-->{"some text", "OK", false}
Text Entry Dialog Example
Text Entry Dialog Example

And here, some of the things you can do with the data derived from this:

returnedText -->"some text"

returnedButton -->"OK"

display dialog gaveupBoolean -->{button returned:"OK"}

if gaveupBoolean = true then display dialog "You gave up dude !" with icon 0
-->{button returned:"OK"}, true is unquoted because it is not a string, but a boolean value

Dialogs for Lists

Making a Choice from a List of Options


In this article, we will deal with situations when you want to choose from multiple options within a list. You can have lists that are preset, such as choosing from a list of months of the year, for instance, or perhaps a list such as that which might be generated from a database program when certain criteria are specified (ie names beginning with the surname Bill).

Take a look at this example:

set theName to (choose from list {"John", "Joe", "Bill"})
if theName is false then
	display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
	set theName to (item 1 of theName)
	display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if
Choose from List Example
Choose from List Example

First note in the first line that 'choose from list' prompts you to choose from the three names given {"john", "joe", "bill"}. the name chosen is assigned to the variable 'thename'.

if the user clicks cancel from a 'choose from list' dialog such as this, then the variable 'thename' takes on the value false indicating that the user decided not to make a choice of the items listed in the dialog.

If the user makes a choice, say for instance "bill", then 'thename' takes on that value and can be used for further script execution.

Adapting the previous dialog, assuming you had a list of items (whatever criteria relevant to what you want) compiled from a database of your own design, in this case we will call the list 'recentOrders', a list of customer names who have ordered products or services from you in recent months. Another version of the list dialog that could be used based on these premises:

set recentOrders to recentOrdersArray as list
try
	set recentCustomer to (choose from list recentOrders)
	if recentCustomer is not equal to false then
		set recentCustomer to (item 1 of recentCustomer)
		set scriptAction to button returned of (display dialog "Get information for last order from '" & recentCustomer & "' ?" with icon note buttons {"Cancel", "Info"} default button {"Info"})
		display dialog "Info for last order from: " & recentCustomer
		--here you would return to the user the info from your database on 'recentCustomer'
	end if
end try

Here, we choose a particular item (customer) from 'recentorders'. next, if we do not cancel execution, the variable 'recentcustomer' is assigned. if we do not cancel the next request dialog, the data on the requested customer can be displayed (based upon info stored in whatever the referenced database).

As list type dialogs deviate from the standard dialogs dealt with up until now, it is important to note that, although computers are supposed to follow some sort of logic, you sometimes have to 'go with the flow' on things that don't seem to follow that logic.

I can't emphasize enough, that the whole process of learning how to applescript builds upon itself. In my coming posts, I will strive to make things easier to grasp by continuing in a step-by-step manner, as I have found it to be effective in learning scripting.

I hope this post has been useful in furthering your knowledge of scripting with AppleScript. As always, if you have any questions or comments or would like to suggest something on another AppleScript issue, please go to my comments section at the bottom of the page.

More on List Dialogs

Continuing with list dialogs with an example that goes into more detail

This article will deal with what I consider a very concrete use of the 'choose from list' dialog. After reading this (and perhaps trying it out in the Script Editor) you will probably be totally confused (just kidding!!) It gets a little complicated, but it is basically a cut-and-paste script.

If you pay close attention to my comments, I'm sure you'll understand most of what is going on and, after all, it's understanding how a script works that allows you adapt it to other applications that you may have in mind.

So anyway, here it is:

set AppleScript's text item delimiters to ","

--This first line is needed, because it sets things up for extracting the info we need

set theLongDate to (current date)
set theLongDate to (date string of theLongDate)
set currentMonth to (word 1 of text item 2 of theLongDate)
set currentDay to (word 2 of text item 2 of theLongDate)

--This gets the numerical value for the month


set currentYear to (word 1 of text item 3 of theLongDate)
set monthList to {January, February, March, April, May, June, July, August, September, October, November, December}

repeat with x from 1 to 12
	if currentMonth = ((item x of monthList) as string) then
		set theRequestNumber to (text -2 thru -1 of ("0" & x))
		exit repeat
	end if
end repeat
set currentMonth to theRequestNumber
set currentDay to (text -2 thru -1 of ("0" & currentDay))
set theShortDate to (currentMonth & "/" & currentDay & "/" & currentYear) as string

Previous code sets up the default text (current date in the form 'MM/DD/YYYY' - something like '02/03/2009') for dialog below :

set theDefaultDate to text returned of (display dialog "Enter a date in the form MM/DD/YYYY:" default answer theShortDate buttons {"Calc Date"} default button {"Calc Date"} giving up after 20)
--This line converts the text supplied by the dialog to class 'date' (the long form of the date, including the time):

set calcLongDate to date theDefaultDate
--This line extracts the date portion and leaves the time portion behind:

set calcLongDateTrunc to (date string of calcLongDate)
--This converts calcLongDateTrunc back into the form 'text' so that it can be displayed in a dialog:

set calcLongDateTrunc to calcLongDateTrunc as string
display dialog calcLongDateTrunc buttons {"Done"} default button {"Done"} giving up after 15

-->Yields something like- 'Tuesday, February 3, 2009'

For a more sophisticated 'choose from list' example, go to http://hubpages.com/technology/More-Advanced-AppleScript-Code and press command-F, then type 'Find Record in FileMaker Database' and press enter

In my next article, I will shift gears and present an AppleScript which I have derived from one of my Filemaker programs, which serves as a convenient file backup program.

FileMaker Pro AppleScript to Backup Files

Backup a specific folder of FileMaker documents, replacing previous backup files

This script was adapted from one written specifically for a FileMaker Pro program, although it could easily be used in any database program you use that supports AppleScript:

Most of what appears here builds upon the information presented in previous posts to this point.

tell application "Finder"
	try
		set todaysDate to (current date)
		set bkpYear to (year of todaysDate)
		set monthlyBkp to ("Monthly Reports " & bkpYear) as text
		if not (folder "Database Backups" exists) then
			set targetFolder to (make new folder at folder "Desktop" of startup disk with properties {name:"Database Backups"})
		end if
		
		set replaceExecute to button returned of (display dialog "Are you sure you want to replace current backup contents with the selected items?" with icon caution buttons {"Cancel", "OK"} default button {"OK"} giving up after 60) --give user the chance to exit in case there is already a folder 'database backups' containing items that the user does not want to replace
		if replaceExecute = "OK" then
			select {file "Home Database" of folder "Database Programs)", file "Appointments" of folder "Database Programs", file monthlyBkp of folder "Database Programs", file "Accounts Receivable" of folder "Database Programs", file "Calendar" of folder "Database Programs"}
duplicate the selection to folder "Database Backups" with replacing --if we proceed, 'with replacing' replaces the contents of the folder "Database Backups"
		end if
		
	on error
		display dialog "Backup cancelled!" with icon stop buttons {"OK"} default button {"OK"} giving up after 3
	end try
end tell

tell application "FileMaker Pro" to activate

Trapping for List Dialog Errors

Intercepting the Dreaded 'Cancel' error (Error Number -128)

With 'List Dialog' type dialogs, since errors cannot be intercepted in an 'on error' handler, there is no 'normal' way to trap for 'Cancel' which, of course, would result in some sort of undesirable error dialog such as 'User cancelled'. Error number -128'. Here is an example of one simple way I have found to trap for this type of error:

set x to (choose from list {"Joe", "Amy", "Bill"} with prompt "Choose a record:")
if x is false then
else
	set targetItem to (x as text)
	show (every record whose cell "Name" contains x)
end if

When the user clicks on 'Cancel', the variable x is assigned the boolean value false. So all you have to do is set up a conditional clause to deal with that (notice it does nothing at all) and to perform the usual statements otherwise.

Display Alert Dialogs

Dialogs that display additional information to user

They are used when it is important to impart further information on the state of the Finder or another application, where, for instance, some data loss could occur as a result of an incorrect action being taken.

try
	display dialog "Enter a number" default answer "" buttons "OK" default button "OK"
	set userEntry to text returned of result
	return userEntry as number
on error
	set alertString to "The text entered is not a number"
	set messageString to ("" & userEntry & " is not a number. ") & "Run the script again and use only number keys."
	display alert alertString message messageString buttons "OK" default button "OK" as informational giving up after 20
end try

This is fairly straightforward, below the resulting dialog when the user happens to enter 'abc' (a non-numerical value):

Result of script above
Result of script above

Note: The Finder icon in the dialog above results from 'as informational'. You could also use 'as critical' or 'as warning' to imply varying degrees of seriousness.

Display Dialog with Password

A password dialog where text entered appears as bullets

This script presents a text entry dialog where the text entered by the user is encrypted as bullets so that nosy people, for instance, cannot see what is being entered on your screen.

Seriously, though, the main purpose of this type of dialog is as a security measure to restrict access to critical files.

set thePass to "pass90805"

Here, depending upon the application, you could have 'thePass' set to the value stored in a global field, In FileMaker it would be a statement something like 'set thePass to data of cell "passwordStorage"'

considering case
	repeat with x from 1 to 3
		display dialog ("Enter the password for access to this file:") default answer "" with icon stop with hidden answer
		if text returned of result is thePass then
			exit repeat
		end if
		if x is 3 then return "You have attempted to access this file too many times. Your access is denied. Please try again."
	end repeat
end considering
Dialog resulting from script above
Dialog resulting from script above

The considering case block tells AppleScript to require that the text entered match the particular case of the pre-determined password (upper or lower).

By the way, the part that gives the bullets instead of the actual text entered is 'with hidden answer'

The repeat block allows the user 3 attempts at entering the password for access and after that, terminates the script.

If you have questions or would like to suggest an article on another AppleScript issue, visit my comments section at the bottom of this page.

Display Notification Dialog
Display Notification Dialog

Display Notification

First available in MacOs X Mavericks, the 'display notification' command is a sort of extension of the 'display dialog' and 'display alert' commands. Similar to the others in purpose, it brings up a type of dialog which briefly slides over from the upper right of your screen and then slides back over again to the right and disappears. The syntax, while different than the other two, is very easy to implement and can add some pizazz to just about any script where you need to send feedback to the user that an operation was successful without having to take any action to dismiss it.

The image above matches the example script below (including icon), when run through the AppleScript Editor.

The simple code:

set theDate to date string of (current date)
set condensedDate to (word 2 of theDate & " " & word 3 of theDate & ", " & word 4 of theDate)
set theReference to "John Doe 3409 Market St" & return & "Dayton, OH 44505"
display notification theReference with title "Appointment Set for " & condensedDate
delay 24

Basic Printing Scripts

A few simple AppleScripts to automate your printing routine

The first script below is for printing a document in TextEdit. Before running the script, you must bring the desired document to the front:

tell application "TextEdit"
	print front document with properties {copies:2, collating:true, starting page:1, ending page:1, pages across:1, pages down:1, error handling:standard} without print dialog
end tell

Most of what appears in 'with properties {....}' above should be fairly obvious. If you want to specify the printer, you could follow the last parameter in the list with a comma and 'target printer:' and the actual name of the desired printer enclosed in quotes.

If you want to use different printers in certain cases, replace 'without print dialog' with 'print dialog'

This second script, so that you aren't required to specify the application file targeted by the print command:

tell application "Printer Setup Utility"
	set current printer to printer "Deskjet D2400 series"
	(alias "Mac HD:Users:administrator:Documents:My Document.cwk")
end tell

Replace 'Deskjet D2400 series' with the name of your printer and replace '(alias "Mac HD:Users:administrator:Documents:My Document.cwk")' with the path to the document that you wish to print (Don't forget to precede the path name by 'alias' - this is important).

The print command is part of the 'Standard Suite' of the Finder's Dictionary, and so, in my next article, We will look at the remaining commands that make up the Standard Suite (there are 3).

Create and Save New 'rtf' File with TextEdit

This script creates a text file using the text stored in the clipboard and saves it in Rich Text (rtf) format. The word 'the' in 'the clipboard' is critical and required. I tried it as simply 'clipboard', because I don't like using 'the' in scripts and found out that it doesn't work without the word 'the'.

tell application "Finder" to set the clipboard to "Sample Text"
tell application "TextEdit"
	activate
	try
		make new document
		set theText to the clipboard
		set text of front document to theText
		set newDoc to text returned of (display dialog "Enter a name for the new document" default answer "Notes" with title "Save New Document" buttons {"Save"} default button 1 with icon 1)
		set newDoc to ("Macintosh HD:Users:appleUser:Desktop:Reminders:" & newDoc & ".rtf") as text
		save document 1 in file newDoc
	on error theError number theNumber
		display alert theNumber message theError
	end try
end tell

The Finder's Standard Suite

These are the core commands that the Finder and every scriptable application should be able to handle In my last article, we took a look at how to use the Finder's print command, which is part of the Standard Suite. As promised, in this article we will now look at the remaining commands that make up the Standard Suite, namely: open,quit and activate.

While the last two are pretty simple to implement, the open command requires some explantion. First, the basic open syntax:

tell application "Finder" to open home

This is easy to understand, it simply tells the Finder to open home of your HD.

If you want to open a specific document, you would use a form such as:

tell application "Finder" to open document file "My Document.cwk" of folder "Documents" of home

Here, 'My Document.cwk' is replaced with your document residing in your 'Documents' folder (or which ever folder you desire).

To get the full path of a document, open the document and hold down the command key while clicking on the window's title bar. The result is something like:

(alias "Mac HD:Users:administrator:Documents:My Document.cwk")

Each level of the path is separated by a colon. The script would look like this:

tell application "Finder" to open document file (alias "Mac HD:Users:administrator:Documents:My Document.cwk")

The basic quit and activate (bring app to front) commands take no parameters:

tell application "Finder" to quit

tell application "Finder" to activate

tell application "FileMaker Pro" to activate

tell application "AppleWorks 6" to activate

Remember that the print command is part of the Finder's Standard Suite and was covered in my previous article.

Order Folder Items by Creation Date

List items of a specified folder numerically by date of creation

tell application "Finder"
	set itemGroup to sort (get every document file of front Finder window) by creation date
	repeat with x from 1 to count of itemGroup
		set groupItem to item x of itemGroup
		set name of groupItem to ((x as string) & "-" & (name of groupItem))
	end repeat
end tell

First note that in statements such as the second line above, what is enclosed in parentheses is executed first (a list of the documents contained in the specified folder). Next that list is sorted by creation date and the value is placed in the variable itemGroup.

The repeat block takes that sorted list and places a number and a hyphen before each item name:

'((x as string) & "-" & (name of groupItem))'

In place of creation date, you could also use 'name', 'size' or 'kind' as your sort criteria.

If after running this script, you decide that you want to restore things back to the way they were, this script will do it (BE SURE THAT YOU HAVE THE CORRECT WINDOW AS THE FRONT FINDER WINDOW):

tell application "Finder"
	set itemGroup to (every document file of front Finder window)
	repeat with x from 1 to count of itemGroup
		set groupItem to item x of itemGroup
		set nameItem to name of groupItem
		set the hyphenOffset to (offset of "-" in nameItem) + 1
		set originalName to text from hyphenOffset to -1 of nameItem
		set name of groupItem to originalName
	end repeat
end tell

Discerning Between When to Use Set and When to Use Copy

Sometimes set and copy can be used interchangeably, sometimes not!

This one can be a difficult one, but if you have been following my posts so far, or otherwise are that much interested in learning AppleScript, this is an important issue to get straight.

Even if you have been using AppleScript for a while, as I have, you may still be unclear as to the difference between using set and using copy. In fact you may, as I thought for the longest time, think that they are synonyms. This is in many cases true, such as in statements like:

set clientName to "Joe Gonzalez"

copy "Joe Gonzalez" to clientName

In both cases, the variable clientName is set to the value of "Joe Gonzalez";.

If we try to use these interchangeably in the following statements, however, we get very different results. To illustrate this, have a look at these two scripts, which, on the surface would appear to have the same result:

set todaysDate to current date
set tomorrowsDate to todaysDate
set day of tomorrowsDate to (day of todaysDate) + 1
return date string of todaysDate

The previous statement, it would seem, would give us the current date: say 'Tuesday, June 9, 2009'. Unexpectedly, the value of the variable 'todaysDate' is now 'Wednesday, June 10, 2009' - not what we want. The reason for this anomaly is that when we use set to 'set' the value of a second variable, any changes to the value of the second are also changed in the former. This is because 'set' makes the second variable a clone of the original.

If we want to use the original variable as an initial value for the second without effecting the value of the original then we must use the keyword 'copy':

set todaysDate to current date
copy todaysDate to tomorrowsDate
set day of tomorrowsDate to (day of todaysDate) + 1
return date string of todaysDate

In the second case with 'copy', todaysdate retains its original value; using copy instead of set makes the new variable tomorrowsDate an independent variable.

This principle holds true for lists, records and script objects as well. In other words, the set keyword is a reference to the original item which is why, with ordinary text strings they can be used interchangeably.

This is one of those things that you will encounter with AppleScript, where you can get the correct result every time you run a script and think that it will always work, and then you try to use it with another data type and get a big surprise.

Apple iMac G3, circa 1996
Apple iMac G3, circa 1996

Choose Folder Dialogs

In the next few articles, we will look at dialogs where the user chooses among items in directories on the desktop that return reference pointers to the actual files (most are aliases) that they represent. The dialogs we will deal with here are 'choose folder', 'choose file', 'choose file name' and 'choose color'.

First, a simple 'choose folder' dialog:

set theFolder to choose folder with prompt "Select a folder:"

Which brings up the following dialog (or something similar) with the result: alias "Mac HD:Users:administrator:Documents:"

Choose folder window
Choose folder window

Where 'prompt' is the text string that appears at the top of the dialog window. When the user selects a folder the alias to that folder is placed in the variable 'thefolder'

There are 4 optional parameters: default location, with (or without) invisibles, with multiple selections allowed and showing package contents. Used together, they look like this:

set theFolder to choose folder with prompt ("Select a folder:") default location (path to documents folder) with invisibles, multiple selections allowed and showing package contents

Although you aren't likely to use all of the possible parameters, I will explain each one here:

default location: The dialog opens with the specified path shown

with invisibles: This shows files that aren't ordinarily visible. Most of you will not need to use this parameter, it can be dangerous to tinker with these files, but if you have a reason...

multiple selections allowed: This allows you to choose more than one folder; each folder alias is separated by a comma in the form: {alias 1,alias 2.....}

showing package contents: This is also not ordinarily visible to the user; it displays bundle contents of application packages.

The next article will cover the 'choose file' command, which allows you to select a specific document and get its alias for further script execution. It has parameters that are very similar to the 'choose folder' command, so it should be very easy to pick up how to use it.

Choose File Dialogs

Getting a reference to a specific document for further script execution

In this article, we continue with the 'choose file' command. Like the 'choose folder' command, it returns a reference pointer to the actual file that it represents. In this case, it returns an alias reference to a document such as:

set theFile to choose file with prompt "Select a file to open:"

--> with a result such as this: alias "Mac HD:Users:administrator:Documents:My Document.cwk"

Choose file dialogs have 3 of the same 4 optional parameters, which function identically to the ones used with choose folder dialogs (there is no showing package contents parameter): default location, with (or without) invisibles and with multiple selections allowed.

One additional parameter, not available with the choose folder command is the 'of type' parameter. This is used when you want to specify what types of files to show:

set theFile to choose file of type {"public.jpg", "public.gif"} with prompt "Select a file to open:"

If you like this site, leave a comment at the bottom of this page.

Apple iMac G4
Apple iMac G4

Choose File Name Command

The 'choose file name' command is similar to the 'choose file' command

Unlike the choose file command, 'choose file name' returns a reference pointer to a file that does not yet exist without actually creating the file:

set theFile to choose file name with prompt "Set file name and location:"

--> with a result such as: file "Mac HD:Users:administrator:Desktop:Untitled"

Choose file name dialogs have 3 optional parameters: 'with prompt' , 'default name' and 'default location'.

Here with the optional parameters:

set theFile to choose file name with prompt "Set file name and location:" default name "Document 1" default location (path to documents folder)

It is pretty simple to see that the last two parameters determine the name of the yet to be created document and its location.
Finally, a TextEdit example that actually creates a document:

set fileReference to choose file name with prompt ("Create new document:") default name "My Text Document" default location (path to desktop)
set newDocText to text returned of (display dialog "Enter initial text for document '" & fileReference & "':" default answer "" with icon note buttons "OK" default button "OK")
open for access fileReference
close access fileReference
tell application "TextEdit"
	activate
	open fileReference
	set text of document 1 to newDocText
end tell

Where fileReference is the reference for the new document and newDocText is the initial text for the new document.

These lines create the new document and then close it:

open for access fileReference

close access fileReference

TextEdit reopens the document and inserts the text stored in the variable newDocText. TextEdit refers to the document as document 1 because it is the front document.

In the next article, I will backtrack a little bit to show you the enhanced parameters for 'choose from list' which became available in Tiger and Leopard.

Enhanced Choose from List (Tiger and Leopard)

Since Tiger (10.4) and Leopard (10.5) came out, Choose from List has a few new parameters that I will cover in this section. In case you need to refresh your memory on the basics of this, here is the basic command again:

set theName to (choose from list {"John", "Joe", "Bill"} with prompt "Choose a name:")
if theName is false then
	display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
	set theName to (item 1 of theName)
	display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if

Since there are a number of enhancements to cover here, I will start by presenting a script which uses all of them (they are highlighted), and then explain their significance:

set theName to (choose from list {"John", "Joe", "Bill"} with prompt "Choose a name:" with title "Database Names" default items {"Joe"} OK button name "Choose" cancel button name "Abort" with multiple selections allowed)
if theName is false then
	display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
	set theName to (item 1 of theName)
	display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if

with title "Database Names": sets the text in the titlebar to "Database Names"

default items {"Joe"}: The dialog selection 'Joe' is selected when the dialog opens.

with multiple selections allowed: If you click on more than 1 item while holding down the shift key a comma-delimited list of the items is returned as the result.

OK button name "Choose": The OK button is renamed "Choose" and behaves as the "OK" button would.

cancel button name "Abort": The cancel button is renamed "Abort" and behaves as the "Cancel" button would.


The 'choose application' command will be covered in the next article. It is somewhat similar to the 'choose file' dialog.

Choose Application

The 'choose application' command is very similar in syntax to the 'choose file' command.

The two commands are so similar that I will not go into too much detail. As I have done in some other sections, I will present a script and then explain the purpose of the parameters used as needed:

set theApp to choose application with title "Installed Applications:" with prompt "Select an application:"

With a result in the form: application "Adobe ImageReady 7.0". The application is automatically opened.

Both of the parameters here, you should recognize.


Here is an example of how the 'choose file' and 'choose application' commands can be used together to open a text file:

set theFile to choose file of type "TEXT" with prompt "Locate a text document to open"
set theApp to choose application with title "Installed Applications:" with prompt "Select an application to open '" & theFile & "':" as alias
tell application "Finder" to open theFile using theApp

This is all pretty straightforward, so if you carefully look over the syntax of this, I don't expect you will have any difficulty with this.

Choose color window
Choose color window

Choosing a Color from the Color Picker

The final 'choose' command, 'choose color' will be covered here. The choose color dialog is somewhat obscure and you aren't as likely to use it often as the others, but it is worth mention. It is not complicated at all. The script below results in the color picker window, with the rainbow effect as in the image to the left:

set colorPref to choose color default color {31270, 38327, 65535}

If the user clicks on the "OK" button without choosing a color, the RGB value {31270,38327,65535} is assigned to the variable colorPref, otherwise its value is set to whatever RGB value results from where the user clicked in the color wheel.

We can then use that value in a script such as this which changes the background color of the frontmost finder window:

set colorPref to choose color default color {31270, 38327, 65535}
tell application "Finder"
	activate
	tell icon view options of front Finder window
		set background color to colorPref
	end tell
	set current view of front Finder window to icon view
end tell

This changes the background color for the icon view only. All of the other views remain unchanged.

Contact me with your questions or suggestions.

Error Handling for Dates

I was inspired to write this script when I discovered that some of the dates that I had entered in a database program that I use, namely FileMaker, had erroneous dates. This script tests for the validity of entered dates. In this script, I have purposely made the default answer to the opening dialog an invalid date to illustrate what happens, when a date is entered which has the incorrect weekday name, but is otherwise valid. The script continues, with testing for other common instances where erroneous info might be inadvertantly entered.

Copy this and run it in the script editor:

try
	set AppleScript's text item delimiters to ","
	set testDate to text returned of (display dialog "Enter a date:" default answer "Tuesday, October 10, 2012" buttons "Test" default button "Test")
	set dateCharCount to (count characters of testDate)
	set commaCount to 0
	repeat with x from 1 to dateCharCount
		if character x of testDate = "," then set commaCount to commaCount + 1
	end repeat
	set testWeekday to (text item 1 of testDate)
	set validWeekdays to {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
	set validMonths to {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
	set testMonth to (word 1 of text item 2 of testDate)
	set testDay to (word 2 of text item 2 of testDate)
	set testYear to (word 1 of text item 3 of testDate)
	set compareDate to date string of (date testDate)
	if testDate is not equal to compareDate then
		display alert "Invalid Date" message "The date, " & testDate & ", which was entered, is invalid ! The correct date is: " & compareDate buttons "Abort" default button "Abort" as warning
	else
		display alert "Valid Date" message "The date " & testDate & "is valid." buttons "OK" default button "OK" as informational
	end if
on error theError number theNumber
	if theNumber = -30720 then
		if testWeekday is not in validWeekdays then
			display alert "Error number " & theNumber & ": Invalid Weekday" message "The weekday, " & testWeekday & ", entered for this date is invalid !" buttons "Abort" default button "Abort" as warning
		else if testMonth is not in validMonths then
			display alert "Error number " & theNumber & ": Invalid Month" message "The month " & testMonth & "entered for this date is invalid !" buttons "Abort" default button "Abort" as warning
		else if not (testDay is number) then
			display alert "Error number " & theNumber & ": Invalid Day" message "The day " & testDay & "entered for this date is invalid !" buttons "Abort" default button "Abort" as warning
		else if not (testYear is number) then
			display alert "Error number " & theNumber & ": Invalid Year" message "The year " & testYear & "entered for this date is invalid !" buttons "Abort" default button "Abort" as warning
		end if
	else if theNumber = -1728 then
		display alert "Error number " & theNumber & ": Invalid Date Format" message "Commas have been omitted for the date " & testDate & "!" buttons "Abort" default button "Abort" as warning
	end if
end try

Most of this script is easy to follow, but just a few script lines to take note of when testing for validity:

1. To test for a general instance of validity, we use:

set testDate to text returned of (display dialog "Enter a date:" default answer "Tuesday, October 10, 2012" buttons "Test" default button "Test")

-->Here is where I have placed an erroneous date; October 10, 2012 which actually falls on a Wednesday

set compareDate to date string of (date testDate)
if testDate is not equal to compareDate then

We save the entered date in the variable testDate because, if we don't, AppleScript will coerce the entered text to a valid date (if it is invalid) and therefore no comparison can be made. With the variable testDate already set, we can set a second variable compareDate that can be coerced to a valid date, if necessary, so that we can compare the values of the two variables.

2. We use lists of valid weekdays, validWeekdays and valid months, validMonths to compare with the weekday or month entered by the user. The variable testYear is tested with the statement: else if not (testYear is number) then If an invalid weekday or month is entered it triggers an appropriate error handler for error number -30720.

3. Finally, just a punctuation test, which uses a count variable dateCharCount to count how many commas are found in the entered text, because there should be 2 in a valid date and, if not, error number -1728 is triggered.

Concatenation or Parsing and Editing of Text Strings

Everything, well almost everything you need to know about text. In this section I deal with various methods to extract different parts of text from lists and other text and at the end, how to put it all together to make a new text string.

This is sort of lengthy, but it is pretty easy to follow.

First, to extract text from a list. Both of these result in the text “Computer”

set theTextList to {"Apple", "Computer"} as list

last item of theTextList

last text item of theTextList --> both statements yield 'Computer'

And then using the 'reverse' keyword:

set theTextList to {"Apple", "Computer", "Inc"} as list
last text item of theTextList --> yields "Inc"
set theTextList to reverse of theTextList --> yields {"Inc", "Computer", "Apple"}
last text item of theTextList --> yields "Apple"

As you can see, the keyword 'reverse' changes the order of items in a list.

If we want to extract a specific word:

set theTextString to "Apple Computer, Inc"
set theAppleString to word 1 of theTextString
display dialog theAppleString --> yields "Apple"

If we want to extract a specific paragraph:

set theTextString to "Apple Computer, Inc" & return & "Home of Mac OS X"
set theAppleString to paragraph 2 of theTextString
display dialog theAppleString --> yields "Home of Mac OS X"

Extracting by numerical index:

set theTextString to "Apple Computer"
set computerStringStart to offset of "Computer" in theTextString
display dialog computerStringStart --> yields 7: position of first letter in the word 'Computer'
set computerText to (text computerStringStart thru -1 of theTextString)
display dialog computerText --> yields 'Computer'-1 is the index for the last letter of the text string, no matter how long the string is; a lot easier than having to determine how long the string is every time!

The same as saying:

set computerText to (text 7 thru -1 of theTextString)
Of course, if we wanted to, we could say:
'set computerText to (text 7 thru 14 of theTextString)' but why, when we wont always know the total number of characters (text) in any given string?
set theTextString to "Apple Computer"
set theAppleString to text 7 thru -2 of theTextString
display dialog theAppleString --> yields 'Compute'-2 gets the numeric index of the letter in 'Computer' that is 2 from the end.



set theTextString to "Apple Computer, Inc"
set theAppleString to text 1 thru -1 of theTextString
display dialog theAppleString --> yields: "Apple Computer, Inc"



set theTextString to "Apple Computer, Inc"
set theAppleString to (words 1 thru -1 of theTextString) as text
display dialog theAppleString --> yields "AppleComputerInc"



set AppleScript's text item delimiters to ","
set theTextString to "Apple Computer, Inc"
set theAppleString to (text items 1 thru -2 of theTextString) as text
display dialog theAppleString --> yields "Apple Computer"

The following would give the same result:

set AppleScript's text item delimiters to ","
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text
display dialog theAppleString

Why? Because with 'set AppleScript's text item delimiters to ","' , what is found before a comma is a text item and what is after a comma is another text item - this can be very useful.

Look at this:

set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text
display dialog theAppleString --> this yields "Apple", because the space determines the value of text items.

set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 2 of theTextString) as text
display dialog theAppleString --> this yields "Computer,", because, once again, the space determines the value of text items.

This illustrates how to concatenate some text to display a dialog:

set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text --> the result is "Apple", because the space determines the value of text items
set theComputerString to (text 1 thru -2 of text item 2 of theTextString) as text --> the result is "Computer", because the space determines the value of text items and 'text 1 thru -2' eliminates the comma

Now we can put it all together:

set dialogString to "Too bad all " & theComputerString & "'s aren't " & theAppleString & "s!"
display dialog dialogString with icon note buttons {"No Doubt"} default button {"No Doubt"} giving up after 5
iTunes, Apple, Inc
iTunes, Apple, Inc | Source

Using Say and Listen Commands with iTunes

In this article, we look at the say and listen commands

Before you try to run this script, go to the Speech Preferences and click on the Speech Recognition tab and click speech on. Also, if you have not used speech recognition before, click on the 'Calibrate...' button. It adjusts speech recognition to your personal voice to optimize its responsiveness. Here is a previous script, which we will use (in part) in this article:

tell application "iTunes"
activate
set visible of front window to true
set view of front window to playlist "Hall & Oates"
copy (get view of front window) to thePlaylist
set soundValue to (choose from list {"25", "50", "75", "100"} with prompt "Select volume level:" OK button name "Play" cancel button name "Abort")
set soundValue to soundValue as integer
set sound volume to soundValue
play thePlaylist
end tell

The new script:

tell application "iTunes"
activate
set visible of front window to true
set myMusic to (name of every playlist)
end tell

set userResponse to voiceQuery("Which playlist would you like to hear?", myMusic, 30)
if userResponse is false then error number -128
say "Playing " & userResponse & " please wait"

tell application "iTunes"
activate
set thePlaylist to userResponse
set view of front window to playlist thePlaylist
copy (get view of front window) to thePlaylist
play thePlaylist
end tell

on voiceQuery(userPrompt, theseItems, timeoutValue)
set cancelCmds to {"Cancel"}
set matchItems to cancelCmds & theseItems
try
tell application "SpeechRecognitionServer"
set userResponse to listen for matchItems with prompt userPrompt giving up after timeoutValue displaying theseItems
end tell
if userResponse is in cancelCmds then
error "user cancelled"
end if
return userResponse
on error
display dialog "The music did not play!"
return false
end try
end voiceQuery

The statement 'set myMusic to (name of every playlist)' gets all of the playlists on your hard drive and puts them into the variable myMusic.

The statement
'voiceQuery("Which playlist would you like to hear?", myMusic, 30)' calls the function 'on voiceQuery(userPrompt, theseItems, timeoutValue)' and places the values into the corresponding variable parameters.

voiceQuery(...) returns a value in the variable userResponse and, if it is not false, plays the desired playlist.

© 2013 AppleScripter

More by this Author

  • AppleScript and FileMaker
    4

    Learning How to Write FileMaker Pro Scripts for Beginners. Free AppleScripts for those who are new. Many scripts are a mix of AppleScript and FileMaker.

  • Advanced AppleScript Code
    0

    Advanced AppleScripts. For reasons of logic, because the original site was becoming rather large, some of the posts you find here were moved from the primer site for those who are beyond the basics

  • More Advanced AppleScript Code
    0

    For those of you who still cannot get enough AppleScript to feed your fix, some more free applescript code,Finder,Microsoft Word,Pages,AppleWorks,PowerPoint,TextEdit,iTunes,POSIX paths,database events


Problems or Questions on AppleScript? 1 comment

Gus 3 years ago

hey thx for the tutorials, it helped me a lot ! One question, in the printing properties, how would you set gray shade printing activated or true ? thx a lot !

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working