Debian Codegraph @

termseq.go

raw
1 package main
2
3 import (
4 "log"
5 "strconv"
6 "strings"
7 "unicode/utf8"
8
9 "github.com/gdamore/tcell/v3"
10 )
11
12 // gEscapeCode is the byte that starts ANSI control sequences.
13 const gEscapeCode byte = '\x1b'
14
15 // stripTermSequence is used to remove style-related ANSI escape sequences from
16 // a given string.
17 //
18 // Note: this function is based on [printLength] and only strips style-related
19 // sequences, `erase in line`, and `OSC 8` sequences. Other codes (e.g. cursor
20 // moves), as well as broken escape sequences, are not removed. This prevents
21 // mismatches between the two functions and avoids misalignment when rendering
22 // the UI.
23 func stripTermSequence(s string) string {
24 var b strings.Builder
25 slen := len(s)
26 for i := 0; i < slen; {
27 seq := readTermSequence(s[i:])
28 if seq != "" {
29 i += len(seq) // skip known sequence
30 continue
31 }
32
33 r, w := utf8.DecodeRuneInString(s[i:])
34 i += w
35 b.WriteRune(r)
36 }
37
38 return b.String()
39 }
40
41 // readTermSequence is used to extract and return a terminal sequence from a
42 // given string. If no supported sequence could be found, an empty string is
43 // returned.
44 //
45 // CSI (Control Sequence Introducer):
46 // - SGR (Select Graphic Rendition) `m`, used for text styling
47 // - EL (Erase in Line) `K`, returned only so we can skip it
48 //
49 // OSC (Operating System Command):
50 // - OSC 8, hyperlinks
51 func readTermSequence(s string) string {
52 slen := len(s)
53 // must start with ESC
54 if slen < 2 || s[0] != gEscapeCode {
55 return ""
56 }
57
58 switch s[1] {
59 case '[': // CSI
60 // Find the final byte (0x40-0x7E per ECMA-48), then check
61 // if it indicates a sequence we support (SGR or EL).
62 for i := 2; i < min(slen, 64); i++ {
63 if s[i] >= 0x40 && s[i] <= 0x7E {
64 if s[i] == 'm' || s[i] == 'K' {
65 return s[:i+1]
66 }
67 return ""
68 }
69 }
70 return ""
71 case ']': // OSC
72 if slen < 4 || s[2] != '8' || s[3] != ';' {
73 return ""
74 }
75 // find string terminator
76 for i := 4; i < slen; i++ {
77 b := s[i]
78 // BEL (XTerm)
79 if b == 0x07 {
80 return s[:i+1]
81 }
82 // ESC\ (ECMA-48)
83 if b == gEscapeCode && i+1 < slen && s[i+1] == '\\' {
84 return s[:i+2]
85 }
86 }
87 // TODO: C1 forms?
88 return ""
89 default:
90 return ""
91 }
92 }
93
94 // optionToFmtstr takes an escape sequence option (e.g. `\033[1m`) and outputs
95 // a complete format string (e.g. `\033[1m%s\033[0m`).
96 func optionToFmtstr(optstr string) string {
97 if !strings.Contains(optstr, "%s") {
98 return optstr + "%s\033[0m"
99 } else {
100 return optstr
101 }
102 }
103
104 // parseEscapeSequence takes an escape sequence option (e.g. `\033[1m`) and
105 // converts it to a [tcell.Style] object.
106 // Legacy function that only accepts SGR. Kept for convenience.
107 func parseEscapeSequence(s string) tcell.Style {
108 s = strings.TrimPrefix(s, "\033[")
109 if i := strings.IndexByte(s, 'm'); i >= 0 {
110 s = s[:i]
111 }
112 return applySGR(s, tcell.StyleDefault)
113 }
114
115 // applyTermSequence takes an escape sequence (e.g. `\033[1m`) and applies it
116 // to the given [tcell.Style] object.
117 // Accepts SGR and OSC sequences.
118 func applyTermSequence(s string, st tcell.Style) tcell.Style {
119 slen := len(s)
120 if slen < 2 || s[0] != gEscapeCode {
121 return st
122 }
123 switch s[1] {
124 case '[':
125 if s[slen-1] == 'm' {
126 return applySGR(s[2:slen-1], st)
127 }
128 return st
129 case ']':
130 // trim terminator (BEL or ESC\), then parse body
131 if s[slen-1] == 0x07 {
132 return applyOSC(s[2:slen-1], st)
133 } else if slen >= 2 && s[slen-2] == gEscapeCode && s[slen-1] == '\\' {
134 return applyOSC(s[2:slen-2], st)
135 }
136 return st
137 default:
138 return st
139 }
140 }
141
142 // applySGR takes an SGR sequence and applies it to the given [tcell.Style]
143 // object.
144 func applySGR(s string, st tcell.Style) tcell.Style {
145 toks := strings.Split(s, ";")
146
147 // ECMA-48 details the standard
148 tokslen := len(toks)
149
150 loop:
151 for i := 0; i < tokslen; i++ {
152 switch strings.TrimLeft(toks[i], "0") {
153 case "":
154 st = tcell.StyleDefault
155 case "1":
156 st = st.Bold(true)
157 case "2":
158 st = st.Dim(true)
159 case "3":
160 st = st.Italic(true)
161 case "4:0":
162 st = st.Underline(false)
163 case "4", "4:1":
164 st = st.Underline(true)
165 case "4:2":
166 st = st.Underline(tcell.UnderlineStyleDouble)
167 case "4:3":
168 st = st.Underline(tcell.UnderlineStyleCurly)
169 case "4:4":
170 st = st.Underline(tcell.UnderlineStyleDotted)
171 case "4:5":
172 st = st.Underline(tcell.UnderlineStyleDashed)
173 case "5", "6":
174 st = st.Blink(true)
175 case "7":
176 st = st.Reverse(true)
177 case "8":
178 // TODO: tcell PR for proper conceal
179 st = st.Foreground(st.GetBackground())
180 case "9":
181 st = st.StrikeThrough(true)
182 case "22":
183 st = st.Bold(false).Dim(false)
184 case "23":
185 st = st.Italic(false)
186 case "24":
187 st = st.Underline(false)
188 case "25":
189 st = st.Blink(false)
190 case "27":
191 st = st.Reverse(false)
192 case "29":
193 st = st.StrikeThrough(false)
194 case "30", "31", "32", "33", "34", "35", "36", "37":
195 n, _ := strconv.Atoi(toks[i])
196 st = st.Foreground(tcell.PaletteColor(n - 30))
197 case "90", "91", "92", "93", "94", "95", "96", "97":
198 n, _ := strconv.Atoi(toks[i])
199 st = st.Foreground(tcell.PaletteColor(n - 82))
200 case "38":
201 color, offset, err := parseColor(toks[i+1:])
202 if err != nil {
203 log.Printf("error processing ansi code 38: %s", err)
204 break loop
205 }
206 st = st.Foreground(color)
207 i += offset
208 case "40", "41", "42", "43", "44", "45", "46", "47":
209 n, _ := strconv.Atoi(toks[i])
210 st = st.Background(tcell.PaletteColor(n - 40))
211 case "100", "101", "102", "103", "104", "105", "106", "107":
212 n, _ := strconv.Atoi(toks[i])
213 st = st.Background(tcell.PaletteColor(n - 92))
214 case "48":
215 color, offset, err := parseColor(toks[i+1:])
216 if err != nil {
217 log.Printf("error processing ansi code 48: %s", err)
218 break loop
219 }
220 st = st.Background(color)
221 i += offset
222 case "58":
223 color, offset, err := parseColor(toks[i+1:])
224 if err != nil {
225 log.Printf("error processing ansi code 58: %s", err)
226 break loop
227 }
228 st = st.Underline(color)
229 i += offset
230 default:
231 log.Printf("unknown ansi code: %s", toks[i])
232 }
233 }
234
235 return st
236 }
237
238 // applyOSC takes an OSC sequence and applies it to the given [tcell.Style]
239 // object.
240 // It currently supports OSC 8 hyperlinks only, implemented as specified by
241 // https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
242 func applyOSC(body string, st tcell.Style) tcell.Style {
243 extractID := func(params string) string {
244 for seg := range strings.SplitSeq(params, ":") {
245 if seg == "" {
246 continue
247 }
248 if k, v, ok := strings.Cut(seg, "="); ok && k == "id" {
249 return v
250 }
251 }
252 return ""
253 }
254
255 toks := strings.SplitN(body, ";", 3)
256 if len(toks) < 2 {
257 return st
258 }
259 switch toks[0] {
260 case "8":
261 if len(toks) < 3 {
262 return st
263 }
264 url := toks[2]
265 if url == "" {
266 return st
267 }
268
269 st = st.Url(url)
270 // Optional property used to identify grouped hyperlinks.
271 if id := extractID(toks[1]); id != "" {
272 st = st.UrlId(id)
273 }
274 return st
275 default:
276 return st
277 }
278 }
279
280 // Sanitation helpers for untrusted text (filenames, previews, messages).
281 // Pick one of these when handling untrusted input:
282 //
283 // sanitizePreview - replace control chars, keep tabs (preview content).
284 // sanitizeName - replace control chars and tabs (names in width/column slots).
285 // sanitizeMessage - replace control chars, keep lf's own SGR/OSC8 (messages).
286 //
287 // isControlChar and isPrintable are internal predicates used by the above
288 // and the renderer; they are not sanitation entry points.
289
290 // isControlChar reports whether a rune is a control character or otherwise
291 // unsafe to display in a terminal.
292 // Covers C0 (0x00-0x1F), DEL (0x7F), and C1 (0x80-0x9F).
293 func isControlChar(r rune) bool {
294 return r < 0x20 || r == 0x7F || r >= 0x80 && r <= 0x9F
295 }
296
297 // sanitizePreview replaces control characters and invalid bytes with the
298 // Unicode replacement character (U+FFFD). Tabs are preserved for content
299 // where tab expansion is handled by the renderer (e.g. preview panes).
300 func sanitizePreview(s string) string {
301 return strings.Map(func(r rune) rune {
302 if r == '\t' || !isControlChar(r) {
303 return r
304 }
305 return '\uFFFD'
306 }, s)
307 }
308
309 // sanitizeName sanitizes a filename, path, or symlink target for display.
310 // Unlike sanitizePreview it also replaces tabs, because tabs in names
311 // are expanded by the renderer to tabstop width while displaywidth.String
312 // counts them as width 1, causing column overflow.
313 func sanitizeName(s string) string {
314 return strings.Map(func(r rune) rune {
315 if !isControlChar(r) {
316 return r
317 }
318 return '\uFFFD'
319 }, s)
320 }
321
322 // sanitizeMessage sanitizes a message intended for the message line. Like
323 // sanitizeName it strips control runes, but it preserves terminal sequences
324 // that lf itself recognizes (SGR, EL, OSC 8) so internal messages that use
325 // color or hyperlinks still render correctly.
326 func sanitizeMessage(s string) string {
327 s = strings.TrimRight(s, "\n\r")
328 var b strings.Builder
329 b.Grow(len(s))
330 for i := 0; i < len(s); {
331 if seq := readTermSequence(s[i:]); seq != "" {
332 b.WriteString(seq)
333 i += len(seq)
334 continue
335 }
336 r, w := utf8.DecodeRuneInString(s[i:])
337 if isControlChar(r) {
338 b.WriteRune('\uFFFD')
339 } else {
340 b.WriteRune(r)
341 }
342 i += w
343 }
344 return b.String()
345 }
346
347 // isPrintable reports whether a grapheme cluster is safe to display.
348 // It rejects C0/C1 controls, DEL, and invalid UTF-8.
349 func isPrintable(gc string) bool {
350 r, size := utf8.DecodeRuneInString(gc)
351 if r == utf8.RuneError && size <= 1 {
352 return false
353 }
354 return !isControlChar(r)
355 }