Skip to content

Metablogging: Syntax Coloring

As I wrote in a previous post:

Syntax coloring is a feature of some text editors that displays different parts of the text in different colors depending upon the logical category of the text. This makes it easier to write structured texts whether these be code or markup. … Syntax coloring makes the logical structure of your document visually apparent and hence the document easier to read.

Given its cognitive utility, it would be nice to use syntax coloring with the occasional code snippets displayed here. There are a number of WordPress plugins that provide syntax coloring. The fact that I use Michel Fortin’s PHP Markdown Extra posed one important limitation. PHP Markdown Extra would interfere with those plugins that used special markup. Fortunately, some plugins, like WP-Syntax, use a variant of HTML markup that counts as valid Markdown. WP-Syntax uses the GeSHI syntax engine that supports a large number of languages. The results, out of the box, were not that attractive and modifications, while possible, were beyond my ken. WP-Syntax Colorizer is another WordPress plugin that makes such modifications easier, but after a number of tries, I was unable to come up with a color scheme that worked as well as I liked (my fault entirely, I am sure).

Part of my dissatisfaction had to do with the high quality of syntax coloring provided by my favored text editor, TextMate. I just didn’t feel comfortable settling for less. Fortunately, for me, TextMate can export your coloring theme as CSS and can export selections as HTML. These two posts, here and here, explained how to exploit these features with your WordPress blog to get TextMate themes in your code snippets. Below is an example. The theme is Twilight, and the code is the initial portion of the generated CSS.

/* Stylesheet generated from TextMate theme
 *
 * Twilight
 * 
 *
 */

/* Mostly to improve view within the TextMate HTML viewer */
body {
    margin: 0;
    padding: 0;
}

pre.textmate-source {
    margin: 0;
    padding: 0 0 0 2px;
    font-family: Consolas, DroidSansMono, Inconsolata, DejaVuSansMono, monospace;
    font-size: 10px;
    line-height: 1.3em;
    word-wrap: break-word;
    white-space: pre;
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -o-pre-wrap;
}

pre.textmate-source {
    color: #F8F8F8;
    background-color: #141414;
}

pre.textmate-source .linenum {
    width: 75px;
    padding: 0.1em 1em 0.2em 0;
    color: #888;
    background-color: #eee;
}

The results are not completely faithful—TextMate’s scopes, on which its themes are based, cannot be fully represented in CSS. Nonetheless, I am much happier now. Expect to see proper syntax coloring from now on.

Post a Comment

You must be logged in to post a comment.
FireStats icon Powered by FireStats