Syntax highlighting in WordPress
Posted by Giovanni Intini | Filed under Programming, Wordpress
Syntax highlighting in most CMS/Blog Engines is a straightforward business, you install a plugin and boom your code snippets get highlighted. Simple, right? Right, unless you want to publish erlang snippet
The plugin I was using was based on PHP-Geshi, a popular syntax highlighting library that unfortunately doesn’t support erlang. Looking through the wordpress plugin repository I found a little gem: WP-VimColor, based on VimColor, a perl module that uses the Vim syntax highlighting engine.
Good old Vim supports more than 200 languages, and obviously it supports erlang, unfortunately the plugin didn’t want to work with my wordpress installation.
Instead of nice cleanly formatted code I got some gibberish followed by unformatted code and then some gibberish again. I looked into the code and couldn’t find what the problem was, then I remembered I had the same problems with Radiant CMS, that used textile. I use textile on this blog too and deactivating the textile filter solved the gibberish problem, but gave me lots of php errors related to the file functions.
Some more tests revealed the source of this problem:
$in_file = tempnam($GLOBALS['conf']['file_directory_temp'], 'pl'); $out_file = tempnam($GLOBALS['conf']['file_directory_temp'], 'htm');
The two global variables do not exist, so I just replaced them with ”/tmp” and this problem was fixed. I still had the textile conflict problem, to fix it I changed the last two lines of the plugin file to:
add_filter('the_content', 'pre_proccess', 1); add_filter('the_content', 'vim_color', 2);
and the if block inside _vimcolor_process_color()_ to
if( $multiline ){ $html = preg_replace('/\r/s','',$html); $html = preg_replace('/\n/s','<br />',$html); $html = '==<pre class="codeblock">'. $html .'
';
$html = preg_replace('/ /s',' ',$html);
}else{
$html = '
'. trim($html) .'==’;
}
These two fixes make the syntax highlighting filter run before textile and use the ”==” modifier to tell textile not to fiddle with the code.
Now I have beatifully formatted code on my blog and I can also publish erlang snippets, nice!.
Or, as my friend Bard would say:
{bard, comment, Value} = {bard, comment, nice}.