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 | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 4 | __all__ = ['analyze_python', 'ansi_highlight', 'default_ansi', |
| 5 | 'html_highlight', 'build_html_page', 'default_css', 'default_html'] |
Raymond Hettinger | 0712f40 | 2012-07-03 14:42:33 -0700 | [diff] [blame] | 6 | |
Raymond Hettinger | 9b8ede6 | 2012-06-30 23:19:30 -0700 | [diff] [blame] | 7 | __author__ = 'Raymond Hettinger' |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 8 | |
| 9 | import keyword, tokenize, cgi, functools |
| 10 | |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 11 | def is_builtin(s): |
| 12 | 'Return True if s is the name of a builtin' |
| 13 | return s in vars(__builtins__) |
| 14 | |
Raymond Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 15 | def combine_range(lines, start, end): |
| 16 | 'Join content from a range of lines between start and end' |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 17 | (srow, scol), (erow, ecol) = start, end |
| 18 | if srow == erow: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 19 | return lines[srow-1][scol:ecol], end |
| 20 | 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] | 21 | return ''.join(rows), end |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 22 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 23 | def 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 Hettinger | ac5f846 | 2012-07-03 00:15:59 -0700 | [diff] [blame] | 29 | lines = source.splitlines(True) |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 30 | lines.append('') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 31 | readline = functools.partial(next, iter(lines), '') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 32 | kind = tok_str = '' |
| 33 | tok_type = tokenize.COMMENT |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 34 | written = (1, 0) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 35 | 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 Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 38 | kind = '' |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 39 | if tok_type == tokenize.COMMENT: |
| 40 | kind = 'comment' |
Raymond Hettinger | e4870b5 | 2012-07-01 00:37:05 -0700 | [diff] [blame] | 41 | elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;': |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 42 | 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 Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 56 | 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 Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 62 | |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 63 | default_ansi = { |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 64 | '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 Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 72 | } |
| 73 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 74 | def ansi_highlight(classified_text, colors=default_ansi): |
| 75 | 'Add syntax highlighting to source code using ANSI escape sequences' |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 76 | # http://en.wikipedia.org/wiki/ANSI_escape_code |
| 77 | result = [] |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 78 | 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 Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 81 | return ''.join(result) |
| 82 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 83 | def 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 Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 87 | 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 Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 95 | result += [closer] |
Raymond Hettinger | f2cc352 | 2012-07-02 13:29:57 -0700 | [diff] [blame] | 96 | return ''.join(result) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 97 | |
| 98 | default_css = { |
| 99 | '.comment': '{color: crimson;}', |
| 100 | '.string': '{color: forestgreen;}', |
Raymond Hettinger | 5da6039 | 2012-07-03 13:13:52 -0700 | [diff] [blame] | 101 | '.docstring': '{color: forestgreen; font-style:italic;}', |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 102 | '.keyword': '{color: darkorange;}', |
| 103 | '.builtin': '{color: purple;}', |
| 104 | '.definition': '{color: darkorange; font-weight:bold;}', |
| 105 | '.defname': '{color: blue;}', |
| 106 | '.operator': '{color: brown;}', |
| 107 | } |
| 108 | |
| 109 | default_html = '''\ |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 110 | <!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 Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 115 | <title> {title} </title> |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 116 | <style type="text/css"> |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 117 | {css} |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 118 | </style> |
| 119 | </head> |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 120 | <body> |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 121 | {body} |
Raymond Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 122 | </body> |
| 123 | </html> |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 124 | ''' |
| 125 | |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 126 | def 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 Hettinger | fd490cc | 2012-06-30 22:19:04 -0700 | [diff] [blame] | 129 | css_str = '\n'.join(['%s %s' % item for item in css.items()]) |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 130 | result = html_highlight(classified_text) |
Raymond Hettinger | 9b8ede6 | 2012-06-30 23:19:30 -0700 | [diff] [blame] | 131 | title = cgi.escape(title) |
Raymond Hettinger | ecea0fb | 2012-07-02 17:17:16 -0700 | [diff] [blame] | 132 | return html.format(title=title, css=css_str, body=result) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 133 | |
| 134 | |
| 135 | if __name__ == '__main__': |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 136 | import sys, argparse, webbrowser, os, textwrap |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 137 | |
| 138 | parser = argparse.ArgumentParser( |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 139 | 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 Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 156 | parser.add_argument('sourcefile', metavar = 'SOURCEFILE', |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 157 | help = 'file containing Python sourcecode') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 158 | parser.add_argument('-b', '--browser', action = 'store_true', |
| 159 | help = 'launch a browser to show results') |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 160 | parser.add_argument('-c', '--complete', action = 'store_true', |
| 161 | help = 'build a complete html webpage') |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 162 | parser.add_argument('-s', '--section', action = 'store_true', |
| 163 | help = 'show an HTML section rather than a complete webpage') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 164 | args = parser.parse_args() |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 165 | |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 166 | if args.section and (args.browser or args.complete): |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 167 | parser.error('The -s/--section option is incompatible with ' |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 168 | 'the -b/--browser or -c/--complete options') |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 169 | |
Raymond Hettinger | cf6eac4 | 2012-07-03 00:12:27 -0700 | [diff] [blame] | 170 | sourcefile = args.sourcefile |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 171 | with open(sourcefile) as f: |
Raymond Hettinger | 0712f40 | 2012-07-03 14:42:33 -0700 | [diff] [blame] | 172 | source = f.read() |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 173 | classified_text = analyze_python(source) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 174 | |
Raymond Hettinger | 5b381a3 | 2012-07-03 17:55:23 -0700 | [diff] [blame] | 175 | if args.complete or args.browser: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 176 | encoded = build_html_page(classified_text, title=sourcefile) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 177 | elif args.section: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 178 | encoded = html_highlight(classified_text) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 179 | else: |
Raymond Hettinger | 42a5f4a | 2012-07-08 15:42:54 -0700 | [diff] [blame] | 180 | encoded = ansi_highlight(classified_text) |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 181 | |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 182 | if args.browser: |
| 183 | htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html' |
| 184 | with open(htmlfile, 'w') as f: |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 185 | f.write(encoded) |
Raymond Hettinger | bc09cf1 | 2012-06-30 16:58:06 -0700 | [diff] [blame] | 186 | webbrowser.open('file://' + os.path.abspath(htmlfile)) |
| 187 | else: |
Raymond Hettinger | 3a96161 | 2012-07-03 14:11:40 -0700 | [diff] [blame] | 188 | sys.stdout.write(encoded) |