okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
6.8 KiB138 linesraw
1"""Syntax highlighting for chat.py's streamed output: fenced code blocks get colored (tags, strings, comments,
2keywords, numbers), everything else passes through unchanged. Standard library only, no dependency.
3
4    from highlight import StreamHighlighter
5    hl = StreamHighlighter(color=True)
6    out = hl.feed(streamed_chunk)   # complete lines, highlighted; a partial last line is held back
7    out += hl.flush()               # the held-back tail (unclosed fence included)
8"""
9from __future__ import annotations
10
11import re
12
13
14# ANSI colors; a disabled colorer returns the text unchanged
15class _Palette:
16    def __init__(self, color: bool):
17        self.on = color
18
19    def paint(self, text: str, code: str) -> str:
20        return f"\033[{code}m{text}\033[0m" if self.on else text
21
22
23# one regex per language family; the first matching family paints the line
24_PY_KEYWORDS = ("False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
25                "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in",
26                "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield")
27_JS_KEYWORDS = ("async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete",
28                "do", "else", "export", "extends", "false", "finally", "for", "function", "if", "import", "in",
29                "instanceof", "let", "new", "null", "return", "static", "super", "switch", "this", "throw", "true",
30                "try", "typeof", "undefined", "var", "void", "while", "yield")
31_C_KEYWORDS = ("alignas", "auto", "bool", "break", "case", "catch", "char", "class", "const", "constexpr",
32               "continue", "default", "delete", "do", "double", "else", "enum", "explicit", "extern", "false",
33               "float", "for", "friend", "if", "inline", "int", "long", "namespace", "new", "noexcept", "nullptr",
34               "private", "protected", "public", "return", "short", "signed", "sizeof", "static", "struct",
35               "switch", "template", "this", "throw", "true", "try", "typedef", "typename", "union", "unsigned",
36               "using", "virtual", "void", "while")
37_SHELL_KEYWORDS = ("case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "then",
38                   "until", "while")
39_JSON_KEYS = ("false", "null", "true")
40
41_STR = r"(\"(?:[^\"\\]|\\.)*\")"        # "..." with escapes
42_SQ_STR = r"('(?:[^'\\]|\\.)*')"
43_COMMENT = r"(#.*$)"
44_SLASH_COMMENT = r"(//.*$)"
45_NUM = r"\b(\d[\w.]*)\b"
46
47_FAMILIES = {
48    "markup": ({"html", "htm", "xml", "svg", "vue", "jsx", "tsx"},
49               re.compile(r"(<!--.*?-->)|(<[A-Za-z][\w:.-]*/?>?)|(</[A-Za-z][\w:.-]*>)|([A-Za-z-]+)(?==)"),
50               {1: "36;1", 2: "96", 3: "96", 4: "94"}),
51    "python": ({"py", "python"},
52               re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_PY_KEYWORDS)})\b|{_NUM}"),
53               {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "34"}),
54    "c-like": ({"c", "cc", "cpp", "c++", "h", "hpp", "cu", "hip", "java", "kt", "rs", "go", "cs"},
55               re.compile(rf"{_SLASH_COMMENT}|{_STR}|\b({'|'.join(_C_KEYWORDS)})\b|\b(0x[0-9a-fA-F]+|\d[\w.]*)\b"),
56               {1: "90", 2: "33", 3: "35;1", 4: "34"}),
57    "js-like": ({"js", "javascript", "ts", "typescript", "mjs"},
58                re.compile(rf"{_SLASH_COMMENT}|{_STR}|{_SQ_STR}|(`[^`]*`)|\b({'|'.join(_JS_KEYWORDS)})\b|{_NUM}"),
59                {1: "90", 2: "33", 3: "33", 4: "33", 5: "35;1", 6: "34"}),
60    "shell": ({"sh", "bash", "zsh", "shell", "console", "bat", "cmd", "powershell", "ps1"},
61              re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_SHELL_KEYWORDS)})\b|(^\s*\$)"),
62              {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "90"}),
63    "json": ({"json", "jsonc", "json5"},
64             re.compile(rf"{_SLASH_COMMENT}|{_STR}(?=\s*:)|\b({'|'.join(_JSON_KEYS)})\b|\b(-?\d[\w.]*)\b"),
65             {1: "90", 2: "94", 3: "35;1", 4: "34"}),
66    "css": ({"css", "scss", "less"},
67            re.compile(r"(/\*.*?\*/)|([.#][\w-]+)|([\w-]+)(?=\s*:)|\b(\d[\w.%]*)\b"),
68            {1: "90", 2: "96", 3: "94", 4: "34"}),
69    "sql": ({"sql"},
70            re.compile(r"(--.*$)|('[^']*')|\b(select|from|where|insert|into|update|set|delete|join|left|right|inner|"
71                       r"outer|on|group|by|order|having|limit|create|table|alter|drop|and|or|not|null|as)\b",
72                       re.IGNORECASE),
73            {1: "90", 2: "33", 3: "35;1"}),
74    "diff": ({"diff", "patch"},
75             re.compile(r"^(\+[^+]*)|^(-.*)|^(@@.*@@)"),
76             {1: "32", 2: "31", 3: "36"}),
77}
78
79_FENCE_RE = re.compile(r"^\s*(```|~~~)\s*([\w+#-]*)")
80_LANG_ALIAS = {"c++": "c-like", "javascript": "js-like", "typescript": "js-like", "python": "python",
81               "py": "python", "shell": "shell", "bash": "shell", "console": "shell"}
82
83
84def _family(lang: str):
85    lang = _LANG_ALIAS.get(lang.lower(), lang.lower())
86    for exts, rx, colors in _FAMILIES.values():
87        if lang in exts:
88            return rx, colors
89    return None, None
90
91
92class StreamHighlighter:
93    """Line-buffered highlighter for streamed text. feed() returns complete lines (highlighted inside fenced code
94    blocks); flush() returns the held-back tail. Outside code fences the text is returned unchanged (color on or
95    off), so prose never gets painted. All characters other than the added ANSI escapes pass through unchanged."""
96
97    def __init__(self, color: bool = True):
98        self.color = color
99        self._pal = _Palette(color)
100        self._buf = ""          # held-back partial line
101        self._in_fence = False
102        self._rx = None
103        self._colors = None
104
105    def feed(self, chunk: str) -> str:
106        self._buf += chunk
107        out = []
108        while "\n" in self._buf:
109            line, self._buf = self._buf.split("\n", 1)
110            out.append(self._line(line))
111            out.append("\n")
112        return "".join(out)
113
114    def flush(self) -> str:
115        tail, self._buf = self._buf, ""
116        return self._line(tail) if tail else ""
117
118    def _line(self, line: str) -> str:
119        fence = _FENCE_RE.match(line)
120        if fence:
121            marker, lang = fence.group(1), fence.group(2)
122            if self._in_fence:
123                self._in_fence, self._rx, self._colors = False, None, None
124                return self._pal.paint(line, "90")
125            self._in_fence = True
126            self._rx, self._colors = _family(lang)
127            if not self._rx:
128                return self._pal.paint(line, "90")
129            return self._pal.paint(marker, "90") + self._pal.paint(lang, "94") + line[fence.end():]
130        if not self._in_fence or not self._rx:
131            return line
132        return self._rx.sub(self._sub, line)
133
134    def _sub(self, m: re.Match) -> str:
135        for gi, code in self._colors.items():
136            if m.group(gi) is not None:
137                return self._pal.paint(m.group(gi), code)
138        return m.group(0)