Skip to content

Commit

Permalink
Fix the display width when mixes cjk and english string.
Browse files Browse the repository at this point in the history
  • Loading branch information
yasukotelin committed Nov 20, 2019
1 parent b482109 commit 24cab3b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 35 deletions.
35 changes: 2 additions & 33 deletions tabwriter.go
Expand Up @@ -14,9 +14,8 @@ package tabwriter
import (
"bytes"
"io"
"unicode/utf8"

"golang.org/x/text/width"
"github.com/mattn/go-runewidth"
)

// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -385,39 +384,9 @@ func (b *Writer) append(text []byte) {
b.cell.size += len(text)
}

func kindWidth(k width.Kind) int {
switch k {
case width.EastAsianAmbiguous:
return 1
case width.EastAsianWide:
return 2
case width.EastAsianFullwidth:
return 2
}
return 1
}

// calculate display width
// CJK word covers 2 columes
func (b *Writer) displayWidth(words []byte) (dw int) {
for i := 0; i < len(words); {
p, s := width.Lookup(words)
if s <= 0 {
return
}
dw += kindWidth(p.Kind())
i += s
}
return
}

// Update the cell width.
func (b *Writer) updateWidth() {
displayWidth := b.displayWidth(b.buf.Bytes()[b.pos:b.buf.Len()])
if displayWidth == 0 {
displayWidth = utf8.RuneCount(b.buf.Bytes()[b.pos:b.buf.Len()])

}
displayWidth := runewidth.StringWidth(string(b.buf.Bytes()[b.pos:b.buf.Len()]))
b.cell.width += displayWidth
b.pos = b.buf.Len()
}
Expand Down
24 changes: 22 additions & 2 deletions tabwriter_test.go
Expand Up @@ -376,8 +376,8 @@ var tests = []struct {
"aaa\tèèèè\t\n",

" a è c\n" +
" aa èèè cccc ddddd\n" +
" aaa èèèè\n",
" aa èèè cccc ddddd\n" +
" aaa èèèè\n",
},

{
Expand Down Expand Up @@ -607,6 +607,26 @@ var tests = []struct {
"a\t|b\t|c\t|d\n" +
"a\t|b\t|c\t|d\t|e\n",
},

{
"17a",
1, 0, 4, '.', 0,
"一二三abc\tb\tc\n" +
"hello\tb\tc",

"一二三abc....b....c\n" +
"hello........b....c",
},

{
"17b",
1, 0, 4, '.', 0,
"123abc\tb\tc\n" +
"hello\tb\tc",

"123abc....b....c\n" +
"hello.....b....c",
},
}

func Test(t *testing.T) {
Expand Down

0 comments on commit 24cab3b

Please sign in to comment.