File: syntax_highlight.py

package info (click to toggle)
python-redbaron 0.9.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 772 kB
  • sloc: python: 6,650; makefile: 145; sh: 28
file content (54 lines) | stat: -rw-r--r-- 1,777 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
50
51
52
53
54
HAS_PYGMENTS = True

try:
    import pygments
except ImportError:
    HAS_PYGMENTS = False


if HAS_PYGMENTS:
    from pygments.token import Comment, Text, String, Keyword, Name, Operator, Generic
    from pygments.lexer import RegexLexer, bygroups
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import Terminal256Formatter, HtmlFormatter


    class HelpLexer(RegexLexer):
        name = 'Lexer for RedBaron .help() method output'

        tokens = {
            'root': [
                (r'\x1b(.*?)\[(\d+)m', Generic),  # avoid escaping twice, see issue#180
                (r"#.*$", Comment),
                (r"('([^\\']|\\.)*'|\"([^\\\"]|\\.)*\")", String),
                (r"(None|False|True)", String),
                (r'(\*)( \w+Node)', bygroups(Operator, Keyword)),
                (r'\w+Node', Name.Function),
                (r'(\*|=|->|\(|\)|\.\.\.)', Operator),
                (r'\w+', Text),
                (r'\s+', Text),
            ]
        }

    def help_highlight(string):
        return highlight(string, HelpLexer(), Terminal256Formatter(style='monokai'))

    def python_highlight(string):
        return highlight(string, PythonLexer(encoding="Utf-8"),
                         Terminal256Formatter(style='monokai',
                                              encoding="Utf-8"))

    def python_html_highlight(string):
        return highlight(string, PythonLexer(encode="Utf-8"),
                         HtmlFormatter(noclasses=True, encoding="UTf-8"))

else:
    def help_highlight(string):
        return string.encode("Utf-8")

    def python_highlight(string):
        return string.encode("Utf-8")

    def python_html_highlight(string):
        return string.encode("Utf-8")