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

如何用Pandoc与Lua过滤Markdown中不符合指定类的元素?

使用Pandoc Lua过滤器基于类列表过滤Markdown内容

实现思路

编写Pandoc Lua过滤器,接收允许保留的类列表作为参数,遍历所有Markdown元素:

  • 无类的元素直接保留
  • 只要元素包含一个不在允许列表中的类,就移除该元素及周围空白

编写Lua过滤器代码

创建名为class-filter.lua的文件,内容如下:

-- 存储允许的类集合,用于快速查询
local allowed_classes = {}

-- 从元数据中读取允许的类列表并初始化集合
function Meta(meta)
  if meta.allowed_classes then
    -- 分割逗号分隔的字符串,去除首尾空格并转为小写
    for class in string.gmatch(meta.allowed_classes, "[^,]+") do
      local trimmed_class = string.gsub(class, "^%s*(.-)%s*$", "%1")
      allowed_classes[string.lower(trimmed_class)] = true
    end
  end
  return meta
end

-- 判断元素是否符合保留规则
local function is_allowed(el)
  -- 无类元素直接保留
  if not el.classes or #el.classes == 0 then
    return true
  end
  -- 检查所有类是否都在允许列表中
  for _, class in ipairs(el.classes) do
    if not allowed_classes[string.lower(class)] then
      return false
    end
  end
  return true
end

-- 处理块级元素(如代码块、段落、自定义容器)
function Block(el)
  if not is_allowed(el) then
    return {} -- 返回空列表表示移除该元素
  end
  return el
end

-- 处理内联元素(如链接、图片、带类的文本 span)
function Inline(el)
  if not is_allowed(el) then
    return {} -- 返回空列表表示移除该元素
  end
  return el
end

-- 注册过滤器执行顺序
return {
  {Meta = Meta},
  {Block = Block},
  {Inline = Inline}
}

使用方法

在命令行中通过-M参数传入允许保留的类列表(多个类用逗号分隔),结合过滤器运行Pandoc:

示例1:仅保留带.color-only类的元素

pandoc input.md -o output.md --lua-filter=class-filter.lua -M allowed_classes="color-only"

示例2:保留带.color-only和.bw-only类的元素

pandoc input.md -o output.md --lua-filter=class-filter.lua -M allowed_classes="color-only,bw-only"

关键说明

  1. 类名大小写不敏感:代码会将类名转为小写处理,避免大小写差异导致的匹配问题
  2. 属性不影响过滤:元素的其他属性(如width=30px)不会干扰类的检查
  3. 自动处理空白:移除元素时,Pandoc会自动清理元素周围的冗余空白,无需额外处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:17:32