QOwnNotes 脚本开发实战指南:用 QML 与 JavaScript 扩展你的 Markdown 笔记应用

原创2026-10-12 10:20:402,303 阅读
文章标签:桌面应用知识管理富文本插件系统跨平台

QOwnNotes 脚本开发实战指南:用 QML 与 JavaScript 扩展你的 Markdown 笔记应用

QOwnNotes 是一款纯文本文件笔记与待办事项管理器,内置 Markdown 支持与 Nextcloud / ownCloud 同步。本篇指南基于仓库中的官方脚本文档(webpage/src/scripting/README.md 及其配套的 classes、hooks、methods-and-objects 三篇文档),系统讲解如何编写、加载和调试 QML 脚本,介绍脚本引擎向脚本暴露的对象模型、API 方法与事件钩子,并结合 src/services/scriptingservice.cpp 等源码揭示底层实现。读完本篇,你将能够从零写出一个可用的 QOwnNotes 脚本,并掌握用自定义动作、钩子与外部程序调用深度扩展应用的能力。

脚本的本质:跑在 Qt QML 引擎里的 JavaScript

QOwnNotes 的脚本绝大部分是写在 Qt QML 文件中的 JavaScript。这意味着你可以在 QML 的声明式结构里直接书写 JavaScript 函数,并借助 QML 的类型系统与 QOwnNotes 注入的对象完成与主程序的交互。一个最小的“Hello world”脚本如下:

import QtQml 2.0
import QOwnNotesTypes 1.0

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

脚本引擎初始化时,会调用脚本组件里的 init() 函数;示例中的 script.log() 则把文本输出到日志面板,便于调试。

从源码可以确认这套机制的实现方式。scriptingservice.cpp 在 ScriptingService 构造阶段做了两件关键事情:

  • 通过 setContextProperty(QStringLiteral("script"), this) 把 ScriptingService 自身以 script 的名字注入 QML 根上下文,因此脚本里可以直接调用 script.log()、script.currentNote() 等所有 Q_INVOKABLE 方法;
  • 通过 qmlRegisterType 在 QOwnNotesTypes 模块(版本 1.0)中注册了 Note、NoteSubFolder、Tag、Script 等 QML 类型,脚本开头的 import QOwnNotesTypes 1.0 就是导入这些类型。

所以“import QtQml 2.0 + import QOwnNotesTypes 1.0 + 一个 Script(或 QtObject)块”是 QOwnNotes 脚本的标准骨架,其中 init() 是所有脚本通用的初始化入口。

加载脚本:本地添加与脚本仓库安装

QML 脚本文件可以放在你电脑上的任意位置,然后在 QOwnNotes 的 Scripting settings(脚本设置) 中把它们加入应用。设置界面里提供 Add script…(添加脚本 / 添加本地脚本)按钮,这一点从 scriptingsettingswidget.ui 中可以找到对应控件 scriptAddButton。选择本地 .qml 文件后,脚本即被加载并生效,之后修改文件可通过脚本设置中的重载让改动立即生效。

除了本地脚本,脚本设置中还可以直接从脚本仓库(Script repository)安装脚本。仓库由社区维护,其中包含大量现成脚本;同时社区还提供一个网页应用用于按关键字搜索脚本列表。仓库脚本的问题、疑问或功能请求应提交到脚本仓库的 issue 页面;如果你想向仓库提议/贡献新脚本,请遵循脚本仓库的贡献说明。另外,所有对 QOwnNotes 本体功能有需求或想法的问题,都可以在 QOwnNotes 的 issue 页面提出。

提示:安装脚本后,如果脚本来自脚本仓库,QOwnNotes 还能在启动更新检查时自动安装可用的更新(见 scriptrepositorydialog.ui 中的相关选项)。

第一个调试手段:日志面板与 script.log()

编写脚本最常用的调试手段是 script.log(),它把文本输出到 Log panel(日志面板)。如果看不到日志面板,通过菜单 Window / Panels 打开即可。日志方法在 scriptingservice.h 中声明为 Q_INVOKABLE void log(QString text);,任何脚本都可以调用:

script.log("my text");

script.log() 可以接收任意字符串,也常用来打印笔记对象、标签名列表等调试信息,例如 script.log(note.name)、script.log(tagNameList)。

脚本可用的对象模型:四大暴露类

QOwnNotes 通过 QML 类型系统向脚本暴露了四个核心对象类(完整定义见 classes.md,源码实现见 src/api/ 目录):

Note(笔记对象,NoteApi)

对应 noteapi.h。常用属性包括:

属性/方法 说明
id 笔记的数据库 id
name 笔记名称
fileName 笔记文件名(如 my note.md)
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 链接

fileCreated、fileLastModified 是 JavaScript 的 Date 对象,可以直接调用 toISOString()、getFullYear() 等 Date 方法;格式化则建议使用 QML 内置的 Qt.formatDateTime 等函数。示例:

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

// renames a note to "new name.md"
note.renameNoteFile("new name");

// check if it is allowed to have a different note file name than the headline
script.log(note.allowDifferentFileName());

NoteSubFolder(笔记子文件夹,NoteSubFolderApi)

对应 notesubfolderapi.h。静态方法 fetchNoteSubFolderById(id)、activeNoteSubFolder()、fetchNoteSubFoldersByParentId(parentId) 以及实例方法 relativePath()、fullPath(),配合 notes 属性可遍历子文件夹里的所有笔记。由于这些方法是静态的,在 QML 中通常先创建一个 NoteSubFolder 对象再调用:

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

// print all subfolder names
noteSubFolderQmlObj
  .fetchNoteSubFoldersByParentId(parentId)
  .forEach(function (nsf) {
    script.log(nsf.name);
  });

// get the active note subfolder
var noteSubFolder = noteSubFolderQmlObj.activeNoteSubFolder();

// print the full and relative path of the active note subfolder
script.log(noteSubFolder.fullPath());
script.log(noteSubFolder.relativePath());

Tag(标签,TagApi)

对应 tagapi.h。属性有 id、name、parentId、notes;方法有 fetchByName(name, parentId)、getParentTagNames()。结合 script.getTagByNameBreadcrumbList() 可按层级路径获取标签对象:

// Don't forget to use "import QOwnNotesTypes 1.0" at the top of your script!

// Fetch tag "home"
var tag = script.getTagByNameBreadcrumbList(["home"]);
// Fetch all notes tagged with the tag
var notes = tag.notes;

// Iterate through notes of the tag
for (var idx in notes) {
  var note = notes[idx];
  script.log(note.name);
}

MainWindow(主窗口)

脚本中可以直接使用 mainWindow 对象调用主窗口能力,例如:

// Force a reload of the note list
mainWindow.buildNotesIndexAndLoadNoteDirectoryList(true, true);

// Creates a new note subfolder "My fancy folder" in the current subfolder
mainWindow.createNewNoteSubFolder("My fancy folder");

// Inserts html in the current note as markdown
mainWindow.insertHtmlAsMarkdownIntoCurrentNote("<h2>my headline</h2>some text");

// Set 'Edit' layout as current layout
mainWindow.setCurrentLayout(mainWindow.getLayoutUuid("Edit"));

// Jump to the tag "test" in the tag tree
var tag = script.getTagByNameBreadcrumbList(["test"]);
mainWindow.jumpToTag(tag.id);

// Get all notes that are opened in tabs
var noteIds = mainWindow.getNoteTabNoteIdList();
noteIds.forEach(function (noteId) {
  var note = script.fetchNoteById(noteId);
  // do something with the note
});

从 mainwindow.cpp 可以找到这些方法对应的实现,例如 reloadTagTree() 最终委托给标签管理器(src/mainwindow.cpp),getLayoutUuid() 委托给布局管理器(src/mainwindow.cpp)。

script 对象:最常用的方法与对象

script 对象背后是 scriptingservice.h 中声明的 ScriptingService,其所有 Q_INVOKABLE 方法都能在脚本中直接调用。完整的方法目录见 methods-and-objects.md,下面按使用场景分类介绍最常用的部分。

笔记与笔记库操作

方法 说明
currentNote() 返回当前笔记的 NoteApi 对象
currentNoteFolderPath() 返回当前笔记库文件夹路径
createNote(text) 创建一条新笔记(text 为笔记文本,可含标题与正文)
fetchNoteById(id) / fetchNoteByFileName(fileName, noteSubFolderId) 按 id / 文件名获取笔记
noteExistsByFileName(fileName, ignoreNoteId, noteSubFolderId) 判断笔记文件是否存在
fetchNoteIdsByNoteTextPart(text, ignoreAccents) 按笔记文本片段搜索,返回笔记 id 列表
setCurrentNote(note, asTab) 跳转到指定笔记(可新标签页打开)
jumpToNoteSubFolder(path, separator) 跳转到笔记子文件夹,分隔符默认 /
selectedNotesPaths() / selectedNotesIds() 返回所有选中笔记的路径 / id 列表

示例:搜索包含 mytext 的笔记,ignoreAccents 为 true 时可以忽略拉丁字符的重音(例如同时命中 Avión 与 avion):

var noteIds = script.fetchNoteIdsByNoteTextPart("mytext");

noteIds.forEach(function (noteId) {
  var note = script.fetchNoteById(noteId);
  // do something with the note
});

createNote() 的注意点:如果你关闭了“笔记文件名由标题决定”的设置,创建后需要自己重命名文件,例如:

var note = script.currentNote();
note.renameNoteFile("your-filename");

笔记文本编辑操作

这些方法直接作用于编辑器光标与选区,适合做文本转换类自定义动作:

方法 说明
noteTextEditWrite(text) 在当前光标位置写入文本
noteTextEditSelectedText() 读取选中的文本
noteTextEditSelectAll() 全选
noteTextEditSelectCurrentLine() / noteTextEditSelectCurrentWord() 选中当前行 / 当前词
noteTextEditSetSelection(start, end) 按字符位置设置选区
noteTextEditSelectionStart() / noteTextEditSelectionEnd() 选区起点 / 终点
noteTextEditSetCursorPosition(position) 移动光标,-1 表示跳到笔记末尾
noteTextEditCursorPosition() 当前光标位置
noteTextEditCurrentWord(withPreviousCharacters) 读取当前词(可包含 @ 等非词字符)
noteTextEditCurrentBlock() 读取当前文本块

例如“把选中文本整体替换”可以用全选 + 写入两步完成:

script.noteTextEditSelectAll();
script.noteTextEditWrite("My custom text");

自定义动作(Custom Actions)

registerCustomAction() 是脚本最强大的能力之一:注册后脚本会在“自定义动作”菜单中出现对应条目,并可附带工具栏按钮与图标。方法签名(见 scriptingservice.h):

  • identifier:动作的唯一标识符;
  • menuText:菜单中显示的文字;
  • buttonText:按钮文字(为空则不显示按钮);
  • icon:图标文件路径,或 freedesktop 主题图标名;
  • useInNoteEditContextMenu:是否在笔记编辑器的右键菜单中使用(默认 false);
  • hideButtonInToolbar:是否在自定义动作工具栏隐藏按钮(默认 false);
  • useInNoteListContextMenu:是否在笔记列表右键菜单中使用(默认 false)。

完整示例:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    function init() {
        // add a custom action without a button
        script.registerCustomAction("mycustomaction1", "Menu text");

        // add a custom action with a button
        script.registerCustomAction("mycustomaction2", "Menu text", "Button text");

        // add a custom action with a button and freedesktop theme icon
        script.registerCustomAction("mycustomaction3", "Menu text", "Button text", "task-new");

        // add a custom action with a button and an icon from a file
        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;
        }
    }
}

从源码看,registerCustomAction() 最终调用主窗口的 addCustomAction()(scriptingservice.cpp),主窗口把动作加入“自定义动作”菜单并设置 objectName 为 customAction_<identifier>(mainwindow.cpp),脚本侧则通过 customActionInvoked(identifier) 回调接收触发事件(见 scriptingservice.h)。更完整的多动作示例见 custom-actions.qml。

提示:可以在 Shortcuts settings(快捷键设置) 中为自定义动作分配局部和全局快捷键;也可以在应用启动后通过命令行参数 --action customAction_<identifier> 触发某个自定义动作(参数解析见 main.cpp)。

注意:freedesktop 主题图标大多只在 Linux 下可用;macOS 或 Windows 上若想使用图标,需要在脚本中自带图标文件。要定位脚本所在目录(例如拼接图标路径),可使用 scriptDirPath 属性(见下文)。

标签操作

方法 说明
tagCurrentNote(tagName) 给当前笔记添加标签
getTagByNameBreadcrumbList(nameList, createMissing) 按标签层级“面包屑”获取/创建标签,createMissing 默认 true
searchTagsByName(name, ignoreAccents) 按名称子串搜索标签,可忽略重音

示例:创建 level1 > level2 > level3 三级标签树并返回最深标签对象:

var tag = script.getTagByNameBreadcrumbList(["level1", "level2", "level3"]);

对话框与输入交互

方法 说明
informationMessageBox(text, title) 信息提示框
questionMessageBox(text, title, buttons, defaultButton) 询问框,返回被按按钮的 id(按钮值参考 Qt StandardButton 枚举)
inputDialogGetItem(title, label, items, current, editable) 下拉选择输入框
inputDialogGetText(title, label, text) 单行文本输入框
inputDialogGetMultiLineText(title, label, text) 多行文本输入框
getOpenFileName(caption, dir, filter) / getSaveFileName(...) 打开 / 保存文件对话框
textDiffDialog(title, label, text1, text2) 对比两段文本并允许编辑第二段

输入类对话框在用户点击 Cancel 或按下 Escape 时返回空字符串,编写脚本时要注意处理。完整的对话框脚本示例见 input-dialogs.qml。

外部程序调用

QOwnNotes 脚本可以启动外部程序,这也是把笔记应用与命令行工具链打通的关键能力。

后台启动(detached,不阻塞界面):

script.startDetachedProcess("/path/to/my/program", ["my parameter"]);

startDetachedProcess 的完整参数为:executablePath、parameters(参数列表)、callbackIdentifier(可选,用于在回调中识别批量任务)、callbackParameter(可选,供循环等场景使用的附加参数)、processData(可选,使用回调时写入进程的数据)、workingDirectory(可选,仅在不使用回调时生效)。底层实现在 scriptingservice.cpp:如果提供了 callbackIdentifier,会创建 ScriptThread 在后台线程执行,任务完成后触发 onDetachedProcessCallback 钩子;否则直接调用 Utils::Misc::startDetachedProcess。批量并发示例:

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]}`);
  }
}

同步执行并等待输出:

var result = script.startSynchronousProcess(
  "/path/to/my/program",
  ["my parameter"],
  "data",
  "/path/to/execute/in",
);

同步方式会阻塞脚本直至进程结束并返回其输出文本,适合“拿到结果再继续处理”的场景(例如加密脚本用外部命令行加解密)。

媒体与附件

方法 说明
downloadUrlToString(url) 下载 URL 并返回文本内容
downloadUrlToMedia(url, returnUrlOnly) 下载 URL 到 media 文件夹,返回 Markdown 图片文本或媒体 URL
insertMediaFile(mediaFilePath, returnUrlOnly) 把本地媒体文件插入 media 文件夹,返回 Markdown 图片文本或 URL
insertAttachmentFile(attachmentFilePath, fileName, returnUrlOnly) 把本地文件插入 attachments 文件夹并返回 Markdown 文本

例如把 LaTeX 公式渲染图片插入笔记(见 paste-latex-image.qml):

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

设置变量、持久变量与文件读写

脚本设置变量(settings variables):在脚本中用 property 声明变量,再通过 settingsVariables 属性数组注册,用户即可在脚本设置中配置这些值:

property string myString;
property bool myBoolean;
property int myInt;

property variant settingsVariables: [
    {
        "identifier": "myString",
        "name": "I am a line edit",
        "description": "Please enter a valid string:",
        "type": "string",
        "default": "My default value",
    },
    {
        "identifier": "myBoolean",
        "name": "I am a checkbox",
        "description": "Some description",
        "text": "Check this checkbox",
        "type": "boolean",
        "default": true,
    },
    {
        "identifier": "myInt",
        "name": "I am a number selector",
        "description": "Please enter a number:",
        "type": "integer",
        "default": 42,
    }
];

支持的类型包括:string(单行输入)、string-secret(密码输入)、boolean(复选框)、text(多行文本)、integer(整数)、file(文件选择)、directory(目录选择)、selection(下拉选择,用 items 提供选项)。还可以用 registerSettingsVariables() 函数在代码中覆盖默认值,例如按操作系统区分 pandoc / pandoc.exe:

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) 可读取应用设置项,例如 script.getApplicationSettingsVariable("gitExecutablePath")。注意设置项可能为空字符串,defaultValue 只在设置完全不存在时生效。

文件读写:fileExists(filePath)、readFromFile(filePath, codec)(默认 UTF-8 编码)、writeToFile(filePath, data, createParentDirs)。写文件时 createParentDirs 默认 false,需要自动创建父目录时传入 true。

平台判断、剪贴板、样式与杂项

方法 说明
platformIsLinux() / platformIsOSX() / platformIsWindows() 判断当前平台
clipboard(asHtml) 读取剪贴板(文本或 HTML)
setClipboardText(text, asHtml) 写入剪贴板
addStyleSheet(stylesheet) 向应用注入 Qt 样式表,可修改界面外观
reloadScriptingEngine() 重载脚本引擎
regenerateNotePreview() 重新生成笔记预览
triggerMenuAction(objectName, checked) 触发某个菜单动作(checked 可限制只在状态不同时触发)
getColorModes() / getCurrentColorModeId() / switchToColorMode(idOrName) 颜色模式(如浅色/深色)的管理与切换
cacheDir(subDir) / clearCacheDir(subDir) 获取 / 清空脚本缓存目录
toNativeDirSeparators(path) / fromNativeDirSeparators(path) / dirSeparator() 路径分隔符转换
scriptDirPath(属性) 脚本所在目录路径,需要在脚本中声明 property string scriptDirPath;

样式表示例(见 custom-stylesheet.qml):

// make the text in the note list bigger
script.addStyleSheet("QTreeWidget#noteTreeWidget {font-size: 30px;}");

控件名称来自 *.ui 文件,例如主窗口布局在 mainwindow.ui;也可以参考 qdarkstyle 的 style.qss 了解可修改的样式项。若想修改笔记预览的 HTML 样式,则应使用 noteToMarkdownHtmlHook 钩子(见下)。

触发菜单动作示例(对应 disable-readonly-mode.qml):

// toggle the read-only mode
script.triggerMenuAction("actionAllow_note_editing");

// disable the read-only mode
script.triggerMenuAction("actionAllow_note_editing", 1);

颜色模式示例(见 toggle-color-mode.qml):内置颜色模式的 id 为 ColorMode-light 与 ColorMode-dark,自定义模式则使用生成的随机 id,因此 switchToColorMode() 同时接受模式的名称作为参数。使用 script.addStyleSheet() 注入的样式在切换颜色模式后仍会保留。

事件钩子(Hooks):让脚本响应应用生命周期

钩子是 QOwnNotes 脚本的另一大支柱:在脚本中定义特定名称的函数,应用在相应时机就会调用它。完整清单见 hooks.md,这里列出最重要的几类。

笔记生命周期类

  • onNoteStored(note):笔记写入磁盘时调用。文档特别强调不能在钩子里修改已存储的笔记,因为你很可能同时在手工编辑它(见 example.qml 中的用法)。
  • noteOpenedHook(note):笔记打开后调用(示例 on-note-opened.qml)。
  • noteDoubleClickedHook(note):笔记被双击后调用(示例 external-note-open.qml)。
  • handleNoteTextFileNameHook(note):当设置“允许笔记文件名与标题不同”时,在笔记存储时调用,返回新的文件名;返回空字符串表示不修改。重复文件名需要脚本自己处理(示例 use-tag-names-in-filename.qml)。
  • handleNoteNameHook(note):在确定笔记显示名称时调用,返回空字符串表示不修改。如果开启了“用文件名作为笔记名”的设置,建议不要使用此钩子。
  • handleNewNoteHeadlineHook(headline):创建笔记前调用,可用来实现笔记模板(例如自动加上日期标题)。注意必须保证标题唯一,否则新笔记不会创建而只会出现在笔记列表中。示例见 custom-new-note-headline.qml。

预览与 HTML 类

  • preNoteToMarkdownHtmlHook(note, markdown, forExport):在 Markdown 转 HTML 之前调用,可修改交给转换器的 Markdown。可用于在多个脚本中把 LaTeX 数学公式、mermaid 图等代码块渲染为图形以便预览,且不会修改笔记本身。
  • noteToMarkdownHtmlHook(note, html, forExport):在 Markdown 转 HTML 之后调用,可修改最终渲染的 HTML。预览与导出都会触发,forExport 用于区分导出(true)与预览(false)。示例见 preview-styling.qml。

插入与粘贴类

  • insertMediaHook(fileName, markdownText):媒体文件插入当前笔记时调用,返回新的 Markdown 文本;多个脚本都定义时,第一个返回非空字符串的脚本生效。
  • insertAttachmentHook(fileName, markdownText):附件文件插入时调用,规则同上。
  • insertingFromMimeDataHook(text, html):用 Ctrl + Shift + V 粘贴 HTML 或媒体文件时调用,返回要插入的字符串(示例 insert-headline-with-link-from-github-url.qml)。
  • fetchUrlTitleHook(url):链接对话框中获取网页标题前调用,返回非空标题可接管标题获取(示例 fetch-url-title-with-kanboard-cli.qml)。

加密类

标签自定义类

  • noteTaggingHook(note, action, tagName, newTagName):实现自定义标签机制,例如用笔记中的 @tag1、@tag2 文本作为标签。action 取值 "add"、"remove"、"rename"、"list";list 时返回标签名列表。一旦脚本激活了该函数,笔记标签的添加、移除、重命名、批量操作以及标签树移动都会由它接管。示例见 note-tagging.qml。

    警告:list 动作必须足够快,因为它会在每次笔记库或标签树重载时对每一条笔记执行(对应 mainwindow.cpp 中所有 reloadTagTree 的调用点)。

  • noteTaggingByObjectHook(note, action, tag, newTagName):与上面类似,但参数是 TagApi 对象而非标签名,且 list 动作需要返回标签 id 列表,因此可以充分利用整棵标签树;缺失的标签需要脚本自己创建。示例见 note-tagging-by-object.qml。

其他系统类

  • autocompletionHook()(经 callAutocompletionHook() 调用):返回字符串列表加入自动补全候选(按 Ctrl + Space 触发),示例 autocompletion.qml。
  • websocketRawDataHook(经 callHandleWebsocketRawDataHook 调用):接收来自 Web Companion 浏览器扩展发送的数据(requestType 为 "page" 或 "selection"),示例 websocket-raw-data-selection-in-note.qml。
  • onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread):startDetachedProcess 的后台线程执行完毕时回调。cmd 数组为 <a href="https://link.gitcode.com/i/91c05710b72c6861b910dbcbf4a2a810" target="_blank">可执行路径, 参数, 退出码];thread 数组为 [回调参数, 该标识符剩余的线程数],其中 thread[1] == 0 可用于判断一批进程是否全部结束。示例 [callback.qml。
  • windowStateChangedHook(windowState):窗口状态变化后调用,取值可为 "minimized"、"maximized"、"fullscreen"、"active"、"nostate"(示例 window-state-changed.qml)。
  • layoutSwitchedHook(oldUuid, newUuid):布局切换时调用(示例 layouts.qml)。
  • openAiBackendsHook():OpenAI 服务配置重载时调用,可返回自定义 OpenAI 兼容后端(如 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"],
    },
  ];
}

OpenAI 相关能力还包括 script.aiComplete(prompt)(对当前选中的 AI 模型执行补全,需要先在 AI 工具栏或主菜单启用 AI 系统,示例见 ai-autocompletion.qml)以及 textDiffDialog() 与 aiComplete 组合的 AI 文本处理流程。

  • highlightingHook(text, previousBlockState):语法高亮时对每个文本块调用,可返回高亮范围数组实现动态、上下文相关的高亮。每个高亮范围对象支持 start、length、state、foregroundColor、backgroundColor、bold、italic、underline、fontSize 字段。该钩子在每次按键时对每个可见文本块都会触发,实现必须保持高效;静态的正则高亮请优先使用 addHighlightingRule(见下)。示例 highlighting.qml 与 custom-highlighting.qml。

编辑器语法高亮:addHighlightingRule

addHighlightingRule 可以直接向编辑器语法高亮器注入正则规则:

void ScriptingService::addHighlightingRule(const QString &pattern,
                                            const QString &shouldContain,
                                            int state,
                                            int capturingGroup,   // 默认 0
                                            int maskedGroup);     // 默认 0
  • pattern:正则表达式模式;
  • shouldContain:被高亮文本必须包含的字符串(可加速匹配);
  • state:语法高亮状态编号,见下表;
  • capturingGroup:用于高亮的捕获组(默认 0,即整个匹配);
  • maskedGroup:用于掩蔽的捕获组(默认 0)。

预定义高亮状态编号(与 methods-and-objects.md 一致):

名称 编号 名称 编号
NoState -1 Link / Image / CodeBlock / CodeBlockComment 0 / 3 / 4 / 5
Italic / Bold / List / Comment 7 / 8 / 9 / 11 H1 ~ H6 12 ~ 17
BlockQuote / HorizontalRule / Table / InlineCodeBlock 18 / 21 / 22 / 23 MaskedSyntax / CurrentLineBackgroundColor / BrokenLink 24 / 25 / 26
FrontmatterBlock / TrailingSpace / CheckBoxUnChecked / CheckBoxChecked 27 / 28 / 29 / 30 StUnderline / WikiLink / WikiLinkBroken / LinkInternal / Whitespace 31 / 32 / 33 / 34 / 35

示例:

// Highlight a text line like "BLOCK: some text" as blockquote (state 18)
script.addHighlightingRule("^BLOCK: (.+)", "BLOCK:", 18);

// Mask out (state 24) all characters after 32 characters in a line
script.addHighlightingRule("^.{32}(.+)", "", 24, 1, -1);

自定义颜色与样式的重载版本:addHighlightingRule(pattern, shouldContain, state, capturingGroup, maskedGroup, formatStyle) 额外接受一个 QVariantMap,可指定 foregroundColor、backgroundColor、bold、italic、underline、fontSize。自定义属性会覆盖预定义状态的默认样式;只用自定义格式时把 state 设为 -1(NoState):

function init() {
  // Highlight "IMPORTANT" with bold red text on a yellow background
  script.addHighlightingRule("IMPORTANT", "IMPORTANT", -1, 0, 0, {
    foregroundColor: "#ff0000",
    backgroundColor: "#ffff00",
    bold: true,
  });

  // Highlight "@username" mentions with underlined blue text
  script.addHighlightingRule("@\\w+", "@", -1, 0, 0, {
    foregroundColor: "#3366cc",
    underline: true,
  });
}

日期时间格式化:内置 Qt.format*

不需要手写日期格式化函数,QML 引擎直接提供 Qt.formatDateTime、Qt.formatDate、Qt.formatTime:

var date = new Date();
// "2026-09-29"
script.log(Qt.formatDateTime(date, "yyyy-MM-dd"));

// "Tuesday, 29. September 2026 at 14:05"
script.log(Qt.formatDateTime(date, "dddd, d. MMMM yyyy 'at' HH:mm"));

// Tag the current note with the current year and month, like "2026-09"
script.tagCurrentNote(Qt.formatDateTime(date, "yyyy-MM"));

// Also works with the dates of a note
var note = script.currentNote();
script.log(Qt.formatDateTime(note.fileLastModified, "yyyy-MM-dd HH:mm:ss"));

常用占位符:yyyy(四位年份)、MM(带前导零的月份)、MMM/MMMM(缩写/完整月份名)、dd/d(带/不带前导零的日)、HH/hh(24/12 小时制)、mm(分钟)、ss(秒)、AP/ap(上午/下午)。要点:

  • 占位符区分大小写:yyyy 是年份,MM 是月份,而 mm 是分钟;YYYY、DD 这类其他日期库的写法不受支持;格式串也不支持 ISO 周数;
  • 单引号内的文本不会被解释为占位符,例如 "yyyy-MM-dd 'at' HH:mm"。

远程控制与 WebSocket

可以通过 WebSocketServer 远程控制 QOwnNotes,或用 WebSocket 连接其他 socket 服务。服务端示例见 websocket-server.qml,客户端示例见 websocket-client.qml。使用 WebSocket 需要系统安装 Qt 的 QML websocket 库,例如 Ubuntu 下安装 qml-module-qtwebsockets。

立即上手的示例脚本

仓库 docs/scripting/examples/ 目录下有 60 个可直接参考的示例脚本,覆盖了上文提到的绝大多数场景,包括:

建议从 example.qml 和 custom-actions.qml 入手,把脚本放入脚本设置后,用日志面板观察各个钩子的触发时机,再逐步加入自己的业务逻辑。

小结

QOwnNotes 的脚本体系由三部分组成:QML 中的 JavaScript 脚本文件(标准骨架是 import QtQml 2.0 + import QOwnNotesTypes 1.0)、通过 script 对象暴露的 200 余个可调用 API(定义于 scriptingservice.h)、以及围绕笔记生命周期、预览渲染、插入粘贴、标签与外部进程的事件钩子(hooks.md)。核心对象模型 NoteApi、NoteSubFolderApi、TagApi 与 MainWindow 则分别在 src/api/ 与 src/mainwindow.cpp 中实现。掌握了“添加脚本 → init() 初始化 → 调用 script.* API → 响应钩子 → 用 script.log() 调试”这条完整链路,你就可以为 QOwnNotes 定制笔记模板、文本转换、标签机制、加密方案、外部工具集成乃至 AI 补全等各类自动化能力。

登录后查看全文
QOwnNotes