Coding for the Web: A Proposal for Better Inline Syntax Highlighting

Monday, March 14, 2011.

Update: I've since switched from this syntax to fenced code blocks.

Markdown is great for semi-structured text. Pygments is great for syntax highlighting. This blog uses both: jekyll+liquid passes code snippets surrounded by {% highlight languageX %} and {% endhighlight %} to pygments. The rest gets processed with markdown.

So is there anything to complain about here? As usual, the answer is yes.

To summarize, a better solution:

On to the specific proposal, which is really nothing fancy or new:

In a sense, this is a solved problem.

My editor already does syntax highlighting based on the shebang line, and chances are, so does yours. In many cases it also makes the code snippet more complete: if you're going to copy and paste it into a new script, you're going to add the shebang line anyway. But you could also choose to suppress the shebang line when rendering.

Another solution might be to use a modeline. In either case, you're embedding information in a language-specific comment, and doing so in a way that already has precedent.

Here's an example code snippet from the documentation for python-percentcoding:

#!/usr/bin/env python
from percentcoding import quote, unquote
str = "This is a test!"
escaped = quote(str)
print escaped
assert(str == unquote(escaped))

I've already implemented the proposal in Python here, in order to generate html documentation for pypi. It would need to be ported over to Ruby for use in jekyll+liquid.

Posted by Alan on Monday, March 14, 2011.