Debian Codegraph @

pkg/highlight/highlighter.go

raw
1 package highlight
2
3 import (
4 "regexp"
5 "strings"
6 )
7
8 func sliceStart(slc []byte, index int) []byte {
9 len := len(slc)
10 i := 0
11 totalSize := 0
12 for totalSize < len {
13 if i >= index {
14 return slc[totalSize:]
15 }
16
17 _, _, size := DecodeCharacter(slc[totalSize:])
18 totalSize += size
19 i++
20 }
21
22 return slc[totalSize:]
23 }
24
25 func sliceEnd(slc []byte, index int) []byte {
26 len := len(slc)
27 i := 0
28 totalSize := 0
29 for totalSize < len {
30 if i >= index {
31 return slc[:totalSize]
32 }
33
34 _, _, size := DecodeCharacter(slc[totalSize:])
35 totalSize += size
36 i++
37 }
38
39 return slc[:totalSize]
40 }
41
42 // RunePos returns the rune index of a given byte index
43 // This could cause problems if the byte index is between code points
44 func runePos(p int, str []byte) int {
45 if p < 0 {
46 return 0
47 }
48 if p >= len(str) {
49 return CharacterCount(str)
50 }
51 return CharacterCount(str[:p])
52 }
53
54 // A State represents the region at the end of a line
55 type State *region
56
57 // LineStates is an interface for a buffer-like object which can also store the states and matches for every line
58 type LineStates interface {
59 LineBytes(n int) []byte
60 LinesNum() int
61 State(lineN int) State
62 SetState(lineN int, s State)
63 SetMatch(lineN int, m LineMatch)
64 Lock()
65 Unlock()
66 }
67
68 // A Highlighter contains the information needed to highlight a string
69 type Highlighter struct {
70 lastRegion *region
71 Def *Def
72 }
73
74 // NewHighlighter returns a new highlighter from the given syntax definition
75 func NewHighlighter(def *Def) *Highlighter {
76 h := new(Highlighter)
77 h.Def = def
78 return h
79 }
80
81 // LineMatch represents the syntax highlighting matches for one line. Each index where the coloring is changed is marked with that
82 // color's group (represented as one byte)
83 type LineMatch map[int]Group
84
85 func findIndex(regex *regexp.Regexp, skip *regexp.Regexp, str []byte) []int {
86 var strbytes []byte
87 if skip != nil {
88 strbytes = skip.ReplaceAllFunc(str, func(match []byte) []byte {
89 res := make([]byte, CharacterCount(match))
90 return res
91 })
92 } else {
93 strbytes = str
94 }
95
96 match := regex.FindIndex(strbytes)
97 if match == nil {
98 return nil
99 }
100 // return []int{match.Index, match.Index + match.Length}
101 return []int{runePos(match[0], str), runePos(match[1], str)}
102 }
103
104 func findAllIndex(regex *regexp.Regexp, str []byte) [][]int {
105 matches := regex.FindAllIndex(str, -1)
106 for i, m := range matches {
107 matches[i][0] = runePos(m[0], str)
108 matches[i][1] = runePos(m[1], str)
109 }
110 return matches
111 }
112
113 func (h *Highlighter) highlightRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, curRegion *region, statesOnly bool) LineMatch {
114 lineLen := CharacterCount(line)
115 if start == 0 {
116 if !statesOnly {
117 if _, ok := highlights[0]; !ok {
118 highlights[0] = curRegion.group
119 }
120 }
121 }
122
123 var firstRegion *region
124 firstLoc := []int{lineLen, 0}
125 searchNesting := true
126 endLoc := findIndex(curRegion.end, curRegion.skip, line)
127 if endLoc != nil {
128 if start == endLoc[0] {
129 searchNesting = false
130 } else {
131 firstLoc = endLoc
132 }
133 }
134 if searchNesting {
135 for _, r := range curRegion.rules.regions {
136 loc := findIndex(r.start, r.skip, line)
137 if loc != nil {
138 if loc[0] < firstLoc[0] {
139 firstLoc = loc
140 firstRegion = r
141 }
142 }
143 }
144 }
145 if firstRegion != nil && firstLoc[0] != lineLen {
146 if !statesOnly {
147 highlights[start+firstLoc[0]] = firstRegion.limitGroup
148 }
149 h.highlightEmptyRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), statesOnly)
150 h.highlightRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), firstRegion, statesOnly)
151 return highlights
152 }
153
154 if !statesOnly {
155 fullHighlights := make([]Group, lineLen)
156 for i := 0; i < len(fullHighlights); i++ {
157 fullHighlights[i] = curRegion.group
158 }
159
160 if searchNesting {
161 for _, p := range curRegion.rules.patterns {
162 if curRegion.group == curRegion.limitGroup || p.group == curRegion.limitGroup {
163 matches := findAllIndex(p.regex, line)
164 for _, m := range matches {
165 if (endLoc == nil) || (m[0] < endLoc[0]) {
166 for i := m[0]; i < m[1]; i++ {
167 fullHighlights[i] = p.group
168 }
169 }
170 }
171 }
172 }
173 }
174 for i, h := range fullHighlights {
175 if i == 0 || h != fullHighlights[i-1] {
176 highlights[start+i] = h
177 }
178 }
179 }
180
181 loc := endLoc
182 if loc != nil {
183 if !statesOnly {
184 highlights[start+loc[0]] = curRegion.limitGroup
185 }
186 if curRegion.parent == nil {
187 if !statesOnly {
188 highlights[start+loc[1]] = 0
189 }
190 h.highlightEmptyRegion(highlights, start+loc[1], canMatchEnd, lineNum, sliceStart(line, loc[1]), statesOnly)
191 return highlights
192 }
193 if !statesOnly {
194 highlights[start+loc[1]] = curRegion.parent.group
195 }
196 h.highlightRegion(highlights, start+loc[1], canMatchEnd, lineNum, sliceStart(line, loc[1]), curRegion.parent, statesOnly)
197 return highlights
198 }
199
200 if canMatchEnd {
201 h.lastRegion = curRegion
202 }
203
204 return highlights
205 }
206
207 func (h *Highlighter) highlightEmptyRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, statesOnly bool) LineMatch {
208 lineLen := CharacterCount(line)
209 if lineLen == 0 {
210 if canMatchEnd {
211 h.lastRegion = nil
212 }
213 return highlights
214 }
215
216 var firstRegion *region
217 firstLoc := []int{lineLen, 0}
218 for _, r := range h.Def.rules.regions {
219 loc := findIndex(r.start, r.skip, line)
220 if loc != nil {
221 if loc[0] < firstLoc[0] {
222 firstLoc = loc
223 firstRegion = r
224 }
225 }
226 }
227 if firstRegion != nil && firstLoc[0] != lineLen {
228 if !statesOnly {
229 highlights[start+firstLoc[0]] = firstRegion.limitGroup
230 }
231 h.highlightEmptyRegion(highlights, start, false, lineNum, sliceEnd(line, firstLoc[0]), statesOnly)
232 h.highlightRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), firstRegion, statesOnly)
233 return highlights
234 }
235
236 if statesOnly {
237 if canMatchEnd {
238 h.lastRegion = nil
239 }
240
241 return highlights
242 }
243
244 fullHighlights := make([]Group, len(line))
245 for _, p := range h.Def.rules.patterns {
246 matches := findAllIndex(p.regex, line)
247 for _, m := range matches {
248 for i := m[0]; i < m[1]; i++ {
249 fullHighlights[i] = p.group
250 }
251 }
252 }
253 for i, h := range fullHighlights {
254 if i == 0 || h != fullHighlights[i-1] {
255 // if _, ok := highlights[start+i]; !ok {
256 highlights[start+i] = h
257 // }
258 }
259 }
260
261 if canMatchEnd {
262 h.lastRegion = nil
263 }
264
265 return highlights
266 }
267
268 // HighlightString syntax highlights a string
269 // Use this function for simple syntax highlighting and use the other functions for
270 // more advanced syntax highlighting. They are optimized for quick rehighlighting of the same
271 // text with minor changes made
272 func (h *Highlighter) HighlightString(input string) []LineMatch {
273 lines := strings.Split(input, "\n")
274 var lineMatches []LineMatch
275
276 for i := 0; i < len(lines); i++ {
277 line := []byte(lines[i])
278 highlights := make(LineMatch)
279
280 if i == 0 || h.lastRegion == nil {
281 lineMatches = append(lineMatches, h.highlightEmptyRegion(highlights, 0, true, i, line, false))
282 } else {
283 lineMatches = append(lineMatches, h.highlightRegion(highlights, 0, true, i, line, h.lastRegion, false))
284 }
285 }
286
287 return lineMatches
288 }
289
290 // HighlightStates correctly sets all states for the buffer
291 func (h *Highlighter) HighlightStates(input LineStates) {
292 for i := 0; ; i++ {
293 input.Lock()
294 if i >= input.LinesNum() {
295 input.Unlock()
296 break
297 }
298
299 line := input.LineBytes(i)
300 // highlights := make(LineMatch)
301
302 if i == 0 || h.lastRegion == nil {
303 h.highlightEmptyRegion(nil, 0, true, i, line, true)
304 } else {
305 h.highlightRegion(nil, 0, true, i, line, h.lastRegion, true)
306 }
307
308 curState := h.lastRegion
309
310 input.SetState(i, curState)
311 input.Unlock()
312 }
313 }
314
315 // HighlightMatches sets the matches for each line from startline to endline
316 // It sets all other matches in the buffer to nil to conserve memory
317 // This assumes that all the states are set correctly
318 func (h *Highlighter) HighlightMatches(input LineStates, startline, endline int) {
319 for i := startline; i <= endline; i++ {
320 input.Lock()
321 if i >= input.LinesNum() {
322 input.Unlock()
323 break
324 }
325
326 line := input.LineBytes(i)
327 highlights := make(LineMatch)
328
329 var match LineMatch
330 if i == 0 || input.State(i-1) == nil {
331 match = h.highlightEmptyRegion(highlights, 0, true, i, line, false)
332 } else {
333 match = h.highlightRegion(highlights, 0, true, i, line, input.State(i-1), false)
334 }
335
336 input.SetMatch(i, match)
337 input.Unlock()
338 }
339 }
340
341 // ReHighlightStates will scan down from `startline` and set the appropriate end of line state
342 // for each line until it comes across a line whose state does not change
343 // returns the number of the final line
344 func (h *Highlighter) ReHighlightStates(input LineStates, startline int) int {
345 // lines := input.LineData()
346
347 h.lastRegion = nil
348 if startline > 0 {
349 input.Lock()
350 if startline-1 < input.LinesNum() {
351 h.lastRegion = input.State(startline - 1)
352 }
353 input.Unlock()
354 }
355 for i := startline; ; i++ {
356 input.Lock()
357 if i >= input.LinesNum() {
358 input.Unlock()
359 break
360 }
361
362 line := input.LineBytes(i)
363 // highlights := make(LineMatch)
364
365 // var match LineMatch
366 if i == 0 || h.lastRegion == nil {
367 h.highlightEmptyRegion(nil, 0, true, i, line, true)
368 } else {
369 h.highlightRegion(nil, 0, true, i, line, h.lastRegion, true)
370 }
371 curState := h.lastRegion
372 lastState := input.State(i)
373
374 input.SetState(i, curState)
375 input.Unlock()
376
377 if curState == lastState {
378 return i
379 }
380 }
381
382 return input.LinesNum() - 1
383 }
384
385 // ReHighlightLine will rehighlight the state and match for a single line
386 func (h *Highlighter) ReHighlightLine(input LineStates, lineN int) {
387 input.Lock()
388 defer input.Unlock()
389
390 line := input.LineBytes(lineN)
391 highlights := make(LineMatch)
392
393 h.lastRegion = nil
394 if lineN > 0 {
395 h.lastRegion = input.State(lineN - 1)
396 }
397
398 var match LineMatch
399 if lineN == 0 || h.lastRegion == nil {
400 match = h.highlightEmptyRegion(highlights, 0, true, lineN, line, false)
401 } else {
402 match = h.highlightRegion(highlights, 0, true, lineN, line, h.lastRegion, false)
403 }
404 curState := h.lastRegion
405
406 input.SetMatch(lineN, match)
407 input.SetState(lineN, curState)
408 }