@vscode/markdown-editor 0.0.2-21 → 0.0.2-22
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 +63 -30
- package/dist/index.js +1420 -1373
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/view/editor.css +11 -39
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../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/diff/diffEdit.ts","../src/diff/vscodeDiff.ts","../src/diff/classifyDiff.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/diffHighlight.ts","../src/view/parts/diffHighlightsView.ts","../src/view/parts/selectionView.ts","../src/view/parts/cursorView.ts","../src/view/parts/gutterMarkersView.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","../src/contrib/comments/commentInputWidget.ts","../src/contrib/comments/commentModeController.ts","../src/contrib/comments/commentsModel.ts","../src/contrib/comments/commentsView.ts","../src/contrib/commentsVscode/stackedRailLayout.ts","../src/contrib/commentsVscode/stackedCommentsPresenter.ts","../src/contrib/commentsVscode/vscodeCommentWidget.ts","../src/contrib/commentsVscode/vscodeStackedCommentsView.ts","../src/contrib/commentsVscode/vscodeCommentWidgetV2.ts","../src/contrib/commentsVscode/vscodeV2CommentsView.ts","../src/contrib/commentsVscode/commentsDesigns.ts"],"sourcesContent":["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 | UnhandledBlockAstNode;\n\n/**\n * A block whose token type the parser does not understand (a setext heading, a\n * frontmatter fence, any future/extension construct). Rather than dropping the\n * span — which would demote its text to invisible glue — the parser captures the\n * whole source range verbatim as a single {@link MarkerAstNode} of kind\n * `content` and records the originating micromark {@link tokenType}, so the view\n * can render it as raw, editable text with an \"unhandled\" affordance. Offsets\n * stay sound: `content` tiles the block's full source span exactly.\n */\nexport class UnhandledBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'unhandledBlock';\n\tconstructor(\n\t\treadonly tokenType: string,\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 code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new UnhandledBlockAstNode(this.tokenType, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): UnhandledBlockAstNode { return new UnhandledBlockAstNode(this.tokenType, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.tokenType === o.tokenType; }\n}\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 instanceof UnhandledBlockAstNode;\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 | UnhandledBlockAstNode;\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, UnhandledBlockAstNode,\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\n/**\n * Block-level micromark tokens we do not model but that carry real content\n * worth preserving verbatim (an HTML block, a setext heading / YAML frontmatter\n * fence, a link-reference definition). When one appears where a block is\n * expected — at the document top level or inside a list item / block quote — it\n * is captured as an {@link UnhandledBlockAstNode} instead of being dropped.\n *\n * Deliberately an allowlist, not a denylist: every *structural* token (line\n * endings, `linePrefix`, `blockQuotePrefix`, `listItemIndent`, …) is simply\n * stepped over and tiles as glue, exactly as before. Enumerating the constructs\n * we fall back on — rather than \"anything unrecognized\" — keeps the many\n * whitespace/prefix tokens from being mistaken for content. To support a new\n * construct, either parse it properly or add its token here.\n */\nconst _UNHANDLED_BLOCK_TOKENS: ReadonlySet<string> = new Set([\n 'htmlFlow', 'setextHeading', 'definition',\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 'unhandledBlock': { const u = node as UnhandledBlockAstNode; return new UnhandledBlockAstNode(u.tokenType, [...u.content, glue], u.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 let coveredEnd = 0;\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); coveredEnd = Math.max(coveredEnd, start + block.length); }\n else {\n const unhandled = this._tryParseUnhandled(coveredEnd);\n if (unhandled) { cb.add(unhandled.node, unhandled.start); coveredEnd = Math.max(coveredEnd, unhandled.start + unhandled.node.length); }\n }\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:\n return undefined;\n }\n }\n\n /**\n * Fallback for an unrecognized top-level token (a setext heading, a\n * frontmatter fence, any extension construct). Consumes the whole\n * `enter…exit` span of that token — depth-counting so a same-typed nested\n * token cannot end it early — and captures the raw source verbatim as a\n * single `content` marker, so the text is preserved and rendered as an\n * explicit \"unhandled\" block instead of being demoted to invisible glue.\n */\n private _parseUnhandledBlock(): UnhandledBlockAstNode {\n const enter = this._events[this._idx];\n const tokenType = enter.tokenType;\n this._idx++;\n let depth = 1;\n let exit = enter;\n while (this._idx < this._events.length && depth > 0) {\n const ev = this._events[this._idx];\n if (ev.tokenType === tokenType) { depth += ev.type === 'enter' ? 1 : -1; }\n if (depth === 0) { exit = ev; }\n this._idx++;\n }\n const raw = this._source.substring(enter.startOffset, exit.endOffset);\n return new UnhandledBlockAstNode(tokenType, [new MarkerAstNode('content', raw)]);\n }\n\n /**\n * Decides what to do with an unrecognized `enter` token at the top of a\n * block-collecting loop (the document, a list item, a block quote), so all\n * three treat unknown constructs identically. A token in\n * {@link _UNHANDLED_BLOCK_TOKENS} that does not overlap an already-claimed\n * sibling (`start < coveredEnd`, e.g. a `setextHeading` micromark re-claims\n * back over a preceding `definition`) is captured verbatim via\n * {@link _parseUnhandledBlock}; every other token — a transparent `content`\n * wrapper, a structural prefix/indent, a line ending — is stepped over so it\n * tiles as glue. Returns the block and its start, or `undefined` when the\n * event was stepped over.\n */\n private _tryParseUnhandled(coveredEnd: number): Entry | undefined {\n const ev = this._events[this._idx];\n const start = ev.startOffset;\n if (start >= coveredEnd && _UNHANDLED_BLOCK_TOKENS.has(ev.tokenType)) {\n return { node: this._parseUnhandledBlock(), start };\n }\n this._idx++;\n return undefined;\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 let coveredEnd = enter.startOffset;\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 coveredEnd = Math.max(coveredEnd, preExit.endOffset);\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; coveredEnd = Math.max(coveredEnd, start + block.length); }\n else {\n const unhandled = this._tryParseUnhandled(coveredEnd);\n if (unhandled) { cb.add(unhandled.node, unhandled.start); seenBlock = true; coveredEnd = Math.max(coveredEnd, unhandled.start + unhandled.node.length); }\n }\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) {\n // An unknown construct inside the item (e.g. an HTML block) is\n // kept verbatim rather than dropped, using the same\n // content-vs-whitespace rule as the top level. `lastBlockEnd`\n // (else the marker end) is the item's covered offset.\n const unhandled = this._tryParseUnhandled(lastBlockEnd ?? markerEnd ?? start);\n if (unhandled && itemCb) {\n itemCb.add(unhandled.node, unhandled.start);\n lastBlockEnd = unhandled.start + unhandled.node.length;\n }\n }\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, UnhandledBlockAstNode, 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 UnhandledBlockAstNode) { attrs.token = node.tokenType; }\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 { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\n\n/**\n * A changed region, expressed in *both* coordinate spaces: {@link original}\n * is the range in the original document, {@link modified} the corresponding\n * range in the modified document. An insertion has an empty {@link original};\n * a deletion an empty {@link modified}.\n */\nexport interface ChangedRange {\n\treadonly original: OffsetRange;\n\treadonly modified: OffsetRange;\n}\n\n/**\n * Transform a {@link StringEdit} (original → modified) into the list of changed\n * ranges, each mapped between the two coordinate spaces. This is the bridge the\n * diff classifier and the word-level highlighter both consume.\n */\nexport function changedRanges(edit: StringEdit): ChangedRange[] {\n\tlet delta = 0;\n\tconst out: ChangedRange[] = [];\n\tfor (const r of edit.replacements) {\n\t\tconst modStart = r.replaceRange.start + delta;\n\t\tout.push({\n\t\t\toriginal: r.replaceRange,\n\t\t\tmodified: OffsetRange.ofStartAndLength(modStart, r.newText.length),\n\t\t});\n\t\tdelta += r.newText.length - r.replaceRange.length;\n\t}\n\treturn out;\n}\n","import { observableValue, type IObservable } from '@vscode/observables';\nimport { createDiffComputer } from '@vscode/diff';\nimport type { IDiffComputer, StringEdit as VscodeStringEdit } from '@vscode/diff';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit, StringReplacement } from '../core/stringEdit.js';\n\nconst _owner = {};\nconst _ready = observableValue<boolean>(_owner, false);\n\n/**\n * Becomes `true` once the `@vscode/diff` computer has loaded. Diff consumers\n * read this so they recompute with the better (character/word-level) algorithm\n * as soon as it is available.\n */\nexport const diffComputerReady: IObservable<boolean> = _ready;\n\nlet _computer: IDiffComputer | undefined;\nlet _readyPromise: Promise<void> | undefined;\n\n/** Load the `@vscode/diff` computer (pure-TS, no WASM). Idempotent. */\nexport function ensureDiffComputer(): Promise<void> {\n\tif (!_readyPromise) {\n\t\t_readyPromise = createDiffComputer({ useWasm: false })\n\t\t\t.then(c => { _computer = c; _ready.set(true, undefined); })\n\t\t\t.catch(() => { /* keep the line-level fallback */ });\n\t}\n\treturn _readyPromise;\n}\n\n// Start loading eagerly so the algorithm is ready as soon as possible.\nvoid ensureDiffComputer();\n\n/** Whether the `@vscode/diff` computer has finished loading. */\nexport function isDiffComputerReady(): boolean {\n\treturn _computer !== undefined;\n}\n\n/**\n * Compute a {@link StringEdit} (original → modified) using `@vscode/diff`'s\n * character/word-level algorithm. The computer loads asynchronously (near\n * instantly, no WASM); callers must ensure it is ready first — observe\n * {@link diffComputerReady} or await {@link ensureDiffComputer}.\n */\nexport function computeStringEdit(original: string, modified: string): StringEdit {\n\tif (!_computer) {\n\t\tthrow new Error('Diff computer not loaded yet — await ensureDiffComputer() / observe diffComputerReady first.');\n\t}\n\tconst result = _computer.computeDiff(original, modified, { extendToSubwords: true });\n\treturn _convert(result.edits.stripData());\n}\n\n/** Convert a `@vscode/diff` StringEdit into the editor's own StringEdit. */\nfunction _convert(edit: VscodeStringEdit): StringEdit {\n\treturn new StringEdit(edit.replacements.map(r =>\n\t\tStringReplacement.replace(new OffsetRange(r.range.start, r.range.endExclusive), r.newText)));\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport type { AstNode, DocumentAstNode } from '../parser/ast.js';\nimport { EditMapper } from '../parser/reconcile.js';\nimport { changedRanges, type ChangedRange } from './diffEdit.js';\nimport type { AnnotatedRange, DiffItem } from './diffItem.js';\n\n/**\n * Node kinds whose changes are diffed *structurally* (render the container\n * once, recurse into its children). Everything else is a leaf: a change there\n * produces a `replaced` item with word-level highlights.\n *\n * A `listItem` is deliberately a *leaf*, not a container: its marker (`- `,\n * `1. `) is structural syntax that the aligner skips, so recursing would orphan\n * a marker character caught in a change boundary (it would belong to no child\n * decoration). As a leaf the whole original item — marker included — is shown\n * over the modified one, with word-level highlights inside. A `tableCell` is a\n * leaf for the same reason (its `|`/padding glue would otherwise be orphaned),\n * and it only ever holds inline content anyway.\n */\nconst CONTAINER_KINDS: ReadonlySet<string> = new Set([\n\t'document', 'list', 'blockQuote', 'table', 'tableRow',\n]);\n\n/** Child kinds that are structural noise for alignment (still counted for offsets). */\nconst SKIP_KINDS: ReadonlySet<string> = new Set(['glue', 'marker']);\n\ninterface PositionedNode { readonly node: AstNode; readonly start: number; }\n\n/**\n * Classify the difference between two parsed documents, using the textual\n * `edit` (original → modified) as the alignment oracle. Returns a recursive\n * {@link DiffItem} list over the document's blocks.\n *\n * The alignment is purely offset-based (no tree-diff): each modified node is\n * mapped back through {@link EditMapper}; a clean mapping that lines up with the\n * next original node is `unchanged`, a same-kind node whose origin lands inside\n * the next original node is a change (recursed if a container, else a leaf\n * `replaced`), an unmappable node is `added`, and any original node not consumed\n * is `removed`.\n */\nexport function classifyDiff(original: DocumentAstNode, modified: DocumentAstNode, edit: StringEdit): DiffItem[] {\n\tconst mapper = new EditMapper(edit);\n\tconst changes = changedRanges(edit);\n\treturn classifyChildren(original, 0, modified, 0, mapper, changes);\n}\n\nfunction classifyChildren(\n\torigParent: AstNode,\n\torigParentStart: number,\n\tmodParent: AstNode,\n\tmodParentStart: number,\n\tmapper: EditMapper,\n\tchanges: readonly ChangedRange[],\n): DiffItem[] {\n\tconst O = structuralChildren(origParent, origParentStart);\n\tconst M = structuralChildren(modParent, modParentStart);\n\tconst items: DiffItem[] = [];\n\tlet oi = 0;\n\n\tfor (const m of M) {\n\t\tconst mRange = OffsetRange.ofStartAndLength(m.start, m.node.length);\n\t\tconst os = mapper.getOriginalOffset(m.start);\n\n\t\t// Original children lying entirely before m's origin were deleted.\n\t\twhile (oi < O.length && os !== undefined && O[oi].start + O[oi].node.length <= os) {\n\t\t\titems.push(removedItem(O[oi], changes));\n\t\t\toi++;\n\t\t}\n\n\t\tconst cand = oi < O.length ? O[oi] : undefined;\n\t\tconst candRange = cand ? OffsetRange.ofStartAndLength(cand.start, cand.node.length) : undefined;\n\t\tconst clean = mapper.getOriginalRange(mRange);\n\n\t\tif (clean && candRange && clean.equals(candRange)) {\n\t\t\titems.push({ kind: 'unchanged', node: m.node, modifiedStart: m.start });\n\t\t\toi++;\n\t\t} else if (cand && candRange && cand.node.kind === m.node.kind && os !== undefined && candRange.contains(os)) {\n\t\t\toi++;\n\t\t\tif (CONTAINER_KINDS.has(m.node.kind)) {\n\t\t\t\titems.push({\n\t\t\t\t\tkind: 'nested',\n\t\t\t\t\toriginal: cand.node, originalStart: cand.start,\n\t\t\t\t\tmodified: m.node, modifiedStart: m.start,\n\t\t\t\t\tchildren: classifyChildren(cand.node, cand.start, m.node, m.start, mapper, changes),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\titems.push({\n\t\t\t\t\tkind: 'replaced',\n\t\t\t\t\toriginal: cand.node, originalStart: cand.start,\n\t\t\t\t\tmodified: m.node, modifiedStart: m.start,\n\t\t\t\t\tinsertedLocal: localRanges(mRange, m.start, changes, 'modified', 'inserted'),\n\t\t\t\t\tdeletedLocal: localRanges(candRange, cand.start, changes, 'original', 'deleted'),\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\titems.push(addedItem(m, changes));\n\t\t}\n\t}\n\n\twhile (oi < O.length) {\n\t\titems.push(removedItem(O[oi], changes));\n\t\toi++;\n\t}\n\treturn items;\n}\n\n/** Children that participate in alignment, with absolute start offsets. */\nfunction structuralChildren(node: AstNode, nodeStart: number): PositionedNode[] {\n\tconst out: PositionedNode[] = [];\n\tlet pos = nodeStart;\n\tfor (const c of node.children) {\n\t\tif (!SKIP_KINDS.has(c.kind)) { out.push({ node: c, start: pos }); }\n\t\tpos += c.length;\n\t}\n\treturn out;\n}\n\nfunction addedItem(m: PositionedNode, changes: readonly ChangedRange[]): DiffItem {\n\tconst range = OffsetRange.ofStartAndLength(m.start, m.node.length);\n\tlet inserted = localRanges(range, m.start, changes, 'modified', 'inserted');\n\tif (inserted.length === 0) { inserted = [{ range: OffsetRange.ofLength(m.node.length), kind: 'inserted' }]; }\n\treturn { kind: 'added', node: m.node, modifiedStart: m.start, insertedLocal: inserted };\n}\n\nfunction removedItem(o: PositionedNode, changes: readonly ChangedRange[]): DiffItem {\n\tconst range = OffsetRange.ofStartAndLength(o.start, o.node.length);\n\tlet deleted = localRanges(range, o.start, changes, 'original', 'deleted');\n\tif (deleted.length === 0) { deleted = [{ range: OffsetRange.ofLength(o.node.length), kind: 'deleted' }]; }\n\treturn { kind: 'removed', node: o.node, originalStart: o.start, deletedLocal: deleted };\n}\n\n/** Intersect the changed ranges with a node and project into the node's local space. */\nfunction localRanges(\n\tnodeRange: OffsetRange,\n\tnodeStart: number,\n\tchanges: readonly ChangedRange[],\n\tside: 'original' | 'modified',\n\tkind: 'inserted' | 'deleted',\n): AnnotatedRange[] {\n\tconst out: AnnotatedRange[] = [];\n\tfor (const c of changes) {\n\t\tconst cr = side === 'original' ? c.original : c.modified;\n\t\tconst inter = cr.intersect(nodeRange);\n\t\tif (inter && !inter.isEmpty) {\n\t\t\tout.push({ range: inter.delta(-nodeStart), kind });\n\t\t}\n\t}\n\treturn out;\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';\nimport { computeStringEdit, classifyDiff, diffComputerReady } from '../diff/index.js';\nimport type { DiffItem } from '../diff/index.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\n\t/**\n\t * Read-only mode. When `true`, the editor never reveals a block's source\n\t * markers (markdown special characters like `**`, `#`, list bullets, code\n\t * fences, `$…$`) — every block stays in its clean rendered form regardless\n\t * of where the caret/selection is — and source-mutating edits are ignored.\n\t * Plain text selection still works everywhere (so the user can copy). The\n\t * default (`false`) is the normal editing mode where the active block\n\t * reveals its markers.\n\t */\n\treadonly readonlyMode = observableValue<boolean>(this, false);\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, undefined);\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 * Whether a pointer-driven selection drag is currently in progress. Set by\n\t * the controller between the pointer-down that starts the drag and the\n\t * pointer-up/cancel that ends it. Contributions read it to defer UI that\n\t * would otherwise flicker mid-drag (e.g. the comment input box appears only\n\t * once the drag ends).\n\t */\n\treadonly isSelecting = 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// Read-only mode never reveals markers: no block is ever active, so every\n\t\t// block renders in its clean form. Selection still works (it is DOM-based\n\t\t// and independent of the active set).\n\t\tif (this.readonlyMode.read(reader)) {\n\t\t\treturn new Set<BlockAstNode>();\n\t\t}\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 * The baseline document to diff against. When set, the editor renders in\n\t * diff mode: the modified document ({@link document}) stays editable, while\n\t * the baseline's removed/changed blocks are shown as read-only decorations.\n\t * `undefined` (the default) renders normally.\n\t */\n\treadonly baseline = observableValue<StringValue | undefined>(this, undefined);\n\n\tprivate readonly _baselineDocument = derived(this, reader => {\n\t\tconst b = reader.readObservable(this.baseline);\n\t\treturn b ? this._parser.parse(b) : undefined;\n\t});\n\n\t/**\n\t * The diff of {@link baseline} → {@link document}, or `undefined` when no\n\t * baseline is set. The view renders the {@link DiffItem}s as stacked\n\t * decorations; `insertedRanges` (modified-side change spans) drive the green\n\t * word-level highlight.\n\t */\n\treadonly diff = derived(this, reader => {\n\t\tconst baselineDoc = reader.readObservable(this._baselineDocument);\n\t\tconst baseline = reader.readObservable(this.baseline);\n\t\tif (!baselineDoc || !baseline) { return undefined; }\n\t\t// No diff until the @vscode/diff algorithm has loaded (near-instant).\n\t\tif (!reader.readObservable(diffComputerReady)) { return undefined; }\n\t\tconst modifiedDoc = reader.readObservable(this.document);\n\t\tconst modifiedText = reader.readObservable(this.sourceText);\n\t\tconst edit = computeStringEdit(baseline.value, modifiedText.value);\n\t\tconst items = classifyDiff(baselineDoc, modifiedDoc, edit);\n\t\t// Green word rects only for *partial* changes (`replaced`, and anything\n\t\t// inside a recursively-diffed container). Whole added blocks get a solid\n\t\t// band instead, so they contribute no inline rects.\n\t\tconst insertedRanges: OffsetRange[] = [];\n\t\tconst collect = (list: readonly DiffItem[], topLevel: boolean): void => {\n\t\t\tfor (const it of list) {\n\t\t\t\tif (it.kind === 'replaced') {\n\t\t\t\t\tfor (const r of it.insertedLocal) { insertedRanges.push(r.range.delta(it.modifiedStart)); }\n\t\t\t\t} else if (it.kind === 'added' && !topLevel) {\n\t\t\t\t\tfor (const r of it.insertedLocal) { insertedRanges.push(r.range.delta(it.modifiedStart)); }\n\t\t\t\t} else if (it.kind === 'nested') {\n\t\t\t\t\tcollect(it.children, false);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tcollect(items, true);\n\t\t// Partially-changed (`replaced`) blocks render in active/source form so\n\t\t// marker-level modifications are visible. Whole added blocks stay rendered.\n\t\tconst changedBlocks = new Set<BlockAstNode>();\n\t\tfor (const it of items) {\n\t\t\tif (it.kind === 'replaced') { changedBlocks.add(it.modified as BlockAstNode); }\n\t\t}\n\t\treturn { items, insertedRanges, changedBlocks };\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\tif (this.readonlyMode.get()) { return; }\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\tif (this.readonlyMode.get()) { return; }\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\tif (this.readonlyMode.get()) { return; }\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.\n\t *\n\t * The runs tile the source but are stored in paint order, not sorted by\n\t * source offset (hidden-marker runs are appended last). So this scans all\n\t * runs rather than assuming any ordering:\n\t *\n\t * - If some run *covers* `offset`, its own geometry places the caret\n\t * (exact glyph boundary for text runs). In the active, markers-visible\n\t * form every offset is covered, so this branch keeps distinct offsets\n\t * distinct.\n\t * - Otherwise `offset` sits in a gap — a hidden inline marker such as the\n\t * `**` of `**bold**`, or before/after the painted text. It snaps to the\n\t * seam between the source-nearest runs on either side: the right edge of\n\t * the closest run ending at/before `offset`, else the left edge of the\n\t * closest run starting at/after it. A hidden marker collapses to zero\n\t * width, so both edges coincide at the seam.\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\tlet leftRight: number | undefined;\n\t\tlet leftEnd = -Infinity;\n\t\tlet rightLeft: number | undefined;\n\t\tlet rightStart = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.sourceEndExclusive <= offset && run.sourceEndExclusive > leftEnd) {\n\t\t\t\tleftEnd = run.sourceEndExclusive;\n\t\t\t\tleftRight = run.rect.right;\n\t\t\t}\n\t\t\tif (run.sourceStart >= offset && run.sourceStart < rightStart) {\n\t\t\t\trightStart = run.sourceStart;\n\t\t\t\trightLeft = run.rect.left;\n\t\t\t}\n\t\t}\n\t\tif (leftRight !== undefined) { return leftRight; }\n\t\tif (rightLeft !== undefined) { return rightLeft; }\n\t\treturn this.runs[0].rect.left;\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 run resolves the offset (exact glyph boundary for text runs,\n\t * nearer edge for source-less runs); otherwise it snaps to the closer\n\t * 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 * This matters for proportional fonts where character widths differ a lot\n * (e.g. `m` vs `i`): a caret placed by anything coarser than real glyph\n * measurement lands several pixels inside the wrong character.\n *\n * A run without a source has no per-offset geometry, so it maps between\n * offsets and x by snapping to the nearer run edge. Real text runs always\n * carry a source; source-less runs are element-only blocks (see\n * {@link _appendElementBlockRun}) and hand-built runs in tests.\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`.\n *\n * A source-less run has no per-offset geometry: it either represents an\n * element-only block (KaTeX math, a mermaid/custom diagram, an image, an\n * inactive `<hr>`) whose box does not correspond to source offsets, or a\n * hand-built run in a test. Either way it maps between offsets and x by\n * snapping to the nearer edge of {@link rect} rather than fabricating\n * interior positions.\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\t// No per-offset geometry: the caret sits at the run edge nearer to\n\t\t// `offset` (see class doc). Real text runs always carry a source, so\n\t\t// this only covers element blocks and hand-built test runs.\n\t\tconst fraction = (offset - this.sourceStart) / this.sourceLength;\n\t\treturn fraction <= 0.5 ? this.rect.left : this.rect.right;\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\t// No per-offset geometry: snap to the nearer edge rather than\n\t\t// fabricating interior positions (matching the element-edge rule in\n\t\t// `ViewNode.getLocalSourceRange`).\n\t\tconst mid = (this.rect.left + this.rect.right) / 2;\n\t\treturn x < mid ? this.sourceStart : this.sourceEndExclusive;\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 has no source (no per-offset geometry), so a hit on it snaps to the\n * nearer edge rather than fabricating positions inside its interior source.\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 'unhandledBlock':\n // The raw `content` marker is real, always-visible text (not\n // hideable markup), so it contributes no marker ranges.\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. For an element hit — an element-only node\n * (KaTeX math, `<hr>`, an image, a hidden marker) or a wrapper/container\n * element — the platform reports a child-index offset, not a text caret, so\n * there is no internal mapping to honour: it snaps to the node's nearer\n * edge, `offset 0` (the \"before\" side) → start, any `offset >= 1` (the\n * \"after\" side) → end. Subclasses may override for finer control.\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(pos.offset >= 1 ? this.sourceLength : 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 { StringEdit, StringReplacement } from '../../core/stringEdit.js';\nimport type {\n\tAnyViewData, CodeBlockViewData, DiffDecorationViewData, DiffHighlightRange, DiffHunkViewData, DiffSideViewData, GlueViewData, HeadingViewData, ImageViewData,\n\tInlineCodeViewData, InlineMathViewData, LinkViewData, ListViewData, ListItemViewData,\n\tMarkerViewData, MathBlockViewData, TableRowViewData, TableViewData, TextViewData, ThematicBreakViewData, UnhandledBlockViewData,\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). Return `false` to use the anchor's native\n\t * navigation behavior.\n\t */\n\treadonly onOpenLink?: (url: string, event: MouseEvent) => false | 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\t/**\n\t * Pluggable factory for an in-place, interactive editor that replaces the\n\t * *rendered* (inactive) form of a fenced code block — see\n\t * {@link IEmbeddedCodeEditor}. When it returns an editor for the block's\n\t * language, that editor's element is mounted instead of the highlighted\n\t * code, and content flows both ways as string edits. Returning `undefined`\n\t * falls back to the default rendering. EXPERIMENTAL.\n\t */\n\treadonly embeddedCodeEditorFactory?: IEmbeddedCodeEditorFactory;\n\n\t/**\n\t * Called when an {@link IEmbeddedCodeEditor} edits its content. `contentEdit`\n\t * is in the block's *content* coordinates; the host translates it to a\n\t * document edit (via {@link CodeBlockAstNode.codeOffset} and the block's\n\t * offset) and applies it to the model.\n\t */\n\treadonly onEmbeddedCodeEditorEdit?: (block: CodeBlockAstNode, contentEdit: StringEdit) => void;\n}\n\n/**\n * A live editor embedded in place of a fenced code block's *rendered* form.\n *\n * This is the internal seam between the block view and a concrete embedded\n * editor (e.g. an `<iframe>` speaking the web-editor protocol). The block view\n * only speaks string edits: it pushes the block's content down via\n * {@link setContent} and receives the editor's own changes back through\n * {@link onEdit} (set by the block view on each (re)construction, so it always\n * routes to the current AST node). The concrete implementation owns its DOM,\n * transport, and lifecycle.\n *\n * A single instance is adopted across re-renders (like the highlighter session)\n * so the underlying editor keeps its state across edits — see\n * {@link CodeBlockViewNode}.\n */\nexport interface IEmbeddedCodeEditor {\n\t/** The element mounted as the block's rendered form. */\n\treadonly element: HTMLElement;\n\t/**\n\t * Document → editor. The block's content changed (from any source). Must be\n\t * idempotent: pushing the content the editor already holds is a no-op, which\n\t * is how edits the editor itself originated are prevented from echoing back.\n\t */\n\tsetContent(content: string): void;\n\t/**\n\t * Optional synchronous height (px) to reserve for `content` *before* the\n\t * editor has laid out. Return `undefined` to let the editor size itself\n\t * (the implementation may report its real height later). Lets a registration\n\t * avoid a layout jump when it can cheaply estimate the size from content.\n\t */\n\testimateHeight?(content: string): number | undefined;\n\t/**\n\t * Editor → document. Set by the block view on every (re)construction to\n\t * route the editor's own edits, expressed in the block's *content*\n\t * coordinates, to the current AST node.\n\t */\n\tonEdit?: (edit: StringEdit) => void;\n\tdispose(): void;\n}\n\n/** Creates an {@link IEmbeddedCodeEditor} for a fenced block, or opts out. */\nexport interface IEmbeddedCodeEditorFactory {\n\t/**\n\t * Return an editor for a fenced block of `language`, or `undefined` to fall\n\t * back to the default (highlighting / {@link BlockViewOptions.renderCustomCodeBlock}).\n\t */\n\tcreate(language: string, initialContent: string): IEmbeddedCodeEditor | 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 * The horizontal scroll viewport for selection/caret clipping\n\t * ({@link blockViewportClip}). For most blocks the scroller *is*\n\t * {@link element} — a code / math / unhandled block's `element` is the very\n\t * `overflow-x: auto` box that scrolls. A table is the exception: its\n\t * `element` stays the inner `<table>` (so the active/markers classes and\n\t * `.md-table` theme styling are unaffected), but the box that actually\n\t * scrolls is the wrapping `.md-table-wrapper`, so {@link TableViewNode}\n\t * overrides this to return that wrapper.\n\t */\n\tget scrollElement(): HTMLElement { return this.element; }\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 'unhandledBlock': return new UnhandledBlockViewNode(data, options, _prev(previous, UnhandledBlockViewNode));\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 TableViewNode(data, options, _prev(previous, TableViewNode));\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\tcase 'diffHunk': return new DiffHunkViewNode(data, options, _prev(previous, DiffHunkViewNode));\n\t\tcase 'diffDecoration': return new DiffDecorationViewNode(data, options, _prev(previous, DiffDecorationViewNode));\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/**\n * Renders a {@link DiffHunkViewData}: the original block stacked over the\n * modified block (either side optional). Each side is a normal block view node\n * — the same renderers the editor uses — wrapped in a container and tagged with\n * `md-diff-original` / `md-diff-modified` so CSS can tint it. The per-side\n * word-level highlight {@link DiffHunkViewNode.sides ranges} are painted\n * separately (via the CSS Custom Highlight API) by the diff view.\n */\nexport class DiffHunkViewNode extends BlockViewNode<DiffHunkViewData> {\n\tprivate readonly _originalNode?: ViewNode;\n\tprivate readonly _modifiedNode?: ViewNode;\n\n\tconstructor(data: DiffHunkViewData, options: BlockViewOptions | undefined, previous?: DiffHunkViewNode) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\twrapper.className = 'md-block md-diff-hunk';\n\n\t\tconst children: ViewNode[] = [];\n\t\tconst mounts: globalThis.Node[] = [];\n\t\tconst original = data.original\n\t\t\t? _buildDiffSide(data.original, 'md-diff-original', options, previous?._originalNode)\n\t\t\t: undefined;\n\t\tconst modified = data.modified\n\t\t\t? _buildDiffSide(data.modified, 'md-diff-modified', options, previous?._modifiedNode)\n\t\t\t: undefined;\n\t\tif (original) { children.push(original); mounts.push(original.mountNode); }\n\t\tif (modified) { children.push(modified); mounts.push(modified.mountNode); }\n\t\t_patchDomNodes(wrapper, mounts);\n\n\t\tsuper(data, wrapper, children);\n\t\tthis._originalNode = original;\n\t\tthis._modifiedNode = modified;\n\t}\n\n\t/** The mounted sides with their highlight ranges, for the diff highlighter. */\n\tget sides(): readonly { readonly node: ViewNode; readonly ranges: readonly DiffHighlightRange[] }[] {\n\t\tconst out: { node: ViewNode; ranges: readonly DiffHighlightRange[] }[] = [];\n\t\tif (this._originalNode && this.data.original) { out.push({ node: this._originalNode, ranges: this.data.original.ranges }); }\n\t\tif (this._modifiedNode && this.data.modified) { out.push({ node: this._modifiedNode, ranges: this.data.modified.ranges }); }\n\t\treturn out;\n\t}\n}\n\nfunction _buildDiffSide(side: DiffSideViewData, cls: string, options: BlockViewOptions | undefined, prev: ViewNode | undefined): ViewNode {\n\tconst node = createViewNode(side.view, options, prev);\n\tconst el = (node as BlockViewNode).element;\n\tel.classList.add(cls);\n\tel.classList.toggle('md-block-active', side.active);\n\tel.classList.toggle('md-markers-hidden', !side.active);\n\treturn node;\n}\n\n/**\n * Renders a {@link DiffDecorationViewData}: a read-only original block shown\n * (red) above its place in the modified document. It is `pointer-events: none`\n * and reports {@link sourceLength} `0`, so it occupies vertical space like a\n * view-zone but is invisible to the editor's source mapping, selection, and\n * measurement (it is never added to the document's `blocks`).\n */\nexport class DiffDecorationViewNode extends BlockViewNode<DiffDecorationViewData> {\n\treadonly sideNode: ViewNode;\n\n\tconstructor(data: DiffDecorationViewData, options: BlockViewOptions | undefined, previous?: DiffDecorationViewNode) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\twrapper.className = 'md-block md-diff-decoration';\n\t\twrapper.style.pointerEvents = 'none';\n\t\tconst sideNode = createViewNode(data.side, options, previous?.sideNode);\n\t\tconst el = (sideNode as BlockViewNode).element;\n\t\t// Partial change: active/source form (markers visible) so marker-level\n\t\t// modifications show. Whole removal: rendered form (clean solid band).\n\t\tconst active = !data.whole;\n\t\tel.classList.add(data.whole ? 'md-diff-removed' : 'md-diff-original');\n\t\tel.classList.toggle('md-block-active', active);\n\t\tel.classList.toggle('md-markers-hidden', !active);\n\t\t_patchDomNodes(wrapper, [sideNode.mountNode]);\n\t\tsuper(data, wrapper, [sideNode]);\n\t\tthis.sideNode = sideNode;\n\t}\n\n\t/** A decoration has no presence in the modified document's source space. */\n\toverride get sourceLength(): number { return 0; }\n\n\t/** True when the whole block was removed (solid band, no word-level rects). */\n\tget whole(): boolean { return this.data.whole; }\n\n\t/** Absolute offset of this block in the *original* document. */\n\tget originalStart(): number { return this.data.originalStart; }\n\n\tget deletedRanges(): readonly DiffHighlightRange[] { return this.data.deletedRanges; }\n}\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 source-less run (no per-offset geometry). When active it reveals the\n * 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 *\n * The inactive `<hr>` is wrapped in a `<div>` that becomes this node's\n * registered {@link dom} (and the node the parent mounts). A bare `<hr>` is a\n * void element the platform hit-test (`caretPositionFromPoint`) cannot place a\n * caret inside — a click on it resolves to the surrounding flow instead. The\n * wrapping block `<div>` gives the hit-test a caret-positionable box that maps\n * back to this break. {@link element} stays the `<hr>` so the block's\n * active/markers classes and rule styling are unaffected.\n */\nclass ThematicBreakViewNode extends BlockViewNode<ThematicBreakViewData> {\n\tprivate readonly _contentEl: HTMLElement;\n\n\tconstructor(data: ThematicBreakViewData, options: BlockViewOptions | undefined, previous: ThematicBreakViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\t// Reuse only a previous *active* node's div: an inactive node's `dom`\n\t\t\t// is the wrapper div, but its children/structure are different.\n\t\t\tconst reuse = previous?.data.showMarkup ? previous : undefined;\n\t\t\tconst el = (reuse?.dom as HTMLElement | undefined) ?? 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\tthis._contentEl = el;\n\t\t\treturn;\n\t\t}\n\t\tconst wrapper = document.createElement('div');\n\t\twrapper.className = 'md-block md-thematic-break-wrapper';\n\t\tconst hr = document.createElement('hr');\n\t\thr.className = 'md-block md-thematic-break';\n\t\twrapper.appendChild(hr);\n\t\tsuper(data, wrapper, _NO_CHILDREN);\n\t\tthis._contentEl = hr;\n\t}\n\n\toverride get element(): HTMLElement { return this._contentEl; }\n}\n\n/**\n * An {@link UnhandledBlockViewData unhandled block}: a construct the parser does\n * not model (a setext heading, a frontmatter fence, an extension token). It has\n * no active/inactive split — the verbatim source is always shown — so it renders\n * like a code block (`<pre><code>` with the raw text as a single leaf) but\n * carries an `md-unhandled-block` class and a `data-unhandled-token` attribute,\n * so the theme can style it distinctly and surface the token type as a badge.\n * The raw `content` marker tiles the block's full span, keeping source ↔ DOM\n * mapping exact; the text stays selectable and editable.\n *\n * The scrolling `<pre>` is wrapped in a non-scrolling `<div>`: the token badge\n * is painted on the wrapper so it stays pinned to the top-right corner while the\n * `<pre>` scrolls horizontally (a badge on the scroll container itself drifts\n * with the content). {@link element} is the inner `<pre>` — the real scroll\n * viewport — so the selection/caret clipping measures the right box.\n */\nclass UnhandledBlockViewNode extends BlockViewNode<UnhandledBlockViewData> {\n\tprivate readonly _scroller: HTMLElement;\n\n\tconstructor(data: UnhandledBlockViewData, options: BlockViewOptions | undefined, previous: UnhandledBlockViewNode | undefined) {\n\t\tconst reuse = previous && previous.dom instanceof HTMLDivElement ? previous : undefined;\n\t\tconst wrapper = (reuse?.dom as HTMLDivElement | undefined) ?? document.createElement('div');\n\t\tif (!reuse) { wrapper.className = 'md-block md-unhandled-block'; }\n\t\twrapper.dataset.unhandledToken = data.ast.tokenType;\n\t\tconst pre = reuse?._scroller ?? document.createElement('pre');\n\t\tif (!reuse) {\n\t\t\tpre.className = 'md-code-block md-unhandled-scroll';\n\t\t\twrapper.appendChild(pre);\n\t\t}\n\t\tconst code = (reuse ? pre.querySelector('code') : null) ?? document.createElement('code');\n\t\tif (!reuse) { pre.appendChild(code); }\n\t\tconst kids = reconcileDomChildren(code, data.content, reuse?.children, (childData, prev) => {\n\t\t\tconst childAst = childData.ast;\n\t\t\tif (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'content') {\n\t\t\t\tconst prevText = prev instanceof RawLeafViewNode && prev.dom.nodeType === globalThis.Node.TEXT_NODE\n\t\t\t\t\t&& (prev.dom as Text).data === (childAst as MarkerAstNode).content ? prev.dom : undefined;\n\t\t\t\tconst text = prevText ?? document.createTextNode((childAst as MarkerAstNode).content);\n\t\t\t\treturn new RawLeafViewNode(childAst, text);\n\t\t\t}\n\t\t\treturn createViewNode(childData, options, prev);\n\t\t});\n\t\tsuper(data, wrapper, kids);\n\t\tthis._scroller = pre;\n\t}\n\n\toverride get element(): HTMLElement { return this._scroller; }\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\t/**\n\t * An in-place interactive editor (e.g. an iframe) mounted instead of the\n\t * rendered code. Like {@link _session} it is adopted from `previous` across\n\t * rebuilds so the underlying editor keeps its state, and must be disposed\n\t * manually (a node reused as `previous` is never {@link dispose}d).\n\t */\n\tprivate _embeddedEditor: IEmbeddedCodeEditor | 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 prevCode = previous instanceof CodeBlockViewNode ? previous : undefined;\n\n\t\t// The `content` marker includes the newline after the open fence and the\n\t\t// newline before the close fence (see parser). An embedded editor must only\n\t\t// see the inner code — otherwise its first/last line would edit those\n\t\t// separators and corrupt the fences — so strip them and remember the leading\n\t\t// length to shift the editor's edits back into code-marker coordinates.\n\t\tconst embeddedLeading = content.startsWith('\\n') ? 1 : 0;\n\t\tconst embeddedTrailing = content.endsWith('\\n') ? 1 : 0;\n\t\tconst embeddedContent = content.slice(embeddedLeading, content.length - embeddedTrailing);\n\n\t\t// Embedded editor: adopt `previous`'s editor when the block is the same\n\t\t// node or an in-content edit links them (getDiff), so the editor keeps\n\t\t// its state across edits; otherwise create a fresh one. Takes precedence\n\t\t// over the custom renderer and highlighting. Any editor on `previous` we\n\t\t// do not adopt is disposed below.\n\t\tlet embedded: IEmbeddedCodeEditor | undefined;\n\t\tif (!data.showMarkup && ast.language && options?.embeddedCodeEditorFactory) {\n\t\t\tif (prevCode?._embeddedEditor && (ast === prevCode.ast || ast.getDiff(prevCode.ast as CodeBlockAstNode))) {\n\t\t\t\tembedded = prevCode._embeddedEditor;\n\t\t\t\tprevCode._embeddedEditor = undefined;\n\t\t\t} else {\n\t\t\t\tembedded = options.embeddedCodeEditorFactory.create(ast.language, embeddedContent) ?? undefined;\n\t\t\t}\n\t\t}\n\t\tif (prevCode?._embeddedEditor) { prevCode._embeddedEditor.dispose(); prevCode._embeddedEditor = undefined; }\n\n\t\tconst custom = (!embedded && !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\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 (!embedded && !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 (embedded) {\n\t\t\t// Push current content down (idempotent — the editor drops content it\n\t\t\t// already holds, so its own edits don't echo back) and route its\n\t\t\t// edits to the current AST node. Reserve a synchronous height estimate\n\t\t\t// so the layout doesn't jump before the editor measures itself.\n\t\t\tembedded.element.classList.add('md-block', 'md-code-block');\n\t\t\tconst estimated = embedded.estimateHeight?.(embeddedContent);\n\t\t\tif (estimated !== undefined) {\n\t\t\t\tembedded.element.style.boxSizing = 'border-box';\n\t\t\t\tembedded.element.style.minHeight = `${estimated}px`;\n\t\t\t}\n\t\t\t// Shift the editor's (inner-content) edit back over the stripped leading\n\t\t\t// newline so it lands in code-marker coordinates, leaving the fence\n\t\t\t// separators untouched.\n\t\t\tembedded.onEdit = (edit) => {\n\t\t\t\tconst shifted = embeddedLeading === 0 ? edit : new StringEdit(\n\t\t\t\t\tedit.replacements.map((r) => StringReplacement.replace(r.replaceRange.delta(embeddedLeading), r.newText)),\n\t\t\t\t);\n\t\t\t\toptions?.onEmbeddedCodeEditorEdit?.(ast, shifted);\n\t\t\t};\n\t\t\tembedded.setContent(embeddedContent);\n\t\t\tdom = embedded.element;\n\t\t\tchildren = _NO_CHILDREN;\n\t\t} else if (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\tthis._embeddedEditor = embedded;\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\tthis._embeddedEditor?.dispose();\n\t\tthis._embeddedEditor = 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`. The class is toggled on\n * every reconciliation because the underlying `<td>` is intentionally reused.\n */\n/**\n * A GFM table. The `<table>` is wrapped in a `<div>` that becomes this node's\n * registered {@link dom} (and the node the parent mounts), so a click on the\n * table's borders or padding — areas the platform hit-test\n * (`caretPositionFromPoint`) does not place a caret inside a `<table>` — lands\n * on a caret-positionable box that maps back to this table rather than the\n * surrounding flow. The cells themselves are their own view nodes, so clicks on\n * cell text still resolve precisely. {@link element} stays the `<table>` so the\n * block's active/markers classes and the `.md-table` theme styling are\n * unaffected, and the row children are reconciled into it. The wrapper is also\n * the horizontal scroll viewport (`overflow-x: auto`), so a wide table scrolls\n * table-locally instead of overflowing the page and scrolling the editor gutter\n * away; {@link scrollElement} returns it so the selection/caret clipping\n * ({@link blockViewportClip}) measures that scroll box rather than the\n * content-sized `<table>`.\n */\nclass TableViewNode extends BlockViewNode<TableViewData> {\n\tprivate readonly _table: HTMLElement;\n\n\tconstructor(data: TableViewData, options: BlockViewOptions | undefined, previous: TableViewNode | undefined) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\tconst table = previous?._table ?? document.createElement('table');\n\t\tif (!previous) {\n\t\t\twrapper.className = 'md-block md-table-wrapper';\n\t\t\ttable.className = 'md-block md-table';\n\t\t\twrapper.appendChild(table);\n\t\t}\n\t\tconst children = reconcileDomChildren(table, _contentOf(data), previous?.children, _buildChild(options));\n\t\tsuper(data, wrapper, children);\n\t\tthis._table = table;\n\t}\n\n\toverride get element(): HTMLElement { return this._table; }\n\n\toverride get scrollElement(): HTMLElement { return this.dom as HTMLElement; }\n}\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') {\n\t\t\t\t\t(children[i] as BlockViewNode).element.classList.toggle('md-table-cell-active', cellData.isActive);\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 click\n\t\t// can place the caret to edit. Middle-click always opens.\n\t\tif (!previous) {\n\t\t\tconst shouldOpen = (e: MouseEvent): boolean => {\n\t\t\t\tif (!a.dataset.mdUrl) { return false; }\n\t\t\t\t// Only primary (open/place caret) and middle (always open) buttons.\n\t\t\t\tif (e.button !== 0 && e.button !== 1) { return false; }\n\t\t\t\tif (e.button === 1) { return true; }\n\t\t\t\tconst blockActive = a.closest('.md-block-active') !== null;\n\t\t\t\treturn !blockActive || e.ctrlKey || e.metaKey;\n\t\t\t};\n\t\t\tconst openLink = (e: MouseEvent): boolean => {\n\t\t\t\tconst url = a.dataset.mdUrl;\n\t\t\t\tif (!url) { return true; }\n\t\t\t\tconst onOpenLink = options?.onOpenLink;\n\t\t\t\tif (!onOpenLink) {\n\t\t\t\t\twindow.open(url, '_blank', 'noopener');\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn onOpenLink(url, e) !== false;\n\t\t\t};\n\t\t\t// The open is decided on `pointerdown`, while the block still reflects its\n\t\t\t// pre-click state and before the controller (which also acts on\n\t\t\t// `pointerdown`) can place the caret; `stopPropagation()` suppresses that\n\t\t\t// caret move. Crucially we do NOT `preventDefault()`: the click must still\n\t\t\t// focus the host frame, because a webview only opens the link once its\n\t\t\t// surrounding window is active (the Markdown preview focuses on click too).\n\t\t\t// The following `click`/`auxclick` then only cancels the anchor's native\n\t\t\t// navigation.\n\t\t\tlet pointerDownResult: 'none' | 'handled' | 'native' = 'none';\n\t\t\ta.addEventListener('pointerdown', (e) => {\n\t\t\t\tpointerDownResult = 'none';\n\t\t\t\tif (!shouldOpen(e)) { return; }\n\t\t\t\te.stopPropagation();\n\t\t\t\tpointerDownResult = openLink(e) ? 'handled' : 'native';\n\t\t\t});\n\t\t\tconst onClick = (e: MouseEvent): void => {\n\t\t\t\tconst result = pointerDownResult;\n\t\t\t\tpointerDownResult = 'none';\n\t\t\t\tif (result === 'native') {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result === 'handled') {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!shouldOpen(e)) { return; }\n\t\t\t\tif (openLink(e)) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t}\n\t\t\t};\n\t\t\ta.addEventListener('click', onClick);\n\t\t\ta.addEventListener('auxclick', onClick);\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 contentDomNode.classList.add('md-document');\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 // Green band on a changed modified block (diff mode); no-op otherwise.\n const diffKind = viewData.children[i].diffKind;\n (node as BlockViewNode).element.classList.toggle('md-diff-added', diffKind === 'added');\n (node as BlockViewNode).element.classList.toggle('md-diff-modified', diffKind === 'modified');\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 type { DiffItem, NestedItem, RemovedItem } from '../diff/diffItem.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, UnhandledBlockAstNode,\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, the\n * transient empty paragraph (see {@link PendingParagraphViewData}), or a\n * {@link DiffHunkViewData diff hunk} (stacked original/modified blocks). */\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 | DiffHunkViewData | DiffDecorationViewData;\n\treadonly kind: 'block' | 'glue' | 'pendingParagraph' | 'diffHunk' | 'diffDecoration';\n\t/**\n\t * Diff mode: how this (modified) block changed. `added` = a whole new block\n\t * (strong green band, no inline rects); `modified` = a partial change (light\n\t * band + inline rects on the changed words).\n\t */\n\treadonly diffKind?: 'added' | 'modified';\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockViewData =\n\t| HeadingViewData | ParagraphViewData | CodeBlockViewData | MathBlockViewData\n\t| ThematicBreakViewData | BlockQuoteViewData | ListViewData | TableViewData | UnhandledBlockViewData;\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\n/**\n * View-data for an {@link UnhandledBlockAstNode}. It has no active/inactive\n * split — the raw source *is* both the source and the rendered form — so it\n * carries no `showMarkup` flag; the renderer always shows the verbatim text.\n */\nexport class UnhandledBlockViewData {\n\treadonly kind = 'unhandledBlock';\n\tconstructor(readonly ast: UnhandledBlockAstNode, readonly content: readonly AnyViewData[]) { }\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\n/** A word/character highlight inside one diff side, in block-local coords. */\nexport interface DiffHighlightRange {\n\treadonly range: OffsetRange;\n\treadonly kind: 'inserted' | 'deleted';\n}\n\n/** One side (original or modified) of a {@link DiffHunkViewData}. */\nexport interface DiffSideViewData {\n\treadonly view: BlockViewData;\n\t/** Render in active form (markers/whitespace visible). */\n\treadonly active: boolean;\n\treadonly ranges: readonly DiffHighlightRange[];\n}\n\n/**\n * A changed block rendered as its original form stacked over its modified form\n * (either side may be absent for a pure deletion/insertion). It is itself a\n * document child the renderer mounts like a block; its {@link ast} is the\n * surviving side's ast, used only for view-node identity/reuse.\n */\nexport class DiffHunkViewData {\n\treadonly kind = 'diffHunk';\n\tconstructor(\n\t\treadonly ast: AstNode,\n\t\treadonly original: DiffSideViewData | undefined,\n\t\treadonly modified: DiffSideViewData | undefined,\n\t) { }\n}\n\n/**\n * A read-only \"removed\" decoration: an original block rendered (red) above its\n * place in the modified document, occupying vertical space like a view-zone but\n * contributing **zero** source length, so the editor's source mapping stays the\n * modified document and editing is unaffected. Used for `removed` and the\n * original side of a `replaced` block in editor diff mode.\n */\nexport class DiffDecorationViewData {\n\treadonly kind = 'diffDecoration';\n\tconstructor(\n\t\treadonly ast: AstNode,\n\t\treadonly side: BlockViewData,\n\t\treadonly deletedRanges: readonly DiffHighlightRange[],\n\t\t/** True when the whole block was removed: solid red band, no word rects. */\n\t\treadonly whole: boolean,\n\t\t/** Absolute offset of this block in the *original* document. */\n\t\treadonly originalStart: number,\n\t) { }\n}\n\nexport type AnyViewData =\n\t| DocumentViewData | BlockViewData | InlineViewData\n\t| ListItemViewData | TableRowViewData | TableCellViewData\n\t| MarkerViewData | GlueViewData | DiffHunkViewData | DiffDecorationViewData;\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\t// A block can be active without the selection intersecting it (diff\n\t\t\t\t// mode forces changed blocks active to reveal markers), so only\n\t\t\t\t// compute an in-node selection when the ranges actually overlap.\n\t\t\t\tconst selectionInNode = selectionRange\n\t\t\t\t\t&& selectionRange.endExclusive >= pos && selectionRange.start <= pos + block.length\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 a single block in isolation, used by the diff\n * renderer to render the two sides of a {@link DiffHunkViewData}. `active`\n * selects the source/markers-visible form (used for changed blocks so edits to\n * markup and whitespace are visible); inactive is the normal rendered form.\n */\nexport function buildBlockViewData(block: AstNode, active: boolean, previous?: AnyViewData): BlockViewData {\n\tconst ctx: BuildCtx = active\n\t\t? { showMarkup: true, showTableGlue: false, selectionInNode: undefined }\n\t\t: _INACTIVE;\n\treturn _buildBlock(block as BlockAstNode, ctx, previous);\n}\n\n/**\n * Build the document view-data for a diff, rendered through the *normal* editor\n * pipeline so the modified blocks remain the real, editable blocks. It reuses\n * {@link buildDocumentViewData} for the modified document (correct glue, active\n * handling, measurement) and then inserts read-only {@link DiffDecorationViewData}\n * children for removed blocks and the original side of replaced blocks. The\n * decorations carry zero source length, so the editor's offset space is exactly\n * the modified document and editing/cursor are unaffected.\n */\n/**\n * Overlay diff decorations onto an already-built document view-data.\n *\n * `base` is the normal {@link buildDocumentViewData} result for the modified\n * document (so it is built with the usual glue / active handling / measurement\n * *and* the per-frame identity reuse, which keeps editing smooth). This inserts\n * read-only {@link DiffDecorationViewData} children for removed blocks and the\n * original side of replaced blocks, and tags changed modified blocks so they\n * get the green band. Decorations carry zero source length, so the editor's\n * offset space is exactly the modified document and editing/cursor are\n * unaffected.\n */\nexport function applyDiffDecorations(base: DocumentViewData, diffItems: readonly DiffItem[], decorationsActive = false): DocumentViewData {\n\t// Index diff items by their modified-side block; collect removed originals to\n\t// insert before the block they precede (the next non-removed item).\n\tconst overlay = new Map<AstNode, DiffItem>();\n\tconst removedBefore = new Map<AstNode, RemovedItem[]>();\n\tlet pending: RemovedItem[] = [];\n\tfor (const item of diffItems) {\n\t\tif (item.kind === 'removed') { pending.push(item); continue; }\n\t\tconst modAst = _diffModifiedAst(item);\n\t\tif (modAst) {\n\t\t\tif (pending.length) { removedBefore.set(modAst, pending); pending = []; }\n\t\t\toverlay.set(modAst, item);\n\t\t}\n\t}\n\tconst removedAtEnd = pending;\n\n\tconst children: DocumentChildViewData[] = [];\n\tconst blocks: DocumentBlockViewData[] = [];\n\tfor (const child of base.children) {\n\t\tif (child.kind !== 'block') { children.push(child); continue; }\n\t\tconst blockView = child.view as BlockViewData;\n\t\tfor (const rem of removedBefore.get(blockView.ast) ?? []) {\n\t\t\tchildren.push(_decorationChild(rem.node, rem.deletedLocal, child.absoluteStart, true, rem.originalStart, decorationsActive));\n\t\t}\n\t\tconst item = overlay.get(blockView.ast);\n\t\t// Only show the red original when content was actually deleted. A pure\n\t\t// insertion (e.g. a trailing blank line added before a new block) renders\n\t\t// as the active modified block with a green highlight — no red duplicate.\n\t\tif (item && item.kind === 'replaced' && item.deletedLocal.length > 0) {\n\t\t\tchildren.push(_decorationChild(item.original, item.deletedLocal, child.absoluteStart, false, item.originalStart, decorationsActive));\n\t\t}\n\t\t// A changed container renders once, editable, with red decorations woven\n\t\t// in next to its changed/removed children (recursively).\n\t\tconst view = item && item.kind === 'nested' ? decorateContainer(blockView, item, decorationsActive) : blockView;\n\t\tconst diffKind = item?.kind === 'added' ? 'added' as const : item?.kind === 'replaced' ? 'modified' as const : undefined;\n\t\tconst outChild: DocumentChildViewData = diffKind ? { ...child, diffKind } : view !== blockView ? { ...child, view } : child;\n\t\tchildren.push(outChild);\n\t\tblocks.push({ ast: blockView.ast, absoluteStart: child.absoluteStart, isActive: child.isActive, view });\n\t}\n\tfor (const rem of removedAtEnd) {\n\t\tchildren.push(_decorationChild(rem.node, rem.deletedLocal, base.ast.length, true, rem.originalStart, decorationsActive));\n\t}\n\treturn new DocumentViewData(base.ast, blocks, children);\n}\n\nfunction _decorationChild(originalBlock: AstNode, deletedRanges: readonly DiffHighlightRange[], absoluteStart: number, whole: boolean, originalStart: number, forceActive: boolean): DocumentChildViewData {\n\treturn {\n\t\tabsoluteStart,\n\t\tisActive: false,\n\t\tview: _decoration(originalBlock, deletedRanges, whole, originalStart, forceActive),\n\t\tkind: 'diffDecoration',\n\t};\n}\n\n/**\n * Build the read-only original-side decoration for a removed/replaced block.\n * Partial change (`whole=false`): active/source form so marker changes show.\n * Whole removal (`whole=true`): rendered form (clean solid band) unless\n * `forceActive` (the coverage test renders every original char as source).\n */\nfunction _decoration(originalBlock: AstNode, deletedRanges: readonly DiffHighlightRange[], whole: boolean, originalStart: number, forceActive: boolean): DiffDecorationViewData {\n\treturn new DiffDecorationViewData(originalBlock, buildBlockViewData(originalBlock, forceActive || !whole), deletedRanges, whole, originalStart);\n}\n\n/**\n * Recursively overlay decorations *inside* a changed container (list, table,\n * blockquote): the modified container still renders once and editable, with a\n * read-only red {@link DiffDecorationViewData} woven in next to each changed or\n * removed child — and recursing again for a nested child container. Mirrors the\n * document-level overlay but in the container's `content` array; decorations\n * carry zero source length, so the modified offset space is unchanged.\n */\nfunction decorateContainer(container: BlockViewData, item: NestedItem, decorationsActive: boolean): BlockViewData {\n\tconst overlay = new Map<AstNode, DiffItem>();\n\tconst removedBefore = new Map<AstNode, RemovedItem[]>();\n\tlet pending: RemovedItem[] = [];\n\tfor (const c of item.children) {\n\t\tif (c.kind === 'removed') { pending.push(c); continue; }\n\t\tconst modAst = _diffModifiedAst(c);\n\t\tif (modAst) {\n\t\t\tif (pending.length) { removedBefore.set(modAst, pending); pending = []; }\n\t\t\toverlay.set(modAst, c);\n\t\t}\n\t}\n\tconst content = (container as unknown as { content?: readonly AnyViewData[] }).content ?? [];\n\tconst newContent: AnyViewData[] = [];\n\tfor (const cvd of content) {\n\t\tfor (const rem of removedBefore.get(cvd.ast) ?? []) {\n\t\t\tnewContent.push(_decoration(rem.node, rem.deletedLocal, true, rem.originalStart, decorationsActive));\n\t\t}\n\t\tconst c = overlay.get(cvd.ast);\n\t\tif (c && c.kind === 'replaced' && c.deletedLocal.length > 0) {\n\t\t\tnewContent.push(_decoration(c.original, c.deletedLocal, false, c.originalStart, decorationsActive));\n\t\t\tnewContent.push(cvd);\n\t\t} else if (c && c.kind === 'nested') {\n\t\t\tnewContent.push(decorateContainer(cvd as BlockViewData, c, decorationsActive));\n\t\t} else {\n\t\t\tnewContent.push(cvd);\n\t\t}\n\t}\n\tfor (const rem of pending) {\n\t\tnewContent.push(_decoration(rem.node, rem.deletedLocal, true, rem.originalStart, decorationsActive));\n\t}\n\treturn _withContent(container, newContent);\n}\n\n/** Clone a view-data node with its `content` array replaced (identity differs). */\nfunction _withContent<T extends object>(vd: T, content: readonly AnyViewData[]): T {\n\treturn Object.assign(Object.create(Object.getPrototypeOf(vd)), vd, { content }) as T;\n}\n\nfunction _diffModifiedAst(item: DiffItem): AstNode | undefined {\n\tswitch (item.kind) {\n\t\tcase 'unchanged': return item.node;\n\t\tcase 'added': return item.node;\n\t\tcase 'replaced': return item.modified;\n\t\tcase 'nested': return item.modified;\n\t\tcase 'removed': return undefined;\n\t}\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 'unhandledBlock': return _reuseOr(prev, new UnhandledBlockViewData(node, _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 type { OffsetRange } from '../core/offsetRange.js';\nimport type { ViewNode } from './content/viewNode.js';\n\ninterface TextLeaf { readonly text: Text; readonly start: number; readonly len: number; }\n\n/** Text leaves of a view-node subtree with their source start offsets (root-local). */\nfunction collectTextLeaves(root: ViewNode): TextLeaf[] {\n\tconst out: TextLeaf[] = [];\n\tconst walk = (n: ViewNode, base: number): void => {\n\t\tconst kids = n.children;\n\t\tif (kids.length === 0) {\n\t\t\tif (n.dom.nodeType === 3 /* TEXT_NODE */) {\n\t\t\t\tout.push({ text: n.dom as Text, start: base, len: n.sourceLength });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tlet pos = base;\n\t\tfor (const c of kids) {\n\t\t\t// Skip zero-source nodes (e.g. the read-only diff decorations): their\n\t\t\t// rendered text is not part of this root's source space, so including\n\t\t\t// it would mis-map offsets onto the wrong (red) text.\n\t\t\tif (c.sourceLength === 0) { continue; }\n\t\t\twalk(c, pos);\n\t\t\tpos += c.sourceLength;\n\t\t}\n\t};\n\twalk(root, 0);\n\treturn out;\n}\n\nfunction rangeFromLeaves(leaves: readonly TextLeaf[], s: number, e: number): Range | undefined {\n\tlet startNode: Text | undefined;\n\tlet startOff = 0;\n\tlet endNode: Text | undefined;\n\tlet endOff = 0;\n\tfor (const lf of leaves) {\n\t\tconst ls = lf.start;\n\t\tconst le = lf.start + lf.len;\n\t\tif (startNode === undefined && s >= ls && s < le) { startNode = lf.text; startOff = s - ls; }\n\t\tif (e > ls && e <= le) { endNode = lf.text; endOff = e - ls; }\n\t}\n\tif (!startNode || !endNode) { return undefined; }\n\tconst range = document.createRange();\n\trange.setStart(startNode, startOff);\n\trange.setEnd(endNode, endOff);\n\treturn range;\n}\n\n/**\n * Build DOM {@link Range}s for the given source `spans` (offsets in the source\n * space the `root` view node maps) by walking `root`'s text leaves. Spans that\n * fall outside the rendered text (or are empty) are skipped.\n */\nexport function rangesForOffsets(root: ViewNode, spans: readonly OffsetRange[]): Range[] {\n\tconst leaves = collectTextLeaves(root);\n\tconst out: Range[] = [];\n\tfor (const span of spans) {\n\t\tif (span.isEmpty) { continue; }\n\t\tconst range = rangeFromLeaves(leaves, span.start, span.endExclusive);\n\t\tif (range) { out.push(range); }\n\t}\n\treturn out;\n}\n","import { Disposable } from '@vscode/observables';\nimport type { OffsetRange } from '../../core/offsetRange.js';\nimport { DiffDecorationViewNode, DiffHunkViewNode } from '../content/blockView.js';\nimport type { ViewNode } from '../content/viewNode.js';\nimport { rangesForOffsets } from '../diffHighlight.js';\n\n/**\n * Paints diff word/character highlights as an absolutely-positioned overlay of\n * rectangles — the same technique the selection layer uses (geometry from the\n * rendered DOM, no mutation of the content). Green rects cover inserted/changed\n * modified text; red rects cover deleted text inside the read-only\n * decorations/hunks. Coordinates are translated into the layer parent's space,\n * exactly like {@link SelectionView}.\n */\nexport class DiffHighlightsView extends Disposable {\n\treadonly element: HTMLElement;\n\tprivate _last: { readonly node: ViewNode; readonly inserted?: readonly OffsetRange[] } | undefined;\n\tprivate readonly _resizeObserver: ResizeObserver;\n\n\tconstructor(private readonly _parent: HTMLElement) {\n\t\tsuper();\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-diff-highlight-layer';\n\t\t// Repaint on size changes — this also covers the first render happening\n\t\t// before the view is attached/laid out (so the initial rects would be\n\t\t// empty), since attachment changes the observed size.\n\t\tthis._resizeObserver = new ResizeObserver(() => { if (this._last) { this._repaint(this._last); } });\n\t\tthis._resizeObserver.observe(this._parent);\n\t\tthis._register({ dispose: () => { this._resizeObserver.disconnect(); this.element.remove(); } });\n\t}\n\n\tclear(): void {\n\t\tthis._last = undefined;\n\t\tthis.element.replaceChildren();\n\t}\n\n\t/**\n\t * Repaint the highlights for the given view-node tree. `insertedRanges`\n\t * (modified-document offsets) are painted green when supplied (editor diff\n\t * mode); a {@link DiffHunkViewNode}'s own sides supply both colours (the\n\t * standalone read-only diff). Deleted ranges from {@link DiffDecorationViewNode}s\n\t * are always painted red.\n\t */\n\trender(documentNode: ViewNode, insertedRanges?: readonly OffsetRange[]): void {\n\t\tthis._last = { node: documentNode, inserted: insertedRanges };\n\t\tthis._repaint(this._last);\n\t}\n\n\tprivate _repaint(last: { readonly node: ViewNode; readonly inserted?: readonly OffsetRange[] }): void {\n\t\tconst green: Range[] = [];\n\t\tconst red: Range[] = [];\n\t\tif (last.inserted) { green.push(...rangesForOffsets(last.node, last.inserted)); }\n\n\t\tconst walk = (n: ViewNode): void => {\n\t\t\tif (n instanceof DiffDecorationViewNode) {\n\t\t\t\t// Whole-block removals show a solid band only (no word rects).\n\t\t\t\tif (!n.whole) { red.push(...rangesForOffsets(n.sideNode, n.deletedRanges.map(r => r.range))); }\n\t\t\t} else if (n instanceof DiffHunkViewNode) {\n\t\t\t\tfor (const side of n.sides) {\n\t\t\t\t\tfor (const r of side.ranges) {\n\t\t\t\t\t\tconst rs = rangesForOffsets(side.node, [r.range]);\n\t\t\t\t\t\t(r.kind === 'inserted' ? green : red).push(...rs);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const c of n.children) { walk(c); }\n\t\t};\n\t\twalk(last.node);\n\t\tthis._paint(green, red);\n\t}\n\n\tprivate _paint(green: readonly Range[], red: readonly Range[]): void {\n\t\tconst parentRect = this._parent.getBoundingClientRect();\n\t\tconst frag = document.createDocumentFragment();\n\t\tconst add = (ranges: readonly Range[], cls: string): void => {\n\t\t\tfor (const range of ranges) {\n\t\t\t\tfor (const rect of range.getClientRects()) {\n\t\t\t\t\tif (rect.width === 0 || rect.height === 0) { continue; }\n\t\t\t\t\tconst el = document.createElement('div');\n\t\t\t\t\tel.className = cls;\n\t\t\t\t\tel.style.left = `${rect.left - parentRect.left}px`;\n\t\t\t\t\tel.style.top = `${rect.top - parentRect.top}px`;\n\t\t\t\t\tel.style.width = `${rect.width}px`;\n\t\t\t\t\tel.style.height = `${rect.height}px`;\n\t\t\t\t\tfrag.appendChild(el);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tadd(green, 'md-diff-ins-rect');\n\t\tadd(red, 'md-diff-del-rect');\n\t\tthis.element.replaceChildren(frag);\n\t}\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 * The block's horizontal scroll viewport. Equal to {@link element} for every\n * block whose element is itself the `overflow-x: auto` scroller (code, math,\n * unhandled), but the wrapping `.md-table-wrapper` for a table, whose\n * {@link element} is the content-sized inner `<table>`. Only\n * {@link blockViewportClip} needs the scroll box; connector/rect geometry\n * still uses {@link element}.\n */\n readonly scrollElement: 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 const rects = computeRangeRects(selection.range, parent, visualLineMap, blocks);\n path.setAttribute('d', buildConnectedPath(rects, 4));\n return new SelectionViewRendering(rects);\n}\n\n/**\n * Width of the trailing space painted at the end of a line whose hard line\n * break is selected, as a fraction of the line height. This mirrors how\n * editors show a selected newline: a small blank gap past the last glyph\n * (here just a space, no ↵ glyph) rather than nothing or a full-line band.\n */\nconst NEWLINE_SELECTION_WIDTH_RATIO = 0.4;\n\n/**\n * Compute the selection-style rectangles covering `range`, in `parent`-local\n * coordinates. Shared by the live selection layer and the comments overlay so\n * both paint identical geometry from the same source of truth. Returns an empty\n * array for an empty range.\n */\nexport function computeRangeRects(\n range: OffsetRange,\n parent: HTMLElement,\n visualLineMap: VisualLineMap,\n blocks: readonly SelectionBlock[],\n): SelectionRect[] {\n if (range.isEmpty) {\n return [];\n }\n\n const selRange = range;\n const parentRect = parent.getBoundingClientRect();\n\n // 1. Collect the visual lines the selection touches, paired with the\n // block that contains them. A line is touched when either:\n // - the selection overlaps its rendered content, or\n // - the selection covers the line's trailing *hard* line break —\n // it starts at/after the line's content end but extends onto a\n // later line. This second case is what lets a selection that\n // runs off the end of a line paint a small trailing space at\n // that line's end (the way editors render a selected newline),\n // even though no glyph there is itself selected.\n const lines = visualLineMap.lines;\n const lineInfos: { line: VisualLine; lineRange: OffsetRange; block: SelectionBlock | undefined; hardBreak: boolean }[] = [];\n for (let k = 0; k < lines.length; k++) {\n const line = lines[k];\n const lineRange = _lineSourceRange(line);\n if (!lineRange) { continue; }\n // The break after this line is \"hard\" (a real `\\n`, or the document\n // end) when the next visual line starts past this line's content\n // end. A soft wrap has the next line starting exactly at this line's\n // content end, so it is not hard and gets no trailing space.\n const nextRange = k + 1 < lines.length ? _lineSourceRange(lines[k + 1]) : undefined;\n const hardBreak = !nextRange || nextRange.start > lineRange.endExclusive;\n const overlapsContent = selRange.intersects(lineRange);\n const selectsTrailingBreak = hardBreak\n && selRange.start <= lineRange.endExclusive\n && selRange.endExclusive > lineRange.endExclusive;\n if (!overlapsContent && !selectsTrailingBreak) { continue; }\n const block = blocks.find(b => OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length).containsRange(lineRange));\n lineInfos.push({ line, lineRange, block, hardBreak });\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. `startX` is clipped to\n // the selection start when it falls on this line, otherwise the line's\n // left edge. `endX` is clipped to the selection end when it falls on\n // this line; when the selection continues onto a later line, `endX`\n // runs to the painted text's right edge — plus a small fixed space\n // when the following break is a hard newline, so a selection that\n // spills off the end of a line shows a trailing gap there.\n for (const { line, lineRange, hardBreak, block } of lineInfos) {\n const cStart = lineRange.start;\n const cEnd = lineRange.endExclusive;\n\n let startX = selRange.start <= cStart\n ? line.rect.left\n : line.xAtOffset(selRange.start);\n\n let endX: number;\n if (selRange.endExclusive < cEnd) {\n endX = line.xAtOffset(selRange.endExclusive);\n } else {\n const breakSelected = selRange.endExclusive > cEnd;\n endX = line.rect.right + (breakSelected && hardBreak ? line.rect.height * NEWLINE_SELECTION_WIDTH_RATIO : 0);\n }\n\n // A block that scrolls horizontally (code / math / unhandled) clips its\n // content to its own viewport, but the selection layer is one overlay\n // spanning the whole editor and is not clipped — so a rect for a wide\n // line would bleed across the page. Clip each line's rect to its block's\n // visible horizontal bounds; a line scrolled fully out collapses to zero\n // width (invisible, and its connector is dropped below).\n const clip = blockViewportClip(block);\n if (clip) {\n startX = Math.max(startX, clip.left);\n endX = Math.min(endX, clip.right);\n }\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 // If a bordering block has visible text lines but none of them are\n // selected, the selection only covers that block's hidden markers\n // (e.g. a heading's `## ` when the selection ends right at the\n // rendered title). There is nothing visible to bridge to, so a\n // connector here would hang a stray bar in empty space — skip it.\n // Blocks with no visual lines at all (hr, image, math) still fall\n // back to their element rect below so they can be bridged into.\n if ((prevLineIdx === undefined && _blockHasVisualLine(visualLineMap, curr))\n || (nextLineIdx === undefined && _blockHasVisualLine(visualLineMap, next))) { continue; }\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 //\n // The check is \"does this block own ANY visual line in the map\" — not\n // \"does it own a *selected* line\". A text paragraph whose only selected\n // part is its trailing block-gap (offset at the paragraph's end, e.g.\n // selecting from the end of a line across the blank line below) has a\n // visual line, it just doesn't intersect the selection. Such a block\n // must NOT be filled wholesale; only genuinely leaf-less blocks qualify.\n for (const b of blocks) {\n const blockRange = OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length);\n if (!selRange.intersects(blockRange)) { continue; }\n if (_blockHasVisualLine(visualLineMap, b)) { 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 return 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 * Whether `block` owns at least one rendered visual line. Leaf-less blocks\n * (<hr>, image, math) own none; every text block owns at least one.\n */\nfunction _blockHasVisualLine(visualLineMap: VisualLineMap, block: SelectionBlock): boolean {\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)) { return true; }\n }\n return false;\n}\n\n/**\n * Horizontal viewport bounds (client coords) a block clips its content to when\n * it scrolls horizontally (code / math / unhandled blocks are `overflow-x:\n * auto`; a table scrolls inside its `.md-table-wrapper`), or `undefined` when\n * the block does not overflow — so only blocks that actually scroll get their\n * selection (or caret) clipped, leaving every other block (and its gutter\n * markers) untouched. Measures {@link SelectionBlock.scrollElement} (the real\n * scroll viewport, which for a table is the wrapper, not the content-sized\n * `<table>`) via its padding box (`clientLeft`/`clientWidth`).\n */\nexport function blockViewportClip(block: SelectionBlock | undefined): { left: number; right: number } | undefined {\n if (!block) { return undefined; }\n const el = block.scrollElement;\n if (el.scrollWidth <= el.clientWidth + 1) { return undefined; }\n const rect = el.getBoundingClientRect();\n const left = rect.left + el.clientLeft;\n return { left, right: left + el.clientWidth };\n}\n\n/** The block whose source range contains `offset`, or `undefined`. */\nexport function blockContainingOffset(blocks: readonly SelectionBlock[], offset: number): SelectionBlock | undefined {\n return blocks.find(b => offset >= b.absoluteStart && offset <= b.absoluteStart + b.block.length);\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 */\nexport function 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, 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';\nimport { blockViewportClip, blockContainingOffset, type SelectionBlock } from './selectionView.js';\n\nexport interface CursorViewOptions {\n readonly offset: IObservable<SourceOffset | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n /**\n * The mounted blocks, used to hide the caret when it sits at an offset that\n * has been scrolled out of its (horizontally scrolling) block's viewport —\n * matching how the selection is clipped there.\n */\n readonly blocks?: IObservable<readonly SelectionBlock[]>;\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\n // Hide the caret when it sits in a horizontally-scrolling block and\n // has been scrolled outside that block's viewport, so it doesn't\n // float over the editor the way an unclipped selection rect would.\n const blocks = options.blocks ? reader.readObservable(options.blocks) : undefined;\n const clip = blocks ? blockViewportClip(blockContainingOffset(blocks, offset)) : undefined;\n if (clip && (caretRect.x < clip.left - 0.5 || caretRect.x > clip.right + 0.5)) {\n this.element.style.display = 'none';\n return new CursorViewRendering(offset, false, Rect2D.EMPTY);\n }\n\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, 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 { OffsetRange } from '../core/offsetRange.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 { ViewNode } from './content/viewNode.js';\nimport { buildDocumentViewData, applyDiffDecorations, type DocumentViewData } from './viewData.js';\nimport { DiffHighlightsView } from './parts/diffHighlightsView.js';\nimport { CursorView } from './parts/cursorView.js';\nimport { GutterMarkersView } from './parts/gutterMarkersView.js';\nimport { SelectionView, type SelectionBlock, type SelectionRect, computeRangeRects } 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 * Whether to render the sticky edit/read-only toggle at the top-right edge\n\t * of the content. Defaults to `true`; set to `false` to omit it (e.g. in\n\t * fixtures that focus on selection rendering).\n\t */\n\treadonly showReadonlyToggle?: boolean;\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\t/**\n\t * Diff mode only: render every read-only original decoration in active\n\t * (source) form, so even whole-block removals expose their markdown markers\n\t * as real text. Used by the diff-coverage fixture to verify that every\n\t * changed original character is rendered somewhere; off in normal use, where\n\t * whole removals show a clean solid band.\n\t */\n\treadonly diffDecorationsActive?: boolean;\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\tprivate readonly _diffHighlightsView: DiffHighlightsView;\n\tprivate _readonlyToggleButton: HTMLButtonElement | undefined;\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\tscrollElement: b.node.scrollElement,\n\t\t}));\n\t});\n\n\t/**\n\t * The caret rect (zero width) at the selection's active end, in\n\t * {@link overlayContainer}-local coordinates, or `undefined` when there is no\n\t * caret. This is the same geometry the editor paints its cursor from, so\n\t * contributions (e.g. comment mode) can anchor an overlay to the active end of\n\t * the selection — where the user's cursor is — without re-deriving geometry.\n\t */\n\tprivate readonly _caretRect = derived(this, reader => {\n\t\tconst rendering = this._cursorView.rendering.read(reader);\n\t\treturn rendering.visible ? rendering.rect : undefined;\n\t});\n\tpublic get caretRect(): IObservable<Rect2D | undefined> { return this._caretRect; }\n\n\t/**\n\t * The container that establishes the positioning context for the editor's\n\t * overlays (cursor, selection, gutter). Contributions mount their own\n\t * absolutely-positioned overlays here so they share the coordinate space of\n\t * {@link caretRect}.\n\t */\n\tpublic get overlayContainer(): HTMLElement { return this._contentContainer; }\n\n\t/**\n\t * Selection-style rectangles covering `range`, in {@link overlayContainer}-\n\t * local coordinates — the same geometry the live selection paints. Exposed so\n\t * contributions (e.g. persistent comments) can highlight arbitrary ranges and\n\t * anchor overlays to them. Recomputes when the measured layout changes.\n\t */\n\tpublic rangeRects(range: OffsetRange): IObservable<readonly SelectionRect[]> {\n\t\treturn derived(this, reader => {\n\t\t\tconst visualLineMap = this.measuredLayout.visualLineMap.read(reader);\n\t\t\tconst blocks = this._selectionBlocksObs.read(reader);\n\t\t\treturn computeRangeRects(range, this._contentContainer, visualLineMap, blocks);\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\t// Re-measure on reflow. The measured layout is otherwise only recomputed\n\t\t// when the *document* changes (via `_publishMeasurements` on the render\n\t\t// path); nothing observes the container width. So any width change caused\n\t\t// by something other than an edit — e.g. a contribution reserving\n\t\t// right-hand rail space and narrowing the text column — would leave\n\t\t// `visualLineMap`, and every geometry derived from it (selection, cursor,\n\t\t// comment highlights), stale. Observing the content box keeps the\n\t\t// measurement in sync with the actually rendered width. The width guard\n\t\t// makes it idempotent so it settles instead of oscillating.\n\t\tlet lastMeasuredContentWidth = -1;\n\t\tconst resizeObserver = new ResizeObserver(() => {\n\t\t\tconst doc = this._document.get();\n\t\t\tif (!doc) { return; }\n\t\t\tconst width = this._contentContainer.clientWidth;\n\t\t\tif (Math.abs(width - lastMeasuredContentWidth) < 0.5) { return; }\n\t\t\tlastMeasuredContentWidth = width;\n\t\t\tthis._publishMeasurements(doc);\n\t\t});\n\t\tresizeObserver.observe(this._contentContainer);\n\t\tthis._register({ dispose: () => resizeObserver.disconnect() });\n\n\t\t// Inner blocks (code / math / unhandled, and a wide table inside its\n\t\t// `.md-table-wrapper`) scroll horizontally on their own. Scrolling one\n\t\t// moves the text within it, so the measured `visualLineMap` — and the\n\t\t// selection / cursor geometry derived from it, which is clipped to each\n\t\t// block's viewport — goes stale. Re-measure on scroll so the cached line\n\t\t// geometry and the live glyph measurements share the current scroll\n\t\t// basis. Scroll events don't bubble, so listen in the capture phase;\n\t\t// coalesce to one re-measure per frame.\n\t\tlet scrollRaf = 0;\n\t\tconst onBlockScroll = () => {\n\t\t\tif (scrollRaf) { return; }\n\t\t\tscrollRaf = requestAnimationFrame(() => {\n\t\t\t\tscrollRaf = 0;\n\t\t\t\tconst doc = this._document.get();\n\t\t\t\tif (doc) { this._publishMeasurements(doc); }\n\t\t\t});\n\t\t};\n\t\tthis._contentContainer.addEventListener('scroll', onBlockScroll, { capture: true, passive: true });\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tthis._contentContainer.removeEventListener('scroll', onBlockScroll, { capture: true });\n\t\t\t\tif (scrollRaf) { cancelAnimationFrame(scrollRaf); }\n\t\t\t},\n\t\t});\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\tblocks: this._selectionBlocksObs,\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._diffHighlightsView = this._register(new DiffHighlightsView(this._contentContainer));\n\t\tthis._contentContainer.appendChild(this._diffHighlightsView.element);\n\n\t\tif (this._options?.showReadonlyToggle !== false) { this._setupReadonlyToggle(); }\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(); this._clearDiff(); } });\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\t/**\n\t * Renders the edit/read-only mode toggle. It flips the model's\n\t * {@link EditorModel.readonlyMode}: when locked (read-only) every block stays\n\t * in its clean rendered form (no markdown markers revealed) and edits are\n\t * ignored, while text selection still works. The control lives in a\n\t * zero-height *sticky* host inside the centered content container, so the\n\t * lock follows the content's right edge and remains pinned as the document\n\t * scrolls. The current mode is also mirrored onto the root as `.md-readonly`\n\t * for any CSS hooks.\n\t */\n\tprivate _setupReadonlyToggle(): void {\n\t\tconst host = document.createElement('div');\n\t\thost.className = 'md-readonly-toggle-host';\n\t\tthis._contentContainer.classList.add('md-editor-content-with-readonly-toggle');\n\n\t\tconst button = document.createElement('button');\n\t\tbutton.type = 'button';\n\t\tbutton.className = 'md-readonly-toggle';\n\t\tthis._readonlyToggleButton = button;\n\n\t\tconst indicator = document.createElement('span');\n\t\tindicator.className = 'md-readonly-toggle-indicator';\n\t\tindicator.setAttribute('aria-hidden', 'true');\n\n\t\tconst lockedIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\tlockedIcon.classList.add('md-readonly-toggle-icon', 'md-readonly-toggle-icon-locked');\n\t\tlockedIcon.setAttribute('viewBox', '0 0 16 16');\n\t\tlockedIcon.setAttribute('fill', 'currentColor');\n\t\tlockedIcon.setAttribute('aria-hidden', 'true');\n\n\t\tconst lockKeyhole = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\tlockKeyhole.setAttribute('d', 'M8 9C8.55228 9 9 9.44771 9 10C9 10.5523 8.55228 11 8 11C7.44772 11 7 10.5523 7 10C7 9.44771 7.44772 9 8 9Z');\n\t\tconst lockBody = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\tlockBody.setAttribute('fill-rule', 'evenodd');\n\t\tlockBody.setAttribute('clip-rule', 'evenodd');\n\t\tlockBody.setAttribute('d', 'M8 1C9.654 1 11 2.346 11 4V6H12C13.103 6 14 6.897 14 8V13C14 14.103 13.103 15 12 15H4C2.897 15 2 14.103 2 13V8C2 6.897 2.897 6 4 6H5V4C5 2.346 6.346 1 8 1ZM4 7C3.449 7 3 7.449 3 8V13C3 13.551 3.449 14 4 14H12C12.551 14 13 13.551 13 13V8C13 7.449 12.551 7 12 7H4ZM8 2C6.897 2 6 2.897 6 4V6H10V4C10 2.897 9.103 2 8 2Z');\n\t\tlockedIcon.append(lockKeyhole, lockBody);\n\n\t\tconst editingIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\teditingIcon.classList.add('md-readonly-toggle-icon', 'md-readonly-toggle-icon-editing');\n\t\teditingIcon.setAttribute('viewBox', '0 0 16 16');\n\t\teditingIcon.setAttribute('fill', 'currentColor');\n\t\teditingIcon.setAttribute('aria-hidden', 'true');\n\t\tconst editingPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\teditingPath.setAttribute('d', 'M14.236 1.76386C13.2123 0.740172 11.5525 0.740171 10.5289 1.76386L2.65722 9.63549C2.28304 10.0097 2.01623 10.4775 1.88467 10.99L1.01571 14.3755C0.971767 14.5467 1.02148 14.7284 1.14646 14.8534C1.27144 14.9783 1.45312 15.028 1.62432 14.9841L5.00978 14.1151C5.52234 13.9836 5.99015 13.7168 6.36433 13.3426L14.236 5.47097C15.2596 4.44728 15.2596 2.78755 14.236 1.76386ZM11.236 2.47097C11.8691 1.8378 12.8957 1.8378 13.5288 2.47097C14.162 3.10413 14.162 4.1307 13.5288 4.76386L12.75 5.54269L10.4571 3.24979L11.236 2.47097ZM9.75002 3.9569L12.0429 6.24979L5.65722 12.6355C5.40969 12.883 5.10023 13.0595 4.76117 13.1465L2.19447 13.8053L2.85327 11.2386C2.9403 10.8996 3.1168 10.5901 3.36433 10.3426L9.75002 3.9569Z');\n\t\teditingIcon.appendChild(editingPath);\n\n\t\tbutton.append(indicator, lockedIcon, editingIcon);\n\t\thost.appendChild(button);\n\n\t\tconst onClick = (): void => {\n\t\t\tthis._model.readonlyMode.set(!this._model.readonlyMode.get(), undefined);\n\t\t};\n\t\tconst onPointerDown = (event: PointerEvent): void => {\n\t\t\tif (event.button !== 0) { return; }\n\t\t\t// Keep focus and selection in the editor instead of letting its root\n\t\t\t// pointer handler interpret the toggle as a click on editor padding.\n\t\t\tevent.preventDefault();\n\t\t\tevent.stopPropagation();\n\t\t\tthis.focus();\n\t\t};\n\t\tconst onKeyDown = (event: KeyboardEvent): void => {\n\t\t\t// Let the button perform its native keyboard activation without the\n\t\t\t// event also reaching the editor's navigation and editing commands.\n\t\t\tevent.stopPropagation();\n\t\t};\n\t\tconst onFocus = (): void => {\n\t\t\t// Chromium's EditContext host otherwise immediately reclaims focus\n\t\t\t// from a non-text control nested inside it.\n\t\t\tthis.element.editContext = null;\n\t\t};\n\t\tconst onBlur = (): void => {\n\t\t\tthis.element.editContext = this.editContext;\n\t\t};\n\t\tconst onAnimationEnd = (event: AnimationEvent): void => {\n\t\t\tif (event.animationName === 'md-readonly-toggle-shine') {\n\t\t\t\tbutton.classList.remove('md-readonly-toggle-shine');\n\t\t\t}\n\t\t};\n\t\tbutton.addEventListener('pointerdown', onPointerDown);\n\t\tbutton.addEventListener('keydown', onKeyDown);\n\t\tbutton.addEventListener('focus', onFocus);\n\t\tbutton.addEventListener('blur', onBlur);\n\t\tbutton.addEventListener('animationend', onAnimationEnd);\n\t\tbutton.addEventListener('click', onClick);\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tbutton.removeEventListener('pointerdown', onPointerDown);\n\t\t\t\tbutton.removeEventListener('keydown', onKeyDown);\n\t\t\t\tbutton.removeEventListener('focus', onFocus);\n\t\t\t\tbutton.removeEventListener('blur', onBlur);\n\t\t\t\tbutton.removeEventListener('animationend', onAnimationEnd);\n\t\t\t\tbutton.removeEventListener('click', onClick);\n\t\t\t\tif (this._readonlyToggleButton === button) {\n\t\t\t\t\tthis._readonlyToggleButton = undefined;\n\t\t\t\t}\n\t\t\t\tif (this.element.editContext === null) {\n\t\t\t\t\tthis.element.editContext = this.editContext;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\n\t\tthis._register(autorun(reader => {\n\t\t\tconst readonly = this._model.readonlyMode.read(reader);\n\t\t\tbutton.classList.toggle('md-readonly-toggle-locked', readonly);\n\t\t\tbutton.setAttribute('aria-pressed', String(readonly));\n\t\t\tbutton.setAttribute('aria-label', readonly\n\t\t\t\t? 'Locked; switch to editing'\n\t\t\t\t: 'Editing; switch to locked mode');\n\t\t\tbutton.title = readonly\n\t\t\t\t? 'Read-only: markers hidden, editing disabled. Click to edit.'\n\t\t\t\t: 'Editing: click to lock (hide markers, disable editing).';\n\t\t\tif (!readonly) {\n\t\t\t\tbutton.classList.remove('md-readonly-toggle-shine');\n\t\t\t}\n\t\t\tthis.element.classList.toggle('md-readonly', readonly);\n\t\t}));\n\n\t\t// Keep the sticky host ahead of the rendered document while anchoring its\n\t\t// horizontal position to the limited-width content container.\n\t\tthis._contentContainer.insertBefore(host, this._contentContainer.firstChild);\n\t}\n\n\t/** Draws attention to the mode toggle after text input is attempted while locked. */\n\tshowReadonlyEditingAttempt(): void {\n\t\tconst button = this._readonlyToggleButton;\n\t\tif (!button || button.classList.contains('md-readonly-toggle-shine')) { return; }\n\t\tbutton.classList.add('md-readonly-toggle-shine');\n\t}\n\n\tfocus(): void { this.element.focus({ preventScroll: true }); }\n\n\t/**\n\t * Own point→offset resolution. When `true` (the default),\n\t * {@link resolveOffsetFromPoint} ignores the platform DOM hit-test\n\t * (`caretPositionFromPoint`) and snaps the point to the nearest offset purely\n\t * from the rendered {@link VisualLineMap} geometry — picking the nearest\n\t * visual line by `y`, then the nearest offset on it by `x`. Because a table\n\t * row's cells share one horizontal line band, this makes the whole width of a\n\t * row resolve into that row (rather than only the cell boxes), with no visible\n\t * layout change. It also lets a drag keep extending toward off-viewport points\n\t * (e.g. the pointer leaving the window), which the platform hit-test cannot\n\t * resolve. Set to `false` to fall back to the platform DOM hit-test.\n\t */\n\tpublic readonly geometricHitTest = observableValue<boolean>(this, 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. Honours {@link geometricHitTest}.\n\t */\n\tresolveOffsetFromPoint(point: Point2D): SourceOffset | undefined {\n\t\tconst tableCellOffset = this._resolveTableCellOffset(point);\n\t\tif (tableCellOffset !== undefined) { return tableCellOffset; }\n\t\tif (this.geometricHitTest.get()) {\n\t\t\tconst map = this.measuredLayout.visualLineMap.get();\n\t\t\treturn map.isEmpty ? undefined : map.offsetAtPoint(point);\n\t\t}\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 * Resolve table-cell hits that have no measurable text run. Empty cells map\n\t * from their own box instead of snapping to a neighboring cell; element-only\n\t * content (for example an inactive image) maps through the hit element's view\n\t * node. Text-bearing cells keep the normal pixel-precise line-map/DOM path.\n\t */\n\tprivate _resolveTableCellOffset(point: Point2D): SourceOffset | undefined {\n\t\tconst hit = document.elementFromPoint(point.x, point.y);\n\t\tconst cell = hit?.closest('td');\n\t\tif (!(cell instanceof HTMLTableCellElement) || !this._contentContainer.contains(cell)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst documentView = this._document.get();\n\t\tif (!documentView) { return undefined; }\n\t\tconst cellNode = ViewNode.forDom(cell);\n\t\tif (cellNode?.ast.kind !== 'tableCell' || cellNode.dom !== cell) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst cellStart = documentView.resolveSource({ node: cell, offset: 0 });\n\t\tconst cellEnd = documentView.resolveSource({ node: cell, offset: 1 });\n\t\tif (cellStart === undefined || cellEnd === undefined) { return undefined; }\n\n\t\tconst domOffsetAtPoint = (element: Element): 0 | 1 => {\n\t\t\tconst rect = element.getBoundingClientRect();\n\t\t\tconst isRtl = getComputedStyle(element).direction === 'rtl';\n\t\t\tconst onStartSide = isRtl ? point.x >= rect.left + rect.width / 2 : point.x < rect.left + rect.width / 2;\n\t\t\treturn onStartSide ? 0 : 1;\n\t\t};\n\n\t\tconst hasSourceRun = (start: SourceOffset, end: SourceOffset): boolean =>\n\t\t\tthis.measuredLayout.visualLineMap.get().lines.some(line =>\n\t\t\t\tline.runs.some(run =>\n\t\t\t\t\trun.source !== undefined\n\t\t\t\t\t&& run.sourceStart < end\n\t\t\t\t\t&& run.sourceEndExclusive > start\n\t\t\t\t)\n\t\t\t);\n\n\t\tconst hitNode = hit ? ViewNode.forDom(hit) : undefined;\n\t\tif (hitNode && hitNode !== cellNode && hitNode.dom instanceof Element) {\n\t\t\tconst hitStart = documentView.resolveSource({ node: hitNode.dom, offset: 0 });\n\t\t\tconst hitEnd = documentView.resolveSource({ node: hitNode.dom, offset: 1 });\n\t\t\tif (hitStart !== undefined && hitEnd !== undefined && !hasSourceRun(hitStart, hitEnd)) {\n\t\t\t\tif (hitEnd - hitStart <= 1) { return hitEnd; }\n\t\t\t\treturn domOffsetAtPoint(hitNode.dom) === 0 ? hitStart + 1 : hitEnd - 1;\n\t\t\t}\n\t\t}\n\n\t\tif (hasSourceRun(cellStart, cellEnd)) { return undefined; }\n\t\tif (cellEnd - cellStart <= 1) { return cellEnd; }\n\t\treturn domOffsetAtPoint(cell) === 0 ? cellStart + 1 : cellEnd - 1;\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\t\tconst diff = reader.readObservable(this._model.diff);\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 baseViewData = buildDocumentViewData(\n\t\t\tdoc, diff ? new Set([...activeBlocks, ...diff.changedBlocks]) : activeBlocks,\n\t\t\tselection?.range, this._previousViewData,\n\t\t\tpending ? { anchorBlock: pending.anchorBlock, ast: pending.syntheticAst } : undefined,\n\t\t);\n\t\tthis._previousViewData = baseViewData;\n\t\tconst viewData = diff ? applyDiffDecorations(baseViewData, diff.items, this._options?.diffDecorationsActive) : baseViewData;\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, preserving any leading view chrome.\n\t\t\tthis._contentContainer.insertBefore(documentNode.contentDomNode, this._selectionView.element);\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\n\t\tif (diff) { this._paintDiff(documentNode, diff.insertedRanges); }\n\t\telse { this._clearDiff(); }\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\t/**\n\t * Paint the diff highlights via the CSS Custom Highlight API: green over the\n\t * inserted/changed modified ranges (mapped on the document's own DOM), and\n\t * red over each {@link DiffDecorationViewNode}'s deleted ranges (mapped on\n\t * the decoration's own subtree). No DOM is mutated, so reconciliation and\n\t * editing are unaffected.\n\t */\n\tprivate _paintDiff(documentNode: DocumentViewNode, insertedRanges: readonly OffsetRange[]): void {\n\t\tthis._diffHighlightsView.render(documentNode, insertedRanges);\n\t}\n\n\tprivate _clearDiff(): void {\n\t\tthis._diffHighlightsView.clear();\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/** Max time between pointer-downs to count as part of the same multi-click. */\nconst MULTI_CLICK_TIME_MS = 500;\n/** Max movement (px, per axis) between pointer-downs of one multi-click. */\nconst MULTI_CLICK_DISTANCE_PX = 5;\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 * - `_clickCount` / `_lastPointerDown` — multi-click detection for pointer\n * input, since `pointerdown` events (unlike `mousedown`) don't populate\n * `detail` with a click count.\n */\nexport class EditorController extends Disposable {\n private _desiredColumn: number | undefined;\n\n /** Running click count for the current multi-click sequence (1, 2, 3, …). */\n private _clickCount = 0;\n /** Timestamp and position of the previous pointer-down, for multi-click detection. */\n private _lastPointerDown: { time: number; point: Point2D } | 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('pointerdown', this._handlePointerDown);\n el.addEventListener('keydown', this._handleKeyDown);\n this._register({\n dispose: () => {\n el.removeEventListener('pointerdown', this._handlePointerDown);\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 if (this._model.readonlyMode.get() && e.text.length > 0) {\n this._view.showReadonlyEditingAttempt();\n }\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 _handlePointerDown = (e: PointerEvent): void => {\n // Only the primary button starts a selection drag.\n if (e.button !== 0) { return; }\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 // `pointerdown` doesn't carry a click count in `detail` (it's always 0),\n // so detect double/triple clicks ourselves: consecutive pointer-downs\n // close in time and position bump the count, otherwise it resets to 1.\n const prev = this._lastPointerDown;\n const isRepeat = prev !== undefined\n && (e.timeStamp - prev.time) < MULTI_CLICK_TIME_MS\n && Math.abs(point.x - prev.point.x) < MULTI_CLICK_DISTANCE_PX\n && Math.abs(point.y - prev.point.y) < MULTI_CLICK_DISTANCE_PX;\n this._clickCount = isRepeat ? this._clickCount + 1 : 1;\n this._lastPointerDown = { time: e.timeStamp, point };\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 (this._clickCount === 2) {\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectWord(ctx, offset), undefined);\n return;\n }\n\n if (this._clickCount === 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 // A primary single click (no Shift) inside locked content hints the user\n // expects to edit, so we flash the mode toggle to reveal the lock — but\n // only once the gesture ends *without* a selection. Deferring the check to\n // pointer-up and keying it off an empty final selection is what tells a\n // click apart from a drag-select (which stays quiet) and tolerates\n // sub-character pointer jitter. A Shift-click extends a selection, so it\n // is excluded here. Padding clicks and the 2nd/3rd press of a\n // double/triple click return earlier, so word/block selection is\n // preserved — but note the *first* press of a multi-click is itself a\n // single click, so it still emits one (bounded, non-stacking) sheen\n // before the word/block is selected. That is an accepted trade:\n // suppressing it would need a 500ms debounce that lags every single-click\n // reveal, or a jarring mid-animation cancel.\n const revealsLockOnClick = this._clickCount === 1\n && !e.shiftKey\n && this._model.readonlyMode.get();\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 // Capture the pointer so the drag keeps receiving move/up events even\n // when the pointer leaves the window — a plain `mouseup` fired outside\n // the window never reaches the page, which would otherwise leave the\n // drag \"stuck\" until the next click. Pointer capture also unifies\n // mouse, touch, and pen input.\n const el = this._view.element;\n const pointerId = e.pointerId;\n el.setPointerCapture(pointerId);\n this._model.isSelecting.set(true, undefined);\n\n const onPointerMove = (me: PointerEvent): 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 onPointerUp = (): void => {\n this._model.isSelecting.set(false, undefined);\n // A click that placed a caret (collapsed selection) rather than a\n // drag-selection reveals the lock; reuses the same sheen as typing.\n if (revealsLockOnClick && (this._model.selection.get()?.isCollapsed ?? true)) {\n this._view.showReadonlyEditingAttempt();\n }\n el.removeEventListener('pointermove', onPointerMove);\n el.removeEventListener('pointerup', onPointerUp);\n el.removeEventListener('pointercancel', onPointerUp);\n el.removeEventListener('lostpointercapture', onPointerUp);\n };\n el.addEventListener('pointermove', onPointerMove);\n el.addEventListener('pointerup', onPointerUp);\n el.addEventListener('pointercancel', onPointerUp);\n el.addEventListener('lostpointercapture', onPointerUp);\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","import { Disposable, autorun, observableValue, type IObservable } from '@vscode/observables';\n\n/**\n * Codicon \"plus\" (add) glyph shown on the submit action, matching VS Code's\n * agent-feedback input widget. Inlined as an SVG so the markdown editor doesn't\n * depend on the codicon font.\n */\nconst PLUS_SVG =\n\t`<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"currentColor\" aria-hidden=\"true\">`\n\t+ `<path d=\"M14 7v1H8v6H7V8H1V7h6V1h1v6h6z\"></path>`\n\t+ `</svg>`;\n\nexport interface CommentInputWidgetOptions {\n\t/** Placeholder shown while the textarea is empty. Defaults to \"Add Comment\". */\n\treadonly placeholder?: string;\n\t/** Called after the textarea changes size. */\n\treadonly onDidChangeSize?: () => void;\n\t/**\n\t * Called when the user submits a non-empty comment (Enter or the send\n\t * button). The text is trimmed; never called with an empty string.\n\t */\n\treadonly onSubmit?: (text: string) => void;\n\t/** Called when the user dismisses the input (Escape). */\n\treadonly onCancel?: () => void;\n}\n\n/**\n * A self-contained comment input box — a rounded panel with an auto-growing\n * textarea and a send button, styled after the gdocs/Word \"add a comment\"\n * affordance.\n *\n * This widget is *positioning-agnostic*: it only owns its own DOM and state.\n * A host (the comment-mode controller, or a fixture) mounts {@link element}\n * wherever it likes and is responsible for placing it relative to a selection.\n *\n * State is observable-driven (no framework): {@link value} reflects the live\n * textarea content; submit/cancel are reported through the option callbacks.\n */\nexport class CommentInputWidget extends Disposable {\n\treadonly element: HTMLElement;\n\n\tprivate readonly _textarea: HTMLTextAreaElement;\n\tprivate readonly _measure: HTMLSpanElement;\n\tprivate readonly _submitButton: HTMLButtonElement;\n\n\tprivate readonly _value = observableValue<string>(this, '');\n\t/** Live, untrimmed textarea content. */\n\tget value(): IObservable<string> { return this._value; }\n\n\t/** The raw textarea, exposed so a host can move focus into it (e.g. on Tab). */\n\tget inputElement(): HTMLTextAreaElement { return this._textarea; }\n\n\tconstructor(private readonly _options?: CommentInputWidgetOptions) {\n\t\tsuper();\n\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-comment-input';\n\n\t\tthis._textarea = document.createElement('textarea');\n\t\tthis._textarea.className = 'md-comment-input-textarea';\n\t\tthis._textarea.rows = 1;\n\t\tthis._textarea.placeholder = _options?.placeholder ?? 'Add Comment';\n\t\tthis.element.appendChild(this._textarea);\n\n\t\t// Hidden element used to measure text width for auto-growing.\n\t\tthis._measure = document.createElement('span');\n\t\tthis._measure.className = 'md-comment-input-measure';\n\t\tthis._measure.setAttribute('aria-hidden', 'true');\n\t\tthis.element.appendChild(this._measure);\n\n\t\tconst footer = document.createElement('div');\n\t\tfooter.className = 'md-comment-input-actions';\n\t\tthis.element.appendChild(footer);\n\n\t\tthis._submitButton = document.createElement('button');\n\t\tthis._submitButton.type = 'button';\n\t\tthis._submitButton.className = 'md-comment-input-submit';\n\t\tthis._submitButton.innerHTML = PLUS_SVG;\n\t\tthis._submitButton.title = 'Comment';\n\t\tfooter.appendChild(this._submitButton);\n\n\t\t// Clicking anywhere in the panel padding (not the button) focuses the\n\t\t// textarea. Stop the event from reaching the host editor, which would\n\t\t// otherwise move focus/selection out of the box on every click inside it.\n\t\t// The editor starts selection drags on `pointerdown`, so guard that.\n\t\tconst onPanelPointerDown = (e: PointerEvent): void => {\n\t\t\te.stopPropagation();\n\t\t\tif (e.target === this._textarea || this._submitButton.contains(e.target as Node)) { return; }\n\t\t\te.preventDefault();\n\t\t\tthis._textarea.focus();\n\t\t};\n\t\tthis.element.addEventListener('pointerdown', onPanelPointerDown);\n\t\tthis._register({ dispose: () => this.element.removeEventListener('pointerdown', onPanelPointerDown) });\n\n\t\tconst onInput = (): void => {\n\t\t\tthis._value.set(this._textarea.value, undefined);\n\t\t\tthis._autoSize();\n\t\t};\n\t\tthis._textarea.addEventListener('input', onInput);\n\t\tthis._register({ dispose: () => this._textarea.removeEventListener('input', onInput) });\n\n\t\tconst onKeyDown = (e: KeyboardEvent): void => {\n\t\t\t// The box lives inside the editor element, so its keystrokes would\n\t\t\t// otherwise bubble to the editor's key handler (moving the editor\n\t\t\t// caret, deleting document text, etc.). Keep every key inside the box —\n\t\t\t// the textarea handles its own editing (typing, arrows, delete) natively.\n\t\t\te.stopPropagation();\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._options?.onCancel?.();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Enter submits; Shift+Enter inserts a newline.\n\t\t\tif (e.key === 'Enter' && !e.shiftKey) {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._submit();\n\t\t\t}\n\t\t};\n\t\tthis._textarea.addEventListener('keydown', onKeyDown);\n\t\tthis._register({ dispose: () => this._textarea.removeEventListener('keydown', onKeyDown) });\n\n\t\tconst onSubmitClick = (): void => this._submit();\n\t\tthis._submitButton.addEventListener('click', onSubmitClick);\n\t\tthis._register({ dispose: () => this._submitButton.removeEventListener('click', onSubmitClick) });\n\n\t\t// Keep the submit button enabled state in sync with the content.\n\t\tthis._register(autorun(reader => {\n\t\t\tconst hasText = this._value.read(reader).trim().length > 0;\n\t\t\tthis._submitButton.disabled = !hasText;\n\t\t\tthis.element.classList.toggle('md-comment-input-empty', !hasText);\n\t\t}));\n\n\t\tthis._autoSize();\n\t}\n\n\t/** Move focus into the textarea (caret at the end). */\n\tfocus(): void {\n\t\tthis._textarea.focus();\n\t\tconst end = this._textarea.value.length;\n\t\tthis._textarea.setSelectionRange(end, end);\n\t}\n\n\t/** Replace the textarea content. */\n\tsetText(text: string): void {\n\t\tthis._textarea.value = text;\n\t\tthis._value.set(text, undefined);\n\t\tthis._autoSize();\n\t}\n\n\t/** Clear the textarea. */\n\tclear(): void {\n\t\tthis.setText('');\n\t}\n\n\tprivate _submit(): void {\n\t\tconst text = this._textarea.value.trim();\n\t\tif (!text) { return; }\n\t\tthis._options?.onSubmit?.(text);\n\t}\n\n\tprivate _autoSize(): void {\n\t\t// Width: measure the text (or placeholder) and grow the textarea to fit,\n\t\t// clamped between a minimum and maximum — mirrors the reference widget so\n\t\t// the bubble hugs short content and wraps long content at the max width.\n\t\tconst text = this._textarea.value || this._textarea.placeholder;\n\t\tthis._measure.textContent = text;\n\t\tconst textWidth = this._measure.scrollWidth;\n\t\tconst minWidth = 150;\n\t\tconst maxWidth = 400;\n\t\tconst width = Math.min(Math.max(minWidth, textWidth + 10), maxWidth);\n\t\tthis._textarea.style.width = `${width}px`;\n\n\t\t// Height: reset to auto, then grow to fit the content.\n\t\tthis._textarea.style.height = 'auto';\n\t\t// While the textarea is detached (e.g. constructed before being mounted)\n\t\t// scrollHeight is 0; leaving height at `auto` keeps the natural one-row\n\t\t// height (and the placeholder visible) until a real measurement is\n\t\t// possible. Once mounted, grow to fit the content.\n\t\tconst scrollHeight = this._textarea.scrollHeight;\n\t\tif (scrollHeight > 0) {\n\t\t\tthis._textarea.style.height = `${scrollHeight}px`;\n\t\t}\n\t\tthis._options?.onDidChangeSize?.();\n\t}\n}\n","import { Disposable, autorun, type IReader } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport { Rect2D } from '../../core/geometry.js';\nimport type { EditorModel } from '../../model/editorModel.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport { CommentInputWidget } from './commentInputWidget.js';\n\n/** A comment the user submitted, with the source range it was anchored to. */\nexport interface CommentSubmission {\n\treadonly text: string;\n\treadonly range: OffsetRange;\n}\n\nexport interface CommentModeControllerOptions {\n\t/** Called when the user submits a comment for the current selection. */\n\treadonly onSubmit?: (submission: CommentSubmission) => void;\n\t/** Gap (px) between the bottom of the selection and the top of the input box. */\n\treadonly gap?: number;\n}\n\n/**\n * Comment mode — a gdocs/Word-style \"add a comment\" affordance layered on top of\n * the editor *without modifying it*. It reads the editor's public observables\n * ({@link EditorModel.readonlyMode}, {@link EditorModel.selection}) and the\n * exposed {@link EditorView.caretRect} geometry, and mounts a\n * {@link CommentInputWidget} into {@link EditorView.overlayContainer}.\n *\n * Behaviour:\n * - Only active in read-only mode (the \"review\" view).\n * - When the selection is non-empty, the input box appears next to the caret\n * (the selection's active end) but does NOT take focus, so keyboard selection\n * keeps working. Press Tab to move focus into the box, then type.\n * - The box appears on mouse-up, not mid-drag, so it doesn't flicker/jump\n * while a selection is being dragged out (keyboard selection shows at once).\n * - While the box has focus or holds a draft it is frozen in place (selection\n * changes, drags and clicks no longer move it). It is dismissed by Escape,\n * by submitting, or by blurring an empty box.\n * - The editor's logical caret geometry remains available for anchoring in\n * read-only mode even though the painted caret is hidden. While the box has\n * focus, `.md-comment-active` also suppresses the painted caret in any mode.\n */\nexport class CommentModeController extends Disposable {\n\tprivate readonly _widget: CommentInputWidget;\n\tprivate readonly _gap: number;\n\tprivate _visible = false;\n\tprivate _anchorX = 0;\n\tprivate _pinnedRange: OffsetRange | undefined;\n\t/**\n\t * The range a comment was just submitted for. The box stays hidden for it\n\t * until the selection changes, so submitting doesn't immediately re-summon an\n\t * empty box on the still-selected text.\n\t */\n\tprivate _submittedRange: OffsetRange | undefined;\n\n\tconstructor(\n\t\tprivate readonly _model: EditorModel,\n\t\tprivate readonly _view: EditorView,\n\t\tprivate readonly _options?: CommentModeControllerOptions,\n\t) {\n\t\tsuper();\n\t\tthis._gap = _options?.gap ?? 8;\n\n\t\tthis._widget = this._register(new CommentInputWidget({\n\t\t\tonDidChangeSize: () => {\n\t\t\t\tif (this._visible) {\n\t\t\t\t\tthis._layoutHorizontally();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonSubmit: text => this._submit(text),\n\t\t\tonCancel: () => this._hideAndRefocus(),\n\t\t}));\n\t\tconst el = this._widget.element;\n\t\tel.style.position = 'absolute';\n\t\tel.style.zIndex = '20';\n\t\tel.style.display = 'none';\n\t\tthis._view.overlayContainer.appendChild(el);\n\t\tthis._register({ dispose: () => el.remove() });\n\t\tthis._register({ dispose: () => this._view.element.classList.remove('md-comment-active') });\n\n\t\tconst resizeObserver = new ResizeObserver(() => {\n\t\t\tif (this._visible) {\n\t\t\t\tthis._layoutHorizontally();\n\t\t\t}\n\t\t});\n\t\tresizeObserver.observe(el);\n\t\tresizeObserver.observe(this._view.overlayContainer);\n\t\tthis._register({ dispose: () => resizeObserver.disconnect() });\n\n\t\tthis._register(autorun(reader => this._update(reader)));\n\n\t\tconst doc = this._view.element.ownerDocument;\n\n\t\t// Suppress the editor's painted caret while focus belongs to the comment\n\t\t// input. Read-only mode already hides it visually without removing the\n\t\t// geometry this controller uses for anchoring.\n\t\tconst onFocus = (): void => { this._view.element.classList.add('md-comment-active'); };\n\t\tthis._widget.inputElement.addEventListener('focus', onFocus);\n\t\tthis._register({ dispose: () => this._widget.inputElement.removeEventListener('focus', onFocus) });\n\n\t\t// Dismiss an empty box once focus leaves it (e.g. a click elsewhere). A\n\t\t// non-empty draft is preserved, and a focused box is never hidden — see\n\t\t// `_autoHide`. Deferred so focus has settled before we decide.\n\t\tconst onBlur = (): void => {\n\t\t\tthis._view.element.classList.remove('md-comment-active');\n\t\t\tdoc.defaultView?.setTimeout(() => this._autoHide(), 0);\n\t\t};\n\t\tthis._widget.inputElement.addEventListener('blur', onBlur);\n\t\tthis._register({ dispose: () => this._widget.inputElement.removeEventListener('blur', onBlur) });\n\n\t\t// Tab moves focus from the document into the visible box, so the user can\n\t\t// select with the keyboard first and then press Tab to start typing. The\n\t\t// editor itself does not handle Tab, so a plain bubble listener suffices.\n\t\tconst onKeyDown = (e: KeyboardEvent): void => {\n\t\t\tif (e.key !== 'Tab' || e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) { return; }\n\t\t\tif (!this._visible || this._widgetHasFocus()) { return; }\n\t\t\te.preventDefault();\n\t\t\tthis._widget.focus();\n\t\t};\n\t\tthis._view.element.addEventListener('keydown', onKeyDown);\n\t\tthis._register({ dispose: () => this._view.element.removeEventListener('keydown', onKeyDown) });\n\t}\n\n\tprivate _update(reader: IReader): void {\n\t\tconst readonly = this._model.readonlyMode.read(reader);\n\t\tconst selection = this._model.selection.read(reader);\n\t\tconst caretRect = this._view.caretRect.read(reader);\n\t\tconst isSelecting = this._model.isSelecting.read(reader);\n\t\tconst hasTypedText = this._widget.value.read(reader).trim().length > 0;\n\n\t\t// Leaving read-only mode tears the box down unconditionally.\n\t\tif (!readonly) {\n\t\t\tthis._hide();\n\t\t\treturn;\n\t\t}\n\n\t\t// Freeze the box while the user is engaged with it — it has focus or a\n\t\t// draft — so selection changes, drags and clicks no longer move or hide it.\n\t\t// They dismiss it via Escape, submit, or by clicking away.\n\t\tif (this._visible && (hasTypedText || this._widgetHasFocus())) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't react while a selection drag is in progress: wait for it to end so\n\t\t// the box doesn't flicker/jump while a selection is dragged out.\n\t\tif (isSelecting) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!selection || selection.isCollapsed || !caretRect) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't re-show the box for a range we just commented on; keep it hidden\n\t\t// until the user selects something else (then this suppression is cleared).\n\t\tif (this._submittedRange?.equals(selection.range)) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\t\tthis._submittedRange = undefined;\n\n\t\t// Anchor to the active end of the selection (where the caret is). A forward\n\t\t// selection's caret sits at the bottom — place the box below it; a backward\n\t\t// selection's caret sits at the top — place it above. This keeps the box next\n\t\t// to the user's cursor regardless of how large the selection is.\n\t\tthis._pinnedRange = selection.range;\n\t\tthis._show(caretRect, /* preferAbove */ !selection.isForward);\n\t}\n\n\tprivate _show(caretRect: Rect2D, preferAbove: boolean): void {\n\t\tconst el = this._widget.element;\n\n\t\t// Reveal before measuring so offset dimensions are valid.\n\t\tel.style.display = '';\n\t\tthis._visible = true;\n\n\t\t// Place the box on the caret's side, flipping only if that side has no room\n\t\t// within the visible viewport. Caret coordinates are overlayContainer-local;\n\t\t// convert to client space (via the container/viewport rects) for the fit\n\t\t// test, then position using the container-local values.\n\t\tconst widgetHeight = el.offsetHeight;\n\t\tconst containerTop = this._view.overlayContainer.getBoundingClientRect().top;\n\t\tconst viewport = this._getViewportRect();\n\t\tconst caretTop = containerTop + caretRect.y;\n\t\tconst caretBottom = containerTop + caretRect.y + caretRect.height;\n\t\tconst roomBelow = caretBottom + this._gap + widgetHeight <= viewport.bottom;\n\t\tconst roomAbove = caretTop - this._gap - widgetHeight >= viewport.top;\n\t\tconst placeAbove = preferAbove ? (roomAbove || !roomBelow) : (!roomBelow && roomAbove);\n\t\tconst topPx = placeAbove\n\t\t\t? caretRect.y - this._gap - widgetHeight\n\t\t\t: caretRect.y + caretRect.height + this._gap;\n\n\t\tthis._anchorX = caretRect.x;\n\t\tthis._layoutHorizontally();\n\t\tel.style.top = `${topPx}px`;\n\t}\n\n\tprivate _layoutHorizontally(): void {\n\t\tconst el = this._widget.element;\n\t\tconst containerWidth = this._view.overlayContainer.clientWidth;\n\t\tel.style.maxWidth = `${Math.max(0, containerWidth - this._gap)}px`;\n\t\tconst maxLeft = Math.max(0, containerWidth - el.offsetWidth - this._gap);\n\t\tel.style.left = `${Math.min(Math.max(0, this._anchorX), maxLeft)}px`;\n\t}\n\n\t/** Force-hide and clear the box (used by Escape and submit). */\n\tprivate _hide(): void {\n\t\tif (!this._visible) { return; }\n\t\tthis._visible = false;\n\t\tthis._pinnedRange = undefined;\n\t\tthis._widget.clear();\n\t\tthis._widget.element.style.display = 'none';\n\t\tthis._view.element.classList.remove('md-comment-active');\n\t}\n\n\t/**\n\t * Hide unless the user is engaged with the box: it has focus or holds a\n\t * non-empty draft. This preserves in-progress text and keeps a focused box\n\t * open (it is dismissed explicitly via Escape/submit, or by blurring it).\n\t */\n\tprivate _autoHide(): void {\n\t\tif (this._widgetHasFocus() || this._widget.value.get().trim().length > 0) { return; }\n\t\tthis._hide();\n\t}\n\n\tprivate _widgetHasFocus(): boolean {\n\t\tconst active = this._view.element.ownerDocument.activeElement;\n\t\treturn active !== null && this._widget.element.contains(active);\n\t}\n\n\t/**\n\t * The visible viewport (client coords) used for the flip-above decision: the\n\t * nearest scrollable ancestor of the editor. `.md-editor` itself spans the\n\t * full document height and never clips, so measuring against it would always\n\t * report room below. Falls back to the window when nothing scrolls.\n\t */\n\tprivate _getViewportRect(): { top: number; bottom: number } {\n\t\tconst win = this._view.element.ownerDocument.defaultView;\n\t\tlet el: HTMLElement | null = this._view.element;\n\t\twhile (el) {\n\t\t\tconst overflowY = win?.getComputedStyle(el).overflowY;\n\t\t\tif ((overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight) {\n\t\t\t\tconst rect = el.getBoundingClientRect();\n\t\t\t\treturn { top: rect.top, bottom: rect.bottom };\n\t\t\t}\n\t\t\tel = el.parentElement;\n\t\t}\n\t\treturn { top: 0, bottom: win?.innerHeight ?? 0 };\n\t}\n\n\tprivate _hideAndRefocus(): void {\n\t\tthis._hide();\n\t\tthis._view.focus();\n\t}\n\n\tprivate _submit(text: string): void {\n\t\tconst range = this._pinnedRange;\n\t\t// Remember the range so the box doesn't immediately reappear for the text\n\t\t// that is still selected after submitting.\n\t\tthis._submittedRange = range;\n\t\tthis._hideAndRefocus();\n\t\tif (range) {\n\t\t\tthis._options?.onSubmit?.({ text, range });\n\t\t}\n\t}\n}\n","import { observableValue, type IObservable, type ISettableObservable } from '@vscode/observables';\nimport type { OffsetRange } from '../../core/offsetRange.js';\n\n/** A persistent comment anchored to a source range. */\nexport interface Comment {\n\treadonly id: string;\n\t/** Source range the comment refers to (its highlighted region). */\n\treadonly range: OffsetRange;\n\t/** The comment text. */\n\treadonly body: string;\n\t/** Display name of the author, if any. */\n\treadonly author?: string;\n\t/** Creation time (epoch ms), used to render a relative timestamp. */\n\treadonly createdAt?: number;\n}\n\n/**\n * Seedable store of {@link Comment}s for the comment-mode contribution. Owns the\n * comment list and the shared hover state; it has no opinion on rendering or\n * persistence — a host seeds it via {@link set}/{@link add} and observes\n * {@link comments}.\n */\nexport class CommentsModel {\n\tprivate readonly _comments = observableValue<readonly Comment[]>(this, []);\n\t/** Monotonic counter for ids of comments created via {@link create}. */\n\tprivate _sequence = 0;\n\t/** The current comments, in insertion order. */\n\tget comments(): IObservable<readonly Comment[]> { return this._comments; }\n\n\t/**\n\t * The comment currently hovered (by its card or its highlight), or\n\t * `undefined`. Shared so the card and the highlight can react together.\n\t */\n\treadonly hoveredId: ISettableObservable<string | undefined> = observableValue<string | undefined>(this, undefined);\n\n\t/** Replace the whole comment set. */\n\tset(comments: readonly Comment[]): void {\n\t\tthis._comments.set(comments, undefined);\n\t}\n\n\t/**\n\t * Create a comment from a user submission and append it, generating its `id`\n\t * and `createdAt` here so id/time allocation stays the store's concern (the\n\t * UI only supplies the range and text). Returns the created comment.\n\t */\n\tcreate(input: { range: OffsetRange; body: string; author?: string }): Comment {\n\t\tconst comment: Comment = {\n\t\t\tid: `comment-${++this._sequence}`,\n\t\t\trange: input.range,\n\t\t\tbody: input.body,\n\t\t\tauthor: input.author,\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\t\tthis.add(comment);\n\t\treturn comment;\n\t}\n\n\t/** Append a comment. */\n\tadd(comment: Comment): void {\n\t\tthis._comments.set([...this._comments.get(), comment], undefined);\n\t}\n\n\t/** Remove a comment by id. */\n\tremove(id: string): void {\n\t\tthis._comments.set(this._comments.get().filter(c => c.id !== id), undefined);\n\t}\n}\n","import { Disposable, autorun, type IObservable, type IReader } from '@vscode/observables';\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport { buildConnectedPath } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport type { Comment, CommentsModel } from './commentsModel.js';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n/** Layout constants (px). */\nconst RAIL_MIN = 260;\nconst RAIL_MAX = 320;\nconst RAIL_FRACTION = 0.32;\n/** Gap between the content's right edge and the rail. */\nconst RAIL_GAP = 28;\n/** Gap between the rail and the editor's right edge. */\nconst RAIL_EDGE = 16;\n/** Vertical gap between stacked cards. */\nconst CARD_GAP = 12;\n/** Where on the card the leader attaches, measured from the card top. */\nconst LEADER_CARD_INSET = 18;\n/** Corner radius of the range highlight. */\nconst HIGHLIGHT_RADIUS = 4;\n/** Stroke width of the leader line (must match .md-comment-leader-path). */\nconst LEADER_WIDTH = 2;\n/** How far the leader starts inside the highlight so the seam is hidden under\n * the (same-colored) fill. */\nconst LEADER_OVERLAP = 10;\n\n/** Per-comment DOM + state, reconciled against the model's comment list. */\ninterface CommentEntry {\n\tcomment: Comment;\n\trects: IObservable<readonly SelectionRect[]>;\n\treadonly group: SVGGElement;\n\treadonly shapePath: SVGPathElement;\n\treadonly leaderPath: SVGPathElement;\n\treadonly card: HTMLElement;\n\treadonly bodyEl: HTMLElement;\n\treadonly authorEl: HTMLElement;\n\treadonly avatarEl: HTMLElement;\n\treadonly timeEl: HTMLElement;\n\treadonly disposables: { dispose(): void }[];\n}\n\n/**\n * Renders persistent comments as a gdocs-style side rail: each comment's range\n * is highlighted (reusing the editor's selection geometry via\n * {@link EditorView.rangeRects}), a leader line curves from the bottom of that\n * highlight to a card stacked in the right rail, and cards never overlap.\n *\n * Everything is mounted into {@link EditorView.overlayContainer} so it shares\n * the selection/caret coordinate space and scrolls with the document. When the\n * editor's natural right margin is too narrow for the rail, the view reserves\n * proportional space by padding the editor on the right — but only while there\n * are comments.\n */\nexport class CommentsView extends Disposable {\n\tprivate readonly _layer: SVGSVGElement;\n\tprivate readonly _entries = new Map<string, CommentEntry>();\n\n\tconstructor(\n\t\tprivate readonly _model: CommentsModel,\n\t\tprivate readonly _view: EditorView,\n\t) {\n\t\tsuper();\n\n\t\tthis._layer = this._createLayer('md-comment-shapes');\n\t\tthis._view.overlayContainer.appendChild(this._layer);\n\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tthis._layer.remove();\n\t\t\t\tfor (const entry of this._entries.values()) { this._disposeEntry(entry); }\n\t\t\t\tthis._entries.clear();\n\t\t\t\tthis._view.element.style.paddingRight = '';\n\t\t\t},\n\t\t});\n\n\t\tthis._register(autorun(reader => this._update(reader)));\n\t}\n\n\tprivate _createLayer(className: string): SVGSVGElement {\n\t\tconst svg = document.createElementNS(SVG_NS, 'svg');\n\t\tsvg.setAttribute('class', className);\n\t\treturn svg;\n\t}\n\n\tprivate _update(reader: IReader): void {\n\t\tconst comments = this._model.comments.read(reader);\n\t\tconst hoveredId = this._model.hoveredId.read(reader);\n\n\t\tthis._reconcile(comments);\n\n\t\t// Read every comment's rects so the autorun re-runs when the layout\n\t\t// changes (e.g. reflow, resize).\n\t\tconst items = comments.map(comment => {\n\t\t\tconst entry = this._entries.get(comment.id)!;\n\t\t\treturn { entry, rects: entry.rects.read(reader) };\n\t\t});\n\n\t\tthis._layout(items);\n\t\tthis._applyHover(hoveredId);\n\t}\n\n\t/** Create/update/remove per-comment DOM to match `comments`. */\n\tprivate _reconcile(comments: readonly Comment[]): void {\n\t\tconst seen = new Set<string>();\n\t\tfor (const comment of comments) {\n\t\t\tseen.add(comment.id);\n\t\t\tconst existing = this._entries.get(comment.id);\n\t\t\tif (!existing) {\n\t\t\t\tthis._entries.set(comment.id, this._createEntry(comment));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Re-anchor if the range changed; refresh content always.\n\t\t\tif (existing.comment.range !== comment.range) {\n\t\t\t\texisting.rects = this._view.rangeRects(comment.range);\n\t\t\t}\n\t\t\texisting.comment = comment;\n\t\t\tthis._fillCard(existing);\n\t\t}\n\t\tfor (const [id, entry] of this._entries) {\n\t\t\tif (!seen.has(id)) {\n\t\t\t\tthis._disposeEntry(entry);\n\t\t\t\tthis._entries.delete(id);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _createEntry(comment: Comment): CommentEntry {\n\t\t// Highlight fill and leader stroke live in one opacity group and share a\n\t\t// solid color, so their overlap never darkens and the seam is invisible.\n\t\t// The leader is drawn first (under the fill) so its overlap is hidden.\n\t\tconst group = document.createElementNS(SVG_NS, 'g');\n\t\tgroup.setAttribute('class', 'md-comment-group');\n\t\tthis._layer.appendChild(group);\n\n\t\tconst leaderPath = document.createElementNS(SVG_NS, 'path');\n\t\tleaderPath.setAttribute('class', 'md-comment-leader-path');\n\t\tgroup.appendChild(leaderPath);\n\n\t\tconst shapePath = document.createElementNS(SVG_NS, 'path');\n\t\tshapePath.setAttribute('class', 'md-comment-shape-path');\n\t\tgroup.appendChild(shapePath);\n\n\t\tconst card = document.createElement('div');\n\t\tcard.className = 'md-comment-card';\n\n\t\tconst header = document.createElement('div');\n\t\theader.className = 'md-comment-card-header';\n\t\tconst avatarEl = document.createElement('span');\n\t\tavatarEl.className = 'md-comment-avatar';\n\t\tconst authorEl = document.createElement('span');\n\t\tauthorEl.className = 'md-comment-author';\n\t\tconst timeEl = document.createElement('span');\n\t\ttimeEl.className = 'md-comment-time';\n\t\tconst menuEl = document.createElement('span');\n\t\tmenuEl.className = 'md-comment-menu';\n\t\tmenuEl.textContent = '\\u22EF'; // ⋯\n\t\theader.append(avatarEl, authorEl, timeEl, menuEl);\n\n\t\tconst bodyEl = document.createElement('div');\n\t\tbodyEl.className = 'md-comment-body';\n\n\t\tconst reply = document.createElement('button');\n\t\treply.type = 'button';\n\t\treply.className = 'md-comment-reply';\n\t\treply.textContent = 'Reply';\n\n\t\tcard.append(header, bodyEl, reply);\n\t\tthis._view.overlayContainer.appendChild(card);\n\n\t\tconst entry: CommentEntry = {\n\t\t\tcomment,\n\t\t\trects: this._view.rangeRects(comment.range),\n\t\t\tgroup, shapePath, leaderPath,\n\t\t\tcard, bodyEl, authorEl, avatarEl, timeEl,\n\t\t\tdisposables: [],\n\t\t};\n\n\t\tconst setHover = (on: boolean): void => this._model.hoveredId.set(on ? comment.id : undefined, undefined);\n\t\tconst enter = (): void => setHover(true);\n\t\tconst leave = (): void => setHover(false);\n\t\t// Hover is driven from the card only; the highlight layer stays\n\t\t// non-interactive so it never blocks selecting the underlying text.\n\t\tcard.addEventListener('mouseenter', enter);\n\t\tcard.addEventListener('mouseleave', leave);\n\t\tentry.disposables.push({\n\t\t\tdispose: () => {\n\t\t\t\tcard.removeEventListener('mouseenter', enter);\n\t\t\t\tcard.removeEventListener('mouseleave', leave);\n\t\t\t},\n\t\t});\n\n\t\tthis._fillCard(entry);\n\t\treturn entry;\n\t}\n\n\tprivate _fillCard(entry: CommentEntry): void {\n\t\tconst { comment } = entry;\n\t\tconst author = comment.author ?? 'You';\n\t\tentry.authorEl.textContent = author;\n\t\tentry.avatarEl.textContent = _initials(author);\n\t\tentry.timeEl.textContent = comment.createdAt !== undefined ? _relativeTime(comment.createdAt) : '';\n\t\tentry.bodyEl.textContent = comment.body;\n\t}\n\n\tprivate _disposeEntry(entry: CommentEntry): void {\n\t\tfor (const d of entry.disposables) { d.dispose(); }\n\t\tentry.group.remove();\n\t\tentry.card.remove();\n\t}\n\n\t/** Position highlights, cards (stacked) and leader lines. */\n\tprivate _layout(items: readonly { entry: CommentEntry; rects: readonly SelectionRect[] }[]): void {\n\t\tconst root = this._view.element;\n\t\tconst overlay = this._view.overlayContainer;\n\n\t\tif (items.length === 0) {\n\t\t\troot.style.paddingRight = '';\n\t\t\tthis._layer.style.display = 'none';\n\t\t\treturn;\n\t\t}\n\t\tthis._layer.style.display = '';\n\n\t\t// --- Reserve rail space (only when comments exist). Compute the target\n\t\t// right padding analytically from stable inputs, so it is idempotent and\n\t\t// does not thrash the layout: the editor's border-box width doesn't change\n\t\t// with padding, and the content column is centered (margin-inline:auto)\n\t\t// with a known max-width. We deliberately avoid the old \"clear padding →\n\t\t// measure → re-apply\" dance: now that the editor re-measures on reflow,\n\t\t// toggling padding to measure would oscillate.\n\t\tconst rootRect = root.getBoundingClientRect();\n\t\tconst rootWidth = rootRect.width;\n\t\tconst cs = getComputedStyle(overlay);\n\t\tconst maxW = parseFloat(cs.maxWidth);\n\t\tconst padX = (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight) || 0);\n\t\tconst borderX = (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth) || 0);\n\t\t// Full outer width of the content column at its max-width (accounting for\n\t\t// box-sizing). `NaN` max-width (limited mode off) → content spans the root.\n\t\tconst contentMaxOuter = Number.isNaN(maxW)\n\t\t\t? rootWidth\n\t\t\t: (cs.boxSizing === 'border-box' ? maxW : maxW + padX + borderX);\n\t\t// The natural right margin when no rail padding is applied (content centered).\n\t\tconst naturalRight = Math.max(0, (rootWidth - Math.min(contentMaxOuter, rootWidth)) / 2);\n\n\t\tconst railWidth = Math.round(Math.max(RAIL_MIN, Math.min(RAIL_MAX, rootWidth * RAIL_FRACTION)));\n\t\tconst need = railWidth + RAIL_GAP + RAIL_EDGE;\n\t\t// While the content still has margins, padding re-centers it, so only half\n\t\t// of each added pixel becomes right margin — reserve twice the shortfall.\n\t\t// But cap at `need`: once the content fills the padding box (no margins),\n\t\t// every added pixel becomes right gap, so `need` is all that's required.\n\t\t// The old code used the uncapped `2 × shortfall`, which in narrow viewports\n\t\t// massively over-reserved and collapsed the content column.\n\t\tconst pad = naturalRight >= need ? 0 : Math.min(2 * (need - naturalRight), need);\n\t\tconst padStr = pad > 0 ? `${Math.ceil(pad)}px` : '';\n\t\tif (root.style.paddingRight !== padStr) {\n\t\t\troot.style.paddingRight = padStr;\n\t\t}\n\n\t\t// Re-measure after reservation (the root's right edge is stable; only the\n\t\t// content shifts), then express the rail in overlay-local coordinates.\n\t\tconst overlayRect = overlay.getBoundingClientRect();\n\t\tconst railLeftLocal = (rootRect.right - RAIL_EDGE - railWidth) - overlayRect.left;\n\t\t// Right edge of the content box (overlay-local): the leader runs straight to\n\t\t// here (so it never crosses text) and only curves beyond it, in the margin.\n\t\tconst contentRightLocal = overlay.clientWidth;\n\n\t\t// Desired vertical anchors.\n\t\tconst placed = items.map(({ entry, rects }) => {\n\t\t\tentry.card.style.left = `${railLeftLocal}px`;\n\t\t\tentry.card.style.width = `${railWidth}px`;\n\t\t\tconst anchor = _lineStart(rects);\n\t\t\tconst desiredTop = rects.length > 0 ? Math.min(...rects.map(r => r.y)) : 0;\n\t\t\treturn { entry, rects, anchor, desiredTop };\n\t\t});\n\n\t\t// Stack: sort by desired top, push each down so they never overlap.\n\t\tplaced.sort((a, b) => a.desiredTop - b.desiredTop);\n\t\tlet prevBottom = -Infinity;\n\t\tfor (const p of placed) {\n\t\t\tconst top = Math.max(p.desiredTop, prevBottom + CARD_GAP);\n\t\t\tp.entry.card.style.top = `${top}px`;\n\t\t\tconst height = p.entry.card.offsetHeight;\n\t\t\tprevBottom = top + height;\n\n\t\t\t// The highlight is a filled shape painted exactly like a normal\n\t\t\t// selection (same rects, same rounded corners). The leader is a\n\t\t\t// same-colored stroke drawn *under* the fill, starting inside the\n\t\t\t// highlight (its seam hidden by the fill) with its bottom edge on the\n\t\t\t// selection bottom; it runs straight through the content, then curves\n\t\t\t// to the card in the margin.\n\t\t\tp.entry.shapePath.setAttribute('d', buildConnectedPath(p.rects, HIGHLIGHT_RADIUS));\n\t\t\tp.entry.leaderPath.setAttribute('d', p.anchor\n\t\t\t\t? _leaderLine(p.anchor, contentRightLocal, { x: railLeftLocal, y: top + LEADER_CARD_INSET })\n\t\t\t\t: '');\n\t\t}\n\t}\n\n\tprivate _applyHover(hoveredId: string | undefined): void {\n\t\tfor (const [id, entry] of this._entries) {\n\t\t\tconst hovered = id === hoveredId;\n\t\t\tentry.card.classList.toggle('md-comment-card-hovered', hovered);\n\t\t\tentry.group.classList.toggle('md-comment-group-hovered', hovered);\n\t\t}\n\t}\n}\n\n/** Where the leader leaves the highlight: a few px inside the squared bottom-right\n * corner, with the y centered on the stroke so the stroke's bottom edge sits\n * exactly on the selection's bottom edge. The x starts inside the highlight by\n * {@link LEADER_OVERLAP} so the seam is hidden under the (same-colored) fill. */\nfunction _lineStart(rects: readonly SelectionRect[]): { x: number; y: number } | undefined {\n\tif (rects.length === 0) { return undefined; }\n\tlet best = rects[0];\n\tfor (const r of rects) {\n\t\tif (r.y + r.height > best.y + best.height) { best = r; }\n\t}\n\tconst rightEdge = best.x + best.width;\n\tconst x = Math.max(best.x, rightEdge - LEADER_OVERLAP);\n\treturn { x, y: best.y + best.height - LEADER_WIDTH / 2 };\n}\n\n/**\n * Leader centerline (stroked): starts horizontal along the selection bottom from\n * `start` to `bendX` (content right edge) so it never crosses text and leaves\n * the highlight tangentially, then a smooth cubic in the margin to `to` (the\n * card). The straight→curve join is tangent-continuous, so the whole line is\n * smooth.\n */\nfunction _leaderLine(start: { x: number; y: number }, bendX: number, to: { x: number; y: number }): string {\n\tconst bend = Math.max(bendX, start.x + 12);\n\tconst dx = to.x - bend;\n\tconst c1x = bend + dx * 0.55;\n\tconst c2x = to.x - dx * 0.45;\n\treturn `M ${start.x} ${start.y} L ${bend} ${start.y} C ${c1x} ${start.y}, ${c2x} ${to.y}, ${to.x} ${to.y}`;\n}\n\nfunction _initials(name: string): string {\n\tconst parts = name.trim().split(/\\s+/).filter(Boolean);\n\tif (parts.length === 0) { return '?'; }\n\tconst first = parts[0][0] ?? '';\n\tconst second = parts.length > 1 ? parts[parts.length - 1][0] ?? '' : '';\n\treturn (first + second).toUpperCase();\n}\n\nfunction _relativeTime(epochMs: number): string {\n\tconst deltaSec = Math.max(0, Math.round((Date.now() - epochMs) / 1000));\n\tif (deltaSec < 60) { return 'just now'; }\n\tconst min = Math.round(deltaSec / 60);\n\tif (min < 60) { return `${min}m ago`; }\n\tconst hours = Math.round(min / 60);\n\tif (hours < 24) { return `${hours}h ago`; }\n\tconst days = Math.round(hours / 24);\n\treturn `${days}d ago`;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Shared geometry for the \"stacked card\" comment presenters (the VS Code V1 and\n// V2 designs). Each comment gets one fixed-width card anchored to the editor's\n// right edge, and cards are stacked so they never overlap one another (they may\n// overlap the text, like an overlay widget). Extracted so both adapters share\n// one implementation.\n//\n\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\n\n/** A card to place: its DOM element and the rects of its anchored source range. */\nexport interface StackItem {\n readonly element: HTMLElement;\n readonly rects: readonly SelectionRect[];\n}\n\n/** Vertical gap between stacked cards. */\nexport const RAIL_GAP = 12;\n/** Inset of each card's right edge from the editor's right edge. */\nexport const RIGHT_INSET = 8;\n\n/**\n * Right-align and vertically stack `items`. The overlay layer lives inside the\n * centered, max-width content box, so the editor-relative right edge is\n * converted to overlay-local coordinates via `offsetLeft`. Pure DOM writes over\n * already-resolved rects, so the caller decides when to run it (an autorun for\n * comment/reflow changes, a ResizeObserver for width changes).\n *\n * Cards whose range has not been measured yet (no rects) are hidden rather than\n * parked at the top-left, so there is no flash before the editor's first\n * measurement anchors them.\n */\nexport function layoutRightAlignedStack(view: EditorView, items: readonly StackItem[]): void {\n const el = view.element;\n const overlay = view.overlayContainer;\n const rightEdge = (el.clientWidth - RIGHT_INSET) - overlay.offsetLeft;\n\n const placed: { element: HTMLElement; y: number }[] = [];\n for (const item of items) {\n if (item.rects.length === 0) {\n // Not measured yet — hide (keeps layout box, so offsetWidth stays\n // valid) until a re-run has real geometry to anchor to.\n item.element.style.visibility = 'hidden';\n continue;\n }\n item.element.style.visibility = '';\n placed.push({ element: item.element, y: Math.min(...item.rects.map(r => r.y)) });\n }\n\n placed.sort((a, b) => a.y - b.y);\n\n let prevBottom = -Infinity;\n for (const p of placed) {\n const top = Math.max(p.y, prevBottom + RAIL_GAP);\n const left = rightEdge - p.element.offsetWidth;\n p.element.style.left = `${left}px`;\n p.element.style.top = `${top}px`;\n prevBottom = top + p.element.offsetHeight;\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Shared base for the \"stacked card\" comment presenters (VS Code V1 and V2).\n// Owns the token-wrapped overlay layer, reconciles one card per comment against\n// the model, and keeps them right-aligned + stacked. Subclasses only say how to\n// build a card from a Comment.\n//\n// Two triggers drive the layout, because the geometry has two independent\n// inputs: the autorun re-runs when comments or their rects change (edits,\n// reflow), and a ResizeObserver re-runs when the editor resizes (width /\n// centering changes that don't touch the rects). Without the observer the\n// horizontal position would go stale on resize.\n//\n\nimport { Disposable, autorun, type IObservable } from '@vscode/observables';\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport type { Comment, CommentsModel } from '../comments/commentsModel.js';\nimport type { ICommentsPresenter, CommentsPresenterContext } from '../comments/commentsPresenter.js';\nimport { layoutRightAlignedStack, type StackItem } from './stackedRailLayout.js';\n\n/** The minimal widget contract a subclass must produce. */\nexport interface StackWidget {\n readonly element: HTMLElement;\n dispose(): void;\n}\n\ninterface Entry {\n readonly widget: StackWidget;\n readonly rects: IObservable<readonly SelectionRect[]>;\n}\n\nexport abstract class StackedCommentsPresenter extends Disposable implements ICommentsPresenter {\n private readonly _layer: HTMLElement;\n private readonly _entries = new Map<string, Entry>();\n private _order: readonly string[] = [];\n\n // Public so subclasses inherit a public constructor (the class is abstract,\n // so it still cannot be instantiated directly).\n constructor(\n protected readonly model: CommentsModel,\n protected readonly view: EditorView,\n protected readonly context?: CommentsPresenterContext,\n ) {\n super();\n // Token-wrapped overlay layer (supplies the `--vscode-*` theme variables\n // the card CSS consumes) that scrolls with the content and lets cards\n // overlap the text.\n this._layer = document.createElement('div');\n this._layer.className = context?.theme === 'light' ? 'vscode-comments-light' : 'vscode-comments-dark';\n this._layer.style.position = 'absolute';\n this._layer.style.inset = '0';\n this._layer.style.pointerEvents = 'none';\n this._layer.style.overflow = 'visible';\n // The `.vscode-comments-*` token wrapper paints `--vscode-editor-background`;\n // override it so this overlay never covers the editor content behind it.\n this._layer.style.background = 'transparent';\n this.view.overlayContainer.appendChild(this._layer);\n\n this._register({\n dispose: () => {\n for (const e of this._entries.values()) { e.widget.dispose(); }\n this._entries.clear();\n this._layer.remove();\n },\n });\n\n this._register(autorun(reader => {\n const comments = this.model.comments.read(reader);\n this._reconcile(comments);\n // Subscribe to each range's rects so reflow re-runs the layout.\n for (const c of comments) { this._entries.get(c.id)!.rects.read(reader); }\n this._relayout();\n }));\n\n // Editor width / centering changes don't touch the rects, so re-run the\n // (horizontal) layout when the element resizes too.\n const resizeObserver = new ResizeObserver(() => this._relayout());\n resizeObserver.observe(this.view.element);\n this._register({ dispose: () => resizeObserver.disconnect() });\n }\n\n /** Build the card DOM for a comment. Called once per new comment. */\n protected abstract createWidget(comment: Comment): StackWidget;\n\n private _reconcile(comments: readonly Comment[]): void {\n this._order = comments.map(c => c.id);\n const seen = new Set(this._order);\n for (const comment of comments) {\n if (this._entries.has(comment.id)) { continue; }\n const widget = this.createWidget(comment);\n // Absolutely positioned so layoutRightAlignedStack's left/top apply\n // (not every widget sets this in its own CSS, e.g. the V2 card).\n widget.element.style.position = 'absolute';\n widget.element.style.pointerEvents = 'auto';\n this._layer.appendChild(widget.element);\n this._entries.set(comment.id, { widget, rects: this.view.rangeRects(comment.range) });\n }\n for (const [id, entry] of this._entries) {\n if (!seen.has(id)) {\n entry.widget.dispose();\n this._entries.delete(id);\n }\n }\n }\n\n private _relayout(): void {\n const items: StackItem[] = this._order\n .map(id => this._entries.get(id))\n .filter((e): e is Entry => e !== undefined)\n .map(e => ({ element: e.widget.element, rects: e.rects.get() }));\n layoutRightAlignedStack(this.view, items);\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Pixel-for-pixel replica of VS Code's agent-feedback editor widget\n// (src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts,\n// class AgentFeedbackEditorWidget). It builds the EXACT same DOM tree and reuses\n// the verbatim CSS (vscodeCommentWidget.css) so we can compare our own comment\n// rendering against VS Code's. It has NO Monaco / workbench-service dependency:\n// the comment body is rendered with a tiny markdown shim and codicons are drawn\n// via unicode placeholders (see vscodeCommentTokens.css).\n//\n\nexport type VscodeCommentSource = 'agentFeedback' | 'prReview';\n\n/** Mirrors AgentFeedbackKind; drives the type badge (see {@link _typeLabel}). */\nexport type VscodeCommentKind = 'userReview' | 'prReview' | 'agentReview';\n\nexport interface VscodeCommentSuggestionEdit {\n readonly startLine: number;\n readonly endLine?: number;\n readonly newText: string;\n}\n\nexport interface VscodeComment {\n readonly id: string;\n readonly source: VscodeCommentSource;\n readonly kind: VscodeCommentKind;\n readonly startLine: number;\n readonly endLine?: number;\n readonly text: string;\n readonly suggestion?: { readonly edits: readonly VscodeCommentSuggestionEdit[] };\n readonly replies?: readonly string[];\n}\n\nexport interface VscodeCommentWidgetOptions {\n readonly expanded?: boolean;\n readonly focusedCommentId?: string;\n}\n\n/** Per-item action affordances, mirroring VS Code's `ICommentItemActions`. */\ninterface ItemActions {\n edit: HTMLAnchorElement;\n remove: HTMLAnchorElement;\n addReply: HTMLAnchorElement;\n setEnabled(enabled: boolean): void;\n}\n\nconst DOM_HELPER_TAG = /^([a-z0-9]+)/i;\n\n/** VS Code's `dom.$('tag.a.b')` shorthand, reduced to what we use. */\nfunction $(selector: string): HTMLElement {\n const tag = DOM_HELPER_TAG.exec(selector)?.[1] ?? 'div';\n const el = document.createElement(tag);\n const classes = selector.slice(tag.length).split('.').filter(Boolean);\n if (classes.length) {\n el.className = classes.join(' ');\n }\n return el;\n}\n\n/**\n * Inline Feather-style icons (stroke=\"currentColor\"), matching the crisp look of\n * the editor's read-only lock toggle — far nicer than a unicode/font glyph. The\n * DOM keeps the real `codicon codicon-<name>` classes; the SVG is the glyph.\n */\nfunction feather(inner: string): string {\n return `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nconst ICON_SVGS: Record<string, string> = {\n 'comment': feather('<path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>'),\n 'comment-discussion': feather('<path d=\"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z\"></path>'),\n 'chevron-down': feather('<polyline points=\"6 9 12 15 18 9\"></polyline>'),\n 'chevron-up': feather('<polyline points=\"18 15 12 9 6 15\"></polyline>'),\n 'edit': feather('<path d=\"M12 20h9\"></path><path d=\"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z\"></path>'),\n 'close': feather('<line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>'),\n};\n\n/** A codicon span carrying the inline Feather SVG for `name`. */\nfunction icon(name: string): HTMLElement {\n const span = $(`span.codicon.codicon-${name}`);\n span.setAttribute('aria-hidden', 'true');\n span.innerHTML = ICON_SVGS[name] ?? '';\n return span;\n}\n\n/**\n * Minimal markdown shim producing the same `.rendered-markdown > p` shape VS\n * Code's MarkdownRenderer emits for these single-paragraph comments, with inline\n * `` `code` `` support.\n */\nfunction renderMarkdown(text: string): HTMLElement {\n const wrap = $('div.rendered-markdown');\n const p = document.createElement('p');\n for (const part of text.split(/(`[^`]+`)/g)) {\n if (/^`[^`]+`$/.test(part)) {\n const code = document.createElement('code');\n code.textContent = part.slice(1, -1);\n p.appendChild(code);\n } else if (part) {\n p.appendChild(document.createTextNode(part));\n }\n }\n wrap.appendChild(p);\n return wrap;\n}\n\nexport class VscodeCommentWidget {\n private readonly _domNode: HTMLElement;\n private readonly _headerNode: HTMLElement;\n private readonly _titleNode: HTMLElement;\n private readonly _toggleButton: HTMLElement;\n private readonly _bodyNode: HTMLElement;\n\n private _isExpanded = false;\n private _focusedId: string | undefined;\n private readonly _itemElements = new Map<string, HTMLElement>();\n private readonly _disposables: (() => void)[] = [];\n\n get element(): HTMLElement { return this._domNode; }\n\n constructor(\n private readonly _comments: readonly VscodeComment[],\n options?: VscodeCommentWidgetOptions,\n ) {\n // Root — starts collapsed (matches production).\n this._domNode = $('div.agent-feedback-widget');\n this._domNode.classList.add('collapsed');\n this._domNode.tabIndex = -1;\n this._domNode.setAttribute('widgetid', 'agent-feedback-widget-0');\n\n // Header: comment icon + title + spacer + toggle.\n this._headerNode = $('div.agent-feedback-widget-header');\n this._headerNode.appendChild(icon('comment'));\n\n this._titleNode = $('span.agent-feedback-widget-title');\n this._updateTitle();\n this._headerNode.appendChild(this._titleNode);\n\n this._headerNode.appendChild($('span.agent-feedback-widget-spacer'));\n\n this._toggleButton = $('div.agent-feedback-widget-toggle');\n this._updateToggleButton();\n this._headerNode.appendChild(this._toggleButton);\n\n this._domNode.appendChild(this._headerNode);\n\n // Body (collapsible) — starts collapsed.\n this._bodyNode = $('div.agent-feedback-widget-body');\n this._bodyNode.classList.add('collapsed');\n this._buildFeedbackItems();\n this._domNode.appendChild(this._bodyNode);\n\n // Arrow pointer.\n this._domNode.appendChild($('div.agent-feedback-widget-arrow'));\n\n this._setupEventHandlers();\n\n this._domNode.classList.add('visible');\n\n if (options?.expanded) { this.expand(); }\n if (options?.focusedCommentId) { this.focusFeedback(options.focusedCommentId); }\n }\n\n // --- Header ----------------------------------------------------------\n\n private _updateTitle(): void {\n const count = this._comments.length;\n this._titleNode.textContent = count === 1 ? this._comments[0].text : `${count} comments`;\n }\n\n private _updateToggleButton(): void {\n this._toggleButton.textContent = '';\n if (this._isExpanded) {\n this._toggleButton.appendChild(icon('chevron-up'));\n this._toggleButton.title = 'Collapse';\n } else {\n this._toggleButton.appendChild(icon('chevron-down'));\n this._toggleButton.title = 'Expand';\n }\n }\n\n private _setupEventHandlers(): void {\n this._listen(this._toggleButton, 'click', e => { e.stopPropagation(); this._toggleExpanded(); });\n this._listen(this._headerNode, 'click', () => this._toggleExpanded());\n }\n\n private _toggleExpanded(): void {\n if (this._isExpanded) { this.collapse(); } else { this.expand(); }\n }\n\n // --- Items -----------------------------------------------------------\n\n private _buildFeedbackItems(): void {\n this._bodyNode.textContent = '';\n this._itemElements.clear();\n\n for (const comment of this._comments) {\n const item = $('div.agent-feedback-widget-item');\n item.classList.add(`agent-feedback-widget-item-${comment.source}`);\n if (comment.suggestion) {\n item.classList.add('agent-feedback-widget-item-suggestion');\n }\n this._itemElements.set(comment.id, item);\n\n // Header: meta (line-info + optional type badge) + hover actions.\n const itemHeader = $('div.agent-feedback-widget-item-header');\n const itemMeta = $('div.agent-feedback-widget-item-meta');\n\n const lineInfo = $('span.agent-feedback-widget-line-info');\n lineInfo.textContent = this._lineLabel(comment.startLine, comment.endLine);\n itemMeta.appendChild(lineInfo);\n\n const typeLabel = this._typeLabel(comment.kind);\n if (typeLabel) {\n const badge = $('span.agent-feedback-widget-item-type');\n badge.textContent = typeLabel;\n itemMeta.appendChild(badge);\n }\n itemHeader.appendChild(itemMeta);\n\n const text = $('div.agent-feedback-widget-text');\n const actions = this._buildItemActions(comment, item, text);\n itemHeader.appendChild(actions.container);\n item.appendChild(itemHeader);\n\n // Body text.\n text.appendChild(renderMarkdown(comment.text));\n item.appendChild(text);\n\n if (comment.suggestion?.edits.length) {\n item.appendChild(this._renderSuggestion(comment));\n }\n if (comment.replies?.length) {\n item.appendChild(this._renderReplies(comment.replies));\n }\n\n // Click navigates/focuses (ignoring action bar, reply input and text\n // selections) — mirrors production.\n this._listen(item, 'click', e => {\n const target = e.target as HTMLElement | null;\n if (target?.closest('.monaco-action-bar') || target?.closest('.agent-feedback-widget-add-reply')) {\n return;\n }\n if (target?.closest('.agent-feedback-widget-text, .agent-feedback-widget-suggestion-text, .agent-feedback-widget-reply-text')) {\n const selection = this._domNode.ownerDocument.defaultView?.getSelection();\n if (selection && !selection.isCollapsed && this._domNode.contains(selection.anchorNode)) {\n return;\n }\n }\n this.focusFeedback(comment.id);\n });\n\n this._bodyNode.appendChild(item);\n }\n }\n\n private _buildItemActions(comment: VscodeComment, item: HTMLElement, text: HTMLElement): { container: HTMLElement; actions: ItemActions } {\n const container = $('div.agent-feedback-widget-item-actions');\n const bar = $('div.monaco-action-bar');\n const list = $('ul.actions-container');\n list.setAttribute('role', 'toolbar');\n\n const addReply = this._actionLabel('comment-discussion', 'Add to Comment');\n const edit = this._actionLabel('edit', 'Edit');\n const remove = this._actionLabel('close', 'Remove');\n\n const actions: ItemActions = {\n addReply, edit, remove,\n setEnabled: (enabled: boolean) => {\n for (const a of [addReply, edit, remove]) {\n a.classList.toggle('disabled', !enabled);\n a.tabIndex = enabled ? 0 : -1;\n }\n },\n };\n\n this._listen(addReply, 'click', e => { e.stopPropagation(); this._startAddingReply(comment, item, actions); });\n this._listen(edit, 'click', e => { e.stopPropagation(); this._startEditing(comment, text, actions); });\n this._listen(remove, 'click', e => { e.stopPropagation(); this._removeItem(comment.id); });\n\n for (const a of [addReply, edit, remove]) {\n const li = $('li.action-item');\n li.appendChild(a);\n list.appendChild(li);\n }\n bar.appendChild(list);\n container.appendChild(bar);\n return { container, actions };\n }\n\n private _actionLabel(codicon: string, ariaLabel: string): HTMLAnchorElement {\n const a = document.createElement('a');\n a.className = `action-label codicon codicon-${codicon}`;\n a.setAttribute('role', 'button');\n a.setAttribute('aria-label', ariaLabel);\n a.title = ariaLabel;\n a.tabIndex = 0;\n a.innerHTML = ICON_SVGS[codicon] ?? '';\n return a;\n }\n\n private _lineLabel(startLine: number, endLine?: number): string {\n return (endLine === undefined || endLine === startLine)\n ? `Line ${startLine}`\n : `Lines ${startLine}-${endLine}`;\n }\n\n private _typeLabel(kind: VscodeCommentKind): string | undefined {\n switch (kind) {\n case 'prReview': return 'PR Review';\n case 'agentReview': return 'Agent Review';\n default: return undefined;\n }\n }\n\n private _renderSuggestion(comment: VscodeComment): HTMLElement {\n const suggestionNode = $('div.agent-feedback-widget-suggestion');\n for (const edit of comment.suggestion?.edits ?? []) {\n const editNode = $('div.agent-feedback-widget-suggestion-edit');\n const header = $('div.agent-feedback-widget-suggestion-header');\n const end = edit.endLine ?? edit.startLine;\n header.textContent = end === edit.startLine\n ? `Suggested Change \\u2022 Line ${edit.startLine}`\n : `Suggested Change \\u2022 Lines ${edit.startLine}-${end}`;\n editNode.appendChild(header);\n\n const pre = $('pre.agent-feedback-widget-suggestion-text');\n pre.textContent = edit.newText;\n editNode.appendChild(pre);\n suggestionNode.appendChild(editNode);\n }\n return suggestionNode;\n }\n\n private _renderReplies(replies: readonly string[]): HTMLElement {\n const repliesNode = $('div.agent-feedback-widget-replies');\n for (const reply of replies) {\n const replyNode = $('div.agent-feedback-widget-reply');\n const replyText = $('div.agent-feedback-widget-reply-text');\n replyText.appendChild(renderMarkdown(reply));\n replyNode.appendChild(replyText);\n repliesNode.appendChild(replyNode);\n }\n return repliesNode;\n }\n\n // --- Interactive behaviour ------------------------------------------\n\n private _startEditing(comment: VscodeComment, textContainer: HTMLElement, actions: ItemActions): void {\n actions.setEnabled(false);\n const previous = Array.from(textContainer.childNodes);\n textContainer.textContent = '';\n textContainer.classList.add('editing');\n\n const textarea = document.createElement('textarea');\n textarea.className = 'agent-feedback-widget-edit-textarea';\n textarea.value = comment.text;\n textarea.rows = 1;\n textContainer.appendChild(textarea);\n\n const autoSize = (): void => {\n textarea.style.height = 'auto';\n if (textarea.scrollHeight > 0) { textarea.style.height = `${textarea.scrollHeight}px`; }\n };\n autoSize();\n\n const restore = (): void => {\n textContainer.classList.remove('editing');\n textContainer.textContent = '';\n for (const n of previous) { textContainer.appendChild(n); }\n actions.setEnabled(true);\n };\n\n this._listen(textarea, 'input', autoSize);\n this._listen(textarea, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n const newText = textarea.value.trim();\n textContainer.classList.remove('editing');\n textContainer.textContent = '';\n textContainer.appendChild(renderMarkdown(newText || comment.text));\n actions.setEnabled(true);\n } else if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n restore();\n }\n });\n this._listen(textarea, 'blur', restore);\n textarea.focus();\n }\n\n private _startAddingReply(comment: VscodeComment, item: HTMLElement, actions: ItemActions): void {\n if (item.querySelector('.agent-feedback-widget-add-reply')) {\n (item.querySelector('.agent-feedback-widget-edit-textarea') as HTMLTextAreaElement | null)?.focus();\n return;\n }\n actions.setEnabled(false);\n\n const replyContainer = $('div.agent-feedback-widget-add-reply');\n const textarea = document.createElement('textarea');\n textarea.className = 'agent-feedback-widget-edit-textarea';\n textarea.placeholder = 'Add a comment\\u2026';\n textarea.rows = 1;\n replyContainer.appendChild(textarea);\n item.appendChild(replyContainer);\n\n const autoSize = (): void => {\n textarea.style.height = 'auto';\n if (textarea.scrollHeight > 0) { textarea.style.height = `${textarea.scrollHeight}px`; }\n };\n autoSize();\n\n const close = (): void => {\n replyContainer.remove();\n actions.setEnabled(true);\n };\n\n this._listen(textarea, 'input', autoSize);\n this._listen(textarea, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n const value = textarea.value.trim();\n if (value) {\n let repliesNode = item.querySelector('.agent-feedback-widget-replies');\n if (!repliesNode) {\n repliesNode = this._renderReplies([]);\n item.insertBefore(repliesNode, replyContainer);\n }\n const replyNode = $('div.agent-feedback-widget-reply');\n const replyText = $('div.agent-feedback-widget-reply-text');\n replyText.appendChild(renderMarkdown(value));\n replyNode.appendChild(replyText);\n repliesNode.appendChild(replyNode);\n }\n close();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n close();\n }\n });\n this._listen(textarea, 'blur', close);\n textarea.focus();\n }\n\n private _removeItem(id: string): void {\n const item = this._itemElements.get(id);\n item?.remove();\n this._itemElements.delete(id);\n }\n\n // --- Public API ------------------------------------------------------\n\n expand(): void {\n this._isExpanded = true;\n this._domNode.classList.remove('collapsed');\n this._bodyNode.classList.remove('collapsed');\n this._updateToggleButton();\n }\n\n collapse(): void {\n this._isExpanded = false;\n this._domNode.classList.add('collapsed');\n this._bodyNode.classList.add('collapsed');\n this._updateToggleButton();\n }\n\n toggle(visible: boolean): void {\n this._domNode.classList.toggle('visible', visible);\n }\n\n /** Marks a single comment item as focused (VS Code's active-selection style). */\n focusFeedback(id: string): void {\n if (this._focusedId) {\n this._itemElements.get(this._focusedId)?.classList.remove('focused');\n }\n this._focusedId = id;\n this._itemElements.get(id)?.classList.add('focused');\n }\n\n private _listen<K extends keyof HTMLElementEventMap>(target: HTMLElement, type: K, handler: (e: HTMLElementEventMap[K]) => void): void {\n target.addEventListener(type, handler as EventListener);\n this._disposables.push(() => target.removeEventListener(type, handler as EventListener));\n }\n\n dispose(): void {\n for (const d of this._disposables) { d(); }\n this._disposables.length = 0;\n this._domNode.remove();\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Presenter that renders each comment from a CommentsModel as a VS Code\n// agent-feedback card (the \"comments-vscode\" design), reusing the real\n// VscodeCommentWidget. Maps the rendering-agnostic Comment onto a VscodeComment;\n// the base class handles anchoring, stacking and lifecycle.\n//\n\nimport type { Comment } from '../comments/commentsModel.js';\nimport { StackedCommentsPresenter, type StackWidget } from './stackedCommentsPresenter.js';\nimport { VscodeCommentWidget, type VscodeComment } from './vscodeCommentWidget.js';\nimport './vscodeCommentTokens.css';\nimport './vscodeCommentWidget.css';\n\nexport class VscodeStackedCommentsView extends StackedCommentsPresenter {\n protected createWidget(comment: Comment): StackWidget {\n const startLine = this.context?.resolveLine?.(comment.range.start) ?? 1;\n const vscodeComment: VscodeComment = {\n id: comment.id,\n source: 'prReview',\n kind: 'prReview',\n startLine,\n text: comment.body,\n };\n return new VscodeCommentWidget([vscodeComment], { expanded: true });\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Pixel-for-pixel replica of the \"Markdown comment\" frames from the Figma\n// \"Comment / Feedback widget\" board\n// (https://www.figma.com/design/lWE17f1tRRDXWsbxTcbsmo/Polish-Push-May---June-2026?node-id=4379-10808).\n//\n// It reproduces the three states of the markdown comment card:\n// 1. 'short' — a single short line, no toggle.\n// 2. 'collapsed' — a long body clamped to three lines with a \"See more\" link.\n// 3. 'expanded' — the full body with a \"See less\" link.\n//\n// Design tokens (from Figma):\n// editorWidget/background #202122\n// editorHoverWidget/border #2a2b2c\n// foreground #bfbfbf\n// icon/foreground #8c8c8c\n// textLink/foreground #48a0c7\n// Outer radius 8px\n// size40 / size60 / size80 4 / 6 / 8px\n// Heading 3 SF Pro Text Semibold 13\n// Body 1 SF Pro Text Regular 13\n// Label 1 SF Pro Text Regular 12\n//\n\n/** The three markdown-comment states captured in the Figma frames. */\nexport type VsCodeCommentV2State = 'short' | 'collapsed' | 'expanded';\n\nexport interface VsCodeCommentWidgetV2Options {\n /** Author label shown in the header (e.g. `@username`). */\n readonly username: string;\n /** The comment body (rendered as plain text; long bodies get a toggle). */\n readonly body: string;\n /**\n * Initial state. `'short'` hides the toggle entirely; `'collapsed'` and\n * `'expanded'` show a \"See more\" / \"See less\" toggle. Defaults to `'short'`.\n */\n readonly state?: VsCodeCommentV2State;\n /** Called when the user toggles between collapsed and expanded. */\n readonly onToggle?: (expanded: boolean) => void;\n /**\n * If provided, an edit button is shown in the header and invokes this on\n * click. When omitted the edit button is hidden.\n */\n readonly onEdit?: () => void;\n /**\n * If provided, the delete (trash) button invokes this on click. When omitted\n * the delete button is hidden.\n */\n readonly onDelete?: () => void;\n}\n\nconst DOM_HELPER_TAG = /^([a-z0-9]+)/i;\n\n/** VS Code's `dom.$('tag.a.b')` shorthand, reduced to what we use. */\nfunction $(selector: string): HTMLElement {\n const tag = DOM_HELPER_TAG.exec(selector)?.[1] ?? 'div';\n const el = document.createElement(tag);\n const classes = selector.slice(tag.length).split('.').filter(Boolean);\n if (classes.length) {\n el.className = classes.join(' ');\n }\n return el;\n}\n\n/**\n * Inline Feather-style icons (stroke=\"currentColor\"), matching the crisp look of\n * VS Code's codicons and the sibling {@link VscodeCommentWidget}.\n */\nfunction feather(inner: string): string {\n return `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nconst ICON_SVGS: Record<string, string> = {\n 'edit': feather('<path d=\"M12 20h9\"></path><path d=\"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z\"></path>'),\n 'trash': feather('<polyline points=\"3 6 5 6 21 6\"></polyline><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"></path><line x1=\"10\" y1=\"11\" x2=\"10\" y2=\"17\"></line><line x1=\"14\" y1=\"11\" x2=\"14\" y2=\"17\"></line>'),\n};\n\n/** An icon-only action button carrying the inline Feather SVG for `name`. */\nfunction actionButton(name: string, label: string): HTMLButtonElement {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'vscode-comment-widget-v2-action';\n btn.setAttribute('aria-label', label);\n btn.title = label;\n btn.innerHTML = ICON_SVGS[name] ?? '';\n return btn;\n}\nexport class VsCodeCommentWidgetV2 {\n private readonly _domNode: HTMLElement;\n private readonly _textNode: HTMLParagraphElement;\n private readonly _toggleNode?: HTMLButtonElement;\n private readonly _onToggle?: (expanded: boolean) => void;\n\n private _state: VsCodeCommentV2State;\n private readonly _disposables: (() => void)[] = [];\n private readonly _onToggleClick = (e: MouseEvent): void => {\n e.preventDefault();\n this.toggle();\n };\n\n get element(): HTMLElement { return this._domNode; }\n\n get expanded(): boolean { return this._state === 'expanded'; }\n\n constructor(options: VsCodeCommentWidgetV2Options) {\n this._state = options.state ?? 'short';\n this._onToggle = options.onToggle;\n\n // Card root — \"PR Review Comment\" frame.\n this._domNode = $('div.vscode-comment-widget-v2');\n\n // Header row: title-group (username) + actions (edit / trash).\n const header = $('div.vscode-comment-widget-v2-header');\n\n const titleGroup = $('div.vscode-comment-widget-v2-title-group');\n const username = $('span.vscode-comment-widget-v2-username');\n username.textContent = options.username;\n titleGroup.appendChild(username);\n header.appendChild(titleGroup);\n\n const actions = $('div.vscode-comment-widget-v2-actions');\n if (options.onEdit) {\n actions.appendChild(this._actionButton('edit', 'Edit', options.onEdit));\n }\n if (options.onDelete) {\n actions.appendChild(this._actionButton('trash', 'Delete', options.onDelete));\n }\n header.appendChild(actions);\n\n this._domNode.appendChild(header);\n\n // Body: comment text + optional \"See more\" / \"See less\" toggle.\n const body = $('div.vscode-comment-widget-v2-body');\n\n this._textNode = document.createElement('p');\n this._textNode.className = 'vscode-comment-widget-v2-text';\n this._textNode.textContent = options.body;\n body.appendChild(this._textNode);\n\n if (this._state !== 'short') {\n const toggle = document.createElement('button');\n toggle.type = 'button';\n toggle.className = 'vscode-comment-widget-v2-toggle';\n toggle.addEventListener('click', this._onToggleClick);\n this._toggleNode = toggle;\n body.appendChild(toggle);\n }\n\n this._domNode.appendChild(body);\n\n this._applyState();\n }\n\n /** Flip between the collapsed and expanded states (no-op for `'short'`). */\n toggle(): void {\n if (this._state === 'short') {\n return;\n }\n this._state = this._state === 'expanded' ? 'collapsed' : 'expanded';\n this._applyState();\n this._onToggle?.(this._state === 'expanded');\n }\n\n private _applyState(): void {\n this._domNode.classList.toggle('vscode-comment-widget-v2--collapsed', this._state === 'collapsed');\n this._domNode.classList.toggle('vscode-comment-widget-v2--expanded', this._state === 'expanded');\n if (this._toggleNode) {\n this._toggleNode.textContent = this._state === 'expanded' ? 'See less' : 'See more';\n }\n }\n\n /** A header action button that runs `onClick` (and cleans up on dispose). */\n private _actionButton(name: string, label: string, onClick: () => void): HTMLButtonElement {\n const button = actionButton(name, label);\n const handler = (e: MouseEvent): void => {\n e.preventDefault();\n e.stopPropagation();\n onClick();\n };\n button.addEventListener('click', handler);\n this._disposables.push(() => button.removeEventListener('click', handler));\n return button;\n }\n\n dispose(): void {\n this._toggleNode?.removeEventListener('click', this._onToggleClick);\n for (const dispose of this._disposables) { dispose(); }\n this._domNode.remove();\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Presenter that renders each comment from a CommentsModel as the Figma\n// \"Markdown comment\" card (the \"comments-vscode-v2\" design), reusing the real\n// VsCodeCommentWidgetV2. The base class handles anchoring, stacking and\n// lifecycle.\n//\n\nimport type { Comment } from '../comments/commentsModel.js';\nimport { StackedCommentsPresenter, type StackWidget } from './stackedCommentsPresenter.js';\nimport { VsCodeCommentWidgetV2 } from './vscodeCommentWidgetV2.js';\nimport './vscodeCommentTokens.css';\nimport './vscodeCommentWidgetV2.css';\n\n/** Bodies longer than this open collapsed (with a \"See more\" toggle). */\nconst COLLAPSE_THRESHOLD = 80;\n\nexport class VsCodeV2CommentsView extends StackedCommentsPresenter {\n protected createWidget(comment: Comment): StackWidget {\n return new VsCodeCommentWidgetV2({\n username: comment.author ?? 'You',\n body: comment.body,\n state: comment.body.length > COLLAPSE_THRESHOLD ? 'collapsed' : 'short',\n // Edit is intentionally omitted (hidden) for now. Delete removes the\n // comment from the shared model; the autorun then disposes the card.\n onDelete: () => this.model.remove(comment.id),\n });\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Composition root that maps a design id to a presenter factory. This is the one\n// place that knows all three renderings; the core (CommentsModel /\n// commentsPresenter) stays unaware of the concrete designs. Hosts (the demo, the\n// fixtures) pick a design here and swap it over a shared CommentsModel.\n//\n\nimport { CommentsView } from '../comments/commentsView.js';\nimport type { CommentsPresenterFactory } from '../comments/commentsPresenter.js';\nimport { VscodeStackedCommentsView } from './vscodeStackedCommentsView.js';\nimport { VsCodeV2CommentsView } from './vscodeV2CommentsView.js';\nimport '../comments/comments.css';\n\n/** The available comment rendering designs. */\nexport type CommentsDesign = 'connected' | 'vscode' | 'vscode-v2';\n\n/** Human-readable labels (for pickers / dropdowns). */\nexport const COMMENTS_DESIGN_LABELS: Record<CommentsDesign, string> = {\n 'connected': 'Connected lines (original)',\n 'vscode': 'VS Code cards',\n 'vscode-v2': 'Markdown cards (V2)',\n};\n\n/** design id → presenter factory over a shared CommentsModel + EditorView. */\nexport const COMMENTS_DESIGNS: Record<CommentsDesign, CommentsPresenterFactory> = {\n 'connected': (model, view) => new CommentsView(model, view),\n 'vscode': (model, view, ctx) => new VscodeStackedCommentsView(model, view, ctx),\n 'vscode-v2': (model, view, ctx) => new VsCodeV2CommentsView(model, view, ctx),\n};\n"],"names":["LengthReplacement","replaceRange","newLength","other","LengthEdit","replacement","replacements","lastEndEx","r","i","StringValue","value","range","Selection","anchor","active","offset","OffsetRange","Point2D","x","y","dx","dy","Rect2D","width","height","left","top","right","bottom","p","findWordBoundaryLeft","text","findWordBoundaryRight","len","findWordAt","ch","start","end","_nextNodeId","AstNode","sum","c","a","b","_other","id","clone","_emptyChildren","_mapArr","map","arr","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","UnhandledBlockAstNode","tokenType","HeadingAstNode","level","marker","ParagraphAstNode","CodeBlockAstNode","language","pos","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","_UNHANDLED_BLOCK_TOKENS","_pullIndentIntoBlocks","cur","next","hosted","_prependLeadingTrivia","prev","glue","firstIdx","items","j","_attachBlockGaps","idx","isParagraphBreak","gap","host","_appendTrailingGlue","h","u","_appendIntoLast","l","it","last","_ensureBlocks","Content","_parentStart","_source","parentLength","s","e","indent","_events","cb","coveredEnd","ev","block","unhandled","enter","depth","exit","raw","markerStart","markerEnd","inlines","seqEnter","seqExit","sawOpenFence","contentStart","contentEnd","fenceEnter","ii","fenceExit","flushContent","prefixEnter","prefixExit","seenBlock","pre","preExit","listType","itemStart","itemCb","itemChecked","lastBlockEnd","flush","itemEnd","columnCount","row","pipes","cellStartsRel","cols","rowCb","cs","ce","cellCb","cellType","cellEnter","cellExit","entries","untilExit","isStrong","openEnter","openExit","closeEnter","closeExit","sawOpen","sawOpenBracket","i2","sawOpenParen","EditMapper","_edit","mod","delta","modStart","dirtyEnd","OldTreeIndex","key","originalStart","_reconcile","fresh","mapper","index","edit","rc","orig","cand","os","old","linked","_linkCodeBlock","oldStart","oldCode","freshCode","_editWithin","_shiftEdit","endExclusive","StringEdit","StringReplacement","reconcile","parseIncremental","MarkdownParser","getAnnotatedSource","escapeXml","tag","_attributes","result","childOffset","attrs","k","v","str","_label","_objectInstanceIds","_nextObjectInstanceId","objectInstanceId","visualizeAst","walk","kids","children","changedRanges","_owner","_ready","observableValue","diffComputerReady","_computer","_readyPromise","ensureDiffComputer","createDiffComputer","computeStringEdit","original","modified","_convert","CONTAINER_KINDS","SKIP_KINDS","classifyDiff","changes","classifyChildren","origParent","origParentStart","modParent","modParentStart","O","structuralChildren","M","oi","mRange","removedItem","candRange","clean","localRanges","addedItem","nodeStart","inserted","deleted","nodeRange","side","inter","NO_ACTIVE_BLOCKS","EditorModel","derived","reader","previousText","pending","doc","cursor","findBlockAtOffset","override","sel","blocksIntersecting","baselineDoc","baseline","modifiedDoc","modifiedText","insertedRanges","collect","list","topLevel","changedBlocks","req","oldText","newText","newActive","newCursor","lastBlock","VisualLineMap","lines","blockViews","_measure","lineIndex","endBoundaryLine","membership","bestIdx","bestDist","dist","point","VisualLine","rect","runs","run","best","d","leftRight","leftEnd","rightLeft","rightStart","bestRun","VisualRun","sourceRange","_xAtTextOffset","localOffset","_offsetAtX","mid","textNode","textOffset","fallbackLeft","bestOffset","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","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","UnhandledBlockViewNode","ListViewNode","ListItemViewNode","TableViewNode","TableRowViewNode","InlineCodeViewNode","InlineMathViewNode","LinkViewNode","ImageViewNode","DiffHunkViewNode","DiffDecorationViewNode","ctor","reconcileDomChildren","parentDom","childData","previousChildren","build","paired","unused","pairNodes","_NO_CHILDREN","_patchDomChildren","_patchDomNodes","nodes","domCursor","toRemove","_buildChild","_inlineChild","wrapper","mounts","_buildDiffSide","cls","el","sideNode","_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","seg","RawLeafViewNode","sourceLength","base","reuse","built","ws","_previous","holder","_appendPlainText","className","hr","code","childAst","prevCode","embeddedLeading","embeddedTrailing","embeddedContent","embedded","custom","highlighter","session","diff","transaction","tx","tokens","contentNode","estimated","shifted","_buildCodeContent","CodeContentViewNode","leaves","runOnChange","snapshot","contentAst","_buildTokenLeaves","tokenLeaves","piece","_mathContentOffset","_buildMathSegmentChildren","nodeLength","sorted","filler","remembered","latex","rendering","div","katex","li","_reconcileListItem","checkbox","onToggle","wasChecked","first","gutter","table","tr","cellData","_isSafeUrl","shouldOpen","openLink","onOpenLink","pointerDownResult","onClick","img","newData","prevNodes","byId","DocumentViewNode","contentDomNode","blocks","pendingElement","viewData","activeByView","childViews","_NO_NODES","PendingParagraphViewNode","diffKind","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","UnhandledBlockViewData","MarkerViewData","visible","GlueViewData","decorateNewline","DiffDecorationViewData","deletedRanges","whole","_INACTIVE","_inline","buildDocumentViewData","activeBlocks","selectionRange","prevByAst","blockSet","_buildBlock","selectionInNode","_reuseOr","_buildNode","buildBlockViewData","applyDiffDecorations","diffItems","decorationsActive","overlay","removedBefore","modAst","_diffModifiedAst","removedAtEnd","blockView","rem","_decorationChild","decorateContainer","outChild","originalBlock","forceActive","_decoration","container","newContent","cvd","_withContent","vd","astNode","neighbors","_buildChildren","_markerVisible","_glueVisible","_buildList","_buildListItem","_buildTable","_buildTableRow","_buildTableCell","_childrenOf","_prevChildByAst","_flagsEqual","_edgeIsWordContent","prevNode","activeItems","_activeItemIndices","itemSet","itemLevel","itemCtx","childCtx","tableActive","delimiterRow","rowSet","rowCtx","activeCells","_activeCellIndices","cellSet","cell","cellActive","cellCtx","_EMPTY_SET","_findActiveCellIndex","cellIdx","collectTextLeaves","rangeFromLeaves","startNode","startOff","endNode","endOff","lf","ls","le","rangesForOffsets","spans","DiffHighlightsView","_parent","documentNode","green","red","rs","parentRect","frag","add","SelectionView","selection","visualLineMap","_renderSelection","autorun","SelectionViewRendering","path","computeRangeRects","buildConnectedPath","NEWLINE_SELECTION_WIDTH_RATIO","selRange","lineInfos","lineRange","_lineSourceRange","nextRange","hardBreak","overlapsContent","selectsTrailingBreak","lineRects","cStart","cEnd","startX","endX","breakSelected","clip","blockViewportClip","blockToFirstLineIdx","blockToLastLineIdx","blockSelected","curr","gapStart","currRect","nextRect","nextFirstLineTop","_firstLineTopOfBlock","prevLineIdx","nextLineIdx","_blockHasVisualLine","prevLR","nextLR","min","max","blockContainingOffset","fallback","radius","clusters","current","yTouches","xOverlaps","_buildClusterPath","corners","aRight","bRight","aConvex","_polygonToRoundedPath","radii","dPrev","_dist","dNext","_moveFrom","parts","_fmt","depart","nextR","approach","from","to","t","CursorView","pendingRect","localRect","CursorViewRendering","caretRect","GutterMarkersView","markers","GutterMarkersViewRendering","_deletedRect","_barRect","parentTop","DEFAULT_LIMITED_WIDTH","EditorView","_model","_options","limitedWidth","constObservable","lastMeasuredContentWidth","resizeObserver","scrollRaf","onBlockScroll","button","indicator","lockedIcon","lockKeyhole","lockBody","editingIcon","editingPath","onPointerDown","event","onKeyDown","onFocus","onBlur","onAnimationEnd","readonly","tableCellOffset","hit","documentView","cellNode","cellStart","cellEnd","domOffsetAtPoint","element","hasSourceRun","hitNode","hitStart","hitEnd","sourceText","baseViewData","pendingEl","document","measurements","entry","blockRect","NativeClipboardStrategy","context","onCopy","onCut","onPaste","AsyncClipboardStrategy","_clipboard","MULTI_CLICK_TIME_MS","MULTI_CLICK_DISTANCE_PX","EditorController","_view","win","clipboardStrategy","editContext","isRepeat","findBlockRangeAt","revealsLockOnClick","pointerId","onPointerMove","me","moveOffset","onPointerUp","command","extend","ctrl","_SHOW_LINE_RECTS_KEY","_readStoredBool","_writeStoredBool","MeasuredLayoutDebugView","_overlayParent","controls","showLineRects","_renderDebug","hovered","applyHoverIsolation","MeasuredLayoutDebugRendering","blockCount","mountedCount","lineCount","mappedOffsets","info","overlayParent","colorForOffset","hoveredOffset","charCount","lineRect","band","runBox","_appendCharRects","header","rows","flag","lc","blockAbsoluteStart","count","covered","isCovered","drawWidth","box","_isolate","off","matches","keep","on","Token","length","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","PLUS_SVG","CommentInputWidget","footer","onPanelPointerDown","onInput","onSubmitClick","hasText","textWidth","scrollHeight","CommentModeController","isSelecting","hasTypedText","preferAbove","widgetHeight","containerTop","viewport","caretTop","roomBelow","roomAbove","topPx","containerWidth","maxLeft","overflowY","CommentsModel","comments","input","comment","SVG_NS","RAIL_MIN","RAIL_MAX","RAIL_FRACTION","RAIL_GAP","RAIL_EDGE","CARD_GAP","LEADER_CARD_INSET","HIGHLIGHT_RADIUS","LEADER_WIDTH","LEADER_OVERLAP","CommentsView","svg","hoveredId","seen","existing","group","leaderPath","shapePath","card","avatarEl","authorEl","timeEl","menuEl","bodyEl","reply","setHover","leave","author","_initials","_relativeTime","rootRect","rootWidth","maxW","padX","borderX","contentMaxOuter","naturalRight","railWidth","need","pad","padStr","overlayRect","railLeftLocal","contentRightLocal","placed","_lineStart","desiredTop","prevBottom","_leaderLine","rightEdge","bendX","bend","c1x","c2x","name","second","epochMs","deltaSec","hours","RIGHT_INSET","layoutRightAlignedStack","StackedCommentsPresenter","model","widget","DOM_HELPER_TAG","$","selector","classes","feather","ICON_SVGS","icon","renderMarkdown","wrap","part","VscodeCommentWidget","_comments","itemHeader","itemMeta","lineInfo","typeLabel","badge","actions","bar","addReply","remove","enabled","codicon","ariaLabel","startLine","endLine","suggestionNode","editNode","replies","repliesNode","replyNode","replyText","textContainer","textarea","autoSize","restore","replyContainer","close","handler","VscodeStackedCommentsView","vscodeComment","actionButton","label","btn","VsCodeCommentWidgetV2","titleGroup","username","body","toggle","dispose","COLLAPSE_THRESHOLD","VsCodeV2CommentsView","COMMENTS_DESIGN_LABELS","COMMENTS_DESIGNS"],"mappings":";;;;;;;;;AAaO,MAAMA,GAAkB;AAAA,EAK3B,YACoBC,GACAC,GAClB;AACE,QAHgB,KAAA,eAAAD,GACA,KAAA,YAAAC,GAEZA,IAAY;AACZ,YAAM,IAAI,MAAM,uCAAuCA,CAAS,EAAE;AAAA,EAE1E;AAAA,EAXA,OAAc,QAAQD,GAA2BC,GAAsC;AACnF,WAAO,IAAIF,GAAkBC,GAAcC,CAAS;AAAA,EACxD;AAAA,EAWA,IAAI,cAAsB;AACtB,WAAO,KAAK,YAAY,KAAK,aAAa;AAAA,EAC9C;AAAA,EAEO,OAAOC,GAAmC;AAC7C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GACjCJ,IAAU,CAAC/8B,MAAwB;AACrC,MAAAA,EAAE,eAAA,GACFA,EAAE,gBAAA,GACF0c,EAAA;AAAA,IACJ;AACA,WAAAoO,EAAO,iBAAiB,SAASiS,CAAO,GACxC,KAAK,aAAa,KAAK,MAAMjS,EAAO,oBAAoB,SAASiS,CAAO,CAAC,GAClEjS;AAAA,EACX;AAAA,EAEA,UAAgB;AACZ,SAAK,aAAa,oBAAoB,SAAS,KAAK,cAAc;AAClE,eAAW4S,KAAW,KAAK;AAAgB,MAAAA,EAAA;AAC3C,SAAK,SAAS,OAAA;AAAA,EAClB;AACJ;AC9KA,MAAMC,KAAqB;AAEpB,MAAMC,WAA6BtD,GAAyB;AAAA,EACrD,aAAa/D,GAA+B;AAClD,WAAO,IAAI8G,GAAsB;AAAA,MAC7B,UAAU9G,EAAQ,UAAU;AAAA,MAC5B,MAAMA,EAAQ;AAAA,MACd,OAAOA,EAAQ,KAAK,SAASoH,KAAqB,cAAc;AAAA;AAAA;AAAA,MAGhE,UAAU,MAAM,KAAK,MAAM,OAAOpH,EAAQ,EAAE;AAAA,IAAA,CAC/C;AAAA,EACL;AACJ;ACVO,MAAMsH,KAAyD;AAAA,EAClE,WAAa;AAAA,EACb,QAAU;AAAA,EACV,aAAa;AACjB,GAGaC,KAAqE;AAAA,EAC9E,WAAa,CAACvD,GAAOttB,MAAS,IAAIkqB,GAAaoD,GAAOttB,CAAI;AAAA,EAC1D,QAAU,CAACstB,GAAOttB,GAAMiD,MAAQ,IAAI8sB,GAA0BzC,GAAOttB,GAAMiD,CAAG;AAAA,EAC9E,aAAa,CAACqqB,GAAOttB,GAAMiD,MAAQ,IAAI0tB,GAAqBrD,GAAOttB,GAAMiD,CAAG;AAChF;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../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/diff/diffEdit.ts","../src/diff/vscodeDiff.ts","../src/diff/classifyDiff.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/editorCoordinateSpace.ts","../src/view/viewData.ts","../src/view/diffHighlight.ts","../src/view/parts/diffHighlightsView.ts","../src/view/parts/selectionView.ts","../src/view/parts/cursorView.ts","../src/view/parts/gutterMarkersView.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","../src/contrib/comments/commentInputWidget.ts","../src/contrib/comments/commentModeController.ts","../src/contrib/comments/commentsModel.ts","../src/contrib/comments/commentsView.ts","../src/contrib/commentsVscode/stackedRailLayout.ts","../src/contrib/commentsVscode/stackedCommentsPresenter.ts","../src/contrib/commentsVscode/vscodeCommentWidget.ts","../src/contrib/commentsVscode/vscodeStackedCommentsView.ts","../src/contrib/commentsVscode/vscodeCommentWidgetV2.ts","../src/contrib/commentsVscode/vscodeV2CommentsView.ts","../src/contrib/commentsVscode/commentsDesigns.ts"],"sourcesContent":["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 a caller-defined 2D CSS-pixel coordinate space.\n * Coordinate-owning APIs must document whether values are viewport-client or\n * editor-local; values from different spaces must not be mixed.\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 a caller-defined 2D CSS-pixel coordinate\n * space. `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 | UnhandledBlockAstNode;\n\n/**\n * A block whose token type the parser does not understand (a setext heading, a\n * frontmatter fence, any future/extension construct). Rather than dropping the\n * span — which would demote its text to invisible glue — the parser captures the\n * whole source range verbatim as a single {@link MarkerAstNode} of kind\n * `content` and records the originating micromark {@link tokenType}, so the view\n * can render it as raw, editable text with an \"unhandled\" affordance. Offsets\n * stay sound: `content` tiles the block's full source span exactly.\n */\nexport class UnhandledBlockAstNode extends BlockAstNodeBase {\n\treadonly kind = 'unhandledBlock';\n\tconstructor(\n\t\treadonly tokenType: string,\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 code(): MarkerAstNode | undefined { return _marker(this.content, 'content'); }\n\toverride mapChildren(m: ReadonlyMap<AstNode, AstNode>): AstNode { return new UnhandledBlockAstNode(this.tokenType, _mapArr(m, this.content), _mapTrivia(m, this.leadingTrivia)); }\n\toverride withLeadingTrivia(trivia: GlueAstNode | undefined): UnhandledBlockAstNode { return new UnhandledBlockAstNode(this.tokenType, this.content, trivia); }\n\tprotected override _localEquals(o: this): boolean { return this.tokenType === o.tokenType; }\n}\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 instanceof UnhandledBlockAstNode;\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 | UnhandledBlockAstNode;\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, UnhandledBlockAstNode,\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\n/**\n * Block-level micromark tokens we do not model but that carry real content\n * worth preserving verbatim (an HTML block, a setext heading / YAML frontmatter\n * fence, a link-reference definition). When one appears where a block is\n * expected — at the document top level or inside a list item / block quote — it\n * is captured as an {@link UnhandledBlockAstNode} instead of being dropped.\n *\n * Deliberately an allowlist, not a denylist: every *structural* token (line\n * endings, `linePrefix`, `blockQuotePrefix`, `listItemIndent`, …) is simply\n * stepped over and tiles as glue, exactly as before. Enumerating the constructs\n * we fall back on — rather than \"anything unrecognized\" — keeps the many\n * whitespace/prefix tokens from being mistaken for content. To support a new\n * construct, either parse it properly or add its token here.\n */\nconst _UNHANDLED_BLOCK_TOKENS: ReadonlySet<string> = new Set([\n 'htmlFlow', 'setextHeading', 'definition',\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 'unhandledBlock': { const u = node as UnhandledBlockAstNode; return new UnhandledBlockAstNode(u.tokenType, [...u.content, glue], u.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 let coveredEnd = 0;\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); coveredEnd = Math.max(coveredEnd, start + block.length); }\n else {\n const unhandled = this._tryParseUnhandled(coveredEnd);\n if (unhandled) { cb.add(unhandled.node, unhandled.start); coveredEnd = Math.max(coveredEnd, unhandled.start + unhandled.node.length); }\n }\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:\n return undefined;\n }\n }\n\n /**\n * Fallback for an unrecognized top-level token (a setext heading, a\n * frontmatter fence, any extension construct). Consumes the whole\n * `enter…exit` span of that token — depth-counting so a same-typed nested\n * token cannot end it early — and captures the raw source verbatim as a\n * single `content` marker, so the text is preserved and rendered as an\n * explicit \"unhandled\" block instead of being demoted to invisible glue.\n */\n private _parseUnhandledBlock(): UnhandledBlockAstNode {\n const enter = this._events[this._idx];\n const tokenType = enter.tokenType;\n this._idx++;\n let depth = 1;\n let exit = enter;\n while (this._idx < this._events.length && depth > 0) {\n const ev = this._events[this._idx];\n if (ev.tokenType === tokenType) { depth += ev.type === 'enter' ? 1 : -1; }\n if (depth === 0) { exit = ev; }\n this._idx++;\n }\n const raw = this._source.substring(enter.startOffset, exit.endOffset);\n return new UnhandledBlockAstNode(tokenType, [new MarkerAstNode('content', raw)]);\n }\n\n /**\n * Decides what to do with an unrecognized `enter` token at the top of a\n * block-collecting loop (the document, a list item, a block quote), so all\n * three treat unknown constructs identically. A token in\n * {@link _UNHANDLED_BLOCK_TOKENS} that does not overlap an already-claimed\n * sibling (`start < coveredEnd`, e.g. a `setextHeading` micromark re-claims\n * back over a preceding `definition`) is captured verbatim via\n * {@link _parseUnhandledBlock}; every other token — a transparent `content`\n * wrapper, a structural prefix/indent, a line ending — is stepped over so it\n * tiles as glue. Returns the block and its start, or `undefined` when the\n * event was stepped over.\n */\n private _tryParseUnhandled(coveredEnd: number): Entry | undefined {\n const ev = this._events[this._idx];\n const start = ev.startOffset;\n if (start >= coveredEnd && _UNHANDLED_BLOCK_TOKENS.has(ev.tokenType)) {\n return { node: this._parseUnhandledBlock(), start };\n }\n this._idx++;\n return undefined;\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 let coveredEnd = enter.startOffset;\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 coveredEnd = Math.max(coveredEnd, preExit.endOffset);\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; coveredEnd = Math.max(coveredEnd, start + block.length); }\n else {\n const unhandled = this._tryParseUnhandled(coveredEnd);\n if (unhandled) { cb.add(unhandled.node, unhandled.start); seenBlock = true; coveredEnd = Math.max(coveredEnd, unhandled.start + unhandled.node.length); }\n }\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) {\n // An unknown construct inside the item (e.g. an HTML block) is\n // kept verbatim rather than dropped, using the same\n // content-vs-whitespace rule as the top level. `lastBlockEnd`\n // (else the marker end) is the item's covered offset.\n const unhandled = this._tryParseUnhandled(lastBlockEnd ?? markerEnd ?? start);\n if (unhandled && itemCb) {\n itemCb.add(unhandled.node, unhandled.start);\n lastBlockEnd = unhandled.start + unhandled.node.length;\n }\n }\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, UnhandledBlockAstNode, 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 UnhandledBlockAstNode) { attrs.token = node.tokenType; }\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 { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\n\n/**\n * A changed region, expressed in *both* coordinate spaces: {@link original}\n * is the range in the original document, {@link modified} the corresponding\n * range in the modified document. An insertion has an empty {@link original};\n * a deletion an empty {@link modified}.\n */\nexport interface ChangedRange {\n\treadonly original: OffsetRange;\n\treadonly modified: OffsetRange;\n}\n\n/**\n * Transform a {@link StringEdit} (original → modified) into the list of changed\n * ranges, each mapped between the two coordinate spaces. This is the bridge the\n * diff classifier and the word-level highlighter both consume.\n */\nexport function changedRanges(edit: StringEdit): ChangedRange[] {\n\tlet delta = 0;\n\tconst out: ChangedRange[] = [];\n\tfor (const r of edit.replacements) {\n\t\tconst modStart = r.replaceRange.start + delta;\n\t\tout.push({\n\t\t\toriginal: r.replaceRange,\n\t\t\tmodified: OffsetRange.ofStartAndLength(modStart, r.newText.length),\n\t\t});\n\t\tdelta += r.newText.length - r.replaceRange.length;\n\t}\n\treturn out;\n}\n","import { observableValue, type IObservable } from '@vscode/observables';\nimport { createDiffComputer } from '@vscode/diff';\nimport type { IDiffComputer, StringEdit as VscodeStringEdit } from '@vscode/diff';\nimport { OffsetRange } from '../core/offsetRange.js';\nimport { StringEdit, StringReplacement } from '../core/stringEdit.js';\n\nconst _owner = {};\nconst _ready = observableValue<boolean>(_owner, false);\n\n/**\n * Becomes `true` once the `@vscode/diff` computer has loaded. Diff consumers\n * read this so they recompute with the better (character/word-level) algorithm\n * as soon as it is available.\n */\nexport const diffComputerReady: IObservable<boolean> = _ready;\n\nlet _computer: IDiffComputer | undefined;\nlet _readyPromise: Promise<void> | undefined;\n\n/** Load the `@vscode/diff` computer (pure-TS, no WASM). Idempotent. */\nexport function ensureDiffComputer(): Promise<void> {\n\tif (!_readyPromise) {\n\t\t_readyPromise = createDiffComputer({ useWasm: false })\n\t\t\t.then(c => { _computer = c; _ready.set(true, undefined); })\n\t\t\t.catch(() => { /* keep the line-level fallback */ });\n\t}\n\treturn _readyPromise;\n}\n\n// Start loading eagerly so the algorithm is ready as soon as possible.\nvoid ensureDiffComputer();\n\n/** Whether the `@vscode/diff` computer has finished loading. */\nexport function isDiffComputerReady(): boolean {\n\treturn _computer !== undefined;\n}\n\n/**\n * Compute a {@link StringEdit} (original → modified) using `@vscode/diff`'s\n * character/word-level algorithm. The computer loads asynchronously (near\n * instantly, no WASM); callers must ensure it is ready first — observe\n * {@link diffComputerReady} or await {@link ensureDiffComputer}.\n */\nexport function computeStringEdit(original: string, modified: string): StringEdit {\n\tif (!_computer) {\n\t\tthrow new Error('Diff computer not loaded yet — await ensureDiffComputer() / observe diffComputerReady first.');\n\t}\n\tconst result = _computer.computeDiff(original, modified, { extendToSubwords: true });\n\treturn _convert(result.edits.stripData());\n}\n\n/** Convert a `@vscode/diff` StringEdit into the editor's own StringEdit. */\nfunction _convert(edit: VscodeStringEdit): StringEdit {\n\treturn new StringEdit(edit.replacements.map(r =>\n\t\tStringReplacement.replace(new OffsetRange(r.range.start, r.range.endExclusive), r.newText)));\n}\n","import { OffsetRange } from '../core/offsetRange.js';\nimport type { StringEdit } from '../core/stringEdit.js';\nimport type { AstNode, DocumentAstNode } from '../parser/ast.js';\nimport { EditMapper } from '../parser/reconcile.js';\nimport { changedRanges, type ChangedRange } from './diffEdit.js';\nimport type { AnnotatedRange, DiffItem } from './diffItem.js';\n\n/**\n * Node kinds whose changes are diffed *structurally* (render the container\n * once, recurse into its children). Everything else is a leaf: a change there\n * produces a `replaced` item with word-level highlights.\n *\n * A `listItem` is deliberately a *leaf*, not a container: its marker (`- `,\n * `1. `) is structural syntax that the aligner skips, so recursing would orphan\n * a marker character caught in a change boundary (it would belong to no child\n * decoration). As a leaf the whole original item — marker included — is shown\n * over the modified one, with word-level highlights inside. A `tableCell` is a\n * leaf for the same reason (its `|`/padding glue would otherwise be orphaned),\n * and it only ever holds inline content anyway.\n */\nconst CONTAINER_KINDS: ReadonlySet<string> = new Set([\n\t'document', 'list', 'blockQuote', 'table', 'tableRow',\n]);\n\n/** Child kinds that are structural noise for alignment (still counted for offsets). */\nconst SKIP_KINDS: ReadonlySet<string> = new Set(['glue', 'marker']);\n\ninterface PositionedNode { readonly node: AstNode; readonly start: number; }\n\n/**\n * Classify the difference between two parsed documents, using the textual\n * `edit` (original → modified) as the alignment oracle. Returns a recursive\n * {@link DiffItem} list over the document's blocks.\n *\n * The alignment is purely offset-based (no tree-diff): each modified node is\n * mapped back through {@link EditMapper}; a clean mapping that lines up with the\n * next original node is `unchanged`, a same-kind node whose origin lands inside\n * the next original node is a change (recursed if a container, else a leaf\n * `replaced`), an unmappable node is `added`, and any original node not consumed\n * is `removed`.\n */\nexport function classifyDiff(original: DocumentAstNode, modified: DocumentAstNode, edit: StringEdit): DiffItem[] {\n\tconst mapper = new EditMapper(edit);\n\tconst changes = changedRanges(edit);\n\treturn classifyChildren(original, 0, modified, 0, mapper, changes);\n}\n\nfunction classifyChildren(\n\torigParent: AstNode,\n\torigParentStart: number,\n\tmodParent: AstNode,\n\tmodParentStart: number,\n\tmapper: EditMapper,\n\tchanges: readonly ChangedRange[],\n): DiffItem[] {\n\tconst O = structuralChildren(origParent, origParentStart);\n\tconst M = structuralChildren(modParent, modParentStart);\n\tconst items: DiffItem[] = [];\n\tlet oi = 0;\n\n\tfor (const m of M) {\n\t\tconst mRange = OffsetRange.ofStartAndLength(m.start, m.node.length);\n\t\tconst os = mapper.getOriginalOffset(m.start);\n\n\t\t// Original children lying entirely before m's origin were deleted.\n\t\twhile (oi < O.length && os !== undefined && O[oi].start + O[oi].node.length <= os) {\n\t\t\titems.push(removedItem(O[oi], changes));\n\t\t\toi++;\n\t\t}\n\n\t\tconst cand = oi < O.length ? O[oi] : undefined;\n\t\tconst candRange = cand ? OffsetRange.ofStartAndLength(cand.start, cand.node.length) : undefined;\n\t\tconst clean = mapper.getOriginalRange(mRange);\n\n\t\tif (clean && candRange && clean.equals(candRange)) {\n\t\t\titems.push({ kind: 'unchanged', node: m.node, modifiedStart: m.start });\n\t\t\toi++;\n\t\t} else if (cand && candRange && cand.node.kind === m.node.kind && os !== undefined && candRange.contains(os)) {\n\t\t\toi++;\n\t\t\tif (CONTAINER_KINDS.has(m.node.kind)) {\n\t\t\t\titems.push({\n\t\t\t\t\tkind: 'nested',\n\t\t\t\t\toriginal: cand.node, originalStart: cand.start,\n\t\t\t\t\tmodified: m.node, modifiedStart: m.start,\n\t\t\t\t\tchildren: classifyChildren(cand.node, cand.start, m.node, m.start, mapper, changes),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\titems.push({\n\t\t\t\t\tkind: 'replaced',\n\t\t\t\t\toriginal: cand.node, originalStart: cand.start,\n\t\t\t\t\tmodified: m.node, modifiedStart: m.start,\n\t\t\t\t\tinsertedLocal: localRanges(mRange, m.start, changes, 'modified', 'inserted'),\n\t\t\t\t\tdeletedLocal: localRanges(candRange, cand.start, changes, 'original', 'deleted'),\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\titems.push(addedItem(m, changes));\n\t\t}\n\t}\n\n\twhile (oi < O.length) {\n\t\titems.push(removedItem(O[oi], changes));\n\t\toi++;\n\t}\n\treturn items;\n}\n\n/** Children that participate in alignment, with absolute start offsets. */\nfunction structuralChildren(node: AstNode, nodeStart: number): PositionedNode[] {\n\tconst out: PositionedNode[] = [];\n\tlet pos = nodeStart;\n\tfor (const c of node.children) {\n\t\tif (!SKIP_KINDS.has(c.kind)) { out.push({ node: c, start: pos }); }\n\t\tpos += c.length;\n\t}\n\treturn out;\n}\n\nfunction addedItem(m: PositionedNode, changes: readonly ChangedRange[]): DiffItem {\n\tconst range = OffsetRange.ofStartAndLength(m.start, m.node.length);\n\tlet inserted = localRanges(range, m.start, changes, 'modified', 'inserted');\n\tif (inserted.length === 0) { inserted = [{ range: OffsetRange.ofLength(m.node.length), kind: 'inserted' }]; }\n\treturn { kind: 'added', node: m.node, modifiedStart: m.start, insertedLocal: inserted };\n}\n\nfunction removedItem(o: PositionedNode, changes: readonly ChangedRange[]): DiffItem {\n\tconst range = OffsetRange.ofStartAndLength(o.start, o.node.length);\n\tlet deleted = localRanges(range, o.start, changes, 'original', 'deleted');\n\tif (deleted.length === 0) { deleted = [{ range: OffsetRange.ofLength(o.node.length), kind: 'deleted' }]; }\n\treturn { kind: 'removed', node: o.node, originalStart: o.start, deletedLocal: deleted };\n}\n\n/** Intersect the changed ranges with a node and project into the node's local space. */\nfunction localRanges(\n\tnodeRange: OffsetRange,\n\tnodeStart: number,\n\tchanges: readonly ChangedRange[],\n\tside: 'original' | 'modified',\n\tkind: 'inserted' | 'deleted',\n): AnnotatedRange[] {\n\tconst out: AnnotatedRange[] = [];\n\tfor (const c of changes) {\n\t\tconst cr = side === 'original' ? c.original : c.modified;\n\t\tconst inter = cr.intersect(nodeRange);\n\t\tif (inter && !inter.isEmpty) {\n\t\t\tout.push({ range: inter.delta(-nodeStart), kind });\n\t\t}\n\t}\n\treturn out;\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';\nimport { computeStringEdit, classifyDiff, diffComputerReady } from '../diff/index.js';\nimport type { DiffItem } from '../diff/index.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\n\t/**\n\t * Read-only mode. When `true`, the editor never reveals a block's source\n\t * markers (markdown special characters like `**`, `#`, list bullets, code\n\t * fences, `$…$`) — every block stays in its clean rendered form regardless\n\t * of where the caret/selection is — and source-mutating edits are ignored.\n\t * Plain text selection still works everywhere (so the user can copy). The\n\t * default (`false`) is the normal editing mode where the active block\n\t * reveals its markers.\n\t */\n\treadonly readonlyMode = observableValue<boolean>(this, false);\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, undefined);\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 * Whether a pointer-driven selection drag is currently in progress. Set by\n\t * the controller between the pointer-down that starts the drag and the\n\t * pointer-up/cancel that ends it. Contributions read it to defer UI that\n\t * would otherwise flicker mid-drag (e.g. the comment input box appears only\n\t * once the drag ends).\n\t */\n\treadonly isSelecting = 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// Read-only mode never reveals markers: no block is ever active, so every\n\t\t// block renders in its clean form. Selection still works (it is DOM-based\n\t\t// and independent of the active set).\n\t\tif (this.readonlyMode.read(reader)) {\n\t\t\treturn new Set<BlockAstNode>();\n\t\t}\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 * The baseline document to diff against. When set, the editor renders in\n\t * diff mode: the modified document ({@link document}) stays editable, while\n\t * the baseline's removed/changed blocks are shown as read-only decorations.\n\t * `undefined` (the default) renders normally.\n\t */\n\treadonly baseline = observableValue<StringValue | undefined>(this, undefined);\n\n\tprivate readonly _baselineDocument = derived(this, reader => {\n\t\tconst b = reader.readObservable(this.baseline);\n\t\treturn b ? this._parser.parse(b) : undefined;\n\t});\n\n\t/**\n\t * The diff of {@link baseline} → {@link document}, or `undefined` when no\n\t * baseline is set. The view renders the {@link DiffItem}s as stacked\n\t * decorations; `insertedRanges` (modified-side change spans) drive the green\n\t * word-level highlight.\n\t */\n\treadonly diff = derived(this, reader => {\n\t\tconst baselineDoc = reader.readObservable(this._baselineDocument);\n\t\tconst baseline = reader.readObservable(this.baseline);\n\t\tif (!baselineDoc || !baseline) { return undefined; }\n\t\t// No diff until the @vscode/diff algorithm has loaded (near-instant).\n\t\tif (!reader.readObservable(diffComputerReady)) { return undefined; }\n\t\tconst modifiedDoc = reader.readObservable(this.document);\n\t\tconst modifiedText = reader.readObservable(this.sourceText);\n\t\tconst edit = computeStringEdit(baseline.value, modifiedText.value);\n\t\tconst items = classifyDiff(baselineDoc, modifiedDoc, edit);\n\t\t// Green word rects only for *partial* changes (`replaced`, and anything\n\t\t// inside a recursively-diffed container). Whole added blocks get a solid\n\t\t// band instead, so they contribute no inline rects.\n\t\tconst insertedRanges: OffsetRange[] = [];\n\t\tconst collect = (list: readonly DiffItem[], topLevel: boolean): void => {\n\t\t\tfor (const it of list) {\n\t\t\t\tif (it.kind === 'replaced') {\n\t\t\t\t\tfor (const r of it.insertedLocal) { insertedRanges.push(r.range.delta(it.modifiedStart)); }\n\t\t\t\t} else if (it.kind === 'added' && !topLevel) {\n\t\t\t\t\tfor (const r of it.insertedLocal) { insertedRanges.push(r.range.delta(it.modifiedStart)); }\n\t\t\t\t} else if (it.kind === 'nested') {\n\t\t\t\t\tcollect(it.children, false);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tcollect(items, true);\n\t\t// Partially-changed (`replaced`) blocks render in active/source form so\n\t\t// marker-level modifications are visible. Whole added blocks stay rendered.\n\t\tconst changedBlocks = new Set<BlockAstNode>();\n\t\tfor (const it of items) {\n\t\t\tif (it.kind === 'replaced') { changedBlocks.add(it.modified as BlockAstNode); }\n\t\t}\n\t\treturn { items, insertedRanges, changedBlocks };\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\tif (this.readonlyMode.get()) { return; }\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\tif (this.readonlyMode.get()) { return; }\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\tif (this.readonlyMode.get()) { return; }\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';\nimport { EditorCoordinateSpace, type EditorCoordinateTransform } from './editorCoordinateSpace.js';\n\n/**\n * Geometry of the rendered document, as a map from source offsets to 2D\n * positions and back. All geometry is expressed in the editor overlay's local\n * CSS-pixel coordinate space.\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(\n\t\tblockViews: readonly { readonly absoluteStart: number; readonly viewNode: ViewNode }[],\n\t\tcoordinateSpace: EditorCoordinateSpace,\n\t\ttransform: EditorCoordinateTransform = coordinateSpace.capture(),\n\t): VisualLineMap {\n\t\treturn _measure(blockViews, coordinateSpace, transform);\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.\n\t *\n\t * The runs tile the source but are stored in paint order, not sorted by\n\t * source offset (hidden-marker runs are appended last). So this scans all\n\t * runs rather than assuming any ordering:\n\t *\n\t * - If some run *covers* `offset`, its own geometry places the caret\n\t * (exact glyph boundary for text runs). In the active, markers-visible\n\t * form every offset is covered, so this branch keeps distinct offsets\n\t * distinct.\n\t * - Otherwise `offset` sits in a gap — a hidden inline marker such as the\n\t * `**` of `**bold**`, or before/after the painted text. It snaps to the\n\t * seam between the source-nearest runs on either side: the right edge of\n\t * the closest run ending at/before `offset`, else the left edge of the\n\t * closest run starting at/after it. A hidden marker collapses to zero\n\t * width, so both edges coincide at the seam.\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\tlet leftRight: number | undefined;\n\t\tlet leftEnd = -Infinity;\n\t\tlet rightLeft: number | undefined;\n\t\tlet rightStart = Infinity;\n\t\tfor (const run of this.runs) {\n\t\t\tif (run.sourceEndExclusive <= offset && run.sourceEndExclusive > leftEnd) {\n\t\t\t\tleftEnd = run.sourceEndExclusive;\n\t\t\t\tleftRight = run.rect.right;\n\t\t\t}\n\t\t\tif (run.sourceStart >= offset && run.sourceStart < rightStart) {\n\t\t\t\trightStart = run.sourceStart;\n\t\t\t\trightLeft = run.rect.left;\n\t\t\t}\n\t\t}\n\t\tif (leftRight !== undefined) { return leftRight; }\n\t\tif (rightLeft !== undefined) { return rightLeft; }\n\t\treturn this.runs[0].rect.left;\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 run resolves the offset (exact glyph boundary for text runs,\n\t * nearer edge for source-less runs); otherwise it snaps to the closer\n\t * 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 * This matters for proportional fonts where character widths differ a lot\n * (e.g. `m` vs `i`): a caret placed by anything coarser than real glyph\n * measurement lands several pixels inside the wrong character.\n *\n * A run without a source has no per-offset geometry, so it maps between\n * offsets and x by snapping to the nearer run edge. Real text runs always\n * carry a source; source-less runs are element-only blocks (see\n * {@link _appendElementBlockRun}) and hand-built runs in tests.\n */\nexport interface VisualRunSource {\n\treadonly textNode: Text;\n\t/** Offset within `textNode.data` corresponding to `sourceRange.start`. */\n\treadonly textNodeStart: number;\n\treadonly coordinateSpace: EditorCoordinateSpace;\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`.\n *\n * A source-less run has no per-offset geometry: it either represents an\n * element-only block (KaTeX math, a mermaid/custom diagram, an image, an\n * inactive `<hr>`) whose box does not correspond to source offsets, or a\n * hand-built run in a test. Either way it maps between offsets and x by\n * snapping to the nearer edge of {@link rect} rather than fabricating\n * interior positions.\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(\n\t\t\t\tthis.source.textNode,\n\t\t\t\tthis.source.textNodeStart + (offset - this.sourceStart),\n\t\t\t\tthis.rect.left,\n\t\t\t\tthis.source.coordinateSpace,\n\t\t\t);\n\t\t}\n\t\t// No per-offset geometry: the caret sits at the run edge nearer to\n\t\t// `offset` (see class doc). Real text runs always carry a source, so\n\t\t// this only covers element blocks and hand-built test runs.\n\t\tconst fraction = (offset - this.sourceStart) / this.sourceLength;\n\t\treturn fraction <= 0.5 ? this.rect.left : this.rect.right;\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(\n\t\t\t\tthis.source.textNode,\n\t\t\t\tthis.source.textNodeStart,\n\t\t\t\tthis.source.textNodeStart + this.sourceLength,\n\t\t\t\tx,\n\t\t\t\tthis.source.coordinateSpace,\n\t\t\t);\n\t\t\treturn this.sourceStart + (localOffset - this.source.textNodeStart);\n\t\t}\n\t\t// No per-offset geometry: snap to the nearer edge rather than\n\t\t// fabricating interior positions (matching the element-edge rule in\n\t\t// `ViewNode.getLocalSourceRange`).\n\t\tconst mid = (this.rect.left + this.rect.right) / 2;\n\t\treturn x < mid ? this.sourceStart : this.sourceEndExclusive;\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(\n\ttextNode: Text,\n\ttextOffset: number,\n\tfallbackLeft: number,\n\tcoordinateSpace: EditorCoordinateSpace,\n): 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 coordinateSpace.capture().toLocalRect(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(\n\ttextNode: Text,\n\tstart: number,\n\tend: number,\n\tx: number,\n\tcoordinateSpace: EditorCoordinateSpace,\n): number {\n\tconst range = document.createRange();\n\tconst transform = coordinateSpace.capture();\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 clientRect = range.getBoundingClientRect();\n\t\tif (clientRect.width === 0 && clientRect.height === 0) { continue; }\n\t\tconst rect = transform.toLocalRect(clientRect);\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 editor-local CSS pixels,\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\tcoordinateSpace: EditorCoordinateSpace,\n\ttransform: EditorCoordinateTransform,\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 clientRects = range.getClientRects();\n\t\t\tif (clientRects.length === 0) { return; }\n\t\t\tconst rects = Array.from(clientRects, rect => transform.toLocalRect(rect));\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, coordinateSpace },\n\t\t\t\t));\n\t\t\t} else {\n\t\t\t\tconst breakOffsets = _findLineBreakOffsets(textNode, rects, transform);\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, coordinateSpace },\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, transform);\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(\n\ttextNode: Text,\n\trects: readonly Rect2D[],\n\ttransform: EditorCoordinateTransform,\n): 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 = transform.toLocalRect(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: Rect2D, 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 has no source (no per-offset geometry), so a hit on it snaps to the\n * nearer edge rather than fabricating positions inside its interior source.\n */\nfunction _appendElementBlockRun(\n\trawRuns: VisualRun[],\n\tviewNode: ViewNode,\n\tabsoluteStart: number,\n\ttransform: EditorCoordinateTransform,\n): void {\n\tconst dom = viewNode.dom;\n\tif (dom.nodeType !== 1 /* ELEMENT_NODE */) { return; }\n\tconst clientRect = (dom as Element).getBoundingClientRect();\n\tif (clientRect.width === 0 && clientRect.height === 0) { return; }\n\tconst rect = transform.toLocalRect(clientRect);\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 { Rect2D } from '../core/geometry.js';\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 * Geometry is in editor-local CSS pixels. `height` 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 /** Local border box when mounted and measured. */\n readonly rect: Rect2D | undefined;\n /** Local horizontal padding-box clip when this block scrolls horizontally. */\n readonly viewportClip: { readonly left: number; readonly right: number } | undefined;\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. Every per-block\n * map uses the same editor-local coordinate space, so concatenation is\n * well-formed without translation or 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 'unhandledBlock':\n // The raw `content` marker is real, always-visible text (not\n // hideable markup), so it contributes no marker ranges.\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. For an element hit — an element-only node\n * (KaTeX math, `<hr>`, an image, a hidden marker) or a wrapper/container\n * element — the platform reports a child-index offset, not a text caret, so\n * there is no internal mapping to honour: it snaps to the node's nearer\n * edge, `offset 0` (the \"before\" side) → start, any `offset >= 1` (the\n * \"after\" side) → end. Subclasses may override for finer control.\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(pos.offset >= 1 ? this.sourceLength : 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 { StringEdit, StringReplacement } from '../../core/stringEdit.js';\nimport type {\n\tAnyViewData, CodeBlockViewData, DiffDecorationViewData, DiffHighlightRange, DiffHunkViewData, DiffSideViewData, GlueViewData, HeadingViewData, ImageViewData,\n\tInlineCodeViewData, InlineMathViewData, LinkViewData, ListViewData, ListItemViewData,\n\tMarkerViewData, MathBlockViewData, TableRowViewData, TableViewData, TextViewData, ThematicBreakViewData, UnhandledBlockViewData,\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). Return `false` to use the anchor's native\n\t * navigation behavior.\n\t */\n\treadonly onOpenLink?: (url: string, event: MouseEvent) => false | 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\t/**\n\t * Pluggable factory for an in-place, interactive editor that replaces the\n\t * *rendered* (inactive) form of a fenced code block — see\n\t * {@link IEmbeddedCodeEditor}. When it returns an editor for the block's\n\t * language, that editor's element is mounted instead of the highlighted\n\t * code, and content flows both ways as string edits. Returning `undefined`\n\t * falls back to the default rendering. EXPERIMENTAL.\n\t */\n\treadonly embeddedCodeEditorFactory?: IEmbeddedCodeEditorFactory;\n\n\t/**\n\t * Called when an {@link IEmbeddedCodeEditor} edits its content. `contentEdit`\n\t * is in the block's *content* coordinates; the host translates it to a\n\t * document edit (via {@link CodeBlockAstNode.codeOffset} and the block's\n\t * offset) and applies it to the model.\n\t */\n\treadonly onEmbeddedCodeEditorEdit?: (block: CodeBlockAstNode, contentEdit: StringEdit) => void;\n}\n\n/**\n * A live editor embedded in place of a fenced code block's *rendered* form.\n *\n * This is the internal seam between the block view and a concrete embedded\n * editor (e.g. an `<iframe>` speaking the web-editor protocol). The block view\n * only speaks string edits: it pushes the block's content down via\n * {@link setContent} and receives the editor's own changes back through\n * {@link onEdit} (set by the block view on each (re)construction, so it always\n * routes to the current AST node). The concrete implementation owns its DOM,\n * transport, and lifecycle.\n *\n * A single instance is adopted across re-renders (like the highlighter session)\n * so the underlying editor keeps its state across edits — see\n * {@link CodeBlockViewNode}.\n */\nexport interface IEmbeddedCodeEditor {\n\t/** The element mounted as the block's rendered form. */\n\treadonly element: HTMLElement;\n\t/**\n\t * Document → editor. The block's content changed (from any source). Must be\n\t * idempotent: pushing the content the editor already holds is a no-op, which\n\t * is how edits the editor itself originated are prevented from echoing back.\n\t */\n\tsetContent(content: string): void;\n\t/**\n\t * Optional synchronous height (px) to reserve for `content` *before* the\n\t * editor has laid out. Return `undefined` to let the editor size itself\n\t * (the implementation may report its real height later). Lets a registration\n\t * avoid a layout jump when it can cheaply estimate the size from content.\n\t */\n\testimateHeight?(content: string): number | undefined;\n\t/**\n\t * Editor → document. Set by the block view on every (re)construction to\n\t * route the editor's own edits, expressed in the block's *content*\n\t * coordinates, to the current AST node.\n\t */\n\tonEdit?: (edit: StringEdit) => void;\n\tdispose(): void;\n}\n\n/** Creates an {@link IEmbeddedCodeEditor} for a fenced block, or opts out. */\nexport interface IEmbeddedCodeEditorFactory {\n\t/**\n\t * Return an editor for a fenced block of `language`, or `undefined` to fall\n\t * back to the default (highlighting / {@link BlockViewOptions.renderCustomCodeBlock}).\n\t */\n\tcreate(language: string, initialContent: string): IEmbeddedCodeEditor | 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 * The horizontal scroll viewport for selection/caret clipping\n\t * ({@link blockViewportClip}). For most blocks the scroller *is*\n\t * {@link element} — a code / math / unhandled block's `element` is the very\n\t * `overflow-x: auto` box that scrolls. A table is the exception: its\n\t * `element` stays the inner `<table>` (so the active/markers classes and\n\t * `.md-table` theme styling are unaffected), but the box that actually\n\t * scrolls is the wrapping `.md-table-wrapper`, so {@link TableViewNode}\n\t * overrides this to return that wrapper.\n\t */\n\tget scrollElement(): HTMLElement { return this.element; }\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 'unhandledBlock': return new UnhandledBlockViewNode(data, options, _prev(previous, UnhandledBlockViewNode));\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 TableViewNode(data, options, _prev(previous, TableViewNode));\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\tcase 'diffHunk': return new DiffHunkViewNode(data, options, _prev(previous, DiffHunkViewNode));\n\t\tcase 'diffDecoration': return new DiffDecorationViewNode(data, options, _prev(previous, DiffDecorationViewNode));\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/**\n * Renders a {@link DiffHunkViewData}: the original block stacked over the\n * modified block (either side optional). Each side is a normal block view node\n * — the same renderers the editor uses — wrapped in a container and tagged with\n * `md-diff-original` / `md-diff-modified` so CSS can tint it. The per-side\n * word-level highlight {@link DiffHunkViewNode.sides ranges} are painted\n * separately (via the CSS Custom Highlight API) by the diff view.\n */\nexport class DiffHunkViewNode extends BlockViewNode<DiffHunkViewData> {\n\tprivate readonly _originalNode?: ViewNode;\n\tprivate readonly _modifiedNode?: ViewNode;\n\n\tconstructor(data: DiffHunkViewData, options: BlockViewOptions | undefined, previous?: DiffHunkViewNode) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\twrapper.className = 'md-block md-diff-hunk';\n\n\t\tconst children: ViewNode[] = [];\n\t\tconst mounts: globalThis.Node[] = [];\n\t\tconst original = data.original\n\t\t\t? _buildDiffSide(data.original, 'md-diff-original', options, previous?._originalNode)\n\t\t\t: undefined;\n\t\tconst modified = data.modified\n\t\t\t? _buildDiffSide(data.modified, 'md-diff-modified', options, previous?._modifiedNode)\n\t\t\t: undefined;\n\t\tif (original) { children.push(original); mounts.push(original.mountNode); }\n\t\tif (modified) { children.push(modified); mounts.push(modified.mountNode); }\n\t\t_patchDomNodes(wrapper, mounts);\n\n\t\tsuper(data, wrapper, children);\n\t\tthis._originalNode = original;\n\t\tthis._modifiedNode = modified;\n\t}\n\n\t/** The mounted sides with their highlight ranges, for the diff highlighter. */\n\tget sides(): readonly { readonly node: ViewNode; readonly ranges: readonly DiffHighlightRange[] }[] {\n\t\tconst out: { node: ViewNode; ranges: readonly DiffHighlightRange[] }[] = [];\n\t\tif (this._originalNode && this.data.original) { out.push({ node: this._originalNode, ranges: this.data.original.ranges }); }\n\t\tif (this._modifiedNode && this.data.modified) { out.push({ node: this._modifiedNode, ranges: this.data.modified.ranges }); }\n\t\treturn out;\n\t}\n}\n\nfunction _buildDiffSide(side: DiffSideViewData, cls: string, options: BlockViewOptions | undefined, prev: ViewNode | undefined): ViewNode {\n\tconst node = createViewNode(side.view, options, prev);\n\tconst el = (node as BlockViewNode).element;\n\tel.classList.add(cls);\n\tel.classList.toggle('md-block-active', side.active);\n\tel.classList.toggle('md-markers-hidden', !side.active);\n\treturn node;\n}\n\n/**\n * Renders a {@link DiffDecorationViewData}: a read-only original block shown\n * (red) above its place in the modified document. It is `pointer-events: none`\n * and reports {@link sourceLength} `0`, so it occupies vertical space like a\n * view-zone but is invisible to the editor's source mapping, selection, and\n * measurement (it is never added to the document's `blocks`).\n */\nexport class DiffDecorationViewNode extends BlockViewNode<DiffDecorationViewData> {\n\treadonly sideNode: ViewNode;\n\n\tconstructor(data: DiffDecorationViewData, options: BlockViewOptions | undefined, previous?: DiffDecorationViewNode) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\twrapper.className = 'md-block md-diff-decoration';\n\t\twrapper.style.pointerEvents = 'none';\n\t\tconst sideNode = createViewNode(data.side, options, previous?.sideNode);\n\t\tconst el = (sideNode as BlockViewNode).element;\n\t\t// Partial change: active/source form (markers visible) so marker-level\n\t\t// modifications show. Whole removal: rendered form (clean solid band).\n\t\tconst active = !data.whole;\n\t\tel.classList.add(data.whole ? 'md-diff-removed' : 'md-diff-original');\n\t\tel.classList.toggle('md-block-active', active);\n\t\tel.classList.toggle('md-markers-hidden', !active);\n\t\t_patchDomNodes(wrapper, [sideNode.mountNode]);\n\t\tsuper(data, wrapper, [sideNode]);\n\t\tthis.sideNode = sideNode;\n\t}\n\n\t/** A decoration has no presence in the modified document's source space. */\n\toverride get sourceLength(): number { return 0; }\n\n\t/** True when the whole block was removed (solid band, no word-level rects). */\n\tget whole(): boolean { return this.data.whole; }\n\n\t/** Absolute offset of this block in the *original* document. */\n\tget originalStart(): number { return this.data.originalStart; }\n\n\tget deletedRanges(): readonly DiffHighlightRange[] { return this.data.deletedRanges; }\n}\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 source-less run (no per-offset geometry). When active it reveals the\n * 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 *\n * The inactive `<hr>` is wrapped in a `<div>` that becomes this node's\n * registered {@link dom} (and the node the parent mounts). A bare `<hr>` is a\n * void element the platform hit-test (`caretPositionFromPoint`) cannot place a\n * caret inside — a click on it resolves to the surrounding flow instead. The\n * wrapping block `<div>` gives the hit-test a caret-positionable box that maps\n * back to this break. {@link element} stays the `<hr>` so the block's\n * active/markers classes and rule styling are unaffected.\n */\nclass ThematicBreakViewNode extends BlockViewNode<ThematicBreakViewData> {\n\tprivate readonly _contentEl: HTMLElement;\n\n\tconstructor(data: ThematicBreakViewData, options: BlockViewOptions | undefined, previous: ThematicBreakViewNode | undefined) {\n\t\tif (data.showMarkup) {\n\t\t\t// Reuse only a previous *active* node's div: an inactive node's `dom`\n\t\t\t// is the wrapper div, but its children/structure are different.\n\t\t\tconst reuse = previous?.data.showMarkup ? previous : undefined;\n\t\t\tconst el = (reuse?.dom as HTMLElement | undefined) ?? 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\tthis._contentEl = el;\n\t\t\treturn;\n\t\t}\n\t\tconst wrapper = document.createElement('div');\n\t\twrapper.className = 'md-block md-thematic-break-wrapper';\n\t\tconst hr = document.createElement('hr');\n\t\thr.className = 'md-block md-thematic-break';\n\t\twrapper.appendChild(hr);\n\t\tsuper(data, wrapper, _NO_CHILDREN);\n\t\tthis._contentEl = hr;\n\t}\n\n\toverride get element(): HTMLElement { return this._contentEl; }\n}\n\n/**\n * An {@link UnhandledBlockViewData unhandled block}: a construct the parser does\n * not model (a setext heading, a frontmatter fence, an extension token). It has\n * no active/inactive split — the verbatim source is always shown — so it renders\n * like a code block (`<pre><code>` with the raw text as a single leaf) but\n * carries an `md-unhandled-block` class so the theme can style it distinctly.\n * The raw `content` marker tiles the block's full span, keeping source ↔ DOM\n * mapping exact; the text stays selectable and editable.\n *\n * The scrolling `<pre>` is wrapped in a non-scrolling `<div>` that owns the\n * border. {@link element} is the inner `<pre>` — the real scroll viewport — so\n * the selection/caret clipping measures the right box.\n */\nclass UnhandledBlockViewNode extends BlockViewNode<UnhandledBlockViewData> {\n\tprivate readonly _scroller: HTMLElement;\n\n\tconstructor(data: UnhandledBlockViewData, options: BlockViewOptions | undefined, previous: UnhandledBlockViewNode | undefined) {\n\t\tconst reuse = previous && previous.dom instanceof HTMLDivElement ? previous : undefined;\n\t\tconst wrapper = (reuse?.dom as HTMLDivElement | undefined) ?? document.createElement('div');\n\t\tif (!reuse) { wrapper.className = 'md-block md-unhandled-block'; }\n\t\tconst pre = reuse?._scroller ?? document.createElement('pre');\n\t\tif (!reuse) {\n\t\t\tpre.className = 'md-code-block md-unhandled-scroll';\n\t\t\twrapper.appendChild(pre);\n\t\t}\n\t\tconst code = (reuse ? pre.querySelector('code') : null) ?? document.createElement('code');\n\t\tif (!reuse) { pre.appendChild(code); }\n\t\tconst kids = reconcileDomChildren(code, data.content, reuse?.children, (childData, prev) => {\n\t\t\tconst childAst = childData.ast;\n\t\t\tif (childData.kind === 'marker' && (childAst as MarkerAstNode).markerKind === 'content') {\n\t\t\t\tconst prevText = prev instanceof RawLeafViewNode && prev.dom.nodeType === globalThis.Node.TEXT_NODE\n\t\t\t\t\t&& (prev.dom as Text).data === (childAst as MarkerAstNode).content ? prev.dom : undefined;\n\t\t\t\tconst text = prevText ?? document.createTextNode((childAst as MarkerAstNode).content);\n\t\t\t\treturn new RawLeafViewNode(childAst, text);\n\t\t\t}\n\t\t\treturn createViewNode(childData, options, prev);\n\t\t});\n\t\tsuper(data, wrapper, kids);\n\t\tthis._scroller = pre;\n\t}\n\n\toverride get element(): HTMLElement { return this._scroller; }\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\t/**\n\t * An in-place interactive editor (e.g. an iframe) mounted instead of the\n\t * rendered code. Like {@link _session} it is adopted from `previous` across\n\t * rebuilds so the underlying editor keeps its state, and must be disposed\n\t * manually (a node reused as `previous` is never {@link dispose}d).\n\t */\n\tprivate _embeddedEditor: IEmbeddedCodeEditor | 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 prevCode = previous instanceof CodeBlockViewNode ? previous : undefined;\n\n\t\t// The `content` marker includes the newline after the open fence and the\n\t\t// newline before the close fence (see parser). An embedded editor must only\n\t\t// see the inner code — otherwise its first/last line would edit those\n\t\t// separators and corrupt the fences — so strip them and remember the leading\n\t\t// length to shift the editor's edits back into code-marker coordinates.\n\t\tconst embeddedLeading = content.startsWith('\\n') ? 1 : 0;\n\t\tconst embeddedTrailing = content.endsWith('\\n') ? 1 : 0;\n\t\tconst embeddedContent = content.slice(embeddedLeading, content.length - embeddedTrailing);\n\n\t\t// Embedded editor: adopt `previous`'s editor when the block is the same\n\t\t// node or an in-content edit links them (getDiff), so the editor keeps\n\t\t// its state across edits; otherwise create a fresh one. Takes precedence\n\t\t// over the custom renderer and highlighting. Any editor on `previous` we\n\t\t// do not adopt is disposed below.\n\t\tlet embedded: IEmbeddedCodeEditor | undefined;\n\t\tif (!data.showMarkup && ast.language && options?.embeddedCodeEditorFactory) {\n\t\t\tif (prevCode?._embeddedEditor && (ast === prevCode.ast || ast.getDiff(prevCode.ast as CodeBlockAstNode))) {\n\t\t\t\tembedded = prevCode._embeddedEditor;\n\t\t\t\tprevCode._embeddedEditor = undefined;\n\t\t\t} else {\n\t\t\t\tembedded = options.embeddedCodeEditorFactory.create(ast.language, embeddedContent) ?? undefined;\n\t\t\t}\n\t\t}\n\t\tif (prevCode?._embeddedEditor) { prevCode._embeddedEditor.dispose(); prevCode._embeddedEditor = undefined; }\n\n\t\tconst custom = (!embedded && !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\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 (!embedded && !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 (embedded) {\n\t\t\t// Push current content down (idempotent — the editor drops content it\n\t\t\t// already holds, so its own edits don't echo back) and route its\n\t\t\t// edits to the current AST node. Reserve a synchronous height estimate\n\t\t\t// so the layout doesn't jump before the editor measures itself.\n\t\t\tembedded.element.classList.add('md-block', 'md-code-block');\n\t\t\tconst estimated = embedded.estimateHeight?.(embeddedContent);\n\t\t\tif (estimated !== undefined) {\n\t\t\t\tembedded.element.style.boxSizing = 'border-box';\n\t\t\t\tembedded.element.style.minHeight = `${estimated}px`;\n\t\t\t}\n\t\t\t// Shift the editor's (inner-content) edit back over the stripped leading\n\t\t\t// newline so it lands in code-marker coordinates, leaving the fence\n\t\t\t// separators untouched.\n\t\t\tembedded.onEdit = (edit) => {\n\t\t\t\tconst shifted = embeddedLeading === 0 ? edit : new StringEdit(\n\t\t\t\t\tedit.replacements.map((r) => StringReplacement.replace(r.replaceRange.delta(embeddedLeading), r.newText)),\n\t\t\t\t);\n\t\t\t\toptions?.onEmbeddedCodeEditorEdit?.(ast, shifted);\n\t\t\t};\n\t\t\tembedded.setContent(embeddedContent);\n\t\t\tdom = embedded.element;\n\t\t\tchildren = _NO_CHILDREN;\n\t\t} else if (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\tthis._embeddedEditor = embedded;\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\tthis._embeddedEditor?.dispose();\n\t\tthis._embeddedEditor = 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`. The class is toggled on\n * every reconciliation because the underlying `<td>` is intentionally reused.\n */\n/**\n * A GFM table. The `<table>` is wrapped in a `<div>` that becomes this node's\n * registered {@link dom} (and the node the parent mounts), so a click on the\n * table's borders or padding — areas the platform hit-test\n * (`caretPositionFromPoint`) does not place a caret inside a `<table>` — lands\n * on a caret-positionable box that maps back to this table rather than the\n * surrounding flow. The cells themselves are their own view nodes, so clicks on\n * cell text still resolve precisely. {@link element} stays the `<table>` so the\n * block's active/markers classes and the `.md-table` theme styling are\n * unaffected, and the row children are reconciled into it. The wrapper is also\n * the horizontal scroll viewport (`overflow-x: auto`), so a wide table scrolls\n * table-locally instead of overflowing the page and scrolling the editor gutter\n * away; {@link scrollElement} returns it so the selection/caret clipping\n * ({@link blockViewportClip}) measures that scroll box rather than the\n * content-sized `<table>`.\n */\nclass TableViewNode extends BlockViewNode<TableViewData> {\n\tprivate readonly _table: HTMLElement;\n\n\tconstructor(data: TableViewData, options: BlockViewOptions | undefined, previous: TableViewNode | undefined) {\n\t\tconst wrapper = (previous?.dom as HTMLElement | undefined) ?? document.createElement('div');\n\t\tconst table = previous?._table ?? document.createElement('table');\n\t\tif (!previous) {\n\t\t\twrapper.className = 'md-block md-table-wrapper';\n\t\t\ttable.className = 'md-block md-table';\n\t\t\twrapper.appendChild(table);\n\t\t}\n\t\tconst children = reconcileDomChildren(table, _contentOf(data), previous?.children, _buildChild(options));\n\t\tsuper(data, wrapper, children);\n\t\tthis._table = table;\n\t}\n\n\toverride get element(): HTMLElement { return this._table; }\n\n\toverride get scrollElement(): HTMLElement { return this.dom as HTMLElement; }\n}\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') {\n\t\t\t\t\t(children[i] as BlockViewNode).element.classList.toggle('md-table-cell-active', cellData.isActive);\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 click\n\t\t// can place the caret to edit. Middle-click always opens.\n\t\tif (!previous) {\n\t\t\tconst shouldOpen = (e: MouseEvent): boolean => {\n\t\t\t\tif (!a.dataset.mdUrl) { return false; }\n\t\t\t\t// Only primary (open/place caret) and middle (always open) buttons.\n\t\t\t\tif (e.button !== 0 && e.button !== 1) { return false; }\n\t\t\t\tif (e.button === 1) { return true; }\n\t\t\t\tconst blockActive = a.closest('.md-block-active') !== null;\n\t\t\t\treturn !blockActive || e.ctrlKey || e.metaKey;\n\t\t\t};\n\t\t\tconst openLink = (e: MouseEvent): boolean => {\n\t\t\t\tconst url = a.dataset.mdUrl;\n\t\t\t\tif (!url) { return true; }\n\t\t\t\tconst onOpenLink = options?.onOpenLink;\n\t\t\t\tif (!onOpenLink) {\n\t\t\t\t\twindow.open(url, '_blank', 'noopener');\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn onOpenLink(url, e) !== false;\n\t\t\t};\n\t\t\t// The open is decided on `pointerdown`, while the block still reflects its\n\t\t\t// pre-click state and before the controller (which also acts on\n\t\t\t// `pointerdown`) can place the caret; `stopPropagation()` suppresses that\n\t\t\t// caret move. Crucially we do NOT `preventDefault()`: the click must still\n\t\t\t// focus the host frame, because a webview only opens the link once its\n\t\t\t// surrounding window is active (the Markdown preview focuses on click too).\n\t\t\t// The following `click`/`auxclick` then only cancels the anchor's native\n\t\t\t// navigation.\n\t\t\tlet pointerDownResult: 'none' | 'handled' | 'native' = 'none';\n\t\t\ta.addEventListener('pointerdown', (e) => {\n\t\t\t\tpointerDownResult = 'none';\n\t\t\t\tif (!shouldOpen(e)) { return; }\n\t\t\t\te.stopPropagation();\n\t\t\t\tpointerDownResult = openLink(e) ? 'handled' : 'native';\n\t\t\t});\n\t\t\tconst onClick = (e: MouseEvent): void => {\n\t\t\t\tconst result = pointerDownResult;\n\t\t\t\tpointerDownResult = 'none';\n\t\t\t\tif (result === 'native') {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result === 'handled') {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!shouldOpen(e)) { return; }\n\t\t\t\tif (openLink(e)) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t}\n\t\t\t};\n\t\t\ta.addEventListener('click', onClick);\n\t\t\ta.addEventListener('auxclick', onClick);\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 contentDomNode.classList.add('md-document');\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 // Green band on a changed modified block (diff mode); no-op otherwise.\n const diffKind = viewData.children[i].diffKind;\n (node as BlockViewNode).element.classList.toggle('md-diff-added', diffKind === 'added');\n (node as BlockViewNode).element.classList.toggle('md-diff-modified', diffKind === 'modified');\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","import { Point2D, Rect2D } from '../core/geometry.js';\n\nconst MATRIX_EPSILON = 1e-7;\n\n/**\n * The editor overlay's local CSS-pixel coordinate space.\n *\n * Browser geometry and pointer APIs expose viewport client coordinates. This\n * boundary converts them immediately into the coordinate system shared by the\n * editor content and its overlays. Range rectangles are axis-aligned, so the\n * current implementation deliberately supports positive axis-aligned scale and\n * translation only.\n */\nexport class EditorCoordinateSpace {\n\tstatic forSvgOverlay(overlay: SVGSVGElement): EditorCoordinateSpace {\n\t\treturn new EditorCoordinateSpace(() => {\n\t\t\t// EditorView performs an initial render before callers mount its root.\n\t\t\t// There is no client coordinate space while detached, so measurements\n\t\t\t// are already local. Mounting changes the observed content size and\n\t\t\t// triggers the normal measured-layout refresh.\n\t\t\tif (!overlay.isConnected) { return new DOMMatrix(); }\n\t\t\tconst matrix = overlay.getScreenCTM();\n\t\t\tif (!matrix) {\n\t\t\t\tthrow new Error('Cannot resolve editor coordinates before the overlay is mounted');\n\t\t\t}\n\t\t\treturn matrix;\n\t\t});\n\t}\n\n\tprivate constructor(private readonly _getLocalToClientMatrix: () => DOMMatrix) { }\n\n\tcapture(): EditorCoordinateTransform {\n\t\tconst localToClient = this._getLocalToClientMatrix();\n\t\tif (localToClient.is2D === false\n\t\t\t|| Math.abs(localToClient.b) > MATRIX_EPSILON\n\t\t\t|| Math.abs(localToClient.c) > MATRIX_EPSILON\n\t\t\t|| localToClient.a <= MATRIX_EPSILON\n\t\t\t|| localToClient.d <= MATRIX_EPSILON) {\n\t\t\tthrow new Error('Markdown editor geometry supports positive axis-aligned scale and translation only');\n\t\t}\n\t\treturn new EditorCoordinateTransform(localToClient);\n\t}\n}\n\n/** A stable coordinate conversion captured for one measurement operation. */\nexport class EditorCoordinateTransform {\n\tprivate readonly _clientToLocal: DOMMatrix;\n\n\tconstructor(private readonly _localToClient: DOMMatrix) {\n\t\tthis._clientToLocal = _localToClient.inverse();\n\t}\n\n\ttoLocalPoint(point: Pick<Point2D, 'x' | 'y'>): Point2D {\n\t\tconst local = new DOMPoint(point.x, point.y).matrixTransform(this._clientToLocal);\n\t\treturn new Point2D(local.x, local.y);\n\t}\n\n\ttoClientPoint(point: Pick<Point2D, 'x' | 'y'>): Point2D {\n\t\tconst client = new DOMPoint(point.x, point.y).matrixTransform(this._localToClient);\n\t\treturn new Point2D(client.x, client.y);\n\t}\n\n\ttoLocalRect(rect: Pick<DOMRectReadOnly, 'left' | 'top' | 'width' | 'height'>): Rect2D {\n\t\treturn this._convertRect(rect, this._clientToLocal);\n\t}\n\n\ttoClientRect(rect: Pick<Rect2D, 'left' | 'top' | 'width' | 'height'>): Rect2D {\n\t\treturn this._convertRect(rect, this._localToClient);\n\t}\n\n\tprivate _convertRect(\n\t\trect: Pick<DOMRectReadOnly, 'left' | 'top' | 'width' | 'height'>,\n\t\tmatrix: DOMMatrix,\n\t): Rect2D {\n\t\tconst topLeft = new DOMPoint(rect.left, rect.top).matrixTransform(matrix);\n\t\tconst bottomRight = new DOMPoint(rect.left + rect.width, rect.top + rect.height).matrixTransform(matrix);\n\t\treturn Rect2D.fromPointPoint(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);\n\t}\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 type { DiffItem, NestedItem, RemovedItem } from '../diff/diffItem.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, UnhandledBlockAstNode,\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, the\n * transient empty paragraph (see {@link PendingParagraphViewData}), or a\n * {@link DiffHunkViewData diff hunk} (stacked original/modified blocks). */\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 | DiffHunkViewData | DiffDecorationViewData;\n\treadonly kind: 'block' | 'glue' | 'pendingParagraph' | 'diffHunk' | 'diffDecoration';\n\t/**\n\t * Diff mode: how this (modified) block changed. `added` = a whole new block\n\t * (strong green band, no inline rects); `modified` = a partial change (light\n\t * band + inline rects on the changed words).\n\t */\n\treadonly diffKind?: 'added' | 'modified';\n}\n\n// ---------------------------------------------------------------------------\n// Blocks\n// ---------------------------------------------------------------------------\n\nexport type BlockViewData =\n\t| HeadingViewData | ParagraphViewData | CodeBlockViewData | MathBlockViewData\n\t| ThematicBreakViewData | BlockQuoteViewData | ListViewData | TableViewData | UnhandledBlockViewData;\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\n/**\n * View-data for an {@link UnhandledBlockAstNode}. It has no active/inactive\n * split — the raw source *is* both the source and the rendered form — so it\n * carries no `showMarkup` flag; the renderer always shows the verbatim text.\n */\nexport class UnhandledBlockViewData {\n\treadonly kind = 'unhandledBlock';\n\tconstructor(readonly ast: UnhandledBlockAstNode, readonly content: readonly AnyViewData[]) { }\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\n/** A word/character highlight inside one diff side, in block-local coords. */\nexport interface DiffHighlightRange {\n\treadonly range: OffsetRange;\n\treadonly kind: 'inserted' | 'deleted';\n}\n\n/** One side (original or modified) of a {@link DiffHunkViewData}. */\nexport interface DiffSideViewData {\n\treadonly view: BlockViewData;\n\t/** Render in active form (markers/whitespace visible). */\n\treadonly active: boolean;\n\treadonly ranges: readonly DiffHighlightRange[];\n}\n\n/**\n * A changed block rendered as its original form stacked over its modified form\n * (either side may be absent for a pure deletion/insertion). It is itself a\n * document child the renderer mounts like a block; its {@link ast} is the\n * surviving side's ast, used only for view-node identity/reuse.\n */\nexport class DiffHunkViewData {\n\treadonly kind = 'diffHunk';\n\tconstructor(\n\t\treadonly ast: AstNode,\n\t\treadonly original: DiffSideViewData | undefined,\n\t\treadonly modified: DiffSideViewData | undefined,\n\t) { }\n}\n\n/**\n * A read-only \"removed\" decoration: an original block rendered (red) above its\n * place in the modified document, occupying vertical space like a view-zone but\n * contributing **zero** source length, so the editor's source mapping stays the\n * modified document and editing is unaffected. Used for `removed` and the\n * original side of a `replaced` block in editor diff mode.\n */\nexport class DiffDecorationViewData {\n\treadonly kind = 'diffDecoration';\n\tconstructor(\n\t\treadonly ast: AstNode,\n\t\treadonly side: BlockViewData,\n\t\treadonly deletedRanges: readonly DiffHighlightRange[],\n\t\t/** True when the whole block was removed: solid red band, no word rects. */\n\t\treadonly whole: boolean,\n\t\t/** Absolute offset of this block in the *original* document. */\n\t\treadonly originalStart: number,\n\t) { }\n}\n\nexport type AnyViewData =\n\t| DocumentViewData | BlockViewData | InlineViewData\n\t| ListItemViewData | TableRowViewData | TableCellViewData\n\t| MarkerViewData | GlueViewData | DiffHunkViewData | DiffDecorationViewData;\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\t// A block can be active without the selection intersecting it (diff\n\t\t\t\t// mode forces changed blocks active to reveal markers), so only\n\t\t\t\t// compute an in-node selection when the ranges actually overlap.\n\t\t\t\tconst selectionInNode = selectionRange\n\t\t\t\t\t&& selectionRange.endExclusive >= pos && selectionRange.start <= pos + block.length\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 a single block in isolation, used by the diff\n * renderer to render the two sides of a {@link DiffHunkViewData}. `active`\n * selects the source/markers-visible form (used for changed blocks so edits to\n * markup and whitespace are visible); inactive is the normal rendered form.\n */\nexport function buildBlockViewData(block: AstNode, active: boolean, previous?: AnyViewData): BlockViewData {\n\tconst ctx: BuildCtx = active\n\t\t? { showMarkup: true, showTableGlue: false, selectionInNode: undefined }\n\t\t: _INACTIVE;\n\treturn _buildBlock(block as BlockAstNode, ctx, previous);\n}\n\n/**\n * Build the document view-data for a diff, rendered through the *normal* editor\n * pipeline so the modified blocks remain the real, editable blocks. It reuses\n * {@link buildDocumentViewData} for the modified document (correct glue, active\n * handling, measurement) and then inserts read-only {@link DiffDecorationViewData}\n * children for removed blocks and the original side of replaced blocks. The\n * decorations carry zero source length, so the editor's offset space is exactly\n * the modified document and editing/cursor are unaffected.\n */\n/**\n * Overlay diff decorations onto an already-built document view-data.\n *\n * `base` is the normal {@link buildDocumentViewData} result for the modified\n * document (so it is built with the usual glue / active handling / measurement\n * *and* the per-frame identity reuse, which keeps editing smooth). This inserts\n * read-only {@link DiffDecorationViewData} children for removed blocks and the\n * original side of replaced blocks, and tags changed modified blocks so they\n * get the green band. Decorations carry zero source length, so the editor's\n * offset space is exactly the modified document and editing/cursor are\n * unaffected.\n */\nexport function applyDiffDecorations(base: DocumentViewData, diffItems: readonly DiffItem[], decorationsActive = false): DocumentViewData {\n\t// Index diff items by their modified-side block; collect removed originals to\n\t// insert before the block they precede (the next non-removed item).\n\tconst overlay = new Map<AstNode, DiffItem>();\n\tconst removedBefore = new Map<AstNode, RemovedItem[]>();\n\tlet pending: RemovedItem[] = [];\n\tfor (const item of diffItems) {\n\t\tif (item.kind === 'removed') { pending.push(item); continue; }\n\t\tconst modAst = _diffModifiedAst(item);\n\t\tif (modAst) {\n\t\t\tif (pending.length) { removedBefore.set(modAst, pending); pending = []; }\n\t\t\toverlay.set(modAst, item);\n\t\t}\n\t}\n\tconst removedAtEnd = pending;\n\n\tconst children: DocumentChildViewData[] = [];\n\tconst blocks: DocumentBlockViewData[] = [];\n\tfor (const child of base.children) {\n\t\tif (child.kind !== 'block') { children.push(child); continue; }\n\t\tconst blockView = child.view as BlockViewData;\n\t\tfor (const rem of removedBefore.get(blockView.ast) ?? []) {\n\t\t\tchildren.push(_decorationChild(rem.node, rem.deletedLocal, child.absoluteStart, true, rem.originalStart, decorationsActive));\n\t\t}\n\t\tconst item = overlay.get(blockView.ast);\n\t\t// Only show the red original when content was actually deleted. A pure\n\t\t// insertion (e.g. a trailing blank line added before a new block) renders\n\t\t// as the active modified block with a green highlight — no red duplicate.\n\t\tif (item && item.kind === 'replaced' && item.deletedLocal.length > 0) {\n\t\t\tchildren.push(_decorationChild(item.original, item.deletedLocal, child.absoluteStart, false, item.originalStart, decorationsActive));\n\t\t}\n\t\t// A changed container renders once, editable, with red decorations woven\n\t\t// in next to its changed/removed children (recursively).\n\t\tconst view = item && item.kind === 'nested' ? decorateContainer(blockView, item, decorationsActive) : blockView;\n\t\tconst diffKind = item?.kind === 'added' ? 'added' as const : item?.kind === 'replaced' ? 'modified' as const : undefined;\n\t\tconst outChild: DocumentChildViewData = diffKind ? { ...child, diffKind } : view !== blockView ? { ...child, view } : child;\n\t\tchildren.push(outChild);\n\t\tblocks.push({ ast: blockView.ast, absoluteStart: child.absoluteStart, isActive: child.isActive, view });\n\t}\n\tfor (const rem of removedAtEnd) {\n\t\tchildren.push(_decorationChild(rem.node, rem.deletedLocal, base.ast.length, true, rem.originalStart, decorationsActive));\n\t}\n\treturn new DocumentViewData(base.ast, blocks, children);\n}\n\nfunction _decorationChild(originalBlock: AstNode, deletedRanges: readonly DiffHighlightRange[], absoluteStart: number, whole: boolean, originalStart: number, forceActive: boolean): DocumentChildViewData {\n\treturn {\n\t\tabsoluteStart,\n\t\tisActive: false,\n\t\tview: _decoration(originalBlock, deletedRanges, whole, originalStart, forceActive),\n\t\tkind: 'diffDecoration',\n\t};\n}\n\n/**\n * Build the read-only original-side decoration for a removed/replaced block.\n * Partial change (`whole=false`): active/source form so marker changes show.\n * Whole removal (`whole=true`): rendered form (clean solid band) unless\n * `forceActive` (the coverage test renders every original char as source).\n */\nfunction _decoration(originalBlock: AstNode, deletedRanges: readonly DiffHighlightRange[], whole: boolean, originalStart: number, forceActive: boolean): DiffDecorationViewData {\n\treturn new DiffDecorationViewData(originalBlock, buildBlockViewData(originalBlock, forceActive || !whole), deletedRanges, whole, originalStart);\n}\n\n/**\n * Recursively overlay decorations *inside* a changed container (list, table,\n * blockquote): the modified container still renders once and editable, with a\n * read-only red {@link DiffDecorationViewData} woven in next to each changed or\n * removed child — and recursing again for a nested child container. Mirrors the\n * document-level overlay but in the container's `content` array; decorations\n * carry zero source length, so the modified offset space is unchanged.\n */\nfunction decorateContainer(container: BlockViewData, item: NestedItem, decorationsActive: boolean): BlockViewData {\n\tconst overlay = new Map<AstNode, DiffItem>();\n\tconst removedBefore = new Map<AstNode, RemovedItem[]>();\n\tlet pending: RemovedItem[] = [];\n\tfor (const c of item.children) {\n\t\tif (c.kind === 'removed') { pending.push(c); continue; }\n\t\tconst modAst = _diffModifiedAst(c);\n\t\tif (modAst) {\n\t\t\tif (pending.length) { removedBefore.set(modAst, pending); pending = []; }\n\t\t\toverlay.set(modAst, c);\n\t\t}\n\t}\n\tconst content = (container as unknown as { content?: readonly AnyViewData[] }).content ?? [];\n\tconst newContent: AnyViewData[] = [];\n\tfor (const cvd of content) {\n\t\tfor (const rem of removedBefore.get(cvd.ast) ?? []) {\n\t\t\tnewContent.push(_decoration(rem.node, rem.deletedLocal, true, rem.originalStart, decorationsActive));\n\t\t}\n\t\tconst c = overlay.get(cvd.ast);\n\t\tif (c && c.kind === 'replaced' && c.deletedLocal.length > 0) {\n\t\t\tnewContent.push(_decoration(c.original, c.deletedLocal, false, c.originalStart, decorationsActive));\n\t\t\tnewContent.push(cvd);\n\t\t} else if (c && c.kind === 'nested') {\n\t\t\tnewContent.push(decorateContainer(cvd as BlockViewData, c, decorationsActive));\n\t\t} else {\n\t\t\tnewContent.push(cvd);\n\t\t}\n\t}\n\tfor (const rem of pending) {\n\t\tnewContent.push(_decoration(rem.node, rem.deletedLocal, true, rem.originalStart, decorationsActive));\n\t}\n\treturn _withContent(container, newContent);\n}\n\n/** Clone a view-data node with its `content` array replaced (identity differs). */\nfunction _withContent<T extends object>(vd: T, content: readonly AnyViewData[]): T {\n\treturn Object.assign(Object.create(Object.getPrototypeOf(vd)), vd, { content }) as T;\n}\n\nfunction _diffModifiedAst(item: DiffItem): AstNode | undefined {\n\tswitch (item.kind) {\n\t\tcase 'unchanged': return item.node;\n\t\tcase 'added': return item.node;\n\t\tcase 'replaced': return item.modified;\n\t\tcase 'nested': return item.modified;\n\t\tcase 'removed': return undefined;\n\t}\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 'unhandledBlock': return _reuseOr(prev, new UnhandledBlockViewData(node, _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 type { OffsetRange } from '../core/offsetRange.js';\nimport type { ViewNode } from './content/viewNode.js';\n\ninterface TextLeaf { readonly text: Text; readonly start: number; readonly len: number; }\n\n/** Text leaves of a view-node subtree with their source start offsets (root-local). */\nfunction collectTextLeaves(root: ViewNode): TextLeaf[] {\n\tconst out: TextLeaf[] = [];\n\tconst walk = (n: ViewNode, base: number): void => {\n\t\tconst kids = n.children;\n\t\tif (kids.length === 0) {\n\t\t\tif (n.dom.nodeType === 3 /* TEXT_NODE */) {\n\t\t\t\tout.push({ text: n.dom as Text, start: base, len: n.sourceLength });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tlet pos = base;\n\t\tfor (const c of kids) {\n\t\t\t// Skip zero-source nodes (e.g. the read-only diff decorations): their\n\t\t\t// rendered text is not part of this root's source space, so including\n\t\t\t// it would mis-map offsets onto the wrong (red) text.\n\t\t\tif (c.sourceLength === 0) { continue; }\n\t\t\twalk(c, pos);\n\t\t\tpos += c.sourceLength;\n\t\t}\n\t};\n\twalk(root, 0);\n\treturn out;\n}\n\nfunction rangeFromLeaves(leaves: readonly TextLeaf[], s: number, e: number): Range | undefined {\n\tlet startNode: Text | undefined;\n\tlet startOff = 0;\n\tlet endNode: Text | undefined;\n\tlet endOff = 0;\n\tfor (const lf of leaves) {\n\t\tconst ls = lf.start;\n\t\tconst le = lf.start + lf.len;\n\t\tif (startNode === undefined && s >= ls && s < le) { startNode = lf.text; startOff = s - ls; }\n\t\tif (e > ls && e <= le) { endNode = lf.text; endOff = e - ls; }\n\t}\n\tif (!startNode || !endNode) { return undefined; }\n\tconst range = document.createRange();\n\trange.setStart(startNode, startOff);\n\trange.setEnd(endNode, endOff);\n\treturn range;\n}\n\n/**\n * Build DOM {@link Range}s for the given source `spans` (offsets in the source\n * space the `root` view node maps) by walking `root`'s text leaves. Spans that\n * fall outside the rendered text (or are empty) are skipped.\n */\nexport function rangesForOffsets(root: ViewNode, spans: readonly OffsetRange[]): Range[] {\n\tconst leaves = collectTextLeaves(root);\n\tconst out: Range[] = [];\n\tfor (const span of spans) {\n\t\tif (span.isEmpty) { continue; }\n\t\tconst range = rangeFromLeaves(leaves, span.start, span.endExclusive);\n\t\tif (range) { out.push(range); }\n\t}\n\treturn out;\n}\n","import { Disposable } from '@vscode/observables';\nimport type { OffsetRange } from '../../core/offsetRange.js';\nimport { DiffDecorationViewNode, DiffHunkViewNode } from '../content/blockView.js';\nimport type { ViewNode } from '../content/viewNode.js';\nimport { rangesForOffsets } from '../diffHighlight.js';\nimport { EditorCoordinateSpace } from '../editorCoordinateSpace.js';\n\n/**\n * Paints diff word/character highlights as an absolutely-positioned overlay of\n * rectangles — the same technique the selection layer uses (geometry from the\n * rendered DOM, no mutation of the content). Green rects cover inserted/changed\n * modified text; red rects cover deleted text inside the read-only\n * decorations/hunks. Client rectangles are converted through the editor's\n * coordinate boundary before being written to the local overlay.\n */\nexport class DiffHighlightsView extends Disposable {\n\treadonly element: HTMLElement;\n\tprivate _last: { readonly node: ViewNode; readonly inserted?: readonly OffsetRange[] } | undefined;\n\tprivate readonly _resizeObserver: ResizeObserver;\n\tprivate readonly _coordinateSpace: EditorCoordinateSpace;\n\tprivate readonly _coordinateProbe: SVGSVGElement | undefined;\n\n\tconstructor(private readonly _parent: HTMLElement, coordinateSpace?: EditorCoordinateSpace) {\n\t\tsuper();\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-diff-highlight-layer';\n\t\tif (coordinateSpace) {\n\t\t\tthis._coordinateSpace = coordinateSpace;\n\t\t\tthis._coordinateProbe = undefined;\n\t\t} else {\n\t\t\tthis._coordinateProbe = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\t\tthis._coordinateProbe.setAttribute('aria-hidden', 'true');\n\t\t\tthis._coordinateProbe.style.position = 'absolute';\n\t\t\tthis._coordinateProbe.style.inset = '0';\n\t\t\tthis._coordinateProbe.style.width = '100%';\n\t\t\tthis._coordinateProbe.style.height = '100%';\n\t\t\tthis._coordinateProbe.style.visibility = 'hidden';\n\t\t\tthis._coordinateProbe.style.pointerEvents = 'none';\n\t\t\tthis.element.appendChild(this._coordinateProbe);\n\t\t\tthis._coordinateSpace = EditorCoordinateSpace.forSvgOverlay(this._coordinateProbe);\n\t\t}\n\t\t// Repaint on size changes — this also covers the first render happening\n\t\t// before the view is attached/laid out (so the initial rects would be\n\t\t// empty), since attachment changes the observed size.\n\t\tthis._resizeObserver = new ResizeObserver(() => { if (this._last) { this._repaint(this._last); } });\n\t\tthis._resizeObserver.observe(this._parent);\n\t\tthis._register({ dispose: () => { this._resizeObserver.disconnect(); this.element.remove(); } });\n\t}\n\n\tclear(): void {\n\t\tthis._last = undefined;\n\t\tthis._replaceHighlights();\n\t}\n\n\t/**\n\t * Repaint the highlights for the given view-node tree. `insertedRanges`\n\t * (modified-document offsets) are painted green when supplied (editor diff\n\t * mode); a {@link DiffHunkViewNode}'s own sides supply both colours (the\n\t * standalone read-only diff). Deleted ranges from {@link DiffDecorationViewNode}s\n\t * are always painted red.\n\t */\n\trender(documentNode: ViewNode, insertedRanges?: readonly OffsetRange[]): void {\n\t\tthis._last = { node: documentNode, inserted: insertedRanges };\n\t\tthis._repaint(this._last);\n\t}\n\n\tprivate _repaint(last: { readonly node: ViewNode; readonly inserted?: readonly OffsetRange[] }): void {\n\t\tconst green: Range[] = [];\n\t\tconst red: Range[] = [];\n\t\tif (last.inserted) { green.push(...rangesForOffsets(last.node, last.inserted)); }\n\n\t\tconst walk = (n: ViewNode): void => {\n\t\t\tif (n instanceof DiffDecorationViewNode) {\n\t\t\t\t// Whole-block removals show a solid band only (no word rects).\n\t\t\t\tif (!n.whole) { red.push(...rangesForOffsets(n.sideNode, n.deletedRanges.map(r => r.range))); }\n\t\t\t} else if (n instanceof DiffHunkViewNode) {\n\t\t\t\tfor (const side of n.sides) {\n\t\t\t\t\tfor (const r of side.ranges) {\n\t\t\t\t\t\tconst rs = rangesForOffsets(side.node, [r.range]);\n\t\t\t\t\t\t(r.kind === 'inserted' ? green : red).push(...rs);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const c of n.children) { walk(c); }\n\t\t};\n\t\twalk(last.node);\n\t\tthis._paint(green, red);\n\t}\n\n\tprivate _paint(green: readonly Range[], red: readonly Range[]): void {\n\t\tconst transform = this._coordinateSpace.capture();\n\t\tconst frag = document.createDocumentFragment();\n\t\tconst add = (ranges: readonly Range[], cls: string): void => {\n\t\t\tfor (const range of ranges) {\n\t\t\t\tfor (const rect of range.getClientRects()) {\n\t\t\t\t\tif (rect.width === 0 || rect.height === 0) { continue; }\n\t\t\t\t\tconst localRect = transform.toLocalRect(rect);\n\t\t\t\t\tconst el = document.createElement('div');\n\t\t\t\t\tel.className = cls;\n\t\t\t\t\tel.style.left = `${localRect.left}px`;\n\t\t\t\t\tel.style.top = `${localRect.top}px`;\n\t\t\t\t\tel.style.width = `${localRect.width}px`;\n\t\t\t\t\tel.style.height = `${localRect.height}px`;\n\t\t\t\t\tfrag.appendChild(el);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tadd(green, 'md-diff-ins-rect');\n\t\tadd(red, 'md-diff-del-rect');\n\t\tthis._replaceHighlights(frag);\n\t}\n\n\tprivate _replaceHighlights(...nodes: Node[]): void {\n\t\tconst children = this._coordinateProbe ? [this._coordinateProbe, ...nodes] : nodes;\n\t\tthis.element.replaceChildren(...children);\n\t}\n}\n","import { Disposable, autorun, derived, type IObservable } from '@vscode/observables';\nimport { Rect2D } from '../../core/geometry.js';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport type { Selection } from '../../core/selection.js';\nimport type { BlockAstNode } from '../../parser/ast.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 /** Block border box in editor-local coordinates. */\n readonly rect: Rect2D;\n /** Visible horizontal padding-box bounds for a scrolling block. */\n readonly viewportClip: { readonly left: number; readonly right: number } | undefined;\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 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, 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 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 const rects = computeRangeRects(selection.range, visualLineMap, blocks);\n path.setAttribute('d', buildConnectedPath(rects, 4));\n return new SelectionViewRendering(rects);\n}\n\n/**\n * Width of the trailing space painted at the end of a line whose hard line\n * break is selected, as a fraction of the line height. This mirrors how\n * editors show a selected newline: a small blank gap past the last glyph\n * (here just a space, no ↵ glyph) rather than nothing or a full-line band.\n */\nconst NEWLINE_SELECTION_WIDTH_RATIO = 0.4;\n\n/**\n * Compute the selection-style rectangles covering `range`, in `parent`-local\n * coordinates. Shared by the live selection layer and the comments overlay so\n * both paint identical geometry from the same source of truth. Returns an empty\n * array for an empty range.\n */\nexport function computeRangeRects(\n range: OffsetRange,\n visualLineMap: VisualLineMap,\n blocks: readonly SelectionBlock[],\n): SelectionRect[] {\n if (range.isEmpty) {\n return [];\n }\n const selRange = range;\n const toRect = (left: number, top: number, right: number, bottom: number): SelectionRect =>\n Rect2D.fromPointPoint(left, top, Math.max(left, right), Math.max(top, bottom));\n\n // 1. Collect the visual lines the selection touches, paired with the\n // block that contains them. A line is touched when either:\n // - the selection overlaps its rendered content, or\n // - the selection covers the line's trailing *hard* line break —\n // it starts at/after the line's content end but extends onto a\n // later line. This second case is what lets a selection that\n // runs off the end of a line paint a small trailing space at\n // that line's end (the way editors render a selected newline),\n // even though no glyph there is itself selected.\n const lines = visualLineMap.lines;\n const lineInfos: { line: VisualLine; lineRange: OffsetRange; block: SelectionBlock | undefined; hardBreak: boolean }[] = [];\n for (let k = 0; k < lines.length; k++) {\n const line = lines[k];\n const lineRange = _lineSourceRange(line);\n if (!lineRange) { continue; }\n // The break after this line is \"hard\" (a real `\\n`, or the document\n // end) when the next visual line starts past this line's content\n // end. A soft wrap has the next line starting exactly at this line's\n // content end, so it is not hard and gets no trailing space.\n const nextRange = k + 1 < lines.length ? _lineSourceRange(lines[k + 1]) : undefined;\n const hardBreak = !nextRange || nextRange.start > lineRange.endExclusive;\n const overlapsContent = selRange.intersects(lineRange);\n const selectsTrailingBreak = hardBreak\n && selRange.start <= lineRange.endExclusive\n && selRange.endExclusive > lineRange.endExclusive;\n if (!overlapsContent && !selectsTrailingBreak) { continue; }\n const block = blocks.find(b => OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length).containsRange(lineRange));\n lineInfos.push({ line, lineRange, block, hardBreak });\n }\n\n const rects: SelectionRect[] = [];\n // Per-line rect in editor-local coordinates. Saved so the connector logic\n // can clip itself 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. `startX` is clipped to\n // the selection start when it falls on this line, otherwise the line's\n // left edge. `endX` is clipped to the selection end when it falls on\n // this line; when the selection continues onto a later line, `endX`\n // runs to the painted text's right edge — plus a small fixed space\n // when the following break is a hard newline, so a selection that\n // spills off the end of a line shows a trailing gap there.\n for (const { line, lineRange, hardBreak, block } of lineInfos) {\n const cStart = lineRange.start;\n const cEnd = lineRange.endExclusive;\n\n let startX = selRange.start <= cStart\n ? line.rect.left\n : line.xAtOffset(selRange.start);\n\n let endX: number;\n if (selRange.endExclusive < cEnd) {\n endX = line.xAtOffset(selRange.endExclusive);\n } else {\n const breakSelected = selRange.endExclusive > cEnd;\n endX = line.rect.right + (breakSelected && hardBreak ? line.rect.height * NEWLINE_SELECTION_WIDTH_RATIO : 0);\n }\n\n // A block that scrolls horizontally (code / math / unhandled) clips its\n // content to its own viewport, but the selection layer is one overlay\n // spanning the whole editor and is not clipped — so a rect for a wide\n // line would bleed across the page. Clip each line's rect to its block's\n // visible horizontal bounds; a line scrolled fully out collapses to zero\n // width (invisible, and its connector is dropped below).\n const clip = blockViewportClip(block);\n if (clip) {\n startX = Math.max(startX, clip.left);\n endX = Math.min(endX, clip.right);\n }\n\n rects.push(toRect(startX, line.rect.top, endX, line.rect.bottom));\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(toRect(left, prev.bottom, right, next.top));\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.rect;\n const nextRect = next.rect;\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 // If a bordering block has visible text lines but none of them are\n // selected, the selection only covers that block's hidden markers\n // (e.g. a heading's `## ` when the selection ends right at the\n // rendered title). There is nothing visible to bridge to, so a\n // connector here would hang a stray bar in empty space — skip it.\n // Blocks with no visual lines at all (hr, image, math) still fall\n // back to their element rect below so they can be bridged into.\n if ((prevLineIdx === undefined && _blockHasVisualLine(visualLineMap, curr))\n || (nextLineIdx === undefined && _blockHasVisualLine(visualLineMap, next))) { continue; }\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(toRect(left, top, right, nextFirstLineTop));\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 //\n // The check is \"does this block own ANY visual line in the map\" — not\n // \"does it own a *selected* line\". A text paragraph whose only selected\n // part is its trailing block-gap (offset at the paragraph's end, e.g.\n // selecting from the end of a line across the blank line below) has a\n // visual line, it just doesn't intersect the selection. Such a block\n // must NOT be filled wholesale; only genuinely leaf-less blocks qualify.\n for (const b of blocks) {\n const blockRange = OffsetRange.ofStartAndLength(b.absoluteStart, b.block.length);\n if (!selRange.intersects(blockRange)) { continue; }\n if (_blockHasVisualLine(visualLineMap, b)) { continue; }\n rects.push(b.rect);\n }\n\n return 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 * Whether `block` owns at least one rendered visual line. Leaf-less blocks\n * (<hr>, image, math) own none; every text block owns at least one.\n */\nfunction _blockHasVisualLine(visualLineMap: VisualLineMap, block: SelectionBlock): boolean {\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)) { return true; }\n }\n return false;\n}\n\n/**\n * Horizontal viewport bounds (editor-local coordinates) a block clips its content to when\n * it scrolls horizontally (code / math / unhandled blocks are `overflow-x:\n * auto`; a table scrolls inside its `.md-table-wrapper`), or `undefined` when\n * the block does not overflow — so only blocks that actually scroll get their\n * selection (or caret) clipped, leaving every other block (and its gutter\n * markers) untouched.\n */\nexport function blockViewportClip(block: SelectionBlock | undefined): { left: number; right: number } | undefined {\n return block?.viewportClip;\n}\n\n/** The block whose source range contains `offset`, or `undefined`. */\nexport function blockContainingOffset(blocks: readonly SelectionBlock[], offset: number): SelectionBlock | undefined {\n return blocks.find(b => offset >= b.absoluteStart && offset <= b.absoluteStart + b.block.length);\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 */\nexport function 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, 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';\nimport { blockViewportClip, blockContainingOffset, type SelectionBlock } from './selectionView.js';\n\nexport interface CursorViewOptions {\n readonly offset: IObservable<SourceOffset | undefined>;\n readonly visualLineMap: IObservable<VisualLineMap>;\n /**\n * The mounted blocks, used to hide the caret when it sits at an offset that\n * has been scrolled out of its (horizontally scrolling) block's viewport —\n * matching how the selection is clipped there.\n */\n readonly blocks?: IObservable<readonly SelectionBlock[]>;\n /**\n * When set, the caret is drawn over the transient empty paragraph instead\n * of at {@link offset} — its editor-local rect 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(options: CursorViewOptions) {\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 this.element.style.left = `${pendingRect.x}px`;\n this.element.style.top = `${pendingRect.y}px`;\n this.element.style.height = `${pendingRect.height}px`;\n this.element.style.display = '';\n return new CursorViewRendering(0, true, pendingRect);\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\n // Hide the caret when it sits in a horizontally-scrolling block and\n // has been scrolled outside that block's viewport, so it doesn't\n // float over the editor the way an unclipped selection rect would.\n const blocks = options.blocks ? reader.readObservable(options.blocks) : undefined;\n const clip = blocks ? blockViewportClip(blockContainingOffset(blocks, offset)) : undefined;\n if (clip && (caretRect.x < clip.left - 0.5 || caretRect.x > clip.right + 0.5)) {\n this.element.style.display = 'none';\n return new CursorViewRendering(offset, false, Rect2D.EMPTY);\n }\n\n this.element.style.left = `${caretRect.x}px`;\n this.element.style.top = `${caretRect.y}px`;\n this.element.style.height = `${caretRect.height}px`;\n this.element.style.display = '';\n return new CursorViewRendering(offset, true, caretRect);\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(options: GutterMarkersViewOptions) {\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 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)\n\t\t\t\t: _barRect(marker, visualLineMap);\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): 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, 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): GutterMarkerRect {\n\tconst lineIdx = visualLineMap.lineIndexOfOffset(marker.range.start);\n\tconst lineRect = visualLineMap.lineRect(lineIdx);\n\treturn { type: 'deleted', y: lineRect.top, 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, 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 { OffsetRange } from '../core/offsetRange.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 { ViewNode } from './content/viewNode.js';\nimport { EditorCoordinateSpace } from './editorCoordinateSpace.js';\nimport { buildDocumentViewData, applyDiffDecorations, type DocumentViewData } from './viewData.js';\nimport { DiffHighlightsView } from './parts/diffHighlightsView.js';\nimport { CursorView } from './parts/cursorView.js';\nimport { GutterMarkersView } from './parts/gutterMarkersView.js';\nimport { SelectionView, type SelectionBlock, type SelectionRect, computeRangeRects } 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 * Whether to render the sticky edit/read-only toggle at the top-right edge\n\t * of the content. Defaults to `true`; set to `false` to omit it (e.g. in\n\t * fixtures that focus on selection rendering).\n\t */\n\treadonly showReadonlyToggle?: boolean;\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\t/**\n\t * Diff mode only: render every read-only original decoration in active\n\t * (source) form, so even whole-block removals expose their markdown markers\n\t * as real text. Used by the diff-coverage fixture to verify that every\n\t * changed original character is rendered somewhere; off in normal use, where\n\t * whole removals show a clean solid band.\n\t */\n\treadonly diffDecorationsActive?: boolean;\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\treadonly coordinateSpace: EditorCoordinateSpace;\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\tprivate readonly _diffHighlightsView: DiffHighlightsView;\n\tprivate _readonlyToggleButton: HTMLButtonElement | undefined;\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\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 (editor-local coordinates) 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 measurements = this.measuredLayout.measurements.read(reader);\n\t\treturn measurements.flatMap((measurement): SelectionBlock[] => {\n\t\t\tif (!measurement.rect || !measurement.viewNode) { return []; }\n\t\t\treturn [{\n\t\t\t\tblock: measurement.block,\n\t\t\t\tabsoluteStart: measurement.absoluteStart,\n\t\t\t\trect: measurement.rect,\n\t\t\t\tviewportClip: measurement.viewportClip,\n\t\t\t}];\n\t\t});\n\t});\n\n\t/**\n\t * The caret rect (zero width) at the selection's active end, in\n\t * {@link overlayContainer}-local coordinates, or `undefined` when there is no\n\t * caret. This is the same geometry the editor paints its cursor from, so\n\t * contributions (e.g. comment mode) can anchor an overlay to the active end of\n\t * the selection — where the user's cursor is — without re-deriving geometry.\n\t */\n\tprivate readonly _caretRect = derived(this, reader => {\n\t\tconst rendering = this._cursorView.rendering.read(reader);\n\t\treturn rendering.visible ? rendering.rect : undefined;\n\t});\n\tpublic get caretRect(): IObservable<Rect2D | undefined> { return this._caretRect; }\n\n\t/**\n\t * The container that establishes the positioning context for the editor's\n\t * overlays (cursor, selection, gutter). Contributions mount their own\n\t * absolutely-positioned overlays here so they share the coordinate space of\n\t * {@link caretRect}.\n\t */\n\tpublic get overlayContainer(): HTMLElement { return this._contentContainer; }\n\n\t/**\n\t * Selection-style rectangles covering `range`, in {@link overlayContainer}-\n\t * local coordinates — the same geometry the live selection paints. Exposed so\n\t * contributions (e.g. persistent comments) can highlight arbitrary ranges and\n\t * anchor overlays to them. Recomputes when the measured layout changes.\n\t */\n\tpublic rangeRects(range: OffsetRange): IObservable<readonly SelectionRect[]> {\n\t\treturn derived(this, reader => {\n\t\t\tconst visualLineMap = this.measuredLayout.visualLineMap.read(reader);\n\t\t\tconst blocks = this._selectionBlocksObs.read(reader);\n\t\t\treturn computeRangeRects(range, visualLineMap, blocks);\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\t// Re-measure on reflow. The measured layout is otherwise only recomputed\n\t\t// when the *document* changes (via `_publishMeasurements` on the render\n\t\t// path); nothing observes the container width. So any width change caused\n\t\t// by something other than an edit — e.g. a contribution reserving\n\t\t// right-hand rail space and narrowing the text column — would leave\n\t\t// `visualLineMap`, and every geometry derived from it (selection, cursor,\n\t\t// comment highlights), stale. Observing the content box keeps the\n\t\t// measurement in sync with the actually rendered width. The width guard\n\t\t// makes it idempotent so it settles instead of oscillating.\n\t\tlet lastMeasuredContentWidth = -1;\n\t\tconst resizeObserver = new ResizeObserver(() => {\n\t\t\tthis.element.classList.toggle('md-editor-narrow', this.element.clientWidth <= 320);\n\t\t\tconst doc = this._document.get();\n\t\t\tif (!doc) { return; }\n\t\t\tconst width = this._contentContainer.clientWidth;\n\t\t\tif (Math.abs(width - lastMeasuredContentWidth) < 0.5) { return; }\n\t\t\tlastMeasuredContentWidth = width;\n\t\t\tthis._publishMeasurements(doc);\n\t\t});\n\t\tresizeObserver.observe(this.element);\n\t\tresizeObserver.observe(this._contentContainer);\n\t\tthis._register({ dispose: () => resizeObserver.disconnect() });\n\n\t\t// Inner blocks (code / math / unhandled, and a wide table inside its\n\t\t// `.md-table-wrapper`) scroll horizontally on their own. Scrolling one\n\t\t// moves the text within it, so the measured `visualLineMap` — and the\n\t\t// selection / cursor geometry derived from it, which is clipped to each\n\t\t// block's viewport — goes stale. Re-measure on scroll so the cached line\n\t\t// geometry and the live glyph measurements share the current scroll\n\t\t// basis. Scroll events don't bubble, so listen in the capture phase;\n\t\t// coalesce to one re-measure per frame.\n\t\tlet scrollRaf = 0;\n\t\tconst onBlockScroll = () => {\n\t\t\tif (scrollRaf) { return; }\n\t\t\tscrollRaf = requestAnimationFrame(() => {\n\t\t\t\tscrollRaf = 0;\n\t\t\t\tconst doc = this._document.get();\n\t\t\t\tif (doc) { this._publishMeasurements(doc); }\n\t\t\t});\n\t\t};\n\t\tthis._contentContainer.addEventListener('scroll', onBlockScroll, { capture: true, passive: true });\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tthis._contentContainer.removeEventListener('scroll', onBlockScroll, { capture: true });\n\t\t\t\tif (scrollRaf) { cancelAnimationFrame(scrollRaf); }\n\t\t\t},\n\t\t});\n\n\t\tthis._selectionView = this._register(new SelectionView({\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\t\tthis.coordinateSpace = EditorCoordinateSpace.forSvgOverlay(this._selectionView.element);\n\n\t\tthis._cursorView = this._register(new CursorView({\n\t\t\toffset: this._model.cursorOffset,\n\t\t\tvisualLineMap: this.measuredLayout.visualLineMap,\n\t\t\tblocks: this._selectionBlocksObs,\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({\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._diffHighlightsView = this._register(new DiffHighlightsView(this._contentContainer, this.coordinateSpace));\n\t\tthis._contentContainer.appendChild(this._diffHighlightsView.element);\n\n\t\tif (this._options?.showReadonlyToggle !== false) { this._setupReadonlyToggle(); }\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(); this._clearDiff(); } });\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\t/**\n\t * Renders the edit/read-only mode toggle. It flips the model's\n\t * {@link EditorModel.readonlyMode}: when locked (read-only) every block stays\n\t * in its clean rendered form (no markdown markers revealed) and edits are\n\t * ignored, while text selection still works. The control lives in a\n\t * zero-height *sticky* host inside the centered content container, so the\n\t * lock follows the content's right edge and remains pinned as the document\n\t * scrolls. The current mode is also mirrored onto the root as `.md-readonly`\n\t * for any CSS hooks.\n\t */\n\tprivate _setupReadonlyToggle(): void {\n\t\tconst host = document.createElement('div');\n\t\thost.className = 'md-readonly-toggle-host';\n\t\tthis._contentContainer.classList.add('md-editor-content-with-readonly-toggle');\n\n\t\tconst button = document.createElement('button');\n\t\tbutton.type = 'button';\n\t\tbutton.className = 'md-readonly-toggle';\n\t\tthis._readonlyToggleButton = button;\n\n\t\tconst indicator = document.createElement('span');\n\t\tindicator.className = 'md-readonly-toggle-indicator';\n\t\tindicator.setAttribute('aria-hidden', 'true');\n\n\t\tconst lockedIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\tlockedIcon.classList.add('md-readonly-toggle-icon', 'md-readonly-toggle-icon-locked');\n\t\tlockedIcon.setAttribute('viewBox', '0 0 16 16');\n\t\tlockedIcon.setAttribute('fill', 'currentColor');\n\t\tlockedIcon.setAttribute('aria-hidden', 'true');\n\n\t\tconst lockKeyhole = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\tlockKeyhole.setAttribute('d', 'M8 9C8.55228 9 9 9.44771 9 10C9 10.5523 8.55228 11 8 11C7.44772 11 7 10.5523 7 10C7 9.44771 7.44772 9 8 9Z');\n\t\tconst lockBody = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\tlockBody.setAttribute('fill-rule', 'evenodd');\n\t\tlockBody.setAttribute('clip-rule', 'evenodd');\n\t\tlockBody.setAttribute('d', 'M8 1C9.654 1 11 2.346 11 4V6H12C13.103 6 14 6.897 14 8V13C14 14.103 13.103 15 12 15H4C2.897 15 2 14.103 2 13V8C2 6.897 2.897 6 4 6H5V4C5 2.346 6.346 1 8 1ZM4 7C3.449 7 3 7.449 3 8V13C3 13.551 3.449 14 4 14H12C12.551 14 13 13.551 13 13V8C13 7.449 12.551 7 12 7H4ZM8 2C6.897 2 6 2.897 6 4V6H10V4C10 2.897 9.103 2 8 2Z');\n\t\tlockedIcon.append(lockKeyhole, lockBody);\n\n\t\tconst editingIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\teditingIcon.classList.add('md-readonly-toggle-icon', 'md-readonly-toggle-icon-editing');\n\t\teditingIcon.setAttribute('viewBox', '0 0 16 16');\n\t\teditingIcon.setAttribute('fill', 'currentColor');\n\t\teditingIcon.setAttribute('aria-hidden', 'true');\n\t\tconst editingPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\t\teditingPath.setAttribute('d', 'M14.236 1.76386C13.2123 0.740172 11.5525 0.740171 10.5289 1.76386L2.65722 9.63549C2.28304 10.0097 2.01623 10.4775 1.88467 10.99L1.01571 14.3755C0.971767 14.5467 1.02148 14.7284 1.14646 14.8534C1.27144 14.9783 1.45312 15.028 1.62432 14.9841L5.00978 14.1151C5.52234 13.9836 5.99015 13.7168 6.36433 13.3426L14.236 5.47097C15.2596 4.44728 15.2596 2.78755 14.236 1.76386ZM11.236 2.47097C11.8691 1.8378 12.8957 1.8378 13.5288 2.47097C14.162 3.10413 14.162 4.1307 13.5288 4.76386L12.75 5.54269L10.4571 3.24979L11.236 2.47097ZM9.75002 3.9569L12.0429 6.24979L5.65722 12.6355C5.40969 12.883 5.10023 13.0595 4.76117 13.1465L2.19447 13.8053L2.85327 11.2386C2.9403 10.8996 3.1168 10.5901 3.36433 10.3426L9.75002 3.9569Z');\n\t\teditingIcon.appendChild(editingPath);\n\n\t\tbutton.append(indicator, lockedIcon, editingIcon);\n\t\thost.appendChild(button);\n\n\t\tconst onClick = (): void => {\n\t\t\tthis._model.readonlyMode.set(!this._model.readonlyMode.get(), undefined);\n\t\t};\n\t\tconst onPointerDown = (event: PointerEvent): void => {\n\t\t\tif (event.button !== 0) { return; }\n\t\t\t// Keep focus and selection in the editor instead of letting its root\n\t\t\t// pointer handler interpret the toggle as a click on editor padding.\n\t\t\tevent.preventDefault();\n\t\t\tevent.stopPropagation();\n\t\t\tthis.focus();\n\t\t};\n\t\tconst onKeyDown = (event: KeyboardEvent): void => {\n\t\t\t// Let the button perform its native keyboard activation without the\n\t\t\t// event also reaching the editor's navigation and editing commands.\n\t\t\tevent.stopPropagation();\n\t\t};\n\t\tconst onFocus = (): void => {\n\t\t\t// Chromium's EditContext host otherwise immediately reclaims focus\n\t\t\t// from a non-text control nested inside it.\n\t\t\tthis.element.editContext = null;\n\t\t};\n\t\tconst onBlur = (): void => {\n\t\t\tthis.element.editContext = this.editContext;\n\t\t};\n\t\tconst onAnimationEnd = (event: AnimationEvent): void => {\n\t\t\tif (event.animationName === 'md-readonly-toggle-shine') {\n\t\t\t\tbutton.classList.remove('md-readonly-toggle-shine');\n\t\t\t}\n\t\t};\n\t\tbutton.addEventListener('pointerdown', onPointerDown);\n\t\tbutton.addEventListener('keydown', onKeyDown);\n\t\tbutton.addEventListener('focus', onFocus);\n\t\tbutton.addEventListener('blur', onBlur);\n\t\tbutton.addEventListener('animationend', onAnimationEnd);\n\t\tbutton.addEventListener('click', onClick);\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tbutton.removeEventListener('pointerdown', onPointerDown);\n\t\t\t\tbutton.removeEventListener('keydown', onKeyDown);\n\t\t\t\tbutton.removeEventListener('focus', onFocus);\n\t\t\t\tbutton.removeEventListener('blur', onBlur);\n\t\t\t\tbutton.removeEventListener('animationend', onAnimationEnd);\n\t\t\t\tbutton.removeEventListener('click', onClick);\n\t\t\t\tif (this._readonlyToggleButton === button) {\n\t\t\t\t\tthis._readonlyToggleButton = undefined;\n\t\t\t\t}\n\t\t\t\tif (this.element.editContext === null) {\n\t\t\t\t\tthis.element.editContext = this.editContext;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\n\t\tthis._register(autorun(reader => {\n\t\t\tconst readonly = this._model.readonlyMode.read(reader);\n\t\t\tbutton.classList.toggle('md-readonly-toggle-locked', readonly);\n\t\t\tbutton.setAttribute('aria-pressed', String(readonly));\n\t\t\tbutton.setAttribute('aria-label', readonly\n\t\t\t\t? 'Locked; switch to editing'\n\t\t\t\t: 'Editing; switch to locked mode');\n\t\t\tbutton.title = readonly\n\t\t\t\t? 'Read-only: markers hidden, editing disabled. Click to edit.'\n\t\t\t\t: 'Editing: click to lock (hide markers, disable editing).';\n\t\t\tif (!readonly) {\n\t\t\t\tbutton.classList.remove('md-readonly-toggle-shine');\n\t\t\t}\n\t\t\tthis.element.classList.toggle('md-readonly', readonly);\n\t\t}));\n\n\t\t// Keep the sticky host ahead of the rendered document while anchoring its\n\t\t// horizontal position to the limited-width content container.\n\t\tthis._contentContainer.insertBefore(host, this._contentContainer.firstChild);\n\t}\n\n\t/** Draws attention to the mode toggle after text input is attempted while locked. */\n\tshowReadonlyEditingAttempt(): void {\n\t\tconst button = this._readonlyToggleButton;\n\t\tif (!button || button.classList.contains('md-readonly-toggle-shine')) { return; }\n\t\tbutton.classList.add('md-readonly-toggle-shine');\n\t}\n\n\tfocus(): void { this.element.focus({ preventScroll: true }); }\n\n\t/**\n\t * Own point→offset resolution. When `true` (the default),\n\t * {@link resolveOffsetFromPoint} ignores the platform DOM hit-test\n\t * (`caretPositionFromPoint`) and snaps the point to the nearest offset purely\n\t * from the rendered {@link VisualLineMap} geometry — picking the nearest\n\t * visual line by `y`, then the nearest offset on it by `x`. Because a table\n\t * row's cells share one horizontal line band, this makes the whole width of a\n\t * row resolve into that row (rather than only the cell boxes), with no visible\n\t * layout change. It also lets a drag keep extending toward off-viewport points\n\t * (e.g. the pointer leaving the window), which the platform hit-test cannot\n\t * resolve. Set to `false` to fall back to the platform DOM hit-test.\n\t */\n\tpublic readonly geometricHitTest = observableValue<boolean>(this, 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. Honours {@link geometricHitTest}.\n\t */\n\tresolveOffsetFromPoint(point: Point2D): SourceOffset | undefined {\n\t\tconst tableCellOffset = this._resolveTableCellOffset(point);\n\t\tif (tableCellOffset !== undefined) { return tableCellOffset; }\n\t\tif (this.geometricHitTest.get()) {\n\t\t\tconst map = this.measuredLayout.visualLineMap.get();\n\t\t\tif (map.isEmpty) { return undefined; }\n\t\t\treturn map.offsetAtPoint(this.coordinateSpace.capture().toLocalPoint(point));\n\t\t}\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 * Resolve table-cell hits that have no measurable text run. Empty cells map\n\t * from their own box instead of snapping to a neighboring cell; element-only\n\t * content (for example an inactive image) maps through the hit element's view\n\t * node. Text-bearing cells keep the normal pixel-precise line-map/DOM path.\n\t */\n\tprivate _resolveTableCellOffset(point: Point2D): SourceOffset | undefined {\n\t\tconst hit = document.elementFromPoint(point.x, point.y);\n\t\tconst cell = hit?.closest('td');\n\t\tif (!(cell instanceof HTMLTableCellElement) || !this._contentContainer.contains(cell)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst documentView = this._document.get();\n\t\tif (!documentView) { return undefined; }\n\t\tconst cellNode = ViewNode.forDom(cell);\n\t\tif (cellNode?.ast.kind !== 'tableCell' || cellNode.dom !== cell) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst cellStart = documentView.resolveSource({ node: cell, offset: 0 });\n\t\tconst cellEnd = documentView.resolveSource({ node: cell, offset: 1 });\n\t\tif (cellStart === undefined || cellEnd === undefined) { return undefined; }\n\n\t\tconst domOffsetAtPoint = (element: Element): 0 | 1 => {\n\t\t\tconst rect = element.getBoundingClientRect();\n\t\t\tconst isRtl = getComputedStyle(element).direction === 'rtl';\n\t\t\tconst onStartSide = isRtl ? point.x >= rect.left + rect.width / 2 : point.x < rect.left + rect.width / 2;\n\t\t\treturn onStartSide ? 0 : 1;\n\t\t};\n\n\t\tconst hasSourceRun = (start: SourceOffset, end: SourceOffset): boolean =>\n\t\t\tthis.measuredLayout.visualLineMap.get().lines.some(line =>\n\t\t\t\tline.runs.some(run =>\n\t\t\t\t\trun.source !== undefined\n\t\t\t\t\t&& run.sourceStart < end\n\t\t\t\t\t&& run.sourceEndExclusive > start\n\t\t\t\t)\n\t\t\t);\n\n\t\tconst hitNode = hit ? ViewNode.forDom(hit) : undefined;\n\t\tif (hitNode && hitNode !== cellNode && hitNode.dom instanceof Element) {\n\t\t\tconst hitStart = documentView.resolveSource({ node: hitNode.dom, offset: 0 });\n\t\t\tconst hitEnd = documentView.resolveSource({ node: hitNode.dom, offset: 1 });\n\t\t\tif (hitStart !== undefined && hitEnd !== undefined && !hasSourceRun(hitStart, hitEnd)) {\n\t\t\t\tif (hitEnd - hitStart <= 1) { return hitEnd; }\n\t\t\t\treturn domOffsetAtPoint(hitNode.dom) === 0 ? hitStart + 1 : hitEnd - 1;\n\t\t\t}\n\t\t}\n\n\t\tif (hasSourceRun(cellStart, cellEnd)) { return undefined; }\n\t\tif (cellEnd - cellStart <= 1) { return cellEnd; }\n\t\treturn domOffsetAtPoint(cell) === 0 ? cellStart + 1 : cellEnd - 1;\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\t\tconst diff = reader.readObservable(this._model.diff);\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 baseViewData = buildDocumentViewData(\n\t\t\tdoc, diff ? new Set([...activeBlocks, ...diff.changedBlocks]) : activeBlocks,\n\t\t\tselection?.range, this._previousViewData,\n\t\t\tpending ? { anchorBlock: pending.anchorBlock, ast: pending.syntheticAst } : undefined,\n\t\t);\n\t\tthis._previousViewData = baseViewData;\n\t\tconst viewData = diff ? applyDiffDecorations(baseViewData, diff.items, this._options?.diffDecorationsActive) : baseViewData;\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, preserving any leading view chrome.\n\t\t\tthis._contentContainer.insertBefore(documentNode.contentDomNode, this._selectionView.element);\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 = this.coordinateSpace.capture().toLocalRect(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\n\t\tif (diff) { this._paintDiff(documentNode, diff.insertedRanges); }\n\t\telse { this._clearDiff(); }\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 transform = this.coordinateSpace.capture();\n\t\tconst measurements: BlockMeasurement[] = [];\n\t\tfor (const entry of document.blocks) {\n\t\t\tconst blockRect = transform.toLocalRect(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 scrollElement = entry.node.scrollElement;\n\t\t\tlet viewportClip: { readonly left: number; readonly right: number } | undefined;\n\t\t\tif (scrollElement.scrollWidth > scrollElement.clientWidth + 1) {\n\t\t\t\tconst scrollRect = transform.toLocalRect(scrollElement.getBoundingClientRect());\n\t\t\t\tconst left = scrollRect.left + scrollElement.clientLeft;\n\t\t\t\tviewportClip = { left, right: left + scrollElement.clientWidth };\n\t\t\t}\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}], this.coordinateSpace, transform);\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\trect: blockRect,\n\t\t\t\tviewportClip,\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\t/**\n\t * Paint the diff highlights via the CSS Custom Highlight API: green over the\n\t * inserted/changed modified ranges (mapped on the document's own DOM), and\n\t * red over each {@link DiffDecorationViewNode}'s deleted ranges (mapped on\n\t * the decoration's own subtree). No DOM is mutated, so reconciliation and\n\t * editing are unaffected.\n\t */\n\tprivate _paintDiff(documentNode: DocumentViewNode, insertedRanges: readonly OffsetRange[]): void {\n\t\tthis._diffHighlightsView.render(documentNode, insertedRanges);\n\t}\n\n\tprivate _clearDiff(): void {\n\t\tthis._diffHighlightsView.clear();\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/** Max time between pointer-downs to count as part of the same multi-click. */\nconst MULTI_CLICK_TIME_MS = 500;\n/** Max movement (px, per axis) between pointer-downs of one multi-click. */\nconst MULTI_CLICK_DISTANCE_PX = 5;\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 * - `_clickCount` / `_lastPointerDown` — multi-click detection for pointer\n * input, since `pointerdown` events (unlike `mousedown`) don't populate\n * `detail` with a click count.\n */\nexport class EditorController extends Disposable {\n private _desiredColumn: number | undefined;\n\n /** Running click count for the current multi-click sequence (1, 2, 3, …). */\n private _clickCount = 0;\n /** Timestamp and position of the previous pointer-down, for multi-click detection. */\n private _lastPointerDown: { time: number; point: Point2D } | 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('pointerdown', this._handlePointerDown);\n el.addEventListener('keydown', this._handleKeyDown);\n this._register({\n dispose: () => {\n el.removeEventListener('pointerdown', this._handlePointerDown);\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 if (this._model.readonlyMode.get() && e.text.length > 0) {\n this._view.showReadonlyEditingAttempt();\n }\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 _handlePointerDown = (e: PointerEvent): void => {\n // Only the primary button starts a selection drag.\n if (e.button !== 0) { return; }\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 // `pointerdown` doesn't carry a click count in `detail` (it's always 0),\n // so detect double/triple clicks ourselves: consecutive pointer-downs\n // close in time and position bump the count, otherwise it resets to 1.\n const prev = this._lastPointerDown;\n const isRepeat = prev !== undefined\n && (e.timeStamp - prev.time) < MULTI_CLICK_TIME_MS\n && Math.abs(point.x - prev.point.x) < MULTI_CLICK_DISTANCE_PX\n && Math.abs(point.y - prev.point.y) < MULTI_CLICK_DISTANCE_PX;\n this._clickCount = isRepeat ? this._clickCount + 1 : 1;\n this._lastPointerDown = { time: e.timeStamp, point };\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 (this._clickCount === 2) {\n const ctx = this._makeCursorContext();\n this._model.selection.set(selectWord(ctx, offset), undefined);\n return;\n }\n\n if (this._clickCount === 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 // A primary single click (no Shift) inside locked content hints the user\n // expects to edit, so we flash the mode toggle to reveal the lock — but\n // only once the gesture ends *without* a selection. Deferring the check to\n // pointer-up and keying it off an empty final selection is what tells a\n // click apart from a drag-select (which stays quiet) and tolerates\n // sub-character pointer jitter. A Shift-click extends a selection, so it\n // is excluded here. Padding clicks and the 2nd/3rd press of a\n // double/triple click return earlier, so word/block selection is\n // preserved — but note the *first* press of a multi-click is itself a\n // single click, so it still emits one (bounded, non-stacking) sheen\n // before the word/block is selected. That is an accepted trade:\n // suppressing it would need a 500ms debounce that lags every single-click\n // reveal, or a jarring mid-animation cancel.\n const revealsLockOnClick = this._clickCount === 1\n && !e.shiftKey\n && this._model.readonlyMode.get();\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 // Capture the pointer so the drag keeps receiving move/up events even\n // when the pointer leaves the window — a plain `mouseup` fired outside\n // the window never reaches the page, which would otherwise leave the\n // drag \"stuck\" until the next click. Pointer capture also unifies\n // mouse, touch, and pen input.\n const el = this._view.element;\n const pointerId = e.pointerId;\n el.setPointerCapture(pointerId);\n this._model.isSelecting.set(true, undefined);\n\n const onPointerMove = (me: PointerEvent): 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 onPointerUp = (): void => {\n this._model.isSelecting.set(false, undefined);\n // A click that placed a caret (collapsed selection) rather than a\n // drag-selection reveals the lock; reuses the same sheen as typing.\n if (revealsLockOnClick && (this._model.selection.get()?.isCollapsed ?? true)) {\n this._view.showReadonlyEditingAttempt();\n }\n el.removeEventListener('pointermove', onPointerMove);\n el.removeEventListener('pointerup', onPointerUp);\n el.removeEventListener('pointercancel', onPointerUp);\n el.removeEventListener('lostpointercapture', onPointerUp);\n };\n el.addEventListener('pointermove', onPointerMove);\n el.addEventListener('pointerup', onPointerUp);\n el.addEventListener('pointercancel', onPointerUp);\n el.addEventListener('lostpointercapture', onPointerUp);\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';\nimport type { EditorCoordinateSpace, EditorCoordinateTransform } from './editorCoordinateSpace.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 readonly coordinateSpace: EditorCoordinateSpace;\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 overlay container so dashed line-bands and run-boxes\n * share the measured editor-local 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 _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(\n this.overlayElement,\n text,\n measurements,\n options.coordinateSpace,\n showLineRects,\n options.colorForOffset,\n options.hoveredOffset,\n );\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 measurements: readonly BlockMeasurement[],\n coordinateSpace: EditorCoordinateSpace,\n showLineRects: boolean,\n colorForOffset?: (offset: number) => string | undefined,\n hoveredOffset?: ISettableObservable<number | undefined>,\n): MeasuredLayoutDebugRendering {\n overlay.textContent = '';\n const transform = coordinateSpace.capture();\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}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}px`,\n top: `${run.rect.y}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, transform, 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 transform: EditorCoordinateTransform,\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 clientRect = 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 (clientRect.height === 0) { continue; }\n const rect = transform.toLocalRect(clientRect);\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}px`,\n top: `${rect.y}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","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","import { Disposable, autorun, observableValue, type IObservable } from '@vscode/observables';\n\n/**\n * Codicon \"plus\" (add) glyph shown on the submit action, matching VS Code's\n * agent-feedback input widget. Inlined as an SVG so the markdown editor doesn't\n * depend on the codicon font.\n */\nconst PLUS_SVG =\n\t`<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"currentColor\" aria-hidden=\"true\">`\n\t+ `<path d=\"M14 7v1H8v6H7V8H1V7h6V1h1v6h6z\"></path>`\n\t+ `</svg>`;\n\nexport interface CommentInputWidgetOptions {\n\t/** Placeholder shown while the textarea is empty. Defaults to \"Add Comment\". */\n\treadonly placeholder?: string;\n\t/** Called after the textarea changes size. */\n\treadonly onDidChangeSize?: () => void;\n\t/**\n\t * Called when the user submits a non-empty comment (Enter or the send\n\t * button). The text is trimmed; never called with an empty string.\n\t */\n\treadonly onSubmit?: (text: string) => void;\n\t/** Called when the user dismisses the input (Escape). */\n\treadonly onCancel?: () => void;\n}\n\n/**\n * A self-contained comment input box — a rounded panel with an auto-growing\n * textarea and a send button, styled after the gdocs/Word \"add a comment\"\n * affordance.\n *\n * This widget is *positioning-agnostic*: it only owns its own DOM and state.\n * A host (the comment-mode controller, or a fixture) mounts {@link element}\n * wherever it likes and is responsible for placing it relative to a selection.\n *\n * State is observable-driven (no framework): {@link value} reflects the live\n * textarea content; submit/cancel are reported through the option callbacks.\n */\nexport class CommentInputWidget extends Disposable {\n\treadonly element: HTMLElement;\n\n\tprivate readonly _textarea: HTMLTextAreaElement;\n\tprivate readonly _measure: HTMLSpanElement;\n\tprivate readonly _submitButton: HTMLButtonElement;\n\n\tprivate readonly _value = observableValue<string>(this, '');\n\t/** Live, untrimmed textarea content. */\n\tget value(): IObservable<string> { return this._value; }\n\n\t/** The raw textarea, exposed so a host can move focus into it (e.g. on Tab). */\n\tget inputElement(): HTMLTextAreaElement { return this._textarea; }\n\n\tconstructor(private readonly _options?: CommentInputWidgetOptions) {\n\t\tsuper();\n\n\t\tthis.element = document.createElement('div');\n\t\tthis.element.className = 'md-comment-input';\n\n\t\tthis._textarea = document.createElement('textarea');\n\t\tthis._textarea.className = 'md-comment-input-textarea';\n\t\tthis._textarea.rows = 1;\n\t\tthis._textarea.placeholder = _options?.placeholder ?? 'Add Comment';\n\t\tthis.element.appendChild(this._textarea);\n\n\t\t// Hidden element used to measure text width for auto-growing.\n\t\tthis._measure = document.createElement('span');\n\t\tthis._measure.className = 'md-comment-input-measure';\n\t\tthis._measure.setAttribute('aria-hidden', 'true');\n\t\tthis.element.appendChild(this._measure);\n\n\t\tconst footer = document.createElement('div');\n\t\tfooter.className = 'md-comment-input-actions';\n\t\tthis.element.appendChild(footer);\n\n\t\tthis._submitButton = document.createElement('button');\n\t\tthis._submitButton.type = 'button';\n\t\tthis._submitButton.className = 'md-comment-input-submit';\n\t\tthis._submitButton.innerHTML = PLUS_SVG;\n\t\tthis._submitButton.title = 'Comment';\n\t\tfooter.appendChild(this._submitButton);\n\n\t\t// Clicking anywhere in the panel padding (not the button) focuses the\n\t\t// textarea. Stop the event from reaching the host editor, which would\n\t\t// otherwise move focus/selection out of the box on every click inside it.\n\t\t// The editor starts selection drags on `pointerdown`, so guard that.\n\t\tconst onPanelPointerDown = (e: PointerEvent): void => {\n\t\t\te.stopPropagation();\n\t\t\tif (e.target === this._textarea || this._submitButton.contains(e.target as Node)) { return; }\n\t\t\te.preventDefault();\n\t\t\tthis._textarea.focus();\n\t\t};\n\t\tthis.element.addEventListener('pointerdown', onPanelPointerDown);\n\t\tthis._register({ dispose: () => this.element.removeEventListener('pointerdown', onPanelPointerDown) });\n\n\t\tconst onInput = (): void => {\n\t\t\tthis._value.set(this._textarea.value, undefined);\n\t\t\tthis._autoSize();\n\t\t};\n\t\tthis._textarea.addEventListener('input', onInput);\n\t\tthis._register({ dispose: () => this._textarea.removeEventListener('input', onInput) });\n\n\t\tconst onKeyDown = (e: KeyboardEvent): void => {\n\t\t\t// The box lives inside the editor element, so its keystrokes would\n\t\t\t// otherwise bubble to the editor's key handler (moving the editor\n\t\t\t// caret, deleting document text, etc.). Keep every key inside the box —\n\t\t\t// the textarea handles its own editing (typing, arrows, delete) natively.\n\t\t\te.stopPropagation();\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._options?.onCancel?.();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Enter submits; Shift+Enter inserts a newline.\n\t\t\tif (e.key === 'Enter' && !e.shiftKey) {\n\t\t\t\te.preventDefault();\n\t\t\t\tthis._submit();\n\t\t\t}\n\t\t};\n\t\tthis._textarea.addEventListener('keydown', onKeyDown);\n\t\tthis._register({ dispose: () => this._textarea.removeEventListener('keydown', onKeyDown) });\n\n\t\tconst onSubmitClick = (): void => this._submit();\n\t\tthis._submitButton.addEventListener('click', onSubmitClick);\n\t\tthis._register({ dispose: () => this._submitButton.removeEventListener('click', onSubmitClick) });\n\n\t\t// Keep the submit button enabled state in sync with the content.\n\t\tthis._register(autorun(reader => {\n\t\t\tconst hasText = this._value.read(reader).trim().length > 0;\n\t\t\tthis._submitButton.disabled = !hasText;\n\t\t\tthis.element.classList.toggle('md-comment-input-empty', !hasText);\n\t\t}));\n\n\t\tthis._autoSize();\n\t}\n\n\t/** Move focus into the textarea (caret at the end). */\n\tfocus(): void {\n\t\tthis._textarea.focus();\n\t\tconst end = this._textarea.value.length;\n\t\tthis._textarea.setSelectionRange(end, end);\n\t}\n\n\t/** Replace the textarea content. */\n\tsetText(text: string): void {\n\t\tthis._textarea.value = text;\n\t\tthis._value.set(text, undefined);\n\t\tthis._autoSize();\n\t}\n\n\t/** Clear the textarea. */\n\tclear(): void {\n\t\tthis.setText('');\n\t}\n\n\tprivate _submit(): void {\n\t\tconst text = this._textarea.value.trim();\n\t\tif (!text) { return; }\n\t\tthis._options?.onSubmit?.(text);\n\t}\n\n\tprivate _autoSize(): void {\n\t\t// Width: measure the text (or placeholder) and grow the textarea to fit,\n\t\t// clamped between a minimum and maximum — mirrors the reference widget so\n\t\t// the bubble hugs short content and wraps long content at the max width.\n\t\tconst text = this._textarea.value || this._textarea.placeholder;\n\t\tthis._measure.textContent = text;\n\t\tconst textWidth = this._measure.scrollWidth;\n\t\tconst minWidth = 150;\n\t\tconst maxWidth = 400;\n\t\tconst width = Math.min(Math.max(minWidth, textWidth + 10), maxWidth);\n\t\tthis._textarea.style.width = `${width}px`;\n\n\t\t// Height: reset to auto, then grow to fit the content.\n\t\tthis._textarea.style.height = 'auto';\n\t\t// While the textarea is detached (e.g. constructed before being mounted)\n\t\t// scrollHeight is 0; leaving height at `auto` keeps the natural one-row\n\t\t// height (and the placeholder visible) until a real measurement is\n\t\t// possible. Once mounted, grow to fit the content.\n\t\tconst scrollHeight = this._textarea.scrollHeight;\n\t\tif (scrollHeight > 0) {\n\t\t\tthis._textarea.style.height = `${scrollHeight}px`;\n\t\t}\n\t\tthis._options?.onDidChangeSize?.();\n\t}\n}\n","import { Disposable, autorun, type IReader } from '@vscode/observables';\nimport { OffsetRange } from '../../core/offsetRange.js';\nimport { Rect2D } from '../../core/geometry.js';\nimport type { EditorModel } from '../../model/editorModel.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport { CommentInputWidget } from './commentInputWidget.js';\n\n/** A comment the user submitted, with the source range it was anchored to. */\nexport interface CommentSubmission {\n\treadonly text: string;\n\treadonly range: OffsetRange;\n}\n\nexport interface CommentModeControllerOptions {\n\t/** Called when the user submits a comment for the current selection. */\n\treadonly onSubmit?: (submission: CommentSubmission) => void;\n\t/** Gap (px) between the bottom of the selection and the top of the input box. */\n\treadonly gap?: number;\n}\n\n/**\n * Comment mode — a gdocs/Word-style \"add a comment\" affordance layered on top of\n * the editor *without modifying it*. It reads the editor's public observables\n * ({@link EditorModel.readonlyMode}, {@link EditorModel.selection}) and the\n * exposed {@link EditorView.caretRect} geometry, and mounts a\n * {@link CommentInputWidget} into {@link EditorView.overlayContainer}.\n *\n * Behaviour:\n * - Only active in read-only mode (the \"review\" view).\n * - When the selection is non-empty, the input box appears next to the caret\n * (the selection's active end) but does NOT take focus, so keyboard selection\n * keeps working. Press Tab to move focus into the box, then type.\n * - The box appears on mouse-up, not mid-drag, so it doesn't flicker/jump\n * while a selection is being dragged out (keyboard selection shows at once).\n * - While the box has focus or holds a draft it is frozen in place (selection\n * changes, drags and clicks no longer move it). It is dismissed by Escape,\n * by submitting, or by blurring an empty box.\n * - The editor's logical caret geometry remains available for anchoring in\n * read-only mode even though the painted caret is hidden. While the box has\n * focus, `.md-comment-active` also suppresses the painted caret in any mode.\n */\nexport class CommentModeController extends Disposable {\n\tprivate readonly _widget: CommentInputWidget;\n\tprivate readonly _gap: number;\n\tprivate _visible = false;\n\tprivate _anchorX = 0;\n\tprivate _pinnedRange: OffsetRange | undefined;\n\t/**\n\t * The range a comment was just submitted for. The box stays hidden for it\n\t * until the selection changes, so submitting doesn't immediately re-summon an\n\t * empty box on the still-selected text.\n\t */\n\tprivate _submittedRange: OffsetRange | undefined;\n\n\tconstructor(\n\t\tprivate readonly _model: EditorModel,\n\t\tprivate readonly _view: EditorView,\n\t\tprivate readonly _options?: CommentModeControllerOptions,\n\t) {\n\t\tsuper();\n\t\tthis._gap = _options?.gap ?? 8;\n\n\t\tthis._widget = this._register(new CommentInputWidget({\n\t\t\tonDidChangeSize: () => {\n\t\t\t\tif (this._visible) {\n\t\t\t\t\tthis._layoutHorizontally();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonSubmit: text => this._submit(text),\n\t\t\tonCancel: () => this._hideAndRefocus(),\n\t\t}));\n\t\tconst el = this._widget.element;\n\t\tel.style.position = 'absolute';\n\t\tel.style.zIndex = '20';\n\t\tel.style.display = 'none';\n\t\tthis._view.overlayContainer.appendChild(el);\n\t\tthis._register({ dispose: () => el.remove() });\n\t\tthis._register({ dispose: () => this._view.element.classList.remove('md-comment-active') });\n\n\t\tconst resizeObserver = new ResizeObserver(() => {\n\t\t\tif (this._visible) {\n\t\t\t\tthis._layoutHorizontally();\n\t\t\t}\n\t\t});\n\t\tresizeObserver.observe(el);\n\t\tresizeObserver.observe(this._view.overlayContainer);\n\t\tthis._register({ dispose: () => resizeObserver.disconnect() });\n\n\t\tthis._register(autorun(reader => this._update(reader)));\n\n\t\tconst doc = this._view.element.ownerDocument;\n\n\t\t// Suppress the editor's painted caret while focus belongs to the comment\n\t\t// input. Read-only mode already hides it visually without removing the\n\t\t// geometry this controller uses for anchoring.\n\t\tconst onFocus = (): void => { this._view.element.classList.add('md-comment-active'); };\n\t\tthis._widget.inputElement.addEventListener('focus', onFocus);\n\t\tthis._register({ dispose: () => this._widget.inputElement.removeEventListener('focus', onFocus) });\n\n\t\t// Dismiss an empty box once focus leaves it (e.g. a click elsewhere). A\n\t\t// non-empty draft is preserved, and a focused box is never hidden — see\n\t\t// `_autoHide`. Deferred so focus has settled before we decide.\n\t\tconst onBlur = (): void => {\n\t\t\tthis._view.element.classList.remove('md-comment-active');\n\t\t\tdoc.defaultView?.setTimeout(() => this._autoHide(), 0);\n\t\t};\n\t\tthis._widget.inputElement.addEventListener('blur', onBlur);\n\t\tthis._register({ dispose: () => this._widget.inputElement.removeEventListener('blur', onBlur) });\n\n\t\t// Tab moves focus from the document into the visible box, so the user can\n\t\t// select with the keyboard first and then press Tab to start typing. The\n\t\t// editor itself does not handle Tab, so a plain bubble listener suffices.\n\t\tconst onKeyDown = (e: KeyboardEvent): void => {\n\t\t\tif (e.key !== 'Tab' || e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) { return; }\n\t\t\tif (!this._visible || this._widgetHasFocus()) { return; }\n\t\t\te.preventDefault();\n\t\t\tthis._widget.focus();\n\t\t};\n\t\tthis._view.element.addEventListener('keydown', onKeyDown);\n\t\tthis._register({ dispose: () => this._view.element.removeEventListener('keydown', onKeyDown) });\n\t}\n\n\tprivate _update(reader: IReader): void {\n\t\tconst readonly = this._model.readonlyMode.read(reader);\n\t\tconst selection = this._model.selection.read(reader);\n\t\tconst caretRect = this._view.caretRect.read(reader);\n\t\tconst isSelecting = this._model.isSelecting.read(reader);\n\t\tconst hasTypedText = this._widget.value.read(reader).trim().length > 0;\n\n\t\t// Leaving read-only mode tears the box down unconditionally.\n\t\tif (!readonly) {\n\t\t\tthis._hide();\n\t\t\treturn;\n\t\t}\n\n\t\t// Freeze the box while the user is engaged with it — it has focus or a\n\t\t// draft — so selection changes, drags and clicks no longer move or hide it.\n\t\t// They dismiss it via Escape, submit, or by clicking away.\n\t\tif (this._visible && (hasTypedText || this._widgetHasFocus())) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't react while a selection drag is in progress: wait for it to end so\n\t\t// the box doesn't flicker/jump while a selection is dragged out.\n\t\tif (isSelecting) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!selection || selection.isCollapsed || !caretRect) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't re-show the box for a range we just commented on; keep it hidden\n\t\t// until the user selects something else (then this suppression is cleared).\n\t\tif (this._submittedRange?.equals(selection.range)) {\n\t\t\tthis._autoHide();\n\t\t\treturn;\n\t\t}\n\t\tthis._submittedRange = undefined;\n\n\t\t// Anchor to the active end of the selection (where the caret is). A forward\n\t\t// selection's caret sits at the bottom — place the box below it; a backward\n\t\t// selection's caret sits at the top — place it above. This keeps the box next\n\t\t// to the user's cursor regardless of how large the selection is.\n\t\tthis._pinnedRange = selection.range;\n\t\tthis._show(caretRect, /* preferAbove */ !selection.isForward);\n\t}\n\n\tprivate _show(caretRect: Rect2D, preferAbove: boolean): void {\n\t\tconst el = this._widget.element;\n\n\t\t// Reveal before measuring so offset dimensions are valid.\n\t\tel.style.display = '';\n\t\tthis._visible = true;\n\n\t\t// Place the box on the caret's side, flipping only if that side has no room\n\t\t// within the visible viewport. Convert the editor-local caret through the\n\t\t// editor's coordinate boundary for the client-space fit test.\n\t\tconst widgetHeight = el.offsetHeight;\n\t\tconst viewport = this._getViewportRect();\n\t\tconst transform = this._view.coordinateSpace.capture();\n\t\tconst clientCaretRect = transform.toClientRect(caretRect);\n\t\tconst clientWidgetHeight = transform.toClientRect(Rect2D.fromPointSize(0, 0, 0, widgetHeight)).height;\n\t\tconst clientGap = transform.toClientRect(Rect2D.fromPointSize(0, 0, 0, this._gap)).height;\n\t\tconst caretTop = clientCaretRect.top;\n\t\tconst caretBottom = clientCaretRect.bottom;\n\t\tconst roomBelow = caretBottom + clientGap + clientWidgetHeight <= viewport.bottom;\n\t\tconst roomAbove = caretTop - clientGap - clientWidgetHeight >= viewport.top;\n\t\tconst placeAbove = preferAbove ? (roomAbove || !roomBelow) : (!roomBelow && roomAbove);\n\t\tconst topPx = placeAbove\n\t\t\t? caretRect.y - this._gap - widgetHeight\n\t\t\t: caretRect.y + caretRect.height + this._gap;\n\n\t\tthis._anchorX = caretRect.x;\n\t\tthis._layoutHorizontally();\n\t\tel.style.top = `${topPx}px`;\n\t}\n\n\tprivate _layoutHorizontally(): void {\n\t\tconst el = this._widget.element;\n\t\tconst containerWidth = this._view.overlayContainer.clientWidth;\n\t\tel.style.maxWidth = `${Math.max(0, containerWidth - this._gap)}px`;\n\t\tconst maxLeft = Math.max(0, containerWidth - el.offsetWidth - this._gap);\n\t\tel.style.left = `${Math.min(Math.max(0, this._anchorX), maxLeft)}px`;\n\t}\n\n\t/** Force-hide and clear the box (used by Escape and submit). */\n\tprivate _hide(): void {\n\t\tif (!this._visible) { return; }\n\t\tthis._visible = false;\n\t\tthis._pinnedRange = undefined;\n\t\tthis._widget.clear();\n\t\tthis._widget.element.style.display = 'none';\n\t\tthis._view.element.classList.remove('md-comment-active');\n\t}\n\n\t/**\n\t * Hide unless the user is engaged with the box: it has focus or holds a\n\t * non-empty draft. This preserves in-progress text and keeps a focused box\n\t * open (it is dismissed explicitly via Escape/submit, or by blurring it).\n\t */\n\tprivate _autoHide(): void {\n\t\tif (this._widgetHasFocus() || this._widget.value.get().trim().length > 0) { return; }\n\t\tthis._hide();\n\t}\n\n\tprivate _widgetHasFocus(): boolean {\n\t\tconst active = this._view.element.ownerDocument.activeElement;\n\t\treturn active !== null && this._widget.element.contains(active);\n\t}\n\n\t/**\n\t * The visible viewport (client coords) used for the flip-above decision: the\n\t * nearest scrollable ancestor of the editor. `.md-editor` itself spans the\n\t * full document height and never clips, so measuring against it would always\n\t * report room below. Falls back to the window when nothing scrolls.\n\t */\n\tprivate _getViewportRect(): { top: number; bottom: number } {\n\t\tconst win = this._view.element.ownerDocument.defaultView;\n\t\tlet el: HTMLElement | null = this._view.element;\n\t\twhile (el) {\n\t\t\tconst overflowY = win?.getComputedStyle(el).overflowY;\n\t\t\tif ((overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight) {\n\t\t\t\tconst rect = el.getBoundingClientRect();\n\t\t\t\treturn { top: rect.top, bottom: rect.bottom };\n\t\t\t}\n\t\t\tel = el.parentElement;\n\t\t}\n\t\treturn { top: 0, bottom: win?.innerHeight ?? 0 };\n\t}\n\n\tprivate _hideAndRefocus(): void {\n\t\tthis._hide();\n\t\tthis._view.focus();\n\t}\n\n\tprivate _submit(text: string): void {\n\t\tconst range = this._pinnedRange;\n\t\t// Remember the range so the box doesn't immediately reappear for the text\n\t\t// that is still selected after submitting.\n\t\tthis._submittedRange = range;\n\t\tthis._hideAndRefocus();\n\t\tif (range) {\n\t\t\tthis._options?.onSubmit?.({ text, range });\n\t\t}\n\t}\n}\n","import { observableValue, type IObservable, type ISettableObservable } from '@vscode/observables';\nimport type { OffsetRange } from '../../core/offsetRange.js';\n\n/** A persistent comment anchored to a source range. */\nexport interface Comment {\n\treadonly id: string;\n\t/** Source range the comment refers to (its highlighted region). */\n\treadonly range: OffsetRange;\n\t/** The comment text. */\n\treadonly body: string;\n\t/** Display name of the author, if any. */\n\treadonly author?: string;\n\t/** Creation time (epoch ms), used to render a relative timestamp. */\n\treadonly createdAt?: number;\n}\n\n/**\n * Seedable store of {@link Comment}s for the comment-mode contribution. Owns the\n * comment list and the shared hover state; it has no opinion on rendering or\n * persistence — a host seeds it via {@link set}/{@link add} and observes\n * {@link comments}.\n */\nexport class CommentsModel {\n\tprivate readonly _comments = observableValue<readonly Comment[]>(this, []);\n\t/** Monotonic counter for ids of comments created via {@link create}. */\n\tprivate _sequence = 0;\n\t/** The current comments, in insertion order. */\n\tget comments(): IObservable<readonly Comment[]> { return this._comments; }\n\n\t/**\n\t * The comment currently hovered (by its card or its highlight), or\n\t * `undefined`. Shared so the card and the highlight can react together.\n\t */\n\treadonly hoveredId: ISettableObservable<string | undefined> = observableValue<string | undefined>(this, undefined);\n\n\t/** Replace the whole comment set. */\n\tset(comments: readonly Comment[]): void {\n\t\tthis._comments.set(comments, undefined);\n\t}\n\n\t/**\n\t * Create a comment from a user submission and append it, generating its `id`\n\t * and `createdAt` here so id/time allocation stays the store's concern (the\n\t * UI only supplies the range and text). Returns the created comment.\n\t */\n\tcreate(input: { range: OffsetRange; body: string; author?: string }): Comment {\n\t\tconst comment: Comment = {\n\t\t\tid: `comment-${++this._sequence}`,\n\t\t\trange: input.range,\n\t\t\tbody: input.body,\n\t\t\tauthor: input.author,\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\t\tthis.add(comment);\n\t\treturn comment;\n\t}\n\n\t/** Append a comment. */\n\tadd(comment: Comment): void {\n\t\tthis._comments.set([...this._comments.get(), comment], undefined);\n\t}\n\n\t/** Remove a comment by id. */\n\tremove(id: string): void {\n\t\tthis._comments.set(this._comments.get().filter(c => c.id !== id), undefined);\n\t}\n}\n","import { Disposable, autorun, type IObservable, type IReader } from '@vscode/observables';\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport { buildConnectedPath } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport type { Comment, CommentsModel } from './commentsModel.js';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n/** Layout constants (px). */\nconst RAIL_MIN = 260;\nconst RAIL_MAX = 320;\nconst RAIL_FRACTION = 0.32;\n/** Gap between the content's right edge and the rail. */\nconst RAIL_GAP = 28;\n/** Gap between the rail and the editor's right edge. */\nconst RAIL_EDGE = 16;\n/** Vertical gap between stacked cards. */\nconst CARD_GAP = 12;\n/** Where on the card the leader attaches, measured from the card top. */\nconst LEADER_CARD_INSET = 18;\n/** Corner radius of the range highlight. */\nconst HIGHLIGHT_RADIUS = 4;\n/** Stroke width of the leader line (must match .md-comment-leader-path). */\nconst LEADER_WIDTH = 2;\n/** How far the leader starts inside the highlight so the seam is hidden under\n * the (same-colored) fill. */\nconst LEADER_OVERLAP = 10;\n\n/** Per-comment DOM + state, reconciled against the model's comment list. */\ninterface CommentEntry {\n\tcomment: Comment;\n\trects: IObservable<readonly SelectionRect[]>;\n\treadonly group: SVGGElement;\n\treadonly shapePath: SVGPathElement;\n\treadonly leaderPath: SVGPathElement;\n\treadonly card: HTMLElement;\n\treadonly bodyEl: HTMLElement;\n\treadonly authorEl: HTMLElement;\n\treadonly avatarEl: HTMLElement;\n\treadonly timeEl: HTMLElement;\n\treadonly disposables: { dispose(): void }[];\n}\n\n/**\n * Renders persistent comments as a gdocs-style side rail: each comment's range\n * is highlighted (reusing the editor's selection geometry via\n * {@link EditorView.rangeRects}), a leader line curves from the bottom of that\n * highlight to a card stacked in the right rail, and cards never overlap.\n *\n * Everything is mounted into {@link EditorView.overlayContainer} so it shares\n * the selection/caret coordinate space and scrolls with the document. When the\n * editor's natural right margin is too narrow for the rail, the view reserves\n * proportional space by padding the editor on the right — but only while there\n * are comments.\n */\nexport class CommentsView extends Disposable {\n\tprivate readonly _layer: SVGSVGElement;\n\tprivate readonly _entries = new Map<string, CommentEntry>();\n\n\tconstructor(\n\t\tprivate readonly _model: CommentsModel,\n\t\tprivate readonly _view: EditorView,\n\t) {\n\t\tsuper();\n\n\t\tthis._layer = this._createLayer('md-comment-shapes');\n\t\tthis._view.overlayContainer.appendChild(this._layer);\n\n\t\tthis._register({\n\t\t\tdispose: () => {\n\t\t\t\tthis._layer.remove();\n\t\t\t\tfor (const entry of this._entries.values()) { this._disposeEntry(entry); }\n\t\t\t\tthis._entries.clear();\n\t\t\t\tthis._view.element.style.paddingRight = '';\n\t\t\t},\n\t\t});\n\n\t\tthis._register(autorun(reader => this._update(reader)));\n\t}\n\n\tprivate _createLayer(className: string): SVGSVGElement {\n\t\tconst svg = document.createElementNS(SVG_NS, 'svg');\n\t\tsvg.setAttribute('class', className);\n\t\treturn svg;\n\t}\n\n\tprivate _update(reader: IReader): void {\n\t\tconst comments = this._model.comments.read(reader);\n\t\tconst hoveredId = this._model.hoveredId.read(reader);\n\n\t\tthis._reconcile(comments);\n\n\t\t// Read every comment's rects so the autorun re-runs when the layout\n\t\t// changes (e.g. reflow, resize).\n\t\tconst items = comments.map(comment => {\n\t\t\tconst entry = this._entries.get(comment.id)!;\n\t\t\treturn { entry, rects: entry.rects.read(reader) };\n\t\t});\n\n\t\tthis._layout(items);\n\t\tthis._applyHover(hoveredId);\n\t}\n\n\t/** Create/update/remove per-comment DOM to match `comments`. */\n\tprivate _reconcile(comments: readonly Comment[]): void {\n\t\tconst seen = new Set<string>();\n\t\tfor (const comment of comments) {\n\t\t\tseen.add(comment.id);\n\t\t\tconst existing = this._entries.get(comment.id);\n\t\t\tif (!existing) {\n\t\t\t\tthis._entries.set(comment.id, this._createEntry(comment));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Re-anchor if the range changed; refresh content always.\n\t\t\tif (existing.comment.range !== comment.range) {\n\t\t\t\texisting.rects = this._view.rangeRects(comment.range);\n\t\t\t}\n\t\t\texisting.comment = comment;\n\t\t\tthis._fillCard(existing);\n\t\t}\n\t\tfor (const [id, entry] of this._entries) {\n\t\t\tif (!seen.has(id)) {\n\t\t\t\tthis._disposeEntry(entry);\n\t\t\t\tthis._entries.delete(id);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _createEntry(comment: Comment): CommentEntry {\n\t\t// Highlight fill and leader stroke live in one opacity group and share a\n\t\t// solid color, so their overlap never darkens and the seam is invisible.\n\t\t// The leader is drawn first (under the fill) so its overlap is hidden.\n\t\tconst group = document.createElementNS(SVG_NS, 'g');\n\t\tgroup.setAttribute('class', 'md-comment-group');\n\t\tthis._layer.appendChild(group);\n\n\t\tconst leaderPath = document.createElementNS(SVG_NS, 'path');\n\t\tleaderPath.setAttribute('class', 'md-comment-leader-path');\n\t\tgroup.appendChild(leaderPath);\n\n\t\tconst shapePath = document.createElementNS(SVG_NS, 'path');\n\t\tshapePath.setAttribute('class', 'md-comment-shape-path');\n\t\tgroup.appendChild(shapePath);\n\n\t\tconst card = document.createElement('div');\n\t\tcard.className = 'md-comment-card';\n\n\t\tconst header = document.createElement('div');\n\t\theader.className = 'md-comment-card-header';\n\t\tconst avatarEl = document.createElement('span');\n\t\tavatarEl.className = 'md-comment-avatar';\n\t\tconst authorEl = document.createElement('span');\n\t\tauthorEl.className = 'md-comment-author';\n\t\tconst timeEl = document.createElement('span');\n\t\ttimeEl.className = 'md-comment-time';\n\t\tconst menuEl = document.createElement('span');\n\t\tmenuEl.className = 'md-comment-menu';\n\t\tmenuEl.textContent = '\\u22EF'; // ⋯\n\t\theader.append(avatarEl, authorEl, timeEl, menuEl);\n\n\t\tconst bodyEl = document.createElement('div');\n\t\tbodyEl.className = 'md-comment-body';\n\n\t\tconst reply = document.createElement('button');\n\t\treply.type = 'button';\n\t\treply.className = 'md-comment-reply';\n\t\treply.textContent = 'Reply';\n\n\t\tcard.append(header, bodyEl, reply);\n\t\tthis._view.overlayContainer.appendChild(card);\n\n\t\tconst entry: CommentEntry = {\n\t\t\tcomment,\n\t\t\trects: this._view.rangeRects(comment.range),\n\t\t\tgroup, shapePath, leaderPath,\n\t\t\tcard, bodyEl, authorEl, avatarEl, timeEl,\n\t\t\tdisposables: [],\n\t\t};\n\n\t\tconst setHover = (on: boolean): void => this._model.hoveredId.set(on ? comment.id : undefined, undefined);\n\t\tconst enter = (): void => setHover(true);\n\t\tconst leave = (): void => setHover(false);\n\t\t// Hover is driven from the card only; the highlight layer stays\n\t\t// non-interactive so it never blocks selecting the underlying text.\n\t\tcard.addEventListener('mouseenter', enter);\n\t\tcard.addEventListener('mouseleave', leave);\n\t\tentry.disposables.push({\n\t\t\tdispose: () => {\n\t\t\t\tcard.removeEventListener('mouseenter', enter);\n\t\t\t\tcard.removeEventListener('mouseleave', leave);\n\t\t\t},\n\t\t});\n\n\t\tthis._fillCard(entry);\n\t\treturn entry;\n\t}\n\n\tprivate _fillCard(entry: CommentEntry): void {\n\t\tconst { comment } = entry;\n\t\tconst author = comment.author ?? 'You';\n\t\tentry.authorEl.textContent = author;\n\t\tentry.avatarEl.textContent = _initials(author);\n\t\tentry.timeEl.textContent = comment.createdAt !== undefined ? _relativeTime(comment.createdAt) : '';\n\t\tentry.bodyEl.textContent = comment.body;\n\t}\n\n\tprivate _disposeEntry(entry: CommentEntry): void {\n\t\tfor (const d of entry.disposables) { d.dispose(); }\n\t\tentry.group.remove();\n\t\tentry.card.remove();\n\t}\n\n\t/** Position highlights, cards (stacked) and leader lines. */\n\tprivate _layout(items: readonly { entry: CommentEntry; rects: readonly SelectionRect[] }[]): void {\n\t\tconst root = this._view.element;\n\t\tconst overlay = this._view.overlayContainer;\n\n\t\tif (items.length === 0) {\n\t\t\troot.style.paddingRight = '';\n\t\t\tthis._layer.style.display = 'none';\n\t\t\treturn;\n\t\t}\n\t\tthis._layer.style.display = '';\n\n\t\t// --- Reserve rail space (only when comments exist). Compute the target\n\t\t// right padding analytically from stable inputs, so it is idempotent and\n\t\t// does not thrash the layout: the editor's border-box width doesn't change\n\t\t// with padding, and the content column is centered (margin-inline:auto)\n\t\t// with a known max-width. We deliberately avoid the old \"clear padding →\n\t\t// measure → re-apply\" dance: now that the editor re-measures on reflow,\n\t\t// toggling padding to measure would oscillate.\n\t\tconst rootWidth = this._view.coordinateSpace.capture().toLocalRect(root.getBoundingClientRect()).width;\n\t\tconst cs = getComputedStyle(overlay);\n\t\tconst maxW = parseFloat(cs.maxWidth);\n\t\tconst padX = (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight) || 0);\n\t\tconst borderX = (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth) || 0);\n\t\t// Full outer width of the content column at its max-width (accounting for\n\t\t// box-sizing). `NaN` max-width (limited mode off) → content spans the root.\n\t\tconst contentMaxOuter = Number.isNaN(maxW)\n\t\t\t? rootWidth\n\t\t\t: (cs.boxSizing === 'border-box' ? maxW : maxW + padX + borderX);\n\t\t// The natural right margin when no rail padding is applied (content centered).\n\t\tconst naturalRight = Math.max(0, (rootWidth - Math.min(contentMaxOuter, rootWidth)) / 2);\n\n\t\tconst railWidth = Math.round(Math.max(RAIL_MIN, Math.min(RAIL_MAX, rootWidth * RAIL_FRACTION)));\n\t\tconst need = railWidth + RAIL_GAP + RAIL_EDGE;\n\t\t// While the content still has margins, padding re-centers it, so only half\n\t\t// of each added pixel becomes right margin — reserve twice the shortfall.\n\t\t// But cap at `need`: once the content fills the padding box (no margins),\n\t\t// every added pixel becomes right gap, so `need` is all that's required.\n\t\t// The old code used the uncapped `2 × shortfall`, which in narrow viewports\n\t\t// massively over-reserved and collapsed the content column.\n\t\tconst pad = naturalRight >= need ? 0 : Math.min(2 * (need - naturalRight), need);\n\t\tconst padStr = pad > 0 ? `${Math.ceil(pad)}px` : '';\n\t\tif (root.style.paddingRight !== padStr) {\n\t\t\troot.style.paddingRight = padStr;\n\t\t}\n\n\t\t// Re-capture after reservation because centering may move the overlay's\n\t\t// local origin relative to the root.\n\t\tconst rootRect = this._view.coordinateSpace.capture().toLocalRect(root.getBoundingClientRect());\n\t\tconst railLeftLocal = rootRect.right - RAIL_EDGE - railWidth;\n\t\t// Right edge of the content box (overlay-local): the leader runs straight to\n\t\t// here (so it never crosses text) and only curves beyond it, in the margin.\n\t\tconst contentRightLocal = overlay.clientWidth;\n\n\t\t// Desired vertical anchors.\n\t\tconst placed = items.map(({ entry, rects }) => {\n\t\t\tentry.card.style.left = `${railLeftLocal}px`;\n\t\t\tentry.card.style.width = `${railWidth}px`;\n\t\t\tconst anchor = _lineStart(rects);\n\t\t\tconst desiredTop = rects.length > 0 ? Math.min(...rects.map(r => r.y)) : 0;\n\t\t\treturn { entry, rects, anchor, desiredTop };\n\t\t});\n\n\t\t// Stack: sort by desired top, push each down so they never overlap.\n\t\tplaced.sort((a, b) => a.desiredTop - b.desiredTop);\n\t\tlet prevBottom = -Infinity;\n\t\tfor (const p of placed) {\n\t\t\tconst top = Math.max(p.desiredTop, prevBottom + CARD_GAP);\n\t\t\tp.entry.card.style.top = `${top}px`;\n\t\t\tconst height = p.entry.card.offsetHeight;\n\t\t\tprevBottom = top + height;\n\n\t\t\t// The highlight is a filled shape painted exactly like a normal\n\t\t\t// selection (same rects, same rounded corners). The leader is a\n\t\t\t// same-colored stroke drawn *under* the fill, starting inside the\n\t\t\t// highlight (its seam hidden by the fill) with its bottom edge on the\n\t\t\t// selection bottom; it runs straight through the content, then curves\n\t\t\t// to the card in the margin.\n\t\t\tp.entry.shapePath.setAttribute('d', buildConnectedPath(p.rects, HIGHLIGHT_RADIUS));\n\t\t\tp.entry.leaderPath.setAttribute('d', p.anchor\n\t\t\t\t? _leaderLine(p.anchor, contentRightLocal, { x: railLeftLocal, y: top + LEADER_CARD_INSET })\n\t\t\t\t: '');\n\t\t}\n\t}\n\n\tprivate _applyHover(hoveredId: string | undefined): void {\n\t\tfor (const [id, entry] of this._entries) {\n\t\t\tconst hovered = id === hoveredId;\n\t\t\tentry.card.classList.toggle('md-comment-card-hovered', hovered);\n\t\t\tentry.group.classList.toggle('md-comment-group-hovered', hovered);\n\t\t}\n\t}\n}\n\n/** Where the leader leaves the highlight: a few px inside the squared bottom-right\n * corner, with the y centered on the stroke so the stroke's bottom edge sits\n * exactly on the selection's bottom edge. The x starts inside the highlight by\n * {@link LEADER_OVERLAP} so the seam is hidden under the (same-colored) fill. */\nfunction _lineStart(rects: readonly SelectionRect[]): { x: number; y: number } | undefined {\n\tif (rects.length === 0) { return undefined; }\n\tlet best = rects[0];\n\tfor (const r of rects) {\n\t\tif (r.y + r.height > best.y + best.height) { best = r; }\n\t}\n\tconst rightEdge = best.x + best.width;\n\tconst x = Math.max(best.x, rightEdge - LEADER_OVERLAP);\n\treturn { x, y: best.y + best.height - LEADER_WIDTH / 2 };\n}\n\n/**\n * Leader centerline (stroked): starts horizontal along the selection bottom from\n * `start` to `bendX` (content right edge) so it never crosses text and leaves\n * the highlight tangentially, then a smooth cubic in the margin to `to` (the\n * card). The straight→curve join is tangent-continuous, so the whole line is\n * smooth.\n */\nfunction _leaderLine(start: { x: number; y: number }, bendX: number, to: { x: number; y: number }): string {\n\tconst bend = Math.max(bendX, start.x + 12);\n\tconst dx = to.x - bend;\n\tconst c1x = bend + dx * 0.55;\n\tconst c2x = to.x - dx * 0.45;\n\treturn `M ${start.x} ${start.y} L ${bend} ${start.y} C ${c1x} ${start.y}, ${c2x} ${to.y}, ${to.x} ${to.y}`;\n}\n\nfunction _initials(name: string): string {\n\tconst parts = name.trim().split(/\\s+/).filter(Boolean);\n\tif (parts.length === 0) { return '?'; }\n\tconst first = parts[0][0] ?? '';\n\tconst second = parts.length > 1 ? parts[parts.length - 1][0] ?? '' : '';\n\treturn (first + second).toUpperCase();\n}\n\nfunction _relativeTime(epochMs: number): string {\n\tconst deltaSec = Math.max(0, Math.round((Date.now() - epochMs) / 1000));\n\tif (deltaSec < 60) { return 'just now'; }\n\tconst min = Math.round(deltaSec / 60);\n\tif (min < 60) { return `${min}m ago`; }\n\tconst hours = Math.round(min / 60);\n\tif (hours < 24) { return `${hours}h ago`; }\n\tconst days = Math.round(hours / 24);\n\treturn `${days}d ago`;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Shared geometry for the \"stacked card\" comment presenters (the VS Code V1 and\n// V2 designs). Each comment gets one fixed-width card anchored to the editor's\n// right edge, and cards are stacked so they never overlap one another (they may\n// overlap the text, like an overlay widget). Extracted so both adapters share\n// one implementation.\n//\n\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\n\n/** A card to place: its DOM element and the rects of its anchored source range. */\nexport interface StackItem {\n readonly element: HTMLElement;\n readonly rects: readonly SelectionRect[];\n}\n\n/** Vertical gap between stacked cards. */\nexport const RAIL_GAP = 12;\n/** Inset of each card's right edge from the editor's right edge. */\nexport const RIGHT_INSET = 8;\n\n/**\n * Right-align and vertically stack `items`. The overlay layer lives inside the\n * centered, max-width content box, so the editor-relative right edge is\n * converted to overlay-local coordinates via `offsetLeft`. Pure DOM writes over\n * already-resolved rects, so the caller decides when to run it (an autorun for\n * comment/reflow changes, a ResizeObserver for width changes).\n *\n * Cards whose range has not been measured yet (no rects) are hidden rather than\n * parked at the top-left, so there is no flash before the editor's first\n * measurement anchors them.\n */\nexport function layoutRightAlignedStack(view: EditorView, items: readonly StackItem[]): void {\n const el = view.element;\n const overlay = view.overlayContainer;\n const rightEdge = (el.clientWidth - RIGHT_INSET) - overlay.offsetLeft;\n\n const placed: { element: HTMLElement; y: number }[] = [];\n for (const item of items) {\n if (item.rects.length === 0) {\n // Not measured yet — hide (keeps layout box, so offsetWidth stays\n // valid) until a re-run has real geometry to anchor to.\n item.element.style.visibility = 'hidden';\n continue;\n }\n item.element.style.visibility = '';\n placed.push({ element: item.element, y: Math.min(...item.rects.map(r => r.y)) });\n }\n\n placed.sort((a, b) => a.y - b.y);\n\n let prevBottom = -Infinity;\n for (const p of placed) {\n const top = Math.max(p.y, prevBottom + RAIL_GAP);\n const left = rightEdge - p.element.offsetWidth;\n p.element.style.left = `${left}px`;\n p.element.style.top = `${top}px`;\n prevBottom = top + p.element.offsetHeight;\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Shared base for the \"stacked card\" comment presenters (VS Code V1 and V2).\n// Owns the token-wrapped overlay layer, reconciles one card per comment against\n// the model, and keeps them right-aligned + stacked. Subclasses only say how to\n// build a card from a Comment.\n//\n// Two triggers drive the layout, because the geometry has two independent\n// inputs: the autorun re-runs when comments or their rects change (edits,\n// reflow), and a ResizeObserver re-runs when the editor resizes (width /\n// centering changes that don't touch the rects). Without the observer the\n// horizontal position would go stale on resize.\n//\n\nimport { Disposable, autorun, type IObservable } from '@vscode/observables';\nimport type { SelectionRect } from '../../view/parts/selectionView.js';\nimport type { EditorView } from '../../view/editorView.js';\nimport type { Comment, CommentsModel } from '../comments/commentsModel.js';\nimport type { ICommentsPresenter, CommentsPresenterContext } from '../comments/commentsPresenter.js';\nimport { layoutRightAlignedStack, type StackItem } from './stackedRailLayout.js';\n\n/** The minimal widget contract a subclass must produce. */\nexport interface StackWidget {\n readonly element: HTMLElement;\n dispose(): void;\n}\n\ninterface Entry {\n readonly widget: StackWidget;\n readonly rects: IObservable<readonly SelectionRect[]>;\n}\n\nexport abstract class StackedCommentsPresenter extends Disposable implements ICommentsPresenter {\n private readonly _layer: HTMLElement;\n private readonly _entries = new Map<string, Entry>();\n private _order: readonly string[] = [];\n\n // Public so subclasses inherit a public constructor (the class is abstract,\n // so it still cannot be instantiated directly).\n constructor(\n protected readonly model: CommentsModel,\n protected readonly view: EditorView,\n protected readonly context?: CommentsPresenterContext,\n ) {\n super();\n // Token-wrapped overlay layer (supplies the `--vscode-*` theme variables\n // the card CSS consumes) that scrolls with the content and lets cards\n // overlap the text.\n this._layer = document.createElement('div');\n this._layer.className = context?.theme === 'light' ? 'vscode-comments-light' : 'vscode-comments-dark';\n this._layer.style.position = 'absolute';\n this._layer.style.inset = '0';\n this._layer.style.pointerEvents = 'none';\n this._layer.style.overflow = 'visible';\n // The `.vscode-comments-*` token wrapper paints `--vscode-editor-background`;\n // override it so this overlay never covers the editor content behind it.\n this._layer.style.background = 'transparent';\n this.view.overlayContainer.appendChild(this._layer);\n\n this._register({\n dispose: () => {\n for (const e of this._entries.values()) { e.widget.dispose(); }\n this._entries.clear();\n this._layer.remove();\n },\n });\n\n this._register(autorun(reader => {\n const comments = this.model.comments.read(reader);\n this._reconcile(comments);\n // Subscribe to each range's rects so reflow re-runs the layout.\n for (const c of comments) { this._entries.get(c.id)!.rects.read(reader); }\n this._relayout();\n }));\n\n // Editor width / centering changes don't touch the rects, so re-run the\n // (horizontal) layout when the element resizes too.\n const resizeObserver = new ResizeObserver(() => this._relayout());\n resizeObserver.observe(this.view.element);\n this._register({ dispose: () => resizeObserver.disconnect() });\n }\n\n /** Build the card DOM for a comment. Called once per new comment. */\n protected abstract createWidget(comment: Comment): StackWidget;\n\n private _reconcile(comments: readonly Comment[]): void {\n this._order = comments.map(c => c.id);\n const seen = new Set(this._order);\n for (const comment of comments) {\n if (this._entries.has(comment.id)) { continue; }\n const widget = this.createWidget(comment);\n // Absolutely positioned so layoutRightAlignedStack's left/top apply\n // (not every widget sets this in its own CSS, e.g. the V2 card).\n widget.element.style.position = 'absolute';\n widget.element.style.pointerEvents = 'auto';\n this._layer.appendChild(widget.element);\n this._entries.set(comment.id, { widget, rects: this.view.rangeRects(comment.range) });\n }\n for (const [id, entry] of this._entries) {\n if (!seen.has(id)) {\n entry.widget.dispose();\n this._entries.delete(id);\n }\n }\n }\n\n private _relayout(): void {\n const items: StackItem[] = this._order\n .map(id => this._entries.get(id))\n .filter((e): e is Entry => e !== undefined)\n .map(e => ({ element: e.widget.element, rects: e.rects.get() }));\n layoutRightAlignedStack(this.view, items);\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Pixel-for-pixel replica of VS Code's agent-feedback editor widget\n// (src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts,\n// class AgentFeedbackEditorWidget). It builds the EXACT same DOM tree and reuses\n// the verbatim CSS (vscodeCommentWidget.css) so we can compare our own comment\n// rendering against VS Code's. It has NO Monaco / workbench-service dependency:\n// the comment body is rendered with a tiny markdown shim and codicons are drawn\n// via unicode placeholders (see vscodeCommentTokens.css).\n//\n\nexport type VscodeCommentSource = 'agentFeedback' | 'prReview';\n\n/** Mirrors AgentFeedbackKind; drives the type badge (see {@link _typeLabel}). */\nexport type VscodeCommentKind = 'userReview' | 'prReview' | 'agentReview';\n\nexport interface VscodeCommentSuggestionEdit {\n readonly startLine: number;\n readonly endLine?: number;\n readonly newText: string;\n}\n\nexport interface VscodeComment {\n readonly id: string;\n readonly source: VscodeCommentSource;\n readonly kind: VscodeCommentKind;\n readonly startLine: number;\n readonly endLine?: number;\n readonly text: string;\n readonly suggestion?: { readonly edits: readonly VscodeCommentSuggestionEdit[] };\n readonly replies?: readonly string[];\n}\n\nexport interface VscodeCommentWidgetOptions {\n readonly expanded?: boolean;\n readonly focusedCommentId?: string;\n}\n\n/** Per-item action affordances, mirroring VS Code's `ICommentItemActions`. */\ninterface ItemActions {\n edit: HTMLAnchorElement;\n remove: HTMLAnchorElement;\n addReply: HTMLAnchorElement;\n setEnabled(enabled: boolean): void;\n}\n\nconst DOM_HELPER_TAG = /^([a-z0-9]+)/i;\n\n/** VS Code's `dom.$('tag.a.b')` shorthand, reduced to what we use. */\nfunction $(selector: string): HTMLElement {\n const tag = DOM_HELPER_TAG.exec(selector)?.[1] ?? 'div';\n const el = document.createElement(tag);\n const classes = selector.slice(tag.length).split('.').filter(Boolean);\n if (classes.length) {\n el.className = classes.join(' ');\n }\n return el;\n}\n\n/**\n * Inline Feather-style icons (stroke=\"currentColor\"), matching the crisp look of\n * the editor's read-only lock toggle — far nicer than a unicode/font glyph. The\n * DOM keeps the real `codicon codicon-<name>` classes; the SVG is the glyph.\n */\nfunction feather(inner: string): string {\n return `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nconst ICON_SVGS: Record<string, string> = {\n 'comment': feather('<path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>'),\n 'comment-discussion': feather('<path d=\"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z\"></path>'),\n 'chevron-down': feather('<polyline points=\"6 9 12 15 18 9\"></polyline>'),\n 'chevron-up': feather('<polyline points=\"18 15 12 9 6 15\"></polyline>'),\n 'edit': feather('<path d=\"M12 20h9\"></path><path d=\"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z\"></path>'),\n 'close': feather('<line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line><line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>'),\n};\n\n/** A codicon span carrying the inline Feather SVG for `name`. */\nfunction icon(name: string): HTMLElement {\n const span = $(`span.codicon.codicon-${name}`);\n span.setAttribute('aria-hidden', 'true');\n span.innerHTML = ICON_SVGS[name] ?? '';\n return span;\n}\n\n/**\n * Minimal markdown shim producing the same `.rendered-markdown > p` shape VS\n * Code's MarkdownRenderer emits for these single-paragraph comments, with inline\n * `` `code` `` support.\n */\nfunction renderMarkdown(text: string): HTMLElement {\n const wrap = $('div.rendered-markdown');\n const p = document.createElement('p');\n for (const part of text.split(/(`[^`]+`)/g)) {\n if (/^`[^`]+`$/.test(part)) {\n const code = document.createElement('code');\n code.textContent = part.slice(1, -1);\n p.appendChild(code);\n } else if (part) {\n p.appendChild(document.createTextNode(part));\n }\n }\n wrap.appendChild(p);\n return wrap;\n}\n\nexport class VscodeCommentWidget {\n private readonly _domNode: HTMLElement;\n private readonly _headerNode: HTMLElement;\n private readonly _titleNode: HTMLElement;\n private readonly _toggleButton: HTMLElement;\n private readonly _bodyNode: HTMLElement;\n\n private _isExpanded = false;\n private _focusedId: string | undefined;\n private readonly _itemElements = new Map<string, HTMLElement>();\n private readonly _disposables: (() => void)[] = [];\n\n get element(): HTMLElement { return this._domNode; }\n\n constructor(\n private readonly _comments: readonly VscodeComment[],\n options?: VscodeCommentWidgetOptions,\n ) {\n // Root — starts collapsed (matches production).\n this._domNode = $('div.agent-feedback-widget');\n this._domNode.classList.add('collapsed');\n this._domNode.tabIndex = -1;\n this._domNode.setAttribute('widgetid', 'agent-feedback-widget-0');\n\n // Header: comment icon + title + spacer + toggle.\n this._headerNode = $('div.agent-feedback-widget-header');\n this._headerNode.appendChild(icon('comment'));\n\n this._titleNode = $('span.agent-feedback-widget-title');\n this._updateTitle();\n this._headerNode.appendChild(this._titleNode);\n\n this._headerNode.appendChild($('span.agent-feedback-widget-spacer'));\n\n this._toggleButton = $('div.agent-feedback-widget-toggle');\n this._updateToggleButton();\n this._headerNode.appendChild(this._toggleButton);\n\n this._domNode.appendChild(this._headerNode);\n\n // Body (collapsible) — starts collapsed.\n this._bodyNode = $('div.agent-feedback-widget-body');\n this._bodyNode.classList.add('collapsed');\n this._buildFeedbackItems();\n this._domNode.appendChild(this._bodyNode);\n\n // Arrow pointer.\n this._domNode.appendChild($('div.agent-feedback-widget-arrow'));\n\n this._setupEventHandlers();\n\n this._domNode.classList.add('visible');\n\n if (options?.expanded) { this.expand(); }\n if (options?.focusedCommentId) { this.focusFeedback(options.focusedCommentId); }\n }\n\n // --- Header ----------------------------------------------------------\n\n private _updateTitle(): void {\n const count = this._comments.length;\n this._titleNode.textContent = count === 1 ? this._comments[0].text : `${count} comments`;\n }\n\n private _updateToggleButton(): void {\n this._toggleButton.textContent = '';\n if (this._isExpanded) {\n this._toggleButton.appendChild(icon('chevron-up'));\n this._toggleButton.title = 'Collapse';\n } else {\n this._toggleButton.appendChild(icon('chevron-down'));\n this._toggleButton.title = 'Expand';\n }\n }\n\n private _setupEventHandlers(): void {\n this._listen(this._toggleButton, 'click', e => { e.stopPropagation(); this._toggleExpanded(); });\n this._listen(this._headerNode, 'click', () => this._toggleExpanded());\n }\n\n private _toggleExpanded(): void {\n if (this._isExpanded) { this.collapse(); } else { this.expand(); }\n }\n\n // --- Items -----------------------------------------------------------\n\n private _buildFeedbackItems(): void {\n this._bodyNode.textContent = '';\n this._itemElements.clear();\n\n for (const comment of this._comments) {\n const item = $('div.agent-feedback-widget-item');\n item.classList.add(`agent-feedback-widget-item-${comment.source}`);\n if (comment.suggestion) {\n item.classList.add('agent-feedback-widget-item-suggestion');\n }\n this._itemElements.set(comment.id, item);\n\n // Header: meta (line-info + optional type badge) + hover actions.\n const itemHeader = $('div.agent-feedback-widget-item-header');\n const itemMeta = $('div.agent-feedback-widget-item-meta');\n\n const lineInfo = $('span.agent-feedback-widget-line-info');\n lineInfo.textContent = this._lineLabel(comment.startLine, comment.endLine);\n itemMeta.appendChild(lineInfo);\n\n const typeLabel = this._typeLabel(comment.kind);\n if (typeLabel) {\n const badge = $('span.agent-feedback-widget-item-type');\n badge.textContent = typeLabel;\n itemMeta.appendChild(badge);\n }\n itemHeader.appendChild(itemMeta);\n\n const text = $('div.agent-feedback-widget-text');\n const actions = this._buildItemActions(comment, item, text);\n itemHeader.appendChild(actions.container);\n item.appendChild(itemHeader);\n\n // Body text.\n text.appendChild(renderMarkdown(comment.text));\n item.appendChild(text);\n\n if (comment.suggestion?.edits.length) {\n item.appendChild(this._renderSuggestion(comment));\n }\n if (comment.replies?.length) {\n item.appendChild(this._renderReplies(comment.replies));\n }\n\n // Click navigates/focuses (ignoring action bar, reply input and text\n // selections) — mirrors production.\n this._listen(item, 'click', e => {\n const target = e.target as HTMLElement | null;\n if (target?.closest('.monaco-action-bar') || target?.closest('.agent-feedback-widget-add-reply')) {\n return;\n }\n if (target?.closest('.agent-feedback-widget-text, .agent-feedback-widget-suggestion-text, .agent-feedback-widget-reply-text')) {\n const selection = this._domNode.ownerDocument.defaultView?.getSelection();\n if (selection && !selection.isCollapsed && this._domNode.contains(selection.anchorNode)) {\n return;\n }\n }\n this.focusFeedback(comment.id);\n });\n\n this._bodyNode.appendChild(item);\n }\n }\n\n private _buildItemActions(comment: VscodeComment, item: HTMLElement, text: HTMLElement): { container: HTMLElement; actions: ItemActions } {\n const container = $('div.agent-feedback-widget-item-actions');\n const bar = $('div.monaco-action-bar');\n const list = $('ul.actions-container');\n list.setAttribute('role', 'toolbar');\n\n const addReply = this._actionLabel('comment-discussion', 'Add to Comment');\n const edit = this._actionLabel('edit', 'Edit');\n const remove = this._actionLabel('close', 'Remove');\n\n const actions: ItemActions = {\n addReply, edit, remove,\n setEnabled: (enabled: boolean) => {\n for (const a of [addReply, edit, remove]) {\n a.classList.toggle('disabled', !enabled);\n a.tabIndex = enabled ? 0 : -1;\n }\n },\n };\n\n this._listen(addReply, 'click', e => { e.stopPropagation(); this._startAddingReply(comment, item, actions); });\n this._listen(edit, 'click', e => { e.stopPropagation(); this._startEditing(comment, text, actions); });\n this._listen(remove, 'click', e => { e.stopPropagation(); this._removeItem(comment.id); });\n\n for (const a of [addReply, edit, remove]) {\n const li = $('li.action-item');\n li.appendChild(a);\n list.appendChild(li);\n }\n bar.appendChild(list);\n container.appendChild(bar);\n return { container, actions };\n }\n\n private _actionLabel(codicon: string, ariaLabel: string): HTMLAnchorElement {\n const a = document.createElement('a');\n a.className = `action-label codicon codicon-${codicon}`;\n a.setAttribute('role', 'button');\n a.setAttribute('aria-label', ariaLabel);\n a.title = ariaLabel;\n a.tabIndex = 0;\n a.innerHTML = ICON_SVGS[codicon] ?? '';\n return a;\n }\n\n private _lineLabel(startLine: number, endLine?: number): string {\n return (endLine === undefined || endLine === startLine)\n ? `Line ${startLine}`\n : `Lines ${startLine}-${endLine}`;\n }\n\n private _typeLabel(kind: VscodeCommentKind): string | undefined {\n switch (kind) {\n case 'prReview': return 'PR Review';\n case 'agentReview': return 'Agent Review';\n default: return undefined;\n }\n }\n\n private _renderSuggestion(comment: VscodeComment): HTMLElement {\n const suggestionNode = $('div.agent-feedback-widget-suggestion');\n for (const edit of comment.suggestion?.edits ?? []) {\n const editNode = $('div.agent-feedback-widget-suggestion-edit');\n const header = $('div.agent-feedback-widget-suggestion-header');\n const end = edit.endLine ?? edit.startLine;\n header.textContent = end === edit.startLine\n ? `Suggested Change \\u2022 Line ${edit.startLine}`\n : `Suggested Change \\u2022 Lines ${edit.startLine}-${end}`;\n editNode.appendChild(header);\n\n const pre = $('pre.agent-feedback-widget-suggestion-text');\n pre.textContent = edit.newText;\n editNode.appendChild(pre);\n suggestionNode.appendChild(editNode);\n }\n return suggestionNode;\n }\n\n private _renderReplies(replies: readonly string[]): HTMLElement {\n const repliesNode = $('div.agent-feedback-widget-replies');\n for (const reply of replies) {\n const replyNode = $('div.agent-feedback-widget-reply');\n const replyText = $('div.agent-feedback-widget-reply-text');\n replyText.appendChild(renderMarkdown(reply));\n replyNode.appendChild(replyText);\n repliesNode.appendChild(replyNode);\n }\n return repliesNode;\n }\n\n // --- Interactive behaviour ------------------------------------------\n\n private _startEditing(comment: VscodeComment, textContainer: HTMLElement, actions: ItemActions): void {\n actions.setEnabled(false);\n const previous = Array.from(textContainer.childNodes);\n textContainer.textContent = '';\n textContainer.classList.add('editing');\n\n const textarea = document.createElement('textarea');\n textarea.className = 'agent-feedback-widget-edit-textarea';\n textarea.value = comment.text;\n textarea.rows = 1;\n textContainer.appendChild(textarea);\n\n const autoSize = (): void => {\n textarea.style.height = 'auto';\n if (textarea.scrollHeight > 0) { textarea.style.height = `${textarea.scrollHeight}px`; }\n };\n autoSize();\n\n const restore = (): void => {\n textContainer.classList.remove('editing');\n textContainer.textContent = '';\n for (const n of previous) { textContainer.appendChild(n); }\n actions.setEnabled(true);\n };\n\n this._listen(textarea, 'input', autoSize);\n this._listen(textarea, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n const newText = textarea.value.trim();\n textContainer.classList.remove('editing');\n textContainer.textContent = '';\n textContainer.appendChild(renderMarkdown(newText || comment.text));\n actions.setEnabled(true);\n } else if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n restore();\n }\n });\n this._listen(textarea, 'blur', restore);\n textarea.focus();\n }\n\n private _startAddingReply(comment: VscodeComment, item: HTMLElement, actions: ItemActions): void {\n if (item.querySelector('.agent-feedback-widget-add-reply')) {\n (item.querySelector('.agent-feedback-widget-edit-textarea') as HTMLTextAreaElement | null)?.focus();\n return;\n }\n actions.setEnabled(false);\n\n const replyContainer = $('div.agent-feedback-widget-add-reply');\n const textarea = document.createElement('textarea');\n textarea.className = 'agent-feedback-widget-edit-textarea';\n textarea.placeholder = 'Add a comment\\u2026';\n textarea.rows = 1;\n replyContainer.appendChild(textarea);\n item.appendChild(replyContainer);\n\n const autoSize = (): void => {\n textarea.style.height = 'auto';\n if (textarea.scrollHeight > 0) { textarea.style.height = `${textarea.scrollHeight}px`; }\n };\n autoSize();\n\n const close = (): void => {\n replyContainer.remove();\n actions.setEnabled(true);\n };\n\n this._listen(textarea, 'input', autoSize);\n this._listen(textarea, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n const value = textarea.value.trim();\n if (value) {\n let repliesNode = item.querySelector('.agent-feedback-widget-replies');\n if (!repliesNode) {\n repliesNode = this._renderReplies([]);\n item.insertBefore(repliesNode, replyContainer);\n }\n const replyNode = $('div.agent-feedback-widget-reply');\n const replyText = $('div.agent-feedback-widget-reply-text');\n replyText.appendChild(renderMarkdown(value));\n replyNode.appendChild(replyText);\n repliesNode.appendChild(replyNode);\n }\n close();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n close();\n }\n });\n this._listen(textarea, 'blur', close);\n textarea.focus();\n }\n\n private _removeItem(id: string): void {\n const item = this._itemElements.get(id);\n item?.remove();\n this._itemElements.delete(id);\n }\n\n // --- Public API ------------------------------------------------------\n\n expand(): void {\n this._isExpanded = true;\n this._domNode.classList.remove('collapsed');\n this._bodyNode.classList.remove('collapsed');\n this._updateToggleButton();\n }\n\n collapse(): void {\n this._isExpanded = false;\n this._domNode.classList.add('collapsed');\n this._bodyNode.classList.add('collapsed');\n this._updateToggleButton();\n }\n\n toggle(visible: boolean): void {\n this._domNode.classList.toggle('visible', visible);\n }\n\n /** Marks a single comment item as focused (VS Code's active-selection style). */\n focusFeedback(id: string): void {\n if (this._focusedId) {\n this._itemElements.get(this._focusedId)?.classList.remove('focused');\n }\n this._focusedId = id;\n this._itemElements.get(id)?.classList.add('focused');\n }\n\n private _listen<K extends keyof HTMLElementEventMap>(target: HTMLElement, type: K, handler: (e: HTMLElementEventMap[K]) => void): void {\n target.addEventListener(type, handler as EventListener);\n this._disposables.push(() => target.removeEventListener(type, handler as EventListener));\n }\n\n dispose(): void {\n for (const d of this._disposables) { d(); }\n this._disposables.length = 0;\n this._domNode.remove();\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Presenter that renders each comment from a CommentsModel as a VS Code\n// agent-feedback card (the \"comments-vscode\" design), reusing the real\n// VscodeCommentWidget. Maps the rendering-agnostic Comment onto a VscodeComment;\n// the base class handles anchoring, stacking and lifecycle.\n//\n\nimport type { Comment } from '../comments/commentsModel.js';\nimport { StackedCommentsPresenter, type StackWidget } from './stackedCommentsPresenter.js';\nimport { VscodeCommentWidget, type VscodeComment } from './vscodeCommentWidget.js';\nimport './vscodeCommentTokens.css';\nimport './vscodeCommentWidget.css';\n\nexport class VscodeStackedCommentsView extends StackedCommentsPresenter {\n protected createWidget(comment: Comment): StackWidget {\n const startLine = this.context?.resolveLine?.(comment.range.start) ?? 1;\n const vscodeComment: VscodeComment = {\n id: comment.id,\n source: 'prReview',\n kind: 'prReview',\n startLine,\n text: comment.body,\n };\n return new VscodeCommentWidget([vscodeComment], { expanded: true });\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Pixel-for-pixel replica of the \"Markdown comment\" frames from the Figma\n// \"Comment / Feedback widget\" board\n// (https://www.figma.com/design/lWE17f1tRRDXWsbxTcbsmo/Polish-Push-May---June-2026?node-id=4379-10808).\n//\n// It reproduces the three states of the markdown comment card:\n// 1. 'short' — a single short line, no toggle.\n// 2. 'collapsed' — a long body clamped to three lines with a \"See more\" link.\n// 3. 'expanded' — the full body with a \"See less\" link.\n//\n// Design tokens (from Figma):\n// editorWidget/background #202122\n// editorHoverWidget/border #2a2b2c\n// foreground #bfbfbf\n// icon/foreground #8c8c8c\n// textLink/foreground #48a0c7\n// Outer radius 8px\n// size40 / size60 / size80 4 / 6 / 8px\n// Heading 3 SF Pro Text Semibold 13\n// Body 1 SF Pro Text Regular 13\n// Label 1 SF Pro Text Regular 12\n//\n\n/** The three markdown-comment states captured in the Figma frames. */\nexport type VsCodeCommentV2State = 'short' | 'collapsed' | 'expanded';\n\nexport interface VsCodeCommentWidgetV2Options {\n /** Author label shown in the header (e.g. `@username`). */\n readonly username: string;\n /** The comment body (rendered as plain text; long bodies get a toggle). */\n readonly body: string;\n /**\n * Initial state. `'short'` hides the toggle entirely; `'collapsed'` and\n * `'expanded'` show a \"See more\" / \"See less\" toggle. Defaults to `'short'`.\n */\n readonly state?: VsCodeCommentV2State;\n /** Called when the user toggles between collapsed and expanded. */\n readonly onToggle?: (expanded: boolean) => void;\n /**\n * If provided, an edit button is shown in the header and invokes this on\n * click. When omitted the edit button is hidden.\n */\n readonly onEdit?: () => void;\n /**\n * If provided, the delete (trash) button invokes this on click. When omitted\n * the delete button is hidden.\n */\n readonly onDelete?: () => void;\n}\n\nconst DOM_HELPER_TAG = /^([a-z0-9]+)/i;\n\n/** VS Code's `dom.$('tag.a.b')` shorthand, reduced to what we use. */\nfunction $(selector: string): HTMLElement {\n const tag = DOM_HELPER_TAG.exec(selector)?.[1] ?? 'div';\n const el = document.createElement(tag);\n const classes = selector.slice(tag.length).split('.').filter(Boolean);\n if (classes.length) {\n el.className = classes.join(' ');\n }\n return el;\n}\n\n/**\n * Inline Feather-style icons (stroke=\"currentColor\"), matching the crisp look of\n * VS Code's codicons and the sibling {@link VscodeCommentWidget}.\n */\nfunction feather(inner: string): string {\n return `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nconst ICON_SVGS: Record<string, string> = {\n 'edit': feather('<path d=\"M12 20h9\"></path><path d=\"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z\"></path>'),\n 'trash': feather('<polyline points=\"3 6 5 6 21 6\"></polyline><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"></path><line x1=\"10\" y1=\"11\" x2=\"10\" y2=\"17\"></line><line x1=\"14\" y1=\"11\" x2=\"14\" y2=\"17\"></line>'),\n};\n\n/** An icon-only action button carrying the inline Feather SVG for `name`. */\nfunction actionButton(name: string, label: string): HTMLButtonElement {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'vscode-comment-widget-v2-action';\n btn.setAttribute('aria-label', label);\n btn.title = label;\n btn.innerHTML = ICON_SVGS[name] ?? '';\n return btn;\n}\nexport class VsCodeCommentWidgetV2 {\n private readonly _domNode: HTMLElement;\n private readonly _textNode: HTMLParagraphElement;\n private readonly _toggleNode?: HTMLButtonElement;\n private readonly _onToggle?: (expanded: boolean) => void;\n\n private _state: VsCodeCommentV2State;\n private readonly _disposables: (() => void)[] = [];\n private readonly _onToggleClick = (e: MouseEvent): void => {\n e.preventDefault();\n this.toggle();\n };\n\n get element(): HTMLElement { return this._domNode; }\n\n get expanded(): boolean { return this._state === 'expanded'; }\n\n constructor(options: VsCodeCommentWidgetV2Options) {\n this._state = options.state ?? 'short';\n this._onToggle = options.onToggle;\n\n // Card root — \"PR Review Comment\" frame.\n this._domNode = $('div.vscode-comment-widget-v2');\n\n // Header row: title-group (username) + actions (edit / trash).\n const header = $('div.vscode-comment-widget-v2-header');\n\n const titleGroup = $('div.vscode-comment-widget-v2-title-group');\n const username = $('span.vscode-comment-widget-v2-username');\n username.textContent = options.username;\n titleGroup.appendChild(username);\n header.appendChild(titleGroup);\n\n const actions = $('div.vscode-comment-widget-v2-actions');\n if (options.onEdit) {\n actions.appendChild(this._actionButton('edit', 'Edit', options.onEdit));\n }\n if (options.onDelete) {\n actions.appendChild(this._actionButton('trash', 'Delete', options.onDelete));\n }\n header.appendChild(actions);\n\n this._domNode.appendChild(header);\n\n // Body: comment text + optional \"See more\" / \"See less\" toggle.\n const body = $('div.vscode-comment-widget-v2-body');\n\n this._textNode = document.createElement('p');\n this._textNode.className = 'vscode-comment-widget-v2-text';\n this._textNode.textContent = options.body;\n body.appendChild(this._textNode);\n\n if (this._state !== 'short') {\n const toggle = document.createElement('button');\n toggle.type = 'button';\n toggle.className = 'vscode-comment-widget-v2-toggle';\n toggle.addEventListener('click', this._onToggleClick);\n this._toggleNode = toggle;\n body.appendChild(toggle);\n }\n\n this._domNode.appendChild(body);\n\n this._applyState();\n }\n\n /** Flip between the collapsed and expanded states (no-op for `'short'`). */\n toggle(): void {\n if (this._state === 'short') {\n return;\n }\n this._state = this._state === 'expanded' ? 'collapsed' : 'expanded';\n this._applyState();\n this._onToggle?.(this._state === 'expanded');\n }\n\n private _applyState(): void {\n this._domNode.classList.toggle('vscode-comment-widget-v2--collapsed', this._state === 'collapsed');\n this._domNode.classList.toggle('vscode-comment-widget-v2--expanded', this._state === 'expanded');\n if (this._toggleNode) {\n this._toggleNode.textContent = this._state === 'expanded' ? 'See less' : 'See more';\n }\n }\n\n /** A header action button that runs `onClick` (and cleans up on dispose). */\n private _actionButton(name: string, label: string, onClick: () => void): HTMLButtonElement {\n const button = actionButton(name, label);\n const handler = (e: MouseEvent): void => {\n e.preventDefault();\n e.stopPropagation();\n onClick();\n };\n button.addEventListener('click', handler);\n this._disposables.push(() => button.removeEventListener('click', handler));\n return button;\n }\n\n dispose(): void {\n this._toggleNode?.removeEventListener('click', this._onToggleClick);\n for (const dispose of this._disposables) { dispose(); }\n this._domNode.remove();\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Presenter that renders each comment from a CommentsModel as the Figma\n// \"Markdown comment\" card (the \"comments-vscode-v2\" design), reusing the real\n// VsCodeCommentWidgetV2. The base class handles anchoring, stacking and\n// lifecycle.\n//\n\nimport type { Comment } from '../comments/commentsModel.js';\nimport { StackedCommentsPresenter, type StackWidget } from './stackedCommentsPresenter.js';\nimport { VsCodeCommentWidgetV2 } from './vscodeCommentWidgetV2.js';\nimport './vscodeCommentTokens.css';\nimport './vscodeCommentWidgetV2.css';\n\n/** Bodies longer than this open collapsed (with a \"See more\" toggle). */\nconst COLLAPSE_THRESHOLD = 80;\n\nexport class VsCodeV2CommentsView extends StackedCommentsPresenter {\n protected createWidget(comment: Comment): StackWidget {\n return new VsCodeCommentWidgetV2({\n username: comment.author ?? 'You',\n body: comment.body,\n state: comment.body.length > COLLAPSE_THRESHOLD ? 'collapsed' : 'short',\n // Edit is intentionally omitted (hidden) for now. Delete removes the\n // comment from the shared model; the autorun then disposes the card.\n onDelete: () => this.model.remove(comment.id),\n });\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n//\n// Composition root that maps a design id to a presenter factory. This is the one\n// place that knows all three renderings; the core (CommentsModel /\n// commentsPresenter) stays unaware of the concrete designs. Hosts (the demo, the\n// fixtures) pick a design here and swap it over a shared CommentsModel.\n//\n\nimport { CommentsView } from '../comments/commentsView.js';\nimport type { CommentsPresenterFactory } from '../comments/commentsPresenter.js';\nimport { VscodeStackedCommentsView } from './vscodeStackedCommentsView.js';\nimport { VsCodeV2CommentsView } from './vscodeV2CommentsView.js';\nimport '../comments/comments.css';\n\n/** The available comment rendering designs. */\nexport type CommentsDesign = 'connected' | 'vscode' | 'vscode-v2';\n\n/** Human-readable labels (for pickers / dropdowns). */\nexport const COMMENTS_DESIGN_LABELS: Record<CommentsDesign, string> = {\n 'connected': 'Connected lines (original)',\n 'vscode': 'VS Code cards',\n 'vscode-v2': 'Markdown cards (V2)',\n};\n\n/** design id → presenter factory over a shared CommentsModel + EditorView. */\nexport const COMMENTS_DESIGNS: Record<CommentsDesign, CommentsPresenterFactory> = {\n 'connected': (model, view) => new CommentsView(model, view),\n 'vscode': (model, view, ctx) => new VscodeStackedCommentsView(model, view, ctx),\n 'vscode-v2': (model, view, ctx) => new VsCodeV2CommentsView(model, view, ctx),\n};\n"],"names":["LengthReplacement","replaceRange","newLength","other","LengthEdit","replacement","replacements","lastEndEx","r","i","StringValue","value","range","Selection","anchor","active","offset","OffsetRange","Point2D","x","y","dx","dy","Rect2D","width","height","left","top","right","bottom","p","findWordBoundaryLeft","text","findWordBoundaryRight","len","findWordAt","ch","start","end","_nextNodeId","AstNode","sum","c","a","b","_other","id","clone","_emptyChildren","_mapArr","map","arr","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","UnhandledBlockAstNode","tokenType","HeadingAstNode","level","marker","ParagraphAstNode","CodeBlockAstNode","language","pos","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","_UNHANDLED_BLOCK_TOKENS","_pullIndentIntoBlocks","cur","next","hosted","_prependLeadingTrivia","prev","glue","firstIdx","items","j","_attachBlockGaps","idx","isParagraphBreak","gap","host","_appendTrailingGlue","h","u","_appendIntoLast","l","it","last","_ensureBlocks","Content","_parentStart","_source","parentLength","s","e","indent","_events","cb","coveredEnd","ev","block","unhandled","enter","depth","exit","raw","markerStart","markerEnd","inlines","seqEnter","seqExit","sawOpenFence","contentStart","contentEnd","fenceEnter","ii","fenceExit","flushContent","prefixEnter","prefixExit","seenBlock","pre","preExit","listType","itemStart","itemCb","itemChecked","lastBlockEnd","flush","itemEnd","columnCount","row","pipes","cellStartsRel","cols","rowCb","cs","ce","cellCb","cellType","cellEnter","cellExit","entries","untilExit","isStrong","openEnter","openExit","closeEnter","closeExit","sawOpen","sawOpenBracket","i2","sawOpenParen","EditMapper","_edit","mod","delta","modStart","dirtyEnd","OldTreeIndex","key","originalStart","_reconcile","fresh","mapper","index","edit","rc","orig","cand","os","old","linked","_linkCodeBlock","oldStart","oldCode","freshCode","_editWithin","_shiftEdit","endExclusive","StringEdit","StringReplacement","reconcile","parseIncremental","MarkdownParser","getAnnotatedSource","escapeXml","tag","_attributes","result","childOffset","attrs","k","v","str","_label","_objectInstanceIds","_nextObjectInstanceId","objectInstanceId","visualizeAst","walk","kids","children","changedRanges","_owner","_ready","observableValue","diffComputerReady","_computer","_readyPromise","ensureDiffComputer","createDiffComputer","computeStringEdit","original","modified","_convert","CONTAINER_KINDS","SKIP_KINDS","classifyDiff","changes","classifyChildren","origParent","origParentStart","modParent","modParentStart","O","structuralChildren","M","oi","mRange","removedItem","candRange","clean","localRanges","addedItem","nodeStart","inserted","deleted","nodeRange","side","inter","NO_ACTIVE_BLOCKS","EditorModel","derived","reader","previousText","pending","doc","cursor","findBlockAtOffset","override","sel","blocksIntersecting","baselineDoc","baseline","modifiedDoc","modifiedText","insertedRanges","collect","list","topLevel","changedBlocks","req","oldText","newText","newActive","newCursor","lastBlock","VisualLineMap","lines","blockViews","coordinateSpace","transform","_measure","lineIndex","endBoundaryLine","membership","bestIdx","bestDist","dist","point","VisualLine","rect","runs","run","best","d","leftRight","leftEnd","rightLeft","rightStart","bestRun","VisualRun","sourceRange","_xAtTextOffset","localOffset","_offsetAtX","mid","textNode","textOffset","fallbackLeft","bestOffset","clientRect","dLeft","dRight","rawRuns","view","runsBefore","leaf","leafOffset","clientRects","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","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","UnhandledBlockViewNode","ListViewNode","ListItemViewNode","TableViewNode","TableRowViewNode","InlineCodeViewNode","InlineMathViewNode","LinkViewNode","ImageViewNode","DiffHunkViewNode","DiffDecorationViewNode","ctor","reconcileDomChildren","parentDom","childData","previousChildren","build","paired","unused","pairNodes","_NO_CHILDREN","_patchDomChildren","_patchDomNodes","nodes","domCursor","toRemove","_buildChild","_inlineChild","wrapper","mounts","_buildDiffSide","cls","el","sideNode","_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","seg","RawLeafViewNode","sourceLength","base","reuse","built","ws","_previous","holder","_appendPlainText","className","hr","code","childAst","prevCode","embeddedLeading","embeddedTrailing","embeddedContent","embedded","custom","highlighter","session","diff","transaction","tx","tokens","contentNode","estimated","shifted","_buildCodeContent","CodeContentViewNode","leaves","runOnChange","snapshot","contentAst","_buildTokenLeaves","tokenLeaves","piece","_mathContentOffset","_buildMathSegmentChildren","nodeLength","sorted","filler","remembered","latex","rendering","div","katex","li","_reconcileListItem","checkbox","onToggle","wasChecked","first","gutter","table","tr","cellData","_isSafeUrl","shouldOpen","openLink","onOpenLink","pointerDownResult","onClick","img","newData","prevNodes","byId","DocumentViewNode","contentDomNode","blocks","pendingElement","viewData","activeByView","childViews","_NO_NODES","PendingParagraphViewNode","diffKind","caretDomPositionFromPoint","api","MATRIX_EPSILON","EditorCoordinateSpace","_getLocalToClientMatrix","overlay","matrix","localToClient","EditorCoordinateTransform","_localToClient","local","client","topLeft","bottomRight","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","UnhandledBlockViewData","MarkerViewData","visible","GlueViewData","decorateNewline","DiffDecorationViewData","deletedRanges","whole","_INACTIVE","_inline","buildDocumentViewData","activeBlocks","selectionRange","prevByAst","blockSet","_buildBlock","selectionInNode","_reuseOr","_buildNode","buildBlockViewData","applyDiffDecorations","diffItems","decorationsActive","removedBefore","modAst","_diffModifiedAst","removedAtEnd","blockView","rem","_decorationChild","decorateContainer","outChild","originalBlock","forceActive","_decoration","container","newContent","cvd","_withContent","vd","astNode","neighbors","_buildChildren","_markerVisible","_glueVisible","_buildList","_buildListItem","_buildTable","_buildTableRow","_buildTableCell","_childrenOf","_prevChildByAst","_flagsEqual","_edgeIsWordContent","prevNode","activeItems","_activeItemIndices","itemSet","itemLevel","itemCtx","childCtx","tableActive","delimiterRow","rowSet","rowCtx","activeCells","_activeCellIndices","cellSet","cell","cellActive","cellCtx","_EMPTY_SET","_findActiveCellIndex","cellIdx","collectTextLeaves","rangeFromLeaves","startNode","startOff","endNode","endOff","lf","ls","le","rangesForOffsets","spans","DiffHighlightsView","_parent","documentNode","green","red","rs","frag","add","localRect","SelectionView","selection","visualLineMap","_renderSelection","autorun","SelectionViewRendering","path","computeRangeRects","buildConnectedPath","NEWLINE_SELECTION_WIDTH_RATIO","selRange","toRect","lineInfos","lineRange","_lineSourceRange","nextRange","hardBreak","overlapsContent","selectsTrailingBreak","lineRects","cStart","cEnd","startX","endX","breakSelected","clip","blockViewportClip","blockToFirstLineIdx","blockToLastLineIdx","blockSelected","curr","gapStart","currRect","nextRect","nextFirstLineTop","_firstLineTopOfBlock","prevLineIdx","nextLineIdx","_blockHasVisualLine","prevLR","nextLR","min","max","blockContainingOffset","fallback","radius","clusters","current","yTouches","xOverlaps","_buildClusterPath","corners","aRight","bRight","aConvex","_polygonToRoundedPath","radii","dPrev","_dist","dNext","_moveFrom","parts","_fmt","depart","nextR","approach","from","to","t","CursorView","pendingRect","CursorViewRendering","caretRect","GutterMarkersView","markers","GutterMarkersViewRendering","_deletedRect","_barRect","DEFAULT_LIMITED_WIDTH","EditorView","_model","_options","limitedWidth","constObservable","lastMeasuredContentWidth","resizeObserver","scrollRaf","onBlockScroll","measurement","button","indicator","lockedIcon","lockKeyhole","lockBody","editingIcon","editingPath","onPointerDown","event","onKeyDown","onFocus","onBlur","onAnimationEnd","readonly","tableCellOffset","hit","documentView","cellNode","cellStart","cellEnd","domOffsetAtPoint","element","hasSourceRun","hitNode","hitStart","hitEnd","sourceText","baseViewData","pendingEl","document","measurements","entry","blockRect","scrollElement","viewportClip","NativeClipboardStrategy","context","onCopy","onCut","onPaste","AsyncClipboardStrategy","_clipboard","MULTI_CLICK_TIME_MS","MULTI_CLICK_DISTANCE_PX","EditorController","_view","win","clipboardStrategy","editContext","isRepeat","findBlockRangeAt","revealsLockOnClick","pointerId","onPointerMove","me","moveOffset","onPointerUp","command","extend","ctrl","_SHOW_LINE_RECTS_KEY","_readStoredBool","_writeStoredBool","MeasuredLayoutDebugView","_overlayParent","controls","showLineRects","_renderDebug","hovered","applyHoverIsolation","MeasuredLayoutDebugRendering","blockCount","mountedCount","lineCount","mappedOffsets","info","colorForOffset","hoveredOffset","charCount","lineRect","band","runBox","_appendCharRects","header","rows","flag","lc","blockAbsoluteStart","count","covered","isCovered","drawWidth","box","_isolate","off","matches","keep","on","Token","length","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","PLUS_SVG","CommentInputWidget","footer","onPanelPointerDown","onInput","onSubmitClick","hasText","textWidth","scrollHeight","CommentModeController","isSelecting","hasTypedText","preferAbove","widgetHeight","viewport","clientCaretRect","clientWidgetHeight","clientGap","caretTop","roomBelow","roomAbove","topPx","containerWidth","maxLeft","overflowY","CommentsModel","comments","input","comment","SVG_NS","RAIL_MIN","RAIL_MAX","RAIL_FRACTION","RAIL_GAP","RAIL_EDGE","CARD_GAP","LEADER_CARD_INSET","HIGHLIGHT_RADIUS","LEADER_WIDTH","LEADER_OVERLAP","CommentsView","svg","hoveredId","seen","existing","group","leaderPath","shapePath","card","avatarEl","authorEl","timeEl","menuEl","bodyEl","reply","setHover","leave","author","_initials","_relativeTime","rootWidth","maxW","padX","borderX","contentMaxOuter","naturalRight","railWidth","need","pad","padStr","railLeftLocal","contentRightLocal","placed","_lineStart","desiredTop","prevBottom","_leaderLine","rightEdge","bendX","bend","c1x","c2x","name","second","epochMs","deltaSec","hours","RIGHT_INSET","layoutRightAlignedStack","StackedCommentsPresenter","model","widget","DOM_HELPER_TAG","$","selector","classes","feather","ICON_SVGS","icon","renderMarkdown","wrap","part","VscodeCommentWidget","_comments","itemHeader","itemMeta","lineInfo","typeLabel","badge","actions","bar","addReply","remove","enabled","codicon","ariaLabel","startLine","endLine","suggestionNode","editNode","replies","repliesNode","replyNode","replyText","textContainer","textarea","autoSize","restore","replyContainer","close","handler","VscodeStackedCommentsView","vscodeComment","actionButton","label","btn","VsCodeCommentWidgetV2","titleGroup","username","body","toggle","dispose","COLLAPSE_THRESHOLD","VsCodeV2CommentsView","COMMENTS_DESIGN_LABELS","COMMENTS_DESIGNS"],"mappings":";;;;;;;;;AAaO,MAAMA,GAAkB;AAAA,EAK3B,YACoBC,GACAC,GAClB;AACE,QAHgB,KAAA,eAAAD,GACA,KAAA,YAAAC,GAEZA,IAAY;AACZ,YAAM,IAAI,MAAM,uCAAuCA,CAAS,EAAE;AAAA,EAE1E;AAAA,EAXA,OAAc,QAAQD,GAA2BC,GAAsC;AACnF,WAAO,IAAIF,GAAkBC,GAAcC,CAAS;AAAA,EACxD;AAAA,EAWA,IAAI,cAAsB;AACtB,WAAO,KAAK,YAAY,KAAK,aAAa;AAAA,EAC9C;AAAA,EAEO,OAAOC,GAAmC;AAC7C,WAAO,KAAK,aAAa,OAAOA,EAAM,YAAY,KAAK,KAAK,cAAcA,EAAM;AAAA,EACpF;AAAA,EAEO,WAAmB;AACtB,WAAO,GAAG,KAAK,YAAY,QAAQ,KAAK,SAAS;AAAA,EACrD;AACJ;AASO,MAAMC,GAAW;AAAA,EACpB,OAAuB,QAAQ,IAAIA,GAAW,EAAE;AAAA,EAEhD,OAAc,OAAOC,GAA4C;AAC7D,WAAO,IAAID,GAAW,CAACC,CAAW,CAAC;AAAA,EACvC;AAAA,EAEA,OAAc,QAAQJ,GAA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