forked from k0kubun/pp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
color.go
129 lines (114 loc) · 2.56 KB
/
color.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package pp
import (
"fmt"
"reflect"
)
const (
// No color
NoColor uint16 = 1 << 15
)
const (
// Foreground colors for ColorScheme.
_ uint16 = iota | NoColor
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White
bitsForeground = 0
maskForeground = 0xf
ansiForegroundOffset = 30 - 1
)
const (
// Background colors for ColorScheme.
_ uint16 = iota<<bitsBackground | NoColor
BackgroundBlack
BackgroundRed
BackgroundGreen
BackgroundYellow
BackgroundBlue
BackgroundMagenta
BackgroundCyan
BackgroundWhite
bitsBackground = 4
maskBackground = 0xf << bitsBackground
ansiBackgroundOffset = 40 - 1
)
const (
// Bold flag for ColorScheme.
Bold uint16 = 1<<bitsBold | NoColor
bitsBold = 8
maskBold = 1 << bitsBold
ansiBold = 1
)
// To use with SetColorScheme.
type ColorScheme struct {
Bool uint16
Integer uint16
Float uint16
String uint16
StringQuotation uint16
EscapedChar uint16
FieldName uint16
PointerAdress uint16
Nil uint16
Time uint16
StructName uint16
ObjectLength uint16
}
var (
// If you set false to this variable, you can use pretty formatter
// without coloring.
ColoringEnabled = true
defaultScheme = ColorScheme{
Bool: Cyan | Bold,
Integer: Blue | Bold,
Float: Magenta | Bold,
String: Red,
StringQuotation: Red | Bold,
EscapedChar: Magenta | Bold,
FieldName: Yellow,
PointerAdress: Blue | Bold,
Nil: Cyan | Bold,
Time: Blue | Bold,
StructName: Green,
ObjectLength: Blue,
}
)
func (cs *ColorScheme) fixColors() {
typ := reflect.Indirect(reflect.ValueOf(cs))
defaultType := reflect.ValueOf(defaultScheme)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.Uint() == 0 {
field.SetUint(defaultType.Field(i).Uint())
}
}
}
func colorize(text string, color uint16) string {
if !ColoringEnabled {
return text
}
foreground := color & maskForeground >> bitsForeground
background := color & maskBackground >> bitsBackground
bold := color & maskBold
if foreground == 0 && background == 0 && bold == 0 {
return text
}
modBold := ""
modForeground := ""
modBackground := ""
if bold > 0 {
modBold = "\033[1m"
}
if foreground > 0 {
modForeground = fmt.Sprintf("\033[%dm", foreground+ansiForegroundOffset)
}
if background > 0 {
modBackground = fmt.Sprintf("\033[%dm", background+ansiBackgroundOffset)
}
return fmt.Sprintf("%s%s%s%s\033[0m", modForeground, modBackground, modBold, text)
}