Code Syntax Highlighting in Tumblr

May 24, 2012

Edited 08/10/2012: See updated post: Add Code Syntax Highlighting to any page in “Two” Lines

It aggravates me that no blogging platform makes it easy to enable code highlighting. Oh well, at least tumblr makes it easy to edit HTML manually to include code highlighting.

I put together the code highlighting on this blog using the following two posts as guidelines:

Both of those posts are great, but I’m a minimalist so I want to make the whole process a bit easier. You can highlight all of your code blocks with one block that you can copy and paste into your html file right before the </body> tag:

<!-- prettify -->
<link
  href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css"
  type="text/style"
  rel="stylesheet"
/>
<script
  src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"
  type="text/javascript"
></script>
<style>
  pre.prettyprint {
    overflow-x: auto;
    margin: 5px 20px 20px;
  }
</style>
<script type="text/javascript">
  function styleCode() {
    if (typeof disableStyleCode != "undefined") {
      return;
    }

    var a = false;

    $("pre code")
      .parent()
      .each(function() {
        if (!$(this).hasClass("prettyprint")) {
          $(this).addClass("prettyprint");
          a = true;
        }
      });

    if (a) {
      prettyPrint();
    }
  }

  $(function() {
    styleCode();
  });
</script>
<!-- end prettify -->