blob: aff5caebdf63540c7c8a3b8fdfbd735382072572 [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
Raymond Hettinger7d390552012-07-09 23:52:08 -07006import keyword, tokenize, cgi, re, functools
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -07007try:
8 import builtins
9except ImportError:
10 import __builtin__ as builtins
Raymond Hettinger7d390552012-07-09 23:52:08 -070011
12#### Analyze Python Source #################################
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070013
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070014def is_builtin(s):
15 'Return True if s is the name of a builtin'
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070016 return hasattr(builtins, s)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070017
Raymond Hettinger5da60392012-07-03 13:13:52 -070018def combine_range(lines, start, end):
19 'Join content from a range of lines between start and end'
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070020 (srow, scol), (erow, ecol) = start, end
21 if srow == erow:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070022 return lines[srow-1][scol:ecol], end
23 rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
Raymond Hettinger5da60392012-07-03 13:13:52 -070024 return ''.join(rows), end
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070025
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070026def analyze_python(source):
27 '''Generate and classify chunks of Python for syntax highlighting.
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070028 Yields tuples in the form: (category, categorized_text).
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070029 '''
Raymond Hettingerac5f8462012-07-03 00:15:59 -070030 lines = source.splitlines(True)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070031 lines.append('')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070032 readline = functools.partial(next, iter(lines), '')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070033 kind = tok_str = ''
34 tok_type = tokenize.COMMENT
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070035 written = (1, 0)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070036 for tok in tokenize.generate_tokens(readline):
37 prev_tok_type, prev_tok_str = tok_type, tok_str
38 tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettingercf6eac42012-07-03 00:12:27 -070039 kind = ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070040 if tok_type == tokenize.COMMENT:
41 kind = 'comment'
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070042 elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;@':
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070043 kind = 'operator'
44 elif tok_type == tokenize.STRING:
45 kind = 'string'
46 if prev_tok_type == tokenize.INDENT or scol==0:
47 kind = 'docstring'
48 elif tok_type == tokenize.NAME:
49 if tok_str in ('def', 'class', 'import', 'from'):
50 kind = 'definition'
51 elif prev_tok_str in ('def', 'class'):
52 kind = 'defname'
53 elif keyword.iskeyword(tok_str):
54 kind = 'keyword'
55 elif is_builtin(tok_str) and prev_tok_str != '.':
56 kind = 'builtin'
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070057 if kind:
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070058 text, written = combine_range(lines, written, (srow, scol))
59 yield '', text
Raymond Hettingerd3f63d32012-07-23 00:24:24 -050060 text, written = tok_str, (erow, ecol)
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070061 yield kind, text
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070062 line_upto_token, written = combine_range(lines, written, (erow, ecol))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070063 yield '', line_upto_token
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070064
Raymond Hettinger7d390552012-07-09 23:52:08 -070065#### Raw Output ###########################################
66
67def raw_highlight(classified_text):
68 'Straight text display of text classifications'
69 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070070 for kind, text in classified_text:
71 result.append('%15s: %r\n' % (kind or 'plain', text))
Raymond Hettinger7d390552012-07-09 23:52:08 -070072 return ''.join(result)
73
74#### ANSI Output ###########################################
75
Raymond Hettinger3a961612012-07-03 14:11:40 -070076default_ansi = {
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070077 'comment': ('\033[0;31m', '\033[0m'),
78 'string': ('\033[0;32m', '\033[0m'),
79 'docstring': ('\033[0;32m', '\033[0m'),
80 'keyword': ('\033[0;33m', '\033[0m'),
81 'builtin': ('\033[0;35m', '\033[0m'),
82 'definition': ('\033[0;33m', '\033[0m'),
83 'defname': ('\033[0;34m', '\033[0m'),
84 'operator': ('\033[0;33m', '\033[0m'),
Raymond Hettinger3a961612012-07-03 14:11:40 -070085}
86
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070087def ansi_highlight(classified_text, colors=default_ansi):
88 'Add syntax highlighting to source code using ANSI escape sequences'
Raymond Hettinger3a961612012-07-03 14:11:40 -070089 # http://en.wikipedia.org/wiki/ANSI_escape_code
90 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070091 for kind, text in classified_text:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070092 opener, closer = colors.get(kind, ('', ''))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -070093 result += [opener, text, closer]
Raymond Hettinger3a961612012-07-03 14:11:40 -070094 return ''.join(result)
95
Raymond Hettinger7d390552012-07-09 23:52:08 -070096#### HTML Output ###########################################
97
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070098def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
99 'Convert classified text to an HTML fragment'
100 result = [opener]
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700101 for kind, text in classified_text:
Raymond Hettinger5da60392012-07-03 13:13:52 -0700102 if kind:
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700103 result.append('<span class="%s">' % kind)
104 result.append(cgi.escape(text))
105 if kind:
106 result.append('</span>')
107 result.append(closer)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -0700108 return ''.join(result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700109
110default_css = {
111 '.comment': '{color: crimson;}',
112 '.string': '{color: forestgreen;}',
Raymond Hettinger5da60392012-07-03 13:13:52 -0700113 '.docstring': '{color: forestgreen; font-style:italic;}',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700114 '.keyword': '{color: darkorange;}',
115 '.builtin': '{color: purple;}',
116 '.definition': '{color: darkorange; font-weight:bold;}',
117 '.defname': '{color: blue;}',
118 '.operator': '{color: brown;}',
119}
120
121default_html = '''\
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700122<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
123 "http://www.w3.org/TR/html4/strict.dtd">
124<html>
125<head>
126<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700127<title> {title} </title>
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700128<style type="text/css">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700129{css}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700130</style>
131</head>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700132<body>
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700133{body}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700134</body>
135</html>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700136'''
137
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700138def build_html_page(classified_text, title='python',
139 css=default_css, html=default_html):
140 'Create a complete HTML page with colorized source code'
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700141 css_str = '\n'.join(['%s %s' % item for item in css.items()])
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700142 result = html_highlight(classified_text)
Raymond Hettinger9b8ede62012-06-30 23:19:30 -0700143 title = cgi.escape(title)
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700144 return html.format(title=title, css=css_str, body=result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700145
Raymond Hettinger7d390552012-07-09 23:52:08 -0700146#### LaTeX Output ##########################################
147
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700148default_latex_commands = {
149 'comment': '{\color{red}#1}',
150 'string': '{\color{ForestGreen}#1}',
151 'docstring': '{\emph{\color{ForestGreen}#1}}',
152 'keyword': '{\color{orange}#1}',
153 'builtin': '{\color{purple}#1}',
154 'definition': '{\color{orange}#1}',
155 'defname': '{\color{blue}#1}',
156 'operator': '{\color{brown}#1}',
Raymond Hettinger7d390552012-07-09 23:52:08 -0700157}
158
159default_latex_document = r'''
160\documentclass{article}
161\usepackage{alltt}
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700162\usepackage{upquote}
Raymond Hettinger7d390552012-07-09 23:52:08 -0700163\usepackage{color}
164\usepackage[usenames,dvipsnames]{xcolor}
165\usepackage[cm]{fullpage}
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700166%(macros)s
Raymond Hettinger7d390552012-07-09 23:52:08 -0700167\begin{document}
168\center{\LARGE{%(title)s}}
169\begin{alltt}
170%(body)s
171\end{alltt}
172\end{document}
173'''
174
Raymond Hettingerd3f63d32012-07-23 00:24:24 -0500175def alltt_escape(s):
176 'Replace backslash and braces with their escaped equivalents'
177 xlat = {'{': r'\{', '}': r'\}', '\\': r'\textbackslash{}'}
178 return re.sub(r'[\\{}]', lambda mo: xlat[mo.group()], s)
Raymond Hettinger7d390552012-07-09 23:52:08 -0700179
180def latex_highlight(classified_text, title = 'python',
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700181 commands = default_latex_commands,
Raymond Hettinger7d390552012-07-09 23:52:08 -0700182 document = default_latex_document):
183 'Create a complete LaTeX document with colorized source code'
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700184 macros = '\n'.join(r'\newcommand{\py%s}[1]{%s}' % c for c in commands.items())
Raymond Hettinger7d390552012-07-09 23:52:08 -0700185 result = []
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700186 for kind, text in classified_text:
Raymond Hettinger7d390552012-07-09 23:52:08 -0700187 if kind:
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700188 result.append(r'\py%s{' % kind)
Raymond Hettingerd3f63d32012-07-23 00:24:24 -0500189 result.append(alltt_escape(text))
Raymond Hettingerfb20a1a2012-07-13 11:52:45 -0700190 if kind:
191 result.append('}')
Raymond Hettingerc4ac7892012-07-14 17:58:29 -0700192 return default_latex_document % dict(title=title, macros=macros, body=''.join(result))
Raymond Hettinger7d390552012-07-09 23:52:08 -0700193
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700194
195if __name__ == '__main__':
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700196 import sys, argparse, webbrowser, os, textwrap
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700197
198 parser = argparse.ArgumentParser(
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700199 description = 'Add syntax highlighting to Python source code',
200 formatter_class=argparse.RawDescriptionHelpFormatter,
201 epilog = textwrap.dedent('''
202 examples:
203
204 # Show syntax highlighted code in the terminal window
205 $ ./highlight.py myfile.py
206
207 # Colorize myfile.py and display in a browser
208 $ ./highlight.py -b myfile.py
209
210 # Create an HTML section to embed in an existing webpage
211 ./highlight.py -s myfile.py
212
213 # Create a complete HTML file
214 $ ./highlight.py -c myfile.py > myfile.html
Raymond Hettinger7d390552012-07-09 23:52:08 -0700215
216 # Create a PDF using LaTeX
217 $ ./highlight.py -l myfile.py | pdflatex
218
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700219 '''))
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700220 parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700221 help = 'file containing Python sourcecode')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700222 parser.add_argument('-b', '--browser', action = 'store_true',
223 help = 'launch a browser to show results')
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700224 parser.add_argument('-c', '--complete', action = 'store_true',
225 help = 'build a complete html webpage')
Raymond Hettinger7d390552012-07-09 23:52:08 -0700226 parser.add_argument('-l', '--latex', action = 'store_true',
227 help = 'build a LaTeX document')
228 parser.add_argument('-r', '--raw', action = 'store_true',
229 help = 'raw parse of categorized text')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700230 parser.add_argument('-s', '--section', action = 'store_true',
231 help = 'show an HTML section rather than a complete webpage')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700232 args = parser.parse_args()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700233
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700234 if args.section and (args.browser or args.complete):
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700235 parser.error('The -s/--section option is incompatible with '
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700236 'the -b/--browser or -c/--complete options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700237
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700238 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700239 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700240 source = f.read()
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700241 classified_text = analyze_python(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700242
Raymond Hettinger7d390552012-07-09 23:52:08 -0700243 if args.raw:
244 encoded = raw_highlight(classified_text)
245 elif args.complete or args.browser:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700246 encoded = build_html_page(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700247 elif args.section:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700248 encoded = html_highlight(classified_text)
Raymond Hettinger7d390552012-07-09 23:52:08 -0700249 elif args.latex:
250 encoded = latex_highlight(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700251 else:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700252 encoded = ansi_highlight(classified_text)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700253
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700254 if args.browser:
255 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
256 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700257 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700258 webbrowser.open('file://' + os.path.abspath(htmlfile))
259 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700260 sys.stdout.write(encoded)