diff --git a/pkg/table/align/align.go b/pkg/table/align/align.go index 4dbe471..5e0c97d 100644 --- a/pkg/table/align/align.go +++ b/pkg/table/align/align.go @@ -3,35 +3,44 @@ package align import ( "fmt" "strings" + "unicode/utf8" + + "github.com/acarl005/stripansi" ) // AlignLeft align left -func AlignLeft(s string, n int) string { - if len(s) > n { +func AlignLeft(t string, n int) string { + s := stripansi.Strip(t) + slen := utf8.RuneCountInString(s) + if slen > n { return s[:n] } - return fmt.Sprintf("%s%s", s, strings.Repeat(" ", n-len(s))) + return fmt.Sprintf("%s%s", t, strings.Repeat(" ", n-slen)) } // AlignRight align right -func AlignRight(s string, n int) string { - if len(s) > n { +func AlignRight(t string, n int) string { + s := stripansi.Strip(t) + slen := utf8.RuneCountInString(s) + if slen > n { return s[:n] } - return fmt.Sprintf("%s%s", strings.Repeat(" ", n-len(s)), s) + return fmt.Sprintf("%s%s", strings.Repeat(" ", n-slen), t) } // AlignCenter align center -func AlignCenter(s string, n int) string { - if len(s) > n { +func AlignCenter(t string, n int) string { + s := stripansi.Strip(t) + slen := utf8.RuneCountInString(s) + if slen > n { return s[:n] } - pad := (n - len(s)) / 2 + pad := (n - slen) / 2 lpad := pad - rpad := n - len(s) - lpad + rpad := n - slen - lpad - return fmt.Sprintf("%s%s%s", strings.Repeat(" ", lpad), s, strings.Repeat(" ", rpad)) + return fmt.Sprintf("%s%s%s", strings.Repeat(" ", lpad), t, strings.Repeat(" ", rpad)) } diff --git a/pkg/table/table.go b/pkg/table/table.go index 9bad7e0..0b42c06 100644 --- a/pkg/table/table.go +++ b/pkg/table/table.go @@ -5,7 +5,9 @@ import ( "io" "sort" "strings" + "unicode/utf8" + "github.com/acarl005/stripansi" "github.com/miguelmota/cointop/pkg/pad" "github.com/miguelmota/cointop/pkg/table/align" ) @@ -129,7 +131,8 @@ func (t *Table) normalizeColWidthPerc() { // Format format table func (t *Table) Format() *Table { for _, c := range t.cols { - c.width = len(c.name) + 1 + s := stripansi.Strip(c.name) + c.width = utf8.RuneCountInString(s) + 1 if c.minWidth > c.width { c.width = c.minWidth } @@ -151,8 +154,10 @@ func (t *Table) Format() *Table { r.strValues[j] = fmt.Sprintf("%v", v) } - if len(r.strValues[j]) > t.cols[j].width { - t.cols[j].width = len(r.strValues[j]) + s := stripansi.Strip(r.strValues[j]) + runeCount := utf8.RuneCountInString(s) + if runeCount > t.cols[j].width { + t.cols[j].width = runeCount } } }