Skip to content

Commit c128055

Browse files
committed
Fix plain text length issue
Make sure that plain text length function correctly uses `RuneCountInString` from the `utf8` package.
1 parent 5105ac0 commit c128055

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

convenience.go

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,35 @@
2020

2121
package bunt
2222

23-
import colorful "github.com/lucasb-eyer/go-colorful"
23+
import (
24+
"regexp"
25+
"strings"
26+
"unicode/utf8"
27+
28+
colorful "github.com/lucasb-eyer/go-colorful"
29+
)
2430

2531
// StyleOption defines style option for strings
2632
type StyleOption func(*String)
2733

2834
// PlainTextLength returns the length of the input text without any escape
29-
// sequences. The function will panic in the unlikely case of a parse issue.
35+
// sequences.
3036
func PlainTextLength(text string) int {
31-
result, err := ParseString(text)
32-
if err != nil {
33-
panic(err)
37+
return utf8.RuneCountInString(RemoveAllEscapeSequences(text))
38+
}
39+
40+
// RemoveAllEscapeSequences return the input string with all escape sequences
41+
// removed.
42+
func RemoveAllEscapeSequences(input string) string {
43+
escapeSeqFinderRegExp := regexp.MustCompile(`\x1b\[([\d;]*)m`)
44+
45+
for loc := escapeSeqFinderRegExp.FindStringIndex(input); loc != nil; loc = escapeSeqFinderRegExp.FindStringIndex(input) {
46+
start := loc[0]
47+
end := loc[1]
48+
input = strings.Replace(input, input[start:end], "", -1)
3449
}
3550

36-
return len(*result)
51+
return input
3752
}
3853

3954
// Substring returns a substring of a text that may contains escape sequences.

convenience_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ var _ = Describe("convenience functions", func() {
5454
It("should return the right size when used on strings created by the bunt package", func() {
5555
Expect(PlainTextLength(Sprintf("*This* text is too long"))).To(BeEquivalentTo(len(Sprintf("This text is too long"))))
5656
})
57+
58+
It("should return the correct length based on the rune count", func() {
59+
Expect(PlainTextLength("fünf")).To(BeEquivalentTo(4))
60+
})
5761
})
5862

5963
Context("style function", func() {

0 commit comments

Comments
 (0)