1 # -*- test-case-name: twisted.python.test.test_htmlizer -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 HTML rendering of Python source.
9 import tokenize, cgi, keyword
14 currentCol, currentLine = 0, 1
15 lastIdentifier = parameters = 0
17 def __init__(self, writer):
20 def printtoken(self, type, token, (srow, scol), (erow, ecol), line):
21 #print "printtoken(%r,%r,%r,(%r,%r),(%r,%r),%r), row=%r,col=%r" % (
22 # self, type, token, srow,scol, erow,ecol, line,
23 # self.currentLine, self.currentCol)
24 if self.currentLine < srow:
25 self.writer('\n'*(srow-self.currentLine))
26 self.currentLine, self.currentCol = srow, 0
27 self.writer(' '*(scol-self.currentCol))
28 if self.lastIdentifier:
31 elif type == tokenize.NAME:
32 if keyword.iskeyword(token):
40 type = tokenize.tok_name.get(type).lower()
41 self.writer(token, type)
42 self.currentCol = ecol
43 self.currentLine += token.count('\n')
44 if self.currentLine != erow:
46 self.lastIdentifier = token in ('def', 'class')
55 def __init__(self, writer):
58 reflect.accumulateClassList(self.__class__, "noSpan", noSpan)
61 def write(self, token, type=None):
62 token = cgi.escape(token)
63 if (type is None) or (type in self.noSpan):
66 self.writer('<span class="py-src-%s">%s</span>' %
70 class SmallerHTMLWriter(HTMLWriter):
71 """HTMLWriter that doesn't generate spans for some junk.
73 Results in much smaller HTML output.
75 noSpan = ["endmarker", "indent", "dedent", "op", "newline", "nl"]
77 def filter(inp, out, writer=HTMLWriter):
79 printer = TokenPrinter(writer(out.write).write).printtoken
81 tokenize.tokenize(inp.readline, printer)
82 except tokenize.TokenError:
88 filter(open(sys.argv[1]), sys.stdout)
90 if __name__ == '__main__':