QOwnNotes 脚本 API 完全指南:script 对象方法、对象类型与脚本设置变量实战解析

原创2026-10-14 07:18:571,984 阅读
文章标签:桌面应用知识管理富文本插件系统跨平台

QOwnNotes 脚本 API 完全指南:script 对象方法、对象类型与脚本设置变量实战解析

本指南以 QOwnNotes 官方脚本文档《Métodos y objetos que proporciona QOwnNotes》(即 webpage/src/es/scripting/methods-and-objects.md)为骨架,系统讲解 QML 脚本中可用的 script 对象方法、NoteApi/TagApi/NoteSubFolderApi 等对象类型,以及 settingsVariables 脚本设置变量的完整定义方式。读完本文,你将能够编写从"后台启动外部程序"到"自定义语法高亮"、从"AI 补全"到"WebSocket 远程控制"的各类 QOwnNotes 脚本,并能在源码层理解每个 API 的底层实现与适用场景。

前置知识:脚本如何加载与运行

QOwnNotes 的脚本本质上是运行在 Qt QML 引擎中的 JavaScript 文件(详见 webpage/src/es/scripting/README.md)。脚本文件以 import QtQml 2.0 和 import QOwnNotesTypes 1.0 开头,并声明一个 Script {} 或 QtObject {} 根对象:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    function init() {
        script.log("Hello world!");
    }
}
  • 脚本文件可放在任意位置,在 脚本设置(Scripting settings)中通过"添加脚本 / 添加本地脚本"按钮加载,也可以从 脚本仓库(Script repository)直接安装。
  • init() 在脚本引擎初始化时被调用,是所有注册类操作(自定义动作、标签、高亮规则等)的推荐入口。
  • 所有 script.* 方法都由 src/services/scriptingservice.h 中的 ScriptingService 类以 Q_INVOKABLE 暴露给 QML,因此文档中所有方法签名均与源码一一对应。

下面按功能域逐一讲解这些方法与对象。

一、进程与外部程序执行

1. 后台启动外部程序:startDetachedProcess

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

对应源码声明见 src/services/scriptingservice.h:

参数 说明
executablePath 可执行文件的路径
parameters 参数列表(QStringList)
callbackIdentifier 回调标识符,用于在 onDetachedProcessCallback() 中区分进程(可选)
callbackParameter 传递给回调的附加参数,常用于循环计数等场景(可选)
processData 使用回调时要写入进程的数据(可选)
workingDirectory 进程的工作目录(可选,仅在无回调时生效)

返回 true 表示启动成功。最简单的用法:

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

批量启动并借助回调统计进度(完整示例见 docs/scripting/examples/callback.qml):

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

onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread) 是配套的钩子函数(详见 hooks 文档):

  • callbackIdentifier:调用 startDetachedProcess() 时提供的标识符;
  • resultSet:进程输出结果;
  • cmd:完整命令数组,[0] 为可执行文件路径、[1] 为参数、[2] 为退出码;
  • thread:线程信息数组,[0] 为传入的 callbackParameter,[1] 为该标识符下剩余线程数(thread[1]==0 可用来判断一批进程是否全部结束)。

回调机制的意义在于释放 UI 线程:大量耗时进程在后台线程执行,界面不卡顿。更多参考:custom-actions.qml、execute-command-after-note-update.qml(在 onNoteStored 钩子中对外部程序做处理)。

2. 同步启动外部程序并等待输出:startSynchronousProcess

QByteArray startSynchronousProcess(QString executablePath, QStringList parameters,
                                   QByteArray data, QString workingDirectory);

源码见 src/services/scriptingservice.h,四个参数全部可选默认值。它阻塞等待进程结束并返回其输出文本:

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

经典实战:用外部命令做笔记加解密。示例 docs/scripting/examples/encryption-keybase.qml 通过 encryptionHook(text, password, decrypt) 调用 keybase 命令行工具:

function encryptionHook(text, password, decrypt) {
  var param = decrypt ? ["decrypt"] : ["encrypt", "pbek"];
  var result = script.startSynchronousProcess("/usr/bin/keybase", param, text);
  return result;
}

3. 平台检测:platformIsLinux / platformIsOSX / platformIsWindows

bool platformIsLinux();
bool platformIsOSX();
bool platformIsWindows();

用于编写跨平台脚本,例如根据操作系统选择可执行文件后缀:

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

二、笔记访问与定位

4. 获取当前笔记文件夹路径:currentNoteFolderPath

QString currentNoteFolderPath();

返回当前笔记文件夹的绝对路径,常用于拼装媒体/附件路径(见 docs/scripting/examples/absolute-media-links.qml):

var path = script.currentNoteFolderPath();

5. 获取当前笔记对象:currentNote

NoteApi* currentNote();

返回类型为 NoteApi(完整属性/方法见 classes 文档),可用 note.name、note.fileName、note.noteText、note.fullNoteFilePath 等属性,以及 renameNoteFile()、addTag()、toMarkdownHtml() 等方法:

var note = script.currentNote();
script.log(note.fullNoteFilePath);

6. 跳转到笔记 / 跳转到子文件夹

void setCurrentNote(NoteApi *note, bool asTab = false);
bool jumpToNoteSubFolder(const QString &noteSubFolderPath, QString separator);
  • setCurrentNote:将指定笔记设为当前笔记(需在笔记列表中可见);asTab = true 时在新标签页打开(若尚未打开)。示例见 journal-entry.qml。
  • jumpToNoteSubFolder:按相对当前笔记文件夹的路径跳转,separator 默认 /:
script.jumpToNoteSubFolder("a subfolder");
script.jumpToNoteSubFolder("a subfolder/sub");

在子文件夹内新建笔记文件夹可配合 mainWindow.createNewNoteSubFolder(见 classes 文档示例)。

7. 通过文件名 / ID 获取笔记

NoteApi* fetchNoteByFileName(QString fileName, int noteSubFolderId = -1);
NoteApi* fetchNoteById(int id);
bool noteExistsByFileName(QString fileName, int ignoreNoteId = 0, int noteSubFolderId = -1);

源码默认值见 src/services/scriptingservice.h。用法:

var note = script.fetchNoteByFileName("my note.md");
var note2 = script.fetchNoteById(243);
script.noteExistsByFileName("my note.md", note.id); // 检查存在性,忽略当前 note

noteExistsByFileName 的典型场景是避免重复创建同名笔记(见 use-tag-names-in-filename.qml)。

8. 按文本搜索笔记 ID

QList<int> fetchNoteIdsByNoteTextPart(QString text);

QML 中无法直接传递 QList<NoteApi*>,因此返回笔记 ID 列表,再配合 fetchNoteById() 取回笔记对象:

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

noteIds.forEach(function (noteId){
  var note = script.fetchNoteById(noteId);
  // 对笔记做进一步处理
});

参考实现示例:unique-note-id.qml。

9. 获取选中的笔记

QStringList selectedNotesPaths();
QList<int> selectedNotesIds();

分别返回所有选中笔记的文件路径列表与 ID 列表,适合批量导出/批量处理(见 external-note-diff.qml、export-notes-as-one-html.qml)。

三、日志、消息框与输入对话框

10. 写日志:log

void log(QString text);

输出到日志面板(在菜单 窗口 / 面板 中开启)。这是脚本调试最基本的手段:

script.log("my text");

11. 信息框与询问框

void informationMessageBox(QString text, QString title);
int questionMessageBox(QString text, QString title, int buttons, int defaultButton);

questionMessageBox 的 buttons 使用 Qt QMessageBox::StandardButton 枚举的位或组合(如 0x01000000|0x02000000 表示 Yes|No),返回被点击按钮的 ID:

var result = script.questionMessageBox(
  "The text I want to show",
  "Some optional title",
  0x01000000|0x02000000,
  0x02000000,
);
script.log(result);

12. 文件打开 / 保存对话框

QString getOpenFileName(QString caption, QString dir, QString filter);
QString getSaveFileName(QString caption, QString dir, QString filter);

三个参数均可选。filter 使用 Qt 过滤器语法(如 "Images (*.png *.xpm *.jpg)"):

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

var outFile = script.getSaveFileName(
  "Select the HTML file to save",
  "output.html",
  "HTML (*.html)",
);

13. 输入对话框三件套

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 inputDialogGetMultiLineText(const QString &title, const QString &label, const QString &text);

分别对应下拉选择、单行输入、多行输入;点击"取消"或按 Escape 时返回空字符串,可作为取消判据:

var result = script.inputDialogGetItem("combo box", "Please select an item", [
  "Item 1", "Item 2", "Item 3",
]);
if (result == "") { /* 用户取消 */ }

更多组合用法见 input-dialogs.qml。

14. 文本差异对话框:textDiffDialog

QString textDiffDialog(const QString &title, const QString &label,
                       const QString &text1, const QString &text2);

text2 是对话框中可编辑的一侧,返回编辑后的结果;取消或按 Escape 返回空串。官方文档给出的实战组合是"AI 翻译 + 差异对比":

const text = script.noteTextEditSelectedText();
const promptAI = "Translate the text to english";
const resultAI = script.aiComplete(promptAI + ":\n\n" + text);

var result = script.textDiffDialog(
  "AI text tool",
  "Resulting text",
  text,
  resultAI,
);
script.log(result);

四、笔记编辑器操作

以下方法围绕笔记编辑器(noteTextEdit)的光标与选区进行读写,全部用于"文本转换类"脚本。

15. 写入、读取与选区控制

void noteTextEditWrite(QString text);
QString noteTextEditSelectedText();
void noteTextEditSelectAll();
void noteTextEditSelectCurrentLine();
void noteTextEditSelectCurrentWord();
void noteTextEditSetSelection(int start, int end);
int noteTextEditSelectionStart();
int noteTextEditSelectionEnd();
  • noteTextEditWrite:在当前光标位置写入文本;与 noteTextEditSelectAll() 组合可整体覆盖当前笔记内容。
  • noteTextEditSelectedText:读取选中文本。ROT13 转换是教科书式用法(见 custom-actions.qml 的 transformTextRot13 动作)。
  • 选区可以扩展:noteTextEditSetSelection(start - 1, end + 1) 把选区向外扩一个字符。

16. 光标定位与读取

void noteTextEditSetCursorPosition(int position);
int noteTextEditCursorPosition();

0 表示笔记开头;特殊值 -1 表示笔记末尾:

script.noteTextEditSetCursorPosition(10); // 跳到第 11 个字符
script.noteTextEditSetCursorPosition(-1); // 跳到笔记末尾

17. 当前词与当前块

QString noteTextEditCurrentWord(bool withPreviousCharacters = false);
QString noteTextEditCurrentBlock();
  • noteTextEditCurrentWord(true):额外包含词前的非单词字符(如 @)。autocompletion 示例正是用它抓取 @用户名 前缀再做标签补全(见 autocompletion.qml)。
  • noteTextEditCurrentBlock():读取当前行/块(Markdown 段落)。AI 补全示例用它抓取整行交给模型续写(见 ai-autocompletion.qml)。

五、剪贴板操作

QString clipboard(bool asHtml = false);
void setClipboardText(QString text, bool asHtml = false);
  • clipboard() 读取剪贴板(文本或 HTML)。
  • setClipboardText() 写入剪贴板(asHtml = true 时写入 HTML MIME 数据)。

实战:把 Markdown 选区转换成 BBCode 再复制走(见 selected-markdown-to-bbcode.qml)。

六、媒体、附件与预览

18. 下载 URL

QString downloadUrlToString(QUrl url);
QString downloadUrlToMedia(QUrl url, bool returnUrlOnly = false);
  • downloadUrlToString:把 URL 内容下载为字符串(如抓取网页标题,见 insert-headline-with-link-from-github-url.qml)。
  • downloadUrlToMedia:把 URL 下载到媒体文件夹,默认返回相对当前笔记的 Markdown 图片文本;returnUrlOnly = true 时只返回 URL。LaTeX 公式转图片是经典用法(见 paste-latex-image.qml):
var markdown = script.downloadUrlToMedia(
  "http://latex.codecogs.com/gif.latex?\frac{1}{1+sin(x)}",
);

19. 插入媒体文件与附件

QString insertMediaFile(QString mediaFilePath, bool returnUrlOnly = false);
QString insertAttachmentFile(const QString &attachmentFilePath,
                             const QString &fileName, bool returnUrlOnly);
  • insertMediaFile:把本地文件复制进媒体文件夹,返回 Markdown 图片文本或 URL。
  • insertAttachmentFile:把文件放入 attachments 附件文件夹,返回附件 Markdown 或 URL。

scribble 示例完整演示了"插入涂鸦模板图 + 交给外部编辑器 + 刷新预览"的链路(见 scribble.qml):

var mediaFile = script.insertMediaFile(imagePath, true);
script.noteTextEditWrite("scribble\n");

20. 重新生成预览

void regenerateNotePreview();

同步执行外部编辑器改图后调用,强制刷新笔记预览(见 scribble.qml 中 startSynchronousProcess 之后的调用)。

七、自定义动作、标签与脚本面板

21. 注册自定义动作:registerCustomAction

void registerCustomAction(QString identifier, QString menuText, QString buttonText,
                          QString icon, bool useInNoteEditContextMenu,
                          bool hideButtonInToolbar, bool useInNoteListContextMenu);

源码默认值见 src/services/scriptingservice.h。参数语义:

参数 说明
identifier 动作标识符
menuText 菜单中显示的文本
buttonText 按钮文本,留空则不显示按钮
icon 图标文件路径,或 freedesktop 主题图标名(如 "task-new")
useInNoteEditContextMenu 是否出现在笔记编辑器右键菜单(默认 false)
hideButtonInToolbar 是否在自定义动作工具栏隐藏按钮(默认 false)
useInNoteListContextMenu 是否出现在笔记列表右键菜单(默认 false)

在 init() 中注册,并实现 customActionInvoked(identifier) 接收触发:

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

完整版见 custom-actions.qml。两点补充:

  • 快捷键:可以在 快捷键设置 中为自定义动作绑定本地/全局快捷键。
  • 命令行触发:应用启动后可用 --action customAction_<identifier> 直接触发某个自定义动作(见 CLI 参数文档)。
  • 图标提醒:freedesktop 主题图标在 Linux 上最全;macOS/Windows 建议用 scriptDirPath(见下文)定位脚本自带图标文件。

22. 触发菜单动作:triggerMenuAction

void triggerMenuAction(QString objectName, QString checked);

objectName 是动作对象名,可从 src/mainwindow.ui 中按英文菜单标题查到(这些名称可能随版本变化)。checked 可选:传入 0/1 时仅当动作当前选中状态与此参数不同才触发(即可靠地"启用"或"禁用"开关):

script.triggerMenuAction("actionAllow_note_editing"); // 切换只读模式
script.triggerMenuAction("actionAllow_note_editing", 1); // 禁用只读模式

示例见 disable-readonly-mode.qml。

23. 标签操作

void tagCurrentNote(QString tagName);
TagApi* getTagByNameBreadcrumbList(const QStringList &nameList, bool createMissing = true);
QStringList searchTagsByName(QString name);
  • tagCurrentNote:给当前笔记打标签(如收藏,见 favorite-note.qml)。
  • getTagByNameBreadcrumbList:按面包屑路径逐级创建/获取标签,createMissing 默认 true 表示自动创建缺失标签;返回最深一层标签的 TagApi 对象:
// 创建 level1 > level2 > level3 三级标签,返回 level3 的标签对象
var tag = script.getTagByNameBreadcrumbList(["level1", "level2", "level3"]);
  • searchTagsByName:按子串搜索标签名,返回名称列表(ignoreAccents 可忽略重音)。autocompletion 示例用它做 @ 触发式标签补全。

24. 脚本标签(Scripting labels):registerLabel / setLabelText

void registerLabel(QString identifier, QString text);
void setLabelText(QString identifier, QString text);

标签显示在脚本面板(窗口 / 面板 中开启)中,支持纯文本或 HTML(文本可选、链接可点击):

script.registerLabel(
  "html-label",
  "HTML text <strong>strong</strong> <br />with three lines<br />and a <a href='https://www.qownnotes.org'>link to a website</a>.",
);
script.registerLabel("long-label", "another very long text that will wrap");
script.registerLabel("counter-label"); // 先注册,再用 setLabelText 更新

定时刷新的完整演示见 scripting-label-demo.qml(用 QML Timer 每秒更新计数标签)。

补充:脚本标签里的链接同时支持外部链接与内部链接(笔记、任务、卡片等),其解析逻辑可在 src/utils/urlhandler.cpp 中查看。

八、笔记创建

void createNote(QString text);

文本中第一个标题行会被用作笔记文件名(若未关闭"标题决定文件名"选项):

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

若已关闭该选项,则需手动重命名文件(使用 NoteApi.renameNoteFile,见 classes 文档):

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

custom-actions.qml 中的 createMeetingNote 动作完整演示了"用时间戳生成标题 → 拼接正文 → createNote"的会议纪要流程。

九、AI 补全

QString aiComplete(const QString& prompt);

对当前选中的 AI 模型(如 ChatGPT、Claude,或 Ollama 等本地系统)发起一次补全请求并返回结果。前提:需要在 AI 工具栏或主菜单中启用 AI 系统。示例 ai-autocompletion.qml 把当前段落交给模型续写:

var text = script.aiComplete("Tell me, how are you feeling today?");

可以与其他 API 组合出强大工作流,例如上文 textDiffDialog 的"选区翻译 + 差异对比"。

十、自定义样式表

void addStyleSheet(QString stylesheet);

给整个应用注入 Qt 样式表(QSS),例如放大笔记列表字体:

script.addStyleSheet("QTreeWidget#noteTreeWidget {font-size: 30px;}");

深化要点:

  • Widget 名称可从 *.ui 文件中获取,主窗口见 src/mainwindow.ui;几乎一切控件都继承自 QWidget,所以 QWidget {background-color: black; color: white;} 会全局生效。
  • 参考样式:内置暗色主题的 src/libraries/qdarkstyle/style.qss 是很好的样式清单。
  • 若想改变预览视图的样式,应使用 noteToMarkdownHtmlHook(见 hooks 文档),而不是 addStyleSheet。
  • 完整示例见 custom-stylesheet.qml。

十一、脚本设置变量:settingsVariables

要让用户能在脚本设置中配置脚本参数,需做两件事:

  1. 声明同名 property,脚本运行时即可直接读取;
  2. 在 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 a 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 单行输入 default
string-secret 密码输入 —
boolean 复选框 text(复选说明)、default
text 多行文本 default
integer 数字选择 default
file 文件选择器 default
directory 目录选择器 default
selection 下拉选择 default、items({值: 显示文本} 映射)

文档注释提到:Qt 没有 QVariantHash,只能使用 QVariantMap(无任意顺序)或 QVariantList(可保持任意顺序),因此 settingsVariables 用数组声明以保留书写顺序。该逻辑与 src/services/scriptingservice.h 中的 registerSettingsVariables() 私有方法对应。

动态覆盖默认值:registerSettingsVariables()

如需按操作系统等条件动态修改默认值,可定义 registerSettingsVariables() 函数(在变量注册后回调):

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

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

十二、持久变量与应用设置

持久变量:setPersistentVariable / getPersistentVariable

void setPersistentVariable(const QString &key, const QVariant &value);
QVariant getPersistentVariable(const QString &key, const QVariant &defaultValue);

持久变量对所有脚本全局可见,因此键名必须使用有意义的前缀(如 PersistentVariablesTest/myVar)。getPersistentVariable 的 defaultValue 仅在键不存在时返回:

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

对应实现示例:persistent-variables.qml。源码中可见其底层存储前缀常量 PERSISTENT_VARIABLE_SETTINGS_PREFIX = "PersistentScripting"(见 src/services/scriptingservice.h)。

应用设置变量:getApplicationSettingsVariable

QVariant getApplicationSettingsVariable(const QString &key, const QVariant &defaultValue);

读取 QOwnNotes 自身设置项(如 gitExecutablePath):

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

注意:设置值可能实际为空,此时 defaultValue 并不会生效(它只在键完全不存在时返回),需自行判空处理。

十三、缓存目录

QString cacheDir(const QString &subDir) const;
bool clearCacheDir(const QString &subDir) const;

在系统标准缓存位置为脚本创建/清理专属子目录,适合存放临时下载或派生文件:

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

十四、脚本目录路径:scriptDirPath

通过声明 property string scriptDirPath; 即可在脚本运行时获得脚本自身所在目录,用于加载同目录资源文件、定位图标等:

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    // 脚本目录路径会被自动写入该属性
    property string scriptDirPath;

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

scribble.qml 中的设置变量 "default": scriptDirPath + "/scribble.png" 正是利用它定位模板图片(见 scribble.qml)。

十五、路径分隔符工具

QString toNativeDirSeparators(QString path);
QString fromNativeDirSeparators(QString path);
QString dirSeparator();

用于跨平台路径转换:

  • toNativeDirSeparators("c:/winnt/system32") 在 Windows 返回 "c:\winnt\system32";
  • fromNativeDirSeparators("c:\\winnt\\system32") 返回 "c:/winnt/system32";
  • dirSeparator() 返回原生目录分隔符(Windows 为 \,其余为 /)。

十六、文件读写

bool fileExists(QString &filePath);
QString readFromFile(const QString &filePath, const QString &codec = "UTF-8");
bool writeToFile(const QString &filePath, const QString &data, bool createParentDirs = false);
  • readFromFile 第二个参数 codec 指定编码,默认 UTF-8;文件不存在时返回 null。
  • writeToFile 的 createParentDirs = true 可自动创建父目录。批量导出 HTML 的完整链路见 export-notes-as-one-html.qml:
if (script.fileExists(filePath)) {
  var data = script.readFromFile(filePath);
  script.log(data);
}

script.writeToFile(filePath, html);

十七、WebSocket 远程控制

脚本可通过 WebSocketServer 暴露端口,实现远程控制 QOwnNotes;也可用 WebSocket 作为客户端连接外部服务:

  • 服务端:绑定固定端口(如 35345),在 onClientConnected 中收发消息(见 websocket-server.qml)。
  • 客户端:连接 ws://echo.websocket.org 等地址做回显测试(见 websocket-client.qml)。
import QtWebSockets 1.1

WebSocketServer {
    port: 35345
    listen: true
    // onClientConnected / onErrorStringChanged 处理收发与异常
}

环境要求:需要 Qt 的 QML websocket 模块;Ubuntu Linux 下安装 qml-module-qtwebsockets 即可。WebSocket 的传输层实现与 QOwnNotes 的服务端服务可对照 src/services/websocketserverservice.h。

十八、编辑器自定义高亮

基于预定义状态的规则:addHighlightingRule(5 参数版本)

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

参数含义:

参数 说明
pattern 要高亮的正则表达式
shouldContain 高亮文本中必须包含的字符串,用于加速正确匹配
state 使用的高亮状态(见下表)
capturingGroup 用于高亮的捕获组(默认 0,即整段匹配)
maskedGroup 用于掩码的捕获组(默认 0)

预定义状态编号表(来自官方文档,与 QOwnNotesMarkdownHighlighter 对应):

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

示例(完整版见 highlighting.qml):

// 把 "BLOCK: some text" 整行按引用块(state 18)高亮
script.addHighlightingRule("^BLOCK: (.+)", "BLOCK:", 18);

// 掩码(state 24)一行中超过 32 个字符的部分
// capturingGroup 1 表示高亮第一个括号捕获的表达式
// maskedGroup -1 表示不做掩码
script.addHighlightingRule("^.{32}(.+)", "", 24, 1, -1);

带自定义格式的规则:addHighlightingRule(6 参数版本)

void addHighlightingRule(const QString &pattern, const QString &shouldContain,
                         int state, int capturingGroup, int maskedGroup,
                         const QVariantMap &formatStyle);

formatStyle 支持:foregroundColor(前景色,名称或 #rrggbb)、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,
  });

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

更多进阶示例见 custom-highlighting.qml。若需要超越静态正则的上下文感知动态高亮,可进一步使用 highlightingHook(text, previousBlockState) 钩子(同样在 highlighting.qml 中演示,返回带 start/length/颜色/字重等属性的高亮区间数组)。

十九、引擎重载

void reloadScriptingEngine();

重新加载脚本引擎,使脚本改动立即生效:

script.reloadScriptingEngine();

附:API 全景速查

以下方法均已在 src/services/scriptingservice.h 中以 Q_INVOKABLE 声明,可通过 script.xxx() 在 QML 中直接调用:

  • 进程:startDetachedProcess、startSynchronousProcess
  • 笔记/文件夹:currentNoteFolderPath、currentNote、setCurrentNote、jumpToNoteSubFolder、fetchNoteByFileName、fetchNoteById、noteExistsByFileName、fetchNoteIdsByNoteTextPart、selectedNotesPaths、selectedNotesIds、createNote
  • 编辑器:noteTextEditWrite、noteTextEditSelectedText、noteTextEditSelectAll、noteTextEditSelectCurrentLine、noteTextEditSelectCurrentWord、noteTextEditSetSelection、noteTextEditSelectionStart、noteTextEditSelectionEnd、noteTextEditSetCursorPosition、noteTextEditCursorPosition、noteTextEditCurrentWord、noteTextEditCurrentBlock
  • 剪贴板:clipboard、setClipboardText
  • 媒体:downloadUrlToString、downloadUrlToMedia、insertMediaFile、insertAttachmentFile、regenerateNotePreview
  • UI:log、informationMessageBox、questionMessageBox、getOpenFileName、getSaveFileName、inputDialogGetItem、inputDialogGetText、inputDialogGetMultiLineText、textDiffDialog、registerLabel、setLabelText
  • 动作:registerCustomAction、triggerMenuAction
  • 标签:tagCurrentNote、getTagByNameBreadcrumbList、searchTagsByName
  • 样式:addStyleSheet
  • 设置/存储:setPersistentVariable、getPersistentVariable、getApplicationSettingsVariable、cacheDir、clearCacheDir
  • 平台/路径:platformIsLinux、platformIsOSX、platformIsWindows、toNativeDirSeparators、fromNativeDirSeparators、dirSeparator
  • 文件:fileExists、readFromFile、writeToFile
  • AI 与高亮:aiComplete、addHighlightingRule(两种重载)、reloadScriptingEngine

配套对象类型(NoteApi、TagApi、NoteSubFolderApi)的完整属性与方法清单见 webpage/src/es/scripting/classes.md,各类钩子函数的签名与时机见 webpage/src/es/scripting/hooks.md。

结语

QOwnNotes 的脚本 API 覆盖面极广:从进程调度、笔记/标签管理到编辑器选区操控,从消息对话框到 WebSocket 远程控制,再到基于正则与自定义格式的语法高亮,足以支撑"自动化工作流"级别的脚本。建议以 docs/scripting/examples 目录下的示例为起点,结合本文的源码路径逐一验证每个 API 的签名与默认值,再按 settingsVariables 模式把可配置项暴露给用户,即可写出专业、健壮且可分享的 QOwnNotes 脚本。

登录后查看全文
QOwnNotes