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

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

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

CotEditorは、次のイベントに対するフックをサポートしています:

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

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

document saved

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

macOSに内蔵されているスクリプトエディタでは、これらのイベントの定義を、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())
}

関連項目