""" Original code from active state recipe 'Colorize Python source using the built-in tokenizer' ---------------------------------------------------------------------------- MoinMoin - Python Source Parser This code is part of MoinMoin (http://moin.sourceforge.net/) and converts Python source code to HTML markup, rendering comments, keywords, operators, numeric and string literals in different colors. It shows how to use the built-in keyword, token and tokenize modules to scan Python source code and re-emit it with no changes to its original formatting (which is the hard part). """ __revision__ = '$Id: python.py 3661 2005-02-23 17:05:31Z tiran $' import string import keyword, token, tokenize from cStringIO import StringIO from Products.PortalTransforms.interfaces import itransform from DocumentTemplate.DT_Util import html_quote ## Python Source Parser ##################################################### _KEYWORD = token.NT_OFFSET + 1 _TEXT = token.NT_OFFSET + 2 class Parser: """ Send colored python source. """ def __init__(self, raw, tags, out): """ Store the source text. """ self.raw = string.strip(string.expandtabs(raw)) self.out = out self.tags = tags def format(self): """ Parse and send the colored source. """ # store line offsets in self.lines self.lines = [0, 0] pos = 0 while 1: pos = string.find(self.raw, '\n', pos) + 1 if not pos: break self.lines.append(pos) self.lines.append(len(self.raw)) # parse the source and write it self.pos = 0 text = StringIO(self.raw) self.out.write('
\n')
try:
tokenize.tokenize(text.readline, self)
except tokenize.TokenError, ex:
msg = ex[0]
line = ex[1][0]
self.out.write("" % (
msg, self.raw[self.lines[line]:]))
self.out.write('\n
\n')
def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line):
""" Token handler.
"""
#print "type", toktype, token.tok_name[toktype], "text", toktext,
#print "start", srow,scol, "end", erow,ecol, "