-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathansi.go
More file actions
109 lines (95 loc) · 2.31 KB
/
Copy pathansi.go
File metadata and controls
109 lines (95 loc) · 2.31 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
package fasttui
import "strings"
const (
CursorMarker = "\x1b_pi:c\x07"
SegmentReset = "\x1b[0m\x1b]8;;\x07"
)
func GetCursorMarker() string {
return CursorMarker
}
func GetSegmentReset() string {
return SegmentReset
}
// ExtractAnsiCode extracts an ANSI escape sequence starting at the given position.
// It supports three types of sequences:
// - CSI (Control Sequence Introducer): ESC [ ... terminator (e.g., ESC[31m for red text)
// - OSC (Operating System Command): ESC ] ... BEL or ESC \ (e.g., ESC]8;;url for hyperlinks)
// - APC (Application Program Command): ESC _ ... BEL or ESC \ (e.g., ESC_pi:c for cursor marker)
//
// Returns the complete escape sequence, its length, and whether extraction succeeded.
func ExtractAnsiCode(s string, pos int) (code string, length int, ok bool) {
if pos >= len(s) || s[pos] != '\x1b' {
return "", 0, false
}
if pos+1 >= len(s) {
return "", 0, false
}
next := s[pos+1]
switch next {
case '[': // CSI sequence
j := pos + 2
for j < len(s) && !isTerminator(s[j]) {
j++
}
if j < len(s) {
return s[pos : j+1], j + 1 - pos, true
}
return "", 0, false
case ']', '_': // OSC or APC sequence
return extractOscOrApc(s, pos)
}
return "", 0, false
}
// StripAnsi removes every escape sequence recognized by ExtractAnsiCode from s.
// Lone ESC bytes and incomplete or unsupported sequences are left unchanged.
func StripAnsi(s string) string {
if !strings.Contains(s, "\x1b") {
return s
}
b := acquireBuilder()
b.Grow(len(s))
for i := 0; i < len(s); {
if s[i] == '\x1b' {
if _, n, ok := ExtractAnsiCode(s, i); ok {
i += n
continue
}
}
b.WriteByte(s[i])
i++
}
out := b.String()
releaseBuilder(b)
return out
}
func extractOscOrApc(s string, pos int) (code string, length int, ok bool) {
j := pos + 2
for j < len(s) {
if s[j] == '\x07' {
return s[pos : j+1], j + 1 - pos, true
}
if j+1 < len(s) && s[j] == '\x1b' && s[j+1] == '\\' {
return s[pos : j+2], j + 2 - pos, true
}
j++
}
return "", 0, false
}
func isTerminator(b byte) bool {
return b >= 0x40 && b <= 0x7E
}
func updateTrackerFromText(text string, tracker *AnsiCodeTracker) {
if isPrintableASCII(text) {
return
}
i := 0
for i < len(text) {
code, length, ok := ExtractAnsiCode(text, i)
if ok {
tracker.Process(code)
i += length
} else {
i++
}
}
}