2007 / June 22nd/ Hacking Markdown: Classes on the <code> element
For the redesign of my site, I decided I wanted some sexy code-highlighting. For a number of reasons I rejected most PHP-based solutions, the driving reason being accessibility and semantics. I want my code untouched in the source — I just want to prettify it visually. How to go about it? Javascript of course. Unfortunately, I needed blocks of code that looked like this:
<pre><code class="javascript">
var test = "Hello, world!";
</code></pre>
That presented a problem since I use markdown and can’t add classes to my <code> elements. I decided to hack Mardown so it would obey me. I wanted to add !!language-name to the beginning of the file and add that class to the <code> block. To do that I hacked up the _DoCodeBlocks_callback function.
function _DoCodeBlocks_callback($matches) {
$codeblock = $matches[1];
// Hacking in some class-names for code blocks
// Grab the language class using !!lang syntax
$pattern = '/^[\t\s]+\!\!(.*)/';
if (preg_match($pattern, $codeblock, $matches)){
$language_class = $matches[1];
// remove the line from the source
$codeblock = preg_replace($pattern, '', $codeblock);
}
// End hacking
$codeblock = _EncodeCode(_Outdent($codeblock));
// $codeblock = _Detab($codeblock);
# trim leading newlines and trailing whitespace
$codeblock = preg_replace(array('/\A\n+/', '/\s+\z/'), '', $codeblock);
$result = "\n\n<pre><code" . ($language_class ? ' class="' . $language_class . '"' : '') . ">" . $codeblock . "\n</code></pre>\n\n";
return $result;
}
And wala! I have nice classed <code>s everywere!
2 Comments
Make a Comment
don’t be afraid, it’s just text

Warpspire is the place that web professional Kyle Neath writes about the web. 


June 23rd | #
How are you achieving the different colors in the code?
June 23rd | #
I’m using Dan Webb’s excelent CodeHighlighter