gunk-dev/the-valley

terminal.go

sourceee200607ca12main's published tip history
2.6 KiB
1package main
2
3import (
4 "io"
5 "os"
6 "strings"
7 "unicode"
8)
9
10// terminal is what valley pending's and valley plan's text is laid out
11// for: a width in columns, and whether text is styled, with names in bold
12// and plan's glyphs in colour.
13type terminal struct {
14 width int
15 bold bool
16}
17
18// terminalOf is the terminal w writes to. Its width is the terminal's
19// own, or 80 columns when w is no terminal or the terminal does not know
20// its width. Text is styled on a terminal, unless NO_COLOR is set to
21// anything but the empty string.
22func terminalOf(w io.Writer) terminal {
23 t := terminal{width: 80}
24 f, ok := w.(*os.File)
25 if !ok {
26 return t
27 }
28 cols, isTerminal := windowColumns(f)
29 if !isTerminal {
30 return t
31 }
32 if cols > 0 {
33 t.width = cols
34 }
35 t.bold = os.Getenv("NO_COLOR") == ""
36 return t
37}
38
39// strong is s in bold, on a terminal that shows it.
40func (t terminal) strong(s string) string {
41 if !t.bold {
42 return s
43 }
44 return "\x1b[1m" + s + "\x1b[0m"
45}
46
47// tint is s in the colour an SGR code names, on a terminal that shows
48// it. An empty code leaves s as it is.
49func (t terminal) tint(code, s string) string {
50 if !t.bold || code == "" {
51 return s
52 }
53 return "\x1b[" + code + "m" + s + "\x1b[0m"
54}
55
56// fit is s cut to the columns a line has left after lead.
57func (t terminal) fit(s, lead string) string {
58 return fit(s, t.width-columns(lead))
59}
60
61// fit is s cut to at most n columns, ending in … where it was cut.
62func fit(s string, n int) string {
63 if columns(s) <= n {
64 return s
65 }
66 var b strings.Builder
67 used := 0
68 for _, r := range s {
69 if used+runeColumns(r) > n-1 {
70 break
71 }
72 b.WriteRune(r)
73 used += runeColumns(r)
74 }
75 return strings.TrimRight(b.String(), " ") + "…"
76}
77
78// columns is how many columns a terminal gives s.
79func columns(s string) int {
80 n := 0
81 for _, r := range s {
82 n += runeColumns(r)
83 }
84 return n
85}
86
87// runeColumns is how many columns a terminal gives r: none for a mark that
88// combines with the character before it, two for a wide character, and
89// one for any other.
90func runeColumns(r rune) int {
91 if unicode.In(r, unicode.Mn, unicode.Me, unicode.Cf) {
92 return 0
93 }
94 for _, w := range wideRunes {
95 if r >= w[0] && r <= w[1] {
96 return 2
97 }
98 }
99 return 1
100}
101
102// wideRunes are the main blocks of East Asian wide and fullwidth
103// characters, and of emoji, which a terminal draws two columns wide.
104var wideRunes = [][2]rune{
105 {0x1100, 0x115f}, {0x2e80, 0x303e}, {0x3041, 0x33ff}, {0x3400, 0x4dbf},
106 {0x4e00, 0x9fff}, {0xa000, 0xa4cf}, {0xac00, 0xd7a3}, {0xf900, 0xfaff},
107 {0xfe30, 0xfe4f}, {0xff00, 0xff60}, {0xffe0, 0xffe6}, {0x1f300, 0x1f64f},
108 {0x1f900, 0x1f9ff}, {0x20000, 0x3fffd},
109}