left_padded.go

 1package text
 2
 3import (
 4	"bytes"
 5	"strings"
 6	"unicode/utf8"
 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(value string, maxValueLength, leftPad int) string {
11	valueLength := utf8.RuneCountInString(value)
12	if maxValueLength-leftPad >= valueLength {
13		return strings.Repeat(" ", leftPad) + value + strings.Repeat(" ", maxValueLength-valueLength-leftPad)
14	} else if maxValueLength-leftPad < valueLength {
15		tmp := strings.Trim(value[0:maxValueLength-leftPad-3], " ") + "..."
16		tmpLength := utf8.RuneCountInString(tmp)
17		return strings.Repeat(" ", leftPad) + tmp + strings.Repeat(" ", maxValueLength-tmpLength-leftPad)
18	}
19
20	return value
21}
22
23// LeftPad left pad each line of the given text
24func LeftPad(text string, leftPad int) string {
25	var result bytes.Buffer
26
27	pad := strings.Repeat(" ", leftPad)
28
29	for _, line := range strings.Split(text, "\n") {
30		result.WriteString(pad)
31		result.WriteString(line)
32		result.WriteString("\n")
33	}
34
35	return result.String()
36}