-
Notifications
You must be signed in to change notification settings - Fork 0
/
matches.go
52 lines (43 loc) · 1.11 KB
/
matches.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
package flare
import (
"sort"
)
// Matches is a structure that stores highlighting results corresponding to a
// certain range of the document. It supports querying the highlight group of
// any index within the range.
type Matches struct {
tokens []token
last int
start, end int
}
func (m *Matches) add(idx int, group string) {
m.tokens = append(m.tokens, token{
idx: idx,
group: group,
})
}
// InRange returns true if the given offset is in this Matches structure.
func (m *Matches) InRange(p int) bool {
return p >= m.start && p < m.end
}
// Group returns the highlighting group at the specified index.
func (m *Matches) Group(idx int) string {
if !m.InRange(idx) {
return ""
}
if m.last >= 0 && m.last < len(m.tokens) {
if idx >= m.tokens[m.last].idx && m.last >= len(m.tokens)-1 {
return m.tokens[m.last].group
}
if idx >= m.tokens[m.last].idx && idx < m.tokens[m.last+1].idx {
return m.tokens[m.last].group
}
}
i := sort.Search(len(m.tokens), func(i int) bool { return m.tokens[i].idx > idx })
m.last = i - 1
return m.tokens[i-1].group
}
type token struct {
idx int
group string
}