Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 2 | '''Add syntax highlighting to Python source code''' |
Raymond Hettinger | 0712f40 | 2012-07-03 14:42:33 -0700 | [diff] [blame] | 3 | |
Raymond Hettinger | 9b8ede6 | 2012-06-30 23:19:30 -0700 | [diff] [blame] | 4 | __author__ = 'Raymond Hettinger' |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 5 | |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 6 | import keyword, tokenize, cgi, re, functools |
| 7 | |
| 8 | #### Analyze Python Source ################################# |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 9 | |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 10 | def is_builtin(s): |
| 11 | 'Return True if s is the name of a builtin' |
Raymond Hettinger | 848245a | 2012-07-09 01:17:22 -0700 | [diff] [blame] | 12 | return hasattr(__builtins__, s) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 13 | |
Raymond Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 14 | def combine_range(lines, start, end): |
| 15 | 'Join content from a range of lines between start and end' |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 16 | (srow, scol), (erow, ecol) = start, end |
| 17 | if srow == erow: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 18 | return lines[srow-1][scol:ecol], end |
| 19 | rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]] |
Raymond Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 20 | return ''.join(rows), end |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 21 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 22 | def 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 Hettinger | ac5f846 | 2012-07-03 00:15:59 -0700 | [diff] [blame] | 28 | lines = source.splitlines(True) |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 29 | lines.append('') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 30 | readline = functools.partial(next, iter(lines), '') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 31 | kind = tok_str = '' |
| 32 | tok_type = tokenize.COMMENT |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 33 | written = (1, 0) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 34 | 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 Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 37 | kind = '' |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 38 | if tok_type == tokenize.COMMENT: |
| 39 | kind = 'comment' |
Raymond Hettinger | e4870b5 | 2012-07-01 00:37:05 -0700 | [diff] [blame] | 40 | elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;': |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 41 | 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 Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 55 | 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 Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 61 | |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 62 | #### Raw Output ########################################### |
| 63 | |
| 64 | def 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 Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 76 | default_ansi = { |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 77 | '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 Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 85 | } |
| 86 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 87 | def ansi_highlight(classified_text, colors=default_ansi): |
| 88 | 'Add syntax highlighting to source code using ANSI escape sequences' |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 89 | # http://en.wikipedia.org/wiki/ANSI_escape_code |
| 90 | result = [] |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 91 | 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 Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 94 | return ''.join(result) |
| 95 | |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 96 | #### HTML Output ########################################### |
| 97 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 98 | def 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 Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 102 | 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 Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 110 | result += [closer] |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 111 | return ''.join(result) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 112 | |
| 113 | default_css = { |
| 114 | '.comment': '{color: crimson;}', |
| 115 | '.string': '{color: forestgreen;}', |
Raymond Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 116 | '.docstring': '{color: forestgreen; font-style:italic;}', |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 117 | '.keyword': '{color: darkorange;}', |
| 118 | '.builtin': '{color: purple;}', |
| 119 | '.definition': '{color: darkorange; font-weight:bold;}', |
| 120 | '.defname': '{color: blue;}', |
| 121 | '.operator': '{color: brown;}', |
| 122 | } |
| 123 | |
| 124 | default_html = '''\ |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 125 | <!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 Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 130 | <title> {title} </title> |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 131 | <style type="text/css"> |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 132 | {css} |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 133 | </style> |
| 134 | </head> |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 135 | <body> |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 136 | {body} |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 137 | </body> |
| 138 | </html> |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 139 | ''' |
| 140 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 141 | def 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 Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 144 | css_str = '\n'.join(['%s %s' % item for item in css.items()]) |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 145 | result = html_highlight(classified_text) |
Raymond Hettinger | 9b8ede6 | 2012-06-30 23:19:30 -0700 | [diff] [blame] | 146 | title = cgi.escape(title) |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 147 | return html.format(title=title, css=css_str, body=result) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 148 | |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 149 | #### LaTeX Output ########################################## |
| 150 | |
| 151 | default_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 | |
| 162 | default_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 | |
| 176 | def 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 | |
| 186 | def 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 Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 202 | |
| 203 | if __name__ == '__main__': |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 204 | import sys, argparse, webbrowser, os, textwrap |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 205 | |
| 206 | parser = argparse.ArgumentParser( |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 207 | 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 Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 223 | |
| 224 | # Create a PDF using LaTeX |
| 225 | $ ./highlight.py -l myfile.py | pdflatex |
| 226 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 227 | ''')) |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 228 | parser.add_argument('sourcefile', metavar = 'SOURCEFILE', |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 229 | help = 'file containing Python sourcecode') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 230 | parser.add_argument('-b', '--browser', action = 'store_true', |
| 231 | help = 'launch a browser to show results') |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 232 | parser.add_argument('-c', '--complete', action = 'store_true', |
| 233 | help = 'build a complete html webpage') |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 234 | 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 Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 238 | parser.add_argument('-s', '--section', action = 'store_true', |
| 239 | help = 'show an HTML section rather than a complete webpage') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 240 | args = parser.parse_args() |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 241 | |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 242 | if args.section and (args.browser or args.complete): |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 243 | parser.error('The -s/--section option is incompatible with ' |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 244 | 'the -b/--browser or -c/--complete options') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 245 | |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 246 | sourcefile = args.sourcefile |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 247 | with open(sourcefile) as f: |
Raymond Hettinger | 0712f40 | 2012-07-03 14:42:33 -0700 | [diff] [blame] | 248 | source = f.read() |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 249 | classified_text = analyze_python(source) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 250 | |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 251 | if args.raw: |
| 252 | encoded = raw_highlight(classified_text) |
| 253 | elif args.complete or args.browser: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 254 | encoded = build_html_page(classified_text, title=sourcefile) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 255 | elif args.section: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 256 | encoded = html_highlight(classified_text) |
Raymond Hettinger | 7d39055 | 2012-07-09 23:52:08 -0700 | [diff] [blame^] | 257 | elif args.latex: |
| 258 | encoded = latex_highlight(classified_text, title=sourcefile) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 259 | else: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 260 | encoded = ansi_highlight(classified_text) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 261 | |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 262 | if args.browser: |
| 263 | htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html' |
| 264 | with open(htmlfile, 'w') as f: |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 265 | f.write(encoded) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 266 | webbrowser.open('file://' + os.path.abspath(htmlfile)) |
| 267 | else: |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 268 | sys.stdout.write(encoded) |