About

Welcome to Panela, Matt Harrison's take on mostly Open Source, Linux, Python, innovation in those areas, other buzzwords and Dick Proenneke. It comes complete with the illustrations as needed. Note the opinions expressed here are merely my opinions and not the opinions of my employer.

about Matt

Calendar

««Nov 2008»»
SMTWTFS
       1
2345678
9101112
13
1415
16171819202122
23242526272829
30

My Top Tags

                                       

Mailing List

My RSS Feeds








Howto create a pygments backend

posted 2007.09.05 Wed

Pygments is a source code highlighter. I believe the main purpose is to format code/markup for webpages (forums, blogs, wikis, trac, etc). (I used it on my previous post). But it also has renderers for latex, rtf and bbcode. I happened to desire an SVG backend yesterday, so I'll share my experience.

On first thought I went to #inkscape (an svg editor) and asked if they understood (or could import) the html/css output of pygments. It turns out that with some careful substitutions it can be done. One kind soul even went so far as to write me some java(!?!) code that did this. Finally my brain kicked in and I though why not just write an SVG backend for pygments? Pygments is written in python and I have done some SVG creating using the SVGdraw.py code before that was pretty straightforward.

(Seems like the creators of SVGdraw.py have let it drift into the ether.... Sad cause it is a useful tool, luckily I have a copy)

So I asked about on #pocoo how to create an SVG backend, and was told to model it after formatters/html.py. Here's what I learned while creating the SVG backend:

  • Subclass
    formatter.Formatter
  • Implement a
    format(self, tokensource, outfile)
    function. Tokensource is an iterable of tokentype, token tuples. Using style information (mapping tokentype to a style) found in the self.style.styles member, write your formatted content to the outfile
  • Add some class attributes: name, aliases, and filename used for command line help. Mine were "SVG", ["svg"], ["*.svg"] respectively.
  • Update
    formatters/_mapping.py
    to add your formatter to the FORMATTERS dictionary.
  • This is the step after the last step

Try out your new code by running the following command:

./pygementize -f svg fileToMakePretty.py
(replace svg with your new formatter)

tags:          

links: digg this    del.icio.us    reddit