Ignore ANSI escape codes when when determining string length

to calculate width and padding for table alignment.
pull/118/head
Alexis Hildebrandt 3 years ago
parent 58c5403c7e
commit 5933f22020

@ -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))
}

@ -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
}
}
}

Loading…
Cancel
Save