QOwnNotes 脚本开发实战指南:用 QML + JavaScript 扩展笔记工作流

原创2026-10-15 10:30:281,611 阅读
文章标签:桌面应用知识管理富文本插件系统跨平台

QOwnNotes 脚本开发实战指南:用 QML + JavaScript 扩展笔记工作流

QOwnNotes 是一套以纯文本文件为核心、支持 Markdown 与 Nextcloud / ownCloud 同步的笔记与待办管理应用,而它的脚本系统则是把应用能力开放给用户的桥梁:脚本以 Qt QML 文件中的 JavaScript 形式存在,由内置的脚本引擎加载执行,可深度介入笔记生命周期、编辑器、预览渲染、标签体系乃至系统级进程调用。本指南将带你从零编写并安装第一个脚本,系统梳理脚本引擎暴露的 API 对象、方法库与事件钩子(hooks),并结合仓库源码与官方示例,掌握自定义菜单动作、语法高亮、加密、标签体系等真实场景的落地写法。

QOwnNotes 中的 QML 脚本面板与脚本化界面

一、理解 QOwnNotes 脚本:QML 文件中的 JavaScript

QOwnNotes 脚本本质上就是运行在 Qt QML 运行时里的 JavaScript 程序。你不需要完整学习 QML 的 UI 语法,只需要遵守 QML 文件的结构约定:文件以 import 声明开头,内部定义一个脚本对象,并实现 QOwnNotes 约定的函数(如 init()),这些函数会在特定时机被脚本引擎回调。

最简单的 "Hello world" 脚本如下:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    /**
     * 脚本引擎初始化时运行
     */
    function init() {
        script.log("Hello world!");
    }
}

要点拆解:

  • import QtQml 2.0:引入 Qt QML 基础模块(Timer 等组件依赖它)。
  • import QOwnNotesTypes 1.0:QOwnNotes 自定义的 QML 类型模块,向脚本暴露 Script、Note、NoteSubFolder、Tag 等类型。从源码看,这些类型由 src/services/scriptingservice.cpp 中的 qmlRegisterType 注册,例如 qmlRegisterType<NoteApi>("QOwnNotesTypes", 1, 0, "Note")。
  • Script { ... }:脚本根对象。也可以写成 QtObject { ... }(官方示例多采用 QtObject),效果相同。
  • function init():脚本引擎初始化时的回调,是注册自定义动作、注入高亮规则、初始化定时器的最佳位置。
  • script.log():向日志面板(Log panel)输出文本,是脚本调试的第一入口;日志面板可在 Window / Panels(窗口 / 面板) 菜单中打开。

脚本引擎在 ScriptingService 中创建 QQmlEngine,并把 script 和 mainWindow 两个对象作为上下文属性注入到所有脚本(见 src/services/scriptingservice.cpp)。这意味着你可以在任意脚本里直接使用全局对象 script(脚本 API 入口)与 mainWindow(主窗口操作入口)。

二、安装与启用脚本

脚本文件(.qml)可以放在磁盘任意位置,然后在 Scripting settings(脚本设置) 中添加:

  • Add script(添加脚本):选择脚本仓库(在线脚本库)中的脚本。
  • Add local script(添加本地脚本):从本地文件系统选择 .qml 文件。

脚本设置还支持直接从 Script repository(脚本仓库) 在线安装脚本,并可通过社区托管的 Web 应用 QOwnNoteScriptsList 搜索可用脚本。若你在脚本仓库中的脚本上发现问题、有疑问或想要新功能,请在脚本仓库的 issue 页面提交;若你希望向脚本仓库提交自己的脚本,请遵循仓库内给出的贡献指引。

关于脚本仓库脚本的加载机制,可参见 src/entities/script.h:每个脚本在数据库中以 Script 实体管理,包含 identifier、scriptPath、priority、enabled、settingsVariablesJson 等字段,支持从远程仓库按标识符拉取与更新(fetchByIdentifier、refetch)。

读取脚本所在目录

如果你需要在脚本中加载同目录下的其他文件(例如自定义图标、资源文件),可以声明一个特殊的字符串属性,脚本引擎会自动把它填充为脚本文件所在目录:

import QtQml 2.0
import QOwnNotesTypes 1.0

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

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

这在注册自定义动作的图标路径时尤其有用:freedesktop 主题图标在 Linux 上可用,但 macOS / Windows 往往没有,此时应使用 scriptDirPath 拼接脚本自带的图标文件路径。

三、脚本核心对象:NoteApi、TagApi、NoteSubFolderApi 与 MainWindow

脚本引擎以 Qt 属性系统(Q_PROPERTY / Q_INVOKABLE)向 QML 暴露核心对象。理解这些对象是编写一切脚本的基础。以下接口签名对应 src/api/noteapi.h、src/api/tagapi.h 及配套文档的实际实现。

NoteApi:笔记对象

笔记对象(QML 类型名 Note)是脚本中最常打交道的对象,主要属性与方法如下:

class NoteApi {
    Q_PROPERTY(int id)
    Q_PROPERTY(QString name)
    Q_PROPERTY(QString fileName)
    Q_PROPERTY(QString fullNoteFilePath)
    Q_PROPERTY(QString fullNoteFileDirPath)
    Q_PROPERTY(QString relativeNoteFileDirPath)
    Q_PROPERTY(int noteSubFolderId)
    Q_PROPERTY(QString noteText)
    Q_PROPERTY(QString decryptedNoteText)
    Q_PROPERTY(bool hasDirtyData)
    Q_PROPERTY(QQmlListProperty<TagApi> tags)
    Q_PROPERTY(QDateTime fileCreated)
    Q_PROPERTY(QDateTime fileLastModified)
    Q_INVOKABLE QStringList tagNames()
    Q_INVOKABLE bool addTag(QString tagName)
    Q_INVOKABLE bool removeTag(QString tagName)
    Q_INVOKABLE bool renameNoteFile(QString newName)
    Q_INVOKABLE QString toMarkdownHtml(bool forExport = true)
    Q_INVOKABLE QString getFileURLFromFileName(QString localFileName)
    Q_INVOKABLE bool allowDifferentFileName()
    // 返回用于通过 noteId 链接到该笔记的 Markdown 笔记 URL
    Q_INVOKABLE QString getNoteUrlForLinkingToNoteId(int noteId)
}

示例:

// fileCreated / fileLastModified 返回 QDateTime,可直接使用 JavaScript Date 的方法
script.log(note.fileCreated.toISOString());
script.log(note.fileLastModified.getFullYear());

// 将笔记文件改名为 "new name.md"
note.renameNoteFile("new name");

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

decryptedNoteText 属性、renameNoteFile、getNoteUrlForLinkingToNoteId 等在 src/api/noteapi.h 中均有对应实现,可作为扩展阅读的入口。

TagApi:标签对象

class TagApi {
    Q_PROPERTY(int id)
    Q_PROPERTY(QString name)
    Q_PROPERTY(int parentId)
    Q_PROPERTY(QQmlListProperty<NoteApi> notes)
    Q_INVOKABLE TagApi fetchByName(const QString &name, int parentId = 0)
    Q_INVOKABLE QStringList 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);
}

NoteSubFolderApi:笔记子文件夹对象

class NoteSubFolderApi {
    Q_PROPERTY(int id)
    Q_PROPERTY(QString name)
    Q_PROPERTY(QQmlListProperty<NoteApi> notes)
    Q_INVOKABLE static NoteSubFolderApi *fetchNoteSubFolderById(int id);
    Q_INVOKABLE static NoteSubFolderApi *activeNoteSubFolder();
    Q_INVOKABLE static QList<QObject*> fetchNoteSubFoldersByParentId(int parentId);
    Q_INVOKABLE QString relativePath();
    Q_INVOKABLE QString fullPath();
}

示例(由于 NoteSubFolder 是静态方法载体,需要先创建 QML 对象再调用):

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

MainWindow:主窗口操作入口

mainWindow 对象提供了大量界面级操作,常用方法如下:

class MainWindow {
    Q_INVOKABLE void reloadTagTree();
    Q_INVOKABLE void reloadNoteSubFolderTree();
    Q_INVOKABLE void buildNotesIndexAndLoadNoteDirectoryList(
            bool forceBuild = false, bool forceLoad = false);
    Q_INVOKABLE void focusNoteTextEdit();
    // 在当前子文件夹中创建新的笔记子文件夹
    Q_INVOKABLE bool createNewNoteSubFolder(QString folderName = "");
    // 将 HTML 以 Markdown 形式插入当前笔记
    // 该方法还会下载远程图片,并把 "data:image" URL 转换为
    // 存储在媒体目录中的本地图片
    Q_INVOKABLE void insertHtmlAsMarkdownIntoCurrentNote(QString html);
    // 按 ID 重新加载当前笔记
    // 当前笔记路径或文件名发生变化时很有用
    Q_INVOKABLE void reloadCurrentNoteByNoteId();
    // 返回布局 UUID 列表
    Q_INVOKABLE QStringList getLayoutUuidList();
    // 传入布局名称返回布局 UUID
    Q_INVOKABLE QString getLayoutUuid(const QString &layoutName);
    // 按 UUID 设置当前布局
    Q_INVOKABLE void setCurrentLayout(const QString &uuid);
    // 关闭指定索引的笔记标签页(成功返回 true)
    Q_INVOKABLE bool removeNoteTab(int index);
    // 返回标签页中打开的笔记 ID 列表
    Q_INVOKABLE QList<int> getNoteTabNoteIdList();
    // 在标签树中跳转到指定标签
    Q_INVOKABLE bool jumpToTag(int 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 对象提供的实用 API

script 对象是所有脚本的全局入口,方法数量众多,下面按用途分组梳理(完整签名见 src/services/scriptingservice.h)。

4.1 启动外部程序

后台启动分离进程(适合调用外部工具且不阻塞 UI):

/**
 * 启动分离进程的 QML 封装
 *
 * @param executablePath 可执行文件路径
 * @param parameters 参数字符串列表
 * @param callbackIdentifier 用于 onDetachedProcessCallback() 的标识符(可选)
 * @param callbackParameter 用于循环等的附加参数(可选)
 * @param processData 使用回调时写入进程的数据(可选)
 * @param workingDirectory 进程工作目录(可选,仅在没有回调时生效)
 * @return 成功返回 true,否则 false
 */
bool startDetachedProcess(QString executablePath, QStringList parameters,
                          QString callbackIdentifier, QVariant callbackParameter,
                          QByteArray processData, QString workingDirectory);

简单示例:

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

批量启动大量进程并利用回调跟踪(配合 onDetachedProcessCallback 钩子):

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

回调参数含义:thread[0] 是传入的 callbackParameter,thread[1] 是该标识符剩余线程数,cmd[1] 是进程参数。

同步启动并等待输出(适合需要立刻拿到结果的一次性调用):

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",
);

实际案例可参考 docs/scripting/examples/callback.qml、docs/scripting/examples/execute-command-after-note-update.qml 与 docs/scripting/examples/encryption-keybase.qml。

4.2 获取当前笔记与笔记文件夹

QString currentNoteFolderPath();      // 当前笔记文件夹路径
NoteApi *currentNote() const;         // 当前笔记对象
var path = script.currentNoteFolderPath();
var note = script.currentNote();

示例见 docs/scripting/examples/absolute-media-links.qml。

4.3 日志输出

void log(QString text);   // 输出到日志面板
script.log("my text");

4.4 下载 URL

下载到字符串:

QString downloadUrlToString(QUrl url);
var html = script.downloadUrlToString("https://www.qownnotes.org");

下载到媒体文件夹(返回相对当前笔记的媒体 URL 或 Markdown 图片文本):

QString downloadUrlToMedia(QUrl url, bool returnUrlOnly);  // returnUrlOnly 默认 false
var markdown = script.downloadUrlToMedia(
  "http://latex.codecogs.com/gif.latex?\frac{1}{1+sin(x)}",
);

这正是 docs/scripting/examples/paste-latex-image.qml 实现 LaTeX 公式转图片的核心调用。

4.5 插入媒体与附件

QString insertMediaFile(QString mediaFilePath, bool returnUrlOnly);      // 插入媒体文件到媒体文件夹
QString insertAttachmentFile(const QString &attachmentFilePath,
                             const QString &fileName, bool returnUrlOnly); // 插入附件到 attachments 文件夹
var markdown = script.insertMediaFile("/path/to/your/image.png");
var markdown2 = script.insertAttachmentFile("/path/to/your/file.png");

绘制涂鸦后自动插入笔记的 docs/scripting/examples/scribble.qml 同时使用了 insertMediaFile 与 regenerateNotePreview(重新生成笔记预览):

script.regenerateNotePreview();

4.6 注册自定义动作(Custom Actions)

自定义动作是脚本与用户交互最常用的机制:脚本在 init() 中注册动作,用户通过菜单、工具栏按钮触发,脚本在 customActionInvoked(identifier) 中响应。

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

完整示例:

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");
    }

    /**
     * 自定义动作被触发时调用
     *
     * @param identifier registerCustomAction 中定义的标识符
     */
    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;
        }
    }
}

两个重要的使用提示:

  1. 自定义动作可以在 快捷键设置 中分配本地与全局快捷键。
  2. 自定义动作还可以在应用启动后通过 CLI 参数触发:QOwnNotes --action customAction_<identifier>。例如执行标识符为 myAction 的自定义动作:QOwnNotes --action customAction_myAction(详见 webpage/src/ko/getting-started/cli-parameters.md)。

功能更丰富的实战示例见 docs/scripting/examples/custom-actions.qml,其中演示了用 kwrite 打开当前笔记、读取剪贴板创建会议笔记、对选中文本做 rot13 变换等场景。

4.7 注册标签(Labels)并在脚本面板显示

脚本可以在脚本面板(Script panel,在 Window / Panels 菜单中启用)中显示自定义文本标签,内容支持纯文本或 HTML,文本可选中、链接可点击。

void ScriptingService::registerLabel(QString identifier, QString text);   // 注册标签
void ScriptingService::setLabelText(QString identifier, QString text);    // 更新标签文本
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");

脚本标签还支持外部链接,以及对笔记、任务、看板卡片等的内部链接——具体支持的链接格式可在 src/utils/urlhandler.cpp 中查看。示例见 docs/scripting/examples/scripting-label-demo.qml。

4.8 笔记的创建与文本编辑

void createNote(QString text);                    // 创建新笔记
QString clipboard(bool asHtml = false);           // 读取剪贴板内容
void noteTextEditWrite(QString text);             // 在光标位置写入文本
QString noteTextEditSelectedText();               // 读取选中文本
void noteTextEditSelectAll();                     // 全选
void noteTextEditSelectCurrentLine();             // 选中当前行
void noteTextEditSelectCurrentWord();             // 选中当前词
void noteTextEditSetSelection(int start, int end);// 设置选区
int noteTextEditSelectionStart();                 // 选区起点
int noteTextEditSelectionEnd();                   // 选区终点
void noteTextEditSetCursorPosition(int position); // 设置光标位置(0 为开头,-1 为末尾)
int noteTextEditCursorPosition();                 // 当前光标位置
QString noteTextEditCurrentWord(bool withPreviousCharacters); // 读取当前词(可包含 @ 等非词字符)
QString noteTextEditCurrentBlock();               // 读取当前块

创建笔记:

script.createNote("My note headline\n===\n\nMy text");

如果关闭了"笔记文件名由标题决定"的选项,创建后需要手动改名:

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

读取选中文本并写回(配合 noteTextEditSelectAll 可整体覆盖当前笔记文本):

var text = script.noteTextEditSelectedText();
// 对 text 做变换...
script.noteTextEditWrite(text);

4.9 消息框与文件对话框

void informationMessageBox(QString text, QString title);   // 信息框
int questionMessageBox(QString text, QString title,
                       int buttons, int defaultButton);     // 询问框,返回被按按钮 ID
QString getOpenFileName(QString caption, QString dir, QString filter);   // 打开文件对话框
QString getSaveFileName(QString caption, QString dir, QString filter);   // 保存文件对话框
// 带 "帮助" 与 "支持" 按钮的询问框
// 按钮取值参见 QMessageBox::StandardButton 枚举
var result = script.questionMessageBox(
  "The text I want to show",
  "Some optional title",
  0x01000000 | 0x02000000,
  0x02000000,
);
script.log(result);

var fileName = script.getOpenFileName(
  "Please select an image",
  "/home/user/images",
  "Images (*.png *.xpm *.jpg)",
);

输入类对话框(点击取消或按 Esc 均返回空字符串):

QString inputDialogGetItem(const QString &title, const QString &label,
                           const QStringList &items, int current = 0,
                           bool editable = false);
QString inputDialogGetText(const QString &title, const QString &label,
                           const QString &text = QString());
QString inputDialogGetMultiLineText(const QString &title, const QString &label,
                                    const QString &text = QString());
QString textDiffDialog(const QString &title, const QString &label,
                       QString text1, QString text2);  // text2 可在对话框中编辑
var result = script.inputDialogGetItem("combo box", "Please select an item", [
  "Item 1",
  "Item 2",
  "Item 3",
]);
script.log(result);

示例见 docs/scripting/examples/input-dialogs.qml。

4.10 标签与笔记检索

void tagCurrentNote(QString tagName);                                  // 为当前笔记打标签
TagApi *getTagByNameBreadcrumbList(const QStringList &nameList,
                                   bool createMissing = true);         // 按面包屑路径获取/创建标签
QStringList searchTagsByName(QString name);                            // 按名称搜索标签
QList<int> fetchNoteIdsByNoteTextPart(QString text);                   // 按笔记文本搜索笔记 ID
NoteApi *fetchNoteByFileName(QString fileName, int noteSubFolderId);   // 按文件名获取笔记
NoteApi *fetchNoteById(int id);                                        // 按 ID 获取笔记
bool noteExistsByFileName(QString fileName, int ignoreNoteId,
                          int noteSubFolderId);                        // 检查笔记文件是否存在
// 给当前笔记添加 "favorite" 标签
script.tagCurrentNote("favorite");

// 创建三级标签并返回最深层标签对象:
// level1 > level2 > level3
var tag = script.getTagByNameBreadcrumbList(["level1", "level2", "level3"]);

// 搜索名称包含 "game" 的所有标签
var tags = script.searchTagsByName("game");

// 按文本片段查找笔记
var noteIds = script.fetchNoteIdsByNoteTextPart("mytext");
noteIds.forEach(function (noteId) {
  var note = script.fetchNoteById(noteId);
  // 对笔记执行操作
});

// 按文件名获取笔记
script.fetchNoteByFileName("my note.md");
// 按 ID 获取笔记
script.fetchNoteById(243);

4.11 设置变量与持久化变量

脚本设置变量:在脚本中定义 property,并通过名为 settingsVariables 的 property variant 数组注册,之后用户即可在脚本设置界面中配置这些变量:

// 先声明要在设置界面中暴露的变量
property string myString;
property string myStringSecret;
property bool myBoolean;
property string myText;
property int myInt;
property string myFile;
property string myDirectory;
property string mySelection;

// 注册设置变量(Qt 没有 QVariantHash,只能用 QVariantList 保证顺序)
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"},
    }
];

支持的 type 有:string(单行输入)、string-secret(密码输入)、boolean(复选框)、text(多行文本)、integer(数字)、file(文件选择)、directory(目录选择)、selection(下拉选择,配合 items 映射)。

还可以用 registerSettingsVariables() 函数在注册时动态改写默认值,例如根据操作系统调整:

function registerSettingsVariables() {
  if (script.platformIsWindows()) {
    // 覆盖 myFile 的默认值
    settingsVariables[3].default = "pandoc.exe";
  }
}

完整示例见 docs/scripting/examples/variables.qml。

持久化变量:跨脚本、跨会话保存数据(所有脚本全局可读),要求使用有意义的前缀作为键名以避免冲突:

void setPersistentVariable(const QString &key, const QVariant &value);
QVariant getPersistentVariable(const QString &key,
                               const QVariant &defaultValue);
// 保存持久化变量
script.setPersistentVariable("PersistentVariablesTest/myVar", result);

// 读取并记录持久化变量(不存在时返回默认值)
script.log(
  script.getPersistentVariable(
    "PersistentVariablesTest/myVar",
    "nothing here yet",
  ),
);

示例见 docs/scripting/examples/persistent-variables.qml。另有 getApplicationSettingsVariable(key, defaultValue) 可直接读取应用自身的设置项(例如 gitExecutablePath),注意设置项可能实际为空,defaultValue 仅在设置完全不存在时生效。

4.12 缓存目录

QString cacheDir(const QString &subFolder) const;   // 返回/创建脚本缓存目录(系统缓存位置下)
bool clearCacheDir(const QString &subFolder) const; // 清空缓存目录
// 为 my-script-id 创建缓存目录
var cacheDirForScript = script.cacheDir("my-script-id");
// 清空缓存
script.clearCacheDir("my-script-id");

4.13 平台判断与路径分隔符

bool platformIsLinux();
bool platformIsOSX();
bool platformIsWindows();
QString toNativeDirSeparators(QString path);   // "/" 转系统分隔符,如 Windows 返回 "c:\winnt\system32"
QString fromNativeDirSeparators(QString path); // 系统分隔符转 "/",如 Windows 返回 "c:/winnt/system32"
QString dirSeparator();                        // 返回系统目录分隔符 "/" 或 "\"
if (script.platformIsLinux()) {
  // 仅在 Linux 下执行
}

4.14 触发器与选择列表

void triggerMenuAction(QString objectName, QString checked);  // 触发菜单动作(可带选中状态约束)
QStringList selectedNotesPaths();                             // 所选笔记的路径列表
QList<int> selectedNotesIds();                                // 所选笔记的 ID 列表
// 切换只读模式
script.triggerMenuAction("actionAllow_note_editing");
// 关闭只读模式(仅当状态不同于 1 时触发)
script.triggerMenuAction("actionAllow_note_editing", 1);

// 获取所有选中笔记的路径
script.log(script.selectedNotesPaths());

菜单动作的对象名可在 src/mainwindow.ui 中按英文菜单标题搜索获取,该文本可能随时间变化。示例见 docs/scripting/examples/disable-readonly-mode.qml。

4.15 文件读写

bool fileExists(QString &filePath);                    // 检查文件是否存在
QString readFromFile(const QString &filePath,
                     const QString &codec = "UTF-8");  // 读取文件文本
bool writeToFile(const QString &filePath, const QString &data,
                 const bool createParentDirs = false); // 写入文件
if (script.fileExists(filePath)) {
  var data = script.readFromFile(filePath);
  script.log(data);
}

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

导出单文件 HTML 的 docs/scripting/examples/export-notes-as-one-html.qml 就大量使用了这些文件 API。

4.16 AI 补全、WebSocket 与跳转

AI 补全:向当前选中的 AI 模型(如 ChatGPT、Claude、Ollama 兼容后端)发送补全提示,需要在 AI 工具栏或主菜单中启用 AI 系统:

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

示例见 docs/scripting/examples/ai-autocompletion.qml。

WebSocket:可以用 WebSocketServer 让 QOwnNotes 被远程控制(示例见 docs/scripting/examples/websocket-server.qml),也可以用 WebSocket 连接外部 socket 服务(示例见 docs/scripting/examples/websocket-client.qml)。使用前提是系统已安装 Qt 的 QML websocket 库,例如 Ubuntu Linux 下需要 qml-module-qtwebsockets。

跳转到笔记/子文件夹:

void setCurrentNote(NoteApi *note, bool asTab = false);   // 将笔记设为当前笔记(可选在新标签打开)
bool jumpToNoteSubFolder(const QString &noteSubFolderPath,
                         const QString &separator = "/"); // 跳转到子文件夹
// 跳转到笔记
script.setCurrentNote(note);
// 在新标签打开(若尚未打开)
script.setCurrentNote(note, true);

// 跳转到笔记子文件夹 "a sub folder"
script.jumpToNoteSubFolder("a sub folder");
// 跳转到 "a sub folder" 下的 "sub" 子文件夹
script.jumpToNoteSubFolder("a sub folder/sub");

五、Hook 事件钩子:让脚本感知应用生命周期

Hook(钩子)是脚本系统最强大的部分:你在脚本中实现特定名称的函数,QOwnNotes 就会在对应事件发生时调用它。下表汇总了核心钩子及其触发时机(详细签名见 webpage/src/ko/scripting/hooks.md)。

钩子函数 触发时机 关键参数 典型应用
onNoteStored(note) 笔记写入磁盘后 note:被存储的笔记对象 记录/统计笔记变更(不可修改存储内容)
noteOpenedHook(note) 笔记打开后 note:被打开的笔记 显示通知、记录打开行为,见 docs/scripting/examples/on-note-opened.qml
noteDoubleClickedHook(note) 笔记被双击后 note:被点击的笔记 用外部程序打开笔记,见 docs/scripting/examples/external-note-open.qml
insertMediaHook(fileName, markdownText) 插入媒体文件到当前笔记时 源文件路径、Markdown 文本 改写插入的媒体 Markdown;多脚本时首个返回非空字符串者生效
insertAttachmentHook(fileName, markdownText) 插入附件时 源附件路径、Markdown 文本 改写附件 Markdown;规则同上
fetchUrlTitleHook(url) 链接对话框获取页面标题前 url 用自定义 CLI 抓取标题,见 docs/scripting/examples/fetch-url-title-with-kanboard-cli.qml
insertingFromMimeDataHook(text, html) Ctrl + Shift + V 粘贴 HTML/媒体时 MIME 数据文本与 HTML 转换粘贴内容,见 docs/scripting/examples/insert-headline-with-link-from-github-url.qml
handleNoteTextFileNameHook(note) 允许文件名异于标题时,笔记存储前 note 自定义笔记文件名,返回空串则不修改;见 docs/scripting/examples/use-tag-names-in-filename.qml
handleNoteNameHook(note) 笔记显示名称确定时 note 修改列表中显示的笔记名(文件名作名称时慎用)
handleNewNoteHeadlineHook(headline) 创建新笔记前 headline:拟定标题 笔记模板、自定义新笔记标题,见 docs/scripting/examples/custom-new-note-headline.qml
preNoteToMarkdownHtmlHook(note, markdown, forExport) Markdown 转 HTML 之前 原始 Markdown、是否导出 注入 LaTeX/Mermaid 渲染代码
noteToMarkdownHtmlHook(note, html, forExport) Markdown 转 HTML 之后 生成的 HTML、是否导出 修改预览/导出 HTML,见 docs/scripting/examples/preview-styling.qml
encryptionHook(text, password, decrypt) 需要加密/解密文本时 文本、密码、方向 接入自定义加密(Keybase/PGP/rot13),见 docs/scripting/examples/encryption-rot13.qml
noteTaggingHook(note, action, tagName, newTagName) 标签增/删/改名/列出时 action 为 add/remove/rename/list 自定义标签机制,见 docs/scripting/examples/note-tagging.qml
noteTaggingByObjectHook(note, action, tag, newTagName) 同上 但传 TagApi 对象,list 返回标签 ID 列表 基于完整标签树的标签机制,见 docs/scripting/examples/note-tagging-by-object.qml
callAutocompletionHook() 自动补全被调用时(如 Ctrl + Space) 无 返回要加入补全列表的字符串列表,见 docs/scripting/examples/autocompletion.qml
callHandleWebsocketRawDataHook(requestType, pageUrl, pageTitle, rawData, screenshotDataUrl) Web Companion 浏览器扩展通过右键菜单发送数据时 requestType 为 page 或 selection 将网页/选中内容写入笔记,见 docs/scripting/examples/websocket-raw-data-selection-in-note.qml
onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread) startDetachedProcess 的脚本线程执行完毕时 回调标识、结果、命令数组、线程信息 跟踪后台进程,见 docs/scripting/examples/callback.qml
windowStateChangedHook(windowState) 窗口状态变化后 minimized/maximized/fullscreen/active/nostate 响应窗口事件,见 docs/scripting/examples/window-state-changed.qml
layoutSwitchedHook(oldUuid, newUuid) 布局切换时 新旧布局 UUID 布局联动,见 docs/scripting/examples/layouts.qml
openAiBackendsHook() OpenAI 服务配置重载时(含脚本引擎重载) 无 提供自定义 ChatGPT API 兼容后端(OpenAI、Claude、Ollama 等),返回 {id, name, baseUrl, apiKey, models} 对象数组,见 docs/scripting/examples/custom-openai-backends.qml
highlightingHook(text, previousBlockState) 语法高亮时对每个文本块调用 当前块文本、上一块高亮状态 动态上下文感知高亮(注意:调用非常频繁,务必保持实现高效)

两个需要留意的性能与行为细节

  1. noteTaggingHook 的 list 动作非常频繁:每当笔记文件夹或标签树刷新时,list 都会对所有笔记执行一次。相关触发点在 src/mainwindow.cpp 的 reloadTagTree() 中。因此 list 实现必须足够快,否则会拖慢整个界面。
  2. highlightingHook 每次按键都会对可见文本块调用:如果只需要静态正则高亮,优先使用 addHighlightingRule,而不是这个钩子。

动态高亮与自定义高亮规则

除了 highlightingHook,还可以用 addHighlightingRule 直接注入正则高亮规则,并关联预定义的语法高亮状态:

void addHighlightingRule(const QString &pattern, const QString &shouldContain,
                         int state, int capturingGroup = 0, int maskedGroup = 0);

常用高亮状态编号(完整表见 webpage/src/ko/scripting/methods-and-objects.md):

名称 编号 名称 编号
NoState(无状态) -1 链接(Link) 0
图片(Image) 3 代码块(CodeBlock) 4
代码块注释 5 斜体(Italic) 7
粗体(Bold) 8 列表(List) 9
注释(Comment) 11 H1 – H6 12 – 17
块引用(BlockQuote) 18 水平线(HR) 21
表格(Table) 22 缩进代码块 23
掩码语法(MaskedSyntax) 24 当前行背景 25
断链(BrokenLink) 26 Frontmatter 块 27
尾随空格 28 复选框未选中/选中 29 / 30
St 下划线 31 WikiLink / WikiLinkBroken 32 / 33
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);

带自定义颜色与样式的规则:可以不受预定义状态限制,为自定义语法指定前景/背景色与字体样式(state 传 -1 表示仅用自定义格式):

void addHighlightingRule(const QString &pattern, const QString &shouldContain,
                         int state, int capturingGroup, int maskedGroup,
                         const QVariantMap &formatStyle);
// formatStyle 支持:foregroundColor、backgroundColor、bold、italic、underline、fontSize
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,
  });
}

更完整的示例见 docs/scripting/examples/highlighting.qml 与 docs/scripting/examples/custom-highlighting.qml。

自定义样式表与预览样式

可以通过 addStyleSheet 注入 Qt 样式表(QSS)修改整个应用的界面样式:

void addStyleSheet(QString stylesheet);
// 把笔记列表的文本放大
script.addStyleSheet("QTreeWidget#noteTreeWidget {font-size: 30px;}");
  • 各个窗口部件(widget)的名称可以从 *.ui 文件中获取,例如主窗口定义在 src/mainwindow.ui;几乎一切部件的基类都是 QWidget,例如 QWidget {background-color: black; color: white;} 会把所有背景置黑、前景置白。
  • 深色主题样式表 src/libraries/qdarkstyle/style.qss 是很好的样式参考。
  • 若要改变笔记预览(HTML 预览)的样式,则应使用 noteToMarkdownHtmlHook(docs/scripting/examples/preview-styling.qml),而不是 addStyleSheet。

六、官方脚本示例资源速查

仓库中的 docs/scripting/examples 目录提供了 40 余个可直接运行的官方示例脚本,是学习脚本开发的最佳起点。按场景分类推荐:

学习目标 参考示例
基础结构与生命周期 example.qml、on-note-opened.qml
自定义动作与外部程序 custom-actions.qml、callback.qml、execute-command-after-note-update.qml
标签体系 note-tagging.qml、note-tagging-by-object.qml、favorite-note.qml、use-tag-names-in-filename.qml
预览与渲染 preview-styling.qml、custom-stylesheet.qml
语法高亮 highlighting.qml、custom-highlighting.qml
加密 encryption-keybase.qml、encryption-pgp.qml、encryption-rot13.qml
媒体与粘贴 paste-latex-image.qml、scribble.qml、paste-full-image-url.qml、insert-headline-with-link-from-github-url.qml
自动补全与 AI autocompletion.qml、ai-autocompletion.qml、custom-openai-backends.qml
WebSocket 与浏览器集成 websocket-server.qml、websocket-client.qml、websocket-raw-data-selection-in-note.qml
对话框与交互 input-dialogs.qml、scripting-label-demo.qml
导出与批量处理 export-notes-as-one-html.qml、external-note-diff.qml
工具与数据 variables.qml、persistent-variables.qml、unique-note-id.qml、weather-stats.qml

结合上文列出的源码入口(scriptingservice.h、scriptingservice.cpp、noteapi.h、tagapi.h),你既可以照着示例直接改出自己的脚本,也可以深入底层理解每个 API 的实现细节。把这些脚本放进 Scripting settings 并勾选启用后,QOwnNotes 的编辑、预览、标签、导出与外部工具集成就全部掌握在你手中了。

登录后查看全文
QOwnNotes