File: format.py

package info (click to toggle)
karrigell 2.3.2-1.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 6,484 kB
  • ctags: 4,167
  • sloc: python: 18,122; ansic: 370; sh: 129; makefile: 53; xml: 29
file content (49 lines) | stat: -rw-r--r-- 1,659 bytes parent folder | download
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
"""The function format(fileName, data, line) takes a file name,
data (usually the content of the file) and a line number,
and returns an HTML code with syntax highlighting"""

import re
import os
import pythonParser
import cStringIO
import cgi

def addTag(match):
    chunk=match.string[match.start()+2:match.end()-2]
    outStream=cStringIO.StringIO()
    pythonParser.Parser(chunk,None,out=outStream).format(None)
    return "<i>&lt;%"+outStream.getvalue()+"%&gt;</i>"

def render(in_data,showLine):
    output=[]
    for lineNum,line in enumerate(in_data.split('\n')):
        if lineNum==showLine:
            output.append('<span class="error">%s</span>' %line)
        else:
            output.append(line)
    return output

def format(fileName, data, line=-1):
    data=data.replace('&','&amp;')
    extension = os.path.splitext(fileName)[1].lower()

    if extension == ".pih":
        print '<br>Python chunks are in <i>italic</i>'
        # replace all < by &lt; except if followed by %
        data=re.sub("<(?!%)","&lt;",data)
        # regular expression for Python chunks. Cannot be written directly with
        # < followed by % because of parsing rules of this pih file...
        pyChunkRE=re.compile("<"+"%.*?%"+">",re.DOTALL)
        data=pyChunkRE.sub(addTag,data)
        code=render(data,line)
    elif extension in [".hip",".py",".ks"]:
        outStream=cStringIO.StringIO()
        p=pythonParser.Parser(cgi.escape(data),None,out=outStream)
        p.format(showLineNums=1)
        data=outStream.getvalue()
        code=render(data,line)
    else:
        code = [ cgi.escape(line) for line in data.split('\n') ]
    return code