1package text
2
3import (
4 "strings"
5)
6
7type Alignment int
8
9const (
10 NoAlign Alignment = iota
11 AlignLeft
12 AlignCenter
13 AlignRight
14)
15
16// LineAlign align the given line as asked and apply the needed padding to match the given
17// lineWidth, while ignoring the terminal escape sequences.
18// If the given lineWidth is too small to fit the given line, it's returned without
19// padding, overflowing lineWidth.
20func LineAlign(line string, lineWidth int, align Alignment) string {
21 switch align {
22 case NoAlign:
23 return line
24 case AlignLeft:
25 return LineAlignLeft(line, lineWidth)
26 case AlignCenter:
27 return LineAlignCenter(line, lineWidth)
28 case AlignRight:
29 return LineAlignRight(line, lineWidth)
30 }
31 panic("unknown alignment")
32}
33
34// LineAlignLeft align the given line on the left while ignoring the terminal escape sequences.
35// If the given lineWidth is too small to fit the given line, it's returned without
36// padding, overflowing lineWidth.
37func LineAlignLeft(line string, lineWidth int) string {
38 return TrimSpace(line)
39}
40
41// LineAlignCenter align the given line on the center and apply the needed left
42// padding, while ignoring the terminal escape sequences.
43// If the given lineWidth is too small to fit the given line, it's returned without
44// padding, overflowing lineWidth.
45func LineAlignCenter(line string, lineWidth int) string {
46 trimmed := TrimSpace(line)
47 totalPadLen := lineWidth - Len(trimmed)
48 if totalPadLen < 0 {
49 totalPadLen = 0
50 }
51 pad := strings.Repeat(" ", totalPadLen/2)
52 return pad + trimmed
53}
54
55// LineAlignRight align the given line on the right and apply the needed left
56// padding to match the given lineWidth, while ignoring the terminal escape sequences.
57// If the given lineWidth is too small to fit the given line, it's returned without
58// padding, overflowing lineWidth.
59func LineAlignRight(line string, lineWidth int) string {
60 trimmed := TrimSpace(line)
61 padLen := lineWidth - Len(trimmed)
62 if padLen < 0 {
63 padLen = 0
64 }
65 pad := strings.Repeat(" ", padLen)
66 return pad + trimmed
67}