I’m impressed by the Google Code Javascript code prettifier. It isn’t too hard to embed into WordPress and makes a huge difference.

It isn’t perfect with its highlighting, but frankly it doesn’t need to be; it just needs to be substantially readable to a blog reader. If that reader decides to grab the code then they will be pasting it into their favorite editor anyway, at which point their own markup engine kicks in.

I’m most impressed by its ability to determine the language on its own. It comes with 18 language specific .js files and it seems to always get it right.

I’ve taken an old post with some PL/SQL code and applied the prettifier and I’m very happy with the results. There are a couple of examples in the how-to section below, but no lengthy samples, see the Google Code samples in the link above. My next post will probably also include more sample code.

How to set it up

This takes a few minutes, but its a one time chore and the use is very easy thereafter.

  • Download the distribution version of prettify, unzip, and copy the whole directory to the root of your server (or elsewhere if you prefer).
  • From the WordPress dashbaord, go to “Appearance” / “Editor”. On the right select “Header (header.php)”.
  • Somewhere in the <head> add the following two lines. If you chose a different directory, adjust accordingly.
    <link href="/google-code-prettify/prettify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="/google-code-prettify/prettify.js"></script>
  • In the same file change <body> to
    <body onload="prettyPrint()">
  • Click the “Update File” button.

I chose to also alter the appearance of the <pre> box. This is optional.

  • Also in the Editor, select “Stylesheet (style.css)”.
  • Search for “.post pre {” and change it to the following.
    .post pre {
        margin-bottom: 10px;
        background-color: #eee;
        font-size: 12px;
        overflow: auto;
        line-height: 1em;
        padding: 5px;
    }

    I like the background being different from my theme, the overflow directive is important to prevent the text from flowing out of the box (forces horizontal scroll bars), and the line-height removes the 1.8em height when the code is within a list tag (applies to all these examples).

  • Dont’ forget to click the “Update File” button.

How to Use It

  • When editing, go into HTML mode.
  • Wrap your code in
    <pre class="prettyprint">
    
    </pre>

One word of warning: WordPress is designed for blog authoring, not coding. If you switch back to Visual and then back to HTML your code will get reformatted according to formatted prose rules, messing up your spacing and line breaks. The WordPress editor should be made smart enough to not mess with anything within the <code> tag, but that’s a subject for another “will never get done” post.