diff --git a/style.go b/style.go index 72be9ef3..380d2e00 100644 --- a/style.go +++ b/style.go @@ -464,36 +464,20 @@ func (s Style) applyMargins(str string, inline bool) string { // Apply left padding. func padLeft(str string, n int, style *termenv.Style) string { - if n == 0 { - return str - } - - sp := strings.Repeat(" ", n) - if style != nil { - sp = style.Styled(sp) - } - - b := strings.Builder{} - l := strings.Split(str, "\n") - - for i := range l { - b.WriteString(sp) - b.WriteString(l[i]) - if i != len(l)-1 { - b.WriteRune('\n') - } - } - - return b.String() + return pad(str, -n, style) } // Apply right padding. func padRight(str string, n int, style *termenv.Style) string { + return pad(str, n, style) +} + +func pad(str string, n int, style *termenv.Style) string { if n == 0 || str == "" { return str } - sp := strings.Repeat(" ", n) + sp := strings.Repeat(" ", abs(n)) if style != nil { sp = style.Styled(sp) } @@ -502,8 +486,17 @@ func padRight(str string, n int, style *termenv.Style) string { l := strings.Split(str, "\n") for i := range l { - b.WriteString(l[i]) - b.WriteString(sp) + switch { + // pad right + case n > 0: + b.WriteString(l[i]) + b.WriteString(sp) + // pad left + default: + b.WriteString(sp) + b.WriteString(l[i]) + } + if i != len(l)-1 { b.WriteRune('\n') } @@ -525,3 +518,11 @@ func min(a, b int) int { } return b } + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +}