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).
The following events are available in CotEditor:
| 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 the specifications under the CotEditor Event Handler Suite section in the CotEditor AppleScript dictionary in Script Editor.
A script bundle is a package-type file format that has 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, the list of events to subscribe to must be written in Contents/Info.plist. Info.plist is a property list containing the metadata of the bundle and formatted 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>
The events to subscribe must be stored at the key CotEditorHandlers and in the form of array of string. For example, to run a script automatically when opening and saving a document, write as follows:
<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. In this section, the ways to write an event handler are described using a simple example that shows a dialog when opening and saving a document.
In AppleScript, handlers are written with a using terms from block and on blocks.
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, function statements on the global object create handlers.
CotEditor = Application.currentApplication()
CotEditor.includeStandardAdditions = true
function documentOpened(document) {
CotEditor.writeToConsole("Opened " + document.name())
}
function documentSaved(document) {
CotEditor.writeToConsole("Saved " + document.name())
}