Pandoc Lua 过滤器完全指南:用内嵌 Lua 解释器操控文档 AST
Pandoc Lua 过滤器完全指南:用内嵌 Lua 解释器操控文档 AST
本文是 pandoc(Universal markup converter,仓库位于 gh_mirrors/pa/pandoc)官方文档 doc/lua-filters.md 的系统性技术解读。文章围绕 pandoc 内嵌的 Lua 5.4 解释器如何直接操控文档抽象语法树(AST)展开,覆盖过滤器编写范式、遍历顺序控制、全局变量与 pandoc 模块 API、调试手段以及十余个可直接落地的完整示例,帮助你掌握从"格式转换器用户"进阶为"文档流水线定制者"的核心能力。
为什么需要 Lua 过滤器:从 JSON 管道到进程内直调
pandoc 很早就支持"过滤器"(filter)机制:在解析(parsing)与写出(writing)两个阶段之间,对文档的抽象语法树(AST)进行任意变换。传统的 pandoc 过滤器以任意编程语言编写,通过 --filter 选项调用,工作方式是:pandoc 将 AST 序列化为 JSON 写入 stdout,过滤器读取后修改,再把修改后的 JSON 写回 stdout 供 pandoc 读入。整个过程涉及两次 JSON 编解码和两次进程间管道通信。
这种设计虽然灵活,却有两个明显缺陷:
- 性能开销:JSON 在 stdin/stdout 之间来回编解码,且每个过滤器两侧各发生一次(共两次)。
- 环境依赖:过滤器能否运行取决于用户环境中是否装有对应语言的解释器,以及操作 pandoc AST 的 JSON 库——你无法提供一个"任何拥有某个版本 pandoc 可执行文件的人都能直接用"的过滤器。
从 pandoc 2.0 开始,pandoc 在可执行文件内部内嵌了一个 Lua 5.4 解释器和一套创建过滤器的 Lua 库,零外部依赖即可编写过滤器。pandoc 数据类型被直接编组(marshal)进 Lua,绕过了 JSON 管道的开销。仓库中 pandoc-lua-engine/src/Text/Pandoc/Lua 目录下的 Haskell 源码(如 Filter.hs、Engine.hs)正是这套 Lua 引擎的实现所在。
下面这个过滤器把加粗强调(Strong)转换为小型大写(SmallCaps):
return {
Strong = function (elem)
return pandoc.SmallCaps(elem.content)
end,
}
等价写法是直接定义顶层函数:
function Strong(elem)
return pandoc.SmallCaps(elem.content)
end
含义是:遍历 AST,每当遇到 Strong 元素,就用内容相同的小型大写元素替换它。将代码保存为 smallcaps.lua,然后运行:
pandoc --lua-filter=smallcaps.lua input.md
官方文档记录了一个快速性能对比(将 pandoc 手册 MANUAL.txt 转为 HTML,同一逻辑分别用编译型 Haskell 与解释型 Python 编写的 JSON 过滤器实现):
| 命令 | 耗时 |
|---|---|
pandoc(不加过滤器) |
1.01s |
pandoc --filter ./smallcaps(Haskell JSON 过滤器) |
1.36s |
pandoc --filter ./smallcaps.py(Python JSON 过滤器) |
1.40s |
pandoc --lua-filter ./smallcaps.lua(Lua 过滤器) |
1.03s |
可见 Lua 过滤器规避了通过管道编解码 JSON 带来的显著开销,性能几乎与不加过滤器持平。该对比数据出自文档原文,可作为选型参考。
Lua 过滤器的结构:表、函数与返回值约定
Lua 过滤器本质是一张"以元素类型名为键、以处理函数为值"的表。过滤器通常放在独立文件中,通过命令行参数 --lua-filter 传入:
pandoc --lua-filter=current-date.lua -f markdown MANUAL.txt
关键规则如下:
- 可多次指定:
--lua-filter可以重复出现;pandoc 会按命令行出现顺序依次应用所有过滤器(包括--filter指定的 JSON 过滤器与--lua-filter指定的 Lua 过滤器)。 - 返回值约定:pandoc 期望每个 Lua 文件返回一个过滤器。若脚本没有返回值,pandoc 会收集所有"名字与 pandoc 元素类型同名"的顶层函数(如
Str、Para、Meta、Pandoc)自动合成一个过滤器——这正是上面两种写法等价的原因。 - 多过滤器:当前也支持从一个 Lua 文件返回一个过滤器列表并顺序执行。在
walk方法出现之前,这是在一个文件里跑多个过滤器的唯一途径;但文档明确建议改用 Pandoc 类型的 walk 方法,返回过滤器列表的功能未来可能被移除。 - 调用方式:对每个过滤器,文档树被遍历,每个元素都被交给对应的处理函数(以元素本身作为参数)。
过滤器函数的返回值必须是以下三种之一:
nil:对象保持不变。- 一个 pandoc 对象:必须与输入类型相同,将替换原对象。
- 一个 pandoc 对象列表:将替换原对象,列表会被"拼接"进原对象所属的序列中;返回空列表即删除该对象。
函数输出必须与输入为同一类型:处理 inline 元素的函数必须返回 nil、一个 inline 或 inline 列表;处理 block 元素的函数必须返回 nil、一个 block 或 block 列表。违反此条件时 pandoc 会抛出错误。
如果没有与元素节点类型匹配的函数,过滤系统会查找更通用的回退函数:支持 Inline 和 Block 两个回退函数,分别匹配相应类型的元素。完全没有匹配函数的元素保持原样。
--lua-filter 选项在 CLI 入口处解析,可参考 src/Text/Pandoc/App/CommandLineOptions.hs 中对该选项的处理。
在元素序列上过滤:Inlines 与 Blocks
某些过滤任务需要知道元素在文档中的出现顺序,此时无法只看单个元素。为此有两个特殊函数名,用于对"块列表"或"行内列表"整体过滤:
Inlines (inlines)
: 若过滤器中有此函数,它会被应用到所有行内元素列表上,如 [Para](段落)块的内容、[Image] 的说明文字。每次调用时参数 inlines 是一个 [Inline] 元素的 [List]。
Blocks (blocks)
: 若过滤器中有此函数,它会被应用到所有块元素列表上,如 [MetaBlocks] 元数据块、列表的每个条目、以及 [Pandoc] 文档的主体内容。参数 blocks 是一个 [Block] 元素的 [List]。
这两个函数的返回值要么是 nil(列表保持不变),要么是与输入同类型的列表。不允许返回单个元素——在此上下文中单个元素通常意味着 bug。该功能自 pandoc 2.9.2 起提供。具体实例见下文"移除引文前的空格"。
遍历顺序:typewise 与 topdown
过滤器的遍历顺序可通过设置键 traverse 为 'topdown' 或 'typewise' 来控制,默认是 'typewise':
local filter = {
traverse = 'topdown',
-- ... filter functions ...
}
return filter
该支持自 pandoc 2.17 加入,更早版本会忽略 traverse 设置。
Typewise 遍历
在 typewise 模式(默认)下,一个过滤器集内的元素过滤函数按固定顺序调用,跳过不存在的函数:
若想强制不同的顺序,可手动用 walk 方法运行过滤器。例如希望 Meta 过滤器先于 Str 过滤器运行:
function Pandoc(doc)
doc = doc:walk { Meta = Meta } -- (1)
return doc:walk { Str = Str } -- (2)
end
Topdown 遍历
有时从根到叶子按深度优先单趟遍历更自然。例如块列表 [Plain [Str "a"], Para [Str "b"]] 会依次尝试:Blocks、Plain、Inlines、Str、Para、Inlines、Str。
Topdown 遍历可以"提前剪枝":过滤器函数以 false 作为第二个返回值时,返回元素的子元素将不再被处理。例如要排除脚注内容被处理:
traverse = 'topdown'
function Note (n)
return n, false
end
全局变量:过滤器与 pandoc 主程序之间的桥梁
pandoc 通过设置全局变量向 Lua 过滤器传递额外数据:
FORMAT
: 被设置为当前使用的 pandoc 写入器格式(html5、latex 等),使过滤器行为可以依最终输出格式而定。源码中该变量的设置见 pandoc-lua-engine/src/Text/Pandoc/Lua/Global.hs(FORMAT format -> ... Lua.setglobal "FORMAT")。
PANDOC_READER_OPTIONS
: 提供给解析器的选项表([ReaderOptions] 类型),如 columns、extensions、tab_stop、standalone、track_changes 等。
PANDOC_WRITER_OPTIONS
: 将传给写入器的选项表([WriterOptions] 类型)。对象可被修改,但修改不会被 pandoc 采纳。自 pandoc 3.0 起,在自定义写入器(custom writers)中访问此变量已被弃用:会被设置为占位值(默认选项),实际写入器选项通过 Writer 或 ByteStringWriter 函数的第二个参数传入。该字段自 pandoc 2.17 提供。
PANDOC_VERSION
: pandoc 版本号,行为类似数字索引表,最高位数字在前。例如 pandoc 2.7.3 的该变量等价于表 {2, 7, 3};用 tostring(PANDOC_VERSION) 可得到版本字符串。此变量在自定义写入器中同样被设置。
PANDOC_API_VERSION
: pandoc 编译所基于的 pandoc-types API 版本,同样为数字索引表。例如基于 pandoc-types 1.17.3 编译时,该变量行为类似表 {1, 17, 3}。此变量在自定义写入器中同样被设置。
PANDOC_SCRIPT_FILE
: 调用过滤器所用的文件名,可用于定位脚本文件相对路径下的资源。此变量在自定义写入器中同样被设置。
PANDOC_STATE
: 所有 reader 与 writer 共享的状态,类型为 [CommonState],只读。字段包括 input_files、output_file、log、request_headers、resource_path、source_url、user_data_dir、trace、verbosity 等。
pandoc
: pandoc 模块本身(见下一节),通过全局 pandoc 可用;本文所述的其他模块以各自名字作为其子字段加载。
lpeg
: 基于解析表达式文法(PEG)的 lpeg 模块,提供出色的解析工具。pandoc 默认使用内置版本,除非包维护者配置为依赖系统级安装。
re
: 基于 LPeg 之上的 LPeg.re 模块,提供正则引擎实现。同样默认使用内置版本。
pandoc 模块:元素创建与主功能访问
pandoc Lua 模块被加载进过滤器的 Lua 环境,提供一组函数与常量,使元素创建和操作更加容易。全局变量 pandoc 绑定到该模块,一般不应覆盖它。
模块提供两大功能:
元素创建函数
: 如 Str、Para、Pandoc 等构造器,用于创建易于使用、可从 Lua 环境读回的新元素。pandoc 内部就是用这些函数创建传给元素过滤函数的 Lua 对象的,因此通过本模块创建的元素与过滤器参数中可访问的元素行为完全一致。完整的构造器清单与参数说明见文档 doc/lua-filters.md 的 "Module pandoc" 章节,对应的 Lua 模块实现位于 pandoc-lua-engine/src/Text/Pandoc/Lua/Module/Pandoc.hs。
暴露的 pandoc 主功能 : 若干 pandoc 函数被引入 Lua:
walk_block与walk_inline:在特定块或行内元素内部应用过滤器;read:将字符串按给定格式解析为 pandoc 文档;pipe:以字符串为 stdin 运行外部命令并捕获 stdout 输出;pandoc.mediabag模块:访问"mediabag",它存放可能被包含进最终文档的二进制内容(如图片);pandoc.utils模块:包含各种工具函数(如stringify、type、sha1、to_simple_table、from_simple_table、must_be_at_least等),实现见 pandoc-lua-engine/src/Text/Pandoc/Lua/Module/Utils.hs。
pandoc.pipe 的签名是 pipe (command, args, input):以参数 args 运行 command,向其 stdin 传入 input,返回 stdout 输出;若命令以非零错误码退出,会抛出一张含 command、error_code、output 键的表。例如:
local output = pandoc.pipe("sed", {"-e","s/a/b/"}, "abc")
核心类型参考
Lua 过滤器处理的 AST 元素具有类型化结构。除只读对象外,所有列出的类型实例都可通过 clone() 方法克隆,例如:
local emph = pandoc.Emph {pandoc.Str 'important'}
local cloned_emph = emph:clone() -- note the colon
Pandoc 类型与 walk 方法
Pandoc(文档对象)字段:blocks(文档内容 [Blocks])、meta(文档元信息 [Meta])。可通过 pandoc.Pandoc(blocks[, meta]) 构造。它有 normalize() 方法(规范化文档,如折叠连续空格、规整表格行列)以及关键的 walk(self, lua_filter) 方法:
walk 将 Lua 过滤器应用到 Pandoc 元素,返回应用过滤器后的(深)拷贝,原元素不受影响。遍历顺序同样受过滤器 traverse 字段控制。示例:
-- returns `pandoc.Pandoc{pandoc.Para{pandoc.Str 'Bye'}}`
return pandoc.Pandoc{pandoc.Para('Hi')}:walk {
Str = function (_) return 'Bye' end,
}
Meta 是文档元信息的字符串索引集合([MetaValues])。MetaValue 并非独立类型,而是可用在需要 MetaValue 处的一组类型,对应 Haskell 构造子:boolean → MetaBool;string/number → MetaString;Inlines → MetaInlines;Blocks → MetaBlocks;整数索引表 → MetaList;字符串索引表 → MetaMap。可用 pandoc.MetaBool、pandoc.MetaString、pandoc.MetaInlines、pandoc.MetaBlocks、pandoc.MetaList、pandoc.MetaMap 构造子确保按预期方式处理(例如空表默认视为 MetaMap,调用 pandoc.MetaList{} 可使其成为空 MetaList)。用 pandoc.utils.type 可获取元数据值类型。
Block 与 Inline 类型
Block 值在 Lua 中等价当且仅当在 Haskell 中等价。常见块类型包括:BlockQuote(content)、BulletList(content)、CodeBlock(text、attr 及 identifier/classes/attributes 别名)、DefinitionList(content)、Div(content、attr)、Figure(content、caption、attr)、Header(level、content、attr)、HorizontalRule、LineBlock(content)、OrderedList(content、listAttributes 及 start/style/delimiter 别名)、Para(content)、Plain(content)、RawBlock(format、text)、Table(attr、caption、colspecs、head、bodies、foot)。所有带内容与属性的块都支持 walk 方法——注意过滤器只应用于子树而不是 self 块元素本身,否则该元素可能被删除或替换为多个块元素,产生意外结果:
-- returns `pandoc.Para{pandoc.Str 'Bye'}`
return pandoc.Para('Hi'):walk {
Str = function (_) return 'Bye' end,
}
Inline 类型包括:Cite(content、citations)、Code(text、attr)、Emph(content)、Image(caption、src、title、attr)、LineBreak、Link(content、target、title、attr)、Math(mathtype、text)、Note(content)、Quoted(quotetype、content)、RawInline(format、text)、SmallCaps(content)、SoftBreak、Space、Span(attr、content)、Str(text)、Strikeout(content)、Strong(content)、Subscript(content)、Superscript(content)、Underline(content)。同样支持 walk:
-- returns `pandoc.SmallCaps('SPQR)`
return pandoc.SmallCaps('spqr'):walk {
Str = function (s) return string.upper(s.text) end,
}
元素组件与其他类型
- Attr:属性集,字段
identifier、classes、attributes。通常无需直接构造,可传 HTML 风格的表,例如pandoc.Span('text', {id = 'text', class = 'a b'})。 - Caption:表格标题,字段
long([Blocks])与short([Inlines])。 - Cell:表格单元格,字段
attr、alignment、contents、col_span、row_span及属性别名。 - Citation:单条引文,字段
id、mode(AuthorInText/SuppressAuthor/NormalCitation)、prefix、suffix、note_num、hash。 - ColSpec:单列的列对齐与宽度规格,是含两个分量的普通表:对齐([Alignment])与列宽(占页宽的比例)。
- ListAttributes:列表属性,字段
start、style(DefaultStyle/Example/Decimal/LowerRoman/UpperRoman/LowerAlpha/UpperAlpha)、delimiter(DefaultDelim/Period/OneParen/TwoParens)。 - Row / TableBody / TableHead / TableFoot:表格行与表格各组成部分。
- List:任何整数索引的 Lua 表(索引从 1 开始)。作为元素一部分或编组过程中生成时,会被做成
pandoc.List类型实例。 - Version:版本对象,行为类似数字索引表(
version[1] == 2等),支持逐元素比较(如Version '1.12' > Version '1.9'),可用PANDOC_VERSION:must_be_at_least '2.7.3'校验版本。 - SimpleTable:类似 pandoc 2.10 之前旧 Table 类型的简单表结构,可用
pandoc.utils.to_simple_table/from_simple_table与 [Table] 双向转换。
Lua 解释器初始化与 init.lua
pandoc Lua 解释器的初始化可由放置在 pandoc 数据目录中的 init.lua 文件控制,常见用途是加载额外模块甚至替换默认模块。例如把 pandoc.text 模块中所有 Unicode 感知函数加到默认 string 模块、以 uc_ 为前缀:
for name, fn in pairs(require 'text') do
string['uc_' .. name] = fn
end
这样就能用冒号语法调用这些函数:mystring:uc_upper()。仓库中 data/init.lua 即为随 pandoc 数据目录分发的初始化脚本,Lua 引擎初始化逻辑见 pandoc-lua-engine/src/Text/Pandoc/Lua/Init.hs。
调试 Lua 过滤器
静态分析可以避免大量错误:可用 luacheck 做静态检查(社区提供了 pandoc 过滤器专用的 luacheck 配置)。William Lupton 编写了一个 Lua 模块,提供若干调试函数,包括美化打印过滤器操纵的 Pandoc AST 元素。此外,还可以通过 mobdebug 包的远程调试接口,在 Pandoc 内部运行 Lua 过滤器时逐行单步执行——配合 ZeroBrane Studio 的 REPL 控制台与界面可查看所有变量与状态。要点:ZeroBrane 不自带 Lua 5.4,需自行安装 Lua 5.4,并用 luarocks 安装 mobdebug 及其依赖 luasocket,在 ZeroBrane 设置中加入 path.lua = "/path/to/your/lua";在过滤器断点处插入 require('mobdebug').start(),将 Project > Lua Interpreter 设为所添加的 Lua 并启用 "Start Debugger Server",再正常运行 Pandoc 即可在对应行中断。
常见陷阱
AST 元素未被更新 : 被过滤的元素只有在过滤器函数返回新元素替换它时才会更新。下面的函数没有效果,因为它没有返回值:
function Str (str)
str.text = string.upper(str.text)
end
正确版本:
function Str (str)
str.text = string.upper(str.text)
return str
end
模式匹配行为依赖 locale
: Lua 模式库中的字符类依赖当前 locale。例如在 CP-1252 locale 下字符 © 被视为标点、能被 %p 匹配,但在 UTF-8 locale 下不会。可靠的做法是在脚本开头加 os.setlocale 'C' 统一处理。
字符串库不感知 Unicode
: Lua 的 string 库把每个字节当作一个字符,string.upper 对非 ASCII 词汇无效;模式 [☃] 会匹配 \240、\159、\154、\178 中的任意字节,却不会匹配雪人 Unicode 字符。应使用 pandoc.text 模块做 Unicode 感知变换,模式匹配则考虑 lpeg 或 re 库。
实战示例:从宏替换到文档再生成
以下示例均出自 doc/lua-filters.md,可直接保存为 .lua 文件后通过 pandoc --lua-filter=xxx.lua 使用。
宏替换
将字符串 {{helloworld}} 转换为强调文本 "Hello, World":
return {
Str = function (elem)
if elem.text == "{{helloworld}}" then
return pandoc.Emph {pandoc.Str "Hello, World"}
else
return elem
end
end,
}
在 LaTeX 与 HTML 输出中居中图片
对 LaTeX,用原始 LaTeX 片段包裹图片实现水平居中;对 HTML,则通过图片元素的 style 属性居中:
-- Filter images with this function if the target format is LaTeX.
if FORMAT:match 'latex' then
function Image (elem)
-- Surround all images with image-centering raw LaTeX.
return {
pandoc.RawInline('latex', '\\hfill\\break{\\centering'),
elem,
pandoc.RawInline('latex', '\\par}')
}
end
end
-- Filter images with this function if the target format is HTML
if FORMAT:match 'html' then
function Image (elem)
-- Use CSS style to center image
elem.attributes.style = 'margin:auto; display: block;'
return elem
end
end
在元数据中设置日期
若文档尚未设置日期,则把当前日期写入元数据:
function Meta(m)
if m.date == nil then
m.date = os.date("%B %e, %Y")
return m
end
end
移除引文前的空格
Markdown 中"作者在文本中"式引文(如 @citekey)前面必须有空格;若不需要这些空格,就得用过滤器移除:
local function is_space_before_author_in_text(spc, cite)
return spc and spc.t == 'Space'
and cite and cite.t == 'Cite'
-- there must be only a single citation, and it must have
-- mode 'AuthorInText'
and #cite.citations == 1
and cite.citations[1].mode == 'AuthorInText'
end
function Inlines (inlines)
-- Go from end to start to avoid problems with shifting indices.
for i = #inlines-1, 1, -1 do
if is_space_before_author_in_text(inlines[i], inlines[i+1]) then
inlines:remove(i)
end
end
return inlines
end
这是 Inlines 过滤函数的标准用法:倒序遍历列表以避免索引移位问题。
用元数据值替换占位符
Lua 过滤器函数按 Inlines → Blocks → Meta → Pandoc 的顺序运行。要让信息从高层(如元数据)传到低层(如行内元素),可用同一文件中的两个过滤器配合 walk:
local vars = {}
local function get_vars (meta)
for k, v in pairs(meta) do
if pandoc.utils.type(v) == 'Inlines' then
vars["%" .. k .. "%"] = {table.unpack(v)}
end
end
end
local function replace (el)
if vars[el.text] then
return pandoc.Span(vars[el.text])
else
return el
end
end
function Pandoc(doc)
return doc:walk { Meta = get_vars }:walk { Str = replace }
end
若文件 occupations.md 内容为:
---
name: Samuel Q. Smith
occupation: Professor of Oenology
---
Name
: %name%
Occupation
: %occupation%
则运行 pandoc --lua-filter=meta-vars.lua occupations.md 会输出:
<dl>
<dt>Name</dt>
<dd><p><span>Samuel Q. Smith</span></p>
</dd>
<dt>Occupation</dt>
<dd><p><span>Professor of Oenology</span></p>
</dd>
</dl>
注意占位符内不能有空格,否则会被拆成两个 Str 元素导致过滤器失效。
为 man 页修改 pandoc 的 MANUAL.txt
这是 pandoc 官方在把 MANUAL.txt 转成 man 页时使用的过滤器:将一级标题转大写(用 walk 变换标题内的行内元素)、移除脚注、把链接替换为纯文本:
-- we use pandoc.text to get a UTF-8 aware 'upper' function
local text = pandoc.text
function Header(el)
if el.level == 1 then
return el:walk {
Str = function(el)
return pandoc.Str(text.upper(el.text))
end
}
end
end
function Link(el)
return el.content
end
function Note(el)
return {}
end
从论文生成讲义
该过滤器抽取文档中所有编号示例、章节标题、块引用与图片,以及任何带 handout 类的 div(只包含"外层"块,忽略嵌套结构如列表项内的块):
-- creates a handout from an article, using its headings,
-- blockquotes, numbered examples, figures, and any
-- Divs with class "handout"
function Pandoc(doc)
local hblocks = {}
for i,el in pairs(doc.blocks) do
if (el.t == "Div" and el.classes[1] == "handout") or
(el.t == "BlockQuote") or
(el.t == "OrderedList" and el.style == "Example") or
(el.t == "Para" and #el.c == 1 and el.c[1].t == "Image") or
(el.t == "Header") then
table.insert(hblocks, el)
end
end
return pandoc.Pandoc(hblocks, doc.meta)
end
统计文档字数
统计文档正文(忽略标题、摘要等元数据,但包括代码中的词)的字数,比直接对 Markdown 跑 wc -w 更准确,因为后者会把 ATX 标题前的 #、HTML 标签等标记字符也算进去。用法:pandoc --lua-filter wordcount.lua myfile.md。
-- counts words in a document
words = 0
wordcount = {
Str = function(el)
-- we don't count a word if it's entirely punctuation:
if el.text:match("%P") then
words = words + 1
end
end,
Code = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
end,
CodeBlock = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
end
}
function Pandoc(el)
-- skip metadata, just count body:
el.blocks:walk(wordcount)
print(words .. " words in body")
os.exit(0)
end
创建表格
该过滤器生成一个含 5 列的表格文档,是 pandoc.Table 构造器的完整工作示例:
+--------+--------+--------+--------+---+ | This | is my | table | header | | +========+:=======+:======:+=======:+===+ | Cell 1 | Cell 2 | Cell 3 | | | +--------+--------+--------+--------+---+ | Cell 4 | Cell 5 | Cell 6 | | | +========+========+========+========+===+ | This is my table footer. | | +===================================+===+
: This is my table caption.
注意:结果 Table 元素的列数等于 colspecs 参数条目数;[ColSpec] 对象必须包含单元格对齐,列宽可选;bodies 参数中的 [TableBody] 对象用 Lua 表指定,因为没有 pandoc.TableBody 构造器(不过新版本中已提供 pandoc.TableBody,本文保留文档原示例写法)。
function Pandoc ()
local caption = pandoc.Caption( "This is my table caption." )
local colspecs = {
{ pandoc.AlignLeft },
{ pandoc.AlignDefault },
{ pandoc.AlignCenter },
{ pandoc.AlignRight },
{ pandoc.AlignDefault }
}
local head = pandoc.TableHead{
pandoc.Row{
pandoc.Cell( "This" ),
pandoc.Cell( "is my" ),
pandoc.Cell( "table" ),
pandoc.Cell( "header" )
}
}
local bodies = {
{
attr={},
body={
pandoc.Row{
pandoc.Cell( "Cell 1" ),
pandoc.Cell( "Cell 2" ),
pandoc.Cell( "Cell 3" )
},
pandoc.Row{
pandoc.Cell( "Cell 4" ),
pandoc.Cell( "Cell 5" ),
pandoc.Cell( "Cell 6" )
}
},
head={},
row_head_columns=0
}
}
local foot = pandoc.TableFoot{
pandoc.Row{
pandoc.Cell( "This is my table footer.", pandoc.AlignDefault, 1, 4 )
}
}
return pandoc.Pandoc {
pandoc.Table(caption, colspecs, head, bodies, foot)
}
end
从文档提取链接
生成一张表,列出输入文档链接到的所有 URL 及各自链接次数:
links = {}
function Link (el)
if links[el.target] then
links[el.target] = links[el.target] + 1
else
links[el.target] = 1
end
return el
end
function Pandoc ()
local caption = pandoc.Caption("Link count.")
local colspecs = {
{ pandoc.AlignDefault, 0.8 },
{ pandoc.AlignLeft, 0.2 }
}
local head = pandoc.TableHead{
pandoc.Row{ pandoc.Cell("Target"), pandoc.Cell("Count") }
}
local foot = pandoc.TableFoot()
local rows = {}
for link, count in pairs(links) do
rows[#rows + 1] = pandoc.Row{
pandoc.Cell( link ),
pandoc.Cell( pandoc.utils.stringify(count) )
}
end
local bodies = {
{
attr={},
body=rows,
head={},
row_head_columns=0
}
}
return pandoc.Pandoc {
pandoc.Table(caption, colspecs, head, bodies, foot)
}
end
把 ABC 乐谱代码转换为音符图片
把带 abc 类的代码块替换为图片:用 abcm2ps 与 ImageMagick 的 convert 运行其内容生成图片并加入 mediabag。二进制格式输出时 pandoc 会使用 mediabag 中的图片;文本格式输出需用 --extract-media 指定目录(或 HTML 时用 --embed-resources)。
-- Pandoc filter to process code blocks with class "abc" containing
-- ABC notation into images.
--
-- * Assumes that abcm2ps and ImageMagick's convert are in the path.
-- * For textual output formats, use --extract-media=abc-images
-- * For HTML formats, you may alternatively use --embed-resources
local filetypes = { html = {"png", "image/png"}
, latex = {"pdf", "application/pdf"}
}
local filetype = filetypes[FORMAT][1] or "png"
local mimetype = filetypes[FORMAT][2] or "image/png"
local function abc2eps(abc, filetype)
local eps = pandoc.pipe("abcm2ps", {"-q", "-O", "-", "-"}, abc)
local final = pandoc.pipe("convert", {"-", filetype .. ":-"}, eps)
return final
end
function CodeBlock(block)
if block.classes[1] == "abc" then
local img = abc2eps(block.text, filetype)
local fname = pandoc.sha1(img) .. "." .. filetype
pandoc.mediabag.insert(fname, mimetype, img)
return pandoc.Para{ pandoc.Image({pandoc.Str("abc tune")}, fname) }
end
end
用 TikZ 构建图片
把原始 LaTeX TikZ 环境转为图片,兼容 PDF 与 HTML 输出。TikZ 代码用 pdflatex 编译为图片,再用 pdf2svg 把 pdf 转为 svg,两者都须在系统 PATH 中。转换后的图片缓存在工作目录,文件名基于源内容哈希,因此不必每次重新生成:
local system = require 'pandoc.system'
local tikz_doc_template = [[
\documentclass{standalone}
\usepackage{xcolor}
\usepackage{tikz}
\begin{document}
\nopagecolor
%s
\end{document}
]]
local function tikz2image(src, filetype, outfile)
system.with_temporary_directory('tikz2image', function (tmpdir)
system.with_working_directory(tmpdir, function()
local f = io.open('tikz.tex', 'w')
f:write(tikz_doc_template:format(src))
f:close()
os.execute('pdflatex tikz.tex')
if filetype == 'pdf' then
os.rename('tikz.pdf', outfile)
else
os.execute('pdf2svg tikz.pdf ' .. outfile)
end
end)
end)
end
extension_for = {
html = 'svg',
html4 = 'svg',
html5 = 'svg',
latex = 'pdf',
beamer = 'pdf' }
local function file_exists(name)
local f = io.open(name, 'r')
if f ~= nil then
io.close(f)
return true
else
return false
end
end
local function starts_with(start, str)
return str:sub(1, #start) == start
end
function RawBlock(el)
if starts_with('\\begin{tikzpicture}', el.text) then
local filetype = extension_for[FORMAT] or 'svg'
local fbasename = pandoc.sha1(el.text) .. '.' .. filetype
local fname = system.get_working_directory() .. '/' .. fbasename
if not file_exists(fname) then
tikz2image(el.text, filetype, fname)
end
return pandoc.Para({pandoc.Image({}, fbasename)})
else
return el
end
end
使用示例:
pandoc --lua-filter tikz.lua -s -o cycle.html <<EOF
Here is a diagram of the cycle:
\begin{tikzpicture}
\def \n {5}
\def \radius {3cm}
\def \margin {8} % margin in angles, depends on the radius
\foreach \s in {1,...,\n}
{
\node[draw, circle] at ({360/\n * (\s - 1)}:\radius) {$\s$};
\draw[->, >=latex] ({360/\n * (\s - 1)+\margin}:\radius)
arc ({360/\n * (\s - 1)+\margin}:{360/\n * (\s)-\margin}:\radius);
}
\end{tikzpicture}
EOF
pandoc.text 模块与 Unicode
Lua 内置 string 库按字节处理字符,对非 ASCII 文本做大小写转换等操作时结果不可靠。pandoc.text 模块提供 Unicode 感知的文本变换函数(如 upper),实现见 pandoc-lua-engine/src/Text/Pandoc/Lua/Module/Text.hs。man 页示例即通过 pandoc.text.upper 安全地把标题转为大写。对更复杂的模式匹配需求,文档建议使用 lpeg 或 re 库(两者均为 pandoc 内置、无需外部安装)。
进阶阅读路径
- 完整类型参考(所有 Block/Inline 类型的字段、全部构造器签名、ReaderOptions/WriterOptions/CommonState 字段说明):doc/lua-filters.md
- Lua 引擎实现:
pandoc-lua-engine/src/Text/Pandoc/Lua/(Global.hs 定义全局变量、Filter.hs 与 Engine.hs 实现过滤器执行、Module/Pandoc.hs 提供pandoc模块、Module/Utils.hs 提供工具函数) - 相关文档:doc/custom-readers.md(自定义 reader)、doc/custom-writers.md(自定义 writer,
PANDOC_WRITER_OPTIONS在其中的弃用说明可参考)、doc/lua-filters.md 之外可继续阅读 doc/filters.md(传统 JSON 过滤器)与 doc/customizing-pandoc.md - 测试用例:
pandoc-lua-engine/test/与test/Tests/目录下包含 Lua 引擎与过滤器的测试集,可结合学习