Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Commit

Permalink
Fix bug when runes with width > 1 in an option with multiple lines (#445
Browse files Browse the repository at this point in the history
)

* Fix bug when runes with width > 1 in an option with multiple lines

* add test

Co-authored-by: Alec Aivazis <alec@aivazis.com>
  • Loading branch information
VCisHere and AlecAivazis authored Sep 22, 2022
1 parent d889203 commit 3f9140e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
5 changes: 2 additions & 3 deletions renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package survey
import (
"bytes"
"fmt"
"unicode/utf8"

"github.com/AlecAivazis/survey/v2/core"
"github.com/AlecAivazis/survey/v2/terminal"
"golang.org/x/term"
Expand Down Expand Up @@ -180,7 +178,8 @@ func (r *Renderer) countLines(buf bytes.Buffer) int {
delim = len(bufBytes) // no new line found, read rest of text
}

if lineWidth := utf8.RuneCount(bufBytes[curr:delim]); lineWidth > w {
str := string(bufBytes[curr:delim])
if lineWidth := terminal.StringWidth(str); lineWidth > w {
// account for word wrapping
count += lineWidth / w
if (lineWidth % w) == 0 {
Expand Down
9 changes: 9 additions & 0 deletions terminal/runereader.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,3 +384,12 @@ func runeWidth(r rune) int {
}
return 1
}

func StringWidth(str string) int {
w := 0
rs := []rune(str)
for _, r := range rs {
w += runeWidth(r)
}
return w
}
4 changes: 3 additions & 1 deletion tests/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/tests/util"
TestUtil "github.com/AlecAivazis/survey/v2/tests/util"
)

var val = ""
Expand All @@ -23,6 +23,8 @@ var table = []TestUtil.TestTableEntry{
"Delete and forward delete test at random location (test if screen overflows)", &survey.Input{Message: "Hello world"}, &val, nil,
}, {
"Moving around lines with left & right arrow keys", &survey.Input{Message: "Hello world"}, &val, nil,
}, {
"Runes with width > 1. Enter 一 you get to the next line", &survey.Input{Message: "Hello world"}, &val, nil,
},
}

Expand Down

0 comments on commit 3f9140e

Please sign in to comment.