vendor/github.com/charmbracelet/x/ansi/width.go
95 lines · 2241 bytes
1package ansi
2
3import (
4 "bytes"
5
6 "github.com/charmbracelet/x/ansi/parser"
7 "github.com/rivo/uniseg"
8)
9
10// Strip removes ANSI escape codes from a string.
11func Strip(s string) string {
12 var (
13 buf bytes.Buffer // buffer for collecting printable characters
14 ri int // rune index
15 rw int // rune width
16 pstate = parser.GroundState // initial state
17 )
18
19 // This implements a subset of the Parser to only collect runes and
20 // printable characters.
21 for i := 0; i < len(s); i++ {
22 if pstate == parser.Utf8State {
23 // During this state, collect rw bytes to form a valid rune in the
24 // buffer. After getting all the rune bytes into the buffer,
25 // transition to GroundState and reset the counters.
26 buf.WriteByte(s[i])
27 ri++
28 if ri < rw {
29 continue
30 }
31 pstate = parser.GroundState
32 ri = 0
33 rw = 0
34 continue
35 }
36
37 state, action := parser.Table.Transition(pstate, s[i])
38 switch action {
39 case parser.CollectAction:
40 if state == parser.Utf8State {
41 // This action happens when we transition to the Utf8State.
42 rw = utf8ByteLen(s[i])
43 buf.WriteByte(s[i])
44 ri++
45 }
46 case parser.PrintAction, parser.ExecuteAction:
47 // collects printable ASCII and non-printable characters
48 buf.WriteByte(s[i])
49 }
50
51 // Transition to the next state.
52 // The Utf8State is managed separately above.
53 if pstate != parser.Utf8State {
54 pstate = state
55 }
56 }
57
58 return buf.String()
59}
60
61// StringWidth returns the width of a string in cells. This is the number of
62// cells that the string will occupy when printed in a terminal. ANSI escape
63// codes are ignored and wide characters (such as East Asians and emojis) are
64// accounted for.
65func StringWidth(s string) int {
66 if s == "" {
67 return 0
68 }
69
70 var (
71 pstate = parser.GroundState // initial state
72 cluster string
73 width int
74 )
75
76 for i := 0; i < len(s); i++ {
77 state, action := parser.Table.Transition(pstate, s[i])
78 if state == parser.Utf8State {
79 var w int
80 cluster, _, w, _ = uniseg.FirstGraphemeClusterInString(s[i:], -1)
81 width += w
82 i += len(cluster) - 1
83 pstate = parser.GroundState
84 continue
85 }
86
87 if action == parser.PrintAction {
88 width++
89 }
90
91 pstate = state
92 }
93
94 return width
95}