如何使用 Pandoc 为 Markdown 内联代码启用语法高亮显示?

How to enable syntax highlighting for Markdown inline code with Pandoc?

Pandoc manual 说:

--no-highlight

Disables syntax highlighting for code blocks and inlines, even when a language attribute is given.

听起来内联代码应该有语法高亮显示。但是每当我使用 Markdown 内联代码时

This is `print("Hello world")` inline code.

没有语法高亮。

好的,应该进一步阅读……找到解决方案。它被称为 Extension: inline_code_attributes:

Attributes can be attached to verbatim text, just as with fenced code blocks:

`<$>`{.haskell}

所以上面的例子变成了:

This is `print("Hello world")`{.python} inline code.

如果您考虑一下,这是有道理的...我仍然会保留它,以防其他人遇到此问题。

在后台,将 Markdown 转换为 PDF 时,Pandoc 使用 \texttt 命令进行内联代码。我们可以破解 \texttt 命令来为文本添加背景颜色。将以下命令添加到 head.tex:

\definecolor{bgcolor}{HTML}{E0E0E0}
\let\oldtexttt\texttt

\renewcommand{\texttt}[1]{
  \colorbox{bgcolor}{\oldtexttt{#1}}
}

要使用 head.tex,请使用 pandoc 的 -H 选项:

pandoc --pdf-engine=xelatex -H head.tex test.md -o test.pdf