Quarto 源码内 Lua 过滤器开发规范:过滤器链、自定义节点与模块加载全解析

原创2026-10-10 23:55:581,820 阅读
文章标签:开发工具文档

Quarto 源码内 Lua 过滤器开发规范:过滤器链、自定义节点与模块加载全解析

本文聚焦 quarto-cli 仓库中 Lua 过滤器(filter)体系的开发约定,覆盖 src/resources/filters/ 与 src/resources/pandoc/datadir/ 下全部过滤器源码的编写范式。阅读本文后,你将掌握:import() / require() 与 _quarto.modules 注册表的正确用法、自定义 AST 节点的遍历与改写模式、_quarto.format 格式检测的时机陷阱、option() / param() 参数读取、日志与外部命令执行约定,以及如何向 main.lua 过滤器链中安全地注册新过滤器并利用 flags 做性能剪枝。

一、过滤器体系全景:qmd 自定义 Reader 是一个特例

Quarto 的文档处理管道由两大部分组成:

  1. qmd 自定义 Reader:src/resources/pandoc/datadir/readqmd.lua(以及入口 src/resources/filters/qmd-reader.lua)是 Quarto 自定义的 Pandoc reader,而不是 filter。它在解析之前运行,位于独立于过滤器链的 Lua 上下文中——filter 侧的全局状态(例如 crossref.categories)在这里不存在,它通过文档元数据(metadata)和 param(...) 与过滤器通信。
  2. 过滤器链:由 src/resources/filters/main.lua 驱动的 INIT → NORMALIZE → PRE → CROSSREF → LAYOUT → POST → FINALIZE 多阶段管道。

两个阶段遵循各自独立的约定:本文的约定针对过滤器管道,而 reader 遵循自己的模式(raw-text 的 escape-then-restore 机制)。在改动 reader 阶段的代码前,务必先阅读 llm-docs/qmd-reader-architecture.md——其中说明了 reader 如何在 Pandoc 解析前看到原始文本,以及 Quarto 如何通过 src/command/render/pandoc.ts 无条件安装该 reader 并把用户原有的 from 值保存为 user-defined-from 参数。

二、模块加载约定

2.1 过滤器文件用 import(),模块用 require()

main.lua 通过 import()(一个 dofile() 的薄封装)加载几乎全部过滤器文件;而 modules/ 目录下的公共模块则应通过 require() 按需引入:

-- ✅ 正确:从 main.lua 导入过滤器文件
import("./quarto-pre/shortcodes.lua")

-- ❌ 错误:require 只用于模块
require("./quarto-pre/shortcodes")

-- ✅ 正确:模块来自 modules/
local patterns = require("modules/patterns")
local md = require("modules/md")

-- ❌ 错误:对模块使用 import
import("./modules/patterns.lua")

2.2 import() 文件内优先使用 _quarto.modules 注册表

这里有一个非常关键、且反复踩坑的机制:打包分发构建会把所有 import() 的文件文本级联(textual concatenation)进同一个共享 Lua chunk(见 package/src/common/package-filters.ts 的 buildFilter()),因此每个文件顶层声明的 local(包括 local x = require("modules/y"))都会与所有内联文件合并竞争 Lua 硬性的 单函数 200 个 local 变量上限。

modules/import_all.lua 已经用一个全局表赋值把大多数 modules/* 注册进了 _quarto.modules(如 _quarto.modules.constants、_quarto.modules.patterns、_quarto.modules.path),而这个注册本身零额外 local 成本。因此,在 import() 引入的文件中应直接引用 _quarto.modules.<name>.<fn>(...),而不是新增顶层 local <name> = require("modules/<name>"):

-- ✅ 正确:零 local 成本
local pattern = _quarto.modules.patterns.html_table

-- ❌ 错误:在 import() 文件里新增顶层 local,挤占 200 上限
local patterns = require("modules/patterns")

注意:该规则不适用于通过 require() 加载的文件本身——它们拥有独立的 chunk,不受影响。完整机制与历史复现记录(包括 199/200 余量告急、三次独立复发修复案例)参见 llm-docs/lua-filter-bundle-local-limit.md。

三、自定义节点(Custom Nodes)模式

Quarto 在 Pandoc AST 之上实现了一套仿真自定义 AST:自定义节点(如 Callout、FloatRefTarget、Shortcode)在物理上仍是 Div/Span(通过 attributes.__quarto_custom、__quarto_custom_type、__quarto_custom_id 标记),但语义上不是普通 Div/Span。相关实现见 src/resources/filters/ast/customnodes.lua。

3.1 遍历一律使用 _quarto.ast.walk()

普通 pandoc.walk_block(div, filter) 会把自定义节点当成普通 Div 处理,从而漏掉自定义语义。必须使用 _quarto.ast.walk()(其内部即 run_emulated_filter,会自动解析自定义节点并回调正确的处理函数):

-- ✅ 正确:处理自定义节点
doc = _quarto.ast.walk(doc, {
  Callout = function(callout)
    -- 处理 callout
  end
})

-- ❌ 错误:会漏掉自定义节点
pandoc.walk_block(div, filter)

3.2 节点类型判断:is_custom_node / is_regular_node

-- 判断是否为指定类型的自定义节点
if is_custom_node(node, "Callout") then
  -- 处理 callout 自定义节点
end

-- 判断是否为普通 Pandoc 节点(明确排除自定义节点)
if is_regular_node(node, "Div") then
  -- 处理普通 Div
end

-- 通过 is_custom_node 标志判断
if node.is_custom_node then
  -- 这是某种自定义节点
end

在 src/resources/filters/ast/customnodes.lua 中可以看到二者的实现差异:is_regular_node 会先检查 attributes.__quarto_custom == "true" 并返回 false,确保自定义节点永远不被当作普通节点处理。

3.3 使用 quarto.utils.match() 做 AST 结构匹配

quarto.utils.match()(定义于 src/resources/pandoc/datadir/_utils.lua)用于对 AST 节点做安全的结构化检查。它内部处理 nil / 空 content 的情况——无需手写 length 或 nil 防护。这在 Lua 中尤其重要,因为空表的 # 是 0(truthy):

-- ✅ 正确:安全,自动处理空内容
if quarto.utils.match("[1]/BulletList")(b) then ...

-- ❌ 错误:空内容时崩溃(0 在 Lua 中是 truthy)
if #b.content and b.content[1].t == "BulletList" then ...

-- ❌ 脆弱:手写 nil 防护,冗长
if #b.content > 0 and b.content[1].t == "BulletList" then ...

选择器语法(从 _utils.lua 的 match() 实现可见其完整解析逻辑)支持:

语法 含义 示例
/ 子节点遍历 "Figure/[1]/Plain/[1]/Image"
[n] 第 n 个子节点 "[1]/BulletList"
{Type} 捕获节点(返回列表) "[1]/{Plain}"
:child 直接子节点搜索(类似 CSS >) ".cell-output-display/:child/{Para}"
:descendant 后代搜索(类似 CSS 空格) "Div/:descendant/Para"
.class / #id CSS 式类名 / id 匹配 ".cell-output-display"、"#fig-id"
-- 检查嵌套结构
quarto.utils.match("Figure/[1]/Plain/[1]/Image")(fig)

-- 捕获匹配节点(以列表返回)
quarto.utils.match("[1]/{Plain}")(content)

-- 在直接子节点中按类名搜索
quarto.utils.match(".cell-output-display/:child/{Para}")(div)

返回值语义:match() 匹配成功返回节点,失败返回 false(而非 nil)。作为布尔守卫这没问题(false 是 falsy);但若把结果当作元素使用,必须检查 if not result——绝不能写 if result == nil,否则 false 会被漏过并传入 Pandoc 构造函数,触发 “Inline-ish expected, got boolean” 错误。

此外,_utils.lua 的实现注释还提醒::descendant 基于 walk 实现,效率不高,同一个 match 中重复调用 :descendant 会较慢。优先使用 match() 而非手写 .content[1].t == 检查——它在仓库中已有 20+ 处调用点。

3.4 插槽(Slot)赋值使用代理(proxy)模式

自定义节点的内容槽位通过 _quarto.ast.create_proxy_accessor 生成的代理表访问。修改槽位时应克隆后再赋值,而不是直接改原节点:

-- ✅ 正确:代理模式
local new_callout = callout:clone()
new_callout.content = modified_content
return new_callout

-- ❌ 错误:直接赋值可能不生效
callout.content = modified_content
return callout

四、格式检测:_quarto.format 与执行时机陷阱

4.1 常用格式判断

_quarto.format 由 src/resources/pandoc/datadir/_format.lua 提供,内部基于 Pandoc 全局 FORMAT 与 format-identifier / quarto-custom-format 参数实现:

-- HTML 输出(含基于 HTML 的格式)
if _quarto.format.isHtmlOutput() then ... end

-- LaTeX/PDF 输出
if _quarto.format.isLatexOutput() then ... end

-- Typst 输出
if _quarto.format.isTypstOutput() then ... end

-- Word/DOCX 输出
if _quarto.format.isDocxOutput() then ... end

-- Reveal.js 幻灯片
if _quarto.format.isRevealJsOutput() then ... end

-- Dashboard 格式
if _quarto.format.isDashboardOutput() then ... end

从 _format.lua 源码可见更多细节:isLatexOutput() 同时覆盖 latex / beamer / pdf;isHtmlOutput() 覆盖 html、html4、html5、epub* 与全部 HTML 幻灯片格式(s5、dzslides、slidy、slideous、revealjs);isMarkdownOutput() 覆盖 markdown*、commonmark*、gfm、markua;还有 isFormat("html:js") 这类组合判断(HTML 但不含 epub)。

4.2 关键陷阱:在元素函数内做格式判断,而非构造时

main.lua 在加载时调用构造函数(filter = my_filter())来构建过滤器表——而此时输出格式尚未解析确定。如果在构造函数顶部写格式门(if not _quarto.format.isLatexOutput() then return {} end),它会过早求值、返回空过滤器,导致该过滤器对所有文档静默失效。

正确做法:把 _quarto.format.* 检查放进返回的元素函数(Meta、Div...)内部,此时格式已确定。参考实现见 src/resources/filters/quarto-pre/font.lua 的 normalize_font_fallbacks()——它在 Meta 函数内才做 isLatexOutput() 与 pdf_engine 判断,并为 mainfontfallback / sansfontfallback / monofontfallback 补充 luaotfload 名称终止符 :。

五、元数据值(Metadata Values)的形状检测

Pandoc Lua 的元数据值不带 .t 标签(val.t 为 nil),因此 val.t == "MetaList" 永远不会匹配。应使用 quarto.utils.type(val)——它是内置 pandoc.utils.type 的自定义节点感知超集:

  • YAML 列表 → "List"(用 ipairs 迭代)
  • 普通标量 → "string"
  • 行内格式化标量 → "Inlines"

重建时将其包装为 pandoc.MetaList(元素为 pandoc.MetaString);pandoc.utils.stringify 可把任意标量拍平成文本。参考实现:src/resources/filters/quarto-post/email.lua 的 meta-list 迭代。

六、选项与参数:option() 与 param()

API 用途 示例
option(name, default) 读取元数据选项(可带默认值) local show_icon = option("callout-icon", true)
option(name) 读取选项,无默认值时返回 nil local custom = option("my-option")
param(name) 读取执行参数(由 TypeScript 侧通过 formatFilterParams 注入) local engine = param("execution-engine")
var(name, default) 读取 _quarto-vars 命名空间下的变量 local v = var("my-var", 1)

option() 由 src/resources/filters/quarto-pre/options.lua 实现:init_options() 在 Meta 阶段把全部元数据缓存进 allOptions,option() 调用 parseOption 支持点分路径索引(如 option("cap-location")),var() 则从 allOptions["_quarto-vars"] 中取值。param() 是 Pandoc 提供的全局函数,读取通过 --metadata 注入的值——main.lua 中大量使用,例如 param("execution-engine")、param("enable-crossref", true)、param("llms-txt", false)、param("output-divs", true) 等。

-- 读取元数据选项(带默认值)
local show_icon = option("callout-icon", true)

-- 读取执行参数
local engine = param("execution-engine")

-- 读取选项(nil 兜底)
local custom = option("my-option")
if custom ~= nil then
  -- 选项已设置
end

七、日志约定

使用 src/resources/filters/common/log.lua 提供的日志函数。从源码可见其实现在 io.stderr 上输出并附带调用位置信息(文件:行号),warn 带黄色、error 带红色前缀:

-- 调试信息(verbose 模式)
info("Processing element: " .. el.t)

-- 警告(在 TypeScript 侧显示为 INFO 级别)
warn("Deprecated feature used")

-- 错误
error("Invalid configuration")

-- 条件化调试输出
if quarto.log.debug then
  quarto.utils.dump(node)
end

八、外部命令执行:用 pandoc.pipe(),不用 io.popen()

io.popen() 把字符串交给 shell 解释,路径含空格时(如 C:\Program Files\...)会解析失败。pandoc.pipe() 直接用参数数组调用可执行文件——无 shell、无引号问题:

-- ✅ 正确:参数以数组传递,无 shell 解释
local ok, result = pcall(pandoc.pipe, command, {"arg1", "arg2"}, "")
if not ok then
  quarto.log.error("Command failed: " .. tostring(result))
end

-- ❌ 错误:走 shell,含空格路径会出错
local handle = io.popen(command .. " arg1 arg2", "r")

仓库内两处典型参考:src/resources/filters/quarto-pre/shiny.lua 调用外部 shiny 命令、src/resources/filters/quarto-post/pdf-images.lua 通过 pandoc.pipe("rsvg-convert", ...) 做 SVG→PDF 转换;src/resources/filters/normalize/astpipeline.lua 也以 pcall(pandoc.pipe, quarto_path, {'run', ...}, '') 的方式调用 quarto run 执行脚本。

九、过滤器返回值约定

function my_filter()
  return {
    Div = function(div)
      -- 返回 nil 表示继续处理(无改动)
      if not should_process(div) then
        return nil
      end

      -- 返回新元素以替换原元素
      return pandoc.Div(modified_content)

      -- 返回空列表以移除元素
      -- return {}
    end
  }
end

十、常用工具速查

10.1 字符串与属性操作

-- 字符串匹配
if string.match(text, "pattern") then ... end

-- 字符串替换
local result = string.gsub(text, "old", "new")

-- 检查类名
if div.classes:includes("callout") then ... end

-- 读取属性
local value = div.attributes["data-foo"]

10.2 Pandoc 辅助构造函数

-- 创建元素
local div = pandoc.Div(content, pandoc.Attr(id, classes, attributes))
local span = pandoc.Span(inlines)
local para = pandoc.Para(inlines)

-- 原始输出
local raw = pandoc.RawBlock("html", "<div>...</div>")
local raw = pandoc.RawInline("latex", "\\textbf{}")

-- 内容拍平为文本
local text = pandoc.utils.stringify(inlines)

十一、调试手段

-- 美化打印任意对象(底层是 _utils.lua 的 tdump,支持自定义节点/循环引用检测)
quarto.utils.dump(node)

-- 类型检查
print("Type: " .. type(obj))
print("Pandoc type: " .. (obj.t or "none"))

-- 追踪执行
warn("Reached checkpoint: " .. checkpoint_name)

quarto.utils.dump 由 src/resources/pandoc/datadir/_utils.lua 的 dump/tdump 实现,能识别 [quarto-emulated-ast:...] 仿真节点、标注循环引用地址并按键排序输出。

十二、过滤器链集成:向 main.lua 注册过滤器

src/resources/filters/main.lua 按阶段组织过滤器表:quarto_init_filters、quarto_normalize_filters、quarto_pre_filters、quarto_crossref_filters、quarto_layout_filters、quarto_post_filters、quarto_finalize_filters,最终合并进 quarto_filter_list 并通过 run_as_extended_ast 交给仿真过滤器执行器(src/resources/filters/ast/runemulation.lua)。

新增过滤器条目遵循如下形态:

-- 每个过滤器有名称与过滤器函数
{ name = "pre-my-feature", filter = my_feature() }

-- 过滤器顺序很重要——注意依赖关系
-- 同一阶段的过滤器按定义顺序执行

条目还支持 flags = { "has_x" } 字段:src/resources/filters/ast/runemulation.lua 在处理每条过滤器时会先检查 flags——当列出的标志全部未命中时,跳过整个过滤器遍历。这比在函数内部 early-return 更高效,因为连整棵树的遍历都省了。标志在 src/resources/filters/normalize/flags.lua 的 compute_flags() 中计算(其返回的第二个表持有 Meta 处理器,用于元数据派生的标志)。现有示例标志:has_notes、has_hidden、has_font_fallback、has_shortcodes、has_tables、has_cites、has_lightbox、has_theorem_refs、has_output_cells、has_conditional_content 等。

十三、API 参考与类型定义

完整的可用方法、属性与函数签名,请查阅 src/resources/lua-types/ 下的类型定义文件:

  • src/resources/lua-types/pandoc/ —— Pandoc Lua API(blocks、inlines、List、utils 等)
  • src/resources/lua-types/quarto/ —— Quarto Lua API(格式检测、自定义节点等)

这些类型定义文件完整记录了 API 表面,也是开发时类型提示与静态检查的依据。

十四、关键约定速查表

  1. 过滤器文件用 import() —— require() 仅用于 modules/ 下的模块;
  2. 遍历自定义节点用 _quarto.ast.walk() —— 不要用 pandoc.walk_*,否则会漏掉自定义节点;
  3. 仔细检查节点类型 —— is_custom_node() vs is_regular_node(),二者语义互补;
  4. 修改自定义节点槽位用代理模式 —— 先 clone() 再赋值;
  5. 格式检测用 _quarto.format —— 并注意检测时机在元素函数内;
  6. 返回 nil 表示继续 —— 返回值将替换该元素;
  7. warn() = TypeScript 侧的 INFO 级别;
  8. 格式门要放在元素函数内部 —— 构造函数在格式解析前运行;
  9. 用 quarto.utils.type 检测元数据形状 —— Meta 值没有 .t 标签;
  10. 用 flags 门控昂贵过滤器 —— 不需要时跳过整个遍历;
  11. 内容检查优先用 quarto.utils.match() —— nil 安全,优于手写 .content[1].t 判断。

以上约定均以当前仓库 src/resources/filters/ 与 src/resources/pandoc/datadir/ 下的真实实现为准,是 Quarto 过滤器开发的“事实标准”:遵循它们,可以避免 200-local 打包失败、格式门过早求值、自定义节点漏处理等一类最隐蔽的回归问题。

登录后查看全文
quarto-cli