blob: 9272fee4ee3b9df4410e192ff9a2b8de9ab82ebe [file] [log] [blame]
Raymond Hettingerbc09cf12012-06-30 16:58:06 -07001#!/usr/bin/env python3
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -07002'''Add syntax highlighting to Python source code'''
Raymond Hettinger0712f402012-07-03 14:42:33 -07003
Raymond Hettinger9b8ede62012-06-30 23:19:30 -07004__author__ = 'Raymond Hettinger'
Raymond Hettingerbc09cf12012-06-30 16:58:06 -07005
Serhiy Storchaka7a1104d2014-12-01 10:50:33 +02006import builtins
7import functools
8import html as html_module
9import keyword
10import re
11import tokenize
Raymond Hettinger7d390552012-07-09 23:52:08 -070012
13#### Analyze Python Source #################################
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070014
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070015def is_builtin(s):
16 'Return True if s is the name of a builtin'
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070017 return hasattr(builtins, s)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070018
Raymond Hettinger5da60392012-07-03 13:13:52 -070019def combine_range(lines, start, end):
20 'Join content from a range of lines between start and end'
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070021 (srow, scol), (erow, ecol) = start, end
22 if srow == erow:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070023 return lines[srow-1][scol:ecol], end
24 rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
Raymond Hettinger5da60392012-07-03 13:13:52 -070025 return ''.join(rows), end
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070026
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070027def analyze_python(source):
28 '''Generate and classify chunks of Python for syntax highlighting.
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070029 Yields tuples in the form: (category, categorized_text).
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070030 '''
Raymond Hettingerac5f8462012-07-03 00:15:59 -070031 lines = source.splitlines(True)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070032 lines.append('')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070033 readline = functools.partial(next, iter(lines), '')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070034 kind = tok_str = ''
35 tok_type = tokenize.COMMENT
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070036 written = (1, 0)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070037 for tok in tokenize.generate_tokens(readline):
38 prev_tok_type, prev_tok_str = tok_type, tok_str
39 tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettingercf6eac42012-07-03 00:12:27 -070040 kind = ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070041 if tok_type == tokenize.COMMENT:
42 kind = 'comment'
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070043 elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;@':
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070044 kind = 'operator'
45 elif tok_type == tokenize.STRING:
46 kind = 'string'
47 if prev_tok_type == tokenize.INDENT or scol==0:
48 kind = 'docstring'
49 elif tok_type == tokenize.NAME:
50 if tok_str in ('def', 'class', 'import', 'from'):
51 kind = 'definition'
52 elif prev_tok_str in ('def', 'class'):
53 kind = 'defname'
54 elif keyword.iskeyword(tok_str):
55 kind = 'keyword'
56 elif is_builtin(tok_str) and prev_tok_str != '.':
57 kind = 'builtin'
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070058 if kind:
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070059 text, written = combine_range(lines, written, (srow, scol))
60 yield '', text
Raymond Hettingerd3f63d32012-07-23 00:24:24 -050061 text, written = tok_str, (erow, ecol)
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070062 yield kind, text
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070063 line_upto_token, written = combine_range(lines, written, (erow, ecol))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070064 yield '', line_upto_token
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070065
Raymond Hettinger7d390552012-07-09 23:52:08 -070066#### Raw Output ###########################################
67
68def raw_highlight(classified_text):
69 'Straight text display of text classifications'
70 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070071 for kind, text in classified_text:
72 result.append('%15s: %r\n' % (kind or 'plain', text))
Raymond Hettinger7d390552012-07-09 23:52:08 -070073 return ''.join(result)
74
75#### ANSI Output ###########################################
76
Raymond Hettinger3a961612012-07-03 14:11:40 -070077default_ansi = {
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070078 'comment': ('\033[0;31m', '\033[0m'),
79 'string': ('\033[0;32m', '\033[0m'),
80 'docstring': ('\033[0;32m', '\033[0m'),
81 'keyword': ('\033[0;33m', '\033[0m'),
82 'builtin': ('\033[0;35m', '\033[0m'),
83 'definition': ('\033[0;33m', '\033[0m'),
84 'defname': ('\033[0;34m', '\033[0m'),
85 'operator': ('\033[0;33m', '\033[0m'),
Raymond Hettinger3a961612012-07-03 14:11:40 -070086}
87
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070088def ansi_highlight(classified_text, colors=default_ansi):
89 'Add syntax highlighting to source code using ANSI escape sequences'
Raymond Hettinger3a961612012-07-03 14:11:40 -070090 # http://en.wikipedia.org/wiki/ANSI_escape_code
91 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070092 for kind, text in classified_text:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070093 opener, closer = colors.get(kind, ('', ''))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070094 result += [opener, text, closer]
Raymond Hettinger3a961612012-07-03 14:11:40 -070095 return ''.join(result)
96
Raymond Hettinger7d390552012-07-09 23:52:08 -070097#### HTML Output ###########################################
98
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070099def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
100 'Convert classified text to an HTML fragment'
101 result = [opener]
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700102 for kind, text in classified_text:
Raymond Hettinger5da60392012-07-03 13:13:52 -0700103 if kind:
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700104 result.append('<span class="%s">' % kind)
Serhiy Storchaka7a1104d2014-12-01 10:50:33 +0200105 result.append(html_module.escape(text))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700106 if kind:
107 result.append('</span>')
108 result.append(closer)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -0700109 return ''.join(result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700110
111default_css = {
112 '.comment': '{color: crimson;}',
113 '.string': '{color: forestgreen;}',
Raymond Hettinger5da60392012-07-03 13:13:52 -0700114 '.docstring': '{color: forestgreen; font-style:italic;}',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700115 '.keyword': '{color: darkorange;}',
116 '.builtin': '{color: purple;}',
117 '.definition': '{color: darkorange; font-weight:bold;}',
118 '.defname': '{color: blue;}',
119 '.operator': '{color: brown;}',
120}
121
122default_html = '''\
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700123<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
124 "http://www.w3.org/TR/html4/strict.dtd">
125<html>
126<head>
127<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700128<title> {title} </title>
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700129<style type="text/css">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700130{css}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700131</style>
132</head>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700133<body>
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700134{body}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700135</body>
136</html>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700137'''
138
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700139def build_html_page(classified_text, title='python',
140 css=default_css, html=default_html):
141 'Create a complete HTML page with colorized source code'
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700142 css_str = '\n'.join(['%s %s' % item for item in css.items()])
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700143 result = html_highlight(classified_text)
Serhiy Storchaka7a1104d2014-12-01 10:50:33 +0200144 title = html_module.escape(title)
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700145 return html.format(title=title, css=css_str, body=result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700146
Raymond Hettinger7d390552012-07-09 23:52:08 -0700147#### LaTeX Output ##########################################
148
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700149default_latex_commands = {
R David Murray44b548d2016-09-08 13:59:53 -0400150 'comment': r'{\color{red}#1}',
151 'string': r'{\color{ForestGreen}#1}',
152 'docstring': r'{\emph{\color{ForestGreen}#1}}',
153 'keyword': r'{\color{orange}#1}',
154 'builtin': r'{\color{purple}#1}',
155 'definition': r'{\color{orange}#1}',
156 'defname': r'{\color{blue}#1}',
157 'operator': r'{\color{brown}#1}',
Raymond Hettinger7d390552012-07-09 23:52:08 -0700158}
159
160default_latex_document = r'''
161\documentclass{article}
162\usepackage{alltt}
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700163\usepackage{upquote}
Raymond Hettinger7d390552012-07-09 23:52:08 -0700164\usepackage{color}
165\usepackage[usenames,dvipsnames]{xcolor}
166\usepackage[cm]{fullpage}
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700167%(macros)s
Raymond Hettinger7d390552012-07-09 23:52:08 -0700168\begin{document}
169\center{\LARGE{%(title)s}}
170\begin{alltt}
171%(body)s
172\end{alltt}
173\end{document}
174'''
175
Raymond Hettingerd3f63d32012-07-23 00:24:24 -0500176def alltt_escape(s):
177 'Replace backslash and braces with their escaped equivalents'
178 xlat = {'{': r'\{', '}': r'\}', '\\': r'\textbackslash{}'}
179 return re.sub(r'[\\{}]', lambda mo: xlat[mo.group()], s)
Raymond Hettinger7d390552012-07-09 23:52:08 -0700180
181def latex_highlight(classified_text, title = 'python',
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700182 commands = default_latex_commands,
Raymond Hettinger7d390552012-07-09 23:52:08 -0700183 document = default_latex_document):
184 'Create a complete LaTeX document with colorized source code'
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700185 macros = '\n'.join(r'\newcommand{\py%s}[1]{%s}' % c for c in commands.items())
Raymond Hettinger7d390552012-07-09 23:52:08 -0700186 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700187 for kind, text in classified_text:
Raymond Hettinger7d390552012-07-09 23:52:08 -0700188 if kind:
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700189 result.append(r'\py%s{' % kind)
Raymond Hettingerd3f63d32012-07-23 00:24:24 -0500190 result.append(alltt_escape(text))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700191 if kind:
192 result.append('}')
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700193 return default_latex_document % dict(title=title, macros=macros, body=''.join(result))
Raymond Hettinger7d390552012-07-09 23:52:08 -0700194
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700195
196if __name__ == '__main__':
Serhiy Storchaka7a1104d2014-12-01 10:50:33 +0200197 import argparse
198 import os.path
199 import sys
200 import textwrap
201 import webbrowser
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700202
203 parser = argparse.ArgumentParser(
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700204 description = 'Add syntax highlighting to Python source code',
205 formatter_class=argparse.RawDescriptionHelpFormatter,
206 epilog = textwrap.dedent('''
207 examples:
208
209 # Show syntax highlighted code in the terminal window
210 $ ./highlight.py myfile.py
211
212 # Colorize myfile.py and display in a browser
213 $ ./highlight.py -b myfile.py
214
215 # Create an HTML section to embed in an existing webpage
216 ./highlight.py -s myfile.py
217
218 # Create a complete HTML file
219 $ ./highlight.py -c myfile.py > myfile.html
Raymond Hettinger7d390552012-07-09 23:52:08 -0700220
221 # Create a PDF using LaTeX
222 $ ./highlight.py -l myfile.py | pdflatex
223
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700224 '''))
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700225 parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700226 help = 'file containing Python sourcecode')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700227 parser.add_argument('-b', '--browser', action = 'store_true',
228 help = 'launch a browser to show results')
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700229 parser.add_argument('-c', '--complete', action = 'store_true',
230 help = 'build a complete html webpage')
Raymond Hettinger7d390552012-07-09 23:52:08 -0700231 parser.add_argument('-l', '--latex', action = 'store_true',
232 help = 'build a LaTeX document')
233 parser.add_argument('-r', '--raw', action = 'store_true',
234 help = 'raw parse of categorized text')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700235 parser.add_argument('-s', '--section', action = 'store_true',
236 help = 'show an HTML section rather than a complete webpage')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700237 args = parser.parse_args()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700238
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700239 if args.section and (args.browser or args.complete):
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700240 parser.error('The -s/--section option is incompatible with '
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700241 'the -b/--browser or -c/--complete options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700242
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700243 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700244 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700245 source = f.read()
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700246 classified_text = analyze_python(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700247
Raymond Hettinger7d390552012-07-09 23:52:08 -0700248 if args.raw:
249 encoded = raw_highlight(classified_text)
250 elif args.complete or args.browser:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700251 encoded = build_html_page(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700252 elif args.section:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700253 encoded = html_highlight(classified_text)
Raymond Hettinger7d390552012-07-09 23:52:08 -0700254 elif args.latex:
255 encoded = latex_highlight(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700256 else:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700257 encoded = ansi_highlight(classified_text)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700258
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700259 if args.browser:
260 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
261 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700262 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700263 webbrowser.open('file://' + os.path.abspath(htmlfile))
264 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700265 sys.stdout.write(encoded)