okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
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 4from highlight import StreamHighlighter 5hl = StreamHighlighter(color=True) 6out = hl.feed(streamed_chunk) # complete lines, highlighted; a partial last line is held back 7out += 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 : 16def __init__ (self ,color :bool ): 17self .on = color 18 19def paint (self ,text :str ,code :str )-> str : 20return 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" }, 49re .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" }, 52re .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" }, 55re .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" }, 58re .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" }, 61re .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" }, 64re .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" }, 67re .compile (r"(/\*.*?\*/)|([.#][\w-]+)|([\w-]+)(?=\s*:)|\b(\d[\w.%]*)\b" ), 68 {1 :"90" ,2 :"96" ,3 :"94" ,4 :"34" }), 69"sql" : ({"sql" }, 70re .compile (r"(--.*$)|('[^']*')|\b(select|from|where|insert|into|update|set|delete|join|left|right|inner|" 71r"outer|on|group|by|order|having|limit|create|table|alter|drop|and|or|not|null|as)\b" , 72re .IGNORECASE ), 73 {1 :"90" ,2 :"33" ,3 :"35;1" }), 74"diff" : ({"diff" ,"patch" }, 75re .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 ): 85lang = _LANG_ALIAS .get (lang .lower (),lang .lower ()) 86for exts ,rx ,colors in _FAMILIES .values (): 87if lang in exts : 88return rx ,colors 89return None ,None 90 91 92class StreamHighlighter : 93"""Line-buffered highlighter for streamed text. feed() returns complete lines (highlighted inside fenced code 94blocks); flush() returns the held-back tail. Outside code fences the text is returned unchanged (color on or 95off), so prose never gets painted. All characters other than the added ANSI escapes pass through unchanged.""" 96 97def __init__ (self ,color :bool = True ): 98self .color = color 99self ._pal = _Palette (color ) 100self ._buf = "" # held-back partial line 101self ._in_fence = False 102self ._rx = None 103self ._colors = None 104 105def feed (self ,chunk :str )-> str : 106self ._buf += chunk 107out = [] 108while "\n" in self ._buf : 109line ,self ._buf = self ._buf .split ("\n" ,1 ) 110out .append (self ._line (line )) 111out .append ("\n" ) 112return "" .join (out ) 113 114def flush (self )-> str : 115tail ,self ._buf = self ._buf ,"" 116return self ._line (tail )if tail else "" 117 118def _line (self ,line :str )-> str : 119fence = _FENCE_RE .match (line ) 120if fence : 121marker ,lang = fence .group (1 ),fence .group (2 ) 122if self ._in_fence : 123self ._in_fence ,self ._rx ,self ._colors = False ,None ,None 124return self ._pal .paint (line ,"90" ) 125self ._in_fence = True 126self ._rx ,self ._colors = _family (lang ) 127if not self ._rx : 128return self ._pal .paint (line ,"90" ) 129return self ._pal .paint (marker ,"90" )+ self ._pal .paint (lang ,"94" )+ line [fence .end ():] 130if not self ._in_fence or not self ._rx : 131return line 132return self ._rx .sub (self ._sub ,line ) 133 134def _sub (self ,m :re .Match )-> str : 135for gi ,code in self ._colors .items (): 136if m .group (gi )is not None : 137return self ._pal .paint (m .group (gi ),code ) 138return m .group (0 )