left_padded.go

 1package text
 2
 3import (
 4	"bytes"
 5	"fmt"
 6	"strings"
 7)
 8
 9// LeftPadMaxLine pads a string on the left by a specified amount and pads the string on the right to fill the maxLength
10func LeftPadMaxLine(text string, length, leftPad int) string {
11	runes := []rune(text)
12
13	// truncate and ellipse if needed
14	if len(runes)+leftPad > length {
15		runes = append(runes[:(length-leftPad-1)], '…')
16	}
17
18	if len(runes)+leftPad < length {
19		runes = append(runes, []rune(strings.Repeat(" ", length-len(runes)-leftPad))...)
20	}
21
22	return fmt.Sprintf("%s%s",
23		strings.Repeat(" ", leftPad),
24		string(runes),
25	)
26}
27
28// LeftPad left pad each line of the given text
29func LeftPad(text string, leftPad int) string {
30	var result bytes.Buffer
31
32	pad := strings.Repeat(" ", leftPad)
33
34	for _, line := range strings.Split(text, "\n") {
35		result.WriteString(pad)
36		result.WriteString(line)
37		result.WriteString("\n")
38	}
39
40	return result.String()
41}