MacのCotEditorで特定のイベントでスクリプトを実行する

スクリプトフックを使うと、特定のイベント発生時にスクリプトを自動で実行することができます。

フックに対応したスクリプトを作成するには、AppleScriptまたはJavaScript for Automation(JXA)で記述して、スクリプトバンドル形式(.scptd)で保存する必要があります。

CotEditorは以下のイベントでのフックをサポートしています:

イベントハンドラ説明
document opened

書類を開いて、テキストが読み込まれたとき。

document saved

書類を明示的に保存して、テキストが書き込まれたとき。

この仕様は、スクリプトエディタで、CotEditorのAppleScript辞書の「CotEditor Event Handler Suite」のセクションで確認することができます。

スクリプトバンドルでフックを宣言する

スクリプトバンドルは、以下のファイル構造を持つパッケージ型のファイルです:

HookingScript.scptd
└── Contents
    ├── Info.plist
    └── Resources
        ├── Scripts
        │   └── main.scpt
        └── description.rtfd

ヒント: Macに標準で内蔵されているスクリプトエディタで、スクリプトをスクリプトバンドル形式で保存することができます。

CotEditorのスクリプトフックに対応させるためには、まず、Contents/Info.plistにフックしたいイベントの一覧を記載する必要があります。 plistファイルはプロパティリストと呼ばれ、その内容は以下に示すようなXML形式で記述されたバンドルのメタデータです。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>CFBundleIdentifier</key>
    <string>com.coteditor.hooking-script</string>
    <key>CFBundleName</key>
    <string>Hooking Script</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
  </dict>
</plist>

フックしたいイベントの一覧は、キーCotEditorHandlersに文字列の配列として記載します。例えば、書類を開いたときと保存したときにスクリプトを自動的に実行したいときは、以下のように記述します:

<key>CotEditorHandlers</key>
<array>
  <string>document opened</string>
  <string>document saved</string>
</array>

イベントの処理を記述する

イベントハンドラは、アプリが発生させたイベントを受信し、処理をするスクリプトを指します。ここでは、ファイルを読み込んだ後と書き込んだ後にダイアログを表示するスクリプトを例に採り上げ、イベントハンドラの記述方法について説明します。

AppleScript

AppleScriptでスクリプトを記述する場合、using terms fromブロックとonブロックを組み合わせることで、ハンドラを作成します。

using terms from application "CotEditor"
	on document opened theDocument
		write to console "Opened " & (theDocument's name)
	end document opened

	on document saved theDocument
		write to console "Saved " & (theDocument's name)
	end document saved
end using terms from

JavaScript for Automation (JXA)

JavaScript for Automationでスクリプトを記述する場合、function文を用いてハンドラを作成します。関数はグローバルオブジェクト上で定義する必要があります。

CotEditor = Application.currentApplication()
CotEditor.includeStandardAdditions = true

function documentOpened(document) {
  CotEditor.writeToConsole("Opened " + document.name())
}

function documentSaved(document) {
  CotEditor.writeToConsole("Saved " + document.name())
}

関連項目