Source

Webware / DocSupport / py2html.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
#!/usr/bin/env python -u

"""Python Highlighter                                    Version: 0.8

py2html.py [options] files...

options:
 -h             print help
 -              read from stdin, write to stdout
 -stdout        read from files, write to stdout
 -files         read from files, write to filename+'.html' (default)
 -format:
   html         output XHTML page (default)
   rawhtml      output pure XHTML (without headers, titles, etc.)
 -mode:
   color        output in color (default)
   mono         output b/w (for printing)
 -title:Title   use 'Title' as title of the generated page
 -bgcolor:color use color as background-color for page
 -header:file   use contents of file as header
 -footer:file   use contents of file as footer
 -URL           replace all occurances of 'URL: link' with
                '<a href="link">link</a>'; this is always enabled
                in CGI mode
 -v             verbose

Takes the input, assuming it is Python code and formats it into
colored XHTML. When called without parameters the script tries to
work in CGI mode. It looks for a field 'script=URL' and tries to
use that URL as input file. If it can't find this field, the path
info (the part of the URL following the CGI script name) is
tried. In case no host is given, the host where the CGI script
lives and HTTP are used.

  * Uses Just van Rossum's PyFontify version 0.3 to tag Python scripts.
    You can get it via his homepage on starship:
    URL: http://starship.python.net/~just/

"""
__comments__ = """

The following snippet is a small shell script I use for viewing
Python scripts via less on Unix:

pyless:
#!/bin/sh
# Browse pretty printed Python code using ANSI codes for highlighting
py2html -stdout -format:ansi -mode:color $* | less -r

History:

Clean-up and modified expand tabs patch by Christoph Zwerschke.

0.8: Added patch by Patrick Lynch to have py2html.py use style
     sheets for markup
0.7: Added patch by Ville Skytta to make py2html.py output
     valid XHTML.
0.6: Fixed a bug in .escape_html(); thanks to Vespe Savikko for
     finding this one.
0.5: Added a few suggestions by Kevin Ng to make the CGI version
     a little more robust.

"""
__copyright__ = """\
Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Copyright (c) 2000-2002, eGenix.com Software GmbH; mailto:info@egenix.com
Distributed under the terms and conditions of the eGenix.com Public
License. See http://www.egenix.com/files/python/mxLicense.html for
details, or contact the author. All Rights Reserved.\
"""

__version__ = '0.8'

__cgifooter__ = ('\n<pre># code highlighted using <a href='
    '"http://www.lemburg.com/files/python/">py2html.py</a> '
    'version %s</pre>\n' % __version__)

import sys, re

# Adjust path so that PyFontify is found...
if '.' not in sys.path:
    sys.path.append('.')


### Constants

# URL of the input form the user is redirected to in case no script=xxx
# form field is given. The URL *must* be absolute. Leave blank to
# have the script issue an error instead.
INPUT_FORM = None

# HTML DOCTYPE and XML namespace
HTML_DOCTYPE = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
    ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
HTML_XMLNS = ' xmlns="http://www.w3.org/1999/xhtml"'


### Helpers

def fileio(file, mode='rb', data=None, close=False):
    if isinstance(file, basestring):
        f = open(file, mode)
        close = True
    else:
        f = file
    if data:
        f.write(data)
    else:
        data = f.read()
    if close:
        f.close()
    return data


### Converter class

class PrettyPrint(object):
    """Generic Pretty Printer class.

      * supports tagging Python scripts in the following ways:

        # format/mode |  color  mono
        # --------------------------
        # rawhtml     |    x     x   (HTML without headers, etc.)
        # html        |    x     x   (a HTML page with HEAD&BODY:)
        # ansi        |    x     x   (with Ansi-escape sequences)

      * interfaces:

         file_filter -- takes two files: input & output (may be stdin/stdout)
         filter -- takes a string and returns the highlighted version

      * to create an instance use:

        c = PrettyPrint(tagfct,format,mode)

        where format and mode must be strings according to the
        above table if you plan to use PyFontify.fontify as tagfct

      * the tagfct has to take one argument, text, and return a taglist
        (format: [(id,left,right,sublist),...], where id is the
        "name" given to the slice left:right in text and sublist is a
        taglist for tags inside the slice or None)

    """

    # misc settings
    title = ''
    bgcolor = '#EEF'
    css = ''
    header = ''
    footer = ''
    replace_URLs = False
    # formats to be used
    formats = {}

    def __init__(self, tagfct=None, format='html', mode='color'):
        self.tag = tagfct
        self.set_mode = getattr(self,'set_mode_%s_%s' % (format, mode))
        self.filter = getattr(self,'filter_%s' % format)

    def file_filter(self, infile, outfile):
        self.set_mode()
        text = fileio(infile, 'r')
        if isinstance(infile, basestring) and not self.title:
            self.title = infile
        fileio(outfile, 'w', self.filter(text))

    ### Set pre- and postfixes for formats & modes
    #
    # These methods must set self.formats to a dictionary having
    # an entry for every tag returned by the tagging function.
    #
    # The format used is simple:
    #  tag:(prefix,postfix)
    # where prefix and postfix are either strings or callable objects,
    # that return a string (they are called with the matching tag text
    # as only parameter). prefix is inserted in front of the tag, postfix
    # is inserted right after the tag.

    def set_mode_html_color(self):
        self.css = """
<style type="text/css">
<!--
body{ background: %s;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10pt;
padding: 3pt; }
.PY_KEYWORD{ color: #00C; font-weight: bold; }
.PY_COMMENT{ color: #008; }
.PY_PARAMETER{ color: #C00; }
.PY_IDENTIFIER{ color: #C00; font-weight: bold; }
.PY_STRING{ color: #080; }
-->
</style>""" % self.bgcolor
        self.formats = {
            'all': ('<pre>', '</pre>'),
            'comment': ('<span class="PY_COMMENT">', '</span>'),
            'keyword': ('<span class="PY_KEYWORD">', '</span>'),
            'parameter': ('<span class="PY_PARAMETER">', '</span>'),
            'identifier': (lambda x:
                '<a name="%s"><span class="PY_IDENTIFIER">' % x.strip(),
                '</span></a>'),
            'string': ('<span class="PY_STRING">', '</span>')
            }

    set_mode_rawhtml_color = set_mode_html_color

    def set_mode_html_mono(self):
        self.css = """
<style type="text/css">
<!--
body{ background-color: %s;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10pt;
padding: 3pt; }
.PY_KEYWORD{ text-decoration: underline }
.PY_COMMENT{ }
.PY_PARAMETER{ }
.PY_IDENTIFIER{ font-weight: bold}
.PY_STRING{ font-style: italic}
-->
</style> """ % self.bgcolor
        self.formats = {
            'all': ('<pre>', '</pre>'),
            'comment': ('<span class="PY_COMMENT">', '</span>'),
            'keyword': ('<span class="PY_KEYWORD">', '</span>'),
            'parameter': ('<span class="PY_PARAMETER">', '</span>'),
            'identifier': (lambda x:
                '<a name="%s"><span class="PY_IDENTIFIER">' % x.strip(),
                '</span></a>'),
            'string': ('<span class="PY_STRING">', '</span>')
            }

    set_mode_rawhtml_mono = set_mode_html_mono

    def set_mode_ansi_mono(self):
        self.formats = {
            'all': ('', ''),
            'comment': ('\033[2m', '\033[m'),
            'keyword': ('\033[4m', '\033[m'),
            'parameter': ('', ''),
            'identifier': ('\033[1m', '\033[m'),
            'string': ('', '')
            }

    def set_mode_ansi_color(self):
        self.formats = {
            'all': ('', ''),
            'comment': ('\033[34;2m', '\033[m'),
            'keyword': ('\033[1;34m', '\033[m'),
            'parameter': ('', ''),
            'identifier': ('\033[1;31m', '\033[m'),
            'string': ('\033[32;2m', '\033[m')
            }

    ### Filters for Python scripts given as string

    def escape_html(self, text):
        t = (('&','&amp;'), ('<','&lt;'), ('>','&gt;'))
        for x, y in t:
            text = y.join(text.split(x))
        return text

    def expand_tabs(self, s):
        # 2005-09-09 cz: convert tabs to spaces
        return s.expandtabs(4)

    def filter_html(self, text):
        output = self.fontify(self.escape_html(self.expand_tabs(text)))
        if self.replace_URLs:
            output = re.sub('URL:([ \t]+)([^ \n\r<]+)',
                'URL:\\1<a href="\\2">\\2</a>', output)
        html = """%s
<html%s>
<head>
<title>%s</title>
<!--css-->
%s
</head>
<body>
<!--header-->
%s
<!--script-->
%s
<!--footer-->
%s
</body>
</html>\n""" % (HTML_DOCTYPE, HTML_XMLNS,
            self.title, self.css,
            self.header, output, self.footer)
        return html

    def filter_rawhtml(self, text):
        output = self.fontify(self.escape_html(self.expand_tabs(text)))
        if self.replace_URLs:
            output = re.sub('URL:([ \t]+)([^ \n\r<]+)',
                'URL:\\1<a href="\\2">\\2</a>', output)
        return self.header + output + self.footer

    def filter_ansi(self, text):
        output = self.fontify(self.expand_tabs(text))
        return self.header + output + self.footer

    ### Fontify engine

    def fontify(self, pytext):
        # parse
        taglist = self.tag(pytext)

        # prepend special 'all' tag:
        taglist[:0] = [('all', 0, len(pytext), None)]

        # prepare splitting
        splits = []
        addsplits(splits, pytext, self.formats, taglist)

        # do splitting & inserting
        s = []
        li = 0
        for ri, dummy, insert in sorted(splits):
            if ri > li:
                s.append(pytext[li:ri])
            s.append(insert)
            li = ri
        if li < len(pytext):
            s.append(pytext[li:])

        return ''.join(s)


### Auxiliary

def addsplits(splits, text, formats, taglist):
    """Helper for .fontify()"""
    for id, left, right, sublist in taglist:
        try:
            pre, post = formats[id]
        except KeyError:
            # print >>sys.stderr, 'No format for %s specified\n' % repr(id)
            pre, post = '',''
        if not isinstance(pre, basestring):
            pre = pre(text[left:right])
        if not isinstance(post, basestring):
            post = post(text[left:right])
        # len(splits) is a dummy used to make sorting stable
        splits.append((left, len(splits), pre))
        if sublist:
            addsplits(splits, text, formats, sublist)
        splits.append((right, len(splits), post))

def write_html_error(titel, text):
    print """\
%s<html%s><head><title>%s</title></head>
<body>
<h2>%s</h2>
%s
</body></html>
""" % (HTML_DOCTYPE, HTML_XMLNS, titel, titel, text)

def redirect_to(url):
    sys.stdout.write('Content-Type: text/html\r\n')
    sys.stdout.write('Status: 302\r\n')
    sys.stdout.write('Location: %s\r\n\r\n' % url)
    print """
%s<html%s><head>
<title>302 Moved Temporarily</title>
</head><body>
<h1>302 Moved Temporarily</h1>
The document has moved to <a href="%s">%s</a>.<p></p>
</body></html>
""" % (HTML_DOCTYPE, HTML_XMLNS, url, url)


### Main

def main(cmdline):
    """main(cmdline) -- process cmdline as if it were sys.argv"""

    # parse options/files
    options = []
    optvalues = {}
    for opt in cmdline[1:]:
        if opt.startswith('-'):
            if ':' in opt:
                k, v = tuple(opt.split(':', 1))
                optvalues[k] = v
                options.append(k)
            else:
                options.append(opt)
        else:
            break
    files = cmdline[len(options)+1:]

    ### create converting object

    verbose = ('-v' in options)

    # load fontifier
    if '-marcs' in options:
        # use mxTextTool's tagging engine as fontifier
        from mx.TextTools import tag
        from mx.TextTools.Examples.Python import python_script
        tagfct = lambda text, tag=tag, pytable=python_script: tag(
            text, pytable)[1]
        print "Py2HTML: using Marc's tagging engine"
    else:
        # load Just's fontifier
        try:
            import PyFontify
            if PyFontify.__version__ < '0.3':
                raise ImportError
            tagfct = PyFontify.fontify
        except ImportError:
            print """
Sorry, but this script needs the PyFontify.py module version 0.3;
You can download it from Just's homepage at
URL: http://starship.python.net/~just/
"""
            sys.exit()

    if '-format' in options:
        format = optvalues['-format']
    else:
        # use default
        format = 'html'

    if '-mode' in options:
        mode = optvalues['-mode']
    else:
        # use default
        mode = 'color'

    c = PrettyPrint(tagfct, format, mode)
    convert = c.file_filter

    ### start working

    if '-title' in options:
        c.title = optvalues['-title']

    if '-bgcolor' in options:
        c.bgcolor = optvalues['-bgcolor']

    if '-header' in options:
        try:
            f = open(optvalues['-header'])
            c.header = f.read()
            f.close()
        except IOError:
            if verbose:
                print 'IOError: header file not found'

    if '-footer' in options:
        try:
            f = open(optvalues['-footer'])
            c.footer = f.read()
            f.close()
        except IOError:
            if verbose:
                print 'IOError: footer file not found'

    if '-URL' in options:
        c.replace_URLs = True

    if '-' in options:
        convert(sys.stdin, sys.stdout)
        sys.exit()

    if '-h' in options:
        print __doc__
        sys.exit()

    if not files:
        # Turn URL processing on
        c.replace_URLs = True
        # Try CGI processing...
        import cgi, urllib, urlparse, os
        form = cgi.FieldStorage()
        if 'script' not in form:
            # Ok, then try pathinfo
            if 'PATH_INFO' not in os.environ:
                if INPUT_FORM:
                    redirect_to(INPUT_FORM)
                else:
                    sys.stdout.write('Content-Type: text/html\r\n\r\n')
                    write_html_error('Missing Parameter',
                        'Missing script=URL field in request')
                sys.exit(1)
            url = os.environ['PATH_INFO'][1:] # skip the leading slash
        else:
            url = form['script'].value
        sys.stdout.write('Content-Type: text/html\r\n\r\n')
        scheme, host, path, params, query, frag = urlparse.urlparse(url)
        if not host:
            scheme = 'http'
            host = os.environ.get('HTTP_HOST', 'localhost')
            url = urlparse.urlunparse((scheme, host, path, params, query, frag))
        #print url; sys.exit()
        network = urllib.URLopener()
        try:
            tempfile, headers = network.retrieve(url)
        except IOError, reason:
            write_html_error('Error opening "%s"' % url,
                'The given URL could not be opened. Reason: %s' % str(reason))
            sys.exit(1)
        f = open(tempfile,'rb')
        c.title = url
        c.footer = __cgifooter__
        convert(f, sys.stdout)
        f.close()
        network.close()
        sys.exit()

    if '-stdout' in options:
        filebreak = '-'*72
        for f in files:
            try:
                if len(files) > 1:
                    print filebreak
                    print 'File:', f
                    print filebreak
                convert(f, sys.stdout)
            except IOError:
                pass
    else:
        if verbose:
            print 'Py2HTML: working on',
        for f in files:
            try:
                if verbose:
                    print f,
                convert(f, f+'.html')
            except IOError:
                if verbose:
                    print '(IOError!)',
        if verbose:
            print
            print 'Done.'


if __name__ == '__main__':
    main(sys.argv)