豆腐メンタルは崩れない

小説家ワナビ視点で、主に執筆環境について書きます。

SafariのMakeLink拡張をAppleScriptで置換してみた

(2014-07-14一部修正)

きっかけ

参考

概要

実行

  • スクリプトメニューから実行
    • Safariがアクティブでなくても実行可能
    • スクリプトファイルを「~/Library/Services/Safari/」に置いておくとSafariアクティブ時のみ表示できる
  • BetterTouchToolから実行できるが、その場合は「~/Library/Services/」に置いておかないと動かない
  • アプリケーションとして書き出すとAlfredとかからも実行可能

コード

tell application "Safari" --または"Shiira"
    try
        set theUrl to (URL of document 1)
        set theTitle to (name of document 1)
    on error
        beep 2
        return
    end try
end tell

set theInfo to "[" & theTitle & "](" & theUrl & ")"
set the clipboard to theInfo

最後にペーストする場合は末尾に以下を追加。ただしすごい遅い。

-- ⌘Vを押す
delay 0
set timeoutSeconds to 2.0
set uiScript to "keystroke \"v\" using command down"
my doWithTimeout(uiScript, timeoutSeconds)

on doWithTimeout(uiScript, timeoutSeconds)
    set endDate to (current date) + timeoutSeconds
    repeat
        try
            run script "tell application \"System Events\"
" & uiScript & "
end tell"
            exit repeat
        on error errorMessage
            if ((current date) > endDate) then
                error "Can not " & uiScript
            end if
        end try
    end repeat
end doWithTimeout

Safariアクティブ時のみ実行する場合は以下のコード。スクリプトファイルは、スクリプトフォルダ内のSafariフォルダに保存する。

try
set theUrl to (URL of document 1)
set theTitle to (name of document 1)
on error
beep 2
return
end try

set theInfo to "[" & theTitle & "]()(" & theUrl & ")"
set the clipboard to theInfo