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
|
package syntax
// Cache holds the spans of one source text and re-scans it only when the text
// has actually changed.
//
// Scanning a file is cheap but not free, and the editor redraws far more often
// than the text changes — every cursor move, every scroll. The revision number
// the buffer hands out is what tells the two apart.
//
// cache.Update(buf.Text(), buf.Revision())
// for line := top; line < bottom; line++ {
// draw(line, cache.Line(line))
// }
type Cache struct {
language Language
scanned bool
revision int
lines [][]Span
}
// NewCache returns a cache that colours one language, or one that colours
// nothing for LanguageNone — which is what a file this package does not
// understand gets.
//
// cache := syntax.NewCache(syntax.LanguageOf(path))
func NewCache(language Language) *Cache {
return &Cache{language: language}
}
// Language returns the language this cache colours.
func (c *Cache) Language() Language { return c.language }
// Enabled reports whether this cache colours anything.
func (c *Cache) Enabled() bool { return c.language != LanguageNone }
// SetLanguage changes what is coloured, discarding what was scanned. Call it
// when the window's file changes, as Save As does.
func (c *Cache) SetLanguage(language Language) {
c.language = language
c.scanned = false
c.lines = nil
}
// Update re-scans src when revision differs from the one already scanned.
func (c *Cache) Update(src string, revision int) {
if !c.Enabled() {
return
}
if c.scanned && c.revision == revision {
return
}
c.lines = Highlight(c.language, src)
c.revision = revision
c.scanned = true
}
// Line returns the spans of line i from the last scan, or nil when there are
// none — an empty line, a line past the end, or colouring turned off.
func (c *Cache) Line(i int) []Span {
if i < 0 || i >= len(c.lines) {
return nil
}
return c.lines[i]
}
// LineCount returns how many lines the last scan covered.
func (c *Cache) LineCount() int { return len(c.lines) }
|