You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandoc Lua过滤器开发:替换LaTeX图片caption为sidecaption

Pandoc 3.0+ 复杂图片转\sidecaption的Lua过滤器方案

核心思路

Pandoc 3.0+的*复杂图片(Complex Figures)*会将图片、标题、标签等元素封装成Figure类型的AST节点,而非零散的RawBlock或段落节点。要替换\caption为\sidecaption,必须直接操作这个Figure节点,而非后期修改生成的LaTeX代码——这也是你之前RawBlock方法无效的根本原因。

Lua过滤器实现代码

function Figure(fig)
  -- 仅对LaTeX输出生效,其他格式直接返回原节点
  if FORMAT ~= "latex" then
    return fig
  end

  -- 提取自定义的短标题属性和主标题内容
  local short_caption = fig.attributes["short-caption"] or ""
  local main_caption = pandoc.utils.stringify(fig.caption)

  -- 构建\sidecaption命令,支持带短标题的语法
  local sidecaption_cmd = short_caption ~= "" 
    and string.format("\\sidecaption[%s]{%s}", short_caption, main_caption)
    or string.format("\\sidecaption{%s}", main_caption)

  -- 将Figure内部的图片内容转换为LaTeX代码,保留原有格式设置
  local img_content = pandoc.write(fig.content, "latex")

  -- 构建完整的figure环境代码块
  local figure_env = string.format([[
\begin{figure}
  %s
  %s
  %s
\end{figure}
]], img_content, sidecaption_cmd, fig.identifier ~= "" and "\\label{" .. fig.identifier .. "}" or "")

  -- 返回RawBlock类型的LaTeX代码,替换原Figure节点
  return pandoc.RawBlock("latex", figure_env)
end

代码细节说明

  • AST节点捕获:直接监听Figure节点,这是Pandoc 3.0+处理复杂图片的核心载体,包含了图片的所有元数据(标题、标签、自定义属性等)。
  • 短标题兼容:直接读取你之前实现的short-caption属性,完美适配已有的工作流。
  • 格式保留:用pandoc.write将Figure内的图片内容转为LaTeX,确保原有的宽度、路径、对齐等设置不丢失。
  • 标签处理:自动保留图片的引用标签(如果有),符合学术排版需求。

复杂图片机制要点

Pandoc 3.0+的Complex Figures机制是为了统一处理带标题、标签、多图组合的图片场景:

  • 所有带标题的Markdown图片(如![主标题](path.png){short-caption="短标题"})都会被解析为Figure节点。
  • 该节点的处理优先级高于RawBlock,所以直接插入RawLaTeX的方法会被覆盖,必须通过修改Figure节点本身来实现自定义输出。
  • 节点内包含content(图片内容)、caption(标题)、identifier(引用标签)、attributes(自定义属性)四大核心部分,完全覆盖排版所需的所有信息。

使用方式

将上述代码保存为sidecaption-filter.lua,在Pandoc转换命令中添加过滤器参数即可:

pandoc input.md -o output.tex --lua-filter=sidecaption-filter.lua

内容的提问来源于stack exchange,提问作者lukeflo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:16:19