With scripting hooks, you can automatically run CotEditor scripts in response to specific events.
To support the scripting hooks, the script must be written in AppleScript or JavaScript for Automation (JXA), and stored in the form of a script bundle (.scptd).
CotEditor supports hooks for the following events:
| Event handler | Description |
|---|---|
document opened |
After the document is opened and the content is loaded. |
document saved |
After the document is explicitly saved and the content is stored. |
You can find this specification in Script Editor, which is built into macOS, under the CotEditor Event Handler Suite section of CotEditor’s AppleScript dictionary.
A script bundle is a package with the following folder structure:
Tip: You can use Script Editor, which is built into macOS, to create scripts in the script bundle format.
To support scripting hooks, list the events to subscribe to in Contents/Info.plist. Info.plist is a property list that stores bundle metadata in XML, like the following example:
<?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>
Store the events to subscribe to in the CotEditorHandlers key as an array of strings. For example, to run a script automatically when a document is opened or saved, write:
<key>CotEditorHandlers</key>
<array>
<string>document opened</string>
<string>document saved</string>
</array>
An event handler is a block of code that receives specific events triggered by the app and performs actions in response. This section shows how to write event handlers using a simple example that writes messages to the console when a document is opened or saved.
In AppleScript, handlers are written by combining a using terms from block with on handlers.
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
In JavaScript for Automation, use global function declarations to create handlers.
CotEditor = Application.currentApplication()
CotEditor.includeStandardAdditions = true
function documentOpened(document) {
CotEditor.writeToConsole("Opened " + document.name())
}
function documentSaved(document) {
CotEditor.writeToConsole("Saved " + document.name())
}