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