vendor/github.com/charmbracelet/x/ansi/parser_decode.go
423 lines · 11867 bytes
1package ansi
2
3import (
4 "bytes"
5 "strings"
6 "unicode/utf8"
7
8 "github.com/charmbracelet/x/ansi/parser"
9 "github.com/rivo/uniseg"
10)
11
12// State represents the state of the ANSI escape sequence parser used by
13// [DecodeSequence].
14type State = byte
15
16// ANSI escape sequence states used by [DecodeSequence].
17const (
18 NormalState State = iota
19 MarkerState
20 ParamsState
21 IntermedState
22 EscapeState
23 StringState
24)
25
26// DecodeSequence decodes the first ANSI escape sequence or a printable
27// grapheme from the given data. It returns the sequence slice, the number of
28// bytes read, the cell width for each sequence, and the new state.
29//
30// The cell width will always be 0 for control and escape sequences, 1 for
31// ASCII printable characters, and the number of cells other Unicode characters
32// occupy. It uses the uniseg package to calculate the width of Unicode
33// graphemes and characters. This means it will always do grapheme clustering
34// (mode 2027).
35//
36// Passing a non-nil [*Parser] as the last argument will allow the decoder to
37// collect sequence parameters, data, and commands. The parser cmd will have
38// the packed command value that contains intermediate and marker characters.
39// In the case of a OSC sequence, the cmd will be the OSC command number. Use
40// [Cmd] and [Param] types to unpack command intermediates and markers as well
41// as parameters.
42//
43// Zero [p.Cmd] means the CSI, DCS, or ESC sequence is invalid. Moreover, checking the
44// validity of other data sequences, OSC, DCS, etc, will require checking for
45// the returned sequence terminator bytes such as ST (ESC \\) and BEL).
46//
47// We store the command byte in [p.Cmd] in the most significant byte, the
48// marker byte in the next byte, and the intermediate byte in the least
49// significant byte. This is done to avoid using a struct to store the command
50// and its intermediates and markers. The command byte is always the least
51// significant byte i.e. [p.Cmd & 0xff]. Use the [Cmd] type to unpack the
52// command, intermediate, and marker bytes. Note that we only collect the last
53// marker character and intermediate byte.
54//
55// The [p.Params] slice will contain the parameters of the sequence. Any
56// sub-parameter will have the [parser.HasMoreFlag] set. Use the [Param] type
57// to unpack the parameters.
58//
59// Example:
60//
61// var state byte // the initial state is always zero [NormalState]
62// p := NewParser(32, 1024) // create a new parser with a 32 params buffer and 1024 data buffer (optional)
63// input := []byte("\x1b[31mHello, World!\x1b[0m")
64// for len(input) > 0 {
65// seq, width, n, newState := DecodeSequence(input, state, p)
66// log.Printf("seq: %q, width: %d", seq, width)
67// state = newState
68// input = input[n:]
69// }
70func DecodeSequence[T string | []byte](b T, state byte, p *Parser) (seq T, width int, n int, newState byte) {
71 for i := 0; i < len(b); i++ {
72 c := b[i]
73
74 switch state {
75 case NormalState:
76 switch c {
77 case ESC:
78 if p != nil {
79 if len(p.Params) > 0 {
80 p.Params[0] = parser.MissingParam
81 }
82 p.Cmd = 0
83 p.ParamsLen = 0
84 p.DataLen = 0
85 }
86 state = EscapeState
87 continue
88 case CSI, DCS:
89 if p != nil {
90 if len(p.Params) > 0 {
91 p.Params[0] = parser.MissingParam
92 }
93 p.Cmd = 0
94 p.ParamsLen = 0
95 p.DataLen = 0
96 }
97 state = MarkerState
98 continue
99 case OSC, APC, SOS, PM:
100 if p != nil {
101 p.Cmd = parser.MissingCommand
102 p.DataLen = 0
103 }
104 state = StringState
105 continue
106 }
107
108 if p != nil {
109 p.DataLen = 0
110 p.ParamsLen = 0
111 p.Cmd = 0
112 }
113 if c > US && c < DEL {
114 // ASCII printable characters
115 return b[i : i+1], 1, 1, NormalState
116 }
117
118 if c <= US || c == DEL || c < 0xC0 {
119 // C0 & C1 control characters & DEL
120 return b[i : i+1], 0, 1, NormalState
121 }
122
123 if utf8.RuneStart(c) {
124 seq, _, width, _ = FirstGraphemeCluster(b, -1)
125 i += len(seq)
126 return b[:i], width, i, NormalState
127 }
128
129 // Invalid UTF-8 sequence
130 return b[:i], 0, i, NormalState
131 case MarkerState:
132 if c >= '<' && c <= '?' {
133 if p != nil {
134 // We only collect the last marker character.
135 p.Cmd &^= 0xff << parser.MarkerShift
136 p.Cmd |= int(c) << parser.MarkerShift
137 }
138 break
139 }
140
141 state = ParamsState
142 fallthrough
143 case ParamsState:
144 if c >= '0' && c <= '9' {
145 if p != nil {
146 if p.Params[p.ParamsLen] == parser.MissingParam {
147 p.Params[p.ParamsLen] = 0
148 }
149
150 p.Params[p.ParamsLen] *= 10
151 p.Params[p.ParamsLen] += int(c - '0')
152 }
153 break
154 }
155
156 if c == ':' {
157 if p != nil {
158 p.Params[p.ParamsLen] |= parser.HasMoreFlag
159 }
160 }
161
162 if c == ';' || c == ':' {
163 if p != nil {
164 p.ParamsLen++
165 if p.ParamsLen < len(p.Params) {
166 p.Params[p.ParamsLen] = parser.MissingParam
167 }
168 }
169 break
170 }
171
172 state = IntermedState
173 fallthrough
174 case IntermedState:
175 if c >= ' ' && c <= '/' {
176 if p != nil {
177 p.Cmd &^= 0xff << parser.IntermedShift
178 p.Cmd |= int(c) << parser.IntermedShift
179 }
180 break
181 }
182
183 state = NormalState
184 if c >= '@' && c <= '~' {
185 if p != nil {
186 // Increment the last parameter
187 if p.ParamsLen > 0 && p.ParamsLen < len(p.Params)-1 ||
188 p.ParamsLen == 0 && len(p.Params) > 0 && p.Params[0] != parser.MissingParam {
189 p.ParamsLen++
190 }
191
192 p.Cmd &^= 0xff
193 p.Cmd |= int(c)
194 }
195
196 if HasDcsPrefix(b) {
197 // Continue to collect DCS data
198 if p != nil {
199 p.DataLen = 0
200 }
201 state = StringState
202 continue
203 }
204
205 return b[:i+1], 0, i + 1, state
206 }
207
208 // Invalid CSI/DCS sequence
209 return b[:i], 0, i, NormalState
210 case EscapeState:
211 switch c {
212 case '[', 'P':
213 if p != nil {
214 if len(p.Params) > 0 {
215 p.Params[0] = parser.MissingParam
216 }
217 p.ParamsLen = 0
218 p.Cmd = 0
219 }
220 state = MarkerState
221 continue
222 case ']', 'X', '^', '_':
223 if p != nil {
224 p.Cmd = parser.MissingCommand
225 p.DataLen = 0
226 }
227 state = StringState
228 continue
229 }
230
231 if c >= ' ' && c <= '/' {
232 if p != nil {
233 p.Cmd &^= 0xff << parser.IntermedShift
234 p.Cmd |= int(c) << parser.IntermedShift
235 }
236 continue
237 } else if c >= '0' && c <= '~' {
238 if p != nil {
239 p.Cmd &^= 0xff
240 p.Cmd |= int(c)
241 }
242 return b[:i+1], 0, i + 1, NormalState
243 }
244
245 // Invalid escape sequence
246 return b[:i], 0, i, NormalState
247 case StringState:
248 switch c {
249 case BEL:
250 if HasOscPrefix(b) {
251 return b[:i+1], 0, i + 1, NormalState
252 }
253 case CAN, SUB:
254 // Cancel the sequence
255 return b[:i], 0, i, NormalState
256 case ST:
257 return b[:i+1], 0, i + 1, NormalState
258 case ESC:
259 if HasStPrefix(b[i:]) {
260 // End of string 7-bit (ST)
261 return b[:i+2], 0, i + 2, NormalState
262 }
263
264 // Otherwise, cancel the sequence
265 return b[:i], 0, i, NormalState
266 }
267
268 if p != nil && p.DataLen < len(p.Data) {
269 p.Data[p.DataLen] = c
270 p.DataLen++
271
272 // Parse the OSC command number
273 if c == ';' && p.Cmd == parser.MissingCommand && HasOscPrefix(b) {
274 for j := 0; j < p.DataLen; j++ {
275 d := p.Data[j]
276 if d < '0' || d > '9' {
277 break
278 }
279 if p.Cmd == parser.MissingCommand {
280 p.Cmd = 0
281 }
282 p.Cmd *= 10
283 p.Cmd += int(d - '0')
284 }
285 }
286 }
287 }
288 }
289
290 return b, 0, len(b), state
291}
292
293// Index returns the index of the first occurrence of the given byte slice in
294// the data. It returns -1 if the byte slice is not found.
295func Index[T string | []byte](data, b T) int {
296 switch data := any(data).(type) {
297 case string:
298 return strings.Index(data, string(b))
299 case []byte:
300 return bytes.Index(data, []byte(b))
301 }
302 panic("unreachable")
303}
304
305// Equal returns true if the given byte slices are equal.
306func Equal[T string | []byte](a, b T) bool {
307 return string(a) == string(b)
308}
309
310// HasPrefix returns true if the given byte slice has prefix.
311func HasPrefix[T string | []byte](b, prefix T) bool {
312 return len(b) >= len(prefix) && Equal(b[0:len(prefix)], prefix)
313}
314
315// HasSuffix returns true if the given byte slice has suffix.
316func HasSuffix[T string | []byte](b, suffix T) bool {
317 return len(b) >= len(suffix) && Equal(b[len(b)-len(suffix):], suffix)
318}
319
320// HasCsiPrefix returns true if the given byte slice has a CSI prefix.
321func HasCsiPrefix[T string | []byte](b T) bool {
322 return (len(b) > 0 && b[0] == CSI) ||
323 (len(b) > 1 && b[0] == ESC && b[1] == '[')
324}
325
326// HasOscPrefix returns true if the given byte slice has an OSC prefix.
327func HasOscPrefix[T string | []byte](b T) bool {
328 return (len(b) > 0 && b[0] == OSC) ||
329 (len(b) > 1 && b[0] == ESC && b[1] == ']')
330}
331
332// HasApcPrefix returns true if the given byte slice has an APC prefix.
333func HasApcPrefix[T string | []byte](b T) bool {
334 return (len(b) > 0 && b[0] == APC) ||
335 (len(b) > 1 && b[0] == ESC && b[1] == '_')
336}
337
338// HasDcsPrefix returns true if the given byte slice has a DCS prefix.
339func HasDcsPrefix[T string | []byte](b T) bool {
340 return (len(b) > 0 && b[0] == DCS) ||
341 (len(b) > 1 && b[0] == ESC && b[1] == 'P')
342}
343
344// HasSosPrefix returns true if the given byte slice has a SOS prefix.
345func HasSosPrefix[T string | []byte](b T) bool {
346 return (len(b) > 0 && b[0] == SOS) ||
347 (len(b) > 1 && b[0] == ESC && b[1] == 'X')
348}
349
350// HasPmPrefix returns true if the given byte slice has a PM prefix.
351func HasPmPrefix[T string | []byte](b T) bool {
352 return (len(b) > 0 && b[0] == PM) ||
353 (len(b) > 1 && b[0] == ESC && b[1] == '^')
354}
355
356// HasStPrefix returns true if the given byte slice has a ST prefix.
357func HasStPrefix[T string | []byte](b T) bool {
358 return (len(b) > 0 && b[0] == ST) ||
359 (len(b) > 1 && b[0] == ESC && b[1] == '\\')
360}
361
362// HasEscPrefix returns true if the given byte slice has an ESC prefix.
363func HasEscPrefix[T string | []byte](b T) bool {
364 return len(b) > 0 && b[0] == ESC
365}
366
367// FirstGraphemeCluster returns the first grapheme cluster in the given string or byte slice.
368// This is a syntactic sugar function that wraps
369// uniseg.FirstGraphemeClusterInString and uniseg.FirstGraphemeCluster.
370func FirstGraphemeCluster[T string | []byte](b T, state int) (T, T, int, int) {
371 switch b := any(b).(type) {
372 case string:
373 cluster, rest, width, newState := uniseg.FirstGraphemeClusterInString(b, state)
374 return T(cluster), T(rest), width, newState
375 case []byte:
376 cluster, rest, width, newState := uniseg.FirstGraphemeCluster(b, state)
377 return T(cluster), T(rest), width, newState
378 }
379 panic("unreachable")
380}
381
382// Cmd represents a sequence command. This is used to pack/unpack a sequence
383// command with its intermediate and marker characters. Those are commonly
384// found in CSI and DCS sequences.
385type Cmd int
386
387// Marker returns the marker byte of the CSI sequence.
388// This is always gonna be one of the following '<' '=' '>' '?' and in the
389// range of 0x3C-0x3F.
390// Zero is returned if the sequence does not have a marker.
391func (c Cmd) Marker() int {
392 return parser.Marker(int(c))
393}
394
395// Intermediate returns the intermediate byte of the CSI sequence.
396// An intermediate byte is in the range of 0x20-0x2F. This includes these
397// characters from ' ', '!', '"', '#', '$', '%', '&', ”', '(', ')', '*', '+',
398// ',', '-', '.', '/'.
399// Zero is returned if the sequence does not have an intermediate byte.
400func (c Cmd) Intermediate() int {
401 return parser.Intermediate(int(c))
402}
403
404// Command returns the command byte of the CSI sequence.
405func (c Cmd) Command() int {
406 return parser.Command(int(c))
407}
408
409// Param represents a sequence parameter. Sequence parameters with
410// sub-parameters are packed with the HasMoreFlag set. This is used to unpack
411// the parameters from a CSI and DCS sequences.
412type Param int
413
414// Param returns the parameter at the given index.
415// It returns -1 if the parameter does not exist.
416func (s Param) Param() int {
417 return int(s) & parser.ParamMask
418}
419
420// HasMore returns true if the parameter has more sub-parameters.
421func (s Param) HasMore() bool {
422 return int(s)&parser.HasMoreFlag != 0
423}