blob: 022e02d80b169e591415b13a4924667d51ba9f4e [file] [log] [blame]
Raymond Hettingerbc09cf12012-06-30 16:58:06 -07001#!/usr/bin/env python3
Raymond Hettinger0712f402012-07-03 14:42:33 -07002'''Add syntax highlighting to Python source code
3
4Example command-line calls:
5
6 # Show syntax highlighted code in the terminal window
7 $ ./highlight.py -a myfile.py
8
9 # Colorize myfile.py and display in a browser
10 $ ./highlight.py -b myfile.py
11
12 # Create an HTML section that can be embedded in an existing webpage
13 ./highlight.py -s myfile.py
14
15 # Create a complete HTML file
16 $ ./highlight.py myfile.py > myfile.html
17
18'''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070019
Raymond Hettinger3a961612012-07-03 14:11:40 -070020__all__ = ['colorize', 'build_page', 'default_css', 'default_html',
21 'ansi_colorize', 'default_ansi']
Raymond Hettinger9b8ede62012-06-30 23:19:30 -070022__author__ = 'Raymond Hettinger'
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070023
24import keyword, tokenize, cgi, functools
25
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070026def is_builtin(s):
27 'Return True if s is the name of a builtin'
28 return s in vars(__builtins__)
29
Raymond Hettinger5da60392012-07-03 13:13:52 -070030def combine_range(lines, start, end):
31 'Join content from a range of lines between start and end'
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070032 (srow, scol), (erow, ecol) = start, end
33 if srow == erow:
34 rows = [lines[srow-1][scol:ecol]]
35 else:
36 rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
Raymond Hettinger5da60392012-07-03 13:13:52 -070037 return ''.join(rows), end
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070038
Raymond Hettinger5da60392012-07-03 13:13:52 -070039def isolate_tokens(source):
Raymond Hettinger1087d9c2012-07-03 14:25:16 -070040 'Generate chunks of source and identify chunks to be highlighted'
Raymond Hettingerac5f8462012-07-03 00:15:59 -070041 lines = source.splitlines(True)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070042 lines.append('')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070043 readline = functools.partial(next, iter(lines), '')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070044 kind = tok_str = ''
45 tok_type = tokenize.COMMENT
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070046 written = (1, 0)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070047 for tok in tokenize.generate_tokens(readline):
48 prev_tok_type, prev_tok_str = tok_type, tok_str
49 tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettingercf6eac42012-07-03 00:12:27 -070050 kind = ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070051 if tok_type == tokenize.COMMENT:
52 kind = 'comment'
Raymond Hettingere4870b52012-07-01 00:37:05 -070053 elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;':
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070054 kind = 'operator'
55 elif tok_type == tokenize.STRING:
56 kind = 'string'
57 if prev_tok_type == tokenize.INDENT or scol==0:
58 kind = 'docstring'
59 elif tok_type == tokenize.NAME:
60 if tok_str in ('def', 'class', 'import', 'from'):
61 kind = 'definition'
62 elif prev_tok_str in ('def', 'class'):
63 kind = 'defname'
64 elif keyword.iskeyword(tok_str):
65 kind = 'keyword'
66 elif is_builtin(tok_str) and prev_tok_str != '.':
67 kind = 'builtin'
Raymond Hettinger5da60392012-07-03 13:13:52 -070068 line_upto_token, written = combine_range(lines, written, (srow, scol))
69 line_thru_token, written = combine_range(lines, written, (erow, ecol))
70 yield kind, line_upto_token, line_thru_token
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070071
Raymond Hettinger3a961612012-07-03 14:11:40 -070072default_ansi = {
73 'comment': '\033[0;31m',
74 'string': '\033[0;32m',
75 'docstring': '\033[0;32m',
76 'keyword': '\033[0;33m',
77 'builtin': '\033[0;35m',
78 'definition': '\033[0;33m',
79 'defname': '\033[0;34m',
80 'operator': '\033[0;33m',
81}
82
83def colorize_ansi(source, colors=default_ansi):
84 'Add syntax highlighting to Python source code using ANSI escape sequences'
85 # http://en.wikipedia.org/wiki/ANSI_escape_code
86 result = []
87 for kind, line_upto_token, line_thru_token in isolate_tokens(source):
88 if kind:
89 result += [line_upto_token, colors[kind], line_thru_token, '\033[0m']
90 else:
91 result += [line_upto_token, line_thru_token]
92 return ''.join(result)
93
94def colorize_html(source):
Raymond Hettinger5da60392012-07-03 13:13:52 -070095 'Convert Python source code to an HTML fragment with colorized markup'
96 result = ['<pre class="python">\n']
97 for kind, line_upto_token, line_thru_token in isolate_tokens(source):
98 if kind:
99 result += [cgi.escape(line_upto_token),
100 '<span class="%s">' % kind,
101 cgi.escape(line_thru_token),
102 '</span>']
103 else:
104 result += [cgi.escape(line_upto_token),
105 cgi.escape(line_thru_token)]
106 result += ['</pre>\n']
Raymond Hettingerf2cc3522012-07-02 13:29:57 -0700107 return ''.join(result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700108
109default_css = {
110 '.comment': '{color: crimson;}',
111 '.string': '{color: forestgreen;}',
Raymond Hettinger5da60392012-07-03 13:13:52 -0700112 '.docstring': '{color: forestgreen; font-style:italic;}',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700113 '.keyword': '{color: darkorange;}',
114 '.builtin': '{color: purple;}',
115 '.definition': '{color: darkorange; font-weight:bold;}',
116 '.defname': '{color: blue;}',
117 '.operator': '{color: brown;}',
118}
119
120default_html = '''\
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700121<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
122 "http://www.w3.org/TR/html4/strict.dtd">
123<html>
124<head>
125<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700126<title> {title} </title>
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700127<style type="text/css">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700128{css}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700129</style>
130</head>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700131<body>
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700132{body}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700133</body>
134</html>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700135'''
136
Raymond Hettinger9b8ede62012-06-30 23:19:30 -0700137def build_page(source, title='python', css=default_css, html=default_html):
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700138 'Create a complete HTML page with colorized Python source code'
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700139 css_str = '\n'.join(['%s %s' % item for item in css.items()])
Raymond Hettinger3a961612012-07-03 14:11:40 -0700140 result = colorize_html(source)
Raymond Hettinger9b8ede62012-06-30 23:19:30 -0700141 title = cgi.escape(title)
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700142 return html.format(title=title, css=css_str, body=result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700143
144
145if __name__ == '__main__':
146 import sys, argparse, webbrowser, os
147
148 parser = argparse.ArgumentParser(
Raymond Hettinger3a961612012-07-03 14:11:40 -0700149 description = 'Add syntax highlighting to Python source')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700150 parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700151 help = 'File containing Python sourcecode')
Raymond Hettinger3a961612012-07-03 14:11:40 -0700152 parser.add_argument('-a', '--ansi', action = 'store_true',
153 help = 'emit ANSI escape highlighted source')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700154 parser.add_argument('-b', '--browser', action = 'store_true',
155 help = 'launch a browser to show results')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700156 parser.add_argument('-s', '--section', action = 'store_true',
157 help = 'show an HTML section rather than a complete webpage')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700158 args = parser.parse_args()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700159
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700160 if args.browser and args.section:
161 parser.error('The -s/--section option is incompatible with '
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700162 'the -b/--browser option')
Raymond Hettinger3a961612012-07-03 14:11:40 -0700163 if args.ansi and (args.browser or args.section):
164 parser.error('The -a/--ansi option is incompatible with '
165 'the -b/--browser and -s/--section options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700166
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700167 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700168 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700169 source = f.read()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700170
171 if args.ansi:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700172 encoded = colorize_ansi(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700173 elif args.section:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700174 encoded = colorize_html(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700175 else:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700176 encoded = build_page(source, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700177
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700178 if args.browser:
179 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
180 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700181 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700182 webbrowser.open('file://' + os.path.abspath(htmlfile))
183 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700184 sys.stdout.write(encoded)