Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor padding functions #254

Merged
merged 1 commit into from
Jan 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 28 additions & 24 deletions style.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 values add to the right side while negative values
// 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)
}
Expand All @@ -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')
}
Expand All @@ -525,3 +521,11 @@ func min(a, b int) int {
}
return b
}

func abs(a int) int {
if a < 0 {
return -a
}

return a
}
Loading