diff --git a/src/ui/editor.ts b/src/ui/editor.ts index 44cf173..8d5ca57 100644 --- a/src/ui/editor.ts +++ b/src/ui/editor.ts @@ -75,6 +75,8 @@ const highlightField = StateField.define({ provide: (f) => EditorView.decorations.from(f), }); +const varHighlightReCache = new Map(); + /** Highlights every occurrence of the variable under the cursor. */ function buildVarHighlight(state: EditorState): DecorationSet { const builder = new RangeSetBuilder(); @@ -90,11 +92,21 @@ function buildVarHighlight(state: EditorState): DecorationSet { if (a === b) return builder.finish(); const word = text.slice(a, b); if (!/^[\p{L}_][\p{L}\d_]*$/u.test(word)) return builder.finish(); + + let cachedRe = varHighlightReCache.get(word); + if (!cachedRe) { + const esc = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + cachedRe = { + assignment: new RegExp(`^\\s*${esc}\\s*=`, "mu"), + highlight: new RegExp(`(? 1000) varHighlightReCache.clear(); + varHighlightReCache.set(word, cachedRe); + } + // only highlight if the word is actually assigned somewhere in the document - const esc = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - if (!new RegExp(`^\\s*${esc}\\s*=`, "mu").test(text)) return builder.finish(); - const re = new RegExp(`(?