RSS Feed

Syntax highlighting in tumblr, the fast & clever way

Ronny,

Comments
Tutorial

The first thing you usually do to customize your new techy blog is adding support for code blocks with syntax highlighting.

Now, some of us like to write our tumblr posts using markdown (the smart, portable markup language). Markdown also gives us easy means to display code - Backticks ` surround inline code while four-spaces indentation creates a code block. It also escapes HTML tags for you (how considerate).

Example code block, highlighted by the code inside it. Pretty recursive.But using markdown you cannot add classes like some syntax highlighters require to declare code language. And anyhow, why bother? I was sure there's a solution which could handles most languages without depending on a manual identification.

Well, turns out there is. Google Code Prettify by Mike Samuel is a lightweight, extensible syntax highlighting module which is being used by Google Code & StackOverflow.

I've even found a post on Trial By Byte with a good snippet for using this tool ontypical tumblr posts with jQuery. But I want something more performant, so I 'ported' it to use require.js, the infamous async resource loader.

I've also optimized the code a little bit. If no code blocks are found in the page, the javascript doesn't even load; And I've tweaked the code a little bit to be more succint.

The Code — Google Code Prettify w/ Require.js & jQuery

In the <head>section (loading this async is an overkill IMO):

	<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet" type="text/css" />
 

And wherever you want in the <body>, preferably near the end:

<script src="http://requirejs.org/docs/release/1.0.3/minified/require.js"></script><script>
require(["http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"], function() {
    $(function() {
        var codeBlocks = $('pre code');
        // only if code blocks were found, bring in the prettifier ...
        if (codeBlocks.length) {
            require(['http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js'], function() {
                codeBlocks.parent().addClass('prettyprint');
                prettyPrint();
            });
        }
    });
});
</script>

Voila! Code blocks are automatically highlighted, blazing fast. Any feedback, questions and comments is welcome.

What do you think?