Cyril Rohr
Cyril Rohr.

Syntax highlighting in Tumblr


There are multiple solutions to add syntax highlighting for code blocks in Tumblr articles written with Markdown, but they all demand to manually put <pre>, <code> tags and class attributes in the text. You can find the references here:

This is too much pollution for me, since you will no longer see the code blocks nicely formatted in your text editor of choice. Therefore I came up with a simple solution that consists in putting an HTML comment before the code blocks you want to highlight. I then use a small bit of Javascript to extract that info and automatically update the class of the <code> tag. Associated with Highlight.js, this gives nice syntax highlighting in just one line. For example, the following Markdown snippet:

<!-- code[ruby] -->
  
    puts "This is Ruby code"

Will give:

puts "This is Ruby code"

Note that most of the time, you don’t even need to specify the language, since Highlight.js will often detect the right brush for you. Also, HTML comments won’t show up in your RSS feed.

To enable this feature, open the ‘customize appearance’ link in your Tumblr dashboard, then click on ‘Edit HTML’, and enter the following code just before the opening <body> tag (you might need to include the jQuery library if you don’t already have it):

<link rel="stylesheet" 
      href="http://yandex.st/highlightjs/6.1/styles/zenburn.min.css">
<style>
  code {
    font-family: monospace;
    overflow: auto;
  }
</style>

<script src='http://yandex.st/highlightjs/6.1/highlight.min.js'></script>
<script type="text/javascript">
  $(document).ready(function() {
    var codeCommentRegexp = /code\[(.+)\]/;
    var match;
    $("pre").parent().contents().filter(function(){
        return this.nodeType == 8;
    }).each(function(i, e){
      if (match=codeCommentRegexp.exec(e.nodeValue)) {
        try{
          $(e).nextAll("pre").first().
            find("code").addClass(match[1]);
        } catch(e) {}
      }
    });
    hljs.tabReplace = '  ';
    hljs.initHighlightingOnLoad();
  });
</script>

Enjoy!

Update (2012/05/29): this technique also works for Jekyll blogs (look at the source code of this site). In the comments, isagalaev (the author of Highlight.js) points out a performance improvement to apply the highlighting brush directly in the loop.