...
1 package text
2
3 import (
4 "fmt"
5 "sort"
6 "strconv"
7 "strings"
8 "sync"
9 )
10
11 var (
12 colorsEnabled = areANSICodesSupported()
13 )
14
15
16 func DisableColors() {
17 colorsEnabled = false
18 }
19
20
21 func EnableColors() {
22 colorsEnabled = true
23 }
24
25
26
27
28
29
30
31
32
33
34 type Color int
35
36
37 const (
38 Reset Color = iota
39 Bold
40 Faint
41 Italic
42 Underline
43 BlinkSlow
44 BlinkRapid
45 ReverseVideo
46 Concealed
47 CrossedOut
48 )
49
50
51 const (
52 FgBlack Color = iota + 30
53 FgRed
54 FgGreen
55 FgYellow
56 FgBlue
57 FgMagenta
58 FgCyan
59 FgWhite
60 )
61
62
63 const (
64 FgHiBlack Color = iota + 90
65 FgHiRed
66 FgHiGreen
67 FgHiYellow
68 FgHiBlue
69 FgHiMagenta
70 FgHiCyan
71 FgHiWhite
72 )
73
74
75 const (
76 BgBlack Color = iota + 40
77 BgRed
78 BgGreen
79 BgYellow
80 BgBlue
81 BgMagenta
82 BgCyan
83 BgWhite
84 )
85
86
87 const (
88 BgHiBlack Color = iota + 100
89 BgHiRed
90 BgHiGreen
91 BgHiYellow
92 BgHiBlue
93 BgHiMagenta
94 BgHiCyan
95 BgHiWhite
96 )
97
98
99 func (c Color) EscapeSeq() string {
100 return EscapeStart + strconv.Itoa(int(c)) + EscapeStop
101 }
102
103
104 func (c Color) HTMLProperty() string {
105 out := ""
106 if class, ok := colorCSSClassMap[c]; ok {
107 out = fmt.Sprintf("class=\"%s\"", class)
108 }
109 return out
110 }
111
112
113 func (c Color) Sprint(a ...interface{}) string {
114 return colorize(fmt.Sprint(a...), c.EscapeSeq())
115 }
116
117
118 func (c Color) Sprintf(format string, a ...interface{}) string {
119 return colorize(fmt.Sprintf(format, a...), c.EscapeSeq())
120 }
121
122
123
124 type Colors []Color
125
126 var (
127
128 colorsSeqMap = sync.Map{}
129 )
130
131
132 func (c Colors) EscapeSeq() string {
133 if len(c) == 0 {
134 return ""
135 }
136
137 colorsKey := fmt.Sprintf("%#v", c)
138 escapeSeq, ok := colorsSeqMap.Load(colorsKey)
139 if !ok || escapeSeq == "" {
140 colorNums := make([]string, len(c))
141 for idx, color := range c {
142 colorNums[idx] = strconv.Itoa(int(color))
143 }
144 escapeSeq = EscapeStart + strings.Join(colorNums, ";") + EscapeStop
145 colorsSeqMap.Store(colorsKey, escapeSeq)
146 }
147 return escapeSeq.(string)
148 }
149
150
151 func (c Colors) HTMLProperty() string {
152 if len(c) == 0 {
153 return ""
154 }
155
156 var classes []string
157 for _, color := range c {
158 if class, ok := colorCSSClassMap[color]; ok {
159 classes = append(classes, class)
160 }
161 }
162 if len(classes) > 1 {
163 sort.Strings(classes)
164 }
165 return fmt.Sprintf("class=\"%s\"", strings.Join(classes, " "))
166 }
167
168
169 func (c Colors) Sprint(a ...interface{}) string {
170 return colorize(fmt.Sprint(a...), c.EscapeSeq())
171 }
172
173
174 func (c Colors) Sprintf(format string, a ...interface{}) string {
175 return colorize(fmt.Sprintf(format, a...), c.EscapeSeq())
176 }
177
178 func colorize(s string, escapeSeq string) string {
179 if !colorsEnabled || escapeSeq == "" {
180 return s
181 }
182 return Escape(s, escapeSeq)
183 }
184
View as plain text