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

使用Pandoc Lua过滤器将标题下内容放入对应LaTeX环境

实现方案

单靠遍历单个Header元素的过滤器函数无法完成需求——Pandoc的元素级过滤器每次仅传入单个元素,Header函数运行时无法直接获取当前标题之后的块内容,需要通过全局文档遍历的方式切割分块,完整可运行的Lua过滤器代码如下:

function Pandoc(doc)
  local blocks = doc.blocks
  local new_blocks = {}
  local i = 1

  while i <= #blocks do
    local current = blocks[i]
    -- 非标题块直接保留
    if current.t ~= "Header" then
      table.insert(new_blocks, current)
      i = i + 1
    else
      local lv = current.level
      local target_env = nil
      -- 匹配h1、h2对应的LaTeX环境
      if lv == 1 then
        target_env = "A"
      elseif lv == 2 then
        target_env = "B"
      end

      -- 非h1/h2标题直接保留,跳过包裹逻辑
      if not target_env then
        table.insert(new_blocks, current)
        i = i + 1
        goto process_next
      end

      -- 收集当前标题下的所有内容,直到遇到级别不高于当前标题的新标题为止
      local content_below = {}
      local scan_idx = i + 1
      while scan_idx <= #blocks do
        local next_block = blocks[scan_idx]
        if next_block.t == "Header" and next_block.level <= lv then
          break
        end
        table.insert(content_below, next_block)
        scan_idx = scan_idx + 1
      end

      -- 拼接LaTeX环境块
      table.insert(new_blocks, pandoc.RawBlock("latex", "\\begin{" .. target_env .. "}"))
      for _, block in ipairs(content_below) do
        table.insert(new_blocks, block)
      end
      table.insert(new_blocks, pandoc.RawBlock("latex", "\\end{" .. target_env .. "}"))

      -- 游标跳到下一个未处理的块位置
      i = scan_idx
      ::process_next::
    end
  end

  return pandoc.Pandoc(new_blocks, doc.meta)
end
输出效果

将上述代码保存为过滤器文件,配合Pandoc转换给出的示例Markdown,输出的LaTeX内容完全符合预期:

\begin{A}
This is text below a h1 header
\end{A}

\begin{B}
This is text below a h2 header
\end{B}

\begin{A}
This is text below a h1 header
\end{A}

\begin{B}
This is text below a h2 header
\end{B}

补充说明:如果需要保留原h1/h2的标题内容,只需要在插入\begin{环境名}标签之后,额外插入当前遍历到的current(Header元素)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:48:29