DIY Code Blocks on Posterous
I realise this topic is mostly of academic interest these days, but I decided to archive an updated version of the post for posterity. And the fact that I put a lot of work into it, dammit! 😀
Posterous provides its bloggers with no less than three methods for including blocks of code:
For various reasons, I chose not to use any of them and came up with my own do-it-yourself solution instead.
Shortcomings of Built-in Solutions
On Posterous, CodeRay code blocks must be used inside a
<markdown> ... </markdown> block. Only one Markdown block is allowed per post. Markdown and HTML cannot be intermixed. This means that if you want to use CodeRay, you have to write the entire post in Markdown.
And Posterous’ support for Markdown leaves much to be desired. For one thing, Markdown doesn’t support page breaks. Worse, Posterous converts Markdown into HTML as soon as you submit a post so you can’t go back and re-edit the original source. 😡
Code blocks rendered by GitHub Gist (free to use, but registration required) and SyntaxHighlighter look similar. Both come with a row of links in an
<iframe> for copying the snippet to the clipboard, viewing it as plain text in a new browser window, etc. These links are a nuisance, imho, and there’s no way of getting rid of them that I’m aware of.
So that just leaves a DIY solution. How about doing funky things with
<pre> tag which Posterous insists on transforming into
<div class="CodeRay"> ... </div> (read Modifying Posterous’ Code Blocks for a workaround).
But I didn’t want to tinker with CSS or create my own custom theme. So, after some experimentation, I came up with this:
<p style="margin-left:2em;"><code>[insert code block here]</code></p>
That’s it in a nutshell. A simple and elegant solution. Well, not exactly… Unfortunately, like most things, it comes with a few provisos:
no fancy syntax highlighting
the usual suspects (
< & >) must be converted into HTML entities (
< & >)
every line in the code block (except for the last one) must end with
indentation will be compressed into a single space so replace leading spaces with
for reasons unexplained, Posterous strips out any inline CSS resembling
white-space: pre;which means you’ll have to replace every space with
in the longest line of the code block to prevent wrapping.
Enough talking! Here’s an example of the raw HTML for a trivial Batch script:
<p style="margin-left: 2em;"><code>@echo off & setlocal enableextensions<br /> <br /> if "%~1" neq "" (<br /> echo(Hello, %~1!<br /> ) else (<br /> echo(Howdy, stranger!<br /> )<br /> <br /> endlocal & exit /b 0</code></p>
And here’s how it would look on Posterous:
@echo off & setlocal enableextensions if "%~1" neq "" ( echo(Hello, %~1! ) else ( echo(Howdy, stranger! ) endlocal & exit /b 0
And there it is! Although how useful this technique will be to anyone at this point is debatable. All the same, I welcome your feedback. Feel free to leave a comment.