blob: ef010e8f31c33cd3b6fa16cbd49f7d20cb8c9ef0 [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 Hettinger42a5f4a2012-07-08 15:42:54 -07004__all__ = ['analyze_python', 'ansi_highlight', 'default_ansi',
5 'html_highlight', 'build_html_page', 'default_css', 'default_html']
Raymond Hettinger0712f402012-07-03 14:42:33 -07006
Raymond Hettinger9b8ede62012-06-30 23:19:30 -07007__author__ = 'Raymond Hettinger'
Raymond Hettingerbc09cf12012-06-30 16:58:06 -07008
9import keyword, tokenize, cgi, functools
10
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070011def is_builtin(s):
12 'Return True if s is the name of a builtin'
13 return s in vars(__builtins__)
14
Raymond Hettinger5da60392012-07-03 13:13:52 -070015def combine_range(lines, start, end):
16 'Join content from a range of lines between start and end'
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070017 (srow, scol), (erow, ecol) = start, end
18 if srow == erow:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070019 return lines[srow-1][scol:ecol], end
20 rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
Raymond Hettinger5da60392012-07-03 13:13:52 -070021 return ''.join(rows), end
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070022
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070023def analyze_python(source):
24 '''Generate and classify chunks of Python for syntax highlighting.
25 Yields tuples in the form: (leadin_text, category, categorized_text).
26 The final tuple has empty strings for the category and categorized text.
27
28 '''
Raymond Hettingerac5f8462012-07-03 00:15:59 -070029 lines = source.splitlines(True)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070030 lines.append('')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070031 readline = functools.partial(next, iter(lines), '')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070032 kind = tok_str = ''
33 tok_type = tokenize.COMMENT
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070034 written = (1, 0)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070035 for tok in tokenize.generate_tokens(readline):
36 prev_tok_type, prev_tok_str = tok_type, tok_str
37 tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettingercf6eac42012-07-03 00:12:27 -070038 kind = ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070039 if tok_type == tokenize.COMMENT:
40 kind = 'comment'
Raymond Hettingere4870b52012-07-01 00:37:05 -070041 elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;':
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070042 kind = 'operator'
43 elif tok_type == tokenize.STRING:
44 kind = 'string'
45 if prev_tok_type == tokenize.INDENT or scol==0:
46 kind = 'docstring'
47 elif tok_type == tokenize.NAME:
48 if tok_str in ('def', 'class', 'import', 'from'):
49 kind = 'definition'
50 elif prev_tok_str in ('def', 'class'):
51 kind = 'defname'
52 elif keyword.iskeyword(tok_str):
53 kind = 'keyword'
54 elif is_builtin(tok_str) and prev_tok_str != '.':
55 kind = 'builtin'
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070056 if kind:
57 line_upto_token, written = combine_range(lines, written, (srow, scol))
58 line_thru_token, written = combine_range(lines, written, (erow, ecol))
59 yield line_upto_token, kind, line_thru_token
60 line_upto_token, written = combine_range(lines, written, (erow, ecol))
61 yield line_upto_token, '', ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070062
Raymond Hettinger3a961612012-07-03 14:11:40 -070063default_ansi = {
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070064 'comment': ('\033[0;31m', '\033[0m'),
65 'string': ('\033[0;32m', '\033[0m'),
66 'docstring': ('\033[0;32m', '\033[0m'),
67 'keyword': ('\033[0;33m', '\033[0m'),
68 'builtin': ('\033[0;35m', '\033[0m'),
69 'definition': ('\033[0;33m', '\033[0m'),
70 'defname': ('\033[0;34m', '\033[0m'),
71 'operator': ('\033[0;33m', '\033[0m'),
Raymond Hettinger3a961612012-07-03 14:11:40 -070072}
73
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070074def ansi_highlight(classified_text, colors=default_ansi):
75 'Add syntax highlighting to source code using ANSI escape sequences'
Raymond Hettinger3a961612012-07-03 14:11:40 -070076 # http://en.wikipedia.org/wiki/ANSI_escape_code
77 result = []
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070078 for line_upto_token, kind, line_thru_token in classified_text:
79 opener, closer = colors.get(kind, ('', ''))
80 result += [line_upto_token, opener, line_thru_token, closer]
Raymond Hettinger3a961612012-07-03 14:11:40 -070081 return ''.join(result)
82
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070083def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
84 'Convert classified text to an HTML fragment'
85 result = [opener]
86 for line_upto_token, kind, line_thru_token in classified_text:
Raymond Hettinger5da60392012-07-03 13:13:52 -070087 if kind:
88 result += [cgi.escape(line_upto_token),
89 '<span class="%s">' % kind,
90 cgi.escape(line_thru_token),
91 '</span>']
92 else:
93 result += [cgi.escape(line_upto_token),
94 cgi.escape(line_thru_token)]
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070095 result += [closer]
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070096 return ''.join(result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070097
98default_css = {
99 '.comment': '{color: crimson;}',
100 '.string': '{color: forestgreen;}',
Raymond Hettinger5da60392012-07-03 13:13:52 -0700101 '.docstring': '{color: forestgreen; font-style:italic;}',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700102 '.keyword': '{color: darkorange;}',
103 '.builtin': '{color: purple;}',
104 '.definition': '{color: darkorange; font-weight:bold;}',
105 '.defname': '{color: blue;}',
106 '.operator': '{color: brown;}',
107}
108
109default_html = '''\
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700110<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
111 "http://www.w3.org/TR/html4/strict.dtd">
112<html>
113<head>
114<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700115<title> {title} </title>
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700116<style type="text/css">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700117{css}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700118</style>
119</head>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700120<body>
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700121{body}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700122</body>
123</html>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700124'''
125
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700126def build_html_page(classified_text, title='python',
127 css=default_css, html=default_html):
128 'Create a complete HTML page with colorized source code'
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700129 css_str = '\n'.join(['%s %s' % item for item in css.items()])
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700130 result = html_highlight(classified_text)
Raymond Hettinger9b8ede62012-06-30 23:19:30 -0700131 title = cgi.escape(title)
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700132 return html.format(title=title, css=css_str, body=result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700133
134
135if __name__ == '__main__':
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700136 import sys, argparse, webbrowser, os, textwrap
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700137
138 parser = argparse.ArgumentParser(
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700139 description = 'Add syntax highlighting to Python source code',
140 formatter_class=argparse.RawDescriptionHelpFormatter,
141 epilog = textwrap.dedent('''
142 examples:
143
144 # Show syntax highlighted code in the terminal window
145 $ ./highlight.py myfile.py
146
147 # Colorize myfile.py and display in a browser
148 $ ./highlight.py -b myfile.py
149
150 # Create an HTML section to embed in an existing webpage
151 ./highlight.py -s myfile.py
152
153 # Create a complete HTML file
154 $ ./highlight.py -c myfile.py > myfile.html
155 '''))
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700156 parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700157 help = 'file containing Python sourcecode')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700158 parser.add_argument('-b', '--browser', action = 'store_true',
159 help = 'launch a browser to show results')
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700160 parser.add_argument('-c', '--complete', action = 'store_true',
161 help = 'build a complete html webpage')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700162 parser.add_argument('-s', '--section', action = 'store_true',
163 help = 'show an HTML section rather than a complete webpage')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700164 args = parser.parse_args()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700165
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700166 if args.section and (args.browser or args.complete):
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700167 parser.error('The -s/--section option is incompatible with '
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700168 'the -b/--browser or -c/--complete options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700169
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700170 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700171 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700172 source = f.read()
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700173 classified_text = analyze_python(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700174
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700175 if args.complete or args.browser:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700176 encoded = build_html_page(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700177 elif args.section:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700178 encoded = html_highlight(classified_text)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700179 else:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700180 encoded = ansi_highlight(classified_text)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700181
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700182 if args.browser:
183 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
184 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700185 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700186 webbrowser.open('file://' + os.path.abspath(htmlfile))
187 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700188 sys.stdout.write(encoded)