Advanced AppleScript Code
Ranked #2,135 in Computers & Electronics, #36,941 overall
Learning Advanced AppleScript Code
Here and there, I will briefly review more basic scripts (or link you to the scripts) where I feel they may be helpful. You will notice that some of the posts that you find here were in the original website, but don't despair, they are not duplicate content, it's just that some of the more advanced ones have been moved to this site for reasons of logic and due to the fact that the sheer size of the original site was making it unmanageable.
Creating New AppleWorks Document Using GUI
This script shows how to go about using GUI to perform menu and sub-menu tasks with AppleWorks 6 to copy the content of the frontmost window to the clipboard and to paste it into a new document.
This script presumes both that Assistive Devices is enabled and that AppleWorks is currently running and has an open text document:
try
tell application "AppleWorks 6"
activate
end tell
(*There are 3 main sub-scripts contained within the 'tell menu bar 1' part of the script below*)
tell application "System Events"
tell process "AppleWorks 6"
tell menu bar 1
--This selects and copies the contents of the frontmost document to the clipboard
tell menu bar item "Edit"
tell menu "Edit"
click menu item "Select All"
click menu item "Copy"
end tell
end tell
--This creates a new text document
tell menu bar item "File"
tell menu "File"
tell menu item "New"
tell menu "New"
click menu item "Word Processing"
end tell
end tell
end tell
end tell
--Finally, this pastes the contents of the clipboard into the new document
tell menu bar item "Edit"
tell menu "Edit"
click menu item "Paste"
end tell
end tell
end tell
end tell
end tell
return true
on error theError
return false
end try
Give me your opinion on this post: hyperscripter@gmail.com or http://facebook.com/hyperscripter
How to Enable GUI Scripting
To enable GUI, click on the checkbox entitled 'Enable access for assistive devices' at the bottom of the pane illustrated below. I highly recommend that you disable it again, either manually or from a script, when you don't need to use GUI, unless you're sure that you are comfortable with leaving it active all the time.Go to: Security Issues with GUI and the Internet
Converting Month of Date into a Different Format
How to Convert Month Name to its Numerical Data and Visa-Versa
This can be very useful when, for instance, you have databases in which you need to display the date in a long, more user-friendly form, and in another, where you want a more condensed, short date for a concise report in tabular form that you may want to print out at a later date. I will also show you the basics of function handlers so that when you have repetitive tasks that need to be performed often, they can be called from your main scripts 'on-the-fly'.
This converts a month name to its numerical data:
set convertMonth to text returned of (display dialog "Enter a month to convert to numerical data:" default answer "" buttons {"Cancel","Set"} default button 2)
set monthText to convertMonth
set convertMonth to (convertData (convertMonth))
display dialog "Numerical conversion for month of " & monthText & ": " & convertMonth with icon 1 buttons {"OK"} default button 1 giving up after 6
The function handler called by the main script (see 'set convertMonth to (convertData (convertMonth))' above):
on convertData (theMonth)
set monthList to {January, February, March, April, May, June, July, August, September, October, November, December}
repeat with i from 1 to 12
if theMonth = ((item i of monthList) as string) then
set monthNumber to (text -2 thru -1 of ("0" & i))
exit repeat
end if
end repeat
return monthNumber
end convertData
This converts a month number to its actual name data:
set convertNumber to text returned of (display dialog "Enter a number from '01 to 12' to convert to month name:" default answer "01" buttons {"Cancel","Set"} default button 2)
set numberText to (convertNumber as string)
set convertNumber to (convertData (convertNumber))
display dialog "Month conversion for number " & numberText & ": " & convertNumber with icon 1 buttons {"OK"} default button 1 giving up after 6
The function handler called by the main script (see "set convertNumber to (convertData (convertNumber))" above):
on convertData (theNumber)
set theNumber to (theNumber as text)
if (text -2 of theNumber = "0") then set theNumber to (text -1 of theNumber)
set numberList to {"1","2","3","4","5","6","7","8","9","10","11","12"}
set monthList to {"January","February","March","April","May","June","July","August","September","October","November","December"}
repeat with i from 1 to 12
if theNumber = (text item i of numberList) then
set monthName to (text item i of monthList)
exit repeat
end if
end repeat
return monthName
end convertData
Amazon On the Go
Great Deals on MP3 Players, Music and More
GUI Scripting for System Preferences Panes and Apps
By directing script statements to the 'System Events' application, you can get the system to perform keyboard and other tasks as if you were actually manually performing them yourself. It is not only a great way to automate tasks, but it is also an effective measure for applications that are otherwise 'unscriptable'. This is referred to as General User Interface Scripting (or 'GUI' Scripting).
Here I will give you two examples of this, one directed to System Preferences, and another example directed to AppleWorks 6 to perform menu tasks that can also be applied to other applications that, while they are scriptable to an extent, do have some limitations.
First, one that deals with the Universal Access preferences pane of System Preferences:
tell application "System Events"
(*If the checkbox (in Universal Access Preferences) with the prompt "Enable access for assistive devices" is not enabled, then the user is prompted to click the box to enable it.*)
if not (UI elements enabled) then
tell application "System Preferences"
activate
set current pane to pane id "com.apple.preference.universalaccess"
display dialog "To proceed, you must enable access for assistive devices." & return & return & "Click 'OK' and enter the security password." with icon 0
end tell
(*If the user clicks 'OK', enters the correct security password and then enables the checkbox, then assistive devices is enabled:*)
set UI elements enabled to true
(*If the user clicks 'Cancel', enters an invalid security password or does not enable the checkbox, the script is aborted without any action being taken*)
if not (UI elements enabled) then return
delay 1
end if
end tell
Now the second, which performs menu tasks in AppleWorks 6 that checks first to determine that Access for Assistive Devices is enabled and, if not, it will pass the script on to Universal Access to notify the user that Assistive Devices needs to be enabled to perform the script:
try
tell application "AppleWorks 6"
activate
end tell
tell application "System Events"
if not (UI elements enabled) then
tell application "System Preferences"
activate
set current pane to pane id "com.apple.preference.universalaccess"
display dialog "To proceed, you must enable access for assistive devices." & return & return & "Click 'OK' and enter the security password." with icon 0
end tell
end if
tell process "AppleWorks 6"
tell menu bar 1
tell menu bar item "File"
tell menu "File"
click menu item "Print%u2026"
end tell
end tell
end tell
end tell
end tell
return true
on error errorMsg
display dialog errorMsg
end try
In the previous script, you could substitute any number of menu commands (most will work without any further scripting). With a little more knowledge of GUI, you could also script to send commands to specific panes that come up when you choose menu items requiring further user input.
NOTE OF CAUTION: Avoid writing scripts that may delete or potentially permanently alter original contents. For instance, if you really need to use such menu items as 'Cut' or 'Clear' it is wise to use them in conjunction with a confirmation dialog, so that the user will be able to abort the action, if desired.
Once you get the hang of it, you will have a sort of intuition on how to delve into GUI's for your specific requirements. If you have any questions about AppleScript, contact me at: hyperscripter@gmail.com or to subscribe, click the By Email link at the top of the page.
The How and Why: Coercing Record and List Data Types
When I was new to scripting, I had a lot of problems with coercing records into lists and visa-versa. It wasn't really the coercing that was so difficult, it was getting the resulting data into a useable form. In addition, I didn't see any real advantage to doing so.
Here, I will try to make clear to my readers, through a number of examples of how to coerce these data types into each other and how to transform that info into a form suitable for further manipulations. I hope that you will come away from this with a sense of the usefulness of these coercions.
Keep in mind, that where I use -- result>...etc.., it indicates the result of execution of a script line.
Note that, due to some formatting problems, if you want to cut and paste any of this for your own use, you will have to convert the quotes from curly quotes so that Script Editor will be able to compile.
First, the statement:
set employee to {name:"Amber Clark", address:"1156 Bendelow Lane", phone:"1-456-228-4338"}
-- result>{name:"Amber Clark", address:"1156 Bendelow Lane", phone:"1-456-228-4338"}
This is straightforward record syntax. Nothing earth-shattering. It essentially assigns an identifier to a given value, similar to when you assign a value to a variable.
Using this we can say:
phone of employee
set employeePhone to (phone of employee)-- result, in both cases>"1-456-228-4338"
Again, nothing earth-shattering. If we want to extract the values without their corresponding identifiers we just say:
employee as list
-- result>{"Amber Clark", "1156 Bendelow Lane", "1-456-228-4338"}
And then we can revert back to the record data type again, if we wish:
employee as record
-- result>{name:"Amber Clark", address:"1156 Bendelow Lane", phone:"1-456-228-4338"}
So far, we've established that we can go back and forth fairly easily and extract specific elements.
Using the 'display dialog' construct, we can set any number of records for any number of employees, i.e.: set employee1, set employee2 etc.
Take a look at this example:
set employeeName to text returned of (display dialog "Enter employee name" default answer "" with icon 1)
set employeeAddress to text returned of (display dialog "Enter employee address" default answer "" with icon 1)
set employeePhone to text returned of (display dialog "Enter employee phone number" default answer "" with icon 1)
set employee to {name:employeeName, address:employeeAddress, phone:employeePhone}
-- result> returns: {name:"Amber Clark", address:"1156 Bendelow Lane", phone:"1-456-228-4338"}, ¬
--where "Amber Clark","1156 Bendelow Lane" and "1-456-228-4338" is entered
If we want to use the data for other manipulations, we must assign the desired info to a variable.
This will store a 'choose from list' selection in the variable 'employeeChoice', but if we try to use it as raw data, AppleScript will send an error that it cannot be processed in it's present form because it is still seen as a list item.
set employeeList to (employee as list)
-- result>{"Amber Clark", "1156 Bendelow Lane", "1-456-228-4338"}
set employeeChoice to (choose from list employeeList with prompt "Choose from data for " & employeeName & ":")
-- result>{"Amber Clark"}
However, if we end the statement with 'as string' as below, it is coerced into a form that can be used for text manipulations (in other words, without the curly quotes):
set employeeChoices to (choose from list employeeList with prompt "Choose from data for " & employeeName & ":") as string
-- result>"Amber Clark"
You can easily see how this can be useful when, for instance, you want to coerce a string into an alias, or an alias into a POSIX path.
If you have any questions about AppleScript, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter or to subscribe, click the By Email link at the top of the page.
Twentieth Anniversary Macintosh
Using Google Maps to Find an Address from FileMaker Pro
A Handy Script that Automates Google Maps
It can be enhanced with a 'choose from list' dialog for frequent address searches or (as you'll see below) you can enhance the script with a database program such as FileMaker Pro, to search for an address from a specific record.
Some notes below, but first the script:
try
set findAddress to text returned ¬
of (display dialog ¬
"Enter address to find:" default answer "Your address here")
exists application "Firefox"
tell application "Firefox"
activate
delay 5
open location ¬
"http://www.google.com/maps"
delay 10
tell application "System Events"
keystroke findAddress
keystroke return
end tell
end tell
on error
display alert ¬
"No address has been entered." message ¬
"Enter required info and try again." as warning
end try
Remember, that for this to work correctly, GUI Scripting must be enabled.
Take note of the statement 'exists application "Firefox"'. I use this because it will activate Firefox and helps with the timing of the delays that follow, which still may need to be adjusted for slower internet access and the speed of your processor.
Between the exists statement and activate there should be enough time for Firefox to be ready to go before the rest of the script continues.
After the Google map page opens, System Events, which requires GUI Scripting, takes over and enters the address in the address field and sends the return command to send the request for the map. It's that simple!
This code below can be used with FileMaker Pro in place of the 'display dialog' text entry code at the beginning of the script.
tell application "FileMaker Pro"
set googleSearch to (get cell "Address" of current record) & " " & (get cell "City" of current record) & ", " & (get cell "State" of current record) & " " & (get cell "Zip Code" of current record)
copy googleSearch to (cell "googleAddress" of current record)
end tell
Just a side note for those that are not familiar with the 'display alert' syntax, that I use in the error block above to see how to write this code go to Display Alert
Books Available at Amazon
Recommended Manuals for Aspiring AppleScript Nerds
Related Sites on AppleScript
Script to Open Gmail Inbox in Firefox
This is a quick and easy way to go to your Gmail Inbox
This script assumes that you have an email account set up through Gmail:
tryset isLoggedIn to button returned ¬
of (display dialog "Have you already logged in ¬
to your email account for this session?" ¬
buttons {"Yes", "No"} default button 2 ¬
with icon note)
if isLoggedIn = "No" then
set theEmail to text returned of ¬
(display dialog "Enter your email account ¬
here:" default answer "yourEmail@gmail.com")
set thePassword to text returned of ¬
(display dialog "Enter your password here:" ¬
default answer "" with hidden answer)
if theEmail = "" or thePassword = "" then error
end if
exists application "Firefox"
tell application "Firefox"
activate
delay 3
if isLoggedIn = "No" then
open location ¬
"https://www.google.com/accounts/ServiceLogin?"
delay 10
tell application "System Events"
keystroke theEmail
keystroke tab
keystroke thePassword
keystroke return
end tell
end if
open location "http://mail.google.com/mail/#inbox"
end tell
on error
display alert "Either your email or password ¬
have not been entered." message "Please enter ¬
the required info and try again." as warning
end try
This script is pretty straightforward. The login dialog prompts gather the email address and password data and place them into the corresponding variables 'theEmail' and 'thePassword'. If either the email or password is not entered, an error message is displayed and the script is aborted.
When Firefox has been launched, the 'System Events' application uses Apple's GUI scripting capability to automate the entry of the text data into the text fields and sends the data to Gmail. For this to work correctly, be sure that the Enable Access for Assistive Devices check box (in your system's Universal Access contol panel in System Preferences) is enabled (for GUI Scripting).
Contact me if you have any questions or comments at: hyperscripter@gmail.com or http://twitter.com/hyperscripter
Advanced AppleScript Guestbook
Give me your opinion on these articles. Suggest new topics.
if you have a topic to suggest of a more advanced nature you can submit it here. If you're fairly new to AppleScript and have a question of a more general nature, I highly recommend that you first visit http://www.squidoo.com/applescript. If then, you still have questions on an issue, please submit your questions to the
AppleScript Guestbook.
Products from CafePress
Everything from Mugs to Sweatshirts for the Scripter
AppleScript Droplet to Convert Text to HTML
Automation of your HTML Templates
Sometimes it's nice to just eliminate some typing when creating html documents, especially when you write your HTML by hand (as I do). Even if it is just for the sake of setting up the initial template so you can get down to the details more efficiently.
Copy this into your Script Editor and be sure to save it as an application.
on open (dropDocument)
set dropInfo to (info for dropDocument)
set dropType to (kind of dropInfo)
if name of dropInfo contains ".html" or name of dropInfo contains ".htm" then
display alert "This is an HTML document!" message "Drop a text document on this droplet!" as warning buttons {"Abort"} default button 1 giving up after 10
else if dropType contains "document" then
tell application "AppleWorks 6"
activate
open dropDocument
set htmlData to ""
repeat with x from 1 to (count paragraphs of document 1)
set htmlData to htmlData & (paragraph x of document 1 & "")
end repeat
set docRefText to "Converted to HTML"
set htmlBody to htmlData
set htmlData to "" & return & "" & return & "--" & docRefText & return & "" & return & "" & return & htmlBody & return & "" & return & ""
make new document at front with data htmlData with properties ¬
{document kind:text document, name:"Converted to HTML.html"}
end tell
end if
end open
If you have any questions about AppleScript, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter or to subscribe, click the By Email link at the top of the page.
Working with Dates and Using Math Operators
An Unexpected Use of Less than and Greater than Operators
This, of course, contradicts everything that we did in math class at school, but it actually is a bullt-in capability of the AppleScript language.
If you run this first script in Script Editor you can see that AppleScript can understand the use of greater than and less than. This script coerces default or entered text to date format with the time appended and returns a result reflecting which time of the entered date occurs logically before the other:
set targetDate to date string of (current date)
set targetDate to text returned of (display dialog "Enter a date:" default answer targetDate buttons {"OK"} default button 1)
set dateTime1 to date (targetDate & " 1:00:00 PM")
set dateTime2 to date (targetDate & ":" & " 7:00:00 AM")
set datetext to date string of dateTime1
set time1 to time string of dateTime1
set time2 to time string of dateTime2
set dateTimeString1 to dateTime1 as string
set dateTimeString2 to dateTime2 as string
if (dateTime1 > dateTime2) then
display dialog (datetext & return & return & time1 & " occurs after " & time2 & ".")
else if (dateTime1 < dateTime2) then
display dialog (datetext & return & return & time2 & " occurs after " & time1 & ".")
end if
And then this example that uses just a little bit of FileMaker scripting at the beginning. It uses the 'exists' keyword to determine if the date can be found before proceeding and therefore is faster than if you tried this by using a repeat loop. Also, since the conditional pre-qualifies the show statement, there is no need for an error handler, although I include one here, because it is always a good practice, since there can always be some circumstance that you may have not anticipated. (FileMaker is in bold):
Freeze Window
Perform AppleScript [tell application "FileMaker Pro"
activate
tell database 1
show every record
sort layout 0 by {field "sortDate"} in order ascending
--'sortDate' is a field defined as type date
set targetRecord to (get ID of current record)
try
set targetCalcDate to (current date)
set targetFound to true
set searchDate to date string of (targetCalcDate)
if exists (some record where searchDate is in ¬
cell "AppointmentsDate") then
--'AppointmentsDate' is a text field that
--contains the long date of each record
show (every record where searchDate is in ¬
cell "AppointmentsDate")
else
set targetFound to false
end if
if targetFound = false then display dialog ¬
"The date \"" & searchDate & ¬
"\" was not found!" with icon 0 buttons {"OK"} ¬
default button 1 giving up after 10
on error errorMsg
display dialog errorMsg
show every record
sort layout 0 by {field "sortDate"} in order ascending
set targetRecord to (get ID of current record)
end try
set targetRecord to (get ID of current record)
show every record
sort layout 0 by {field "sortDate"} in order ascending
go to record ID targetRecord
end tell
end tell]

Have questions or suggestions? Give me your opinion on my site. Please go to the Advanced AppleScript Guestbook and leave a comment. If you like this site, please click on one of the stars at the top of the page to rate me, to subscribe, click the Email button at the top of the page.
Extracting Text Using Offset and Reverse vs Text Item Delimiters
There are times when you want to extract part of a text string from another for some specific purpose. There are two basic methods and each has its advantages and disadvantages. We'll start with a combination of offset and reverse to remove the suffix from "seattleSunset.jpg":
set jpgFile to characters of "seattleSunset.jpg"
--This gives us the characters as a list: {"s", "e", "a", "t", "t", "l", "e", "S", "u", "n", "s", "e", "t", ".", "j", "p", "g"}
set jpgFile to (reverse of jpgFile) as string
-->result: "gpj.tesnuSelttaes"
Or we can combine the statements into one:
set jpgFile to (reverse of characters of "seattleSunset.jpg") as string
-->result: "gpj.tesnuSelttaes"
Next we extract the file name without the prefix:
set periodDelimiter to offset of "." in jpgFile
set jpgFile to text (periodDelimiter + 1) thru -1 of jpgFile
-->result: "tesnuSelttaes"
set AppleScript's text item delimiters to {""} --we must reset the item delimiters to empty for this to work correctly
set jpgFile to (reverse of characters of jpgFile) as string
--After resetting the item delimiters, we use the same syntax as above.
First, remembering that what is in parentheses is performed first, jpgFile is coerced to list form and converted to the reverse order.
Then it is coerced back to a string: "seattleSunset"
If we start with set jpgFile to characters of "seattleSunset.jpeg" we still get the result: "seattleSunset"
Note that we could set the text item delimiters to "." to get the same result:
set AppleScript's text item delimiters to "."
set jpgFile to text item 1 of "seattleSunset.jpg"
-->result: "seattleSunset"
The problem with this method is that if we have something such as "http://www.scriptsforapple.com/" (my website), the result is: "http://www", which is probably not the result that we want. The original version, however gives us "http://www.scriptsforapple" which is useful if we want to change ".com/" to ".org/":
set AppleScript's text item delimiters to "."
set theURL to "http://www.scriptsforapple.com/"
set AppleScript's text item delimiters to {""}
set trimURL to (reverse of characters of theURL) as string
set periodDelimiter to offset of "." in trimURL
set trimURL to text (periodDelimiter + 1) thru -1 of trimURL
set trimURL to (reverse of characters of trimURL) as string
set theURL to trimURL & ".org/"
-->"http://www.scriptsforapple.org/"
The point here being that if you use this method, you can get the correct result for many, if not most, cases that you will encounter. That is not to say that there are not times when using text item delimiters alone will not be the right way to go depending upon the situation.
Give me your opinion on my site. Please go to the Advanced AppleScript Guestbook and leave a comment or suggestion. If you like this site, please click on one of the stars at the top of the page to rate me.
Working with Dates in AppleScript
If you have ever worked with date coercions and manipulations in AppleScript, you know how frustrating it can be, from something as simple as trying to coerce it to text so that it can be displayed in a dialog, to trying to convert it to a different date format; you have one simple thing in your syntax that keeps causing errors and you just can't figure it out!Here, I will try to help you through some of the most common frustrations that you will encounter. First, something that I have found very useful in my specific work, a script that verifies whether or not a date is valid in the first place. It is really pretty simple, and relies on AppleScript error messaging.
The second will deal with two aspects of coercions: 1) Converting a date in textual form to date format and then 2) Determining a future date (1 week hence, 1 month hence, etc) from the given date. This is particularly useful in databases when you want to determine a future appointment for a customer, when it is supposed to be scheduled at a regular given interval.
First, validating a given date. Keep in mind that getting the current date will also include the time of day, which may not be useful for what you want to do. Run this in the Script Editor:
set dateRecord to (current date)
set defaultDate to (date string of dateRecord)
try
set apptDate to text returned of (display dialog "Enter appointment date:" default answer defaultDate buttons {"Set"} default button {"Set"})
set datetext to apptDate as text
date apptDate --if an invalid date is entered, the next dialog is aborted and it triggers the error alert below.
display dialog datetext & " is a valid date." with icon note buttons {"OK"} default button {"OK"}
on error
set alertText to "An error has occurred!"
set messageText to quote & datetext & quote & " is an invalid date."
display alert alertText message messageText as warning buttons {"OK"} default button "OK" giving up after 15
return
end try
Now the second part, which is used here in a FileMaker database and is a bit more complex, but, once you understand how it works, can be used with other types of database formats that support AppleScript.
Like the previous script, it begins by getting the current date and coercing the result to text for further manipulations. Run this in Script Editor. The result will appear its result pane:
set AppleScript's text item delimiters to ","
set dateResult to (current date)
set comparisonDate to (date string of dateResult)
set calcBoolean to button returned of (display dialog "Determine date for next appointment?" with icon note buttons {"No", "Yes"} default button {"Yes"})
if calcBoolean = "Yes" then
set AppleScript's text item delimiters to "@"
--This next line would be used with FileMaker, otherwise something like the line of code that follows this line would compile just fine, in case you want to test this on your system:
--set prevAppointment to (get cell "History" of current record)
set prevAppointment to "Saturday, November 7, 2009 @ 8:00 am - see Joe Palmer about specs on upcoming contract"
set prevReference to (text item 1 of prevAppointment)
set dateResult to date prevReference
set scheduleInterval to (choose from list {"1 Week", "2 Weeks", "1 Month"} with prompt "Schedule interval:") as text
if scheduleInterval = "1 Week" then
set dateResult to (dateResult + 24 * 60 * 60 * 7)
else if scheduleInterval = "2 Weeks" then
set dateResult to (dateResult + 24 * 60 * 60 * 14)
else if scheduleInterval = "1 Month" then
set dateResult to (dateResult + 24 * 60 * 60 * 28)
end if
set targetDate to (date string of dateResult)
else if calcBoolean = "No" then
set targetDate to comparisonDate
end if
set defaultDate to targetDate
Questions or comments? Contact me at: hyperscripter@gmail.com or if you like this site, click on the twitter icon at the top of or bottom of the page the page. For RSS feed, click the RSS icon at the top or bottom of the page.
New Drawing Document with AppleWorks 6
The basics of creating a drawing document with AppleWorks 6 are similar to those for creating a text document.

The script below, appropriately named 'Graphics Hodgepodge', shows a variety of graphics objects that can be created and some of the properties that can be set with a script. There are a lot of details in this script, so we won't go into all of them. Reading the script should be explanation enough for most of this:
property cyan : {0, 65534, 65534}
property yellow : {65534, 65534, 0}
property red : {65534, 0, 0}
property blue : {0, 0, 65534}
property violet : {55000, 0, 65534}
tell application "AppleWorks 6"
make new document at front with properties ¬
{document kind:drawing document, name:"Graphics Hodgepodge"}
tell document "Graphics Hodgepodge"
set firstObject to (make new oval at front with properties {fill color:cyan})
set {xleft, ytop, xright, ybottom} to bounds of firstObject
make new rectangle at end with properties ¬
{fill color:yellow, bounds:{0, 250, 800, 500}, fill pattern:18}
make new rounded rectangle at end with properties ¬
{fill gradient:8, bounds:{xleft + 0, ytop + 40, xright + 400, ybottom + 40}, fill color:blue}
make new polygon at end with properties {fill color:red, fill pattern:16} with data ¬
{{xleft + 60, ytop + 60}, {xleft + 60, ytop + 160}, {xleft + 160, ytop + 160}, {xleft + 60, ytop + 60}}
set lastOval to (make new oval at front with properties {fill color:red})
select lastOval
set properties of firstObject to {bounds:{xleft + 0, ytop + 40, xright + 400, ybottom + 40}}
set properties of firstObject to {fill color:violet, fill pattern:64}
end tell
end tell
First we use properties to store RGB info on the colors we will use (saves some typing).
Next we tell AppleWorks to create a drawing document for us:
make new document at front with properties ¬
{document kind:drawing document, name:"Graphics Hodgepodge"}
In the next part, we direct statements to our new document "Graphics Hodgepodge":
set firstObject to (make new oval at front with properties {fill color:cyan})
set {xleft, ytop, xright, ybottom} to bounds of firstObject
This creates our first object, an oval, with the variables 'xleft, ytop, xright, ybottom' for the default object dimensions that will be used later and assigns a reference to the object (also needed later) to the variable firstObject.
The rest of the script pretty much explains itself. To create a new object use the syntax: 'make new objectType', where objectType can be oval (used also for circle), rectangle (used also for square), rounded rectangle and polygon. Use the bounds parameter to determine the size of the object.
You use fill gradient and fill pattern with an integer reference to the gradients (there are 32) and patterns (there are 64) available from their respective palettes.
By the way, for other types of AppleWorks documents, document kind can be any of the following: drawing document,text document,spreadsheet document,database document, painting document, presentation document

Conceptual Drawing for Modern iMac
Creating a Calendar in TextEdit with Shell Script
This is sort of a fun script which gives you some idea of the power behind the UNIX side of Mac OS X. Impressive as this little bit of shell code is though, it only scratches the surface on what you can do combining the power of AppleScript with the shell.display dialog "Choose a color for your calendar" buttons {"OK"} default button 1 giving up after 1
choose color default color {65535, 5786, 28421}
set calendarColor to the result
set defaultYear to year of (current date)
display dialog "Enter desired calendar year:" default answer defaultYear buttons {"Cancel", "Make Calendar"} default button 2
copy the result as list to {calendarYear, returnedButton}
if returnedButton = "Make Calendar" then
set cmdResult to (do shell script "cal " & calendarYear)
tell application "TextEdit"
activate
set yearCalendar to make new document with properties {text:cmdResult}
set properties of text of yearCalendar to {size:12.0, color:calendarColor, font:"Monaco"}
--Font must be monospaced type like Andale Mono,Monaco,Courier,Courier New for correct formatting
set bounds of window 1 to {0, 22, 612, 792}
end tell
else
try
on error errorMsg number errorNumber
set errorText to "Error: " & the errorNumber & ". " & errorMsg
display dialog errorText buttons {"OK"} default button 1
return errorText
end try
end if
Give me your opinion on my site. Visit Advanced AppleScript Guestbook and leave me a comment or follow me on twitter: http://twitter.com/hyperscripter.
Formatting and Editing Text Objects with Word 2008
Here we will look at some of the most necessary scripting elements for Word 2008 through a single document named 'MyText.doc'.
First creating and opening the newly created document:
tell application "Microsoft Word"
activate
set createDoc to make new document
set name of font object of text object of createDoc to "Lucida Grande"
set size of font object of text object of createDoc to "14"
save as createDoc file name "MyText.doc"
open createDoc
end tell
'set createDoc to make new document' creates the new document and places a file reference to the new document into the variable 'createDoc'
Once that reference to the document is made, you can direct individual statements to the reference named createDoc or within a tell block:
tell createdoc
...
end tell
Now, let's look at a few ways that you can edit text in the document given this initial text:
It was a stormy day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.
tell createDoc
select word 4 of createDoc (or select word 4 of active document)
set bold of font object of selection to true
set content of text object of selection to "sunny"
end tell
This results in:
It was a sunny day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.
The fourth word is selected, its font style set to bold, and its content changed to 'sunny'.
Note that changing styles of the selected text requires the use of the expression 'font object' >and to replace the content with the word 'sunny' you must use 'text object'
.
Then to add text to the end of the document by way of a text entry dialog:
set appendText to text returned of (display dialog "Enter text to append to the end of this document:" default answer "" buttons {"Cancel","Insert"} default button "Insert")
set appendText to (return & return & appendText)
insert text appendText at end of text object of active document
Questions or comments? Contact me at: hyperscripter@gmail.com or if you like this site, click on the twitter icon at the top of or bottom of the page the page. For RSS feed, click the RSS icon at the top or bottom of the page.
Enhanced - New Doc for AppleWorks 6
A more detailed script with text entry fields.
It has become abundantly clear to me that there is still a lot of interest in AppleScripts for AppleWorks 6 and questions on implementation of scripts that my previous posts on this topic have not addressed to the satisfaction of those who use AppleWorks 6 and, since it is an application that is still fairly universal in the Mac OS, I guess it is worth further examination. So, here's an enhancement of an earlier script that I hope will be useful:set theDocName to text returned of (display dialog "Enter new document name:" default answer "" buttons {"Set"} default button {"Set"})
set paragraph1 to text returned of (display dialog "Enter text for first paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: Notes on AppleScript and AppleWorks 6:
set paragraph2 to text returned of (display dialog "Enter text for second paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: As it appears in this document, this is the second paragraph but, to AppleScript,this is the third paragraph, because even an empty return is a paragraph in AppleScript.
set paragraph3 to text returned of (display dialog "Enter text for third paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: This, it would seem is the fourth paragraph but, it is actually the fifth to AppleScript.
set theData to paragraph1 & return & return & paragraph2 & return & return & paragraph3
tell application "AppleWorks 6"
activate
make new document with data theData with properties {name:theDocName}
tell front document
select paragraph 1
set the properties of the selection to {font:"Lucida Grande", size:18}
set color of the selection to {9960, 12194, 65535} --blue, an RGB value
select (paragraphs 3 thru 5)
set the properties of the selection to {font:"Monaco", size:9}
select word 14 of paragraph 3
set the properties of the selection to {size:12}
set size of the selection to 12
--Two ways to express things (look above)
set colorPref to default color {65535, 5195, 6617} --red, an RGB value
set color of the selection to colorPref
select (text 1 thru -1 of last word of paragraph 3)
set size of the selection to 12
set color of the selection to colorPref --red, an RGB value
select (text 1 thru -1 of last word of last paragraph)
set size of the selection to 12
set color of the selection to colorPref --red, an RGB value
save document theDocName in alias (path to desktop folder) as file type {"CWWP"}
end tell
end tell
Most of this is pretty straightforward. Take note of my use of negative indexes to groups of text above.
This could be used to change the color of a number of words in the initial script all at once:
tell application "AppleWorks 6"
tell front document
try
set everyWord to (every text)
set textCount to (count everyWord)
repeat with x from 7 to textCount
if word x = "AppleScript" then
select word x
set color of the selection to {65535, 5195, 6617} --red
end if
end repeat
on error
return
end try
end tell
end tell
This is how the initial script would appear:

To change the text style is a bit more complicated, something like this would work:
tell paragraph 1
select (words 3 thru 4)
set size of the selection to 14
set style of the selection to {class:text style info, on styles:{bold, italic}}
select word 6
set size of the selection to 14
set style of the selection to {class:text style info, on styles:{bold, outline}}
end tell
Which would look something like this:

If you run this script in Script Editor with our document in front...
tell application "AppleWorks 6"
activate
tell front document
select paragraph 1
get properties of the selection
end tell
end tell
The result for the text below (our first line), gives us some idea of the kinds of information we have at our disposal for writing scripts:

Out of this, we can see that we have these styles available:
{plain, bold, italic, underline, outline, shadow, condensed, expanded, strikethrough, superscript, subscript, superior, inferior, double underline}
Give me your opinion on my site. Please go to the Advanced AppleScript Guestbook and leave a comment or suggestion. If you like this site, please click on one of the stars at the top of the page to rate me,
Universal Access Preferences: Enabling GUI Scripting
From the Apple Menu, Choose 'System Preferences...', then click on 'Universal Access'

To Enable GUI Scripting, be sure that the checkbox entitled 'Enable Access for Assistive Devices' is checked
Amazon Books and Software
A respected name in the ecommerce business, if you can't find it at Amazon, it isn't worth finding!
iPhone Shuffle
by Hyperscripter
Insanely obsessed with anything involving 'cracking the code', I am an AppleScript and Mac OS Afficionado. I have learned a lot, but have so much more... more »
- 7 featured lenses
- Winner of 6 trophies!
- Top lens » Free AppleScript Code Examples
Explore related pages
- Free AppleScript Code Examples Free AppleScript Code Examples
- AppleScript Dictionary Explained in Plain English AppleScript Dictionary Explained in Plain English
- Facts About Apple Computer, Mac OS X and AppleScript Facts About Apple Computer, Mac OS X and AppleScript
- More Advanced AppleScript Code More Advanced AppleScript Code
- using Basic HTML in Squidoo lenses using Basic HTML in Squidoo lenses
- Advanced HTML for Squidoo Advanced HTML for Squidoo

