AppleScript

Single line

(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
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 containing folder of a script
POSIX path of (path to home folder as text) is (system attribute "HOME") & "/" -- true
POSIX path of (path to temporary items) & (random number)
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 -- class and length of different versions of the clipboard
date "12/31/2013 11:59 PM" -- the recognized formats depend on the settings selected in System Preferences
display dialog "" default answer "" buttons {"a", "b", "c"} default button 3 cancel button 1
display notification "text" with title "title" subtitle "subtitle" -- added in 10.9
do shell script "LC_CTYPE=UTF-8 pbpaste" -- pbpaste and pbcopy don't preserve non-ASCII characters in the C locale
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" -- second frontmost application in 10.9 and later
do shell script "pwd" -- "/"
do shell script "x=" & quoted form of input & ";x=${x//+/%20};printf \"${x//\\%/\\x}\""
do shell script POSIX path of (path to me) & "Contents/Resources/script.sh"
get eof of POSIX file "/tmp/file" -- size in bytes
id of "aあ" -- {97, 12354}
id of "»" -- 187 (ASCII number of has been deprecated)
if result of (do shell script "f=${TMPDIR}lastrun;find $f -mtime +5m;touch $f") is not "" then return
log "message" -- add a message to the event log in AppleScript Editor
middle item of {1, 2, 3, 4} -- 2
month of (current date) as integer
open location "dict:///word"
path to me -- the location of a script if a script has been saved
path to resource "Mail.icns" in bundle (path to application "Mail")
quote of AppleScript -- quote is a property of the global AppleScript object, not a constant
read POSIX file "/path/to/file" as «class utf8» using delimiter linefeed
reverse of characters of "esrever" as text
run script file "script.scpt" with parameters {"arg1", "arg2"}
say "[[rate 180]] a [[slnc 1000]] b" using "Victoria" saving to "/tmp/test.aif"
set is_reference to count references of reference_object is 1 -- class of reference_object returns the class of the referred object
set the clipboard to (read (POSIX file "/Library/Desktop Pictures/Antelope Canyon.jpg") as JPEG picture)
set the clipboard to POSIX file "/Library/Desktop Pictures/Antelope Canyon.jpg"
set volume output volume ((output volume of (get volume settings)) + 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 (system attributes doesn't work)
tell (info for (path to frontmost application)) to text 1 thru (-(number of name extension) - 2) of name
tell app "System Events" to set frontmost of process 1 where unix id is 1234 to true
tell application "Alfred 2" to search "query"
tell application "AppleScript Editor to contents of selection of document 1
tell application "AppleScript Editor" to set bounds of windows to {0, 0, 1919, 1279}
tell application "Calendar" to delete events of calendars where 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 where has keyboard shortcut is true
tell application "Finder" to default application of (info for POSIX file "/Library/Desktop Pictures/Abstract.jpg")
tell application "Finder" to disks where 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 -- an alternative to cp -a ~/ /Volumes/WD (with exact copy preserves owner and group)
tell application "Finder" to duplicate selection to desktop replacing yes
tell application "Finder" to eject disks
tell application "Finder" to eject disks where name is not "MobileBackups"
tell application "Finder" to empty -- alias to empty trash
tell application "Finder" to empty trash if free space of startup disk < 2e9
tell application "Finder" to files of (path to preferences folder) where 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
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 item in the selection
tell application "Finder" to select (items of (insertion location as alias) where 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 -- hide desktop icons by minimizing the window of the desktop
tell application "Finder" to set label index of (get selection) to (item 3 of {2, 1, 3, 6, 4, 5, 7})
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) where 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 "Font Book" to name of typefaces where style name is "Regular"
tell application "Google Chrome" to make new window with properties {mode:"incognito"}
tell application "Google Chrome" to tell active tab of window 1 to execute javascript "o='';for(i=0;e=document.querySelectorAll('a')[i];i++){o+=e.href+'\\n'};o"
tell application "LaunchBar" to display in notification center with title "title" subtitle "subtitle"
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 path to application support from user domain -- alias "HD:Users:lauri:Library:Containers:com.apple.mail:Data:Library:Application Support:"
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" where 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" where date sent < (current date) - 14 * days
tell application "Messages" to send "message" to buddy "Name" of service "E:name@example.com"
tell application "Microsoft Word" to save as active document file name "output.html" file format format HTML
tell application "Pages" to select insertion point after character 7 of body text of document 1
tell application "QuickTime Player" to set rate of document 1 to 0.8
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 where name is not "Untitled") is not {}
tell application "Safari" to delete tab 2 of window 1 -- close a tab
tell application "Safari" to do JavaScript "''+document.getSelection()" in document 1
tell application "Safari" to do JavaScript "document.body.innerHTML" in document 1
tell application "Safari" to do JavaScript "document.getElementById('element').childNodes[0].click()" in document 1
tell application "Safari" to make new document -- open a new window
tell application "Safari" to tell (window 1 where (its document is not missing value)) to set current tab to (make new tab)
tell application "Safari" to tell (window 1 where its document is not missing value) to set current tab to make new tab
tell application "Safari" to tell document 1 to do JavaScript "document.body.innerHTML" -- generated source
tell application "Safari" to tell document 1 to set the clipboard to "[" & name & "](" & URL & ")"
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 where (its type is highlight note)) to its text
tell application "System Events" to POSIX path of disk items of folder "~/Documents"
tell application "System Events" to URL of (item 1 of (get selection of application "Finder") as alias) -- file:/// URL
tell application "System Events" to click (button 1 where subrole is "AXZoomButton") of (window 1 where subrole is "AXStandardWindow") of (process 1 where frontmost is true)
tell application "System Events" to click UI element 1 of menu bar 2 of process "SystemUIServer" -- 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 where background only is false
tell application "System Events" to picture of current desktop -- POSIX path of the desktop picture of the current space
tell application "System Events" to properties of desktops
tell application "System Events" to set UI elements enabled to true
tell application "System Events" to set picture of desktops to "/Library/Desktop Pictures/Antelope Canyon.jpg"
tell application "System Events" to set visible of processes where bundle identifier is not "my.emacs" and name is not "Safari" to false
tell application "System Events" to tell (process 1 where frontmost is true) to value of attribute "AXDocument" of window 1
tell application "System Events" to tell (process 1 where it is frontmost) to tell (window 1 where 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 where 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 where 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 rows of outline 1 of scroll area 1 of splitter group 1 of window 1 where 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 where 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 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 "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) where 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 scroll bar 1 of scroll area 1 of group 1 of group 1 of group -1 of window 1 of process "Safari" to set value of attribute "AXValue" to 0
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 where it is frontmost) to set {position, size} to {{0, 22}, {1920, 1258}}
tell application "System Events" to tell window 1 of (process 1 where it is frontmost) to set {position, size} to {{0, 22}, {1920, 1258}}
tell application "System Events" to tell window 1 of process "Safari" to set value of scroll bar 1 of scroll area 1 of group 1 of group 1 of group 1 to 1.0
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 where 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 "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", "pa55word", "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 (not the playlist shown by iTunes)
tell application "iTunes" to duplicate current track to playlist "Favorites"
tell application "iTunes" to if player state is playing then tell current track to artist & " - " & name
tell application "iTunes" to location of tracks where 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 where artist contains "y"
tell application "iTunes" to play (track 1 of current playlist where 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 after editing tags outside iTunes
tell application "iTunes" to reveal current track -- select the currently playing track on a playlist or in the library view
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 where special kind is none)
tell application "loginwindow" to «event aevtrlgo» -- log out without showing a confirmation dialog
tell application "loginwindow" to «event aevtrsdn» -- show the shut down dialog
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 path of document 1
tell application id "com.Growl.GrowlHelperApp" to close all notifications
tell document 1 of application "TextEdit" to copy word 1 to before paragraph 3
tell window 1 of application "Safari" to close tabs where index > (get index of current tab)
tell window 1 of application "Safari" to set current tab to tab ((index of current tab) + 1)
windows of application "Finder" where visible is true and floating is false and modal is false
«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://appscript.sourceforge.net/osascript.html
http://www.leancrew.com/all-this/2012/06/the-first-nail-in-the-coffin-of-python-appscript/
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

Scripts

Applications/AppleScript Editor/toggle comment.scpt

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

Applications/Finder/copy paths.scpt

activate application "SystemUIServer"
activate application "Finder"
set l to {}
tell application "Finder" to repeat with f in (get selection as alias list)
    set end of l to POSIX path of f
end repeat
set text item delimiters to linefeed
set the clipboard to l as text

Applications/Finder/reset view options.scpt

try
    tell application "Finder"
        if number of 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 {474, 250, 1438, 793}
            tell its column view options
                set shows icon to false
            end tell
        end tell
    end tell
end try

Applications/Finder/zoom in.scpt

try
    tell application "Finder" to tell window 1
        tell its icon view options
            set icon size to (icon size * 1.5)
            if arrangement is none then set arrangement to arranged by name
        end tell
    end tell
end try

Applications/iTunes/edit tags.scpt

set text item delimiters to " - "
tell application "iTunes"
    repeat with t in selection
        tell t
            set ti to text items of (get name)
            set track number to item 1 of ti
            set artist to item 2 of ti
            set name to item 3 of ti
        end tell
    end repeat
end tell

on titlecase(input)
    do shell script "ruby -rubygems -KUe 'require \"titlecase\"; print ARGV[0].titlecase' " & quoted form of input without altering line endings
end titlecase

on replace(input, search, replace)
    set text item delimiters to search
    set ti to text items of input
    set text item delimiters to replace
    ti as text
end replace

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

Applications/iTunes/edit youtube tags.scpt

set text item delimiters to " - "
tell application "iTunes"
    repeat with t in (get selection)
        set name of t to text 1 thru -13 of (get name of t)
        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

Applications/iTunes/remove deleted tracks.scpt

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

Applications/iTunes/renumber tracks.scpt

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

Applications/Safari/add bookmark.scpt

tell application "Safari" to URL of document 1
do shell script "f=~/Notes/bookmarks.txt
[[ -f $f ]] && out=\"$(cat $f)
\"
out+=" & quoted form of result & "
printf %s \"$out\" | awk '!x[$0]++' > $f"

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

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

Applications/Safari/copy URL.scpt

try
    tell application "Safari" to tell document 1
        set the clipboard to (get URL)
    end tell
end try

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/TextEdit/append to study.scpt

try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "x" using option down -- selectParagraph:, cut:
do shell script "[[ $(tail -c1 ~/Notes/study.txt) ]] && x=$'\\n'
x+=$(LC_CTYPE=UTF-8 pbpaste)
printf '%s\\n' \"$x\" >> ~/Notes/study.txt"
try
    set the clipboard to old
end try

Applications/TextEdit/mark as done.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "x" using option down -- selectParagraph:, cut:
    do shell script "[[ $(tail -c1 ~/Notes/done.txt) ]] && x=$'\\n' || x=
printf %s \"$x$(date +%m-%d) $(LC_CTYPE=UTF-8 pbpaste)\"$'\\n' >> ~/Notes/done.txt"
    delay 0.1
end try
try
    set the clipboard to old
end try

copy path.scpt

try
    tell application (path to frontmost application as text)
        set the clipboard to (path of document 1) as text
    end tell
on error
    try
        tell application "System Events" to tell (process 1 where frontmost is true)
            value of attribute "AXDocument" of window 1
        end tell
        do shell script "ruby -rcgi -e 'print CGI.unescape ARGV[0][16..-1]' " & quoted form of result
        set the clipboard to result
    end try
end try

execute as ruby.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "c" using command down
    delay 0.1
    set text item delimiters to linefeed
    set input to (paragraphs of (the clipboard as text)) as text
    set r to do shell script "ruby -e 'def temp;'" & quoted form of input & "';end;puts temp'" without altering line endings
    set the clipboard to text 1 thru -2 of r
    tell application "System Events" to keystroke "v" using command down
    delay 0.1
end try
try
    set the clipboard to old
end try

expand text.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events"
        key code 123 using {option down, shift down}
        keystroke "c" using command down
    end tell
    set match to do shell script "awk -v v=\"$(LC_CTYPE=UTF-8 pbpaste)\" '$1==v{print;exit}' ~/Notes/snippets.txt ~/Notes/unicode.txt ~/Projects/Unicode/html_entities.txt | cut -d' ' -f2-"
    if match is not "" then
        set the clipboard to match
        tell application "System Events" to keystroke "v" using command down
        delay 0.05
    end if
end try
try
    set the clipboard to old
end try

f.scpt

try
    set prev to read POSIX file ((system attribute "TMPDIR") & "me.lri.f") as «class utf8»
on error
    set prev to ""
end try
tell application (path to frontmost application as text)
    set answer to text returned of (display dialog "" default answer prev)
end tell
if answer is "" then return
try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "c" using command down
set input to (do shell script "printf %s " & quoted form of answer & " > ${TMPDIR}me.lri.f
LC_CTYPE=UTF-8 pbpaste | tee ${TMPDIR}me.lri.finput" without altering line endings)
try
    set the clipboard to old
end try
set output to do shell script "/usr/local/bin/bash -lc " & quoted form of (". ~/Scripts/f; cat ${TMPDIR}me.lri.finput | tr '\\r' '\\n' | " & answer) without altering line endings
if output is "" then return
if last character of input is not linefeed and last character of output is linefeed then set output to text 1 thru -2 of output
set the clipboard to output
tell application "System Events" to keystroke "v" using option down -- delete:, setMark:, paste:, selectToMark:
delay 0.05
try
    set the clipboard to old
end try

go down.scpt

try
    tell application "iTunes"
        next track
        set player position to (duration of current track) / 2
        play
    end tell
end try

go forward.scpt

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

maximize left.scpt

try
    tell application "Finder"
        set b to bounds of window of desktop
    end tell
    set item 3 of b to ((item 3 of b) / 2)
    set item 2 of b to 22
    tell application (path to frontmost application as text)
        set bounds of window 1 to b
    end tell
end try

maximize.scpt

try
    tell application "Finder"
        bounds of window of desktop
    end tell
    tell application (path to frontmost application as text)
        set bounds of window 1 to result
    end tell
on error
    try
        tell application "System Events" to tell (process 1 where it is frontmost)
            click (button 1 of window 1 where subrole is "AXZoomButton")
        end tell
    end try
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
set p to (system attribute "HOME") & "/Notes/temp.txt"
tell application "TextEdit"
    close (documents where path is not p)
    if number of documents is 0 then open (POSIX file p) as alias
    set bounds of window 1 to {1100, 23, 1919, 1079}
    activate
end tell

open.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "c" using command down
    do shell script "LC_CTYPE=UTF-8 pbpaste | while IFS= read -r l || [[ $l ]]; do l=${l/#~\\//$HOME/}; l=${l//\\\\}; open \"$l\"; done"
end try
try
    set the clipboard to old
end try

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

puts.scpt

try
    set prev to read POSIX file ((system attribute "TMPDIR") & "putsdialog") as «class utf8»
on error
    set prev to ""
end try
tell application (path to frontmost application as text)
    set answer to text returned of (display dialog "" default answer prev)
end tell
if answer is "" then return
try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "c" using command down
set input to (do shell script "printf %s " & quoted form of answer & " > ${TMPDIR}putsdialog
LC_CTYPE=UTF-8 pbpaste | tee ${TMPDIR}putsinput" without altering line endings)
try
    set the clipboard to old
end try
set output to do shell script "cat ${TMPDIR}putsinput | ruby -e 'puts STDIN.read.'" & quoted form of answer without altering line endings
if output is "" then return
if last character of input is not linefeed and last character of output is linefeed then set output to text 1 thru -2 of output
set the clipboard to output
tell application "System Events" to keystroke "v" using option down
delay 0.05
try
    set the clipboard to old
end try

reveal in Finder.scpt

try
    tell application "System Events" to tell (process 1 where frontmost is true)
        value of attribute "AXDocument" of window 1
    end tell
    do shell script "ruby -rcgi -e 'print CGI.unescape ARGV[0].sub /^file:\\/\\/localhost/, \"\"' " & result
    POSIX file result
    tell application "Finder"
        select result
        activate
    end tell
end try

say in Japanese.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "c" using command down
    delay 0.1
    set input to the clipboard
    try
        set the clipboard to old
    end try
    say input using "Kyoko"
end try

search with Google.scpt

try
    set old to the clipboard as record
end try
tell application "System Events" to keystroke "c" using command down
open location "http://www.google.com/search?q=" & (do shell script "LC_CTYPE=en_US.UTF-8 pbpaste | ruby -e 'require \"cgi\"; print CGI.escape(STDIN.read.strip)'")
try
    set the clipboard to old
end try

show statistics.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "c" using command down
    do shell script "LC_CTYPE=en_US.UTF-8 pbpaste | ruby -KUe 'input = STDIN.read; puts \"#{input.lines.count} lines\"; puts \"#{input.strip.split(/\\s+/m).size} words\"; puts \"#{input.scan(/./mu).length} characters\"'"
    tell application "FastScripts" to display message result dismissing after delay 3
end try
try
    set the clipboard to old
end try

translate.scpt

try
    set old to the clipboard as record
end try
try
    tell application "System Events" to keystroke "c" using command down
    do shell script "open \"http://translate.google.com/#auto/auto/$(LC_CTYPE=UTF-8 pbpaste | ruby -rcgi 'print CGI.escape(STDIN.read.chomp)')\""
end try
try
    set the clipboard to old
end try

Notes

Opening an application

tell application "TextEdit"
    reopen -- open a new default window if there are no open windows
    activate -- make the application frontmost
end tell

activate app "TextEdit" and tell app "System Events" to set frontmost of process "TextEdit" to true raise all windows, but open -a TextEdit raises a single window.

There are at least three ways to open an application hidden and on the background:

launch app "TextEdit"
do shell script "pgrep -x TextEdit||open -jga TextEdit"
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. To avoid it, you can use pgrep -x TextEdit to check if TextEdit is already running. If TextEdit is already running, open -ja TextEdit (without -g) would just make TextEdit frontmost.

lsappinfo was added in 10.9.

Getting the frontmost application or process

tell application (path to frontmost application as text) to properties
tell application "System Events" to tell (process 1 where frontmost is true) to properties

These are equivalent:

process 1 where frontmost is true
front process where it is frontmost
first process whose it is frontmost
item 1 of (processes whose frontmost is true)

Replacing text

set txt to "aa;bb,cc"
set text item delimiters to {";", ","}
set ti to text items of txt
set text item delimiters to "-"
ti as text -- aa-bb-cc

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. See http://stackoverflow.com/questions/14598385/is-restoring-text-item-delimiters-necessary.

According to http://macscripter.net/viewtopic.php?id=24725, changing the text item delimiters property in one window in Script Editor used to also change it in other windows, but that changed at some point. I don't know any places where changing text item delimiters would affect other scripts.

Reading and writing files

There is a single line command for reading a file but not for writing to a file:

read "/usr/share/dict/connectives" as «class utf8»

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

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

get eof returns the size of a file in bytes:

get eof of "/usr/share/dict/connectives" -- 706

Use starting at eof to append text:

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

set eof to 0 makes a file empty:

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

using delimiter linefeed returns the lines of a file as a list:

read POSIX file "/usr/share/dict/connectives" as «class utf8» using delimiter linefeed

You can create an empty file by opening and closing a file reference:

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

pbcopy and pbpaste encodings

pbcopy and pbpaste don't default to UTF-8 if LC_CTYPE is unset or C. Terminal and iTerm 2 set LANG to a value like en_US.UTF-8 by default, but the locale variables are unset by default in AppleScript Editor and Automator.

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).

Ignoring held down modifier keys

If you run the script below by pressing command-R in AppleScript Editor, it probably opens the preferences window.

tell application "System Events" to keystroke ","

One workaround is to add a small delay to the start:

delay 0.2
tell application "System Events" to keystroke ","

Another option is to run the script with FastScripts or Keyboard Maestro. FastScripts pauses a script before a keystroke or key code command until modifier keys have been released. Keyboard Maestro has an action for pausing until modifier keys are not down.

CR line endings

When you compile a script in AppleScript Editor, line endings are preserved in strings and in multi-line comments but converted to carriage returns in other places. The return key always inserts a linefeed.

do shell script replaces linefeeds with carriage returns unless you add a without altering line endings specifier.

the clipboard as text uses CR line endings, but you can convert the line endings by using text item delimiters:

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

Modifying a text selection

try
    set old to the clipboard as record
end try
set the clipboard to ""
tell application "System Events" to keystroke "c" using command down
repeat 100 times
    if (the clipboard) is not "" then exit repeat
    delay 0.01
end repeat
set text item delimiters to linefeed
set input to (paragraphs of (get the clipboard)) as text
try
    set the clipboard to old
end try
if input is "" then return
set the clipboard to "a" & input
tell application "System Events" to keystroke "v" using command down

If the clipboard is empty, trying to get it results in an error. Longer selections need longer delays. All versions of the clipboard that can be accessed with AppleScript use CR line endings.

echo in do shell script

do shell script uses sh, which is a POSIX-compliant version of bash in OS X. When bash is invoked as sh, xpg_echo 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"

You can preserve backslashes by using printf, by unsetting xpg_echo, or by using a here string:

(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
do shell script "tr '[:lower:]' '[:upper:]' <<< " & quoted form of "aa\\tbb\\n" -- "AA\\TBB\\N"

You can use options with echo by unsetting xpg_echo, but you can usually also use printf instead of echo.

ARG_MAX

There is no way to pass input to a do shell script command without making the input a part of the command line. The maximum length of a command line is currently 2^18 bytes:

$ getconf ARG_MAX
262144

So for example this results in an error:

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

As a workaround, you can use a temporary file:

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 "hexdump < " & f & "; rm " & f

AppleScript Editor syntax highlighting settings bug

There has been a bug since at least 10.6 where AppleScript Editor's syntax highlighting settings occasionally revert to the defaults after for example AppleScript Editor is forced to quit.

I don't know any workarounds for the bug. chflags uchg ~/Library/Preferences/com.apple.applescript.plist doesn't help.

Displaying a text dialog

display dialog "" default answer "" buttons {"Cancel", "Maybe", "OK"} cancel button 1 default button 3
set {answer, btn} to {text returned, button returned} of result
if answer is "" then return

"OK" is not recognized as a default button but "Cancel" is recognized as a cancel button. A script exits if the user presses a cancel button or closes the dialog but not if the answer is empty.

Changing volume

set vol to output volume of (get volume settings)
set volume output volume (vol - 2)

set volume output volume 50 and set volume 3.5 both correspond to eight bars.

Finding UI elements

You can use /Applications/Xcode.app/Contents/Applications/Accessibility Inspector.app to see a hierarchy of UI elements. It doesn't show the indexes of UI elements though, and it doesn't tell that for example AXSplitGroup is called splitter group in AppleScript.

If you for example run tell app "System Events" to tell process "Finder" to class of UI elements of window 1, it returns something like {button, button, button, splitter group, image, toolbar, button, static text}. If the UI element you are trying to find has AXSplitGroup as a parent element in Accessibility Inspector, you can then run tell app "System Events" to tell process "Finder" to class of UI elements of splitter group 1 of window 1, and so on.

class of doesn't display parent objects which can make the results easier to read. You can also use properties of to help identify UI elements.

You can also insert System Events code for specifying a UI element by copying steps from a Watch Me Do Action in Automator. Open Automator, create a new workflow, press the record button, click the UI element you want to specify, stop recording, and copy the steps from the Watch Me Do action to AppleScript Editor.

UI scripting

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 always 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 100 times
        if (do JavaScript "document.readyState") is "complete" then exit repeat
        delay 0.1
    end repeat
    URL
end tell

You can often just use window.addEventListener('load',function(){}) instead:

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

If a page already has a listener for window.onload, window.onload=function(){} would replace the listener.

Checking if a file or folder exists

Finder and System Events have an exists command:

set p to (system attribute "HOME") & "/Desktop/test.txt"
tell application "Finder" to exists POSIX file p
tell application "System Events" to exists POSIX file p

You can also try to coerce the file to an alias:

try
    POSIX file p as alias
    true
on error
    false
end try

Getting arguments with osascript

osascript -e 'on run argv
    item 2 of argv
end run' -- aa

Use - as the filename for heredocs:

osascript - aa <<'END'
on run argv
    item 1 of argv
end run
END

Getting stdin with osascript

This used to work in 10.7 and earlier:

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

In 10.8 and later you can use another file descriptor:

$ echo a | osascript 3<&0 -e 'do shell script "cat 0<&3"'
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

osascript relative paths

When a relative path is converted to an alias, there has been a warning like this since 10.8:

$ osascript -e 'POSIX file "Documents" as alias'
2012-11-22 09:40:26.936 osascript[41600:707] CFURLGetFSRef was passed this URL which has no scheme (the URL may not work with other CFURL routines): Documents
alias HD:Users:lauri:Documents:

You can just ignore the warning or redirect stderr:

paths() {
  osascript - "$@" <<'END' 2> /dev/null
on run argv
    POSIX file (item 1 of argv) as alias
end run
END
}
paths test.txt

A get is needed

For application terminology inside AppleScript terminology:

tell application "TextEdit" to text 3 thru -1 of (get name of document 1)

For application terminology inside Standard Additions terminology:

tell application "iTunes" to POSIX path of (get location of current track)

In whose clauses:

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

For some commands where get is actually part of the name of the command:

get volume settings

Finder selection bug in 10.7 and 10.8

This bug was fixed in 10.9.

In 10.7 or 10.8, if you open a new Finder window, select some items in it, and run tell app "Finder" to selection in AppleScript Editor, the result is the items selected in some window behind the frontmost window or on the desktop, which is often an empty list. One workaround is to move focus to another application and back:

activate application "SystemUIServer"
tell application "Finder"
    activate
    selection
end tell

The bug also affects the insertion location property but not the target properties of windows.

Getting files as alias list is faster

$ time osascript -e 'tell application "Finder" to files of (POSIX file "/usr/bin/" as alias) as alias list' > /dev/null
3.367
$ time osascript -e 'tell application "Finder" to files of (POSIX file "/usr/bin/" as alias) as alias list' > /dev/null
0.680
$ time osascript -e 'tell application "Finder" to files of (POSIX file "/usr/bin/" as alias)' > /dev/null
7.366
$ time osascript -e 'tell application "Finder" to files of (POSIX file "/usr/bin/" as alias)' > /dev/null
2.093

Shuffling 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)

There are i * ... * 2 = i! possible sequences of random numbers. Each of them corresponds to exactly one out of the i! permutations of the list.

A faster version that uses 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:

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

If you paste the script below to AppleScript Editor and run it, it can not be saved as .scpt:

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

If you don't run the script, you can save it as .scpt, but there is an error like this if you run it outside AppleScript Editor after that:

$ osascript test.scpt
osascript: couldn't save changes to script test.scpt: Signaled when the runtime stack overflows

Properties and globals are saved in the file of a compiled script, and 10000 is over the maximum number of items that can be saved. You can either use an uncompliled script, add something like set l to {} to the end, or use a handler so that variables are local:

on test()
    set l to {}
    repeat with x from 1 to 10000
        set end of l to x
    end repeat
end test

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"

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

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

Key codes

$ grep '^  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

document.body.innerHTML
window.location.reload()
''+document.getSelection()
document.getElementById('email-field').value='name@example.com'
out='';all=document.links;for(i=0;e=all[i];i++){out+=e.href+'\n'};out
window.scroll(0,999999)
window.scroll(0,document.body.scrollHeight)
all=document.querySelectorAll('div[style]');for(i=0;e=all[i];i++){e.parentNode.removeChild(e)}
document.getElementById('someid').getAttribute('data-hovercard').replace(/.*user.php\?id=/,'').replace(/&.*/,'')
window.addEventListener('load',function(){document.querySelectorAll('.r a')[0].click()})

Date and time

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" doesn't work if the British region is selected in System Preferences and date "31/12/2013" doesn't work if the U.S. region is selected in 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

Getting the path of the current document

try
    tell application (path to frontmost application as text)
        (path 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 "in=" & quoted form of result & ";printf %b \"${in//%/\\\\x}\""
end try

The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn.

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

tell app "System Events" to log out -- kAELogOut (logo): log out after showing a confirmation dialog
tell app "loginwindow" to «event aevtrrst» -- kAEShowRestartDialog (rrst): restart after showing a confirmation dialog
tell app "loginwindow" to «event aevtrsdn» -- kAEShowShutdownDialog (rsdn): shut down after showing a confirmation dialog
tell app "loginwindow" to «event aevtrlgo» -- kAEReallyLogOut (rlgo): log out
tell app "System Events" to restart -- kAERestart (rest): restart
tell app "System Events" to shut down -- kAEShutDown (shut): shut down
tell app "System Events" to sleep -- kAESleep (slep): go to sleep

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

Changes in 10.9

Sending a message with Mail

tell application "Mail"
    tell (make new outgoing message)
        set subject to "subject"
        set content to "content"
        --set visible to true
        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

Setting the clipboard to a URL

set f to (open for access file ((path to temporary items as text) & "urlscratch.tmp") with write permission)
set eof f to 0
write "http://example.com" to f
set u to (read f as URL)
set eof f to 0
write "example" to f as «class utf8»
set urln to (read f as «class urln»)
close access f
set the clipboard to {URL:u, «class urln»:urln}

You can use textutil to copy a URL as rich text:

echo '<a href="http://example.com">example</a>'|textutil -inputencoding UTF-8 -format html -convert rtf -stdin -stdout|LC_CTYPE=UTF-8 pbcopy

Escaping XML

on replace(input, search, replace)
    set text item delimiters to search
    set ti to text items of input
    set text item delimiters to replace
    ti as text
end replace

on escapexml(input)
    replace(replace(replace(input, "&", "&amp;"), "<", "&lt;"), ">", "&gt;")
end escapexml

Registering an AppleScript application as a URL handler

Save this script as /tmp/a.app:

on open location u
    say u
end open location

Then run:

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

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

Making copies of folders that are flattened to remove subfolders

tell application "Finder"
    repeat with f in (get folders of (POSIX file "/Users/username/dir" as alias))
        make new folder at desktop with properties {name:(get name of f)}
        duplicate files of entire contents of f to result
    end repeat
end tell

Allowing access for assistive devices in 10.9

I haven't found any way to always allow access for assistive devices like in 10.8. You can add multiple applications to the list in System Preferences by using drag and drop. For example open a Spotlight window, set the kind to application, select all, and then drag the applications to the list in System Preferences.

The settings are stored in /Library/Application Support/com.apple.TCC/TCC.db, and ~/Library/Preferences/com.apple.universalaccessAuthWarning.plist contains a list of applications for which the warning dialog has been shown.

osacompile and osadecompile

osadecompile file.scpt # show file.scpt as text
for f in *.applescript;do osacompile -o "${f%applescript}scpt" "$f";done # redirecting STDOUT would also create an a.scpt file
for f in *.scpt;do osadecompile "$f">"${f%scpt}applescript";done # osadecompile has no -o option
find ~/Library/Scripts -name \*.scpt|while read f;do osadecompile "$f"|tr \\r \\n|sed 's/search/replace/g'|osacompile -o "$f";done

Disabling auto-save in AppleScript Editor

AppleScript Editor has supported auto-save since 10.8, but if you run a compiled script outside AppleScript Editor, you still have to compile or save the script manually to apply the changes. I kept forgetting to do it, so I disabled auto-save:

defaults write com.apple.ScriptEditor2 ApplePersistence -bool false

If you run a script with uncompiled changes outside AppleScript Editor, there is an error like "This script contains uncompiled changes and cannot be run" in 10.8, and the previously compiled version of the script is run in 10.9.

Creating an application that receives dropped files as input

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

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

Scripts saved as .scpt or .applescript cannot receive dropped files as input.

Another option is to use Automator. Applications created with AppleScript Editor cannot be selected from an Open With menu or given files as an argument with open -a but applications created with Automator can.

Listing 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 - 1 and start date < d + 86400)
        set out to out & time string of (get start date of e) & " "
        set out to out & time string of (get end date of e) & " " & summary of e & linefeed
    end repeat
end tell

Unsorted notes

`open location "http://ja.wikipedia.org/wiki/漢字"` doesn't work but `do shell script "open http://ja.wikipedia.org/wiki/漢字"` does
`Unicode text` has been equivalent with text and string since 10.5
AppleScript Editor replaces \n and \r in strings with literal LF and CR characters by default
you can insert code for System Events commands by recording actions in Automator and then dragging steps from the Watch Me Do action to AppleScript Editor
a multi-line comment that contains an odd number of double quotes like `(* " *)` result in an error
10.9 came with AppleScript 2.3 and 10.8 came with AppleScript 2.2.2
there is a bug in 10.9 where changes to Finder's icon view options are not applied until you for example change the target to another folder and back
scripts that can be run by NSUserScriptTask must be stored in NSApplicationScriptsDirectory
support for initializer-based scripting additions was removed in 10.7
123 is left, 124 is right, 125 is down, and 126 is up
if clicking a UI element doesn't work, try using `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` doesn't
`display dialog` returns an error if the user presses a cancel button but `choose from list` returns false
only a few applications like Finder and BBEdit have ever supported recording AppleScripts
using `AppleScript's text item delimiters` instead of `text item delimiters` is only needed inside tell blocks
`on open` is used for droplets and `on open location` is used when an application is set as a handler for a URL
ASDictionary creates plain text or HTML files for dictionaries and ASTranslate converts scripts to appscript
NSAppleScript is part of Foundation so it is linked by all Cocoa applications
`info for` has been deprecated in favor of `tell application "System Events" to properties of`
`ASCII character` and `ASCII number of` have been deprecated in favor of `character ID` and `id of`
`tell application "Mail" to path to application support from user domain` returns a folder in the sandbox container
`quote` is a property of the global AppleScript object and not a constant