From a603d3de038ae75abddd33078a1c8c56614eaf0d Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Sat, 4 Mar 2023 01:37:18 +0100 Subject: table: fix center padding When a column has ALIGN_CENTER and the number of white space character of padding is not a multiple of two, the last cell(character) is not padded and that can cause coloring glitches. Make sure to pad all the way. Fixes: 49de9b09cacc ("ui: parse strings for ansi styles") Signed-off-by: Robin Jarry Acked-by: Tim Culverhouse --- lib/parse/ansi.go | 27 ++++++++++++++++++++++++--- lib/ui/table.go | 16 +++++----------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/lib/parse/ansi.go b/lib/parse/ansi.go index a9a46fdd..94f0c4fc 100644 --- a/lib/parse/ansi.go +++ b/lib/parse/ansi.go @@ -67,9 +67,30 @@ func (rb *RuneBuffer) Write(r rune, style tcell.Style) { } // Prepend inserts the rune at the beginning of the rune buffer -func (rb *RuneBuffer) Prepend(r rune, style tcell.Style) { - w := runewidth.RuneWidth(r) - rb.buf = append([]*StyledRune{{r, w, style}}, rb.buf...) +func (rb *RuneBuffer) PadLeft(width int, r rune, style tcell.Style) { + w := rb.Len() + if w >= width { + return + } + w = width - w + for w > 0 { + ww := runewidth.RuneWidth(r) + w -= ww + rb.buf = append([]*StyledRune{{r, ww, style}}, rb.buf...) + } +} + +func (rb *RuneBuffer) PadRight(width int, r rune, style tcell.Style) { + w := rb.Len() + if w >= width { + return + } + w = width - w + for w > 0 { + ww := runewidth.RuneWidth(r) + w -= ww + rb.buf = append(rb.buf, &StyledRune{r, ww, style}) + } } // String outputs a styled-string using TERM=xterm-256color diff --git a/lib/ui/table.go b/lib/ui/table.go index 704dd2be..9cb96bd9 100644 --- a/lib/ui/table.go +++ b/lib/ui/table.go @@ -166,29 +166,23 @@ func (col *Column) alignCell(cell string) string { switch { case col.Def.Flags.Has(config.ALIGN_LEFT): if width < col.Width { - for i := 0; i < (col.Width - width); i += 1 { - buf.Write(' ', tcell.StyleDefault) - } + buf.PadRight(col.Width, ' ', tcell.StyleDefault) cell = buf.String() } else if width > col.Width { cell = buf.Truncate(col.Width, '…') } case col.Def.Flags.Has(config.ALIGN_CENTER): if width < col.Width { - pad := (col.Width - width) / 2 - for i := 0; i < pad; i += 1 { - buf.Prepend(' ', tcell.StyleDefault) - buf.Write(' ', tcell.StyleDefault) - } + pad := col.Width - width + buf.PadLeft(col.Width-(pad/2), ' ', tcell.StyleDefault) + buf.PadRight(col.Width, ' ', tcell.StyleDefault) cell = buf.String() } else if width > col.Width { cell = buf.Truncate(col.Width, '…') } case col.Def.Flags.Has(config.ALIGN_RIGHT): if width < col.Width { - for i := 0; i < (col.Width - width); i += 1 { - buf.Prepend(' ', tcell.StyleDefault) - } + buf.PadLeft(col.Width, ' ', tcell.StyleDefault) cell = buf.String() } else if width > col.Width { cell = buf.TruncateHead(col.Width, '…') -- cgit v1.2.3-54-g00ecf