⚡ CodeMirror 6 Lezer & Highlighting

🌲 Lezer Parser (Incremental LR)

  • Parser ➡️ Generates AST from input.
  • Tree ➡️ Immutable hierarchical syntax tree.
  • Node ➡️ Individual syntactic element in the tree.
  • Incremental ♻️ Reuses unchanged nodes from the previous tree using viewport ranges.

🌐 Language Integration

import { LRLanguage } from "@codemirror/language"
 
const myLanguage = LRLanguage.define({
  parser: parser.configure({ ... }), // Lezer parser + facets
  languageData: { ... }              // Node metadata (e.g., comment syntax)
})

🎨 Syntax Highlighting Flow

graph LR
  Node --"styleTags()"--> Tag --"HighlightStyle.define()"--> CSS
  1. Tag Nodes: Map parser nodes to abstract tags.
    import { styleTags, tags as t } from "@lezer/highlight"
    const parserWithTags = parser.configure({
      props: [styleTags({ "Identifier": t.variableName, "String": t.string })]
    })
  2. Define Theme: Map tags to CSS rules.
    import { HighlightStyle } from "@codemirror/language"
    const myHighlightStyle = HighlightStyle.define([
      { tag: t.variableName, color: "#fc6" },
      { tag: t.string, color: "#859900", fontStyle: "italic" }
    ])
  3. Enable Extension: Inject into editor configuration.
    import { syntaxHighlighting } from "@codemirror/language"
    const extensions = [myLanguage, syntaxHighlighting(myHighlightStyle)]