-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathcount.go
More file actions
70 lines (61 loc) · 1.27 KB
/
count.go
File metadata and controls
70 lines (61 loc) · 1.27 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
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.24
package tui
import (
"strings"
"github.com/mattn/go-runewidth"
)
func cleanANSI(s string) string {
for {
start := strings.Index(s, "\x1b")
if start == -1 {
return s
}
end := strings.Index(s[start:], "m")
if end == -1 {
return s
}
s = s[:start] + s[start+end+1:]
}
}
// Width returns the width of the string, ignoring ANSI escape codes.
// Not all ANSI escape codes are supported yet.
func Width(s string) int {
return runewidth.StringWidth(cleanANSI(s))
}
// Ellipsis truncates a string to a given number of runes with an ellipsis at the end.
// It tries to persist the ANSI escape sequences.
func Ellipsis(s string, length int) string {
out := make([]rune, 0, length)
ln := 0
inEscape := false
tooLong := false
for _, r := range s {
if r == '\x1b' {
out = append(out, r)
inEscape = true
continue
}
if inEscape {
out = append(out, r)
if r == 'm' {
inEscape = false
if tooLong {
break
}
}
continue
}
ln += 1
if ln == length {
tooLong = true
}
if !tooLong {
out = append(out, r)
}
}
if tooLong {
return string(out) + "…"
}
return string(out)
}