Safari で開いているページのリンクを Evernote クライアントに送る
最近、プログラミング関係のまとめやインストール手順の記録といったものには Evernote を利用している。
画像中の手書き文字認識や「脳を拡張する」といった誇大広告ばかりが取り沙汰されるサービスだが、単純にメモツールとして優れており、特に Mac クライアントと iPhone クライアントの出来がすばらしい。
Evernote: Mac クライアント
プログラミング関係の話題をノートにまとめていると、興味深いページへのリンクを多く埋め込むことになる。ノートの編集は Mac のクライアントで行うことが多いのだが、この作業がけっこう面倒だ:
- Safari で開いているページのタイトルをコピーして、Evernote クライアントにペースト
- コピーしたタイトルを選択
- リンクを追加するためのシートを表示
- Safari で開いているページの URL をコピーして、Evernote クライアントにペースト
- OK ボタンをクリック
この手順を毎回、繰り返さなければならない。慣れれば無意識に出来るような単純作業ではあるが、単純作業なら自動化した方がいい。
AppleScript
Mac で自動化といえば AppleScript の出番なのだが、残念ながら Mac 向け Evernote クライアントの AppleScript 対応は今回の要件には不十分である。そのため、今回は System Events による GUI スクリプティングにより、上記手順のキー操作やボタンクリックをエミュレートすることにした。
-- EvernoteCopyLink.applescript
-- Copy title and URL in the front most window of Safari to Evernote with link
-- Author: Takanori Ishikawa
on copyLinkToEvernote(theTitle, theURL)
tell application "System Events"
-- copy & paste
set the clipboard to theTitle as text
keystroke "v" using command down
tell process "Evernote"
-- Select pasted text
-- Note 1: 'ASCII character 28' means 'move left'.
-- Note 2: "shift + option" selection might be more efficient,
-- but it does not work correctly with Japanese text.
(*
repeat (length of words of theTitle) times
keystroke (ASCII character 28) using {shift down, option down}
end repeat
*)
repeat length of theTitle times
keystroke (ASCII character 28) using shift down
end repeat
-- Link, Add...
keystroke "k" using command down
delay 0.1
set the clipboard to theURL as text
keystroke "v" using command down
-- click "OK"
delay 0.1
repeat with w in windows
if exists sheet 1 of w then
click button "OK" of sheet 1 of w
end if
end repeat
end tell
end tell
end copyLinkToEvernote
tell application "System Events"
if not (exists application process "Evernote") or not (exists application process "Safari") then
display alert "Evernote and Safari Required" message "You have to launch Evernote and Safari before executing script"
end if
end tell
tell first document of application "Safari"
set pageTitle to name
set pageURL to URL
end tell
tell application "Evernote" to activate
set theClipboard to the clipboard
copyLinkToEvernote(pageTitle, pageURL)
set the clipboard to theClipboard
このスクリプトを実行すると、Safari で開いているページのリンクを、Evernote クライアントのノートに挿入することができる。スクリプト・メニューに登録して、しばらく使ってみるつもりだ。スクリプトは gist:33786 でも公開している。
Note
System Events を使っているため、上記スクリプトを実行するには「システム環境設定」>「ユニバーサル・アクセス」>「補助装置にアクセスできるようにする」チェックボックスをオンにする必要がある。
なお、Pygments による AppleScript ソースコードのハイライトには自作の The Pygments lexer for AppleScript language を使用した。AppleScript 構文のサポートはまだ完全ではないが、何もないよりはマシだろう。
(2008/12/13 追記)Pygments 1.0 で AppleScript のサポートが追加された。このブログも Pygments 1.0 にアップデートし、自作のモジュールは OBSOLETE 扱いとした。