Source code elsie/text/highlight.py

 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
from pygments import highlight
from pygments.formatter import Formatter
from pygments.lexers import get_lexer_by_name
from pygments.styles import get_style_by_name

from .textparser import NEWLINE_1, normalize_tokens
from .textstyle import TextStyle


class MyFormatter(Formatter):
    def __init__(self):
        super().__init__()
        self.stream = []

    def format(self, tokensource, outfile):
        stream = self.stream
        for ttype, value in tokensource:
            if value == "\n":
                stream.append(NEWLINE_1)
            else:
                stream.append(("begin", "pygments-" + str(ttype)))
                if "\n" in value:
                    for t in value.split("\n"):
                        if t:
                            stream.append(("text", t))
                        stream.append(NEWLINE_1)
                    stream.pop()
                else:
                    stream.append(("text", value))
                stream.append(("end", None))


def highlight_code(code, language):
    lexer = get_lexer_by_name(language)
    formatter = MyFormatter()
    highlight(code, lexer, formatter)
    return normalize_tokens(formatter.stream)


def make_highlight_styles(pygments_style):
    results = {}
    for token, s in get_style_by_name(pygments_style):
        style = TextStyle()
        if s["color"]:
            style.color = "#" + s["color"]
        if s["bold"]:
            style.bold = True
        if s["italic"]:
            style.italic = True
        results["pygments-" + str(token)] = style
    return results