QOwnNotes 脚本钩子(Scripting Hooks)完全指南:从签名、调用链到实战示例

原创2026-10-14 08:49:551,899 阅读
文章标签:桌面应用知识管理富文本插件系统跨平台

QOwnNotes 脚本钩子(Scripting Hooks)完全指南:从签名、调用链到实战示例

QOwnNotes 是一款以纯文本文件为核心、支持 Markdown 与 Nextcloud/ownCloud 同步的笔记与待办事项管理工具。它的 QML 脚本引擎提供了一整套脚本钩子(Hooks)——即由主程序在特定事件发生时主动调用的、约定好名称与参数签名的脚本函数,让用户可以在笔记保存、打开、标签管理、HTML 预览生成、加密解密等环节注入自定义逻辑。本文以仓库脚本钩子文档(webpage/src/fa/scripting/hooks.md,英文内容为原文、波斯文为翻译)为骨架,结合 src/services/scriptingservice.cpp 等源码逐一讲解每个钩子的调用时机、参数语义、返回值约定与典型实战用法;读完你可以照着示例脚本写出自己的钩子,并理解其底层调用机制与性能约束。

钩子机制概览:脚本如何被主程序调用

QOwnNotes 的脚本引擎(ScriptingService)在加载脚本时,会用 methodExistsForObject() 探测脚本对象上是否存在某个特定签名的函数(例如 onNoteStored(QVariant)、noteOpenedHook(QVariant)),存在则将其接入对应的调用点。从源码看,大部分钩子通过 QMetaObject::invokeMethod() 反射式调用,并统一记录每次调用的耗时(logScriptHookTiming(),见 scriptingservice.cpp),便于在脚本日志中定位慢钩子。

所有钩子的通用约定如下:

  • 定义位置:钩子函数定义在 QML 脚本顶层对象(QtObject 或 Script 类型)内,函数名必须与文档约定的名称完全一致;
  • 多脚本共存:当多个脚本定义了同一钩子时,大多数返回字符串/文本的钩子按脚本加载顺序依次调用,第一个返回非空字符串的脚本“获胜”,其返回值作为最终结果(例如 insertMediaHook、insertAttachmentHook、fetchUrlTitleHook、handleNoteTextFileNameHook 等);
  • 返回约定:返回空字符串表示“不修改/不接管”,让 QOwnNotes 走默认逻辑;部分钩子返回布尔值表示“是否已处理”;
  • 参数传递:NoteApi 对象通过 QVariant::fromValue(static_cast<QObject *>(noteApi)) 包装后传入脚本,脚本内可直接访问其属性与方法(如 note.noteText、note.name、note.tagNames())。

下面按“笔记生命周期 / 内容渲染 / 标签与编辑 / 系统集成”四组逐一展开。

一、笔记生命周期钩子

onNoteStored:笔记写入磁盘时

这是最底层的存储钩子。onNoteStored 在笔记被写入磁盘后触发,签名如下:

/**
 * This function is called when a note gets stored to disk
 * You cannot modify stored notes, that would be a mess since
 * you are most likely editing them by hand at the same time
 *
 * @param {NoteApi} note - the note object of the stored note
 */
function onNoteStored(note);

关键约束:文档明确警告不要在钩子内修改已存储的笔记——此时你可能正同时在手动编辑该文件,任何写入都可能造成混乱。因此它适合做“通知/观察类”任务,例如记录笔记变更历史、触发外部同步动作,而不是改写内容。

源码印证:ScriptingService 在加载脚本时通过信号槽连接实现该钩子:

if (methodExistsForObject(object, QStringLiteral("onNoteStored(QVariant)"))) {
    QObject::connect(this, SIGNAL(noteStored(QVariant)), object,
                     SLOT(onNoteStored(QVariant)));
}

(scriptingservice.cpp);信号 noteStored(QVariant) 在笔记实体写入磁盘时发出(note.cpp)。也就是说,onNoteStored 是所有钩子中唯一通过 Qt 信号槽机制连接的,其余钩子大多为直接反射调用。

noteOpenedHook:笔记打开后

/**
 * This function is called after a note was opened
 *
 * @param {NoteApi} note - the note object that was opened
 */
function noteOpenedHook(note);

该钩子在笔记被打开之后调用,是“感知用户当前正在看哪篇笔记”的入口。触发点在 mainwindow.cpp 的 callHandleNoteOpenedHook(&currentNote);实现中会先 noteApi->fetch(note->getId()) 构造完整的 NoteApi 对象再传入(scriptingservice.cpp)。

实战示例:官方示例 on-note-opened.qml 展示了最小实现——在每次打开笔记时把完整文件路径写入脚本日志:

import QtQml 2.0
import QOwnNotesTypes 1.0

QtObject {
    function noteOpenedHook(note) {
        script.log(note.fullNoteFilePath);
    }
}

noteDoubleClickedHook:笔记被双击时

/**
 * This function is called after a note was double clicked
 *
 * @param {NoteApi} note - the note object that was clicked
 */
function noteDoubleClickedHook(note);

该钩子在笔记列表中被双击时触发,可用于拦截默认行为、实现自定义的打开/外部编辑器联动。源码中它由笔记树管理器在双击事件中调用(notetreemanager.cpp),返回 bool 表示是否有脚本处理了该事件(scriptingservice.cpp)。

实战示例:官方示例 external-note-open.qml 用该钩子把双击行为重定向为“在外部编辑器打开笔记”,文档建议实现自定义双击行为时参考它。

handleNewNoteHeadlineHook:创建新笔记前改写标题

/**
 * This function is called before a note is created
 *
 * It allows you to modify the headline of the note before it is created
 * Note that you have to take care about a unique note name, otherwise
 * the new note will not be created, it will just be found in the note list
 *
 * You can use this function for creating note templates
 *
 * @param headline text that would be used to create the headline
 * @return {string} the headline of the note
 */
function handleNewNoteHeadlineHook(headline);

该钩子在新笔记创建之前被调用,接收将要使用的标题文本,返回修改后的标题。文档特别提示:如果你改变了标题,必须自行保证笔记名称的唯一性——否则新笔记不会真正创建,而只是在笔记列表中被“找到”。

典型用途是笔记模板:例如根据日期生成标题、附加固定前缀。触发点位于搜索/新建过滤器管理器(searchfiltermanager.cpp)。官方示例 custom-new-note-headline.qml 演示了自定义新笔记标题的完整写法。

handleNoteTextFileNameHook:存储时改写笔记文件名

/**
 * This function is called when a note gets stored to disk if
 * "Allow note file name to be different from headline" is enabled
 * in the settings
 *
 * It allows you to modify the name of the note file
 * Keep in mind that you have to care about duplicate names yourself!
 *
 * Return an empty string if the file name of the note should
 * not be modified
 *
 * @param {NoteApi} note - the note object of the stored note
 * @return {string} the file name of the note
 */
function handleNoteTextFileNameHook(note);

前置条件:该钩子只在设置中启用了 “允许笔记文件名与标题不同”(Allow note file name to be different from headline) 时才会在笔记写盘时被调用。它允许你修改笔记文件的名称,返回值是“不含扩展名”的文件名;返回空字符串表示不改名。

注意:文档与源码都强调重名问题需要你自己负责——钩子不会帮你检测或避免文件名冲突。实现中在写盘路径处调用(note.cpp)。

实战示例:官方示例 use-tag-names-in-filename.qml 演示了一个非常实用的场景——把笔记的标签名拼接到文件名中:

function handleNoteTextFileNameHook(note) {
    // the current note name is the fallback
    var fileName = note.name;

    // get a list of note text lines
    var noteLines = note.noteText.split("\n");

    // set the first line of the note as base for the file name
    if (noteLines.length > 0) {
        fileName = noteLines[0];
    }

    // get a list of all assigned tag names
    var tagNameList = note.tagNames();

    // add the tag names to the filename
    if (tagNameList.length > 0) {
        fileName += " [" + tagNameList.join("] [") + "]";
    }

    script.log("note file name: " + fileName);

    var noteExists = script.noteExistsByFileName(fileName + ".md", note.id);
    script.log("note " + (noteExists ? "exists" : "doesn't exist"));

    return fileName;
}

该示例还展示了配套 API 的用法:note.noteText 读取正文、note.tagNames() 获取标签、script.noteExistsByFileName() 检查重名,正好印证“文件名唯一性由脚本负责”的约定。

handleNoteNameHook:改写笔记显示名称

/**
 * This function is called when the note name is determined for a note
 *
 * It allows you to modify the name of the note that is viewed
 *
 * Return an empty string if the name of the note should not be modified
 *
 * @param {NoteApi} note - the note object of the stored note
 * @return {string} the name of the note
 */
function handleNoteNameHook(note);

与文件名钩子不同,handleNoteNameHook 只影响笔记的显示名称(主要在笔记列表中展示时使用,文档原文:“The note name is mainly used when showing the note in the lists.”),不改变磁盘上的文件名。返回空字符串表示不改名。它在笔记名称被确定时调用,触发点包括 note.cpp 与 searchfiltermanager.cpp。

波斯文文档中的补充提示:如果设置中启用了“用文件名作为笔记名”,再使用该钩子就不太合适了(两者会互相冲突)。官方示例见 example.qml。

二、内容插入与粘贴钩子

insertMediaHook / insertAttachmentHook:媒体与附件插入

这两个钩子分别在媒体文件或附件文件被插入当前笔记时调用,允许你改写最终写入笔记的 Markdown 文本:

/**
 * @param fileName string the file path of the source media file before it was copied to the media folder
 * @param markdownText string the markdown text of the media file, e.g. my-image
 * @return string the new markdown text of the media file
 */
function insertMediaHook(fileName, markdownText);
/**
 * @param fileName string the file path of the source attachment file before it was copied to the attachment folder
 * @param markdownText string the markdown text of the attachment file, e.g. my-file.txt
 * @return string the new markdown text of the attachment file
 */
function insertAttachmentHook(fileName, markdownText);

两个钩子的共性规则(文档原文明确写出):

  • 在媒体/附件文件被复制到媒体文件夹或附件文件夹之前,你拿到的 fileName 是源文件路径,markdownText 是即将插入的 Markdown(示例给出了真实格式:my-image 与 my-file.txt,其中的长数字是去重后缀);
  • 如果多个脚本都定义了该钩子,第一个返回非空字符串的脚本获胜。

源码印证:callInsertMediaHook() 与 callInsertAttachmentHook() 的实现几乎一致——按脚本组件顺序遍历,命中函数签名 insertMediaHook(QVariant,QVariant) / insertAttachmentHook(QVariant,QVariant) 后反射调用,返回非空则立即短路返回(scriptingservice.cpp)。触发点分别在媒体插入与附件插入流程中(mainwindow.cpp、mainwindow.cpp)。文档推荐的参考示例为 example.qml。

insertingFromMimeDataHook:拦截 Ctrl + Shift + V 粘贴

/**
 * This function is called when html or a media file is pasted to a note with `Ctrl + Shift + V`
 *
 * @param text text of the QMimeData object
 * @param html html of the QMimeData object
 * @returns the string that should be inserted instead of the text from the QMimeData object
 */
function insertingFromMimeDataHook(text, html);

当用户用 Ctrl + Shift + V 把 HTML 或媒体文件粘贴进笔记时,该钩子被调用。它接收剪贴板 QMimeData 对象的纯文本与 HTML 两个字段,返回的字符串替换默认粘贴内容;返回空则走默认插入逻辑。实现上通过 mimeData->text() / mimeData->html() 取数(scriptingservice.cpp),触发点在粘贴处理处(mainwindow.cpp)。

文档给出的三个参考示例覆盖了三种典型场景:

fetchUrlTitleHook:接管链接标题抓取

/**
 * @param url string the URL whose title should be fetched
 * @return string the title for the URL, or an empty string to let QOwnNotes fetch it
 */
function fetchUrlTitleHook(url);

该钩子在链接对话框中、QOwnNotes 尝试从 URL 抓取网页标题之前被调用。若脚本返回非空标题,则直接使用;返回空字符串则继续由 QOwnNotes 自行抓取。多脚本共存时同样遵循“第一个返回非空者获胜”。

触发点在链接对话框中(linkdialog.cpp),实现见 scriptingservice.cpp。官方示例 fetch-url-title-with-kanboard-cli.qml 演示了调用外部 CLI 工具抓取标题的思路——适合那些无法被内置抓取器访问的内网系统。

三、Markdown 渲染与加密钩子

preNoteToMarkdownHtmlHook:转换前改写 Markdown

/**
 * This function is called before the markdown html of a note is generated
 *
 * It allows you to modify what is passed to the markdown to html converter
 *
 * The function can for example be used in multiple scripts to render code (like LaTeX math or mermaid)
 * to its graphical representation for the preview
 *
 * The note will not be changed in this process
 *
 * @param {NoteApi} note - the note object
 * @param {string} markdown - the markdown that is about to being converted to html
 * @param {bool} forExport - true if the html is used for an export, false for the preview
 * @return {string} the modified markdown or an empty string if nothing should be modified
 */
function preNoteToMarkdownHtmlHook(note, markdown, forExport);

在笔记的 Markdown 被转换为 HTML 之前调用,允许修改“将要交给 Markdown→HTML 转换器”的输入。这是渲染管线中最早的一环,文档给出的典型用途是:在多个脚本中把 LaTeX 数学公式、mermaid 图表等代码块渲染成图形表示,供预览使用。注意此过程不会改动笔记本身(The note will not be changed in this process)。

参数 forExport:true 表示本次 HTML 用于导出(如导出/打印),false 表示用于预览——这让脚本可以对“导出版”和“预览版”分别处理。

源码印证:callPreNoteToMarkdownHtmlHook() 遍历所有脚本组件,把上一个脚本的返回结果作为下一个脚本的输入(链式流水线),并在最后与原始 markdown 比较,未变化则返回空串(scriptingservice.cpp)。触发点在笔记实体生成导出/预览 HTML 的流程中(note.cpp)。参考示例:preview-styling.qml。

noteToMarkdownHtmlHook:转换后改写 HTML

/**
 * This function is called when the markdown html of a note is generated
 *
 * It allows you to modify this html
 * This is for example called before by the note preview
 *
 * The function can be used in multiple scripts to modify the html of the preview
 *
 * @param {NoteApi} note - the note object
 * @param {string} html - the html that is about to being rendered
 * @param {bool} forExport - true if the html is used for an export, false for the preview
 * @return {string} the modified html or an empty string if nothing should be modified
 */
function noteToMarkdownHtmlHook(note, html, forExport);

与上一钩子互补:它在 Markdown 已转换为 HTML 之后调用,允许修改将要渲染的 HTML,例如注入自定义 CSS、改写标签结构。forExport 语义相同。触发点同样在 HTML 生成流程中(note.cpp)。

源码细节:实现同时兼容旧的二参数签名 noteToMarkdownHtmlHook(note, html)——如果脚本只定义了两个参数,会触发弃用警告并继续工作(scriptingservice.cpp),建议新脚本一律使用三参数签名。返回结果采用链式叠加:每个脚本的输出 HTML 成为下一个脚本的输入。参考示例:example.qml、preview-styling.qml。

波斯文文档附注:如需查看预览支持的全部 CSS 样式能力,可查阅 Qt 富文本所支持的 HTML 子集文档(Rich Text HTML Subset),这决定了你能在预览 HTML 中使用哪些标签与样式。

encryptionHook:自定义加解密算法

/**
 * This function is called when text has to be encrypted or decrypted
 *
 * @param text string the text to encrypt or decrypt
 * @param password string the password
 * @param decrypt bool if false encryption is demanded, if true decryption is demanded
 * @return the encrypted decrypted text
 */
function encryptionHook(text, password, decrypt);

当 QOwnNotes 需要加密或解密文本时调用,允许用任意自定义算法接管加解密过程。参数语义清晰:decrypt=false 表示加密请求,decrypt=true 表示解密请求;返回加解密后的文本。

源码印证:加密与解密两条路径都调用该钩子(note.cpp 加密、note.cpp 解密),实现见 scriptingservice.cpp。

实战示例:官方提供了三种完全不同算法的参考实现——

  • encryption-keybase.qml:调用系统 keybase CLI 加解密。其 init() 中先调用 script.encryptionDisablePassword() 禁用内置密码对话框,再在钩子内用 script.startSynchronousProcess() 同步执行外部程序:
function encryptionHook(text, password, decrypt) {
    // encrypt or decrypt text with keybase.io for user pbek
    var param = decrypt ? ["decrypt"] : ["encrypt", "pbek"];
    var result = script.startSynchronousProcess("/usr/bin/keybase", param, text);
    return result;
}

四、标签机制钩子

noteTaggingHook:接管笔记标签机制

/**
 * Handles note tagging for a note
 *
 * This function is called when tags are added to, removed from or renamed in
 * a note or the tags of a note should be listed
 *
 * @param note
 * @param action can be "add", "remove", "rename" or "list"
 * @param tagName tag name to be added, removed or renamed
 * @param newTagName tag name to be renamed to if action = "rename"
 * @return note text string or string-list of tag names (if action = "list")
 */
function noteTaggingHook(note, action, tagName, newTagName);

这是 QOwnNotes 脚本体系中最强大的钩子之一:一旦某个已激活脚本实现了 noteTaggingHook,笔记的标签机制就整体移交给该函数(文档原文:“as soon as a script is activated that implements the new function noteTaggingHook note tagging will be handled by that function”)。它的典型自定义实现是把标签作为笔记内的特殊文本,例如 @tag1、@tag2、@tag3。

action 支持四个值,对应四类操作:

action 含义 期望返回值
add 给笔记添加标签 修改后的笔记文本(把标签写进正文)
remove 从笔记移除标签 修改后的笔记文本(把标签从正文删除)
rename 重命名标签(newTagName 为目标名) 修改后的笔记文本
list 列出笔记的标签 标签名组成的字符串列表

接管后,以下内置界面功能将经由该函数实现(文档原文逐条列出):

  • 从笔记中初始导入 @tag 形式的标签,并覆盖当前标签分配(不会丢失标签树本身,只丢失原先的笔记分配关系);标签树中同名的多个标签只分配第一个命中项;你仍然可以把标签移动到其他标签之下;
  • 在界面中给笔记添加标签 → 钩子把标签写入笔记文本;
  • 从笔记删除标签 → 钩子把标签从笔记文本移除;
  • 在标签列表中删除标签 → 从所有相关笔记中移除该标签;
  • 在标签列表中重命名标签 → 在相关笔记中同步改名;
  • 在笔记列表中批量打标签 → 为选中的多篇笔记写入标签;
  • 在笔记列表中批量移除标签 → 从选中的多篇笔记移除标签;
  • 在标签面板中移动标签 → 应用会对所有选中的标签及其子标签在所有笔记上触发一系列 add / remove 动作。

性能警告(文档重点):务必让你的 list 动作足够快——因为每次笔记文件夹或标签树重载时,该钩子会对每篇笔记执行一次 list!也就是每次你在 mainwindow.cpp 中看到 reloadTagTree 的地方都会触发。如果 list 实现缓慢,整个界面都会卡顿。

源码印证:标签管理器通过 callNoteTaggingHook() 完成 add/list/rename 等全部操作(tagmanager.cpp),并用 noteTaggingHookExists() 检测是否有脚本接管标签机制(scriptingservice.cpp)。官方参考实现:note-tagging.qml。

noteTaggingByObjectHook:基于 TagApi 对象的标签机制

/**
 * Handles note tagging for a note
 *
 * This function is called when tags are added to, removed from or renamed in
 * a note or the tags of a note should be listed
 *
 * @param note
 * @param action can be "add", "remove", "rename" or "list"
 * @param tag to be added, removed or renamed
 * @param newTagName tag name to be renamed to if action = "rename"
 * @return note text string or string-list of tag ids (if action = "list")
 */
function noteTaggingByObjectHook(note, action, tag, newTagName);

与 noteTaggingHook 机制相同,但有两个关键差异(文档原文明确):

  1. 参数形式:第三个参数不再是标签名字符串,而是 TagApi 对象(对应标签树中的真实节点);
  2. 返回值形式:list 动作返回的不再是标签名列表,而是标签 ID 列表。

由此带来的能力是:你不必把标签绑定在“标签树根节点下的扁平名称列表”上,而是可以利用完整的标签树结构(子标签、层级关系)。代价是你需要自行创建缺失的标签,才能为 list 动作提供可用的标签 ID 列表。

源码印证:实现中同时构造 NoteApi 与 TagApi 对象传入脚本(scriptingservice.cpp)。官方参考实现:note-tagging-by-object.qml。

五、编辑器与输入辅助钩子

autocompletionHook:自定义自动补全

/**
 * Calls the autocompletionHook function for all script components
 * This function is called when autocompletion is invoked in a note
 *
 * @return QStringList of text for the autocomplete list
 */
function callAutocompletionHook();

当用户在笔记中触发自动补全(例如按下 Ctrl + 空格)时,脚本可以返回一个字符串列表,追加到自动补全候选列表。

源码细节:callAutocompletionHook() 会聚合所有脚本返回的字符串列表,并按字典序排序后返回(scriptingservice.cpp)——这与“第一个非空者获胜”的文本钩子不同,多个脚本的补全建议是合并的。

实战示例:官方示例 autocompletion.qml 实现了一个非常贴合的玩法——当光标前的单词以 @ 开头时,用 script.searchTagsByName() 搜索标签名作为补全候选:

function autocompletionHook() {
    // get the current word plus non-word-characters before the word to also get the "@"-character
    var word = script.noteTextEditCurrentWord(true);

    if (!word.startsWith("@")) {
        return [];
    }

    // cut the "@" off of the string and do a substring search for tags
    var tags = script.searchTagsByName(word.substr(1));
    return tags;
}

highlightingHook:上下文感知的动态语法高亮

/**
 * This function is called for each text block during syntax highlighting.
 * It allows context-aware, dynamic highlighting.
 *
 * @param text {QString} the text of the current block being highlighted
 * @param previousBlockState {int} the highlighter state of the previous block
 *     (-1 if this is the first block)
 * @return {Array} an array of highlight range objects, each with:
 *     start {int} - start position in the text
 *     length {int} - number of characters to highlight
 *     state {int} - the HighlighterState to use (optional, -1 for custom only)
 *     foregroundColor {string} - foreground color name or hex (optional)
 *     backgroundColor {string} - background color name or hex (optional)
 *     bold {bool} - bold font weight (optional)
 *     italic {bool} - italic font style (optional)
 *     underline {bool} - underline the text (optional)
 *     fontSize {int} - font point size (optional)
 */
function highlightingHook(text, previousBlockState) {
  var highlights = [];

  // Example: highlight all occurrences of "FIXME" with red bold underline
  var re = /FIXME/g;
  var match;
  while ((match = re.exec(text)) !== null) {
    highlights.push({
      start: match.index,
      length: match[0].length,
      foregroundColor: "#ff0000",
      underline: true,
      bold: true,
    });
  }

  return highlights;
}

该钩子在编辑器语法高亮期间对每个文本块调用,允许实现超越静态正则规则的动态、上下文感知高亮。

性能警告(文档重点):该钩子调用非常频繁——每次按键都会对每个可见文本块执行一次!因此实现必须保持轻量快速。文档明确建议:如果只需要静态正则高亮,优先使用 addHighlightingRule(含自定义颜色版本),而不要动用 highlightingHook。

源码印证:QOwnNotesMarkdownHighlighter::highlightScriptingHook() 会在高亮每个文本块时先检测 highlightingHookExists(),再调用 callHighlightingHook(text, baseBlockState(previousBlockState())),随后把返回的高亮区间(start、length、state 及自定义格式)逐一应用到 QTextCharFormat 上(qownnotesmarkdownhighlighter.cpp),实现见 scriptingservice.cpp。返回区间中 length <= 0 的项会被跳过。

参考示例:highlighting.qml 与 custom-highlighting.qml。其中 highlighting.qml 同时演示了静态 addHighlightingRule(如 ^BLOCK: (.+) 匹配块引用状态、带自定义颜色格式的 IMPORTANT 高亮)与动态 highlightingHook 两种方案的取舍。

六、进程、窗口、布局与 AI 集成钩子

onDetachedProcessCallback:后台进程完成回调

该钩子与脚本 API 中的 startDetachedProcess(后台启动外部程序)配套使用:当脚本启动的后台进程执行完成时被调用:

/**
 * This function is called when a script thread is done executing.
 * Hint: thread[1]==0 helps to determine if a bulk of started processes for a certain identifier is done.
 *
 * @param {QString} callbackIdentifier - the provided id when calling startDetachedProcess()
 * @param {QString} resultSet - the result of the process
 * @param {QVariantList} cmd - the entire command array [0-executablePath, 1-parameters, 2-exitCode]
 * @param {QVariantList} thread - the thread information array [0-passed callbackParameter, 1-remaining threads for this identifier]
 */
function onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread);

四个参数分别携带:启动时提供的回调标识符、进程输出结果、完整命令数组(可执行路径 / 参数列表 / 退出码)、线程信息数组(传入的回调参数 / 该标识符下剩余未完成的线程数)。文档给出的提示:当 thread[1]==0 时,意味着某一标识符下成批启动的进程已全部完成——非常适合做批量任务的收尾逻辑。

源码印证:startDetachedProcess() 在提供 callbackIdentifier 时创建 ScriptThread 线程执行(scriptingservice.cpp);线程结束后 onScriptThreadDone() 把 cmdList(可执行路径、参数、退出码)与 threadList(线程索引、剩余计数)组装后回调(scriptingservice.cpp)。官方示例:callback.qml。

windowStateChangedHook:窗口状态变化

/**
 * This function is called after a WindowStateChange event was triggered
 *
 * @param {QString} windowState - the new window state, parameter value can be "minimized", "maximized", "fullscreen", "active" or "nostate"
 */
function windowStateChangedHook(windowState);

在主窗口状态变化事件发生后调用,windowState 可取 minimized、maximized、fullscreen、active、nostate 五种值。触发点在 mainwindow.cpp(callWindowStateChangeHook(windowStateString)),实现见 scriptingservice.cpp。官方示例:window-state-changed.qml。

layoutSwitchedHook:布局切换

/**
 * This function is called when layouts are switched
 *
 * @param oldUuid old uuid of layout
 * @param newUuid new uuid of layout
 */
function layoutSwitchedHook(oldUuid, newUuid);

当界面布局切换时调用,携带旧布局与新布局的 UUID。触发点位于布局管理器(layoutmanager.cpp),实现见 scriptingservice.cpp。源码还保留了旧的 workspaceSwitchedHook 兼容路径(已标记弃用,见 scriptingservice.cpp)。官方示例:layouts.qml。

websocketRawDataHook:浏览器扩展原始数据

/**
 * @param requestType can be "page" or "selection"
 * @param pageUrl the url of the webpage where the request was made
 * @param pageTitle the page title of the webpage where the request was made
 * @param rawData the data that was transmitted, html for requestType "page" or plain text for requestType "selection"
 * @param screenshotDataUrl the data url of the screenshot of the webpage where the request was made
 * @return true if data was handled by a hook
 */
function callHandleWebsocketRawDataHook(requestType, pageUrl, pageTitle, rawData, screenshotDataUrl);

该钩子当数据从 QOwnNotes Web Companion 浏览器扩展(通过浏览器右键菜单)发送过来时被调用:

  • requestType:"page"(发送整页 HTML)或 "selection"(发送选中文本);
  • rawData:随 requestType 变化,page 时为 HTML,selection 时为纯文本;
  • screenshotDataUrl:页面截图的 Data URL;
  • 返回 true 表示数据已由钩子处理,QOwnNotes 将不再创建新笔记。

源码印证:在 WebSocket 服务处理浏览器请求时,若客户端请求原始数据处理,则调用该钩子;返回 true 时跳过默认的“新建笔记”流程(websocketserverservice.cpp),实现见 scriptingservice.cpp。官方示例:layouts.qml 与 websocket-raw-data-selection-in-note.qml(后者演示如何把选中文本整理进当前笔记)。

openAiBackendsHook:自定义 OpenAI 兼容后端

/**
 * This function is called when the OpenAI service config is reloaded
 * It returns a list of objects with config parameters for new OpenAI backends
 */
function openAiBackendsHook() {
  return [
    {
      id: "my-custom-ai",
      name: "My Custom AI",
      baseUrl: "http://localhost:5000",
      apiKey: "kDFJkjk3asdm",
      models: ["gpt-3.5-turbo", "gpt-4.0-turbo"],
    },
    {
      id: "my-custom-ai2",
      name: "My Custom AI 2",
      baseUrl: "http://localhost:5001",
      apiKey: "lOikf7eNdb9",
      models: ["gpt-3.5-turbo2", "gpt-4.0-turbo2"],
    },
  ];
}

该钩子在 OpenAI 服务配置重新加载时被调用(例如脚本引擎重新加载时也会触发),用于为自定义 OpenAI 兼容后端提供配置——比如自建的 OpenAI API 兼容 LLM、ChatGPT、Claude,或 Ollama 这类本地推理系统。

返回值结构:一个对象数组,每个对象包含 id(后端标识)、name(显示名称)、baseUrl(API 地址)、apiKey(密钥)与 models(可用模型列表)五个字段。

实用技巧(文档 Tip):可以配合 Registering script settings variables(注册脚本设置变量)把后端配置存入脚本设置,避免把 API Key 硬编码在脚本里。

源码印证:callOpenAiBackendsHook() 会把每个脚本返回的对象转换为 QVariantMap 并聚合成列表(scriptingservice.cpp);OpenAI 服务初始化时消费该列表(openaiservice.cpp)。官方示例:custom-openai-backends.qml。

钩子选择速查表

钩子 触发时机 关键参数 返回值语义
onNoteStored(note) 笔记写入磁盘后(信号槽机制) NoteApi 无(禁止修改笔记)
noteOpenedHook(note) 笔记打开后 NoteApi 无
noteDoubleClickedHook(note) 笔记被双击 NoteApi 无(源码返回 bool 表示是否处理)
handleNewNoteHeadlineHook(headline) 新笔记创建前 标题字符串 新标题;需自保唯一性
handleNoteTextFileNameHook(note) 存储时(需开启“允许文件名≠标题”设置) NoteApi 新文件名(不含扩展名);需自保唯一
handleNoteNameHook(note) 确定显示名称时 NoteApi 新显示名称
insertMediaHook(fileName, markdownText) 媒体插入时 源路径 + 待插入 Markdown 新 Markdown(首个非空者胜)
insertAttachmentHook(fileName, markdownText) 附件插入时 源路径 + 待插入 Markdown 新 Markdown(首个非空者胜)
insertingFromMimeDataHook(text, html) Ctrl+Shift+V 粘贴时 剪贴板文本 + HTML 替换粘贴的字符串
fetchUrlTitleHook(url) 链接对话框抓取标题前 URL 标题(空则走默认抓取)
preNoteToMarkdownHtmlHook(note, markdown, forExport) Markdown→HTML 转换前 Markdown 文本 修改后的 Markdown(链式)
noteToMarkdownHtmlHook(note, html, forExport) Markdown→HTML 转换后 HTML 文本 修改后的 HTML(链式)
encryptionHook(text, password, decrypt) 加解密时 文本 + 密码 + 方向 加解密结果
noteTaggingHook(note, action, tagName, newTagName) 标签 add/remove/rename/list 动作 + 标签名 笔记文本或标签名列表
noteTaggingByObjectHook(note, action, tag, newTagName) 同上(对象版) 动作 + TagApi 笔记文本或标签 ID 列表
autocompletionHook() 自动补全触发(Ctrl+空格) 无 字符串列表(多脚本合并、排序)
highlightingHook(text, previousBlockState) 每个文本块高亮时(调用极频繁) 块文本 + 上一块状态 高亮区间对象数组
onDetachedProcessCallback(id, result, cmd, thread) 后台进程完成时 标识符 + 结果 + 命令 + 线程信息 无
windowStateChangedHook(windowState) 窗口状态变化后 状态字符串 无
layoutSwitchedHook(oldUuid, newUuid) 布局切换时 新旧 UUID 无
websocketRawDataHook(requestType, ...) 浏览器扩展发送数据时 类型 + URL + 标题 + 数据 + 截图 true = 已处理
openAiBackendsHook() OpenAI 配置重载时 无 后端配置对象数组

性能与设计建议

综合文档警告与源码实现,编写钩子时应注意以下几点:

  1. 高频钩子务必轻量:highlightingHook 每次按键都会对每个可见文本块执行,noteTaggingHook 的 list 动作在每次笔记文件夹/标签树重载时对每篇笔记执行(对应 mainwindow.cpp 中的每次 reloadTagTree)。这两类钩子内部不应有磁盘 IO、网络请求或重计算;
  2. 能静态就静态:如果高亮需求可以用正则表达,优先用 script.addHighlightingRule()(含自定义颜色版本,见 scriptingservice.cpp),而不是 highlightingHook;
  3. 返回约定要遵守:文本类钩子返回空串 = 不接管;websocketRawDataHook 返回 true = 已处理;多个脚本共存时记住“第一个非空者获胜”或“链式叠加”的差异;
  4. 唯一性责任自负:handleNoteTextFileNameHook 与 handleNewNoteHeadlineHook 都不会替你保证名称唯一,需自行用 script.noteExistsByFileName() 等 API 检查;
  5. 版本兼容:preNoteToMarkdownHtmlHook / noteToMarkdownHtmlHook 的旧二参数签名仍被兼容但已弃用(源码会打印警告),新脚本应使用带 forExport 的三参数签名;workspaceSwitchedHook 已由 layoutSwitchedHook 取代。

延伸阅读

登录后查看全文
QOwnNotes