AppleScript 覚え書き
TextMate, QuickSilver を使っていると AppleScript が欠かせないものになってくる。
今まで見よう見まねで AppleScript を使っていたけど思うようにいかない、、のでリファレンスに目を通してみた。
メインはコードと一緒に gist に、gist に書けなかった覚え書きをここにメモ。
学び終えた今は MacRuby 頑張れ!!の気持ちでいっぱいです。
AppleScript is an object-oriented language. An object is an instantiation of a class definition, which can include properties and actions. "script" is the top-level object, which is the overall script we are working in.
自然言語的な見かけを持てるよう設計された言語で、面白いけどとっつき悪いように思う。
-- オブジェクトのプロパティを of で辿る。 as integer でキャスト (coercion) -- log や say は utf-8 クラスが扱えないので注意 log(size of first file of window 1 of application "Finder" as integer)
handler、所謂関数の定義は
-- 普通ぽい形 -- AS っぽい事をしたい人は log に代えて say を使うとか on rock(clock) log (clock as text) end rock rock(current date) -- こうも書ける on rock around clock log (clock as text) end rock -- 呼び出し側も変わる。() では呼べない。 rock around current date -- optional に the も使える on rock around the clock log (clock as text) end rock -- こちらの the も省略可能 rock around the current date
更に
-- labeled parameters to findNumbers of numberList above minLimit given rounding:roundBoolean end findNumbers -- call findNumbers of myList above 19 given rounding:true -- もしくは findNumbers of {5.1, 20.1, 20.5, 33} above 20 with rounding findNumbers of {5.1, 20.1, 20.5, 33.7} above 20 without rounding -- patterned positional parameters on hl({x,y}) log x * y end hl hl({10, 20})
シェルスクリプト実行
-- シェルスクリプト実行 log (do shell script "cd ~; ls") -- Technical Note TN2065, do shell script in AppleScript. -- http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
tell について、ScriptEditor にて次を実行する
log name of window 1 as text tell application "Finder" log name of window 1 as text end tell log name of window 1 of application "Finder" as text
どのオブジェクトにメッセージ送信されるかにより結果が変わっている。
... of me や my ... でステートメント単位でコントロール出来る。 tell を使うとブロック内を括れる。
tell の外部と内部ではスコープが異なるので外部で定義されているハンドラの参照には my や of me が必要 (me はスクリプト自体を指す)
tell application "Finder" my fn(name of window 1) end tell on fn(x) log x & "!!!" end fn
シェルから AppleScript を使う
#!/usr/bin/osascript
osascript -e 'tell app "Address Book" to get the name of every person' | perl -pe 's/, /\n/g' | sort | uniq