blob: 763be837e3b56853210c4ccfbe063be1bb46c0f2 [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
7
8#### Analyze Python Source #################################
Raymond Hettingerbc09cf12012-06-30 16:58:06 -07009
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070010def is_builtin(s):
11 'Return True if s is the name of a builtin'
Raymond Hettinger848245a2012-07-09 01:17:22 -070012 return hasattr(__builtins__, s)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070013
Raymond Hettinger5da60392012-07-03 13:13:52 -070014def combine_range(lines, start, end):
15 'Join content from a range of lines between start and end'
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070016 (srow, scol), (erow, ecol) = start, end
17 if srow == erow:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070018 return lines[srow-1][scol:ecol], end
19 rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
Raymond Hettinger5da60392012-07-03 13:13:52 -070020 return ''.join(rows), end
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070021
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070022def analyze_python(source):
23 '''Generate and classify chunks of Python for syntax highlighting.
24 Yields tuples in the form: (leadin_text, category, categorized_text).
25 The final tuple has empty strings for the category and categorized text.
26
27 '''
Raymond Hettingerac5f8462012-07-03 00:15:59 -070028 lines = source.splitlines(True)
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070029 lines.append('')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070030 readline = functools.partial(next, iter(lines), '')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070031 kind = tok_str = ''
32 tok_type = tokenize.COMMENT
Raymond Hettingerf2cc3522012-07-02 13:29:57 -070033 written = (1, 0)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070034 for tok in tokenize.generate_tokens(readline):
35 prev_tok_type, prev_tok_str = tok_type, tok_str
36 tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettingercf6eac42012-07-03 00:12:27 -070037 kind = ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070038 if tok_type == tokenize.COMMENT:
39 kind = 'comment'
Raymond Hettingere4870b52012-07-01 00:37:05 -070040 elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;':
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070041 kind = 'operator'
42 elif tok_type == tokenize.STRING:
43 kind = 'string'
44 if prev_tok_type == tokenize.INDENT or scol==0:
45 kind = 'docstring'
46 elif tok_type == tokenize.NAME:
47 if tok_str in ('def', 'class', 'import', 'from'):
48 kind = 'definition'
49 elif prev_tok_str in ('def', 'class'):
50 kind = 'defname'
51 elif keyword.iskeyword(tok_str):
52 kind = 'keyword'
53 elif is_builtin(tok_str) and prev_tok_str != '.':
54 kind = 'builtin'
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -070055 if kind:
56 line_upto_token, written = combine_range(lines, written, (srow, scol))
57 line_thru_token, written = combine_range(lines, written, (erow, ecol))
58 yield line_upto_token, kind, line_thru_token
59 line_upto_token, written = combine_range(lines, written, (erow, ecol))
60 yield line_upto_token, '', ''
Raymond Hettingerbc09cf12012-06-30 16:58:06 -070061
Raymond Hettinger7d390552012-07-09 23:52:08 -070062#### Raw Output ###########################################
63
64def raw_highlight(classified_text):
65 'Straight text display of text classifications'
66 result = []
67 for line_upto_token, kind, line_thru_token in classified_text:
68 if line_upto_token:
69 result.append(' plain: %r\n' % line_upto_token)
70 if line_thru_token:
71 result.append('%15s: %r\n' % (kind, line_thru_token))
72 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 Hettinger42a5f4a2012-07-08 15:42:54 -070091 for line_upto_token, kind, line_thru_token in classified_text:
92 opener, closer = colors.get(kind, ('', ''))
93 result += [line_upto_token, opener, line_thru_token, 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]
101 for line_upto_token, kind, line_thru_token in classified_text:
Raymond Hettinger5da60392012-07-03 13:13:52 -0700102 if kind:
103 result += [cgi.escape(line_upto_token),
104 '<span class="%s">' % kind,
105 cgi.escape(line_thru_token),
106 '</span>']
107 else:
108 result += [cgi.escape(line_upto_token),
109 cgi.escape(line_thru_token)]
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700110 result += [closer]
Raymond Hettingerf2cc3522012-07-02 13:29:57 -0700111 return ''.join(result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700112
113default_css = {
114 '.comment': '{color: crimson;}',
115 '.string': '{color: forestgreen;}',
Raymond Hettinger5da60392012-07-03 13:13:52 -0700116 '.docstring': '{color: forestgreen; font-style:italic;}',
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700117 '.keyword': '{color: darkorange;}',
118 '.builtin': '{color: purple;}',
119 '.definition': '{color: darkorange; font-weight:bold;}',
120 '.defname': '{color: blue;}',
121 '.operator': '{color: brown;}',
122}
123
124default_html = '''\
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700125<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
126 "http://www.w3.org/TR/html4/strict.dtd">
127<html>
128<head>
129<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700130<title> {title} </title>
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700131<style type="text/css">
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700132{css}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700133</style>
134</head>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700135<body>
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700136{body}
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700137</body>
138</html>
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700139'''
140
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700141def build_html_page(classified_text, title='python',
142 css=default_css, html=default_html):
143 'Create a complete HTML page with colorized source code'
Raymond Hettingerfd490cc2012-06-30 22:19:04 -0700144 css_str = '\n'.join(['%s %s' % item for item in css.items()])
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700145 result = html_highlight(classified_text)
Raymond Hettinger9b8ede62012-06-30 23:19:30 -0700146 title = cgi.escape(title)
Raymond Hettingerecea0fb2012-07-02 17:17:16 -0700147 return html.format(title=title, css=css_str, body=result)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700148
Raymond Hettinger7d390552012-07-09 23:52:08 -0700149#### LaTeX Output ##########################################
150
151default_latex_colors = {
152 'comment': 'red',
153 'string': 'green',
154 'docstring': 'green',
155 'keyword': 'orange',
156 'builtin': 'purple',
157 'definition': 'orange',
158 'defname': 'blue',
159 'operator': 'brown',
160}
161
162default_latex_document = r'''
163\documentclass{article}
164\usepackage{alltt}
165\usepackage{color}
166\usepackage[usenames,dvipsnames]{xcolor}
167\usepackage[cm]{fullpage}
168\begin{document}
169\center{\LARGE{%(title)s}}
170\begin{alltt}
171%(body)s
172\end{alltt}
173\end{document}
174'''
175
176def latex_escape(s):
177 'Replace LaTeX special characters with their escaped equivalents'
178 # http://en.wikibooks.org/wiki/LaTeX/Basics#Special_Characters
179 xlat = {
180 '#': r'\#', '$': r'\$', '%': r'\%', '^': r'\textasciicircum{}',
181 '&': r'\&', '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\~{}',
182 '\\': r'\textbackslash{}',
183 }
184 return re.sub(r'[\\#$%^&_{}~]', lambda mo: xlat[mo.group()], s)
185
186def latex_highlight(classified_text, title = 'python',
187 colors = default_latex_colors,
188 document = default_latex_document):
189 'Create a complete LaTeX document with colorized source code'
190 result = []
191 for line_upto_token, kind, line_thru_token in classified_text:
192 if kind:
193 result += [latex_escape(line_upto_token),
194 r'{\color{%s}' % colors[kind],
195 latex_escape(line_thru_token),
196 '}']
197 else:
198 result += [latex_escape(line_upto_token),
199 latex_escape(line_thru_token)]
200 return default_latex_document % dict(title=title, body=''.join(result))
201
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700202
203if __name__ == '__main__':
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700204 import sys, argparse, webbrowser, os, textwrap
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700205
206 parser = argparse.ArgumentParser(
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700207 description = 'Add syntax highlighting to Python source code',
208 formatter_class=argparse.RawDescriptionHelpFormatter,
209 epilog = textwrap.dedent('''
210 examples:
211
212 # Show syntax highlighted code in the terminal window
213 $ ./highlight.py myfile.py
214
215 # Colorize myfile.py and display in a browser
216 $ ./highlight.py -b myfile.py
217
218 # Create an HTML section to embed in an existing webpage
219 ./highlight.py -s myfile.py
220
221 # Create a complete HTML file
222 $ ./highlight.py -c myfile.py > myfile.html
Raymond Hettinger7d390552012-07-09 23:52:08 -0700223
224 # Create a PDF using LaTeX
225 $ ./highlight.py -l myfile.py | pdflatex
226
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700227 '''))
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700228 parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700229 help = 'file containing Python sourcecode')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700230 parser.add_argument('-b', '--browser', action = 'store_true',
231 help = 'launch a browser to show results')
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700232 parser.add_argument('-c', '--complete', action = 'store_true',
233 help = 'build a complete html webpage')
Raymond Hettinger7d390552012-07-09 23:52:08 -0700234 parser.add_argument('-l', '--latex', action = 'store_true',
235 help = 'build a LaTeX document')
236 parser.add_argument('-r', '--raw', action = 'store_true',
237 help = 'raw parse of categorized text')
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700238 parser.add_argument('-s', '--section', action = 'store_true',
239 help = 'show an HTML section rather than a complete webpage')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700240 args = parser.parse_args()
Raymond Hettinger3a961612012-07-03 14:11:40 -0700241
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700242 if args.section and (args.browser or args.complete):
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700243 parser.error('The -s/--section option is incompatible with '
Raymond Hettinger5b381a32012-07-03 17:55:23 -0700244 'the -b/--browser or -c/--complete options')
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700245
Raymond Hettingercf6eac42012-07-03 00:12:27 -0700246 sourcefile = args.sourcefile
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700247 with open(sourcefile) as f:
Raymond Hettinger0712f402012-07-03 14:42:33 -0700248 source = f.read()
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700249 classified_text = analyze_python(source)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700250
Raymond Hettinger7d390552012-07-09 23:52:08 -0700251 if args.raw:
252 encoded = raw_highlight(classified_text)
253 elif args.complete or args.browser:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700254 encoded = build_html_page(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700255 elif args.section:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700256 encoded = html_highlight(classified_text)
Raymond Hettinger7d390552012-07-09 23:52:08 -0700257 elif args.latex:
258 encoded = latex_highlight(classified_text, title=sourcefile)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700259 else:
Raymond Hettinger42a5f4a2012-07-08 15:42:54 -0700260 encoded = ansi_highlight(classified_text)
Raymond Hettinger3a961612012-07-03 14:11:40 -0700261
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700262 if args.browser:
263 htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
264 with open(htmlfile, 'w') as f:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700265 f.write(encoded)
Raymond Hettingerbc09cf12012-06-30 16:58:06 -0700266 webbrowser.open('file://' + os.path.abspath(htmlfile))
267 else:
Raymond Hettinger3a961612012-07-03 14:11:40 -0700268 sys.stdout.write(encoded)