highlight 实验性
实验性
本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
import "github.com/tangoui/tango/ui/editor/highlight"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package highlight runs Monarch tokenization incrementally for the code editor view: the UI thread tokenizes what is about to be drawn within a time budget (Highlight), and a background goroutine (Start) catches up on the rest of the document from immutable buffer snapshots.
Storage. Every line keeps its end State (a uint32), so any line can be re-tokenized from the line above. Token slices are kept only in token windows of ±TokenWindow lines around the line each view most recently requested; outside them they are dropped and recomputed from the stored start state on demand. Each view of the document (a ViewKey; the methods without a key use DefaultView) has a window of its own, up to four, the least recently used evicted beyond that, so two views far apart in one document do not move one shared window back and forth every frame.
Invalidation. Edit maps each edit to lines of the old snapshot and the number of line breaks it inserts, shifts the per-line arrays accordingly and marks the edited lines dirty. Re-tokenizing always starts at the first dirty line, so its start state is final. After tokenizing a line, the next line is marked dirty unless the new end state equals the stored one. A Degraded line (monarch.LineInfo) never counts as "state unchanged": the next line is always re-tokenized, and the degraded line itself is retried after RetryDelay, up to MaxRetries times, before its result is accepted. Until then it and every line below it are not final.
Background and versions. Snapshots are immutable, so the background goroutine tokenizes a batch of lines outside the lock and applies the result under the lock. Each batch records the Highlighter's generation, which changes on every Edit, Reset and resynchronisation (a snapshot that did not come through Edit). A batch whose generation is outdated is discarded. Within the same generation (same text, same Lexer) each line's result is re-validated before it is applied: it is used only if the start state it was computed from still equals the stored end state of the line above (the foreground may have re-tokenized those lines meanwhile); the rest of the batch is dropped at the first mismatch.
Contracts:
- One Highlighter follows one buffer.Buffer: call Edit for every new snapshot (or pass it to Highlight). A snapshot whose Version differs from the last one seen, without an Edit linking them, makes the whole document dirty (correct, but a full re-tokenization).
- After monarch.Registry.Add replaces the grammar, call Reset with the new Lexer: every stored State belongs to the old Lexer.
- Tokens that are not final are a display hint: they tokenize the current line text from a guessed start state (the stored state of the line above), so their offsets always match the text, but types may be stale.
Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").
常量
const (
DefaultTokenWindow = 2000
DefaultRetryDelay = time.Second
DefaultMaxRetries = 3
)Defaults for the exported tuning fields.
类型
Highlighter
type Highlighter struct {
// TokenWindow is how many lines above and below each view's most
// recently requested line keep their token slices (default 2000).
TokenWindow int
// RetryDelay is the delay before a Degraded line is tokenized again
// (default 1s).
RetryDelay time.Duration
// MaxRetries is how many times a Degraded line is retried before its
// degraded tokens are accepted as final (default 3; 0 accepts at once).
MaxRetries int
// contains filtered or unexported fields
}Highlighter tokenizes one document incrementally. Its methods are safe for concurrent use; the tuning fields must be set before the first call.
func New
func New(lx *monarch.Lexer) *HighlighterNew returns a Highlighter for lx. A nil lx means plain text: every line is final and has no tokens.
func (*Highlighter) BackgroundBehind
func (h *Highlighter) BackgroundBehind(snap buffer.Snapshot, line int) boolBackgroundBehind reports whether the background goroutine (Start) runs and line of snap is not final yet: it will be, without the caller tokenizing the lines before it. A frame's work that can wait a frame or two (the editor's bracket matching) leaves them to the goroutine, whose ready callback asks for the next frame, instead of tokenizing them on the UI thread at the same time.
func (*Highlighter) Done
func (h *Highlighter) Done(snap buffer.Snapshot) boolDone reports whether every line of snap is final: snap is the current snapshot, no line is dirty and no Degraded line awaits a retry. Unlike Highlight(snap, snap.LineCount(), 0) it changes nothing: it tokenizes nothing, does not move the token window and does not adopt snap (a snapshot the Highlighter has not seen is simply not done).
func (*Highlighter) DropView
func (h *Highlighter) DropView(view ViewKey)DropView forgets view's token window (a closed editor), so it no longer holds token slices or takes one of the window slots. Unknown keys and DefaultView without a window are ignored.
func (*Highlighter) Edit
func (h *Highlighter) Edit(old, new buffer.Snapshot, edits []buffer.Edit)Edit records that new was produced from old by edits (as passed to buffer.Snapshot.Apply or buffer.Buffer.Edit): lines touched by an edit become dirty, the per-line arrays shift by the number of inserted and deleted line breaks, and every other line keeps its state and tokens. If old is not the snapshot the Highlighter last saw, the whole document becomes dirty.
func (*Highlighter) FinalBefore
func (h *Highlighter) FinalBefore(snap buffer.Snapshot, line int) boolFinalBefore reports whether every line of snap before line is final, like Highlight(snap, line, 0) but without side effects: it tokenizes nothing, moves no token window and does not adopt snap (a snapshot the Highlighter has not seen is not final). The editor's typing assistance uses it as Monaco's isCheapToTokenize.
func (*Highlighter) FinalLines
func (h *Highlighter) FinalLines(snap buffer.Snapshot) intFinalLines returns how many leading lines of snap are final, like the largest line for which FinalBefore reports true, without side effects: 0 for a snapshot the Highlighter has not seen, every line without a lexer. The editor's bracket pairs scan only final lines.
func (*Highlighter) GrammarGeneration
func (h *Highlighter) GrammarGeneration() uint64GrammarGeneration changes on every Reset, including Reset with the same lexer. It is safe to read while the background tokenizer is running.
func (*Highlighter) Highlight
func (h *Highlighter) Highlight(snap buffer.Snapshot, upToLine int, budget time.Duration) boolHighlight tokenizes dirty lines before upToLine, starting at the first dirty line, until they are all done or budget has elapsed (it always finishes the line it started; a budget <= 0 tokenizes nothing). It reports whether every line before upToLine is final. Degraded lines whose retry is due are retried first. upToLine also moves the token window of DefaultView; it is HighlightFor(DefaultView, ...).
func (*Highlighter) HighlightFor
func (h *Highlighter) HighlightFor(view ViewKey, snap buffer.Snapshot, upToLine int, budget time.Duration) boolHighlightFor is Highlight for view: upToLine moves view's token window.
func (*Highlighter) HighlightViewFor
func (h *Highlighter) HighlightViewFor(view ViewKey, snap buffer.Snapshot, upToLine int, budget time.Duration) boolHighlightViewFor is HighlightFor for a view's frame (the editor's paint): while the background goroutine runs (Start) and the first line not final lies more than viewCatchUpLines above upToLine, it tokenizes nothing and reports false. The goroutine is catching up on the lines above the view (a large document just opened): a frame's budget spent there would not reach the view, only repeat the goroutine's work. The view draws its lines from their stored start states meanwhile (Tokens: not final), as Monaco does. Otherwise (no goroutine, or the lines before the view final up to an edit close to it) it is HighlightFor.
func (*Highlighter) LexerIdentity
func (h *Highlighter) LexerIdentity() *monarch.LexerLexerIdentity returns the current immutable lexer. Preview caches use its identity to invalidate after Reset without discarding unchanged lines on Edit.
func (*Highlighter) LineSummary
func (h *Highlighter) LineSummary(key any, snap buffer.Snapshot, line int, dst []uint64) ([]uint64, bool)LineSummary appends line's summary (SetLineSummary) to dst[:0] and reports whether it has one: the line is final in snap (the current snapshot), the key matches, and the line was summarized when tokenized.
func (*Highlighter) PeekCompleteTokens
func (h *Highlighter) PeekCompleteTokens(snap buffer.Snapshot, line int, dst []monarch.Token) (tokens []monarch.Token, found bool)PeekCompleteTokens copies cached whole-line tokens only when they are final for this exact snapshot and tokenizer start state. Accepted degraded previews are final for scheduling, but are not complete token results and must miss. Like PeekTokens, this never lexes, moves a window or touches window LRU order; the returned tokens belong to dst, not to the cache. A miss returns dst[:0].
func (*Highlighter) PeekTokenRange
func (h *Highlighter) PeekTokenRange(snap buffer.Snapshot, line, from, to int, dst []monarch.Token) ([]monarch.Token, bool)PeekTokenRange copies only tokens intersecting [from,to), preserving their model-line byte and UTF-16 coordinates. It includes the token covering from and never moves a window or lexes a line; lookup is logarithmic in the tokens.
func (*Highlighter) PeekTokens
func (h *Highlighter) PeekTokens(snap buffer.Snapshot, line int, dst []monarch.Token) (tokens []monarch.Token, found bool)PeekTokens copies tokens already cached for line, without tokenizing, creating or moving a token window, or changing window LRU order. found distinguishes an empty token list from an uncached line. Consumers such as the minimap must not evict the visible editor's token window.
func (*Highlighter) Reset
func (h *Highlighter) Reset(lx *monarch.Lexer)Reset switches to lx (for example after monarch.Registry.Add replaced the grammar) and marks every line dirty.
func (*Highlighter) SetLineSummary
func (h *Highlighter) SetLineSummary(key any, fn LineSummaryFunc)SetLineSummary sets the function that summarizes each line tokenized from now on (nil: none), identified by key: another key drops the lines' summaries, the same key keeps them. The key must be comparable.
func (*Highlighter) Start
func (h *Highlighter) Start(ctx context.Context, snapshots <-chan buffer.Snapshot, ready func())Start runs the background catch-up goroutine until ctx is done or snapshots is closed. Each snapshot received wakes it (the first one also initialises a Highlighter that has not seen a snapshot yet); it then tokenizes every remaining dirty line of the current snapshot in batches, calling ready after a batch that changed lines inside the token window and when the document is fully tokenized. Snapshots that are not the current one are ignored: the caller is expected to pass them to Edit, which also wakes the goroutine. ready is called from the background goroutine. Call Start at most once.
func (*Highlighter) StartState
func (h *Highlighter) StartState(snap buffer.Snapshot, line int) (monarch.State, bool)StartState returns the stored start state of line of snap: the end state of the line above as last tokenized (final when line is below FinalLines). It reports false for a snapshot the Highlighter has not seen, a line out of range or no lexer. The editor's bracket pairs use it to notice token changes that edits do not (an opened comment).
func (*Highlighter) Sync
func (h *Highlighter) Sync(snap buffer.Snapshot)Sync makes snap the current snapshot without tokenizing anything or moving a token window: a snapshot other than the last one seen (one that did not come through Edit) makes the whole document dirty, as Highlight would. It wakes the background goroutine. Callers that skipped Edit for a while (a document shown as plain text) call it after Reset.
func (*Highlighter) TokenizeSpan
func (h *Highlighter) TokenizeSpan(snap buffer.Snapshot, line int, span string, dst []monarch.Token) []monarch.TokenTokenizeSpan tokenizes span, a piece of line of snap that starts at the line's first byte or at a point the caller treats as such (the View's visible window of a long line), with the current lexer (so Reset is honoured) from the stored start state of line: the end state of the line above as last tokenized, final or not. Token offsets are relative to span. It is a display hint like non-final Tokens: nothing is stored. For a snapshot other than the current one, or a line out of range, it starts from the lexer's initial state. Plain text (nil lexer) yields dst[:0].
func (*Highlighter) Tokens
func (h *Highlighter) Tokens(snap buffer.Snapshot, line int, dst []monarch.Token) ([]monarch.Token, bool)Tokens appends line's tokens to dst[:0] and reports whether they are final. Tokens that are not final tokenize the current text from the line above's stored state (a guess; see the package doc); a line outside every token window moves DefaultView's window to it. For a snapshot other than the current one, or a line out of range, it returns dst[:0] and false. It is TokensFor(DefaultView, ...).
func (*Highlighter) TokensFor
func (h *Highlighter) TokensFor(view ViewKey, snap buffer.Snapshot, line int, dst []monarch.Token) ([]monarch.Token, bool)TokensFor is Tokens for view: a line in view's window, or else in another view's, uses that window's cached tokens; a line in none moves view's window to it.
func (*Highlighter) WindowRange
func (h *Highlighter) WindowRange() (lo, hi int)WindowRange returns the lines [lo, hi) whose token slices DefaultView's token window currently keeps (diagnostics and tests: a caller can check that it does not move the window back and forth); it is WindowRangeFor(DefaultView).
func (*Highlighter) WindowRangeFor
func (h *Highlighter) WindowRangeFor(view ViewKey) (lo, hi int)WindowRangeFor returns the lines [lo, hi) of view's token window, 0, 0 when view has none (never requested, or evicted).
LineSummaryFunc
type LineSummaryFunc func(text string, toks []monarch.Token, dst []uint64) []uint64LineSummaryFunc summarizes a line from its final tokens, appending to dst (the editor's brackets: where they are, those in strings and comments left out). The Highlighter keeps each line's summary while the line stays final, so a reader of every line (the editor's bracket tree, built from the document's start) need not tokenize lines again outside the token windows. It returns nil for a line it does not summarize (the reader then looks at the line itself) and must not keep text or toks.
ViewKey
type ViewKey uint64ViewKey identifies one view of the document for its token window (see HighlightFor). DefaultView is the key of Highlight, Tokens and WindowRange.
const DefaultView ViewKey = 0DefaultView is the ViewKey of the single-view methods.
func NewViewKey
func NewViewKey() ViewKeyNewViewKey returns a ViewKey no other call returns (never DefaultView).