Blogofile has support out-of-the-box for reStructuredText and Pygments. Blogofile's syntax_highlight.py filter wants you to mark your code blocks with a token such as $$code(lang=python). I wanted to use the method I am more familiar with, by configuring reStructuredText with a custom directive. Luckily this is very easy. Here is how I did it.

First of all, I checked what version of Pygments I had since I used Ubuntu's package manager to install it. I then visited Pygments on BitBucket, and switched to the tag that matched my version. I then drilled into the external directory. I then saved the rst-directive.py file to my blog's local repository under the name _rst_directive.py. I named it with a leading underscore so that Blogofile would ignore it. If this bothers you, you could also add it to Blogofile's site.file_ignore_patterns setting.

Next, I tweaked the settings in _rst_directive.py by un-commenting the linenos variant.

All we have to do now is to get Blogofile to import this module. This can be accomplished by making use of the pre_build() hook in your _config.py file. This is a convenient place to hang custom code that will run before your blog is built. I added the following code to my _config.py module

def pre_build():
    # Register the Pygments Docutils directive
    import _rst_directive

This allows me to embed code in my .rst files with the sourcecode directive. For example, here is what I typed to create the source code snippet above:

.. sourcecode:: python

   def pre_build():
       # Register the Pygments Docutils directive
       import _rst_directive

Of course to get it to look nice, we'll need some CSS. I used this Pygments command to generate a .css file for the blog.

$ pygmentize -f html -S monokai -a .highlight > pygments.css

I saved pygments.css in my css directory and updated my site template to link it in. Blogofile will copy this file into my _site directory when I build the blog.

Here is what I added to my blog's main .css file to style the code snippets. The important thing for me was to add an overflow: auto; setting. This will ensure that a scrollbar will appear on long lines instead of the code being truncated.

.highlight {
   width: 96%;
   padding: 0.5em 0.5em;
   border: 1px solid #00ff00;
   margin: 1.0em auto;
   overflow: auto;
}

That's it!


Comments

comments powered by Disqus