-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_plaintext.go
86 lines (75 loc) · 2.11 KB
/
utils_plaintext.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
package glog
import (
"bytes"
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var (
reANSI = regexp.MustCompile(`\x1b\[(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[mABCDHfKsu]`)
)
func StripANSI(str string) string {
return reANSI.ReplaceAllStringFunc(str, func(s string) string {
return ""
})
}
func ReplaceRunes(str string, replacement string, list []rune) string {
var buf bytes.Buffer
for _, r := range str {
m := false
for _, ru := range list {
if ru == r {
m = true
break
}
}
if m {
buf.WriteString(replacement)
continue
}
buf.WriteRune(r)
}
return buf.String()
}
func ReplaceEmojis(str string, replacement string) string {
var buf bytes.Buffer
for _, r := range str {
if unicode.In(r, unicode.So, unicode.Sk) {
buf.WriteString(replacement)
} else {
buf.WriteRune(r)
}
}
return buf.String()
}
func RemoveNonPrintable(str string) string {
str = StripANSI(str)
var buf bytes.Buffer
for _, r := range str {
if r == 0x00 {
continue
}
if r >= 0x20 && r <= 0x7E || unicode.IsSpace(r) || (r >= 0x1F600 && r <= 0x1F64F) || (r >= 0x1F300 && r <= 0x1F5FF) || (r >= 0x1F680 && r <= 0x1F6FF) || (r >= 0x2600 && r <= 0x26FF) || (r >= 0x2700 && r <= 0x27BF) || (r >= 0x1F900 && r <= 0x1F9FF) {
buf.WriteRune(r)
}
}
return buf.String()
}
func PlaintextString(str string) string {
str = RemoveNonPrintable(str)
return str
}
func PlaintextStringLength(str string) int {
str = ReplaceRunes(str, " ", []rune{'μ', 'µ'}) // for padding calculations we actually need to count emojis as two
str = ReplaceEmojis(str, " ")
str = RemoveNonPrintable(str)
return utf8.RuneCountInString(str)
}
func plaintextStringLengthForPadding(str string, padChar rune) int {
str = strings.ReplaceAll(str, string(padChar), " ") // replace surrounding padding characters with single space
str = ReplaceRunes(str, " ", []rune{'μ', 'µ'}) // for padding calculations we actually need to count emojis as two chars
str = ReplaceEmojis(str, " ") // for padding calculations we actually need to count emojis as two chars
str = RemoveNonPrintable(str)
return utf8.RuneCountInString(str)
}