[]RSS

About Archives Artwork Comic Contact Philosophy Projects Tags

Syntax highlighting for WordPress

December 19th, 2007 in Micro Blog

I finally got around to adding syntax highlighting to the site today, a feature I’ve been meaning to add for several months now. I decided to use the Google code prettify script, via a handy-dandy Wordpress plugin.1

To make it easier to post prettified things, I also hacked the plugin so it automatically adds a prettyprint class to indented pre/code and backtick2 blocks:

function _doCodeBlocks_callback($matches) {
    $codeblock = $matches[1];

    $codeblock = $this->encodeCode($this->outdent($codeblock));
    $codeblock = $this->detab($codeblock);
    # trim leading newlines and trailing whitespace
    $codeblock = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $codeblock);

    $result = "\n\n".$this->hashBlock("<pre><code class='prettyprint'>" 
            . $codeblock . "\n</code></pre>")."\n\n";

    return $result;
}

While I was at it, I fixed an old bug in my SimpleLink plugin too, as it was munging array syntax like $a[9] in pre blocks. Some day I’ll rewrite the plugin as a full parser, merging it with Markdown (and RestructuredText).3 But not today.

  1. While I don’t strictly need the plugin (adding it to the template header would be enough), it may be a handy way to hook it into my RSS feed in the future
  2. The backtick hack is similar to the indented pre/code here
  3. Markdown has a similar set of parsing bugs, as it hacks parsing the posts too

2 Responses to “Syntax highlighting for WordPress”

  1. eldila says:
    December 19th, 2007 at 11:41 am

    The syntax highlighting doesn’t work in you RSS Feed yet. It would be nice to have in the future.

  2. mx says:
    December 19th, 2007 at 11:46 am

    Yeah, RSS isn’t there yet. I need to spend some time to see how various RSS readers deal with Javascript in-feed (if at all), and also figure out if I have to push the CSS to the content HTML or not.

 

Leave a Reply

Subscribe to comments