Better Jekyll Syntax Highlighting with Prism

April 4th, 2017

I personally am not a huge fan of the default syntax highlighting that comes with jekyll. To me, rouge seems very tempermental and there are some things that I just couldn't get to work properly. For one, I wanted to be able to show commands in code snippets. While it pygments supossedly has support for bash highlighting, it never worked.

Prism!

Then I found Prism, a JavaScript/CSS library that adds support for many different libraries and comes with many plugins that extend its functionality. One specific plugin was the command line plugin that solved one of problems with the native jekyll highlighter. I then set about integrating it into jekyll.

Steps

The first step was to obviously disable the native highlighter in the config.yml file.

{% prism yaml %} highlighter: none {% endprism %}

The next step was to download Prism from its website. For my own customized build, I chose the languages I needed highlighting for, along with the highlighting plugin and command line plugin.

To install Prism on a site, you have to add both the prism.js and prism.css file to a script tag and link tag respectively. I chose to place my prism.css file in the head and prism.js just before the closing body tag.

prism.css {% prism html %} <link rel="stylesheet" href="{{ "/css/vendor/prism.css" | prepend: site.baseurl }}"> {% endprism %}

prism.js {% prism html %} <script src="{{ '/assets/js/vendor/prism.js' | prepend: site.baseurl }}"></script> {% endprism %}

Prism and Jekyll

For using prism highlighting from within markdown in Jekyll, I chose the jekyll-prism-plugin by MitMaro.

To call the syntax highlighter from inside markdown all I had to do was the following: {% prism liquid %} {.% prism html %.} <script src="{{ '/assets/js/vendor/prism.js' | prepend: site.baseurl }}"></script> {.% endprism %.} {% endprism %}

Note that the dots between the curly brace and percentage sign is so Jekyll doesn't actually process it.

Command Line and Jekyll-Prism-Plugin

The one downside to the plugin is that it had no support for the Command Line plugin for prism. So I rolled up my language learning sleeves and did a 20 minute crash course in Ruby and added support for it to the plugin. While I have used Ruby a little in the past, I am by no means an expert so it was a fun experience to learn more about the language (Along with Jekyll plugins).

I sent a Pull Request to the original repository so hopefully by the time this is published, it will be integrated officially! (Which would be surprising cause again, first time using Ruby for awhile).