blob: 74f864910f9ae9a32e28f34dfd2534750d0e58c0 [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
Raymond Hettinger5b381a32012-07-03 17:55:23 -07007 $ ./highlight.py myfile.py
Raymond Hettinger0712f402012-07-03 14:42:33 -07008
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
Raymond Hettinger5b381a32012-07-03 17:55:23 -070016 $ ./highlight.py -c myfile.py > myfile.html
Raymond Hettinger0712f402012-07-03 14:42:33 -070017
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')
152 parser.add_argument('-b', '--browser', action = 'store_true',
153 help = 'launch a browser to show results')
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700154 parser.add_argument('-c', '--complete', action = 'store_true',
155 help = 'build a complete html webpage')
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 Hettinger5b381a32012-07-03 17:55:23 -0700160 if args.section and (args.browser or args.complete):
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700161 parser.error('The -s/--section option is incompatible with '
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700162 'the -b/--browser or -c/--complete options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700163
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700164 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700165 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700166 source = f.read()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700167
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700168 if args.complete or args.browser:
169 encoded = build_page(source, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700170 elif args.section:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700171 encoded = colorize_html(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700172 else:
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700173 encoded = colorize_ansi(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700174
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700175 if args.browser:
176 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
177 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700178 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700179 webbrowser.open('file://' + os.path.abspath(htmlfile))
180 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700181 sys.stdout.write(encoded)