highlight.py 8.94 KB
Newer Older
1
#!/usr/bin/env python3
2
'''Add syntax highlighting to Python source code'''
3

4
__author__ = 'Raymond Hettinger'
5

6 7 8 9 10 11
import builtins
import functools
import html as html_module
import keyword
import re
import tokenize
12 13

#### Analyze Python Source #################################
14 15 16

def is_builtin(s):
    'Return True if s is the name of a builtin'
17
    return hasattr(builtins, s)
18

19 20
def combine_range(lines, start, end):
    'Join content from a range of lines between start and end'
21 22
    (srow, scol), (erow, ecol) = start, end
    if srow == erow:
23 24
        return lines[srow-1][scol:ecol], end
    rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
25
    return ''.join(rows), end
26

27 28
def analyze_python(source):
    '''Generate and classify chunks of Python for syntax highlighting.
29
       Yields tuples in the form: (category, categorized_text).
30
    '''
Raymond Hettinger's avatar
Raymond Hettinger committed
31
    lines = source.splitlines(True)
32
    lines.append('')
33 34 35
    readline = functools.partial(next, iter(lines), '')
    kind = tok_str = ''
    tok_type = tokenize.COMMENT
36
    written = (1, 0)
37 38 39
    for tok in tokenize.generate_tokens(readline):
        prev_tok_type, prev_tok_str = tok_type, tok_str
        tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
Raymond Hettinger's avatar
Raymond Hettinger committed
40
        kind = ''
41 42
        if tok_type == tokenize.COMMENT:
            kind = 'comment'
43
        elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;@':
44 45 46 47 48 49 50 51 52 53 54 55 56 57
            kind = 'operator'
        elif tok_type == tokenize.STRING:
            kind = 'string'
            if prev_tok_type == tokenize.INDENT or scol==0:
                kind = 'docstring'
        elif tok_type == tokenize.NAME:
            if tok_str in ('def', 'class', 'import', 'from'):
                kind = 'definition'
            elif prev_tok_str in ('def', 'class'):
                kind = 'defname'
            elif keyword.iskeyword(tok_str):
                kind = 'keyword'
            elif is_builtin(tok_str) and prev_tok_str != '.':
                kind = 'builtin'
58
        if kind:
59 60
            text, written = combine_range(lines, written, (srow, scol))
            yield '', text
61
            text, written = tok_str, (erow, ecol)
62
            yield kind, text
63
    line_upto_token, written = combine_range(lines, written, (erow, ecol))
64
    yield '', line_upto_token
65

66 67 68 69 70
#### Raw Output  ###########################################

def raw_highlight(classified_text):
    'Straight text display of text classifications'
    result = []
71 72
    for kind, text in classified_text:
        result.append('%15s:  %r\n' % (kind or 'plain', text))
73 74 75 76
    return ''.join(result)

#### ANSI Output ###########################################

77
default_ansi = {
78 79 80 81 82 83 84 85
    'comment': ('\033[0;31m', '\033[0m'),
    'string': ('\033[0;32m', '\033[0m'),
    'docstring': ('\033[0;32m', '\033[0m'),
    'keyword': ('\033[0;33m', '\033[0m'),
    'builtin': ('\033[0;35m', '\033[0m'),
    'definition': ('\033[0;33m', '\033[0m'),
    'defname': ('\033[0;34m', '\033[0m'),
    'operator': ('\033[0;33m', '\033[0m'),
86 87
}

88 89
def ansi_highlight(classified_text, colors=default_ansi):
    'Add syntax highlighting to source code using ANSI escape sequences'
90 91
    # http://en.wikipedia.org/wiki/ANSI_escape_code
    result = []
92
    for kind, text in classified_text:
93
        opener, closer = colors.get(kind, ('', ''))
94
        result += [opener, text, closer]
95 96
    return ''.join(result)

97 98
#### HTML Output ###########################################

99 100 101
def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
    'Convert classified text to an HTML fragment'
    result = [opener]
102 103 104
    for kind, text in classified_text:
        if kind:
            result.append('<span class="%s">' % kind)
105
        result.append(html_module.escape(text))
106
        if kind:
107 108
            result.append('</span>')
    result.append(closer)
109
    return ''.join(result)
110 111 112 113

default_css = {
    '.comment': '{color: crimson;}',
    '.string':  '{color: forestgreen;}',
114
    '.docstring': '{color: forestgreen; font-style:italic;}',
115 116 117 118 119 120 121 122
    '.keyword': '{color: darkorange;}',
    '.builtin': '{color: purple;}',
    '.definition': '{color: darkorange; font-weight:bold;}',
    '.defname': '{color: blue;}',
    '.operator': '{color: brown;}',
}

default_html = '''\
Raymond Hettinger's avatar
Raymond Hettinger committed
123 124 125 126 127
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
128
<title> {title} </title>
Raymond Hettinger's avatar
Raymond Hettinger committed
129
<style type="text/css">
130
{css}
Raymond Hettinger's avatar
Raymond Hettinger committed
131 132
</style>
</head>
133
<body>
134
{body}
Raymond Hettinger's avatar
Raymond Hettinger committed
135 136
</body>
</html>
137 138
'''

139 140 141
def build_html_page(classified_text, title='python',
                    css=default_css, html=default_html):
    'Create a complete HTML page with colorized source code'
Raymond Hettinger's avatar
Raymond Hettinger committed
142
    css_str = '\n'.join(['%s %s' % item for item in css.items()])
143
    result = html_highlight(classified_text)
144
    title = html_module.escape(title)
145
    return html.format(title=title, css=css_str, body=result)
146

147 148
#### LaTeX Output ##########################################

Raymond Hettinger's avatar
Raymond Hettinger committed
149 150 151 152 153 154 155 156 157
default_latex_commands = {
    'comment': '{\color{red}#1}',
    'string': '{\color{ForestGreen}#1}',
    'docstring': '{\emph{\color{ForestGreen}#1}}',
    'keyword': '{\color{orange}#1}',
    'builtin': '{\color{purple}#1}',
    'definition': '{\color{orange}#1}',
    'defname': '{\color{blue}#1}',
    'operator': '{\color{brown}#1}',
158 159 160 161 162
}

default_latex_document = r'''
\documentclass{article}
\usepackage{alltt}
Raymond Hettinger's avatar
Raymond Hettinger committed
163
\usepackage{upquote}
164 165 166
\usepackage{color}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[cm]{fullpage}
Raymond Hettinger's avatar
Raymond Hettinger committed
167
%(macros)s
168 169 170 171 172 173 174 175
\begin{document}
\center{\LARGE{%(title)s}}
\begin{alltt}
%(body)s
\end{alltt}
\end{document}
'''

176 177 178 179
def alltt_escape(s):
    'Replace backslash and braces with their escaped equivalents'
    xlat = {'{': r'\{', '}': r'\}', '\\': r'\textbackslash{}'}
    return re.sub(r'[\\{}]', lambda mo: xlat[mo.group()], s)
180 181

def latex_highlight(classified_text, title = 'python',
Raymond Hettinger's avatar
Raymond Hettinger committed
182
                    commands = default_latex_commands,
183 184
                    document = default_latex_document):
    'Create a complete LaTeX document with colorized source code'
Raymond Hettinger's avatar
Raymond Hettinger committed
185
    macros = '\n'.join(r'\newcommand{\py%s}[1]{%s}' % c for c in commands.items())
186
    result = []
187 188
    for kind, text in classified_text:
        if kind:
Raymond Hettinger's avatar
Raymond Hettinger committed
189
            result.append(r'\py%s{' % kind)
190
        result.append(alltt_escape(text))
191
        if kind:
192
            result.append('}')
Raymond Hettinger's avatar
Raymond Hettinger committed
193
    return default_latex_document % dict(title=title, macros=macros, body=''.join(result))
194

195 196

if __name__ == '__main__':
197 198 199 200 201
    import argparse
    import os.path
    import sys
    import textwrap
    import webbrowser
202 203

    parser = argparse.ArgumentParser(
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
            description = 'Add syntax highlighting to Python source code',
            formatter_class=argparse.RawDescriptionHelpFormatter,
            epilog = textwrap.dedent('''
                examples:

                  # Show syntax highlighted code in the terminal window
                  $ ./highlight.py myfile.py

                  # Colorize myfile.py and display in a browser
                  $ ./highlight.py -b myfile.py

                  # Create an HTML section to embed in an existing webpage
                  ./highlight.py -s myfile.py

                  # Create a complete HTML file
                  $ ./highlight.py -c myfile.py > myfile.html
220 221 222 223

                  # Create a PDF using LaTeX
                  $ ./highlight.py -l myfile.py | pdflatex

224
            '''))
Raymond Hettinger's avatar
Raymond Hettinger committed
225
    parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
226
            help = 'file containing Python sourcecode')
227 228
    parser.add_argument('-b', '--browser', action = 'store_true',
            help = 'launch a browser to show results')
229 230
    parser.add_argument('-c', '--complete', action = 'store_true',
            help = 'build a complete html webpage')
231 232 233 234
    parser.add_argument('-l', '--latex', action = 'store_true',
            help = 'build a LaTeX document')
    parser.add_argument('-r', '--raw', action = 'store_true',
            help = 'raw parse of categorized text')
Raymond Hettinger's avatar
Raymond Hettinger committed
235 236
    parser.add_argument('-s', '--section', action = 'store_true',
            help = 'show an HTML section rather than a complete webpage')
237
    args = parser.parse_args()
238

239
    if args.section and (args.browser or args.complete):
Raymond Hettinger's avatar
Raymond Hettinger committed
240
        parser.error('The -s/--section option is incompatible with '
241
                     'the -b/--browser or -c/--complete options')
242

Raymond Hettinger's avatar
Raymond Hettinger committed
243
    sourcefile = args.sourcefile
244
    with open(sourcefile) as f:
245
        source = f.read()
246
    classified_text = analyze_python(source)
247

248 249 250
    if args.raw:
        encoded = raw_highlight(classified_text)
    elif args.complete or args.browser:
251
        encoded = build_html_page(classified_text, title=sourcefile)
252
    elif args.section:
253
        encoded = html_highlight(classified_text)
254 255
    elif args.latex:
        encoded = latex_highlight(classified_text, title=sourcefile)
256
    else:
257
        encoded = ansi_highlight(classified_text)
258

259 260 261
    if args.browser:
        htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
        with open(htmlfile, 'w') as f:
262
            f.write(encoded)
263 264
        webbrowser.open('file://' + os.path.abspath(htmlfile))
    else:
265
        sys.stdout.write(encoded)