aboutsummaryrefslogtreecommitdiffstats
path: root/util/text/left_padded.go
blob: 43e84966bdedc580087a8b17316e3ba07356db14 (plain) (blame)
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
package text

import (
	"bytes"
	"fmt"
	"github.com/mattn/go-runewidth"
	"strings"
)

// Force runewidth not to treat ambiguous runes as wide chars, so that things
// like unicode ellipsis/up/down/left/right glyphs can have correct runewidth
// and can be displayed correctly in terminals.
func init() {
	runewidth.DefaultCondition.EastAsianWidth = false
}

// LeftPadMaxLine pads a string on the left by a specified amount and pads the
// string on the right to fill the maxLength
func LeftPadMaxLine(text string, length, leftPad int) string {
	var rightPart string = text

	scrWidth := runewidth.StringWidth(text)
	// truncate and ellipse if needed
	if scrWidth+leftPad > length {
		rightPart = runewidth.Truncate(text, length-leftPad, "…")
	} else if scrWidth+leftPad < length {
		rightPart = runewidth.FillRight(text, length-leftPad)
	}

	return fmt.Sprintf("%s%s",
		strings.Repeat(" ", leftPad),
		rightPart,
	)
}

// LeftPad left pad each line of the given text
func LeftPad(text string, leftPad int) string {
	var result bytes.Buffer

	pad := strings.Repeat(" ", leftPad)

	for _, line := range strings.Split(text, "\n") {
		result.WriteString(pad)
		result.WriteString(line)
		result.WriteString("\n")
	}

	return result.String()
}