11

I have a Markdown file, e.g.

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

This is some code:

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

and I'd like to leverage the syntax highlighting of Pandoc. This works fine:

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

Because it includes the necessary CSS, e.g.:

<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;}
    ...

However, I'm actually using Pypandoc to compile the Markdown into HTML, and then I'm including the HTML into a web page. Therefore, I'd like the CSS to be standalone, something I can reference in a file, e.g.

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

How can I do this?

2 Answers 2

18

One can inspect the default template used for HTML generation by running

pandoc --print-default-template=html5

The result will depend on your version, but should contain everything interesting. E.g., for pandoc 2.10, this will include the code

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

which causes pandoc to include a file styles.html, the content of which is retrievable via

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

In principle, this is what you are looking for. Now, you'll notice that there are a lot of templating commands, and the syntax highlighting CSS seems not to be included. This is because pandoc generates the CSS on the fly: the styles are stored in a way which makes it easy to use them with other outputs as well. Checkout --list-highlight-styles and --print-highlight-style.

What this means for you is that you can either just generate HTML output and copy-paste the code from there. Or you can create a helper template which just contains

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

Then use that template to create your highlighting.css:

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

Note that sample.md must contain a highlightable code block such as

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

This is necessary, as pandoc generates highlighting CSS only if there is something to highlight.

1
  • 8
    Just want to say that this was exceptionally clear and detailed. Worked perfectly. Thanks.
    – jds
    Jul 9, 2020 at 1:39
4

Here's a small shell script that does what @tarleb describes in his answer and cleans up after itself:

#!/bin/sh
style=${1:-pygments}
tmp=
trap 'rm -f "$tmp"' EXIT
tmp=$(mktemp)
echo '$highlighting-css$' > "$tmp"
echo '`test`{.c}' | pandoc --highlight-style=$style --template=$tmp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.