Switching From Pygments to Prettify

When I first converted this blog to Jekyll I was using pygments for source highlighting. While this felt weird being a deviation from markdown syntax within my markdown files it was easy to do and the examples on setting up a Jekyll site all seemed to use it. At first pygments seemed to be a fine solution. But, I have a fair number of code snippets in my files. Processing through these ended up taking more time than I was comfortable with. I was ready to switch when every time I used the Jekyll server or deployed my site to production it took 30 seconds. I felt like I was living in a compiling world! This is how and why I switched from pygments to Prettify.

Choosing Prettify

There are a number of great JavaScript based code highlighting solutions. I took a look at newer solutions like Prism and Rainbow along with more tried solutions like SyntaxHighlighter. I ended up choosing Prettify for one simple markdown based reason.

In my switch from Pygments I wanted to use markdown formated code snippets. Sure, there are setups like Github flavored markdown that allow you to specify a programming language for a code block. But, I regularly use tools on markdown that don’t support this. So, I wanted a solution that could generically highlight code without being told the language and be mostly intelligent about it. Prettify can do just this so it became my solution.

Making the Change

There were two parts to making this switch. First, I had to convert my code snippets from the pygments method to the markdown method for comments. When I looked over older posts to start scripting a change I realized there was a bit of a mess in how I handled some of my older material that had been migrated from Drupal. So, rather than come up with a scripted solution I just spent a little time and manually made the switch with some simple search and replace tools. This gave me an opportunity to find some other messes in the content and fix them.

The second part was to implent Prettify which is fairly simple to do. I included Prettify in the page and the extra files for some languages like SQL, CSS, etc. This is detailed in the README file. My initialization code looks a little different from the Prettify code.

(function($, window, undefined) {

  // Add pretty print to all pre and code tags.
  $('pre, code').addClass("prettyprint");

  // Remove prettify from code tags inside pre tags.
  $('pre code').removeClass("prettyprint");

  // Activate pretty presentation.
})(jQuery, this);

In this case I use jQuery to add the prettyprint class to the relevant tags before activating Prettify. This allows me to have standard markdown code elements and have them be generically syntax highlighted.