-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathansi_tokenizer.go
More file actions
466 lines (413 loc) · 10.3 KB
/
ansi_tokenizer.go
File metadata and controls
466 lines (413 loc) · 10.3 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package main
import "bytes"
type TokenKind int
const (
TokenText TokenKind = iota // Plain text, may contain symbols to link
TokenSGR // CSI Pm m - Select Graphic Rendition (colors, bold, etc.)
TokenCSI // CSI sequences other than SGR (cursor control, etc.)
TokenOSC8 // OSC 8 hyperlink sequence
TokenOSC // OSC sequences other than OSC 8 (window title, etc.)
TokenDCS // Device Control String (ESC P ... ST)
TokenOther // APC, PM, SOS, or buffer overflow
TokenESC // ESC + single byte that's not a sequence introducer
)
type Token struct {
Kind TokenKind
Data []byte
Styled bool // TokenSGR: true if styling remains active after this token
IsEnd bool // TokenOSC8: true if this is a link-closing sequence (empty URI)
URI []byte // TokenOSC8: the URI portion of the hyperlink (empty for IsEnd). e.g. for "\x1b]8;;file:///tmp/a\x1b\\" URI is "file:///tmp/a"; for "\x1b]8;id=foo;https://x\x1b\\" URI is "https://x".
}
type state int
const (
stateGround state = iota // Normal text processing
stateEsc // Received ESC, waiting for sequence introducer
stateCSI // Inside CSI sequence (ESC [), collecting params
stateOSC // Inside OSC sequence (ESC ]), collecting string
stateSTCandidate // Received ESC inside OSC/DCS, checking for ST (\)
stateDCS // Inside DCS/APC/PM sequence, waiting for ST
)
const (
escByte = 0x1b
belByte = 0x07
)
// maxBufferSize limits buffer growth for unterminated OSC/DCS sequences.
// If exceeded, the incomplete sequence is emitted as TokenOther and parsing resets.
const maxBufferSize = 4096
type sgrState struct {
fgActive bool
bgActive bool
attrs uint16
}
const (
attrBold uint16 = 1 << iota
attrFaint
attrItalic
attrUnderline
attrBlinkSlow
attrBlinkRapid
attrInverse
attrConceal
attrStrikethrough
)
func (s *sgrState) styled() bool {
return s.fgActive || s.bgActive || s.attrs != 0
}
func (s *sgrState) reset() {
s.fgActive = false
s.bgActive = false
s.attrs = 0
}
type AnsiTokenizer struct {
buf []byte
state state
prevState state
sgr sgrState
inOSC8 bool
}
func NewAnsiTokenizer() *AnsiTokenizer {
return &AnsiTokenizer{
state: stateGround,
}
}
func (t *AnsiTokenizer) Feed(p []byte) []Token {
var tokens []Token
for i := 0; i < len(p); i++ {
b := p[i]
switch t.state {
case stateGround:
if b == escByte {
if len(t.buf) > 0 {
tokens = append(tokens, Token{Kind: TokenText, Data: t.copyBuf()})
t.buf = t.buf[:0]
}
t.buf = append(t.buf, b)
t.state = stateEsc
} else {
t.buf = append(t.buf, b)
}
case stateEsc:
t.buf = append(t.buf, b)
switch b {
case '[':
t.state = stateCSI
case ']':
t.state = stateOSC
case 'P', '_', '^':
t.state = stateDCS
default:
tokens = append(tokens, Token{Kind: TokenESC, Data: t.copyBuf()})
t.buf = t.buf[:0]
t.state = stateGround
}
case stateCSI:
t.buf = append(t.buf, b)
if isCSIFinalByte(b) {
tok := t.emitCSI()
tokens = append(tokens, tok)
t.buf = t.buf[:0]
t.state = stateGround
} else if !isCSIParamByte(b) && !isCSIIntermediateByte(b) {
tokens = append(tokens, Token{Kind: TokenCSI, Data: t.copyBuf()})
t.buf = t.buf[:0]
t.state = stateGround
}
case stateOSC:
t.buf = append(t.buf, b)
switch b {
case belByte:
tok := t.emitOSC()
tokens = append(tokens, tok)
t.buf = t.buf[:0]
t.state = stateGround
case escByte:
t.prevState = stateOSC
t.state = stateSTCandidate
}
case stateSTCandidate:
t.buf = append(t.buf, b)
switch b {
case '\\':
if t.prevState == stateDCS {
tokens = append(tokens, Token{Kind: TokenDCS, Data: t.copyBuf()})
} else {
tok := t.emitOSC()
tokens = append(tokens, tok)
}
t.buf = t.buf[:0]
t.state = stateGround
default:
t.state = t.prevState
}
case stateDCS:
t.buf = append(t.buf, b)
switch b {
case escByte:
t.prevState = stateDCS
t.state = stateSTCandidate
default:
}
}
if len(t.buf) > maxBufferSize {
if t.state == stateGround {
tokens = append(tokens, Token{Kind: TokenText, Data: t.copyBuf()})
} else {
tokens = append(tokens, Token{Kind: TokenOther, Data: t.copyBuf()})
t.state = stateGround
}
t.buf = t.buf[:0]
}
}
if t.state == stateGround && len(t.buf) > 0 {
tokens = append(tokens, Token{Kind: TokenText, Data: t.copyBuf()})
t.buf = t.buf[:0]
}
return tokens
}
func (t *AnsiTokenizer) Flush() []Token {
if len(t.buf) == 0 {
return nil
}
kind := t.inferIncompleteKind()
tok := Token{Kind: kind, Data: t.copyBuf()}
if kind == TokenCSI && len(t.buf) >= 2 {
params := t.buf[2:]
applySGRParams(params, &t.sgr)
tok.Styled = t.sgr.styled()
}
t.buf = t.buf[:0]
t.state = stateGround
return []Token{tok}
}
func (t *AnsiTokenizer) Styled() bool {
return t.sgr.styled()
}
func (t *AnsiTokenizer) InOSC8() bool {
return t.inOSC8
}
func (t *AnsiTokenizer) copyBuf() []byte {
cp := make([]byte, len(t.buf))
copy(cp, t.buf)
return cp
}
func (t *AnsiTokenizer) inferIncompleteKind() TokenKind {
if len(t.buf) == 0 {
return TokenText
}
if t.buf[0] != escByte {
return TokenText
}
if len(t.buf) == 1 {
return TokenESC
}
switch t.buf[1] {
case '[':
return TokenCSI
case ']':
return TokenOSC
case 'P', '_', '^':
return TokenDCS
default:
return TokenESC
}
}
func (t *AnsiTokenizer) emitCSI() Token {
data := t.copyBuf()
tok := Token{Kind: TokenCSI, Data: data}
if len(data) >= 3 && data[len(data)-1] == 'm' {
tok.Kind = TokenSGR
params := data[2 : len(data)-1]
applySGRParams(params, &t.sgr)
tok.Styled = t.sgr.styled()
}
return tok
}
func (t *AnsiTokenizer) emitOSC() Token {
data := t.copyBuf()
oscData := extractOSCData(data)
if isEnd, uri, ok := parseOSC8(oscData); ok {
t.inOSC8 = !isEnd
return Token{Kind: TokenOSC8, Data: data, IsEnd: isEnd, URI: uri}
}
return Token{Kind: TokenOSC, Data: data}
}
func extractOSCData(data []byte) []byte {
if len(data) < 2 {
return nil
}
start := 2
if len(data) > start && data[start] == ';' {
start++
}
end := len(data)
if end > 0 && data[end-1] == belByte {
end--
} else if end >= 2 && data[end-2] == escByte && data[end-1] == '\\' {
end -= 2
}
if start >= end {
return nil
}
return data[start:end]
}
func isCSIFinalByte(b byte) bool {
return b >= 0x40 && b <= 0x7e
}
func isCSIParamByte(b byte) bool {
return b >= 0x30 && b <= 0x3f
}
func isCSIIntermediateByte(b byte) bool {
return b >= 0x20 && b <= 0x2f
}
func sgrSetsStyled(params []byte) (styled bool, explicit bool) {
var st sgrState
explicit = applySGRParams(params, &st)
return st.styled(), explicit
}
func applySGRParams(params []byte, st *sgrState) (explicit bool) {
if len(params) == 0 {
st.reset()
return true
}
codes := parseCSIParams(params)
for i := 0; i < len(codes); i++ {
code := codes[i]
switch code {
case 0:
st.reset()
explicit = true
case 1:
st.attrs |= attrBold
explicit = true
case 2:
st.attrs |= attrFaint
explicit = true
case 3:
st.attrs |= attrItalic
explicit = true
case 4:
st.attrs |= attrUnderline
explicit = true
case 5:
st.attrs |= attrBlinkSlow
explicit = true
case 6:
st.attrs |= attrBlinkRapid
explicit = true
case 7:
st.attrs |= attrInverse
explicit = true
case 8:
st.attrs |= attrConceal
explicit = true
case 9:
st.attrs |= attrStrikethrough
explicit = true
case 22:
st.attrs &^= attrBold | attrFaint
explicit = true
case 23:
st.attrs &^= attrItalic
explicit = true
case 24:
st.attrs &^= attrUnderline
explicit = true
case 25:
st.attrs &^= attrBlinkSlow | attrBlinkRapid
explicit = true
case 27:
st.attrs &^= attrInverse
explicit = true
case 28:
st.attrs &^= attrConceal
explicit = true
case 29:
st.attrs &^= attrStrikethrough
explicit = true
case 39:
st.fgActive = false
explicit = true
case 49:
st.bgActive = false
explicit = true
default:
if (code >= 30 && code <= 37) || (code >= 90 && code <= 97) {
st.fgActive = true
explicit = true
} else if code == 38 {
st.fgActive = true
explicit = true
i += skipExtendedColor(codes, i+1)
} else if (code >= 40 && code <= 47) || (code >= 100 && code <= 107) {
st.bgActive = true
explicit = true
} else if code == 48 {
st.bgActive = true
explicit = true
i += skipExtendedColor(codes, i+1)
}
}
}
return explicit
}
func skipExtendedColor(codes []int, start int) int {
if start >= len(codes) {
return 0
}
switch codes[start] {
case 5:
return 2
case 2:
return 4
default:
return 0
}
}
func parseCSIParams(params []byte) []int {
var codes []int
start := 0
for i := 0; i <= len(params); i++ {
if i == len(params) || params[i] == ';' {
if i > start {
code := parseNumber(params[start:i])
codes = append(codes, code)
} else {
codes = append(codes, 0)
}
start = i + 1
}
}
return codes
}
func parseNumber(s []byte) int {
n := 0
for _, b := range s {
if b >= '0' && b <= '9' {
n = n*10 + int(b-'0')
}
}
return n
}
// parseOSC8 parses an OSC 8 hyperlink payload (the bytes between ESC]
// and the string terminator, excluding the terminator).
//
// Examples (input → isEnd, uri, ok):
//
// "8;;https://example.com" → false, "https://example.com", true // link open
// "8;id=foo;https://example.com" → false, "https://example.com", true // link open with params
// "8;;linker.go" → false, "linker.go", true // malformed (no scheme) but still parses
// "8;;" → true, "", true // link close
// "8;id=foo;" → true, "", true // link close with params
// "0;window title" → false, nil, false // not OSC 8
// "8;" → false, nil, false // malformed: missing URI field
func parseOSC8(data []byte) (isEnd bool, uri []byte, ok bool) {
if !bytes.HasPrefix(data, []byte("8;")) {
return false, nil, false
}
parts := bytes.SplitN(data, []byte(";"), 3)
if len(parts) < 3 {
return false, nil, false
}
uri = parts[2]
return len(uri) == 0, uri, true
}