-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmkcolor.go
94 lines (80 loc) · 2.01 KB
/
mkcolor.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
package readline
import (
"io"
"unicode/utf8"
)
type Highlight struct {
Pattern interface{ FindAllStringIndex(string, int) [][]int }
Sequence string
}
type escapeSequenceId uint
var (
escapeSequences = []string{}
escapeSequenceStringToId = map[string]escapeSequenceId{}
)
func newEscapeSequenceId(s string) escapeSequenceId {
if code, ok := escapeSequenceStringToId[s]; ok {
return code
}
code := escapeSequenceId(len(escapeSequences))
escapeSequences = append(escapeSequences, s)
escapeSequenceStringToId[s] = code
return code
}
func (e escapeSequenceId) WriteTo(w io.Writer) (int64, error) {
n, err := io.WriteString(w, escapeSequences[e])
return int64(n), err
}
func (e escapeSequenceId) Equals(other colorInterface) bool {
o, ok := other.(escapeSequenceId)
return ok && o == e
}
type highlightColorSequence struct {
colorMap []escapeSequenceId
index int
resetSeq escapeSequenceId
}
func highlightToColoring(input string, resetColor, defaultColor string, H []Highlight) *highlightColorSequence {
colorMap := make([]escapeSequenceId, len(input))
defaultSeq := newEscapeSequenceId(defaultColor)
for i := 0; i < len(input); i++ {
colorMap[i] = defaultSeq
}
for _, h := range H {
positions := h.Pattern.FindAllStringIndex(input, -1)
if positions == nil {
continue
}
seq := newEscapeSequenceId(h.Sequence)
for _, p := range positions {
for i := p[0]; i < p[1]; i++ {
colorMap[i] = seq
}
}
}
return &highlightColorSequence{
colorMap: colorMap,
resetSeq: newEscapeSequenceId(resetColor),
}
}
func (H *highlightColorSequence) Init() colorInterface {
H.index = 0
return H.resetSeq
}
func (H *highlightColorSequence) Next(r rune) colorInterface {
if r == CursorPositionDummyRune {
return newEscapeSequenceId("")
}
rv := H.colorMap[H.index]
H.index += utf8.RuneLen(r)
return rv
}
type colorBridge struct {
base Coloring
}
func (c *colorBridge) Init() colorInterface {
return c.base.Init()
}
func (c *colorBridge) Next(r rune) colorInterface {
return c.base.Next(r)
}