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) }