Search code examples
javascriptbashhaskellpandocprismjs

Output semantic code blocks with Prism


I'm inputting markdown data and outputting HTML files with Pandoc. Using the --no-highlight flag, I can get the syntax to output without the built-in basic syntax highlighting, and use Prism.js to highlight the code instead, which is much more robust.

However, Prism requires that the code or pre have language-* in the class name. Using php as an example, Pandoc outputs <pre class="php">. I've managed to hack it to work by using:

```language-php

As the start of each code block. However, when I want to export the same code as an EPUB, it won't recognize the language to be able to use the built in syntax highlighting.

Here are the commands I use for EPUB and HTML output:

# epub output
pandoc assets/metadata.yaml chapters/*.md -o build/book.epub

# html output
pandoc assets/metadata.yaml chapters/*.md -s --toc --no-highlight  --css ../assets/style.css -A assets/template/footer.html -o build/book.html

My issue:

I want to be able to write

```php

As the start of my code blocks, instead of

```language-php

So both Prism.js and the built-in syntax highlighter will work, with my EPUB and HTML generation.

If I could get Pandoc to interpret "```php" as class="language-php", this would solve the issue.

Here is a link on the Pandoc GitHub for someone else with the same issue I'm trying to solve.


Solution

  • I'm for using sed as well, but as a pre-processor. You could write a script like the one below, and name it pre-process:

    #!/bin/bash -e
    
    derived_dir=derived
    rm -fr ${derived_dir} && mkdir -p ${derived_dir}
    for file in $*
    do
        cat ${file} | sed 's/```php/```language-php/g' > ${derived_dir}/$(basename ${file})
    done
    echo "${derived_dir}/*"
    

    Then you could use ```php in your source, and produce html via:

    pandoc assets/metadata.yaml $(pre-process chapters/*.md) -s --toc --no-highlight --css ../assets/style.css -A assets/template/footer.html -o build/book.html

    Hope this helps.