Skip to content

Commit 6d1f3b0

Browse files
committed
fix: incorrect table padding for strings with multiple special characters
1 parent 83feb20 commit 6d1f3b0

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

internal/ux/table.go

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package ux
22

3-
import "strings"
3+
import (
4+
"strings"
5+
"unicode/utf8"
6+
)
47

58
type Table struct {
69
Header []string
@@ -55,19 +58,22 @@ func (t *Table) calculateColumnWidths() map[int]int {
5558
// calculate the longest string in each column
5659
for i, row := range t.Rows {
5760
for j, cell := range row {
58-
if len(cell) > colWidths[j] {
59-
colWidths[j] = len(cell)
61+
cellWidth := utf8.RuneCountInString(cell)
62+
if cellWidth > colWidths[j] {
63+
colWidths[j] = cellWidth
6064
}
6165

62-
if len(t.Header[j]) > colWidths[j] {
63-
colWidths[j] = len(t.Header[j])
66+
headerWidth := utf8.RuneCountInString(t.Header[j])
67+
if headerWidth > colWidths[j] {
68+
colWidths[j] = headerWidth
6469
}
6570
}
6671

6772
if i == 0 {
6873
for j, header := range t.Header {
69-
if len(header) > colWidths[j] {
70-
colWidths[j] = len(header)
74+
headerWidth := utf8.RuneCountInString(header)
75+
if headerWidth > colWidths[j] {
76+
colWidths[j] = headerWidth
7177
}
7278
}
7379
}
@@ -85,15 +91,17 @@ func (t *Table) String() string {
8591
// print padded cells
8692
for i, header := range t.Header {
8793
s += header + " "
88-
s += strings.Repeat(" ", longestInCol[i]-len(header)) + "\t"
94+
headerWidth := utf8.RuneCountInString(header)
95+
s += strings.Repeat(" ", longestInCol[i]-headerWidth) + "\t"
8996
}
9097

9198
s += "\n"
9299

93100
for _, row := range t.Rows {
94101
for i, cell := range row {
95102
s += cell + " "
96-
s += strings.Repeat(" ", longestInCol[i]-len(cell)) + "\t"
103+
cellWidth := utf8.RuneCountInString(cell)
104+
s += strings.Repeat(" ", longestInCol[i]-cellWidth) + "\t"
97105
}
98106

99107
s += "\n"

0 commit comments

Comments
 (0)