#!/usr/bin/python """ MoinMoin - Python Source Parser """ # Imports import cgi, string, sys, cStringIO import keyword, token, tokenize ############################################################################# ### Python Source Parser (does Hilighting) ############################################################################# _KEYWORD = token.NT_OFFSET + 1 _TEXT = token.NT_OFFSET + 2 _colors = { token.NUMBER: '#0080C0', token.OP: '#0000C0', token.STRING: '#004080', tokenize.COMMENT: '#008000', token.NAME: '#000000', token.ERRORTOKEN: '#FF8080', _KEYWORD: '#C00000', _TEXT: '#000000', } class Parser: """ Send colored python source. """ def __init__(self, raw, out = sys.stdout): """ Store the source text. """ self.raw = string.strip(string.expandtabs(raw)) self.out = out def format(self, formatter, form): """ 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 = cStringIO.StringIO(self.raw) self.out.write('
') try: tokenize.tokenize(text.readline, self) except tokenize.TokenError, ex: msg = ex[0] line = ex[1][0] self.out.write("') def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line): """ Token handler. """ if 0: print "type", toktype, token.tok_name[toktype], "text", toktext, print "start", srow,scol, "end", erow,ecol, "ERROR: %s
%s\n" % ( msg, self.raw[self.lines[line]:])) self.out.write('