You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

260 lines
8.9 KiB

14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. #!/usr/bin/env python3
  2. '''Add syntax highlighting to Python source code'''
  3. __author__ = 'Raymond Hettinger'
  4. import keyword, tokenize, cgi, re, functools
  5. try:
  6. import builtins
  7. except ImportError:
  8. import __builtin__ as builtins
  9. #### Analyze Python Source #################################
  10. def is_builtin(s):
  11. 'Return True if s is the name of a builtin'
  12. return hasattr(builtins, s)
  13. def combine_range(lines, start, end):
  14. 'Join content from a range of lines between start and end'
  15. (srow, scol), (erow, ecol) = start, end
  16. if srow == erow:
  17. return lines[srow-1][scol:ecol], end
  18. rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
  19. return ''.join(rows), end
  20. def analyze_python(source):
  21. '''Generate and classify chunks of Python for syntax highlighting.
  22. Yields tuples in the form: (category, categorized_text).
  23. '''
  24. lines = source.splitlines(True)
  25. lines.append('')
  26. readline = functools.partial(next, iter(lines), '')
  27. kind = tok_str = ''
  28. tok_type = tokenize.COMMENT
  29. written = (1, 0)
  30. for tok in tokenize.generate_tokens(readline):
  31. prev_tok_type, prev_tok_str = tok_type, tok_str
  32. tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
  33. kind = ''
  34. if tok_type == tokenize.COMMENT:
  35. kind = 'comment'
  36. elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;@':
  37. kind = 'operator'
  38. elif tok_type == tokenize.STRING:
  39. kind = 'string'
  40. if prev_tok_type == tokenize.INDENT or scol==0:
  41. kind = 'docstring'
  42. elif tok_type == tokenize.NAME:
  43. if tok_str in ('def', 'class', 'import', 'from'):
  44. kind = 'definition'
  45. elif prev_tok_str in ('def', 'class'):
  46. kind = 'defname'
  47. elif keyword.iskeyword(tok_str):
  48. kind = 'keyword'
  49. elif is_builtin(tok_str) and prev_tok_str != '.':
  50. kind = 'builtin'
  51. if kind:
  52. text, written = combine_range(lines, written, (srow, scol))
  53. yield '', text
  54. text, written = tok_str, (erow, ecol)
  55. yield kind, text
  56. line_upto_token, written = combine_range(lines, written, (erow, ecol))
  57. yield '', line_upto_token
  58. #### Raw Output ###########################################
  59. def raw_highlight(classified_text):
  60. 'Straight text display of text classifications'
  61. result = []
  62. for kind, text in classified_text:
  63. result.append('%15s: %r\n' % (kind or 'plain', text))
  64. return ''.join(result)
  65. #### ANSI Output ###########################################
  66. default_ansi = {
  67. 'comment': ('\033[0;31m', '\033[0m'),
  68. 'string': ('\033[0;32m', '\033[0m'),
  69. 'docstring': ('\033[0;32m', '\033[0m'),
  70. 'keyword': ('\033[0;33m', '\033[0m'),
  71. 'builtin': ('\033[0;35m', '\033[0m'),
  72. 'definition': ('\033[0;33m', '\033[0m'),
  73. 'defname': ('\033[0;34m', '\033[0m'),
  74. 'operator': ('\033[0;33m', '\033[0m'),
  75. }
  76. def ansi_highlight(classified_text, colors=default_ansi):
  77. 'Add syntax highlighting to source code using ANSI escape sequences'
  78. # http://en.wikipedia.org/wiki/ANSI_escape_code
  79. result = []
  80. for kind, text in classified_text:
  81. opener, closer = colors.get(kind, ('', ''))
  82. result += [opener, text, closer]
  83. return ''.join(result)
  84. #### HTML Output ###########################################
  85. def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
  86. 'Convert classified text to an HTML fragment'
  87. result = [opener]
  88. for kind, text in classified_text:
  89. if kind:
  90. result.append('<span class="%s">' % kind)
  91. result.append(cgi.escape(text))
  92. if kind:
  93. result.append('</span>')
  94. result.append(closer)
  95. return ''.join(result)
  96. default_css = {
  97. '.comment': '{color: crimson;}',
  98. '.string': '{color: forestgreen;}',
  99. '.docstring': '{color: forestgreen; font-style:italic;}',
  100. '.keyword': '{color: darkorange;}',
  101. '.builtin': '{color: purple;}',
  102. '.definition': '{color: darkorange; font-weight:bold;}',
  103. '.defname': '{color: blue;}',
  104. '.operator': '{color: brown;}',
  105. }
  106. default_html = '''\
  107. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  108. "http://www.w3.org/TR/html4/strict.dtd">
  109. <html>
  110. <head>
  111. <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
  112. <title> {title} </title>
  113. <style type="text/css">
  114. {css}
  115. </style>
  116. </head>
  117. <body>
  118. {body}
  119. </body>
  120. </html>
  121. '''
  122. def build_html_page(classified_text, title='python',
  123. css=default_css, html=default_html):
  124. 'Create a complete HTML page with colorized source code'
  125. css_str = '\n'.join(['%s %s' % item for item in css.items()])
  126. result = html_highlight(classified_text)
  127. title = cgi.escape(title)
  128. return html.format(title=title, css=css_str, body=result)
  129. #### LaTeX Output ##########################################
  130. default_latex_commands = {
  131. 'comment': '{\color{red}#1}',
  132. 'string': '{\color{ForestGreen}#1}',
  133. 'docstring': '{\emph{\color{ForestGreen}#1}}',
  134. 'keyword': '{\color{orange}#1}',
  135. 'builtin': '{\color{purple}#1}',
  136. 'definition': '{\color{orange}#1}',
  137. 'defname': '{\color{blue}#1}',
  138. 'operator': '{\color{brown}#1}',
  139. }
  140. default_latex_document = r'''
  141. \documentclass{article}
  142. \usepackage{alltt}
  143. \usepackage{upquote}
  144. \usepackage{color}
  145. \usepackage[usenames,dvipsnames]{xcolor}
  146. \usepackage[cm]{fullpage}
  147. %(macros)s
  148. \begin{document}
  149. \center{\LARGE{%(title)s}}
  150. \begin{alltt}
  151. %(body)s
  152. \end{alltt}
  153. \end{document}
  154. '''
  155. def alltt_escape(s):
  156. 'Replace backslash and braces with their escaped equivalents'
  157. xlat = {'{': r'\{', '}': r'\}', '\\': r'\textbackslash{}'}
  158. return re.sub(r'[\\{}]', lambda mo: xlat[mo.group()], s)
  159. def latex_highlight(classified_text, title = 'python',
  160. commands = default_latex_commands,
  161. document = default_latex_document):
  162. 'Create a complete LaTeX document with colorized source code'
  163. macros = '\n'.join(r'\newcommand{\py%s}[1]{%s}' % c for c in commands.items())
  164. result = []
  165. for kind, text in classified_text:
  166. if kind:
  167. result.append(r'\py%s{' % kind)
  168. result.append(alltt_escape(text))
  169. if kind:
  170. result.append('}')
  171. return default_latex_document % dict(title=title, macros=macros, body=''.join(result))
  172. if __name__ == '__main__':
  173. import sys, argparse, webbrowser, os, textwrap
  174. parser = argparse.ArgumentParser(
  175. description = 'Add syntax highlighting to Python source code',
  176. formatter_class=argparse.RawDescriptionHelpFormatter,
  177. epilog = textwrap.dedent('''
  178. examples:
  179. # Show syntax highlighted code in the terminal window
  180. $ ./highlight.py myfile.py
  181. # Colorize myfile.py and display in a browser
  182. $ ./highlight.py -b myfile.py
  183. # Create an HTML section to embed in an existing webpage
  184. ./highlight.py -s myfile.py
  185. # Create a complete HTML file
  186. $ ./highlight.py -c myfile.py > myfile.html
  187. # Create a PDF using LaTeX
  188. $ ./highlight.py -l myfile.py | pdflatex
  189. '''))
  190. parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
  191. help = 'file containing Python sourcecode')
  192. parser.add_argument('-b', '--browser', action = 'store_true',
  193. help = 'launch a browser to show results')
  194. parser.add_argument('-c', '--complete', action = 'store_true',
  195. help = 'build a complete html webpage')
  196. parser.add_argument('-l', '--latex', action = 'store_true',
  197. help = 'build a LaTeX document')
  198. parser.add_argument('-r', '--raw', action = 'store_true',
  199. help = 'raw parse of categorized text')
  200. parser.add_argument('-s', '--section', action = 'store_true',
  201. help = 'show an HTML section rather than a complete webpage')
  202. args = parser.parse_args()
  203. if args.section and (args.browser or args.complete):
  204. parser.error('The -s/--section option is incompatible with '
  205. 'the -b/--browser or -c/--complete options')
  206. sourcefile = args.sourcefile
  207. with open(sourcefile) as f:
  208. source = f.read()
  209. classified_text = analyze_python(source)
  210. if args.raw:
  211. encoded = raw_highlight(classified_text)
  212. elif args.complete or args.browser:
  213. encoded = build_html_page(classified_text, title=sourcefile)
  214. elif args.section:
  215. encoded = html_highlight(classified_text)
  216. elif args.latex:
  217. encoded = latex_highlight(classified_text, title=sourcefile)
  218. else:
  219. encoded = ansi_highlight(classified_text)
  220. if args.browser:
  221. htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
  222. with open(htmlfile, 'w') as f:
  223. f.write(encoded)
  224. webbrowser.open('file://' + os.path.abspath(htmlfile))
  225. else:
  226. sys.stdout.write(encoded)