AppleScript

Single line examples

(path to frontmost application) is (path to application "Mail")
(time to GMT) / 3600 -- UTC offset
1 as meters as feet -- feet 3.280839895013
100 as degrees fahrenheit as degrees celsius -- degrees Celsius 37.777777777778
11 div 2 -- 5 (integer division)
4 mod 3 -- 1
AppleScript version of (system info)
DNS form of host of ("http://google.com" as URL) -- "google.com"
POSIX path of ((path to me as text) & "::") -- the folder that contains the current script
POSIX path of (path to home folder as text) is (system attribute "HOME") & "/" -- true
POSIX path of (path to temporary items) -- same as `(system attribute "TMPDIR") & "TemporaryItems/"`
application "TextEdit" is running
character ID (random number from 97 to 122)
character ID 97 -- "a" (`ASCII character` has been deprecated)
choose file name default name "Untitled.scpt" default location (path to scripts folder as alias)
choose file of type "public.jpeg" with invisibles
choose from list {"a", "b"} with title "Title" with prompt "Prompt" OK button name "ok" cancel button name "cancel" default items {"a"} with multiple selections allowed
class of ("" as Unicode text) -- text (`Unicode text` and `string` have been synonymous with `text` since AppleScript 2.0)
clipboard info -- show different versions of the clipboard
date "12/31/2013 11:59 PM" -- create a date object (this results in an error if the British region is selected from System Preferences)
delay (random number from 1 to 10)
display dialog "" default answer "" buttons {"a", "b", "c"} default button 3 cancel button 1
display notification "text" with title "title" subtitle "subtitle"
do shell script "MouseTools -x 500 -y 500;MouseTools -leftClick" -- `tell app "System Events" to click at {500, 500}` stopped working in 10.9
do shell script "lsappinfo visibleProcessList|cut -d\\\" -f4" -- print the name of the second frontmost application in 10.9 and later
do shell script "pwd" -- "/" (the default working directory for `do shell script` is `/`)
get eof of POSIX file "/tmp/a" -- get size in bytes
id of "aあ" -- {97, 12354}
id of "»" -- 187
if result of (do shell script "f=${TMPDIR}lastrun;find $f -mtime +5m;touch $f") is not "" then return -- exit a script if the time since the script was last run is under five minutes
log "message" -- add a message to the event log in Script Editor
middle item of {1, 2, 3} -- 2
month of (current date) as integer
open location "dict:///word"
paragraphs of "aa\nbb\n" -- {"aa", "bb", ""}
paragraphs of text 1 thru -2 of "aa\nbb\n" -- {"aa", "bb"}
path to me -- return the location of a script
path to resource "Mail.icns" in bundle (path to application "Mail")
quote of AppleScript -- "\"" (`quote` is a property of the AppleScript object and not a constant)
read "/tmp/a" as «class utf8» using delimiter linefeed -- get the lines of a file as a list
reverse of characters of "esrever" as text -- "reverse"
run script file "script.scpt" with parameters {"arg1", "arg2"}
say "[[rate 180]]a[[slnc 1000]]b" using "Victoria" saving to "/tmp/a.aif"
set the clipboard to (read (POSIX file "/Library/Desktop Pictures/Abstract.jpg") as JPEG picture) -- set the clipboard to image data
set the clipboard to POSIX file "/Library/Desktop Pictures/Abstract.jpg" -- set the clipboard to a file (this only works with a single file or folder and not with a list of files or folders)
set volume output volume ((output volume of (get volume settings)) + 2) -- increase volume by 2%
set volume with output muted
system attribute "USER" -- same as `short user name of (system info)`
system attribute -- list the names of environment variables
tell application "Alfred 2" to search "query"
tell application "Calendar" to delete events of calendars whose start date < date "12/31/2012"
tell application "Contacts" to name of people
tell application "Contacts" to value of email 1 of people
tell application "FastScripts" to display message "message" dismissing after delay 5
tell application "FastScripts" to shortcut string of keyboard shortcut of some script item whose has keyboard shortcut is true
tell application "Finder" to POSIX path of (application file id "com.apple.TextEdit" as alias) -- an alternative to `POSIX path of path to app "TextEdit"` that doesn't open TextEdit
tell application "Finder" to default application of (info for POSIX file "/Library/Desktop Pictures/Abstract.jpg")
tell application "Finder" to disks whose ejectable is true and local volume is true and physical size < 1e9
tell application "Finder" to duplicate items of home to disk "WD" with exact copy -- like `cp -Ra ~/ /Volumes/WD` (most metadata is preserved by default but `with exact copy` also preserves permissions and ownership)
tell application "Finder" to duplicate selection to desktop replacing yes
tell application "Finder" to eject disks whose name is not "MobileBackups"
tell application "Finder" to empty trash if free space of startup disk < 1e10
tell application "Finder" to files of (path to preferences folder) whose modification date < ((current date) - (days * 14))
tell application "Finder" to items of home
tell application "Finder" to make new Finder window to (get target of Finder window 1) -- duplicate a window
tell application "Finder" to make new Finder window to trash -- open a window for the trash
tell application "Finder" to make new alias file at desktop to POSIX file "/tmp"
tell application "Finder" to make new file at desktop with properties {name:"file.txt", comment:"file"}
tell application "Finder" to make new internet location file at desktop to "http://apple.com" with properties {name:"Apple"}
tell application "Finder" to move items of desktop to trash
tell application "Finder" to reveal item 1 of (sort selection by modification date) -- select the newest file in a selection with multiple files
tell application "Finder" to select (items of (insertion location as alias) whose kind is (get kind of item 1 of (get selection)))
tell application "Finder" to set collapsed of window of desktop to not collapsed of window of desktop -- toggle hiding the desktop
tell application "Finder" to set label index of entire contents of (path to downloads folder) to 0
tell application "Finder" to set label index of item 1 of (get selection) to item 1 of {2, 1, 3, 6, 4, 5, 7}
tell application "Finder" to set selection to (get items of container of item 1 of (get selection) whose label index is (get label index of item 1 of (get selection)))
tell application "Finder" to set selection to (make new file at (get insertion location) with properties {name:(text returned of (display dialog "" default answer "Untitled.txt"))})
tell application "Finder" to set selection to make new file at (get insertion location)
tell application "Finder" to set sort column of list view options of window 1 to modification date column
tell application "Finder" to set {bounds:{rest:{rest:{dtw, dth}}}} to window of desktop
tell application "Finder" to set {current view of window 1, bounds of window 1, icon size of icon view options of window 1} to {icon view, bounds of window of desktop, 256}
tell application "Finder" to sort files of (path to downloads folder) by creation date
tell application "Finder" to tell icon view options of window 1 to set {icon size, arrangement} to {(icon size * 1.5), arranged by name}
tell application "Finder" to tell item 1 of (get selection) to if class is alias file then original item
tell application "Finder" to windows whose visible is true and floating is false and modal is false
tell application "Font Book" to name of typefaces whose style name is "Regular"
tell application "Google Chrome" to close active tab of window 1
tell application "Google Chrome" to loading of tabs of windows contains true
tell application "Google Chrome" to make new window with properties {mode:"incognito"}
tell application "Google Chrome" to set active tab index of window 1 to 2
tell application "Google Chrome" to tell active tab of window 1 to execute javascript "o='';a=document.querySelectorAll('.aa a');for(i=0;e=a[i];i++){o+=e.href+'\\n'};o"
tell application "Google Chrome" to tell window 1 to close tabs whose id is not (get id of active tab)
tell application "Mail" to make new outgoing message with properties {subject:"subject", content:"content", visible:true}
tell application "Mail" to move selected messages of message viewer 1 to mailbox "[Gmail]/Archive" of account "Gmail"
tell application "Mail" to properties of item 1 of (get selected messages of message viewer 1)
tell application "Mail" to tell account "Gmail" to move (a reference to (messages of mailbox "INBOX" whose flagged status is false and read status is true)) to mailbox "[Gmail]/Archive"
tell application "Mail" to tell account 1 to messages of mailbox "INBOX" whose date sent < (current date) - 14 * days
tell application "Messages" to log in -- log in to all services
tell application "Messages" to send "message" to buddy "buddy" of service "E:name@example.com"
tell application "Numbers" to make new document with properties {document template:template "Blank"}
tell application "Numbers" to tell table 1 of sheet 1 of document 1 to set value of cell 1 of column 1 to "a"
tell application "Pages" to select insertion point after character 7 of body text of document 1
tell application "QuickTime Player" to tell (new screen recording) to start
tell application "Safari" make new document with properties {URL:"about:blank"} -- open a new window
tell application "Safari" to (do JavaScript "document.readyState" in document 1) is "complete"
tell application "Safari" to (do JavaScript "document.readyState" in tabs of window 1) contains "loading"
tell application "Safari" to (documents whose name is not "Untitled") is not {}
tell application "Safari" to close current tab of window 1
tell application "Safari" to close tabs of window 1 whose URL does not contain "substring"
tell application "Safari" to close tabs of window 1 whose name is "Untitled"
tell application "Safari" to do JavaScript "''+document.getSelection()" in document 1 -- get selection as text
tell application "Safari" to do JavaScript "document.body.innerHTML" in document 1 -- generated source
tell application "Safari" to do JavaScript "document.getElementById('element').childNodes[0].click()" in document 1
tell application "Safari" to do JavaScript "window.scroll(0,999999)" in document 1
tell application "Safari" to make new document -- open a new window
tell application "Safari" to tell (documents whose name is "Failed to open page") to do JavaScript "window.location.reload()"
tell application "Safari" to tell (window 1 whose its document is not missing value) to set current tab to make new tab
tell application "Safari" to tell document 1 to do JavaScript "window.scrollBy(0,window.innerHeight)" -- scroll one page down
tell application "Safari" to tell document 1 to set URL to "http://web.archive.org/*/" & URL
tell application "Safari" to tell document 1 to set the clipboard to "[" & name & "](" & URL & ")"
tell application "Safari" to tell window 1 set current tab to tab ((index of current tab) + 1)
tell application "Safari" to tell window 1 to close tabs whose index > (get index of current tab)
tell application "Safari" to tell window 1 to set current tab to tab -1
tell application "Safari" to tell window 1 to set current tab to tab 1 whose URL contains "substring"
tell application "Script Editor to contents of selection of document 1
tell application "Script Editor" to set bounds of windows to {0, 0, 1919, 1279}
tell application "Skim" to index of current page of document 1
tell application "Skim" to selection of document 1 as text
tell application "Skim" to tell (notes of document 1 whose (its type is highlight note)) to its text
tell application "Spotify" to play track "spotify:track:" & trackid
tell application "System Events" to POSIX path of disk items of folder "~/Documents"
tell application "System Events" to URL of (POSIX file "/Library" as alias) -- file:///Library/
tell application "System Events" to click (button 1 whose subrole is "AXZoomButton") of (window 1 whose subrole is "AXStandardWindow") of (process 1 whose frontmost is true)
tell application "System Events" to click UI element 1 of menu bar 2 of process "SystemUIServer" whose accessibility description is "spotlight menu"
tell application "System Events" to click window 1 of process "Notification Center"
tell application "System Events" to exists process "Finder"
tell application "System Events" to localized string "Services" from table "Services" in bundle "/System/Library/Frameworks/AppKit.framework/Versions/Current"
tell application "System Events" to make new login item at end with properties {path:"/Applications/TextEdit.app", name:"TextEdit", hidden:true}
tell application "System Events" to name of processes whose background only is false
tell application "System Events" to picture of current desktop
tell application "System Events" to properties of desktops
tell application "System Events" to set frontmost of process 1 whose unix id is 1234 to true
tell application "System Events" to set picture of desktops to "/Library/Desktop Pictures/Antelope Canyon.jpg"
tell application "System Events" to set value of scroll bar 1 of scroll area 1 of group 1 of group 1 of group -1 of window 1 of process "Safari" to 1.0
tell application "System Events" to set visible of processes whose bundle identifier is not "my.emacs" and name is not "Safari" to false
tell application "System Events" to tell (process 1 whose frontmost is true) to perform action "AXRaise" of (window 1 whose value of attribute "AXMain" is true)
tell application "System Events" to tell (process 1 whose frontmost is true) to value of attribute "AXDocument" of window 1
tell application "System Events" to tell (process 1 whose it is frontmost) to tell (window 1 whose value of attribute "AXMain" is true) to value of attribute "AXTitle"
tell application "System Events" to tell contents of property list file "/tmp/test.plist" to make new property list item at end with properties {kind:string, name:"key", value:"value"}
tell application "System Events" to tell current location of network preferences to tell (a reference to (service 1 whose kind is 10)) to if exists then connect
tell application "System Events" to tell dock preferences to set autohide to not autohide
tell application "System Events" to tell process "Adobe Reader" to tell window 1 to perform action "AXPress" of (get value of attribute "AXCloseButton")
tell application "System Events" to tell process "Dock" to click (UI elements of list 1 whose role description is "minimized window")
tell application "System Events" to tell process "Dock" to perform action "AXShowMenu" of UI element "System Preferences" of list 1
tell application "System Events" to tell process "Finder" to class of UI elements of window 1
tell application "System Events" to tell process "Finder" to rows of outline 1 of scroll area 1 of splitter group 1 of window 1 whose selected is true
tell application "System Events" to tell process "Finder" to tell menu 1 of menu bar item 3 of menu bar 1 to click (menu item 1 whose name starts with "Compress")
tell application "System Events" to tell process "Finder" to value of attribute "AXMenuItemCmdModifiers" of menu item "New Folder" of menu 1 of menu bar item 3 of menu bar 1
tell application "System Events" to tell process "Notational Velocity" to value of text field 1 of group 1 of tool bar 1 of window 1
tell application "System Events" to tell process "Notification Center" to click (button "Close" of windows whose subrole is "AXNotificationCenterAlert" or subrole is "AXNotificationCenterBanner")
tell application "System Events" to tell process "Notification Center" to click menu bar item 1 of menu bar 1
tell application "System Events" to tell process "Preview" to has scripting terminology
tell application "System Events" to tell process "QuickTime Player" to set value of attribute "AXFullScreen" of window 1 to true
tell application "System Events" to tell process "Safari" to value of attribute "AXFullScreen" of window 1
tell application "System Events" to tell process "Safari" to value of text field 1 of group 2 of toolbar 1 of window 1 -- contents of the location bar
tell application "System Events" to tell process "TextEdit" to value of attribute "AXSelectedTextRange" of text area 1 of scroll area 1 of window 1
tell application "System Events" to tell process "iTunes" to click ((button 1 of window 1) whose description is "close button")
tell application "System Events" to tell property list file "~/Library/Preferences/com.apple.recentitems.plist" to properties of property list item "RecentDocuments"
tell application "System Events" to tell security preferences to set require password to wake to not require password to wake
tell application "System Events" to tell window 1 of (process 1 whose it is frontmost) to set {position, size} to {{0, 22}, {1920, 1258}}
tell application "System Events" to tell window 1 of (process 1 whose it is frontmost) to set {position, size} to {{0, 22}, {1920, 1258}}
tell application "System Events" to |persistent-apps| of (get value of contents of property list file ((path to preferences folder as text) & "com.apple.dock.plist"))
tell application "System Preferences" to anchors of panes
tell application "System Preferences" to reveal anchor "Privacy_Assistive" of pane id "com.apple.preference.security"
tell application "System Prefereneces" to anchors of tabs
tell application "Terminal" to do script "" -- open a new window
tell application "Terminal" to set current settings of selected tab of window 1 to settings set "Grass"
tell application "Terminal" to tell window 1 to set {number of columns, number of rows} to {80, 50}
tell application "TextEdit" to attribute runs of text of document 1 whose font contains "Bold"
tell application "TextEdit" to if number of windows is 0 then open POSIX file ((system attribute "HOME") & "/Notes/temp.txt") as text
tell application "TextEdit" to set color of characters 5 thru 10 of document 1 to {65535, 0, 0}
tell application "TextEdit" to tell document 1 to copy word 1 to before paragraph 3
tell application "Things" to make new to do list at "Inbox" with properties {name:"name", notes:"notes", due date:date "12/31/13"}
tell application "Twitter" to text of item 1 of statuses of home timeline of current account
tell application "VLC" to set current time to current time + 60
tell application "VLC" to set fullscreen mode to not full screen mode
tell application "http://blogname.wordpress.com/xmlrpc.php" to call xmlrpc {method name:"wp.getPosts", parameters:{"1", "username", "password", "1"}}
tell application "iTerm" to tell (make new terminal) to tell (make new session at end of sessions) to exec command "emacs"
tell application "iTerm" to tell session -1 of current terminal to write text "say a"
tell application "iTerm" to text of current session of current terminal -- `terminal 1` is the terminal that was opened first
tell application "iTunes" to POSIX path of (get location of current track)
tell application "iTunes" to POSIX path of (get location of item 1 of (get selection))
tell application "iTunes" to current playlist -- the playlist of the currently playing track
tell application "iTunes" to delete (tracks of current playlist whose album is (get album of current track))
tell application "iTunes" to delete playlists whose size is 0 and special kind is none -- delete empty playlists
tell application "iTunes" to duplicate current track to playlist "Favorites"
tell application "iTunes" to location of tracks whose kind is "AAC audio file"
tell application "iTunes" to make new user playlist with properties {name:"name"}
tell application "iTunes" to name of tracks of source 1 whose artist contains "substring"
tell application "iTunes" to play (track 1 of current playlist whose artist is not (get artist of current track) and index > (get index of current track))
tell application "iTunes" to refresh selection -- update the tags of the selected items if the tags have been edited outside iTunes
tell application "iTunes" to reveal current track -- same as command-L
tell application "iTunes" to set player position to (duration of current track) / 2
tell application "iTunes" to set player position to player position + 30
tell application "iTunes" to set rating of current track to 60 -- 3 stars
tell application "iTunes" to set view of browser window 1 to (get user playlist 1 whose special kind is none)
tell application "iTunes" to tell current track to artist & " - " & name
tell application "iTunes" to tracks of current playlist whose rating is 20
tell application "iTunes" to tracks of playlist "some playlist" whose played count is not 0
tell application "iTunes" to view of browser window 1 -- the currently shown playlist or other view
tell application "loginwindow" to «event aevtrlgo» -- log out without showing a confirmation dialog
tell application "loginwindow" to «event aevtrsdn» -- open the dialog shown by control-eject
tell application (path to frontmost application as text) to POSIX file (path of document 1) as text
tell application (path to frontmost application as text) to quit saving no
tell application (path to frontmost application as text) to set the clipboard to (get path of document 1)
{1, 2} & {3} -- {1, 2, 3}
«data utxt3042» as text -- "あ"

Bookmarks

https://developer.apple.com/library/mac/documentation/applescript/conceptual/applescriptlangguide/AppleScriptLanguageGuide.pdf
http://www.cs.utexas.edu/~wcook/papers/AppleScript/AppleScript95.pdf
http://www.cs.utexas.edu/~wcook/Drafts/2006/ashopl.pdf
http://dl.acm.org/ft_gateway.cfm?id=1238845&type=pdf&path=%2F1240000%2F1238845%2Fsupp%2FAppleScript%2Epdf&supp=1&dwn=1&CFID=334275816&CFTOKEN=16694215
http://www.apeth.net/matt/downloads/ASTDG2Scripts.txt
http://developer.apple.com/library/mac/#technotes/tn2065/_index.html
http://developer.apple.com/library/mac/#releasenotes/AppleScript/RN-AppleScript/RN-10_5/RN-10_5.html
http://macscripter.net/viewtopic.php?id=24737
http://macscripter.net/viewtopic.php?id=24587
http://stackoverflow.com/questions/13973347/how-applescript-can-get-stdin-inside-the-code
http://support.apple.com/kb/HT5914
http://macosxautomation.com/mavericks/guiscripting/index.html
https://developer.apple.com/library/mac/releasenotes/AppleScript/RN-AppleScript/RN-10_9/RN-10_9.html#//apple_ref/doc/uid/TP40000982-CH109-SW1
http://macscripter.net/viewtopic.php?id=39019
https://discussions.apple.com/thread/1897143
http://stackoverflow.com/a/15820786
https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html
https://developer.apple.com/library/mac/releasenotes/AppleScript/RN-AppleScript/RN-10_10/RN-10_10.html

Scripts

Applications/Finder/add itunes playlist.scpt

tell application "Finder"
    set s to selection as alias list
    set n to name of item 1 of s
end tell
tell application "iTunes"
    try -- this sometimes times out
        if number of s is 1 then
            set p to make new user playlist with properties {name:n}
        else
            set p to make new user playlist
        end if
        set view of browser window 1 to p
        add s to p
        reveal item 1 of p
        activate
    end try
end tell

Applications/Finder/copy paths.scpt

tell application "Finder" to set s to selection as alias list
if s is {} then return
set out to {}
repeat with f in s
    set end of out to POSIX path of f
end repeat
set text item delimiters to linefeed
set the clipboard to (out as text)

Applications/Finder/reset view options.scpt

tell application "Finder"
    if number of Finder windows is 0 then return
    tell Finder window 1
        set toolbar visible to false
        set sidebar width to 0
        set statusbar visible to false
        set current view to column view
        set bounds to {960, 22, 1920, 1076}
        tell its column view options
            set shows icon to false
        end tell
    end tell
end tell

Applications/Safari/close to left.scpt

tell application "Safari" to tell window 1 to close (tabs where index ≤ (get index of current tab))

Applications/Safari/close to right.scpt

tell application "Safari" to tell window 1 to close (tabs where index ≥ (get index of current tab))

Applications/Safari/copy all.scpt

set text item delimiters to linefeed
tell application "Safari" to URL of tabs of window 1
set the clipboard to result as text

Applications/Safari/copy link.scpt

tell application "Safari" to tell document 1
    set the clipboard to "[" & name & "](" & URL & ")"
end tell

Applications/Safari/copy url.scpt

tell application "Safari" to set u to URL of document 1
set the clipboard to u

Applications/Safari/open web archive.scpt

tell application "Safari" to tell document 1 to set URL to "http://web.archive.org/*/" & URL

Applications/Safari/select first tab.scpt

tell window 1 of application "Safari" to set current tab to tab 1

Applications/Safari/select last tab.scpt

tell window 1 of application "Safari" to set current tab to tab -1

Applications/Safari/translate.scpt

tell application "Safari" to URL of document 1
do shell script "open 'http://translate.google.com/translate?sl=auto&tl=auto&u='$(ruby -rcgi -e 'print CGI.escape ARGV[0]' " & quoted form of result & ")"

Applications/Script Editor/toggle comment.scpt

set text item delimiters to linefeed
tell application "Script Editor" to tell document 1
    set input to its text
    set {c1, c2} to character range of selection
    if c1 is 0 then
        set {p1, p2} to {1, 1}
    else
        set p1 to count paragraphs of text 1 thru c1 of input
        set p2 to count paragraphs of text 1 thru c2 of input
        if p1 is not p2 and {return, linefeed} contains item c2 of input then set p2 to p2 - 1
    end if
    set selection to paragraphs p1 thru p2
    do shell script "input=" & quoted form of (paragraphs p1 thru p2 of input as text) & "
if [[ -z $(sed -E '/^[[:space:]]*($|#|--)/d' <<< \"$input\") ]]; then
  sed -E 's/^([[:space:]]*)(#|--)[[:space:]]*/\\1/g' <<< \"$input\"
else
  sed -E 's/^([[:space:]]*)/\\1--/g' <<< \"$input\"
fi" without altering line endings
    set contents of selection to result
end tell

Applications/iTunes/delete album from playlist.scpt

tell application "iTunes"
    set x to track 1 of current playlist where album is not (get album of current track) and index > (get index of current track)
    delete (tracks of current playlist where album is (get album of current track))
    if x is not missing value then
        play x
        reveal current track
    end if
end tell

Applications/iTunes/edit tags.scpt

set text item delimiters to {" - "}
tell application "iTunes"
    repeat with t in (get selection)
        if name of t contains " - " then
            set artist of t to text item 1 of (get name of t)
            set name of t to (text items 2 thru -1 of (get name of t) as text)
        end if
    end repeat
end tell

on replace(x, y, z)
    set text item delimiters to y
    set ti to text items of x
    set text item delimiters to z
    ti as text
end replace

on split(x, y)
    if x does not contain y then return {x}
    set text item delimiters to y
    text items of x
end split

on titlecase(x)
    do shell script "ruby -rtitlecase -e'print ARGV[0].titlecase' " & quoted form of x without altering line endings
end titlecase

on capitalize(x)
    do shell script "printf %s " & quoted form of x & "|tr A-Z a-z|gsed 's/\\b./\\u&/g'"
end capitalize

Applications/iTunes/move folders.scpt

tell application "iTunes" to location of selection
tell application "Finder" to repeat with f in result
    if exists folder of f then move folder of f to desktop
end repeat

Applications/iTunes/move to trash.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set f to location of t
        delete t
        tell application "Finder" to move f to trash
    end repeat
end tell

Applications/iTunes/next album.scpt

tell application "iTunes"
    set t to (track 1 of current playlist where album is not (get album of current track) and index > (get index of current track))
    play t
    reveal t
end tell

Applications/iTunes/open in last.fm.scpt

tell application "iTunes" to artist of current track
do shell script "open http://last.fm/music/$(ruby -rcgi -e 'print CGI.escape ARGV[0]' " & quoted form of result & ")"

Applications/iTunes/preview tracks.scpt

repeat
    tell application "iTunes"
        next track
        set player position to 0.5 * (duration of current track)
        play
        delay 10
    end tell
end repeat

Applications/iTunes/rating 0.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 0
    end repeat
end tell

Applications/iTunes/rating 1.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 20
    end repeat
end tell

Applications/iTunes/rating 2.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 40
    end repeat
end tell

Applications/iTunes/rating 3.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 60
    end repeat
end tell

Applications/iTunes/rating 4.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 80
    end repeat
end tell

Applications/iTunes/rating 5.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set rating of t to 100
    end repeat
end tell

Applications/iTunes/renumber tracks.scpt

tell application "iTunes"
    set n to text returned of (display dialog "Start from" default answer "1")
    set s to selection
    repeat with i from 1 to (count s)
        set track number of item i of s to n + i - 1
    end repeat
end tell

Applications/iTunes/tags from filenames.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set n to name of t
        set x to text items of text 4 thru -1 of n
        set track number of t to text 1 thru 2 of n
        set artist of t to item 1 of x
        set name of t to item 2 of x
    end repeat
end tell

Applications/iTunes/tags to filenames.scpt

tell application "iTunes"
    repeat with t in (get selection)
        set n to track number of t
        set l to location of t
        tell application "Finder" to set name of file l to (n & " " & name of t & ".aif") as text
    end repeat
end tell

append to copied.scpt

try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "c" using command down
delay 1
do shell script "printf \\\\n%s\\\\n \"$(LC_CTYPE=UTF-8 pbpaste)\">>~/notes/copied"
try
    set the clipboard to old
end try

itunes delete and next.scpt

tell application "iTunes"
    set t to current track
    next track
    play
    reveal current track
    delete t
end tell

itunes go backward.scpt

try
    tell application "iTunes"
        if player position < 30 then
            previous track
        else
            set player position to player position - 30
        end if
    end tell
end try

itunes go down.scpt

try
    tell application "iTunes"
        next track
        set player position to 0.5 * (duration of current track)
        reveal current track
    end tell
end try

itunes go forward.scpt

try
    tell application "iTunes"
        set player position to player position + 30
    end tell
end try

itunes go up.scpt

try
    tell application "iTunes"
        previous track
        set player position to 0.5 * (duration of current track)
        reveal current track
    end tell
end try

itunes star and next.scpt

tell application "iTunes"
    set rating of current track to 20
    next track
    set player position to 0.5 * (duration of current track)
    play
    reveal current track
end tell

itunes stars 0.scpt

tell application "iTunes" to set rating of current track to 0

itunes stars 1.scpt

tell application "iTunes" to set rating of current track to 20

itunes stars 2.scpt

tell application "iTunes" to set rating of current track to 40

itunes stars 3.scpt

tell application "iTunes" to set rating of current track to 60

itunes stars 4.scpt

tell application "iTunes" to set rating of current track to 80

itunes stars 5.scpt

tell application "iTunes" to set rating of current track to 100

itunes trash and next.scpt

tell application "iTunes"
    set t to current track
    set l to location of t
    next track
    play
    reveal current track
    delete t
    tell application "Finder" to move l to trash
end tell

kill and reopen frontmost.scpt

do shell script "a=$(lsappinfo visibleProcessList|cut -d\\\" -f2);killall \"$a\";open -a \"$a\""

kill frontmost.scpt

do shell script "kill $(lsappinfo info -app \"$(lsappinfo front)\" -only pid|cut -d= -f2)"

maximize.scpt

try
    tell application (path to frontmost application as text)
        set bounds of window 1 to {0, 22, 1920, 1258}
    end tell
on error
    tell application "System Events" to tell window 1 of (process 1 where it is frontmost)
        try
            set position to {0, 22}
            set size to {1920, 1258}
        end try
    end tell
end try

note mode.scpt

tell application (path to frontmost application as text)
    set bounds of window 1 to {0, 23, 1100, 1079}
end tell
tell application "TextEdit"
    open POSIX file ((system attribute "HOME") & "/notes/textedit") as alias
    set bounds of windows to {1100, 23, 1919, 1079}
    activate
end tell

open recent or open with.scpt

tell application "System Events" to tell (process 1 where it is frontmost)
    tell menu bar item 3 of menu bar 1
        click
        repeat with x in {"Open Recent", "Open Recent File", "Recent Projects", "Open With"}
            if exists menu item x of menu 1 then
                click menu item x of menu 1
                exit repeat
            end if
        end repeat
    end tell
end tell

reveal in finder.scpt

try
    try
        error
        tell application (path to frontmost application as text)
            set f to POSIX file («class ppth» of document 1) as text
        end tell
    on error
        tell application "System Events" to tell (process 1 where frontmost is true)
            value of attribute "AXDocument" of window 1
        end tell
        do shell script "x=" & quoted form of result & ";x=${x/#file:\\/\\/};printf ${x//%/\\\\x}"
        set f to POSIX file result
    end try
    tell application "Finder"
        select f
        activate
    end tell
end try

Notes

Opening or activating applications

To open an application, you can usually send it the reopen and activate commands:

tell application "TextEdit"
    reopen
    activate
end tell

reopen opens a new default window if there are no open windows, and if all windows are minimized, it unminimizes the first minimized window. activate makes the application frontmost.

If for example TextEdit is not frontmost and has multiple open windows, activate app "TextEdit" and tell app "System Events" to set frontmost of process "TextEdit" to true raise all windows but open -atextedit only raises a single window.

You can open TextEdit hidden and on the background by running launch app "TextEdit", do shell script "pgrep -x TextEdit||open -jga TextEdit", or do shell script "lsappinfo launch launchandhide=true nofront=true /Applications/TextEdit.app". launch app "TextEdit" is blocked until TextEdit finishes opening but the other two commands are not.

If TextEdit is running but has no open windows, open -jga TextEdit opens a new visible window on the background but pgrep -xq TextEdit||open -jga TextEdit does not.

Restoring text item delimiters

As far as I know, the text item delimiters property does not have to be restored if it is not used later in the same script.

According to http://macscripter.net/viewtopic.php?id=24725, when a script that changed the text item delimiters property was run in one window in Script Editor, the text item delimiters property was also changed in other windows of Script Editor, but that has not been the case since at least 10.8. I don't know any other contexts where changing the text item delimiters property would have some more global effect outside the current script.

Basic IO

Read the contents of a file:

read "/tmp/a" as «class utf8»

Write text to a file:

set fd to open for access "/tmp/a" with write permission
set eof fd to 0
write "a" & linefeed to fd as «class utf8»
close access fd

Append text to a file:

set fd to open for access "/tmp/a" with write permission
write "a" & linefeed to fd as «class utf8» starting at eof
close access fd

Get the lines of a file as a list:

read POSIX file "/tmp/a" as «class utf8» using delimiter linefeed

Get the size of a file in bytes:

get eof of "/tmp/a"

Make a file empty:

set fd to open for access "/tmp/a" with write permission
set eof fd to 0
close access fd

Create an empty file:

set fd to "/tmp/a"
open for access fd
close access fd

The read and write commands use an encoding like MacRoman or MacJapanese by default. Unicode text is UTF-16 and «class utf8» is UTF-8.

pbcopy and pbpaste encodings

pbcopy and pbpaste do not preserve non-ASCII characters in the C locale or when locale variables are unset. Terminal and iTerm 2 set LANG to a value like en_US.UTF-8 by default, but locale variables are unset by default in Script Editor and Automator.

You can use LC_CTYPE=UTF-8 pbcopy or LC_CTYPE=UTF-8 pbpaste to always preserve non-ASCII characters in UTF-8 text:

do shell script "printf %s Ā|pbcopy"
the clipboard -- "Ā"
set the clipboard to "Ā"
do shell script "pbpaste" -- "?"
do shell script "printf %s Ā|LC_CTYPE=UTF-8 pbcopy"
the clipboard -- "Ā"
do shell script "LC_CTYPE=UTF-8 pbpaste" -- "Ā"

LC_CTYPE can be set to just UTF-8, but LANG and LC_ALL also have to include the language and territory parts, like en_US.UTF-8.

CR line endings

Scripts written in Script Editor often contain a mix of CR and LF line endings. The return key always inserts a linefeed. When a script is compiled in Script Editor, line endings are preserved inside strings and in multi-line comments but converted to carriage returns in other places.

The do shell script command replaces linefeeds with carriage returns without the without altering line endings specifier, which additionally disables chomping a newline from the end of the output.

The result of the clipboard as text uses CR line endings, but you can do something like this to convert the line endings to LF:

set text item delimiters to linefeed
(paragraphs of (get the clipboard as text)) as text

echo in do shell script

The shell used by do shell script is /bin/sh, which is a POSIX-compliant version of Bash in OS X. When Bash is invoked as sh, xpg_echo is enabled by default, so echo interprets escape sequences and does not support any options:

(do shell script "echo " & quoted form of "\\t") is tab -- true
do shell script "echo -n a" -- "-n a"

As a workaround, you can use printf or unset the xpg_echo option:

(do shell script "printf %s " & quoted form of "\\t") is tab -- false
(do shell script "shopt -u xpg_echo;echo " & quoted form of "\\t") is tab -- false

Passing input longer than ARG_MAX to do shell script

The maximum length of a command line is 2**18 bytes:

$ getconf ARG_MAX
262144

So that for example this results in an error:

read "/usr/share/dict/web2" for 270000
do shell script "printf %s " & quoted form of result

You can use a temporary file as a workaround:

set input to read "/usr/share/dict/web2" for 270000
set f to (system attribute "TMPDIR") & "my.tempfile"
set fd to open for access f with write permission
set eof fd to 0
write input to fd as «class utf8»
close access fd
do shell script "wc<" & f & ";rm " & f

UI scripting examples

reopen application "Finder"
tell application "System Events" to tell window 1 of process "Finder"
    {class, value} of UI elements of UI elements
    description of UI elements
    properties of some UI element
    attributes of some UI element
    value of attribute "AXFocused" of some UI element
    actions of button 2
end tell
tell application "System Events" to tell process "Preview"
    repeat with w in (get windows where title contains "pdf")
        click (button 1 of w where description is "close button")
    end repeat
end tell
tell application "System Events" to tell process "Finder"
    tell menu 1 of menu bar item "File" of menu bar 1
        click menu item "New Finder Window"
        click (menu item 1 where its name starts with "Compress")
    end tell
    tell menu bar item "File" of menu bar 1
        click
        click menu item "Open With" of menu 1
    end tell
end tell
tell application "System Events" to tell process "SecurityAgent"
    set value of text field 2 of scroll area 1 of group 1 of window 1 to "pa55word"
    click button 2 of group 2 of window 1
end tell
tell application "System Events" to tell process "TextEdit"
    set frontmost to true
    set e to exists window "Fonts"
    if not e then keystroke "t" using command down
    click menu button 1 of group 1 of group 2 of group 1 of splitter group 1 of window "Fonts"
    click menu item "Single" of menu 1 of menu button 1 of group 1 of group 2 of group 1 of splitter group 1 of window "Fonts"
    if not e then click button 1 of window "Fonts"
end tell

Reloading a page in Safari

This works if the page is loading and keeps the scroll position:

tell application "Safari" to tell document 1 to do JavaScript "window.location.reload()"

This does not work if the page is loading and does not keep the scroll position:

tell application "Safari" to tell document 1 to set URL to (get URL)

Waiting until a page has finished loading in Safari

tell application "Safari" to tell document 1
    repeat until (do JavaScript "document.readyState") is "complete"
        delay 0.1
    end repeat
end tell

To run JavaScript after a page has finished loading, you can listen for the load event:

tell application "Safari" to tell document 1
    do JavaScript "window.addEventListener('load',function(){prompt('','')})"
end tell

Waiting until a page has finished loading in Chrome

tell application "Google Chrome" to tell active tab of window 1
    repeat while loading is true
        delay 0.1
    end repeat
end tell

Different ways to check if a file or folder exists

System Events has an exist command:

tell application "System Events" to exists POSIX file "/tmp/a"

Finder also has an exist command:

tell application "Finder" to exists POSIX file "/tmp/a"

Coercing a file object to alias fails if the file of the file object does not exist:

try
    POSIX file "/tmp/a" as alias
    true
on error
    false
end try

Getting command line arguments with osascript

Get all arguments as a list:

osascript -e'on run a
    a -- {"aa", "bb"}
end' aa bb

Get a single argument:

osascript -e'on run{a}
    a -- "aa"
end' aa

Get all arguments as a list when using a HEREDOC:

osascript - aa bb <<'END'
on run a
    a -- {"aa", "bb"}
end
END

Getting STDIN with osascript

This stopped working in 10.8:

$ echo a|osascript -e'do shell script"cat"'
a

In 10.8 and later you can use another file descriptor:

$ echo a|osascript -e'do shell script"cat<&3"' 3<&0
a

considering case

"A" is "a" -- true
considering case
    "A" is "a" -- false
end considering

considering numeric strings

"11" > "9" -- false
"10.4.11" > "10.4.9" -- false
considering numeric strings
    "11" > "9" -- true
    "10.4.11" > "10.4.9" -- true
end considering

Getting files as an alias list is faster

$ TIMEFMT=%U
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)as alias list'>/dev/null
5.832
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)as alias list'>/dev/null
0.902
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)as alias list'>/dev/null
0.902
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)'>/dev/null
1.262
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)'>/dev/null
1.310
$ time osascript -e'tell app"finder"to files of(posix file"/usr/bin/"as alias)'>/dev/null
1.276

Shuffling a list

This shuffles a list using the Fisher-Yates algorithm:

on shuffle(l)
    set i to count of l
    repeat while i ≥ 2
        set j to random number from 1 to i
        tell l to set {item i, item j} to {item j, item i}
        set i to i - 1
    end repeat
    l
end shuffle

set l to {}
repeat 1000 times
    set end of l to random number from 1 to 1000
end repeat
shuffle(l)

When the length of the list is i, there are i * ... * 2 = i! possible sequences of random numbers, each of which corresponds to exactly one out of the i! permutations of the list.

You can make the function faster by using a script object:

on shuffle(input)
    script s
        property l : input
    end script
    set i to count of l of s
    repeat while i ≥ 2
        set j to random number from 1 to i
        set {item i of l of s, item j of l of s} to {item j of l of s, item i of l of s}
        set i to i - 1
    end repeat
    l of s
end shuffle

The scripts took about 0.06 and 0.04 seconds for a list with 100 elements, about 0.15 and 0.06 seconds for a list with 1000 elements, about 12 and 0.5 seconds for a list with 10000 elements, and about 976 seconds and 4 seconds for a list with 100000 elements.

The number of items that can be saved in a compiled script is limited

Try to open a new script window in Script Editor and run this:

set l to {}
repeat with x from 1 to 10000
    set end of l to x
end repeat

If you then try to save the script as .scpt, it results in an error like The document “Untitled” could not be saved as “Untitled.scpt”. If you do not run the script, you can save it as .scpt, but if you then run the script outside Script Editor, or for example with osascript, there is an error like couldn't save changes to script test.scpt: Signaled when the runtime stack overflows.

As a workaround, you can save the script as .applescript instead of .scpt, add set l to missing value to the end of the script, or put the whole script inside a handler to make the l variable local.

Reference forms

The AppleScript Language Guide classifies reference forms under the ten types listed below. I added the examples.

http://www.cs.utexas.edu/~wcook/papers/AppleScript/AppleScript95.pdf classifies object specifiers under the four types listed below.

Reference objects

tell application "TextEdit"
    open POSIX file "/usr/share/dict/connectives"
    set r to a reference to document 1
    open POSIX file "/usr/share/dict/propernames"

    r -- document 1 of application "TextEdit"

    --evaluate a reference object
    contents of r -- document "propernames" of application "TextEdit"

    --perform an implicit dereference
    name of r -- "propernames"
end tell

Key codes

You can look up key codes from Events.h:

$ grep -a '^  kVK' /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h|tr -d ,|while read x y z;do printf '%d %s %s\n' $z $z ${x#kVK_};done|sort -n
0 0x00 ANSI_A
1 0x01 ANSI_S
2 0x02 ANSI_D
3 0x03 ANSI_F
4 0x04 ANSI_H
5 0x05 ANSI_G
6 0x06 ANSI_Z
7 0x07 ANSI_X
8 0x08 ANSI_C
9 0x09 ANSI_V
10 0x0A ISO_Section
11 0x0B ANSI_B
12 0x0C ANSI_Q
13 0x0D ANSI_W
14 0x0E ANSI_E
15 0x0F ANSI_R
16 0x10 ANSI_Y
17 0x11 ANSI_T
18 0x12 ANSI_1
19 0x13 ANSI_2
20 0x14 ANSI_3
21 0x15 ANSI_4
22 0x16 ANSI_6
23 0x17 ANSI_5
24 0x18 ANSI_Equal
25 0x19 ANSI_9
26 0x1A ANSI_7
27 0x1B ANSI_Minus
28 0x1C ANSI_8
29 0x1D ANSI_0
30 0x1E ANSI_RightBracket
31 0x1F ANSI_O
32 0x20 ANSI_U
33 0x21 ANSI_LeftBracket
34 0x22 ANSI_I
35 0x23 ANSI_P
36 0x24 Return
37 0x25 ANSI_L
38 0x26 ANSI_J
39 0x27 ANSI_Quote
40 0x28 ANSI_K
41 0x29 ANSI_Semicolon
42 0x2A ANSI_Backslash
43 0x2B ANSI_Comma
44 0x2C ANSI_Slash
45 0x2D ANSI_N
46 0x2E ANSI_M
47 0x2F ANSI_Period
48 0x30 Tab
49 0x31 Space
50 0x32 ANSI_Grave
51 0x33 Delete
53 0x35 Escape
55 0x37 Command
56 0x38 Shift
57 0x39 CapsLock
58 0x3A Option
59 0x3B Control
60 0x3C RightShift
61 0x3D RightOption
62 0x3E RightControl
63 0x3F Function
64 0x40 F17
65 0x41 ANSI_KeypadDecimal
67 0x43 ANSI_KeypadMultiply
69 0x45 ANSI_KeypadPlus
71 0x47 ANSI_KeypadClear
72 0x48 VolumeUp
73 0x49 VolumeDown
74 0x4A Mute
75 0x4B ANSI_KeypadDivide
76 0x4C ANSI_KeypadEnter
78 0x4E ANSI_KeypadMinus
79 0x4F F18
80 0x50 F19
81 0x51 ANSI_KeypadEquals
82 0x52 ANSI_Keypad0
83 0x53 ANSI_Keypad1
84 0x54 ANSI_Keypad2
85 0x55 ANSI_Keypad3
86 0x56 ANSI_Keypad4
87 0x57 ANSI_Keypad5
88 0x58 ANSI_Keypad6
89 0x59 ANSI_Keypad7
90 0x5A F20
91 0x5B ANSI_Keypad8
92 0x5C ANSI_Keypad9
93 0x5D JIS_Yen
94 0x5E JIS_Underscore
95 0x5F JIS_KeypadComma
96 0x60 F5
97 0x61 F6
98 0x62 F7
99 0x63 F3
100 0x64 F8
101 0x65 F9
102 0x66 JIS_Eisu
103 0x67 F11
104 0x68 JIS_Kana
105 0x69 F13
106 0x6A F16
107 0x6B F14
109 0x6D F10
111 0x6F F12
113 0x71 F15
114 0x72 Help
115 0x73 Home
116 0x74 PageUp
117 0x75 ForwardDelete
118 0x76 F4
119 0x77 End
120 0x78 F2
121 0x79 PageDown
122 0x7A F1
123 0x7B LeftArrow
124 0x7C RightArrow
125 0x7D DownArrow
126 0x7E UpArrow

JavaScript examples for scripts that run JavaScript in a browser

Return the generated source of a page:

document.body.innerHTML

Reload a page:

window.location.reload()

Get the URL of a page:

window.location.href

Get the selected text as a string:

''+document.getSelection()

Change the value of an element:

document.getElementById('aa').value='bb'

Make a list of the href attributes of links:

o='';a=document.links;for(i=0;e=a[i];i++){o+=e.href+'\n'};o

Scroll to the end of a page:

window.scroll(0,document.body.scrollHeight)

Scroll one page down:

window.scrollBy(0,window.innerHeight)

Remove div elements that have a style attribute:

a=document.querySelectorAll('div[style]');for(i=0;e=a[i];i++){e.parentNode.removeChild(e)}

Return the part after the first equals sign of the bb attribute of the element with the ID aa:

document.getElementById('aa').getAttribute('bb').replace(/^.*?=/,'')

Click the element with the ID aa when the page has finished loading:

window.addEventListener('load',function(){document.getElementById('aa').click()})

Scroll the first element with the class aa into view and return the scroll position:

document.getElementsByClassName('aa')[0].scrollIntoView();window.scrollY

Add jQuery:

x=document.createElement('script');x.src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';document.getElementsByTagName('head')[0].appendChild(x)

Date and time examples

year of (current date)
(current date) + 1 * days
tell (current date) + 1 * days to set time to 0
month of date "12/31/2013" as integer -- 12
time of date "12/31/2013 11:59:59 PM" -- 86399
time string of date "12/31/2013 11:59:59 PM" -- "11:59:59 PM"
date "12/31/2013" as «class isot» -- «data isot323031332D31322D33315430303A30303A3030»

date "12/31/2013" results in an error if the British region is selected from System Preferences and date "31/12/2013" results in an error if the U.S. region is selected from System Preferences. This works with all regions:

set d to current date
tell d to set {year, month, date, time} to {2013, 12, 31, 0}
d -- date "Saturday, October 19, 2013 12:00:00 AM"

Get a date object for 9:00 AM today:

set d to current date
set hours of d to 9
set minutes of d to 0
set seconds of d to 0
d

Two ways to get the path of the current document

This did not work with Preview, TextMate 2, Sublime Text, or iChm:

 tell application (path to frontmost application as text)
     (path of document 1) as text
 end tell

This did not work with Acorn:

tell application "System Events" to tell (process 1 where frontmost is true)
    value of attribute "AXDocument" of window 1
end tell
do shell script "x=" & quoted form of result & ";x=${x/#file:\\/\\/};printf ${x//%/\\\\x}"

Apple events for logging out, restarting, shutting down, and going to sleep

Log out after showing a confirmation dialog (kAELogOut or logo):

tell application "System Events" to log out

Restart after showing a confirmation dialog (kAEShowRestartDialog or rrst):

tell application "loginwindow" to «event aevtrrst»

Shut down after showing a confirmation dialog (kAEShowShutdownDialog or rsdn):

tell application "loginwindow" to «event aevtrsdn»

Log out without showing a confirmation dialog (kAEReallyLogOut or rlgo):

tell application "loginwindow" to «event aevtrlgo»

Restart without showing a confirmation dialog (kAERestart or rest):

tell application "System Events" to restart

Shut down without showing a confirmation dialog (kAEShutDown or shut):

tell application "System Events" to shut down

Go to sleep (kAESleep or slep):

tell application "System Events" to sleep

The four letter codes for Apple events are listed in AERegistry.h.

Changes in 10.9

osascript is now a UI element process, so you can use for example osascript -e'display dialog""' instead of osascript -e'tell app(path to frontmost application as text)to display dialog""'.

Persistent properties are not saved by default for AppleScript applications that use accessibility features.

There is a new syntax for interleaved arguments for handlers. For example on doThis_withThat_(a, b) is compiled to on doThis:a withThat:b.

NSAppleScriptEnabled is set to true by default in Preview's Info.plist.

Sending a message with Mail

tell application "Mail"
    tell (make new outgoing message)
        set subject to "subject"
        set content to "content"
        make new to recipient at end of to recipients with properties {address:"name@example.com"}
        make new attachment with properties {file name:(POSIX file "/tmp/test.txt")} at after last paragraph
        send
    end tell
end tell

Escaping XML

on replace(x, y, z)
    set text item delimiters to y
    set t to text items of x
    set text item delimiters to z
    t as text
end replace

on escapexml(x)
    replace(x, "&", "&amp;")
    replace(result, "<", "&lt;")
    replace(result, ">", "&gt;")
    replace(result, "\"", "&quot;")
end escapexml

Registering an AppleScript application as a URL handler

Save this script as /tmp/a.app in Script Editor:

on open location x
    say x
end open location

Then run:

defaults write /tmp/a.app/Contents/Info.plist CFBundleURLTypes '({CFBundleURLName=myurlscheme;CFBundleURLSchemes=(myurlscheme);})'

The changes should be registered automatically within a few seconds, and then for example the URL myurlscheme://?aa=bb should be opened in the application.

osacompile and osadecompile examples

Display a compiled script as text:

osadecompile file.scpt

Create a compiled script from the clipboard:

pbpaste|osacompile -o file.scpt

Convert uncompiled scripts to compiled scripts:

for f in *.applescript;do osacompile -o "${f%applescript}scpt" "$f";done

Convert compiled scripts to uncompiled scripts:

for f in *.scpt;do osadecompile "$f">"${f%scpt}applescript";done

Search and replace in multiple compiled scripts:

for f in ~/Library/Scripts/**/*.scpt;do osadecompile "$f"|tr \\r \\n|sed s/search/replace/g|osacompile -o "$f";done

osacompile>file.scpt also creates an a.scpt file but osacompile -o file.scpt does not. osadecompile has no -o option.

Creating an application that receives dropped files as input

One option is to save a script like this as an application in Script Editor:

on open input
    say POSIX path of item 1 of input
end open

The script has to be saved as an application because scripts saved as .scpt or .applescript cannot receive dropped files as input.

Another option is to use Automator to create an application with a Run AppleScript command like this:

on run {input, parameters}
    say POSIX path of item 1 of input
end run

Applications created with Automator can be selected from an Open With menu and be given files as an argument with open -a but applications created with Script Editor can not.

Revealing a list of files in Finder

set l to {}
read "/tmp/filestoreveal" as «class utf8» using delimiter linefeed
repeat with p in result
    set end of l to POSIX file p
end repeat
tell application "Finder" to reveal l

Making a list of today's calendar events

set d to current date
set hours of d to 0
set minutes of d to 0
set seconds of d to 0
set out to ""
tell application "Calendar" to tell calendar "Calendar Name"
    repeat with e in (events where start date >= d and start date <= d + 86399)
        set out to out & time string of (get start date of e) & " " & time string of (get end date of e) & " " & summary of e & linefeed
    end repeat
end tell

Removing tracks whose title is contained in a text file from a playlist in iTunes

set x to paragraphs of (read "/tmp/trackstoremove" as «class utf8»)
tell application "iTunes"
    repeat with t in (get tracks of playlist "playlist name")
        if x contains name of t then delete t
    end repeat
end tell

Shell functions

sjs(){ osascript -e'on run{a}' -e'tell app"safari"to do javascript a in document 1' -eend "$1"; }
sjss(){ osascript -e'on run{a}' -e'set out to""' -e'tell app"safari"to repeat with t in(get tabs of window 1)' -e'set out to out&(do javascript a in t)&linefeed' -eend -eout -eend "$1"; }
sso(){ osascript -e'tell app"safari"to source of document 1'; }
ss(){ sjs document.body.innerHTML; }
sss(){ sjss document.body.innerHTML; }
st(){ osascript -e'set text item delimiters to linefeed' -e'tell app"safari"to(url of tabs of window 1)as text'|sed s,^file://,,; }
s1(){ osascript -e'tell app"safari"to url of document 1'|sed s,^file://,,; }
scl(){ osascript -e'tell app"safari"to close window 1'; }
scm(){ osascript -e'on run{a}' -e'tell app"safari"to close tabs of window 1 whose url contains a' -eend "$1"; }
notify(){ osascript -e'on run{a}' -e'display notification""with title a' -eend "${1-notification}"; }
copy(){ osascript -e'on run{a}' -e'set the clipboard to posix file a' -eend "$(readlink -f "$1")"; }
fs(){ osascript -e'set l to{}' -e'tell app"finder"to repeat with f in(get selection)' -e'set end of l to posix path of(f as alias)' -eend -e'set text item delimiters to linefeed' -e'l as text'; }
itt(){ osascript -e'set text item delimiters to linefeed' -e'tell app"itunes"' -e'set l to{}' -e'repeat with t in(get selection)' -e'set end of l to posix path of(get location of t)' -eend -eend -e'l as text'; }
cf(){ cd "$(osascript -e'tell app"finder"to posix path of(insertion location as alias)')"; }
quit(){ osascript -e'on run a' -e'repeat with x in a' -e'quit app x' -eend -eend "$@"; }
qo(){ local x;for x;do quit "$f";open -Fa"$x";done; }

Making a new iTunes playlist for the tracks of a playlist where the artist of the track is contained in a text file

set l to {}
set a to paragraphs of (read "/tmp/artists" as «class utf8»)
tell application "iTunes"
    repeat with t in (get tracks of playlist "playlist name")
        if a contains artist of t then set end of l to location of t
    end repeat
    add items of l to (make new user playlist)
end tell

Removing items whose files have been deleted from the iTunes library

tell application "iTunes"
    repeat with t in (get file tracks of library playlist 1)
        if location of t is missing value then delete t
    end repeat
end tell

Bugs

A multi-line comment that contains an odd number of double quotes (like (* " *) or (* """ *)) results in an error.

Since at least 10.6, when Script Editor's syntax highlighting settings have been changed, they occasionally revert to the default settings when for example Script Editor crashes.

Since 10.8, a warning like CFURLGetFSRef was passed this URL which has no scheme is displayed when a relative path is converted to an alias in a script run with osascript.

Since 10.9, changes to Finder's icon view options are not applied until for example the folder of the Finder window is changed to another folder and back.

Listing the URLs of tabs that have failed to load in Safari

If multiple tabs have failed to load in Safari but you cannot reload the tabs, you can use this script to make a list of the URLs (or the URL-like strings shown on the location bar that are not actually URLs) of all tabs of the frontmost window.

set out to ""
tell application "Safari"
    tell window 1 to repeat with t in (get tabs)
        set current tab to t
        tell application "System Events" to tell process "Safari"
            value of text field 1 of group 2 of toolbar 1 of window 1
            set out to out & result & linefeed
        end tell
    end repeat
end tell

Unsorted notes

`open location "http://ja.wikipedia.org/wiki/漢字"` does not work but `do shell script "open http://ja.wikipedia.org/wiki/漢字"` does
`Unicode text` has been equivalent to `text` and `string` since 10.5
Script Editor replaces escape sequences like `\r` in strings with literal characters by default, so properties like `return` should often be used instead of escape sequences like `\r`
you can insert code for System Events commands by recording UI events in Automator and then dragging the steps from the resulting Watch Me Do action to Script Editor
10.9 came with AppleScript 2.3 and 10.8 came with AppleScript 2.2.2
support for initializer-based scripting additions was removed in 10.7
key code 123 is left, 124 is right, 125 is down, and 126 is up
if the `click` command does not work for selecting a UI element, you can try to use `perform action "AXPress"`, `set selected to true`, or `set focused to true`
`tell app "Finder" to windows` includes view options windows and preferences windows but `tell app "Finder" to Finder windows` does not
if the user presses a cancel button, `display dialog` throws an error but `choose from list` returns false
only a few applications like Finder and BBEdit have ever supported recording AppleScript
`tell application "Mail" to path to application support from user domain` has returned a folder in the sandbox container since 10.8
an `open` handler is used by droplets and an `open location` handler is used when an application is set as a handler for a URL
the `ASCII character` command of Standard Additions has been deprecated in favor of the `character ID` command
the `ASCII number` command of Standard Additions has been deprecated in favor of the `id` property of System Events
the `info for` command of Standard Additions has been deprecated in favor of the `properties` property of System Events
`number` is a pseudo-property equivalent to `count`
text objects have not contained style information since AppleScript 2.0
FastScripts pauses a script before a `key code` or `keystroke` command until modifier keys are released
`set volume output volume 50` and `set volume 3.5` both set the output volume to 50%
you can use `/Applications/Xcode.app/Contents/Applications/Accessibility Inspector.app` to see information about UI elements
the four letter codes for Apple events are listed in `AERegistry.h`, which can be opened by running `open -h aeregistry.h`