QOwnNotes 脚本开发实战指南:QML/JavaScript 扩展机制与 API 详解

原创2026-10-14 05:59:511,463 阅读
文章标签:桌面应用知识管理富文本插件系统跨平台

QOwnNotes 脚本开发实战指南:QML/JavaScript 扩展机制与 API 详解

QOwnNotes 是一款支持 Markdown、Nextcloud/ownCloud 集成的纯文本笔记与待办事项管理工具,而它最具可玩性的能力在于脚本系统:你可以用几乎人人都熟悉的 JavaScript,配合 Qt 的 QML 文件格式,为编辑器、标签、预览、快捷键乃至 WebSocket 服务注入自定义行为。本文以官方脚本入门文档为核心,结合仓库内 src/services/scriptingservice.cpp 等源码实现,系统讲解脚本的加载原理、暴露对象、方法速查、事件钩子与完整实战示例,读完即可动手写出第一个 QOwnNotes 扩展脚本。

QOwnNotes QML 脚本相关界面截图

一、脚本的本质:QML 容器中的 JavaScript

QOwnNotes 脚本的绝大部分内容就是 JavaScript,只是被放置在 Qt QML 文件(扩展名为 .qml)中,以声明式的结构组织。一个最小的脚本如下:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    /**
     * Will be run when the scripting engine initializes
     */
    function init() {
        script.log("Hello world!");
    }
}

要点解析:

  • import QtQml 2.0:引入 QML 基础模块,提供 Qt 全局对象(如日期格式化、createQmlObject 等能力)。
  • import QOwnNotesTypes 1.0:引入 QOwnNotes 自定义类型模块。从源码 src/services/scriptingservice.cpp 可以看到该模块通过 qmlRegisterType 注册了 Note、NoteSubFolder、Tag、Script 四种类型,因此脚本内可以直接使用这些类型。
  • Script { ... }:脚本根对象。init() 是脚本引擎初始化时被调用的入口函数(源码中 initComponent() 会检测并调用 init(),见 src/services/scriptingservice.cpp)。
  • script.log():向日志面板输出文本。脚本运行期,script 对象作为上下文属性注入 QML 引擎(见 src/services/scriptingservice.cpp),它代理了 ScriptingService 的大量方法;同理 mainWindow 对象也被注入,用于访问主窗口操作(src/services/scriptingservice.cpp)。

如何添加脚本

你可以把 .qml 文件放在磁盘上的任意位置,然后在 脚本设置(Scripting settings) 中通过 Add script(添加脚本) 或 Add local script(添加本地脚本) 按钮将其加入 QOwnNotes。脚本加载时,引擎还会自动把脚本所在目录写入 scriptDirPath 属性,方便脚本加载同目录的其他资源(详见后文)。

日志面板(Log panel)

调试脚本时最常用的输出通道是 script.log(),其输出会显示在 日志面板中。日志面板可以通过菜单 窗口 / 面板(Window / Panels) 打开。日志内容在提交 Issue 时也很有用——仓库中的问题助手对话框会自动收集日志面板的输出来辅助排错(见 src/dialogs/issueassistantdialog.cpp)。

二、脚本的获取与安装:示例脚本与脚本仓库

  • 官方示例脚本:仓库 docs/scripting/examples 目录下提供了数十个可立即运行的示例,涵盖自定义动作、自动补全、AI 后端、加密、标签、WebSocket 等场景,是快速上手的最佳起点。
  • 脚本仓库(Script repository):在脚本设置中可以直接从脚本仓库安装脚本(对应源码实现见 src/dialogs/scriptrepositorydialog.cpp,其会拉取脚本元数据、下载脚本文件及其附带资源)。社区还提供了用于搜索脚本的网页应用。
  • 问题与贡献:脚本仓库中的脚本若存在问题、疑问或功能请求,可在脚本仓库的 Issue 页面提出;若想把自己写的脚本贡献进仓库,可遵循脚本仓库的提交说明。如果需要对 QOwnNotes 本身新增某个脚本可访问的功能,可在 QOwnNotes 的 Issue 页面提出。

三、脚本加载机制:从 QML 文件到运行对象

理解脚本引擎的加载过程有助于排查“脚本没生效”的问题。在 src/services/scriptingservice.cpp 的 initComponent() 中,加载流程如下:

  1. 读取脚本路径,通过 QQmlComponent 加载 QML 文件;
  2. component->create() 创建脚本对象,若组件就绪且无错误则登记到 _scriptComponents;
  3. 设置 scriptDirPath 属性为脚本所在目录(转为原生路径分隔符);
  4. 注册脚本的 settingsVariables 设置项;
  5. 若存在 init() 函数,则调用之;
  6. 若存在 onNoteStored(QVariant) 函数,则连接到笔记保存信号。

加载失败时,组件错误会输出到日志(qWarning() << "script errors:"),因此脚本加载失败通常会在日志中留下具体报错信息,务必善用日志面板。

四、暴露给脚本的核心对象

1. Note(笔记对象)

NoteApi 的完整属性与方法定义见 src/api/noteapi.h,脚本中可通过 script.currentNote() 等获取。

属性:

属性 含义
id 笔记在数据库中的 id
name 笔记名称
fileName 笔记文件名(含扩展名)
fullNoteFilePath 笔记文件的绝对路径
fullNoteFileDirPath 笔记所在目录的绝对路径
relativeNoteFileDirPath 笔记所在目录相对于笔记文件夹的路径
noteSubFolderId 笔记所属子文件夹 id
noteText 笔记正文
decryptedNoteText 解密后的笔记正文
hasDirtyData 笔记是否有未保存的改动
tags 笔记的标签列表
fileCreated / fileLastModified 创建时间 / 最后修改时间(QDateTime)

方法: tagNames() 返回标签名列表;addTag(tagName) / removeTag(tagName) 增删标签;renameNoteFile(newName) 重命名笔记文件;toMarkdownHtml(forExport) 将笔记转为 HTML;getFileURLFromFileName(localFileName) 获取本地文件的 URL;allowDifferentFileName() 查询是否允许笔记文件名与标题不同;getNoteUrlForLinkingToNoteId(noteId) 返回用于链接到指定笔记的 Markdown 链接。

示例:

script.log(note.fileCreated.toISOString());
script.log(note.fileLastModified.getFullYear());

// 将笔记重命名为 "new name.md"
note.renameNoteFile("new name");

// 检查是否允许笔记文件名与标题不同
script.log(note.allowDifferentFileName());

fileCreated、fileLastModified 是标准的 JavaScript Date 对象,可直接使用其方法;如需格式化输出,可用 Qt.formatDateTime(见后文“日期格式化”一节)。

2. NoteSubFolder(笔记子文件夹)

属性: id、name、notes(子文件夹内的笔记列表)。

静态方法: fetchNoteSubFolderById(id) 按 id 获取;activeNoteSubFolder() 获取当前活动子文件夹;fetchNoteSubFoldersByParentId(parentId) 按父级 id 获取子文件夹列表。

实例方法: relativePath() 返回相对笔记文件夹的路径;fullPath() 返回绝对路径。

示例:

var noteSubFolderQmlObj = Qt.createQmlObject(
  "import QOwnNotesTypes 1.0; NoteSubFolder{}",
  mainWindow,
  "noteSubFolder",
);

// 打印父级下所有子文件夹名称
noteSubFolderQmlObj
  .fetchNoteSubFoldersByParentId(parentId)
  .forEach(function (nsf) {
    script.log(nsf.name);
  });

// 获取当前活动子文件夹
var noteSubFolder = noteSubFolderQmlObj.activeNoteSubFolder();
script.log(noteSubFolder.fullPath());
script.log(noteSubFolder.relativePath());
script.log(noteSubFolder.id);
script.log(noteSubFolder.name);

// 遍历子文件夹中的笔记
for (var idx in noteSubFolder.notes) {
  var note = noteSubFolder.notes[idx];
}

3. Tag(标签对象)

属性: id、name、parentId、notes(挂在该标签下的笔记)。

方法: fetchByName(name, parentId = 0) 按名称获取标签;getParentTagNames() 返回父级标签名列表。

示例:

// 不要忘记在脚本顶部使用 "import QOwnNotesTypes 1.0"
// 获取标签 "home"
var tag = script.getTagByNameBreadcrumbList(["home"]);
// 获取所有带该标签的笔记
var notes = tag.notes;

// 遍历标签下的笔记
for (var idx in notes) {
  var note = notes[idx];
  script.log(note.name);
}

更完整的按对象打标签示例可参考 note-tagging-by-object.qml。

4. MainWindow(主窗口操作)

mainWindow 暴露了若干界面级操作:

方法 作用
reloadTagTree() 重载标签树
reloadNoteSubFolderTree() 重载笔记子文件夹树
buildNotesIndexAndLoadNoteDirectoryList(forceBuild, forceLoad) 强制重建笔记索引并加载目录列表
focusNoteTextEdit() 聚焦笔记编辑区
createNewNoteSubFolder(folderName) 在当前子文件夹下新建子文件夹
insertHtmlAsMarkdownIntoCurrentNote(html) 把 HTML 以 Markdown 形式插入当前笔记(会自动下载远程图片、转换 data:image URL 为本地媒体目录图片)
reloadCurrentNoteByNoteId() 按 id 重载当前笔记(路径或文件名变更时有用)
getLayoutUuidList() 返回所有布局的 UUID 列表
getLayoutUuid(layoutName) 按布局名获取 UUID
setCurrentLayout(uuid) 按 UUID 切换布局
removeNoteTab(index) 关闭指定索引的笔记标签页(成功返回 true)
getNoteTabNoteIdList() 返回已打开标签页中的笔记 id 列表
jumpToTag(tagId) 跳转到标签树中的指定标签

示例:

// 强制重载笔记列表
mainWindow.buildNotesIndexAndLoadNoteDirectoryList(true, true);

// 在当前子文件夹创建 "My fancy folder"
mainWindow.createNewNoteSubFolder("My fancy folder");

// 将 HTML 以 Markdown 插入当前笔记
mainWindow.insertHtmlAsMarkdownIntoCurrentNote("<h2>my headline</h2>some text");

// 将 'Edit' 布局设为当前布局
mainWindow.setCurrentLayout(mainWindow.getLayoutUuid("Edit"));

// 跳转到标签树中的 "test" 标签
var tag = script.getTagByNameBreadcrumbList(["test"]);
mainWindow.jumpToTag(tag.id);

// 遍历所有已打开标签页中的笔记
var noteIds = mainWindow.getNoteTabNoteIdList();
noteIds.forEach(function (noteId) {
  var note = script.fetchNoteById(noteId);
  // 对笔记做点什么
});

五、方法速查:script 对象提供的能力

以下按功能分类整理 script 对象(即 ScriptingService)提供的方法,全部方法声明可在 src/services/scriptingservice.h 中核对。

1. 外部程序调用

后台启动进程(不阻塞界面):

bool startDetachedProcess(QString executablePath, QStringList parameters,
                          QString callbackIdentifier, QVariant callbackParameter,
                          QByteArray processData, QString workingDirectory);

参数说明:callbackIdentifier 为回调标识,配合 onDetachedProcessCallback() 钩子使用;callbackParameter 可额外传递一个参数(适合循环场景);processData 是写入进程的数据(仅在用到回调时);workingDirectory 指定工作目录(仅在不使用回调时生效)。返回 true 表示启动成功。

// 简单示例:后台运行程序
script.startDetachedProcess("/path/to/my/program", ["my parameter"]);
// 批量启动多个进程,并利用回调收集结果
for (var i = 0; i < 100; i++) {
  var dur = Math.floor(Math.random() * 10) + 1;
  script.startDetachedProcess("sleep", [`${dur}s`], "my-callback", i);
}

function onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread) {
  if (callbackIdentifier == "my-callback") {
    script.log(`#${thread[1]} i[${thread[0]}] t${cmd[1]}`);
  }
}

相关示例:custom-actions.qml、callback.qml、execute-command-after-note-update.qml。

同步启动进程并等待输出:

QByteArray startSynchronousProcess(QString executablePath, QStringList parameters,
                                   QByteArray data, QString workingDirectory);
var result = script.startSynchronousProcess(
  "/path/to/my/program",
  ["my parameter"],
  "data",
  "/path/to/execute/in",
);

同步调用会阻塞直到进程结束并返回其输出文本,适合需要拿到结果的场景(例如 encryption-keybase.qml 调用外部程序做加解密)。

2. 笔记与文件夹

方法 说明
currentNoteFolderPath() 当前笔记文件夹的路径
currentNote() 当前笔记对象(NoteApi)
fetchNoteByFileName(fileName, noteSubFolderId) 按文件名获取笔记(noteSubFolderId 可省略,省略时在全部子文件夹中查找)
fetchNoteById(id) 按 id 获取笔记
noteExistsByFileName(fileName, ignoreNoteId, noteSubFolderId) 按文件名检查笔记是否存在,ignoreNoteId 用于排除某条笔记自身
setCurrentNote(note, asTab = false) 跳转到指定笔记,asTab=true 时在新标签页打开
jumpToNoteSubFolder(path, separator = "/") 跳转到相对路径的子文件夹
createNote(text) 新建一条笔记
tagCurrentNote(tagName) 给当前笔记打标签
getTagByNameBreadcrumbList(nameList, createMissing = true) 按标签名面包屑路径获取/创建标签,如 ["level1","level2","level3"] 表示树中的 level1 > level2 > level3
searchTagsByName(name, ignoreAccents = false) 按名称子串搜索标签,返回标签名列表
fetchNoteIdsByNoteTextPart(text, ignoreAccents = false) 按正文文本搜索,返回匹配笔记的 id 列表
var path = script.currentNoteFolderPath();

// 创建新笔记
script.createNote("My note headline\n===\n\nMy text");

// 若设置了“文件名不跟随标题”,需手动重命名文件
var note = script.currentNote();
note.renameNoteFile("your-filename");

// 按文本搜索笔记
var noteIds = script.fetchNoteIdsByNoteTextPart("mytext");
// 忽略变音符(可同时匹配 "Avión" 与 "avion")
var accentInsensitiveNoteIds = script.fetchNoteIdsByNoteTextPart("avion", true);
noteIds.forEach(function (noteId) {
  var note = script.fetchNoteById(noteId);
});

相关示例:journal-entry.qml、unique-note-id.qml。

3. 编辑器文本操作

这一组方法围绕当前笔记的编辑器选区与光标展开,是编写“文本处理类脚本”的基础:

方法 说明
noteTextEditWrite(text) 在当前光标位置写入文本
noteTextEditSelectedText() 读取当前选中的文本
noteTextEditSelectAll() 全选文本
noteTextEditSelectCurrentLine() 选中当前行
noteTextEditSelectCurrentWord() 选中当前词
noteTextEditSetSelection(start, end) 将选区设为指定范围
noteTextEditSelectionStart() / noteTextEditSelectionEnd() 选区起止位置
noteTextEditSetCursorPosition(position) 将光标移到指定位置(0 为开头,-1 为末尾)
noteTextEditCursorPosition() 当前光标位置
noteTextEditCurrentWord(withPreviousCharacters = false) 读取光标处的词(withPreviousCharacters=true 可把 @ 等非词字符也纳入)
noteTextEditCurrentBlock() 读取当前文本块
// 写入文本
script.noteTextEditWrite("My custom text");

// 读取选区
var text = script.noteTextEditSelectedText();

// 选区向外扩展一个字符
script.noteTextEditSetSelection(
  script.noteTextEditSelectionStart() - 1,
  script.noteTextEditSelectionEnd() + 1,
);

// 跳到笔记末尾
script.noteTextEditSetCursorPosition(-1);

// 读取当前词
var word = script.noteTextEditCurrentWord();

用 noteTextEditSelectAll() 配合 noteTextEditWrite() 即可整体覆盖当前笔记内容。相关示例:autocompletion.qml、ai-autocompletion.qml。

4. 剪贴板

var clipboardText = script.clipboard();      // 读取纯文本
var clipboardHtml = script.clipboard(true);  // 读取 HTML
script.setClipboardText("text to copy");     // 写入纯文本
script.setClipboardText("<b>html</b>", true); // 写入 HTML mime 数据

相关示例:selected-markdown-to-bbcode.qml。

5. 网络、媒体与附件

方法 说明
downloadUrlToString(url) 下载 URL 内容并作为字符串返回
downloadUrlToMedia(url, returnUrlOnly = false) 下载 URL 到媒体目录,默认返回相对当前笔记的 Markdown 图片文本,returnUrlOnly=true 时只返回媒体 URL
insertMediaFile(mediaFilePath, returnUrlOnly = false) 把本地媒体文件插入媒体目录并返回 Markdown 或 URL
insertAttachmentFile(attachmentFilePath, fileName, returnUrlOnly = false) 把附件文件插入 attachments 文件夹并返回 Markdown 或 URL
regenerateNotePreview() 重新生成笔记预览
var html = script.downloadUrlToString("https://www.qownnotes.org");

var markdown = script.downloadUrlToMedia(
  "http://latex.codecogs.com/gif.latex?\frac{1}{1+sin(x)}",
);

var markdown = script.insertMediaFile("/path/to/your/image.png");
var markdown = script.insertAttachmentFile("/path/to/your/file.png");

script.regenerateNotePreview();

相关示例:paste-latex-image.qml、scribble.qml、insert-headline-with-link-from-github-url.qml。

6. 自定义动作(Custom Actions)

registerCustomAction 是扩展菜单与工具栏的核心能力:

void registerCustomAction(QString identifier,   // 动作标识符
                          QString menuText,     // 菜单中显示的文本
                          QString buttonText,   // 按钮文本(为空则不显示按钮)
                          QString icon,         // 图标:文件路径或 freedesktop 主题图标名
                          bool useInNoteEditContextMenu,   // 是否出现在笔记编辑右键菜单(默认 false)
                          bool hideButtonInToolbar,        // 是否在自定义动作工具栏隐藏按钮(默认 false)
                          bool useInNoteListContextMenu); // 是否出现在笔记列表右键菜单(默认 false)

完整示例:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    function init() {
        // 只有菜单项,没有按钮
        script.registerCustomAction("mycustomaction1", "Menu text");

        // 菜单项 + 按钮
        script.registerCustomAction("mycustomaction2", "Menu text", "Button text");

        // 菜单项 + 按钮 + freedesktop 主题图标
        script.registerCustomAction("mycustomaction3", "Menu text", "Button text", "task-new");

        // 菜单项 + 按钮 + 文件图标
        script.registerCustomAction("mycustomaction4", "Menu text", "Button text", "/usr/share/icons/breeze/actions/24/view-calendar-tasks.svg");
    }

    /**
     * 自定义动作被触发时调用
     */
    function customActionInvoked(identifier) {
        switch (identifier) {
            case "mycustomaction1":
                script.log("Action 1");
            break;
            case "mycustomaction2":
                script.log("Action 2");
            break;
            case "mycustomaction3":
                script.log("Action 3");
            break;
            case "mycustomaction4":
                script.log("Action 4");
            break;
        }
    }
}

注意事项:

  • 自定义动作还可以在 快捷键设置(Shortcuts settings) 中绑定本地与全局快捷键;
  • freedesktop 主题图标在 Linux 下才基本可用,macOS 或 Windows 上若想显示图标,需要在脚本中自带图标文件;
  • 获取图标文件路径时可利用 scriptDirPath 属性(见后文);
  • 可以用命令行参数 --action customAction_<identifier> 在应用启动后触发某个自定义动作。

完整范例见 custom-actions.qml。

7. 标签(Label)与样式

registerLabel(identifier, text) 注册一个脚本标签(显示在 脚本面板 中,需在 窗口 / 面板 菜单启用);setLabelText(identifier, text) 更新标签内容。标签支持纯文本或 HTML,文字可选中、链接可点击。标签文本中的链接还支持笔记、任务、卡片等内部链接(链接处理逻辑可参考 src/utils/urlhandler.cpp)。

script.registerLabel(
  "html-label",
  "<strong>Strong</strong> HTML text<br />with three lines<br />and a <a href='https://www.qownnotes.org'>link to a website</a>.",
);

script.registerLabel("counter-label");
script.setLabelText("counter-label", "counter text");

相关示例:scripting-label-demo.qml。

addStyleSheet(stylesheet) 可向应用注入自定义 QSS 样式:

// 放大笔记列表中的文字
script.addStyleSheet("QTreeWidget#noteTreeWidget {font-size: 30px;}");

组件名可从 *.ui 文件获取(如主窗口布局 src/mainwindow.ui);几乎所有控件的基类都是 QWidget,因此 QWidget {background-color: black; color: white;} 会把全局变成黑底白字。仓库内置的 src/libraries/qdarkstyle/style.qss 也是很好的样式参考。若要修改 HTML 预览的样式,应使用 noteToMarkdownHtmlHook 钩子。

8. 菜单动作与颜色模式

triggerMenuAction(objectName, checked) 可以触发主窗口菜单动作。objectName 可从 src/mainwindow.ui 中按英文菜单标题找到(注意这些名称可能随版本变化):

// 切换只读模式
script.triggerMenuAction("actionAllow_note_editing");

// 关闭只读模式
script.triggerMenuAction("actionAllow_note_editing", 1);

相关示例:disable-readonly-mode.qml。

颜色模式(Color modes) 在“颜色模式”设置中管理,统一打包了暗色模式、图标主题与编辑器配色方案:

script.getColorModes().forEach(function (mode) {
  script.log(
    mode.name +
      " (" +
      mode.id +
      "), editor color schema: " +
      mode.editorColorSchemaName,
  );
});

// 在内置浅色/深色模式间切换
const isDark = script.getCurrentColorModeId() === "ColorMode-dark";
script.switchToColorMode(isDark ? "ColorMode-light" : "ColorMode-dark");

内置颜色模式的 id 是 ColorMode-light 与 ColorMode-dark;自定义颜色模式会得到形如 ColorMode-3f2a9c1e-... 的生成 id,与设置中填写的名称不同,因此 switchToColorMode() 也接受名称(先按 id 匹配,再按名称精确匹配)。切换颜色模式后,通过 addStyleSheet() 添加的样式会保留。相关示例:toggle-color-mode.qml。

9. 对话框与交互

方法 说明
informationMessageBox(text, title) 信息消息框
questionMessageBox(text, title, buttons, defaultButton) 问题消息框,返回被按下的按钮 id;按钮常量来自 Qt 的 QMessageBox::StandardButton 枚举
getOpenFileName(caption, dir, filter) 打开文件对话框
getSaveFileName(caption, dir, filter) 保存文件对话框
inputDialogGetItem(title, label, items, current = 0, editable = false) 下拉选择输入框
inputDialogGetText(title, label, text) 单行文本输入框
inputDialogGetMultiLineText(title, label, text) 多行文本输入框
textDiffDialog(title, label, text1, text2) 文本差异对话框,text2 是可编辑的一侧
// 问题消息框:显示 Apply 与 Help 两个按钮(0x01000000 | 0x02000000)
var result = script.questionMessageBox(
  "The text I want to show",
  "Some optional title",
  0x01000000 | 0x02000000,
  0x02000000,
);

// 打开文件对话框
var fileName = script.getOpenFileName(
  "Please select an image",
  "/home/user/images",
  "Images (*.png *.xpm *.jpg)",
);

// 下拉选择,点击 Cancel 或按 Esc 返回空字符串
var result = script.inputDialogGetItem("combo box", "Please select an item", [
  "Item 1",
  "Item 2",
  "Item 3",
]);

相关示例:input-dialogs.qml、export-notes-as-one-html.qml。

10. 文件与缓存操作

方法 说明
fileExists(filePath) 检查文件是否存在
readFromFile(filePath, codec = "UTF-8") 按指定编码读取文本文件
writeToFile(filePath, data, createParentDirs = false) 写入文本到文件,可选自动创建父目录
cacheDir(subDir) 在系统默认缓存位置为脚本创建缓存目录,返回路径
clearCacheDir(subDir) 清空脚本缓存目录
selectedNotesPaths() 所有选中笔记的路径列表
selectedNotesIds() 所有选中笔记的 id 列表
if (script.fileExists(filePath)) {
  var data = script.readFromFile(filePath);
  script.log(data);
}

var result = script.writeToFile(filePath, html);

var cacheDirForScript = script.cacheDir("my-script-id");
script.clearCacheDir("my-script-id");

11. 脚本目录与路径工具

property string scriptDirPath; 是引擎自动填充的脚本所在目录(加载时由 src/services/scriptingservice.cpp 写入),可用于加载同目录资源或定位图标:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    // 脚本所在目录的路径会被自动设置到这里
    property string scriptDirPath;

    function init() {
        script.log(scriptDirPath);
    }
}

路径工具方法:toNativeDirSeparators(path) 把 / 转为平台原生分隔符(Windows 上 "c:/winnt/system32" → "c:\winnt\system32");fromNativeDirSeparators(path) 反向转换;dirSeparator() 返回平台分隔符(Windows 为 \,其他为 /)。

12. 配置与持久化变量

脚本设置变量(settingsVariables):在脚本中把需要用户配置的项声明为属性,并在 settingsVariables 数组中注册,用户即可在脚本设置界面中修改:

property string myString;
property string myStringSecret;
property bool myBoolean;
property string myText;
property int myInt;
property string myFile;
property string myDirectory;
property string mySelection;

property variant settingsVariables: [
    {
        "identifier": "myString",
        "name": "I am a line edit",
        "description": "Please enter a valid string:",
        "type": "string",
        "default": "My default value",
    },
    {
        "identifier": "myStringSecret",
        "name": "I am a password field",
        "description": "Please enter a valid string:",
        "type": "string-secret",
    },
    {
        "identifier": "myBoolean",
        "name": "I am a checkbox",
        "description": "Some description",
        "text": "Check this checkbox",
        "type": "boolean",
        "default": true,
    },
    {
        "identifier": "myText",
        "name": "I am textbox",
        "description": "Please enter your text:",
        "type": "text",
        "default": "This can be a really long text\nwith multiple lines.",
    },
    {
        "identifier": "myInt",
        "name": "I am a number selector",
        "description": "Please enter a number:",
        "type": "integer",
        "default": 42,
    },
    {
        "identifier": "myFile",
        "name": "I am a file selector",
        "description": "Please select the file:",
        "type": "file",
        "default": "pandoc",
    },
    {
        "identifier": "myDirectory",
        "name": "I am a directory selector",
        "description": "Please select the directory:",
        "type": "directory",
        "default": "/home",
    },
    {
        "identifier": "mySelection",
        "name": "I am an item selector",
        "description": "Please select an item:",
        "type": "selection",
        "default": "option2",
        "items": {"option1": "Text for option 1", "option2": "Text for option 2", "option3": "Text for option 3"},
    }
];

支持的类型包括:string(单行输入)、string-secret(密码输入)、boolean(复选框)、text(多行文本)、integer(数字)、file(文件选择)、directory(目录选择)、selection(下拉选择,通过 items 提供选项映射)。此外还可以用 registerSettingsVariables() 函数以代码方式覆盖设置项(例如按平台调整默认值):

function registerSettingsVariables() {
  if (script.platformIsWindows()) {
    settingsVariables[3].default = "pandoc.exe";
  }
}

相关示例:variables.qml。

持久化变量(Persistent Variables):跨脚本全局共享,键名务必使用有意义的命名空间前缀:

script.setPersistentVariable("PersistentVariablesTest/myVar", result);

script.log(
  script.getPersistentVariable(
    "PersistentVariablesTest/myVar",
    "nothing here yet",
  ),
);

应用设置变量:getApplicationSettingsVariable(key, defaultValue) 可读取 QOwnNotes 应用自身的设置项(注意设置值可能为空字符串,defaultValue 仅在设置完全不存在时生效):

script.log(script.getApplicationSettingsVariable("gitExecutablePath"));

13. AI 补全与平台判断

aiComplete(prompt) 对当前选定的 AI 模型(如 ChatGPT、Claude 或 Ollama 等系统)发起补全请求,返回补全结果。使用前需要在 AI 工具栏或主菜单中启用 AI 系统:

var text = script.aiComplete("Tell me how do you feel today?");

相关示例:ai-autocompletion.qml。

平台判断方法 platformIsLinux()、platformIsOSX()、platformIsWindows() 可用于编写跨平台脚本:

if (script.platformIsLinux()) {
  // 仅在 Linux 下执行
}

14. 日期与时间格式化

无需手写格式化函数,QML 引擎自带 Qt.formatDateTime(date, format)、Qt.formatDate(date, format)、Qt.formatTime(date, format)。常用占位符:

占位符 含义 示例
yyyy / yy 四位 / 两位年份 2026 / 26
MM / M 带前导零 / 不带前导零的月份 09 / 9
MMM / MMMM 缩写 / 完整本地化月份名 Sep / September
dd / d 带前导零 / 不带前导零的日期 05 / 5
ddd / dddd 缩写 / 完整本地化星期名 Tue / Tuesday
HH / hh 24 小时制 / 12 小时制小时 07
mm 分钟 04
ss 秒 09
AP / ap 上午 / 下午 AM

注意占位符区分大小写:yyyy 是年份、MM 是月份、mm 才是分钟;YYYY、DD 这类其他日期库的写法不支持;单引号内的文字不会被解释为占位符。

var date = new Date();
script.log(Qt.formatDateTime(date, "yyyy-MM-dd"));
script.log(Qt.formatDateTime(date, "yyyyMMdd"));
script.log(Qt.formatDateTime(date, "dddd, d. MMMM yyyy 'at' HH:mm"));

// 用当前年月给笔记打标签,如 "2026-09"
script.tagCurrentNote(Qt.formatDateTime(date, "yyyy-MM"));

// 也可以格式化笔记自身的时间属性
var note = script.currentNote();
script.log(Qt.formatDateTime(note.fileLastModified, "yyyy-MM-dd HH:mm:ss"));

相关示例:journal-entry.qml。

15. 编辑器语法高亮规则

addHighlightingRule(pattern, shouldContain, state, capturingGroup = 0, maskedGroup = 0) 直接向编辑器语法高亮器注入正则规则。pattern 为正则表达式;shouldContain 是必须出现在被高亮文本中的字符串;state 指定高亮状态;capturingGroup 指定用于高亮的捕获组;maskedGroup 指定用于掩蔽的捕获组(-1 表示不做掩蔽)。

高亮状态编号表:

名称 编号 名称 编号
NoState -1 BlockQuote 18
Link 0 HorizontalRule 21
Image 3 Table 22
CodeBlock 4 InlineCodeBlock 23
CodeBlockComment 5 MaskedSyntax 24
Italic 7 CurrentLineBackgroundColor 25
Bold 8 BrokenLink 26
List 9 FrontmatterBlock 27
Comment 11 TrailingSpace 28
H1 12 CheckBoxUnChecked 29
H2 13 CheckBoxChecked 30
H3 14 StUnderline 31
H4 15 WikiLink 32
H5 16 WikiLinkBroken 33
H6 17 LinkInternal 34
Whitespace 35
// 把形如 "BLOCK: some text" 的行高亮为引用块(状态 18)
script.addHighlightingRule("^BLOCK: (.+)", "BLOCK:", 18);

// 掩蔽一行 32 字符之后的所有字符(状态 24)
// capturingGroup 1:使用第一个括号捕获组进行高亮
// maskedGroup -1:不做掩蔽
script.addHighlightingRule("^.{32}(.+)", "", 24, 1, -1);

自定义颜色与字样的高亮规则: 重载的 addHighlightingRule(pattern, shouldContain, state, capturingGroup, maskedGroup, formatStyle) 允许直接指定前景色、背景色与字体样式,formatStyle 支持 foregroundColor、backgroundColor、bold、italic、underline、fontSize 键;state 传 -1(NoState)可只使用自定义格式:

function init() {
  // 将 "IMPORTANT" 高亮为黄底红字加粗
  script.addHighlightingRule("IMPORTANT", "IMPORTANT", -1, 0, 0, {
    foregroundColor: "#ff0000",
    backgroundColor: "#ffff00",
    bold: true,
  });

  // 将 "@username" 高亮为蓝色下划线
  script.addHighlightingRule("@\\w+", "@", -1, 0, 0, {
    foregroundColor: "#3366cc",
    underline: true,
  });

  // 将 "NOTE:" 高亮为绿色斜体
  script.addHighlightingRule("NOTE:", "NOTE:", -1, 0, 0, {
    foregroundColor: "#00aa00",
    italic: true,
  });
}

相关示例:highlighting.qml、custom-highlighting.qml。

16. 其他工具方法

  • reloadScriptingEngine():重载脚本引擎,用于脚本热更新。
  • WebSocket:可以通过 WebSocketServer 远程控制 QOwnNotes(参见 websocket-server.qml,可连接 ws://127.0.0.1:35345 测试),也可以通过 WebSocket 作为客户端连接其他服务(参见 websocket-client.qml)。注意使用 WebSocket 需要安装 Qt 的 QML websocket 库,例如 Ubuntu 下安装 qml-module-qtwebsockets。

六、事件钩子(Hooks):在生命周期节点接管行为

钩子是脚本在特定事件点被回调的函数。多数钩子通过“返回非空字符串即生效”的约定工作;若多个脚本定义了同一钩子,通常第一个返回非空结果的脚本生效。完整清单见 hooks.md。

1. 笔记生命周期钩子

钩子 触发时机 签名
onNoteStored(note) 笔记保存到磁盘后。不可修改已保存的笔记(你可能同时在手工编辑它) (NoteApi note)
noteOpenedHook(note) 笔记打开之后 (NoteApi note)
noteDoubleClickedHook(note) 笔记被双击之后 (NoteApi note)
handleNoteNameHook(note) 确定笔记显示名称时(主要用于列表显示);返回空串表示不修改 (NoteApi note) → string
handleNoteTextFileNameHook(note) 启用“允许文件名与标题不同”设置时,保存笔记时确定文件名;需自行处理重名问题;返回空串表示不修改 (NoteApi note) → string
handleNewNoteHeadlineHook(headline) 创建新笔记前,可修改标题(注意标题必须唯一,否则新笔记不会被创建而只是在列表中找到);可用于实现笔记模板 (string headline) → string
function onNoteStored(note) {
  // 笔记保存到磁盘后被调用
}

function handleNewNoteHeadlineHook(headline) {
  // 返回模板化的标题
  return "Template: " + headline;
}

相关示例:on-note-opened.qml、external-note-open.qml、custom-new-note-headline.qml、use-tag-names-in-filename.qml。

2. 预览与 HTML 生成钩子

钩子 触发时机 签名
preNoteToMarkdownHtmlHook(note, markdown, forExport) Markdown 转 HTML 之前,可修改传给转换器的 Markdown(例如把 LaTeX、mermaid 代码渲染成预览用图形;不会改动笔记本身) → string(空串表示不修改)
noteToMarkdownHtmlHook(note, html, forExport) Markdown 转 HTML 之后,可修改最终 HTML(例如注入预览样式) → string(空串表示不修改)

forExport 为 true 表示用于导出,false 表示用于预览。HTML 支持样式范围以 Qt 富文本子集为准。相关示例:preview-styling.qml、example.qml。

3. 媒体、附件与粘贴钩子

钩子 触发时机 签名
insertMediaHook(fileName, markdownText) 媒体文件被插入当前笔记时;可改写插入的 Markdown 文本 (string fileName, string markdownText) → string
insertAttachmentHook(fileName, markdownText) 附件文件被插入当前笔记时 (string fileName, string markdownText) → string
fetchUrlTitleHook(url) 链接对话框中 QOwnNotes 获取网页标题之前;返回空串则交给 QOwnNotes 处理 (string url) → string
insertingFromMimeDataHook(text, html) 用 Ctrl + Shift + V 粘贴 HTML 或媒体文件时;返回要插入的替代文本 (string text, string html) → string

相关示例:example.qml、fetch-url-title-with-kanboard-cli.qml、insert-headline-with-link-from-github-url.qml、note-text-from-5pm-mail.qml。

4. 加密钩子

encryptionHook(text, password, decrypt) 在文本需要加密或解密时被调用,decrypt=false 表示加密、true 表示解密。这让脚本可以用任意外部加密方案(Keybase、PGP、甚至 ROT13)替代内置加密:

function encryptionHook(text, password, decrypt) {
  // 返回加密或解密后的文本
  return myCustomEncrypt(text, password, decrypt);
}

相关示例:encryption-keybase.qml、encryption-pgp.qml、encryption-rot13.qml。

5. 标签机制钩子

noteTaggingHook(note, action, tagName, newTagName):一旦有脚本实现了该函数,笔记标签机制就由该函数接管。action 可取 "add"、"remove"、"rename"、"list"。可用它实现“在笔记文本中写 @tag1、@tag2 即视为标签”的自定义打标机制。UI 层面支持的操作包括:从笔记导入 @tag 形式的标签并覆盖当前分配、给笔记添加/移除标签、在标签列表删除/重命名标签、批量打标/去标、在标签面板中移动标签时自动触发一系列 add/remove 动作。

function noteTaggingHook(note, action, tagName, newTagName) {
  if (action === "list") {
    // 返回标签名列表
    return extractTagsFromNoteText(note);
  }
  // add / remove / rename:返回修改后的笔记文本
  return modifyNoteText(note, action, tagName, newTagName);
}

⚠️ 性能警告:list 动作会在每次重载笔记文件夹或标签树时对每条笔记执行(对应源码中 src/mainwindow.cpp 的 reloadTagTree() 调用点),务必让 list 保持极快。

noteTaggingByObjectHook(note, action, tag, newTagName):与上一钩子类似,但参数直接是 TagApi 对象(而非标签名字符串),且 list 动作需返回标签 id 列表,因此可以借助完整的标签树(而不只限于树根下的标签名)。注意:需要自己预先创建缺失的标签,才能为 list 动作提供已存在的标签 id。

相关示例:note-tagging.qml、note-tagging-by-object.qml。

6. 自动补全与动态高亮

autocompletionHook:在编辑器触发自动补全(例如按 Ctrl + Space)时调用,返回要加入补全列表的字符串列表。

function callAutocompletionHook() {
  return ["myword1", "myword2"];
}

相关示例:autocompletion.qml。

highlightingHook(text, previousBlockState):在语法高亮时对每个文本块调用,用于实现超越静态正则的上下文感知高亮。返回高亮区间对象数组,每个对象可含 start、length、state、foregroundColor、backgroundColor、bold、italic、underline、fontSize 字段:

function highlightingHook(text, previousBlockState) {
  var highlights = [];

  // 示例:把所有 "FIXME" 高亮为红色加粗下划线
  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(含自定义颜色版本)。

相关示例:highlighting.qml、custom-highlighting.qml。

7. WebSocket、窗口与布局钩子

钩子 触发时机 签名
websocketRawDataHook(requestType, pageUrl, pageTitle, rawData, screenshotDataUrl) Web Companion 浏览器扩展通过浏览器右键菜单发送数据时;requestType 为 "page" 或 "selection",返回 true 表示数据已被处理 → bool
windowStateChangedHook(windowState) 窗口状态变化后;取值为 "minimized"、"maximized"、"fullscreen"、"active" 或 "nostate" (string)
layoutSwitchedHook(oldUuid, newUuid) 布局切换时 (string, string)
onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread) startDetachedProcess 的脚本线程执行完毕时;cmd 数组为 [0-executablePath, 1-parameters, 2-exitCode],thread 数组为 [0-传入的 callbackParameter, 1-该标识剩余的线程数];thread[1]==0 可判断整批进程是否全部结束 (string, string, list, list)

相关示例:layouts.qml、websocket-raw-data-selection-in-note.qml、callback.qml、window-state-changed.qml。

8. AI 后端钩子

openAiBackendsHook():在 OpenAI 服务配置重载(例如脚本引擎重载)时被调用,用于为自定义的 OpenAI 兼容后端(自建 LLM、ChatGPT、Claude、Ollama 等)提供配置:

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"],
    },
  ];
}

后端配置可用脚本设置变量(settingsVariables)来存储。相关示例:custom-openai-backends.qml。

七、实战:一个完整的自定义动作脚本

下面综合运用前面介绍的 API,实现一个“用外部编辑器打开当前笔记 + 创建会议纪要 + ROT13 转换选区 + 跳转标签”的多功能脚本(源自仓库 custom-actions.qml):

import QtQml 2.0
import QOwnNotesTypes 1.0

QtObject {
    function init() {
        // 创建带按钮的菜单项
        script.registerCustomAction("openWithKWrite", "Open with KWrite", "KWrite");
        script.registerCustomAction("createMeetingNote", "Create meeting note", "Meeting note", "task-new");
        script.registerCustomAction("noButtonAction", "No button here");
        // 在笔记编辑右键菜单中可用
        script.registerCustomAction("transformTextRot13", "Transform selected text with rot13", "rot13", "text-wrap", true);
        script.registerCustomAction("noteSubFolder", "Show active note subfolder information", "Subfolder");
        script.registerCustomAction("setActiveTag", "Set active tag", "Active tag");
    }

    function customActionInvoked(identifier) {
        switch (identifier) {
            case "openWithKWrite":
                var note = script.currentNote();
                var fileName = note.fullNoteFilePath;
                // 后台启动外部程序
                script.startDetachedProcess("kwrite", [fileName]);
                break;

            case "createMeetingNote":
                var date = new Date();
                // 文件名中不允许出现 ":",因此替换掉
                var text = "Meeting note " + date.toISOString().replace(/:/g, ".") + "\n";
                var underline = "";
                for (var i = 0; i < (text.length - 1); i++) {
                    underline += "=";
                }
                text += underline + "\n\n## Important points\n\n\n## Things to remember\n\n";
                // 把剪贴板内容追加进去
                text += script.clipboard();
                script.createNote(text);
                break;

            case "transformTextRot13":
                var text = script.noteTextEditSelectedText();
                text = text.replace(/[a-zA-Z]/g, function(c){
                    return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
                });
                script.noteTextEditWrite(text);
                break;

            case "noteSubFolder":
                var noteSubFolderQmlObj = Qt.createQmlObject("import QOwnNotesTypes 1.0; NoteSubFolder{}", mainWindow, "noteSubFolder");
                var subFolder = noteSubFolderQmlObj.activeNoteSubFolder();
                script.log(subFolder.fullPath());
                script.log(subFolder.relativePath());
                break;

            case "setActiveTag":
                var tag = script.getTagByNameBreadcrumbList(["test"]);
                mainWindow.jumpToTag(tag.id);
                break;
        }
    }
}

这个示例覆盖了:自定义动作注册与分发、startDetachedProcess 调用外部程序、createNote 创建带标题下划线的笔记、clipboard 读取剪贴板、noteTextEditSelectedText/noteTextEditWrite 选区变换、NoteSubFolder 动态创建与查询、getTagByNameBreadcrumbList + jumpToTag 跳转标签。把它保存为 .qml 文件并在脚本设置中添加,即可体验完整的扩展链路。

八、调试与排错建议

  1. 善用日志面板:在脚本的关键路径加 script.log(),通过 窗口 / 面板 打开日志面板观察输出;脚本加载与运行错误也会出现在这里。
  2. 检查加载错误:QML 语法错误、类型导入错误会导致组件加载失败,脚本设置界面会有对应反馈,日志中也会输出组件错误信息。
  3. 注意钩子性能:noteTaggingHook 的 list 动作和 highlightingHook 会被高频调用,实现务必轻量,否则会影响笔记文件夹与标签树的重载体验。
  4. 谨慎处理重名:使用 handleNoteTextFileNameHook 自定义文件名时需自行保证唯一性;使用 handleNewNoteHeadlineHook 修改标题时也要保证标题唯一。
  5. 平台差异:freedesktop 主题图标在 Linux 外不可用,跨平台脚本应自带图标或利用 scriptDirPath 定位脚本资源。

九、进一步深入

掌握脚本系统后,你可以把 QOwnNotes 从“笔记软件”升级为“自己的生产力工作台”:自定义动作、外部命令集成、自定义标签体系、动态语法高亮、AI 补全后端,乃至通过 WebSocket 远程控制,全部由你手中的 JavaScript 决定。

登录后查看全文
QOwnNotes