首页 > 解决方案 > Pandoc:语法高亮代码的 CSS 文件在哪里?

问题描述

我有一个 Markdown 文件,例如

---
title: Question
date: 2020-07-07
---

This is some code:

```python
def add(a, b):
    return a+b
```

我想利用 Pandoc 的语法高亮。这工作正常:

pandoc -s --to=html5 2020-07-07-question.md

因为它包含必要的 CSS,例如:

<style>
    code{white-space: pre-wrap;}
    span.smallcaps{font-variant: small-caps;}
    span.underline{text-decoration: underline;}
    div.column{display: inline-block; vertical-align: top; width: 50%;}
    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
    ul.task-list{list-style: none;}
    ...

但是,我实际上是使用 Pypandoc 将 Markdown 编译为 HTML,然后将 HTML 包含到网页中。因此,我希望 CSS 是独立的,可以在文件中引用,例如

<link rel='stylesheet' href='/path/to/some/highlighting.css'/>

我怎样才能做到这一点?

标签: markdownpandoc

解决方案


可以通过运行检查用于 HTML 生成的默认模板

pandoc --print-default-template=html5

结果将取决于您的版本,但应该包含所有有趣的内容。例如,对于 pandoc 2.10,这将包括代码

<style>
  $styles.html()$
</style>

这会导致 pandoc 包含一个文件styles.html,其内容可通过以下方式检索

pandoc --print-default-data-file=templates/styles.html

原则上,这就是您要寻找的。现在,您会注意到有很多模板命令,并且似乎没有包含突出显示 CSS 的语法。这是因为 pandoc 动态生成 CSS:样式的存储方式使其易于与其他输出一起使用。结帐--list-highlight-styles--print-highlight-style.

这对您来说意味着您可以生成 HTML 输出并从那里复制粘贴代码。或者您可以创建一个仅包含

$-- this is file highlighting-css.template
$highlighting-css$

然后使用该模板创建您的highlighting.css

pandoc --template=highlighting-css.template sample.md -o highlighting.css

请注意,sample.md必须包含可突出显示的代码块,例如

~~~html
<p>placeholder</p>
~~~

这是必要的,因为 pandoc 仅在有要突出显示的内容时才会生成突出显示 CSS。


推荐阅读