62159
Sy
symb / files
symb / internal / highlight / highlight.go
6.4 KB
1// Package highlight provides syntax highlighting via Chroma, decoupled from any 2// specific TUI component. 3package highlight 4 5import ( 6 "fmt" 7 "strings" 8 9 "github.com/alecthomas/chroma/v2" 10 "github.com/alecthomas/chroma/v2/formatters" 11 "github.com/alecthomas/chroma/v2/lexers" 12 "github.com/alecthomas/chroma/v2/styles" 13) 14 15// Highlight returns an ANSI-highlighted version of text using the given 16// Chroma language and theme. bgHex ("#rrggbb") is injected after every ANSI 17// reset so the background color is never lost. 18func Highlight(text, language, theme, bgHex string) string { 19 lex := lexers.Get(language) 20 if lex == nil { 21 return text 22 } 23 lex = chroma.Coalesce(lex) 24 sty := styles.Get(theme) 25 fmtr := formatters.Get("terminal16m") 26 if fmtr == nil { 27 fmtr = formatters.Fallback 28 } 29 it, err := lex.Tokenise(nil, text) 30 if err != nil { 31 return text 32 } 33 var buf strings.Builder 34 if err := fmtr.Format(&buf, sty, it); err != nil { 35 return text 36 } 37 raw := strings.TrimRight(buf.String(), "\n") 38 39 // Chroma's terminal16m formatter skips bg on tokens that inherit from 40 // the Background entry, and every \x1b[0m reset clears bg. Fix by 41 // replacing resets with reset+bg so the background is always active. 42 bgSeq := hexToBgSeq(bgHex) 43 return bgSeq + strings.ReplaceAll(raw, "\x1b[0m", "\x1b[0m"+bgSeq) 44} 45 46// hexToBgSeq converts "#rrggbb" to an ANSI 24-bit background escape sequence. 47func hexToBgSeq(hex string) string { 48 if len(hex) != 7 || hex[0] != '#' { 49 return "" 50 } 51 r := hexByte(hex[1], hex[2]) 52 g := hexByte(hex[3], hex[4]) 53 b := hexByte(hex[5], hex[6]) 54 return fmt.Sprintf("\x1b[48;2;%d;%d;%dm", r, g, b) 55} 56 57func hexByte(hi, lo byte) int { 58 return hexNibble(hi)<<4 | hexNibble(lo) 59} 60 61func hexNibble(c byte) int { 62 switch { 63 case c >= '0' && c <= '9': 64 return int(c - '0') 65 case c >= 'a' && c <= 'f': 66 return int(c-'a') + 10 67 case c >= 'A' && c <= 'F': 68 return int(c-'A') + 10 69 } 70 return 0 71} 72 73// SplitLines splits a highlighted block into per-line strings, propagating 74// ANSI style state across lines so each is independently renderable. 75func SplitLines(block string) []string { 76 lines := strings.Split(block, "\n") 77 if len(lines) <= 1 { 78 return lines 79 } 80 var active []string 81 for i, line := range lines { 82 if i > 0 && len(active) > 0 { 83 lines[i] = strings.Join(active, "") + line 84 } 85 active = scanSGR(line, active) 86 } 87 return lines 88} 89 90// scanSGR scans a line for SGR escape sequences and updates the active 91// sequence list. Resets clear the list; other SGRs are appended. 92func scanSGR(line string, active []string) []string { 93 for j := 0; j < len(line); j++ { 94 if line[j] != '\x1b' || j+1 >= len(line) || line[j+1] != '[' { 95 continue 96 } 97 k := j + 2 98 for k < len(line) && line[k] != 'm' && line[k] != '\x1b' { 99 k++ 100 } 101 if k >= len(line) || line[k] != 'm' { 102 continue 103 } 104 params := line[j+2 : k] 105 if params == "" || params == "0" { 106 active = active[:0] 107 } else { 108 active = append(active, line[j:k+1]) 109 } 110 j = k 111 } 112 return active 113} 114 115// ThemeBg extracts the background hex color from a Chroma style. 116// Returns "" if no background is set. 117func ThemeBg(theme string) string { 118 sty := styles.Get(theme) 119 if sty == nil { 120 return "" 121 } 122 bg := sty.Get(chroma.Background).Background 123 if !bg.IsSet() { 124 return "" 125 } 126 return bg.String() // "#rrggbb" 127} 128 129// Palette holds UI chrome colors derived deterministically from a Chroma theme. 130// The grayscale ramp is a linear interpolation from bg to fg; the accent is the 131// most saturated token color in the palette; error comes from the Error token. 132type Palette struct { 133 Bg string // Theme background 134 Fg string // Theme foreground (primary text) 135 Border string // 10% bg→fg — borders, dividers 136 LinkBg string // 7% bg→fg — subtle hover background 137 Dim string // 25% bg→fg — tertiary text, timestamps 138 Muted string // 45% bg→fg — secondary text, reasoning 139 Accent string // Most saturated token color 140 Error string // From chroma Error token, lerped 45% toward fg 141} 142 143// ThemePalette derives a full UI color palette from a Chroma theme name. 144// Deterministic: same theme → same output. Falls back to sensible defaults 145// when the theme is missing entries. 146func ThemePalette(theme string) Palette { 147 sty := styles.Get(theme) 148 if sty == nil { 149 return defaultPalette() 150 } 151 entry := sty.Get(chroma.Background) 152 bg := "#000000" 153 fg := "#c8c8c8" 154 if entry.Background.IsSet() { 155 bg = entry.Background.String() 156 } 157 if entry.Colour.IsSet() { 158 fg = entry.Colour.String() 159 } 160 161 p := Palette{ 162 Bg: bg, 163 Fg: fg, 164 Border: lerpHex(bg, fg, 0.10), 165 LinkBg: lerpHex(bg, fg, 0.07), 166 Dim: lerpHex(bg, fg, 0.25), 167 Muted: lerpHex(bg, fg, 0.45), 168 Accent: pickAccent(sty, fg), 169 Error: pickError(sty, bg, fg), 170 } 171 return p 172} 173 174func defaultPalette() Palette { 175 return Palette{ 176 Bg: "#000000", Fg: "#c8c8c8", 177 Border: "#141414", LinkBg: "#0e0e0e", 178 Dim: "#323232", Muted: "#5a5a5a", 179 Accent: "#00dfff", Error: "#932e2e", 180 } 181} 182 183// pickAccent returns the most saturated foreground color across all tokens. 184func pickAccent(sty *chroma.Style, fallback string) string { 185 best := fallback 186 bestSat := 0.0 187 for tt := chroma.TokenType(0); tt < 2000; tt++ { 188 e := sty.Get(tt) 189 if !e.Colour.IsSet() { 190 continue 191 } 192 hex := e.Colour.String() 193 r, g, b := hexToRGBf(hex) 194 mx := maxf(r, maxf(g, b)) 195 mn := minf(r, minf(g, b)) 196 if mx == 0 { 197 continue 198 } 199 sat := (mx - mn) / mx 200 if sat > bestSat { 201 bestSat = sat 202 best = hex 203 } 204 } 205 return best 206} 207 208// pickError extracts the Error token color and lerps it 45% toward fg 209// so it's visible but not garish against the theme background. 210func pickError(sty *chroma.Style, bg, fg string) string { 211 e := sty.Get(chroma.Error) 212 if !e.Colour.IsSet() { 213 return lerpHex(bg, fg, 0.45) // muted fallback 214 } 215 return lerpHex(bg, e.Colour.String(), 0.45) 216} 217 218// lerpHex linearly interpolates between two hex colors at fraction t. 219func lerpHex(a, b string, t float64) string { 220 ar, ag, ab := hexToRGBf(a) 221 br, bg, bb := hexToRGBf(b) 222 return fmt.Sprintf("#%02x%02x%02x", 223 clampByte(ar+(br-ar)*t), 224 clampByte(ag+(bg-ag)*t), 225 clampByte(ab+(bb-ab)*t), 226 ) 227} 228 229func hexToRGBf(hex string) (float64, float64, float64) { 230 if len(hex) != 7 || hex[0] != '#' { 231 return 0, 0, 0 232 } 233 return float64(hexByte(hex[1], hex[2])), 234 float64(hexByte(hex[3], hex[4])), 235 float64(hexByte(hex[5], hex[6])) 236} 237 238func clampByte(v float64) int { 239 if v < 0 { 240 return 0 241 } 242 if v > 255 { 243 return 255 244 } 245 return int(v + 0.5) 246} 247 248func maxf(a, b float64) float64 { 249 if a > b { 250 return a 251 } 252 return b 253} 254 255func minf(a, b float64) float64 { 256 if a < b { 257 return a 258 } 259 return b 260}