left_padded.go

 1package text
 2
 3import (
 4	"bytes"
 5	"fmt"
 6	"github.com/mattn/go-runewidth"
 7	"strings"
 8)
 9
10// Force runewidth not to treat ambiguous runes as wide chars, so that things
11// like unicode ellipsis/up/down/left/right glyphs can have correct runewidth
12// and can be displayed correctly in terminals.
13func init() {
14	runewidth.DefaultCondition.EastAsianWidth = false
15}
16
17// LeftPadMaxLine pads a string on the left by a specified amount and pads the
18// string on the right to fill the maxLength
19func LeftPadMaxLine(text string, length, leftPad int) string {
20	var rightPart string = text
21
22	scrWidth := runewidth.StringWidth(text)
23	// truncate and ellipse if needed
24	if scrWidth+leftPad > length {
25		rightPart = runewidth.Truncate(text, length-leftPad, "…")
26	} else if scrWidth+leftPad < length {
27		rightPart = runewidth.FillRight(text, length-leftPad)
28	}
29
30	return fmt.Sprintf("%s%s",
31		strings.Repeat(" ", leftPad),
32		rightPart,
33	)
34}
35
36// LeftPad left pad each line of the given text
37func LeftPad(text string, leftPad int) string {
38	var result bytes.Buffer
39
40	pad := strings.Repeat(" ", leftPad)
41
42	for _, line := range strings.Split(text, "\n") {
43		result.WriteString(pad)
44		result.WriteString(line)
45		result.WriteString("\n")
46	}
47
48	return result.String()
49}