1package text
2
3import (
4 "bytes"
5 "strings"
6
7 "github.com/mattn/go-runewidth"
8)
9
10// LeftPadMaxLine pads a line on the left by a specified amount and pads the
11// string on the right to fill the maxLength.
12// If the given string is too long, it is truncated with an ellipsis.
13// Handle properly terminal color escape code
14func LeftPadMaxLine(line string, length, leftPad int) string {
15 cleaned, escapes := ExtractTermEscapes(line)
16
17 scrWidth := runewidth.StringWidth(cleaned)
18 // truncate and ellipse if needed
19 if scrWidth+leftPad > length {
20 cleaned = runewidth.Truncate(cleaned, length-leftPad, "…")
21 } else if scrWidth+leftPad < length {
22 cleaned = runewidth.FillRight(cleaned, length-leftPad)
23 }
24
25 rightPart := ApplyTermEscapes(cleaned, escapes)
26 pad := strings.Repeat(" ", leftPad)
27
28 return pad + rightPart
29}
30
31// LeftPad left pad each line of the given text
32func LeftPadLines(text string, leftPad int) string {
33 var result bytes.Buffer
34
35 pad := strings.Repeat(" ", leftPad)
36
37 lines := strings.Split(text, "\n")
38
39 for i, line := range lines {
40 result.WriteString(pad)
41 result.WriteString(line)
42
43 // no additional line break at the end
44 if i < len(lines)-1 {
45 result.WriteString("\n")
46 }
47 }
48
49 return result.String()
50}