diff --git a/style.go b/style.go index ad96f79c..b061c4b6 100644 --- a/style.go +++ b/style.go @@ -464,36 +464,23 @@ 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) +} + +// pad adds padding to either the left or right side of a string. +// Positive numbers add to the right side while negative numbers +// add to the left side. +func pad(str string, n int, style *termenv.Style) string { if n == 0 { return str } - sp := strings.Repeat(" ", n) + sp := strings.Repeat(" ", abs(n)) if style != nil { sp = style.Styled(sp) } @@ -502,8 +489,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 +521,11 @@ func min(a, b int) int { } return b } + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +}