@vscode/markdown-editor 0.0.2-4 → 0.0.2-6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +170 -3
- package/dist/index.js +1503 -1160
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
- package/src/view/editor.css +81 -4
- package/src/view/themes/github.css +0 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/core/offsetRange.ts","../src/core/stringEdit.ts","../src/core/lengthEdit.ts","../src/core/stringValue.ts","../src/core/selection.ts","../src/core/geometry.ts","../src/core/wordUtils.ts","../src/parser/ast.ts","../src/parser/_micromarkAdapter.ts","../src/parser/parse.ts","../src/parser/reconcile.ts","../src/parser/parser.ts","../src/parser/test/getAnnotatedSource.ts","../src/parser/visualizeAst.ts","../src/model/editorModel.ts","../src/view/visualLineMap.ts","../src/model/measuredLayoutModel.ts","../src/model/cursorNavigation.ts","../src/commands/cursorCommands.ts","../src/commands/editCommands.ts","../src/commands/selectionCommands.ts","../src/view/content/viewNode.ts","../src/view/content/blockView.ts","../src/view/content/documentView.ts","../src/view/content/dom.ts","../src/view/viewData.ts","../src/view/parts/cursorView.ts","../src/view/parts/selectionView.ts","../src/view/editorView.ts","../src/view/clipboardStrategy.ts","../src/view/editorController.ts","../src/view/measuredLayoutDebugView.ts","../src/highlighter/syntaxHighlighter.ts","../src/highlighter/monacoSyntaxHighlighter.ts","../src/highlighter/defaultMonacoSyntaxHighlighter.ts"],"sourcesContent":["export class OffsetRange {\n\tpublic static fromTo(start: number, endExclusive: number): OffsetRange {\n\t\treturn new OffsetRange(start, endExclusive);\n\t}\n\n\tpublic static ofLength(length: number): OffsetRange {\n\t\treturn new OffsetRange(0, length);\n\t}\n\n\tpublic static ofStartAndLength(start: number, length: number): OffsetRange {\n\t\treturn new OffsetRange(start, start + length);\n\t}\n\n\tpublic static emptyAt(offset: number): OffsetRange {\n\t\treturn new OffsetRange(offset, offset);\n\t}\n\n\tconstructor(\n\t\tpublic readonly start: number,\n\t\tpublic readonly endExclusive: number,\n\t) {\n\t\tif (start > endExclusive) {\n\t\t\tthrow new Error(`Invalid range: [${start}, ${endExclusive})`);\n\t\t}\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.start === this.endExclusive;\n\t}\n\n\tget length(): number {\n\t\treturn this.endExclusive - this.start;\n\t}\n\n\tpublic delta(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start + offset, this.endExclusive + offset);\n\t}\n\n\tpublic deltaStart(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start + offset, this.endExclusive);\n\t}\n\n\tpublic deltaEnd(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start, this.endExclusive + offset);\n\t}\n\n\tpublic contains(offset: number): boolean {\n\t\treturn this.start <= offset && offset < this.endExclusive;\n\t}\n\n\tpublic containsRange(other: OffsetRange): boolean {\n\t\treturn this.start <= other.start && other.endExclusive <= this.endExclusive;\n\t}\n\n\tpublic intersects(other: OffsetRange): boolean {\n\t\treturn Math.max(this.start, other.start) < Math.min(this.endExclusive, other.endExclusive);\n\t}\n\n\tpublic intersectsOrTouches(other: OffsetRange): boolean {\n\t\treturn Math.max(this.start, other.start) <= Math.min(this.endExclusive, other.endExclusive);\n\t}\n\n\tpublic intersect(other: OffsetRange): OffsetRange | undefined {\n\t\tconst start = Math.max(this.start, other.start);\n\t\tconst end = Math.min(this.endExclusive, other.endExclusive);\n\t\tif (start <= end) {\n\t\t\treturn new OffsetRange(start, end);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tpublic join(other: OffsetRange): OffsetRange {\n\t\treturn new OffsetRange(\n\t\t\tMath.min(this.start, other.start),\n\t\t\tMath.max(this.endExclusive, other.endExclusive),\n\t\t);\n\t}\n\n\tpublic isBefore(other: OffsetRange): boolean {\n\t\treturn this.endExclusive <= other.start;\n\t}\n\n\tpublic isAfter(other: OffsetRange): boolean {\n\t\treturn this.start >= other.endExclusive;\n\t}\n\n\tpublic substring(str: string): string {\n\t\treturn str.substring(this.start, this.endExclusive);\n\t}\n\n\tpublic slice<T>(arr: readonly T[]): T[] {\n\t\treturn arr.slice(this.start, this.endExclusive);\n\t}\n\n\tpublic equals(other: OffsetRange): boolean {\n\t\treturn this.start === other.start && this.endExclusive === other.endExclusive;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `[${this.start}, ${this.endExclusive})`;\n\t}\n}\n","import { OffsetRange } from './offsetRange.js';\n\nexport class StringReplacement {\n\tpublic static insert(offset: number, text: string): StringReplacement {\n\t\treturn new StringReplacement(OffsetRange.emptyAt(offset), text);\n\t}\n\n\tpublic static replace(range: OffsetRange, text: string): StringReplacement {\n\t\treturn new StringReplacement(range, text);\n\t}\n\n\tpublic static delete(range: OffsetRange): StringReplacement {\n\t\treturn new StringReplacement(range, '');\n\t}\n\n\tconstructor(\n\t\tpublic readonly replaceRange: OffsetRange,\n\t\tpublic readonly newText: string,\n\t) {}\n\n\tget isEmpty(): boolean {\n\t\treturn this.replaceRange.isEmpty && this.newText.length === 0;\n\t}\n\n\tpublic equals(other: StringReplacement): boolean {\n\t\treturn this.replaceRange.equals(other.replaceRange) && this.newText === other.newText;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `${this.replaceRange} -> ${JSON.stringify(this.newText)}`;\n\t}\n}\n\nexport class StringEdit {\n\tpublic static readonly empty = new StringEdit([]);\n\n\tpublic static single(replacement: StringReplacement): StringEdit {\n\t\treturn new StringEdit([replacement]);\n\t}\n\n\tpublic static replace(range: OffsetRange, text: string): StringEdit {\n\t\treturn new StringEdit([StringReplacement.replace(range, text)]);\n\t}\n\n\tpublic static insert(offset: number, text: string): StringEdit {\n\t\treturn new StringEdit([StringReplacement.insert(offset, text)]);\n\t}\n\n\tpublic static delete(range: OffsetRange): StringEdit {\n\t\treturn new StringEdit([StringReplacement.delete(range)]);\n\t}\n\n\tpublic readonly replacements: readonly StringReplacement[];\n\n\tconstructor(replacements: readonly StringReplacement[]) {\n\t\tlet lastEndEx = -1;\n\t\tfor (const replacement of replacements) {\n\t\t\tif (replacement.replaceRange.start < lastEndEx) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Edits must be disjoint and sorted. Found ${replacement} after ${lastEndEx}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlastEndEx = replacement.replaceRange.endExclusive;\n\t\t}\n\t\tthis.replacements = replacements;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.replacements.length === 0;\n\t}\n\n\tpublic apply(base: string): string {\n\t\tconst parts: string[] = [];\n\t\tlet pos = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tparts.push(base.substring(pos, r.replaceRange.start));\n\t\t\tparts.push(r.newText);\n\t\t\tpos = r.replaceRange.endExclusive;\n\t\t}\n\t\tparts.push(base.substring(pos));\n\t\treturn parts.join('');\n\t}\n\n\tpublic inverse(original: string): StringEdit {\n\t\tconst edits: StringReplacement[] = [];\n\t\tlet offset = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tconst oldText = original.substring(r.replaceRange.start, r.replaceRange.endExclusive);\n\t\t\tedits.push(\n\t\t\t\tStringReplacement.replace(\n\t\t\t\t\tOffsetRange.ofStartAndLength(r.replaceRange.start + offset, r.newText.length),\n\t\t\t\t\toldText,\n\t\t\t\t),\n\t\t\t);\n\t\t\toffset += r.newText.length - r.replaceRange.length;\n\t\t}\n\t\treturn new StringEdit(edits);\n\t}\n\n\tpublic equals(other: StringEdit): boolean {\n\t\tif (this.replacements.length !== other.replacements.length) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let i = 0; i < this.replacements.length; i++) {\n\t\t\tif (!this.replacements[i].equals(other.replacements[i])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic mapOffset(offset: number): number {\n\t\tlet delta = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tif (r.replaceRange.start > offset) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (r.replaceRange.endExclusive <= offset) {\n\t\t\t\tdelta += r.newText.length - r.replaceRange.length;\n\t\t\t} else {\n\t\t\t\t// offset is inside a replaced range — map to end of replacement\n\t\t\t\treturn r.replaceRange.start + delta + r.newText.length;\n\t\t\t}\n\t\t}\n\t\treturn offset + delta;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `[${this.replacements.map(r => r.toString()).join(', ')}]`;\n\t}\n}\n","import { OffsetRange } from './offsetRange.js';\n\n/**\n * A single \"the text in `replaceRange` now spans `newLength` characters\"\n * statement. Unlike {@link StringReplacement} it carries no text — it only\n * describes *where* and *by how much* something changed, not *what to*.\n *\n * For syntax highlighting it means: the characters that used to occupy\n * `replaceRange` are replaced by `newLength` characters whose tokens may now\n * be coloured differently. A same-length replacement (`replaceRange.length ===\n * newLength`) therefore means \"these characters kept their positions but got\n * re-coloured\".\n */\nexport class LengthReplacement {\n public static replace(replaceRange: OffsetRange, newLength: number): LengthReplacement {\n return new LengthReplacement(replaceRange, newLength);\n }\n\n constructor(\n public readonly replaceRange: OffsetRange,\n public readonly newLength: number,\n ) {\n if (newLength < 0) {\n throw new Error(`newLength must be non-negative, got ${newLength}`);\n }\n }\n\n get lengthDelta(): number {\n return this.newLength - this.replaceRange.length;\n }\n\n public equals(other: LengthReplacement): boolean {\n return this.replaceRange.equals(other.replaceRange) && this.newLength === other.newLength;\n }\n\n public toString(): string {\n return `${this.replaceRange} -> +${this.newLength}`;\n }\n}\n\n/**\n * A set of disjoint, sorted {@link LengthReplacement}s — the length-only\n * counterpart of {@link StringEdit}. Used as the change reason of an\n * observable so observers learn which offset ranges of the previous value map\n * to which ranges of the new value (and thus what to invalidate) without\n * carrying the new content itself.\n */\nexport class LengthEdit {\n public static readonly empty = new LengthEdit([]);\n\n public static single(replacement: LengthReplacement): LengthEdit {\n return new LengthEdit([replacement]);\n }\n\n public static replace(replaceRange: OffsetRange, newLength: number): LengthEdit {\n return new LengthEdit([LengthReplacement.replace(replaceRange, newLength)]);\n }\n\n public readonly replacements: readonly LengthReplacement[];\n\n constructor(replacements: readonly LengthReplacement[]) {\n let lastEndEx = -1;\n for (const r of replacements) {\n if (r.replaceRange.start < lastEndEx) {\n throw new Error(`Edits must be disjoint and sorted. Found ${r} after end ${lastEndEx}`);\n }\n lastEndEx = r.replaceRange.endExclusive;\n }\n this.replacements = replacements;\n }\n\n get isEmpty(): boolean {\n return this.replacements.length === 0;\n }\n\n public equals(other: LengthEdit): boolean {\n if (this.replacements.length !== other.replacements.length) {\n return false;\n }\n for (let i = 0; i < this.replacements.length; i++) {\n if (!this.replacements[i].equals(other.replacements[i])) {\n return false;\n }\n }\n return true;\n }\n\n public toString(): string {\n return this.isEmpty ? 'LengthEdit.empty' : this.replacements.join(', ');\n }\n}\n","import { OffsetRange } from './offsetRange.js';\n\nexport class StringValue {\n\tconstructor(readonly value: string) {}\n\n\tget length(): number {\n\t\treturn this.value.length;\n\t}\n\n\tpublic substring(range: OffsetRange): string {\n\t\treturn range.substring(this.value);\n\t}\n\n\tpublic toString(): string {\n\t\treturn this.value;\n\t}\n}\n","import type { SourceOffset } from './sourceOffset.js';\nimport { OffsetRange } from './offsetRange.js';\n\nexport class Selection {\n\tstatic collapsed(offset: SourceOffset): Selection {\n\t\treturn new Selection(offset, offset);\n\t}\n\n\tconstructor(\n\t\treadonly anchor: SourceOffset,\n\t\treadonly active: SourceOffset,\n\t) {}\n\n\tget isCollapsed(): boolean {\n\t\treturn this.anchor === this.active;\n\t}\n\n\tget isForward(): boolean {\n\t\treturn this.active >= this.anchor;\n\t}\n\n\tget range(): OffsetRange {\n\t\treturn this.isForward\n\t\t\t? new OffsetRange(this.anchor, this.active)\n\t\t\t: new OffsetRange(this.active, this.anchor);\n\t}\n\n\tcollapseToActive(): Selection {\n\t\treturn Selection.collapsed(this.active);\n\t}\n\n\twithActive(active: SourceOffset): Selection {\n\t\treturn new Selection(this.anchor, active);\n\t}\n}\n","/**\n * Immutable point in 2D space, in CSS-pixel client coordinates.\n */\nexport class Point2D {\n static readonly ZERO = new Point2D(0, 0);\n\n constructor(\n readonly x: number,\n readonly y: number,\n ) { }\n\n translate(dx: number, dy: number): Point2D {\n return new Point2D(this.x + dx, this.y + dy);\n }\n}\n\n/**\n * Immutable axis-aligned rectangle in 2D space, in CSS-pixel client\n * coordinates. `x`/`y` is the top-left corner, growing right/down.\n *\n * Half-open in both dimensions: `right` and `bottom` are excluded.\n */\nexport class Rect2D {\n static readonly EMPTY = new Rect2D(0, 0, 0, 0);\n\n static fromPointPoint(left: number, top: number, right: number, bottom: number): Rect2D {\n return new Rect2D(left, top, right - left, bottom - top);\n }\n\n static fromPointSize(x: number, y: number, width: number, height: number): Rect2D {\n return new Rect2D(x, y, width, height);\n }\n\n private constructor(\n readonly x: number,\n readonly y: number,\n readonly width: number,\n readonly height: number,\n ) { }\n\n get left(): number { return this.x; }\n get top(): number { return this.y; }\n get right(): number { return this.x + this.width; }\n get bottom(): number { return this.y + this.height; }\n\n get topLeft(): Point2D { return new Point2D(this.x, this.y); }\n\n containsX(x: number): boolean { return x >= this.left && x < this.right; }\n containsY(y: number): boolean { return y >= this.top && y < this.bottom; }\n containsPoint(p: Point2D): boolean { return this.containsX(p.x) && this.containsY(p.y); }\n\n /** Same y/height, zero-width band at `x = this.left`. Useful for caret rects derived from a line. */\n withZeroWidthAt(x: number): Rect2D {\n return new Rect2D(x, this.y, 0, this.height);\n }\n\n translate(dx: number, dy: number): Rect2D {\n return new Rect2D(this.x + dx, this.y + dy, this.width, this.height);\n }\n}\n","export function findWordBoundaryLeft(text: string, offset: number): number {\n\tif (offset <= 0) { return 0; }\n\tlet i = offset - 1;\n\t// Skip whitespace\n\twhile (i > 0 && /\\s/.test(text[i])) { i--; }\n\t// Skip word characters\n\tif (i >= 0 && /\\w/.test(text[i])) {\n\t\twhile (i > 0 && /\\w/.test(text[i - 1])) { i--; }\n\t} else if (i >= 0) {\n\t\t// Skip punctuation\n\t\twhile (i > 0 && !/\\w/.test(text[i - 1]) && !/\\s/.test(text[i - 1])) { i--; }\n\t}\n\treturn i;\n}\n\nexport function findWordBoundaryRight(text: string, offset: number): number {\n\tconst len = text.length;\n\tif (offset >= len) { return len; }\n\tlet i = offset;\n\t// Skip whitespace\n\twhile (i < len && /\\s/.test(text[i])) { i++; }\n\t// Skip word characters\n\tif (i < len && /\\w/.test(text[i])) {\n\t\twhile (i < len && /\\w/.test(text[i])) { i++; }\n\t} else if (i < len) {\n\t\t// Skip punctuation\n\t\twhile (i < len && !/\\w/.test(text[i]) && !/\\s/.test(text[i])) { i++; }\n\t}\n\treturn i;\n}\n\nexport function findWordAt(text: string, offset: number): { start: number; end: number } {\n\tif (offset >= text.length) {\n\t\treturn { start: text.length, end: text.length };\n\t}\n\tconst ch = text[offset];\n\tif (/\\w/.test(ch)) {\n\t\tlet start = offset;\n\t\tlet end = offset;\n\t\twhile (start > 0 && /\\w/.test(text[start - 1])) { start--; }\n\t\twhile (end < text.length && /\\w/.test(text[end])) { end++; }\n\t\treturn { start, end };\n\t}\n\tif (/\\s/.test(ch)) {\n\t\tlet start = offset;\n\t\tlet end = offset;\n\t\twhile (start > 0 && /\\s/.test(text[start - 1])) { start--; }\n\t\twhile (end < text.length && /\\s/.test(text[end])) { end++; }\n\t\treturn { start, end };\n\t}\n\t// Punctuation\n\tlet start = offset;\n\tlet end = offset;\n\twhile (start > 0 && !/\\w/.test(text[start - 1]) && !/\\s/.test(text[start - 1])) { start--; }\n\twhile (end < text.length && !/\\w/.test(text[end]) && !/\\s/.test(text[end])) { end++; }\n\treturn { start, end };\n}\n","/**\n * Prototype AST for the incremental reconciliation design — full grammar.\n *\n * Design rules (all enforced structurally):\n * - Every node stores exactly one ordered `content` array of its children.\n * `children` is *computed* from it; nothing is passed in as a separate\n * `children` param, so the two can never drift.\n * - Syntactic glue (inter-block newlines, table pipes/padding, the whitespace\n * micromark doesn't assign to any token) is a first-class {@link GlueAstNode} node.\n * Each container's element type names it explicitly, e.g. `(Block | Glue)[]`,\n * so it is impossible to forget an array may contain glue. Semantic\n * accessors (`blocks`, `cells`, `marker`, …) filter glue out.\n * - Structural equality is the {@link AstNode.equalsShallow} method. The\n * generic part (kind, length, children-by-identity) lives once on the base;\n * each node contributes only its scalar comparison via {@link AstNode._localEquals}.\n * - `length` is cached on first access (the tree is immutable).\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\n\nlet _nextNodeId = 1;\nexport function _resetNodeIds(): void { _nextNodeId = 1; }\n\nexport abstract class AstNode {\n\n\n\tabstract readonly kind: string;\n\tabstract get children(): readonly AstNode[];\n\n\t/**\n\t * A stable identity. Every node has one: it is minted on construction and\n\t * carried across edits by reconciliation, so a node that survives an edit\n\t * (even with changed content) keeps the same id.\n\t */\n\treadonly id: number = _nextNodeId++;\n\n\t/** Rebuild this node with each child replaced by `map.get(child) ?? child`. */\n\tabstract mapChildren(map: ReadonlyMap<AstNode, AstNode>): AstNode;\n\n\tprivate _length = -1;\n\tget length(): number {\n\t\tif (this._length < 0) {\n\t\t\tlet sum = 0;\n\t\t\tfor (const c of this.children) { sum += c.length; }\n\t\t\tthis._length = sum;\n\t\t}\n\t\treturn this._length;\n\t}\n\n\t/**\n\t * True when `other` has the same content. Containers compare children *by\n\t * identity* (`===`): bottom-up reconciliation substitutes reused old\n\t * instances into the fresh tree first, so equal children already share\n\t * instances — keeping this O(children), not O(subtree). Leaves have no\n\t * children, so {@link _localEquals} is their whole comparison.\n\t */\n\tequalsShallow(other: AstNode): boolean {\n\t\tif (this === other) { return true; }\n\t\tif (this.kind !== other.kind || this.length !== other.length) { return false; }\n\t\tif (!this._localEquals(other as this)) { return false; }\n\t\tconst a = this.children;\n\t\tconst b = other.children;\n\t\tif (a.length !== b.length) { return false; }\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (a[i] !== b[i]) { return false; }\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Compares only this node's own scalar fields (kind/length already match). */\n\tprotected _localEquals(_other: this): boolean { return true; }\n\n\t/**\n\t * A copy of this node that adopts `id`. Reconciliation uses this to carry an\n\t * old identity onto a node whose content changed. Nodes are immutable value\n\t * holders, so a shallow prototype copy with `id` overridden is sound.\n\t */\n\tcloneWithId(id: number): this {\n\t\tconst clone: this = Object.create(Object.getPrototypeOf(this));\n\t\tObject.assign(clone, this);\n\t\t(clone as { id: number }).id = id;\n\t\treturn clone;\n\t}\n}\n\nconst _emptyChildren: readonly AstNode[] = [];\n\nfunction _mapArr<T extends AstNode>(map: ReadonlyMap<AstNode, AstNode>, arr: readonly T[]): readonly T[] {\n\tlet out: T[] | undefined;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst m = map.get(arr[i]);\n\t\tif (m && m !== arr[i]) { (out ??= arr.slice())[i] = m as T; }\n\t}\n\treturn out ?? arr;\n}\n\nfunction _mapOne<T extends AstNode>(map: ReadonlyMap<AstNode, AstNode>, n: T): T {\n\tconst m = map.get(n);\n\treturn (m && m !== n ? m : n) as T;\n}\n\nfunction _mapTrivia(map: ReadonlyMap<AstNode, AstNode>, trivia: GlueAstNode | undefined): GlueAstNode | undefined {\n\treturn trivia ? _mapOne(map, trivia) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Leaves\n// ---------------------------------------------------------------------------\n\nabstract class LeafAstNode extends AstNode {\n\tabstract readonly content: string;\n\tget children(): readonly AstNode[] { return _emptyChildren; }\n\toverride get length(): number { return this.content.length; }\n\toverride mapChildren(): AstNode { return this; }\n}\n\n/** Real document text (an {@link InlineAstNode}). */\nexport class TextAstNode extends LeafAstNode {\n\treadonly kind = 'text';\n\tconstructor(readonly content: string) { super(); }\n\tprotected override _localEquals(o: this): boolean { return this.content === o.content; }\n}\n\n/** A semantic syntax marker (heading `#`, fences, brackets, list bullet, …). */\nexport class MarkerAstNode extends LeafAstNode {\n\treadonly kind = 'marker';\n\tconstructor(readonly markerKind: string, readonly content: string) { super(); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.markerKind === o.markerKind && this.content === o.content;\n\t}\n}\n\n/** Non-semantic syntactic glue: whitespace, padding, table pipes. */\nexport class GlueAstNode extends LeafAstNode {\n\treadonly kind = 'glue';\n\tconstructor(readonly content: string, readonly glueKind?: string) { super(); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.content === o.content && this.glueKind === o.glueKind;\n\t}\n}\n\n/**\n * A block-level node. Every block may carry a {@link leadingTrivia} glue — the\n * whitespace that precedes it on its own line (a nested list's indentation, the\n * leading space of a continued paragraph). It is owned by the block it precedes\n * (not the one it trails), so the view reveals it exactly when *this* block is\n * active, and it tiles at the block's front: {@link children} prepends it to the\n * block's own content while `content` stays the block's real payload.\n */\nexport abstract class BlockAstNodeBase extends AstNode {\n\tabstract readonly leadingTrivia?: GlueAstNode;\n\t/** This block with its leading trivia replaced — re-homes a leading glue onto it. */\n\tabstract withLeadingTrivia(trivia: GlueAstNode | undefined): BlockAstNode;\n\t/** Prepends {@link leadingTrivia}, if any, ahead of the block's own children. */\n\tprotected _withLeading(own: readonly AstNode[]): readonly AstNode[] {\n\t\treturn this.leadingTrivia ? [this.leadingTrivia, ...own] : own;\n\t}\n}\n\nexport class ThematicBreakAstNode extends BlockAstNodeBase {\n\treadonly kind = 'thematicBreak';\n\tconstructor(\n\t\treadonly content: readonly (MarkerAstNode | GlueAstNode)[],\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget marker(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ThematicBreakAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ThematicBreakAstNode { return new ThematicBreakAstNode(this.content, trivia); }\n}\n\n// ---------------------------------------------------------------------------\n// Inlines\n// ---------------------------------------------------------------------------\n\nexport type InlineAstNode = TextAstNode | StrongAstNode | EmphasisAstNode | StrikethroughAstNode | InlineCodeAstNode | InlineMathAstNode | LinkAstNode | ImageAstNode;\n\nfunction _marker(content: readonly AstNode[], kind: string): MarkerAstNode | undefined {\n\treturn content.find((n): n is MarkerAstNode => n instanceof MarkerAstNode && n.markerKind === kind);\n}\n\nexport class StrongAstNode extends AstNode {\n\treadonly kind = 'strong';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new StrongAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class EmphasisAstNode extends AstNode {\n\treadonly kind = 'emphasis';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new EmphasisAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class StrikethroughAstNode extends AstNode {\n\treadonly kind = 'strikethrough';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new StrikethroughAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class InlineCodeAstNode extends AstNode {\n\treadonly kind = 'inlineCode';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new InlineCodeAstNode(_mapArr(m, this.content)); }\n}\n\nexport class InlineMathAstNode extends AstNode {\n\treadonly kind = 'inlineMath';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new InlineMathAstNode(_mapArr(m, this.content)); }\n}\n\nexport class LinkAstNode extends AstNode {\n\treadonly kind = 'link';\n\tconstructor(readonly url: string, readonly content: readonly (MarkerAstNode | InlineAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new LinkAstNode(this.url, _mapArr(m, this.content)); }\n\tprotected override _localEquals(o: this): boolean { return this.url === o.url; }\n}\n\nexport class ImageAstNode extends AstNode {\n\treadonly kind = 'image';\n\tconstructor(readonly alt: string, readonly url: string, readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ImageAstNode(this.alt, this.url, _mapArr(m, this.content)); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.alt === o.alt && this.url === o.url;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockAstNode = HeadingAstNode | ParagraphAstNode | CodeBlockAstNode | MathBlockAstNode | ThematicBreakAstNode | BlockQuoteAstNode | ListAstNode | TableAstNode;\n\nexport class HeadingAstNode extends BlockAstNodeBase {\n\treadonly kind = 'heading';\n\tconstructor(\n\t\treadonly level: 1 | 2 | 3 | 4 | 5 | 6,\n\t\treadonly marker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading([this.marker, ...this.content]); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new HeadingAstNode(this.level, _mapOne(m, this.marker), _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia));\n\t}\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): HeadingAstNode {\n\t\treturn new HeadingAstNode(this.level, this.marker, this.content, trivia);\n\t}\n\tprotected override _localEquals(o: this): boolean { return this.level === o.level; }\n}\n\nexport class ParagraphAstNode extends BlockAstNodeBase {\n\treadonly kind = 'paragraph';\n\tconstructor(readonly content: readonly (InlineAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ParagraphAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ParagraphAstNode { return new ParagraphAstNode(this.content, trivia); }\n}\n\nexport class CodeBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'codeBlock';\n\tprivate _previous?: WeakRef<CodeBlockAstNode>;\n\tprivate _contentEdit?: StringEdit;\n\tconstructor(readonly language: string, readonly content: readonly (MarkerAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget openFence(): MarkerAstNode | undefined { return _marker(this.content, 'openFence'); }\n\tget closeFence(): MarkerAstNode | undefined { return _marker(this.content, 'closeFence'); }\n\tget code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\n\t/** Relative start offset of the {@link code} marker within this block. */\n\tget codeOffset(): number {\n\t\tlet pos = this.leadingTrivia?.length ?? 0;\n\t\tfor (const c of this.content) { if (c.kind === 'marker' && (c as MarkerAstNode).markerKind === 'content') { return pos; } pos += c.length; }\n\t\treturn pos;\n\t}\n\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new CodeBlockAstNode(this.language, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): CodeBlockAstNode { return new CodeBlockAstNode(this.language, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.language === o.language; }\n\n\t/**\n\t * A copy of this block carrying an incremental link to `previous`:\n\t * `contentEdit` (in the block's *content* coordinates) turns `previous`'s\n\t * content into this one. Uses a weak reference so the previous tree can be\n\t * garbage-collected.\n\t */\n\twithCodeDiff(previous: CodeBlockAstNode, contentEdit: StringEdit): CodeBlockAstNode {\n\t\tconst clone = this.cloneWithId(this.id) as CodeBlockAstNode;\n\t\tclone._previous = new WeakRef(previous);\n\t\tclone._contentEdit = contentEdit;\n\t\treturn clone;\n\t}\n\n\t/**\n\t * When this block was incrementally derived from `previous` (same\n\t * fences/language, edit entirely within the content), returns the\n\t * content-coordinate edit; otherwise `undefined`.\n\t */\n\tgetDiff(previous: CodeBlockAstNode): CodeBlockDiff | undefined {\n\t\tif (this._contentEdit && this._previous?.deref() === previous) {\n\t\t\treturn { stringEdit: this._contentEdit };\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Describes how a {@link CodeBlockAstNode} was incrementally derived from a previous\n * one: {@link stringEdit} (in the block's *content* coordinates) turns the\n * previous content into this one.\n */\nexport interface CodeBlockDiff {\n\treadonly stringEdit: StringEdit;\n}\n\nexport class MathBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'mathBlock';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new MathBlockAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): MathBlockAstNode { return new MathBlockAstNode(this.content, trivia); }\n}\n\nexport class BlockQuoteAstNode extends BlockAstNodeBase {\n\treadonly kind = 'blockQuote';\n\tconstructor(readonly content: readonly (MarkerAstNode | BlockAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new BlockQuoteAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): BlockQuoteAstNode { return new BlockQuoteAstNode(this.content, trivia); }\n}\n\nexport class ListAstNode extends BlockAstNodeBase {\n\treadonly kind = 'list';\n\tconstructor(readonly ordered: boolean, readonly content: readonly (ListItemAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget items(): readonly ListItemAstNode[] { return this.content.filter((n): n is ListItemAstNode => n instanceof ListItemAstNode); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ListAstNode(this.ordered, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ListAstNode { return new ListAstNode(this.ordered, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.ordered === o.ordered; }\n}\n\nexport class ListItemAstNode extends AstNode {\n\treadonly kind = 'listItem';\n\tconstructor(\n\t\treadonly marker: MarkerAstNode,\n\t\treadonly content: readonly (BlockAstNode | GlueAstNode)[],\n\t\treadonly checked?: boolean,\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] {\n\t\treturn this.leadingTrivia ? [this.leadingTrivia, this.marker, ...this.content] : [this.marker, ...this.content];\n\t}\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new ListItemAstNode(\n\t\t\t_mapOne(m, this.marker),\n\t\t\t_mapArr(m, this.content),\n\t\t\tthis.checked,\n\t\t\tthis.leadingTrivia ? _mapOne(m, this.leadingTrivia) : undefined,\n\t\t);\n\t}\n\twithLeadingTrivia(trivia: GlueAstNode | undefined): ListItemAstNode {\n\t\treturn new ListItemAstNode(this.marker, this.content, this.checked, trivia);\n\t}\n\tprotected override _localEquals(o: this): boolean { return this.checked === o.checked; }\n}\n\nexport class TableAstNode extends BlockAstNodeBase {\n\treadonly kind = 'table';\n\tconstructor(readonly content: readonly (TableRowAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tprivate get _rows(): readonly TableRowAstNode[] { return this.content.filter((n): n is TableRowAstNode => n instanceof TableRowAstNode); }\n\tget headerRow(): TableRowAstNode | undefined { return this._rows[0]; }\n\tget delimiterRow(): TableRowAstNode | undefined { return this._rows[1]; }\n\tget bodyRows(): readonly TableRowAstNode[] { return this._rows.slice(2); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): TableAstNode { return new TableAstNode(this.content, trivia); }\n}\n\nexport class TableRowAstNode extends AstNode {\n\treadonly kind = 'tableRow';\n\tconstructor(readonly content: readonly (TableCellAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\tget cells(): readonly TableCellAstNode[] { return this.content.filter((n): n is TableCellAstNode => n instanceof TableCellAstNode); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableRowAstNode(_mapArr(m, this.content)); }\n}\n\nexport class TableCellAstNode extends AstNode {\n\treadonly kind = 'tableCell';\n\tconstructor(readonly content: readonly (InlineAstNode | MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableCellAstNode(_mapArr(m, this.content)); }\n}\n\nexport class DocumentAstNode extends AstNode {\n\treadonly kind = 'document';\n\tconstructor(readonly content: readonly (BlockAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new DocumentAstNode(_mapArr(m, this.content)); }\n}\n\nfunction _isBlock(n: AstNode): n is BlockAstNode {\n\treturn n instanceof HeadingAstNode || n instanceof ParagraphAstNode || n instanceof CodeBlockAstNode\n\t\t|| n instanceof MathBlockAstNode || n instanceof ThematicBreakAstNode || n instanceof BlockQuoteAstNode\n\t\t|| n instanceof ListAstNode || n instanceof TableAstNode;\n}\n// ---------------------------------------------------------------------------\n// Public helpers\n// ---------------------------------------------------------------------------\n\n/** Every concrete node kind, for exhaustive consumer-side dispatch. */\nexport type AnyAstNode =\n\t| TextAstNode | MarkerAstNode | GlueAstNode | ThematicBreakAstNode\n\t| StrongAstNode | EmphasisAstNode | StrikethroughAstNode | InlineCodeAstNode | InlineMathAstNode | LinkAstNode | ImageAstNode\n\t| HeadingAstNode | ParagraphAstNode | CodeBlockAstNode | MathBlockAstNode | BlockQuoteAstNode | ListAstNode | ListItemAstNode\n\t| TableAstNode | TableRowAstNode | TableCellAstNode | DocumentAstNode;\n\n/**\n * Source offset (relative to `root`) of the node with `target`'s id, or\n * `undefined` when it is not in the tree. Ids are stable across edits, so this\n * locates a node even after reconciliation has rebuilt the tree around it.\n */\nexport function findNodeOffsetById(root: AstNode, target: AstNode): number | undefined {\n\tif (root.id === target.id) { return 0; }\n\tlet pos = 0;\n\tfor (const child of root.children) {\n\t\tconst inner = findNodeOffsetById(child, target);\n\t\tif (inner !== undefined) { return pos + inner; }\n\t\tpos += child.length;\n\t}\n\treturn undefined;\n}\n\nconst _TASK_CHECKBOX_RE = /\\[[ xX]\\]/;\n\n/**\n * Source range (relative to `item`) of a task list item's `[x]`/`[ ]`\n * checkbox, or `undefined` when the item is not a task item. The checkbox is\n * plain glue in the AST, so a host that wants to toggle it locates the literal\n * `[x]`/`[ ]` token here.\n */\nexport function taskCheckboxRange(item: ListItemAstNode): OffsetRange | undefined {\n\tif (item.checked === undefined) { return undefined; }\n\tconst match = _TASK_CHECKBOX_RE.exec(_nodeText(item));\n\tif (!match) { return undefined; }\n\treturn OffsetRange.ofStartAndLength(match.index, match[0].length);\n}\n\n/** Source text of a node, reconstructed from its leaf content. */\nfunction _nodeText(node: AstNode): string {\n\tif (node instanceof LeafAstNode) { return node.content; }\n\tlet text = '';\n\tfor (const child of node.children) { text += _nodeText(child); }\n\treturn text;\n}","import { parse, preprocess, postprocess } from 'micromark';\nimport { math } from 'micromark-extension-math';\nimport { gfmTable } from 'micromark-extension-gfm-table';\nimport { gfmTaskListItem } from 'micromark-extension-gfm-task-list-item';\nimport { gfmStrikethrough } from 'micromark-extension-gfm-strikethrough';\n\nexport interface MicromarkEvent {\n\treadonly type: 'enter' | 'exit';\n\treadonly tokenType: string;\n\treadonly startOffset: number;\n\treadonly endOffset: number;\n}\n\nexport function tokenize(source: string): MicromarkEvent[] {\n\tconst parser = parse({ extensions: [math(), gfmTable(), gfmTaskListItem(), gfmStrikethrough()] });\n\tconst chunks = preprocess()(source, undefined, true);\n\tconst nativeEvents = postprocess(parser.document().write(chunks));\n\n\treturn nativeEvents.map(([type, token]) => ({\n\t\ttype,\n\t\ttokenType: token.type,\n\t\tstartOffset: token.start.offset,\n\t\tendOffset: token.end.offset,\n\t}));\n}\n","/**\n * Full-grammar parser for the prototype AST. Tokenizes with micromark (via the\n * shared adapter) and distills the event stream into the computed-`children`\n * AST. Spans no token claims become explicit {@link GlueAstNode}, so every node's\n * `content` tiles its source range exactly and contiguously — the property\n * that makes offset-based reconciliation sound.\n */\n\nimport {\n BlockAstNodeBase, BlockQuoteAstNode, CodeBlockAstNode, DocumentAstNode, EmphasisAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, InlineCodeAstNode,\n InlineMathAstNode, LinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode, AstNode, ParagraphAstNode,\n StrikethroughAstNode, StrongAstNode, TableAstNode, TableCellAstNode, TableRowAstNode, TextAstNode, ThematicBreakAstNode,\n type BlockAstNode,\n} from './ast.js';\nimport { tokenize, type MicromarkEvent } from './_micromarkAdapter.js';\n\nexport function parse(source: string): DocumentAstNode {\n return new AstBuilder(tokenize(source), source).build();\n}\n\ntype Entry = { node: AstNode; start: number };\n\n/**\n * Re-attributes an `indent` glue (the spaces after a line break) onto the block\n * it precedes, as that block's leading trivia, so the whitespace tiles and\n * renders on the indented block's own line (revealed when *it* is active) rather\n * than trailing the previous one:\n * - before a {@link ListAstNode}: onto that list's first item,\n * - before a {@link ListItemAstNode}: onto that item,\n * - before any other {@link BlockAstNodeBase}: onto the block itself,\n * all via the node's `leadingTrivia` slot. An indent glue with no such host is\n * merged back into the preceding line-break glue, so it never renders as a\n * standalone run between blocks. Offsets stay exact: the glue keeps its source\n * span, it just moves inside (or back into) a sibling.\n */\nfunction _pullIndentIntoBlocks<T extends AstNode>(content: readonly T[]): T[] {\n const out: T[] = [];\n for (let i = 0; i < content.length; i++) {\n const cur = content[i];\n const next = content[i + 1];\n if (cur instanceof GlueAstNode && cur.glueKind === 'indent') {\n const hosted = next !== undefined ? _prependLeadingTrivia(next, cur) : undefined;\n if (hosted) {\n out.push(hosted as unknown as T);\n i++;\n continue;\n }\n // No host for the indentation: fold it back into the preceding\n // line break so it stays hidden rather than rendering as dots.\n const prev = out[out.length - 1];\n if (prev instanceof GlueAstNode && prev.glueKind === undefined) {\n out[out.length - 1] = new GlueAstNode(prev.content + cur.content) as unknown as T;\n continue;\n }\n out.push(cur);\n continue;\n }\n out.push(cur);\n }\n return out;\n}\n\n/**\n * Hosts `glue` as the leading trivia of `next` when `next` can carry it — a\n * list (onto its first item), a list item, or any block — returning the rebuilt\n * node, or `undefined` when `next` cannot host leading trivia.\n */\nfunction _prependLeadingTrivia(next: AstNode, glue: GlueAstNode): AstNode | undefined {\n if (next instanceof ListAstNode) {\n const firstIdx = next.content.findIndex(n => n instanceof ListItemAstNode);\n if (firstIdx < 0) { return undefined; }\n const items = next.content.map((n, j) => (j === firstIdx ? (n as ListItemAstNode).withLeadingTrivia(glue) : n));\n return new ListAstNode(next.ordered, items, next.leadingTrivia);\n }\n if (next instanceof ListItemAstNode) { return next.withLeadingTrivia(glue); }\n if (next instanceof BlockAstNodeBase) { return next.withLeadingTrivia(glue); }\n return undefined;\n}\n\n/**\n * Re-attributes every plain document-level glue — the blank lines and trailing\n * newlines that separate top-level blocks — onto the block it follows, as a\n * trailing glue appended to that block's own `content`. The view then reveals\n * the gap (character-for-character) exactly when that preceding block is active,\n * and renders it at the end of the block rather than as a standalone run between\n * blocks.\n *\n * The gap is tagged by what it does:\n * - `blockBreak` — it separates two *paragraphs* (`para\\n\\npara`), the only\n * case where deleting a newline merges the blocks: the two paragraphs fuse\n * into one and the surviving newline re-parses as an ordinary soft break.\n * The view paints its leading newline as a distinct (blue) glyph. A heading\n * or any other block self-delimits after a single newline, so a gap after it\n * (or before a non-paragraph) is structurally inert and is *not* a break.\n * - `blockGap` — every other gap: after a non-paragraph block, before a\n * non-paragraph block, a trailing gap with no following block, or a\n * leading/hostless gap (one at the very start of the document, before the\n * first block, with no preceding block to host it).\n * Its newlines are neutral.\n *\n * Only untagged glue is touched (an `indent` glue keeps its kind); offsets are\n * untouched — the glue keeps its source span, it just moves inside the preceding\n * block.\n */\nfunction _attachBlockGaps<T extends AstNode>(content: readonly (T | GlueAstNode)[]): (T | GlueAstNode)[] {\n const out: (T | GlueAstNode)[] = [];\n for (let idx = 0; idx < content.length; idx++) {\n const n = content[idx];\n if (n instanceof GlueAstNode && n.glueKind === undefined) {\n const prev = out[out.length - 1];\n const next = content[idx + 1];\n // A break only exists between two paragraphs: that is the sole gap\n // whose deletion merges the blocks. After a heading (or before any\n // non-paragraph) the gap is structurally inert, so it stays neutral.\n const isParagraphBreak = prev instanceof ParagraphAstNode && next instanceof ParagraphAstNode;\n const gap = new GlueAstNode(n.content, isParagraphBreak ? 'blockBreak' : 'blockGap');\n const host = prev !== undefined ? _appendTrailingGlue(prev, gap) : undefined;\n if (host) { out[out.length - 1] = host as T | GlueAstNode; } else { out.push(gap); }\n continue;\n }\n out.push(n);\n }\n return out;\n}\n\n/**\n * Returns `node` rebuilt with `glue` consumed as its trailing trivia — the\n * greedy-block rule: a block (and the item/quote that hosts it) swallows the\n * whitespace that follows it, exactly like a recursive-descent scanner attaches\n * trailing trivia to the token it just read. Leaf blocks append `glue` to their\n * own `content`; containers ({@link BlockQuoteAstNode}, {@link ListAstNode},\n * {@link ListItemAstNode}) recurse into their last child so the glue lands at the\n * end of the deepest trailing paragraph. Returns `undefined` when `node` cannot\n * host trailing glue (a leaf marker, a glue, an inline), so the caller keeps the\n * gap standalone.\n */\nfunction _appendTrailingGlue(node: AstNode, glue: GlueAstNode): AstNode | undefined {\n switch (node.kind) {\n case 'paragraph': { const p = node as ParagraphAstNode; return new ParagraphAstNode([...p.content, glue], p.leadingTrivia); }\n case 'heading': { const h = node as HeadingAstNode; return new HeadingAstNode(h.level, h.marker, [...h.content, glue], h.leadingTrivia); }\n case 'codeBlock': { const c = node as CodeBlockAstNode; return new CodeBlockAstNode(c.language, [...c.content, glue], c.leadingTrivia); }\n case 'mathBlock': { const m = node as MathBlockAstNode; return new MathBlockAstNode([...m.content, glue], m.leadingTrivia); }\n case 'thematicBreak': { const t = node as ThematicBreakAstNode; return new ThematicBreakAstNode([...t.content, glue], t.leadingTrivia); }\n case 'table': { const t = node as TableAstNode; return new TableAstNode([...t.content, glue], t.leadingTrivia); }\n case 'blockQuote': { const b = node as BlockQuoteAstNode; return new BlockQuoteAstNode(_appendIntoLast(b.content, glue), b.leadingTrivia); }\n case 'list': { const l = node as ListAstNode; return new ListAstNode(l.ordered, _appendIntoLast(l.content, glue), l.leadingTrivia); }\n case 'listItem': { const it = node as ListItemAstNode; return new ListItemAstNode(it.marker, _appendIntoLast(it.content, glue), it.checked, it.leadingTrivia); }\n default: return undefined;\n }\n}\n\n/**\n * Recurses {@link _appendTrailingGlue} into the *last* child of `content` so the\n * glue sinks into the deepest trailing paragraph. Only the last child is tried —\n * the glue is the trailing-most run in source, so it must stay after any glue the\n * last child already carries; when the last child cannot host it (or there is\n * none), the glue is appended at the end, preserving source order.\n */\nfunction _appendIntoLast<T extends AstNode>(content: readonly T[], glue: GlueAstNode): T[] {\n const last = content[content.length - 1];\n const host = last !== undefined ? _appendTrailingGlue(last, glue) : undefined;\n if (host) { const out = content.slice(); out[out.length - 1] = host as T; return out; }\n return [...content, glue as unknown as T];\n}\n\n/**\n * Guarantees the document has at least one block. A source with no blocks (the\n * empty string, or whitespace-only input that produced only leading glue)\n * becomes a single empty {@link ParagraphAstNode} hosting whatever glue was\n * present, so document content is always a run of blocks.\n */\nfunction _ensureBlocks(content: readonly (BlockAstNode | GlueAstNode)[]): readonly (BlockAstNode | GlueAstNode)[] {\n if (content.some(n => !(n instanceof GlueAstNode))) { return content; }\n return [new ParagraphAstNode(content as readonly GlueAstNode[])];\n}\n\n/**\n * Collects a node's placed children and fills the gaps between them with\n * {@link GlueAstNode}, yielding an array that tiles `[parentStart, parentStart+len)`\n * exactly. `glueKind` tags glue that must stay hideable (table cell pipes).\n */\nclass Content {\n private readonly _entries: Entry[] = [];\n constructor(private readonly _parentStart: number, private readonly _source: string) { }\n\n add(node: AstNode, start: number): void { this._entries.push({ node, start }); }\n\n build<T extends AstNode = AstNode>(parentLength: number, glueKind?: string): T[] {\n this._entries.sort((a, b) => a.start - b.start);\n const out: AstNode[] = [];\n let pos = this._parentStart;\n const end = this._parentStart + parentLength;\n // Split a gap that ends in indentation (a newline followed by spaces/tabs)\n // into the line break plus a separate `indent` glue, mirroring how a\n // tokenizer attributes leading trivia to the following token. The indent\n // glue is later re-attributed onto the block it precedes (see\n // `_pullIndentIntoBlocks`), so its whitespace renders on that block's line\n // instead of trailing the previous one.\n const gap = (s: number, e: number) => {\n const text = this._source.substring(s, e);\n const m = glueKind ? null : /\\n[^\\S\\n]+$/.exec(text);\n if (!m) { out.push(new GlueAstNode(text, glueKind)); return; }\n const indent = text.slice(m.index + 1);\n out.push(new GlueAstNode(text.slice(0, text.length - indent.length)));\n out.push(new GlueAstNode(indent, 'indent'));\n };\n for (const { node, start } of this._entries) {\n if (node.length === 0) { continue; }\n if (start > pos) { gap(pos, start); }\n out.push(node);\n pos = start + node.length;\n }\n if (pos < end) { gap(pos, end); }\n return out as T[];\n }\n}\n\nclass AstBuilder {\n private _idx = 0;\n private _checkChecked: boolean | undefined;\n\n constructor(private readonly _events: MicromarkEvent[], private readonly _source: string) { }\n\n build(): DocumentAstNode {\n const cb = new Content(0, this._source);\n while (this._idx < this._events.length) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter') {\n const start = ev.startOffset;\n const block = this._tryParseBlock();\n if (block) { cb.add(block, start); } else { this._idx++; }\n } else { this._idx++; }\n }\n return new DocumentAstNode(_ensureBlocks(_attachBlockGaps(_pullIndentIntoBlocks(cb.build<BlockAstNode | GlueAstNode>(this._source.length)))));\n }\n\n private _tryParseBlock(): BlockAstNode | undefined {\n switch (this._events[this._idx].tokenType) {\n case 'atxHeading': return this._parseHeading();\n case 'paragraph': return this._parseParagraph();\n case 'codeFenced': return this._parseCodeFenced();\n case 'codeIndented': return this._parseCodeIndented();\n case 'mathFlow': return this._parseMathFlow();\n case 'thematicBreak': return this._parseThematicBreak();\n case 'blockQuote': return this._parseBlockQuote();\n case 'listUnordered':\n case 'listOrdered': return this._parseList();\n case 'table': return this._parseTable();\n default: return undefined;\n }\n }\n\n private _parseHeading(): HeadingAstNode {\n const enter = this._consume('enter', 'atxHeading');\n let level: 1 | 2 | 3 | 4 | 5 | 6 = 1;\n let markerStart = enter.startOffset;\n let markerEnd = enter.startOffset;\n const inlines: Entry[] = [];\n\n while (this._notExit('atxHeading')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'atxHeadingSequence') {\n const seqEnter = this._consume('enter', 'atxHeadingSequence');\n const seqExit = this._consume('exit', 'atxHeadingSequence');\n if (markerEnd === enter.startOffset) {\n level = Math.min(6, Math.max(1, seqExit.endOffset - seqEnter.startOffset)) as 1 | 2 | 3 | 4 | 5 | 6;\n markerStart = seqEnter.startOffset;\n markerEnd = seqExit.endOffset;\n }\n } else if (ev.type === 'enter' && ev.tokenType === 'atxHeadingText') {\n this._consume('enter', 'atxHeadingText');\n this._parseInlines(inlines, 'atxHeadingText');\n this._consume('exit', 'atxHeadingText');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'atxHeading');\n if (markerEnd > markerStart && inlines.length > 0) { markerEnd = inlines[0].start; }\n\n const marker = new MarkerAstNode('headingMarker', this._source.substring(enter.startOffset, markerEnd));\n const cb = new Content(markerEnd, this._source);\n for (const e of inlines) { cb.add(e.node, e.start); }\n const content = cb.build<HeadingAstNode['content'][number]>(exit.endOffset - markerEnd);\n return new HeadingAstNode(level, marker, content);\n }\n\n private _parseParagraph(): ParagraphAstNode {\n const enter = this._consume('enter', 'paragraph');\n const inlines: Entry[] = [];\n while (this._notExit('paragraph')) { this._parseInlineEvent(inlines); }\n const exit = this._consume('exit', 'paragraph');\n const cb = new Content(enter.startOffset, this._source);\n for (const e of inlines) { cb.add(e.node, e.start); }\n return new ParagraphAstNode(cb.build<ParagraphAstNode['content'][number]>(exit.endOffset - enter.startOffset));\n }\n\n private _parseCodeFenced(): CodeBlockAstNode {\n const enter = this._consume('enter', 'codeFenced');\n let language = '';\n const cb = new Content(enter.startOffset, this._source);\n let sawOpenFence = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n\n while (this._notExit('codeFenced')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'codeFencedFence') {\n const fenceEnter = this._consume('enter', 'codeFencedFence');\n while (this._notExit('codeFencedFence')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'codeFencedFenceInfo') {\n this._consume('enter', 'codeFencedFenceInfo');\n while (this._notExit('codeFencedFenceInfo')) {\n const ii = this._events[this._idx];\n if (ii.tokenType === 'data') { language = this._source.substring(ii.startOffset, ii.endOffset); }\n this._idx++;\n }\n this._consume('exit', 'codeFencedFenceInfo');\n } else { this._idx++; }\n }\n const fenceExit = this._consume('exit', 'codeFencedFence');\n cb.add(new MarkerAstNode(sawOpenFence ? 'closeFence' : 'openFence',\n this._source.substring(fenceEnter.startOffset, fenceExit.endOffset)), fenceEnter.startOffset);\n sawOpenFence = true;\n } else if (ev.tokenType === 'codeFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'codeFenced');\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n }\n return new CodeBlockAstNode(language, cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n /**\n * An indented code block has no fences and no info string: micromark strips a\n * four-space `linePrefix` from each line and emits the rest as `codeFlowValue`.\n * Each line's `linePrefix` becomes a hideable `codeIndent` marker (so the\n * structural indentation can be dropped from the rendered block, like a\n * heading's `#`), while the actual code is kept verbatim as `content` markers\n * — one run per line — so the block round-trips the source.\n */\n private _parseCodeIndented(): CodeBlockAstNode {\n const enter = this._consume('enter', 'codeIndented');\n const cb = new Content(enter.startOffset, this._source);\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n const flushContent = () => {\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n contentStart = undefined;\n }\n };\n while (this._notExit('codeIndented')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'linePrefix') {\n flushContent();\n const prefixEnter = this._consume('enter', 'linePrefix');\n const prefixExit = this._consume('exit', 'linePrefix');\n cb.add(new MarkerAstNode('codeIndent', this._source.substring(prefixEnter.startOffset, prefixExit.endOffset)), prefixEnter.startOffset);\n } else if (ev.tokenType === 'codeFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n flushContent();\n const exit = this._consume('exit', 'codeIndented');\n return new CodeBlockAstNode('', cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseMathFlow(): MathBlockAstNode {\n const enter = this._consume('enter', 'mathFlow');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpenFence = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n\n while (this._notExit('mathFlow')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'mathFlowFence') {\n const fenceEnter = this._consume('enter', 'mathFlowFence');\n while (this._notExit('mathFlowFence')) { this._idx++; }\n const fenceExit = this._consume('exit', 'mathFlowFence');\n cb.add(new MarkerAstNode(sawOpenFence ? 'closeFence' : 'openFence',\n this._source.substring(fenceEnter.startOffset, fenceExit.endOffset)), fenceEnter.startOffset);\n sawOpenFence = true;\n } else if (ev.tokenType === 'mathFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'mathFlow');\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n }\n return new MathBlockAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseThematicBreak(): ThematicBreakAstNode {\n const enter = this._consume('enter', 'thematicBreak');\n while (this._notExit('thematicBreak')) { this._idx++; }\n const exit = this._consume('exit', 'thematicBreak');\n const marker = new MarkerAstNode('content', this._source.substring(enter.startOffset, exit.endOffset));\n return new ThematicBreakAstNode([marker]);\n }\n\n private _parseBlockQuote(): BlockQuoteAstNode {\n const enter = this._consume('enter', 'blockQuote');\n const cb = new Content(enter.startOffset, this._source);\n let seenBlock = false;\n while (this._notExit('blockQuote')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'blockQuotePrefix') {\n const pre = this._consume('enter', 'blockQuotePrefix');\n while (this._notExit('blockQuotePrefix')) { this._idx++; }\n const preExit = this._consume('exit', 'blockQuotePrefix');\n // The *leading* `>` (this level's prefix, before its first child\n // block) becomes a real `blockQuoteMarker` marker: it sits at the\n // block's start with a single, unambiguous caret position, so the\n // view can hang it in the quote's left padding gutter (adding no\n // inline width, keeping content at the same x in active/inactive)\n // and a nested quote — itself inset by the outer padding — forms a\n // column one level in.\n //\n // Continuation prefixes (a blank quoted line, the `>` that starts a\n // later block) *follow* a block on their own line; a gutter marker\n // there would share the previous line's trailing caret position and\n // break the one-offset-one-caret invariant. They stay inline glue\n // (tiled by `Content` / attached by `_attachBlockGaps`), reading\n // naturally where the `>` falls in the source.\n if (!seenBlock) {\n cb.add(new MarkerAstNode('blockQuoteMarker', this._source.substring(pre.startOffset, preExit.endOffset)), pre.startOffset);\n }\n } else if (ev.type === 'enter') {\n const start = ev.startOffset;\n const block = this._tryParseBlock();\n if (block) { cb.add(block, start); seenBlock = true; } else { this._idx++; }\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'blockQuote');\n return new BlockQuoteAstNode(_attachBlockGaps(_pullIndentIntoBlocks(cb.build<BlockQuoteAstNode['content'][number]>(exit.endOffset - enter.startOffset))));\n }\n\n private _parseList(): ListAstNode {\n const listType = this._events[this._idx].tokenType;\n const ordered = listType === 'listOrdered';\n const enter = this._consume('enter', listType);\n const cb = new Content(enter.startOffset, this._source);\n\n let itemStart: number | undefined;\n let markerStart: number | undefined;\n let markerEnd: number | undefined;\n let itemCb: Content | undefined;\n let itemChecked: boolean | undefined;\n let lastBlockEnd: number | undefined;\n\n const flush = () => {\n if (itemStart === undefined || markerStart === undefined || itemCb === undefined) { return; }\n const marker = new MarkerAstNode('listItemMarker', this._source.substring(markerStart, markerEnd!));\n // The task checkbox lives inside the item's first paragraph, so it\n // tiles there as Glue; only its checked state is lifted to the item.\n const itemEnd = lastBlockEnd ?? markerEnd!;\n const content = itemCb.build<ListItemAstNode['content'][number]>(itemEnd - markerEnd!);\n cb.add(new ListItemAstNode(marker, _attachBlockGaps(_pullIndentIntoBlocks(content)), itemChecked), itemStart);\n };\n\n while (this._notExit(listType)) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'listItemPrefix') {\n flush();\n this._consume('enter', 'listItemPrefix');\n itemStart = inner.startOffset;\n markerStart = inner.startOffset;\n itemChecked = undefined;\n lastBlockEnd = undefined;\n this._checkChecked = undefined;\n while (this._notExit('listItemPrefix')) { this._idx++; }\n markerEnd = this._events[this._idx].endOffset;\n this._consume('exit', 'listItemPrefix');\n itemCb = new Content(markerEnd, this._source);\n } else if (inner.type === 'enter') {\n const start = inner.startOffset;\n const block = this._tryParseBlock();\n if (block && itemCb) {\n itemCb.add(block, start);\n lastBlockEnd = start + block.length;\n if (itemChecked === undefined && this._checkChecked !== undefined) { itemChecked = this._checkChecked; }\n } else if (!block) { this._idx++; }\n } else { this._idx++; }\n }\n flush();\n const exit = this._consume('exit', listType);\n return new ListAstNode(ordered, _attachBlockGaps(_pullIndentIntoBlocks(cb.build<ListItemAstNode | GlueAstNode>(exit.endOffset - enter.startOffset))));\n }\n\n private _parseTable(): TableAstNode {\n const enter = this._consume('enter', 'table');\n const cb = new Content(enter.startOffset, this._source);\n let columnCount = 0;\n\n while (this._notExit('table')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'tableHead') {\n this._consume('enter', 'tableHead');\n while (this._notExit('tableHead')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableRow') {\n const row = this._parseTableRow('tableHeader');\n columnCount = row.cells.length;\n cb.add(row, inner.startOffset);\n } else if (inner.type === 'enter' && inner.tokenType === 'tableDelimiterRow') {\n const start = inner.startOffset;\n while (this._notExit('tableDelimiterRow')) { this._idx++; }\n const end = this._events[this._idx].endOffset;\n this._idx++;\n cb.add(this._buildDelimiterRow(start, end, columnCount), start);\n } else { this._idx++; }\n }\n this._consume('exit', 'tableHead');\n } else if (ev.type === 'enter' && ev.tokenType === 'tableBody') {\n this._consume('enter', 'tableBody');\n while (this._notExit('tableBody')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableRow') {\n cb.add(this._parseTableRow('tableData'), inner.startOffset);\n } else { this._idx++; }\n }\n this._consume('exit', 'tableBody');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'table');\n return new TableAstNode(cb.build<TableRowAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _buildDelimiterRow(start: number, end: number, columnCount: number): TableRowAstNode {\n const raw = this._source.substring(start, end);\n const pipes: number[] = [];\n for (let i = 0; i < raw.length; i++) { if (raw[i] === '|') { pipes.push(i); } }\n const cellStartsRel: number[] = [];\n const cols = Math.max(1, columnCount);\n if (raw[0] === '|') {\n for (let i = 0; i < cols && i < pipes.length; i++) { cellStartsRel.push(pipes[i]); }\n } else {\n cellStartsRel.push(0);\n for (let i = 0; i < cols - 1 && i < pipes.length; i++) { cellStartsRel.push(pipes[i]); }\n }\n const rowCb = new Content(start, this._source);\n for (let i = 0; i < cellStartsRel.length; i++) {\n const cs = cellStartsRel[i];\n const ce = i + 1 < cellStartsRel.length ? cellStartsRel[i + 1] : raw.length;\n const cellCb = new Content(start + cs, this._source);\n const text = raw.substring(cs, ce);\n // The last cell's closing `|` is split into its own marker so the\n // view can pin it to the column's right gridline (matching the body\n // rows' closing-pipe glue); without the split the trailing pipe\n // floats right after the dashes and the last column's outline is\n // ragged. The leading `| --- ` stays a single `tableDelimiter`.\n const isLast = i === cellStartsRel.length - 1;\n if (isLast && text.length > 1 && text.endsWith('|')) {\n cellCb.add(new MarkerAstNode('tableDelimiter', text.slice(0, -1)), start + cs);\n cellCb.add(new MarkerAstNode('tableDelimiterClose', '|'), start + cs + text.length - 1);\n } else {\n cellCb.add(new MarkerAstNode('tableDelimiter', text), start + cs);\n }\n rowCb.add(new TableCellAstNode(cellCb.build<TableCellAstNode['content'][number]>(ce - cs)), start + cs);\n }\n return new TableRowAstNode(rowCb.build<TableCellAstNode | GlueAstNode>(end - start));\n }\n\n private _parseTableRow(cellType: 'tableHeader' | 'tableData'): TableRowAstNode {\n const enter = this._consume('enter', 'tableRow');\n const rowCb = new Content(enter.startOffset, this._source);\n while (this._notExit('tableRow')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === cellType) {\n const cellEnter = this._consume('enter', cellType);\n const inlines: Entry[] = [];\n while (this._notExit(cellType)) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableContent') {\n this._consume('enter', 'tableContent');\n while (this._notExit('tableContent')) { this._parseInlineEvent(inlines); }\n this._consume('exit', 'tableContent');\n } else { this._idx++; }\n }\n const cellExit = this._consume('exit', cellType);\n const cellCb = new Content(cellEnter.startOffset, this._source);\n for (const e of inlines) { cellCb.add(e.node, e.start); }\n rowCb.add(new TableCellAstNode(cellCb.build<TableCellAstNode['content'][number]>(cellExit.endOffset - cellEnter.startOffset, 'tableCellGlue')), cellEnter.startOffset);\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'tableRow');\n return new TableRowAstNode(rowCb.build<TableCellAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseInlines(entries: Entry[], untilExit: string): void {\n while (this._idx < this._events.length) {\n const ev = this._events[this._idx];\n if (ev.type === 'exit' && ev.tokenType === untilExit) { return; }\n this._parseInlineEvent(entries);\n }\n }\n\n private _parseInlineEvent(entries: Entry[]): void {\n const ev = this._events[this._idx];\n if (ev.type === 'enter') {\n switch (ev.tokenType) {\n case 'strongSequence':\n case 'emphasisSequence': this._parseEmphasisOrStrong(entries); return;\n case 'codeText': entries.push(this._parseInlineCode()); return;\n case 'mathText': entries.push(this._parseInlineMath()); return;\n case 'link': entries.push(this._parseLink()); return;\n case 'image': entries.push(this._parseImage()); return;\n case 'strikethrough': entries.push(this._parseStrikethrough()); return;\n case 'hardBreakTrailing':\n case 'hardBreakEscape': entries.push(this._parseHardBreak()); return;\n }\n }\n if (ev.type === 'exit' && (ev.tokenType === 'data' || ev.tokenType === 'codeTextData')) {\n entries.push({ node: new TextAstNode(this._source.substring(ev.startOffset, ev.endOffset)), start: ev.startOffset });\n }\n if (ev.type === 'exit' && ev.tokenType === 'taskListCheckValueChecked') { this._checkChecked = true; }\n else if (ev.type === 'exit' && ev.tokenType === 'taskListCheckValueUnchecked') { this._checkChecked = false; }\n this._idx++;\n }\n\n /**\n * A GFM hard line break — either two-or-more trailing spaces\n * (`hardBreakTrailing`) or a backslash (`hardBreakEscape`) — followed by the\n * line ending it forces. Both halves are absorbed into a single\n * `hardBreak` marker, so the node *is* the whole break: a bare `lineEnding`\n * (a soft break) is never matched here and stays glue that collapses to a\n * space. Whether the line ending breaks is thus micromark's call, not ours.\n */\n private _parseHardBreak(): Entry {\n const enter = this._events[this._idx];\n const tokenType = enter.tokenType;\n this._consume('enter', tokenType);\n while (this._notExit(tokenType)) { this._idx++; }\n let end = this._consume('exit', tokenType).endOffset;\n const next = this._events[this._idx];\n if (next && next.type === 'enter' && next.tokenType === 'lineEnding') {\n this._consume('enter', 'lineEnding');\n end = this._consume('exit', 'lineEnding').endOffset;\n }\n return { node: new MarkerAstNode('hardBreak', this._source.substring(enter.startOffset, end)), start: enter.startOffset };\n }\n\n private _parseEmphasisOrStrong(entries: Entry[]): void {\n const tokenType = this._events[this._idx].tokenType;\n const isStrong = tokenType === 'strongSequence';\n const openEnter = this._consume('enter', tokenType);\n const openExit = this._consume('exit', tokenType);\n const inner: Entry[] = [];\n\n while (this._idx < this._events.length) {\n const next = this._events[this._idx];\n if (next.type === 'enter' && next.tokenType === tokenType) {\n const closeEnter = this._consume('enter', tokenType);\n const closeExit = this._consume('exit', tokenType);\n const openMarker = new MarkerAstNode('openMarker', this._source.substring(openEnter.startOffset, openExit.endOffset));\n const closeMarker = new MarkerAstNode('closeMarker', this._source.substring(closeEnter.startOffset, closeExit.endOffset));\n const cb = new Content(openExit.endOffset, this._source);\n for (const e of inner) { cb.add(e.node, e.start); }\n const content = cb.build<StrongAstNode['content'][number]>(closeEnter.startOffset - openExit.endOffset);\n const node = isStrong\n ? new StrongAstNode(openMarker, content, closeMarker)\n : new EmphasisAstNode(openMarker, content, closeMarker);\n entries.push({ node, start: openEnter.startOffset });\n return;\n }\n this._parseInlineEvent(inner);\n }\n entries.push({ node: new TextAstNode(this._source.substring(openEnter.startOffset, openExit.endOffset)), start: openEnter.startOffset });\n }\n\n private _parseInlineCode(): Entry {\n const enter = this._consume('enter', 'codeText');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpen = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n while (this._notExit('codeText')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'codeTextSequence') {\n cb.add(new MarkerAstNode(sawOpen ? 'closeMarker' : 'openMarker', this._source.substring(ev.startOffset, ev.endOffset)), ev.startOffset);\n sawOpen = true;\n } else if (ev.type === 'enter' && ev.tokenType === 'codeTextData') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n }\n this._idx++;\n }\n const exit = this._consume('exit', 'codeText');\n if (contentStart !== undefined) { cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart); }\n return { node: new InlineCodeAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseInlineMath(): Entry {\n const enter = this._consume('enter', 'mathText');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpen = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n while (this._notExit('mathText')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'mathTextSequence') {\n cb.add(new MarkerAstNode(sawOpen ? 'closeMarker' : 'openMarker', this._source.substring(ev.startOffset, ev.endOffset)), ev.startOffset);\n sawOpen = true;\n } else if (ev.type === 'enter' && ev.tokenType === 'mathTextData') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n }\n this._idx++;\n }\n const exit = this._consume('exit', 'mathText');\n if (contentStart !== undefined) { cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart); }\n return { node: new InlineMathAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseStrikethrough(): Entry {\n const enter = this._consume('enter', 'strikethrough');\n let openMarker: MarkerAstNode | undefined;\n let closeMarker: MarkerAstNode | undefined;\n let contentStart = enter.startOffset;\n let contentEnd = enter.startOffset;\n const inner: Entry[] = [];\n while (this._notExit('strikethrough')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'strikethroughSequence') {\n const text = this._source.substring(ev.startOffset, ev.endOffset);\n if (!openMarker) { openMarker = new MarkerAstNode('openMarker', text); contentStart = ev.endOffset; }\n else { closeMarker = new MarkerAstNode('closeMarker', text); contentEnd = ev.startOffset; }\n this._idx++;\n } else if (ev.type === 'enter' && ev.tokenType === 'strikethroughText') {\n this._consume('enter', 'strikethroughText');\n this._parseInlines(inner, 'strikethroughText');\n this._consume('exit', 'strikethroughText');\n } else { this._idx++; }\n }\n this._consume('exit', 'strikethrough');\n const cb = new Content(contentStart, this._source);\n for (const e of inner) { cb.add(e.node, e.start); }\n const content = cb.build<StrikethroughAstNode['content'][number]>(contentEnd - contentStart);\n return { node: new StrikethroughAstNode(openMarker!, content, closeMarker!), start: enter.startOffset };\n }\n\n private _parseLink(): Entry {\n const enter = this._consume('enter', 'link');\n const cb = new Content(enter.startOffset, this._source);\n const inner: Entry[] = [];\n let url = '';\n let sawOpenBracket = false;\n\n while (this._notExit('link')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'label') {\n this._consume('enter', 'label');\n while (this._notExit('label')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'labelMarker') {\n cb.add(new MarkerAstNode(sawOpenBracket ? 'closeBracket' : 'openBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenBracket = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'labelText') {\n this._consume('enter', 'labelText');\n this._parseInlines(inner, 'labelText');\n this._consume('exit', 'labelText');\n continue;\n }\n this._idx++;\n }\n this._consume('exit', 'label');\n } else if (ev.type === 'enter' && ev.tokenType === 'resource') {\n this._consume('enter', 'resource');\n let sawOpenParen = false;\n while (this._notExit('resource')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'resourceMarker') {\n cb.add(new MarkerAstNode(sawOpenParen ? 'closeParen' : 'openParen', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenParen = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'resourceDestinationString') {\n url = this._source.substring(i2.startOffset, i2.endOffset);\n cb.add(new MarkerAstNode('url', url), i2.startOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'resource');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'link');\n for (const e of inner) { cb.add(e.node, e.start); }\n return { node: new LinkAstNode(url, cb.build<LinkAstNode['content'][number]>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseImage(): Entry {\n const enter = this._consume('enter', 'image');\n const cb = new Content(enter.startOffset, this._source);\n let alt = '';\n let url = '';\n let sawOpenBracket = false;\n\n while (this._notExit('image')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'label') {\n this._consume('enter', 'label');\n while (this._notExit('label')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'labelImageMarker') {\n cb.add(new MarkerAstNode('bangBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n } else if (i2.type === 'enter' && i2.tokenType === 'labelMarker') {\n cb.add(new MarkerAstNode(sawOpenBracket ? 'closeBracket' : 'openBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenBracket = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'labelText') {\n alt = this._source.substring(i2.startOffset, i2.endOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'label');\n } else if (ev.type === 'enter' && ev.tokenType === 'resource') {\n this._consume('enter', 'resource');\n let sawOpenParen = false;\n while (this._notExit('resource')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'resourceMarker') {\n cb.add(new MarkerAstNode(sawOpenParen ? 'closeParen' : 'openParen', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenParen = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'resourceDestinationString') {\n url = this._source.substring(i2.startOffset, i2.endOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'resource');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'image');\n return { node: new ImageAstNode(alt, url, cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _notExit(tokenType: string): boolean {\n if (this._idx >= this._events.length) { return false; }\n const ev = this._events[this._idx];\n return !(ev.type === 'exit' && ev.tokenType === tokenType);\n }\n\n private _consume(type: 'enter' | 'exit', tokenType: string): MicromarkEvent {\n const ev = this._events[this._idx];\n if (!ev || ev.type !== type || ev.tokenType !== tokenType) {\n throw new Error(`Expected ${type}:${tokenType} at ${this._idx}, got ${ev?.type}:${ev?.tokenType}`);\n }\n this._idx++;\n return ev;\n }\n}\n","/**\n * Incremental reconciliation: build the fresh tree normally, then walk it\n * bottom-up against the previous tree, substituting previous instances where\n * the content is provably unchanged, and carrying over stable ids where a\n * node's identity survived an edit.\n *\n * Two soundness rules drive the whole thing:\n * - Full reuse of a node requires that its span maps to a *clean* (untouched)\n * original range, and that the rebuilt node is `structurallyEqual` to the\n * old one at that range. Because children are reconciled first, that\n * structural check is by identity and stays linear.\n * - Id carry-over uses the node's *start* offset (which, for a node that\n * merely contains an edit, lies before the edit and maps back cleanly), so\n * a node edited in place gets a new instance but keeps its old id.\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit, StringReplacement } from '../core/stringEdit.js';\nimport { CodeBlockAstNode, DocumentAstNode, AstNode } from './ast.js';\nimport { parse } from './parse.js';\n\n/** Maps offsets/ranges from modified (new) coordinates back to original (previous). */\nexport class EditMapper {\n constructor(private readonly _edit: StringEdit) { }\n\n /**\n * The original range corresponding to `mod`, or `undefined` if `mod`\n * overlaps any replaced/inserted text (i.e. is not provably unchanged).\n */\n getOriginalRange(mod: OffsetRange): OffsetRange | undefined {\n let delta = 0;\n for (const r of this._edit.replacements) {\n const modStart = r.replaceRange.start + delta;\n if (modStart >= mod.endExclusive) { break; }\n const dirtyEnd = modStart + r.newText.length;\n if (Math.max(modStart, mod.start) < Math.min(dirtyEnd, mod.endExclusive)) {\n return undefined;\n }\n delta += r.newText.length - r.replaceRange.length;\n }\n return mod.delta(-delta);\n }\n\n /** The original offset for `mod`, or `undefined` if it falls inside inserted text. */\n getOriginalOffset(mod: number): number | undefined {\n let delta = 0;\n for (const r of this._edit.replacements) {\n const modStart = r.replaceRange.start + delta;\n if (mod < modStart) { break; }\n if (mod < modStart + r.newText.length) { return undefined; }\n delta += r.newText.length - r.replaceRange.length;\n }\n return mod - delta;\n }\n}\n\n/** Indexes the previous tree for O(1) lookup by exact range or by stable id. */\nexport class OldTreeIndex {\n private readonly _byRange = new Map<string, AstNode[]>();\n private readonly _byId = new Map<string, AstNode>();\n\n constructor(root: AstNode) { this._walk(root, 0); }\n\n private _walk(n: AstNode, start: number): void {\n const key = `${start}:${start + n.length}`;\n let arr = this._byRange.get(key);\n if (!arr) { arr = []; this._byRange.set(key, arr); }\n arr.push(n);\n this._byId.set(`${start}:${n.kind}`, n);\n let pos = start;\n for (const c of n.children) { this._walk(c, pos); pos += c.length; }\n }\n\n /** The old node spanning exactly `range` with the given `kind`, if any. */\n lookupExact(range: OffsetRange, kind: string): AstNode | undefined {\n return this._byRange.get(`${range.start}:${range.endExclusive}`)?.find(n => n.kind === kind);\n }\n\n /** The old node that began at `originalStart` with the given `kind`. */\n lookupId(originalStart: number, kind: string): AstNode | undefined {\n return this._byId.get(`${originalStart}:${kind}`);\n }\n}\n\nfunction _reconcile(fresh: AstNode, start: number, mapper: EditMapper, index: OldTreeIndex, edit: StringEdit): AstNode {\n // 1. Reconcile children first, substituting reused instances upward.\n let map: Map<AstNode, AstNode> | undefined;\n let pos = start;\n for (const c of fresh.children) {\n const rc = _reconcile(c, pos, mapper, index, edit);\n if (rc !== c) { (map ??= new Map()).set(c, rc); }\n pos += c.length;\n }\n let n = map ? fresh.mapChildren(map) : fresh;\n\n // 2. Full reuse: clean original range + structurally identical old node.\n const orig = mapper.getOriginalRange(OffsetRange.ofStartAndLength(start, fresh.length));\n if (orig) {\n const cand = index.lookupExact(orig, n.kind);\n if (cand && n.equalsShallow(cand)) { return cand; }\n }\n\n // 3. Id carry-over: a changed node whose start maps cleanly to an old node\n // of the same kind keeps that old node's id (new instance, same identity).\n const os = mapper.getOriginalOffset(start);\n const old = os !== undefined ? index.lookupId(os, n.kind) : undefined;\n if (old && old.id !== n.id) { n = n.cloneWithId(old.id); }\n\n // 4. Code-block content link: when only the content changed, attach a\n // content-coordinate diff to the old block so the view can update in place.\n if (n instanceof CodeBlockAstNode && old instanceof CodeBlockAstNode && os !== undefined) {\n const linked = _linkCodeBlock(n, old, os, edit);\n if (linked) { return linked; }\n }\n\n return n;\n}\n\n/**\n * If `edit` lies entirely within `old`'s content and the fences/language are\n * unchanged, returns `fresh` carrying a content-coordinate diff to `old`;\n * otherwise `undefined`.\n */\nfunction _linkCodeBlock(fresh: CodeBlockAstNode, old: CodeBlockAstNode, oldStart: number, edit: StringEdit): CodeBlockAstNode | undefined {\n const oldCode = old.code;\n const freshCode = fresh.code;\n if (!oldCode || !freshCode) { return undefined; }\n if (fresh.language !== old.language) { return undefined; }\n if (fresh.openFence?.content !== old.openFence?.content) { return undefined; }\n if (fresh.closeFence?.content !== old.closeFence?.content) { return undefined; }\n\n const contentStart = oldStart + old.codeOffset;\n const contentEnd = contentStart + oldCode.length;\n if (!_editWithin(edit, contentStart, contentEnd)) { return undefined; }\n\n const contentEdit = _shiftEdit(edit, -contentStart);\n if (contentEdit.apply(oldCode.content) !== freshCode.content) { return undefined; }\n\n return fresh.withCodeDiff(old, contentEdit);\n}\n\n/** Whether every replacement of `edit` lies within `[start, endExclusive)`. */\nfunction _editWithin(edit: StringEdit, start: number, endExclusive: number): boolean {\n for (const r of edit.replacements) {\n if (r.replaceRange.start < start || r.replaceRange.endExclusive > endExclusive) { return false; }\n }\n return true;\n}\n\n/** `edit` with every replacement range shifted by `delta`. */\nfunction _shiftEdit(edit: StringEdit, delta: number): StringEdit {\n return new StringEdit(edit.replacements.map(r =>\n StringReplacement.replace(r.replaceRange.delta(delta), r.newText)));\n}\n\nexport function reconcile(fresh: AstNode, previous: AstNode, edit: StringEdit): AstNode {\n return _reconcile(fresh, 0, new EditMapper(edit), new OldTreeIndex(previous), edit);\n}\n\n/**\n * Parses `text`; when `previous` and `edit` are given, reconciles the fresh\n * tree against `previous` so unchanged subtrees keep their old instances and\n * edited id-bearing nodes keep their old ids.\n */\nexport function parseIncremental(text: string, previous?: DocumentAstNode, edit?: StringEdit): DocumentAstNode {\n const fresh = parse(text);\n if (!previous || !edit) {\n return fresh;\n }\n return reconcile(fresh, previous, edit) as DocumentAstNode;\n}\n","import { StringValue } from '../core/stringValue.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport { DocumentAstNode } from './ast.js';\nimport { parseIncremental } from './reconcile.js';\n\n/**\n * Parses markdown into a {@link DocumentAstNode}.\n *\n * When given the `previous` document and the `edit` that produced the new\n * text, it reuses unchanged subtrees and carries node identities across the\n * edit (see {@link parseIncremental}), so views can diff cheaply and code\n * blocks keep their incremental highlighting sessions.\n */\nexport class MarkdownParser {\n\tparse(text: StringValue, previous?: DocumentAstNode, edit?: StringEdit): DocumentAstNode {\n\t\treturn parseIncremental(text.value, previous, edit);\n\t}\n}\n","/**\n * Renders a node as XML-annotated source: every container becomes a\n * `<kind …>` element wrapping its children, leaves render their literal source\n * text, and {@link GlueAstNode}/{@link TextAstNode} render as raw text (no tag). This mirrors\n * the original parser's annotated-source format, adapted to the computed-\n * `children` + explicit-glue AST.\n */\n\nimport {\n CodeBlockAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, LinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, TextAstNode, type AstNode,\n} from '../ast.js';\n\nexport function getAnnotatedSource(node: AstNode, source: string, offset: number = 0): string {\n if (node.children.length === 0) {\n const text = escapeXml(source.substring(offset, offset + node.length));\n if (node instanceof TextAstNode) { return text; }\n const tag = node instanceof MarkerAstNode ? node.markerKind : node.kind;\n return `<${tag}${_attributes(node)}>${text}</${tag}>`;\n }\n\n let result = '';\n let childOffset = offset;\n for (const child of node.children) {\n result += getAnnotatedSource(child, source, childOffset);\n childOffset += child.length;\n }\n return `<${node.kind}${_attributes(node)}>${result}</${node.kind}>`;\n}\n\nfunction _attributes(node: AstNode): string {\n const attrs: Record<string, string> = {};\n if (node instanceof HeadingAstNode) { attrs.level = String(node.level); }\n else if (node instanceof ListAstNode) { attrs.ordered = String(node.ordered); }\n else if (node instanceof CodeBlockAstNode) { if (node.language) { attrs.language = node.language; } }\n else if (node instanceof LinkAstNode) { attrs.url = node.url; }\n else if (node instanceof ImageAstNode) { attrs.alt = node.alt; attrs.url = node.url; }\n else if (node instanceof ListItemAstNode) { if (node.checked !== undefined) { attrs.checked = String(node.checked); } }\n else if (node instanceof GlueAstNode) { if (node.glueKind) { attrs.kind = node.glueKind; } }\n return Object.entries(attrs).map(([k, v]) => ` ${k}=\"${escapeXml(v)}\"`).join('');\n}\n\nfunction escapeXml(str: string): string {\n return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n","/**\n * Adapts a parsed {@link AstNode} tree into the `ast.w` visualization payload\n * consumed by the web AST viewer\n * (`https://microsoft.github.io/vscode-web-editor-text-tools/?editor=ast-viewer`).\n *\n * The tree is dense and ordered — every node's `length` is the sum of its\n * children's lengths and siblings are contiguous — so source offsets are just a\n * running cursor threaded through a depth-first walk. No offset table or\n * per-node length arithmetic is needed beyond advancing past leaf text.\n */\n\nimport {\n AstNode, CodeBlockAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, LinkAstNode,\n ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode, TextAstNode, ThematicBreakAstNode,\n} from './ast.js';\nimport { tokenize } from './_micromarkAdapter.js';\n\nexport interface AstVisualizationNode {\n label: string;\n range: [start: number, endExclusive: number];\n children?: AstVisualizationNode[];\n}\n\nexport interface AstVisualization {\n $fileExtension: 'ast.w';\n source: string;\n root: AstVisualizationNode;\n}\n\nfunction _label(n: AstNode): string {\n if (n instanceof TextAstNode) { return `text ${JSON.stringify(n.content)}`; }\n if (n instanceof GlueAstNode) { return `glue${n.glueKind ? `(${n.glueKind})` : ''} ${JSON.stringify(n.content)}`; }\n if (n instanceof MarkerAstNode) { return `marker(${n.markerKind}) ${JSON.stringify(n.content)}`; }\n if (n instanceof ThematicBreakAstNode) { return `thematicBreak ${JSON.stringify(n.content)}`; }\n if (n instanceof HeadingAstNode) { return `heading(level=${n.level})`; }\n if (n instanceof ListAstNode) { return `list(ordered=${n.ordered})`; }\n if (n instanceof ListItemAstNode) { return n.checked === undefined ? 'listItem' : `listItem(checked=${n.checked})`; }\n if (n instanceof CodeBlockAstNode) { return `codeBlock(language=${JSON.stringify(n.language)})`; }\n if (n instanceof MathBlockAstNode) { return 'mathBlock'; }\n if (n instanceof LinkAstNode) { return `link(url=${JSON.stringify(n.url)})`; }\n if (n instanceof ImageAstNode) { return `image(alt=${JSON.stringify(n.alt)}, url=${JSON.stringify(n.url)})`; }\n return n.kind;\n}\n\nconst _objectInstanceIds = new WeakMap<object, number>();\nlet _nextObjectInstanceId = 0;\n\n/**\n * Globally-stable per-object-instance id, assigned in first-seen order across\n * every visualization (AST, view-data, view-node). A single registry — not one\n * per tree — is the whole point: the same object always renders the same `#N`,\n * so you can correlate instances across the different trees and across edits.\n */\nexport function objectInstanceId(n: object): number {\n let id = _objectInstanceIds.get(n);\n if (id === undefined) { id = _nextObjectInstanceId++; _objectInstanceIds.set(n, id); }\n return id;\n}\n\nexport function visualizeAst(root: AstNode, source: string): AstVisualization {\n let pos = 0;\n function walk(n: AstNode): AstVisualizationNode {\n const start = pos;\n const kids = n.children;\n let children: AstVisualizationNode[] | undefined;\n if (kids.length === 0) {\n pos += n.length;\n } else {\n children = kids.map(walk);\n }\n const label = `${_label(n)} #${objectInstanceId(n)} nid=${n.id}`;\n return { label, range: [start, pos], children };\n }\n return { $fileExtension: 'ast.w', source, root: walk(root) };\n}\n\n/**\n * Adapts the raw micromark token stream into the same `ast.w` visualization\n * payload, as a flat list (no nesting): one child per event, in document order.\n * This is the input the {@link visualizeAst} tree is built from, so showing both\n * side by side makes the parser's tokens → AST step inspectable.\n *\n * Both `enter` and `exit` events are emitted — the open/close structure is the\n * one piece of micromark's information that is NOT derivable from a flat list of\n * ranges (tokens can share a range, and ranges alone don't disambiguate nesting\n * order). Everything else a token carries is here too: its type, its\n * `[start, end)` range, and the source slice that range covers (so the length,\n * which the AST view derives, is visible directly).\n */\nexport function visualizeTokens(source: string): AstVisualization {\n const children: AstVisualizationNode[] = [];\n for (const ev of tokenize(source)) {\n const text = source.substring(ev.startOffset, ev.endOffset);\n children.push({\n label: `${ev.type} ${ev.tokenType} ${JSON.stringify(text)}`,\n range: [ev.startOffset, ev.endOffset],\n });\n }\n const root: AstVisualizationNode = {\n label: `events (${children.length})`,\n range: [0, source.length],\n children,\n };\n return { $fileExtension: 'ast.w', source, root };\n}\n","import { observableValue, derived } from '@vscode/observables';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport { StringValue } from '../core/stringValue.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { Selection } from '../core/selection.js';\nimport { MarkdownParser } from '../parser/parser.js';\nimport type { BlockAstNode, DocumentAstNode } from '../parser/ast.js';\n\nexport const NO_ACTIVE_BLOCKS = Symbol('NO_ACTIVE_BLOCKS');\n\nexport class EditorModel {\n\tprivate readonly _parser = new MarkdownParser();\n\n\t/**\n\t * The most recent edit applied to {@link sourceText}, used by\n\t * {@link document} to let the parser link incrementally edited code\n\t * blocks. Only trusted when it exactly bridges the previous and current\n\t * source text (see {@link document}).\n\t */\n\tprivate _pendingEdit: { baseText: string; newText: string; edit: StringEdit } | undefined;\n\n\treadonly sourceText = observableValue<StringValue>(this, new StringValue(''));\n\t/**\n\t * The current selection, or `undefined` when the editor has no caret\n\t * (e.g. an inactive/unfocused rendering).\n\t */\n\treadonly selection = observableValue<Selection | undefined>(this, Selection.collapsed(0));\n\n\t/**\n\t * Forces the rendered active-block set. `undefined` (the default)\n\t * derives the set from the current selection range (see\n\t * {@link activeBlocks}). The sentinel {@link NO_ACTIVE_BLOCKS} forces\n\t * \"no active block\" — useful in fixtures that always want the\n\t * collapsed/inactive rendering.\n\t */\n\treadonly activeBlocksOverride = observableValue<readonly BlockAstNode[] | typeof NO_ACTIVE_BLOCKS | undefined>(this, undefined);\n\n\treadonly cursorOffset = derived(this, reader =>\n\t\treader.readObservable(this.selection)?.active,\n\t);\n\n\t/**\n\t * The parsed document. Threads the previous document into the parser so\n\t * unchanged blocks keep their object identity across reparses (see\n\t * {@link MarkdownParser.parse}). Writing `previous` inside the compute is\n\t * a safe optimization: `derived` only recomputes when `sourceText`\n\t * changes, and the result is structurally identical to a full reparse.\n\t */\n\treadonly document = (() => {\n\t\tlet previous: DocumentAstNode | undefined;\n\t\tlet previousText: string | undefined;\n\t\treturn derived(this, reader => {\n\t\t\tconst text = reader.readObservable(this.sourceText);\n\t\t\tconst pending = this._pendingEdit;\n\t\t\tconst edit = pending && pending.baseText === previousText && pending.newText === text.value\n\t\t\t\t? pending.edit\n\t\t\t\t: undefined;\n\t\t\tconst next = this._parser.parse(text, previous, edit);\n\t\t\tprevious = next;\n\t\t\tpreviousText = text.value;\n\t\t\treturn next;\n\t\t});\n\t})();\n\n\t/**\n\t * Block that contains the cursor (selection's active end). Used by\n\t * cursor navigation to know which block's marker ranges count as\n\t * visible. Unaffected by {@link activeBlocksOverride} because\n\t * navigation is independent of rendering.\n\t */\n\treadonly activeBlock = derived(this, reader => {\n\t\tconst doc = reader.readObservable(this.document);\n\t\tconst cursor = reader.readObservable(this.cursorOffset);\n\t\tif (cursor === undefined) { return undefined; }\n\t\treturn findBlockAtOffset(doc, cursor);\n\t});\n\n\t/**\n\t * All blocks whose source range intersects the current selection.\n\t * The rendering side uses this to decide which blocks render in\n\t * their expanded (markers-visible) form. When the selection is\n\t * collapsed this is a one-element set holding {@link activeBlock}.\n\t */\n\treadonly activeBlocks = derived(this, reader => {\n\t\tconst override = reader.readObservable(this.activeBlocksOverride);\n\t\tif (override === NO_ACTIVE_BLOCKS) { return new Set<BlockAstNode>(); }\n\t\tif (override !== undefined) { return new Set<BlockAstNode>(override); }\n\t\tconst doc = reader.readObservable(this.document);\n\t\tconst sel = reader.readObservable(this.selection);\n\t\tif (sel === undefined) { return new Set<BlockAstNode>(); }\n\t\treturn new Set<BlockAstNode>(blocksIntersecting(doc, sel.range.start, sel.range.endExclusive));\n\t});\n\n\tapplyEdit(edit: StringEdit): void {\n\t\tconst oldText = this.sourceText.get();\n\t\tconst newText = new StringValue(edit.apply(oldText.value));\n\t\tconst sel = this.selection.get() ?? Selection.collapsed(0);\n\t\tconst newActive = edit.mapOffset(sel.active);\n\t\tthis._pendingEdit = { baseText: oldText.value, newText: newText.value, edit };\n\t\tthis.sourceText.set(newText, undefined);\n\t\tthis.selection.set(Selection.collapsed(newActive), undefined);\n\t}\n\n\tapplyEditForSelection(edit: StringEdit): void {\n\t\tconst oldText = this.sourceText.get();\n\t\tconst newText = new StringValue(edit.apply(oldText.value));\n\t\tconst sel = this.selection.get() ?? Selection.collapsed(0);\n\t\tconst newCursor = edit.mapOffset(sel.range.endExclusive);\n\t\tthis._pendingEdit = { baseText: oldText.value, newText: newText.value, edit };\n\t\tthis.sourceText.set(newText, undefined);\n\t\tthis.selection.set(Selection.collapsed(newCursor), undefined);\n\t}\n}\n\nfunction findBlockAtOffset(doc: DocumentAstNode, offset: SourceOffset): BlockAstNode | undefined {\n\tlet pos = 0;\n\tlet lastBlock: BlockAstNode | undefined;\n\tfor (const child of doc.children) {\n\t\tconst end = pos + child.length;\n\t\tif (doc.blocks.includes(child as BlockAstNode)) {\n\t\t\tif (pos <= offset && offset < end) {\n\t\t\t\treturn child as BlockAstNode;\n\t\t\t}\n\t\t\tif (end === offset) {\n\t\t\t\tlastBlock = child as BlockAstNode;\n\t\t\t}\n\t\t}\n\t\tpos = end;\n\t}\n\treturn lastBlock;\n}\n\n/**\n * All blocks whose source range intersects `[start, endExclusive]`. A\n * collapsed range (start === endExclusive) matches the block containing\n * that offset (with the same boundary rule as {@link findBlockAtOffset}).\n */\nfunction blocksIntersecting(doc: DocumentAstNode, start: SourceOffset, endExclusive: SourceOffset): BlockAstNode[] {\n\tif (start === endExclusive) {\n\t\tconst b = findBlockAtOffset(doc, start);\n\t\treturn b ? [b] : [];\n\t}\n\tconst out: BlockAstNode[] = [];\n\tlet pos = 0;\n\tfor (const child of doc.children) {\n\t\tconst end = pos + child.length;\n\t\tif (doc.blocks.includes(child as BlockAstNode) && pos < endExclusive && end > start) {\n\t\t\tout.push(child as BlockAstNode);\n\t\t}\n\t\tpos = end;\n\t}\n\treturn out;\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Point2D, Rect2D } from '../core/geometry.js';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport type { ViewNode } from './content/viewNode.js';\n\n/**\n * Geometry of the rendered document, as a map from source offsets to 2D\n * positions and back.\n *\n * Structure (top to bottom):\n *\n * VisualLineMap = ordered list of VisualLines\n * VisualLine = a horizontal band [rect.top, rect.bottom) split\n * into one or more VisualRuns\n * VisualRun = a contiguous source range painted at a rectangle\n * on the line\n *\n * Invariants:\n * - `lines[i].rect.bottom <= lines[i+1].rect.top + ε`\n * - For any offset `o` covered by some run on line `L`:\n * `xAtOffset(o)` is inside that run's horizontal range\n * `xAtOffset(o)` is inside `L.rect.left..L.rect.right`\n *\n * The \"map\" goes both ways:\n * - SourceOffset → (line, x) via {@link lineIndexOfOffset} + {@link xAtOffset}\n * - Point2D → SourceOffset via {@link offsetAtPoint}\n *\n * Both directions are total but not bijective: many offsets at a line\n * boundary map to the same `x`, and large areas of the document\n * (padding, gaps) map onto the nearest offset on the nearest line.\n *\n * Rendering a caret rect from these primitives is a consumer concern:\n *\n * const i = map.lineIndexOfOffset(o);\n * const caretRect = map.lineRect(i).withZeroWidthAt(map.xAtOffset(o));\n */\nexport class VisualLineMap {\n\tstatic readonly EMPTY = new VisualLineMap([]);\n\n\tstatic measure(blockViews: readonly { readonly absoluteStart: number; readonly viewNode: ViewNode }[]): VisualLineMap {\n\t\treturn _measure(blockViews);\n\t}\n\n\tconstructor(readonly lines: readonly VisualLine[]) { }\n\n\tget lineCount(): number { return this.lines.length; }\n\tget isEmpty(): boolean { return this.lines.length === 0; }\n\n\tlineRect(lineIndex: number): Rect2D {\n\t\treturn this.lines[lineIndex].rect;\n\t}\n\n\t// ---- SourceOffset → ... -------------------------------------------\n\n\t/**\n\t * Line whose runs cover the offset, or the nearest line by source\n\t * distance if no run covers it.\n\t *\n\t * An offset that is only a run's *trailing* boundary (`offset ===\n\t * endExclusive`) — most notably the source offset just past a\n\t * line-breaking `\\n`, which a zero-width run reports as its end on the line\n\t * it terminates — belongs to the START of the NEXT line instead. Preferring\n\t * the line that actually *starts* the offset makes the caret advance past a\n\t * newline to the next line rather than collapsing onto the previous line's\n\t * end (which would render two distinct offsets at the same caret position).\n\t * The first such trailing-boundary line is remembered as a fallback for the\n\t * document's very last offset, where no later line starts it.\n\t */\n\tlineIndexOfOffset(offset: SourceOffset): number {\n\t\tlet endBoundaryLine = -1;\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tconst membership = this.lines[i].offsetMembership(offset);\n\t\t\tif (membership === 'covers') { return i; }\n\t\t\tif (membership === 'end' && endBoundaryLine < 0) { endBoundaryLine = i; }\n\t\t}\n\t\tif (endBoundaryLine >= 0) { return endBoundaryLine; }\n\n\t\tlet bestIdx = 0;\n\t\tlet bestDist = Infinity;\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tconst dist = this.lines[i].sourceDistanceTo(offset);\n\t\t\tif (dist < bestDist) { bestDist = dist; bestIdx = i; }\n\t\t}\n\t\treturn bestIdx;\n\t}\n\n\t/**\n\t * x of the caret position before `offset`, on the line returned by\n\t * {@link lineIndexOfOffset}. Returns `0` when the map is empty.\n\t */\n\txAtOffset(offset: SourceOffset): number {\n\t\tif (this.lines.length === 0) { return 0; }\n\t\treturn this.lines[this.lineIndexOfOffset(offset)].xAtOffset(offset);\n\t}\n\n\t// ---- Point2D → ... -------------------------------------------------\n\n\t/**\n\t * Line whose vertical band contains `y`, clamped to the first/last\n\t * line when `y` is outside the document.\n\t */\n\tlineIndexAtY(y: number): number {\n\t\tif (this.lines.length === 0) { return 0; }\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tif (y < this.lines[i].rect.bottom) { return i; }\n\t\t}\n\t\treturn this.lines.length - 1;\n\t}\n\n\t/**\n\t * Snap a 2D point to the nearest source offset. Uses `y` to pick a\n\t * line, then `x` to pick an offset within it. Up/down navigation\n\t * uses {@link offsetInLineAtX} directly to preserve desired column.\n\t */\n\toffsetAtPoint(point: Point2D): SourceOffset {\n\t\treturn this.offsetInLineAtX(this.lineIndexAtY(point.y), point.x);\n\t}\n\n\t/** Snap `x` to the nearest offset on a specific line. */\n\toffsetInLineAtX(lineIndex: number, x: number): SourceOffset {\n\t\tif (lineIndex < 0 || lineIndex >= this.lines.length) { return 0; }\n\t\treturn this.lines[lineIndex].offsetAtX(x);\n\t}\n}\n\n/**\n * One visual line of rendered text: a horizontal band\n * (`rect.top`..`rect.bottom`) split into one or more {@link VisualRun}s\n * arranged left-to-right.\n */\nexport class VisualLine {\n\tconstructor(\n\t\treadonly rect: Rect2D,\n\t\treadonly runs: readonly VisualRun[],\n\t) { }\n\n\tcontainsOffset(offset: SourceOffset): boolean {\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.containsOffset(offset)) { return true; }\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * How `offset` relates to this line's runs:\n\t * - `'covers'`: a run starts at or strictly contains the offset\n\t * (`start <= offset < endExclusive`) — the caret belongs on this line.\n\t * - `'end'`: the offset is only some run's trailing boundary\n\t * (`offset === endExclusive`) with no run covering it — a line-break\n\t * boundary the caret should leave for the next line.\n\t * - `'none'`: no run touches the offset.\n\t */\n\toffsetMembership(offset: SourceOffset): 'covers' | 'end' | 'none' {\n\t\tlet end = false;\n\t\tfor (const run of this.runs) {\n\t\t\tif (offset >= run.sourceStart && offset < run.sourceEndExclusive) { return 'covers'; }\n\t\t\tif (offset === run.sourceEndExclusive) { end = true; }\n\t\t}\n\t\treturn end ? 'end' : 'none';\n\t}\n\n\t/**\n\t * Min `|offset - r|` over offsets `r` in any of this line's runs. Used\n\t * to pick the nearest line when no run actually covers the offset.\n\t */\n\tsourceDistanceTo(offset: SourceOffset): number {\n\t\tlet best = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tconst d = run.sourceDistanceTo(offset);\n\t\t\tif (d < best) { best = d; }\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * x of the caret position before `offset` on this line. When `offset`\n\t * is past all runs (trailing whitespace / blank line), returns the\n\t * right edge of the last run; when before all runs, returns the left\n\t * edge of the first run.\n\t */\n\txAtOffset(offset: SourceOffset): number {\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.containsOffset(offset)) { return run.xAtOffset(offset); }\n\t\t}\n\t\t// `runs` is non-empty by construction (`_measure.flush` and any\n\t\t// hand-built line in tests).\n\t\tconst first = this.runs[0];\n\t\tif (offset <= first.sourceStart) { return first.rect.left; }\n\t\treturn this.runs[this.runs.length - 1].rect.right;\n\t}\n\n\t/**\n\t * Snap `x` to the nearest offset on this line. If `x` falls inside a\n\t * run, the offset is interpolated by character fraction; otherwise it\n\t * snaps to the closer edge of the nearest run.\n\t */\n\toffsetAtX(x: number): SourceOffset {\n\t\tif (this.runs.length === 0) { return 0; }\n\n\t\tlet bestRun = this.runs[0];\n\t\tlet bestDist = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.rect.containsX(x) || x === run.rect.right) {\n\t\t\t\treturn run.offsetAtX(x);\n\t\t\t}\n\t\t\tconst dist = Math.min(Math.abs(x - run.rect.left), Math.abs(x - run.rect.right));\n\t\t\tif (dist < bestDist) { bestDist = dist; bestRun = run; }\n\t\t}\n\t\treturn x <= bestRun.rect.left\n\t\t\t? bestRun.sourceRange.start\n\t\t\t: bestRun.sourceRange.endExclusive;\n\t}\n}\n\n/**\n * The DOM source of a {@link VisualRun}. When set, `xAtOffset` and\n * `offsetAtX` measure exact glyph positions via `Range.getBoundingClientRect`\n * instead of linear interpolation across the run's rect. This matters for\n * proportional fonts where character widths differ a lot (e.g. `m` vs `i`)\n * and a caret placed by interpolation lands several pixels inside the\n * wrong character.\n *\n * Hand-built runs (tests) omit this; their `xAtOffset` falls back to\n * linear interpolation.\n */\nexport interface VisualRunSource {\n\treadonly textNode: Text;\n\t/** Offset within `textNode.data` corresponding to `sourceRange.start`. */\n\treadonly textNodeStart: number;\n}\n\n/**\n * One contiguous run of text painted on a single visual line.\n *\n * When constructed with a {@link VisualRunSource}, `xAtOffset` returns the\n * pixel-exact x of the caret before character `offset` by measuring the\n * prefix `[textNodeStart, textNodeStart + (offset - sourceStart))` with a\n * DOM `Range`. Without a source it falls back to linear interpolation\n * across `rect.width`.\n */\nexport class VisualRun {\n\tconstructor(\n\t\treadonly sourceRange: OffsetRange,\n\t\treadonly rect: Rect2D,\n\t\treadonly source?: VisualRunSource,\n\t) { }\n\n\tget sourceStart(): SourceOffset { return this.sourceRange.start; }\n\tget sourceEndExclusive(): SourceOffset { return this.sourceRange.endExclusive; }\n\tget sourceLength(): number { return this.sourceRange.length; }\n\n\tcontainsOffset(offset: SourceOffset): boolean {\n\t\treturn offset >= this.sourceStart && offset <= this.sourceEndExclusive;\n\t}\n\n\tsourceDistanceTo(offset: SourceOffset): number {\n\t\tif (offset < this.sourceStart) { return this.sourceStart - offset; }\n\t\tif (offset > this.sourceEndExclusive) { return offset - this.sourceEndExclusive; }\n\t\treturn 0;\n\t}\n\n\txAtOffset(offset: SourceOffset): number {\n\t\tif (this.sourceLength === 0) { return this.rect.left; }\n\t\tif (this.source) {\n\t\t\treturn _xAtTextOffset(this.source.textNode, this.source.textNodeStart + (offset - this.sourceStart), this.rect.left);\n\t\t}\n\t\tconst fraction = (offset - this.sourceStart) / this.sourceLength;\n\t\treturn this.rect.left + fraction * this.rect.width;\n\t}\n\n\toffsetAtX(x: number): SourceOffset {\n\t\tif (this.rect.width <= 0) { return this.sourceStart; }\n\t\tif (this.source) {\n\t\t\tconst localOffset = _offsetAtX(this.source.textNode, this.source.textNodeStart, this.source.textNodeStart + this.sourceLength, x);\n\t\t\treturn this.sourceStart + (localOffset - this.source.textNodeStart);\n\t\t}\n\t\tconst fraction = (x - this.rect.left) / this.rect.width;\n\t\treturn this.sourceStart + Math.round(fraction * this.sourceLength);\n\t}\n}\n\n/**\n * x position of the caret before character `textOffset` in `textNode`.\n * Uses the right edge of the preceding character (or the left edge of\n * the run if `textOffset` is at the run's start).\n */\nfunction _xAtTextOffset(textNode: Text, textOffset: number, fallbackLeft: number): number {\n\tif (textOffset <= 0) { return fallbackLeft; }\n\tconst range = document.createRange();\n\trange.setStart(textNode, textOffset - 1);\n\trange.setEnd(textNode, textOffset);\n\tconst rect = range.getBoundingClientRect();\n\tif (rect.width === 0 && rect.height === 0) { return fallbackLeft; }\n\treturn rect.right;\n}\n\n/**\n * Snap `x` to a character boundary in `textNode[start..end]` via binary\n * search on per-character rects. Returns an offset in `[start, end]`.\n */\nfunction _offsetAtX(textNode: Text, start: number, end: number, x: number): number {\n\tconst range = document.createRange();\n\tlet bestOffset = start;\n\tlet bestDist = Infinity;\n\tfor (let i = start; i < end; i++) {\n\t\trange.setStart(textNode, i);\n\t\trange.setEnd(textNode, i + 1);\n\t\tconst rect = range.getBoundingClientRect();\n\t\tif (rect.width === 0 && rect.height === 0) { continue; }\n\t\tconst mid = (rect.left + rect.right) / 2;\n\t\t// Pick the edge of this character closest to x.\n\t\tconst dLeft = Math.abs(x - rect.left);\n\t\tconst dRight = Math.abs(x - rect.right);\n\t\tif (dLeft < bestDist) { bestDist = dLeft; bestOffset = i; }\n\t\tif (dRight < bestDist) { bestDist = dRight; bestOffset = i + 1; }\n\t\t// Early-exit: if x is inside this char, pick the closer edge.\n\t\tif (x >= rect.left && x <= rect.right) {\n\t\t\treturn x < mid ? i : i + 1;\n\t\t}\n\t}\n\treturn bestOffset;\n}\n\n// ---------- measurement ------------------------------------------------\n\n/**\n * Walk a DOM Text leaf and return rects in CSS-pixel client coordinates,\n * expanded vertically to the parent element's line-height so caret height\n * matches the visual line box (with leading), not just the glyph height.\n */\nfunction _measure(\n\tblockViews: readonly { readonly absoluteStart: number; readonly viewNode: ViewNode }[],\n): VisualLineMap {\n\tconst rawRuns: VisualRun[] = [];\n\n\tfor (const view of blockViews) {\n\t\tconst runsBefore = rawRuns.length;\n\t\tview.viewNode.forEachTextLeaf(view.absoluteStart, (leaf, leafOffset) => {\n\t\t\tconst textNode = leaf.dom as Text;\n\t\t\tif (textNode.length === 0) { return; }\n\n\t\t\tconst range = document.createRange();\n\t\t\trange.selectNodeContents(textNode);\n\t\t\tconst rects = range.getClientRects();\n\t\t\tif (rects.length === 0) { return; }\n\n\t\t\tconst lineBoxHeight = _lineBoxHeight(textNode);\n\n\t\t\tif (rects.length === 1) {\n\t\t\t\trawRuns.push(new VisualRun(\n\t\t\t\t\tOffsetRange.fromTo(leafOffset, leafOffset + textNode.length),\n\t\t\t\t\t_expandToLineBox(rects[0], lineBoxHeight),\n\t\t\t\t\t{ textNode, textNodeStart: 0 },\n\t\t\t\t));\n\t\t\t} else {\n\t\t\t\tconst breakOffsets = _findLineBreakOffsets(textNode, rects);\n\t\t\t\tfor (let i = 0; i < rects.length; i++) {\n\t\t\t\t\tconst start = i === 0 ? 0 : breakOffsets[i - 1];\n\t\t\t\t\tconst end = i < breakOffsets.length ? breakOffsets[i] : textNode.length;\n\t\t\t\t\trawRuns.push(new VisualRun(\n\t\t\t\t\t\tOffsetRange.fromTo(leafOffset + start, leafOffset + end),\n\t\t\t\t\t\t_expandToLineBox(rects[i], lineBoxHeight),\n\t\t\t\t\t\t{ textNode, textNodeStart: start },\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (rawRuns.length === runsBefore) {\n\t\t\t_appendElementBlockRun(rawRuns, view.viewNode, view.absoluteStart);\n\t\t}\n\t}\n\n\trawRuns.sort((a, b) => a.rect.y - b.rect.y || a.rect.x - b.rect.x);\n\n\tconst lines: VisualLine[] = [];\n\tlet currentRuns: VisualRun[] = [];\n\tlet currentY = -Infinity;\n\tlet currentHeight = 0;\n\tlet currentLeft = Infinity;\n\tlet currentRight = -Infinity;\n\n\tconst flush = (): void => {\n\t\tif (currentRuns.length === 0) { return; }\n\t\tlines.push(new VisualLine(\n\t\t\tRect2D.fromPointPoint(currentLeft, currentY, currentRight, currentY + currentHeight),\n\t\t\tcurrentRuns,\n\t\t));\n\t};\n\n\tfor (const run of rawRuns) {\n\t\tconst r = run.rect;\n\t\t// A run joins the current line only if it overlaps the current line band\n\t\t// by more than half the (smaller) height. Comparing against the current\n\t\t// bottom alone fails when glyph rects are taller than the line advance\n\t\t// (e.g. wrapped headings whose 43px rects advance only 40px), which would\n\t\t// otherwise collapse every wrapped line into one.\n\t\tconst overlap = Math.min(currentY + currentHeight, r.y + r.height) - Math.max(currentY, r.y);\n\t\tconst sameLine = currentRuns.length > 0 && overlap > Math.min(currentHeight, r.height) / 2;\n\t\tif (!sameLine) {\n\t\t\tflush();\n\t\t\tcurrentRuns = [run];\n\t\t\tcurrentY = r.y;\n\t\t\tcurrentHeight = r.height;\n\t\t\tcurrentLeft = r.left;\n\t\t\tcurrentRight = r.right;\n\t\t} else {\n\t\t\tcurrentRuns.push(run);\n\t\t\tcurrentHeight = Math.max(currentHeight, r.y + r.height - currentY);\n\t\t\tcurrentLeft = Math.min(currentLeft, r.left);\n\t\t\tcurrentRight = Math.max(currentRight, r.right);\n\t\t}\n\t}\n\tflush();\n\n\treturn new VisualLineMap(lines);\n}\n\nfunction _findLineBreakOffsets(textNode: Text, rects: DOMRectList): number[] {\n\tconst breaks: number[] = [];\n\tconst range = document.createRange();\n\n\tfor (let r = 0; r < rects.length - 1; r++) {\n\t\tconst nextY = rects[r + 1].y;\n\t\tlet lo = r === 0 ? 0 : breaks[r - 1];\n\t\tlet hi = textNode.length;\n\n\t\twhile (lo < hi) {\n\t\t\tconst mid = (lo + hi) >>> 1;\n\t\t\trange.setStart(textNode, mid);\n\t\t\trange.setEnd(textNode, Math.min(mid + 1, textNode.length));\n\t\t\tconst charRect = range.getBoundingClientRect();\n\t\t\tif (charRect.y < nextY - 1) {\n\t\t\t\tlo = mid + 1;\n\t\t\t} else {\n\t\t\t\thi = mid;\n\t\t\t}\n\t\t}\n\t\tbreaks.push(lo);\n\t}\n\n\treturn breaks;\n}\n\nfunction _lineBoxHeight(textNode: Text): number {\n\tconst parent = textNode.parentElement;\n\tif (!parent) { return 0; }\n\tconst cs = getComputedStyle(parent);\n\tlet lineHeight = parseFloat(cs.lineHeight);\n\tif (!isFinite(lineHeight)) {\n\t\t// `normal` — approximate as 1.2 * font-size, matching browser defaults.\n\t\tlineHeight = parseFloat(cs.fontSize) * 1.2;\n\t}\n\treturn lineHeight;\n}\n\nfunction _expandToLineBox(rect: DOMRect, lineBoxHeight: number): Rect2D {\n\tif (lineBoxHeight <= rect.height) {\n\t\treturn Rect2D.fromPointSize(rect.x, rect.y, rect.width, rect.height);\n\t}\n\tconst leading = (lineBoxHeight - rect.height) / 2;\n\treturn Rect2D.fromPointSize(rect.x, rect.y - leading, rect.width, lineBoxHeight);\n}\n\n/**\n * A block that renders as a non-text element (an inactive `<hr>` thematic\n * break, a KaTeX math block, a standalone image) yields no text leaf, so it\n * would contribute no {@link VisualLine}. Without one, the next block's lines\n * shift up and stepping the caret off such a block onto the following block\n * does not advance its line index — two distinct source offsets render at the\n * same caret position. Give the block one run spanning its whole source range\n * at the element's box so it occupies a line like any text block, keeping line\n * indices stable across its active (text) ↔ inactive (element) renderings. The\n * run carries no {@link VisualRunSource}, so x within it is interpolated — fine,\n * since the caret only ever lands inside the block in its active (text) form.\n */\nfunction _appendElementBlockRun(rawRuns: VisualRun[], viewNode: ViewNode, absoluteStart: number): void {\n\tconst dom = viewNode.dom;\n\tif (dom.nodeType !== 1 /* ELEMENT_NODE */) { return; }\n\tconst rect = (dom as Element).getBoundingClientRect();\n\tif (rect.width === 0 && rect.height === 0) { return; }\n\trawRuns.push(new VisualRun(\n\t\tOffsetRange.fromTo(absoluteStart, absoluteStart + viewNode.sourceLength),\n\t\tRect2D.fromPointSize(rect.x, rect.y, rect.width, rect.height),\n\t));\n}\n","import { derived, observableValue } from '@vscode/observables';\nimport type { BlockAstNode } from '../parser/ast.js';\nimport type { ViewNode } from '../view/content/viewNode.js';\nimport { VisualLineMap } from '../view/visualLineMap.js';\n\n/**\n * One block's place in the rendered document.\n *\n * `height` is in CSS pixels. It is either a real DOM measurement\n * (`isMeasured: true`) or an estimate produced when the block is not\n * currently mounted (`isMeasured: false`). Estimates exist so virtual\n * rendering can size the scroll container without mounting every block.\n *\n * `visualLineMap` and `viewNode` are set only when the block is mounted\n * and measured. Cursor positioning, selection painting and up/down\n * navigation read through `visualLineMap`; the debug view walks\n * `viewNode` to enumerate text leaves for per-character introspection.\n * Unmeasured blocks have neither.\n */\nexport interface BlockMeasurement {\n readonly block: BlockAstNode;\n readonly absoluteStart: number;\n readonly height: number;\n readonly isMeasured: boolean;\n readonly visualLineMap: VisualLineMap | undefined;\n readonly viewNode: ViewNode | undefined;\n}\n\n/**\n * The set of measurements/estimates the view has produced for the current\n * document. This is the \"view → derived facts about layout\" channel: the\n * view writes here as a side effect of rendering and measuring; the\n * controller (and selection/cursor rendering) reads from here.\n *\n * Keeping these facts in their own observable model — instead of as ad-hoc\n * fields on the view — preserves the invariant\n *\n * view(model + Δ) = view(model) + Δ\n *\n * i.e. the view becomes a pure function of (EditorModel, MeasuredLayoutModel).\n * Everything else that depends on layout (controller, commands) goes\n * through this model and never touches view fields directly.\n */\nexport class MeasuredLayoutModel {\n readonly measurements = observableValue<readonly BlockMeasurement[]>(this, []);\n\n /**\n * Concatenated visual line map across all mounted blocks. Lines are\n * left in DOM (client-coordinate) y order — each per-block map already\n * uses absolute client coordinates from `getClientRects()`, so the\n * concatenation is well-formed without re-sorting.\n */\n readonly visualLineMap = derived(this, reader => {\n const ms = reader.readObservable(this.measurements);\n const lines = ms.flatMap(m => m.visualLineMap?.lines ?? []);\n return new VisualLineMap(lines);\n });\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { MarkerAstNode, type BlockAstNode, type DocumentAstNode, type ListAstNode, type AstNode } from '../parser/ast.js';\n\n/**\n * Move the cursor one position left or right, skipping over hidden marker\n * ranges in inactive blocks (and inactive items of an active list).\n */\nexport function nextCursorPosition(\n doc: DocumentAstNode,\n activeBlock: BlockAstNode | undefined,\n cursor: number,\n direction: 'left' | 'right',\n): number {\n let target = direction === 'right' ? cursor + 1 : cursor - 1;\n\n let blockStart = 0;\n for (const child of doc.children) {\n const isBlock = doc.blocks.includes(child as BlockAstNode);\n if (isBlock) {\n const block = child as BlockAstNode;\n const ranges = hiddenRangesFor(block, block === activeBlock, cursor - blockStart);\n target = applySkip(target, blockStart, ranges, direction);\n }\n blockStart += child.length;\n }\n\n if (direction === 'right') { return Math.min(target, doc.length); }\n return Math.max(target, 0);\n}\n\nfunction hiddenRangesFor(block: BlockAstNode, isActive: boolean, relCursor: number): readonly OffsetRange[] {\n if (!isActive) { return collectMarkerRanges(block); }\n if (block.kind === 'list') {\n const activeItemIndex = findActiveListItemIndex(block, relCursor);\n return collectListHiddenRanges(block, activeItemIndex);\n }\n return [];\n}\n\nfunction applySkip(target: number, blockStart: number, ranges: readonly OffsetRange[], direction: 'left' | 'right'): number {\n if (direction === 'right') {\n for (const range of ranges) {\n const rel = target - blockStart;\n if (range.contains(rel) || range.start === rel) {\n target = blockStart + range.endExclusive;\n }\n }\n } else {\n for (let i = ranges.length - 1; i >= 0; i--) {\n const range = ranges[i];\n const rel = target - blockStart;\n if (range.contains(rel) || range.endExclusive === rel) {\n target = blockStart + range.start;\n }\n }\n }\n return target;\n}\n\nexport function findActiveListItemIndex(list: ListAstNode, cursorOffset: number): number | undefined {\n let pos = 0;\n let boundaryFallback: number | undefined;\n for (let i = 0; i < list.children.length; i++) {\n const child = list.children[i];\n const end = pos + child.length;\n const itemIdx = list.items.indexOf(child as never);\n if (itemIdx >= 0) {\n // Prefer the item that actually contains the offset. An offset that\n // sits exactly on the boundary between two items belongs to the item\n // that *starts* there, so the preceding item (which merely ends\n // there) is only used as a fallback for the very end of the list.\n if (pos <= cursorOffset && cursorOffset < end) {\n return itemIdx;\n }\n if (end === cursorOffset) {\n boundaryFallback = itemIdx;\n }\n }\n pos = end;\n }\n return boundaryFallback;\n}\n\nfunction collectListHiddenRanges(list: ListAstNode, activeItemIndex: number | undefined): OffsetRange[] {\n const ranges: OffsetRange[] = [];\n let listOffset = 0;\n for (const listChild of list.children) {\n const itemIdx = list.items.indexOf(listChild as never);\n if (itemIdx >= 0 && itemIdx !== activeItemIndex) {\n const item = list.items[itemIdx];\n walkCollectMarkerRanges(item, listOffset, ranges);\n }\n listOffset += listChild.length;\n }\n ranges.sort((a, b) => a.start - b.start);\n return ranges;\n}\n\nfunction collectMarkerRanges(block: BlockAstNode): OffsetRange[] {\n const ranges: OffsetRange[] = [];\n walkCollectMarkerRanges(block, 0, ranges);\n ranges.sort((a, b) => a.start - b.start);\n return ranges;\n}\n\nfunction walkCollectMarkerRanges(node: AstNode, offset: number, ranges: OffsetRange[]): void {\n if (node.children.length === 0) {\n if (node instanceof MarkerAstNode) {\n ranges.push(OffsetRange.ofStartAndLength(offset, node.length));\n }\n return;\n }\n\n switch (node.kind) {\n case 'codeBlock':\n case 'mathBlock': {\n let childOffset = offset;\n for (const child of node.children) {\n if (child instanceof MarkerAstNode && (child.markerKind === 'openFence' || child.markerKind === 'closeFence')) {\n ranges.push(OffsetRange.ofStartAndLength(childOffset, child.length));\n }\n childOffset += child.length;\n }\n return;\n }\n case 'inlineCode':\n case 'inlineMath': {\n let childOffset = offset;\n for (const child of node.children) {\n if (child instanceof MarkerAstNode && (child.markerKind === 'openMarker' || child.markerKind === 'closeMarker')) {\n ranges.push(OffsetRange.ofStartAndLength(childOffset, child.length));\n }\n childOffset += child.length;\n }\n return;\n }\n case 'thematicBreak':\n return;\n case 'image': {\n ranges.push(OffsetRange.ofStartAndLength(offset, node.length));\n return;\n }\n }\n\n let childOffset = offset;\n for (const child of node.children) {\n walkCollectMarkerRanges(child, childOffset, ranges);\n childOffset += child.length;\n }\n}\n","import { findWordBoundaryLeft, findWordBoundaryRight } from '../core/wordUtils.js';\nimport type { CursorCommand, VisualCursorCommand } from './types.js';\n\nexport const cursorRight: CursorCommand = (ctx) => {\n\tif (!ctx.selection.isCollapsed) {\n\t\treturn ctx.selection.range.endExclusive;\n\t}\n\treturn Math.min(ctx.selection.active + 1, ctx.text.length);\n};\n\nexport const cursorLeft: CursorCommand = (ctx) => {\n\tif (!ctx.selection.isCollapsed) {\n\t\treturn ctx.selection.range.start;\n\t}\n\treturn Math.max(ctx.selection.active - 1, 0);\n};\n\nexport const cursorMoveRight: CursorCommand = (ctx) =>\n\tMath.min(ctx.selection.active + 1, ctx.text.length);\n\nexport const cursorMoveLeft: CursorCommand = (ctx) =>\n\tMath.max(ctx.selection.active - 1, 0);\n\nexport const cursorWordRight: CursorCommand = (ctx) =>\n\tfindWordBoundaryRight(ctx.text, ctx.selection.active);\n\nexport const cursorWordLeft: CursorCommand = (ctx) =>\n\tfindWordBoundaryLeft(ctx.text, ctx.selection.active);\n\nexport const cursorLineStart: CursorCommand = (ctx) =>\n\tctx.text.lastIndexOf('\\n', ctx.selection.active - 1) + 1;\n\nexport const cursorLineEnd: CursorCommand = (ctx) => {\n\tconst idx = ctx.text.indexOf('\\n', ctx.selection.active);\n\treturn idx === -1 ? ctx.text.length : idx;\n};\n\nexport const cursorDocumentStart: CursorCommand = () => 0;\n\nexport const cursorDocumentEnd: CursorCommand = (ctx) => ctx.text.length;\n\nexport const cursorDown: VisualCursorCommand = (ctx) => {\n\tconst lineIdx = ctx.lineMap.lineIndexOfOffset(ctx.selection.active);\n\tconst x = ctx.desiredColumn ?? ctx.lineMap.xAtOffset(ctx.selection.active);\n\tif (lineIdx >= ctx.lineMap.lineCount - 1) {\n\t\treturn { offset: ctx.selection.active, desiredColumn: x };\n\t}\n\treturn { offset: ctx.lineMap.offsetInLineAtX(lineIdx + 1, x), desiredColumn: x };\n};\n\nexport const cursorUp: VisualCursorCommand = (ctx) => {\n\tconst lineIdx = ctx.lineMap.lineIndexOfOffset(ctx.selection.active);\n\tconst x = ctx.desiredColumn ?? ctx.lineMap.xAtOffset(ctx.selection.active);\n\tif (lineIdx <= 0) {\n\t\treturn { offset: ctx.selection.active, desiredColumn: x };\n\t}\n\treturn { offset: ctx.lineMap.offsetInLineAtX(lineIdx - 1, x), desiredColumn: x };\n};\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Selection } from '../core/selection.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { findWordBoundaryLeft, findWordBoundaryRight } from '../core/wordUtils.js';\nimport { nextCursorPosition } from '../model/cursorNavigation.js';\nimport type { EditCommand } from './types.js';\n\nexport const deleteLeft: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active === 0) { return undefined; }\n\tconst deleteRange = new OffsetRange(nextCursorPosition(ctx.document, ctx.activeBlock, sel.active, 'left'), sel.active);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(deleteRange.start),\n\t};\n};\n\nexport const deleteRight: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active >= ctx.text.length) { return undefined; }\n\tconst deleteRange = new OffsetRange(sel.active, nextCursorPosition(ctx.document, ctx.activeBlock, sel.active, 'right'));\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(deleteRange.start),\n\t};\n};\n\nexport const deleteWordLeft: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active === 0) { return undefined; }\n\tconst boundary = findWordBoundaryLeft(ctx.text, sel.active);\n\tconst deleteRange = new OffsetRange(boundary, sel.active);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(boundary),\n\t};\n};\n\nexport const deleteWordRight: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active >= ctx.text.length) { return undefined; }\n\tconst boundary = findWordBoundaryRight(ctx.text, sel.active);\n\tconst deleteRange = new OffsetRange(sel.active, boundary);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(sel.active),\n\t};\n};\n\nexport function insertText(text: string): EditCommand {\n\treturn (ctx) => {\n\t\tconst edit = StringEdit.replace(ctx.selection.range, text);\n\t\tconst newOffset = ctx.selection.range.start + text.length;\n\t\treturn {\n\t\t\tedit,\n\t\t\tselection: Selection.collapsed(newOffset),\n\t\t};\n\t};\n}\n\nexport const insertParagraph: EditCommand = (ctx) => {\n\tconst edit = StringEdit.replace(ctx.selection.range, '\\n\\n');\n\tconst newOffset = ctx.selection.range.start + 2;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n\nexport const insertLineBreak: EditCommand = (ctx) => {\n\tconst edit = StringEdit.replace(ctx.selection.range, '\\n');\n\tconst newOffset = ctx.selection.range.start + 1;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n\n/**\n * A Markdown hard line break: a `\\n` whose preceding line ends with two spaces.\n * Any spaces already trailing the insertion point count toward the two, so the\n * line never accumulates more than the two needed to form the break.\n */\nexport const insertHardLineBreak: EditCommand = (ctx) => {\n\tconst start = ctx.selection.range.start;\n\tlet existingSpaces = 0;\n\twhile (existingSpaces < 2 && ctx.text[start - 1 - existingSpaces] === ' ') { existingSpaces++; }\n\tconst padding = ' '.repeat(2 - existingSpaces);\n\tconst inserted = padding + '\\n';\n\tconst edit = StringEdit.replace(ctx.selection.range, inserted);\n\tconst newOffset = start + inserted.length;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Selection } from '../core/selection.js';\nimport { findWordAt } from '../core/wordUtils.js';\nimport type { CursorCommandContext, SelectionCommand } from './types.js';\n\nexport const selectAll: SelectionCommand = (ctx) =>\n\tnew Selection(0, ctx.text.length);\n\nexport const selectWord: SelectionCommand = (_ctx, offset) => {\n\tconst word = findWordAt(_ctx.text, offset);\n\treturn new Selection(word.start, word.end);\n};\n\nexport function selectBlock(ctx: CursorCommandContext, blockRange: OffsetRange): Selection {\n\treturn new Selection(blockRange.start, blockRange.endExclusive);\n}\n","import { Disposable } from '@vscode/observables';\nimport type { AstNode } from '../../parser/ast.js';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { DomPosition } from './dom.js';\n\nexport type { DomPosition } from './dom.js';\n\n/**\n * Reverse index: the DOM node a view node renders → the view node. Written only\n * in the {@link ViewNode} constructor, so it always reflects the live tree (a\n * reused subtree keeps its entries; a rebuilt node overwrites its own). It lets\n * a hit-test result (an arbitrary DOM node deep inside, e.g. a KaTeX element)\n * be walked up via {@link ViewNode.forDom} to the closest owning view node\n * without scanning the tree.\n */\nconst _domToViewNode = new WeakMap<globalThis.Node, ViewNode>();\n\n/**\n * Parent pointers, maintained incrementally: a node sets itself as the parent\n * of each of its children in its constructor. Because construction is\n * bottom-up and a reused subtree is never re-constructed, the only write per\n * frame is re-pointing each rebuilt node's direct children — O(reconciled\n * region), never the whole tree.\n */\nconst _parentOf = new WeakMap<ViewNode, ViewNode | undefined>();\n\n/**\n * Immutable view of an AST node. Pairs `ast` with its rendered `dom` and a\n * mirror of `ast.children` as ViewNode children. Source offsets are NEVER\n * stored — they are recomputed by walking and summing `ast.length` of\n * preceding siblings, just like the AST itself.\n *\n * Leaves are ViewNodes with no children. A leaf whose `dom` is a Text node\n * participates in source mapping; a leaf whose `dom` is an Element does not\n * (e.g. KaTeX-rendered math, or `<hr>` for a thematic break).\n */\nexport class ViewNode extends Disposable {\n private _children: readonly ViewNode[];\n\n constructor(\n readonly ast: AstNode,\n readonly dom: globalThis.Node,\n children: readonly ViewNode[] = _emptyChildren,\n ) {\n super();\n this._children = children;\n _domToViewNode.set(dom, this);\n for (const child of children) { _parentOf.set(child, this); }\n }\n\n /** This node's view children (a mirror of `ast.children`). */\n get children(): readonly ViewNode[] { return this._children; }\n\n /**\n * Replace this node's children in place, disposing the old ones and\n * re-pointing the new ones' parent to this node. The node value is still\n * conceptually immutable with respect to its `ast`/`dom` *identity*; this\n * is used only when a node patches its own DOM subtree in place (a code\n * block re-tokenising on a highlighter recolour), where the source-mapping\n * leaves must follow the new DOM text nodes without rebuilding the node\n * itself.\n */\n protected _replaceChildren(children: readonly ViewNode[]): void {\n for (const child of this._children) { child.dispose(); }\n this._children = children;\n for (const child of children) { _parentOf.set(child, this); }\n }\n\n dispose(): void {\n for (const child of this._children) { child.dispose(); }\n }\n\n /**\n * The number of source characters this node spans. Defaults to the length\n * of its {@link ast}; a synthetic leaf that subdivides one ast node (a\n * decorated-whitespace character, a code-block token span) shares that ast\n * for identity but overrides this with the length of its own slice, so the\n * renderer never has to fabricate an AST node just to carry a length.\n */\n get sourceLength(): number { return this.ast.length; }\n\n /**\n * The DOM node a parent mounts for this child. It is {@link dom} for almost\n * everything; a marker is the exception — its `dom` is the inner Text node\n * (so source ↔ DOM mapping lands on it) while the node it mounts is the\n * wrapping `<span>`.\n */\n get mountNode(): globalThis.Node { return this.dom; }\n\n /** The view node that rendered this node's parent, or `undefined` for a root. */\n get parent(): ViewNode | undefined { return _parentOf.get(this); }\n\n /**\n * Closest view node owning `domNode`: the node itself if registered, else\n * the nearest registered ancestor. Returns `undefined` if the DOM node is\n * outside any view tree.\n */\n static forDom(domNode: globalThis.Node | null): ViewNode | undefined {\n for (let n: globalThis.Node | null = domNode; n; n = n.parentNode) {\n const vn = _domToViewNode.get(n);\n if (vn) { return vn; }\n }\n return undefined;\n }\n\n /**\n * This node's start offset within its parent's local source space: the sum\n * of the `ast.length` of the siblings before it. Polymorphic via\n * {@link _localOffsetOfChild} so a parent whose children do not map\n * linearly (e.g. it hides or reorders some) can override how its children\n * are placed.\n */\n localOffsetInParent(): number {\n const p = this.parent;\n return p ? p._localOffsetOfChild(this) : 0;\n }\n\n /** Start offset of `child` within this node's local source space. */\n protected _localOffsetOfChild(child: ViewNode): number {\n let offset = 0;\n for (const c of this.children) {\n if (c === child) { return offset; }\n offset += c.sourceLength;\n }\n return offset;\n }\n\n /**\n * Map a DOM hit that lands on THIS node's own representation into a source\n * range in this node's local space `[0, ast.length)`. Polymorphic: a text\n * leaf maps the caret offset 1:1; an element-only node (KaTeX math, `<hr>`,\n * an image, a hidden marker) has no internal text mapping and snaps to its\n * start by default — subclasses may override (e.g. to snap to the nearer\n * edge by x).\n */\n getLocalSourceRange(pos: DomPosition): OffsetRange {\n if (this.dom === pos.node && this.dom.nodeType === 3 /* TEXT_NODE */) {\n return OffsetRange.emptyAt(Math.max(0, Math.min(pos.offset, this.sourceLength)));\n }\n return OffsetRange.emptyAt(0);\n }\n\n /**\n * DOM hit (any node + offset within it) → source offset relative to THIS\n * node, or `undefined` when the hit is outside this node's subtree. Enters\n * the tree at the closest owning view node ({@link forDom}), maps the hit\n * into that node's local space ({@link getLocalSourceRange}), then lifts the\n * range up the parent chain — adding each node's {@link localOffsetInParent} —\n * until it reaches this node.\n */\n resolveSource(pos: DomPosition): number | undefined {\n let node: ViewNode | undefined = ViewNode.forDom(pos.node);\n if (!node) { return undefined; }\n let range = node.getLocalSourceRange(pos);\n while (node !== this) {\n const p: ViewNode | undefined = node.parent;\n if (!p) { return undefined; }\n range = range.delta(node.localOffsetInParent());\n node = p;\n }\n return range.start;\n }\n\n /**\n * Source offset → DOM position. `nodeOffset` is the absolute source\n * offset of THIS node's start. Returns a position into a DOM Text node,\n * descending into children based on accumulated lengths.\n */\n sourceToDom(localSourceOffset: number, nodeSourceOffset: number = 0): DomPosition | undefined {\n if (localSourceOffset < nodeSourceOffset || localSourceOffset > nodeSourceOffset + this.sourceLength) {\n return undefined;\n }\n if (this.children.length === 0) {\n if (this.dom.nodeType === 3 /* TEXT_NODE */) {\n return { node: this.dom as Text, offset: localSourceOffset - nodeSourceOffset };\n }\n return undefined;\n }\n let childOffset = nodeSourceOffset;\n for (const child of this.children) {\n const childEnd = childOffset + child.sourceLength;\n if (localSourceOffset >= childOffset && localSourceOffset <= childEnd) {\n const result = child.sourceToDom(localSourceOffset, childOffset);\n if (result) { return result; }\n }\n childOffset = childEnd;\n }\n return undefined;\n }\n\n /** Visit every text-bearing leaf in this subtree with its absolute offset. */\n forEachTextLeaf(nodeOffset: number, visitor: (leaf: ViewNode, leafOffset: number) => void): void {\n if (this.children.length === 0) {\n if (this.dom.nodeType === 3 /* TEXT_NODE */) {\n visitor(this, nodeOffset);\n }\n return;\n }\n let childOffset = nodeOffset;\n for (const child of this.children) {\n child.forEachTextLeaf(childOffset, visitor);\n childOffset += child.sourceLength;\n }\n }\n}\n\nconst _emptyChildren: readonly ViewNode[] = [];\n\n","import katex from 'katex';\nimport { transaction, runOnChange } from '@vscode/observables';\nimport type { IDisposable } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { AstNode, BlockAstNode, ListItemAstNode, MarkerAstNode } from '../../parser/ast.js';\nimport { CodeBlockAstNode } from '../../parser/ast.js';\nimport type {\n\tAnyViewData, CodeBlockViewData, GlueViewData, HeadingViewData, ImageViewData,\n\tInlineCodeViewData, InlineMathViewData, LinkViewData, ListViewData, ListItemViewData,\n\tMarkerViewData, MathBlockViewData, TableRowViewData, TextViewData, ThematicBreakViewData,\n} from '../viewData.js';\nimport type { ISyntaxHighlighter, ISyntaxHighlighterDocument, Token } from '../../highlighter/syntaxHighlighter.js';\nimport { ViewNode } from './viewNode.js';\n\nexport interface BlockViewOptions {\n\treadonly renderCustomCodeBlock?: (language: string, content: string) => HTMLElement | undefined;\n\treadonly onToggleCheckbox?: (item: ListItemAstNode, newChecked: boolean) => void;\n\t/**\n\t * Opens a link's URL. Called when the user activates a link: a plain click\n\t * while the link's block is inactive (rendered), or a Ctrl/Cmd+click while it\n\t * is active (source shown). Defaults to `window.open(url, '_blank')`.\n\t */\n\treadonly onOpenLink?: (url: string, event: MouseEvent) => void;\n\t/**\n\t * Colours fenced code blocks. When set, a code block's content is rendered\n\t * as a sequence of token spans instead of one plain text node. This is the\n\t * non-incremental path: the snapshot is read once at render time.\n\t */\n\treadonly syntaxHighlighter?: ISyntaxHighlighter;\n\t/**\n\t * Pluggable renderer for the *inactive* (rendered) form of a math node —\n\t * both `$$…$$` blocks and inline `$…$`. When set and it returns a result,\n\t * its {@link MathRendering.dom} replaces the default opaque `katex.render`\n\t * output, and its {@link MathRendering.segments} let parts of the rendered\n\t * math (e.g. individual identifier glyphs) map back to source ranges so the\n\t * caret can land inside them. Returning `undefined` falls back to the\n\t * default whole-node KaTeX leaf. The active (source) form is unaffected.\n\t *\n\t * This is the seam used to explore in-place editing of rendered math (see\n\t * `katexEditableIdentifiers.ts`).\n\t */\n\treadonly renderMath?: (request: MathRenderRequest) => MathRendering | undefined;\n}\n\n/** Input to a {@link BlockViewOptions.renderMath} renderer. */\nexport interface MathRenderRequest {\n\t/** The LaTeX source of the math content (without the `$$`/`$` fences). */\n\treadonly latex: string;\n\t/** `true` for a `$$…$$` block, `false` for inline `$…$`. */\n\treadonly displayMode: boolean;\n\t/** CSS class the host element must carry (editor styling/measurement hooks). */\n\treadonly className: string;\n\t/** Full source length of the math node (fences/`$` included). */\n\treadonly nodeLength: number;\n\t/** Offset of {@link latex} within the node (i.e. after the opening fence/`$`). */\n\treadonly contentStart: number;\n}\n\n/**\n * A span of the rendered math output that maps to a slice of source. The\n * renderer reports these for the parts it can map (e.g. identifier glyphs);\n * the editor tiles the gaps between them so the whole math node stays mapped.\n */\nexport interface MathSourceSegment {\n\t/** A DOM node (ideally a Text node) within the rendered output. */\n\treadonly dom: globalThis.Node;\n\t/** Start offset of the mapped slice, relative to the math node's start. */\n\treadonly start: number;\n\t/** Source length of the mapped slice. */\n\treadonly length: number;\n}\n\n/** Result of a {@link BlockViewOptions.renderMath} renderer. */\nexport interface MathRendering {\n\t/** Host element to mount (the rendered math output). */\n\treadonly dom: HTMLElement;\n\t/** Source-mapped spans within {@link dom} (need not tile the whole node). */\n\treadonly segments: readonly MathSourceSegment[];\n}\n\n/**\n * Base view node for everything the editor renders, generic over the\n * {@link AnyViewData view-data} it renders so subclasses get a precisely-typed\n * {@link data} (e.g. `BlockViewNode<HeadingViewData>`). Every view-data kind has\n * a subclass whose constructor builds the node's DOM and, recursively,\n * constructs its child view nodes — so *constructing a node is rendering it*.\n * There is no separate render pass: the view tree is the result of construction,\n * and {@link createViewNode} is the single entry point that turns a `ViewData`\n * into a node (reusing a `previous` node untouched when it still matches).\n *\n * The name is historical — it is the base for inline and leaf nodes too — but\n * top-level blocks are always instances of it, and {@link element}/{@link block}\n * are the conveniences {@link EditorView} uses for those.\n */\nexport class BlockViewNode<T extends AnyViewData = AnyViewData> extends ViewNode {\n\tconstructor(\n\t\treadonly data: T,\n\t\tdom: globalThis.Node,\n\t\tchildren: readonly ViewNode[],\n\t) {\n\t\tsuper(data.ast, dom, children);\n\t}\n\n\tget block(): BlockAstNode { return this.data.ast as BlockAstNode; }\n\tget element(): HTMLElement { return this.dom as HTMLElement; }\n\n\t/**\n\t * Whether this already-built node can stand in for `data` unchanged. The\n\t * builder preserves view-data identity for any subtree whose ast and\n\t * selection-derived flags are unchanged (see `buildDocumentViewData`), so a\n\t * single identity check captures \"nothing in my subtree changed\" — and its\n\t * whole subtree, and any session it owns, are kept as-is.\n\t */\n\tcanReuse(data: AnyViewData): boolean {\n\t\treturn this.data === data;\n\t}\n\n\t/**\n\t * Called by the view after this block is mounted and measured, with the\n\t * block's rendered height in px. The default is a no-op; subclasses whose\n\t * active/inactive renderings have different intrinsic heights (e.g. a math\n\t * block) override this to remember a height to reserve across the toggle.\n\t */\n\trecordMeasuredHeight(_height: number): void { /* no-op */ }\n}\n\n/**\n * Turn a {@link AnyViewData view-data} node into its view node, reusing\n * `previous` when it still renders the very same view-data object (see\n * {@link BlockViewNode.canReuse}). Otherwise the matching subclass is\n * constructed, which renders it and recursively constructs its children —\n * threading `previous` down so an edited node can adopt its predecessor's DOM\n * (and, for an edited {@link CodeBlockAstNode}, the highlighting session of the\n * node it was derived from).\n *\n * On a rebuild `previous` is the view node {@link pairNodes} paired by stable id:\n * identity-matched nodes (same view-data) short-circuit above, an edited node is\n * paired with the node carrying its previous id, and any previous node whose id\n * is gone is dropped (disposed by its container's reconcile) so its replacement\n * is built with `previous === undefined`.\n */\nexport function createViewNode(data: AnyViewData, options: BlockViewOptions | undefined, previous?: ViewNode): ViewNode {\n\tif (previous instanceof BlockViewNode) {\n\t\tif (previous.canReuse(data)) {\n\t\t\treturn previous;\n\t\t}\n\t} else if (previous?.ast === data.ast) {\n\t\treturn previous;\n\t}\n\n\tswitch (data.kind) {\n\t\tcase 'text': return _textLeaf(data, _prev(previous, LeafViewNode));\n\t\tcase 'marker': return data.ast.markerKind === 'hardBreak'\n\t\t\t? new HardBreakViewNode(data, _prev(previous, HardBreakViewNode))\n\t\t\t: new MarkerViewNode(data, _prev(previous, MarkerViewNode));\n\t\tcase 'glue': return new GlueViewNode(data, _prev(previous, GlueViewNode));\n\t\tcase 'heading': return new HeadingViewNode(data, options, _prev(previous, HeadingViewNode));\n\t\tcase 'paragraph': return new ContainerViewNode(data, 'p', 'md-block md-paragraph', options, _prevContainer(previous));\n\t\tcase 'codeBlock': return new CodeBlockViewNode(data, options, previous);\n\t\tcase 'mathBlock': return new MathBlockViewNode(data, options, _prev(previous, MathBlockViewNode));\n\t\tcase 'thematicBreak': return new ThematicBreakViewNode(data, options, _prev(previous, ThematicBreakViewNode));\n\t\tcase 'blockQuote': return new ContainerViewNode(data, 'blockquote', 'md-block md-blockquote', options, _prevContainer(previous));\n\t\tcase 'list': return new ListViewNode(data, options, _prev(previous, ListViewNode));\n\t\tcase 'listItem': return new ListItemViewNode(data, options, _prev(previous, ListItemViewNode));\n\t\tcase 'table': return new ContainerViewNode(data, 'table', 'md-block md-table', options, _prevContainer(previous));\n\t\tcase 'tableRow': return new TableRowViewNode(data, options, _prev(previous, TableRowViewNode));\n\t\tcase 'tableCell': return new ContainerViewNode(data, 'td', '', options, _prevContainer(previous));\n\t\tcase 'strong': return new ContainerViewNode(data, 'strong', '', options, _prevContainer(previous));\n\t\tcase 'emphasis': return new ContainerViewNode(data, 'em', '', options, _prevContainer(previous));\n\t\tcase 'strikethrough': return new ContainerViewNode(data, 'del', '', options, _prevContainer(previous));\n\t\tcase 'inlineCode': return new InlineCodeViewNode(data, options, _prev(previous, InlineCodeViewNode));\n\t\tcase 'inlineMath': return new InlineMathViewNode(data, options, _prev(previous, InlineMathViewNode));\n\t\tcase 'link': return new LinkViewNode(data, options, _prev(previous, LinkViewNode));\n\t\tcase 'image': return new ImageViewNode(data, options, _prev(previous, ImageViewNode));\n\t\tcase 'document': return new ContainerViewNode(data, 'div', '', options, _prevContainer(previous));\n\t}\n}\n\n/** Narrow `previous` to a specific view-node subclass, or `undefined`. */\nfunction _prev<V extends ViewNode>(previous: ViewNode | undefined, ctor: new (...args: never[]) => V): V | undefined {\n\treturn previous instanceof ctor ? previous : undefined;\n}\n\n/** Narrow `previous` to a {@link ContainerViewNode}, or `undefined`. */\nfunction _prevContainer(previous: ViewNode | undefined): ContainerViewNode | undefined {\n\treturn previous instanceof ContainerViewNode ? previous : undefined;\n}\n\n/**\n * Build the view children for `childData` and patch `parentDom`'s child DOM in\n * place to match, in one step. Each new child-data is paired with the previous\n * view child that should render it ({@link pairNodes}) — by stable node id, which\n * covers both unchanged subtrees and edited nodes — so DOM and session adoption\n * carry over; the\n * `build` callback turns `(childData, prev)` into its view node (usually via\n * {@link createViewNode}). Previous children left unpaired are disposed, then\n * {@link _patchDomChildren} reorders/inserts/removes `parentDom`'s children so\n * the DOM matches the new view nodes — moving reused child DOM into place\n * rather than re-creating it. The returned array mirrors `childData` 1:1,\n * preserving the source ↔ DOM mapping invariant.\n */\nexport function reconcileDomChildren(\n\tparentDom: globalThis.Node,\n\tchildData: readonly AnyViewData[],\n\tpreviousChildren: readonly ViewNode[] | undefined,\n\tbuild: (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode,\n): ViewNode[] {\n\tconst { paired, unused } = pairNodes(childData, previousChildren ?? _NO_CHILDREN);\n\tconst children = childData.map(d => build(d, paired.get(d)));\n\tfor (const u of unused) { u.dispose(); }\n\t_patchDomChildren(parentDom, children);\n\treturn children;\n}\n\n/**\n * Make `parent`'s child DOM nodes match `children`'s {@link ViewNode.mountNode}s\n * in order. The overwhelmingly common case — the DOM is already correct (a\n * no-op frame, or a rebuild that only reused nodes) — is detected by a linear\n * scan up front and returns without touching the DOM at all. Otherwise it\n * reorders/inserts/removes in place from where they first diverge: only nodes\n * that actually move are touched, so a node the selection lives in is left\n * attached and the cursor survives (a `replaceChildren` swap would detach every\n * child and collapse the selection).\n */\nfunction _patchDomChildren(parent: globalThis.Node, children: readonly ViewNode[]): void {\n\t_patchDomNodes(parent, children.map(c => c.mountNode));\n}\n\n/**\n * Like {@link _patchDomChildren} but over raw mount nodes, so a caller can mount\n * a mix of view-node DOM and synthetic wrappers (e.g. a list item's gutter\n * span) in place without detaching the nodes that stay put.\n */\nexport function _patchDomNodes(parent: globalThis.Node, nodes: readonly globalThis.Node[]): void {\n\tlet domCursor: ChildNode | null = parent.firstChild;\n\tlet i = 0;\n\tfor (; i < nodes.length; i++) {\n\t\tif (domCursor !== nodes[i]) { break; }\n\t\tdomCursor = domCursor!.nextSibling;\n\t}\n\tif (i === nodes.length && domCursor === null) {\n\t\treturn; // already in the right order — nothing to do\n\t}\n\tfor (; i < nodes.length; i++) {\n\t\tconst node = nodes[i];\n\t\tif (domCursor === node) {\n\t\t\tdomCursor = node.nextSibling;\n\t\t} else {\n\t\t\tparent.insertBefore(node, domCursor);\n\t\t}\n\t}\n\twhile (domCursor) {\n\t\tconst toRemove = domCursor;\n\t\tdomCursor = domCursor.nextSibling;\n\t\tparent.removeChild(toRemove);\n\t}\n}\n\n/** Default child builder: render each child-data, threading `prev`. */\nfunction _buildChild(options: BlockViewOptions | undefined): (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode {\n\treturn (childData, prev) => createViewNode(childData, options, prev);\n}\n\n/**\n * Child builder for inline containers whose `content` marker must be a bare\n * Text node (no wrapping `<span>`), e.g. inline code / math: the content is\n * rendered as a {@link LeafViewNode} over a Text node so its characters map\n * directly. Every other child renders normally.\n */\nfunction _inlineChild(options: BlockViewOptions | undefined): (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode {\n\treturn (childData, prev) => {\n\t\tif (childData.kind === 'marker' && childData.ast.markerKind === 'content') {\n\t\t\treturn new LeafViewNode(childData, document.createTextNode(childData.ast.content));\n\t\t}\n\t\treturn createViewNode(childData, options, prev);\n\t};\n}\n\nconst _NO_CHILDREN: readonly ViewNode[] = [];\n\n/** The view-data children of a container node (empty for leaves). */\nfunction _contentOf(data: AnyViewData): readonly AnyViewData[] {\n\treturn 'content' in data ? data.content : _NO_VIEW_CHILDREN;\n}\n\nconst _NO_VIEW_CHILDREN: readonly AnyViewData[] = [];\n\n/**\n * Text leaf. When the active block reveals source, non-obvious whitespace is\n * decorated with visible indicators (see {@link _appendDecorated}); the leaf is\n * then a `<span>` over source-mapped slices. Otherwise it is a bare Text node,\n * reused unchanged when the previous leaf rendered the same string so the node\n * the selection lives in stays attached and the cursor survives.\n */\nfunction _textLeaf(data: TextViewData, previous: LeafViewNode | undefined): ViewNode {\n\tconst content = data.ast.content;\n\tconst ctx: WhitespaceContext = {\n\t\tleftBoundary: data.leftWordBoundary,\n\t\trightBoundary: data.rightWordBoundary,\n\t\tdecorateNewline: true,\n\t};\n\tif (data.showWhitespace && _hasDecoratableWhitespace(content, ctx)) {\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-text';\n\t\tconst children = _appendDecorated(span, content, ctx, data.ast);\n\t\treturn new BlockViewNode(data, span, children);\n\t}\n\tconst prevDom = previous?.dom;\n\tconst dom = prevDom instanceof globalThis.Text && prevDom.data === content\n\t\t? prevDom\n\t\t: document.createTextNode(content);\n\treturn new LeafViewNode(data, dom);\n}\n\n/** A character that is whitespace (space, tab, or a line ending). */\nfunction _isWhitespaceChar(ch: string): boolean {\n\treturn ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r';\n}\n\n/**\n * Context that controls how the whitespace in a string is classified.\n * `leftBoundary`/`rightBoundary` say whether the inline sibling on that side\n * presents visible word content, so a single space at the leaf edge between two\n * words stays obvious. `decorateNewline` is false where a `<br>` already makes\n * the break visible (a hard line break) — the newline then gets no redundant\n * `↵`; elsewhere a source newline is collapsed (e.g. a soft break rendered as a\n * space) and the `↵` reveals the line ending hiding there.\n *\n * `newlineGlyph` switches a decorated newline from a CSS `::before` overlay (on\n * a collapsing `\\n`, whose selectable box ends up beside the glyph rather than\n * under it) to a real `↵` glyph character: a non-whitespace text node that\n * keeps its own width, so the selection box coincides with the glyph and every\n * newline is individually selectable. The trailing newline of the run is left\n * as a literal collapsing `\\n` (no glyph) so the glyph hugs the preceding text\n * without a stray leading space, and the blank-line glyph count is one per\n * blank line. Used for the inter-block gap glue.\n *\n * `breakGlyphClass`, when set, marks the run as a structural block break: its\n * *first* newline is the break that starts the next block and is always painted\n * as a glyph with this class (even when it is also the last/only newline, so it\n * never collapses), giving it a distinct look (blue) from the neutral\n * blank-line glyphs that follow.\n */\ninterface WhitespaceContext {\n\treadonly leftBoundary: boolean;\n\treadonly rightBoundary: boolean;\n\treadonly decorateNewline: boolean;\n\treadonly newlineGlyph?: boolean;\n\treadonly breakGlyphClass?: string;\n}\n\n/** A hard break's `<br>` already shows the line break, so its newline gets no `↵`. */\nconst _HARD_BREAK_WHITESPACE: WhitespaceContext = { leftBoundary: false, rightBoundary: false, decorateNewline: false };\n\n/**\n * An indented code block's structural indentation: every space is leading\n * (no word neighbours), so each is non-obvious and earns a `·` dot when shown.\n */\nconst _CODE_INDENT_WHITESPACE: WhitespaceContext = { leftBoundary: false, rightBoundary: false, decorateNewline: false };\n\n/**\n * A single space is \"obvious\" — and so left undecorated — only when it sits\n * between two non-whitespace characters. The neighbours are this leaf's own\n * characters, or — at the leaf's first/last position — the adjacent inline\n * sibling when it presents visible word content (`leftBoundary`/`rightBoundary`).\n * Leading, trailing and run (2+) spaces are non-obvious and get a visible dot.\n */\nfunction _isObviousSpace(content: string, i: number, ctx: WhitespaceContext): boolean {\n\tconst prevObvious = i > 0 ? !_isWhitespaceChar(content[i - 1]) : ctx.leftBoundary;\n\tconst nextObvious = i < content.length - 1 ? !_isWhitespaceChar(content[i + 1]) : ctx.rightBoundary;\n\treturn prevObvious && nextObvious;\n}\n\n/**\n * The indicator class for the character at `i`, or `undefined` when it needs no\n * indicator (plain text, an obvious space, or a newline whose break is already\n * visible). Single source of truth for both detection and segmentation below.\n */\nfunction _whitespaceClass(content: string, i: number, ctx: WhitespaceContext): string | undefined {\n\tconst ch = content[i];\n\tif (ch === '\\t') { return 'md-ws-tab'; }\n\tif (ch === '\\n' || ch === '\\r') { return ctx.decorateNewline ? 'md-ws-newline' : undefined; }\n\tif (ch === ' ' && !_isObviousSpace(content, i, ctx)) { return 'md-ws-space'; }\n\treturn undefined;\n}\n\n/** Whether `content` contains any whitespace that would be decorated when revealed. */\nfunction _hasDecoratableWhitespace(content: string, ctx: WhitespaceContext): boolean {\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst ch = content[i];\n\t\t// `newlineGlyph` turns a newline into a `↵` glyph even when the inline\n\t\t// `decorateNewline` overlay is off (a trailing block gap), so it counts.\n\t\tif (ctx.newlineGlyph && (ch === '\\n' || ch === '\\r')) { return true; }\n\t\tif (_whitespaceClass(content, i, ctx) !== undefined) { return true; }\n\t}\n\treturn false;\n}\n\ninterface WhitespaceSegment {\n\treadonly text: string;\n\treadonly cls: string | undefined;\n\t/** DOM text to render; defaults to `text`. The source-mapped length still comes from `text`. */\n\treadonly display?: string;\n}\n\n/** Split `content` into plain runs and individually-decorated whitespace characters. */\nfunction _segmentWhitespace(content: string, ctx: WhitespaceContext): WhitespaceSegment[] {\n\tconst segments: WhitespaceSegment[] = [];\n\tlet plainStart = -1;\n\tconst flushPlain = (end: number) => {\n\t\tif (plainStart >= 0) { segments.push({ text: content.slice(plainStart, end), cls: undefined }); plainStart = -1; }\n\t};\n\t// The structural-break newline (the gap's first) is always painted as a glyph\n\t// and never collapses; the trailing newline is the line terminator and stays a\n\t// collapsing `\\n` so the glyph hugs the preceding text with no stray leading space.\n\tconst breakNewline = ctx.breakGlyphClass ? content.indexOf('\\n') : -1;\n\tconst lastNewline = ctx.newlineGlyph ? content.lastIndexOf('\\n') : -1;\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst ch = content[i];\n\t\tif (ctx.newlineGlyph && (ch === '\\n' || ch === '\\r')) {\n\t\t\tconst isBreak = i === breakNewline;\n\t\t\tif (i !== lastNewline || isBreak) {\n\t\t\t\tflushPlain(i);\n\t\t\t\tsegments.push({ text: ch, cls: isBreak ? ctx.breakGlyphClass! : 'md-ws-newline-glyph', display: '↵' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst cls = ctx.newlineGlyph && (ch === '\\n' || ch === '\\r') ? undefined : _whitespaceClass(content, i, ctx);\n\t\tif (cls === undefined) { if (plainStart < 0) { plainStart = i; } continue; }\n\t\tflushPlain(i);\n\t\tsegments.push({ text: ch, cls });\n\t}\n\tflushPlain(content.length);\n\treturn segments;\n}\n\n/**\n * Append `content` to `host`, wrapping each non-obvious whitespace character in\n * a `<span>` whose CSS overlays a visible indicator while the real character\n * stays in the DOM. Returns one source-mapped {@link RawLeafViewNode} per\n * segment, so the slices' lengths sum to `content.length` and source ↔ DOM\n * mapping is unaffected. Every segment shares the enclosing `ast` node (the text\n * or glue leaf whose content this is) for identity and carries the length of\n * its own slice — the renderer never fabricates an AST node.\n */\nfunction _appendDecorated(host: HTMLElement, content: string, ctx: WhitespaceContext, ast: AstNode): ViewNode[] {\n\tconst children: ViewNode[] = [];\n\tfor (const seg of _segmentWhitespace(content, ctx)) {\n\t\tconst text = document.createTextNode(seg.display ?? seg.text);\n\t\tif (seg.cls) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = seg.cls;\n\t\t\tspan.appendChild(text);\n\t\t\thost.appendChild(span);\n\t\t} else {\n\t\t\thost.appendChild(text);\n\t\t}\n\t\t// The DOM may show a glyph (`seg.display`) while the source slice is\n\t\t// `seg.text`; both are length-1, so source ↔ DOM mapping is exact.\n\t\tchildren.push(new RawLeafViewNode(ast, text, _NO_CHILDREN, seg.text.length));\n\t}\n\treturn children;\n}\n\n/** Generic leaf: a single DOM node with no children (text, KaTeX output, `<hr>`, …). */\nclass LeafViewNode extends BlockViewNode {\n\tconstructor(data: AnyViewData, dom: globalThis.Node) {\n\t\tsuper(data, dom, _NO_CHILDREN);\n\t}\n}\n\n/**\n * A leaf over a raw AST node with no view-data of its own — used for synthetic\n * fragments the renderer creates internally (code-block content and its token\n * spans, decorated-whitespace characters), which participate in source mapping\n * but are never reconciled or reused on their own. It shares the enclosing real\n * ast node for identity (the renderer never fabricates AST), so {@link\n * sourceLength} is given explicitly when the fragment is only a slice of that\n * ast's content; it defaults to the full `ast.length` for a whole-content leaf.\n */\nclass RawLeafViewNode extends ViewNode {\n\tprivate readonly _sourceLength: number;\n\tconstructor(ast: AstNode, dom: globalThis.Node, children: readonly ViewNode[] = _NO_CHILDREN, sourceLength: number = ast.length) {\n\t\tsuper(ast, dom, children);\n\t\tthis._sourceLength = sourceLength;\n\t}\n\toverride get sourceLength(): number { return this._sourceLength; }\n}\n\n/**\n * A marker (fence, list bullet, emphasis `*`, table pipe, …). Present in the\n * DOM as `<span class=\"md-marker …\">` wrapping a Text node; the span gains\n * `md-marker-hidden` (→ `display: none`) when markers are hidden, so it leaves\n * layout entirely. The view node's {@link dom} is the inner Text node so source\n * offsets map onto it, while {@link mountNode} is the span the parent mounts.\n */\nclass MarkerViewNode extends BlockViewNode<MarkerViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: MarkerViewData, previous: MarkerViewNode | undefined) {\n\t\tconst marker = data.ast;\n\t\tconst base = `md-marker md-marker-${marker.markerKind}`;\n\t\t// Reuse the previous span + Text node when the rendered string is\n\t\t// unchanged so the node the selection lives in stays attached and the\n\t\t// cursor survives; only the class (which depends on `visible`) is updated.\n\t\tconst reuse = previous && previous.dom instanceof globalThis.Text && previous.dom.data === marker.content;\n\t\tconst span = reuse ? previous._span : document.createElement('span');\n\t\tspan.className = data.visible ? base : `${base} md-marker-hidden`;\n\t\tconst text = reuse ? previous.dom as globalThis.Text : document.createTextNode(marker.content);\n\t\tif (!reuse) { span.appendChild(text); }\n\t\tsuper(data, text, _NO_CHILDREN);\n\t\tthis._span = span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n}\n\n/**\n * Non-semantic syntactic glue: table cell pipes (`| `), the task-list `[x] `\n * source, and other source padding. Rendered like a {@link MarkerViewNode} —\n * a `<span>` wrapping a Text node — but when hidden it keeps its inline width\n * (`visibility: hidden`, via `md-glue-hidden`) instead of leaving layout, so\n * column widths and the checkbox gutter stay stable as markers toggle. When\n * visible, its non-obvious whitespace is decorated with visible indicators\n * (see {@link _appendDecorated}).\n */\nclass GlueViewNode extends BlockViewNode<GlueViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: GlueViewData, previous: GlueViewNode | undefined) {\n\t\tconst built = GlueViewNode._build(data, previous);\n\t\tsuper(data, built.dom, built.children);\n\t\tthis._span = built.span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n\n\tprivate static _build(\n\t\tdata: GlueViewData,\n\t\tprevious: GlueViewNode | undefined,\n\t): { span: HTMLElement; dom: globalThis.Node; children: readonly ViewNode[] } {\n\t\tconst glue = data.ast;\n\t\tconst base = glue.glueKind ? `md-glue md-glue-${glue.glueKind}` : 'md-glue';\n\t\t// Glue has no inline word neighbours; whether its newline gets a `↵`\n\t\t// depends on whether this glue sits in inline flow (decided at build time).\n\t\t// A `blockBreak` additionally paints its first newline as the blue\n\t\t// structural-break glyph (see `breakGlyphClass`).\n\t\tconst isBreak = glue.glueKind === 'blockBreak';\n\t\t// A trailing block gap shows its blank-line newlines as `↵` glyphs purely by\n\t\t// virtue of its kind: `_attachBlockGaps` tags glue `blockGap`/`blockBreak`\n\t\t// only when it absorbs a gap as some block's trailing trivia, so the kind\n\t\t// itself proves \"this is an editable trailing gap\" — no per-block opt-in (an\n\t\t// ambient `inlineFlow`/`decorateNewline`) is needed, and every block type\n\t\t// (table, code, math, heading, …) reveals it uniformly. The hostless\n\t\t// document-level gap (leading the first block) is built always-hidden (see\n\t\t// `buildDocumentViewData`), so it never decorates and `---\\n\\n…` / `---\\n…`\n\t\t// still render identically. `decorateNewline` now governs only the inline\n\t\t// soft-break overlay (`md-ws-newline`) for whitespace inside paragraphs.\n\t\tconst ws: WhitespaceContext = {\n\t\t\tleftBoundary: false,\n\t\t\trightBoundary: false,\n\t\t\tdecorateNewline: data.decorateNewline,\n\t\t\tnewlineGlyph: glue.glueKind === 'blockGap' || isBreak,\n\t\t\tbreakGlyphClass: isBreak ? 'md-ws-blockbreak-glyph' : undefined,\n\t\t};\n\t\tconst decorate = data.visible && _hasDecoratableWhitespace(glue.content, ws);\n\t\tif (decorate) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = base;\n\t\t\tconst children = _appendDecorated(span, glue.content, ws, glue);\n\t\t\treturn { span, dom: span, children };\n\t\t}\n\t\t// Reuse the previous span + Text node when the rendered string is unchanged\n\t\t// so the node the selection lives in stays attached and the cursor survives;\n\t\t// only the class (which depends on `visible`) is updated.\n\t\tconst reuse = previous && previous.dom instanceof globalThis.Text\n\t\t\t&& previous.dom.data === glue.content && previous.children.length === 0;\n\t\tconst span = reuse ? previous._span : document.createElement('span');\n\t\tspan.className = data.visible ? base : `${base} md-glue-hidden`;\n\t\tconst text = reuse ? previous.dom as globalThis.Text : document.createTextNode(glue.content);\n\t\tif (!reuse) { span.appendChild(text); }\n\t\treturn { span, dom: text, children: _NO_CHILDREN };\n\t}\n}\n\n/**\n * A GFM hard line break (`··\\n` or `\\`). Always renders a `<br>` so the line\n * breaks in both the rendered and the source view; the break's source\n * characters (the trailing spaces / backslash and the newline) are revealed —\n * with the same whitespace indicators as everything else — only while the block\n * is active, and otherwise hidden. The source text stays in the DOM either way\n * so source ↔ DOM mapping is unaffected; the `<br>` carries no source length and\n * so is not a child view node.\n */\nclass HardBreakViewNode extends BlockViewNode<MarkerViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: MarkerViewData, _previous: HardBreakViewNode | undefined) {\n\t\tconst content = data.ast.content;\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-hardbreak';\n\t\tconst holder = document.createElement('span');\n\t\tholder.className = data.visible ? 'md-hardbreak-src' : 'md-hardbreak-src md-hardbreak-src-hidden';\n\t\t// The `<br>` already shows the break, so the newline gets no redundant `↵`.\n\t\tconst children = data.visible\n\t\t\t? _appendDecorated(holder, content, _HARD_BREAK_WHITESPACE, data.ast)\n\t\t\t: _appendPlainText(holder, content, data.ast);\n\t\tspan.appendChild(holder);\n\t\tspan.appendChild(document.createElement('br'));\n\t\tsuper(data, span, children);\n\t\tthis._span = span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n}\n\n/** Append `content` as a single Text node and return its source-mapped leaf. */\nfunction _appendPlainText(host: HTMLElement, content: string, ast: AstNode): ViewNode[] {\n\tconst text = document.createTextNode(content);\n\thost.appendChild(text);\n\treturn [new RawLeafViewNode(ast, text)];\n}\n\n/** A plain element container (`<p>`, `<blockquote>`, `<strong>`, `<td>`, …) whose children mirror the node's children. Reuses `previous`'s element when given one (same kind ⇒ same tag), so only its children are reconciled. */\nclass ContainerViewNode<T extends AnyViewData = AnyViewData> extends BlockViewNode<T> {\n\tconstructor(data: T, tag: string, className: string, options: BlockViewOptions | undefined, previous: ContainerViewNode | undefined) {\n\t\tconst el = previous?.element ?? document.createElement(tag);\n\t\t// A reused element already carries this kind's class (same kind ⇒ same\n\t\t// tag ⇒ same className), so only a freshly created one needs it set.\n\t\tif (!previous && className) { el.className = className; }\n\t\tconst children = reconcileDomChildren(el, _contentOf(data), previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\nclass HeadingViewNode extends BlockViewNode<HeadingViewData> {\n\tconstructor(data: HeadingViewData, options: BlockViewOptions | undefined, previous: HeadingViewNode | undefined) {\n\t\tconst reuse = previous && previous.element.tagName === `H${data.ast.level}`;\n\t\tconst el = reuse ? previous.element : document.createElement(`h${data.ast.level}`);\n\t\tif (!reuse) { el.className = 'md-block md-heading'; }\n\t\tconst children = reconcileDomChildren(el, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\n/**\n * A thematic break (`---`). When inactive it renders a non-text `<hr>` leaf\n * whose `sourceLength` is the node's full `ast.length` (the `---` plus any\n * trailing blank-line glue the parser absorbed), so mapping steps over it as a\n * single opaque run. When active it reveals the source as an editable\n * container: a `<div>` whose children mirror the marker (and any trailing glue),\n * so the cursor can land on and edit the `---` like any other source.\n */\nclass ThematicBreakViewNode extends BlockViewNode<ThematicBreakViewData> {\n\tconstructor(data: ThematicBreakViewData, options: BlockViewOptions | undefined, previous: ThematicBreakViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\tconst reuse = previous?.dom instanceof HTMLDivElement ? previous : undefined;\n\t\t\tconst el = reuse?.element ?? document.createElement('div');\n\t\t\tif (!reuse) { el.className = 'md-block md-thematic-break-source'; }\n\t\t\tconst children = reconcileDomChildren(el, data.content, reuse?.children, _buildChild(options));\n\t\t\tsuper(data, el, children);\n\t\t\treturn;\n\t\t}\n\t\tconst hr = document.createElement('hr');\n\t\thr.className = 'md-block md-thematic-break';\n\t\tsuper(data, hr, _NO_CHILDREN);\n\t}\n}\n\n/**\n * A fenced code block. It owns its incremental\n * {@link ISyntaxHighlighterDocument} session: constructing the node creates (or\n * adopts from `previous`) the session, and disposing the node disposes it, so\n * colouring stays incremental across edits — the session is reused and\n * `update`d rather than rebuilt. A node at any depth owns a session; the only\n * difference today is that the parser links `getDiff` for top-level code blocks\n * only, so a nested block currently builds a fresh session on each rebuild.\n */\nexport class CodeBlockViewNode extends BlockViewNode<CodeBlockViewData> {\n\tprivate _session: ISyntaxHighlighterDocument | undefined;\n\t/**\n\t * Subscription that re-tokenises the rendered `<code>` in place whenever the\n\t * session advances its {@link ISyntaxHighlighterDocument.snapshot} *without*\n\t * a source edit (an async grammar finishing, a live recolour). It is tied to\n\t * this node's lifetime, but like {@link _session} it must be disposed\n\t * manually: a node reused as `previous` for a rebuild is never `dispose`d\n\t * (see {@link reconcileDomChildren}), so the rebuilding constructor disposes\n\t * its predecessor's subscription explicitly.\n\t */\n\tprivate _snapshotSub: IDisposable | undefined;\n\n\tconstructor(data: CodeBlockViewData, options: BlockViewOptions | undefined, previous: ViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst content = ast.code?.content ?? '';\n\t\tconst custom = (!data.showMarkup && ast.language && options?.renderCustomCodeBlock)\n\t\t\t? (options.renderCustomCodeBlock(ast.language, content) ?? undefined)\n\t\t\t: undefined;\n\t\tconst highlighter = options?.syntaxHighlighter;\n\t\tconst prevCode = previous instanceof CodeBlockViewNode ? previous : undefined;\n\n\t\t// Adopt `previous`'s session when we can (same block, or an in-content\n\t\t// edit reported by getDiff); otherwise create a fresh one. Any session\n\t\t// on `previous` we do not adopt is disposed.\n\t\tlet session: ISyntaxHighlighterDocument | undefined;\n\t\tif (!custom && highlighter && ast.language) {\n\t\t\tif (prevCode?._session && ast === prevCode.ast) {\n\t\t\t\tsession = prevCode._session;\n\t\t\t\tprevCode._session = undefined;\n\t\t\t} else if (prevCode?._session) {\n\t\t\t\tconst diff = ast.getDiff(prevCode.ast as CodeBlockAstNode);\n\t\t\t\tif (diff) {\n\t\t\t\t\tsession = prevCode._session;\n\t\t\t\t\tprevCode._session = undefined;\n\t\t\t\t\ttransaction(tx => session!.update(diff.stringEdit, tx));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!session) { session = highlighter.create(ast.language, content); }\n\t\t}\n\t\tif (prevCode?._session) { prevCode._session.dispose(); prevCode._session = undefined; }\n\t\t// The predecessor's in-place subscription is bound to its (now discarded)\n\t\t// DOM; drop it before this node installs its own.\n\t\tprevCode?._snapshotSub?.dispose();\n\t\tif (prevCode) { prevCode._snapshotSub = undefined; }\n\n\t\tconst tokens = session\n\t\t\t? session.snapshot.get().getTokens(OffsetRange.ofLength(content.length)).tokens\n\t\t\t: undefined;\n\n\t\tlet dom: HTMLElement;\n\t\tlet children: readonly ViewNode[];\n\t\tlet contentNode: CodeContentViewNode | undefined;\n\t\tif (custom) {\n\t\t\tcustom.classList.add('md-block', 'md-code-block');\n\t\t\tdom = custom;\n\t\t\tchildren = _NO_CHILDREN;\n\t\t} else if (!ast.openFence) {\n\t\t\t// Indented code block: no fences, no language (so no highlighting).\n\t\t\t// The per-line `codeIndent` markers are hideable so the structural\n\t\t\t// indentation drops out of the rendered block when markup is hidden\n\t\t\t// (like a heading's `#`); the `content` markers carry the code text\n\t\t\t// verbatim. Everything tiles one `<code>`; any trailing block glue\n\t\t\t// (a following gap) sits in the `<pre>` after it, as for fences.\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-code-block';\n\t\t\tconst code = document.createElement('code');\n\t\t\tpre.appendChild(code);\n\t\t\tconst kids: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tconst childAst = childData.ast;\n\t\t\t\tif (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'content') {\n\t\t\t\t\tconst text = document.createTextNode((childAst as MarkerAstNode).content);\n\t\t\t\t\tcode.appendChild(text);\n\t\t\t\t\tkids.push(new RawLeafViewNode(childAst, text));\n\t\t\t\t} else if (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'codeIndent') {\n\t\t\t\t\tconst marker = childAst as MarkerAstNode;\n\t\t\t\t\t// When revealed, the structural indentation is all non-obvious\n\t\t\t\t\t// whitespace, so paint each space as a `·` dot (like decorated\n\t\t\t\t\t// inline whitespace); when hidden it collapses to nothing\n\t\t\t\t\t// (`md-marker-hidden`), dedenting the code.\n\t\t\t\t\tif ((childData as MarkerViewData).visible) {\n\t\t\t\t\t\tconst span = document.createElement('span');\n\t\t\t\t\t\tspan.className = 'md-marker md-marker-codeIndent';\n\t\t\t\t\t\tconst leaves = _appendDecorated(span, marker.content, _CODE_INDENT_WHITESPACE, marker);\n\t\t\t\t\t\tcode.appendChild(span);\n\t\t\t\t\t\tkids.push(new RawLeafViewNode(marker, span, leaves));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\t\tcode.appendChild(vn.mountNode);\n\t\t\t\t\t\tkids.push(vn);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tkids.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdom = pre;\n\t\t\tchildren = kids;\n\t\t} else {\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-code-block';\n\t\t\tconst kids: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tif (childData.ast === ast.code) {\n\t\t\t\t\tconst code = document.createElement('code');\n\t\t\t\t\tif (ast.language) { code.className = `language-${CSS.escape(ast.language)}`; }\n\t\t\t\t\tconst built = _buildCodeContent(ast.code, content, code, tokens);\n\t\t\t\t\tif (built instanceof CodeContentViewNode) { contentNode = built; }\n\t\t\t\t\tkids.push(built);\n\t\t\t\t\tpre.appendChild(code);\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tkids.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdom = pre;\n\t\t\tchildren = kids;\n\t\t}\n\n\t\tsuper(data, dom, children);\n\t\tthis._session = session;\n\t\t// Re-tokenise in place on every later snapshot change. `runOnChange`\n\t\t// fires only on *future* changes, so the synchronous `session.update`\n\t\t// above (a source edit) is already reflected and does not re-trigger.\n\t\tif (session && contentNode) {\n\t\t\tthis._snapshotSub = runOnChange(session.snapshot, () => {\n\t\t\t\tconst snapshot = session!.snapshot.get();\n\t\t\t\tcontentNode!.refresh(content, snapshot.getTokens(OffsetRange.ofLength(content.length)).tokens);\n\t\t\t});\n\t\t}\n\t}\n\n\toverride dispose(): void {\n\t\tthis._snapshotSub?.dispose();\n\t\tthis._snapshotSub = undefined;\n\t\tthis._session?.dispose();\n\t\tthis._session = undefined;\n\t\tsuper.dispose();\n\t}\n}\n\n/**\n * The single view node for a code block's content (the `content` marker),\n * mirroring its character length exactly so source ↔ DOM mapping is unaffected.\n * With `tokens` the content is split into coloured token spans under `code`\n * (token leaves as children); without, it is one Text node.\n */\nfunction _buildCodeContent(\n\tcontentAst: MarkerAstNode,\n\tcontent: string,\n\tcode: HTMLElement,\n\ttokens: readonly Token[] | undefined,\n): ViewNode {\n\tif (!tokens) {\n\t\tconst text = document.createTextNode(content);\n\t\tcode.appendChild(text);\n\t\treturn new RawLeafViewNode(contentAst, text);\n\t}\n\treturn new CodeContentViewNode(contentAst, code, content, tokens);\n}\n\n/**\n * The `<code>` content of a syntax-highlighted code block. Its DOM (the token\n * `<span>`s) and its source-mapping token leaves are rebuilt in place by\n * {@link refresh} when the highlighter recolours, so a recolour patches only\n * this subtree's DOM — the surrounding view-node tree (and the editor's\n * measured layout) is untouched.\n */\nclass CodeContentViewNode extends ViewNode {\n\tconstructor(contentAst: MarkerAstNode, code: HTMLElement, content: string, tokens: readonly Token[]) {\n\t\tsuper(contentAst, code, _buildTokenLeaves(contentAst, code, content, tokens));\n\t}\n\n\t/** Re-render the token spans for a new colouring, in place. */\n\trefresh(content: string, tokens: readonly Token[]): void {\n\t\tconst code = this.dom as HTMLElement;\n\t\tcode.replaceChildren();\n\t\tthis._replaceChildren(_buildTokenLeaves(this.ast as MarkerAstNode, code, content, tokens));\n\t}\n}\n\n/**\n * Append the token spans for `content` to `code` and return the per-token\n * source-mapping leaves (each a Text-node leaf carrying its slice length), so\n * the leaves tile `[0, content.length)` exactly.\n */\nfunction _buildTokenLeaves(\n\tcontentAst: MarkerAstNode,\n\tcode: HTMLElement,\n\tcontent: string,\n\ttokens: readonly Token[],\n): ViewNode[] {\n\tconst tokenLeaves: ViewNode[] = [];\n\tlet offset = 0;\n\tfor (const token of tokens) {\n\t\tconst piece = content.slice(offset, offset + token.length);\n\t\toffset += token.length;\n\t\tconst text = document.createTextNode(piece);\n\t\tif (token.className) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tfor (const cls of token.className.split('.')) {\n\t\t\t\tif (cls) { span.classList.add(`tok-${cls}`); }\n\t\t\t}\n\t\t\tspan.appendChild(text);\n\t\t\tcode.appendChild(span);\n\t\t} else {\n\t\t\tcode.appendChild(text);\n\t\t}\n\t\ttokenLeaves.push(new RawLeafViewNode(contentAst, text, _NO_CHILDREN, piece.length));\n\t}\n\treturn tokenLeaves;\n}\n\n/**\n * Relative start offset of the math content (the `content` marker) within a\n * math node's children. Mirrors `CodeBlockAstNode.codeOffset` for math nodes,\n * which do not carry it themselves.\n */\nfunction _mathContentOffset(content: readonly AstNode[]): number {\n\tlet pos = 0;\n\tfor (const c of content) {\n\t\tif (c.kind === 'marker' && (c as MarkerAstNode).markerKind === 'content') { return pos; }\n\t\tpos += c.length;\n\t}\n\treturn pos;\n}\n\n/**\n * Build a fully-tiled child list for an inactive (rendered) math node from the\n * source-mapped {@link MathSourceSegment segments} a {@link BlockViewOptions.renderMath}\n * renderer reported. The segments cover only the spans the renderer could map\n * back to source (e.g. identifier glyphs); the gaps before/between/after them\n * are filled with synthetic filler leaves (a detached, empty Text node carrying\n * only a length) so the children tile the node's whole `[0, nodeLength)` source\n * range in source order. That ordered tiling is what\n * {@link ViewNode.localOffsetInParent}/{@link ViewNode.sourceToDom} rely on to\n * lift a hit on a mapped glyph to the correct absolute source offset; a hit that\n * lands on an unmapped (filler) region simply resolves to the math node's start.\n */\nfunction _buildMathSegmentChildren(ast: AstNode, segments: readonly MathSourceSegment[], nodeLength: number): ViewNode[] {\n\tconst sorted = segments\n\t\t.filter(s => s.length > 0 && s.start >= 0 && s.start + s.length <= nodeLength)\n\t\t.slice()\n\t\t.sort((a, b) => a.start - b.start);\n\tconst children: ViewNode[] = [];\n\tlet pos = 0;\n\tconst filler = (len: number) => {\n\t\tif (len > 0) { children.push(new RawLeafViewNode(ast, document.createTextNode(''), _NO_CHILDREN, len)); }\n\t};\n\tfor (const seg of sorted) {\n\t\tif (seg.start < pos) { continue; } // overlapping segment — skip to keep tiling monotone\n\t\tfiller(seg.start - pos);\n\t\tchildren.push(new RawLeafViewNode(ast, seg.dom, _NO_CHILDREN, seg.length));\n\t\tpos = seg.start + seg.length;\n\t}\n\tfiller(nodeLength - pos);\n\treturn children;\n}\n\nclass MathBlockViewNode extends BlockViewNode<MathBlockViewData> {\n\t/**\n\t * The rendered (inactive, KaTeX) height in px, measured after mount and\n\t * carried forward across rebuilds via `previous`. When the block becomes\n\t * active (source markers shown) this height is reserved as a `min-height`\n\t * so the editor does not collapse below the rendered size, keeping the\n\t * surrounding layout stable as the caret enters and leaves the block.\n\t */\n\tprivate _renderedHeight: number | undefined;\n\n\tconstructor(data: MathBlockViewData, options: BlockViewOptions | undefined, previous: MathBlockViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst remembered = previous?._renderedHeight;\n\t\tif (data.showMarkup) {\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-math-block';\n\t\t\t// Reserve the rendered height measured while inactive so toggling to\n\t\t\t// the source view does not shrink the block (and the layout below it\n\t\t\t// stays put). Only ever grows the box, never clips the source.\n\t\t\t// `border-box` so the reserved (getBoundingClientRect) height — which\n\t\t\t// includes padding — is matched exactly rather than padding-on-padding.\n\t\t\tif (remembered !== undefined) {\n\t\t\t\tpre.style.boxSizing = 'border-box';\n\t\t\t\tpre.style.minHeight = `${remembered}px`;\n\t\t\t}\n\t\t\tconst children: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tif (childData.ast === ast.code) {\n\t\t\t\t\tconst code = document.createElement('code');\n\t\t\t\t\tconst text = document.createTextNode(ast.code.content);\n\t\t\t\t\tcode.appendChild(text);\n\t\t\t\t\tpre.appendChild(code);\n\t\t\t\t\tchildren.push(new RawLeafViewNode(ast.code, text));\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tchildren.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuper(data, pre, children);\n\t\t\tthis._renderedHeight = remembered;\n\t\t\treturn;\n\t\t}\n\t\tconst latex = ast.code?.content ?? '';\n\t\tconst rendering = options?.renderMath?.({\n\t\t\tlatex,\n\t\t\tdisplayMode: true,\n\t\t\tclassName: 'md-block md-math-block',\n\t\t\tnodeLength: ast.length,\n\t\t\tcontentStart: _mathContentOffset(ast.content),\n\t\t});\n\t\tif (rendering) {\n\t\t\tsuper(data, rendering.dom, _buildMathSegmentChildren(ast, rendering.segments, ast.length));\n\t\t\tthis._renderedHeight = remembered;\n\t\t\treturn;\n\t\t}\n\t\tconst div = document.createElement('div');\n\t\tdiv.className = 'md-block md-math-block';\n\t\ttry {\n\t\t\tkatex.render(latex, div, { displayMode: true, throwOnError: false });\n\t\t} catch {\n\t\t\tdiv.textContent = latex;\n\t\t}\n\t\tsuper(data, div, _NO_CHILDREN);\n\t\tthis._renderedHeight = remembered;\n\t}\n\n\toverride recordMeasuredHeight(height: number): void {\n\t\t// Only the inactive (rendered) form defines the height to reserve; the\n\t\t// active form's height is whatever the source needs (>= the reserved min).\n\t\tif (!this.data.showMarkup) { this._renderedHeight = height; }\n\t}\n}\n\n/**\n * A list. Each item carries its own `isActive` flag (the builder computes which\n * items the selection reaches), so the list just dispatches each child to its\n * view node — the per-item active state lives on the {@link ListItemViewData}.\n */\nclass ListViewNode extends BlockViewNode<ListViewData> {\n\tconstructor(data: ListViewData, options: BlockViewOptions | undefined, previous: ListViewNode | undefined) {\n\t\tconst tag = data.ast.ordered ? 'ol' : 'ul';\n\t\tconst reuse = previous && previous.element.tagName === tag.toUpperCase();\n\t\tconst el = reuse ? previous.element : document.createElement(tag);\n\t\tif (!reuse) { el.className = 'md-block md-list'; }\n\t\tconst children = reconcileDomChildren(el, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\nclass ListItemViewNode extends BlockViewNode<ListItemViewData> {\n\tconstructor(data: ListItemViewData, options: BlockViewOptions | undefined, previous: ListItemViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst li = document.createElement('li');\n\t\tif (data.isActive) { li.classList.add('md-list-item-active'); }\n\t\tif (ast.checked !== undefined) { li.classList.add('md-task-list-item'); }\n\t\tif (!data.isActive) { li.classList.add('md-markers-hidden'); }\n\t\tli.style.setProperty('--md-list-level', String(data.level));\n\n\t\tconst children = _reconcileListItem(li, data.content, previous, options);\n\n\t\t// Checkbox affordance for collapsed task items. Not part of the AST\n\t\t// mirror, so it is prepended after the children are reconciled.\n\t\tif (!data.isActive && ast.checked !== undefined) {\n\t\t\tconst checkbox = document.createElement('input');\n\t\t\tcheckbox.type = 'checkbox';\n\t\t\tcheckbox.checked = ast.checked;\n\t\t\tcheckbox.className = 'md-checkbox';\n\t\t\tconst onToggle = options?.onToggleCheckbox;\n\t\t\tif (onToggle) {\n\t\t\t\tconst wasChecked = ast.checked;\n\t\t\t\tcheckbox.addEventListener('mousedown', (e) => {\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tonToggle(ast, !wasChecked);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tcheckbox.disabled = true;\n\t\t\t}\n\t\t\tli.insertBefore(checkbox, li.firstChild);\n\t\t}\n\n\t\tsuper(data, li, children);\n\t}\n}\n\n/**\n * Reconcile a list item's children into `li`. A nested item carries its source\n * indentation as a leading `indent` glue before the bullet marker; that pair is\n * mounted together inside an absolutely-positioned `.md-list-gutter` span so the\n * indentation dots sit in the gutter *before* the bullet (matching the source\n * `␣␣- text`) while the item text stays at the content edge in both states.\n * Items without a leading indent (top-level bullets) mount their children\n * directly, keeping the bullet in the gutter via `.md-marker-listItemMarker`.\n *\n * The returned children array always mirrors `content` 1:1 and in source order,\n * so the source ↔ DOM mapping is unaffected by the gutter wrapper.\n */\nfunction _reconcileListItem(\n\tli: HTMLElement,\n\tcontent: readonly AnyViewData[],\n\tprevious: ListItemViewNode | undefined,\n\toptions: BlockViewOptions | undefined,\n): ViewNode[] {\n\tconst { paired, unused } = pairNodes(content, previous?.children ?? _NO_CHILDREN);\n\tconst children = content.map(d => createViewNode(d, options, paired.get(d)));\n\tfor (const u of unused) { u.dispose(); }\n\n\tconst hasIndentGutter = content.length >= 2\n\t\t&& content[0].kind === 'glue' && content[0].ast.glueKind === 'indent'\n\t\t&& content[1].kind === 'marker' && content[1].ast.markerKind === 'listItemMarker';\n\n\tif (!hasIndentGutter) {\n\t\t_patchDomNodes(li, children.map(c => c.mountNode));\n\t\treturn children;\n\t}\n\n\tconst first = li.firstElementChild;\n\tconst gutter = first && first.classList.contains('md-list-gutter')\n\t\t? first as HTMLElement\n\t\t: document.createElement('span');\n\tgutter.className = 'md-list-gutter';\n\t_patchDomNodes(gutter, [children[0].mountNode, children[1].mountNode]);\n\t_patchDomNodes(li, [gutter, ...children.slice(2).map(c => c.mountNode)]);\n\treturn children;\n}\n\n\n/**\n * A table row (`<tr>`). The delimiter row (`| --- | --- |`) gets\n * `md-table-delimiter-row` so the CSS can collapse/reveal it. After its cells\n * are reconciled, each cell the selection reaches ({@link TableCellViewData.isActive}\n * on a non-delimiter row) gets `md-table-cell-active`; because any change to a\n * cell's active state changes its view-data identity and so rebuilds the cell\n * fresh, a reused cell never carries a stale active class.\n */\nclass TableRowViewNode extends BlockViewNode<TableRowViewData> {\n\tconstructor(data: TableRowViewData, options: BlockViewOptions | undefined, previous: TableRowViewNode | undefined) {\n\t\tconst tr = previous?.element ?? document.createElement('tr');\n\t\tif (data.isDelimiter) { tr.classList.add('md-table-delimiter-row'); }\n\t\tconst children = reconcileDomChildren(tr, data.content, previous?.children, _buildChild(options));\n\t\tif (!data.isDelimiter) {\n\t\t\tdata.content.forEach((cellData, i) => {\n\t\t\t\tif (cellData.kind === 'tableCell' && cellData.isActive) {\n\t\t\t\t\t(children[i] as BlockViewNode).element.classList.add('md-table-cell-active');\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tsuper(data, tr, children);\n\t}\n}\n\nclass InlineCodeViewNode extends BlockViewNode<InlineCodeViewData> {\n\tconstructor(data: InlineCodeViewData, options: BlockViewOptions | undefined, previous: InlineCodeViewNode | undefined) {\n\t\tconst code = previous?.element ?? document.createElement('code');\n\t\tconst children = reconcileDomChildren(code, data.content, previous?.children, _inlineChild(options));\n\t\tsuper(data, code, children);\n\t}\n}\n\nclass InlineMathViewNode extends BlockViewNode<InlineMathViewData> {\n\tconstructor(data: InlineMathViewData, options: BlockViewOptions | undefined, previous: InlineMathViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = 'md-inline-math';\n\t\t\tconst children = reconcileDomChildren(span, data.content, previous?.children, _inlineChild(options));\n\t\t\tsuper(data, span, children);\n\t\t\treturn;\n\t\t}\n\t\tconst contentMarker = data.content.find(\n\t\t\t(c): c is MarkerViewData => c.kind === 'marker' && c.ast.markerKind === 'content',\n\t\t);\n\t\tconst latex = contentMarker?.ast.content ?? '';\n\t\tconst rendering = options?.renderMath?.({\n\t\t\tlatex,\n\t\t\tdisplayMode: false,\n\t\t\tclassName: 'md-inline-math',\n\t\t\tnodeLength: data.ast.length,\n\t\t\tcontentStart: _mathContentOffset(data.ast.content),\n\t\t});\n\t\tif (rendering) {\n\t\t\tsuper(data, rendering.dom, _buildMathSegmentChildren(data.ast, rendering.segments, data.ast.length));\n\t\t\treturn;\n\t\t}\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-inline-math';\n\t\ttry {\n\t\t\tkatex.render(latex, span, { throwOnError: false });\n\t\t} catch {\n\t\t\tspan.textContent = latex;\n\t\t}\n\t\tsuper(data, span, _NO_CHILDREN);\n\t}\n}\n\nclass LinkViewNode extends BlockViewNode<LinkViewData> {\n\tconstructor(data: LinkViewData, options: BlockViewOptions | undefined, previous: LinkViewNode | undefined) {\n\t\tconst a = (previous?.element ?? document.createElement('a')) as HTMLAnchorElement;\n\t\tif (_isSafeUrl(data.ast.url)) {\n\t\t\ta.href = data.ast.url;\n\t\t\ta.dataset.mdUrl = data.ast.url;\n\t\t} else {\n\t\t\ta.removeAttribute('href');\n\t\t\tdelete a.dataset.mdUrl;\n\t\t}\n\t\t// Wire the open-on-click affordance once per element (it persists across\n\t\t// reconciliation; the URL it opens is read live from `dataset.mdUrl`).\n\t\t// A plain click opens the link only while its block is inactive; once the\n\t\t// block is active (source shown) opening requires Ctrl/Cmd so a plain\n\t\t// click can place the caret. Stopping propagation keeps the controller\n\t\t// from treating an opening click as a caret move.\n\t\tif (!previous) {\n\t\t\ta.addEventListener('mousedown', (e) => {\n\t\t\t\tconst url = a.dataset.mdUrl;\n\t\t\t\tif (!url) { return; }\n\t\t\t\tconst blockActive = a.closest('.md-block-active') !== null;\n\t\t\t\tif (blockActive && !(e.ctrlKey || e.metaKey)) { return; }\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tif (options?.onOpenLink) { options.onOpenLink(url, e); }\n\t\t\t\telse { window.open(url, '_blank', 'noopener'); }\n\t\t\t});\n\t\t}\n\t\tconst children = reconcileDomChildren(a, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, a, children);\n\t}\n}\n\nclass ImageViewNode extends BlockViewNode<ImageViewData> {\n\tconstructor(data: ImageViewData, options: BlockViewOptions | undefined, previous: ImageViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tif (data.showMarkup) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = 'md-image-source';\n\t\t\tconst children = reconcileDomChildren(span, data.content, previous?.children, _buildChild(options));\n\t\t\tsuper(data, span, children);\n\t\t\treturn;\n\t\t}\n\t\tconst img = document.createElement('img');\n\t\tif (_isSafeUrl(ast.url)) { img.src = ast.url; }\n\t\timg.alt = ast.alt;\n\t\tsuper(data, img, _NO_CHILDREN);\n\t}\n}\n\n/**\n * Pair each new node with the previous view node that should render it, then\n * report the previous nodes left over. Pairing is by {@link AstNode.id} — the\n * stable identity the parser mints on construction and carries across edits (see\n * `reconcile`). One key covers both reuse cases uniformly: an unchanged subtree\n * keeps its node object (so, trivially, its id), and an edited node — e.g. a\n * code block whose content changed — is rebuilt as a fresh object cloned with\n * its previous id. So the previous view node (which owns any DOM and, for a code\n * block, the highlighting session) is paired with the new view-data derived from\n * it, and that DOM/session is adopted rather than rebuilt.\n *\n * Previous nodes whose id no longer appears are returned in `unused`; the caller\n * disposes them (freeing any session they still own).\n */\nexport function pairNodes(\n\tnewData: readonly AnyViewData[],\n\tprevNodes: readonly ViewNode[],\n): { paired: Map<AnyViewData, ViewNode>; unused: ViewNode[] } {\n\tconst byId = new Map<number, ViewNode>();\n\tfor (const n of prevNodes) { byId.set(n.ast.id, n); }\n\n\tconst paired = new Map<AnyViewData, ViewNode>();\n\tfor (const d of newData) {\n\t\tconst n = byId.get(d.ast.id);\n\t\tif (n) { paired.set(d, n); byId.delete(d.ast.id); }\n\t}\n\n\treturn { paired, unused: [...byId.values()] };\n}\n\nfunction _isSafeUrl(url: string): boolean {\n\treturn !url.trim().toLowerCase().startsWith('javascript:');\n}\n","import type { AnyViewData, DocumentViewData } from '../viewData.js';\nimport type { DocumentAstNode } from '../../parser/ast.js';\nimport { BlockViewNode, createViewNode, pairNodes, _patchDomNodes, type BlockViewOptions } from './blockView.js';\nimport { ViewNode } from './viewNode.js';\n\n/** A mounted block: its view node paired with where it starts in the source. */\nexport interface DocumentBlock {\n readonly node: BlockViewNode;\n readonly absoluteStart: number;\n}\n\n/**\n * Immutable view of the document's block sequence — the document-level\n * analogue of {@link BlockViewNode}. Each {@link create} maps the\n * {@link DocumentViewData} (the AST overlaid with selection-derived flags) to\n * the block sequence, reusing the previous node's blocks by view-data identity,\n * rebuilding only what changed, and patching its {@link contentDomNode}'s\n * children to match.\n *\n * Like a {@link BlockViewNode}, it owns its DOM: the first `create` allocates\n * the content element, and every later `create` keeps the previous node's\n * element rather than making a new one. The element is therefore stable\n * across rebuilds:\n *\n * create(viewData, …, old).contentDomNode === old.contentDomNode\n *\n * so a parent can mount it once and never re-parent it.\n *\n * Because it is rebuilt rather than mutated, {@link EditorView} can hold the\n * whole block cache as one value and simply swap it each frame, instead of\n * carrying a mutable entry array and the reconcile bookkeeping itself.\n *\n * It is itself a {@link ViewNode} (the root of the view-node tree), so DOM ↔\n * source mapping such as {@link ViewNode.resolveSource} is inherited: a hit on\n * any descendant lifts up the parent chain to here, yielding an absolute\n * document offset.\n */\nexport class DocumentViewNode extends ViewNode {\n static create(\n viewData: DocumentViewData,\n options: BlockViewOptions | undefined,\n previous: DocumentViewNode | undefined,\n ): DocumentViewNode {\n const contentDomNode = previous?.contentDomNode ?? document.createElement('div');\n const activeByView = new Map<AnyViewData, boolean>(\n viewData.children.filter(c => c.kind === 'block').map(c => [c.view, c.isActive]),\n );\n\n // Build every child (blocks and any leading/standalone glue) in source\n // order, pairing each with the previous node that rendered it so reused\n // nodes keep their DOM, and disposing the leftovers. A block's trailing\n // `blockGap` glue is part of the block's own content now (the parser\n // attributes it there), so it is mounted at the end of the block's last\n // line by the block's own reconciliation — no document-level reparenting.\n const prevNodes = previous?.children;\n const childViews = viewData.children.map(c => c.view);\n const { paired, unused } = pairNodes(childViews, prevNodes ?? _NO_NODES);\n const nodes = childViews.map((view, i) => {\n const prev = paired.get(view);\n const node = createViewNode(view, options, prev);\n // The active/markers-hidden classes are a top-level concern (the\n // block's own markers are handled within its subtree), so they are\n // applied here rather than inside the node. Glue carries no such\n // classes, so it is left untouched.\n if (viewData.children[i].kind === 'block') {\n const isActive = activeByView.get(view);\n if (isActive !== undefined) {\n (node as BlockViewNode).element.classList.toggle('md-block-active', isActive);\n (node as BlockViewNode).element.classList.toggle('md-markers-hidden', !isActive);\n }\n }\n return node;\n });\n for (const u of unused) { u.dispose(); }\n\n _patchDomNodes(contentDomNode, nodes.map(n => n.mountNode));\n\n const blocks: DocumentBlock[] = [];\n viewData.children.forEach((c, i) => {\n if (c.kind === 'block') { blocks.push({ node: nodes[i] as BlockViewNode, absoluteStart: c.absoluteStart }); }\n });\n return new DocumentViewNode(viewData.ast, contentDomNode, blocks, nodes);\n }\n\n private constructor(\n ast: DocumentAstNode,\n contentDomNode: HTMLElement,\n readonly blocks: readonly DocumentBlock[],\n /** Every mounted child (blocks and glue) in source order. */\n nodes: readonly ViewNode[],\n ) {\n super(ast, contentDomNode, nodes);\n }\n\n /** The stable content element this document mounts its children into. */\n get contentDomNode(): HTMLElement { return this.dom as HTMLElement; }\n}\n\nconst _NO_NODES: readonly ViewNode[] = [];\n","import { Point2D } from '../../core/geometry.js';\n\n/**\n * A DOM node paired with a caret offset inside it. The node is an arbitrary\n * {@link globalThis.Node} (a Text node for a caret inside text, an Element for\n * a hit on element-only content), and `offset` is the caret offset within it.\n */\nexport interface DomPosition {\n readonly node: globalThis.Node;\n readonly offset: number;\n}\n\n/**\n * Client-coordinate point → the DOM caret position under it, using the\n * platform hit-test API (`caretPositionFromPoint`, with a `caretRangeFromPoint`\n * fallback). Returns `undefined` when the point hits nothing.\n */\nexport function caretDomPositionFromPoint(point: Point2D): DomPosition | undefined {\n const api = document as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: globalThis.Node; offset: number } | null;\n caretRangeFromPoint?: (x: number, y: number) => Range | null;\n };\n if (api.caretPositionFromPoint) {\n const result = api.caretPositionFromPoint(point.x, point.y);\n return result ? { node: result.offsetNode, offset: result.offset } : undefined;\n }\n const range = api.caretRangeFromPoint?.(point.x, point.y);\n if (!range) { return undefined; }\n return { node: range.startContainer, offset: range.startOffset };\n}\n","/**\n * The view-data overlay over the {@link AstNode} tree.\n *\n * Every AST kind has a parallel `*ViewData` class that mirrors its child\n * structure but carries, on top, the *selection-derived* render inputs the\n * renderer needs (which markers are visible, which list item / table cell is\n * active, whether an inline-math / image / code block shows its source or its\n * rendered form). Scalars (`level`, `url`, `language`, …) are read through the\n * referenced {@link AstNode}, never copied, so the overlay stays a thin layer\n * and the two trees can never drift.\n *\n * Splitting these inputs out makes a selection change a pure function over the\n * *unchanged* AST: only the {@link DocumentViewData} is rebuilt (cheap — no\n * DOM), and inactive blocks reuse the previous frame's view-data subtree by\n * identity (see {@link buildDocumentViewData}), so the eventual diff against\n * the rendered tree bottoms out at the one or two nodes whose flags flipped.\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { findActiveListItemIndex } from '../model/cursorNavigation.js';\nimport { GlueAstNode } from '../parser/ast.js';\nimport type {\n\tAnyAstNode, AstNode, BlockAstNode, CodeBlockAstNode, DocumentAstNode, EmphasisAstNode,\n\tHeadingAstNode, ImageAstNode, InlineCodeAstNode, InlineMathAstNode,\n\tLinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode,\n\tParagraphAstNode, StrikethroughAstNode, StrongAstNode, TableAstNode, TableCellAstNode,\n\tTableRowAstNode, TextAstNode, ThematicBreakAstNode, BlockQuoteAstNode,\n} from '../parser/ast.js';\n\n// ---------------------------------------------------------------------------\n// Document\n// ---------------------------------------------------------------------------\n\n/**\n * The view-data root. Mirrors {@link DocumentAstNode}: {@link blocks} holds only\n * its top-level blocks (each wrapped with where it starts and whether it is\n * active), while {@link children} additionally interleaves the rendered\n * document-level glue (the blank lines between blocks) in source order.\n */\nexport class DocumentViewData {\n\treadonly kind = 'document';\n\tconstructor(\n\t\treadonly ast: DocumentAstNode,\n\t\treadonly blocks: readonly DocumentBlockViewData[],\n\t\t/**\n\t\t * Blocks and inter-block glue interleaved in source order — the actual\n\t\t * mount sequence. {@link blocks} is the block-only projection used for\n\t\t * measurement and selection.\n\t\t */\n\t\treadonly children: readonly DocumentChildViewData[],\n\t) { }\n}\n\n/** A top-level block plus the document-level state the renderer applies to it. */\nexport interface DocumentBlockViewData {\n\treadonly ast: BlockAstNode;\n\treadonly absoluteStart: number;\n\t/** Whether the selection reaches this block (drives `md-block-active`). */\n\treadonly isActive: boolean;\n\treadonly view: BlockViewData;\n}\n\n/** A mounted document child: a block or a run of inter-block glue. */\nexport interface DocumentChildViewData {\n\treadonly absoluteStart: number;\n\t/** For a block: selection reaches it. For glue: always false (unowned, hidden). */\n\treadonly isActive: boolean;\n\treadonly view: BlockViewData | GlueViewData;\n\treadonly kind: 'block' | 'glue';\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockViewData =\n\t| HeadingViewData | ParagraphViewData | CodeBlockViewData | MathBlockViewData\n\t| ThematicBreakViewData | BlockQuoteViewData | ListViewData | TableViewData;\n\nexport class HeadingViewData {\n\treadonly kind = 'heading';\n\tconstructor(readonly ast: HeadingAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ParagraphViewData {\n\treadonly kind = 'paragraph';\n\tconstructor(readonly ast: ParagraphAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class CodeBlockViewData {\n\treadonly kind = 'codeBlock';\n\tconstructor(\n\t\treadonly ast: CodeBlockAstNode,\n\t\t/** Active: render the fenced source; inactive: the (custom/highlighted) block. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class MathBlockViewData {\n\treadonly kind = 'mathBlock';\n\tconstructor(\n\t\treadonly ast: MathBlockAstNode,\n\t\t/** Active: render the source; inactive: the KaTeX output. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class BlockQuoteViewData {\n\treadonly kind = 'blockQuote';\n\tconstructor(readonly ast: BlockQuoteAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ListViewData {\n\treadonly kind = 'list';\n\tconstructor(readonly ast: ListAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class TableViewData {\n\treadonly kind = 'table';\n\tconstructor(readonly ast: TableAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\n// ---------------------------------------------------------------------------\n// Inlines\n// ---------------------------------------------------------------------------\n\nexport type InlineViewData =\n\t| TextViewData | StrongViewData | EmphasisViewData | StrikethroughViewData\n\t| InlineCodeViewData | InlineMathViewData | LinkViewData | ImageViewData;\n\nexport class StrongViewData {\n\treadonly kind = 'strong';\n\tconstructor(readonly ast: StrongAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class EmphasisViewData {\n\treadonly kind = 'emphasis';\n\tconstructor(readonly ast: EmphasisAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class StrikethroughViewData {\n\treadonly kind = 'strikethrough';\n\tconstructor(readonly ast: StrikethroughAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class InlineCodeViewData {\n\treadonly kind = 'inlineCode';\n\tconstructor(readonly ast: InlineCodeAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class InlineMathViewData {\n\treadonly kind = 'inlineMath';\n\tconstructor(\n\t\treadonly ast: InlineMathAstNode,\n\t\t/** Active: render the `$…$` source; inactive: the KaTeX output. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class LinkViewData {\n\treadonly kind = 'link';\n\tconstructor(readonly ast: LinkAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ImageViewData {\n\treadonly kind = 'image';\n\tconstructor(\n\t\treadonly ast: ImageAstNode,\n\t\t/** Active: render the `` source; inactive: the `<img>`. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\n// ---------------------------------------------------------------------------\n// Containers without their own AST union (list item, table row/cell)\n// ---------------------------------------------------------------------------\n\nexport class ListItemViewData {\n\treadonly kind = 'listItem';\n\tconstructor(\n\t\treadonly ast: ListItemAstNode,\n\t\t/** Whether the selection reaches this item (reveals its markers). */\n\t\treadonly isActive: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t\t/** 1-based list nesting depth, used to size the indentation gutter. */\n\t\treadonly level: number,\n\t) { }\n}\n\nexport class TableRowViewData {\n\treadonly kind = 'tableRow';\n\tconstructor(\n\t\treadonly ast: TableRowAstNode,\n\t\treadonly isDelimiter: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class TableCellViewData {\n\treadonly kind = 'tableCell';\n\tconstructor(\n\t\treadonly ast: TableCellAstNode,\n\t\t/** Whether the selection reaches this cell (reveals its inline markers). */\n\t\treadonly isActive: boolean,\n\t\t/** Whether the owning table is active (reveals the structural pipes). */\n\t\treadonly showTableGlue: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\n// ---------------------------------------------------------------------------\n// Leaves\n// ---------------------------------------------------------------------------\n\nexport class TextViewData {\n\treadonly kind = 'text';\n\t/**\n\t * Whether non-obvious whitespace in this text is revealed (block is active).\n\t * `leftWordBoundary`/`rightWordBoundary` say whether the inline sibling on\n\t * that side ends/starts with visible word content (e.g. inline code, a link,\n\t * emphasis); a single space touching such a sibling is obvious and stays\n\t * undecorated, just like a space between two words within this leaf.\n\t */\n\tconstructor(\n\t\treadonly ast: TextAstNode,\n\t\treadonly showWhitespace: boolean,\n\t\treadonly leftWordBoundary: boolean = false,\n\t\treadonly rightWordBoundary: boolean = false,\n\t) { }\n}\n\nexport class ThematicBreakViewData {\n\treadonly kind = 'thematicBreak';\n\tconstructor(\n\t\treadonly ast: ThematicBreakAstNode,\n\t\t/** Active: reveal the source markup (`---`) instead of the rendered rule. */\n\t\treadonly showMarkup: boolean,\n\t\t/** Marker (and any absorbed trailing glue), rendered only when active. */\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class MarkerViewData {\n\treadonly kind = 'marker';\n\tconstructor(readonly ast: MarkerAstNode, readonly visible: boolean) { }\n}\n\nexport class GlueViewData {\n\treadonly kind = 'glue';\n\tconstructor(\n\t\treadonly ast: GlueAstNode,\n\t\treadonly visible: boolean,\n\t\t/**\n\t\t * Whether a source newline in this glue gets a visible `↵`. True only in\n\t\t * inline flow, where the newline collapses to a space and the `↵` reveals\n\t\t * the line ending hiding there; between block-level siblings (list items,\n\t\t * block children) the break is already visible, so no `↵` is drawn.\n\t\t */\n\t\treadonly decorateNewline: boolean,\n\t) { }\n}\n\nexport type AnyViewData =\n\t| DocumentViewData | BlockViewData | InlineViewData\n\t| ListItemViewData | TableRowViewData | TableCellViewData\n\t| MarkerViewData | GlueViewData;\n\n// ---------------------------------------------------------------------------\n// Builder\n// ---------------------------------------------------------------------------\n\n/** The selection-derived inputs threaded down while building one subtree. */\ninterface BuildCtx {\n\t/** Whether markers/source are revealed in this node's region. */\n\treadonly showMarkup: boolean;\n\t/** Whether `tableCellGlue` pipes are forced visible (the owning table is active). */\n\treadonly showTableGlue: boolean;\n\t/** Selection range relative to the node being built, or `undefined` when inactive. */\n\treadonly selectionInNode: OffsetRange | undefined;\n\t/**\n\t * Whether the node being built lays its children out in inline flow (a\n\t * paragraph, heading, table cell, or an inline wrapper). A source newline\n\t * there collapses to a space and so earns a visible `↵`; in block flow the\n\t * line break is already visible and the newline gets none. Defaults to false.\n\t */\n\treadonly inlineFlow?: boolean;\n\t/** 1-based nesting depth of the list currently being built (0 outside lists). */\n\treadonly listLevel?: number;\n}\n\nconst _INACTIVE: BuildCtx = { showMarkup: false, showTableGlue: false, selectionInNode: undefined };\n\n/** Descend into inline flow, where a source newline collapses to a space (so its `↵` is shown). */\nfunction _inline(ctx: BuildCtx): BuildCtx {\n\treturn ctx.inlineFlow ? ctx : { ...ctx, inlineFlow: true };\n}\n\n/**\n * Map the parsed document + active/selection state to its view-data tree.\n *\n * Top-level blocks are mirrored into {@link DocumentViewData.blocks}. A block's\n * trailing blank lines are attributed by the parser to the block itself (a\n * `blockGap`/`blockBreak` glue at the end of its content), and a leading indent\n * to the block it precedes (its `leadingTrivia`), so both are built as part of\n * the block and revealed only when that block is active — no neighbour scan. The\n * only glue that survives at the document level is an unowned leading gap before\n * the first block; it is mirrored into {@link DocumentViewData.children} and\n * stays collapsed (never revealed), like the gap between two blocks.\n * An inactive block's view-data is a pure function of its AST, so when `previous`\n * holds a view-data for the same block object (the parser preserves identity for\n * unchanged subtrees) that was *also* inactive, the whole subtree is reused by\n * identity — the common case for a selection move, making it O(active blocks).\n */\nexport function buildDocumentViewData(\n\tdoc: DocumentAstNode,\n\tactiveBlocks: ReadonlySet<BlockAstNode>,\n\tselectionRange: OffsetRange | undefined,\n\tprevious: DocumentViewData | undefined,\n): DocumentViewData {\n\tconst prevByAst = new Map<AstNode, DocumentChildViewData>();\n\tif (previous) {\n\t\tfor (const c of previous.children) { prevByAst.set(c.view.ast, c); }\n\t}\n\n\tconst content = doc.content;\n\tconst blockSet = new Set<BlockAstNode>(doc.blocks);\n\n\tconst blocks: DocumentBlockViewData[] = [];\n\tconst children: DocumentChildViewData[] = [];\n\tlet pos = 0;\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst child = content[i];\n\t\tif (blockSet.has(child as BlockAstNode)) {\n\t\t\tconst block = child as BlockAstNode;\n\t\t\tconst isActive = activeBlocks.has(block);\n\t\t\tconst prev = prevByAst.get(block);\n\t\t\tlet view: BlockViewData;\n\t\t\tif (!isActive) {\n\t\t\t\t// Fast path: an unchanged block that stays inactive keeps its whole\n\t\t\t\t// subtree by identity without rebuilding anything (the O(active) case).\n\t\t\t\tview = prev && !prev.isActive\n\t\t\t\t\t? prev.view as BlockViewData\n\t\t\t\t\t: _buildBlock(block, _INACTIVE, prev?.view);\n\t\t\t} else {\n\t\t\t\tconst selectionInNode = selectionRange\n\t\t\t\t\t? new OffsetRange(\n\t\t\t\t\t\tMath.max(0, selectionRange.start - pos),\n\t\t\t\t\t\tMath.min(block.length, selectionRange.endExclusive - pos),\n\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\t\t\t\tview = _buildBlock(block, { showMarkup: true, showTableGlue: false, selectionInNode }, prev?.view);\n\t\t\t}\n\t\t\tblocks.push({ ast: block, absoluteStart: pos, isActive, view });\n\t\t\tchildren.push({ absoluteStart: pos, isActive, view, kind: 'block' });\n\t\t} else if (child instanceof GlueAstNode) {\n\t\t\t// Any glue that survives at the document level is unowned inter-block\n\t\t\t// glue (a leading gap before the first block): every gap that trails a\n\t\t\t// block is attributed to that block by the parser, and every leading\n\t\t\t// indent to the block it precedes, so the only glue left here has no\n\t\t\t// owning block. With no owner it is never revealed — it stays collapsed\n\t\t\t// in both states, exactly like the gap between two blocks.\n\t\t\tconst prev = prevByAst.get(child);\n\t\t\tconst view = _reuseOr(prev?.view, new GlueViewData(child, false, false));\n\t\t\tchildren.push({ absoluteStart: pos, isActive: false, view, kind: 'glue' });\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new DocumentViewData(doc, blocks, children);\n}\n\nfunction _buildBlock(block: BlockAstNode, ctx: BuildCtx, prev: AnyViewData | undefined): BlockViewData {\n\treturn _buildNode(block, ctx, prev) as BlockViewData;\n}\n\n/**\n * Build the view-data for one node, threading the previous frame's view-data\n * for the same node so identity can be preserved bottom-up: a freshly-built\n * candidate that has the same ast, the same flags, and identity-equal children\n * as `prev` *is* `prev` (see {@link _reuseOr}). Because unchanged children are\n * already shared this way, the comparison stays O(children), and an unchanged\n * subtree keeps one stable view-data object across frames — which is exactly\n * what lets the renderer reuse its DOM by a single identity check.\n */\nfunction _buildNode(astNode: AstNode, ctx: BuildCtx, prev: AnyViewData | undefined, neighbors?: _Neighbors): AnyViewData {\n\tconst node = astNode as AnyAstNode;\n\tswitch (node.kind) {\n\t\tcase 'text': return _reuseOr(prev, new TextViewData(node, ctx.showMarkup, neighbors?.left ?? false, neighbors?.right ?? false));\n\t\t// The trailing gap is revealed as `↵` glyphs by virtue of its `blockGap`\n\t\t// kind (see `GlueViewNode`), so the break needs no inline-flow opt-in.\n\t\tcase 'thematicBreak': return _reuseOr(prev, new ThematicBreakViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'marker': return _reuseOr(prev, new MarkerViewData(node, _markerVisible(node.markerKind, ctx)));\n\t\tcase 'glue': return _reuseOr(prev, new GlueViewData(node, _glueVisible(node.glueKind, ctx), ctx.inlineFlow ?? false));\n\t\tcase 'heading': return _reuseOr(prev, new HeadingViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'paragraph': return _reuseOr(prev, new ParagraphViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'codeBlock': return _reuseOr(prev, new CodeBlockViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'mathBlock': return _reuseOr(prev, new MathBlockViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'blockQuote': return _reuseOr(prev, new BlockQuoteViewData(node, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'list': return _reuseOr(prev, _buildList(node, ctx, prev));\n\t\tcase 'listItem': return _reuseOr(prev, _buildListItem(node, ctx, prev));\n\t\tcase 'table': return _reuseOr(prev, _buildTable(node, ctx, prev));\n\t\tcase 'tableRow': return _reuseOr(prev, _buildTableRow(node, ctx, false, prev));\n\t\tcase 'tableCell': return _reuseOr(prev, _buildTableCell(node, ctx.showMarkup, ctx.showTableGlue, ctx.selectionInNode, prev));\n\t\tcase 'strong': return _reuseOr(prev, new StrongViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'emphasis': return _reuseOr(prev, new EmphasisViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'strikethrough': return _reuseOr(prev, new StrikethroughViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'inlineCode': return _reuseOr(prev, new InlineCodeViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'inlineMath': return _reuseOr(prev, new InlineMathViewData(node, ctx.showMarkup, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'link': return _reuseOr(prev, new LinkViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'image': return _reuseOr(prev, new ImageViewData(node, ctx.showMarkup, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'document': return buildDocumentViewData(node, new Set(), OffsetRange.ofLength(0), undefined);\n\t}\n}\n\n/** Children of a view-data node, for identity comparison and prev-matching. */\nfunction _childrenOf(node: AnyViewData): readonly AnyViewData[] {\n\tif (node.kind === 'document') { return node.blocks.map(b => b.view); }\n\treturn 'content' in node ? node.content : _NO_CHILDREN;\n}\n\nconst _NO_CHILDREN: readonly AnyViewData[] = [];\n\n/** Index the previous node's children by their ast, so each new child finds its match. */\nfunction _prevChildByAst(prev: AnyViewData | undefined): ReadonlyMap<AstNode, AnyViewData> | undefined {\n\tif (!prev) { return undefined; }\n\tconst map = new Map<AstNode, AnyViewData>();\n\tfor (const c of _childrenOf(prev)) { map.set(c.ast, c); }\n\treturn map;\n}\n\n/**\n * Reuse `prev` in place of the freshly-built `cand` when the two are\n * indistinguishable: same kind, same ast, equal flags, and identity-equal\n * children (unchanged children are already shared, so this is a cheap `===`\n * sweep). Returning `prev` keeps the whole subtree's view-data object stable.\n */\nfunction _reuseOr<T extends AnyViewData>(prev: AnyViewData | undefined, cand: T): T {\n\tif (prev && prev.kind === cand.kind && prev.ast === cand.ast && _flagsEqual(prev, cand)) {\n\t\tconst a = _childrenOf(prev);\n\t\tconst b = _childrenOf(cand);\n\t\tif (a.length === b.length && a.every((c, i) => c === b[i])) { return prev as T; }\n\t}\n\treturn cand;\n}\n\n/** Compare the selection-derived flags of two same-kind view-data nodes. */\nfunction _flagsEqual(a: AnyViewData, b: AnyViewData): boolean {\n\tswitch (a.kind) {\n\t\tcase 'text': return a.showWhitespace === (b as TextViewData).showWhitespace\n\t\t\t&& a.leftWordBoundary === (b as TextViewData).leftWordBoundary\n\t\t\t&& a.rightWordBoundary === (b as TextViewData).rightWordBoundary;\n\t\tcase 'marker': return a.visible === (b as MarkerViewData).visible;\n\t\tcase 'glue': return a.visible === (b as GlueViewData).visible\n\t\t\t&& a.decorateNewline === (b as GlueViewData).decorateNewline;\n\t\tcase 'thematicBreak': return a.showMarkup === (b as ThematicBreakViewData).showMarkup;\n\t\tcase 'codeBlock': return a.showMarkup === (b as CodeBlockViewData).showMarkup;\n\t\tcase 'mathBlock': return a.showMarkup === (b as MathBlockViewData).showMarkup;\n\t\tcase 'inlineMath': return a.showMarkup === (b as InlineMathViewData).showMarkup;\n\t\tcase 'image': return a.showMarkup === (b as ImageViewData).showMarkup;\n\t\tcase 'listItem': return a.isActive === (b as ListItemViewData).isActive;\n\t\tcase 'tableCell': {\n\t\t\tconst o = b as TableCellViewData;\n\t\t\treturn a.isActive === o.isActive && a.showTableGlue === o.showTableGlue;\n\t\t}\n\t\tcase 'tableRow': return a.isDelimiter === (b as TableRowViewData).isDelimiter;\n\t\tdefault: return true;\n\t}\n}\n\n/** Build children against the same ctx — plain containers do not shift the selection. */\nfunction _buildChildren(children: readonly AstNode[], ctx: BuildCtx, prev: AnyViewData | undefined): AnyViewData[] {\n\tconst prevByAst = _prevChildByAst(prev);\n\treturn children.map((c, i) => {\n\t\tconst neighbors = c.kind === 'text'\n\t\t\t? {\n\t\t\t\tleft: i > 0 && _edgeIsWordContent(children[i - 1], 'end'),\n\t\t\t\tright: i < children.length - 1 && _edgeIsWordContent(children[i + 1], 'start'),\n\t\t\t}\n\t\t\t: undefined;\n\t\treturn _buildNode(c, ctx, prevByAst?.get(c), neighbors);\n\t});\n}\n\ninterface _Neighbors { readonly left: boolean; readonly right: boolean; }\n\n/**\n * Whether `node`'s `start`/`end` edge renders as visible word content — so a\n * single space touching it reads as an ordinary inter-word space. Inline\n * wrappers (code, math, links, images, emphasis, …) always present a visible\n * glyph at both edges; a text run depends on its own edge character.\n */\nfunction _edgeIsWordContent(node: AstNode, side: 'start' | 'end'): boolean {\n\tswitch (node.kind) {\n\t\tcase 'text': {\n\t\t\tconst c = (node as TextAstNode).content;\n\t\t\tconst ch = side === 'end' ? c[c.length - 1] : c[0];\n\t\t\treturn ch !== undefined && ch !== ' ' && ch !== '\\t' && ch !== '\\n' && ch !== '\\r';\n\t\t}\n\t\tcase 'inlineCode':\n\t\tcase 'inlineMath':\n\t\tcase 'link':\n\t\tcase 'image':\n\t\tcase 'strong':\n\t\tcase 'emphasis':\n\t\tcase 'strikethrough':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction _markerVisible(markerKind: string, ctx: BuildCtx): boolean {\n\treturn ctx.showMarkup || (markerKind === 'tableCellGlue' && ctx.showTableGlue);\n}\n\nfunction _glueVisible(glueKind: string | undefined, ctx: BuildCtx): boolean {\n\treturn ctx.showMarkup || (glueKind === 'tableCellGlue' && ctx.showTableGlue);\n}\n\n/**\n * A list reveals each item's markers only when the selection reaches it, so it\n * computes which items intersect the selection and builds each with the\n * selection range shifted to its own start.\n */\nfunction _buildList(list: ListAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): ListViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst activeItems = _activeItemIndices(list, ctx);\n\tconst itemSet = new Set<ListItemAstNode>(list.items);\n\tconst itemLevel = (ctx.listLevel ?? 0) + 1;\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of list.children) {\n\t\tif (itemSet.has(child as ListItemAstNode)) {\n\t\t\tconst item = child as ListItemAstNode;\n\t\t\tconst isActive = activeItems.has(list.items.indexOf(item));\n\t\t\tconst itemCtx: BuildCtx = {\n\t\t\t\tshowMarkup: isActive,\n\t\t\t\tshowTableGlue: false,\n\t\t\t\tselectionInNode: isActive && ctx.selectionInNode ? ctx.selectionInNode.delta(-pos) : undefined,\n\t\t\t\tlistLevel: itemLevel,\n\t\t\t};\n\t\t\tcontent.push(_reuseOr(prevByAst?.get(item), _buildListItem(item, itemCtx, prevByAst?.get(item))));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new ListViewData(list, content);\n}\n\nfunction _buildListItem(item: ListItemAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): ListItemViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of item.children) {\n\t\tconst childCtx: BuildCtx = ctx.selectionInNode\n\t\t\t? { ...ctx, selectionInNode: ctx.selectionInNode.delta(-pos) }\n\t\t\t: ctx;\n\t\tcontent.push(_buildNode(child, childCtx, prevByAst?.get(child)));\n\t\tpos += child.length;\n\t}\n\treturn new ListItemViewData(item, ctx.showMarkup, content, ctx.listLevel ?? 1);\n}\n\n/**\n * A table reveals its delimiter and structural pipes whenever any cell is\n * active, but only the cell(s) the selection reaches reveal their inline\n * markers. Each non-delimiter row gets the table-relative selection shifted to\n * its own start; the delimiter row always reveals its cells when the table is\n * active.\n */\nfunction _buildTable(table: TableAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): TableViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst tableActive = ctx.showMarkup;\n\tconst delimiterRow = table.delimiterRow;\n\tconst rowSet = new Set<TableRowAstNode>(\n\t\t[table.headerRow, table.delimiterRow, ...table.bodyRows].filter((r): r is TableRowAstNode => r !== undefined),\n\t);\n\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of table.children) {\n\t\tif (rowSet.has(child as TableRowAstNode)) {\n\t\t\tconst row = child as TableRowAstNode;\n\t\t\tconst isDelimiter = row === delimiterRow;\n\t\t\tconst rowCtx: BuildCtx = {\n\t\t\t\tshowMarkup: tableActive,\n\t\t\t\tshowTableGlue: tableActive,\n\t\t\t\tselectionInNode: !isDelimiter && tableActive && ctx.selectionInNode\n\t\t\t\t\t? ctx.selectionInNode.delta(-pos)\n\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t\tcontent.push(_reuseOr(prevByAst?.get(row), _buildTableRow(row, rowCtx, isDelimiter, prevByAst?.get(row))));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new TableViewData(table, content);\n}\n\nfunction _buildTableRow(row: TableRowAstNode, ctx: BuildCtx, isDelimiter: boolean, prevNode: AnyViewData | undefined): TableRowViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst tableActive = ctx.showMarkup;\n\tconst activeCells = isDelimiter ? undefined : _activeCellIndices(row, ctx);\n\tconst cellSet = new Set<TableCellAstNode>(row.cells);\n\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tif (cellSet.has(child as TableCellAstNode)) {\n\t\t\tconst cell = child as TableCellAstNode;\n\t\t\tconst cellActive = isDelimiter ? tableActive : activeCells!.has(row.cells.indexOf(cell));\n\t\t\tconst selectionInNode = cellActive && ctx.selectionInNode ? ctx.selectionInNode.delta(-pos) : undefined;\n\t\t\tcontent.push(_buildTableCell(cell, cellActive, tableActive, selectionInNode, prevByAst?.get(cell)));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new TableRowViewData(row, isDelimiter, content);\n}\n\nfunction _buildTableCell(\n\tcell: TableCellAstNode,\n\tisActive: boolean,\n\tshowTableGlue: boolean,\n\tselectionInNode: OffsetRange | undefined,\n\tprevNode: AnyViewData | undefined,\n): TableCellViewData {\n\tconst cellCtx: BuildCtx = { showMarkup: isActive, showTableGlue, selectionInNode };\n\treturn new TableCellViewData(cell, isActive, showTableGlue, _buildChildren(cell.children, _inline(cellCtx), prevNode));\n}\n\nconst _EMPTY_SET: ReadonlySet<number> = new Set();\n\n/** Indices of the list's items whose source range intersects the selection. */\nfunction _activeItemIndices(list: ListAstNode, ctx: BuildCtx): ReadonlySet<number> {\n\tif (!ctx.showMarkup || !ctx.selectionInNode) { return _EMPTY_SET; }\n\tconst sel = ctx.selectionInNode;\n\tif (sel.isEmpty) {\n\t\tconst idx = findActiveListItemIndex(list, sel.start);\n\t\treturn idx === undefined ? _EMPTY_SET : new Set([idx]);\n\t}\n\tconst result = new Set<number>();\n\tlet pos = 0;\n\tfor (const child of list.children) {\n\t\tconst itemIdx = list.items.indexOf(child as ListItemAstNode);\n\t\tif (itemIdx >= 0 && pos < sel.endExclusive && pos + child.length > sel.start) {\n\t\t\tresult.add(itemIdx);\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn result;\n}\n\n/** Indices of the row's cells whose source range intersects the selection. */\nfunction _activeCellIndices(row: TableRowAstNode, ctx: BuildCtx): ReadonlySet<number> {\n\tif (!ctx.showMarkup || !ctx.selectionInNode) { return _EMPTY_SET; }\n\tconst sel = ctx.selectionInNode;\n\tif (sel.isEmpty) {\n\t\tconst idx = _findActiveCellIndex(row, sel.start);\n\t\treturn idx === undefined ? _EMPTY_SET : new Set([idx]);\n\t}\n\tconst result = new Set<number>();\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tconst cellIdx = row.cells.indexOf(child as TableCellAstNode);\n\t\tif (cellIdx >= 0 && pos < sel.endExclusive && pos + child.length > sel.start) {\n\t\t\tresult.add(cellIdx);\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn result;\n}\n\n/**\n * Cell containing a collapsed cursor, or `undefined` when the cursor is outside\n * this row. A cursor on the boundary between adjacent cells activates the\n * preceding one.\n */\nfunction _findActiveCellIndex(row: TableRowAstNode, cursorOffset: number): number | undefined {\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tconst end = pos + child.length;\n\t\tconst cellIdx = row.cells.indexOf(child as TableCellAstNode);\n\t\tif (cellIdx >= 0 && ((pos <= cursorOffset && cursorOffset < end) || end === cursorOffset)) {\n\t\t\treturn cellIdx;\n\t\t}\n\t\tpos = end;\n\t}\n\treturn undefined;\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { Rect2D } from '../../core/geometry.js';\nimport type { SourceOffset } from '../../core/sourceOffset.js';\nimport type { VisualLineMap } from '../visualLineMap.js';\n\nexport interface CursorViewOptions {\n readonly offset: IObservable<SourceOffset | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n}\n\n/**\n * Owns the blinking cursor DOM element.\n *\n * The rendering pipeline is a single `derived` whose compute callback\n * asks the {@link VisualLineMap} for the caret rect at the current\n * offset, writes it to {@link element}, and returns a\n * {@link CursorViewRendering} value as proof. An autorun keeps the\n * derived subscribed.\n */\nexport class CursorView extends Disposable {\n readonly element: HTMLElement;\n readonly rendering: IObservable<CursorViewRendering>;\n\n constructor(\n private readonly _parent: HTMLElement,\n options: CursorViewOptions,\n ) {\n super();\n this.element = document.createElement('div');\n this.element.className = 'md-cursor';\n\n this.rendering = derived(this, reader => {\n const offset = reader.readObservable(options.offset);\n const visualLineMap = reader.readObservable(options.visualLineMap);\n if (offset === undefined || visualLineMap.isEmpty) {\n this.element.style.display = 'none';\n return new CursorViewRendering(offset ?? 0, false, Rect2D.EMPTY);\n }\n const lineIdx = visualLineMap.lineIndexOfOffset(offset);\n const caretRect = visualLineMap.lineRect(lineIdx).withZeroWidthAt(visualLineMap.xAtOffset(offset));\n const parentRect = this._parent.getBoundingClientRect();\n const localRect = caretRect.translate(-parentRect.left, -parentRect.top);\n this.element.style.left = `${localRect.x}px`;\n this.element.style.top = `${localRect.y}px`;\n this.element.style.height = `${localRect.height}px`;\n this.element.style.display = '';\n return new CursorViewRendering(offset, true, localRect);\n });\n\n this._register(autorun(reader => { reader.readObservable(this.rendering); }));\n\n this._register(autorun(reader => {\n reader.readObservable(options.offset);\n this.element.style.animation = 'none';\n void this.element.offsetWidth;\n this.element.style.animation = '';\n }));\n }\n}\n\nexport class CursorViewRendering {\n constructor(\n readonly offset: SourceOffset,\n readonly visible: boolean,\n readonly rect: Rect2D,\n ) { }\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { Selection } from '../../core/selection.js';\nimport type { BlockAstNode } from '../../parser/ast.js';\nimport type { ViewNode } from '../content/viewNode.js';\nimport type { VisualLine, VisualLineMap } from '../visualLineMap.js';\n\n/**\n * One mounted block, as far as selection painting is concerned. The view\n * supplies its block cache in this shape so the selection layer never has\n * to reach back into private view state.\n */\nexport interface SelectionBlock {\n readonly block: BlockAstNode;\n readonly absoluteStart: number;\n readonly viewNode: ViewNode;\n readonly element: HTMLElement;\n}\n\nexport interface SelectionViewOptions {\n readonly selection: IObservable<Selection | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n readonly blocks: IObservable<readonly SelectionBlock[]>;\n}\n\nexport interface SelectionRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Owns the SVG overlay that paints the selection.\n *\n * Rendering is *line-based*, not glyph-based:\n *\n * 1. Each {@link VisualLine} overlapping the selection produces one rect\n * using the full line-box height (so the selection has even, line-\n * height bands instead of jagged glyph rects).\n * 2. Inter-block gaps fully inside the selection become connector rects.\n * 3. All rects are grouped into vertically-adjacent clusters and each\n * cluster is rendered as a single connected polygon with rounded\n * corners.\n *\n * To keep the polygon connected without gaps, \"middle\" lines (any line\n * that is neither the first nor the last selected line in the document)\n * are extended to their full line extent, while the first and last lines\n * are clipped to the actual selection start/end. This is the standard\n * envelope shape used by IDE selection rendering.\n */\nexport class SelectionView extends Disposable {\n readonly element: SVGSVGElement;\n readonly rendering: IObservable<SelectionViewRendering>;\n\n private readonly _path: SVGPathElement;\n\n constructor(\n private readonly _parent: HTMLElement,\n options: SelectionViewOptions,\n ) {\n super();\n this.element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n this.element.setAttribute('class', 'md-selection-layer');\n this._path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n this._path.setAttribute('class', 'md-selection-path');\n this.element.appendChild(this._path);\n\n this.rendering = derived(this, reader => {\n const selection = reader.readObservable(options.selection);\n const visualLineMap = reader.readObservable(options.visualLineMap);\n const blocks = reader.readObservable(options.blocks);\n return _renderSelection(this._path, this._parent, selection, visualLineMap, blocks);\n });\n\n this._register(autorun(reader => { reader.readObservable(this.rendering); }));\n }\n}\n\nexport class SelectionViewRendering {\n constructor(readonly rects: readonly SelectionRect[]) { }\n}\n\nfunction _renderSelection(\n path: SVGPathElement,\n parent: HTMLElement,\n selection: Selection | undefined,\n visualLineMap: VisualLineMap,\n blocks: readonly SelectionBlock[],\n): SelectionViewRendering {\n if (!selection || selection.isCollapsed) {\n path.setAttribute('d', '');\n return new SelectionViewRendering([]);\n }\n\n const selRange = selection.range;\n const parentRect = parent.getBoundingClientRect();\n\n // 1. Collect visual lines overlapping the selection, paired with the\n // block that contains them.\n const lineInfos: { line: VisualLine; lineRange: OffsetRange; block: SelectionBlock | undefined }[] = [];\n for (const line of visualLineMap.lines) {\n const lineRange = _lineSourceRange(line);\n if (!lineRange || !selRange.intersects(lineRange)) { continue; }\n const block = blocks.find(b => OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length).containsRange(lineRange));\n lineInfos.push({ line, lineRange, block });\n }\n\n const rects: SelectionRect[] = [];\n // Per-line rect in absolute client coordinates (translated to\n // parent-local later). Saved so the connector logic can clip itself\n // to the overlap of the bordering line rects.\n const lineRects: { left: number; right: number; top: number; bottom: number }[] = [];\n\n // One rect per visual line, full line-height. The first line is\n // x-clipped to the selection start; the last line to the selection\n // end. Interior lines use the visual line's own extent (`line.rect`)\n // — the *actual painted text*, not the block element width — so the\n // selection covers the minimum area needed to enclose the content\n // while still forming a connected polygon (adjacent lines in the\n // same block share their left edge, which is enough to connect).\n for (let i = 0; i < lineInfos.length; i++) {\n const { line, lineRange } = lineInfos[i];\n const isFirst = i === 0;\n const isLast = i === lineInfos.length - 1;\n\n const startX = isFirst\n ? line.xAtOffset(Math.max(selRange.start, lineRange.start))\n : line.rect.left;\n const endX = isLast\n ? line.xAtOffset(Math.min(selRange.endExclusive, lineRange.endExclusive))\n : line.rect.right;\n\n rects.push({\n x: startX - parentRect.left,\n y: line.rect.top - parentRect.top,\n width: Math.max(0, endX - startX),\n height: line.rect.height,\n });\n lineRects.push({ left: startX, right: endX, top: line.rect.top, bottom: line.rect.top + line.rect.height });\n }\n\n // 2a. Intra-line-pair connectors: between every consecutive pair of\n // selected lines (same block or not), if there's a vertical gap and\n // the lines share x, fill the gap clipped to that overlap. This\n // matters for blocks like <pre> where `line-height` leaves a few\n // pixels between consecutive lines that the polygon would otherwise\n // not bridge.\n for (let i = 0; i < lineRects.length - 1; i++) {\n const prev = lineRects[i];\n const next = lineRects[i + 1];\n if (next.top <= prev.bottom) { continue; }\n const left = Math.max(prev.left, next.left);\n const right = Math.min(prev.right, next.right);\n if (right <= left) { continue; }\n rects.push({\n x: left - parentRect.left,\n y: prev.bottom - parentRect.top,\n width: right - left,\n height: next.top - prev.bottom,\n });\n }\n\n // 2. Connectors that bridge the visual gap between two consecutive\n // selected blocks. The connector x-range is the overlap of the\n // bordering line rects (the last selected line of the previous block\n // and the first selected line of the next block) so the connector\n // stays as narrow as possible while still bridging both polygons.\n // If the bordering lines don't horizontally overlap at all, the\n // connector degenerates to a 1px-wide bridge at the closer edge so\n // the two clusters merge into one polygon.\n const blockToFirstLineIdx = new Map<SelectionBlock, number>();\n const blockToLastLineIdx = new Map<SelectionBlock, number>();\n for (let i = 0; i < lineInfos.length; i++) {\n const b = lineInfos[i].block;\n if (!b) { continue; }\n if (!blockToFirstLineIdx.has(b)) { blockToFirstLineIdx.set(b, i); }\n blockToLastLineIdx.set(b, i);\n }\n const blockSelected = blocks.map(b =>\n selRange.intersects(OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length))\n );\n for (let i = 0; i < blocks.length - 1; i++) {\n const curr = blocks[i];\n const next = blocks[i + 1];\n const gapStart = curr.absoluteStart + curr.block.length;\n const gapEnd = next.absoluteStart;\n if (gapStart < gapEnd && !selRange.containsRange(OffsetRange.fromTo(gapStart, gapEnd))) { continue; }\n if (gapStart >= gapEnd && !(blockSelected[i] && blockSelected[i + 1])) { continue; }\n\n const currRect = curr.element.getBoundingClientRect();\n const nextRect = next.element.getBoundingClientRect();\n // Extend through any padding so the connector meets the first\n // visual line of the next block, not just the element top.\n const nextFirstLineTop = _firstLineTopOfBlock(visualLineMap, next, nextRect.top);\n const top = currRect.bottom;\n if (nextFirstLineTop <= top) { continue; }\n\n const prevLineIdx = blockToLastLineIdx.get(curr);\n const nextLineIdx = blockToFirstLineIdx.get(next);\n const prevLR = prevLineIdx !== undefined ? lineRects[prevLineIdx] : { left: currRect.left, right: currRect.right };\n const nextLR = nextLineIdx !== undefined ? lineRects[nextLineIdx] : { left: nextRect.left, right: nextRect.right };\n\n const left = Math.max(prevLR.left, nextLR.left);\n const right = Math.min(prevLR.right, nextLR.right);\n // No vertical connector when the bordering line rects don't share\n // any x — the polygon clusterer keeps the two stacks as separate\n // subpaths so we don't get a thin \"jump\" through empty space.\n if (right <= left) { continue; }\n\n rects.push({\n x: left - parentRect.left,\n y: top - parentRect.top,\n width: right - left,\n height: nextFirstLineTop - top,\n });\n }\n\n // 3. Blocks with no text leaves (e.g. <hr>, image, math) that are\n // inside the selection range — they produce no visual lines, so fall\n // back to the block element's bounding rect.\n for (const b of blocks) {\n const blockRange = OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length);\n if (!selRange.intersects(blockRange)) { continue; }\n let hasLine = false;\n for (const { lineRange } of lineInfos) {\n if (lineRange.intersects(blockRange)) { hasLine = true; break; }\n }\n if (hasLine) { continue; }\n const rect = b.element.getBoundingClientRect();\n rects.push({\n x: rect.left - parentRect.left,\n y: rect.top - parentRect.top,\n width: rect.width,\n height: rect.height,\n });\n }\n\n path.setAttribute('d', _buildConnectedPath(rects, 4));\n return new SelectionViewRendering(rects);\n}\n\nfunction _lineSourceRange(line: VisualLine): OffsetRange | undefined {\n if (line.runs.length === 0) { return undefined; }\n let min = Infinity;\n let max = -Infinity;\n for (const run of line.runs) {\n if (run.sourceStart < min) { min = run.sourceStart; }\n if (run.sourceEndExclusive > max) { max = run.sourceEndExclusive; }\n }\n return OffsetRange.fromTo(min, max);\n}\n\n/**\n * Top of the first visual line whose source range falls inside `block`.\n * Falls back to `fallback` (the block element's top) when the block\n * itself has no text leaves (e.g. <hr>, image, math).\n */\nfunction _firstLineTopOfBlock(visualLineMap: VisualLineMap, block: SelectionBlock, fallback: number): number {\n const blockRange = OffsetRange.ofStartAndLength(block.absoluteStart, block.block.length);\n for (const line of visualLineMap.lines) {\n const lineRange = _lineSourceRange(line);\n if (lineRange && blockRange.containsRange(lineRange)) {\n return line.rect.top;\n }\n }\n return fallback;\n}\n\n// ---------- polygon ---------------------------------------------------\n\ninterface PolygonCorner {\n readonly x: number;\n readonly y: number;\n /** True for outer corners (rounded outward), false for inner (rounded inward). */\n readonly convex: boolean;\n}\n\n/**\n * Build one connected SVG path for `rects`. Each cluster of rects that\n * are *both* vertically adjacent and horizontally overlapping with the\n * previous rect becomes one closed sub-shape; any rect that fails either\n * condition starts a new sub-shape. This is what prevents thin \"jumps\"\n * through empty space when two y-adjacent selected lines don't share any\n * x range (e.g. end-of-paragraph vs. start-of-heading further left).\n */\nfunction _buildConnectedPath(rects: readonly SelectionRect[], radius: number): string {\n if (rects.length === 0) { return ''; }\n const sorted = rects.slice().sort((a, b) => a.y - b.y || a.x - b.x);\n\n const clusters: SelectionRect[][] = [];\n let current: SelectionRect[] = [];\n for (const r of sorted) {\n const prev = current[current.length - 1];\n const yTouches = prev !== undefined && r.y <= prev.y + prev.height + 0.5;\n const xOverlaps = prev !== undefined && Math.max(prev.x, r.x) < Math.min(prev.x + prev.width, r.x + r.width);\n if (yTouches && xOverlaps) {\n current.push(r);\n } else {\n if (current.length > 0) { clusters.push(current); }\n current = [r];\n }\n }\n if (current.length > 0) { clusters.push(current); }\n\n return clusters.map(c => _buildClusterPath(c, radius)).filter(Boolean).join(' ');\n}\n\n/**\n * Walk one vertically-adjacent cluster of rects clockwise:\n * top edge of first → down the right side (with steps between lines) →\n * bottom edge of last → up the left side (with steps).\n * Each axis-aligned 90° turn is rendered with a rounded arc.\n */\nfunction _buildClusterPath(rects: SelectionRect[], radius: number): string {\n const corners: PolygonCorner[] = [];\n\n // Right side, top to bottom.\n corners.push({ x: rects[0].x + rects[0].width, y: rects[0].y, convex: true });\n for (let i = 0; i < rects.length - 1; i++) {\n const a = rects[i];\n const b = rects[i + 1];\n const aRight = a.x + a.width;\n const bRight = b.x + b.width;\n if (Math.abs(aRight - bRight) > 0.5) {\n const y = a.y + a.height;\n const aConvex = aRight > bRight;\n corners.push({ x: aRight, y, convex: aConvex });\n corners.push({ x: bRight, y, convex: !aConvex });\n }\n }\n const last = rects[rects.length - 1];\n corners.push({ x: last.x + last.width, y: last.y + last.height, convex: true });\n\n // Left side, bottom to top.\n corners.push({ x: last.x, y: last.y + last.height, convex: true });\n for (let i = rects.length - 1; i > 0; i--) {\n const a = rects[i];\n const b = rects[i - 1];\n if (Math.abs(a.x - b.x) > 0.5) {\n const y = a.y;\n const aConvex = a.x < b.x;\n corners.push({ x: a.x, y, convex: aConvex });\n corners.push({ x: b.x, y, convex: !aConvex });\n }\n }\n corners.push({ x: rects[0].x, y: rects[0].y, convex: true });\n\n return _polygonToRoundedPath(corners, radius);\n}\n\nfunction _polygonToRoundedPath(corners: readonly PolygonCorner[], radius: number): string {\n const n = corners.length;\n if (n < 3) { return ''; }\n\n const radii: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const prev = corners[(i + n - 1) % n];\n const next = corners[(i + 1) % n];\n const dPrev = _dist(corners[i], prev);\n const dNext = _dist(corners[i], next);\n radii[i] = Math.min(radius, dPrev / 2, dNext / 2);\n }\n\n // Approach point of corner 0 on the edge corner[n-1] → corner[0].\n const start = _moveFrom(corners[n - 1], corners[0], _dist(corners[n - 1], corners[0]) - radii[0]);\n const parts: string[] = [`M${_fmt(start.x)},${_fmt(start.y)}`];\n\n for (let i = 0; i < n; i++) {\n const curr = corners[i];\n const next = corners[(i + 1) % n];\n const r = radii[i];\n\n // Arc from approach point of `curr` to departure point on the next edge.\n const depart = _moveFrom(curr, next, r);\n if (r > 0) {\n parts.push(`A${_fmt(r)},${_fmt(r)} 0 0 ${curr.convex ? 1 : 0} ${_fmt(depart.x)},${_fmt(depart.y)}`);\n } else {\n parts.push(`L${_fmt(depart.x)},${_fmt(depart.y)}`);\n }\n\n // Line along the edge up to the approach point of the next corner.\n const nextR = radii[(i + 1) % n];\n const approach = _moveFrom(curr, next, _dist(curr, next) - nextR);\n parts.push(`L${_fmt(approach.x)},${_fmt(approach.y)}`);\n }\n\n parts.push('Z');\n return parts.join(' ');\n}\n\nfunction _dist(a: { x: number; y: number }, b: { x: number; y: number }): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nfunction _moveFrom(from: { x: number; y: number }, to: { x: number; y: number }, dist: number): { x: number; y: number } {\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) { return { x: from.x, y: from.y }; }\n const t = dist / len;\n return { x: from.x + dx * t, y: from.y + dy * t };\n}\n\nfunction _fmt(n: number): string {\n return n.toFixed(2);\n}\n","import { Disposable, autorun, constObservable, derived, observableValue } from '@vscode/observables';\nimport type { IObservable, IReader } from '@vscode/observables';\nimport { Point2D } from '../core/geometry.js';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport type { EditorModel } from '../model/editorModel.js';\nimport { MeasuredLayoutModel, type BlockMeasurement } from '../model/measuredLayoutModel.js';\nimport { caretDomPositionFromPoint } from './content/dom.js';\nimport type { BlockViewOptions } from './content/blockView.js';\nimport { DocumentViewNode, type DocumentBlock } from './content/documentView.js';\nimport { buildDocumentViewData, type DocumentViewData } from './viewData.js';\nimport { CursorView } from './parts/cursorView.js';\nimport { SelectionView, type SelectionBlock } from './parts/selectionView.js';\nimport { VisualLineMap } from './visualLineMap.js';\n\n/** Default max content width (px) used when {@link EditorViewOptions.limitedWidth} is omitted. */\nconst DEFAULT_LIMITED_WIDTH = 900;\n\nexport interface EditorViewOptions extends BlockViewOptions {\n\t/**\n\t * Extra class names added to the editor root element, e.g. a theme class\n\t * such as `'md-theme-default'` or `'github-markdown-theme'`. Theme styles\n\t * are scoped under these classes, so the editor is unstyled (base chrome\n\t * only) unless a theme class is supplied.\n\t */\n\treadonly classNames?: readonly string[];\n\n\t/**\n\t * Controls \"limited width mode\". The observable yields the maximum content\n\t * width in pixels, or `undefined` to let the content fill the available\n\t * width. When the option is omitted, the width is capped at\n\t * {@link DEFAULT_LIMITED_WIDTH}px (limited mode is on by default).\n\t *\n\t * The cap and centering apply to an inner content container; the editor\n\t * root ({@link element}) always spans the full available width.\n\t */\n\treadonly limitedWidth?: IObservable<number | undefined>;\n}\n\n/**\n * Pure-render view of an {@link EditorModel}.\n *\n * Invariant (the whole point of this file):\n *\n * view(model + Δ) = view(model) + Δ\n *\n * The DOM the view produces is a function of the model. The only state the\n * view holds is *DOM management*: the cached `BlockViewNode` instances and the\n * `EditContext`. Anything that influences correctness but is not derivable\n * from the model lives elsewhere:\n *\n * - measured heights and per-block visual line maps → {@link MeasuredLayoutModel}\n * - desired column, drag-time freeze → EditorController\n *\n * The view does not own a controller — callers construct an\n * `EditorController` separately and pass it the view, so input handling is\n * explicit and the view stays a pure renderer.\n *\n * The view writes into the measured-layout model as a side effect of\n * rendering. It never reads its own measurements during rendering, so\n * there is no feedback loop.\n */\nexport class EditorView extends Disposable {\n\treadonly element: HTMLElement;\n\treadonly editContext: EditContext;\n\treadonly measuredLayout: MeasuredLayoutModel;\n\n\t/**\n\t * Inner container that holds the rendered document and the cursor/selection\n\t * overlays. The outer {@link element} spans the full width; this container\n\t * is what limited-width mode caps and centers, so the overlays (which anchor\n\t * to their parent's box) stay aligned with the content.\n\t */\n\tprivate readonly _contentContainer: HTMLElement;\n\n\tprivate readonly _cursorView: CursorView;\n\tprivate readonly _selectionView: SelectionView;\n\n\t/**\n\t * The mounted block sequence, in source order. Rebuilt (not mutated) each\n\t * frame by {@link DocumentViewNode.create}; the view just swaps one\n\t * immutable node for the next. Never used for source-of-truth lookups\n\t * (those go through the measured-layout model).\n\t */\n\tprivate readonly _document = observableValue<DocumentViewNode | undefined>(this, undefined);\n\n\t/** The current view-node tree (AST overlaid with rendered DOM), for debugging. */\n\tpublic get documentViewNode(): IObservable<DocumentViewNode | undefined> { return this._document; }\n\n\t/**\n\t * Last frame's view-data overlay, threaded back into\n\t * {@link buildDocumentViewData} so any subtree whose ast and selection flags\n\t * are unchanged keeps its view-data object — which lets the renderer reuse\n\t * its DOM by identity.\n\t */\n\tprivate _previousViewData: DocumentViewData | undefined;\n\n\t/** The current view-data tree (AST overlaid with selection flags), for debugging. */\n\tprivate readonly _viewData = observableValue<DocumentViewData | undefined>(this, undefined);\n\tpublic get viewData(): IObservable<DocumentViewData | undefined> { return this._viewData; }\n\n\t/**\n\t * The block cache projected for views (selection painting) that need to\n\t * react to mount/unmount. Derived from {@link _document}, so it stays in\n\t * lock-step without any manual bookkeeping.\n\t */\n\tprivate readonly _selectionBlocksObs = derived(this, reader => {\n\t\tconst doc = this._document.read(reader);\n\t\tif (!doc) { return []; }\n\t\treturn doc.blocks.map((b): SelectionBlock => ({\n\t\t\tblock: b.node.block,\n\t\t\tabsoluteStart: b.absoluteStart,\n\t\t\tviewNode: b.node,\n\t\t\telement: b.node.element,\n\t\t}));\n\t});\n\n\tconstructor(\n\t\tprivate readonly _model: EditorModel,\n\t\tprivate readonly _options?: EditorViewOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-editor';\n\t\tif (this._options?.classNames) {\n\t\t\tthis.element.classList.add(...this._options.classNames);\n\t\t}\n\t\tthis.element.tabIndex = 0;\n\n\t\tthis._contentContainer = document.createElement('div');\n\t\tthis._contentContainer.className = 'md-editor-content';\n\t\tthis.element.appendChild(this._contentContainer);\n\n\t\tconst limitedWidth = this._options?.limitedWidth ?? constObservable<number | undefined>(DEFAULT_LIMITED_WIDTH);\n\t\tthis._register(autorun(reader => {\n\t\t\tconst width = limitedWidth.read(reader);\n\t\t\tthis._contentContainer.style.maxWidth = width === undefined ? '' : `${width}px`;\n\t\t}));\n\n\t\tthis.measuredLayout = new MeasuredLayoutModel();\n\n\t\tthis._selectionView = this._register(new SelectionView(this._contentContainer, {\n\t\t\tselection: this._model.selection,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t\tblocks: this._selectionBlocksObs,\n\t\t}));\n\t\tthis._contentContainer.appendChild(this._selectionView.element);\n\n\t\tthis._cursorView = this._register(new CursorView(this._contentContainer, {\n\t\t\toffset: this._model.cursorOffset,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t}));\n\t\tthis._contentContainer.appendChild(this._cursorView.element);\n\n\t\tthis.editContext = new EditContext({\n\t\t\ttext: this._model.sourceText.get().value,\n\t\t\tselectionStart: 0,\n\t\t\tselectionEnd: 0,\n\t\t});\n\t\tthis.element.editContext = this.editContext;\n\n\t\tthis._register(autorun(this._renderAutorun));\n\t\tthis._register(autorun(reader => {\n\t\t\tconst sel = reader.readObservable(this._model.selection)?.range;\n\t\t\tthis.editContext.updateSelection(sel?.start ?? 0, sel?.endExclusive ?? 0);\n\t\t}));\n\t\tthis._register({ dispose: () => { this._document.get()?.dispose(); } });\n\t}\n\n\tfocus(): void { this.element.focus({ preventScroll: true }); }\n\n\t/**\n\t * Client coordinates → absolute source offset (any block). Used during\n\t * drag to keep extending the selection even when the pointer leaves the\n\t * original block.\n\t */\n\tresolveOffsetFromPoint(point: Point2D): SourceOffset | undefined {\n\t\tconst pos = caretDomPositionFromPoint(point);\n\t\tif (!pos) { return undefined; }\n\t\treturn this._document.get()?.resolveSource(pos);\n\t}\n\n\t/**\n\t * Whether a client point falls on the rendered document content, as\n\t * opposed to the surrounding editor padding (the green area). Uses DOM\n\t * containment rather than the content node's bounding box so that markers\n\t * which overflow into the padding (e.g. a heading's `##`, which renders in\n\t * the left margin) still count as content. Overlays (cursor, selection)\n\t * have `pointer-events: none`, so the hit-test sees through them.\n\t */\n\tisPointInContent(point: Point2D): boolean {\n\t\tconst content = this._document.get()?.contentDomNode;\n\t\tif (!content) { return false; }\n\t\tconst hit = document.elementFromPoint(point.x, point.y);\n\t\treturn hit !== null && content.contains(hit);\n\t}\n\n\t// ----- render autorun ------------------------------------------------\n\n\tprivate readonly _renderAutorun = (reader: IReader): void => {\n\t\tconst doc = reader.readObservable(this._model.document);\n\t\tconst sourceText = reader.readObservable(this._model.sourceText).value;\n\t\tconst activeBlocks = reader.readObservable(this._model.activeBlocks);\n\t\tconst selection = reader.readObservable(this._model.selection);\n\n\t\tif (this.editContext.text !== sourceText) {\n\t\t\tthis.editContext.updateText(0, this.editContext.text.length, sourceText);\n\t\t}\n\n\t\t// Rebuild the document node, reusing the previous one's blocks where\n\t\t// the AST identity and render inputs are unchanged. The parser\n\t\t// preserves block objects across reparses (see {@link MarkdownParser.parse}),\n\t\t// so a matching `Block` reference means the rendered DOM is still valid.\n\t\tconst previous = this._document.get();\n\t\t// Overlay the AST with the selection-derived flags, reusing the previous\n\t\t// frame's view-data for any unchanged subtree so the rebuild below collapses\n\t\t// to a single identity check per node (see {@link buildDocumentViewData}).\n\t\tconst viewData = buildDocumentViewData(doc, activeBlocks, selection?.range, this._previousViewData);\n\t\tthis._previousViewData = viewData;\n\t\tthis._viewData.set(viewData, undefined);\n\t\tconst documentNode = DocumentViewNode.create(viewData, this._options, previous);\n\t\tif (previous) {\n\t\t\t// The content element is stable across rebuilds, so once mounted it\n\t\t\t// never moves.\n\t\t\tif (documentNode.contentDomNode !== previous.contentDomNode) {\n\t\t\t\tthrow new Error('DocumentViewNode.contentDomNode must be stable across rebuilds');\n\t\t\t}\n\t\t} else {\n\t\t\t// First render: mount the freshly-created content element ahead of\n\t\t\t// the selection/cursor overlays.\n\t\t\tthis._contentContainer.insertBefore(documentNode.contentDomNode, this._contentContainer.firstChild);\n\t\t}\n\t\tthis._document.set(documentNode, undefined);\n\t\tthis._publishMeasurements(documentNode);\n\t};\n\n\t/** Current mounted blocks, or empty before the first render. */\n\tprivate get _blocks(): readonly DocumentBlock[] {\n\t\treturn this._document.get()?.blocks ?? [];\n\t}\n\n\t/**\n\t * Measure each mounted block's rect and per-block visual line map, then\n\t * publish the result into the {@link MeasuredLayoutModel}. The model\n\t * is not read here, so there is no feedback loop into the render autorun.\n\t */\n\tprivate _publishMeasurements(document: DocumentViewNode): void {\n\t\tconst measurements: BlockMeasurement[] = [];\n\t\tfor (const entry of document.blocks) {\n\t\t\tconst blockRect = entry.node.element.getBoundingClientRect();\n\t\t\t// Let the block remember its own measured height (a math block reserves\n\t\t\t// its rendered height to keep the layout stable across the active toggle).\n\t\t\tentry.node.recordMeasuredHeight(blockRect.height);\n\t\t\tconst visualLineMap = VisualLineMap.measure([{\n\t\t\t\tabsoluteStart: entry.absoluteStart,\n\t\t\t\tviewNode: entry.node,\n\t\t\t}]);\n\t\t\tmeasurements.push({\n\t\t\t\tblock: entry.node.block,\n\t\t\t\tabsoluteStart: entry.absoluteStart,\n\t\t\t\theight: blockRect.height,\n\t\t\t\tisMeasured: true,\n\t\t\t\tvisualLineMap,\n\t\t\t\tviewNode: entry.node,\n\t\t\t});\n\t\t}\n\t\tthis.measuredLayout.measurements.set(measurements, undefined);\n\t}\n}\n","import type { IDisposable } from '@vscode/observables';\n\n/**\n * The editor operations a clipboard strategy drives. The strategy never\n * touches the model or the DOM directly — it asks through this seam, so the\n * same strategy works regardless of how the editor is wired up.\n */\nexport interface IClipboardContext {\n /** The element that owns focus and receives clipboard/keyboard events. */\n readonly element: HTMLElement;\n /** The selected source text, or `undefined` when the selection is empty. */\n getSelectedText(): string | undefined;\n /** Delete the current selection (the cut half of cut). */\n deleteSelection(): void;\n /** Insert text at the caret, replacing any selection (the paste action). */\n insertText(text: string): void;\n}\n\n/**\n * How copy/cut/paste intent reaches the editor. Host environments deliver it\n * differently, so the controller owns no clipboard logic itself — it\n * {@link connect}s a strategy and lets it install whatever listeners it needs.\n *\n * Two implementations ship:\n * - {@link NativeClipboardStrategy} (default) reads the browser's native\n * `copy`/`cut`/`paste` events and their synchronous `clipboardData`.\n * - {@link AsyncClipboardStrategy} drives the async `navigator.clipboard` API\n * from Ctrl/Cmd+C/X/V keystrokes, for hosts (e.g. VS Code webviews) that\n * swallow the native clipboard events before they reach the editor.\n */\nexport interface IClipboardStrategy {\n /**\n * Wire up clipboard handling against `context`. The returned disposable\n * tears down every listener the strategy installed.\n */\n connect(context: IClipboardContext): IDisposable;\n}\n\n/**\n * Default strategy: handle the browser's native `copy`/`cut`/`paste` events,\n * reading and writing the synchronous {@link ClipboardEvent.clipboardData}.\n * This is the standard rich-editor approach and works wherever the browser\n * actually dispatches those events to the focused element (e.g. a standalone\n * web page).\n */\nexport class NativeClipboardStrategy implements IClipboardStrategy {\n connect(context: IClipboardContext): IDisposable {\n const onCopy = (e: ClipboardEvent): void => {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n e.clipboardData?.setData('text/plain', text);\n };\n const onCut = (e: ClipboardEvent): void => {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n e.clipboardData?.setData('text/plain', text);\n context.deleteSelection();\n };\n const onPaste = (e: ClipboardEvent): void => {\n e.preventDefault();\n const text = e.clipboardData?.getData('text/plain');\n if (!text) { return; }\n context.insertText(text);\n };\n\n const el = context.element;\n el.addEventListener('copy', onCopy);\n el.addEventListener('cut', onCut);\n el.addEventListener('paste', onPaste);\n return {\n dispose: () => {\n el.removeEventListener('copy', onCopy);\n el.removeEventListener('cut', onCut);\n el.removeEventListener('paste', onPaste);\n },\n };\n }\n}\n\n/**\n * Strategy for hosts that never deliver native clipboard events to the editor\n * — most importantly VS Code webviews, whose preload calls `preventDefault()`\n * on the Ctrl/Cmd+C/X/V keydowns, so no `copy`/`cut`/`paste` event is ever\n * dispatched. Here the keystrokes are the only signal, so this strategy\n * listens for them directly and drives the async {@link Clipboard} API\n * (`navigator.clipboard`), which webviews are granted.\n *\n * Cut deletes synchronously once the text is captured; the clipboard write is\n * fire-and-forget. Paste must wait for the async read before inserting.\n */\nexport class AsyncClipboardStrategy implements IClipboardStrategy {\n constructor(private readonly _clipboard: Clipboard = navigator.clipboard) { }\n\n connect(context: IClipboardContext): IDisposable {\n const onKeyDown = (e: KeyboardEvent): void => {\n const ctrl = e.ctrlKey || e.metaKey;\n if (!ctrl || e.altKey) { return; }\n\n switch (e.key.toLowerCase()) {\n case 'c': {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n void this._clipboard.writeText(text);\n break;\n }\n case 'x': {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n void this._clipboard.writeText(text);\n context.deleteSelection();\n break;\n }\n case 'v': {\n e.preventDefault();\n void this._clipboard.readText().then(text => {\n if (text) { context.insertText(text); }\n });\n break;\n }\n }\n };\n\n const el = context.element;\n el.addEventListener('keydown', onKeyDown);\n return { dispose: () => el.removeEventListener('keydown', onKeyDown) };\n }\n}\n","import { Disposable } from '@vscode/observables';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { Point2D } from '../core/geometry.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { Selection } from '../core/selection.js';\nimport type { EditorModel } from '../model/editorModel.js';\nimport type { BlockAstNode, DocumentAstNode } from '../parser/ast.js';\nimport {\n cursorRight, cursorLeft, cursorMoveRight, cursorMoveLeft,\n cursorWordRight, cursorWordLeft, cursorLineStart, cursorLineEnd,\n cursorDocumentStart, cursorDocumentEnd, cursorUp, cursorDown,\n} from '../commands/cursorCommands.js';\nimport {\n deleteLeft, deleteRight, deleteWordLeft, deleteWordRight,\n insertText, insertParagraph, insertLineBreak, insertHardLineBreak,\n} from '../commands/editCommands.js';\nimport { selectAll, selectWord, selectBlock } from '../commands/selectionCommands.js';\nimport type { CursorCommand, EditCommand, VisualCursorCommand, CursorCommandContext, VisualCursorCommandContext } from '../commands/types.js';\nimport type { EditorView } from './editorView.js';\nimport { NativeClipboardStrategy, type IClipboardStrategy } from './clipboardStrategy.js';\n\n/** Options for an {@link EditorController}. */\nexport interface EditorControllerOptions {\n /**\n * How copy/cut/paste is handled. Defaults to {@link NativeClipboardStrategy},\n * which reads the browser's native clipboard events — pass a different\n * strategy (e.g. `AsyncClipboardStrategy`) in hosts that swallow them.\n */\n readonly clipboardStrategy?: IClipboardStrategy;\n}\n\n/**\n * Translates raw browser input (mouse, keyboard, EditContext) into model\n * mutations. Knows about DOM event types but never reads/writes the DOM\n * directly — it asks the {@link EditorView} to broker DOM↔source-offset\n * conversions so the model stays free of view types.\n *\n * Owns the only non-derivable controller state:\n * - `_desiredColumn` — sticky column for up/down navigation\n */\nexport class EditorController extends Disposable {\n private _desiredColumn: number | undefined;\n\n constructor(\n private readonly _model: EditorModel,\n private readonly _view: EditorView,\n options?: EditorControllerOptions,\n ) {\n super();\n const el = this._view.element;\n el.addEventListener('mousedown', this._handleMouseDown);\n el.addEventListener('keydown', this._handleKeyDown);\n this._register({\n dispose: () => {\n el.removeEventListener('mousedown', this._handleMouseDown);\n el.removeEventListener('keydown', this._handleKeyDown);\n },\n });\n\n const clipboardStrategy = options?.clipboardStrategy ?? new NativeClipboardStrategy();\n this._register(clipboardStrategy.connect({\n element: el,\n getSelectedText: () => this._selectedText(),\n deleteSelection: () => this._executeEditCommand(deleteLeft),\n insertText: text => this._executeEditCommand(insertText(text)),\n }));\n\n const editContext = this._view.editContext;\n editContext.addEventListener('textupdate', this._handleTextUpdate);\n this._register({\n dispose: () => editContext.removeEventListener('textupdate', this._handleTextUpdate as EventListener),\n });\n }\n\n private readonly _handleTextUpdate = (e: TextUpdateEvent): void => {\n const edit = StringEdit.replace(\n new OffsetRange(e.updateRangeStart, e.updateRangeEnd),\n e.text,\n );\n this._model.applyEdit(edit);\n };\n\n private readonly _handleMouseDown = (e: MouseEvent): void => {\n e.preventDefault();\n this._view.focus();\n this._desiredColumn = undefined;\n\n const point = new Point2D(e.clientX, e.clientY);\n\n // A click on the editor padding (outside the rendered document content)\n // clears the selection entirely.\n if (!this._view.isPointInContent(point)) {\n this._model.selection.set(undefined, undefined);\n return;\n }\n\n const offset = this._view.resolveOffsetFromPoint(point)\n ?? this._model.sourceText.get().value.length;\n\n if (e.detail === 2) {\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectWord(ctx, offset), undefined);\n return;\n }\n\n if (e.detail === 3) {\n const blockRange = findBlockRangeAt(this._model.document.get(), offset);\n if (blockRange) {\n this._model.selection.set(selectBlock(this._makeCursorContext(), blockRange), undefined);\n }\n return;\n }\n\n if (e.shiftKey) {\n const sel = this._model.selection.get() ?? Selection.collapsed(offset);\n this._model.selection.set(sel.withActive(offset), undefined);\n } else {\n this._model.selection.set(Selection.collapsed(offset), undefined);\n }\n\n const onMouseMove = (me: MouseEvent): void => {\n const sel = this._model.selection.get() ?? Selection.collapsed(offset);\n const moveOffset = this._view.resolveOffsetFromPoint(new Point2D(me.clientX, me.clientY))\n ?? sel.active;\n this._model.selection.set(new Selection(sel.anchor, moveOffset), undefined);\n };\n const onMouseUp = (): void => {\n document.removeEventListener('mousemove', onMouseMove);\n document.removeEventListener('mouseup', onMouseUp);\n };\n document.addEventListener('mousemove', onMouseMove);\n document.addEventListener('mouseup', onMouseUp);\n };\n\n private _makeCursorContext(): CursorCommandContext {\n return {\n text: this._model.sourceText.get().value,\n selection: this._model.selection.get() ?? Selection.collapsed(0),\n document: this._model.document.get(),\n activeBlock: this._model.activeBlock.get(),\n };\n }\n\n private _makeVisualCursorContext(): VisualCursorCommandContext {\n return {\n ...this._makeCursorContext(),\n desiredColumn: this._desiredColumn,\n lineMap: this._view.measuredLayout.visualLineMap.get(),\n };\n }\n\n private _executeCursorCommand(command: CursorCommand, extend: boolean): void {\n const ctx = this._makeCursorContext();\n const newOffset = command(ctx);\n const sel = ctx.selection;\n this._model.selection.set(\n extend ? sel.withActive(newOffset) : Selection.collapsed(newOffset),\n undefined,\n );\n this._desiredColumn = undefined;\n }\n\n private _executeEditCommand(command: EditCommand): void {\n const ctx = this._makeCursorContext();\n const result = command(ctx);\n if (!result) { return; }\n this._model.applyEdit(result.edit);\n this._desiredColumn = undefined;\n }\n\n private _executeVisualCursorCommand(command: VisualCursorCommand, extend: boolean): void {\n const ctx = this._makeVisualCursorContext();\n const result = command(ctx);\n this._model.selection.set(\n extend ? ctx.selection.withActive(result.offset) : Selection.collapsed(result.offset),\n undefined,\n );\n this._desiredColumn = result.desiredColumn;\n }\n\n /** Move the cursor down one visual line (Arrow Down). */\n cursorDown(extend = false): void {\n this._executeVisualCursorCommand(cursorDown, extend);\n }\n\n /** Move the cursor up one visual line (Arrow Up). */\n cursorUp(extend = false): void {\n this._executeVisualCursorCommand(cursorUp, extend);\n }\n\n private _selectedText(): string | undefined {\n const sel = this._model.selection.get();\n if (!sel || sel.isCollapsed) { return undefined; }\n return this._model.sourceText.get().value.slice(sel.range.start, sel.range.endExclusive);\n }\n\n private readonly _handleKeyDown = (e: KeyboardEvent): void => {\n const ctrl = e.ctrlKey || e.metaKey;\n\n if (e.key === 'ArrowLeft') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(e.shiftKey ? cursorWordLeft : cursorWordLeft, e.shiftKey);\n } else if (e.shiftKey) {\n this._executeCursorCommand(cursorMoveLeft, true);\n } else {\n this._executeCursorCommand(cursorLeft, false);\n }\n } else if (e.key === 'ArrowRight') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorWordRight, e.shiftKey);\n } else if (e.shiftKey) {\n this._executeCursorCommand(cursorMoveRight, true);\n } else {\n this._executeCursorCommand(cursorRight, false);\n }\n } else if (e.key === 'ArrowUp') {\n e.preventDefault();\n this._executeVisualCursorCommand(cursorUp, e.shiftKey);\n } else if (e.key === 'ArrowDown') {\n e.preventDefault();\n this._executeVisualCursorCommand(cursorDown, e.shiftKey);\n } else if (e.key === 'Home') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorDocumentStart, e.shiftKey);\n } else {\n this._executeCursorCommand(cursorLineStart, e.shiftKey);\n }\n } else if (e.key === 'End') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorDocumentEnd, e.shiftKey);\n } else {\n this._executeCursorCommand(cursorLineEnd, e.shiftKey);\n }\n } else if (e.key === 'a' && ctrl) {\n e.preventDefault();\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectAll(ctx, 0), undefined);\n } else if (e.key === 'Backspace') {\n e.preventDefault();\n this._executeEditCommand(ctrl ? deleteWordLeft : deleteLeft);\n } else if (e.key === 'Delete') {\n e.preventDefault();\n this._executeEditCommand(ctrl ? deleteWordRight : deleteRight);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n this._executeEditCommand(ctrl ? insertParagraph : e.shiftKey ? insertHardLineBreak : insertLineBreak);\n }\n };\n}\n\nfunction findBlockRangeAt(doc: DocumentAstNode, offset: number): OffsetRange | undefined {\n let pos = 0;\n for (const child of doc.children) {\n if (doc.blocks.includes(child as BlockAstNode)) {\n const range = OffsetRange.ofStartAndLength(pos, child.length);\n if (range.contains(offset) || range.endExclusive === offset) {\n return range;\n }\n }\n pos += child.length;\n }\n return undefined;\n}\n","import { Disposable, autorun, derived, observableValue, type IObservable, type ISettableObservable } from '@vscode/observables';\nimport type { BlockMeasurement, MeasuredLayoutModel } from '../model/measuredLayoutModel.js';\nimport type { ViewNode } from './content/viewNode.js';\n\nconst _SHOW_LINE_RECTS_KEY = 'md-debug-show-line-rects';\n\nfunction _readStoredBool(key: string, fallback: boolean): boolean {\n try {\n const v = localStorage.getItem(key);\n return v === null ? fallback : v === 'true';\n } catch {\n return fallback;\n }\n}\n\nfunction _writeStoredBool(key: string, value: boolean): void {\n try {\n localStorage.setItem(key, String(value));\n } catch {\n // Ignore: debug-only, storage may be unavailable.\n }\n}\n\nexport interface MeasuredLayoutDebugViewOptions {\n readonly model: MeasuredLayoutModel;\n /**\n * DEBUG ONLY. Maps an absolute source offset to a fill color for that\n * character's glyph rect. The fixture passes the same function to the\n * raw-source view so a character and its rect share one color — a\n * mismatch exposes a source ↔ DOM mapping bug.\n */\n readonly colorForOffset?: (offset: number) => string | undefined;\n /**\n * DEBUG ONLY. Shared \"currently hovered source offset\". When set, the\n * overlay isolates the matching glyph rect; the fixture passes the same\n * observable to the raw-source view so hovering either side highlights the\n * same character in both. Hovering a rect writes this; `undefined` clears.\n */\n readonly hoveredOffset?: ISettableObservable<number | undefined>;\n}\n\n/**\n * Debug view for a {@link MeasuredLayoutModel}.\n *\n * Exposes two DOM nodes the caller can place independently:\n *\n * - {@link overlayElement} — absolutely positioned; the caller mounts it\n * inside the editor element so dashed line-bands and run-boxes line up\n * with the editor's client coordinates.\n * - {@link infoElement} — block-flow; the caller mounts it as a sibling\n * *below* the editor. Contains the per-block summary table that used\n * to live on the overlay.\n *\n * Same pattern as `CursorView` / `SelectionView`: the rendering pipeline\n * is a single `derived` whose compute callback writes the DOM and returns\n * a {@link MeasuredLayoutDebugRendering} value as proof. An autorun keeps\n * the derived subscribed.\n */\nexport class MeasuredLayoutDebugView extends Disposable {\n readonly overlayElement: HTMLElement;\n readonly infoElement: HTMLElement;\n readonly rendering: IObservable<MeasuredLayoutDebugRendering>;\n\n /** Absolute source offsets that map to a rendered DOM character. */\n readonly mappedOffsets: IObservable<ReadonlySet<number>>;\n\n /** Whether the dashed line-bands and run boxes are drawn (persisted). */\n private readonly _showLineRects = observableValue(this, _readStoredBool(_SHOW_LINE_RECTS_KEY, true));\n\n constructor(\n private readonly _overlayParent: HTMLElement,\n options: MeasuredLayoutDebugViewOptions,\n ) {\n super();\n\n this.overlayElement = document.createElement('div');\n this.overlayElement.className = 'md-debug-layout-overlay';\n Object.assign(this.overlayElement.style, {\n position: 'absolute',\n top: '0',\n left: '0',\n right: '0',\n bottom: '0',\n pointerEvents: 'none',\n } satisfies Partial<CSSStyleDeclaration>);\n\n this.infoElement = document.createElement('div');\n this.infoElement.className = 'md-debug-layout-info';\n Object.assign(this.infoElement.style, {\n fontFamily: 'monospace',\n fontSize: '11px',\n padding: '8px 12px',\n background: '#111',\n color: '#fff',\n borderRadius: '4px',\n lineHeight: '1.4',\n } satisfies Partial<CSSStyleDeclaration>);\n\n // Controls row (survives re-render) + a text element the render rewrites.\n const controls = document.createElement('label');\n Object.assign(controls.style, {\n display: 'flex',\n alignItems: 'center',\n gap: '6px',\n marginBottom: '6px',\n cursor: 'pointer',\n userSelect: 'none',\n } satisfies Partial<CSSStyleDeclaration>);\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = this._showLineRects.get();\n checkbox.addEventListener('change', () => {\n this._showLineRects.set(checkbox.checked, undefined);\n _writeStoredBool(_SHOW_LINE_RECTS_KEY, checkbox.checked);\n });\n controls.appendChild(checkbox);\n controls.appendChild(document.createTextNode('show line rects'));\n this.infoElement.appendChild(controls);\n\n const text = document.createElement('pre');\n text.style.margin = '0';\n text.style.whiteSpace = 'pre';\n this.infoElement.appendChild(text);\n\n this.rendering = derived(this, reader => {\n const measurements = reader.readObservable(options.model.measurements);\n const showLineRects = reader.readObservable(this._showLineRects);\n return _renderDebug(this.overlayElement, text, this._overlayParent, measurements, showLineRects, options.colorForOffset, options.hoveredOffset);\n });\n\n this.mappedOffsets = derived(this, reader => reader.readObservable(this.rendering).mappedOffsets);\n\n // Re-read `rendering` so isolation re-applies after every rebuild, and\n // `hoveredOffset` so hovering either view isolates the matching rect.\n this._register(autorun(reader => {\n reader.readObservable(this.rendering);\n const hovered = options.hoveredOffset ? reader.readObservable(options.hoveredOffset) : undefined;\n if (options.hoveredOffset) { applyHoverIsolation(this.overlayElement, hovered); }\n }));\n }\n}\n\n\n/**\n * Immutable record of one rendered debug frame.\n */\nexport class MeasuredLayoutDebugRendering {\n constructor(\n readonly blockCount: number,\n readonly mountedCount: number,\n readonly lineCount: number,\n /** Absolute source offsets that map to a rendered DOM character. */\n readonly mappedOffsets: ReadonlySet<number>,\n ) { }\n}\n\nfunction _renderDebug(\n overlay: HTMLElement,\n info: HTMLElement,\n overlayParent: HTMLElement,\n measurements: readonly BlockMeasurement[],\n showLineRects: boolean,\n colorForOffset?: (offset: number) => string | undefined,\n hoveredOffset?: ISettableObservable<number | undefined>,\n): MeasuredLayoutDebugRendering {\n overlay.textContent = '';\n const parentRect = overlayParent.getBoundingClientRect();\n\n let mountedCount = 0;\n let lineCount = 0;\n let charCount = 0;\n const mappedOffsets = new Set<number>();\n\n for (let i = 0; i < measurements.length; i++) {\n const m = measurements[i];\n const lines = m.visualLineMap?.lines ?? [];\n if (m.isMeasured) { mountedCount++; }\n lineCount += lines.length;\n\n if (showLineRects) {\n for (let li = 0; li < lines.length; li++) {\n const line = lines[li];\n const lineRect = line.rect;\n const band = document.createElement('div');\n Object.assign(band.style, {\n position: 'absolute',\n left: '0',\n right: '0',\n top: `${lineRect.y - parentRect.top}px`,\n height: `${lineRect.height}px`,\n border: '1px dashed rgba(180, 0, 200, 0.45)',\n boxSizing: 'border-box',\n } satisfies Partial<CSSStyleDeclaration>);\n overlay.appendChild(band);\n\n for (const run of line.runs) {\n const runBox = document.createElement('div');\n Object.assign(runBox.style, {\n position: 'absolute',\n left: `${run.rect.x - parentRect.left}px`,\n top: `${run.rect.y - parentRect.top}px`,\n width: `${run.rect.width}px`,\n height: `${run.rect.height}px`,\n outline: '1px solid rgba(255, 100, 0, 0.45)',\n boxSizing: 'border-box',\n } satisfies Partial<CSSStyleDeclaration>);\n overlay.appendChild(runBox);\n }\n }\n }\n\n // Per-character glyph rects (mounted blocks only). Resolve each source\n // offset back to a DOM position through the production source ↔ DOM\n // mapping, so a misplaced rect reveals a mapping bug.\n if (m.viewNode) {\n charCount += _appendCharRects(overlay, parentRect, m.viewNode, m.absoluteStart, mappedOffsets, colorForOffset, hoveredOffset);\n }\n }\n\n const header = `blocks: ${measurements.length} mounted: ${mountedCount} lines: ${lineCount} chars: ${charCount}`;\n const rows = measurements.map((m, i) => {\n const flag = m.isMeasured ? 'M' : 'e';\n const lc = m.visualLineMap?.lines.length ?? 0;\n return `${String(i).padStart(2)} ${flag} start=${String(m.absoluteStart).padStart(4)} h=${m.height.toFixed(1).padStart(6)} lines=${lc} kind=${m.block.kind}`;\n });\n info.textContent = [header, ...rows].join('\\n');\n\n return new MeasuredLayoutDebugRendering(measurements.length, mountedCount, lineCount, mappedOffsets);\n}\n\n/**\n * Draw one filled box per character of the block's source range. Each source\n * offset `o` is mapped to a DOM position with {@link ViewNode.sourceToDom}\n * (the same mapping the cursor uses), and `[o, o+1)` is measured with a\n * `Range`. The box is filled (no border) with {@link colorForOffset}`(o)` so\n * it matches the same character in the raw-source view.\n *\n * Each box carries `data-offset` so {@link applyHoverIsolation} can isolate it.\n * Hovering a box writes its offset into {@link hoveredOffset} (shared with the\n * raw-source view); when no shared observable is supplied it falls back to a\n * local overlay-only isolation. Returns the number of character boxes appended.\n */\nfunction _appendCharRects(\n overlay: HTMLElement,\n parentRect: DOMRect,\n viewNode: ViewNode,\n blockAbsoluteStart: number,\n mappedOffsets: Set<number>,\n colorForOffset?: (offset: number) => string | undefined,\n hoveredOffset?: ISettableObservable<number | undefined>,\n): number {\n let count = 0;\n const range = document.createRange();\n const end = blockAbsoluteStart + viewNode.sourceLength;\n // Source offsets actually backed by a rendered DOM Text leaf. Characters\n // outside any leaf (list markers `- `, newlines, other syntax) are not\n // rendered, so we must not draw a rect for them. `sourceToDom` alone can't\n // tell them apart because it clamps unmapped offsets to an adjacent leaf's\n // boundary; the leaf coverage from `forEachTextLeaf` is authoritative.\n const covered: Array<{ start: number; end: number }> = [];\n viewNode.forEachTextLeaf(blockAbsoluteStart, (leaf, leafOffset) => {\n covered.push({ start: leafOffset, end: leafOffset + leaf.sourceLength });\n });\n const isCovered = (o: number) => covered.some(r => o >= r.start && o < r.end);\n for (let o = blockAbsoluteStart; o < end; o++) {\n if (!isCovered(o)) { continue; }\n // The character occupies source range [o, o+1). Use its END position to\n // identify the rendered DOM character, then step back one within the\n // same Text node to get its start.\n const b = viewNode.sourceToDom(o + 1, blockAbsoluteStart);\n if (!b || b.offset < 1) { continue; }\n range.setStart(b.node, b.offset - 1);\n range.setEnd(b.node, b.offset);\n const rect = range.getBoundingClientRect();\n // A character with no height isn't laid out at all — skip it. A\n // zero-WIDTH rect, though, is a real mapped character that simply has no\n // advance (a `\\n` inside a code block maps to a real `\\n` Text node):\n // render it as a thin 2px line so the mapping is still visible.\n if (rect.height === 0) { continue; }\n const drawWidth = rect.width === 0 ? 2 : rect.width;\n const box = document.createElement('div');\n Object.assign(box.style, {\n position: 'absolute',\n left: `${rect.x - parentRect.left}px`,\n top: `${rect.y - parentRect.top}px`,\n width: `${drawWidth}px`,\n height: `${rect.height}px`,\n background: colorForOffset?.(o) ?? 'rgba(0, 120, 220, 0.30)',\n boxSizing: 'border-box',\n pointerEvents: 'auto',\n } satisfies Partial<CSSStyleDeclaration>);\n const ch = (b.node as Text).data?.[b.offset - 1] ?? '';\n box.title = `offset ${o}: ${JSON.stringify(ch)}`;\n box.dataset.offset = String(o);\n if (hoveredOffset) {\n box.addEventListener('mouseenter', () => hoveredOffset.set(o, undefined));\n box.addEventListener('mouseleave', () => hoveredOffset.set(undefined, undefined));\n } else {\n box.addEventListener('mouseenter', () => _isolate(overlay, box, true));\n box.addEventListener('mouseleave', () => _isolate(overlay, box, false));\n }\n overlay.appendChild(box);\n mappedOffsets.add(o);\n count++;\n }\n return count;\n}\n\n/**\n * Show only the element whose `data-offset` equals `hovered`, hiding every\n * other child (and all children lacking a `data-offset`, e.g. line bands).\n * When `hovered` is `undefined` everything is restored. `visibility: hidden`\n * preserves layout so the source view's text never reflows.\n *\n * Used identically for the editor overlay and the raw-source view, so a hover\n * on either side highlights the same character in both. Debug-only.\n */\nexport function applyHoverIsolation(container: HTMLElement, hovered: number | undefined): void {\n for (const el of Array.from(container.children) as HTMLElement[]) {\n if (!el.style) { continue; }\n const off = el.dataset.offset;\n const matches = off !== undefined && Number(off) === hovered;\n el.style.visibility = hovered === undefined || matches ? '' : 'hidden';\n }\n}\n\n/**\n * Show only `keep` (when `on`) or restore every overlay element (when `off`).\n * Debug-only, so the brute-force walk over all siblings is fine.\n */\nfunction _isolate(overlay: HTMLElement, keep: HTMLElement, on: boolean): void {\n for (const el of Array.from(overlay.children) as HTMLElement[]) {\n el.style.visibility = on && el !== keep ? 'hidden' : '';\n }\n}\n\n","import type { IObservableWithChange, ITransaction, IDisposable } from '@vscode/observables';\nimport type { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport type { LengthEdit } from '../core/lengthEdit.js';\n\nexport interface ISyntaxHighlighter {\n create(language: string, initialText: string): ISyntaxHighlighterDocument;\n}\n\nexport interface ISyntaxHighlighterDocument extends IDisposable {\n /**\n * Apply a source edit. The {@link snapshot} updates synchronously within\n * `tx`, and the change it carries is the *minimal* {@link LengthEdit} that\n * actually re-coloured — not the whole document.\n */\n update(edit: StringEdit, tx: ITransaction): void;\n\n /**\n * The current snapshot. Its change reason is a {@link LengthEdit} mapping\n * the previous snapshot's offsets to this one's wherever tokens changed.\n */\n readonly snapshot: IObservableWithChange<ISyntaxHighlightedSnapshot, LengthEdit>;\n}\n\n/**\n * An immutable view of one document's tokens at a point in time. It may be a\n * thin view over the highlighter's mutable state: once the underlying document\n * advances, calling a stale snapshot is allowed to throw.\n *\n * Token stability: across snapshots `S1 -> S2` (with the change delivered as a\n * {@link LengthEdit}), `getTokens(r)` returns the same tokens for any range `r`\n * not touched by that edit. Only ranges the edit reports as changed may recolour.\n */\nexport interface ISyntaxHighlightedSnapshot {\n /**\n * Tokens covering a region that contains `queryRange`. Tokens are never\n * split: the returned {@link SnapshotTokens.range} is `queryRange` *grown*\n * to whole-token boundaries, so a token that straddles an end of\n * `queryRange` is returned in full. The result is dense over that grown\n * range — `sum(token.length) === range.length` — which is why the range is\n * returned alongside the tokens.\n */\n getTokens(queryRange: OffsetRange): SnapshotTokens;\n}\n\n/**\n * A run of {@link Token}s together with the exact {@link OffsetRange} they\n * cover.\n *\n * Because tokens are returned whole (never clipped), this is the natural unit\n * of structural comparison: for any region untouched by an edit, two snapshots\n * return an equal `SnapshotTokens` (same `range`, same token lengths/classes).\n */\nexport interface SnapshotTokens {\n readonly range: OffsetRange;\n readonly tokens: readonly Token[];\n}\n\n/**\n * A coloured run of `length` characters. Tokens are *dense* and *offset-free*:\n * a snapshot's tokens for a range cover it exactly, back to back, so\n * `sum(token.length) === range.length`. A token never stores where it is — its\n * position is implied by the lengths of the tokens before it, mirroring how the\n * rest of the editor keeps source offsets out of its data structures.\n */\nexport class Token {\n constructor(\n readonly length: number,\n /** CSS class for this run, or `undefined` for an unstyled run. */\n readonly className: string | undefined,\n ) { }\n}\n","import { observableValue, type ISettableObservable, type ITransaction } from '@vscode/observables';\nimport type { MonarchTokenizer, IMonarchTokenizerState } from 'monaco-editor/esm/vs/editor/standalone/common/monarch/monarchLexer.js';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { LengthEdit } from '../core/lengthEdit.js';\nimport { Token, type ISyntaxHighlightedSnapshot, type ISyntaxHighlighterDocument, type ISyntaxHighlighter, type SnapshotTokens } from './syntaxHighlighter.js';\n\n/**\n * The slice of monaco's Monarch internals the highlighter needs at runtime.\n *\n * `monaco-editor` is only a *type* dependency of this package; the caller (who\n * owns a real monaco runtime) passes these in, keeping monaco out of the bundle.\n */\nexport interface IMonarchApi {\n /** Compiles a Monarch language definition into the internal lexer form. */\n compile(languageId: string, json: unknown): unknown;\n MonarchTokenizer: new (\n languageService: unknown,\n standaloneThemeService: unknown,\n languageId: string,\n lexer: unknown,\n configurationService: unknown,\n ) => MonarchTokenizer;\n}\n\n/**\n * {@link ISyntaxHighlighter} backed by monaco's Monarch tokenizer.\n *\n * Highlighting is synchronous and incremental: an edit only re-runs the\n * tokenizer from the first changed line onward (earlier lines and their saved\n * end-states are reused), and the {@link LengthEdit} delivered with the new\n * snapshot is the minimal char range whose colour actually changed.\n *\n * Only Monarch's *classic* tokenizer path is used, which needs neither a theme\n * nor the DOM, so this runs headless (Node, workers) as well as in the browser.\n */\nexport class MonacoSyntaxHighlighter implements ISyntaxHighlighter {\n private readonly _tokenizers = new Map<string, MonarchTokenizer>();\n\n /**\n * @param _monaco The Monarch runtime ({@link IMonarchApi}), injected so this\n * package depends on `monaco-editor` for types only.\n * @param _grammars Maps a language id to its Monarch language definition.\n */\n constructor(\n private readonly _monaco: IMonarchApi,\n private readonly _grammars: ReadonlyMap<string, unknown>,\n ) { }\n\n create(language: string, initialText: string): ISyntaxHighlighterDocument {\n return new MonacoHighlighterDocument(this._tokenizerFor(language), initialText);\n }\n\n dispose(): void {\n for (const t of this._tokenizers.values()) { t.dispose(); }\n this._tokenizers.clear();\n }\n\n private _tokenizerFor(language: string): MonarchTokenizer | undefined {\n const grammar = this._grammars.get(language);\n if (grammar === undefined) { return undefined; }\n let tokenizer = this._tokenizers.get(language);\n if (!tokenizer) {\n tokenizer = new this._monaco.MonarchTokenizer(_stubLanguageService, _stubThemeService, language, this._monaco.compile(language, grammar), _stubConfigurationService);\n this._tokenizers.set(language, tokenizer);\n }\n return tokenizer;\n }\n}\n\ninterface LineData {\n readonly text: string;\n /** Tokens covering `text` exactly: `sum(token.length) === text.length`. */\n readonly tokens: readonly Token[];\n /** Monarch state after this line — the start state of the next line. */\n readonly endState: IMonarchTokenizerState;\n}\n\nclass MonacoHighlighterDocument implements ISyntaxHighlighterDocument {\n private _text: string;\n private _lines: LineData[];\n /** Source offset of each line's first char; `length === _lines.length`. */\n private _lineStarts: number[];\n private _version = 1;\n private _disposed = false;\n\n private readonly _initialState: IMonarchTokenizerState | undefined;\n private readonly _snapshotObs: ISettableObservable<ISyntaxHighlightedSnapshot, LengthEdit>;\n\n constructor(\n private readonly _tokenizer: MonarchTokenizer | undefined,\n initialText: string,\n ) {\n this._initialState = _tokenizer?.getInitialState();\n this._text = initialText;\n this._lines = this._tokenizeFrom(0, [], this._initialState, initialText.split('\\n'));\n this._lineStarts = this._computeLineStarts();\n this._snapshotObs = observableValue('syntaxSnapshot', new MonacoHighlightedSnapshot(this, this._version));\n }\n\n get snapshot() { return this._snapshotObs; }\n\n update(edit: StringEdit, tx: ITransaction): void {\n if (this._disposed) { throw new Error('document is disposed'); }\n if (edit.isEmpty) { return; }\n\n const oldTokens = _flatTokens(this._lines);\n const newText = edit.apply(this._text);\n const firstChangedOffset = edit.replacements[0].replaceRange.start;\n const firstChangedLine = this._lineIndexAt(firstChangedOffset);\n\n const reusedPrefix = this._lines.slice(0, firstChangedLine);\n const startState = firstChangedLine === 0\n ? this._initialState\n : this._lines[firstChangedLine - 1].endState;\n\n this._text = newText;\n this._lines = this._tokenizeFrom(firstChangedLine, reusedPrefix, startState, newText.split('\\n'));\n this._lineStarts = this._computeLineStarts();\n this._version++;\n\n const lengthEdit = _minimalRecolor(oldTokens, _flatTokens(this._lines));\n this._snapshotObs.set(new MonacoHighlightedSnapshot(this, this._version), tx, lengthEdit);\n }\n\n dispose(): void {\n // The tokenizer is shared and owned by the highlighter, not this document.\n this._disposed = true;\n }\n\n /**\n * Tokenize `allLines[fromLine..]`, keeping `reusedPrefix` (already tokenized\n * lines `[0, fromLine)`) verbatim. `startState` is the state entering\n * `fromLine`.\n */\n private _tokenizeFrom(\n fromLine: number,\n reusedPrefix: readonly LineData[],\n startState: IMonarchTokenizerState | undefined,\n allLines: readonly string[],\n ): LineData[] {\n const lines: LineData[] = reusedPrefix.slice();\n let state = startState;\n for (let i = fromLine; i < allLines.length; i++) {\n const text = allLines[i];\n const hasEOL = i < allLines.length - 1;\n if (this._tokenizer && state) {\n const result = this._tokenizer.tokenize(text, hasEOL, state);\n lines.push({ text, tokens: _toTokens(result.tokens, text.length), endState: result.endState });\n state = result.endState;\n } else {\n lines.push({ text, tokens: text.length === 0 ? [] : [new Token(text.length, undefined)], endState: state! });\n }\n }\n return lines;\n }\n\n private _computeLineStarts(): number[] {\n const starts: number[] = [];\n let offset = 0;\n for (const line of this._lines) {\n starts.push(offset);\n offset += line.text.length + 1; // + newline\n }\n return starts;\n }\n\n private _lineIndexAt(offset: number): number {\n for (let i = this._lineStarts.length - 1; i >= 0; i--) {\n if (offset >= this._lineStarts[i]) { return i; }\n }\n return 0;\n }\n\n /** @internal Called by {@link MonacoHighlightedSnapshot}. */\n _getTokens(version: number, queryRange: OffsetRange): SnapshotTokens {\n if (version !== this._version) { throw new Error('stale snapshot'); }\n const docLen = this._text.length;\n const queryStart = Math.max(0, Math.min(queryRange.start, docLen));\n const queryEnd = Math.max(queryStart, Math.min(queryRange.endExclusive, docLen));\n\n const tokens: Token[] = [];\n let rangeStart = queryStart;\n let rangeEnd = queryStart;\n let started = false;\n let pos = 0;\n const consider = (length: number, className: string | undefined): void => {\n const tokenStart = pos;\n const tokenEnd = pos + length;\n pos = tokenEnd;\n if (length === 0) { return; }\n // Keep whole tokens that overlap the query (an empty query overlaps none).\n if (tokenStart < queryEnd && tokenEnd > queryStart) {\n if (!started) { rangeStart = tokenStart; started = true; }\n tokens.push(new Token(length, className));\n rangeEnd = tokenEnd;\n }\n };\n for (let i = 0; i < this._lines.length && pos < queryEnd; i++) {\n for (const t of this._lines[i].tokens) { consider(t.length, t.className); }\n if (i < this._lines.length - 1) { consider(1, undefined); } // newline char\n }\n return { range: new OffsetRange(rangeStart, started ? rangeEnd : queryStart), tokens };\n }\n}\n\nclass MonacoHighlightedSnapshot implements ISyntaxHighlightedSnapshot {\n constructor(\n private readonly _doc: MonacoHighlighterDocument,\n private readonly _version: number,\n ) { }\n\n getTokens(queryRange: OffsetRange): SnapshotTokens {\n return this._doc._getTokens(this._version, queryRange);\n }\n}\n\n/** Monarch token type → CSS class. The empty type is an unstyled run. */\nfunction _classNameOf(type: string): string | undefined {\n return type === '' ? undefined : type;\n}\n\n/** Convert Monarch's (offset, type) tokens into dense length-based tokens. */\nfunction _toTokens(monarchTokens: readonly { readonly offset: number; readonly type: string }[], lineLength: number): Token[] {\n if (monarchTokens.length === 0) {\n return lineLength === 0 ? [] : [new Token(lineLength, undefined)];\n }\n const tokens: Token[] = [];\n for (let i = 0; i < monarchTokens.length; i++) {\n const startOffset = monarchTokens[i].offset;\n const endOffset = i + 1 < monarchTokens.length ? monarchTokens[i + 1].offset : lineLength;\n if (endOffset > startOffset) {\n tokens.push(new Token(endOffset - startOffset, _classNameOf(monarchTokens[i].type)));\n }\n }\n return tokens;\n}\n\n/**\n * The whole document's tokens as one dense, offset-free run — exactly the\n * sequence {@link MonacoHighlighterDocument._getTokens} would emit for the full\n * range, including the length-1 unstyled token for each inter-line newline.\n */\nfunction _flatTokens(lines: readonly LineData[]): Token[] {\n const tokens: Token[] = [];\n for (let i = 0; i < lines.length; i++) {\n for (const t of lines[i].tokens) { tokens.push(t); }\n if (i < lines.length - 1) { tokens.push(new Token(1, undefined)); } // newline char\n }\n return tokens;\n}\n\nfunction _tokensEqual(a: Token, b: Token): boolean {\n return a.length === b.length && a.className === b.className;\n}\n\nfunction _sumLengths(tokens: readonly Token[]): number {\n let sum = 0;\n for (const t of tokens) { sum += t.length; }\n return sum;\n}\n\n/**\n * The minimal {@link LengthEdit} taking the old token run to the new one,\n * snapped to *token* boundaries: trim the run of identical leading tokens and\n * the run of identical trailing tokens; whatever lies between is the only\n * region whose tokenization actually changed.\n *\n * Snapping to whole tokens (rather than to per-character colours) is what makes\n * the edit faithful: if a token merely grows or merges at a boundary, the whole\n * affected token is reported, so {@link ISyntaxHighlightedSnapshot.getTokens}\n * over any range the edit leaves untouched is structurally unchanged.\n */\nfunction _minimalRecolor(oldTokens: readonly Token[], newTokens: readonly Token[]): LengthEdit {\n const oldCount = oldTokens.length;\n const newCount = newTokens.length;\n\n let prefix = 0;\n let prefixChars = 0;\n while (prefix < oldCount && prefix < newCount && _tokensEqual(oldTokens[prefix], newTokens[prefix])) {\n prefixChars += oldTokens[prefix].length;\n prefix++;\n }\n\n let suffix = 0;\n let suffixChars = 0;\n while (suffix < oldCount - prefix && suffix < newCount - prefix\n && _tokensEqual(oldTokens[oldCount - 1 - suffix], newTokens[newCount - 1 - suffix])) {\n suffixChars += oldTokens[oldCount - 1 - suffix].length;\n suffix++;\n }\n\n const oldChars = _sumLengths(oldTokens);\n const newChars = _sumLengths(newTokens);\n const oldRange = new OffsetRange(prefixChars, oldChars - suffixChars);\n const newRangeLength = newChars - suffixChars - prefixChars;\n if (oldRange.isEmpty && newRangeLength === 0) { return LengthEdit.empty; }\n return LengthEdit.replace(oldRange, newRangeLength);\n}\n\n// --- Minimal headless stand-ins for the services MonarchTokenizer asks for. ---\n// The classic tokenizer path touches none of these on the hot path (only\n// embedded-language and encoded-token paths do), so empty stubs suffice.\n\nconst _stubLanguageService = {\n languageIdCodec: { encodeLanguageId: () => 0, decodeLanguageId: () => '' },\n isRegisteredLanguageId: () => false,\n getLanguageIdByLanguageName: () => null,\n getLanguageIdByMimeType: () => null,\n requestBasicLanguageFeatures: () => { },\n};\n\nconst _stubThemeService = {\n getColorTheme: () => ({ tokenTheme: {} }),\n};\n\nconst _stubConfigurationService = {\n getValue: () => 20000,\n onDidChangeConfiguration: () => ({ dispose() { } }),\n};\n","import { MonacoSyntaxHighlighter, type IMonarchApi } from './monacoSyntaxHighlighter.js';\n\n/** The Monarch language definitions the default highlighter wires up. */\nexport interface IDefaultMonarchGrammars {\n typescript: unknown;\n javascript: unknown;\n css: unknown;\n html: unknown;\n python: unknown;\n rust: unknown;\n shell: unknown;\n}\n\n/**\n * A {@link MonacoSyntaxHighlighter} preloaded with a handful of common Monarch\n * grammars (plus the usual short aliases). Unknown languages fall back to an\n * unstyled single token, so the highlighter is always safe to call.\n *\n * The Monarch runtime and grammar definitions are injected so this package\n * depends on `monaco-editor` for types only.\n */\nexport function createDefaultMonacoSyntaxHighlighter(\n monaco: IMonarchApi,\n grammars: IDefaultMonarchGrammars,\n): MonacoSyntaxHighlighter {\n const grammarMap = new Map<string, unknown>([\n ['typescript', grammars.typescript],\n ['ts', grammars.typescript],\n ['javascript', grammars.javascript],\n ['js', grammars.javascript],\n ['css', grammars.css],\n ['html', grammars.html],\n ['python', grammars.python],\n ['py', grammars.python],\n ['rust', grammars.rust],\n ['rs', grammars.rust],\n ['shell', grammars.shell],\n ['sh', grammars.shell],\n ['bash', grammars.shell],\n ]);\n return new MonacoSyntaxHighlighter(monaco, grammarMap);\n}\n"],"names":["OffsetRange","start","endExclusive","length","offset","other","end","str","arr","StringReplacement","replaceRange","newText","text","range","StringEdit","replacement","replacements","lastEndEx","base","parts","pos","r","original","edits","oldText","i","delta","LengthReplacement","newLength","LengthEdit","StringValue","value","Selection","anchor","active","Point2D","x","y","dx","dy","Rect2D","width","height","left","top","right","bottom","p","findWordBoundaryLeft","findWordBoundaryRight","len","findWordAt","ch","_nextNodeId","AstNode","sum","c","a","b","_other","id","clone","_emptyChildren","_mapArr","map","out","m","_mapOne","n","_mapTrivia","trivia","LeafAstNode","TextAstNode","content","o","MarkerAstNode","markerKind","GlueAstNode","glueKind","BlockAstNodeBase","own","ThematicBreakAstNode","leadingTrivia","_marker","kind","StrongAstNode","openMarker","closeMarker","EmphasisAstNode","StrikethroughAstNode","InlineCodeAstNode","InlineMathAstNode","LinkAstNode","url","ImageAstNode","alt","HeadingAstNode","level","marker","ParagraphAstNode","CodeBlockAstNode","language","previous","contentEdit","MathBlockAstNode","BlockQuoteAstNode","_isBlock","ListAstNode","ordered","ListItemAstNode","checked","TableAstNode","TableRowAstNode","TableCellAstNode","DocumentAstNode","findNodeOffsetById","root","target","child","inner","_TASK_CHECKBOX_RE","taskCheckboxRange","item","match","_nodeText","node","tokenize","source","parser","parse","math","gfmTable","gfmTaskListItem","gfmStrikethrough","chunks","preprocess","postprocess","type","token","AstBuilder","_pullIndentIntoBlocks","cur","next","hosted","_prependLeadingTrivia","prev","glue","firstIdx","items","j","_attachBlockGaps","idx","isParagraphBreak","gap","host","_appendTrailingGlue","h","_appendIntoLast","l","it","last","_ensureBlocks","Content","_parentStart","_source","parentLength","s","e","indent","_events","cb","ev","block","enter","markerStart","markerEnd","inlines","seqEnter","seqExit","exit","sawOpenFence","contentStart","contentEnd","fenceEnter","ii","fenceExit","flushContent","prefixEnter","prefixExit","seenBlock","pre","preExit","listType","itemStart","itemCb","itemChecked","lastBlockEnd","flush","itemEnd","columnCount","row","raw","pipes","cellStartsRel","cols","rowCb","cs","ce","cellCb","cellType","cellEnter","cellExit","entries","untilExit","tokenType","isStrong","openEnter","openExit","closeEnter","closeExit","sawOpen","sawOpenBracket","i2","sawOpenParen","EditMapper","_edit","mod","modStart","dirtyEnd","OldTreeIndex","key","originalStart","_reconcile","fresh","mapper","index","edit","rc","orig","cand","os","old","linked","_linkCodeBlock","oldStart","oldCode","freshCode","_editWithin","_shiftEdit","reconcile","parseIncremental","MarkdownParser","getAnnotatedSource","escapeXml","tag","_attributes","result","childOffset","attrs","k","v","_label","_objectInstanceIds","_nextObjectInstanceId","objectInstanceId","visualizeAst","walk","kids","children","NO_ACTIVE_BLOCKS","EditorModel","observableValue","derived","reader","previousText","pending","doc","cursor","findBlockAtOffset","override","sel","blocksIntersecting","newActive","newCursor","lastBlock","VisualLineMap","lines","blockViews","_measure","lineIndex","endBoundaryLine","membership","bestIdx","bestDist","dist","point","VisualLine","rect","runs","run","best","d","first","bestRun","VisualRun","sourceRange","_xAtTextOffset","fraction","localOffset","_offsetAtX","textNode","textOffset","fallbackLeft","bestOffset","mid","dLeft","dRight","rawRuns","view","runsBefore","leaf","leafOffset","rects","lineBoxHeight","_lineBoxHeight","_expandToLineBox","breakOffsets","_findLineBreakOffsets","_appendElementBlockRun","currentRuns","currentY","currentHeight","currentLeft","currentRight","overlap","breaks","nextY","lo","hi","parent","lineHeight","leading","viewNode","absoluteStart","dom","MeasuredLayoutModel","nextCursorPosition","activeBlock","direction","blockStart","ranges","hiddenRangesFor","applySkip","isActive","relCursor","collectMarkerRanges","activeItemIndex","findActiveListItemIndex","collectListHiddenRanges","rel","list","cursorOffset","boundaryFallback","itemIdx","listOffset","listChild","walkCollectMarkerRanges","cursorRight","ctx","cursorLeft","cursorMoveRight","cursorMoveLeft","cursorWordRight","cursorWordLeft","cursorLineStart","cursorLineEnd","cursorDocumentStart","cursorDocumentEnd","cursorDown","lineIdx","cursorUp","deleteLeft","deleteRange","deleteRight","deleteWordLeft","boundary","deleteWordRight","insertText","newOffset","insertParagraph","insertLineBreak","insertHardLineBreak","existingSpaces","inserted","selectAll","selectWord","_ctx","word","selectBlock","blockRange","_domToViewNode","_parentOf","ViewNode","Disposable","ast","domNode","vn","localSourceOffset","nodeSourceOffset","childEnd","nodeOffset","visitor","BlockViewNode","data","_height","createViewNode","options","_textLeaf","_prev","LeafViewNode","HardBreakViewNode","MarkerViewNode","GlueViewNode","HeadingViewNode","ContainerViewNode","_prevContainer","CodeBlockViewNode","MathBlockViewNode","ThematicBreakViewNode","ListViewNode","ListItemViewNode","TableRowViewNode","InlineCodeViewNode","InlineMathViewNode","LinkViewNode","ImageViewNode","ctor","reconcileDomChildren","parentDom","childData","previousChildren","build","paired","unused","pairNodes","_NO_CHILDREN","u","_patchDomChildren","_patchDomNodes","nodes","domCursor","toRemove","_buildChild","_inlineChild","_contentOf","_NO_VIEW_CHILDREN","_hasDecoratableWhitespace","span","_appendDecorated","prevDom","_isWhitespaceChar","_HARD_BREAK_WHITESPACE","_CODE_INDENT_WHITESPACE","_isObviousSpace","prevObvious","nextObvious","_whitespaceClass","_segmentWhitespace","segments","plainStart","flushPlain","breakNewline","lastNewline","isBreak","cls","seg","RawLeafViewNode","sourceLength","reuse","built","ws","_previous","holder","_appendPlainText","className","el","hr","custom","highlighter","prevCode","session","diff","transaction","tx","tokens","contentNode","code","_buildCodeContent","CodeContentViewNode","childAst","leaves","runOnChange","snapshot","contentAst","_buildTokenLeaves","tokenLeaves","piece","_mathContentOffset","_buildMathSegmentChildren","nodeLength","sorted","filler","remembered","latex","rendering","div","katex","li","_reconcileListItem","checkbox","onToggle","wasChecked","gutter","tr","cellData","_isSafeUrl","img","newData","prevNodes","byId","DocumentViewNode","contentDomNode","blocks","viewData","activeByView","childViews","_NO_NODES","caretDomPositionFromPoint","api","DocumentViewData","HeadingViewData","ParagraphViewData","CodeBlockViewData","showMarkup","MathBlockViewData","BlockQuoteViewData","ListViewData","TableViewData","StrongViewData","EmphasisViewData","StrikethroughViewData","InlineCodeViewData","InlineMathViewData","LinkViewData","ImageViewData","ListItemViewData","TableRowViewData","isDelimiter","TableCellViewData","showTableGlue","TextViewData","showWhitespace","leftWordBoundary","rightWordBoundary","ThematicBreakViewData","MarkerViewData","visible","GlueViewData","decorateNewline","_INACTIVE","_inline","buildDocumentViewData","activeBlocks","selectionRange","prevByAst","blockSet","_buildBlock","selectionInNode","_reuseOr","_buildNode","astNode","neighbors","_buildChildren","_markerVisible","_glueVisible","_buildList","_buildListItem","_buildTable","_buildTableRow","_buildTableCell","_childrenOf","_prevChildByAst","_flagsEqual","_edgeIsWordContent","side","prevNode","activeItems","_activeItemIndices","itemSet","itemLevel","itemCtx","childCtx","table","tableActive","delimiterRow","rowSet","rowCtx","activeCells","_activeCellIndices","cellSet","cell","cellActive","cellCtx","_EMPTY_SET","_findActiveCellIndex","cellIdx","CursorView","_parent","visualLineMap","CursorViewRendering","caretRect","parentRect","localRect","autorun","SelectionView","selection","_renderSelection","SelectionViewRendering","path","selRange","lineInfos","line","lineRange","_lineSourceRange","lineRects","isFirst","isLast","startX","endX","blockToFirstLineIdx","blockToLastLineIdx","blockSelected","curr","gapStart","gapEnd","currRect","nextRect","nextFirstLineTop","_firstLineTopOfBlock","prevLineIdx","nextLineIdx","prevLR","nextLR","hasLine","_buildConnectedPath","min","max","fallback","radius","clusters","current","yTouches","xOverlaps","_buildClusterPath","corners","aRight","bRight","aConvex","_polygonToRoundedPath","radii","dPrev","_dist","dNext","_moveFrom","_fmt","depart","nextR","approach","from","to","t","DEFAULT_LIMITED_WIDTH","EditorView","_model","_options","limitedWidth","constObservable","hit","sourceText","documentNode","document","measurements","entry","blockRect","NativeClipboardStrategy","context","onCopy","onCut","onPaste","AsyncClipboardStrategy","_clipboard","onKeyDown","EditorController","_view","clipboardStrategy","editContext","findBlockRangeAt","onMouseMove","me","moveOffset","onMouseUp","command","extend","ctrl","_SHOW_LINE_RECTS_KEY","_readStoredBool","_writeStoredBool","MeasuredLayoutDebugView","_overlayParent","controls","showLineRects","_renderDebug","hovered","applyHoverIsolation","MeasuredLayoutDebugRendering","blockCount","mountedCount","lineCount","mappedOffsets","overlay","info","overlayParent","colorForOffset","hoveredOffset","charCount","lineRect","band","runBox","_appendCharRects","header","rows","flag","lc","blockAbsoluteStart","count","covered","isCovered","drawWidth","box","_isolate","container","off","matches","keep","on","Token","MonacoSyntaxHighlighter","_monaco","_grammars","initialText","MonacoHighlighterDocument","grammar","tokenizer","_stubLanguageService","_stubThemeService","_stubConfigurationService","_tokenizer","MonacoHighlightedSnapshot","oldTokens","_flatTokens","firstChangedOffset","firstChangedLine","reusedPrefix","startState","lengthEdit","_minimalRecolor","fromLine","allLines","state","hasEOL","_toTokens","starts","version","queryRange","docLen","queryStart","queryEnd","rangeStart","rangeEnd","started","consider","tokenStart","tokenEnd","_doc","_version","_classNameOf","monarchTokens","lineLength","startOffset","endOffset","_tokensEqual","_sumLengths","newTokens","oldCount","newCount","prefix","prefixChars","suffix","suffixChars","oldChars","newChars","oldRange","newRangeLength","createDefaultMonacoSyntaxHighlighter","monaco","grammars","grammarMap"],"mappings":";;;;;;;AAAO,MAAMA,EAAY;AAAA,EAiBxB,YACiBC,GACAC,GACf;AACD,QAHgB,KAAA,QAAAD,GACA,KAAA,eAAAC,GAEZD,IAAQC;AACX,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AC9B,6BAA6B,MAAM;AAAA,EACnC,yBAAyB,MAAM;AAAA,EAC/B,8BAA8B,MAAM;AAAA,EAAE;AAC1C,GAEMC,KAAoB;AAAA,EACtB,eAAe,OAAO,EAAE,YAAY,GAAC;AACzC,GAEMC,KAA4B;AAAA,EAC9B,UAAU,MAAM;AAAA,EAChB,0BAA0B,OAAO,EAAE,UAAU;AAAA,EAAE,EAAA;AACnD;AC1SO,SAASgD,GACZC,GACAC,GACuB;AACvB,QAAMC,wBAAiB,IAAqB;AAAA,IACxC,CAAC,cAAcD,EAAS,UAAU;AAAA,IAClC,CAAC,MAAMA,EAAS,UAAU;AAAA,IAC1B,CAAC,cAAcA,EAAS,UAAU;AAAA,IAClC,CAAC,MAAMA,EAAS,UAAU;AAAA,IAC1B,CAAC,OAAOA,EAAS,GAAG;AAAA,IACpB,CAAC,QAAQA,EAAS,IAAI;AAAA,IACtB,CAAC,UAAUA,EAAS,MAAM;AAAA,IAC1B,CAAC,MAAMA,EAAS,MAAM;AAAA,IACtB,CAAC,QAAQA,EAAS,IAAI;AAAA,IACtB,CAAC,MAAMA,EAAS,IAAI;AAAA,IACpB,CAAC,SAASA,EAAS,KAAK;AAAA,IACxB,CAAC,MAAMA,EAAS,KAAK;AAAA,IACrB,CAAC,QAAQA,EAAS,KAAK;AAAA,EAAA,CAC1B;AACD,SAAO,IAAI3D,GAAwB0D,GAAQE,CAAU;AACzD;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/core/offsetRange.ts","../src/core/stringEdit.ts","../src/core/lengthEdit.ts","../src/core/stringValue.ts","../src/core/selection.ts","../src/core/geometry.ts","../src/core/wordUtils.ts","../src/parser/ast.ts","../src/parser/_micromarkAdapter.ts","../src/parser/parse.ts","../src/parser/reconcile.ts","../src/parser/parser.ts","../src/parser/test/getAnnotatedSource.ts","../src/parser/visualizeAst.ts","../src/model/editorModel.ts","../src/view/visualLineMap.ts","../src/model/measuredLayoutModel.ts","../src/model/cursorNavigation.ts","../src/commands/cursorCommands.ts","../src/commands/editCommands.ts","../src/commands/selectionCommands.ts","../src/view/content/viewNode.ts","../src/view/content/blockView.ts","../src/view/content/documentView.ts","../src/view/content/dom.ts","../src/view/viewData.ts","../src/view/parts/cursorView.ts","../src/view/parts/gutterMarkersView.ts","../src/view/parts/selectionView.ts","../src/view/editorView.ts","../src/view/clipboardStrategy.ts","../src/view/editorController.ts","../src/view/measuredLayoutDebugView.ts","../src/highlighter/syntaxHighlighter.ts","../src/highlighter/monacoSyntaxHighlighter.ts","../src/highlighter/defaultMonacoSyntaxHighlighter.ts"],"sourcesContent":["export class OffsetRange {\n\tpublic static fromTo(start: number, endExclusive: number): OffsetRange {\n\t\treturn new OffsetRange(start, endExclusive);\n\t}\n\n\tpublic static ofLength(length: number): OffsetRange {\n\t\treturn new OffsetRange(0, length);\n\t}\n\n\tpublic static ofStartAndLength(start: number, length: number): OffsetRange {\n\t\treturn new OffsetRange(start, start + length);\n\t}\n\n\tpublic static emptyAt(offset: number): OffsetRange {\n\t\treturn new OffsetRange(offset, offset);\n\t}\n\n\tconstructor(\n\t\tpublic readonly start: number,\n\t\tpublic readonly endExclusive: number,\n\t) {\n\t\tif (start > endExclusive) {\n\t\t\tthrow new Error(`Invalid range: [${start}, ${endExclusive})`);\n\t\t}\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.start === this.endExclusive;\n\t}\n\n\tget length(): number {\n\t\treturn this.endExclusive - this.start;\n\t}\n\n\tpublic delta(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start + offset, this.endExclusive + offset);\n\t}\n\n\tpublic deltaStart(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start + offset, this.endExclusive);\n\t}\n\n\tpublic deltaEnd(offset: number): OffsetRange {\n\t\treturn new OffsetRange(this.start, this.endExclusive + offset);\n\t}\n\n\tpublic contains(offset: number): boolean {\n\t\treturn this.start <= offset && offset < this.endExclusive;\n\t}\n\n\tpublic containsRange(other: OffsetRange): boolean {\n\t\treturn this.start <= other.start && other.endExclusive <= this.endExclusive;\n\t}\n\n\tpublic intersects(other: OffsetRange): boolean {\n\t\treturn Math.max(this.start, other.start) < Math.min(this.endExclusive, other.endExclusive);\n\t}\n\n\tpublic intersectsOrTouches(other: OffsetRange): boolean {\n\t\treturn Math.max(this.start, other.start) <= Math.min(this.endExclusive, other.endExclusive);\n\t}\n\n\tpublic intersect(other: OffsetRange): OffsetRange | undefined {\n\t\tconst start = Math.max(this.start, other.start);\n\t\tconst end = Math.min(this.endExclusive, other.endExclusive);\n\t\tif (start <= end) {\n\t\t\treturn new OffsetRange(start, end);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tpublic join(other: OffsetRange): OffsetRange {\n\t\treturn new OffsetRange(\n\t\t\tMath.min(this.start, other.start),\n\t\t\tMath.max(this.endExclusive, other.endExclusive),\n\t\t);\n\t}\n\n\tpublic isBefore(other: OffsetRange): boolean {\n\t\treturn this.endExclusive <= other.start;\n\t}\n\n\tpublic isAfter(other: OffsetRange): boolean {\n\t\treturn this.start >= other.endExclusive;\n\t}\n\n\tpublic substring(str: string): string {\n\t\treturn str.substring(this.start, this.endExclusive);\n\t}\n\n\tpublic slice<T>(arr: readonly T[]): T[] {\n\t\treturn arr.slice(this.start, this.endExclusive);\n\t}\n\n\tpublic equals(other: OffsetRange): boolean {\n\t\treturn this.start === other.start && this.endExclusive === other.endExclusive;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `[${this.start}, ${this.endExclusive})`;\n\t}\n}\n","import { OffsetRange } from './offsetRange.js';\n\nexport class StringReplacement {\n\tpublic static insert(offset: number, text: string): StringReplacement {\n\t\treturn new StringReplacement(OffsetRange.emptyAt(offset), text);\n\t}\n\n\tpublic static replace(range: OffsetRange, text: string): StringReplacement {\n\t\treturn new StringReplacement(range, text);\n\t}\n\n\tpublic static delete(range: OffsetRange): StringReplacement {\n\t\treturn new StringReplacement(range, '');\n\t}\n\n\tconstructor(\n\t\tpublic readonly replaceRange: OffsetRange,\n\t\tpublic readonly newText: string,\n\t) {}\n\n\tget isEmpty(): boolean {\n\t\treturn this.replaceRange.isEmpty && this.newText.length === 0;\n\t}\n\n\tpublic equals(other: StringReplacement): boolean {\n\t\treturn this.replaceRange.equals(other.replaceRange) && this.newText === other.newText;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `${this.replaceRange} -> ${JSON.stringify(this.newText)}`;\n\t}\n}\n\nexport class StringEdit {\n\tpublic static readonly empty = new StringEdit([]);\n\n\tpublic static single(replacement: StringReplacement): StringEdit {\n\t\treturn new StringEdit([replacement]);\n\t}\n\n\tpublic static replace(range: OffsetRange, text: string): StringEdit {\n\t\treturn new StringEdit([StringReplacement.replace(range, text)]);\n\t}\n\n\tpublic static insert(offset: number, text: string): StringEdit {\n\t\treturn new StringEdit([StringReplacement.insert(offset, text)]);\n\t}\n\n\tpublic static delete(range: OffsetRange): StringEdit {\n\t\treturn new StringEdit([StringReplacement.delete(range)]);\n\t}\n\n\tpublic readonly replacements: readonly StringReplacement[];\n\n\tconstructor(replacements: readonly StringReplacement[]) {\n\t\tlet lastEndEx = -1;\n\t\tfor (const replacement of replacements) {\n\t\t\tif (replacement.replaceRange.start < lastEndEx) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Edits must be disjoint and sorted. Found ${replacement} after ${lastEndEx}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlastEndEx = replacement.replaceRange.endExclusive;\n\t\t}\n\t\tthis.replacements = replacements;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.replacements.length === 0;\n\t}\n\n\tpublic apply(base: string): string {\n\t\tconst parts: string[] = [];\n\t\tlet pos = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tparts.push(base.substring(pos, r.replaceRange.start));\n\t\t\tparts.push(r.newText);\n\t\t\tpos = r.replaceRange.endExclusive;\n\t\t}\n\t\tparts.push(base.substring(pos));\n\t\treturn parts.join('');\n\t}\n\n\tpublic inverse(original: string): StringEdit {\n\t\tconst edits: StringReplacement[] = [];\n\t\tlet offset = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tconst oldText = original.substring(r.replaceRange.start, r.replaceRange.endExclusive);\n\t\t\tedits.push(\n\t\t\t\tStringReplacement.replace(\n\t\t\t\t\tOffsetRange.ofStartAndLength(r.replaceRange.start + offset, r.newText.length),\n\t\t\t\t\toldText,\n\t\t\t\t),\n\t\t\t);\n\t\t\toffset += r.newText.length - r.replaceRange.length;\n\t\t}\n\t\treturn new StringEdit(edits);\n\t}\n\n\tpublic equals(other: StringEdit): boolean {\n\t\tif (this.replacements.length !== other.replacements.length) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let i = 0; i < this.replacements.length; i++) {\n\t\t\tif (!this.replacements[i].equals(other.replacements[i])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic mapOffset(offset: number): number {\n\t\tlet delta = 0;\n\t\tfor (const r of this.replacements) {\n\t\t\tif (r.replaceRange.start > offset) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (r.replaceRange.endExclusive <= offset) {\n\t\t\t\tdelta += r.newText.length - r.replaceRange.length;\n\t\t\t} else {\n\t\t\t\t// offset is inside a replaced range — map to end of replacement\n\t\t\t\treturn r.replaceRange.start + delta + r.newText.length;\n\t\t\t}\n\t\t}\n\t\treturn offset + delta;\n\t}\n\n\tpublic toString(): string {\n\t\treturn `[${this.replacements.map(r => r.toString()).join(', ')}]`;\n\t}\n}\n","import { OffsetRange } from './offsetRange.js';\n\n/**\n * A single \"the text in `replaceRange` now spans `newLength` characters\"\n * statement. Unlike {@link StringReplacement} it carries no text — it only\n * describes *where* and *by how much* something changed, not *what to*.\n *\n * For syntax highlighting it means: the characters that used to occupy\n * `replaceRange` are replaced by `newLength` characters whose tokens may now\n * be coloured differently. A same-length replacement (`replaceRange.length ===\n * newLength`) therefore means \"these characters kept their positions but got\n * re-coloured\".\n */\nexport class LengthReplacement {\n public static replace(replaceRange: OffsetRange, newLength: number): LengthReplacement {\n return new LengthReplacement(replaceRange, newLength);\n }\n\n constructor(\n public readonly replaceRange: OffsetRange,\n public readonly newLength: number,\n ) {\n if (newLength < 0) {\n throw new Error(`newLength must be non-negative, got ${newLength}`);\n }\n }\n\n get lengthDelta(): number {\n return this.newLength - this.replaceRange.length;\n }\n\n public equals(other: LengthReplacement): boolean {\n return this.replaceRange.equals(other.replaceRange) && this.newLength === other.newLength;\n }\n\n public toString(): string {\n return `${this.replaceRange} -> +${this.newLength}`;\n }\n}\n\n/**\n * A set of disjoint, sorted {@link LengthReplacement}s — the length-only\n * counterpart of {@link StringEdit}. Used as the change reason of an\n * observable so observers learn which offset ranges of the previous value map\n * to which ranges of the new value (and thus what to invalidate) without\n * carrying the new content itself.\n */\nexport class LengthEdit {\n public static readonly empty = new LengthEdit([]);\n\n public static single(replacement: LengthReplacement): LengthEdit {\n return new LengthEdit([replacement]);\n }\n\n public static replace(replaceRange: OffsetRange, newLength: number): LengthEdit {\n return new LengthEdit([LengthReplacement.replace(replaceRange, newLength)]);\n }\n\n public readonly replacements: readonly LengthReplacement[];\n\n constructor(replacements: readonly LengthReplacement[]) {\n let lastEndEx = -1;\n for (const r of replacements) {\n if (r.replaceRange.start < lastEndEx) {\n throw new Error(`Edits must be disjoint and sorted. Found ${r} after end ${lastEndEx}`);\n }\n lastEndEx = r.replaceRange.endExclusive;\n }\n this.replacements = replacements;\n }\n\n get isEmpty(): boolean {\n return this.replacements.length === 0;\n }\n\n public equals(other: LengthEdit): boolean {\n if (this.replacements.length !== other.replacements.length) {\n return false;\n }\n for (let i = 0; i < this.replacements.length; i++) {\n if (!this.replacements[i].equals(other.replacements[i])) {\n return false;\n }\n }\n return true;\n }\n\n public toString(): string {\n return this.isEmpty ? 'LengthEdit.empty' : this.replacements.join(', ');\n }\n}\n","import { OffsetRange } from './offsetRange.js';\n\nexport class StringValue {\n\tconstructor(readonly value: string) {}\n\n\tget length(): number {\n\t\treturn this.value.length;\n\t}\n\n\tpublic substring(range: OffsetRange): string {\n\t\treturn range.substring(this.value);\n\t}\n\n\tpublic toString(): string {\n\t\treturn this.value;\n\t}\n}\n","import type { SourceOffset } from './sourceOffset.js';\nimport { OffsetRange } from './offsetRange.js';\n\nexport class Selection {\n\tstatic collapsed(offset: SourceOffset): Selection {\n\t\treturn new Selection(offset, offset);\n\t}\n\n\tconstructor(\n\t\treadonly anchor: SourceOffset,\n\t\treadonly active: SourceOffset,\n\t) {}\n\n\tget isCollapsed(): boolean {\n\t\treturn this.anchor === this.active;\n\t}\n\n\tget isForward(): boolean {\n\t\treturn this.active >= this.anchor;\n\t}\n\n\tget range(): OffsetRange {\n\t\treturn this.isForward\n\t\t\t? new OffsetRange(this.anchor, this.active)\n\t\t\t: new OffsetRange(this.active, this.anchor);\n\t}\n\n\tcollapseToActive(): Selection {\n\t\treturn Selection.collapsed(this.active);\n\t}\n\n\twithActive(active: SourceOffset): Selection {\n\t\treturn new Selection(this.anchor, active);\n\t}\n}\n","/**\n * Immutable point in 2D space, in CSS-pixel client coordinates.\n */\nexport class Point2D {\n static readonly ZERO = new Point2D(0, 0);\n\n constructor(\n readonly x: number,\n readonly y: number,\n ) { }\n\n translate(dx: number, dy: number): Point2D {\n return new Point2D(this.x + dx, this.y + dy);\n }\n}\n\n/**\n * Immutable axis-aligned rectangle in 2D space, in CSS-pixel client\n * coordinates. `x`/`y` is the top-left corner, growing right/down.\n *\n * Half-open in both dimensions: `right` and `bottom` are excluded.\n */\nexport class Rect2D {\n static readonly EMPTY = new Rect2D(0, 0, 0, 0);\n\n static fromPointPoint(left: number, top: number, right: number, bottom: number): Rect2D {\n return new Rect2D(left, top, right - left, bottom - top);\n }\n\n static fromPointSize(x: number, y: number, width: number, height: number): Rect2D {\n return new Rect2D(x, y, width, height);\n }\n\n private constructor(\n readonly x: number,\n readonly y: number,\n readonly width: number,\n readonly height: number,\n ) { }\n\n get left(): number { return this.x; }\n get top(): number { return this.y; }\n get right(): number { return this.x + this.width; }\n get bottom(): number { return this.y + this.height; }\n\n get topLeft(): Point2D { return new Point2D(this.x, this.y); }\n\n containsX(x: number): boolean { return x >= this.left && x < this.right; }\n containsY(y: number): boolean { return y >= this.top && y < this.bottom; }\n containsPoint(p: Point2D): boolean { return this.containsX(p.x) && this.containsY(p.y); }\n\n /** Same y/height, zero-width band at `x = this.left`. Useful for caret rects derived from a line. */\n withZeroWidthAt(x: number): Rect2D {\n return new Rect2D(x, this.y, 0, this.height);\n }\n\n translate(dx: number, dy: number): Rect2D {\n return new Rect2D(this.x + dx, this.y + dy, this.width, this.height);\n }\n}\n","export function findWordBoundaryLeft(text: string, offset: number): number {\n\tif (offset <= 0) { return 0; }\n\tlet i = offset - 1;\n\t// Skip whitespace\n\twhile (i > 0 && /\\s/.test(text[i])) { i--; }\n\t// Skip word characters\n\tif (i >= 0 && /\\w/.test(text[i])) {\n\t\twhile (i > 0 && /\\w/.test(text[i - 1])) { i--; }\n\t} else if (i >= 0) {\n\t\t// Skip punctuation\n\t\twhile (i > 0 && !/\\w/.test(text[i - 1]) && !/\\s/.test(text[i - 1])) { i--; }\n\t}\n\treturn i;\n}\n\nexport function findWordBoundaryRight(text: string, offset: number): number {\n\tconst len = text.length;\n\tif (offset >= len) { return len; }\n\tlet i = offset;\n\t// Skip whitespace\n\twhile (i < len && /\\s/.test(text[i])) { i++; }\n\t// Skip word characters\n\tif (i < len && /\\w/.test(text[i])) {\n\t\twhile (i < len && /\\w/.test(text[i])) { i++; }\n\t} else if (i < len) {\n\t\t// Skip punctuation\n\t\twhile (i < len && !/\\w/.test(text[i]) && !/\\s/.test(text[i])) { i++; }\n\t}\n\treturn i;\n}\n\nexport function findWordAt(text: string, offset: number): { start: number; end: number } {\n\tif (offset >= text.length) {\n\t\treturn { start: text.length, end: text.length };\n\t}\n\tconst ch = text[offset];\n\tif (/\\w/.test(ch)) {\n\t\tlet start = offset;\n\t\tlet end = offset;\n\t\twhile (start > 0 && /\\w/.test(text[start - 1])) { start--; }\n\t\twhile (end < text.length && /\\w/.test(text[end])) { end++; }\n\t\treturn { start, end };\n\t}\n\tif (/\\s/.test(ch)) {\n\t\tlet start = offset;\n\t\tlet end = offset;\n\t\twhile (start > 0 && /\\s/.test(text[start - 1])) { start--; }\n\t\twhile (end < text.length && /\\s/.test(text[end])) { end++; }\n\t\treturn { start, end };\n\t}\n\t// Punctuation\n\tlet start = offset;\n\tlet end = offset;\n\twhile (start > 0 && !/\\w/.test(text[start - 1]) && !/\\s/.test(text[start - 1])) { start--; }\n\twhile (end < text.length && !/\\w/.test(text[end]) && !/\\s/.test(text[end])) { end++; }\n\treturn { start, end };\n}\n","/**\n * Prototype AST for the incremental reconciliation design — full grammar.\n *\n * Design rules (all enforced structurally):\n * - Every node stores exactly one ordered `content` array of its children.\n * `children` is *computed* from it; nothing is passed in as a separate\n * `children` param, so the two can never drift.\n * - Syntactic glue (inter-block newlines, table pipes/padding, the whitespace\n * micromark doesn't assign to any token) is a first-class {@link GlueAstNode} node.\n * Each container's element type names it explicitly, e.g. `(Block | Glue)[]`,\n * so it is impossible to forget an array may contain glue. Semantic\n * accessors (`blocks`, `cells`, `marker`, …) filter glue out.\n * - Structural equality is the {@link AstNode.equalsShallow} method. The\n * generic part (kind, length, children-by-identity) lives once on the base;\n * each node contributes only its scalar comparison via {@link AstNode._localEquals}.\n * - `length` is cached on first access (the tree is immutable).\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\n\nlet _nextNodeId = 1;\nexport function _resetNodeIds(): void { _nextNodeId = 1; }\n\nexport abstract class AstNode {\n\n\n\tabstract readonly kind: string;\n\tabstract get children(): readonly AstNode[];\n\n\t/**\n\t * A stable identity. Every node has one: it is minted on construction and\n\t * carried across edits by reconciliation, so a node that survives an edit\n\t * (even with changed content) keeps the same id.\n\t */\n\treadonly id: number = _nextNodeId++;\n\n\t/** Rebuild this node with each child replaced by `map.get(child) ?? child`. */\n\tabstract mapChildren(map: ReadonlyMap<AstNode, AstNode>): AstNode;\n\n\tprivate _length = -1;\n\tget length(): number {\n\t\tif (this._length < 0) {\n\t\t\tlet sum = 0;\n\t\t\tfor (const c of this.children) { sum += c.length; }\n\t\t\tthis._length = sum;\n\t\t}\n\t\treturn this._length;\n\t}\n\n\t/**\n\t * True when `other` has the same content. Containers compare children *by\n\t * identity* (`===`): bottom-up reconciliation substitutes reused old\n\t * instances into the fresh tree first, so equal children already share\n\t * instances — keeping this O(children), not O(subtree). Leaves have no\n\t * children, so {@link _localEquals} is their whole comparison.\n\t */\n\tequalsShallow(other: AstNode): boolean {\n\t\tif (this === other) { return true; }\n\t\tif (this.kind !== other.kind || this.length !== other.length) { return false; }\n\t\tif (!this._localEquals(other as this)) { return false; }\n\t\tconst a = this.children;\n\t\tconst b = other.children;\n\t\tif (a.length !== b.length) { return false; }\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (a[i] !== b[i]) { return false; }\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Compares only this node's own scalar fields (kind/length already match). */\n\tprotected _localEquals(_other: this): boolean { return true; }\n\n\t/**\n\t * A copy of this node that adopts `id`. Reconciliation uses this to carry an\n\t * old identity onto a node whose content changed. Nodes are immutable value\n\t * holders, so a shallow prototype copy with `id` overridden is sound.\n\t */\n\tcloneWithId(id: number): this {\n\t\tconst clone: this = Object.create(Object.getPrototypeOf(this));\n\t\tObject.assign(clone, this);\n\t\t(clone as { id: number }).id = id;\n\t\treturn clone;\n\t}\n}\n\nconst _emptyChildren: readonly AstNode[] = [];\n\nfunction _mapArr<T extends AstNode>(map: ReadonlyMap<AstNode, AstNode>, arr: readonly T[]): readonly T[] {\n\tlet out: T[] | undefined;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst m = map.get(arr[i]);\n\t\tif (m && m !== arr[i]) { (out ??= arr.slice())[i] = m as T; }\n\t}\n\treturn out ?? arr;\n}\n\nfunction _mapOne<T extends AstNode>(map: ReadonlyMap<AstNode, AstNode>, n: T): T {\n\tconst m = map.get(n);\n\treturn (m && m !== n ? m : n) as T;\n}\n\nfunction _mapTrivia(map: ReadonlyMap<AstNode, AstNode>, trivia: GlueAstNode | undefined): GlueAstNode | undefined {\n\treturn trivia ? _mapOne(map, trivia) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Leaves\n// ---------------------------------------------------------------------------\n\nabstract class LeafAstNode extends AstNode {\n\tabstract readonly content: string;\n\tget children(): readonly AstNode[] { return _emptyChildren; }\n\toverride get length(): number { return this.content.length; }\n\toverride mapChildren(): AstNode { return this; }\n}\n\n/** Real document text (an {@link InlineAstNode}). */\nexport class TextAstNode extends LeafAstNode {\n\treadonly kind = 'text';\n\tconstructor(readonly content: string) { super(); }\n\tprotected override _localEquals(o: this): boolean { return this.content === o.content; }\n}\n\n/** A semantic syntax marker (heading `#`, fences, brackets, list bullet, …). */\nexport class MarkerAstNode extends LeafAstNode {\n\treadonly kind = 'marker';\n\tconstructor(readonly markerKind: string, readonly content: string) { super(); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.markerKind === o.markerKind && this.content === o.content;\n\t}\n}\n\n/** Non-semantic syntactic glue: whitespace, padding, table pipes. */\nexport class GlueAstNode extends LeafAstNode {\n\treadonly kind = 'glue';\n\tconstructor(readonly content: string, readonly glueKind?: string) { super(); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.content === o.content && this.glueKind === o.glueKind;\n\t}\n}\n\n/**\n * A block-level node. Every block may carry a {@link leadingTrivia} glue — the\n * whitespace that precedes it on its own line (a nested list's indentation, the\n * leading space of a continued paragraph). It is owned by the block it precedes\n * (not the one it trails), so the view reveals it exactly when *this* block is\n * active, and it tiles at the block's front: {@link children} prepends it to the\n * block's own content while `content` stays the block's real payload.\n */\nexport abstract class BlockAstNodeBase extends AstNode {\n\tabstract readonly leadingTrivia?: GlueAstNode;\n\t/** This block with its leading trivia replaced — re-homes a leading glue onto it. */\n\tabstract withLeadingTrivia(trivia: GlueAstNode | undefined): BlockAstNode;\n\t/** Prepends {@link leadingTrivia}, if any, ahead of the block's own children. */\n\tprotected _withLeading(own: readonly AstNode[]): readonly AstNode[] {\n\t\treturn this.leadingTrivia ? [this.leadingTrivia, ...own] : own;\n\t}\n}\n\nexport class ThematicBreakAstNode extends BlockAstNodeBase {\n\treadonly kind = 'thematicBreak';\n\tconstructor(\n\t\treadonly content: readonly (MarkerAstNode | GlueAstNode)[],\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget marker(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ThematicBreakAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ThematicBreakAstNode { return new ThematicBreakAstNode(this.content, trivia); }\n}\n\n// ---------------------------------------------------------------------------\n// Inlines\n// ---------------------------------------------------------------------------\n\nexport type InlineAstNode = TextAstNode | StrongAstNode | EmphasisAstNode | StrikethroughAstNode | InlineCodeAstNode | InlineMathAstNode | LinkAstNode | ImageAstNode;\n\nfunction _marker(content: readonly AstNode[], kind: string): MarkerAstNode | undefined {\n\treturn content.find((n): n is MarkerAstNode => n instanceof MarkerAstNode && n.markerKind === kind);\n}\n\nexport class StrongAstNode extends AstNode {\n\treadonly kind = 'strong';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new StrongAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class EmphasisAstNode extends AstNode {\n\treadonly kind = 'emphasis';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new EmphasisAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class StrikethroughAstNode extends AstNode {\n\treadonly kind = 'strikethrough';\n\tconstructor(\n\t\treadonly openMarker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly closeMarker: MarkerAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return [this.openMarker, ...this.content, this.closeMarker]; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new StrikethroughAstNode(_mapOne(m, this.openMarker), _mapArr(m, this.content), _mapOne(m, this.closeMarker));\n\t}\n}\n\nexport class InlineCodeAstNode extends AstNode {\n\treadonly kind = 'inlineCode';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new InlineCodeAstNode(_mapArr(m, this.content)); }\n}\n\nexport class InlineMathAstNode extends AstNode {\n\treadonly kind = 'inlineMath';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new InlineMathAstNode(_mapArr(m, this.content)); }\n}\n\nexport class LinkAstNode extends AstNode {\n\treadonly kind = 'link';\n\tconstructor(readonly url: string, readonly content: readonly (MarkerAstNode | InlineAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new LinkAstNode(this.url, _mapArr(m, this.content)); }\n\tprotected override _localEquals(o: this): boolean { return this.url === o.url; }\n}\n\nexport class ImageAstNode extends AstNode {\n\treadonly kind = 'image';\n\tconstructor(readonly alt: string, readonly url: string, readonly content: readonly (MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ImageAstNode(this.alt, this.url, _mapArr(m, this.content)); }\n\tprotected override _localEquals(o: this): boolean {\n\t\treturn this.alt === o.alt && this.url === o.url;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockAstNode = HeadingAstNode | ParagraphAstNode | CodeBlockAstNode | MathBlockAstNode | ThematicBreakAstNode | BlockQuoteAstNode | ListAstNode | TableAstNode;\n\nexport class HeadingAstNode extends BlockAstNodeBase {\n\treadonly kind = 'heading';\n\tconstructor(\n\t\treadonly level: 1 | 2 | 3 | 4 | 5 | 6,\n\t\treadonly marker: MarkerAstNode,\n\t\treadonly content: readonly (InlineAstNode | GlueAstNode)[],\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading([this.marker, ...this.content]); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new HeadingAstNode(this.level, _mapOne(m, this.marker), _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia));\n\t}\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): HeadingAstNode {\n\t\treturn new HeadingAstNode(this.level, this.marker, this.content, trivia);\n\t}\n\tprotected override _localEquals(o: this): boolean { return this.level === o.level; }\n}\n\nexport class ParagraphAstNode extends BlockAstNodeBase {\n\treadonly kind = 'paragraph';\n\tconstructor(readonly content: readonly (InlineAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ParagraphAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ParagraphAstNode { return new ParagraphAstNode(this.content, trivia); }\n}\n\nexport class CodeBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'codeBlock';\n\tprivate _previous?: WeakRef<CodeBlockAstNode>;\n\tprivate _contentEdit?: StringEdit;\n\tconstructor(readonly language: string, readonly content: readonly (MarkerAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget openFence(): MarkerAstNode | undefined { return _marker(this.content, 'openFence'); }\n\tget closeFence(): MarkerAstNode | undefined { return _marker(this.content, 'closeFence'); }\n\tget code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\n\t/** Relative start offset of the {@link code} marker within this block. */\n\tget codeOffset(): number {\n\t\tlet pos = this.leadingTrivia?.length ?? 0;\n\t\tfor (const c of this.content) { if (c.kind === 'marker' && (c as MarkerAstNode).markerKind === 'content') { return pos; } pos += c.length; }\n\t\treturn pos;\n\t}\n\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new CodeBlockAstNode(this.language, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): CodeBlockAstNode { return new CodeBlockAstNode(this.language, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.language === o.language; }\n\n\t/**\n\t * A copy of this block carrying an incremental link to `previous`:\n\t * `contentEdit` (in the block's *content* coordinates) turns `previous`'s\n\t * content into this one. Uses a weak reference so the previous tree can be\n\t * garbage-collected.\n\t */\n\twithCodeDiff(previous: CodeBlockAstNode, contentEdit: StringEdit): CodeBlockAstNode {\n\t\tconst clone = this.cloneWithId(this.id) as CodeBlockAstNode;\n\t\tclone._previous = new WeakRef(previous);\n\t\tclone._contentEdit = contentEdit;\n\t\treturn clone;\n\t}\n\n\t/**\n\t * When this block was incrementally derived from `previous` (same\n\t * fences/language, edit entirely within the content), returns the\n\t * content-coordinate edit; otherwise `undefined`.\n\t */\n\tgetDiff(previous: CodeBlockAstNode): CodeBlockDiff | undefined {\n\t\tif (this._contentEdit && this._previous?.deref() === previous) {\n\t\t\treturn { stringEdit: this._contentEdit };\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Describes how a {@link CodeBlockAstNode} was incrementally derived from a previous\n * one: {@link stringEdit} (in the block's *content* coordinates) turns the\n * previous content into this one.\n */\nexport interface CodeBlockDiff {\n\treadonly stringEdit: StringEdit;\n}\n\nexport class MathBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'mathBlock';\n\tconstructor(readonly content: readonly (MarkerAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new MathBlockAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): MathBlockAstNode { return new MathBlockAstNode(this.content, trivia); }\n}\n\nexport class BlockQuoteAstNode extends BlockAstNodeBase {\n\treadonly kind = 'blockQuote';\n\tconstructor(readonly content: readonly (MarkerAstNode | BlockAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new BlockQuoteAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): BlockQuoteAstNode { return new BlockQuoteAstNode(this.content, trivia); }\n}\n\nexport class ListAstNode extends BlockAstNodeBase {\n\treadonly kind = 'list';\n\tconstructor(readonly ordered: boolean, readonly content: readonly (ListItemAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tget items(): readonly ListItemAstNode[] { return this.content.filter((n): n is ListItemAstNode => n instanceof ListItemAstNode); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new ListAstNode(this.ordered, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): ListAstNode { return new ListAstNode(this.ordered, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.ordered === o.ordered; }\n}\n\nexport class ListItemAstNode extends AstNode {\n\treadonly kind = 'listItem';\n\tconstructor(\n\t\treadonly marker: MarkerAstNode,\n\t\treadonly content: readonly (BlockAstNode | GlueAstNode)[],\n\t\treadonly checked?: boolean,\n\t\treadonly leadingTrivia?: GlueAstNode,\n\t) { super(); }\n\tget children(): readonly AstNode[] {\n\t\treturn this.leadingTrivia ? [this.leadingTrivia, this.marker, ...this.content] : [this.marker, ...this.content];\n\t}\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode {\n\t\treturn new ListItemAstNode(\n\t\t\t_mapOne(m, this.marker),\n\t\t\t_mapArr(m, this.content),\n\t\t\tthis.checked,\n\t\t\tthis.leadingTrivia ? _mapOne(m, this.leadingTrivia) : undefined,\n\t\t);\n\t}\n\twithLeadingTrivia(trivia: GlueAstNode | undefined): ListItemAstNode {\n\t\treturn new ListItemAstNode(this.marker, this.content, this.checked, trivia);\n\t}\n\tprotected override _localEquals(o: this): boolean { return this.checked === o.checked; }\n}\n\nexport class TableAstNode extends BlockAstNodeBase {\n\treadonly kind = 'table';\n\tconstructor(readonly content: readonly (TableRowAstNode | GlueAstNode)[], readonly leadingTrivia?: GlueAstNode) { super(); }\n\tget children(): readonly AstNode[] { return this._withLeading(this.content); }\n\tprivate get _rows(): readonly TableRowAstNode[] { return this.content.filter((n): n is TableRowAstNode => n instanceof TableRowAstNode); }\n\tget headerRow(): TableRowAstNode | undefined { return this._rows[0]; }\n\tget delimiterRow(): TableRowAstNode | undefined { return this._rows[1]; }\n\tget bodyRows(): readonly TableRowAstNode[] { return this._rows.slice(2); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableAstNode(_mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): TableAstNode { return new TableAstNode(this.content, trivia); }\n}\n\nexport class TableRowAstNode extends AstNode {\n\treadonly kind = 'tableRow';\n\tconstructor(readonly content: readonly (TableCellAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\tget cells(): readonly TableCellAstNode[] { return this.content.filter((n): n is TableCellAstNode => n instanceof TableCellAstNode); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableRowAstNode(_mapArr(m, this.content)); }\n}\n\nexport class TableCellAstNode extends AstNode {\n\treadonly kind = 'tableCell';\n\tconstructor(readonly content: readonly (InlineAstNode | MarkerAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new TableCellAstNode(_mapArr(m, this.content)); }\n}\n\nexport class DocumentAstNode extends AstNode {\n\treadonly kind = 'document';\n\tconstructor(readonly content: readonly (BlockAstNode | GlueAstNode)[]) { super(); }\n\tget children(): readonly AstNode[] { return this.content; }\n\tget blocks(): readonly BlockAstNode[] { return this.content.filter(_isBlock); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new DocumentAstNode(_mapArr(m, this.content)); }\n}\n\nfunction _isBlock(n: AstNode): n is BlockAstNode {\n\treturn n instanceof HeadingAstNode || n instanceof ParagraphAstNode || n instanceof CodeBlockAstNode\n\t\t|| n instanceof MathBlockAstNode || n instanceof ThematicBreakAstNode || n instanceof BlockQuoteAstNode\n\t\t|| n instanceof ListAstNode || n instanceof TableAstNode;\n}\n// ---------------------------------------------------------------------------\n// Public helpers\n// ---------------------------------------------------------------------------\n\n/** Every concrete node kind, for exhaustive consumer-side dispatch. */\nexport type AnyAstNode =\n\t| TextAstNode | MarkerAstNode | GlueAstNode | ThematicBreakAstNode\n\t| StrongAstNode | EmphasisAstNode | StrikethroughAstNode | InlineCodeAstNode | InlineMathAstNode | LinkAstNode | ImageAstNode\n\t| HeadingAstNode | ParagraphAstNode | CodeBlockAstNode | MathBlockAstNode | BlockQuoteAstNode | ListAstNode | ListItemAstNode\n\t| TableAstNode | TableRowAstNode | TableCellAstNode | DocumentAstNode;\n\n/**\n * Source offset (relative to `root`) of the node with `target`'s id, or\n * `undefined` when it is not in the tree. Ids are stable across edits, so this\n * locates a node even after reconciliation has rebuilt the tree around it.\n */\nexport function findNodeOffsetById(root: AstNode, target: AstNode): number | undefined {\n\tif (root.id === target.id) { return 0; }\n\tlet pos = 0;\n\tfor (const child of root.children) {\n\t\tconst inner = findNodeOffsetById(child, target);\n\t\tif (inner !== undefined) { return pos + inner; }\n\t\tpos += child.length;\n\t}\n\treturn undefined;\n}\n\nconst _TASK_CHECKBOX_RE = /\\[[ xX]\\]/;\n\n/**\n * Source range (relative to `item`) of a task list item's `[x]`/`[ ]`\n * checkbox, or `undefined` when the item is not a task item. The checkbox is\n * plain glue in the AST, so a host that wants to toggle it locates the literal\n * `[x]`/`[ ]` token here.\n */\nexport function taskCheckboxRange(item: ListItemAstNode): OffsetRange | undefined {\n\tif (item.checked === undefined) { return undefined; }\n\tconst match = _TASK_CHECKBOX_RE.exec(_nodeText(item));\n\tif (!match) { return undefined; }\n\treturn OffsetRange.ofStartAndLength(match.index, match[0].length);\n}\n\n/** Source text of a node, reconstructed from its leaf content. */\nfunction _nodeText(node: AstNode): string {\n\tif (node instanceof LeafAstNode) { return node.content; }\n\tlet text = '';\n\tfor (const child of node.children) { text += _nodeText(child); }\n\treturn text;\n}","import { parse, preprocess, postprocess } from 'micromark';\nimport { math } from 'micromark-extension-math';\nimport { gfmTable } from 'micromark-extension-gfm-table';\nimport { gfmTaskListItem } from 'micromark-extension-gfm-task-list-item';\nimport { gfmStrikethrough } from 'micromark-extension-gfm-strikethrough';\n\nexport interface MicromarkEvent {\n\treadonly type: 'enter' | 'exit';\n\treadonly tokenType: string;\n\treadonly startOffset: number;\n\treadonly endOffset: number;\n}\n\nexport function tokenize(source: string): MicromarkEvent[] {\n\tconst parser = parse({ extensions: [math(), gfmTable(), gfmTaskListItem(), gfmStrikethrough()] });\n\tconst chunks = preprocess()(source, undefined, true);\n\tconst nativeEvents = postprocess(parser.document().write(chunks));\n\n\treturn nativeEvents.map(([type, token]) => ({\n\t\ttype,\n\t\ttokenType: token.type,\n\t\tstartOffset: token.start.offset,\n\t\tendOffset: token.end.offset,\n\t}));\n}\n","/**\n * Full-grammar parser for the prototype AST. Tokenizes with micromark (via the\n * shared adapter) and distills the event stream into the computed-`children`\n * AST. Spans no token claims become explicit {@link GlueAstNode}, so every node's\n * `content` tiles its source range exactly and contiguously — the property\n * that makes offset-based reconciliation sound.\n */\n\nimport {\n BlockAstNodeBase, BlockQuoteAstNode, CodeBlockAstNode, DocumentAstNode, EmphasisAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, InlineCodeAstNode,\n InlineMathAstNode, LinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode, AstNode, ParagraphAstNode,\n StrikethroughAstNode, StrongAstNode, TableAstNode, TableCellAstNode, TableRowAstNode, TextAstNode, ThematicBreakAstNode,\n type BlockAstNode,\n} from './ast.js';\nimport { tokenize, type MicromarkEvent } from './_micromarkAdapter.js';\n\nexport function parse(source: string): DocumentAstNode {\n return new AstBuilder(tokenize(source), source).build();\n}\n\ntype Entry = { node: AstNode; start: number };\n\n/**\n * Re-attributes an `indent` glue (the spaces after a line break) onto the block\n * it precedes, as that block's leading trivia, so the whitespace tiles and\n * renders on the indented block's own line (revealed when *it* is active) rather\n * than trailing the previous one:\n * - before a {@link ListAstNode}: onto that list's first item,\n * - before a {@link ListItemAstNode}: onto that item,\n * - before any other {@link BlockAstNodeBase}: onto the block itself,\n * all via the node's `leadingTrivia` slot. An indent glue with no such host is\n * merged back into the preceding line-break glue, so it never renders as a\n * standalone run between blocks. Offsets stay exact: the glue keeps its source\n * span, it just moves inside (or back into) a sibling.\n */\nfunction _pullIndentIntoBlocks<T extends AstNode>(content: readonly T[]): T[] {\n const out: T[] = [];\n for (let i = 0; i < content.length; i++) {\n const cur = content[i];\n const next = content[i + 1];\n if (cur instanceof GlueAstNode && cur.glueKind === 'indent') {\n const hosted = next !== undefined ? _prependLeadingTrivia(next, cur) : undefined;\n if (hosted) {\n out.push(hosted as unknown as T);\n i++;\n continue;\n }\n // No host for the indentation: fold it back into the preceding\n // line break so it stays hidden rather than rendering as dots.\n const prev = out[out.length - 1];\n if (prev instanceof GlueAstNode && prev.glueKind === undefined) {\n out[out.length - 1] = new GlueAstNode(prev.content + cur.content) as unknown as T;\n continue;\n }\n out.push(cur);\n continue;\n }\n out.push(cur);\n }\n return out;\n}\n\n/**\n * Hosts `glue` as the leading trivia of `next` when `next` can carry it — a\n * list (onto its first item), a list item, or any block — returning the rebuilt\n * node, or `undefined` when `next` cannot host leading trivia.\n */\nfunction _prependLeadingTrivia(next: AstNode, glue: GlueAstNode): AstNode | undefined {\n if (next instanceof ListAstNode) {\n const firstIdx = next.content.findIndex(n => n instanceof ListItemAstNode);\n if (firstIdx < 0) { return undefined; }\n const items = next.content.map((n, j) => (j === firstIdx ? (n as ListItemAstNode).withLeadingTrivia(glue) : n));\n return new ListAstNode(next.ordered, items, next.leadingTrivia);\n }\n if (next instanceof ListItemAstNode) { return next.withLeadingTrivia(glue); }\n if (next instanceof BlockAstNodeBase) { return next.withLeadingTrivia(glue); }\n return undefined;\n}\n\n/**\n * Re-attributes every plain document-level glue — the blank lines and trailing\n * newlines that separate top-level blocks — onto the block it follows, as a\n * trailing glue appended to that block's own `content`. The view then reveals\n * the gap (character-for-character) exactly when that preceding block is active,\n * and renders it at the end of the block rather than as a standalone run between\n * blocks.\n *\n * The gap is tagged by what it does:\n * - `blockBreak` — it separates two *paragraphs* (`para\\n\\npara`), the only\n * case where deleting a newline merges the blocks: the two paragraphs fuse\n * into one and the surviving newline re-parses as an ordinary soft break.\n * The view paints its leading newline as a distinct (blue) glyph. A heading\n * or any other block self-delimits after a single newline, so a gap after it\n * (or before a non-paragraph) is structurally inert and is *not* a break.\n * - `blockGap` — every other gap: after a non-paragraph block, before a\n * non-paragraph block, a trailing gap with no following block, or a\n * leading/hostless gap (one at the very start of the document, before the\n * first block, with no preceding block to host it).\n * Its newlines are neutral.\n *\n * Only untagged glue is touched (an `indent` glue keeps its kind); offsets are\n * untouched — the glue keeps its source span, it just moves inside the preceding\n * block.\n */\nfunction _attachBlockGaps<T extends AstNode>(content: readonly (T | GlueAstNode)[]): (T | GlueAstNode)[] {\n const out: (T | GlueAstNode)[] = [];\n for (let idx = 0; idx < content.length; idx++) {\n const n = content[idx];\n if (n instanceof GlueAstNode && n.glueKind === undefined) {\n const prev = out[out.length - 1];\n const next = content[idx + 1];\n // A break only exists between two paragraphs: that is the sole gap\n // whose deletion merges the blocks. After a heading (or before any\n // non-paragraph) the gap is structurally inert, so it stays neutral.\n const isParagraphBreak = prev instanceof ParagraphAstNode && next instanceof ParagraphAstNode;\n const gap = new GlueAstNode(n.content, isParagraphBreak ? 'blockBreak' : 'blockGap');\n const host = prev !== undefined ? _appendTrailingGlue(prev, gap) : undefined;\n if (host) { out[out.length - 1] = host as T | GlueAstNode; } else { out.push(gap); }\n continue;\n }\n out.push(n);\n }\n return out;\n}\n\n/**\n * Returns `node` rebuilt with `glue` consumed as its trailing trivia — the\n * greedy-block rule: a block (and the item/quote that hosts it) swallows the\n * whitespace that follows it, exactly like a recursive-descent scanner attaches\n * trailing trivia to the token it just read. Leaf blocks append `glue` to their\n * own `content`; containers ({@link BlockQuoteAstNode}, {@link ListAstNode},\n * {@link ListItemAstNode}) recurse into their last child so the glue lands at the\n * end of the deepest trailing paragraph. Returns `undefined` when `node` cannot\n * host trailing glue (a leaf marker, a glue, an inline), so the caller keeps the\n * gap standalone.\n */\nfunction _appendTrailingGlue(node: AstNode, glue: GlueAstNode): AstNode | undefined {\n switch (node.kind) {\n case 'paragraph': { const p = node as ParagraphAstNode; return new ParagraphAstNode([...p.content, glue], p.leadingTrivia); }\n case 'heading': { const h = node as HeadingAstNode; return new HeadingAstNode(h.level, h.marker, [...h.content, glue], h.leadingTrivia); }\n case 'codeBlock': { const c = node as CodeBlockAstNode; return new CodeBlockAstNode(c.language, [...c.content, glue], c.leadingTrivia); }\n case 'mathBlock': { const m = node as MathBlockAstNode; return new MathBlockAstNode([...m.content, glue], m.leadingTrivia); }\n case 'thematicBreak': { const t = node as ThematicBreakAstNode; return new ThematicBreakAstNode([...t.content, glue], t.leadingTrivia); }\n case 'table': { const t = node as TableAstNode; return new TableAstNode([...t.content, glue], t.leadingTrivia); }\n case 'blockQuote': { const b = node as BlockQuoteAstNode; return new BlockQuoteAstNode(_appendIntoLast(b.content, glue), b.leadingTrivia); }\n case 'list': { const l = node as ListAstNode; return new ListAstNode(l.ordered, _appendIntoLast(l.content, glue), l.leadingTrivia); }\n case 'listItem': { const it = node as ListItemAstNode; return new ListItemAstNode(it.marker, _appendIntoLast(it.content, glue), it.checked, it.leadingTrivia); }\n default: return undefined;\n }\n}\n\n/**\n * Recurses {@link _appendTrailingGlue} into the *last* child of `content` so the\n * glue sinks into the deepest trailing paragraph. Only the last child is tried —\n * the glue is the trailing-most run in source, so it must stay after any glue the\n * last child already carries; when the last child cannot host it (or there is\n * none), the glue is appended at the end, preserving source order.\n */\nfunction _appendIntoLast<T extends AstNode>(content: readonly T[], glue: GlueAstNode): T[] {\n const last = content[content.length - 1];\n const host = last !== undefined ? _appendTrailingGlue(last, glue) : undefined;\n if (host) { const out = content.slice(); out[out.length - 1] = host as T; return out; }\n return [...content, glue as unknown as T];\n}\n\n/**\n * Guarantees the document has at least one block. A source with no blocks (the\n * empty string, or whitespace-only input that produced only leading glue)\n * becomes a single empty {@link ParagraphAstNode} hosting whatever glue was\n * present, so document content is always a run of blocks.\n */\nfunction _ensureBlocks(content: readonly (BlockAstNode | GlueAstNode)[]): readonly (BlockAstNode | GlueAstNode)[] {\n if (content.some(n => !(n instanceof GlueAstNode))) { return content; }\n return [new ParagraphAstNode(content as readonly GlueAstNode[])];\n}\n\n/**\n * Collects a node's placed children and fills the gaps between them with\n * {@link GlueAstNode}, yielding an array that tiles `[parentStart, parentStart+len)`\n * exactly. `glueKind` tags glue that must stay hideable (table cell pipes).\n */\nclass Content {\n private readonly _entries: Entry[] = [];\n constructor(private readonly _parentStart: number, private readonly _source: string) { }\n\n add(node: AstNode, start: number): void { this._entries.push({ node, start }); }\n\n build<T extends AstNode = AstNode>(parentLength: number, glueKind?: string): T[] {\n this._entries.sort((a, b) => a.start - b.start);\n const out: AstNode[] = [];\n let pos = this._parentStart;\n const end = this._parentStart + parentLength;\n // Split a gap that ends in indentation (a newline followed by spaces/tabs)\n // into the line break plus a separate `indent` glue, mirroring how a\n // tokenizer attributes leading trivia to the following token. The indent\n // glue is later re-attributed onto the block it precedes (see\n // `_pullIndentIntoBlocks`), so its whitespace renders on that block's line\n // instead of trailing the previous one.\n const gap = (s: number, e: number) => {\n const text = this._source.substring(s, e);\n const m = glueKind ? null : /\\n[^\\S\\n]+$/.exec(text);\n if (!m) { out.push(new GlueAstNode(text, glueKind)); return; }\n const indent = text.slice(m.index + 1);\n out.push(new GlueAstNode(text.slice(0, text.length - indent.length)));\n out.push(new GlueAstNode(indent, 'indent'));\n };\n for (const { node, start } of this._entries) {\n if (node.length === 0) { continue; }\n if (start > pos) { gap(pos, start); }\n out.push(node);\n pos = start + node.length;\n }\n if (pos < end) { gap(pos, end); }\n return out as T[];\n }\n}\n\nclass AstBuilder {\n private _idx = 0;\n private _checkChecked: boolean | undefined;\n\n constructor(private readonly _events: MicromarkEvent[], private readonly _source: string) { }\n\n build(): DocumentAstNode {\n const cb = new Content(0, this._source);\n while (this._idx < this._events.length) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter') {\n const start = ev.startOffset;\n const block = this._tryParseBlock();\n if (block) { cb.add(block, start); } else { this._idx++; }\n } else { this._idx++; }\n }\n return new DocumentAstNode(_ensureBlocks(_attachBlockGaps(_pullIndentIntoBlocks(cb.build<BlockAstNode | GlueAstNode>(this._source.length)))));\n }\n\n private _tryParseBlock(): BlockAstNode | undefined {\n switch (this._events[this._idx].tokenType) {\n case 'atxHeading': return this._parseHeading();\n case 'paragraph': return this._parseParagraph();\n case 'codeFenced': return this._parseCodeFenced();\n case 'codeIndented': return this._parseCodeIndented();\n case 'mathFlow': return this._parseMathFlow();\n case 'thematicBreak': return this._parseThematicBreak();\n case 'blockQuote': return this._parseBlockQuote();\n case 'listUnordered':\n case 'listOrdered': return this._parseList();\n case 'table': return this._parseTable();\n default: return undefined;\n }\n }\n\n private _parseHeading(): HeadingAstNode {\n const enter = this._consume('enter', 'atxHeading');\n let level: 1 | 2 | 3 | 4 | 5 | 6 = 1;\n let markerStart = enter.startOffset;\n let markerEnd = enter.startOffset;\n const inlines: Entry[] = [];\n\n while (this._notExit('atxHeading')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'atxHeadingSequence') {\n const seqEnter = this._consume('enter', 'atxHeadingSequence');\n const seqExit = this._consume('exit', 'atxHeadingSequence');\n if (markerEnd === enter.startOffset) {\n level = Math.min(6, Math.max(1, seqExit.endOffset - seqEnter.startOffset)) as 1 | 2 | 3 | 4 | 5 | 6;\n markerStart = seqEnter.startOffset;\n markerEnd = seqExit.endOffset;\n }\n } else if (ev.type === 'enter' && ev.tokenType === 'atxHeadingText') {\n this._consume('enter', 'atxHeadingText');\n this._parseInlines(inlines, 'atxHeadingText');\n this._consume('exit', 'atxHeadingText');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'atxHeading');\n if (markerEnd > markerStart && inlines.length > 0) { markerEnd = inlines[0].start; }\n\n const marker = new MarkerAstNode('headingMarker', this._source.substring(enter.startOffset, markerEnd));\n const cb = new Content(markerEnd, this._source);\n for (const e of inlines) { cb.add(e.node, e.start); }\n const content = cb.build<HeadingAstNode['content'][number]>(exit.endOffset - markerEnd);\n return new HeadingAstNode(level, marker, content);\n }\n\n private _parseParagraph(): ParagraphAstNode {\n const enter = this._consume('enter', 'paragraph');\n const inlines: Entry[] = [];\n while (this._notExit('paragraph')) { this._parseInlineEvent(inlines); }\n const exit = this._consume('exit', 'paragraph');\n const cb = new Content(enter.startOffset, this._source);\n for (const e of inlines) { cb.add(e.node, e.start); }\n return new ParagraphAstNode(cb.build<ParagraphAstNode['content'][number]>(exit.endOffset - enter.startOffset));\n }\n\n private _parseCodeFenced(): CodeBlockAstNode {\n const enter = this._consume('enter', 'codeFenced');\n let language = '';\n const cb = new Content(enter.startOffset, this._source);\n let sawOpenFence = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n\n while (this._notExit('codeFenced')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'codeFencedFence') {\n const fenceEnter = this._consume('enter', 'codeFencedFence');\n while (this._notExit('codeFencedFence')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'codeFencedFenceInfo') {\n this._consume('enter', 'codeFencedFenceInfo');\n while (this._notExit('codeFencedFenceInfo')) {\n const ii = this._events[this._idx];\n if (ii.tokenType === 'data') { language = this._source.substring(ii.startOffset, ii.endOffset); }\n this._idx++;\n }\n this._consume('exit', 'codeFencedFenceInfo');\n } else { this._idx++; }\n }\n const fenceExit = this._consume('exit', 'codeFencedFence');\n cb.add(new MarkerAstNode(sawOpenFence ? 'closeFence' : 'openFence',\n this._source.substring(fenceEnter.startOffset, fenceExit.endOffset)), fenceEnter.startOffset);\n sawOpenFence = true;\n } else if (ev.tokenType === 'codeFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'codeFenced');\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n }\n return new CodeBlockAstNode(language, cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n /**\n * An indented code block has no fences and no info string: micromark strips a\n * four-space `linePrefix` from each line and emits the rest as `codeFlowValue`.\n * Each line's `linePrefix` becomes a hideable `codeIndent` marker (so the\n * structural indentation can be dropped from the rendered block, like a\n * heading's `#`), while the actual code is kept verbatim as `content` markers\n * — one run per line — so the block round-trips the source.\n */\n private _parseCodeIndented(): CodeBlockAstNode {\n const enter = this._consume('enter', 'codeIndented');\n const cb = new Content(enter.startOffset, this._source);\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n const flushContent = () => {\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n contentStart = undefined;\n }\n };\n while (this._notExit('codeIndented')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'linePrefix') {\n flushContent();\n const prefixEnter = this._consume('enter', 'linePrefix');\n const prefixExit = this._consume('exit', 'linePrefix');\n cb.add(new MarkerAstNode('codeIndent', this._source.substring(prefixEnter.startOffset, prefixExit.endOffset)), prefixEnter.startOffset);\n } else if (ev.tokenType === 'codeFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n flushContent();\n const exit = this._consume('exit', 'codeIndented');\n return new CodeBlockAstNode('', cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseMathFlow(): MathBlockAstNode {\n const enter = this._consume('enter', 'mathFlow');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpenFence = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n\n while (this._notExit('mathFlow')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'mathFlowFence') {\n const fenceEnter = this._consume('enter', 'mathFlowFence');\n while (this._notExit('mathFlowFence')) { this._idx++; }\n const fenceExit = this._consume('exit', 'mathFlowFence');\n cb.add(new MarkerAstNode(sawOpenFence ? 'closeFence' : 'openFence',\n this._source.substring(fenceEnter.startOffset, fenceExit.endOffset)), fenceEnter.startOffset);\n sawOpenFence = true;\n } else if (ev.tokenType === 'mathFlowValue' || ev.tokenType === 'lineEnding') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n this._idx++;\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'mathFlow');\n if (contentStart !== undefined) {\n cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart);\n }\n return new MathBlockAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseThematicBreak(): ThematicBreakAstNode {\n const enter = this._consume('enter', 'thematicBreak');\n while (this._notExit('thematicBreak')) { this._idx++; }\n const exit = this._consume('exit', 'thematicBreak');\n const marker = new MarkerAstNode('content', this._source.substring(enter.startOffset, exit.endOffset));\n return new ThematicBreakAstNode([marker]);\n }\n\n private _parseBlockQuote(): BlockQuoteAstNode {\n const enter = this._consume('enter', 'blockQuote');\n const cb = new Content(enter.startOffset, this._source);\n let seenBlock = false;\n while (this._notExit('blockQuote')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'blockQuotePrefix') {\n const pre = this._consume('enter', 'blockQuotePrefix');\n while (this._notExit('blockQuotePrefix')) { this._idx++; }\n const preExit = this._consume('exit', 'blockQuotePrefix');\n // The *leading* `>` (this level's prefix, before its first child\n // block) becomes a real `blockQuoteMarker` marker: it sits at the\n // block's start with a single, unambiguous caret position, so the\n // view can hang it in the quote's left padding gutter (adding no\n // inline width, keeping content at the same x in active/inactive)\n // and a nested quote — itself inset by the outer padding — forms a\n // column one level in.\n //\n // Continuation prefixes (a blank quoted line, the `>` that starts a\n // later block) *follow* a block on their own line; a gutter marker\n // there would share the previous line's trailing caret position and\n // break the one-offset-one-caret invariant. They stay inline glue\n // (tiled by `Content` / attached by `_attachBlockGaps`), reading\n // naturally where the `>` falls in the source.\n if (!seenBlock) {\n cb.add(new MarkerAstNode('blockQuoteMarker', this._source.substring(pre.startOffset, preExit.endOffset)), pre.startOffset);\n }\n } else if (ev.type === 'enter') {\n const start = ev.startOffset;\n const block = this._tryParseBlock();\n if (block) { cb.add(block, start); seenBlock = true; } else { this._idx++; }\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'blockQuote');\n return new BlockQuoteAstNode(_attachBlockGaps(_pullIndentIntoBlocks(cb.build<BlockQuoteAstNode['content'][number]>(exit.endOffset - enter.startOffset))));\n }\n\n private _parseList(): ListAstNode {\n const listType = this._events[this._idx].tokenType;\n const ordered = listType === 'listOrdered';\n const enter = this._consume('enter', listType);\n const cb = new Content(enter.startOffset, this._source);\n\n let itemStart: number | undefined;\n let markerStart: number | undefined;\n let markerEnd: number | undefined;\n let itemCb: Content | undefined;\n let itemChecked: boolean | undefined;\n let lastBlockEnd: number | undefined;\n\n const flush = () => {\n if (itemStart === undefined || markerStart === undefined || itemCb === undefined) { return; }\n const marker = new MarkerAstNode('listItemMarker', this._source.substring(markerStart, markerEnd!));\n // The task checkbox lives inside the item's first paragraph, so it\n // tiles there as Glue; only its checked state is lifted to the item.\n const itemEnd = lastBlockEnd ?? markerEnd!;\n const content = itemCb.build<ListItemAstNode['content'][number]>(itemEnd - markerEnd!);\n cb.add(new ListItemAstNode(marker, _attachBlockGaps(_pullIndentIntoBlocks(content)), itemChecked), itemStart);\n };\n\n while (this._notExit(listType)) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'listItemPrefix') {\n flush();\n this._consume('enter', 'listItemPrefix');\n itemStart = inner.startOffset;\n markerStart = inner.startOffset;\n itemChecked = undefined;\n lastBlockEnd = undefined;\n this._checkChecked = undefined;\n while (this._notExit('listItemPrefix')) { this._idx++; }\n markerEnd = this._events[this._idx].endOffset;\n this._consume('exit', 'listItemPrefix');\n itemCb = new Content(markerEnd, this._source);\n } else if (inner.type === 'enter') {\n const start = inner.startOffset;\n const block = this._tryParseBlock();\n if (block && itemCb) {\n itemCb.add(block, start);\n lastBlockEnd = start + block.length;\n if (itemChecked === undefined && this._checkChecked !== undefined) { itemChecked = this._checkChecked; }\n } else if (!block) { this._idx++; }\n } else { this._idx++; }\n }\n flush();\n const exit = this._consume('exit', listType);\n return new ListAstNode(ordered, _attachBlockGaps(_pullIndentIntoBlocks(cb.build<ListItemAstNode | GlueAstNode>(exit.endOffset - enter.startOffset))));\n }\n\n private _parseTable(): TableAstNode {\n const enter = this._consume('enter', 'table');\n const cb = new Content(enter.startOffset, this._source);\n let columnCount = 0;\n\n while (this._notExit('table')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'tableHead') {\n this._consume('enter', 'tableHead');\n while (this._notExit('tableHead')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableRow') {\n const row = this._parseTableRow('tableHeader');\n columnCount = row.cells.length;\n cb.add(row, inner.startOffset);\n } else if (inner.type === 'enter' && inner.tokenType === 'tableDelimiterRow') {\n const start = inner.startOffset;\n while (this._notExit('tableDelimiterRow')) { this._idx++; }\n const end = this._events[this._idx].endOffset;\n this._idx++;\n cb.add(this._buildDelimiterRow(start, end, columnCount), start);\n } else { this._idx++; }\n }\n this._consume('exit', 'tableHead');\n } else if (ev.type === 'enter' && ev.tokenType === 'tableBody') {\n this._consume('enter', 'tableBody');\n while (this._notExit('tableBody')) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableRow') {\n cb.add(this._parseTableRow('tableData'), inner.startOffset);\n } else { this._idx++; }\n }\n this._consume('exit', 'tableBody');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'table');\n return new TableAstNode(cb.build<TableRowAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _buildDelimiterRow(start: number, end: number, columnCount: number): TableRowAstNode {\n const raw = this._source.substring(start, end);\n const pipes: number[] = [];\n for (let i = 0; i < raw.length; i++) { if (raw[i] === '|') { pipes.push(i); } }\n const cellStartsRel: number[] = [];\n const cols = Math.max(1, columnCount);\n if (raw[0] === '|') {\n for (let i = 0; i < cols && i < pipes.length; i++) { cellStartsRel.push(pipes[i]); }\n } else {\n cellStartsRel.push(0);\n for (let i = 0; i < cols - 1 && i < pipes.length; i++) { cellStartsRel.push(pipes[i]); }\n }\n const rowCb = new Content(start, this._source);\n for (let i = 0; i < cellStartsRel.length; i++) {\n const cs = cellStartsRel[i];\n const ce = i + 1 < cellStartsRel.length ? cellStartsRel[i + 1] : raw.length;\n const cellCb = new Content(start + cs, this._source);\n const text = raw.substring(cs, ce);\n // The last cell's closing `|` is split into its own marker so the\n // view can pin it to the column's right gridline (matching the body\n // rows' closing-pipe glue); without the split the trailing pipe\n // floats right after the dashes and the last column's outline is\n // ragged. The leading `| --- ` stays a single `tableDelimiter`.\n const isLast = i === cellStartsRel.length - 1;\n if (isLast && text.length > 1 && text.endsWith('|')) {\n cellCb.add(new MarkerAstNode('tableDelimiter', text.slice(0, -1)), start + cs);\n cellCb.add(new MarkerAstNode('tableDelimiterClose', '|'), start + cs + text.length - 1);\n } else {\n cellCb.add(new MarkerAstNode('tableDelimiter', text), start + cs);\n }\n rowCb.add(new TableCellAstNode(cellCb.build<TableCellAstNode['content'][number]>(ce - cs)), start + cs);\n }\n return new TableRowAstNode(rowCb.build<TableCellAstNode | GlueAstNode>(end - start));\n }\n\n private _parseTableRow(cellType: 'tableHeader' | 'tableData'): TableRowAstNode {\n const enter = this._consume('enter', 'tableRow');\n const rowCb = new Content(enter.startOffset, this._source);\n while (this._notExit('tableRow')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === cellType) {\n const cellEnter = this._consume('enter', cellType);\n const inlines: Entry[] = [];\n while (this._notExit(cellType)) {\n const inner = this._events[this._idx];\n if (inner.type === 'enter' && inner.tokenType === 'tableContent') {\n this._consume('enter', 'tableContent');\n while (this._notExit('tableContent')) { this._parseInlineEvent(inlines); }\n this._consume('exit', 'tableContent');\n } else { this._idx++; }\n }\n const cellExit = this._consume('exit', cellType);\n const cellCb = new Content(cellEnter.startOffset, this._source);\n for (const e of inlines) { cellCb.add(e.node, e.start); }\n rowCb.add(new TableCellAstNode(cellCb.build<TableCellAstNode['content'][number]>(cellExit.endOffset - cellEnter.startOffset, 'tableCellGlue')), cellEnter.startOffset);\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'tableRow');\n return new TableRowAstNode(rowCb.build<TableCellAstNode | GlueAstNode>(exit.endOffset - enter.startOffset));\n }\n\n private _parseInlines(entries: Entry[], untilExit: string): void {\n while (this._idx < this._events.length) {\n const ev = this._events[this._idx];\n if (ev.type === 'exit' && ev.tokenType === untilExit) { return; }\n this._parseInlineEvent(entries);\n }\n }\n\n private _parseInlineEvent(entries: Entry[]): void {\n const ev = this._events[this._idx];\n if (ev.type === 'enter') {\n switch (ev.tokenType) {\n case 'strongSequence':\n case 'emphasisSequence': this._parseEmphasisOrStrong(entries); return;\n case 'codeText': entries.push(this._parseInlineCode()); return;\n case 'mathText': entries.push(this._parseInlineMath()); return;\n case 'link': entries.push(this._parseLink()); return;\n case 'image': entries.push(this._parseImage()); return;\n case 'strikethrough': entries.push(this._parseStrikethrough()); return;\n case 'hardBreakTrailing':\n case 'hardBreakEscape': entries.push(this._parseHardBreak()); return;\n }\n }\n if (ev.type === 'exit' && (ev.tokenType === 'data' || ev.tokenType === 'codeTextData')) {\n entries.push({ node: new TextAstNode(this._source.substring(ev.startOffset, ev.endOffset)), start: ev.startOffset });\n }\n if (ev.type === 'exit' && ev.tokenType === 'taskListCheckValueChecked') { this._checkChecked = true; }\n else if (ev.type === 'exit' && ev.tokenType === 'taskListCheckValueUnchecked') { this._checkChecked = false; }\n this._idx++;\n }\n\n /**\n * A GFM hard line break — either two-or-more trailing spaces\n * (`hardBreakTrailing`) or a backslash (`hardBreakEscape`) — followed by the\n * line ending it forces. Both halves are absorbed into a single\n * `hardBreak` marker, so the node *is* the whole break: a bare `lineEnding`\n * (a soft break) is never matched here and stays glue that collapses to a\n * space. Whether the line ending breaks is thus micromark's call, not ours.\n */\n private _parseHardBreak(): Entry {\n const enter = this._events[this._idx];\n const tokenType = enter.tokenType;\n this._consume('enter', tokenType);\n while (this._notExit(tokenType)) { this._idx++; }\n let end = this._consume('exit', tokenType).endOffset;\n const next = this._events[this._idx];\n if (next && next.type === 'enter' && next.tokenType === 'lineEnding') {\n this._consume('enter', 'lineEnding');\n end = this._consume('exit', 'lineEnding').endOffset;\n }\n return { node: new MarkerAstNode('hardBreak', this._source.substring(enter.startOffset, end)), start: enter.startOffset };\n }\n\n private _parseEmphasisOrStrong(entries: Entry[]): void {\n const tokenType = this._events[this._idx].tokenType;\n const isStrong = tokenType === 'strongSequence';\n const openEnter = this._consume('enter', tokenType);\n const openExit = this._consume('exit', tokenType);\n const inner: Entry[] = [];\n\n while (this._idx < this._events.length) {\n const next = this._events[this._idx];\n if (next.type === 'enter' && next.tokenType === tokenType) {\n const closeEnter = this._consume('enter', tokenType);\n const closeExit = this._consume('exit', tokenType);\n const openMarker = new MarkerAstNode('openMarker', this._source.substring(openEnter.startOffset, openExit.endOffset));\n const closeMarker = new MarkerAstNode('closeMarker', this._source.substring(closeEnter.startOffset, closeExit.endOffset));\n const cb = new Content(openExit.endOffset, this._source);\n for (const e of inner) { cb.add(e.node, e.start); }\n const content = cb.build<StrongAstNode['content'][number]>(closeEnter.startOffset - openExit.endOffset);\n const node = isStrong\n ? new StrongAstNode(openMarker, content, closeMarker)\n : new EmphasisAstNode(openMarker, content, closeMarker);\n entries.push({ node, start: openEnter.startOffset });\n return;\n }\n this._parseInlineEvent(inner);\n }\n entries.push({ node: new TextAstNode(this._source.substring(openEnter.startOffset, openExit.endOffset)), start: openEnter.startOffset });\n }\n\n private _parseInlineCode(): Entry {\n const enter = this._consume('enter', 'codeText');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpen = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n while (this._notExit('codeText')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'codeTextSequence') {\n cb.add(new MarkerAstNode(sawOpen ? 'closeMarker' : 'openMarker', this._source.substring(ev.startOffset, ev.endOffset)), ev.startOffset);\n sawOpen = true;\n } else if (ev.type === 'enter' && ev.tokenType === 'codeTextData') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n }\n this._idx++;\n }\n const exit = this._consume('exit', 'codeText');\n if (contentStart !== undefined) { cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart); }\n return { node: new InlineCodeAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseInlineMath(): Entry {\n const enter = this._consume('enter', 'mathText');\n const cb = new Content(enter.startOffset, this._source);\n let sawOpen = false;\n let contentStart: number | undefined;\n let contentEnd: number | undefined;\n while (this._notExit('mathText')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'mathTextSequence') {\n cb.add(new MarkerAstNode(sawOpen ? 'closeMarker' : 'openMarker', this._source.substring(ev.startOffset, ev.endOffset)), ev.startOffset);\n sawOpen = true;\n } else if (ev.type === 'enter' && ev.tokenType === 'mathTextData') {\n if (contentStart === undefined) { contentStart = ev.startOffset; }\n contentEnd = ev.endOffset;\n }\n this._idx++;\n }\n const exit = this._consume('exit', 'mathText');\n if (contentStart !== undefined) { cb.add(new MarkerAstNode('content', this._source.substring(contentStart, contentEnd!)), contentStart); }\n return { node: new InlineMathAstNode(cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseStrikethrough(): Entry {\n const enter = this._consume('enter', 'strikethrough');\n let openMarker: MarkerAstNode | undefined;\n let closeMarker: MarkerAstNode | undefined;\n let contentStart = enter.startOffset;\n let contentEnd = enter.startOffset;\n const inner: Entry[] = [];\n while (this._notExit('strikethrough')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'strikethroughSequence') {\n const text = this._source.substring(ev.startOffset, ev.endOffset);\n if (!openMarker) { openMarker = new MarkerAstNode('openMarker', text); contentStart = ev.endOffset; }\n else { closeMarker = new MarkerAstNode('closeMarker', text); contentEnd = ev.startOffset; }\n this._idx++;\n } else if (ev.type === 'enter' && ev.tokenType === 'strikethroughText') {\n this._consume('enter', 'strikethroughText');\n this._parseInlines(inner, 'strikethroughText');\n this._consume('exit', 'strikethroughText');\n } else { this._idx++; }\n }\n this._consume('exit', 'strikethrough');\n const cb = new Content(contentStart, this._source);\n for (const e of inner) { cb.add(e.node, e.start); }\n const content = cb.build<StrikethroughAstNode['content'][number]>(contentEnd - contentStart);\n return { node: new StrikethroughAstNode(openMarker!, content, closeMarker!), start: enter.startOffset };\n }\n\n private _parseLink(): Entry {\n const enter = this._consume('enter', 'link');\n const cb = new Content(enter.startOffset, this._source);\n const inner: Entry[] = [];\n let url = '';\n let sawOpenBracket = false;\n\n while (this._notExit('link')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'label') {\n this._consume('enter', 'label');\n while (this._notExit('label')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'labelMarker') {\n cb.add(new MarkerAstNode(sawOpenBracket ? 'closeBracket' : 'openBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenBracket = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'labelText') {\n this._consume('enter', 'labelText');\n this._parseInlines(inner, 'labelText');\n this._consume('exit', 'labelText');\n continue;\n }\n this._idx++;\n }\n this._consume('exit', 'label');\n } else if (ev.type === 'enter' && ev.tokenType === 'resource') {\n this._consume('enter', 'resource');\n let sawOpenParen = false;\n while (this._notExit('resource')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'resourceMarker') {\n cb.add(new MarkerAstNode(sawOpenParen ? 'closeParen' : 'openParen', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenParen = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'resourceDestinationString') {\n url = this._source.substring(i2.startOffset, i2.endOffset);\n cb.add(new MarkerAstNode('url', url), i2.startOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'resource');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'link');\n for (const e of inner) { cb.add(e.node, e.start); }\n return { node: new LinkAstNode(url, cb.build<LinkAstNode['content'][number]>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _parseImage(): Entry {\n const enter = this._consume('enter', 'image');\n const cb = new Content(enter.startOffset, this._source);\n let alt = '';\n let url = '';\n let sawOpenBracket = false;\n\n while (this._notExit('image')) {\n const ev = this._events[this._idx];\n if (ev.type === 'enter' && ev.tokenType === 'label') {\n this._consume('enter', 'label');\n while (this._notExit('label')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'labelImageMarker') {\n cb.add(new MarkerAstNode('bangBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n } else if (i2.type === 'enter' && i2.tokenType === 'labelMarker') {\n cb.add(new MarkerAstNode(sawOpenBracket ? 'closeBracket' : 'openBracket', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenBracket = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'labelText') {\n alt = this._source.substring(i2.startOffset, i2.endOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'label');\n } else if (ev.type === 'enter' && ev.tokenType === 'resource') {\n this._consume('enter', 'resource');\n let sawOpenParen = false;\n while (this._notExit('resource')) {\n const i2 = this._events[this._idx];\n if (i2.type === 'enter' && i2.tokenType === 'resourceMarker') {\n cb.add(new MarkerAstNode(sawOpenParen ? 'closeParen' : 'openParen', this._source.substring(i2.startOffset, i2.endOffset)), i2.startOffset);\n sawOpenParen = true;\n } else if (i2.type === 'enter' && i2.tokenType === 'resourceDestinationString') {\n url = this._source.substring(i2.startOffset, i2.endOffset);\n }\n this._idx++;\n }\n this._consume('exit', 'resource');\n } else { this._idx++; }\n }\n const exit = this._consume('exit', 'image');\n return { node: new ImageAstNode(alt, url, cb.build<MarkerAstNode | GlueAstNode>(exit.endOffset - enter.startOffset)), start: enter.startOffset };\n }\n\n private _notExit(tokenType: string): boolean {\n if (this._idx >= this._events.length) { return false; }\n const ev = this._events[this._idx];\n return !(ev.type === 'exit' && ev.tokenType === tokenType);\n }\n\n private _consume(type: 'enter' | 'exit', tokenType: string): MicromarkEvent {\n const ev = this._events[this._idx];\n if (!ev || ev.type !== type || ev.tokenType !== tokenType) {\n throw new Error(`Expected ${type}:${tokenType} at ${this._idx}, got ${ev?.type}:${ev?.tokenType}`);\n }\n this._idx++;\n return ev;\n }\n}\n","/**\n * Incremental reconciliation: build the fresh tree normally, then walk it\n * bottom-up against the previous tree, substituting previous instances where\n * the content is provably unchanged, and carrying over stable ids where a\n * node's identity survived an edit.\n *\n * Two soundness rules drive the whole thing:\n * - Full reuse of a node requires that its span maps to a *clean* (untouched)\n * original range, and that the rebuilt node is `structurallyEqual` to the\n * old one at that range. Because children are reconciled first, that\n * structural check is by identity and stays linear.\n * - Id carry-over uses the node's *start* offset (which, for a node that\n * merely contains an edit, lies before the edit and maps back cleanly), so\n * a node edited in place gets a new instance but keeps its old id.\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit, StringReplacement } from '../core/stringEdit.js';\nimport { CodeBlockAstNode, DocumentAstNode, AstNode } from './ast.js';\nimport { parse } from './parse.js';\n\n/** Maps offsets/ranges from modified (new) coordinates back to original (previous). */\nexport class EditMapper {\n constructor(private readonly _edit: StringEdit) { }\n\n /**\n * The original range corresponding to `mod`, or `undefined` if `mod`\n * overlaps any replaced/inserted text (i.e. is not provably unchanged).\n */\n getOriginalRange(mod: OffsetRange): OffsetRange | undefined {\n let delta = 0;\n for (const r of this._edit.replacements) {\n const modStart = r.replaceRange.start + delta;\n if (modStart >= mod.endExclusive) { break; }\n const dirtyEnd = modStart + r.newText.length;\n if (Math.max(modStart, mod.start) < Math.min(dirtyEnd, mod.endExclusive)) {\n return undefined;\n }\n delta += r.newText.length - r.replaceRange.length;\n }\n return mod.delta(-delta);\n }\n\n /** The original offset for `mod`, or `undefined` if it falls inside inserted text. */\n getOriginalOffset(mod: number): number | undefined {\n let delta = 0;\n for (const r of this._edit.replacements) {\n const modStart = r.replaceRange.start + delta;\n if (mod < modStart) { break; }\n if (mod < modStart + r.newText.length) { return undefined; }\n delta += r.newText.length - r.replaceRange.length;\n }\n return mod - delta;\n }\n}\n\n/** Indexes the previous tree for O(1) lookup by exact range or by stable id. */\nexport class OldTreeIndex {\n private readonly _byRange = new Map<string, AstNode[]>();\n private readonly _byId = new Map<string, AstNode>();\n\n constructor(root: AstNode) { this._walk(root, 0); }\n\n private _walk(n: AstNode, start: number): void {\n const key = `${start}:${start + n.length}`;\n let arr = this._byRange.get(key);\n if (!arr) { arr = []; this._byRange.set(key, arr); }\n arr.push(n);\n this._byId.set(`${start}:${n.kind}`, n);\n let pos = start;\n for (const c of n.children) { this._walk(c, pos); pos += c.length; }\n }\n\n /** The old node spanning exactly `range` with the given `kind`, if any. */\n lookupExact(range: OffsetRange, kind: string): AstNode | undefined {\n return this._byRange.get(`${range.start}:${range.endExclusive}`)?.find(n => n.kind === kind);\n }\n\n /** The old node that began at `originalStart` with the given `kind`. */\n lookupId(originalStart: number, kind: string): AstNode | undefined {\n return this._byId.get(`${originalStart}:${kind}`);\n }\n}\n\nfunction _reconcile(fresh: AstNode, start: number, mapper: EditMapper, index: OldTreeIndex, edit: StringEdit): AstNode {\n // 1. Reconcile children first, substituting reused instances upward.\n let map: Map<AstNode, AstNode> | undefined;\n let pos = start;\n for (const c of fresh.children) {\n const rc = _reconcile(c, pos, mapper, index, edit);\n if (rc !== c) { (map ??= new Map()).set(c, rc); }\n pos += c.length;\n }\n let n = map ? fresh.mapChildren(map) : fresh;\n\n // 2. Full reuse: clean original range + structurally identical old node.\n const orig = mapper.getOriginalRange(OffsetRange.ofStartAndLength(start, fresh.length));\n if (orig) {\n const cand = index.lookupExact(orig, n.kind);\n if (cand && n.equalsShallow(cand)) { return cand; }\n }\n\n // 3. Id carry-over: a changed node whose start maps cleanly to an old node\n // of the same kind keeps that old node's id (new instance, same identity).\n const os = mapper.getOriginalOffset(start);\n const old = os !== undefined ? index.lookupId(os, n.kind) : undefined;\n if (old && old.id !== n.id) { n = n.cloneWithId(old.id); }\n\n // 4. Code-block content link: when only the content changed, attach a\n // content-coordinate diff to the old block so the view can update in place.\n if (n instanceof CodeBlockAstNode && old instanceof CodeBlockAstNode && os !== undefined) {\n const linked = _linkCodeBlock(n, old, os, edit);\n if (linked) { return linked; }\n }\n\n return n;\n}\n\n/**\n * If `edit` lies entirely within `old`'s content and the fences/language are\n * unchanged, returns `fresh` carrying a content-coordinate diff to `old`;\n * otherwise `undefined`.\n */\nfunction _linkCodeBlock(fresh: CodeBlockAstNode, old: CodeBlockAstNode, oldStart: number, edit: StringEdit): CodeBlockAstNode | undefined {\n const oldCode = old.code;\n const freshCode = fresh.code;\n if (!oldCode || !freshCode) { return undefined; }\n if (fresh.language !== old.language) { return undefined; }\n if (fresh.openFence?.content !== old.openFence?.content) { return undefined; }\n if (fresh.closeFence?.content !== old.closeFence?.content) { return undefined; }\n\n const contentStart = oldStart + old.codeOffset;\n const contentEnd = contentStart + oldCode.length;\n if (!_editWithin(edit, contentStart, contentEnd)) { return undefined; }\n\n const contentEdit = _shiftEdit(edit, -contentStart);\n if (contentEdit.apply(oldCode.content) !== freshCode.content) { return undefined; }\n\n return fresh.withCodeDiff(old, contentEdit);\n}\n\n/** Whether every replacement of `edit` lies within `[start, endExclusive)`. */\nfunction _editWithin(edit: StringEdit, start: number, endExclusive: number): boolean {\n for (const r of edit.replacements) {\n if (r.replaceRange.start < start || r.replaceRange.endExclusive > endExclusive) { return false; }\n }\n return true;\n}\n\n/** `edit` with every replacement range shifted by `delta`. */\nfunction _shiftEdit(edit: StringEdit, delta: number): StringEdit {\n return new StringEdit(edit.replacements.map(r =>\n StringReplacement.replace(r.replaceRange.delta(delta), r.newText)));\n}\n\nexport function reconcile(fresh: AstNode, previous: AstNode, edit: StringEdit): AstNode {\n return _reconcile(fresh, 0, new EditMapper(edit), new OldTreeIndex(previous), edit);\n}\n\n/**\n * Parses `text`; when `previous` and `edit` are given, reconciles the fresh\n * tree against `previous` so unchanged subtrees keep their old instances and\n * edited id-bearing nodes keep their old ids.\n */\nexport function parseIncremental(text: string, previous?: DocumentAstNode, edit?: StringEdit): DocumentAstNode {\n const fresh = parse(text);\n if (!previous || !edit) {\n return fresh;\n }\n return reconcile(fresh, previous, edit) as DocumentAstNode;\n}\n","import { StringValue } from '../core/stringValue.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport { DocumentAstNode } from './ast.js';\nimport { parseIncremental } from './reconcile.js';\n\n/**\n * Parses markdown into a {@link DocumentAstNode}.\n *\n * When given the `previous` document and the `edit` that produced the new\n * text, it reuses unchanged subtrees and carries node identities across the\n * edit (see {@link parseIncremental}), so views can diff cheaply and code\n * blocks keep their incremental highlighting sessions.\n */\nexport class MarkdownParser {\n\tparse(text: StringValue, previous?: DocumentAstNode, edit?: StringEdit): DocumentAstNode {\n\t\treturn parseIncremental(text.value, previous, edit);\n\t}\n}\n","/**\n * Renders a node as XML-annotated source: every container becomes a\n * `<kind …>` element wrapping its children, leaves render their literal source\n * text, and {@link GlueAstNode}/{@link TextAstNode} render as raw text (no tag). This mirrors\n * the original parser's annotated-source format, adapted to the computed-\n * `children` + explicit-glue AST.\n */\n\nimport {\n CodeBlockAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, LinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, TextAstNode, type AstNode,\n} from '../ast.js';\n\nexport function getAnnotatedSource(node: AstNode, source: string, offset: number = 0): string {\n if (node.children.length === 0) {\n const text = escapeXml(source.substring(offset, offset + node.length));\n if (node instanceof TextAstNode) { return text; }\n const tag = node instanceof MarkerAstNode ? node.markerKind : node.kind;\n return `<${tag}${_attributes(node)}>${text}</${tag}>`;\n }\n\n let result = '';\n let childOffset = offset;\n for (const child of node.children) {\n result += getAnnotatedSource(child, source, childOffset);\n childOffset += child.length;\n }\n return `<${node.kind}${_attributes(node)}>${result}</${node.kind}>`;\n}\n\nfunction _attributes(node: AstNode): string {\n const attrs: Record<string, string> = {};\n if (node instanceof HeadingAstNode) { attrs.level = String(node.level); }\n else if (node instanceof ListAstNode) { attrs.ordered = String(node.ordered); }\n else if (node instanceof CodeBlockAstNode) { if (node.language) { attrs.language = node.language; } }\n else if (node instanceof LinkAstNode) { attrs.url = node.url; }\n else if (node instanceof ImageAstNode) { attrs.alt = node.alt; attrs.url = node.url; }\n else if (node instanceof ListItemAstNode) { if (node.checked !== undefined) { attrs.checked = String(node.checked); } }\n else if (node instanceof GlueAstNode) { if (node.glueKind) { attrs.kind = node.glueKind; } }\n return Object.entries(attrs).map(([k, v]) => ` ${k}=\"${escapeXml(v)}\"`).join('');\n}\n\nfunction escapeXml(str: string): string {\n return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n","/**\n * Adapts a parsed {@link AstNode} tree into the `ast.w` visualization payload\n * consumed by the web AST viewer\n * (`https://microsoft.github.io/vscode-web-editor-text-tools/?editor=ast-viewer`).\n *\n * The tree is dense and ordered — every node's `length` is the sum of its\n * children's lengths and siblings are contiguous — so source offsets are just a\n * running cursor threaded through a depth-first walk. No offset table or\n * per-node length arithmetic is needed beyond advancing past leaf text.\n */\n\nimport {\n AstNode, CodeBlockAstNode, GlueAstNode, HeadingAstNode, ImageAstNode, LinkAstNode,\n ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode, TextAstNode, ThematicBreakAstNode,\n} from './ast.js';\nimport { tokenize } from './_micromarkAdapter.js';\n\nexport interface AstVisualizationNode {\n label: string;\n range: [start: number, endExclusive: number];\n children?: AstVisualizationNode[];\n}\n\nexport interface AstVisualization {\n $fileExtension: 'ast.w';\n source: string;\n root: AstVisualizationNode;\n}\n\nfunction _label(n: AstNode): string {\n if (n instanceof TextAstNode) { return `text ${JSON.stringify(n.content)}`; }\n if (n instanceof GlueAstNode) { return `glue${n.glueKind ? `(${n.glueKind})` : ''} ${JSON.stringify(n.content)}`; }\n if (n instanceof MarkerAstNode) { return `marker(${n.markerKind}) ${JSON.stringify(n.content)}`; }\n if (n instanceof ThematicBreakAstNode) { return `thematicBreak ${JSON.stringify(n.content)}`; }\n if (n instanceof HeadingAstNode) { return `heading(level=${n.level})`; }\n if (n instanceof ListAstNode) { return `list(ordered=${n.ordered})`; }\n if (n instanceof ListItemAstNode) { return n.checked === undefined ? 'listItem' : `listItem(checked=${n.checked})`; }\n if (n instanceof CodeBlockAstNode) { return `codeBlock(language=${JSON.stringify(n.language)})`; }\n if (n instanceof MathBlockAstNode) { return 'mathBlock'; }\n if (n instanceof LinkAstNode) { return `link(url=${JSON.stringify(n.url)})`; }\n if (n instanceof ImageAstNode) { return `image(alt=${JSON.stringify(n.alt)}, url=${JSON.stringify(n.url)})`; }\n return n.kind;\n}\n\nconst _objectInstanceIds = new WeakMap<object, number>();\nlet _nextObjectInstanceId = 0;\n\n/**\n * Globally-stable per-object-instance id, assigned in first-seen order across\n * every visualization (AST, view-data, view-node). A single registry — not one\n * per tree — is the whole point: the same object always renders the same `#N`,\n * so you can correlate instances across the different trees and across edits.\n */\nexport function objectInstanceId(n: object): number {\n let id = _objectInstanceIds.get(n);\n if (id === undefined) { id = _nextObjectInstanceId++; _objectInstanceIds.set(n, id); }\n return id;\n}\n\nexport function visualizeAst(root: AstNode, source: string): AstVisualization {\n let pos = 0;\n function walk(n: AstNode): AstVisualizationNode {\n const start = pos;\n const kids = n.children;\n let children: AstVisualizationNode[] | undefined;\n if (kids.length === 0) {\n pos += n.length;\n } else {\n children = kids.map(walk);\n }\n const label = `${_label(n)} #${objectInstanceId(n)} nid=${n.id}`;\n return { label, range: [start, pos], children };\n }\n return { $fileExtension: 'ast.w', source, root: walk(root) };\n}\n\n/**\n * Adapts the raw micromark token stream into the same `ast.w` visualization\n * payload, as a flat list (no nesting): one child per event, in document order.\n * This is the input the {@link visualizeAst} tree is built from, so showing both\n * side by side makes the parser's tokens → AST step inspectable.\n *\n * Both `enter` and `exit` events are emitted — the open/close structure is the\n * one piece of micromark's information that is NOT derivable from a flat list of\n * ranges (tokens can share a range, and ranges alone don't disambiguate nesting\n * order). Everything else a token carries is here too: its type, its\n * `[start, end)` range, and the source slice that range covers (so the length,\n * which the AST view derives, is visible directly).\n */\nexport function visualizeTokens(source: string): AstVisualization {\n const children: AstVisualizationNode[] = [];\n for (const ev of tokenize(source)) {\n const text = source.substring(ev.startOffset, ev.endOffset);\n children.push({\n label: `${ev.type} ${ev.tokenType} ${JSON.stringify(text)}`,\n range: [ev.startOffset, ev.endOffset],\n });\n }\n const root: AstVisualizationNode = {\n label: `events (${children.length})`,\n range: [0, source.length],\n children,\n };\n return { $fileExtension: 'ast.w', source, root };\n}\n","import { observableValue, derived } from '@vscode/observables';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport type { GutterMarker } from '../core/gutterMarker.js';\nimport { StringValue } from '../core/stringValue.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { Selection } from '../core/selection.js';\nimport { MarkdownParser } from '../parser/parser.js';\nimport { ParagraphAstNode, type BlockAstNode, type DocumentAstNode } from '../parser/ast.js';\n\nexport const NO_ACTIVE_BLOCKS = Symbol('NO_ACTIVE_BLOCKS');\n\n/**\n * A *transient* editing state: the empty paragraph the user conjured by\n * pressing Enter at the end of a paragraph. Markdown has no empty-paragraph\n * node, so this never lives in {@link EditorModel.sourceText} or the parsed\n * {@link EditorModel.document} — it is pure edit intent that the view renders\n * as a synthetic blank line and that the controller either *materializes* (the\n * user types) or *cancels* (the user navigates away / backspaces).\n */\nexport interface PendingParagraph {\n\t/** The paragraph the blank line is rendered directly after. */\n\treadonly anchorBlock: BlockAstNode;\n\t/**\n\t * Source region rewritten when the pending paragraph is materialized — the\n\t * gap between {@link anchorBlock}'s text and whatever follows it.\n\t */\n\treadonly replaceRange: OffsetRange;\n\t/** Whether {@link replaceRange} ends at the end of the document. */\n\treadonly atEof: boolean;\n\t/**\n\t * A throwaway AST node that exists only to give the synthetic view child a\n\t * stable identity across render frames (the view pairs nodes by `ast.id`).\n\t * It is never part of {@link document}.\n\t */\n\treadonly syntheticAst: ParagraphAstNode;\n}\n\nexport class EditorModel {\n\tprivate readonly _parser = new MarkdownParser();\n\n\t/**\n\t * The most recent edit applied to {@link sourceText}, used by\n\t * {@link document} to let the parser link incrementally edited code\n\t * blocks. Only trusted when it exactly bridges the previous and current\n\t * source text (see {@link document}).\n\t */\n\tprivate _pendingEdit: { baseText: string; newText: string; edit: StringEdit } | undefined;\n\n\treadonly sourceText = observableValue<StringValue>(this, new StringValue(''));\n\t/**\n\t * The current selection, or `undefined` when the editor has no caret\n\t * (e.g. an inactive/unfocused rendering).\n\t */\n\treadonly selection = observableValue<Selection | undefined>(this, Selection.collapsed(0));\n\n\t/**\n\t * Whether a Ctrl/Cmd modifier is currently held. Set by the controller from\n\t * live keyboard state; the view reads it to show the link-open affordance\n\t * (underline + pointer cursor) only while a Ctrl/Cmd+click would open a link\n\t * whose block is active.\n\t */\n\treadonly ctrlOrMetaDown = observableValue<boolean>(this, false);\n\n\t/**\n\t * Gutter markers (source-control style change indicators) painted in the\n\t * left gutter. Each entry maps a source {@link OffsetRange} to a change kind\n\t * — see {@link GutterMarker}. Purely decorative: markers never affect the\n\t * parsed {@link document}, selection, or layout. Empty by default.\n\t */\n\treadonly gutterMarkers = observableValue<readonly GutterMarker[]>(this, []);\n\n\t/**\n\t * Forces the rendered active-block set. `undefined` (the default)\n\t * derives the set from the current selection range (see\n\t * {@link activeBlocks}). The sentinel {@link NO_ACTIVE_BLOCKS} forces\n\t * \"no active block\" — useful in fixtures that always want the\n\t * collapsed/inactive rendering.\n\t */\n\treadonly activeBlocksOverride = observableValue<readonly BlockAstNode[] | typeof NO_ACTIVE_BLOCKS | undefined>(this, undefined);\n\n\t/**\n\t * The transient empty-paragraph editing state, or `undefined` when none is\n\t * armed. See {@link PendingParagraph}. This is *not* document data — it is\n\t * cleared by any source edit and lives only between the Enter that armed it\n\t * and the next keystroke.\n\t */\n\treadonly pendingParagraph = observableValue<PendingParagraph | undefined>(this, undefined);\n\n\treadonly cursorOffset = derived(this, reader =>\n\t\treader.readObservable(this.selection)?.active,\n\t);\n\n\t/**\n\t * The parsed document. Threads the previous document into the parser so\n\t * unchanged blocks keep their object identity across reparses (see\n\t * {@link MarkdownParser.parse}). Writing `previous` inside the compute is\n\t * a safe optimization: `derived` only recomputes when `sourceText`\n\t * changes, and the result is structurally identical to a full reparse.\n\t */\n\treadonly document = (() => {\n\t\tlet previous: DocumentAstNode | undefined;\n\t\tlet previousText: string | undefined;\n\t\treturn derived(this, reader => {\n\t\t\tconst text = reader.readObservable(this.sourceText);\n\t\t\tconst pending = this._pendingEdit;\n\t\t\tconst edit = pending && pending.baseText === previousText && pending.newText === text.value\n\t\t\t\t? pending.edit\n\t\t\t\t: undefined;\n\t\t\tconst next = this._parser.parse(text, previous, edit);\n\t\t\tprevious = next;\n\t\t\tpreviousText = text.value;\n\t\t\treturn next;\n\t\t});\n\t})();\n\n\t/**\n\t * Block that contains the cursor (selection's active end). Used by\n\t * cursor navigation to know which block's marker ranges count as\n\t * visible. Unaffected by {@link activeBlocksOverride} because\n\t * navigation is independent of rendering.\n\t */\n\treadonly activeBlock = derived(this, reader => {\n\t\tconst doc = reader.readObservable(this.document);\n\t\tconst cursor = reader.readObservable(this.cursorOffset);\n\t\tif (cursor === undefined) { return undefined; }\n\t\treturn findBlockAtOffset(doc, cursor);\n\t});\n\n\t/**\n\t * All blocks whose source range intersects the current selection.\n\t * The rendering side uses this to decide which blocks render in\n\t * their expanded (markers-visible) form. When the selection is\n\t * collapsed this is a one-element set holding {@link activeBlock}.\n\t */\n\treadonly activeBlocks = derived(this, reader => {\n\t\t// While an empty paragraph is pending, the caret lives on the synthetic\n\t\t// blank line, not in any real block — so no AST block is active (the\n\t\t// anchor paragraph renders in its normal, rendered form).\n\t\tif (reader.readObservable(this.pendingParagraph) !== undefined) {\n\t\t\treturn new Set<BlockAstNode>();\n\t\t}\n\t\tconst override = reader.readObservable(this.activeBlocksOverride);\n\t\tif (override === NO_ACTIVE_BLOCKS) { return new Set<BlockAstNode>(); }\n\t\tif (override !== undefined) { return new Set<BlockAstNode>(override); }\n\t\tconst doc = reader.readObservable(this.document);\n\t\tconst sel = reader.readObservable(this.selection);\n\t\tif (sel === undefined) { return new Set<BlockAstNode>(); }\n\t\treturn new Set<BlockAstNode>(blocksIntersecting(doc, sel.range.start, sel.range.endExclusive));\n\t});\n\n\t/**\n\t * Arm a {@link PendingParagraph} at the given gap, minting a fresh synthetic\n\t * AST node for it, and park the caret at the gap start. No source edit is\n\t * applied — the blank line exists only in the view until it is materialized.\n\t */\n\tarmPendingParagraph(req: { anchorBlock: BlockAstNode; replaceRange: OffsetRange; atEof: boolean }): void {\n\t\tthis.pendingParagraph.set({ ...req, syntheticAst: new ParagraphAstNode([]) }, undefined);\n\t\tthis.selection.set(Selection.collapsed(req.replaceRange.start), undefined);\n\t}\n\n\t/** Discard the pending paragraph (if any) without touching the source. */\n\tcancelPendingParagraph(): void {\n\t\tif (this.pendingParagraph.get() !== undefined) {\n\t\t\tthis.pendingParagraph.set(undefined, undefined);\n\t\t}\n\t}\n\n\t/**\n\t * Turn the pending paragraph into real source: rewrite its gap so the typed\n\t * `text` becomes its own paragraph, separated from its neighbours by blank\n\t * lines, and place the caret after the inserted text.\n\t */\n\tmaterializePendingParagraph(text: string): void {\n\t\tconst pending = this.pendingParagraph.get();\n\t\tif (!pending) { return; }\n\t\tconst inserted = '\\n\\n' + text + (pending.atEof ? '' : '\\n\\n');\n\t\tconst cursor = pending.replaceRange.start + 2 + text.length;\n\t\tconst edit = StringEdit.replace(pending.replaceRange, inserted);\n\t\tthis.pendingParagraph.set(undefined, undefined);\n\t\tconst oldText = this.sourceText.get();\n\t\tconst newText = new StringValue(edit.apply(oldText.value));\n\t\tthis._pendingEdit = { baseText: oldText.value, newText: newText.value, edit };\n\t\tthis.sourceText.set(newText, undefined);\n\t\tthis.selection.set(Selection.collapsed(cursor), undefined);\n\t}\n\n\tapplyEdit(edit: StringEdit): void {\n\t\tthis.cancelPendingParagraph();\n\t\tconst oldText = this.sourceText.get();\n\t\tconst newText = new StringValue(edit.apply(oldText.value));\n\t\tconst sel = this.selection.get() ?? Selection.collapsed(0);\n\t\tconst newActive = edit.mapOffset(sel.active);\n\t\tthis._pendingEdit = { baseText: oldText.value, newText: newText.value, edit };\n\t\tthis.sourceText.set(newText, undefined);\n\t\tthis.selection.set(Selection.collapsed(newActive), undefined);\n\t}\n\n\tapplyEditForSelection(edit: StringEdit): void {\n\t\tconst oldText = this.sourceText.get();\n\t\tconst newText = new StringValue(edit.apply(oldText.value));\n\t\tconst sel = this.selection.get() ?? Selection.collapsed(0);\n\t\tconst newCursor = edit.mapOffset(sel.range.endExclusive);\n\t\tthis._pendingEdit = { baseText: oldText.value, newText: newText.value, edit };\n\t\tthis.sourceText.set(newText, undefined);\n\t\tthis.selection.set(Selection.collapsed(newCursor), undefined);\n\t}\n}\n\nfunction findBlockAtOffset(doc: DocumentAstNode, offset: SourceOffset): BlockAstNode | undefined {\n\tlet pos = 0;\n\tlet lastBlock: BlockAstNode | undefined;\n\tfor (const child of doc.children) {\n\t\tconst end = pos + child.length;\n\t\tif (doc.blocks.includes(child as BlockAstNode)) {\n\t\t\tif (pos <= offset && offset < end) {\n\t\t\t\treturn child as BlockAstNode;\n\t\t\t}\n\t\t\tif (end === offset) {\n\t\t\t\tlastBlock = child as BlockAstNode;\n\t\t\t}\n\t\t}\n\t\tpos = end;\n\t}\n\treturn lastBlock;\n}\n\n/**\n * All blocks whose source range intersects `[start, endExclusive]`. A\n * collapsed range (start === endExclusive) matches the block containing\n * that offset (with the same boundary rule as {@link findBlockAtOffset}).\n */\nfunction blocksIntersecting(doc: DocumentAstNode, start: SourceOffset, endExclusive: SourceOffset): BlockAstNode[] {\n\tif (start === endExclusive) {\n\t\tconst b = findBlockAtOffset(doc, start);\n\t\treturn b ? [b] : [];\n\t}\n\tconst out: BlockAstNode[] = [];\n\tlet pos = 0;\n\tfor (const child of doc.children) {\n\t\tconst end = pos + child.length;\n\t\tif (doc.blocks.includes(child as BlockAstNode) && pos < endExclusive && end > start) {\n\t\t\tout.push(child as BlockAstNode);\n\t\t}\n\t\tpos = end;\n\t}\n\treturn out;\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Point2D, Rect2D } from '../core/geometry.js';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport type { ViewNode } from './content/viewNode.js';\n\n/**\n * Geometry of the rendered document, as a map from source offsets to 2D\n * positions and back.\n *\n * Structure (top to bottom):\n *\n * VisualLineMap = ordered list of VisualLines\n * VisualLine = a horizontal band [rect.top, rect.bottom) split\n * into one or more VisualRuns\n * VisualRun = a contiguous source range painted at a rectangle\n * on the line\n *\n * Invariants:\n * - `lines[i].rect.bottom <= lines[i+1].rect.top + ε`\n * - For any offset `o` covered by some run on line `L`:\n * `xAtOffset(o)` is inside that run's horizontal range\n * `xAtOffset(o)` is inside `L.rect.left..L.rect.right`\n *\n * The \"map\" goes both ways:\n * - SourceOffset → (line, x) via {@link lineIndexOfOffset} + {@link xAtOffset}\n * - Point2D → SourceOffset via {@link offsetAtPoint}\n *\n * Both directions are total but not bijective: many offsets at a line\n * boundary map to the same `x`, and large areas of the document\n * (padding, gaps) map onto the nearest offset on the nearest line.\n *\n * Rendering a caret rect from these primitives is a consumer concern:\n *\n * const i = map.lineIndexOfOffset(o);\n * const caretRect = map.lineRect(i).withZeroWidthAt(map.xAtOffset(o));\n */\nexport class VisualLineMap {\n\tstatic readonly EMPTY = new VisualLineMap([]);\n\n\tstatic measure(blockViews: readonly { readonly absoluteStart: number; readonly viewNode: ViewNode }[]): VisualLineMap {\n\t\treturn _measure(blockViews);\n\t}\n\n\tconstructor(readonly lines: readonly VisualLine[]) { }\n\n\tget lineCount(): number { return this.lines.length; }\n\tget isEmpty(): boolean { return this.lines.length === 0; }\n\n\tlineRect(lineIndex: number): Rect2D {\n\t\treturn this.lines[lineIndex].rect;\n\t}\n\n\t// ---- SourceOffset → ... -------------------------------------------\n\n\t/**\n\t * Line whose runs cover the offset, or the nearest line by source\n\t * distance if no run covers it.\n\t *\n\t * An offset that is only a run's *trailing* boundary (`offset ===\n\t * endExclusive`) — most notably the source offset just past a\n\t * line-breaking `\\n`, which a zero-width run reports as its end on the line\n\t * it terminates — belongs to the START of the NEXT line instead. Preferring\n\t * the line that actually *starts* the offset makes the caret advance past a\n\t * newline to the next line rather than collapsing onto the previous line's\n\t * end (which would render two distinct offsets at the same caret position).\n\t * The first such trailing-boundary line is remembered as a fallback for the\n\t * document's very last offset, where no later line starts it.\n\t */\n\tlineIndexOfOffset(offset: SourceOffset): number {\n\t\tlet endBoundaryLine = -1;\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tconst membership = this.lines[i].offsetMembership(offset);\n\t\t\tif (membership === 'covers') { return i; }\n\t\t\tif (membership === 'end' && endBoundaryLine < 0) { endBoundaryLine = i; }\n\t\t}\n\t\tif (endBoundaryLine >= 0) { return endBoundaryLine; }\n\n\t\tlet bestIdx = 0;\n\t\tlet bestDist = Infinity;\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tconst dist = this.lines[i].sourceDistanceTo(offset);\n\t\t\tif (dist < bestDist) { bestDist = dist; bestIdx = i; }\n\t\t}\n\t\treturn bestIdx;\n\t}\n\n\t/**\n\t * x of the caret position before `offset`, on the line returned by\n\t * {@link lineIndexOfOffset}. Returns `0` when the map is empty.\n\t */\n\txAtOffset(offset: SourceOffset): number {\n\t\tif (this.lines.length === 0) { return 0; }\n\t\treturn this.lines[this.lineIndexOfOffset(offset)].xAtOffset(offset);\n\t}\n\n\t// ---- Point2D → ... -------------------------------------------------\n\n\t/**\n\t * Line whose vertical band contains `y`, clamped to the first/last\n\t * line when `y` is outside the document.\n\t */\n\tlineIndexAtY(y: number): number {\n\t\tif (this.lines.length === 0) { return 0; }\n\t\tfor (let i = 0; i < this.lines.length; i++) {\n\t\t\tif (y < this.lines[i].rect.bottom) { return i; }\n\t\t}\n\t\treturn this.lines.length - 1;\n\t}\n\n\t/**\n\t * Snap a 2D point to the nearest source offset. Uses `y` to pick a\n\t * line, then `x` to pick an offset within it. Up/down navigation\n\t * uses {@link offsetInLineAtX} directly to preserve desired column.\n\t */\n\toffsetAtPoint(point: Point2D): SourceOffset {\n\t\treturn this.offsetInLineAtX(this.lineIndexAtY(point.y), point.x);\n\t}\n\n\t/** Snap `x` to the nearest offset on a specific line. */\n\toffsetInLineAtX(lineIndex: number, x: number): SourceOffset {\n\t\tif (lineIndex < 0 || lineIndex >= this.lines.length) { return 0; }\n\t\treturn this.lines[lineIndex].offsetAtX(x);\n\t}\n}\n\n/**\n * One visual line of rendered text: a horizontal band\n * (`rect.top`..`rect.bottom`) split into one or more {@link VisualRun}s\n * arranged left-to-right.\n */\nexport class VisualLine {\n\tconstructor(\n\t\treadonly rect: Rect2D,\n\t\treadonly runs: readonly VisualRun[],\n\t) { }\n\n\tcontainsOffset(offset: SourceOffset): boolean {\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.containsOffset(offset)) { return true; }\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * How `offset` relates to this line's runs:\n\t * - `'covers'`: a run starts at or strictly contains the offset\n\t * (`start <= offset < endExclusive`) — the caret belongs on this line.\n\t * - `'end'`: the offset is only some run's trailing boundary\n\t * (`offset === endExclusive`) with no run covering it — a line-break\n\t * boundary the caret should leave for the next line.\n\t * - `'none'`: no run touches the offset.\n\t */\n\toffsetMembership(offset: SourceOffset): 'covers' | 'end' | 'none' {\n\t\tlet end = false;\n\t\tfor (const run of this.runs) {\n\t\t\tif (offset >= run.sourceStart && offset < run.sourceEndExclusive) { return 'covers'; }\n\t\t\tif (offset === run.sourceEndExclusive) { end = true; }\n\t\t}\n\t\treturn end ? 'end' : 'none';\n\t}\n\n\t/**\n\t * Min `|offset - r|` over offsets `r` in any of this line's runs. Used\n\t * to pick the nearest line when no run actually covers the offset.\n\t */\n\tsourceDistanceTo(offset: SourceOffset): number {\n\t\tlet best = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tconst d = run.sourceDistanceTo(offset);\n\t\t\tif (d < best) { best = d; }\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * x of the caret position before `offset` on this line. When `offset`\n\t * is past all runs (trailing whitespace / blank line), returns the\n\t * right edge of the last run; when before all runs, returns the left\n\t * edge of the first run.\n\t */\n\txAtOffset(offset: SourceOffset): number {\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.containsOffset(offset)) { return run.xAtOffset(offset); }\n\t\t}\n\t\t// `runs` is non-empty by construction (`_measure.flush` and any\n\t\t// hand-built line in tests).\n\t\tconst first = this.runs[0];\n\t\tif (offset <= first.sourceStart) { return first.rect.left; }\n\t\treturn this.runs[this.runs.length - 1].rect.right;\n\t}\n\n\t/**\n\t * Snap `x` to the nearest offset on this line. If `x` falls inside a\n\t * run, the offset is interpolated by character fraction; otherwise it\n\t * snaps to the closer edge of the nearest run.\n\t */\n\toffsetAtX(x: number): SourceOffset {\n\t\tif (this.runs.length === 0) { return 0; }\n\n\t\tlet bestRun = this.runs[0];\n\t\tlet bestDist = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.rect.containsX(x) || x === run.rect.right) {\n\t\t\t\treturn run.offsetAtX(x);\n\t\t\t}\n\t\t\tconst dist = Math.min(Math.abs(x - run.rect.left), Math.abs(x - run.rect.right));\n\t\t\tif (dist < bestDist) { bestDist = dist; bestRun = run; }\n\t\t}\n\t\treturn x <= bestRun.rect.left\n\t\t\t? bestRun.sourceRange.start\n\t\t\t: bestRun.sourceRange.endExclusive;\n\t}\n}\n\n/**\n * The DOM source of a {@link VisualRun}. When set, `xAtOffset` and\n * `offsetAtX` measure exact glyph positions via `Range.getBoundingClientRect`\n * instead of linear interpolation across the run's rect. This matters for\n * proportional fonts where character widths differ a lot (e.g. `m` vs `i`)\n * and a caret placed by interpolation lands several pixels inside the\n * wrong character.\n *\n * Hand-built runs (tests) omit this; their `xAtOffset` falls back to\n * linear interpolation.\n */\nexport interface VisualRunSource {\n\treadonly textNode: Text;\n\t/** Offset within `textNode.data` corresponding to `sourceRange.start`. */\n\treadonly textNodeStart: number;\n}\n\n/**\n * One contiguous run of text painted on a single visual line.\n *\n * When constructed with a {@link VisualRunSource}, `xAtOffset` returns the\n * pixel-exact x of the caret before character `offset` by measuring the\n * prefix `[textNodeStart, textNodeStart + (offset - sourceStart))` with a\n * DOM `Range`. Without a source it falls back to linear interpolation\n * across `rect.width`.\n */\nexport class VisualRun {\n\tconstructor(\n\t\treadonly sourceRange: OffsetRange,\n\t\treadonly rect: Rect2D,\n\t\treadonly source?: VisualRunSource,\n\t) { }\n\n\tget sourceStart(): SourceOffset { return this.sourceRange.start; }\n\tget sourceEndExclusive(): SourceOffset { return this.sourceRange.endExclusive; }\n\tget sourceLength(): number { return this.sourceRange.length; }\n\n\tcontainsOffset(offset: SourceOffset): boolean {\n\t\treturn offset >= this.sourceStart && offset <= this.sourceEndExclusive;\n\t}\n\n\tsourceDistanceTo(offset: SourceOffset): number {\n\t\tif (offset < this.sourceStart) { return this.sourceStart - offset; }\n\t\tif (offset > this.sourceEndExclusive) { return offset - this.sourceEndExclusive; }\n\t\treturn 0;\n\t}\n\n\txAtOffset(offset: SourceOffset): number {\n\t\tif (this.sourceLength === 0) { return this.rect.left; }\n\t\tif (this.source) {\n\t\t\treturn _xAtTextOffset(this.source.textNode, this.source.textNodeStart + (offset - this.sourceStart), this.rect.left);\n\t\t}\n\t\tconst fraction = (offset - this.sourceStart) / this.sourceLength;\n\t\treturn this.rect.left + fraction * this.rect.width;\n\t}\n\n\toffsetAtX(x: number): SourceOffset {\n\t\tif (this.rect.width <= 0) { return this.sourceStart; }\n\t\tif (this.source) {\n\t\t\tconst localOffset = _offsetAtX(this.source.textNode, this.source.textNodeStart, this.source.textNodeStart + this.sourceLength, x);\n\t\t\treturn this.sourceStart + (localOffset - this.source.textNodeStart);\n\t\t}\n\t\tconst fraction = (x - this.rect.left) / this.rect.width;\n\t\treturn this.sourceStart + Math.round(fraction * this.sourceLength);\n\t}\n}\n\n/**\n * x position of the caret before character `textOffset` in `textNode`.\n * Uses the right edge of the preceding character (or the left edge of\n * the run if `textOffset` is at the run's start).\n */\nfunction _xAtTextOffset(textNode: Text, textOffset: number, fallbackLeft: number): number {\n\tif (textOffset <= 0) { return fallbackLeft; }\n\tconst range = document.createRange();\n\trange.setStart(textNode, textOffset - 1);\n\trange.setEnd(textNode, textOffset);\n\tconst rect = range.getBoundingClientRect();\n\tif (rect.width === 0 && rect.height === 0) { return fallbackLeft; }\n\treturn rect.right;\n}\n\n/**\n * Snap `x` to a character boundary in `textNode[start..end]` via binary\n * search on per-character rects. Returns an offset in `[start, end]`.\n */\nfunction _offsetAtX(textNode: Text, start: number, end: number, x: number): number {\n\tconst range = document.createRange();\n\tlet bestOffset = start;\n\tlet bestDist = Infinity;\n\tfor (let i = start; i < end; i++) {\n\t\trange.setStart(textNode, i);\n\t\trange.setEnd(textNode, i + 1);\n\t\tconst rect = range.getBoundingClientRect();\n\t\tif (rect.width === 0 && rect.height === 0) { continue; }\n\t\tconst mid = (rect.left + rect.right) / 2;\n\t\t// Pick the edge of this character closest to x.\n\t\tconst dLeft = Math.abs(x - rect.left);\n\t\tconst dRight = Math.abs(x - rect.right);\n\t\tif (dLeft < bestDist) { bestDist = dLeft; bestOffset = i; }\n\t\tif (dRight < bestDist) { bestDist = dRight; bestOffset = i + 1; }\n\t\t// Early-exit: if x is inside this char, pick the closer edge.\n\t\tif (x >= rect.left && x <= rect.right) {\n\t\t\treturn x < mid ? i : i + 1;\n\t\t}\n\t}\n\treturn bestOffset;\n}\n\n// ---------- measurement ------------------------------------------------\n\n/**\n * Walk a DOM Text leaf and return rects in CSS-pixel client coordinates,\n * expanded vertically to the parent element's line-height so caret height\n * matches the visual line box (with leading), not just the glyph height.\n */\nfunction _measure(\n\tblockViews: readonly { readonly absoluteStart: number; readonly viewNode: ViewNode }[],\n): VisualLineMap {\n\tconst rawRuns: VisualRun[] = [];\n\n\tfor (const view of blockViews) {\n\t\tconst runsBefore = rawRuns.length;\n\t\tview.viewNode.forEachTextLeaf(view.absoluteStart, (leaf, leafOffset) => {\n\t\t\tconst textNode = leaf.dom as Text;\n\t\t\tif (textNode.length === 0) { return; }\n\n\t\t\tconst range = document.createRange();\n\t\t\trange.selectNodeContents(textNode);\n\t\t\tconst rects = range.getClientRects();\n\t\t\tif (rects.length === 0) { return; }\n\n\t\t\tconst lineBoxHeight = _lineBoxHeight(textNode);\n\n\t\t\tif (rects.length === 1) {\n\t\t\t\trawRuns.push(new VisualRun(\n\t\t\t\t\tOffsetRange.fromTo(leafOffset, leafOffset + textNode.length),\n\t\t\t\t\t_expandToLineBox(rects[0], lineBoxHeight),\n\t\t\t\t\t{ textNode, textNodeStart: 0 },\n\t\t\t\t));\n\t\t\t} else {\n\t\t\t\tconst breakOffsets = _findLineBreakOffsets(textNode, rects);\n\t\t\t\tfor (let i = 0; i < rects.length; i++) {\n\t\t\t\t\tconst start = i === 0 ? 0 : breakOffsets[i - 1];\n\t\t\t\t\tconst end = i < breakOffsets.length ? breakOffsets[i] : textNode.length;\n\t\t\t\t\trawRuns.push(new VisualRun(\n\t\t\t\t\t\tOffsetRange.fromTo(leafOffset + start, leafOffset + end),\n\t\t\t\t\t\t_expandToLineBox(rects[i], lineBoxHeight),\n\t\t\t\t\t\t{ textNode, textNodeStart: start },\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (rawRuns.length === runsBefore) {\n\t\t\t_appendElementBlockRun(rawRuns, view.viewNode, view.absoluteStart);\n\t\t}\n\t}\n\n\trawRuns.sort((a, b) => a.rect.y - b.rect.y || a.rect.x - b.rect.x);\n\n\tconst lines: VisualLine[] = [];\n\tlet currentRuns: VisualRun[] = [];\n\tlet currentY = -Infinity;\n\tlet currentHeight = 0;\n\tlet currentLeft = Infinity;\n\tlet currentRight = -Infinity;\n\n\tconst flush = (): void => {\n\t\tif (currentRuns.length === 0) { return; }\n\t\tlines.push(new VisualLine(\n\t\t\tRect2D.fromPointPoint(currentLeft, currentY, currentRight, currentY + currentHeight),\n\t\t\tcurrentRuns,\n\t\t));\n\t};\n\n\tfor (const run of rawRuns) {\n\t\tconst r = run.rect;\n\t\t// A run joins the current line only if it overlaps the current line band\n\t\t// by more than half the (smaller) height. Comparing against the current\n\t\t// bottom alone fails when glyph rects are taller than the line advance\n\t\t// (e.g. wrapped headings whose 43px rects advance only 40px), which would\n\t\t// otherwise collapse every wrapped line into one.\n\t\tconst overlap = Math.min(currentY + currentHeight, r.y + r.height) - Math.max(currentY, r.y);\n\t\tconst sameLine = currentRuns.length > 0 && overlap > Math.min(currentHeight, r.height) / 2;\n\t\tif (!sameLine) {\n\t\t\tflush();\n\t\t\tcurrentRuns = [run];\n\t\t\tcurrentY = r.y;\n\t\t\tcurrentHeight = r.height;\n\t\t\tcurrentLeft = r.left;\n\t\t\tcurrentRight = r.right;\n\t\t} else {\n\t\t\tcurrentRuns.push(run);\n\t\t\tcurrentHeight = Math.max(currentHeight, r.y + r.height - currentY);\n\t\t\tcurrentLeft = Math.min(currentLeft, r.left);\n\t\t\tcurrentRight = Math.max(currentRight, r.right);\n\t\t}\n\t}\n\tflush();\n\n\treturn new VisualLineMap(lines);\n}\n\nfunction _findLineBreakOffsets(textNode: Text, rects: DOMRectList): number[] {\n\tconst breaks: number[] = [];\n\tconst range = document.createRange();\n\n\tfor (let r = 0; r < rects.length - 1; r++) {\n\t\tconst nextY = rects[r + 1].y;\n\t\tlet lo = r === 0 ? 0 : breaks[r - 1];\n\t\tlet hi = textNode.length;\n\n\t\twhile (lo < hi) {\n\t\t\tconst mid = (lo + hi) >>> 1;\n\t\t\trange.setStart(textNode, mid);\n\t\t\trange.setEnd(textNode, Math.min(mid + 1, textNode.length));\n\t\t\tconst charRect = range.getBoundingClientRect();\n\t\t\tif (charRect.y < nextY - 1) {\n\t\t\t\tlo = mid + 1;\n\t\t\t} else {\n\t\t\t\thi = mid;\n\t\t\t}\n\t\t}\n\t\tbreaks.push(lo);\n\t}\n\n\treturn breaks;\n}\n\nfunction _lineBoxHeight(textNode: Text): number {\n\tconst parent = textNode.parentElement;\n\tif (!parent) { return 0; }\n\tconst cs = getComputedStyle(parent);\n\tlet lineHeight = parseFloat(cs.lineHeight);\n\tif (!isFinite(lineHeight)) {\n\t\t// `normal` — approximate as 1.2 * font-size, matching browser defaults.\n\t\tlineHeight = parseFloat(cs.fontSize) * 1.2;\n\t}\n\treturn lineHeight;\n}\n\nfunction _expandToLineBox(rect: DOMRect, lineBoxHeight: number): Rect2D {\n\tif (lineBoxHeight <= rect.height) {\n\t\treturn Rect2D.fromPointSize(rect.x, rect.y, rect.width, rect.height);\n\t}\n\tconst leading = (lineBoxHeight - rect.height) / 2;\n\treturn Rect2D.fromPointSize(rect.x, rect.y - leading, rect.width, lineBoxHeight);\n}\n\n/**\n * A block that renders as a non-text element (an inactive `<hr>` thematic\n * break, a KaTeX math block, a standalone image) yields no text leaf, so it\n * would contribute no {@link VisualLine}. Without one, the next block's lines\n * shift up and stepping the caret off such a block onto the following block\n * does not advance its line index — two distinct source offsets render at the\n * same caret position. Give the block one run spanning its whole source range\n * at the element's box so it occupies a line like any text block, keeping line\n * indices stable across its active (text) ↔ inactive (element) renderings. The\n * run carries no {@link VisualRunSource}, so x within it is interpolated — fine,\n * since the caret only ever lands inside the block in its active (text) form.\n */\nfunction _appendElementBlockRun(rawRuns: VisualRun[], viewNode: ViewNode, absoluteStart: number): void {\n\tconst dom = viewNode.dom;\n\tif (dom.nodeType !== 1 /* ELEMENT_NODE */) { return; }\n\tconst rect = (dom as Element).getBoundingClientRect();\n\tif (rect.width === 0 && rect.height === 0) { return; }\n\trawRuns.push(new VisualRun(\n\t\tOffsetRange.fromTo(absoluteStart, absoluteStart + viewNode.sourceLength),\n\t\tRect2D.fromPointSize(rect.x, rect.y, rect.width, rect.height),\n\t));\n}\n","import { derived, observableValue } from '@vscode/observables';\nimport type { BlockAstNode } from '../parser/ast.js';\nimport type { ViewNode } from '../view/content/viewNode.js';\nimport { VisualLineMap } from '../view/visualLineMap.js';\n\n/**\n * One block's place in the rendered document.\n *\n * `height` is in CSS pixels. It is either a real DOM measurement\n * (`isMeasured: true`) or an estimate produced when the block is not\n * currently mounted (`isMeasured: false`). Estimates exist so virtual\n * rendering can size the scroll container without mounting every block.\n *\n * `visualLineMap` and `viewNode` are set only when the block is mounted\n * and measured. Cursor positioning, selection painting and up/down\n * navigation read through `visualLineMap`; the debug view walks\n * `viewNode` to enumerate text leaves for per-character introspection.\n * Unmeasured blocks have neither.\n */\nexport interface BlockMeasurement {\n readonly block: BlockAstNode;\n readonly absoluteStart: number;\n readonly height: number;\n readonly isMeasured: boolean;\n readonly visualLineMap: VisualLineMap | undefined;\n readonly viewNode: ViewNode | undefined;\n}\n\n/**\n * The set of measurements/estimates the view has produced for the current\n * document. This is the \"view → derived facts about layout\" channel: the\n * view writes here as a side effect of rendering and measuring; the\n * controller (and selection/cursor rendering) reads from here.\n *\n * Keeping these facts in their own observable model — instead of as ad-hoc\n * fields on the view — preserves the invariant\n *\n * view(model + Δ) = view(model) + Δ\n *\n * i.e. the view becomes a pure function of (EditorModel, MeasuredLayoutModel).\n * Everything else that depends on layout (controller, commands) goes\n * through this model and never touches view fields directly.\n */\nexport class MeasuredLayoutModel {\n readonly measurements = observableValue<readonly BlockMeasurement[]>(this, []);\n\n /**\n * Concatenated visual line map across all mounted blocks. Lines are\n * left in DOM (client-coordinate) y order — each per-block map already\n * uses absolute client coordinates from `getClientRects()`, so the\n * concatenation is well-formed without re-sorting.\n */\n readonly visualLineMap = derived(this, reader => {\n const ms = reader.readObservable(this.measurements);\n const lines = ms.flatMap(m => m.visualLineMap?.lines ?? []);\n return new VisualLineMap(lines);\n });\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { MarkerAstNode, type BlockAstNode, type DocumentAstNode, type ListAstNode, type AstNode } from '../parser/ast.js';\n\n/**\n * Move the cursor one position left or right, skipping over hidden marker\n * ranges in inactive blocks (and inactive items of an active list).\n */\nexport function nextCursorPosition(\n doc: DocumentAstNode,\n activeBlock: BlockAstNode | undefined,\n cursor: number,\n direction: 'left' | 'right',\n): number {\n let target = direction === 'right' ? cursor + 1 : cursor - 1;\n\n let blockStart = 0;\n for (const child of doc.children) {\n const isBlock = doc.blocks.includes(child as BlockAstNode);\n if (isBlock) {\n const block = child as BlockAstNode;\n const ranges = hiddenRangesFor(block, block === activeBlock, cursor - blockStart);\n target = applySkip(target, blockStart, ranges, direction);\n }\n blockStart += child.length;\n }\n\n if (direction === 'right') { return Math.min(target, doc.length); }\n return Math.max(target, 0);\n}\n\nfunction hiddenRangesFor(block: BlockAstNode, isActive: boolean, relCursor: number): readonly OffsetRange[] {\n if (!isActive) { return collectMarkerRanges(block); }\n if (block.kind === 'list') {\n const activeItemIndex = findActiveListItemIndex(block, relCursor);\n return collectListHiddenRanges(block, activeItemIndex);\n }\n return [];\n}\n\nfunction applySkip(target: number, blockStart: number, ranges: readonly OffsetRange[], direction: 'left' | 'right'): number {\n if (direction === 'right') {\n for (const range of ranges) {\n const rel = target - blockStart;\n if (range.contains(rel) || range.start === rel) {\n target = blockStart + range.endExclusive;\n }\n }\n } else {\n for (let i = ranges.length - 1; i >= 0; i--) {\n const range = ranges[i];\n const rel = target - blockStart;\n if (range.contains(rel) || range.endExclusive === rel) {\n target = blockStart + range.start;\n }\n }\n }\n return target;\n}\n\nexport function findActiveListItemIndex(list: ListAstNode, cursorOffset: number): number | undefined {\n let pos = 0;\n let boundaryFallback: number | undefined;\n for (let i = 0; i < list.children.length; i++) {\n const child = list.children[i];\n const end = pos + child.length;\n const itemIdx = list.items.indexOf(child as never);\n if (itemIdx >= 0) {\n // Prefer the item that actually contains the offset. An offset that\n // sits exactly on the boundary between two items belongs to the item\n // that *starts* there, so the preceding item (which merely ends\n // there) is only used as a fallback for the very end of the list.\n if (pos <= cursorOffset && cursorOffset < end) {\n return itemIdx;\n }\n if (end === cursorOffset) {\n boundaryFallback = itemIdx;\n }\n }\n pos = end;\n }\n return boundaryFallback;\n}\n\nfunction collectListHiddenRanges(list: ListAstNode, activeItemIndex: number | undefined): OffsetRange[] {\n const ranges: OffsetRange[] = [];\n let listOffset = 0;\n for (const listChild of list.children) {\n const itemIdx = list.items.indexOf(listChild as never);\n if (itemIdx >= 0 && itemIdx !== activeItemIndex) {\n const item = list.items[itemIdx];\n walkCollectMarkerRanges(item, listOffset, ranges);\n }\n listOffset += listChild.length;\n }\n ranges.sort((a, b) => a.start - b.start);\n return ranges;\n}\n\nfunction collectMarkerRanges(block: BlockAstNode): OffsetRange[] {\n const ranges: OffsetRange[] = [];\n walkCollectMarkerRanges(block, 0, ranges);\n ranges.sort((a, b) => a.start - b.start);\n return ranges;\n}\n\nfunction walkCollectMarkerRanges(node: AstNode, offset: number, ranges: OffsetRange[]): void {\n if (node.children.length === 0) {\n if (node instanceof MarkerAstNode) {\n ranges.push(OffsetRange.ofStartAndLength(offset, node.length));\n }\n return;\n }\n\n switch (node.kind) {\n case 'codeBlock':\n case 'mathBlock': {\n let childOffset = offset;\n for (const child of node.children) {\n if (child instanceof MarkerAstNode && (child.markerKind === 'openFence' || child.markerKind === 'closeFence')) {\n ranges.push(OffsetRange.ofStartAndLength(childOffset, child.length));\n }\n childOffset += child.length;\n }\n return;\n }\n case 'inlineCode':\n case 'inlineMath': {\n let childOffset = offset;\n for (const child of node.children) {\n if (child instanceof MarkerAstNode && (child.markerKind === 'openMarker' || child.markerKind === 'closeMarker')) {\n ranges.push(OffsetRange.ofStartAndLength(childOffset, child.length));\n }\n childOffset += child.length;\n }\n return;\n }\n case 'thematicBreak':\n return;\n case 'image': {\n ranges.push(OffsetRange.ofStartAndLength(offset, node.length));\n return;\n }\n }\n\n let childOffset = offset;\n for (const child of node.children) {\n walkCollectMarkerRanges(child, childOffset, ranges);\n childOffset += child.length;\n }\n}\n","import { findWordBoundaryLeft, findWordBoundaryRight } from '../core/wordUtils.js';\nimport type { CursorCommand, VisualCursorCommand } from './types.js';\n\nexport const cursorRight: CursorCommand = (ctx) => {\n\tif (!ctx.selection.isCollapsed) {\n\t\treturn ctx.selection.range.endExclusive;\n\t}\n\treturn Math.min(ctx.selection.active + 1, ctx.text.length);\n};\n\nexport const cursorLeft: CursorCommand = (ctx) => {\n\tif (!ctx.selection.isCollapsed) {\n\t\treturn ctx.selection.range.start;\n\t}\n\treturn Math.max(ctx.selection.active - 1, 0);\n};\n\nexport const cursorMoveRight: CursorCommand = (ctx) =>\n\tMath.min(ctx.selection.active + 1, ctx.text.length);\n\nexport const cursorMoveLeft: CursorCommand = (ctx) =>\n\tMath.max(ctx.selection.active - 1, 0);\n\nexport const cursorWordRight: CursorCommand = (ctx) =>\n\tfindWordBoundaryRight(ctx.text, ctx.selection.active);\n\nexport const cursorWordLeft: CursorCommand = (ctx) =>\n\tfindWordBoundaryLeft(ctx.text, ctx.selection.active);\n\nexport const cursorLineStart: CursorCommand = (ctx) =>\n\tctx.text.lastIndexOf('\\n', ctx.selection.active - 1) + 1;\n\nexport const cursorLineEnd: CursorCommand = (ctx) => {\n\tconst idx = ctx.text.indexOf('\\n', ctx.selection.active);\n\treturn idx === -1 ? ctx.text.length : idx;\n};\n\nexport const cursorDocumentStart: CursorCommand = () => 0;\n\nexport const cursorDocumentEnd: CursorCommand = (ctx) => ctx.text.length;\n\nexport const cursorDown: VisualCursorCommand = (ctx) => {\n\tconst lineIdx = ctx.lineMap.lineIndexOfOffset(ctx.selection.active);\n\tconst x = ctx.desiredColumn ?? ctx.lineMap.xAtOffset(ctx.selection.active);\n\tif (lineIdx >= ctx.lineMap.lineCount - 1) {\n\t\treturn { offset: ctx.selection.active, desiredColumn: x };\n\t}\n\treturn { offset: ctx.lineMap.offsetInLineAtX(lineIdx + 1, x), desiredColumn: x };\n};\n\nexport const cursorUp: VisualCursorCommand = (ctx) => {\n\tconst lineIdx = ctx.lineMap.lineIndexOfOffset(ctx.selection.active);\n\tconst x = ctx.desiredColumn ?? ctx.lineMap.xAtOffset(ctx.selection.active);\n\tif (lineIdx <= 0) {\n\t\treturn { offset: ctx.selection.active, desiredColumn: x };\n\t}\n\treturn { offset: ctx.lineMap.offsetInLineAtX(lineIdx - 1, x), desiredColumn: x };\n};\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Selection } from '../core/selection.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { findWordBoundaryLeft, findWordBoundaryRight } from '../core/wordUtils.js';\nimport { findActiveListItemIndex, nextCursorPosition } from '../model/cursorNavigation.js';\nimport { findNodeOffsetById, GlueAstNode, TextAstNode, type AstNode, type BlockAstNode, type DocumentAstNode, type ListAstNode, type ListItemAstNode } from '../parser/ast.js';\nimport type { CursorCommandContext, EditCommand } from './types.js';\n\nexport const deleteLeft: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active === 0) { return undefined; }\n\tconst deleteRange = new OffsetRange(nextCursorPosition(ctx.document, ctx.activeBlock, sel.active, 'left'), sel.active);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(deleteRange.start),\n\t};\n};\n\nexport const deleteRight: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active >= ctx.text.length) { return undefined; }\n\tconst deleteRange = new OffsetRange(sel.active, nextCursorPosition(ctx.document, ctx.activeBlock, sel.active, 'right'));\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(deleteRange.start),\n\t};\n};\n\nexport const deleteWordLeft: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active === 0) { return undefined; }\n\tconst boundary = findWordBoundaryLeft(ctx.text, sel.active);\n\tconst deleteRange = new OffsetRange(boundary, sel.active);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(boundary),\n\t};\n};\n\nexport const deleteWordRight: EditCommand = (ctx) => {\n\tconst sel = ctx.selection;\n\tif (!sel.isCollapsed) {\n\t\treturn {\n\t\t\tedit: StringEdit.delete(sel.range),\n\t\t\tselection: Selection.collapsed(sel.range.start),\n\t\t};\n\t}\n\tif (sel.active >= ctx.text.length) { return undefined; }\n\tconst boundary = findWordBoundaryRight(ctx.text, sel.active);\n\tconst deleteRange = new OffsetRange(sel.active, boundary);\n\treturn {\n\t\tedit: StringEdit.delete(deleteRange),\n\t\tselection: Selection.collapsed(sel.active),\n\t};\n};\n\nexport function insertText(text: string): EditCommand {\n\treturn (ctx) => {\n\t\tconst edit = StringEdit.replace(ctx.selection.range, text);\n\t\tconst newOffset = ctx.selection.range.start + text.length;\n\t\treturn {\n\t\t\tedit,\n\t\t\tselection: Selection.collapsed(newOffset),\n\t\t};\n\t};\n}\n\nexport const insertParagraph: EditCommand = (ctx) => {\n\tconst edit = StringEdit.replace(ctx.selection.range, '\\n\\n');\n\tconst newOffset = ctx.selection.range.start + 2;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n\nexport const insertLineBreak: EditCommand = (ctx) => {\n\tconst edit = StringEdit.replace(ctx.selection.range, '\\n');\n\tconst newOffset = ctx.selection.range.start + 1;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n\n/**\n * A Markdown hard line break: a `\\n` whose preceding line ends with two spaces.\n * Any spaces already trailing the insertion point count toward the two, so the\n * line never accumulates more than the two needed to form the break.\n */\nexport const insertHardLineBreak: EditCommand = (ctx) => {\n\tconst start = ctx.selection.range.start;\n\tlet existingSpaces = 0;\n\twhile (existingSpaces < 2 && ctx.text[start - 1 - existingSpaces] === ' ') { existingSpaces++; }\n\tconst padding = ' '.repeat(2 - existingSpaces);\n\tconst inserted = padding + '\\n';\n\tconst edit = StringEdit.replace(ctx.selection.range, inserted);\n\tconst newOffset = start + inserted.length;\n\treturn {\n\t\tedit,\n\t\tselection: Selection.collapsed(newOffset),\n\t};\n};\n\n/**\n * The outcome of {@link insertSmartEnter}: either a concrete source edit (the\n * ordinary cases), or a request to arm a transient empty paragraph (Enter at\n * the very end of a paragraph), which the controller turns into\n * {@link EditorModel.armPendingParagraph} rather than a source edit. Modelling\n * the empty paragraph as state instead of source keeps the document valid\n * Markdown — which has no empty-paragraph node — until the user actually types.\n */\nexport type SmartEnterResult =\n\t| { readonly kind: 'edit'; readonly edit: StringEdit; readonly selection: Selection }\n\t| { readonly kind: 'pending'; readonly anchorBlock: BlockAstNode; readonly replaceRange: OffsetRange; readonly atEof: boolean };\n\n/**\n * Context-aware Enter. The behaviour is chosen from the active block:\n * - paragraph / heading / thematic break — the \"rich text\" thing: at the\n * block's end arm a transient empty paragraph (see {@link SmartEnterResult});\n * elsewhere split into two paragraphs (`\\n\\n`).\n * - code block — insert a newline that preserves the current line's indentation,\n * staying inside the fence.\n * - block quote — continue the quote (`\\n> `); an empty quote line exits it.\n * - list — continue the list with the next marker (incrementing ordered\n * numbers, re-emitting task checkboxes); an empty item exits the list.\n * A non-collapsed selection, or any other block, falls back to a plain soft line\n * break, preserving today's behaviour.\n */\nexport const insertSmartEnter = (ctx: CursorCommandContext): SmartEnterResult => {\n\tconst sel = ctx.selection;\n\tconst block = ctx.activeBlock;\n\tif (!sel.isCollapsed || !block) {\n\t\treturn _lineBreak(ctx);\n\t}\n\tswitch (block.kind) {\n\t\tcase 'paragraph':\n\t\tcase 'heading':\n\t\tcase 'thematicBreak':\n\t\t\treturn _paragraphLikeEnter(ctx, block);\n\t\tcase 'codeBlock':\n\t\t\treturn _codeBlockEnter(ctx);\n\t\tcase 'blockQuote':\n\t\t\treturn _blockQuoteEnter(ctx);\n\t\tcase 'list':\n\t\t\treturn _listEnter(ctx, block);\n\t\tdefault:\n\t\t\treturn _lineBreak(ctx);\n\t}\n};\n\n/** Paragraph-like Enter: pending empty paragraph at the end, split otherwise. */\nfunction _paragraphLikeEnter(ctx: CursorCommandContext, block: BlockAstNode): SmartEnterResult {\n\tconst sel = ctx.selection;\n\tconst start = _blockAbsoluteStart(ctx.document, block);\n\tif (start === undefined) { return _lineBreak(ctx); }\n\n\tconst textEnd = start + block.length - _trailingGlueLength(block);\n\tif (sel.active < textEnd) {\n\t\t// Mid-block: split into two paragraphs.\n\t\treturn {\n\t\t\tkind: 'edit',\n\t\t\tedit: StringEdit.replace(sel.range, '\\n\\n'),\n\t\t\tselection: Selection.collapsed(sel.range.start + 2),\n\t\t};\n\t}\n\n\tconst gapEnd = start + block.length;\n\treturn {\n\t\tkind: 'pending',\n\t\tanchorBlock: block,\n\t\treplaceRange: new OffsetRange(textEnd, gapEnd),\n\t\tatEof: gapEnd >= ctx.text.length,\n\t};\n}\n\n/** Code-block Enter: newline that copies the current line's leading whitespace. */\nfunction _codeBlockEnter(ctx: CursorCommandContext): SmartEnterResult {\n\tconst sel = ctx.selection;\n\tconst lineStart = ctx.text.lastIndexOf('\\n', sel.active - 1) + 1;\n\tlet i = lineStart;\n\twhile (i < sel.active && (ctx.text[i] === ' ' || ctx.text[i] === '\\t')) { i++; }\n\tconst inserted = '\\n' + ctx.text.slice(lineStart, i);\n\treturn _insertAt(sel, inserted);\n}\n\n/** Block-quote Enter: continue with the line's `> ` prefix; empty line exits. */\nfunction _blockQuoteEnter(ctx: CursorCommandContext): SmartEnterResult {\n\tconst sel = ctx.selection;\n\tconst lineStart = ctx.text.lastIndexOf('\\n', sel.active - 1) + 1;\n\tconst lineEnd = _lineEnd(ctx.text, sel.active);\n\tconst line = ctx.text.slice(lineStart, lineEnd);\n\tconst match = /^(\\s*(?:>\\s*)+)/.exec(line);\n\tconst prefix = match ? match[1] : '> ';\n\tconst body = line.slice(prefix.length);\n\tif (body.trim() === '') {\n\t\treturn _exitToParagraph(ctx, lineStart, lineEnd);\n\t}\n\t// Continue: re-emit the quote markers with a single trailing space.\n\tconst inserted = '\\n' + prefix.replace(/\\s*$/, ' ');\n\treturn _insertAt(sel, inserted);\n}\n\n/** List Enter: continue with the next marker; an empty item exits the list. */\nfunction _listEnter(ctx: CursorCommandContext, list: ListAstNode): SmartEnterResult {\n\tconst sel = ctx.selection;\n\tconst listStart = _blockAbsoluteStart(ctx.document, list);\n\tif (listStart === undefined) { return _lineBreak(ctx); }\n\tconst index = findActiveListItemIndex(list, sel.active - listStart);\n\tif (index === undefined) { return _lineBreak(ctx); }\n\tconst item = list.items[index];\n\tconst itemStart = findNodeOffsetById(ctx.document, item);\n\tif (itemStart === undefined) { return _lineBreak(ctx); }\n\n\tif (!_hasText(item)) {\n\t\t// Empty item: drop the marker and exit the list into a paragraph.\n\t\treturn _exitToParagraph(ctx, itemStart, itemStart + item.length);\n\t}\n\tconst inserted = '\\n' + _continuationMarker(list, item);\n\treturn _insertAt(sel, inserted);\n}\n\n/**\n * Replace the line spanning `[lineStart, lineEnd)` (a marker-only quote line or\n * list item) and its preceding newline with a paragraph break, so the caret\n * leaves the construct and lands on a fresh blank line.\n */\nfunction _exitToParagraph(ctx: CursorCommandContext, lineStart: number, lineEnd: number): SmartEnterResult {\n\tconst prevNewline = lineStart > 0 ? ctx.text.lastIndexOf('\\n', lineStart - 1) : -1;\n\tif (prevNewline >= 0) {\n\t\treturn {\n\t\t\tkind: 'edit',\n\t\t\tedit: StringEdit.replace(new OffsetRange(prevNewline, lineEnd), '\\n\\n'),\n\t\t\tselection: Selection.collapsed(prevNewline + 2),\n\t\t};\n\t}\n\t// No preceding line: the construct is the whole document; just drop it.\n\treturn {\n\t\tkind: 'edit',\n\t\tedit: StringEdit.replace(new OffsetRange(lineStart, lineEnd), ''),\n\t\tselection: Selection.collapsed(lineStart),\n\t};\n}\n\n/** The marker that continues `item` on the next line of `list`. */\nfunction _continuationMarker(list: ListAstNode, item: ListItemAstNode): string {\n\tconst marker = item.marker.content.trim();\n\tconst bullet = marker.charAt(0) || '-';\n\tif (item.checked !== undefined) {\n\t\treturn `${bullet} [ ] `;\n\t}\n\tif (list.ordered) {\n\t\tconst ordered = /^(\\d+)([.)])/.exec(marker);\n\t\tif (ordered) {\n\t\t\treturn `${Number(ordered[1]) + 1}${ordered[2]} `;\n\t\t}\n\t}\n\treturn `${bullet} `;\n}\n\n/** A collapsed insertion at the cursor, advancing the caret past it. */\nfunction _insertAt(sel: CursorCommandContext['selection'], inserted: string): SmartEnterResult {\n\treturn {\n\t\tkind: 'edit',\n\t\tedit: StringEdit.replace(sel.range, inserted),\n\t\tselection: Selection.collapsed(sel.range.start + inserted.length),\n\t};\n}\n\n/** End offset of the line containing `offset` (the next `\\n`, or end of text). */\nfunction _lineEnd(text: string, offset: number): number {\n\tconst nl = text.indexOf('\\n', offset);\n\treturn nl === -1 ? text.length : nl;\n}\n\n/** Whether `node` carries any non-whitespace text leaf (ignores markers/glue). */\nfunction _hasText(node: AstNode): boolean {\n\tif (node instanceof TextAstNode) { return node.content.trim().length > 0; }\n\treturn node.children.some(_hasText);\n}\n\nfunction _lineBreak(ctx: CursorCommandContext): SmartEnterResult {\n\tconst result = insertLineBreak(ctx)!;\n\treturn { kind: 'edit', edit: result.edit, selection: result.selection };\n}\n\n/** Absolute start offset of `block` within `doc`, or `undefined` if absent. */\nfunction _blockAbsoluteStart(doc: DocumentAstNode, block: BlockAstNode): number | undefined {\n\tlet pos = 0;\n\tfor (const child of doc.children) {\n\t\tif (child === block) { return pos; }\n\t\tpos += child.length;\n\t}\n\treturn undefined;\n}\n\n/** Combined length of the block's trailing glue (its inter-block gap newlines). */\nfunction _trailingGlueLength(block: BlockAstNode): number {\n\tconst content = block.children;\n\tlet len = 0;\n\tfor (let i = content.length - 1; i >= 0; i--) {\n\t\tif (content[i] instanceof GlueAstNode) { len += content[i].length; } else { break; }\n\t}\n\treturn len;\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport { Selection } from '../core/selection.js';\nimport { findWordAt } from '../core/wordUtils.js';\nimport type { CursorCommandContext, SelectionCommand } from './types.js';\n\nexport const selectAll: SelectionCommand = (ctx) =>\n\tnew Selection(0, ctx.text.length);\n\nexport const selectWord: SelectionCommand = (_ctx, offset) => {\n\tconst word = findWordAt(_ctx.text, offset);\n\treturn new Selection(word.start, word.end);\n};\n\nexport function selectBlock(ctx: CursorCommandContext, blockRange: OffsetRange): Selection {\n\treturn new Selection(blockRange.start, blockRange.endExclusive);\n}\n","import { Disposable } from '@vscode/observables';\nimport type { AstNode } from '../../parser/ast.js';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { DomPosition } from './dom.js';\n\nexport type { DomPosition } from './dom.js';\n\n/**\n * Reverse index: the DOM node a view node renders → the view node. Written only\n * in the {@link ViewNode} constructor, so it always reflects the live tree (a\n * reused subtree keeps its entries; a rebuilt node overwrites its own). It lets\n * a hit-test result (an arbitrary DOM node deep inside, e.g. a KaTeX element)\n * be walked up via {@link ViewNode.forDom} to the closest owning view node\n * without scanning the tree.\n */\nconst _domToViewNode = new WeakMap<globalThis.Node, ViewNode>();\n\n/**\n * Parent pointers, maintained incrementally: a node sets itself as the parent\n * of each of its children in its constructor. Because construction is\n * bottom-up and a reused subtree is never re-constructed, the only write per\n * frame is re-pointing each rebuilt node's direct children — O(reconciled\n * region), never the whole tree.\n */\nconst _parentOf = new WeakMap<ViewNode, ViewNode | undefined>();\n\n/**\n * Immutable view of an AST node. Pairs `ast` with its rendered `dom` and a\n * mirror of `ast.children` as ViewNode children. Source offsets are NEVER\n * stored — they are recomputed by walking and summing `ast.length` of\n * preceding siblings, just like the AST itself.\n *\n * Leaves are ViewNodes with no children. A leaf whose `dom` is a Text node\n * participates in source mapping; a leaf whose `dom` is an Element does not\n * (e.g. KaTeX-rendered math, or `<hr>` for a thematic break).\n */\nexport class ViewNode extends Disposable {\n private _children: readonly ViewNode[];\n\n constructor(\n readonly ast: AstNode,\n readonly dom: globalThis.Node,\n children: readonly ViewNode[] = _emptyChildren,\n ) {\n super();\n this._children = children;\n _domToViewNode.set(dom, this);\n for (const child of children) { _parentOf.set(child, this); }\n }\n\n /** This node's view children (a mirror of `ast.children`). */\n get children(): readonly ViewNode[] { return this._children; }\n\n /**\n * Replace this node's children in place, disposing the old ones and\n * re-pointing the new ones' parent to this node. The node value is still\n * conceptually immutable with respect to its `ast`/`dom` *identity*; this\n * is used only when a node patches its own DOM subtree in place (a code\n * block re-tokenising on a highlighter recolour), where the source-mapping\n * leaves must follow the new DOM text nodes without rebuilding the node\n * itself.\n */\n protected _replaceChildren(children: readonly ViewNode[]): void {\n for (const child of this._children) { child.dispose(); }\n this._children = children;\n for (const child of children) { _parentOf.set(child, this); }\n }\n\n dispose(): void {\n for (const child of this._children) { child.dispose(); }\n }\n\n /**\n * The number of source characters this node spans. Defaults to the length\n * of its {@link ast}; a synthetic leaf that subdivides one ast node (a\n * decorated-whitespace character, a code-block token span) shares that ast\n * for identity but overrides this with the length of its own slice, so the\n * renderer never has to fabricate an AST node just to carry a length.\n */\n get sourceLength(): number { return this.ast.length; }\n\n /**\n * The DOM node a parent mounts for this child. It is {@link dom} for almost\n * everything; a marker is the exception — its `dom` is the inner Text node\n * (so source ↔ DOM mapping lands on it) while the node it mounts is the\n * wrapping `<span>`.\n */\n get mountNode(): globalThis.Node { return this.dom; }\n\n /** The view node that rendered this node's parent, or `undefined` for a root. */\n get parent(): ViewNode | undefined { return _parentOf.get(this); }\n\n /**\n * Closest view node owning `domNode`: the node itself if registered, else\n * the nearest registered ancestor. Returns `undefined` if the DOM node is\n * outside any view tree.\n */\n static forDom(domNode: globalThis.Node | null): ViewNode | undefined {\n for (let n: globalThis.Node | null = domNode; n; n = n.parentNode) {\n const vn = _domToViewNode.get(n);\n if (vn) { return vn; }\n }\n return undefined;\n }\n\n /**\n * This node's start offset within its parent's local source space: the sum\n * of the `ast.length` of the siblings before it. Polymorphic via\n * {@link _localOffsetOfChild} so a parent whose children do not map\n * linearly (e.g. it hides or reorders some) can override how its children\n * are placed.\n */\n localOffsetInParent(): number {\n const p = this.parent;\n return p ? p._localOffsetOfChild(this) : 0;\n }\n\n /** Start offset of `child` within this node's local source space. */\n protected _localOffsetOfChild(child: ViewNode): number {\n let offset = 0;\n for (const c of this.children) {\n if (c === child) { return offset; }\n offset += c.sourceLength;\n }\n return offset;\n }\n\n /**\n * Map a DOM hit that lands on THIS node's own representation into a source\n * range in this node's local space `[0, ast.length)`. Polymorphic: a text\n * leaf maps the caret offset 1:1; an element-only node (KaTeX math, `<hr>`,\n * an image, a hidden marker) has no internal text mapping and snaps to its\n * start by default — subclasses may override (e.g. to snap to the nearer\n * edge by x).\n */\n getLocalSourceRange(pos: DomPosition): OffsetRange {\n if (this.dom === pos.node && this.dom.nodeType === 3 /* TEXT_NODE */) {\n return OffsetRange.emptyAt(Math.max(0, Math.min(pos.offset, this.sourceLength)));\n }\n return OffsetRange.emptyAt(0);\n }\n\n /**\n * DOM hit (any node + offset within it) → source offset relative to THIS\n * node, or `undefined` when the hit is outside this node's subtree. Enters\n * the tree at the closest owning view node ({@link forDom}), maps the hit\n * into that node's local space ({@link getLocalSourceRange}), then lifts the\n * range up the parent chain — adding each node's {@link localOffsetInParent} —\n * until it reaches this node.\n */\n resolveSource(pos: DomPosition): number | undefined {\n let node: ViewNode | undefined = ViewNode.forDom(pos.node);\n if (!node) { return undefined; }\n let range = node.getLocalSourceRange(pos);\n while (node !== this) {\n const p: ViewNode | undefined = node.parent;\n if (!p) { return undefined; }\n range = range.delta(node.localOffsetInParent());\n node = p;\n }\n return range.start;\n }\n\n /**\n * Source offset → DOM position. `nodeOffset` is the absolute source\n * offset of THIS node's start. Returns a position into a DOM Text node,\n * descending into children based on accumulated lengths.\n */\n sourceToDom(localSourceOffset: number, nodeSourceOffset: number = 0): DomPosition | undefined {\n if (localSourceOffset < nodeSourceOffset || localSourceOffset > nodeSourceOffset + this.sourceLength) {\n return undefined;\n }\n if (this.children.length === 0) {\n if (this.dom.nodeType === 3 /* TEXT_NODE */) {\n return { node: this.dom as Text, offset: localSourceOffset - nodeSourceOffset };\n }\n return undefined;\n }\n let childOffset = nodeSourceOffset;\n for (const child of this.children) {\n const childEnd = childOffset + child.sourceLength;\n if (localSourceOffset >= childOffset && localSourceOffset <= childEnd) {\n const result = child.sourceToDom(localSourceOffset, childOffset);\n if (result) { return result; }\n }\n childOffset = childEnd;\n }\n return undefined;\n }\n\n /** Visit every text-bearing leaf in this subtree with its absolute offset. */\n forEachTextLeaf(nodeOffset: number, visitor: (leaf: ViewNode, leafOffset: number) => void): void {\n if (this.children.length === 0) {\n if (this.dom.nodeType === 3 /* TEXT_NODE */) {\n visitor(this, nodeOffset);\n }\n return;\n }\n let childOffset = nodeOffset;\n for (const child of this.children) {\n child.forEachTextLeaf(childOffset, visitor);\n childOffset += child.sourceLength;\n }\n }\n}\n\nconst _emptyChildren: readonly ViewNode[] = [];\n\n","import katex from 'katex';\nimport { transaction, runOnChange } from '@vscode/observables';\nimport type { IDisposable } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { AstNode, BlockAstNode, ListItemAstNode, MarkerAstNode } from '../../parser/ast.js';\nimport { CodeBlockAstNode } from '../../parser/ast.js';\nimport type {\n\tAnyViewData, CodeBlockViewData, GlueViewData, HeadingViewData, ImageViewData,\n\tInlineCodeViewData, InlineMathViewData, LinkViewData, ListViewData, ListItemViewData,\n\tMarkerViewData, MathBlockViewData, TableRowViewData, TextViewData, ThematicBreakViewData,\n} from '../viewData.js';\nimport type { ISyntaxHighlighter, ISyntaxHighlighterDocument, Token } from '../../highlighter/syntaxHighlighter.js';\nimport { ViewNode } from './viewNode.js';\n\nexport interface BlockViewOptions {\n\treadonly renderCustomCodeBlock?: (language: string, content: string) => HTMLElement | undefined;\n\treadonly onToggleCheckbox?: (item: ListItemAstNode, newChecked: boolean) => void;\n\t/**\n\t * Opens a link's URL. Called when the user activates a link: a plain click\n\t * while the link's block is inactive (rendered), or a Ctrl/Cmd+click while it\n\t * is active (source shown). Defaults to `window.open(url, '_blank')`.\n\t */\n\treadonly onOpenLink?: (url: string, event: MouseEvent) => void;\n\t/**\n\t * Colours fenced code blocks. When set, a code block's content is rendered\n\t * as a sequence of token spans instead of one plain text node. This is the\n\t * non-incremental path: the snapshot is read once at render time.\n\t */\n\treadonly syntaxHighlighter?: ISyntaxHighlighter;\n\t/**\n\t * Pluggable renderer for the *inactive* (rendered) form of a math node —\n\t * both `$$…$$` blocks and inline `$…$`. When set and it returns a result,\n\t * its {@link MathRendering.dom} replaces the default opaque `katex.render`\n\t * output, and its {@link MathRendering.segments} let parts of the rendered\n\t * math (e.g. individual identifier glyphs) map back to source ranges so the\n\t * caret can land inside them. Returning `undefined` falls back to the\n\t * default whole-node KaTeX leaf. The active (source) form is unaffected.\n\t *\n\t * This is the seam used to explore in-place editing of rendered math (see\n\t * `katexEditableIdentifiers.ts`).\n\t */\n\treadonly renderMath?: (request: MathRenderRequest) => MathRendering | undefined;\n}\n\n/** Input to a {@link BlockViewOptions.renderMath} renderer. */\nexport interface MathRenderRequest {\n\t/** The LaTeX source of the math content (without the `$$`/`$` fences). */\n\treadonly latex: string;\n\t/** `true` for a `$$…$$` block, `false` for inline `$…$`. */\n\treadonly displayMode: boolean;\n\t/** CSS class the host element must carry (editor styling/measurement hooks). */\n\treadonly className: string;\n\t/** Full source length of the math node (fences/`$` included). */\n\treadonly nodeLength: number;\n\t/** Offset of {@link latex} within the node (i.e. after the opening fence/`$`). */\n\treadonly contentStart: number;\n}\n\n/**\n * A span of the rendered math output that maps to a slice of source. The\n * renderer reports these for the parts it can map (e.g. identifier glyphs);\n * the editor tiles the gaps between them so the whole math node stays mapped.\n */\nexport interface MathSourceSegment {\n\t/** A DOM node (ideally a Text node) within the rendered output. */\n\treadonly dom: globalThis.Node;\n\t/** Start offset of the mapped slice, relative to the math node's start. */\n\treadonly start: number;\n\t/** Source length of the mapped slice. */\n\treadonly length: number;\n}\n\n/** Result of a {@link BlockViewOptions.renderMath} renderer. */\nexport interface MathRendering {\n\t/** Host element to mount (the rendered math output). */\n\treadonly dom: HTMLElement;\n\t/** Source-mapped spans within {@link dom} (need not tile the whole node). */\n\treadonly segments: readonly MathSourceSegment[];\n}\n\n/**\n * Base view node for everything the editor renders, generic over the\n * {@link AnyViewData view-data} it renders so subclasses get a precisely-typed\n * {@link data} (e.g. `BlockViewNode<HeadingViewData>`). Every view-data kind has\n * a subclass whose constructor builds the node's DOM and, recursively,\n * constructs its child view nodes — so *constructing a node is rendering it*.\n * There is no separate render pass: the view tree is the result of construction,\n * and {@link createViewNode} is the single entry point that turns a `ViewData`\n * into a node (reusing a `previous` node untouched when it still matches).\n *\n * The name is historical — it is the base for inline and leaf nodes too — but\n * top-level blocks are always instances of it, and {@link element}/{@link block}\n * are the conveniences {@link EditorView} uses for those.\n */\nexport class BlockViewNode<T extends AnyViewData = AnyViewData> extends ViewNode {\n\tconstructor(\n\t\treadonly data: T,\n\t\tdom: globalThis.Node,\n\t\tchildren: readonly ViewNode[],\n\t) {\n\t\tsuper(data.ast, dom, children);\n\t}\n\n\tget block(): BlockAstNode { return this.data.ast as BlockAstNode; }\n\tget element(): HTMLElement { return this.dom as HTMLElement; }\n\n\t/**\n\t * Whether this already-built node can stand in for `data` unchanged. The\n\t * builder preserves view-data identity for any subtree whose ast and\n\t * selection-derived flags are unchanged (see `buildDocumentViewData`), so a\n\t * single identity check captures \"nothing in my subtree changed\" — and its\n\t * whole subtree, and any session it owns, are kept as-is.\n\t */\n\tcanReuse(data: AnyViewData): boolean {\n\t\treturn this.data === data;\n\t}\n\n\t/**\n\t * Called by the view after this block is mounted and measured, with the\n\t * block's rendered height in px. The default is a no-op; subclasses whose\n\t * active/inactive renderings have different intrinsic heights (e.g. a math\n\t * block) override this to remember a height to reserve across the toggle.\n\t */\n\trecordMeasuredHeight(_height: number): void { /* no-op */ }\n}\n\n/**\n * Turn a {@link AnyViewData view-data} node into its view node, reusing\n * `previous` when it still renders the very same view-data object (see\n * {@link BlockViewNode.canReuse}). Otherwise the matching subclass is\n * constructed, which renders it and recursively constructs its children —\n * threading `previous` down so an edited node can adopt its predecessor's DOM\n * (and, for an edited {@link CodeBlockAstNode}, the highlighting session of the\n * node it was derived from).\n *\n * On a rebuild `previous` is the view node {@link pairNodes} paired by stable id:\n * identity-matched nodes (same view-data) short-circuit above, an edited node is\n * paired with the node carrying its previous id, and any previous node whose id\n * is gone is dropped (disposed by its container's reconcile) so its replacement\n * is built with `previous === undefined`.\n */\nexport function createViewNode(data: AnyViewData, options: BlockViewOptions | undefined, previous?: ViewNode): ViewNode {\n\tif (previous instanceof BlockViewNode) {\n\t\tif (previous.canReuse(data)) {\n\t\t\treturn previous;\n\t\t}\n\t} else if (previous?.ast === data.ast) {\n\t\treturn previous;\n\t}\n\n\tswitch (data.kind) {\n\t\tcase 'text': return _textLeaf(data, _prev(previous, LeafViewNode));\n\t\tcase 'marker': return data.ast.markerKind === 'hardBreak'\n\t\t\t? new HardBreakViewNode(data, _prev(previous, HardBreakViewNode))\n\t\t\t: new MarkerViewNode(data, _prev(previous, MarkerViewNode));\n\t\tcase 'glue': return new GlueViewNode(data, _prev(previous, GlueViewNode));\n\t\tcase 'heading': return new HeadingViewNode(data, options, _prev(previous, HeadingViewNode));\n\t\tcase 'paragraph': return new ContainerViewNode(data, 'p', 'md-block md-paragraph', options, _prevContainer(previous));\n\t\tcase 'codeBlock': return new CodeBlockViewNode(data, options, previous);\n\t\tcase 'mathBlock': return new MathBlockViewNode(data, options, _prev(previous, MathBlockViewNode));\n\t\tcase 'thematicBreak': return new ThematicBreakViewNode(data, options, _prev(previous, ThematicBreakViewNode));\n\t\tcase 'blockQuote': return new ContainerViewNode(data, 'blockquote', 'md-block md-blockquote', options, _prevContainer(previous));\n\t\tcase 'list': return new ListViewNode(data, options, _prev(previous, ListViewNode));\n\t\tcase 'listItem': return new ListItemViewNode(data, options, _prev(previous, ListItemViewNode));\n\t\tcase 'table': return new ContainerViewNode(data, 'table', 'md-block md-table', options, _prevContainer(previous));\n\t\tcase 'tableRow': return new TableRowViewNode(data, options, _prev(previous, TableRowViewNode));\n\t\tcase 'tableCell': return new ContainerViewNode(data, 'td', '', options, _prevContainer(previous));\n\t\tcase 'strong': return new ContainerViewNode(data, 'strong', '', options, _prevContainer(previous));\n\t\tcase 'emphasis': return new ContainerViewNode(data, 'em', '', options, _prevContainer(previous));\n\t\tcase 'strikethrough': return new ContainerViewNode(data, 'del', '', options, _prevContainer(previous));\n\t\tcase 'inlineCode': return new InlineCodeViewNode(data, options, _prev(previous, InlineCodeViewNode));\n\t\tcase 'inlineMath': return new InlineMathViewNode(data, options, _prev(previous, InlineMathViewNode));\n\t\tcase 'link': return new LinkViewNode(data, options, _prev(previous, LinkViewNode));\n\t\tcase 'image': return new ImageViewNode(data, options, _prev(previous, ImageViewNode));\n\t\tcase 'document': return new ContainerViewNode(data, 'div', '', options, _prevContainer(previous));\n\t}\n}\n\n/** Narrow `previous` to a specific view-node subclass, or `undefined`. */\nfunction _prev<V extends ViewNode>(previous: ViewNode | undefined, ctor: new (...args: never[]) => V): V | undefined {\n\treturn previous instanceof ctor ? previous : undefined;\n}\n\n/** Narrow `previous` to a {@link ContainerViewNode}, or `undefined`. */\nfunction _prevContainer(previous: ViewNode | undefined): ContainerViewNode | undefined {\n\treturn previous instanceof ContainerViewNode ? previous : undefined;\n}\n\n/**\n * Build the view children for `childData` and patch `parentDom`'s child DOM in\n * place to match, in one step. Each new child-data is paired with the previous\n * view child that should render it ({@link pairNodes}) — by stable node id, which\n * covers both unchanged subtrees and edited nodes — so DOM and session adoption\n * carry over; the\n * `build` callback turns `(childData, prev)` into its view node (usually via\n * {@link createViewNode}). Previous children left unpaired are disposed, then\n * {@link _patchDomChildren} reorders/inserts/removes `parentDom`'s children so\n * the DOM matches the new view nodes — moving reused child DOM into place\n * rather than re-creating it. The returned array mirrors `childData` 1:1,\n * preserving the source ↔ DOM mapping invariant.\n */\nexport function reconcileDomChildren(\n\tparentDom: globalThis.Node,\n\tchildData: readonly AnyViewData[],\n\tpreviousChildren: readonly ViewNode[] | undefined,\n\tbuild: (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode,\n): ViewNode[] {\n\tconst { paired, unused } = pairNodes(childData, previousChildren ?? _NO_CHILDREN);\n\tconst children = childData.map(d => build(d, paired.get(d)));\n\tfor (const u of unused) { u.dispose(); }\n\t_patchDomChildren(parentDom, children);\n\treturn children;\n}\n\n/**\n * Make `parent`'s child DOM nodes match `children`'s {@link ViewNode.mountNode}s\n * in order. The overwhelmingly common case — the DOM is already correct (a\n * no-op frame, or a rebuild that only reused nodes) — is detected by a linear\n * scan up front and returns without touching the DOM at all. Otherwise it\n * reorders/inserts/removes in place from where they first diverge: only nodes\n * that actually move are touched, so a node the selection lives in is left\n * attached and the cursor survives (a `replaceChildren` swap would detach every\n * child and collapse the selection).\n */\nfunction _patchDomChildren(parent: globalThis.Node, children: readonly ViewNode[]): void {\n\t_patchDomNodes(parent, children.map(c => c.mountNode));\n}\n\n/**\n * Like {@link _patchDomChildren} but over raw mount nodes, so a caller can mount\n * a mix of view-node DOM and synthetic wrappers (e.g. a list item's gutter\n * span) in place without detaching the nodes that stay put.\n */\nexport function _patchDomNodes(parent: globalThis.Node, nodes: readonly globalThis.Node[]): void {\n\tlet domCursor: ChildNode | null = parent.firstChild;\n\tlet i = 0;\n\tfor (; i < nodes.length; i++) {\n\t\tif (domCursor !== nodes[i]) { break; }\n\t\tdomCursor = domCursor!.nextSibling;\n\t}\n\tif (i === nodes.length && domCursor === null) {\n\t\treturn; // already in the right order — nothing to do\n\t}\n\tfor (; i < nodes.length; i++) {\n\t\tconst node = nodes[i];\n\t\tif (domCursor === node) {\n\t\t\tdomCursor = node.nextSibling;\n\t\t} else {\n\t\t\tparent.insertBefore(node, domCursor);\n\t\t}\n\t}\n\twhile (domCursor) {\n\t\tconst toRemove = domCursor;\n\t\tdomCursor = domCursor.nextSibling;\n\t\tparent.removeChild(toRemove);\n\t}\n}\n\n/** Default child builder: render each child-data, threading `prev`. */\nfunction _buildChild(options: BlockViewOptions | undefined): (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode {\n\treturn (childData, prev) => createViewNode(childData, options, prev);\n}\n\n/**\n * Child builder for inline containers whose `content` marker must be a bare\n * Text node (no wrapping `<span>`), e.g. inline code / math: the content is\n * rendered as a {@link LeafViewNode} over a Text node so its characters map\n * directly. Every other child renders normally.\n */\nfunction _inlineChild(options: BlockViewOptions | undefined): (childData: AnyViewData, prev: ViewNode | undefined) => ViewNode {\n\treturn (childData, prev) => {\n\t\tif (childData.kind === 'marker' && childData.ast.markerKind === 'content') {\n\t\t\treturn new LeafViewNode(childData, document.createTextNode(childData.ast.content));\n\t\t}\n\t\treturn createViewNode(childData, options, prev);\n\t};\n}\n\nconst _NO_CHILDREN: readonly ViewNode[] = [];\n\n/** The view-data children of a container node (empty for leaves). */\nfunction _contentOf(data: AnyViewData): readonly AnyViewData[] {\n\treturn 'content' in data ? data.content : _NO_VIEW_CHILDREN;\n}\n\nconst _NO_VIEW_CHILDREN: readonly AnyViewData[] = [];\n\n/**\n * Text leaf. When the active block reveals source, non-obvious whitespace is\n * decorated with visible indicators (see {@link _appendDecorated}); the leaf is\n * then a `<span>` over source-mapped slices. Otherwise it is a bare Text node,\n * reused unchanged when the previous leaf rendered the same string so the node\n * the selection lives in stays attached and the cursor survives.\n */\nfunction _textLeaf(data: TextViewData, previous: LeafViewNode | undefined): ViewNode {\n\tconst content = data.ast.content;\n\tconst ctx: WhitespaceContext = {\n\t\tleftBoundary: data.leftWordBoundary,\n\t\trightBoundary: data.rightWordBoundary,\n\t\tdecorateNewline: true,\n\t};\n\tif (data.showWhitespace && _hasDecoratableWhitespace(content, ctx)) {\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-text';\n\t\tconst children = _appendDecorated(span, content, ctx, data.ast);\n\t\treturn new BlockViewNode(data, span, children);\n\t}\n\tconst prevDom = previous?.dom;\n\tconst dom = prevDom instanceof globalThis.Text && prevDom.data === content\n\t\t? prevDom\n\t\t: document.createTextNode(content);\n\treturn new LeafViewNode(data, dom);\n}\n\n/** A character that is whitespace (space, tab, or a line ending). */\nfunction _isWhitespaceChar(ch: string): boolean {\n\treturn ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r';\n}\n\n/**\n * Context that controls how the whitespace in a string is classified.\n * `leftBoundary`/`rightBoundary` say whether the inline sibling on that side\n * presents visible word content, so a single space at the leaf edge between two\n * words stays obvious. `decorateNewline` is false where a `<br>` already makes\n * the break visible (a hard line break) — the newline then gets no redundant\n * `↵`; elsewhere a source newline is collapsed (e.g. a soft break rendered as a\n * space) and the `↵` reveals the line ending hiding there.\n *\n * `newlineGlyph` switches a decorated newline from a CSS `::before` overlay (on\n * a collapsing `\\n`, whose selectable box ends up beside the glyph rather than\n * under it) to a real `↵` glyph character: a non-whitespace text node that\n * keeps its own width, so the selection box coincides with the glyph and every\n * newline is individually selectable. The trailing newline of the run is left\n * as a literal collapsing `\\n` (no glyph) so the glyph hugs the preceding text\n * without a stray leading space, and the blank-line glyph count is one per\n * blank line. Used for the inter-block gap glue.\n *\n * `breakGlyphClass`, when set, marks the run as a structural block break: its\n * *first* newline is the break that starts the next block and is always painted\n * as a glyph with this class (even when it is also the last/only newline, so it\n * never collapses), giving it a distinct look (blue) from the neutral\n * blank-line glyphs that follow.\n */\ninterface WhitespaceContext {\n\treadonly leftBoundary: boolean;\n\treadonly rightBoundary: boolean;\n\treadonly decorateNewline: boolean;\n\treadonly newlineGlyph?: boolean;\n\treadonly breakGlyphClass?: string;\n}\n\n/** A hard break's `<br>` already shows the line break, so its newline gets no `↵`. */\nconst _HARD_BREAK_WHITESPACE: WhitespaceContext = { leftBoundary: false, rightBoundary: false, decorateNewline: false };\n\n/**\n * An indented code block's structural indentation: every space is leading\n * (no word neighbours), so each is non-obvious and earns a `·` dot when shown.\n */\nconst _CODE_INDENT_WHITESPACE: WhitespaceContext = { leftBoundary: false, rightBoundary: false, decorateNewline: false };\n\n/**\n * A single space is \"obvious\" — and so left undecorated — only when it sits\n * between two non-whitespace characters. The neighbours are this leaf's own\n * characters, or — at the leaf's first/last position — the adjacent inline\n * sibling when it presents visible word content (`leftBoundary`/`rightBoundary`).\n * Leading, trailing and run (2+) spaces are non-obvious and get a visible dot.\n */\nfunction _isObviousSpace(content: string, i: number, ctx: WhitespaceContext): boolean {\n\tconst prevObvious = i > 0 ? !_isWhitespaceChar(content[i - 1]) : ctx.leftBoundary;\n\tconst nextObvious = i < content.length - 1 ? !_isWhitespaceChar(content[i + 1]) : ctx.rightBoundary;\n\treturn prevObvious && nextObvious;\n}\n\n/**\n * The indicator class for the character at `i`, or `undefined` when it needs no\n * indicator (plain text, an obvious space, or a newline whose break is already\n * visible). Single source of truth for both detection and segmentation below.\n */\nfunction _whitespaceClass(content: string, i: number, ctx: WhitespaceContext): string | undefined {\n\tconst ch = content[i];\n\tif (ch === '\\t') { return 'md-ws-tab'; }\n\tif (ch === '\\n' || ch === '\\r') { return ctx.decorateNewline ? 'md-ws-newline' : undefined; }\n\tif (ch === ' ' && !_isObviousSpace(content, i, ctx)) { return 'md-ws-space'; }\n\treturn undefined;\n}\n\n/** Whether `content` contains any whitespace that would be decorated when revealed. */\nfunction _hasDecoratableWhitespace(content: string, ctx: WhitespaceContext): boolean {\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst ch = content[i];\n\t\t// `newlineGlyph` turns a newline into a `↵` glyph even when the inline\n\t\t// `decorateNewline` overlay is off (a trailing block gap), so it counts.\n\t\tif (ctx.newlineGlyph && (ch === '\\n' || ch === '\\r')) { return true; }\n\t\tif (_whitespaceClass(content, i, ctx) !== undefined) { return true; }\n\t}\n\treturn false;\n}\n\ninterface WhitespaceSegment {\n\treadonly text: string;\n\treadonly cls: string | undefined;\n\t/** DOM text to render; defaults to `text`. The source-mapped length still comes from `text`. */\n\treadonly display?: string;\n}\n\n/** Split `content` into plain runs and individually-decorated whitespace characters. */\nfunction _segmentWhitespace(content: string, ctx: WhitespaceContext): WhitespaceSegment[] {\n\tconst segments: WhitespaceSegment[] = [];\n\tlet plainStart = -1;\n\tconst flushPlain = (end: number) => {\n\t\tif (plainStart >= 0) { segments.push({ text: content.slice(plainStart, end), cls: undefined }); plainStart = -1; }\n\t};\n\t// The structural-break newline (the gap's first) is always painted as a glyph\n\t// and never collapses; the trailing newline is the line terminator and stays a\n\t// collapsing `\\n` so the glyph hugs the preceding text with no stray leading space.\n\tconst breakNewline = ctx.breakGlyphClass ? content.indexOf('\\n') : -1;\n\tconst lastNewline = ctx.newlineGlyph ? content.lastIndexOf('\\n') : -1;\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst ch = content[i];\n\t\tif (ctx.newlineGlyph && (ch === '\\n' || ch === '\\r')) {\n\t\t\tconst isBreak = i === breakNewline;\n\t\t\tif (i !== lastNewline || isBreak) {\n\t\t\t\tflushPlain(i);\n\t\t\t\tsegments.push({ text: ch, cls: isBreak ? ctx.breakGlyphClass! : 'md-ws-newline-glyph', display: '↵' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst cls = ctx.newlineGlyph && (ch === '\\n' || ch === '\\r') ? undefined : _whitespaceClass(content, i, ctx);\n\t\tif (cls === undefined) { if (plainStart < 0) { plainStart = i; } continue; }\n\t\tflushPlain(i);\n\t\tsegments.push({ text: ch, cls });\n\t}\n\tflushPlain(content.length);\n\treturn segments;\n}\n\n/**\n * Append `content` to `host`, wrapping each non-obvious whitespace character in\n * a `<span>` whose CSS overlays a visible indicator while the real character\n * stays in the DOM. Returns one source-mapped {@link RawLeafViewNode} per\n * segment, so the slices' lengths sum to `content.length` and source ↔ DOM\n * mapping is unaffected. Every segment shares the enclosing `ast` node (the text\n * or glue leaf whose content this is) for identity and carries the length of\n * its own slice — the renderer never fabricates an AST node.\n */\nfunction _appendDecorated(host: HTMLElement, content: string, ctx: WhitespaceContext, ast: AstNode): ViewNode[] {\n\tconst children: ViewNode[] = [];\n\tfor (const seg of _segmentWhitespace(content, ctx)) {\n\t\tconst text = document.createTextNode(seg.display ?? seg.text);\n\t\tif (seg.cls) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = seg.cls;\n\t\t\tspan.appendChild(text);\n\t\t\thost.appendChild(span);\n\t\t} else {\n\t\t\thost.appendChild(text);\n\t\t}\n\t\t// The DOM may show a glyph (`seg.display`) while the source slice is\n\t\t// `seg.text`; both are length-1, so source ↔ DOM mapping is exact.\n\t\tchildren.push(new RawLeafViewNode(ast, text, _NO_CHILDREN, seg.text.length));\n\t}\n\treturn children;\n}\n\n/** Generic leaf: a single DOM node with no children (text, KaTeX output, `<hr>`, …). */\nclass LeafViewNode extends BlockViewNode {\n\tconstructor(data: AnyViewData, dom: globalThis.Node) {\n\t\tsuper(data, dom, _NO_CHILDREN);\n\t}\n}\n\n/**\n * A leaf over a raw AST node with no view-data of its own — used for synthetic\n * fragments the renderer creates internally (code-block content and its token\n * spans, decorated-whitespace characters), which participate in source mapping\n * but are never reconciled or reused on their own. It shares the enclosing real\n * ast node for identity (the renderer never fabricates AST), so {@link\n * sourceLength} is given explicitly when the fragment is only a slice of that\n * ast's content; it defaults to the full `ast.length` for a whole-content leaf.\n */\nclass RawLeafViewNode extends ViewNode {\n\tprivate readonly _sourceLength: number;\n\tconstructor(ast: AstNode, dom: globalThis.Node, children: readonly ViewNode[] = _NO_CHILDREN, sourceLength: number = ast.length) {\n\t\tsuper(ast, dom, children);\n\t\tthis._sourceLength = sourceLength;\n\t}\n\toverride get sourceLength(): number { return this._sourceLength; }\n}\n\n/**\n * A marker (fence, list bullet, emphasis `*`, table pipe, …). Present in the\n * DOM as `<span class=\"md-marker …\">` wrapping a Text node; the span gains\n * `md-marker-hidden` (→ `display: none`) when markers are hidden, so it leaves\n * layout entirely. The view node's {@link dom} is the inner Text node so source\n * offsets map onto it, while {@link mountNode} is the span the parent mounts.\n */\nclass MarkerViewNode extends BlockViewNode<MarkerViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: MarkerViewData, previous: MarkerViewNode | undefined) {\n\t\tconst marker = data.ast;\n\t\tconst base = `md-marker md-marker-${marker.markerKind}`;\n\t\t// Reuse the previous span + Text node when the rendered string is\n\t\t// unchanged so the node the selection lives in stays attached and the\n\t\t// cursor survives; only the class (which depends on `visible`) is updated.\n\t\tconst reuse = previous && previous.dom instanceof globalThis.Text && previous.dom.data === marker.content;\n\t\tconst span = reuse ? previous._span : document.createElement('span');\n\t\tspan.className = data.visible ? base : `${base} md-marker-hidden`;\n\t\tconst text = reuse ? previous.dom as globalThis.Text : document.createTextNode(marker.content);\n\t\tif (!reuse) { span.appendChild(text); }\n\t\tsuper(data, text, _NO_CHILDREN);\n\t\tthis._span = span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n}\n\n/**\n * Non-semantic syntactic glue: table cell pipes (`| `), the task-list `[x] `\n * source, and other source padding. Rendered like a {@link MarkerViewNode} —\n * a `<span>` wrapping a Text node — but when hidden it keeps its inline width\n * (`visibility: hidden`, via `md-glue-hidden`) instead of leaving layout, so\n * column widths and the checkbox gutter stay stable as markers toggle. When\n * visible, its non-obvious whitespace is decorated with visible indicators\n * (see {@link _appendDecorated}).\n */\nclass GlueViewNode extends BlockViewNode<GlueViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: GlueViewData, previous: GlueViewNode | undefined) {\n\t\tconst built = GlueViewNode._build(data, previous);\n\t\tsuper(data, built.dom, built.children);\n\t\tthis._span = built.span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n\n\tprivate static _build(\n\t\tdata: GlueViewData,\n\t\tprevious: GlueViewNode | undefined,\n\t): { span: HTMLElement; dom: globalThis.Node; children: readonly ViewNode[] } {\n\t\tconst glue = data.ast;\n\t\tconst base = glue.glueKind ? `md-glue md-glue-${glue.glueKind}` : 'md-glue';\n\t\t// Glue has no inline word neighbours; whether its newline gets a `↵`\n\t\t// depends on whether this glue sits in inline flow (decided at build time).\n\t\t// A `blockBreak` additionally paints its first newline as the blue\n\t\t// structural-break glyph (see `breakGlyphClass`).\n\t\tconst isBreak = glue.glueKind === 'blockBreak';\n\t\t// A trailing block gap shows its blank-line newlines as `↵` glyphs purely by\n\t\t// virtue of its kind: `_attachBlockGaps` tags glue `blockGap`/`blockBreak`\n\t\t// only when it absorbs a gap as some block's trailing trivia, so the kind\n\t\t// itself proves \"this is an editable trailing gap\" — no per-block opt-in (an\n\t\t// ambient `inlineFlow`/`decorateNewline`) is needed, and every block type\n\t\t// (table, code, math, heading, …) reveals it uniformly. The hostless\n\t\t// document-level gap (leading the first block) is built always-hidden (see\n\t\t// `buildDocumentViewData`), so it never decorates and `---\\n\\n…` / `---\\n…`\n\t\t// still render identically. `decorateNewline` now governs only the inline\n\t\t// soft-break overlay (`md-ws-newline`) for whitespace inside paragraphs.\n\t\tconst ws: WhitespaceContext = {\n\t\t\tleftBoundary: false,\n\t\t\trightBoundary: false,\n\t\t\tdecorateNewline: data.decorateNewline,\n\t\t\tnewlineGlyph: glue.glueKind === 'blockGap' || isBreak,\n\t\t\tbreakGlyphClass: isBreak ? 'md-ws-blockbreak-glyph' : undefined,\n\t\t};\n\t\tconst decorate = data.visible && _hasDecoratableWhitespace(glue.content, ws);\n\t\tif (decorate) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = base;\n\t\t\tconst children = _appendDecorated(span, glue.content, ws, glue);\n\t\t\treturn { span, dom: span, children };\n\t\t}\n\t\t// Reuse the previous span + Text node when the rendered string is unchanged\n\t\t// so the node the selection lives in stays attached and the cursor survives;\n\t\t// only the class (which depends on `visible`) is updated.\n\t\tconst reuse = previous && previous.dom instanceof globalThis.Text\n\t\t\t&& previous.dom.data === glue.content && previous.children.length === 0;\n\t\tconst span = reuse ? previous._span : document.createElement('span');\n\t\tspan.className = data.visible ? base : `${base} md-glue-hidden`;\n\t\tconst text = reuse ? previous.dom as globalThis.Text : document.createTextNode(glue.content);\n\t\tif (!reuse) { span.appendChild(text); }\n\t\treturn { span, dom: text, children: _NO_CHILDREN };\n\t}\n}\n\n/**\n * A GFM hard line break (`··\\n` or `\\`). Always renders a `<br>` so the line\n * breaks in both the rendered and the source view; the break's source\n * characters (the trailing spaces / backslash and the newline) are revealed —\n * with the same whitespace indicators as everything else — only while the block\n * is active, and otherwise hidden. The source text stays in the DOM either way\n * so source ↔ DOM mapping is unaffected; the `<br>` carries no source length and\n * so is not a child view node.\n */\nclass HardBreakViewNode extends BlockViewNode<MarkerViewData> {\n\tprivate readonly _span: HTMLElement;\n\n\tconstructor(data: MarkerViewData, _previous: HardBreakViewNode | undefined) {\n\t\tconst content = data.ast.content;\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-hardbreak';\n\t\tconst holder = document.createElement('span');\n\t\tholder.className = data.visible ? 'md-hardbreak-src' : 'md-hardbreak-src md-hardbreak-src-hidden';\n\t\t// The `<br>` already shows the break, so the newline gets no redundant `↵`.\n\t\tconst children = data.visible\n\t\t\t? _appendDecorated(holder, content, _HARD_BREAK_WHITESPACE, data.ast)\n\t\t\t: _appendPlainText(holder, content, data.ast);\n\t\tspan.appendChild(holder);\n\t\tspan.appendChild(document.createElement('br'));\n\t\tsuper(data, span, children);\n\t\tthis._span = span;\n\t}\n\n\toverride get mountNode(): globalThis.Node { return this._span; }\n}\n\n/** Append `content` as a single Text node and return its source-mapped leaf. */\nfunction _appendPlainText(host: HTMLElement, content: string, ast: AstNode): ViewNode[] {\n\tconst text = document.createTextNode(content);\n\thost.appendChild(text);\n\treturn [new RawLeafViewNode(ast, text)];\n}\n\n/** A plain element container (`<p>`, `<blockquote>`, `<strong>`, `<td>`, …) whose children mirror the node's children. Reuses `previous`'s element when given one (same kind ⇒ same tag), so only its children are reconciled. */\nclass ContainerViewNode<T extends AnyViewData = AnyViewData> extends BlockViewNode<T> {\n\tconstructor(data: T, tag: string, className: string, options: BlockViewOptions | undefined, previous: ContainerViewNode | undefined) {\n\t\tconst el = previous?.element ?? document.createElement(tag);\n\t\t// A reused element already carries this kind's class (same kind ⇒ same\n\t\t// tag ⇒ same className), so only a freshly created one needs it set.\n\t\tif (!previous && className) { el.className = className; }\n\t\tconst children = reconcileDomChildren(el, _contentOf(data), previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\nclass HeadingViewNode extends BlockViewNode<HeadingViewData> {\n\tconstructor(data: HeadingViewData, options: BlockViewOptions | undefined, previous: HeadingViewNode | undefined) {\n\t\tconst reuse = previous && previous.element.tagName === `H${data.ast.level}`;\n\t\tconst el = reuse ? previous.element : document.createElement(`h${data.ast.level}`);\n\t\tif (!reuse) { el.className = 'md-block md-heading'; }\n\t\tconst children = reconcileDomChildren(el, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\n/**\n * A thematic break (`---`). When inactive it renders a non-text `<hr>` leaf\n * whose `sourceLength` is the node's full `ast.length` (the `---` plus any\n * trailing blank-line glue the parser absorbed), so mapping steps over it as a\n * single opaque run. When active it reveals the source as an editable\n * container: a `<div>` whose children mirror the marker (and any trailing glue),\n * so the cursor can land on and edit the `---` like any other source.\n */\nclass ThematicBreakViewNode extends BlockViewNode<ThematicBreakViewData> {\n\tconstructor(data: ThematicBreakViewData, options: BlockViewOptions | undefined, previous: ThematicBreakViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\tconst reuse = previous?.dom instanceof HTMLDivElement ? previous : undefined;\n\t\t\tconst el = reuse?.element ?? document.createElement('div');\n\t\t\tif (!reuse) { el.className = 'md-block md-thematic-break-source'; }\n\t\t\tconst children = reconcileDomChildren(el, data.content, reuse?.children, _buildChild(options));\n\t\t\tsuper(data, el, children);\n\t\t\treturn;\n\t\t}\n\t\tconst hr = document.createElement('hr');\n\t\thr.className = 'md-block md-thematic-break';\n\t\tsuper(data, hr, _NO_CHILDREN);\n\t}\n}\n\n/**\n * A fenced code block. It owns its incremental\n * {@link ISyntaxHighlighterDocument} session: constructing the node creates (or\n * adopts from `previous`) the session, and disposing the node disposes it, so\n * colouring stays incremental across edits — the session is reused and\n * `update`d rather than rebuilt. A node at any depth owns a session; the only\n * difference today is that the parser links `getDiff` for top-level code blocks\n * only, so a nested block currently builds a fresh session on each rebuild.\n */\nexport class CodeBlockViewNode extends BlockViewNode<CodeBlockViewData> {\n\tprivate _session: ISyntaxHighlighterDocument | undefined;\n\t/**\n\t * Subscription that re-tokenises the rendered `<code>` in place whenever the\n\t * session advances its {@link ISyntaxHighlighterDocument.snapshot} *without*\n\t * a source edit (an async grammar finishing, a live recolour). It is tied to\n\t * this node's lifetime, but like {@link _session} it must be disposed\n\t * manually: a node reused as `previous` for a rebuild is never `dispose`d\n\t * (see {@link reconcileDomChildren}), so the rebuilding constructor disposes\n\t * its predecessor's subscription explicitly.\n\t */\n\tprivate _snapshotSub: IDisposable | undefined;\n\n\tconstructor(data: CodeBlockViewData, options: BlockViewOptions | undefined, previous: ViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst content = ast.code?.content ?? '';\n\t\tconst custom = (!data.showMarkup && ast.language && options?.renderCustomCodeBlock)\n\t\t\t? (options.renderCustomCodeBlock(ast.language, content) ?? undefined)\n\t\t\t: undefined;\n\t\tconst highlighter = options?.syntaxHighlighter;\n\t\tconst prevCode = previous instanceof CodeBlockViewNode ? previous : undefined;\n\n\t\t// Adopt `previous`'s session when we can (same block, or an in-content\n\t\t// edit reported by getDiff); otherwise create a fresh one. Any session\n\t\t// on `previous` we do not adopt is disposed.\n\t\tlet session: ISyntaxHighlighterDocument | undefined;\n\t\tif (!custom && highlighter && ast.language) {\n\t\t\tif (prevCode?._session && ast === prevCode.ast) {\n\t\t\t\tsession = prevCode._session;\n\t\t\t\tprevCode._session = undefined;\n\t\t\t} else if (prevCode?._session) {\n\t\t\t\tconst diff = ast.getDiff(prevCode.ast as CodeBlockAstNode);\n\t\t\t\tif (diff) {\n\t\t\t\t\tsession = prevCode._session;\n\t\t\t\t\tprevCode._session = undefined;\n\t\t\t\t\ttransaction(tx => session!.update(diff.stringEdit, tx));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!session) { session = highlighter.create(ast.language, content); }\n\t\t}\n\t\tif (prevCode?._session) { prevCode._session.dispose(); prevCode._session = undefined; }\n\t\t// The predecessor's in-place subscription is bound to its (now discarded)\n\t\t// DOM; drop it before this node installs its own.\n\t\tprevCode?._snapshotSub?.dispose();\n\t\tif (prevCode) { prevCode._snapshotSub = undefined; }\n\n\t\tconst tokens = session\n\t\t\t? session.snapshot.get().getTokens(OffsetRange.ofLength(content.length)).tokens\n\t\t\t: undefined;\n\n\t\tlet dom: HTMLElement;\n\t\tlet children: readonly ViewNode[];\n\t\tlet contentNode: CodeContentViewNode | undefined;\n\t\tif (custom) {\n\t\t\tcustom.classList.add('md-block', 'md-code-block');\n\t\t\tdom = custom;\n\t\t\tchildren = _NO_CHILDREN;\n\t\t} else if (!ast.openFence) {\n\t\t\t// Indented code block: no fences, no language (so no highlighting).\n\t\t\t// The per-line `codeIndent` markers are hideable so the structural\n\t\t\t// indentation drops out of the rendered block when markup is hidden\n\t\t\t// (like a heading's `#`); the `content` markers carry the code text\n\t\t\t// verbatim. Everything tiles one `<code>`; any trailing block glue\n\t\t\t// (a following gap) sits in the `<pre>` after it, as for fences.\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-code-block';\n\t\t\tconst code = document.createElement('code');\n\t\t\tpre.appendChild(code);\n\t\t\tconst kids: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tconst childAst = childData.ast;\n\t\t\t\tif (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'content') {\n\t\t\t\t\tconst text = document.createTextNode((childAst as MarkerAstNode).content);\n\t\t\t\t\tcode.appendChild(text);\n\t\t\t\t\tkids.push(new RawLeafViewNode(childAst, text));\n\t\t\t\t} else if (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'codeIndent') {\n\t\t\t\t\tconst marker = childAst as MarkerAstNode;\n\t\t\t\t\t// When revealed, the structural indentation is all non-obvious\n\t\t\t\t\t// whitespace, so paint each space as a `·` dot (like decorated\n\t\t\t\t\t// inline whitespace); when hidden it collapses to nothing\n\t\t\t\t\t// (`md-marker-hidden`), dedenting the code.\n\t\t\t\t\tif ((childData as MarkerViewData).visible) {\n\t\t\t\t\t\tconst span = document.createElement('span');\n\t\t\t\t\t\tspan.className = 'md-marker md-marker-codeIndent';\n\t\t\t\t\t\tconst leaves = _appendDecorated(span, marker.content, _CODE_INDENT_WHITESPACE, marker);\n\t\t\t\t\t\tcode.appendChild(span);\n\t\t\t\t\t\tkids.push(new RawLeafViewNode(marker, span, leaves));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\t\tcode.appendChild(vn.mountNode);\n\t\t\t\t\t\tkids.push(vn);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tkids.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdom = pre;\n\t\t\tchildren = kids;\n\t\t} else {\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-code-block';\n\t\t\tconst kids: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tif (childData.ast === ast.code) {\n\t\t\t\t\tconst code = document.createElement('code');\n\t\t\t\t\tif (ast.language) { code.className = `language-${CSS.escape(ast.language)}`; }\n\t\t\t\t\tconst built = _buildCodeContent(ast.code, content, code, tokens);\n\t\t\t\t\tif (built instanceof CodeContentViewNode) { contentNode = built; }\n\t\t\t\t\tkids.push(built);\n\t\t\t\t\tpre.appendChild(code);\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tkids.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdom = pre;\n\t\t\tchildren = kids;\n\t\t}\n\n\t\tsuper(data, dom, children);\n\t\tthis._session = session;\n\t\t// Re-tokenise in place on every later snapshot change. `runOnChange`\n\t\t// fires only on *future* changes, so the synchronous `session.update`\n\t\t// above (a source edit) is already reflected and does not re-trigger.\n\t\tif (session && contentNode) {\n\t\t\tthis._snapshotSub = runOnChange(session.snapshot, () => {\n\t\t\t\tconst snapshot = session!.snapshot.get();\n\t\t\t\tcontentNode!.refresh(content, snapshot.getTokens(OffsetRange.ofLength(content.length)).tokens);\n\t\t\t});\n\t\t}\n\t}\n\n\toverride dispose(): void {\n\t\tthis._snapshotSub?.dispose();\n\t\tthis._snapshotSub = undefined;\n\t\tthis._session?.dispose();\n\t\tthis._session = undefined;\n\t\tsuper.dispose();\n\t}\n}\n\n/**\n * The single view node for a code block's content (the `content` marker),\n * mirroring its character length exactly so source ↔ DOM mapping is unaffected.\n * With `tokens` the content is split into coloured token spans under `code`\n * (token leaves as children); without, it is one Text node.\n */\nfunction _buildCodeContent(\n\tcontentAst: MarkerAstNode,\n\tcontent: string,\n\tcode: HTMLElement,\n\ttokens: readonly Token[] | undefined,\n): ViewNode {\n\tif (!tokens) {\n\t\tconst text = document.createTextNode(content);\n\t\tcode.appendChild(text);\n\t\treturn new RawLeafViewNode(contentAst, text);\n\t}\n\treturn new CodeContentViewNode(contentAst, code, content, tokens);\n}\n\n/**\n * The `<code>` content of a syntax-highlighted code block. Its DOM (the token\n * `<span>`s) and its source-mapping token leaves are rebuilt in place by\n * {@link refresh} when the highlighter recolours, so a recolour patches only\n * this subtree's DOM — the surrounding view-node tree (and the editor's\n * measured layout) is untouched.\n */\nclass CodeContentViewNode extends ViewNode {\n\tconstructor(contentAst: MarkerAstNode, code: HTMLElement, content: string, tokens: readonly Token[]) {\n\t\tsuper(contentAst, code, _buildTokenLeaves(contentAst, code, content, tokens));\n\t}\n\n\t/** Re-render the token spans for a new colouring, in place. */\n\trefresh(content: string, tokens: readonly Token[]): void {\n\t\tconst code = this.dom as HTMLElement;\n\t\tcode.replaceChildren();\n\t\tthis._replaceChildren(_buildTokenLeaves(this.ast as MarkerAstNode, code, content, tokens));\n\t}\n}\n\n/**\n * Append the token spans for `content` to `code` and return the per-token\n * source-mapping leaves (each a Text-node leaf carrying its slice length), so\n * the leaves tile `[0, content.length)` exactly.\n */\nfunction _buildTokenLeaves(\n\tcontentAst: MarkerAstNode,\n\tcode: HTMLElement,\n\tcontent: string,\n\ttokens: readonly Token[],\n): ViewNode[] {\n\tconst tokenLeaves: ViewNode[] = [];\n\tlet offset = 0;\n\tfor (const token of tokens) {\n\t\tconst piece = content.slice(offset, offset + token.length);\n\t\toffset += token.length;\n\t\tconst text = document.createTextNode(piece);\n\t\tif (token.className) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tfor (const cls of token.className.split('.')) {\n\t\t\t\tif (cls) { span.classList.add(`tok-${cls}`); }\n\t\t\t}\n\t\t\tspan.appendChild(text);\n\t\t\tcode.appendChild(span);\n\t\t} else {\n\t\t\tcode.appendChild(text);\n\t\t}\n\t\ttokenLeaves.push(new RawLeafViewNode(contentAst, text, _NO_CHILDREN, piece.length));\n\t}\n\treturn tokenLeaves;\n}\n\n/**\n * Relative start offset of the math content (the `content` marker) within a\n * math node's children. Mirrors `CodeBlockAstNode.codeOffset` for math nodes,\n * which do not carry it themselves.\n */\nfunction _mathContentOffset(content: readonly AstNode[]): number {\n\tlet pos = 0;\n\tfor (const c of content) {\n\t\tif (c.kind === 'marker' && (c as MarkerAstNode).markerKind === 'content') { return pos; }\n\t\tpos += c.length;\n\t}\n\treturn pos;\n}\n\n/**\n * Build a fully-tiled child list for an inactive (rendered) math node from the\n * source-mapped {@link MathSourceSegment segments} a {@link BlockViewOptions.renderMath}\n * renderer reported. The segments cover only the spans the renderer could map\n * back to source (e.g. identifier glyphs); the gaps before/between/after them\n * are filled with synthetic filler leaves (a detached, empty Text node carrying\n * only a length) so the children tile the node's whole `[0, nodeLength)` source\n * range in source order. That ordered tiling is what\n * {@link ViewNode.localOffsetInParent}/{@link ViewNode.sourceToDom} rely on to\n * lift a hit on a mapped glyph to the correct absolute source offset; a hit that\n * lands on an unmapped (filler) region simply resolves to the math node's start.\n */\nfunction _buildMathSegmentChildren(ast: AstNode, segments: readonly MathSourceSegment[], nodeLength: number): ViewNode[] {\n\tconst sorted = segments\n\t\t.filter(s => s.length > 0 && s.start >= 0 && s.start + s.length <= nodeLength)\n\t\t.slice()\n\t\t.sort((a, b) => a.start - b.start);\n\tconst children: ViewNode[] = [];\n\tlet pos = 0;\n\tconst filler = (len: number) => {\n\t\tif (len > 0) { children.push(new RawLeafViewNode(ast, document.createTextNode(''), _NO_CHILDREN, len)); }\n\t};\n\tfor (const seg of sorted) {\n\t\tif (seg.start < pos) { continue; } // overlapping segment — skip to keep tiling monotone\n\t\tfiller(seg.start - pos);\n\t\tchildren.push(new RawLeafViewNode(ast, seg.dom, _NO_CHILDREN, seg.length));\n\t\tpos = seg.start + seg.length;\n\t}\n\tfiller(nodeLength - pos);\n\treturn children;\n}\n\nclass MathBlockViewNode extends BlockViewNode<MathBlockViewData> {\n\t/**\n\t * The rendered (inactive, KaTeX) height in px, measured after mount and\n\t * carried forward across rebuilds via `previous`. When the block becomes\n\t * active (source markers shown) this height is reserved as a `min-height`\n\t * so the editor does not collapse below the rendered size, keeping the\n\t * surrounding layout stable as the caret enters and leaves the block.\n\t */\n\tprivate _renderedHeight: number | undefined;\n\n\tconstructor(data: MathBlockViewData, options: BlockViewOptions | undefined, previous: MathBlockViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst remembered = previous?._renderedHeight;\n\t\tif (data.showMarkup) {\n\t\t\tconst pre = document.createElement('pre');\n\t\t\tpre.className = 'md-block md-math-block';\n\t\t\t// Reserve the rendered height measured while inactive so toggling to\n\t\t\t// the source view does not shrink the block (and the layout below it\n\t\t\t// stays put). Only ever grows the box, never clips the source.\n\t\t\t// `border-box` so the reserved (getBoundingClientRect) height — which\n\t\t\t// includes padding — is matched exactly rather than padding-on-padding.\n\t\t\tif (remembered !== undefined) {\n\t\t\t\tpre.style.boxSizing = 'border-box';\n\t\t\t\tpre.style.minHeight = `${remembered}px`;\n\t\t\t}\n\t\t\tconst children: ViewNode[] = [];\n\t\t\tfor (const childData of data.content) {\n\t\t\t\tif (childData.ast === ast.code) {\n\t\t\t\t\tconst code = document.createElement('code');\n\t\t\t\t\tconst text = document.createTextNode(ast.code.content);\n\t\t\t\t\tcode.appendChild(text);\n\t\t\t\t\tpre.appendChild(code);\n\t\t\t\t\tchildren.push(new RawLeafViewNode(ast.code, text));\n\t\t\t\t} else {\n\t\t\t\t\tconst vn = createViewNode(childData, options, undefined);\n\t\t\t\t\tpre.appendChild(vn.mountNode);\n\t\t\t\t\tchildren.push(vn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuper(data, pre, children);\n\t\t\tthis._renderedHeight = remembered;\n\t\t\treturn;\n\t\t}\n\t\tconst latex = ast.code?.content ?? '';\n\t\tconst rendering = options?.renderMath?.({\n\t\t\tlatex,\n\t\t\tdisplayMode: true,\n\t\t\tclassName: 'md-block md-math-block',\n\t\t\tnodeLength: ast.length,\n\t\t\tcontentStart: _mathContentOffset(ast.content),\n\t\t});\n\t\tif (rendering) {\n\t\t\tsuper(data, rendering.dom, _buildMathSegmentChildren(ast, rendering.segments, ast.length));\n\t\t\tthis._renderedHeight = remembered;\n\t\t\treturn;\n\t\t}\n\t\tconst div = document.createElement('div');\n\t\tdiv.className = 'md-block md-math-block';\n\t\ttry {\n\t\t\tkatex.render(latex, div, { displayMode: true, throwOnError: false });\n\t\t} catch {\n\t\t\tdiv.textContent = latex;\n\t\t}\n\t\tsuper(data, div, _NO_CHILDREN);\n\t\tthis._renderedHeight = remembered;\n\t}\n\n\toverride recordMeasuredHeight(height: number): void {\n\t\t// Only the inactive (rendered) form defines the height to reserve; the\n\t\t// active form's height is whatever the source needs (>= the reserved min).\n\t\tif (!this.data.showMarkup) { this._renderedHeight = height; }\n\t}\n}\n\n/**\n * A list. Each item carries its own `isActive` flag (the builder computes which\n * items the selection reaches), so the list just dispatches each child to its\n * view node — the per-item active state lives on the {@link ListItemViewData}.\n */\nclass ListViewNode extends BlockViewNode<ListViewData> {\n\tconstructor(data: ListViewData, options: BlockViewOptions | undefined, previous: ListViewNode | undefined) {\n\t\tconst tag = data.ast.ordered ? 'ol' : 'ul';\n\t\tconst reuse = previous && previous.element.tagName === tag.toUpperCase();\n\t\tconst el = reuse ? previous.element : document.createElement(tag);\n\t\tif (!reuse) { el.className = 'md-block md-list'; }\n\t\tconst children = reconcileDomChildren(el, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, el, children);\n\t}\n}\n\nclass ListItemViewNode extends BlockViewNode<ListItemViewData> {\n\tconstructor(data: ListItemViewData, options: BlockViewOptions | undefined, previous: ListItemViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tconst li = document.createElement('li');\n\t\tif (data.isActive) { li.classList.add('md-list-item-active'); }\n\t\tif (ast.checked !== undefined) { li.classList.add('md-task-list-item'); }\n\t\tif (!data.isActive) { li.classList.add('md-markers-hidden'); }\n\t\tli.style.setProperty('--md-list-level', String(data.level));\n\n\t\tconst children = _reconcileListItem(li, data.content, previous, options);\n\n\t\t// Checkbox affordance for collapsed task items. Not part of the AST\n\t\t// mirror, so it is prepended after the children are reconciled.\n\t\tif (!data.isActive && ast.checked !== undefined) {\n\t\t\tconst checkbox = document.createElement('input');\n\t\t\tcheckbox.type = 'checkbox';\n\t\t\tcheckbox.checked = ast.checked;\n\t\t\tcheckbox.className = 'md-checkbox';\n\t\t\tconst onToggle = options?.onToggleCheckbox;\n\t\t\tif (onToggle) {\n\t\t\t\tconst wasChecked = ast.checked;\n\t\t\t\tcheckbox.addEventListener('mousedown', (e) => {\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tonToggle(ast, !wasChecked);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tcheckbox.disabled = true;\n\t\t\t}\n\t\t\tli.insertBefore(checkbox, li.firstChild);\n\t\t}\n\n\t\tsuper(data, li, children);\n\t}\n}\n\n/**\n * Reconcile a list item's children into `li`. A nested item carries its source\n * indentation as a leading `indent` glue before the bullet marker; that pair is\n * mounted together inside an absolutely-positioned `.md-list-gutter` span so the\n * indentation dots sit in the gutter *before* the bullet (matching the source\n * `␣␣- text`) while the item text stays at the content edge in both states.\n * Items without a leading indent (top-level bullets) mount their children\n * directly, keeping the bullet in the gutter via `.md-marker-listItemMarker`.\n *\n * The returned children array always mirrors `content` 1:1 and in source order,\n * so the source ↔ DOM mapping is unaffected by the gutter wrapper.\n */\nfunction _reconcileListItem(\n\tli: HTMLElement,\n\tcontent: readonly AnyViewData[],\n\tprevious: ListItemViewNode | undefined,\n\toptions: BlockViewOptions | undefined,\n): ViewNode[] {\n\tconst { paired, unused } = pairNodes(content, previous?.children ?? _NO_CHILDREN);\n\tconst children = content.map(d => createViewNode(d, options, paired.get(d)));\n\tfor (const u of unused) { u.dispose(); }\n\n\tconst hasIndentGutter = content.length >= 2\n\t\t&& content[0].kind === 'glue' && content[0].ast.glueKind === 'indent'\n\t\t&& content[1].kind === 'marker' && content[1].ast.markerKind === 'listItemMarker';\n\n\tif (!hasIndentGutter) {\n\t\t_patchDomNodes(li, children.map(c => c.mountNode));\n\t\treturn children;\n\t}\n\n\tconst first = li.firstElementChild;\n\tconst gutter = first && first.classList.contains('md-list-gutter')\n\t\t? first as HTMLElement\n\t\t: document.createElement('span');\n\tgutter.className = 'md-list-gutter';\n\t_patchDomNodes(gutter, [children[0].mountNode, children[1].mountNode]);\n\t_patchDomNodes(li, [gutter, ...children.slice(2).map(c => c.mountNode)]);\n\treturn children;\n}\n\n\n/**\n * A table row (`<tr>`). The delimiter row (`| --- | --- |`) gets\n * `md-table-delimiter-row` so the CSS can collapse/reveal it. After its cells\n * are reconciled, each cell the selection reaches ({@link TableCellViewData.isActive}\n * on a non-delimiter row) gets `md-table-cell-active`; because any change to a\n * cell's active state changes its view-data identity and so rebuilds the cell\n * fresh, a reused cell never carries a stale active class.\n */\nclass TableRowViewNode extends BlockViewNode<TableRowViewData> {\n\tconstructor(data: TableRowViewData, options: BlockViewOptions | undefined, previous: TableRowViewNode | undefined) {\n\t\tconst tr = previous?.element ?? document.createElement('tr');\n\t\tif (data.isDelimiter) { tr.classList.add('md-table-delimiter-row'); }\n\t\tconst children = reconcileDomChildren(tr, data.content, previous?.children, _buildChild(options));\n\t\tif (!data.isDelimiter) {\n\t\t\tdata.content.forEach((cellData, i) => {\n\t\t\t\tif (cellData.kind === 'tableCell' && cellData.isActive) {\n\t\t\t\t\t(children[i] as BlockViewNode).element.classList.add('md-table-cell-active');\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tsuper(data, tr, children);\n\t}\n}\n\nclass InlineCodeViewNode extends BlockViewNode<InlineCodeViewData> {\n\tconstructor(data: InlineCodeViewData, options: BlockViewOptions | undefined, previous: InlineCodeViewNode | undefined) {\n\t\tconst code = previous?.element ?? document.createElement('code');\n\t\tconst children = reconcileDomChildren(code, data.content, previous?.children, _inlineChild(options));\n\t\tsuper(data, code, children);\n\t}\n}\n\nclass InlineMathViewNode extends BlockViewNode<InlineMathViewData> {\n\tconstructor(data: InlineMathViewData, options: BlockViewOptions | undefined, previous: InlineMathViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = 'md-inline-math';\n\t\t\tconst children = reconcileDomChildren(span, data.content, previous?.children, _inlineChild(options));\n\t\t\tsuper(data, span, children);\n\t\t\treturn;\n\t\t}\n\t\tconst contentMarker = data.content.find(\n\t\t\t(c): c is MarkerViewData => c.kind === 'marker' && c.ast.markerKind === 'content',\n\t\t);\n\t\tconst latex = contentMarker?.ast.content ?? '';\n\t\tconst rendering = options?.renderMath?.({\n\t\t\tlatex,\n\t\t\tdisplayMode: false,\n\t\t\tclassName: 'md-inline-math',\n\t\t\tnodeLength: data.ast.length,\n\t\t\tcontentStart: _mathContentOffset(data.ast.content),\n\t\t});\n\t\tif (rendering) {\n\t\t\tsuper(data, rendering.dom, _buildMathSegmentChildren(data.ast, rendering.segments, data.ast.length));\n\t\t\treturn;\n\t\t}\n\t\tconst span = document.createElement('span');\n\t\tspan.className = 'md-inline-math';\n\t\ttry {\n\t\t\tkatex.render(latex, span, { throwOnError: false });\n\t\t} catch {\n\t\t\tspan.textContent = latex;\n\t\t}\n\t\tsuper(data, span, _NO_CHILDREN);\n\t}\n}\n\nclass LinkViewNode extends BlockViewNode<LinkViewData> {\n\tconstructor(data: LinkViewData, options: BlockViewOptions | undefined, previous: LinkViewNode | undefined) {\n\t\tconst a = (previous?.element ?? document.createElement('a')) as HTMLAnchorElement;\n\t\tif (_isSafeUrl(data.ast.url)) {\n\t\t\ta.href = data.ast.url;\n\t\t\ta.dataset.mdUrl = data.ast.url;\n\t\t} else {\n\t\t\ta.removeAttribute('href');\n\t\t\tdelete a.dataset.mdUrl;\n\t\t}\n\t\t// Wire the open-on-click affordance once per element (it persists across\n\t\t// reconciliation; the URL it opens is read live from `dataset.mdUrl`).\n\t\t// A plain click opens the link only while its block is inactive; once the\n\t\t// block is active (source shown) opening requires Ctrl/Cmd so a plain\n\t\t// click can place the caret. Stopping propagation keeps the controller\n\t\t// from treating an opening click as a caret move.\n\t\tif (!previous) {\n\t\t\ta.addEventListener('mousedown', (e) => {\n\t\t\t\tconst url = a.dataset.mdUrl;\n\t\t\t\tif (!url) { return; }\n\t\t\t\tconst blockActive = a.closest('.md-block-active') !== null;\n\t\t\t\tif (blockActive && !(e.ctrlKey || e.metaKey)) { return; }\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tif (options?.onOpenLink) { options.onOpenLink(url, e); }\n\t\t\t\telse { window.open(url, '_blank', 'noopener'); }\n\t\t\t});\n\t\t}\n\t\tconst children = reconcileDomChildren(a, data.content, previous?.children, _buildChild(options));\n\t\tsuper(data, a, children);\n\t}\n}\n\nclass ImageViewNode extends BlockViewNode<ImageViewData> {\n\tconstructor(data: ImageViewData, options: BlockViewOptions | undefined, previous: ImageViewNode | undefined) {\n\t\tconst ast = data.ast;\n\t\tif (data.showMarkup) {\n\t\t\tconst span = document.createElement('span');\n\t\t\tspan.className = 'md-image-source';\n\t\t\tconst children = reconcileDomChildren(span, data.content, previous?.children, _buildChild(options));\n\t\t\tsuper(data, span, children);\n\t\t\treturn;\n\t\t}\n\t\tconst img = document.createElement('img');\n\t\tif (_isSafeUrl(ast.url)) { img.src = ast.url; }\n\t\timg.alt = ast.alt;\n\t\tsuper(data, img, _NO_CHILDREN);\n\t}\n}\n\n/**\n * Pair each new node with the previous view node that should render it, then\n * report the previous nodes left over. Pairing is by {@link AstNode.id} — the\n * stable identity the parser mints on construction and carries across edits (see\n * `reconcile`). One key covers both reuse cases uniformly: an unchanged subtree\n * keeps its node object (so, trivially, its id), and an edited node — e.g. a\n * code block whose content changed — is rebuilt as a fresh object cloned with\n * its previous id. So the previous view node (which owns any DOM and, for a code\n * block, the highlighting session) is paired with the new view-data derived from\n * it, and that DOM/session is adopted rather than rebuilt.\n *\n * Previous nodes whose id no longer appears are returned in `unused`; the caller\n * disposes them (freeing any session they still own).\n */\nexport function pairNodes(\n\tnewData: readonly AnyViewData[],\n\tprevNodes: readonly ViewNode[],\n): { paired: Map<AnyViewData, ViewNode>; unused: ViewNode[] } {\n\tconst byId = new Map<number, ViewNode>();\n\tfor (const n of prevNodes) { byId.set(n.ast.id, n); }\n\n\tconst paired = new Map<AnyViewData, ViewNode>();\n\tfor (const d of newData) {\n\t\tconst n = byId.get(d.ast.id);\n\t\tif (n) { paired.set(d, n); byId.delete(d.ast.id); }\n\t}\n\n\treturn { paired, unused: [...byId.values()] };\n}\n\nfunction _isSafeUrl(url: string): boolean {\n\treturn !url.trim().toLowerCase().startsWith('javascript:');\n}\n","import type { AnyViewData, DocumentViewData, PendingParagraphViewData } from '../viewData.js';\nimport type { DocumentAstNode } from '../../parser/ast.js';\nimport { BlockViewNode, createViewNode, pairNodes, _patchDomNodes, type BlockViewOptions } from './blockView.js';\nimport { ViewNode } from './viewNode.js';\n\n/** A mounted block: its view node paired with where it starts in the source. */\nexport interface DocumentBlock {\n readonly node: BlockViewNode;\n readonly absoluteStart: number;\n}\n\n/**\n * Immutable view of the document's block sequence — the document-level\n * analogue of {@link BlockViewNode}. Each {@link create} maps the\n * {@link DocumentViewData} (the AST overlaid with selection-derived flags) to\n * the block sequence, reusing the previous node's blocks by view-data identity,\n * rebuilding only what changed, and patching its {@link contentDomNode}'s\n * children to match.\n *\n * Like a {@link BlockViewNode}, it owns its DOM: the first `create` allocates\n * the content element, and every later `create` keeps the previous node's\n * element rather than making a new one. The element is therefore stable\n * across rebuilds:\n *\n * create(viewData, …, old).contentDomNode === old.contentDomNode\n *\n * so a parent can mount it once and never re-parent it.\n *\n * Because it is rebuilt rather than mutated, {@link EditorView} can hold the\n * whole block cache as one value and simply swap it each frame, instead of\n * carrying a mutable entry array and the reconcile bookkeeping itself.\n *\n * It is itself a {@link ViewNode} (the root of the view-node tree), so DOM ↔\n * source mapping such as {@link ViewNode.resolveSource} is inherited: a hit on\n * any descendant lifts up the parent chain to here, yielding an absolute\n * document offset.\n */\nexport class DocumentViewNode extends ViewNode {\n static create(\n viewData: DocumentViewData,\n options: BlockViewOptions | undefined,\n previous: DocumentViewNode | undefined,\n ): DocumentViewNode {\n const contentDomNode = previous?.contentDomNode ?? document.createElement('div');\n const activeByView = new Map<AnyViewData, boolean>(\n viewData.children.filter(c => c.kind === 'block').map(c => [c.view as AnyViewData, c.isActive]),\n );\n\n // Build every child (blocks and any leading/standalone glue) in source\n // order, pairing each with the previous node that rendered it so reused\n // nodes keep their DOM, and disposing the leftovers. A block's trailing\n // `blockGap` glue is part of the block's own content now (the parser\n // attributes it there), so it is mounted at the end of the block's last\n // line by the block's own reconciliation — no document-level reparenting.\n const prevNodes = previous?.children;\n const childViews = viewData.children.map(c => c.view);\n const { paired, unused } = pairNodes(childViews as readonly AnyViewData[], prevNodes ?? _NO_NODES);\n let pendingElement: HTMLElement | undefined;\n const nodes = childViews.map((view, i) => {\n const prev = paired.get(view as AnyViewData);\n // The transient empty paragraph is not an AST-backed block, so it is\n // built here rather than through `createViewNode`: a bare `<p><br></p>`\n // the caret floats over (positioned by a dedicated rect, not the\n // visual-line map). It reuses its previous element while it stays armed.\n if (viewData.children[i].kind === 'pendingParagraph') {\n const node = prev instanceof PendingParagraphViewNode\n ? prev\n : new PendingParagraphViewNode(view as PendingParagraphViewData);\n pendingElement = node.element;\n return node;\n }\n const node = createViewNode(view as AnyViewData, options, prev);\n // The active/markers-hidden classes are a top-level concern (the\n // block's own markers are handled within its subtree), so they are\n // applied here rather than inside the node. Glue carries no such\n // classes, so it is left untouched.\n if (viewData.children[i].kind === 'block') {\n const isActive = activeByView.get(view as AnyViewData);\n if (isActive !== undefined) {\n (node as BlockViewNode).element.classList.toggle('md-block-active', isActive);\n (node as BlockViewNode).element.classList.toggle('md-markers-hidden', !isActive);\n }\n }\n return node;\n });\n for (const u of unused) { u.dispose(); }\n\n _patchDomNodes(contentDomNode, nodes.map(n => n.mountNode));\n\n const blocks: DocumentBlock[] = [];\n viewData.children.forEach((c, i) => {\n if (c.kind === 'block') { blocks.push({ node: nodes[i] as BlockViewNode, absoluteStart: c.absoluteStart }); }\n });\n return new DocumentViewNode(viewData.ast, contentDomNode, blocks, nodes, pendingElement);\n }\n\n private constructor(\n ast: DocumentAstNode,\n contentDomNode: HTMLElement,\n readonly blocks: readonly DocumentBlock[],\n /** Every mounted child (blocks and glue) in source order. */\n nodes: readonly ViewNode[],\n /** The transient empty-paragraph element, when one is armed. */\n readonly pendingElement?: HTMLElement,\n ) {\n super(ast, contentDomNode, nodes);\n }\n\n /** The stable content element this document mounts its children into. */\n get contentDomNode(): HTMLElement { return this.dom as HTMLElement; }\n}\n\n/**\n * The mounted transient empty paragraph: a `<p class=\"md-pending-paragraph\">`\n * holding a single `<br>` so it occupies a line's height. It is a leaf view\n * node with no inline content, so it contributes no entry to the visual-line\n * map — the caret is drawn over it from {@link DocumentViewNode.pendingElement}'s\n * geometry instead.\n */\nclass PendingParagraphViewNode extends ViewNode {\n readonly element: HTMLElement;\n constructor(view: PendingParagraphViewData) {\n const p = document.createElement('p');\n p.className = 'md-block md-paragraph md-pending-paragraph';\n p.appendChild(document.createElement('br'));\n super(view.ast, p);\n this.element = p;\n }\n}\n\nconst _NO_NODES: readonly ViewNode[] = [];\n","import { Point2D } from '../../core/geometry.js';\n\n/**\n * A DOM node paired with a caret offset inside it. The node is an arbitrary\n * {@link globalThis.Node} (a Text node for a caret inside text, an Element for\n * a hit on element-only content), and `offset` is the caret offset within it.\n */\nexport interface DomPosition {\n readonly node: globalThis.Node;\n readonly offset: number;\n}\n\n/**\n * Client-coordinate point → the DOM caret position under it, using the\n * platform hit-test API (`caretPositionFromPoint`, with a `caretRangeFromPoint`\n * fallback). Returns `undefined` when the point hits nothing.\n */\nexport function caretDomPositionFromPoint(point: Point2D): DomPosition | undefined {\n const api = document as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: globalThis.Node; offset: number } | null;\n caretRangeFromPoint?: (x: number, y: number) => Range | null;\n };\n if (api.caretPositionFromPoint) {\n const result = api.caretPositionFromPoint(point.x, point.y);\n return result ? { node: result.offsetNode, offset: result.offset } : undefined;\n }\n const range = api.caretRangeFromPoint?.(point.x, point.y);\n if (!range) { return undefined; }\n return { node: range.startContainer, offset: range.startOffset };\n}\n","/**\n * The view-data overlay over the {@link AstNode} tree.\n *\n * Every AST kind has a parallel `*ViewData` class that mirrors its child\n * structure but carries, on top, the *selection-derived* render inputs the\n * renderer needs (which markers are visible, which list item / table cell is\n * active, whether an inline-math / image / code block shows its source or its\n * rendered form). Scalars (`level`, `url`, `language`, …) are read through the\n * referenced {@link AstNode}, never copied, so the overlay stays a thin layer\n * and the two trees can never drift.\n *\n * Splitting these inputs out makes a selection change a pure function over the\n * *unchanged* AST: only the {@link DocumentViewData} is rebuilt (cheap — no\n * DOM), and inactive blocks reuse the previous frame's view-data subtree by\n * identity (see {@link buildDocumentViewData}), so the eventual diff against\n * the rendered tree bottoms out at the one or two nodes whose flags flipped.\n */\n\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { findActiveListItemIndex } from '../model/cursorNavigation.js';\nimport { GlueAstNode } from '../parser/ast.js';\nimport type {\n\tAnyAstNode, AstNode, BlockAstNode, CodeBlockAstNode, DocumentAstNode, EmphasisAstNode,\n\tHeadingAstNode, ImageAstNode, InlineCodeAstNode, InlineMathAstNode,\n\tLinkAstNode, ListAstNode, ListItemAstNode, MarkerAstNode, MathBlockAstNode,\n\tParagraphAstNode, StrikethroughAstNode, StrongAstNode, TableAstNode, TableCellAstNode,\n\tTableRowAstNode, TextAstNode, ThematicBreakAstNode, BlockQuoteAstNode,\n} from '../parser/ast.js';\n\n// ---------------------------------------------------------------------------\n// Document\n// ---------------------------------------------------------------------------\n\n/**\n * The view-data root. Mirrors {@link DocumentAstNode}: {@link blocks} holds only\n * its top-level blocks (each wrapped with where it starts and whether it is\n * active), while {@link children} additionally interleaves the rendered\n * document-level glue (the blank lines between blocks) in source order.\n */\nexport class DocumentViewData {\n\treadonly kind = 'document';\n\tconstructor(\n\t\treadonly ast: DocumentAstNode,\n\t\treadonly blocks: readonly DocumentBlockViewData[],\n\t\t/**\n\t\t * Blocks and inter-block glue interleaved in source order — the actual\n\t\t * mount sequence. {@link blocks} is the block-only projection used for\n\t\t * measurement and selection.\n\t\t */\n\t\treadonly children: readonly DocumentChildViewData[],\n\t) { }\n}\n\n/** A top-level block plus the document-level state the renderer applies to it. */\nexport interface DocumentBlockViewData {\n\treadonly ast: BlockAstNode;\n\treadonly absoluteStart: number;\n\t/** Whether the selection reaches this block (drives `md-block-active`). */\n\treadonly isActive: boolean;\n\treadonly view: BlockViewData;\n}\n\n/** A mounted document child: a block, a run of inter-block glue, or the\n * transient empty paragraph (see {@link PendingParagraphViewData}). */\nexport interface DocumentChildViewData {\n\treadonly absoluteStart: number;\n\t/** For a block: selection reaches it. For glue: always false (unowned, hidden). */\n\treadonly isActive: boolean;\n\treadonly view: BlockViewData | GlueViewData | PendingParagraphViewData;\n\treadonly kind: 'block' | 'glue' | 'pendingParagraph';\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockViewData =\n\t| HeadingViewData | ParagraphViewData | CodeBlockViewData | MathBlockViewData\n\t| ThematicBreakViewData | BlockQuoteViewData | ListViewData | TableViewData;\n\nexport class HeadingViewData {\n\treadonly kind = 'heading';\n\tconstructor(readonly ast: HeadingAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ParagraphViewData {\n\treadonly kind = 'paragraph';\n\tconstructor(readonly ast: ParagraphAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\n/**\n * View-data for the transient empty paragraph (see `PendingParagraph` in the\n * model). It carries only the throwaway {@link ParagraphAstNode} that gives the\n * rendered blank line a stable identity across frames; it has no content and is\n * never measured or part of the selection geometry — the caret is positioned\n * over it via a dedicated rect, not via the visual-line map.\n */\nexport class PendingParagraphViewData {\n\treadonly kind = 'pendingParagraph';\n\tconstructor(readonly ast: ParagraphAstNode) { }\n}\n\nexport class CodeBlockViewData {\n\treadonly kind = 'codeBlock';\n\tconstructor(\n\t\treadonly ast: CodeBlockAstNode,\n\t\t/** Active: render the fenced source; inactive: the (custom/highlighted) block. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class MathBlockViewData {\n\treadonly kind = 'mathBlock';\n\tconstructor(\n\t\treadonly ast: MathBlockAstNode,\n\t\t/** Active: render the source; inactive: the KaTeX output. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class BlockQuoteViewData {\n\treadonly kind = 'blockQuote';\n\tconstructor(readonly ast: BlockQuoteAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ListViewData {\n\treadonly kind = 'list';\n\tconstructor(readonly ast: ListAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class TableViewData {\n\treadonly kind = 'table';\n\tconstructor(readonly ast: TableAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\n// ---------------------------------------------------------------------------\n// Inlines\n// ---------------------------------------------------------------------------\n\nexport type InlineViewData =\n\t| TextViewData | StrongViewData | EmphasisViewData | StrikethroughViewData\n\t| InlineCodeViewData | InlineMathViewData | LinkViewData | ImageViewData;\n\nexport class StrongViewData {\n\treadonly kind = 'strong';\n\tconstructor(readonly ast: StrongAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class EmphasisViewData {\n\treadonly kind = 'emphasis';\n\tconstructor(readonly ast: EmphasisAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class StrikethroughViewData {\n\treadonly kind = 'strikethrough';\n\tconstructor(readonly ast: StrikethroughAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class InlineCodeViewData {\n\treadonly kind = 'inlineCode';\n\tconstructor(readonly ast: InlineCodeAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class InlineMathViewData {\n\treadonly kind = 'inlineMath';\n\tconstructor(\n\t\treadonly ast: InlineMathAstNode,\n\t\t/** Active: render the `$…$` source; inactive: the KaTeX output. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class LinkViewData {\n\treadonly kind = 'link';\n\tconstructor(readonly ast: LinkAstNode, readonly content: readonly AnyViewData[]) { }\n}\n\nexport class ImageViewData {\n\treadonly kind = 'image';\n\tconstructor(\n\t\treadonly ast: ImageAstNode,\n\t\t/** Active: render the `` source; inactive: the `<img>`. */\n\t\treadonly showMarkup: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\n// ---------------------------------------------------------------------------\n// Containers without their own AST union (list item, table row/cell)\n// ---------------------------------------------------------------------------\n\nexport class ListItemViewData {\n\treadonly kind = 'listItem';\n\tconstructor(\n\t\treadonly ast: ListItemAstNode,\n\t\t/** Whether the selection reaches this item (reveals its markers). */\n\t\treadonly isActive: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t\t/** 1-based list nesting depth, used to size the indentation gutter. */\n\t\treadonly level: number,\n\t) { }\n}\n\nexport class TableRowViewData {\n\treadonly kind = 'tableRow';\n\tconstructor(\n\t\treadonly ast: TableRowAstNode,\n\t\treadonly isDelimiter: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class TableCellViewData {\n\treadonly kind = 'tableCell';\n\tconstructor(\n\t\treadonly ast: TableCellAstNode,\n\t\t/** Whether the selection reaches this cell (reveals its inline markers). */\n\t\treadonly isActive: boolean,\n\t\t/** Whether the owning table is active (reveals the structural pipes). */\n\t\treadonly showTableGlue: boolean,\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\n// ---------------------------------------------------------------------------\n// Leaves\n// ---------------------------------------------------------------------------\n\nexport class TextViewData {\n\treadonly kind = 'text';\n\t/**\n\t * Whether non-obvious whitespace in this text is revealed (block is active).\n\t * `leftWordBoundary`/`rightWordBoundary` say whether the inline sibling on\n\t * that side ends/starts with visible word content (e.g. inline code, a link,\n\t * emphasis); a single space touching such a sibling is obvious and stays\n\t * undecorated, just like a space between two words within this leaf.\n\t */\n\tconstructor(\n\t\treadonly ast: TextAstNode,\n\t\treadonly showWhitespace: boolean,\n\t\treadonly leftWordBoundary: boolean = false,\n\t\treadonly rightWordBoundary: boolean = false,\n\t) { }\n}\n\nexport class ThematicBreakViewData {\n\treadonly kind = 'thematicBreak';\n\tconstructor(\n\t\treadonly ast: ThematicBreakAstNode,\n\t\t/** Active: reveal the source markup (`---`) instead of the rendered rule. */\n\t\treadonly showMarkup: boolean,\n\t\t/** Marker (and any absorbed trailing glue), rendered only when active. */\n\t\treadonly content: readonly AnyViewData[],\n\t) { }\n}\n\nexport class MarkerViewData {\n\treadonly kind = 'marker';\n\tconstructor(readonly ast: MarkerAstNode, readonly visible: boolean) { }\n}\n\nexport class GlueViewData {\n\treadonly kind = 'glue';\n\tconstructor(\n\t\treadonly ast: GlueAstNode,\n\t\treadonly visible: boolean,\n\t\t/**\n\t\t * Whether a source newline in this glue gets a visible `↵`. True only in\n\t\t * inline flow, where the newline collapses to a space and the `↵` reveals\n\t\t * the line ending hiding there; between block-level siblings (list items,\n\t\t * block children) the break is already visible, so no `↵` is drawn.\n\t\t */\n\t\treadonly decorateNewline: boolean,\n\t) { }\n}\n\nexport type AnyViewData =\n\t| DocumentViewData | BlockViewData | InlineViewData\n\t| ListItemViewData | TableRowViewData | TableCellViewData\n\t| MarkerViewData | GlueViewData;\n\n// ---------------------------------------------------------------------------\n// Builder\n// ---------------------------------------------------------------------------\n\n/** The selection-derived inputs threaded down while building one subtree. */\ninterface BuildCtx {\n\t/** Whether markers/source are revealed in this node's region. */\n\treadonly showMarkup: boolean;\n\t/** Whether `tableCellGlue` pipes are forced visible (the owning table is active). */\n\treadonly showTableGlue: boolean;\n\t/** Selection range relative to the node being built, or `undefined` when inactive. */\n\treadonly selectionInNode: OffsetRange | undefined;\n\t/**\n\t * Whether the node being built lays its children out in inline flow (a\n\t * paragraph, heading, table cell, or an inline wrapper). A source newline\n\t * there collapses to a space and so earns a visible `↵`; in block flow the\n\t * line break is already visible and the newline gets none. Defaults to false.\n\t */\n\treadonly inlineFlow?: boolean;\n\t/** 1-based nesting depth of the list currently being built (0 outside lists). */\n\treadonly listLevel?: number;\n}\n\nconst _INACTIVE: BuildCtx = { showMarkup: false, showTableGlue: false, selectionInNode: undefined };\n\n/** Descend into inline flow, where a source newline collapses to a space (so its `↵` is shown). */\nfunction _inline(ctx: BuildCtx): BuildCtx {\n\treturn ctx.inlineFlow ? ctx : { ...ctx, inlineFlow: true };\n}\n\n/**\n * Map the parsed document + active/selection state to its view-data tree.\n *\n * Top-level blocks are mirrored into {@link DocumentViewData.blocks}. A block's\n * trailing blank lines are attributed by the parser to the block itself (a\n * `blockGap`/`blockBreak` glue at the end of its content), and a leading indent\n * to the block it precedes (its `leadingTrivia`), so both are built as part of\n * the block and revealed only when that block is active — no neighbour scan. The\n * only glue that survives at the document level is an unowned leading gap before\n * the first block; it is mirrored into {@link DocumentViewData.children} and\n * stays collapsed (never revealed), like the gap between two blocks.\n * An inactive block's view-data is a pure function of its AST, so when `previous`\n * holds a view-data for the same block object (the parser preserves identity for\n * unchanged subtrees) that was *also* inactive, the whole subtree is reused by\n * identity — the common case for a selection move, making it O(active blocks).\n */\nexport function buildDocumentViewData(\n\tdoc: DocumentAstNode,\n\tactiveBlocks: ReadonlySet<BlockAstNode>,\n\tselectionRange: OffsetRange | undefined,\n\tprevious: DocumentViewData | undefined,\n\tpending?: { readonly anchorBlock: BlockAstNode; readonly ast: ParagraphAstNode },\n): DocumentViewData {\n\tconst prevByAst = new Map<AstNode, DocumentChildViewData>();\n\tif (previous) {\n\t\tfor (const c of previous.children) { prevByAst.set(c.view.ast, c); }\n\t}\n\n\tconst content = doc.content;\n\tconst blockSet = new Set<BlockAstNode>(doc.blocks);\n\n\tconst blocks: DocumentBlockViewData[] = [];\n\tconst children: DocumentChildViewData[] = [];\n\tlet pos = 0;\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst child = content[i];\n\t\tif (blockSet.has(child as BlockAstNode)) {\n\t\t\tconst block = child as BlockAstNode;\n\t\t\tconst isActive = activeBlocks.has(block);\n\t\t\tconst prev = prevByAst.get(block);\n\t\t\tlet view: BlockViewData;\n\t\t\tif (!isActive) {\n\t\t\t\t// Fast path: an unchanged block that stays inactive keeps its whole\n\t\t\t\t// subtree by identity without rebuilding anything (the O(active) case).\n\t\t\t\tview = prev && !prev.isActive\n\t\t\t\t\t? prev.view as BlockViewData\n\t\t\t\t\t: _buildBlock(block, _INACTIVE, prev?.view as AnyViewData | undefined);\n\t\t\t} else {\n\t\t\t\tconst selectionInNode = selectionRange\n\t\t\t\t\t? new OffsetRange(\n\t\t\t\t\t\tMath.max(0, selectionRange.start - pos),\n\t\t\t\t\t\tMath.min(block.length, selectionRange.endExclusive - pos),\n\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\t\t\t\tview = _buildBlock(block, { showMarkup: true, showTableGlue: false, selectionInNode }, prev?.view as AnyViewData | undefined);\n\t\t\t}\n\t\t\tblocks.push({ ast: block, absoluteStart: pos, isActive, view });\n\t\t\tchildren.push({ absoluteStart: pos, isActive, view, kind: 'block' });\n\t\t\t// Render the transient empty paragraph directly after its anchor. It\n\t\t\t// is intentionally absent from `blocks` so it never participates in\n\t\t\t// measurement or selection geometry.\n\t\t\tif (pending && pending.anchorBlock === block) {\n\t\t\t\tchildren.push({\n\t\t\t\t\tabsoluteStart: pos + block.length,\n\t\t\t\t\tisActive: true,\n\t\t\t\t\tview: new PendingParagraphViewData(pending.ast),\n\t\t\t\t\tkind: 'pendingParagraph',\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (child instanceof GlueAstNode) {\n\t\t\t// Any glue that survives at the document level is unowned inter-block\n\t\t\t// glue (a leading gap before the first block): every gap that trails a\n\t\t\t// block is attributed to that block by the parser, and every leading\n\t\t\t// indent to the block it precedes, so the only glue left here has no\n\t\t\t// owning block. With no owner it is never revealed — it stays collapsed\n\t\t\t// in both states, exactly like the gap between two blocks.\n\t\t\tconst prev = prevByAst.get(child);\n\t\t\tconst view = _reuseOr(prev?.view as AnyViewData | undefined, new GlueViewData(child, false, false));\n\t\t\tchildren.push({ absoluteStart: pos, isActive: false, view, kind: 'glue' });\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new DocumentViewData(doc, blocks, children);\n}\n\nfunction _buildBlock(block: BlockAstNode, ctx: BuildCtx, prev: AnyViewData | undefined): BlockViewData {\n\treturn _buildNode(block, ctx, prev) as BlockViewData;\n}\n\n/**\n * Build the view-data for one node, threading the previous frame's view-data\n * for the same node so identity can be preserved bottom-up: a freshly-built\n * candidate that has the same ast, the same flags, and identity-equal children\n * as `prev` *is* `prev` (see {@link _reuseOr}). Because unchanged children are\n * already shared this way, the comparison stays O(children), and an unchanged\n * subtree keeps one stable view-data object across frames — which is exactly\n * what lets the renderer reuse its DOM by a single identity check.\n */\nfunction _buildNode(astNode: AstNode, ctx: BuildCtx, prev: AnyViewData | undefined, neighbors?: _Neighbors): AnyViewData {\n\tconst node = astNode as AnyAstNode;\n\tswitch (node.kind) {\n\t\tcase 'text': return _reuseOr(prev, new TextViewData(node, ctx.showMarkup, neighbors?.left ?? false, neighbors?.right ?? false));\n\t\t// The trailing gap is revealed as `↵` glyphs by virtue of its `blockGap`\n\t\t// kind (see `GlueViewNode`), so the break needs no inline-flow opt-in.\n\t\tcase 'thematicBreak': return _reuseOr(prev, new ThematicBreakViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'marker': return _reuseOr(prev, new MarkerViewData(node, _markerVisible(node.markerKind, ctx)));\n\t\tcase 'glue': return _reuseOr(prev, new GlueViewData(node, _glueVisible(node.glueKind, ctx), ctx.inlineFlow ?? false));\n\t\tcase 'heading': return _reuseOr(prev, new HeadingViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'paragraph': return _reuseOr(prev, new ParagraphViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'codeBlock': return _reuseOr(prev, new CodeBlockViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'mathBlock': return _reuseOr(prev, new MathBlockViewData(node, ctx.showMarkup, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'blockQuote': return _reuseOr(prev, new BlockQuoteViewData(node, _buildChildren(node.children, ctx, prev)));\n\t\tcase 'list': return _reuseOr(prev, _buildList(node, ctx, prev));\n\t\tcase 'listItem': return _reuseOr(prev, _buildListItem(node, ctx, prev));\n\t\tcase 'table': return _reuseOr(prev, _buildTable(node, ctx, prev));\n\t\tcase 'tableRow': return _reuseOr(prev, _buildTableRow(node, ctx, false, prev));\n\t\tcase 'tableCell': return _reuseOr(prev, _buildTableCell(node, ctx.showMarkup, ctx.showTableGlue, ctx.selectionInNode, prev));\n\t\tcase 'strong': return _reuseOr(prev, new StrongViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'emphasis': return _reuseOr(prev, new EmphasisViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'strikethrough': return _reuseOr(prev, new StrikethroughViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'inlineCode': return _reuseOr(prev, new InlineCodeViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'inlineMath': return _reuseOr(prev, new InlineMathViewData(node, ctx.showMarkup, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'link': return _reuseOr(prev, new LinkViewData(node, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'image': return _reuseOr(prev, new ImageViewData(node, ctx.showMarkup, _buildChildren(node.children, _inline(ctx), prev)));\n\t\tcase 'document': return buildDocumentViewData(node, new Set(), OffsetRange.ofLength(0), undefined);\n\t}\n}\n\n/** Children of a view-data node, for identity comparison and prev-matching. */\nfunction _childrenOf(node: AnyViewData): readonly AnyViewData[] {\n\tif (node.kind === 'document') { return node.blocks.map(b => b.view); }\n\treturn 'content' in node ? node.content : _NO_CHILDREN;\n}\n\nconst _NO_CHILDREN: readonly AnyViewData[] = [];\n\n/** Index the previous node's children by their ast, so each new child finds its match. */\nfunction _prevChildByAst(prev: AnyViewData | undefined): ReadonlyMap<AstNode, AnyViewData> | undefined {\n\tif (!prev) { return undefined; }\n\tconst map = new Map<AstNode, AnyViewData>();\n\tfor (const c of _childrenOf(prev)) { map.set(c.ast, c); }\n\treturn map;\n}\n\n/**\n * Reuse `prev` in place of the freshly-built `cand` when the two are\n * indistinguishable: same kind, same ast, equal flags, and identity-equal\n * children (unchanged children are already shared, so this is a cheap `===`\n * sweep). Returning `prev` keeps the whole subtree's view-data object stable.\n */\nfunction _reuseOr<T extends AnyViewData>(prev: AnyViewData | undefined, cand: T): T {\n\tif (prev && prev.kind === cand.kind && prev.ast === cand.ast && _flagsEqual(prev, cand)) {\n\t\tconst a = _childrenOf(prev);\n\t\tconst b = _childrenOf(cand);\n\t\tif (a.length === b.length && a.every((c, i) => c === b[i])) { return prev as T; }\n\t}\n\treturn cand;\n}\n\n/** Compare the selection-derived flags of two same-kind view-data nodes. */\nfunction _flagsEqual(a: AnyViewData, b: AnyViewData): boolean {\n\tswitch (a.kind) {\n\t\tcase 'text': return a.showWhitespace === (b as TextViewData).showWhitespace\n\t\t\t&& a.leftWordBoundary === (b as TextViewData).leftWordBoundary\n\t\t\t&& a.rightWordBoundary === (b as TextViewData).rightWordBoundary;\n\t\tcase 'marker': return a.visible === (b as MarkerViewData).visible;\n\t\tcase 'glue': return a.visible === (b as GlueViewData).visible\n\t\t\t&& a.decorateNewline === (b as GlueViewData).decorateNewline;\n\t\tcase 'thematicBreak': return a.showMarkup === (b as ThematicBreakViewData).showMarkup;\n\t\tcase 'codeBlock': return a.showMarkup === (b as CodeBlockViewData).showMarkup;\n\t\tcase 'mathBlock': return a.showMarkup === (b as MathBlockViewData).showMarkup;\n\t\tcase 'inlineMath': return a.showMarkup === (b as InlineMathViewData).showMarkup;\n\t\tcase 'image': return a.showMarkup === (b as ImageViewData).showMarkup;\n\t\tcase 'listItem': return a.isActive === (b as ListItemViewData).isActive;\n\t\tcase 'tableCell': {\n\t\t\tconst o = b as TableCellViewData;\n\t\t\treturn a.isActive === o.isActive && a.showTableGlue === o.showTableGlue;\n\t\t}\n\t\tcase 'tableRow': return a.isDelimiter === (b as TableRowViewData).isDelimiter;\n\t\tdefault: return true;\n\t}\n}\n\n/** Build children against the same ctx — plain containers do not shift the selection. */\nfunction _buildChildren(children: readonly AstNode[], ctx: BuildCtx, prev: AnyViewData | undefined): AnyViewData[] {\n\tconst prevByAst = _prevChildByAst(prev);\n\treturn children.map((c, i) => {\n\t\tconst neighbors = c.kind === 'text'\n\t\t\t? {\n\t\t\t\tleft: i > 0 && _edgeIsWordContent(children[i - 1], 'end'),\n\t\t\t\tright: i < children.length - 1 && _edgeIsWordContent(children[i + 1], 'start'),\n\t\t\t}\n\t\t\t: undefined;\n\t\treturn _buildNode(c, ctx, prevByAst?.get(c), neighbors);\n\t});\n}\n\ninterface _Neighbors { readonly left: boolean; readonly right: boolean; }\n\n/**\n * Whether `node`'s `start`/`end` edge renders as visible word content — so a\n * single space touching it reads as an ordinary inter-word space. Inline\n * wrappers (code, math, links, images, emphasis, …) always present a visible\n * glyph at both edges; a text run depends on its own edge character.\n */\nfunction _edgeIsWordContent(node: AstNode, side: 'start' | 'end'): boolean {\n\tswitch (node.kind) {\n\t\tcase 'text': {\n\t\t\tconst c = (node as TextAstNode).content;\n\t\t\tconst ch = side === 'end' ? c[c.length - 1] : c[0];\n\t\t\treturn ch !== undefined && ch !== ' ' && ch !== '\\t' && ch !== '\\n' && ch !== '\\r';\n\t\t}\n\t\tcase 'inlineCode':\n\t\tcase 'inlineMath':\n\t\tcase 'link':\n\t\tcase 'image':\n\t\tcase 'strong':\n\t\tcase 'emphasis':\n\t\tcase 'strikethrough':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction _markerVisible(markerKind: string, ctx: BuildCtx): boolean {\n\treturn ctx.showMarkup || (markerKind === 'tableCellGlue' && ctx.showTableGlue);\n}\n\nfunction _glueVisible(glueKind: string | undefined, ctx: BuildCtx): boolean {\n\treturn ctx.showMarkup || (glueKind === 'tableCellGlue' && ctx.showTableGlue);\n}\n\n/**\n * A list reveals each item's markers only when the selection reaches it, so it\n * computes which items intersect the selection and builds each with the\n * selection range shifted to its own start.\n */\nfunction _buildList(list: ListAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): ListViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst activeItems = _activeItemIndices(list, ctx);\n\tconst itemSet = new Set<ListItemAstNode>(list.items);\n\tconst itemLevel = (ctx.listLevel ?? 0) + 1;\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of list.children) {\n\t\tif (itemSet.has(child as ListItemAstNode)) {\n\t\t\tconst item = child as ListItemAstNode;\n\t\t\tconst isActive = activeItems.has(list.items.indexOf(item));\n\t\t\tconst itemCtx: BuildCtx = {\n\t\t\t\tshowMarkup: isActive,\n\t\t\t\tshowTableGlue: false,\n\t\t\t\tselectionInNode: isActive && ctx.selectionInNode ? ctx.selectionInNode.delta(-pos) : undefined,\n\t\t\t\tlistLevel: itemLevel,\n\t\t\t};\n\t\t\tcontent.push(_reuseOr(prevByAst?.get(item), _buildListItem(item, itemCtx, prevByAst?.get(item))));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new ListViewData(list, content);\n}\n\nfunction _buildListItem(item: ListItemAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): ListItemViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of item.children) {\n\t\tconst childCtx: BuildCtx = ctx.selectionInNode\n\t\t\t? { ...ctx, selectionInNode: ctx.selectionInNode.delta(-pos) }\n\t\t\t: ctx;\n\t\tcontent.push(_buildNode(child, childCtx, prevByAst?.get(child)));\n\t\tpos += child.length;\n\t}\n\treturn new ListItemViewData(item, ctx.showMarkup, content, ctx.listLevel ?? 1);\n}\n\n/**\n * A table reveals its delimiter and structural pipes whenever any cell is\n * active, but only the cell(s) the selection reaches reveal their inline\n * markers. Each non-delimiter row gets the table-relative selection shifted to\n * its own start; the delimiter row always reveals its cells when the table is\n * active.\n */\nfunction _buildTable(table: TableAstNode, ctx: BuildCtx, prevNode: AnyViewData | undefined): TableViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst tableActive = ctx.showMarkup;\n\tconst delimiterRow = table.delimiterRow;\n\tconst rowSet = new Set<TableRowAstNode>(\n\t\t[table.headerRow, table.delimiterRow, ...table.bodyRows].filter((r): r is TableRowAstNode => r !== undefined),\n\t);\n\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of table.children) {\n\t\tif (rowSet.has(child as TableRowAstNode)) {\n\t\t\tconst row = child as TableRowAstNode;\n\t\t\tconst isDelimiter = row === delimiterRow;\n\t\t\tconst rowCtx: BuildCtx = {\n\t\t\t\tshowMarkup: tableActive,\n\t\t\t\tshowTableGlue: tableActive,\n\t\t\t\tselectionInNode: !isDelimiter && tableActive && ctx.selectionInNode\n\t\t\t\t\t? ctx.selectionInNode.delta(-pos)\n\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t\tcontent.push(_reuseOr(prevByAst?.get(row), _buildTableRow(row, rowCtx, isDelimiter, prevByAst?.get(row))));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new TableViewData(table, content);\n}\n\nfunction _buildTableRow(row: TableRowAstNode, ctx: BuildCtx, isDelimiter: boolean, prevNode: AnyViewData | undefined): TableRowViewData {\n\tconst prevByAst = _prevChildByAst(prevNode);\n\tconst tableActive = ctx.showMarkup;\n\tconst activeCells = isDelimiter ? undefined : _activeCellIndices(row, ctx);\n\tconst cellSet = new Set<TableCellAstNode>(row.cells);\n\n\tconst content: AnyViewData[] = [];\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tif (cellSet.has(child as TableCellAstNode)) {\n\t\t\tconst cell = child as TableCellAstNode;\n\t\t\tconst cellActive = isDelimiter ? tableActive : activeCells!.has(row.cells.indexOf(cell));\n\t\t\tconst selectionInNode = cellActive && ctx.selectionInNode ? ctx.selectionInNode.delta(-pos) : undefined;\n\t\t\tcontent.push(_buildTableCell(cell, cellActive, tableActive, selectionInNode, prevByAst?.get(cell)));\n\t\t} else {\n\t\t\tcontent.push(_buildNode(child, ctx, prevByAst?.get(child)));\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn new TableRowViewData(row, isDelimiter, content);\n}\n\nfunction _buildTableCell(\n\tcell: TableCellAstNode,\n\tisActive: boolean,\n\tshowTableGlue: boolean,\n\tselectionInNode: OffsetRange | undefined,\n\tprevNode: AnyViewData | undefined,\n): TableCellViewData {\n\tconst cellCtx: BuildCtx = { showMarkup: isActive, showTableGlue, selectionInNode };\n\treturn new TableCellViewData(cell, isActive, showTableGlue, _buildChildren(cell.children, _inline(cellCtx), prevNode));\n}\n\nconst _EMPTY_SET: ReadonlySet<number> = new Set();\n\n/** Indices of the list's items whose source range intersects the selection. */\nfunction _activeItemIndices(list: ListAstNode, ctx: BuildCtx): ReadonlySet<number> {\n\tif (!ctx.showMarkup || !ctx.selectionInNode) { return _EMPTY_SET; }\n\tconst sel = ctx.selectionInNode;\n\tif (sel.isEmpty) {\n\t\tconst idx = findActiveListItemIndex(list, sel.start);\n\t\treturn idx === undefined ? _EMPTY_SET : new Set([idx]);\n\t}\n\tconst result = new Set<number>();\n\tlet pos = 0;\n\tfor (const child of list.children) {\n\t\tconst itemIdx = list.items.indexOf(child as ListItemAstNode);\n\t\tif (itemIdx >= 0 && pos < sel.endExclusive && pos + child.length > sel.start) {\n\t\t\tresult.add(itemIdx);\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn result;\n}\n\n/** Indices of the row's cells whose source range intersects the selection. */\nfunction _activeCellIndices(row: TableRowAstNode, ctx: BuildCtx): ReadonlySet<number> {\n\tif (!ctx.showMarkup || !ctx.selectionInNode) { return _EMPTY_SET; }\n\tconst sel = ctx.selectionInNode;\n\tif (sel.isEmpty) {\n\t\tconst idx = _findActiveCellIndex(row, sel.start);\n\t\treturn idx === undefined ? _EMPTY_SET : new Set([idx]);\n\t}\n\tconst result = new Set<number>();\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tconst cellIdx = row.cells.indexOf(child as TableCellAstNode);\n\t\tif (cellIdx >= 0 && pos < sel.endExclusive && pos + child.length > sel.start) {\n\t\t\tresult.add(cellIdx);\n\t\t}\n\t\tpos += child.length;\n\t}\n\treturn result;\n}\n\n/**\n * Cell containing a collapsed cursor, or `undefined` when the cursor is outside\n * this row. A cursor on the boundary between adjacent cells activates the\n * preceding one.\n */\nfunction _findActiveCellIndex(row: TableRowAstNode, cursorOffset: number): number | undefined {\n\tlet pos = 0;\n\tfor (const child of row.children) {\n\t\tconst end = pos + child.length;\n\t\tconst cellIdx = row.cells.indexOf(child as TableCellAstNode);\n\t\tif (cellIdx >= 0 && ((pos <= cursorOffset && cursorOffset < end) || end === cursorOffset)) {\n\t\t\treturn cellIdx;\n\t\t}\n\t\tpos = end;\n\t}\n\treturn undefined;\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { Rect2D } from '../../core/geometry.js';\nimport type { SourceOffset } from '../../core/sourceOffset.js';\nimport type { VisualLineMap } from '../visualLineMap.js';\n\nexport interface CursorViewOptions {\n readonly offset: IObservable<SourceOffset | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n /**\n * When set, the caret is drawn over the transient empty paragraph instead\n * of at {@link offset} — its rect (in client coordinates) comes straight\n * from that synthetic element's geometry, since it has no visual-line-map\n * entry. Takes priority over the normal offset-based placement.\n */\n readonly pendingCaretRect?: IObservable<Rect2D | undefined>;\n}\n\n/**\n * Owns the blinking cursor DOM element.\n *\n * The rendering pipeline is a single `derived` whose compute callback\n * asks the {@link VisualLineMap} for the caret rect at the current\n * offset, writes it to {@link element}, and returns a\n * {@link CursorViewRendering} value as proof. An autorun keeps the\n * derived subscribed.\n */\nexport class CursorView extends Disposable {\n readonly element: HTMLElement;\n readonly rendering: IObservable<CursorViewRendering>;\n\n constructor(\n private readonly _parent: HTMLElement,\n options: CursorViewOptions,\n ) {\n super();\n this.element = document.createElement('div');\n this.element.className = 'md-cursor';\n\n this.rendering = derived(this, reader => {\n const pendingRect = options.pendingCaretRect ? reader.readObservable(options.pendingCaretRect) : undefined;\n if (pendingRect) {\n const parentRect = this._parent.getBoundingClientRect();\n const localRect = pendingRect.translate(-parentRect.left, -parentRect.top);\n this.element.style.left = `${localRect.x}px`;\n this.element.style.top = `${localRect.y}px`;\n this.element.style.height = `${localRect.height}px`;\n this.element.style.display = '';\n return new CursorViewRendering(0, true, localRect);\n }\n const offset = reader.readObservable(options.offset);\n const visualLineMap = reader.readObservable(options.visualLineMap);\n if (offset === undefined || visualLineMap.isEmpty) {\n this.element.style.display = 'none';\n return new CursorViewRendering(offset ?? 0, false, Rect2D.EMPTY);\n }\n const lineIdx = visualLineMap.lineIndexOfOffset(offset);\n const caretRect = visualLineMap.lineRect(lineIdx).withZeroWidthAt(visualLineMap.xAtOffset(offset));\n const parentRect = this._parent.getBoundingClientRect();\n const localRect = caretRect.translate(-parentRect.left, -parentRect.top);\n this.element.style.left = `${localRect.x}px`;\n this.element.style.top = `${localRect.y}px`;\n this.element.style.height = `${localRect.height}px`;\n this.element.style.display = '';\n return new CursorViewRendering(offset, true, localRect);\n });\n\n this._register(autorun(reader => { reader.readObservable(this.rendering); }));\n\n this._register(autorun(reader => {\n reader.readObservable(options.offset);\n this.element.style.animation = 'none';\n void this.element.offsetWidth;\n this.element.style.animation = '';\n }));\n }\n}\n\nexport class CursorViewRendering {\n constructor(\n readonly offset: SourceOffset,\n readonly visible: boolean,\n readonly rect: Rect2D,\n ) { }\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { GutterMarker, GutterMarkerType } from '../../core/gutterMarker.js';\nimport type { VisualLine, VisualLineMap } from '../visualLineMap.js';\n\nexport interface GutterMarkersViewOptions {\n\treadonly markers: IObservable<readonly GutterMarker[]>;\n\treadonly visualLineMap: IObservable<VisualLineMap>;\n}\n\n/**\n * One painted gutter element, in parent-local coordinates. A `'deleted'` marker\n * is zero-height (`height === 0`) and rendered as a wedge sitting at `y`; the\n * others are bars spanning `[y, y + height)`.\n */\nexport interface GutterMarkerRect {\n\treadonly type: GutterMarkerType;\n\treadonly y: number;\n\treadonly height: number;\n}\n\n/**\n * Owns the gutter overlay that paints source-control style change markers\n * (added / modified / deleted) in the editor's left gutter.\n *\n * Same shape as {@link CursorView}/{@link SelectionView}: a single `derived`\n * resolves each {@link GutterMarker}'s source range to the {@link VisualLine}s\n * it covers via the {@link VisualLineMap}, writes one absolutely-positioned\n * child element per marker, and returns a {@link GutterMarkersViewRendering} as\n * proof. An autorun keeps the derived subscribed.\n *\n * The view only sets vertical geometry (`top`/`height`) and a type class; the\n * gutter's horizontal placement, width and colors live in CSS so themes can\n * tune them. The layer is `pointer-events: none` like the other overlays.\n */\nexport class GutterMarkersView extends Disposable {\n\treadonly element: HTMLElement;\n\treadonly rendering: IObservable<GutterMarkersViewRendering>;\n\n\tconstructor(\n\t\tprivate readonly _parent: HTMLElement,\n\t\toptions: GutterMarkersViewOptions,\n\t) {\n\t\tsuper();\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-gutter-layer';\n\n\t\tthis.rendering = derived(this, reader => {\n\t\t\tconst markers = reader.readObservable(options.markers);\n\t\t\tconst visualLineMap = reader.readObservable(options.visualLineMap);\n\t\t\treturn this._render(markers, visualLineMap);\n\t\t});\n\n\t\tthis._register(autorun(reader => { reader.readObservable(this.rendering); }));\n\t}\n\n\tprivate _render(markers: readonly GutterMarker[], visualLineMap: VisualLineMap): GutterMarkersViewRendering {\n\t\tthis.element.replaceChildren();\n\t\tif (visualLineMap.isEmpty) { return new GutterMarkersViewRendering([]); }\n\n\t\tconst parentRect = this._parent.getBoundingClientRect();\n\t\tconst rects: GutterMarkerRect[] = [];\n\n\t\tfor (const marker of markers) {\n\t\t\tconst rect = marker.type === 'deleted' || marker.range.isEmpty\n\t\t\t\t? _deletedRect(marker, visualLineMap, parentRect.top)\n\t\t\t\t: _barRect(marker, visualLineMap, parentRect.top);\n\t\t\tif (!rect) { continue; }\n\n\t\t\tconst el = document.createElement('div');\n\t\t\tel.className = `md-gutter-marker md-gutter-marker-${rect.type}`;\n\t\t\tel.style.top = `${rect.y}px`;\n\t\t\tif (rect.height > 0) { el.style.height = `${rect.height}px`; }\n\t\t\tthis.element.appendChild(el);\n\t\t\trects.push(rect);\n\t\t}\n\n\t\treturn new GutterMarkersViewRendering(rects);\n\t}\n}\n\nexport class GutterMarkersViewRendering {\n\tconstructor(readonly rects: readonly GutterMarkerRect[]) { }\n}\n\n/**\n * Bar spanning every visual line the marker's range intersects: top of the\n * first such line to the bottom of the last. Returns `undefined` when the range\n * covers no rendered line.\n */\nfunction _barRect(marker: GutterMarker, visualLineMap: VisualLineMap, parentTop: number): GutterMarkerRect | undefined {\n\tlet top = Infinity;\n\tlet bottom = -Infinity;\n\tfor (const line of visualLineMap.lines) {\n\t\tconst lineRange = _lineSourceRange(line);\n\t\tif (!lineRange || !marker.range.intersects(lineRange)) { continue; }\n\t\ttop = Math.min(top, line.rect.top);\n\t\tbottom = Math.max(bottom, line.rect.top + line.rect.height);\n\t}\n\tif (bottom <= top) { return undefined; }\n\treturn { type: marker.type, y: top - parentTop, height: bottom - top };\n}\n\n/**\n * Wedge for a deletion: anchored at the top of the line that *starts* at the\n * deletion offset, so it points at the seam where the removed text used to be.\n */\nfunction _deletedRect(marker: GutterMarker, visualLineMap: VisualLineMap, parentTop: number): GutterMarkerRect {\n\tconst lineIdx = visualLineMap.lineIndexOfOffset(marker.range.start);\n\tconst lineRect = visualLineMap.lineRect(lineIdx);\n\treturn { type: 'deleted', y: lineRect.top - parentTop, height: 0 };\n}\n\nfunction _lineSourceRange(line: VisualLine): OffsetRange | undefined {\n\tif (line.runs.length === 0) { return undefined; }\n\tlet min = Infinity;\n\tlet max = -Infinity;\n\tfor (const run of line.runs) {\n\t\tif (run.sourceStart < min) { min = run.sourceStart; }\n\t\tif (run.sourceEndExclusive > max) { max = run.sourceEndExclusive; }\n\t}\n\treturn OffsetRange.fromTo(min, max);\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { Selection } from '../../core/selection.js';\nimport type { BlockAstNode } from '../../parser/ast.js';\nimport type { ViewNode } from '../content/viewNode.js';\nimport type { VisualLine, VisualLineMap } from '../visualLineMap.js';\n\n/**\n * One mounted block, as far as selection painting is concerned. The view\n * supplies its block cache in this shape so the selection layer never has\n * to reach back into private view state.\n */\nexport interface SelectionBlock {\n readonly block: BlockAstNode;\n readonly absoluteStart: number;\n readonly viewNode: ViewNode;\n readonly element: HTMLElement;\n}\n\nexport interface SelectionViewOptions {\n readonly selection: IObservable<Selection | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n readonly blocks: IObservable<readonly SelectionBlock[]>;\n}\n\nexport interface SelectionRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Owns the SVG overlay that paints the selection.\n *\n * Rendering is *line-based*, not glyph-based:\n *\n * 1. Each {@link VisualLine} overlapping the selection produces one rect\n * using the full line-box height (so the selection has even, line-\n * height bands instead of jagged glyph rects).\n * 2. Inter-block gaps fully inside the selection become connector rects.\n * 3. All rects are grouped into vertically-adjacent clusters and each\n * cluster is rendered as a single connected polygon with rounded\n * corners.\n *\n * To keep the polygon connected without gaps, \"middle\" lines (any line\n * that is neither the first nor the last selected line in the document)\n * are extended to their full line extent, while the first and last lines\n * are clipped to the actual selection start/end. This is the standard\n * envelope shape used by IDE selection rendering.\n */\nexport class SelectionView extends Disposable {\n readonly element: SVGSVGElement;\n readonly rendering: IObservable<SelectionViewRendering>;\n\n private readonly _path: SVGPathElement;\n\n constructor(\n private readonly _parent: HTMLElement,\n options: SelectionViewOptions,\n ) {\n super();\n this.element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n this.element.setAttribute('class', 'md-selection-layer');\n this._path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n this._path.setAttribute('class', 'md-selection-path');\n this.element.appendChild(this._path);\n\n this.rendering = derived(this, reader => {\n const selection = reader.readObservable(options.selection);\n const visualLineMap = reader.readObservable(options.visualLineMap);\n const blocks = reader.readObservable(options.blocks);\n return _renderSelection(this._path, this._parent, selection, visualLineMap, blocks);\n });\n\n this._register(autorun(reader => { reader.readObservable(this.rendering); }));\n }\n}\n\nexport class SelectionViewRendering {\n constructor(readonly rects: readonly SelectionRect[]) { }\n}\n\nfunction _renderSelection(\n path: SVGPathElement,\n parent: HTMLElement,\n selection: Selection | undefined,\n visualLineMap: VisualLineMap,\n blocks: readonly SelectionBlock[],\n): SelectionViewRendering {\n if (!selection || selection.isCollapsed) {\n path.setAttribute('d', '');\n return new SelectionViewRendering([]);\n }\n\n const selRange = selection.range;\n const parentRect = parent.getBoundingClientRect();\n\n // 1. Collect visual lines overlapping the selection, paired with the\n // block that contains them.\n const lineInfos: { line: VisualLine; lineRange: OffsetRange; block: SelectionBlock | undefined }[] = [];\n for (const line of visualLineMap.lines) {\n const lineRange = _lineSourceRange(line);\n if (!lineRange || !selRange.intersects(lineRange)) { continue; }\n const block = blocks.find(b => OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length).containsRange(lineRange));\n lineInfos.push({ line, lineRange, block });\n }\n\n const rects: SelectionRect[] = [];\n // Per-line rect in absolute client coordinates (translated to\n // parent-local later). Saved so the connector logic can clip itself\n // to the overlap of the bordering line rects.\n const lineRects: { left: number; right: number; top: number; bottom: number }[] = [];\n\n // One rect per visual line, full line-height. The first line is\n // x-clipped to the selection start; the last line to the selection\n // end. Interior lines use the visual line's own extent (`line.rect`)\n // — the *actual painted text*, not the block element width — so the\n // selection covers the minimum area needed to enclose the content\n // while still forming a connected polygon (adjacent lines in the\n // same block share their left edge, which is enough to connect).\n for (let i = 0; i < lineInfos.length; i++) {\n const { line, lineRange } = lineInfos[i];\n const isFirst = i === 0;\n const isLast = i === lineInfos.length - 1;\n\n const startX = isFirst\n ? line.xAtOffset(Math.max(selRange.start, lineRange.start))\n : line.rect.left;\n const endX = isLast\n ? line.xAtOffset(Math.min(selRange.endExclusive, lineRange.endExclusive))\n : line.rect.right;\n\n rects.push({\n x: startX - parentRect.left,\n y: line.rect.top - parentRect.top,\n width: Math.max(0, endX - startX),\n height: line.rect.height,\n });\n lineRects.push({ left: startX, right: endX, top: line.rect.top, bottom: line.rect.top + line.rect.height });\n }\n\n // 2a. Intra-line-pair connectors: between every consecutive pair of\n // selected lines (same block or not), if there's a vertical gap and\n // the lines share x, fill the gap clipped to that overlap. This\n // matters for blocks like <pre> where `line-height` leaves a few\n // pixels between consecutive lines that the polygon would otherwise\n // not bridge.\n for (let i = 0; i < lineRects.length - 1; i++) {\n const prev = lineRects[i];\n const next = lineRects[i + 1];\n if (next.top <= prev.bottom) { continue; }\n const left = Math.max(prev.left, next.left);\n const right = Math.min(prev.right, next.right);\n if (right <= left) { continue; }\n rects.push({\n x: left - parentRect.left,\n y: prev.bottom - parentRect.top,\n width: right - left,\n height: next.top - prev.bottom,\n });\n }\n\n // 2. Connectors that bridge the visual gap between two consecutive\n // selected blocks. The connector x-range is the overlap of the\n // bordering line rects (the last selected line of the previous block\n // and the first selected line of the next block) so the connector\n // stays as narrow as possible while still bridging both polygons.\n // If the bordering lines don't horizontally overlap at all, the\n // connector degenerates to a 1px-wide bridge at the closer edge so\n // the two clusters merge into one polygon.\n const blockToFirstLineIdx = new Map<SelectionBlock, number>();\n const blockToLastLineIdx = new Map<SelectionBlock, number>();\n for (let i = 0; i < lineInfos.length; i++) {\n const b = lineInfos[i].block;\n if (!b) { continue; }\n if (!blockToFirstLineIdx.has(b)) { blockToFirstLineIdx.set(b, i); }\n blockToLastLineIdx.set(b, i);\n }\n const blockSelected = blocks.map(b =>\n selRange.intersects(OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length))\n );\n for (let i = 0; i < blocks.length - 1; i++) {\n const curr = blocks[i];\n const next = blocks[i + 1];\n const gapStart = curr.absoluteStart + curr.block.length;\n const gapEnd = next.absoluteStart;\n if (gapStart < gapEnd && !selRange.containsRange(OffsetRange.fromTo(gapStart, gapEnd))) { continue; }\n if (gapStart >= gapEnd && !(blockSelected[i] && blockSelected[i + 1])) { continue; }\n\n const currRect = curr.element.getBoundingClientRect();\n const nextRect = next.element.getBoundingClientRect();\n // Extend through any padding so the connector meets the first\n // visual line of the next block, not just the element top.\n const nextFirstLineTop = _firstLineTopOfBlock(visualLineMap, next, nextRect.top);\n const top = currRect.bottom;\n if (nextFirstLineTop <= top) { continue; }\n\n const prevLineIdx = blockToLastLineIdx.get(curr);\n const nextLineIdx = blockToFirstLineIdx.get(next);\n const prevLR = prevLineIdx !== undefined ? lineRects[prevLineIdx] : { left: currRect.left, right: currRect.right };\n const nextLR = nextLineIdx !== undefined ? lineRects[nextLineIdx] : { left: nextRect.left, right: nextRect.right };\n\n const left = Math.max(prevLR.left, nextLR.left);\n const right = Math.min(prevLR.right, nextLR.right);\n // No vertical connector when the bordering line rects don't share\n // any x — the polygon clusterer keeps the two stacks as separate\n // subpaths so we don't get a thin \"jump\" through empty space.\n if (right <= left) { continue; }\n\n rects.push({\n x: left - parentRect.left,\n y: top - parentRect.top,\n width: right - left,\n height: nextFirstLineTop - top,\n });\n }\n\n // 3. Blocks with no text leaves (e.g. <hr>, image, math) that are\n // inside the selection range — they produce no visual lines, so fall\n // back to the block element's bounding rect.\n for (const b of blocks) {\n const blockRange = OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length);\n if (!selRange.intersects(blockRange)) { continue; }\n let hasLine = false;\n for (const { lineRange } of lineInfos) {\n if (lineRange.intersects(blockRange)) { hasLine = true; break; }\n }\n if (hasLine) { continue; }\n const rect = b.element.getBoundingClientRect();\n rects.push({\n x: rect.left - parentRect.left,\n y: rect.top - parentRect.top,\n width: rect.width,\n height: rect.height,\n });\n }\n\n path.setAttribute('d', _buildConnectedPath(rects, 4));\n return new SelectionViewRendering(rects);\n}\n\nfunction _lineSourceRange(line: VisualLine): OffsetRange | undefined {\n if (line.runs.length === 0) { return undefined; }\n let min = Infinity;\n let max = -Infinity;\n for (const run of line.runs) {\n if (run.sourceStart < min) { min = run.sourceStart; }\n if (run.sourceEndExclusive > max) { max = run.sourceEndExclusive; }\n }\n return OffsetRange.fromTo(min, max);\n}\n\n/**\n * Top of the first visual line whose source range falls inside `block`.\n * Falls back to `fallback` (the block element's top) when the block\n * itself has no text leaves (e.g. <hr>, image, math).\n */\nfunction _firstLineTopOfBlock(visualLineMap: VisualLineMap, block: SelectionBlock, fallback: number): number {\n const blockRange = OffsetRange.ofStartAndLength(block.absoluteStart, block.block.length);\n for (const line of visualLineMap.lines) {\n const lineRange = _lineSourceRange(line);\n if (lineRange && blockRange.containsRange(lineRange)) {\n return line.rect.top;\n }\n }\n return fallback;\n}\n\n// ---------- polygon ---------------------------------------------------\n\ninterface PolygonCorner {\n readonly x: number;\n readonly y: number;\n /** True for outer corners (rounded outward), false for inner (rounded inward). */\n readonly convex: boolean;\n}\n\n/**\n * Build one connected SVG path for `rects`. Each cluster of rects that\n * are *both* vertically adjacent and horizontally overlapping with the\n * previous rect becomes one closed sub-shape; any rect that fails either\n * condition starts a new sub-shape. This is what prevents thin \"jumps\"\n * through empty space when two y-adjacent selected lines don't share any\n * x range (e.g. end-of-paragraph vs. start-of-heading further left).\n */\nfunction _buildConnectedPath(rects: readonly SelectionRect[], radius: number): string {\n if (rects.length === 0) { return ''; }\n const sorted = rects.slice().sort((a, b) => a.y - b.y || a.x - b.x);\n\n const clusters: SelectionRect[][] = [];\n let current: SelectionRect[] = [];\n for (const r of sorted) {\n const prev = current[current.length - 1];\n const yTouches = prev !== undefined && r.y <= prev.y + prev.height + 0.5;\n const xOverlaps = prev !== undefined && Math.max(prev.x, r.x) < Math.min(prev.x + prev.width, r.x + r.width);\n if (yTouches && xOverlaps) {\n current.push(r);\n } else {\n if (current.length > 0) { clusters.push(current); }\n current = [r];\n }\n }\n if (current.length > 0) { clusters.push(current); }\n\n return clusters.map(c => _buildClusterPath(c, radius)).filter(Boolean).join(' ');\n}\n\n/**\n * Walk one vertically-adjacent cluster of rects clockwise:\n * top edge of first → down the right side (with steps between lines) →\n * bottom edge of last → up the left side (with steps).\n * Each axis-aligned 90° turn is rendered with a rounded arc.\n */\nfunction _buildClusterPath(rects: SelectionRect[], radius: number): string {\n const corners: PolygonCorner[] = [];\n\n // Right side, top to bottom.\n corners.push({ x: rects[0].x + rects[0].width, y: rects[0].y, convex: true });\n for (let i = 0; i < rects.length - 1; i++) {\n const a = rects[i];\n const b = rects[i + 1];\n const aRight = a.x + a.width;\n const bRight = b.x + b.width;\n if (Math.abs(aRight - bRight) > 0.5) {\n const y = a.y + a.height;\n const aConvex = aRight > bRight;\n corners.push({ x: aRight, y, convex: aConvex });\n corners.push({ x: bRight, y, convex: !aConvex });\n }\n }\n const last = rects[rects.length - 1];\n corners.push({ x: last.x + last.width, y: last.y + last.height, convex: true });\n\n // Left side, bottom to top.\n corners.push({ x: last.x, y: last.y + last.height, convex: true });\n for (let i = rects.length - 1; i > 0; i--) {\n const a = rects[i];\n const b = rects[i - 1];\n if (Math.abs(a.x - b.x) > 0.5) {\n const y = a.y;\n const aConvex = a.x < b.x;\n corners.push({ x: a.x, y, convex: aConvex });\n corners.push({ x: b.x, y, convex: !aConvex });\n }\n }\n corners.push({ x: rects[0].x, y: rects[0].y, convex: true });\n\n return _polygonToRoundedPath(corners, radius);\n}\n\nfunction _polygonToRoundedPath(corners: readonly PolygonCorner[], radius: number): string {\n const n = corners.length;\n if (n < 3) { return ''; }\n\n const radii: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const prev = corners[(i + n - 1) % n];\n const next = corners[(i + 1) % n];\n const dPrev = _dist(corners[i], prev);\n const dNext = _dist(corners[i], next);\n radii[i] = Math.min(radius, dPrev / 2, dNext / 2);\n }\n\n // Approach point of corner 0 on the edge corner[n-1] → corner[0].\n const start = _moveFrom(corners[n - 1], corners[0], _dist(corners[n - 1], corners[0]) - radii[0]);\n const parts: string[] = [`M${_fmt(start.x)},${_fmt(start.y)}`];\n\n for (let i = 0; i < n; i++) {\n const curr = corners[i];\n const next = corners[(i + 1) % n];\n const r = radii[i];\n\n // Arc from approach point of `curr` to departure point on the next edge.\n const depart = _moveFrom(curr, next, r);\n if (r > 0) {\n parts.push(`A${_fmt(r)},${_fmt(r)} 0 0 ${curr.convex ? 1 : 0} ${_fmt(depart.x)},${_fmt(depart.y)}`);\n } else {\n parts.push(`L${_fmt(depart.x)},${_fmt(depart.y)}`);\n }\n\n // Line along the edge up to the approach point of the next corner.\n const nextR = radii[(i + 1) % n];\n const approach = _moveFrom(curr, next, _dist(curr, next) - nextR);\n parts.push(`L${_fmt(approach.x)},${_fmt(approach.y)}`);\n }\n\n parts.push('Z');\n return parts.join(' ');\n}\n\nfunction _dist(a: { x: number; y: number }, b: { x: number; y: number }): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nfunction _moveFrom(from: { x: number; y: number }, to: { x: number; y: number }, dist: number): { x: number; y: number } {\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) { return { x: from.x, y: from.y }; }\n const t = dist / len;\n return { x: from.x + dx * t, y: from.y + dy * t };\n}\n\nfunction _fmt(n: number): string {\n return n.toFixed(2);\n}\n","import { Disposable, autorun, constObservable, derived, observableValue } from '@vscode/observables';\nimport type { IObservable, IReader } from '@vscode/observables';\nimport { Point2D, Rect2D } from '../core/geometry.js';\nimport type { SourceOffset } from '../core/sourceOffset.js';\nimport type { EditorModel } from '../model/editorModel.js';\nimport { MeasuredLayoutModel, type BlockMeasurement } from '../model/measuredLayoutModel.js';\nimport { caretDomPositionFromPoint } from './content/dom.js';\nimport type { BlockViewOptions } from './content/blockView.js';\nimport { DocumentViewNode, type DocumentBlock } from './content/documentView.js';\nimport { buildDocumentViewData, type DocumentViewData } from './viewData.js';\nimport { CursorView } from './parts/cursorView.js';\nimport { GutterMarkersView } from './parts/gutterMarkersView.js';\nimport { SelectionView, type SelectionBlock } from './parts/selectionView.js';\nimport { VisualLineMap } from './visualLineMap.js';\n\n/** Default max content width (px) used when {@link EditorViewOptions.limitedWidth} is omitted. */\nconst DEFAULT_LIMITED_WIDTH = 900;\n\nexport interface EditorViewOptions extends BlockViewOptions {\n\t/**\n\t * Extra class names added to the editor root element, e.g. a theme class\n\t * such as `'md-theme-default'` or `'github-markdown-theme'`. Theme styles\n\t * are scoped under these classes, so the editor is unstyled (base chrome\n\t * only) unless a theme class is supplied.\n\t */\n\treadonly classNames?: readonly string[];\n\n\t/**\n\t * Controls \"limited width mode\". The observable yields the maximum content\n\t * width in pixels, or `undefined` to let the content fill the available\n\t * width. When the option is omitted, the width is capped at\n\t * {@link DEFAULT_LIMITED_WIDTH}px (limited mode is on by default).\n\t *\n\t * The cap and centering apply to an inner content container; the editor\n\t * root ({@link element}) always spans the full available width.\n\t */\n\treadonly limitedWidth?: IObservable<number | undefined>;\n}\n\n/**\n * Pure-render view of an {@link EditorModel}.\n *\n * Invariant (the whole point of this file):\n *\n * view(model + Δ) = view(model) + Δ\n *\n * The DOM the view produces is a function of the model. The only state the\n * view holds is *DOM management*: the cached `BlockViewNode` instances and the\n * `EditContext`. Anything that influences correctness but is not derivable\n * from the model lives elsewhere:\n *\n * - measured heights and per-block visual line maps → {@link MeasuredLayoutModel}\n * - desired column, drag-time freeze → EditorController\n *\n * The view does not own a controller — callers construct an\n * `EditorController` separately and pass it the view, so input handling is\n * explicit and the view stays a pure renderer.\n *\n * The view writes into the measured-layout model as a side effect of\n * rendering. It never reads its own measurements during rendering, so\n * there is no feedback loop.\n */\nexport class EditorView extends Disposable {\n\treadonly element: HTMLElement;\n\treadonly editContext: EditContext;\n\treadonly measuredLayout: MeasuredLayoutModel;\n\n\t/**\n\t * Inner container that holds the rendered document and the cursor/selection\n\t * overlays. The outer {@link element} spans the full width; this container\n\t * is what limited-width mode caps and centers, so the overlays (which anchor\n\t * to their parent's box) stay aligned with the content.\n\t */\n\tprivate readonly _contentContainer: HTMLElement;\n\n\tprivate readonly _cursorView: CursorView;\n\tprivate readonly _selectionView: SelectionView;\n\tprivate readonly _gutterMarkersView: GutterMarkersView;\n\n\t/**\n\t * The mounted block sequence, in source order. Rebuilt (not mutated) each\n\t * frame by {@link DocumentViewNode.create}; the view just swaps one\n\t * immutable node for the next. Never used for source-of-truth lookups\n\t * (those go through the measured-layout model).\n\t */\n\tprivate readonly _document = observableValue<DocumentViewNode | undefined>(this, undefined);\n\n\t/** The current view-node tree (AST overlaid with rendered DOM), for debugging. */\n\tpublic get documentViewNode(): IObservable<DocumentViewNode | undefined> { return this._document; }\n\n\t/**\n\t * Last frame's view-data overlay, threaded back into\n\t * {@link buildDocumentViewData} so any subtree whose ast and selection flags\n\t * are unchanged keeps its view-data object — which lets the renderer reuse\n\t * its DOM by identity.\n\t */\n\tprivate _previousViewData: DocumentViewData | undefined;\n\n\t/** The current view-data tree (AST overlaid with selection flags), for debugging. */\n\tprivate readonly _viewData = observableValue<DocumentViewData | undefined>(this, undefined);\n\tpublic get viewData(): IObservable<DocumentViewData | undefined> { return this._viewData; }\n\n\t/**\n\t * Caret rect (client coords) for the transient empty paragraph, or\n\t * `undefined` when none is armed. Set each frame from the synthetic\n\t * paragraph element's geometry and fed to the {@link CursorView}, which has\n\t * no visual-line-map entry to place the caret from otherwise.\n\t */\n\tprivate readonly _pendingCaretRect = observableValue<Rect2D | undefined>(this, undefined);\n\n\t/**\n\t * The block cache projected for views (selection painting) that need to\n\t * react to mount/unmount. Derived from {@link _document}, so it stays in\n\t * lock-step without any manual bookkeeping.\n\t */\n\tprivate readonly _selectionBlocksObs = derived(this, reader => {\n\t\tconst doc = this._document.read(reader);\n\t\tif (!doc) { return []; }\n\t\treturn doc.blocks.map((b): SelectionBlock => ({\n\t\t\tblock: b.node.block,\n\t\t\tabsoluteStart: b.absoluteStart,\n\t\t\tviewNode: b.node,\n\t\t\telement: b.node.element,\n\t\t}));\n\t});\n\n\tconstructor(\n\t\tprivate readonly _model: EditorModel,\n\t\tprivate readonly _options?: EditorViewOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-editor';\n\t\tif (this._options?.classNames) {\n\t\t\tthis.element.classList.add(...this._options.classNames);\n\t\t}\n\t\tthis.element.tabIndex = 0;\n\n\t\tthis._contentContainer = document.createElement('div');\n\t\tthis._contentContainer.className = 'md-editor-content';\n\t\tthis.element.appendChild(this._contentContainer);\n\n\t\tconst limitedWidth = this._options?.limitedWidth ?? constObservable<number | undefined>(DEFAULT_LIMITED_WIDTH);\n\t\tthis._register(autorun(reader => {\n\t\t\tconst width = limitedWidth.read(reader);\n\t\t\tthis._contentContainer.style.maxWidth = width === undefined ? '' : `${width}px`;\n\t\t}));\n\n\t\tthis.measuredLayout = new MeasuredLayoutModel();\n\n\t\tthis._selectionView = this._register(new SelectionView(this._contentContainer, {\n\t\t\tselection: this._model.selection,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t\tblocks: this._selectionBlocksObs,\n\t\t}));\n\t\tthis._contentContainer.appendChild(this._selectionView.element);\n\n\t\tthis._cursorView = this._register(new CursorView(this._contentContainer, {\n\t\t\toffset: this._model.cursorOffset,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t\tpendingCaretRect: this._pendingCaretRect,\n\t\t}));\n\t\tthis._contentContainer.appendChild(this._cursorView.element);\n\n\t\tthis._gutterMarkersView = this._register(new GutterMarkersView(this._contentContainer, {\n\t\t\tmarkers: this._model.gutterMarkers,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t}));\n\t\tthis._contentContainer.appendChild(this._gutterMarkersView.element);\n\n\t\tthis.editContext = new EditContext({\n\t\t\ttext: this._model.sourceText.get().value,\n\t\t\tselectionStart: 0,\n\t\t\tselectionEnd: 0,\n\t\t});\n\t\tthis.element.editContext = this.editContext;\n\n\t\tthis._register(autorun(this._renderAutorun));\n\t\tthis._setupModifierTracking();\n\t\tthis._register(autorun(reader => {\n\t\t\tconst sel = reader.readObservable(this._model.selection)?.range;\n\t\t\tthis.editContext.updateSelection(sel?.start ?? 0, sel?.endExclusive ?? 0);\n\t\t}));\n\t\tthis._register({ dispose: () => { this._document.get()?.dispose(); } });\n\t}\n\n\t/**\n\t * Mirrors the model's live Ctrl/Cmd state onto the editor root as\n\t * `.md-mod-down` so CSS can show the link-open underline and pointer cursor\n\t * only while a click would actually open the link: an inactive link opens on\n\t * a plain click, but an active link only opens with the modifier held.\n\t */\n\tprivate _setupModifierTracking(): void {\n\t\tthis._register(autorun(reader => {\n\t\t\tthis.element.classList.toggle('md-mod-down', this._model.ctrlOrMetaDown.read(reader));\n\t\t}));\n\t}\n\n\tfocus(): void { this.element.focus({ preventScroll: true }); }\n\n\t/**\n\t * Client coordinates → absolute source offset (any block). Used during\n\t * drag to keep extending the selection even when the pointer leaves the\n\t * original block.\n\t */\n\tresolveOffsetFromPoint(point: Point2D): SourceOffset | undefined {\n\t\tconst pos = caretDomPositionFromPoint(point);\n\t\tif (!pos) { return undefined; }\n\t\treturn this._document.get()?.resolveSource(pos);\n\t}\n\n\t/**\n\t * Whether a client point falls on the rendered document content, as\n\t * opposed to the surrounding editor padding (the green area). Uses DOM\n\t * containment rather than the content node's bounding box so that markers\n\t * which overflow into the padding (e.g. a heading's `##`, which renders in\n\t * the left margin) still count as content. Overlays (cursor, selection)\n\t * have `pointer-events: none`, so the hit-test sees through them.\n\t */\n\tisPointInContent(point: Point2D): boolean {\n\t\tconst content = this._document.get()?.contentDomNode;\n\t\tif (!content) { return false; }\n\t\tconst hit = document.elementFromPoint(point.x, point.y);\n\t\treturn hit !== null && content.contains(hit);\n\t}\n\n\t// ----- render autorun ------------------------------------------------\n\n\tprivate readonly _renderAutorun = (reader: IReader): void => {\n\t\tconst doc = reader.readObservable(this._model.document);\n\t\tconst sourceText = reader.readObservable(this._model.sourceText).value;\n\t\tconst activeBlocks = reader.readObservable(this._model.activeBlocks);\n\t\tconst selection = reader.readObservable(this._model.selection);\n\t\tconst pending = reader.readObservable(this._model.pendingParagraph);\n\n\t\tif (this.editContext.text !== sourceText) {\n\t\t\tthis.editContext.updateText(0, this.editContext.text.length, sourceText);\n\t\t}\n\n\t\t// Rebuild the document node, reusing the previous one's blocks where\n\t\t// the AST identity and render inputs are unchanged. The parser\n\t\t// preserves block objects across reparses (see {@link MarkdownParser.parse}),\n\t\t// so a matching `Block` reference means the rendered DOM is still valid.\n\t\tconst previous = this._document.get();\n\t\t// Overlay the AST with the selection-derived flags, reusing the previous\n\t\t// frame's view-data for any unchanged subtree so the rebuild below collapses\n\t\t// to a single identity check per node (see {@link buildDocumentViewData}).\n\t\tconst viewData = buildDocumentViewData(\n\t\t\tdoc, activeBlocks, selection?.range, this._previousViewData,\n\t\t\tpending ? { anchorBlock: pending.anchorBlock, ast: pending.syntheticAst } : undefined,\n\t\t);\n\t\tthis._previousViewData = viewData;\n\t\tthis._viewData.set(viewData, undefined);\n\t\tconst documentNode = DocumentViewNode.create(viewData, this._options, previous);\n\t\tif (previous) {\n\t\t\t// The content element is stable across rebuilds, so once mounted it\n\t\t\t// never moves.\n\t\t\tif (documentNode.contentDomNode !== previous.contentDomNode) {\n\t\t\t\tthrow new Error('DocumentViewNode.contentDomNode must be stable across rebuilds');\n\t\t\t}\n\t\t} else {\n\t\t\t// First render: mount the freshly-created content element ahead of\n\t\t\t// the selection/cursor overlays.\n\t\t\tthis._contentContainer.insertBefore(documentNode.contentDomNode, this._contentContainer.firstChild);\n\t\t}\n\t\tthis._document.set(documentNode, undefined);\n\t\tthis._publishMeasurements(documentNode);\n\n\t\t// Derive the pending caret rect from the synthetic paragraph's geometry —\n\t\t// it has no visual-line-map entry, so the CursorView can only place its\n\t\t// caret from this rect.\n\t\tconst pendingEl = documentNode.pendingElement;\n\t\tif (pendingEl) {\n\t\t\tconst r = pendingEl.getBoundingClientRect();\n\t\t\tthis._pendingCaretRect.set(Rect2D.fromPointSize(r.left, r.top, 2, r.height), undefined);\n\t\t} else {\n\t\t\tthis._pendingCaretRect.set(undefined, undefined);\n\t\t}\n\t};\n\n\t/** Current mounted blocks, or empty before the first render. */\n\tprivate get _blocks(): readonly DocumentBlock[] {\n\t\treturn this._document.get()?.blocks ?? [];\n\t}\n\n\t/**\n\t * Measure each mounted block's rect and per-block visual line map, then\n\t * publish the result into the {@link MeasuredLayoutModel}. The model\n\t * is not read here, so there is no feedback loop into the render autorun.\n\t */\n\tprivate _publishMeasurements(document: DocumentViewNode): void {\n\t\tconst measurements: BlockMeasurement[] = [];\n\t\tfor (const entry of document.blocks) {\n\t\t\tconst blockRect = entry.node.element.getBoundingClientRect();\n\t\t\t// Let the block remember its own measured height (a math block reserves\n\t\t\t// its rendered height to keep the layout stable across the active toggle).\n\t\t\tentry.node.recordMeasuredHeight(blockRect.height);\n\t\t\tconst visualLineMap = VisualLineMap.measure([{\n\t\t\t\tabsoluteStart: entry.absoluteStart,\n\t\t\t\tviewNode: entry.node,\n\t\t\t}]);\n\t\t\tmeasurements.push({\n\t\t\t\tblock: entry.node.block,\n\t\t\t\tabsoluteStart: entry.absoluteStart,\n\t\t\t\theight: blockRect.height,\n\t\t\t\tisMeasured: true,\n\t\t\t\tvisualLineMap,\n\t\t\t\tviewNode: entry.node,\n\t\t\t});\n\t\t}\n\t\tthis.measuredLayout.measurements.set(measurements, undefined);\n\t}\n}\n","import type { IDisposable } from '@vscode/observables';\n\n/**\n * The editor operations a clipboard strategy drives. The strategy never\n * touches the model or the DOM directly — it asks through this seam, so the\n * same strategy works regardless of how the editor is wired up.\n */\nexport interface IClipboardContext {\n /** The element that owns focus and receives clipboard/keyboard events. */\n readonly element: HTMLElement;\n /** The selected source text, or `undefined` when the selection is empty. */\n getSelectedText(): string | undefined;\n /** Delete the current selection (the cut half of cut). */\n deleteSelection(): void;\n /** Insert text at the caret, replacing any selection (the paste action). */\n insertText(text: string): void;\n}\n\n/**\n * How copy/cut/paste intent reaches the editor. Host environments deliver it\n * differently, so the controller owns no clipboard logic itself — it\n * {@link connect}s a strategy and lets it install whatever listeners it needs.\n *\n * Two implementations ship:\n * - {@link NativeClipboardStrategy} (default) reads the browser's native\n * `copy`/`cut`/`paste` events and their synchronous `clipboardData`.\n * - {@link AsyncClipboardStrategy} drives the async `navigator.clipboard` API\n * from Ctrl/Cmd+C/X/V keystrokes, for hosts (e.g. VS Code webviews) that\n * swallow the native clipboard events before they reach the editor.\n */\nexport interface IClipboardStrategy {\n /**\n * Wire up clipboard handling against `context`. The returned disposable\n * tears down every listener the strategy installed.\n */\n connect(context: IClipboardContext): IDisposable;\n}\n\n/**\n * Default strategy: handle the browser's native `copy`/`cut`/`paste` events,\n * reading and writing the synchronous {@link ClipboardEvent.clipboardData}.\n * This is the standard rich-editor approach and works wherever the browser\n * actually dispatches those events to the focused element (e.g. a standalone\n * web page).\n */\nexport class NativeClipboardStrategy implements IClipboardStrategy {\n connect(context: IClipboardContext): IDisposable {\n const onCopy = (e: ClipboardEvent): void => {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n e.clipboardData?.setData('text/plain', text);\n };\n const onCut = (e: ClipboardEvent): void => {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n e.clipboardData?.setData('text/plain', text);\n context.deleteSelection();\n };\n const onPaste = (e: ClipboardEvent): void => {\n e.preventDefault();\n const text = e.clipboardData?.getData('text/plain');\n if (!text) { return; }\n context.insertText(text);\n };\n\n const el = context.element;\n el.addEventListener('copy', onCopy);\n el.addEventListener('cut', onCut);\n el.addEventListener('paste', onPaste);\n return {\n dispose: () => {\n el.removeEventListener('copy', onCopy);\n el.removeEventListener('cut', onCut);\n el.removeEventListener('paste', onPaste);\n },\n };\n }\n}\n\n/**\n * Strategy for hosts that never deliver native clipboard events to the editor\n * — most importantly VS Code webviews, whose preload calls `preventDefault()`\n * on the Ctrl/Cmd+C/X/V keydowns, so no `copy`/`cut`/`paste` event is ever\n * dispatched. Here the keystrokes are the only signal, so this strategy\n * listens for them directly and drives the async {@link Clipboard} API\n * (`navigator.clipboard`), which webviews are granted.\n *\n * Cut deletes synchronously once the text is captured; the clipboard write is\n * fire-and-forget. Paste must wait for the async read before inserting.\n */\nexport class AsyncClipboardStrategy implements IClipboardStrategy {\n constructor(private readonly _clipboard: Clipboard = navigator.clipboard) { }\n\n connect(context: IClipboardContext): IDisposable {\n const onKeyDown = (e: KeyboardEvent): void => {\n const ctrl = e.ctrlKey || e.metaKey;\n if (!ctrl || e.altKey) { return; }\n\n switch (e.key.toLowerCase()) {\n case 'c': {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n void this._clipboard.writeText(text);\n break;\n }\n case 'x': {\n const text = context.getSelectedText();\n if (text === undefined) { return; }\n e.preventDefault();\n void this._clipboard.writeText(text);\n context.deleteSelection();\n break;\n }\n case 'v': {\n e.preventDefault();\n void this._clipboard.readText().then(text => {\n if (text) { context.insertText(text); }\n });\n break;\n }\n }\n };\n\n const el = context.element;\n el.addEventListener('keydown', onKeyDown);\n return { dispose: () => el.removeEventListener('keydown', onKeyDown) };\n }\n}\n","import { Disposable } from '@vscode/observables';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { Point2D } from '../core/geometry.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { Selection } from '../core/selection.js';\nimport type { EditorModel } from '../model/editorModel.js';\nimport type { BlockAstNode, DocumentAstNode } from '../parser/ast.js';\nimport {\n cursorRight, cursorLeft, cursorMoveRight, cursorMoveLeft,\n cursorWordRight, cursorWordLeft, cursorLineStart, cursorLineEnd,\n cursorDocumentStart, cursorDocumentEnd, cursorUp, cursorDown,\n} from '../commands/cursorCommands.js';\nimport {\n deleteLeft, deleteRight, deleteWordLeft, deleteWordRight,\n insertText, insertParagraph, insertHardLineBreak, insertSmartEnter,\n} from '../commands/editCommands.js';\nimport { selectAll, selectWord, selectBlock } from '../commands/selectionCommands.js';\nimport type { CursorCommand, EditCommand, VisualCursorCommand, CursorCommandContext, VisualCursorCommandContext } from '../commands/types.js';\nimport type { EditorView } from './editorView.js';\nimport { NativeClipboardStrategy, type IClipboardStrategy } from './clipboardStrategy.js';\n\n/** Options for an {@link EditorController}. */\nexport interface EditorControllerOptions {\n /**\n * How copy/cut/paste is handled. Defaults to {@link NativeClipboardStrategy},\n * which reads the browser's native clipboard events — pass a different\n * strategy (e.g. `AsyncClipboardStrategy`) in hosts that swallow them.\n */\n readonly clipboardStrategy?: IClipboardStrategy;\n}\n\n/**\n * Translates raw browser input (mouse, keyboard, EditContext) into model\n * mutations. Knows about DOM event types but never reads/writes the DOM\n * directly — it asks the {@link EditorView} to broker DOM↔source-offset\n * conversions so the model stays free of view types.\n *\n * Owns the only non-derivable controller state:\n * - `_desiredColumn` — sticky column for up/down navigation\n */\nexport class EditorController extends Disposable {\n private _desiredColumn: number | undefined;\n\n constructor(\n private readonly _model: EditorModel,\n private readonly _view: EditorView,\n options?: EditorControllerOptions,\n ) {\n super();\n const el = this._view.element;\n el.addEventListener('mousedown', this._handleMouseDown);\n el.addEventListener('keydown', this._handleKeyDown);\n this._register({\n dispose: () => {\n el.removeEventListener('mousedown', this._handleMouseDown);\n el.removeEventListener('keydown', this._handleKeyDown);\n },\n });\n\n // Track the live Ctrl/Cmd state on the model. Listen on the window (not\n // just the editor element) so a release or focus loss while the pointer\n // is elsewhere still clears it, avoiding a stuck modifier.\n const win = el.ownerDocument.defaultView ?? window;\n win.addEventListener('keydown', this._updateModifierState);\n win.addEventListener('keyup', this._updateModifierState);\n win.addEventListener('blur', this._clearModifierState);\n this._register({\n dispose: () => {\n win.removeEventListener('keydown', this._updateModifierState);\n win.removeEventListener('keyup', this._updateModifierState);\n win.removeEventListener('blur', this._clearModifierState);\n },\n });\n\n const clipboardStrategy = options?.clipboardStrategy ?? new NativeClipboardStrategy();\n this._register(clipboardStrategy.connect({\n element: el,\n getSelectedText: () => this._selectedText(),\n deleteSelection: () => this._executeEditCommand(deleteLeft),\n insertText: text => {\n // Paste while a paragraph is pending materializes it, mirroring\n // the typed-character path in `_handleTextUpdate`.\n if (this._model.pendingParagraph.get() !== undefined) {\n this._model.materializePendingParagraph(text);\n } else {\n this._executeEditCommand(insertText(text));\n }\n },\n }));\n\n const editContext = this._view.editContext;\n editContext.addEventListener('textupdate', this._handleTextUpdate);\n this._register({\n dispose: () => editContext.removeEventListener('textupdate', this._handleTextUpdate as EventListener),\n });\n }\n\n private readonly _handleTextUpdate = (e: TextUpdateEvent): void => {\n // While an empty paragraph is pending, the first typed text materializes\n // it into real source; an empty update just cancels it.\n if (this._model.pendingParagraph.get() !== undefined) {\n if (e.text.length > 0) {\n this._model.materializePendingParagraph(e.text);\n } else {\n this._model.cancelPendingParagraph();\n }\n return;\n }\n const edit = StringEdit.replace(\n new OffsetRange(e.updateRangeStart, e.updateRangeEnd),\n e.text,\n );\n this._model.applyEdit(edit);\n };\n\n private readonly _handleMouseDown = (e: MouseEvent): void => {\n e.preventDefault();\n this._model.cancelPendingParagraph();\n this._view.focus();\n this._desiredColumn = undefined;\n\n const point = new Point2D(e.clientX, e.clientY);\n\n // A click on the editor padding (outside the rendered document content)\n // clears the selection entirely.\n if (!this._view.isPointInContent(point)) {\n this._model.selection.set(undefined, undefined);\n return;\n }\n\n const offset = this._view.resolveOffsetFromPoint(point)\n ?? this._model.sourceText.get().value.length;\n\n if (e.detail === 2) {\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectWord(ctx, offset), undefined);\n return;\n }\n\n if (e.detail === 3) {\n const blockRange = findBlockRangeAt(this._model.document.get(), offset);\n if (blockRange) {\n this._model.selection.set(selectBlock(this._makeCursorContext(), blockRange), undefined);\n }\n return;\n }\n\n if (e.shiftKey) {\n const sel = this._model.selection.get() ?? Selection.collapsed(offset);\n this._model.selection.set(sel.withActive(offset), undefined);\n } else {\n this._model.selection.set(Selection.collapsed(offset), undefined);\n }\n\n const onMouseMove = (me: MouseEvent): void => {\n const sel = this._model.selection.get() ?? Selection.collapsed(offset);\n const moveOffset = this._view.resolveOffsetFromPoint(new Point2D(me.clientX, me.clientY))\n ?? sel.active;\n this._model.selection.set(new Selection(sel.anchor, moveOffset), undefined);\n };\n const onMouseUp = (): void => {\n document.removeEventListener('mousemove', onMouseMove);\n document.removeEventListener('mouseup', onMouseUp);\n };\n document.addEventListener('mousemove', onMouseMove);\n document.addEventListener('mouseup', onMouseUp);\n };\n\n private _makeCursorContext(): CursorCommandContext {\n return {\n text: this._model.sourceText.get().value,\n selection: this._model.selection.get() ?? Selection.collapsed(0),\n document: this._model.document.get(),\n activeBlock: this._model.activeBlock.get(),\n };\n }\n\n private _makeVisualCursorContext(): VisualCursorCommandContext {\n return {\n ...this._makeCursorContext(),\n desiredColumn: this._desiredColumn,\n lineMap: this._view.measuredLayout.visualLineMap.get(),\n };\n }\n\n private _executeCursorCommand(command: CursorCommand, extend: boolean): void {\n const ctx = this._makeCursorContext();\n const newOffset = command(ctx);\n const sel = ctx.selection;\n this._model.selection.set(\n extend ? sel.withActive(newOffset) : Selection.collapsed(newOffset),\n undefined,\n );\n this._desiredColumn = undefined;\n }\n\n private _executeEditCommand(command: EditCommand): void {\n const ctx = this._makeCursorContext();\n const result = command(ctx);\n if (!result) { return; }\n this._model.applyEdit(result.edit);\n this._desiredColumn = undefined;\n }\n\n private _executeVisualCursorCommand(command: VisualCursorCommand, extend: boolean): void {\n const ctx = this._makeVisualCursorContext();\n const result = command(ctx);\n this._model.selection.set(\n extend ? ctx.selection.withActive(result.offset) : Selection.collapsed(result.offset),\n undefined,\n );\n this._desiredColumn = result.desiredColumn;\n }\n\n /** Move the cursor down one visual line (Arrow Down). */\n cursorDown(extend = false): void {\n this._executeVisualCursorCommand(cursorDown, extend);\n }\n\n /** Move the cursor up one visual line (Arrow Up). */\n cursorUp(extend = false): void {\n this._executeVisualCursorCommand(cursorUp, extend);\n }\n\n private _selectedText(): string | undefined {\n const sel = this._model.selection.get();\n if (!sel || sel.isCollapsed) { return undefined; }\n return this._model.sourceText.get().value.slice(sel.range.start, sel.range.endExclusive);\n }\n\n private readonly _updateModifierState = (e: KeyboardEvent): void => {\n this._model.ctrlOrMetaDown.set(e.ctrlKey || e.metaKey, undefined);\n };\n\n private readonly _clearModifierState = (): void => {\n this._model.ctrlOrMetaDown.set(false, undefined);\n };\n\n private readonly _handleKeyDown = (e: KeyboardEvent): void => {\n const ctrl = e.ctrlKey || e.metaKey;\n\n // A pending empty paragraph is transient. Navigation and deletion keys\n // abandon it here; a printable character must instead be left for the\n // `textupdate` handler to *materialize* it (cancelling here would drop\n // the pending state and the character would land in the old paragraph),\n // and a bare Enter falls through to `_smartEnter` (re-arm / push down).\n if (this._model.pendingParagraph.get() !== undefined) {\n if (e.key === 'Backspace' || e.key === 'Escape') {\n e.preventDefault();\n this._model.cancelPendingParagraph();\n return;\n }\n if (\n e.key === 'ArrowLeft' || e.key === 'ArrowRight'\n || e.key === 'ArrowUp' || e.key === 'ArrowDown'\n || e.key === 'Home' || e.key === 'End' || e.key === 'Delete'\n ) {\n this._model.cancelPendingParagraph();\n }\n }\n\n if (e.key === 'ArrowLeft') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(e.shiftKey ? cursorWordLeft : cursorWordLeft, e.shiftKey);\n } else if (e.shiftKey) {\n this._executeCursorCommand(cursorMoveLeft, true);\n } else {\n this._executeCursorCommand(cursorLeft, false);\n }\n } else if (e.key === 'ArrowRight') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorWordRight, e.shiftKey);\n } else if (e.shiftKey) {\n this._executeCursorCommand(cursorMoveRight, true);\n } else {\n this._executeCursorCommand(cursorRight, false);\n }\n } else if (e.key === 'ArrowUp') {\n e.preventDefault();\n this._executeVisualCursorCommand(cursorUp, e.shiftKey);\n } else if (e.key === 'ArrowDown') {\n e.preventDefault();\n this._executeVisualCursorCommand(cursorDown, e.shiftKey);\n } else if (e.key === 'Home') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorDocumentStart, e.shiftKey);\n } else {\n this._executeCursorCommand(cursorLineStart, e.shiftKey);\n }\n } else if (e.key === 'End') {\n e.preventDefault();\n if (ctrl) {\n this._executeCursorCommand(cursorDocumentEnd, e.shiftKey);\n } else {\n this._executeCursorCommand(cursorLineEnd, e.shiftKey);\n }\n } else if (e.key === 'a' && ctrl) {\n e.preventDefault();\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectAll(ctx, 0), undefined);\n } else if (e.key === 'Backspace') {\n e.preventDefault();\n this._executeEditCommand(ctrl ? deleteWordLeft : deleteLeft);\n } else if (e.key === 'Delete') {\n e.preventDefault();\n this._executeEditCommand(ctrl ? deleteWordRight : deleteRight);\n } else if (e.key === 'Enter') {\n e.preventDefault();\n if (ctrl) {\n this._executeEditCommand(insertParagraph);\n } else if (e.shiftKey) {\n this._executeEditCommand(insertHardLineBreak);\n } else {\n this._smartEnter();\n }\n }\n };\n\n /**\n * Context-aware Enter: splits / line-breaks via {@link insertSmartEnter}, or\n * arms a transient empty paragraph when at the end of a paragraph.\n */\n private _smartEnter(): void {\n const ctx = this._makeCursorContext();\n const result = insertSmartEnter(ctx);\n if (result.kind === 'edit') {\n this._model.applyEdit(result.edit);\n this._model.selection.set(result.selection, undefined);\n } else {\n this._model.armPendingParagraph({\n anchorBlock: result.anchorBlock,\n replaceRange: result.replaceRange,\n atEof: result.atEof,\n });\n }\n this._desiredColumn = undefined;\n }\n}\n\nfunction findBlockRangeAt(doc: DocumentAstNode, offset: number): OffsetRange | undefined {\n let pos = 0;\n for (const child of doc.children) {\n if (doc.blocks.includes(child as BlockAstNode)) {\n const range = OffsetRange.ofStartAndLength(pos, child.length);\n if (range.contains(offset) || range.endExclusive === offset) {\n return range;\n }\n }\n pos += child.length;\n }\n return undefined;\n}\n","import { Disposable, autorun, derived, observableValue, type IObservable, type ISettableObservable } from '@vscode/observables';\nimport type { BlockMeasurement, MeasuredLayoutModel } from '../model/measuredLayoutModel.js';\nimport type { ViewNode } from './content/viewNode.js';\n\nconst _SHOW_LINE_RECTS_KEY = 'md-debug-show-line-rects';\n\nfunction _readStoredBool(key: string, fallback: boolean): boolean {\n try {\n const v = localStorage.getItem(key);\n return v === null ? fallback : v === 'true';\n } catch {\n return fallback;\n }\n}\n\nfunction _writeStoredBool(key: string, value: boolean): void {\n try {\n localStorage.setItem(key, String(value));\n } catch {\n // Ignore: debug-only, storage may be unavailable.\n }\n}\n\nexport interface MeasuredLayoutDebugViewOptions {\n readonly model: MeasuredLayoutModel;\n /**\n * DEBUG ONLY. Maps an absolute source offset to a fill color for that\n * character's glyph rect. The fixture passes the same function to the\n * raw-source view so a character and its rect share one color — a\n * mismatch exposes a source ↔ DOM mapping bug.\n */\n readonly colorForOffset?: (offset: number) => string | undefined;\n /**\n * DEBUG ONLY. Shared \"currently hovered source offset\". When set, the\n * overlay isolates the matching glyph rect; the fixture passes the same\n * observable to the raw-source view so hovering either side highlights the\n * same character in both. Hovering a rect writes this; `undefined` clears.\n */\n readonly hoveredOffset?: ISettableObservable<number | undefined>;\n}\n\n/**\n * Debug view for a {@link MeasuredLayoutModel}.\n *\n * Exposes two DOM nodes the caller can place independently:\n *\n * - {@link overlayElement} — absolutely positioned; the caller mounts it\n * inside the editor element so dashed line-bands and run-boxes line up\n * with the editor's client coordinates.\n * - {@link infoElement} — block-flow; the caller mounts it as a sibling\n * *below* the editor. Contains the per-block summary table that used\n * to live on the overlay.\n *\n * Same pattern as `CursorView` / `SelectionView`: the rendering pipeline\n * is a single `derived` whose compute callback writes the DOM and returns\n * a {@link MeasuredLayoutDebugRendering} value as proof. An autorun keeps\n * the derived subscribed.\n */\nexport class MeasuredLayoutDebugView extends Disposable {\n readonly overlayElement: HTMLElement;\n readonly infoElement: HTMLElement;\n readonly rendering: IObservable<MeasuredLayoutDebugRendering>;\n\n /** Absolute source offsets that map to a rendered DOM character. */\n readonly mappedOffsets: IObservable<ReadonlySet<number>>;\n\n /** Whether the dashed line-bands and run boxes are drawn (persisted). */\n private readonly _showLineRects = observableValue(this, _readStoredBool(_SHOW_LINE_RECTS_KEY, true));\n\n constructor(\n private readonly _overlayParent: HTMLElement,\n options: MeasuredLayoutDebugViewOptions,\n ) {\n super();\n\n this.overlayElement = document.createElement('div');\n this.overlayElement.className = 'md-debug-layout-overlay';\n Object.assign(this.overlayElement.style, {\n position: 'absolute',\n top: '0',\n left: '0',\n right: '0',\n bottom: '0',\n pointerEvents: 'none',\n } satisfies Partial<CSSStyleDeclaration>);\n\n this.infoElement = document.createElement('div');\n this.infoElement.className = 'md-debug-layout-info';\n Object.assign(this.infoElement.style, {\n fontFamily: 'monospace',\n fontSize: '11px',\n padding: '8px 12px',\n background: '#111',\n color: '#fff',\n borderRadius: '4px',\n lineHeight: '1.4',\n } satisfies Partial<CSSStyleDeclaration>);\n\n // Controls row (survives re-render) + a text element the render rewrites.\n const controls = document.createElement('label');\n Object.assign(controls.style, {\n display: 'flex',\n alignItems: 'center',\n gap: '6px',\n marginBottom: '6px',\n cursor: 'pointer',\n userSelect: 'none',\n } satisfies Partial<CSSStyleDeclaration>);\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = this._showLineRects.get();\n checkbox.addEventListener('change', () => {\n this._showLineRects.set(checkbox.checked, undefined);\n _writeStoredBool(_SHOW_LINE_RECTS_KEY, checkbox.checked);\n });\n controls.appendChild(checkbox);\n controls.appendChild(document.createTextNode('show line rects'));\n this.infoElement.appendChild(controls);\n\n const text = document.createElement('pre');\n text.style.margin = '0';\n text.style.whiteSpace = 'pre';\n this.infoElement.appendChild(text);\n\n this.rendering = derived(this, reader => {\n const measurements = reader.readObservable(options.model.measurements);\n const showLineRects = reader.readObservable(this._showLineRects);\n return _renderDebug(this.overlayElement, text, this._overlayParent, measurements, showLineRects, options.colorForOffset, options.hoveredOffset);\n });\n\n this.mappedOffsets = derived(this, reader => reader.readObservable(this.rendering).mappedOffsets);\n\n // Re-read `rendering` so isolation re-applies after every rebuild, and\n // `hoveredOffset` so hovering either view isolates the matching rect.\n this._register(autorun(reader => {\n reader.readObservable(this.rendering);\n const hovered = options.hoveredOffset ? reader.readObservable(options.hoveredOffset) : undefined;\n if (options.hoveredOffset) { applyHoverIsolation(this.overlayElement, hovered); }\n }));\n }\n}\n\n\n/**\n * Immutable record of one rendered debug frame.\n */\nexport class MeasuredLayoutDebugRendering {\n constructor(\n readonly blockCount: number,\n readonly mountedCount: number,\n readonly lineCount: number,\n /** Absolute source offsets that map to a rendered DOM character. */\n readonly mappedOffsets: ReadonlySet<number>,\n ) { }\n}\n\nfunction _renderDebug(\n overlay: HTMLElement,\n info: HTMLElement,\n overlayParent: HTMLElement,\n measurements: readonly BlockMeasurement[],\n showLineRects: boolean,\n colorForOffset?: (offset: number) => string | undefined,\n hoveredOffset?: ISettableObservable<number | undefined>,\n): MeasuredLayoutDebugRendering {\n overlay.textContent = '';\n const parentRect = overlayParent.getBoundingClientRect();\n\n let mountedCount = 0;\n let lineCount = 0;\n let charCount = 0;\n const mappedOffsets = new Set<number>();\n\n for (let i = 0; i < measurements.length; i++) {\n const m = measurements[i];\n const lines = m.visualLineMap?.lines ?? [];\n if (m.isMeasured) { mountedCount++; }\n lineCount += lines.length;\n\n if (showLineRects) {\n for (let li = 0; li < lines.length; li++) {\n const line = lines[li];\n const lineRect = line.rect;\n const band = document.createElement('div');\n Object.assign(band.style, {\n position: 'absolute',\n left: '0',\n right: '0',\n top: `${lineRect.y - parentRect.top}px`,\n height: `${lineRect.height}px`,\n border: '1px dashed rgba(180, 0, 200, 0.45)',\n boxSizing: 'border-box',\n } satisfies Partial<CSSStyleDeclaration>);\n overlay.appendChild(band);\n\n for (const run of line.runs) {\n const runBox = document.createElement('div');\n Object.assign(runBox.style, {\n position: 'absolute',\n left: `${run.rect.x - parentRect.left}px`,\n top: `${run.rect.y - parentRect.top}px`,\n width: `${run.rect.width}px`,\n height: `${run.rect.height}px`,\n outline: '1px solid rgba(255, 100, 0, 0.45)',\n boxSizing: 'border-box',\n } satisfies Partial<CSSStyleDeclaration>);\n overlay.appendChild(runBox);\n }\n }\n }\n\n // Per-character glyph rects (mounted blocks only). Resolve each source\n // offset back to a DOM position through the production source ↔ DOM\n // mapping, so a misplaced rect reveals a mapping bug.\n if (m.viewNode) {\n charCount += _appendCharRects(overlay, parentRect, m.viewNode, m.absoluteStart, mappedOffsets, colorForOffset, hoveredOffset);\n }\n }\n\n const header = `blocks: ${measurements.length} mounted: ${mountedCount} lines: ${lineCount} chars: ${charCount}`;\n const rows = measurements.map((m, i) => {\n const flag = m.isMeasured ? 'M' : 'e';\n const lc = m.visualLineMap?.lines.length ?? 0;\n return `${String(i).padStart(2)} ${flag} start=${String(m.absoluteStart).padStart(4)} h=${m.height.toFixed(1).padStart(6)} lines=${lc} kind=${m.block.kind}`;\n });\n info.textContent = [header, ...rows].join('\\n');\n\n return new MeasuredLayoutDebugRendering(measurements.length, mountedCount, lineCount, mappedOffsets);\n}\n\n/**\n * Draw one filled box per character of the block's source range. Each source\n * offset `o` is mapped to a DOM position with {@link ViewNode.sourceToDom}\n * (the same mapping the cursor uses), and `[o, o+1)` is measured with a\n * `Range`. The box is filled (no border) with {@link colorForOffset}`(o)` so\n * it matches the same character in the raw-source view.\n *\n * Each box carries `data-offset` so {@link applyHoverIsolation} can isolate it.\n * Hovering a box writes its offset into {@link hoveredOffset} (shared with the\n * raw-source view); when no shared observable is supplied it falls back to a\n * local overlay-only isolation. Returns the number of character boxes appended.\n */\nfunction _appendCharRects(\n overlay: HTMLElement,\n parentRect: DOMRect,\n viewNode: ViewNode,\n blockAbsoluteStart: number,\n mappedOffsets: Set<number>,\n colorForOffset?: (offset: number) => string | undefined,\n hoveredOffset?: ISettableObservable<number | undefined>,\n): number {\n let count = 0;\n const range = document.createRange();\n const end = blockAbsoluteStart + viewNode.sourceLength;\n // Source offsets actually backed by a rendered DOM Text leaf. Characters\n // outside any leaf (list markers `- `, newlines, other syntax) are not\n // rendered, so we must not draw a rect for them. `sourceToDom` alone can't\n // tell them apart because it clamps unmapped offsets to an adjacent leaf's\n // boundary; the leaf coverage from `forEachTextLeaf` is authoritative.\n const covered: Array<{ start: number; end: number }> = [];\n viewNode.forEachTextLeaf(blockAbsoluteStart, (leaf, leafOffset) => {\n covered.push({ start: leafOffset, end: leafOffset + leaf.sourceLength });\n });\n const isCovered = (o: number) => covered.some(r => o >= r.start && o < r.end);\n for (let o = blockAbsoluteStart; o < end; o++) {\n if (!isCovered(o)) { continue; }\n // The character occupies source range [o, o+1). Use its END position to\n // identify the rendered DOM character, then step back one within the\n // same Text node to get its start.\n const b = viewNode.sourceToDom(o + 1, blockAbsoluteStart);\n if (!b || b.offset < 1) { continue; }\n range.setStart(b.node, b.offset - 1);\n range.setEnd(b.node, b.offset);\n const rect = range.getBoundingClientRect();\n // A character with no height isn't laid out at all — skip it. A\n // zero-WIDTH rect, though, is a real mapped character that simply has no\n // advance (a `\\n` inside a code block maps to a real `\\n` Text node):\n // render it as a thin 2px line so the mapping is still visible.\n if (rect.height === 0) { continue; }\n const drawWidth = rect.width === 0 ? 2 : rect.width;\n const box = document.createElement('div');\n Object.assign(box.style, {\n position: 'absolute',\n left: `${rect.x - parentRect.left}px`,\n top: `${rect.y - parentRect.top}px`,\n width: `${drawWidth}px`,\n height: `${rect.height}px`,\n background: colorForOffset?.(o) ?? 'rgba(0, 120, 220, 0.30)',\n boxSizing: 'border-box',\n pointerEvents: 'auto',\n } satisfies Partial<CSSStyleDeclaration>);\n const ch = (b.node as Text).data?.[b.offset - 1] ?? '';\n box.title = `offset ${o}: ${JSON.stringify(ch)}`;\n box.dataset.offset = String(o);\n if (hoveredOffset) {\n box.addEventListener('mouseenter', () => hoveredOffset.set(o, undefined));\n box.addEventListener('mouseleave', () => hoveredOffset.set(undefined, undefined));\n } else {\n box.addEventListener('mouseenter', () => _isolate(overlay, box, true));\n box.addEventListener('mouseleave', () => _isolate(overlay, box, false));\n }\n overlay.appendChild(box);\n mappedOffsets.add(o);\n count++;\n }\n return count;\n}\n\n/**\n * Show only the element whose `data-offset` equals `hovered`, hiding every\n * other child (and all children lacking a `data-offset`, e.g. line bands).\n * When `hovered` is `undefined` everything is restored. `visibility: hidden`\n * preserves layout so the source view's text never reflows.\n *\n * Used identically for the editor overlay and the raw-source view, so a hover\n * on either side highlights the same character in both. Debug-only.\n */\nexport function applyHoverIsolation(container: HTMLElement, hovered: number | undefined): void {\n for (const el of Array.from(container.children) as HTMLElement[]) {\n if (!el.style) { continue; }\n const off = el.dataset.offset;\n const matches = off !== undefined && Number(off) === hovered;\n el.style.visibility = hovered === undefined || matches ? '' : 'hidden';\n }\n}\n\n/**\n * Show only `keep` (when `on`) or restore every overlay element (when `off`).\n * Debug-only, so the brute-force walk over all siblings is fine.\n */\nfunction _isolate(overlay: HTMLElement, keep: HTMLElement, on: boolean): void {\n for (const el of Array.from(overlay.children) as HTMLElement[]) {\n el.style.visibility = on && el !== keep ? 'hidden' : '';\n }\n}\n\n","import type { IObservableWithChange, ITransaction, IDisposable } from '@vscode/observables';\nimport type { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport type { LengthEdit } from '../core/lengthEdit.js';\n\nexport interface ISyntaxHighlighter {\n create(language: string, initialText: string): ISyntaxHighlighterDocument;\n}\n\nexport interface ISyntaxHighlighterDocument extends IDisposable {\n /**\n * Apply a source edit. The {@link snapshot} updates synchronously within\n * `tx`, and the change it carries is the *minimal* {@link LengthEdit} that\n * actually re-coloured — not the whole document.\n */\n update(edit: StringEdit, tx: ITransaction): void;\n\n /**\n * The current snapshot. Its change reason is a {@link LengthEdit} mapping\n * the previous snapshot's offsets to this one's wherever tokens changed.\n */\n readonly snapshot: IObservableWithChange<ISyntaxHighlightedSnapshot, LengthEdit>;\n}\n\n/**\n * An immutable view of one document's tokens at a point in time. It may be a\n * thin view over the highlighter's mutable state: once the underlying document\n * advances, calling a stale snapshot is allowed to throw.\n *\n * Token stability: across snapshots `S1 -> S2` (with the change delivered as a\n * {@link LengthEdit}), `getTokens(r)` returns the same tokens for any range `r`\n * not touched by that edit. Only ranges the edit reports as changed may recolour.\n */\nexport interface ISyntaxHighlightedSnapshot {\n /**\n * Tokens covering a region that contains `queryRange`. Tokens are never\n * split: the returned {@link SnapshotTokens.range} is `queryRange` *grown*\n * to whole-token boundaries, so a token that straddles an end of\n * `queryRange` is returned in full. The result is dense over that grown\n * range — `sum(token.length) === range.length` — which is why the range is\n * returned alongside the tokens.\n */\n getTokens(queryRange: OffsetRange): SnapshotTokens;\n}\n\n/**\n * A run of {@link Token}s together with the exact {@link OffsetRange} they\n * cover.\n *\n * Because tokens are returned whole (never clipped), this is the natural unit\n * of structural comparison: for any region untouched by an edit, two snapshots\n * return an equal `SnapshotTokens` (same `range`, same token lengths/classes).\n */\nexport interface SnapshotTokens {\n readonly range: OffsetRange;\n readonly tokens: readonly Token[];\n}\n\n/**\n * A coloured run of `length` characters. Tokens are *dense* and *offset-free*:\n * a snapshot's tokens for a range cover it exactly, back to back, so\n * `sum(token.length) === range.length`. A token never stores where it is — its\n * position is implied by the lengths of the tokens before it, mirroring how the\n * rest of the editor keeps source offsets out of its data structures.\n */\nexport class Token {\n constructor(\n readonly length: number,\n /** CSS class for this run, or `undefined` for an unstyled run. */\n readonly className: string | undefined,\n ) { }\n}\n","import { observableValue, type ISettableObservable, type ITransaction } from '@vscode/observables';\nimport type { MonarchTokenizer, IMonarchTokenizerState } from 'monaco-editor/esm/vs/editor/standalone/common/monarch/monarchLexer.js';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit } from '../core/stringEdit.js';\nimport { LengthEdit } from '../core/lengthEdit.js';\nimport { Token, type ISyntaxHighlightedSnapshot, type ISyntaxHighlighterDocument, type ISyntaxHighlighter, type SnapshotTokens } from './syntaxHighlighter.js';\n\n/**\n * The slice of monaco's Monarch internals the highlighter needs at runtime.\n *\n * `monaco-editor` is only a *type* dependency of this package; the caller (who\n * owns a real monaco runtime) passes these in, keeping monaco out of the bundle.\n */\nexport interface IMonarchApi {\n /** Compiles a Monarch language definition into the internal lexer form. */\n compile(languageId: string, json: unknown): unknown;\n MonarchTokenizer: new (\n languageService: unknown,\n standaloneThemeService: unknown,\n languageId: string,\n lexer: unknown,\n configurationService: unknown,\n ) => MonarchTokenizer;\n}\n\n/**\n * {@link ISyntaxHighlighter} backed by monaco's Monarch tokenizer.\n *\n * Highlighting is synchronous and incremental: an edit only re-runs the\n * tokenizer from the first changed line onward (earlier lines and their saved\n * end-states are reused), and the {@link LengthEdit} delivered with the new\n * snapshot is the minimal char range whose colour actually changed.\n *\n * Only Monarch's *classic* tokenizer path is used, which needs neither a theme\n * nor the DOM, so this runs headless (Node, workers) as well as in the browser.\n */\nexport class MonacoSyntaxHighlighter implements ISyntaxHighlighter {\n private readonly _tokenizers = new Map<string, MonarchTokenizer>();\n\n /**\n * @param _monaco The Monarch runtime ({@link IMonarchApi}), injected so this\n * package depends on `monaco-editor` for types only.\n * @param _grammars Maps a language id to its Monarch language definition.\n */\n constructor(\n private readonly _monaco: IMonarchApi,\n private readonly _grammars: ReadonlyMap<string, unknown>,\n ) { }\n\n create(language: string, initialText: string): ISyntaxHighlighterDocument {\n return new MonacoHighlighterDocument(this._tokenizerFor(language), initialText);\n }\n\n dispose(): void {\n for (const t of this._tokenizers.values()) { t.dispose(); }\n this._tokenizers.clear();\n }\n\n private _tokenizerFor(language: string): MonarchTokenizer | undefined {\n const grammar = this._grammars.get(language);\n if (grammar === undefined) { return undefined; }\n let tokenizer = this._tokenizers.get(language);\n if (!tokenizer) {\n tokenizer = new this._monaco.MonarchTokenizer(_stubLanguageService, _stubThemeService, language, this._monaco.compile(language, grammar), _stubConfigurationService);\n this._tokenizers.set(language, tokenizer);\n }\n return tokenizer;\n }\n}\n\ninterface LineData {\n readonly text: string;\n /** Tokens covering `text` exactly: `sum(token.length) === text.length`. */\n readonly tokens: readonly Token[];\n /** Monarch state after this line — the start state of the next line. */\n readonly endState: IMonarchTokenizerState;\n}\n\nclass MonacoHighlighterDocument implements ISyntaxHighlighterDocument {\n private _text: string;\n private _lines: LineData[];\n /** Source offset of each line's first char; `length === _lines.length`. */\n private _lineStarts: number[];\n private _version = 1;\n private _disposed = false;\n\n private readonly _initialState: IMonarchTokenizerState | undefined;\n private readonly _snapshotObs: ISettableObservable<ISyntaxHighlightedSnapshot, LengthEdit>;\n\n constructor(\n private readonly _tokenizer: MonarchTokenizer | undefined,\n initialText: string,\n ) {\n this._initialState = _tokenizer?.getInitialState();\n this._text = initialText;\n this._lines = this._tokenizeFrom(0, [], this._initialState, initialText.split('\\n'));\n this._lineStarts = this._computeLineStarts();\n this._snapshotObs = observableValue('syntaxSnapshot', new MonacoHighlightedSnapshot(this, this._version));\n }\n\n get snapshot() { return this._snapshotObs; }\n\n update(edit: StringEdit, tx: ITransaction): void {\n if (this._disposed) { throw new Error('document is disposed'); }\n if (edit.isEmpty) { return; }\n\n const oldTokens = _flatTokens(this._lines);\n const newText = edit.apply(this._text);\n const firstChangedOffset = edit.replacements[0].replaceRange.start;\n const firstChangedLine = this._lineIndexAt(firstChangedOffset);\n\n const reusedPrefix = this._lines.slice(0, firstChangedLine);\n const startState = firstChangedLine === 0\n ? this._initialState\n : this._lines[firstChangedLine - 1].endState;\n\n this._text = newText;\n this._lines = this._tokenizeFrom(firstChangedLine, reusedPrefix, startState, newText.split('\\n'));\n this._lineStarts = this._computeLineStarts();\n this._version++;\n\n const lengthEdit = _minimalRecolor(oldTokens, _flatTokens(this._lines));\n this._snapshotObs.set(new MonacoHighlightedSnapshot(this, this._version), tx, lengthEdit);\n }\n\n dispose(): void {\n // The tokenizer is shared and owned by the highlighter, not this document.\n this._disposed = true;\n }\n\n /**\n * Tokenize `allLines[fromLine..]`, keeping `reusedPrefix` (already tokenized\n * lines `[0, fromLine)`) verbatim. `startState` is the state entering\n * `fromLine`.\n */\n private _tokenizeFrom(\n fromLine: number,\n reusedPrefix: readonly LineData[],\n startState: IMonarchTokenizerState | undefined,\n allLines: readonly string[],\n ): LineData[] {\n const lines: LineData[] = reusedPrefix.slice();\n let state = startState;\n for (let i = fromLine; i < allLines.length; i++) {\n const text = allLines[i];\n const hasEOL = i < allLines.length - 1;\n if (this._tokenizer && state) {\n const result = this._tokenizer.tokenize(text, hasEOL, state);\n lines.push({ text, tokens: _toTokens(result.tokens, text.length), endState: result.endState });\n state = result.endState;\n } else {\n lines.push({ text, tokens: text.length === 0 ? [] : [new Token(text.length, undefined)], endState: state! });\n }\n }\n return lines;\n }\n\n private _computeLineStarts(): number[] {\n const starts: number[] = [];\n let offset = 0;\n for (const line of this._lines) {\n starts.push(offset);\n offset += line.text.length + 1; // + newline\n }\n return starts;\n }\n\n private _lineIndexAt(offset: number): number {\n for (let i = this._lineStarts.length - 1; i >= 0; i--) {\n if (offset >= this._lineStarts[i]) { return i; }\n }\n return 0;\n }\n\n /** @internal Called by {@link MonacoHighlightedSnapshot}. */\n _getTokens(version: number, queryRange: OffsetRange): SnapshotTokens {\n if (version !== this._version) { throw new Error('stale snapshot'); }\n const docLen = this._text.length;\n const queryStart = Math.max(0, Math.min(queryRange.start, docLen));\n const queryEnd = Math.max(queryStart, Math.min(queryRange.endExclusive, docLen));\n\n const tokens: Token[] = [];\n let rangeStart = queryStart;\n let rangeEnd = queryStart;\n let started = false;\n let pos = 0;\n const consider = (length: number, className: string | undefined): void => {\n const tokenStart = pos;\n const tokenEnd = pos + length;\n pos = tokenEnd;\n if (length === 0) { return; }\n // Keep whole tokens that overlap the query (an empty query overlaps none).\n if (tokenStart < queryEnd && tokenEnd > queryStart) {\n if (!started) { rangeStart = tokenStart; started = true; }\n tokens.push(new Token(length, className));\n rangeEnd = tokenEnd;\n }\n };\n for (let i = 0; i < this._lines.length && pos < queryEnd; i++) {\n for (const t of this._lines[i].tokens) { consider(t.length, t.className); }\n if (i < this._lines.length - 1) { consider(1, undefined); } // newline char\n }\n return { range: new OffsetRange(rangeStart, started ? rangeEnd : queryStart), tokens };\n }\n}\n\nclass MonacoHighlightedSnapshot implements ISyntaxHighlightedSnapshot {\n constructor(\n private readonly _doc: MonacoHighlighterDocument,\n private readonly _version: number,\n ) { }\n\n getTokens(queryRange: OffsetRange): SnapshotTokens {\n return this._doc._getTokens(this._version, queryRange);\n }\n}\n\n/** Monarch token type → CSS class. The empty type is an unstyled run. */\nfunction _classNameOf(type: string): string | undefined {\n return type === '' ? undefined : type;\n}\n\n/** Convert Monarch's (offset, type) tokens into dense length-based tokens. */\nfunction _toTokens(monarchTokens: readonly { readonly offset: number; readonly type: string }[], lineLength: number): Token[] {\n if (monarchTokens.length === 0) {\n return lineLength === 0 ? [] : [new Token(lineLength, undefined)];\n }\n const tokens: Token[] = [];\n for (let i = 0; i < monarchTokens.length; i++) {\n const startOffset = monarchTokens[i].offset;\n const endOffset = i + 1 < monarchTokens.length ? monarchTokens[i + 1].offset : lineLength;\n if (endOffset > startOffset) {\n tokens.push(new Token(endOffset - startOffset, _classNameOf(monarchTokens[i].type)));\n }\n }\n return tokens;\n}\n\n/**\n * The whole document's tokens as one dense, offset-free run — exactly the\n * sequence {@link MonacoHighlighterDocument._getTokens} would emit for the full\n * range, including the length-1 unstyled token for each inter-line newline.\n */\nfunction _flatTokens(lines: readonly LineData[]): Token[] {\n const tokens: Token[] = [];\n for (let i = 0; i < lines.length; i++) {\n for (const t of lines[i].tokens) { tokens.push(t); }\n if (i < lines.length - 1) { tokens.push(new Token(1, undefined)); } // newline char\n }\n return tokens;\n}\n\nfunction _tokensEqual(a: Token, b: Token): boolean {\n return a.length === b.length && a.className === b.className;\n}\n\nfunction _sumLengths(tokens: readonly Token[]): number {\n let sum = 0;\n for (const t of tokens) { sum += t.length; }\n return sum;\n}\n\n/**\n * The minimal {@link LengthEdit} taking the old token run to the new one,\n * snapped to *token* boundaries: trim the run of identical leading tokens and\n * the run of identical trailing tokens; whatever lies between is the only\n * region whose tokenization actually changed.\n *\n * Snapping to whole tokens (rather than to per-character colours) is what makes\n * the edit faithful: if a token merely grows or merges at a boundary, the whole\n * affected token is reported, so {@link ISyntaxHighlightedSnapshot.getTokens}\n * over any range the edit leaves untouched is structurally unchanged.\n */\nfunction _minimalRecolor(oldTokens: readonly Token[], newTokens: readonly Token[]): LengthEdit {\n const oldCount = oldTokens.length;\n const newCount = newTokens.length;\n\n let prefix = 0;\n let prefixChars = 0;\n while (prefix < oldCount && prefix < newCount && _tokensEqual(oldTokens[prefix], newTokens[prefix])) {\n prefixChars += oldTokens[prefix].length;\n prefix++;\n }\n\n let suffix = 0;\n let suffixChars = 0;\n while (suffix < oldCount - prefix && suffix < newCount - prefix\n && _tokensEqual(oldTokens[oldCount - 1 - suffix], newTokens[newCount - 1 - suffix])) {\n suffixChars += oldTokens[oldCount - 1 - suffix].length;\n suffix++;\n }\n\n const oldChars = _sumLengths(oldTokens);\n const newChars = _sumLengths(newTokens);\n const oldRange = new OffsetRange(prefixChars, oldChars - suffixChars);\n const newRangeLength = newChars - suffixChars - prefixChars;\n if (oldRange.isEmpty && newRangeLength === 0) { return LengthEdit.empty; }\n return LengthEdit.replace(oldRange, newRangeLength);\n}\n\n// --- Minimal headless stand-ins for the services MonarchTokenizer asks for. ---\n// The classic tokenizer path touches none of these on the hot path (only\n// embedded-language and encoded-token paths do), so empty stubs suffice.\n\nconst _stubLanguageService = {\n languageIdCodec: { encodeLanguageId: () => 0, decodeLanguageId: () => '' },\n isRegisteredLanguageId: () => false,\n getLanguageIdByLanguageName: () => null,\n getLanguageIdByMimeType: () => null,\n requestBasicLanguageFeatures: () => { },\n};\n\nconst _stubThemeService = {\n getColorTheme: () => ({ tokenTheme: {} }),\n};\n\nconst _stubConfigurationService = {\n getValue: () => 20000,\n onDidChangeConfiguration: () => ({ dispose() { } }),\n};\n","import { MonacoSyntaxHighlighter, type IMonarchApi } from './monacoSyntaxHighlighter.js';\n\n/** The Monarch language definitions the default highlighter wires up. */\nexport interface IDefaultMonarchGrammars {\n typescript: unknown;\n javascript: unknown;\n css: unknown;\n html: unknown;\n python: unknown;\n rust: unknown;\n shell: unknown;\n}\n\n/**\n * A {@link MonacoSyntaxHighlighter} preloaded with a handful of common Monarch\n * grammars (plus the usual short aliases). Unknown languages fall back to an\n * unstyled single token, so the highlighter is always safe to call.\n *\n * The Monarch runtime and grammar definitions are injected so this package\n * depends on `monaco-editor` for types only.\n */\nexport function createDefaultMonacoSyntaxHighlighter(\n monaco: IMonarchApi,\n grammars: IDefaultMonarchGrammars,\n): MonacoSyntaxHighlighter {\n const grammarMap = new Map<string, unknown>([\n ['typescript', grammars.typescript],\n ['ts', grammars.typescript],\n ['javascript', grammars.javascript],\n ['js', grammars.javascript],\n ['css', grammars.css],\n ['html', grammars.html],\n ['python', grammars.python],\n ['py', grammars.python],\n ['rust', grammars.rust],\n ['rs', grammars.rust],\n ['shell', grammars.shell],\n ['sh', grammars.shell],\n ['bash', grammars.shell],\n ]);\n return new MonacoSyntaxHighlighter(monaco, grammarMap);\n}\n"],"names":["OffsetRange","start","endExclusive","length","offset","other","end","str","arr","StringReplacement","replaceRange","newText","text","range","StringEdit","replacement","replacements","lastEndEx","base","parts","pos","r","original","edits","oldText","i","delta","LengthReplacement","newLength","LengthEdit","StringValue","value","Selection","anchor","active","Point2D","x","y","dx","dy","Rect2D","width","height","left","top","right","bottom","p","findWordBoundaryLeft","findWordBoundaryRight","len","findWordAt","ch","_nextNodeId","AstNode","sum","c","a","b","_other","id","clone","_emptyChildren","_mapArr","map","out","m","_mapOne","n","_mapTrivia","trivia","LeafAstNode","TextAstNode","content","o","MarkerAstNode","markerKind","GlueAstNode","glueKind","BlockAstNodeBase","own","ThematicBreakAstNode","leadingTrivia","_marker","kind","StrongAstNode","openMarker","closeMarker","EmphasisAstNode","StrikethroughAstNode","InlineCodeAstNode","InlineMathAstNode","LinkAstNode","url","ImageAstNode","alt","HeadingAstNode","level","marker","ParagraphAstNode","CodeBlockAstNode","language","previous","contentEdit","MathBlockAstNode","BlockQuoteAstNode","_isBlock","ListAstNode","ordered","ListItemAstNode","checked","TableAstNode","TableRowAstNode","TableCellAstNode","DocumentAstNode","findNodeOffsetById","root","target","child","inner","_TASK_CHECKBOX_RE","taskCheckboxRange","item","match","_nodeText","node","tokenize","source","parser","parse","math","gfmTable","gfmTaskListItem","gfmStrikethrough","chunks","preprocess","postprocess","type","token","AstBuilder","_pullIndentIntoBlocks","cur","next","hosted","_prependLeadingTrivia","prev","glue","firstIdx","items","j","_attachBlockGaps","idx","isParagraphBreak","gap","host","_appendTrailingGlue","h","_appendIntoLast","l","it","last","_ensureBlocks","Content","_parentStart","_source","parentLength","s","e","indent","_events","cb","ev","block","enter","markerStart","markerEnd","inlines","seqEnter","seqExit","exit","sawOpenFence","contentStart","contentEnd","fenceEnter","ii","fenceExit","flushContent","prefixEnter","prefixExit","seenBlock","pre","preExit","listType","itemStart","itemCb","itemChecked","lastBlockEnd","flush","itemEnd","columnCount","row","raw","pipes","cellStartsRel","cols","rowCb","cs","ce","cellCb","cellType","cellEnter","cellExit","entries","untilExit","tokenType","isStrong","openEnter","openExit","closeEnter","closeExit","sawOpen","sawOpenBracket","i2","sawOpenParen","EditMapper","_edit","mod","modStart","dirtyEnd","OldTreeIndex","key","originalStart","_reconcile","fresh","mapper","index","edit","rc","orig","cand","os","old","linked","_linkCodeBlock","oldStart","oldCode","freshCode","_editWithin","_shiftEdit","reconcile","parseIncremental","MarkdownParser","getAnnotatedSource","escapeXml","tag","_attributes","result","childOffset","attrs","k","v","_label","_objectInstanceIds","_nextObjectInstanceId","objectInstanceId","visualizeAst","walk","kids","children","NO_ACTIVE_BLOCKS","EditorModel","observableValue","derived","reader","previousText","pending","doc","cursor","findBlockAtOffset","override","sel","blocksIntersecting","req","inserted","newActive","newCursor","lastBlock","VisualLineMap","lines","blockViews","_measure","lineIndex","endBoundaryLine","membership","bestIdx","bestDist","dist","point","VisualLine","rect","runs","run","best","d","first","bestRun","VisualRun","sourceRange","_xAtTextOffset","fraction","localOffset","_offsetAtX","textNode","textOffset","fallbackLeft","bestOffset","mid","dLeft","dRight","rawRuns","view","runsBefore","leaf","leafOffset","rects","lineBoxHeight","_lineBoxHeight","_expandToLineBox","breakOffsets","_findLineBreakOffsets","_appendElementBlockRun","currentRuns","currentY","currentHeight","currentLeft","currentRight","overlap","breaks","nextY","lo","hi","parent","lineHeight","leading","viewNode","absoluteStart","dom","MeasuredLayoutModel","nextCursorPosition","activeBlock","direction","blockStart","ranges","hiddenRangesFor","applySkip","isActive","relCursor","collectMarkerRanges","activeItemIndex","findActiveListItemIndex","collectListHiddenRanges","rel","list","cursorOffset","boundaryFallback","itemIdx","listOffset","listChild","walkCollectMarkerRanges","cursorRight","ctx","cursorLeft","cursorMoveRight","cursorMoveLeft","cursorWordRight","cursorWordLeft","cursorLineStart","cursorLineEnd","cursorDocumentStart","cursorDocumentEnd","cursorDown","lineIdx","cursorUp","deleteLeft","deleteRange","deleteRight","deleteWordLeft","boundary","deleteWordRight","insertText","newOffset","insertParagraph","insertLineBreak","insertHardLineBreak","existingSpaces","insertSmartEnter","_lineBreak","_paragraphLikeEnter","_codeBlockEnter","_blockQuoteEnter","_listEnter","_blockAbsoluteStart","textEnd","_trailingGlueLength","gapEnd","lineStart","_insertAt","lineEnd","_lineEnd","line","prefix","_exitToParagraph","listStart","_hasText","_continuationMarker","prevNewline","bullet","nl","selectAll","selectWord","_ctx","word","selectBlock","blockRange","_domToViewNode","_parentOf","ViewNode","Disposable","ast","domNode","vn","localSourceOffset","nodeSourceOffset","childEnd","nodeOffset","visitor","BlockViewNode","data","_height","createViewNode","options","_textLeaf","_prev","LeafViewNode","HardBreakViewNode","MarkerViewNode","GlueViewNode","HeadingViewNode","ContainerViewNode","_prevContainer","CodeBlockViewNode","MathBlockViewNode","ThematicBreakViewNode","ListViewNode","ListItemViewNode","TableRowViewNode","InlineCodeViewNode","InlineMathViewNode","LinkViewNode","ImageViewNode","ctor","reconcileDomChildren","parentDom","childData","previousChildren","build","paired","unused","pairNodes","_NO_CHILDREN","u","_patchDomChildren","_patchDomNodes","nodes","domCursor","toRemove","_buildChild","_inlineChild","_contentOf","_NO_VIEW_CHILDREN","_hasDecoratableWhitespace","span","_appendDecorated","prevDom","_isWhitespaceChar","_HARD_BREAK_WHITESPACE","_CODE_INDENT_WHITESPACE","_isObviousSpace","prevObvious","nextObvious","_whitespaceClass","_segmentWhitespace","segments","plainStart","flushPlain","breakNewline","lastNewline","isBreak","cls","seg","RawLeafViewNode","sourceLength","reuse","built","ws","_previous","holder","_appendPlainText","className","el","hr","custom","highlighter","prevCode","session","diff","transaction","tx","tokens","contentNode","code","_buildCodeContent","CodeContentViewNode","childAst","leaves","runOnChange","snapshot","contentAst","_buildTokenLeaves","tokenLeaves","piece","_mathContentOffset","_buildMathSegmentChildren","nodeLength","sorted","filler","remembered","latex","rendering","div","katex","li","_reconcileListItem","checkbox","onToggle","wasChecked","gutter","tr","cellData","_isSafeUrl","img","newData","prevNodes","byId","DocumentViewNode","contentDomNode","blocks","pendingElement","viewData","activeByView","childViews","_NO_NODES","PendingParagraphViewNode","caretDomPositionFromPoint","api","DocumentViewData","HeadingViewData","ParagraphViewData","PendingParagraphViewData","CodeBlockViewData","showMarkup","MathBlockViewData","BlockQuoteViewData","ListViewData","TableViewData","StrongViewData","EmphasisViewData","StrikethroughViewData","InlineCodeViewData","InlineMathViewData","LinkViewData","ImageViewData","ListItemViewData","TableRowViewData","isDelimiter","TableCellViewData","showTableGlue","TextViewData","showWhitespace","leftWordBoundary","rightWordBoundary","ThematicBreakViewData","MarkerViewData","visible","GlueViewData","decorateNewline","_INACTIVE","_inline","buildDocumentViewData","activeBlocks","selectionRange","prevByAst","blockSet","_buildBlock","selectionInNode","_reuseOr","_buildNode","astNode","neighbors","_buildChildren","_markerVisible","_glueVisible","_buildList","_buildListItem","_buildTable","_buildTableRow","_buildTableCell","_childrenOf","_prevChildByAst","_flagsEqual","_edgeIsWordContent","side","prevNode","activeItems","_activeItemIndices","itemSet","itemLevel","itemCtx","childCtx","table","tableActive","delimiterRow","rowSet","rowCtx","activeCells","_activeCellIndices","cellSet","cell","cellActive","cellCtx","_EMPTY_SET","_findActiveCellIndex","cellIdx","CursorView","_parent","pendingRect","parentRect","localRect","CursorViewRendering","visualLineMap","caretRect","autorun","GutterMarkersView","markers","GutterMarkersViewRendering","_deletedRect","_barRect","parentTop","lineRange","_lineSourceRange","min","max","SelectionView","selection","_renderSelection","SelectionViewRendering","path","selRange","lineInfos","lineRects","isFirst","isLast","startX","endX","blockToFirstLineIdx","blockToLastLineIdx","blockSelected","curr","gapStart","currRect","nextRect","nextFirstLineTop","_firstLineTopOfBlock","prevLineIdx","nextLineIdx","prevLR","nextLR","hasLine","_buildConnectedPath","fallback","radius","clusters","current","yTouches","xOverlaps","_buildClusterPath","corners","aRight","bRight","aConvex","_polygonToRoundedPath","radii","dPrev","_dist","dNext","_moveFrom","_fmt","depart","nextR","approach","from","to","t","DEFAULT_LIMITED_WIDTH","EditorView","_model","_options","limitedWidth","constObservable","hit","sourceText","documentNode","pendingEl","document","measurements","entry","blockRect","NativeClipboardStrategy","context","onCopy","onCut","onPaste","AsyncClipboardStrategy","_clipboard","onKeyDown","EditorController","_view","win","clipboardStrategy","editContext","findBlockRangeAt","onMouseMove","me","moveOffset","onMouseUp","command","extend","ctrl","_SHOW_LINE_RECTS_KEY","_readStoredBool","_writeStoredBool","MeasuredLayoutDebugView","_overlayParent","controls","showLineRects","_renderDebug","hovered","applyHoverIsolation","MeasuredLayoutDebugRendering","blockCount","mountedCount","lineCount","mappedOffsets","overlay","info","overlayParent","colorForOffset","hoveredOffset","charCount","lineRect","band","runBox","_appendCharRects","header","rows","flag","lc","blockAbsoluteStart","count","covered","isCovered","drawWidth","box","_isolate","container","off","matches","keep","on","Token","MonacoSyntaxHighlighter","_monaco","_grammars","initialText","MonacoHighlighterDocument","grammar","tokenizer","_stubLanguageService","_stubThemeService","_stubConfigurationService","_tokenizer","MonacoHighlightedSnapshot","oldTokens","_flatTokens","firstChangedOffset","firstChangedLine","reusedPrefix","startState","lengthEdit","_minimalRecolor","fromLine","allLines","state","hasEOL","_toTokens","starts","version","queryRange","docLen","queryStart","queryEnd","rangeStart","rangeEnd","started","consider","tokenStart","tokenEnd","_doc","_version","_classNameOf","monarchTokens","lineLength","startOffset","endOffset","_tokensEqual","_sumLengths","newTokens","oldCount","newCount","prefixChars","suffix","suffixChars","oldChars","newChars","oldRange","newRangeLength","createDefaultMonacoSyntaxHighlighter","monaco","grammars","grammarMap"],"mappings":";;;;;;;AAAO,MAAMA,EAAY;AAAA,EAiBxB,YACiBC,GACAC,GACf;AACD,QAHgB,KAAA,QAAAD,GACA,KAAA,eAAAC,GAEZD,IAAQC;AACX,YAAM,IAAI,MAAM,mBAAmBD,CAAK,KAAKC,CAAY,GAAG;AAAA,EAE9D;AAAA,EAvBA,OAAc,OAAOD,GAAeC,GAAmC;AACtE,WAAO,IAAIF,EAAYC,GAAOC,CAAY;AAAA,EAC3C;AAAA,EAEA,OAAc,SAASC,GAA6B;AACnD,WAAO,IAAIH,EAAY,GAAGG,CAAM;AAAA,EACjC;AAAA,EAEA,OAAc,iBAAiBF,GAAeE,GAA6B;AAC1E,WAAO,IAAIH,EAAYC,GAAOA,IAAQE,CAAM;AAAA,EAC7C;AAAA,EAEA,OAAc,QAAQC,GAA6B;AAClD,WAAO,IAAIJ,EAAYI,GAAQA,CAAM;AAAA,EACtC;AAAA,EAWA,IAAI,UAAmB;AACtB,WAAO,KAAK,UAAU,KAAK;AAAA,EAC5B;AAAA,EAEA,IAAI,SAAiB;AACpB,WAAO,KAAK,eAAe,KAAK;AAAA,EACjC;AAAA,E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