htmlizer.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- test-case-name: twisted.python.test.test_htmlizer -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HTML rendering of Python source.
  6. """
  7. from twisted.python.compat import _tokenize, escape
  8. import tokenize, keyword
  9. from . import reflect
  10. from twisted.python._oldstyle import _oldStyle
  11. @_oldStyle
  12. class TokenPrinter:
  13. """
  14. Format a stream of tokens and intermediate whitespace, for pretty-printing.
  15. """
  16. currentCol, currentLine = 0, 1
  17. lastIdentifier = parameters = 0
  18. encoding = "utf-8"
  19. def __init__(self, writer):
  20. self.writer = writer
  21. def printtoken(self, type, token, sCoordinates, eCoordinates, line):
  22. if hasattr(tokenize, "ENCODING") and type == tokenize.ENCODING:
  23. self.encoding = token
  24. return
  25. (srow, scol) = sCoordinates
  26. (erow, ecol) = eCoordinates
  27. if self.currentLine < srow:
  28. self.writer('\n'*(srow-self.currentLine))
  29. self.currentLine, self.currentCol = srow, 0
  30. self.writer(' '*(scol-self.currentCol))
  31. if self.lastIdentifier:
  32. type = "identifier"
  33. self.parameters = 1
  34. elif type == tokenize.NAME:
  35. if keyword.iskeyword(token):
  36. type = 'keyword'
  37. else:
  38. if self.parameters:
  39. type = 'parameter'
  40. else:
  41. type = 'variable'
  42. else:
  43. type = tokenize.tok_name.get(type).lower()
  44. self.writer(token, type)
  45. self.currentCol = ecol
  46. self.currentLine += token.count('\n')
  47. if self.currentLine != erow:
  48. self.currentCol = 0
  49. self.lastIdentifier = token in ('def', 'class')
  50. if token == ':':
  51. self.parameters = 0
  52. @_oldStyle
  53. class HTMLWriter:
  54. """
  55. Write the stream of tokens and whitespace from L{TokenPrinter}, formating
  56. tokens as HTML spans.
  57. """
  58. noSpan = []
  59. def __init__(self, writer):
  60. self.writer = writer
  61. noSpan = []
  62. reflect.accumulateClassList(self.__class__, "noSpan", noSpan)
  63. self.noSpan = noSpan
  64. def write(self, token, type=None):
  65. if isinstance(token, bytes):
  66. token = token.decode("utf-8")
  67. token = escape(token)
  68. token = token.encode("utf-8")
  69. if (type is None) or (type in self.noSpan):
  70. self.writer(token)
  71. else:
  72. self.writer(
  73. b'<span class="py-src-' + type.encode("utf-8") + b'">' +
  74. token + b'</span>')
  75. class SmallerHTMLWriter(HTMLWriter):
  76. """
  77. HTMLWriter that doesn't generate spans for some junk.
  78. Results in much smaller HTML output.
  79. """
  80. noSpan = ["endmarker", "indent", "dedent", "op", "newline", "nl"]
  81. def filter(inp, out, writer=HTMLWriter):
  82. out.write(b'<pre>')
  83. printer = TokenPrinter(writer(out.write).write).printtoken
  84. try:
  85. for token in _tokenize(inp.readline):
  86. (tokenType, string, start, end, line) = token
  87. printer(tokenType, string, start, end, line)
  88. except tokenize.TokenError:
  89. pass
  90. out.write(b'</pre>\n')
  91. def main():
  92. import sys
  93. stdout = getattr(sys.stdout, "buffer", sys.stdout)
  94. with open(sys.argv[1], "rb") as f:
  95. filter(f, stdout)
  96. if __name__ == '__main__':
  97. main()