スクリプトフックの追加

スクリプトフックは、特定のイベント発生時にスクリプトを起動する機能です。CotEditorは、次に挙げるイベントでのフックをサポートしています。

イベントの詳細な仕様については、AppleScript辞書のCotEditor Event Handler suite項を参照してください。

このページではCotEditorスクリプトをスクリプトフックへ対応させる方法について説明します。

概要

フックに対応したスクリプトを作成する場合、以下の制約を満足する必要があります。

以上に加えて、フックしたいイベントをメタデータファイルにて明示し、イベントハンドラを記述する必要があります。

スクリプトバンドルの構造

スクリプトバンドルは、以下に示す構造を持つディレクトリ構造です。

HookingScript.scptd
└── Contents
    ├── Info.plist
    └── Resources
        ├── Script Libraries
        │   └── my-fancy-library.scpt
        ├── Scripts
        │   └── main.scpt
        └── description.rtfd
            └── TXT.rtf

この形式には、macOSに標準で添付されているスクリプトエディタを用いることにより、簡単に書き出すことができます。

CotEditorのスクリプトフックに対応させるためには、まず、`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
        set thePath to file of theDocument
        display alert "Opened " & thePath
    end document opened

    on document saved theDocument
        set thePath to file of theDocument
        display alert "Saved " & thePath
    end document saved
end using terms from

JavaScript for Automation (JXA)

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

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

function documentOpened(document) {
  CotEditor.displayAlert("Opened " + document.file().toString())
}

function documentSaved(document) {
  CotEditor.displayAlert("Saved " + document.file().toString())
}

関連項目