reStructuredText directive for google-code-prettify
reStructuredText is teh light markup format, if you never heard about it go check it out. If you are still living in a Docbook world, you would be amazed of what rst and Sphinx can do for your productivity.
Anyway, for the last articles I needed a prettify solution to publish several code listings. I use django-mingus as my blog engine, it comes with not one but two solutions for this problem. The first one is Pygments, which is very nice but no matter what I tried could not make it work. The second is prettify.js, a javascript module plus some css, that prettifies in the client side at runtime.
The only problem of this approach is that the code list will not show up prettified in RSS and such. But you suffered the same problem with Pygments anyway unless you inlined the styles.
The reStructuredText directive
The code is deadly simple:
from cgi import escape
from docutils import nodes
from docutils.parsers.rst import directives, Directive
class CodeDirective(Directive):
"""
reStructuredText directive to show code listings with google-code-prettify
"""
has_content = True
def run(self):
self.assert_has_content()
text = '<pre class="prettyprint">%s</pre>' % self._get_escaped_content()
return [nodes.raw('', text, format='html')]
def _get_escaped_content(self):
return '\n'.join(map(escape, self.content))
directives.register_directive("code-list", CodeDirective)
directives.register_directive("sourcecode", CodeDirective)It just wraps the code in <pre class="prettyprint"> and </pre>, and that's it. Oh well, it also wanted the content to be escaped, fortunately Python comes with a handy function for it: cgi.escape. I will probably write an article about rst directives soon, there is not that much documentation about it.
blog comments powered by Disqus