Skip to content

Commit 6921c75

Browse files
committed
fix(ansi): width: always use grapheme finder for width calculation
When we're encountering half-width characters, or joining characters, it's important that we use the grapheme cluster finder to determine the width of the string. For example, an ASCII + a joining character is a single grapheme, but we used to treat it as two separate characters, which caused the width to be incorrectly calculated as 2 instead of 1.
1 parent 266cf5a commit 6921c75

2 files changed

Lines changed: 2 additions & 1 deletion

File tree

ansi/width.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func stringWidth(m Method, s string) int {
8787

8888
for i := 0; i < len(s); i++ {
8989
state, action := parser.Table.Transition(pstate, s[i])
90-
if state == parser.Utf8State {
90+
if action == parser.PrintAction || state == parser.Utf8State {
9191
cluster, w := FirstGraphemeCluster(s[i:], m)
9292
width += w
9393

ansi/width_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ var cases = []struct {
3434
{"unclosed_ansi", "Hey, \x1b[7m\n猴", "Hey, \n猴", 7, 7},
3535
{"double_asian_runes", " 你\x1b[8m好.", " 你好.", 6, 6},
3636
{"flag", "🇸🇦", "🇸🇦", 2, 1},
37+
{"half width and ascii", "(゚", "(゚", 1, 1},
3738
}
3839

3940
func TestStrip(t *testing.T) {

0 commit comments

Comments
 (0)