在 Pandoc Markdown 中对 html 和 pdf 使用 span (f) 或字体颜色?

sdb*_*bbs 6 markdown lua pandoc

我想用 Markdown 编写,然后使用 或<font color="red">red text</font><span style="color: red;">red text</span>为文本着色,这样当在 Gitlab 中签入 .md 文件时,浏览 HTML 格式版本时会自动解析字体颜色 - 但我也想使用相同的.md 文件作为通过 (xe)latex 生成 PDF 的源。

我见过:

...我的选择似乎是:

  • 显式用于<span>HTML,并\textcolor通过 Latex 显式用于 PDF,这迫使我保留同一 Markdown 文档的两个版本
  • 使用 Lua 过滤器,并像这样编写violets are [blue]{color="blue"}- 这绝对不会被 Gitlab 等使用的任何 Markdown-to-HTML 引擎解析

所以,我在想 - 一定有可能,我在我的文件中写入<span><font>(这将/应该被 Gitlab 和此类解析器识别),然后有一个用于 pandoc 的 Lua 过滤器,\textcolor当使用.md 文件作为创建 PDF 的源。

不幸的是,我对 Lua 很烂,并且对 Pandoc 的内部文档模型了解不够,无法轻松猜测如何在 Markdown 文件中获取这些类型的标签。所以我的问题是:是否有一个现有的过滤器或设置pandoc已经可以做到这一点 - 或者缺少那个,一个在 Markdown 文档中查找此类标签的 Lua 过滤器脚本,我可以使用这种过滤的基础?

sdb*_*bbs 9

好吧,我想我得到了某个地方 - 这是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
Run Code Online (Sandbox Code Playgroud)

测试文件-test.md:

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

Hello, <span style="color: red;">red text</span>

And hello <span style="color: green;">green text</span>
Run Code Online (Sandbox Code Playgroud)

调用命令:

pandoc test.md --lua-filter=color-text-span.lua --pdf-engine=xelatex -o test.pdf
Run Code Online (Sandbox Code Playgroud)

输出:

输出