-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
359 lines (317 loc) · 7.4 KB
/
main.go
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
package main
import (
"bytes"
"cmp"
"fmt"
"io"
"os"
"strings"
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/ansi/parser"
"github.com/spf13/cobra"
)
const (
markerShift = parser.MarkerShift
intermedShift = parser.IntermedShift
)
var (
buf bytes.Buffer
raw bool
// Version as provided by goreleaser.
Version = ""
)
func main() {
if err := cmd().Execute(); err != nil {
os.Exit(1)
}
}
func cmd() *cobra.Command {
root := &cobra.Command{
Use: "sequin",
Short: "Human-readable ANSI sequences",
Args: cobra.ArbitraryArgs,
Example: `
printf '\x1b[m' | sequin
sequin <file
sequin -- some command to execute
`,
RunE: func(cmd *cobra.Command, args []string) error {
w := colorprofile.NewWriter(cmd.OutOrStdout(), os.Environ())
var in []byte
var err error
if len(args) == 0 {
in, err = io.ReadAll(cmd.InOrStdin())
} else {
in, err = executeCommand(cmd.Context(), args)
}
if err != nil {
return err
}
return process(w, in)
},
}
root.Flags().BoolVarP(&raw, "raw", "r", false, "raw mode (no explanation)")
root.Version = cmp.Or(Version, "unknown (built from source)")
return root
}
func process(w *colorprofile.Writer, in []byte) error {
var t theme
switch strings.ToLower(os.Getenv("SEQUIN_THEME")) {
case "ansi", "carlos", "secret_carlos", "matchy":
t = base16Theme(false)
default:
hasDarkBG := lipgloss.HasDarkBackground(os.Stdin, os.Stdout)
t = charmTheme(hasDarkBG)
}
t.IsRaw = raw
seqPrint := func(kind string, seq []byte) {
s := fmt.Sprintf("%q", seq)
s = strings.TrimPrefix(s, `"`)
s = strings.TrimSuffix(s, `"`)
if raw {
_, _ = fmt.Fprint(w, t.kindStyle(kind).Render(s))
return
}
// Trim introducers and terminators
// CSI
s = strings.TrimPrefix(s, "\\x9b")
s = strings.TrimPrefix(s, "\\x1b[")
// DCS
s = strings.TrimPrefix(s, "\\x90")
s = strings.TrimPrefix(s, "\\x1bP")
// OSC
s = strings.TrimPrefix(s, "\\x9d")
s = strings.TrimPrefix(s, "\\x1b]")
// BEL
if !bytes.Equal(seq, []byte{ansi.BEL}) {
// Remove only if not a literal bell
s = strings.TrimSuffix(s, "\\a")
}
// SOS
s = strings.TrimPrefix(s, "\\x98")
s = strings.TrimPrefix(s, "\\x1bX")
// PM
s = strings.TrimPrefix(s, "\\x9e")
s = strings.TrimPrefix(s, "\\x1b^")
// APC
s = strings.TrimPrefix(s, "\\x9f")
s = strings.TrimPrefix(s, "\\x1b_")
// ESC
if !bytes.Equal(seq, []byte{ansi.ESC}) {
// Remove only if not a standalone ESC
s = strings.TrimPrefix(s, "\\x1b")
}
// ST
if !bytes.Equal(seq, []byte{ansi.ST}) {
// Remove only if accompanied by a sequence introducer
s = strings.TrimSuffix(s, "\\x9c")
}
s = strings.TrimSuffix(s, "\\x1b\\\\")
_, _ = fmt.Fprintf(w, "%s", t.kindStyle(kind))
switch kind {
case "Ctrl":
_, _ = fmt.Fprintf(
w,
"%s%s%s\n",
t.sequence.Render(s),
t.separator,
t.explanation.Render(ctrlCodes[seq[0]]),
)
case "PM":
_, _ = fmt.Fprintf(
w,
"%s%s\n",
t.separator,
t.explanation.Render(fmt.Sprintf("Privacy message %q", s)),
)
case "SOS":
_, _ = fmt.Fprintf(
w,
"%s%s\n",
t.separator,
t.explanation.Render(fmt.Sprintf("Control string %q", s)),
)
case "":
_, _ = fmt.Fprintf(
w,
"%s%sUnknown %q\n",
t.sequence.Render(s),
t.separator,
seq,
)
default:
// For sequences with own handlers print only the kind and the sequence.
// Explanation will be provided by handlers themselves:
_, _ = fmt.Fprintf(
w,
"%s%s",
t.sequence.Render(s),
t.separator,
)
}
}
flushPrint := func() {
if buf.Len() == 0 {
return
}
if raw {
_, _ = fmt.Fprint(w, t.kindStyle("Text").Render(buf.String()))
} else {
_, _ = fmt.Fprintf(w, "%s%s\n", t.kindStyle("text"), t.text.Render(buf.String()))
}
buf.Reset()
}
handle := func(reg map[int]handlerFn, p *ansi.Parser) {
if raw {
return
}
handler, ok := reg[int(p.Cmd())]
if !ok {
_, _ = fmt.Fprintln(w, t.error.Render(errUnhandled.Error()))
return
}
out, err := handler(p)
if err != nil {
_, _ = fmt.Fprintln(w, t.error.Render(err.Error()))
return
}
_, _ = fmt.Fprintln(w, t.explanation.Render(out))
}
var state byte
p := ansi.GetParser()
defer ansi.PutParser(p)
for len(in) > 0 {
seq, width, n, newState := ansi.DecodeSequence(in, state, p)
switch {
case ansi.HasCsiPrefix(seq):
flushPrint()
seqPrint("CSI", seq)
handle(csiHandlers, p)
case ansi.HasDcsPrefix(seq):
flushPrint()
seqPrint("DCS", seq)
handle(dcsHandlers, p)
case ansi.HasOscPrefix(seq):
flushPrint()
seqPrint("OSC", seq)
handle(oscHandlers, p)
case ansi.HasPmPrefix(seq):
flushPrint()
seqPrint("PM", seq)
case ansi.HasSosPrefix(seq):
flushPrint()
seqPrint("SOS", seq)
case ansi.HasApcPrefix(seq):
flushPrint()
seqPrint("APC", seq)
switch {
case ansi.HasPrefix(p.Data(), []byte("G")):
// TODO: Kitty graphics
}
_, _ = fmt.Fprintln(w)
case ansi.HasEscPrefix(seq):
flushPrint()
if len(seq) == 1 && !raw {
// just an ESC
_, _ = fmt.Fprintf(
w,
"%s%s%s%s\n",
t.kindStyle("Ctrl"),
t.sequence.Render("ESC"),
t.separator,
t.explanation.Render("Escape"),
)
break
}
seqPrint("ESC", seq)
handle(escHandler, p)
case width == 0 && len(seq) == 1:
flushPrint()
// control code
seqPrint("Ctrl", seq)
case width > 0:
// Text
buf.WriteString(t.explanation.Render(string(seq)))
default:
flushPrint()
seqPrint("", seq)
}
in = in[n:]
state = newState
}
flushPrint()
return nil
}
var ctrlCodes = map[byte]string{
// C0
0: "Null",
1: "Start of heading",
2: "Start of text",
3: "End of text",
4: "End of transmission",
5: "Enquiry",
6: "Acknowledge",
7: "Bell",
8: "Backspace",
9: "Horizontal tab",
10: "Line feed",
11: "Vertical tab",
12: "Form feed",
13: "Carriage return",
14: "Shift out",
15: "Shift in",
16: "Data link escape",
17: "Device control 1",
18: "Device control 2",
19: "Device control 3",
20: "Device control 4",
21: "Negative acknowledge",
22: "Synchronous idle",
23: "End of transmission block",
24: "Cancel",
25: "End of medium",
26: "Substitute",
27: "Escape",
28: "File separator",
29: "Group separator",
30: "Record separator",
31: "Unit separator",
// RFC 20, section 4.1 "Control Characters" includes DEL with the note:
// "In the strict sense, DEL is not a control character."
127: "Delete",
// C1
0x80: "Padding character",
0x81: "High octet preset",
0x82: "Break permitted here",
0x83: "No break here",
0x84: "Index",
0x85: "Next line",
0x86: "Start of selected area",
0x87: "End of selected area",
0x88: "Character tabulation set",
0x89: "Character tabulation with justification",
0x8a: "Line tabulation set",
0x8b: "Partial line forward",
0x8c: "Partial line backward",
0x8d: "Reverse line feed",
0x8e: "Single shift 2",
0x8f: "Single shift 3",
0x90: "Device control string",
0x91: "Private use 1",
0x92: "Private use 2",
0x93: "Set transmit state",
0x94: "Cancel character",
0x95: "Message waiting",
0x96: "Start of guarded area",
0x97: "End of guarded area",
0x98: "Start of string",
0x99: "Single graphic character introducer",
0x9a: "Single character introducer",
0x9b: "Control sequence introducer",
0x9c: "String terminator",
0x9d: "Operating system command",
0x9e: "Privacy message",
0x9f: "Application program command",
}