如何在 Pandoc Markdown 中使用 span 标签实现 HTML 和 PDF 中的字体颜色?

我想以 Markdown 格式写作,然后使用<font color="red">red text</font><span style="color: red;">red text</span> 对文字进行着色,这样在查看 HTML 版本时, Gitlab 等网站会自动解析字体颜色。 同时,我还想使用相同的 .md 文件作为 (xe)latex 生成PDF文件的源代码。

我已经参考了以下资源:

… 我的选择似乎是:

  • HTML 显示需要显式使用 <span>,PDF 显示需要显式使用 \textcolor,这样强制我必须保留同一份 Markdown 文档的两个版本
  • 使用 Lua 过滤器,并编写类似紫罗兰是[蓝色]{color="蓝色"}的代码 — 这绝对无法被 Gitlab 和其他 Markdown-to-HTML 引擎解析

所以,我认为很有可能在文件中写入<span><font>(这些应该被 Gitlab 等解析器识别),然后使用 pandoc 的 Lua 过滤器将它们转换为 \textcolor

遗憾的是,我不懂 Lua,也不完全知道 Pandoc 的内部文档模型,无法轻松猜测如何在 Markdown 文件中获取这些标签。 因此,我的问题是:是否已经存在可用于处理此类过滤操作的pandoc过滤器或设置,或者一种有 Lua 过滤器脚本可以查找 Markdown 文档中的此类标记,我可以将其用作此类过滤器代码的基础?

点赞
用户6197439
用户6197439

好的,我认为我有点明白了 - 这是 color-text-span.lua(有点糟糕,因为正则表达式明确要求在 color: 冒号之后加上一个空格,但嘿 - 好过没有):

-- https://stackoverflow.com/questions/62831191/using-span-for-font-color-in-pandoc-markdown-for-both-html-and-pdf
-- https://bookdown.org/yihui/rmarkdown-cookbook/font-color.html
-- https://ulriklyngs.com/post/2019/02/20/how-to-use-pandoc-filters-for-advanced-customisation-of-your-r-markdown-documents/

function Span (el)
  if string.find(el.attributes.style, "color") then
    stylestr = el.attributes.style
    thecolor = string.match(stylestr, "color: (%a+);")
    --print(thecolor)
    if FORMAT:match 'latex' then
      -- encapsulate in latex code
      table.insert(
        el.content, 1,
        pandoc.RawInline('latex', '\\textcolor{'..thecolor..'}{')
      )
      table.insert(
        el.content,
        pandoc.RawInline('latex', '}')
      )
      -- returns only span content
      return el.content
    else
      -- for other format return unchanged
      return el
    end
  else
    return el
  end
end

测试文件 - test.md:

---
title: "Test of color-text-span.lua"
author: Bob Alice
date: 2010年7月7日
geometry: margin=2cm
fontsize: 12pt
output:
  pdf_document:
    pandoc_args: ["--lua-filter=color-text-span.lua"]
---

你好,<span style="color: red;">红色文字</span>

还有,你好<span style="color: green;">绿色文字</span>

调用命令:

pandoc test.md --lua-filter=color-text-span.lua --pdf-engine=xelatex -o test.pdf

输出:

output

2020-07-10 12:11:23
用户7482400
用户7482400

如果在正则表达式模式中去除空格,您可以省略显式空格的操作。或者更好的举措是允许空格和非强制性的分号:

将行 thecolor = string.match(stylestr, "color: (%a+);") 改为 thecolor = string.match(stylestr, "color:%s*(%a+);?")

2021-02-21 21:11:50