Some notes on computer stuff code tags rss about

Enabling code highlighing in jekyll

October 8, 2012
[web] [jekyll] [pygmentize] [tutorial]

It's not hard to do, but not as easy as one might expect. So here are the main steps one need to follow to make code highlighing work:

1. Install pygmentize

In my case it was as easy as running the command:

sbopkg -i Pygments

To test if it works one may try executing the following command found in this post:

ruby -e "require 'albino'; puts Albino.colorize('puts \'Hello World\'', :ruby)"

The output produced by the command should be:

<div class="highlight"><pre><span class="nb">puts</span> <span class="s1">&#39;Hello World&#39;</span>
</pre>
</div>

2. Define appropriate .highlight styles to CSS file

As you code notice above, pygmentize uses <span> tags to define syntax elements using CSS classes. So we need to generate a CSS style and include it to our style file. Such file can be easily generated by the pygmentize itself, with the following command:

pygmentize -f html -S friendly > css/syntax.css

In which friendly is a name of style I choose. You can list all available styles by running the command:

pygmentize -L styles | less

After that I imported newly generated CSS file into my css/style.css file using the following directive:

@import "syntax.css";

That CSS file is linked in _layouts/layout.html template by this line:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

3. Enclose code in posts in {% highlight lang %}/{% endhighlight %} pseudo-tags

Now, when most things are set up one needs to tell jekyll which parts of posts should be highlighted. This is done by putting such parts between to pseudo-tags, like in this code from a paragraph above:

{% highlight html %}
    <link rel="stylesheet" type="text/css" href="/css/style.css" />
{% endhighlight %}

You can find out correct value for lang argument of the highlight tag from the of output of the following command:

pygmentize -L lexers | less

4. Run jekyll with --pygments flag

After finishing with previous steps I was almost sure it will work, but I get only <div> tag prepended to my code blocks instead. It turned out that the very important thing is to start jekyll with --pygments argument, like this:

jekyll --server --pygments

After this it all worked.