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" 
  code {
    font-family: monospace;
    overflow: auto;

<script src=''></script>
<script type="text/javascript">
  $(document).ready(function() {
    var codeCommentRegexp = /code\[(.+)\]/;
    var match;
        return this.nodeType == 8;
    }).each(function(i, e){
      if (match=codeCommentRegexp.exec(e.nodeValue)) {
        } catch(e) {}
    hljs.tabReplace = '  ';


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.