blob: ae7a364aed7c3a53333ce132203484dccf3b31bd [file] [log] [blame]
Anand S Katti09541352020-01-29 15:54:01 +05301package tablewriter
2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7)
8
9const ESC = "\033"
10const SEP = ";"
11
12const (
13 BgBlackColor int = iota + 40
14 BgRedColor
15 BgGreenColor
16 BgYellowColor
17 BgBlueColor
18 BgMagentaColor
19 BgCyanColor
20 BgWhiteColor
21)
22
23const (
24 FgBlackColor int = iota + 30
25 FgRedColor
26 FgGreenColor
27 FgYellowColor
28 FgBlueColor
29 FgMagentaColor
30 FgCyanColor
31 FgWhiteColor
32)
33
34const (
35 BgHiBlackColor int = iota + 100
36 BgHiRedColor
37 BgHiGreenColor
38 BgHiYellowColor
39 BgHiBlueColor
40 BgHiMagentaColor
41 BgHiCyanColor
42 BgHiWhiteColor
43)
44
45const (
46 FgHiBlackColor int = iota + 90
47 FgHiRedColor
48 FgHiGreenColor
49 FgHiYellowColor
50 FgHiBlueColor
51 FgHiMagentaColor
52 FgHiCyanColor
53 FgHiWhiteColor
54)
55
56const (
57 Normal = 0
58 Bold = 1
59 UnderlineSingle = 4
60 Italic
61)
62
63type Colors []int
64
65func startFormat(seq string) string {
66 return fmt.Sprintf("%s[%sm", ESC, seq)
67}
68
69func stopFormat() string {
70 return fmt.Sprintf("%s[%dm", ESC, Normal)
71}
72
73// Making the SGR (Select Graphic Rendition) sequence.
74func makeSequence(codes []int) string {
75 codesInString := []string{}
76 for _, code := range codes {
77 codesInString = append(codesInString, strconv.Itoa(code))
78 }
79 return strings.Join(codesInString, SEP)
80}
81
82// Adding ANSI escape sequences before and after string
83func format(s string, codes interface{}) string {
84 var seq string
85
86 switch v := codes.(type) {
87
88 case string:
89 seq = v
90 case []int:
91 seq = makeSequence(v)
92 case Colors:
93 seq = makeSequence(v)
94 default:
95 return s
96 }
97
98 if len(seq) == 0 {
99 return s
100 }
101 return startFormat(seq) + s + stopFormat()
102}
103
104// Adding header colors (ANSI codes)
105func (t *Table) SetHeaderColor(colors ...Colors) {
106 if t.colSize != len(colors) {
107 panic("Number of header colors must be equal to number of headers.")
108 }
109 for i := 0; i < len(colors); i++ {
110 t.headerParams = append(t.headerParams, makeSequence(colors[i]))
111 }
112}
113
114// Adding column colors (ANSI codes)
115func (t *Table) SetColumnColor(colors ...Colors) {
116 if t.colSize != len(colors) {
117 panic("Number of column colors must be equal to number of headers.")
118 }
119 for i := 0; i < len(colors); i++ {
120 t.columnsParams = append(t.columnsParams, makeSequence(colors[i]))
121 }
122}
123
124// Adding column colors (ANSI codes)
125func (t *Table) SetFooterColor(colors ...Colors) {
126 if len(t.footers) != len(colors) {
127 panic("Number of footer colors must be equal to number of footer.")
128 }
129 for i := 0; i < len(colors); i++ {
130 t.footerParams = append(t.footerParams, makeSequence(colors[i]))
131 }
132}
133
134func Color(colors ...int) []int {
135 return colors
136}