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

如何用Pandoc Lua过滤器将Div自定义样式转为LaTeX环境及章节标题

Pandoc Lua 过滤器解决方案

需求1:HTML中带custom-style属性的Div自动转为对应LaTeX环境

你的尝试代码无效的核心原因是:返回的元素列表里混合了字符串和RawBlock元素,Pandoc Lua过滤器要求返回的必须是Block类型元素的列表。正确做法是把样式名和LaTeX命令拼接成完整的RawBlock字符串。

正确实现代码

function Div(elem)
    local style_name = elem.attributes['custom-style']
    if style_name then
        return {
            pandoc.RawBlock('latex', '\\begin{' .. style_name .. '}'),
            elem,
            pandoc.RawBlock('latex', '\\end{' .. style_name .. '}')
        }
    end
    return elem
end

效果说明

  • 只要Div带有custom-style属性,就会自动生成对应名称的LaTeX环境:比如custom-style="NiceStyle"会转为\begin{NiceStyle}...\end{NiceStyle},custom-style="BADStyle"会转为\begin{BADStyle}...\end{BADStyle}
  • 没有custom-style属性的Div会保持原样,不做修改

需求2:DOCX中「Chapter Title」样式文本转为LaTeX的\chapter命令

DOCX导入Pandoc时,自定义样式会被转换为元素的class属性,原样式名里的空格会被替换为连字符(即Chapter Title→Chapter-Title)。需要同时处理段落和标题元素,避免遗漏不同结构的标题内容。

正确实现代码

-- 处理段落形式的章节标题
function Para(elem)
    for _, inline in ipairs(elem.content) do
        if inline.attr and inline.attr.classes:includes('Chapter-Title') then
            local chapter_text = pandoc.utils.stringify(elem)
            return pandoc.RawBlock('latex', '\\chapter{' .. chapter_text .. '}')
        end
    end
    return elem
end

-- 处理标题块形式的章节标题
function Header(elem)
    if elem.attr and elem.attr.classes:includes('Chapter-Title') then
        local chapter_text = pandoc.utils.stringify(elem)
        return pandoc.RawBlock('latex', '\\chapter{' .. chapter_text .. '}')
    end
    return elem
end

效果说明

  • 所有带「Chapter Title」自定义样式的文本,无论是段落还是标题块,都会被转为\chapter{文本内容}的LaTeX命令:比如样式为Chapter Title的“My Great Chapter”会生成\chapter{My Great Chapter}

内容的提问来源于stack exchange,提问作者Jack M. Lyon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:30:15