Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownChunks.ts

1,110 lines42.0 KB

1import remarkGfm from "remark-gfm";
2import remarkParse from "remark-parse";
3import { unified } from "unified";
4​
5import { maskMarkdownFrontmatter } from "./markdownFrontmatter.ts";
6​
7// About one screen of rendered Markdown; parsing costs up to ~40 ms per KB with tables and math.
8const CHUNK_TARGET_CHARS = 4 * 1024;
9// A chunk past this (one huge fence or HTML block) is too slow to parse at once; show source.
10export const LARGE_MARKDOWN_CHUNK_MAX_CHARS = 128 * 1024;
11// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
12const FENCE_OPEN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
13const ATX_HEADING = /^ {0,3}#{1,6}(?:[ \t]|\r?$)/;
14// A thematic break, or a "---" setext underline; no paragraph stays open after either. A lone
15// "===" is paragraph text unless it underlines one, so it is left out.
16const THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
17const SETEXT_UNDERLINE = /^ {0,3}(?:=+|-+)[ \t]*\r?$/;
18const TABLE_DELIMITER = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*(?:\|[ \t]*)?\r?$/;
19// A column-0 paragraph, quote or table after a blank line closes any open list, quote or table.
20const BLOCK_START = /^[\p{L}\p{N}`[!|>]/u;
21const LIST_ITEM = /^( {0,3}(?:[-*+]|\d{1,9}[.)]))([ \t]+|(?=\r?$))/;
22// Further markers on an item's first line open nested items that start on the same line.
23const NESTED_LIST_MARKERS = /^(?:(?:[-*+]|\d{1,9}[.)])(?:[ \t]+|(?=\r?$)))+/;
24const BLOCK_QUOTE = /^ {0,3}>/;
25const DISPLAY_MATH_OPEN = /^ {0,3}\$\$/;
26// CommonMark HTML blocks of types 1-5 and display math run past blank lines until their closer.
27const SPANNING_BLOCKS: ReadonlyArray<readonly [open: RegExp, close: RegExp]> = [
28 [/^ {0,3}<(?:script|pre|style|textarea)(?=[\s>]|$)/i, /<\/(?:script|pre|style|textarea)>/i],
29 // "<!-->" and "<!--->" close themselves, so the closer is searched from just after "<!".
30 [/^ {0,3}<!(?=--)/, /-->/],
31 [/^ {0,3}<\?/, /\?>/],
32 [/^ {0,3}<!\[CDATA\[/, /\]\]>/],
33 [/^ {0,3}<![A-Za-z]/, />/],
34 [DISPLAY_MATH_OPEN, /\$\$/],
35];
36​
37// CommonMark type-6 block tags start an HTML block even with trailing text or across lines.
38const HTML_BLOCK_TAG =
39 /^ {0,3}<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?=[ \t>]|\/>|\r?$)/i;
40// CommonMark type-7 HTML blocks require a complete standalone open or closing tag on the line.
41const HTML_STANDALONE_TAG =
42 /^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t]*=[ \t]*(?:[^ \t\r"'=<>`]+|'[^']*'|"[^"]*"))?)*[ \t]*\/?>|<\/[A-Za-z][A-Za-z0-9-]*[ \t]*>)[ \t]*\r?$/;
43const BLANK_LINE = /^[ \t]*\r?$/;
44const closesAtBlankLine = (next: string) => BLANK_LINE.test(next);
45const flowParser = unified().use(remarkParse).use(remarkGfm).freeze();
46const HTML_FLOW_MAX_CHARS = 8 * 1024;
47// Parsing is far slower than the line scan, so a whole document shares one budget.
48const HTML_PARSE_BUDGET_CHARS = 16 * 1024;
49// Charge for parser startup even when a block is only a few characters long.
50const MIN_FLOW_PARSE_COST = 512;
51const SETEXT_EQUALS = /^ {0,3}=+[ \t]*\r?$/;
52// A plain line in this position cannot be a table, link definition, or block opener.
53const PLAIN_PROSE = /^ {0,3}[\p{L}\p{N}][^|\r]*\r?$/u;
54type FlowLineKind = "indented-code" | "paragraph";
55​
56/** Classifies candidate lines in ascending, 1-based order, with one parse budget per document. */
57export function markdownFlowLineLookup(source: string) {
58 const knownLines = new Map<number, FlowLineKind>();
59 const chunks =
60 source.length <= HTML_PARSE_BUDGET_CHARS
61 ? [{ text: source, lines: Infinity }]
62 : splitMarkdownBlocks(source, 0, knownLines).chunks;
63 let remaining = HTML_PARSE_BUDGET_CHARS;
64 let precedingLines = 0;
65 let chunkIndex = 0;
66 let kinds: ReturnType<typeof classifyFlowLines> | undefined;
67​
68 return (line: number) => {
69 const known = knownLines.get(line);
70 if (known) return known;
71 let chunk = chunks[chunkIndex];
72 while (chunk && line > precedingLines + chunk.lines) {
73 precedingLines += chunk.lines;
74 chunk = chunks[++chunkIndex];
75 kinds = undefined;
76 }
77 if (!chunk) return undefined;
78 if (kinds === undefined) {
79 const cost = Math.max(chunk.text.length, MIN_FLOW_PARSE_COST);
80 if (cost > remaining) return undefined;
81 remaining -= cost;
82 kinds = classifyFlowLines(chunk.text);
83 }
84 return kinds.get(line - precedingLines);
85 };
87​
88function classifyFlowLines(source: string) {
89 const kinds = new Map<number, FlowLineKind>();
90 const nodes = [...flowParser.parse(source).children];
91 const topLevelCount = nodes.length;
92 const bomOffset = source.startsWith("\uFEFF") ? 1 : 0;
93 for (let i = 0; i < nodes.length; i++) {
94 const node = nodes[i]!;
95 const position = node.position;
96 if (node.type === "paragraph" && position) {
97 for (let line = position.start.line; line <= position.end.line; line++) {
98 kinds.set(line, "paragraph");
99 }
100 } else if (node.type === "code" && position && i < topLevelCount) {
101 const first = source[(position.start.offset ?? 0) + bomOffset];
102 if (first !== " " && first !== "\t") continue;
103 for (let line = position.start.line; line <= position.end.line; line++) {
104 kinds.set(line, "indented-code");
105 }
106 } else if ("children" in node) nodes.push(...node.children);
107 }
108 return kinds;
110​
111function indentationColumn(whitespace: string, column = 0): number {
112 for (const character of whitespace) {
113 column += character === "\t" ? 4 - (column % 4) : 1;
114 }
115 return column;
117​
118// A <details> or <table> wraps the Markdown between its tags, across the blank lines that end
119// each HTML block, so a cut waits until the ones an HTML block opened are closed.
120const WRAPPER_TAG = /<(\/?)(?:details|table)(?=[\s/>]|$)/gi;
121// An end tag that never comes, or back-to-back wrappers, must not make one huge piece.
122const WRAPPED_MAX_CHARS = 32 * 1024;
123​
124function withoutComments(line: string): string {
125 let kept = "";
126 let at = 0;
127 for (let open = line.indexOf("<!--"); open !== -1; open = line.indexOf("<!--", at)) {
128 const close = line.indexOf("-->", open + 4);
129 if (close === -1) break;
130 kept += line.slice(at, open);
131 at = close + 3;
132 }
133 return kept + line.slice(at);
135​
136function openedWrappers(line: string): number {
137 let opened = 0;
138 for (const [, closing] of withoutComments(line).matchAll(WRAPPER_TAG)) {
139 opened += closing ? -1 : 1;
140 }
141 return opened;
143​
144/** Whether `text` opens a block that ends a paragraph and is not one itself. */
145function opensNonParagraph(text: string): boolean {
146 return (
147 ATX_HEADING.test(text) ||
148 THEMATIC_BREAK.test(text) ||
149 BLOCK_QUOTE.test(text) ||
150 FENCE_OPEN.test(text) ||
151 HTML_BLOCK_TAG.test(text) ||
152 SPANNING_BLOCKS.some(([open]) => open.test(text))
153 );
155​
156/** Null means the block ends on this line. Undefined means no block opens. */
157function blockCloser(line: string): ((line: string) => boolean) | null | undefined {
158 const fence = FENCE_OPEN.exec(line)?.[1];
159 if (fence) {
160 return (next) => {
161 const match = FENCE_OPEN.exec(next);
162 const closer = match?.[1];
163 return (
164 match !== null &&
165 closer !== undefined &&
166 closer[0] === fence[0] &&
167 closer.length >= fence.length &&
168 BLANK_LINE.test(next.slice(match[0].length))
169 );
170 };
171 }
172 for (const [open, close] of SPANNING_BLOCKS) {
173 const opener = open.exec(line)?.[0];
174 if (opener === undefined) continue;
175 return close.test(line.slice(opener.length)) ? null : (next) => close.test(next);
176 }
177 return HTML_BLOCK_TAG.test(line) ? closesAtBlankLine : undefined;
179​
180export interface MarkdownChunk {
181 readonly text: string;
182 readonly lines: number;
183 readonly separator?: "\n" | "\r";
185​
186const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/;
187const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/;
188// Cap the lookahead for a frontmatter closer; a leading rule with none is a thematic break.
189const FRONTMATTER_MAX_LINES = 1000;
190​
191// A bare CR ends a line too; CRLF lines keep their `\r`, which the patterns here allow.
192function nextLineBreak(text: string, from: number): number {
193 for (let i = from; i < text.length; i++) {
194 const code = text.charCodeAt(i);
195 if (code === 10 || (code === 13 && text.charCodeAt(i + 1) !== 10)) return i;
196 }
197 return text.length;
199​
200const hasFrontmatterClose = (lines: readonly string[]) =>
201 lines.slice(1, FRONTMATTER_MAX_LINES + 1).some((line) => FRONTMATTER_CLOSE.test(line));
202​
203// Footnotes are collected separately so body pieces do not each render their own footnote section.
204const LINK_DEFINITION_START = /^ {0,3}\[(?!\^)/;
205const LINK_LABEL_MAX_CHARS = 999;
206const LINK_TITLE_START = /^[ \t]*(["'(])/;
207// Definitions past this are not repeated into every piece; their parse cost would outweigh links.
208const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024;
209const SHARED_FOOTNOTES_MAX_CHARS = 64 * 1024;
210const FOOTNOTE_DEFINITION_START = /^ {0,3}\[\^([^\s[\]]+)\]:/;
211const FOOTNOTE_CONTINUATION_INDENT = /^(?: {4}|\t)/;
212const LIST_ITEM_START = /^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:[ \t]|\r?$)/;
213const FOOTNOTE_BLOCK_INTERRUPT = /^ {0,3}(?:>|[-*+](?:[ \t]|\r?$)|\d{1,9}[.)](?:[ \t]|\r?$))/;
214const definitionParser = unified().use(remarkParse);
215​
216function hasDefinitionLabel(lines: readonly string[], start: number): boolean {
217 const opener = LINK_DEFINITION_START.exec(lines[start]!);
218 if (!opener) return false;
219​
220 let column = opener[0].length;
221 let labelChars = 0;
222 for (let index = start; index < lines.length; index++) {
223 const line = lines[index]!;
224 if (BLANK_LINE.test(line)) return false;
225 const end = line.endsWith("\r") ? line.length - 1 : line.length;
226 for (; column < end && labelChars <= LINK_LABEL_MAX_CHARS; column++, labelChars++) {
227 const char = line[column];
228 if (char === "]") return line[column + 1] === ":";
229 if (char === "[") return false;
230 if (char === "\\" && /[\\[\]]/.test(line[column + 1] ?? "")) {
231 column++;
232 labelChars++;
233 }
234 }
235 if (labelChars > LINK_LABEL_MAX_CHARS) return false;
236 column = 0;
237 }
238 return false;
240​
241function endsDefinitionRun(line: string) {
242 // The preview treats display math as a block even when plain Remark would consume its opener.
243 return (
244 BLANK_LINE.test(line) ||
245 ATX_HEADING.test(line) ||
246 THEMATIC_BREAK.test(line) ||
247 FENCE_OPEN.test(line) ||
248 DISPLAY_MATH_OPEN.test(line)
249 );
251​
252function findTitleEnd(lines: readonly string[], start: number, opener: RegExpExecArray) {
253 const closer = opener[1] === "(" ? ")" : opener[1];
254 let column = opener[0].length;
255 for (let index = start; index < lines.length; index++) {
256 const line = lines[index]!;
257 if (endsDefinitionRun(line)) return;
258 for (; column < line.length; column++) {
259 const char = line[column];
260 if (char === closer) return BLANK_LINE.test(line.slice(column + 1)) ? index : undefined;
261 if (char === "\\" && (line[column + 1] === closer || line[column + 1] === "\\")) column++;
262 }
263 column = 0;
264 }
266​
267function readLinkDefinitions(lines: readonly string[], start: number) {
268 const definitions = new Map<number, { text?: string; end: number; identifier: string }>();
269 let chars = lines[start]!.length;
270 if (chars >= SHARED_DEFINITIONS_MAX_CHARS) return definitions;
271 let end = start + 1;
272 let capped = false;
273 for (; end < lines.length; end++) {
274 const line = lines[end]!;
275 if (endsDefinitionRun(line)) break;
276 chars += line.length + 1;
277 if (chars >= SHARED_DEFINITIONS_MAX_CHARS) {
278 capped = true;
279 break;
280 }
281 }
282​
283 const text = lines.slice(start, end).join("\n");
284 let partialTitleStart: number | undefined;
285 for (const node of definitionParser.parse(text).children) {
286 if (node.type !== "definition" || !node.position) break;
287 const { start: from, end: to } = node.position;
288 const firstLine = start + from.line - 1;
289 if (!LINK_DEFINITION_START.test(lines[firstLine]!)) break;
290 const lastLine = start + to.line - 1;
291 definitions.set(firstLine, {
292 text: text.slice(from.offset, to.offset),
293 end: lastLine,
294 identifier: node.identifier,
295 });
296 partialTitleStart =
297 capped && node.title == null && LINK_TITLE_START.test(lines[lastLine + 1] ?? "")
298 ? firstLine
299 : undefined;
300 }
301 if (partialTitleStart !== undefined) {
302 // Retry at the candidate's label before looking beyond the batch limit.
303 if (partialTitleStart !== start) {
304 definitions.delete(partialTitleStart);
305 } else {
306 const titleStart = definitions.get(start)!.end + 1;
307 const opener = LINK_TITLE_START.exec(lines[titleStart]!)!;
308 const titleEnd = findTitleEnd(lines, titleStart, opener);
309 if (titleEnd !== undefined && titleEnd >= end) {
310 const full = definitionParser.parse(lines.slice(start, titleEnd + 1).join("\n"))
311 .children[0];
312 if (full?.type === "definition" && full.title != null) {
313 definitions.set(start, { end: titleEnd, identifier: full.identifier });
314 }
315 }
316 }
317 }
318 return definitions;
320​
321function isSpanningBlockOpen(line: string): boolean {
322 const firstChar = line.trimStart()[0];
323 if (firstChar !== "<" && firstChar !== "$") return false;
324 return SPANNING_BLOCKS.some(([open]) => open.test(line));
326​
327function interruptsFootnoteDefinition(line: string): boolean {
328 return (
329 (line.includes("[^") && FOOTNOTE_DEFINITION_START.test(line)) ||
330 ATX_HEADING.test(line) ||
331 THEMATIC_BREAK.test(line) ||
332 FENCE_OPEN.test(line) ||
333 FOOTNOTE_BLOCK_INTERRUPT.test(line) ||
334 HTML_BLOCK_TAG.test(line) ||
335 HTML_STANDALONE_TAG.test(line) ||
336 isSpanningBlockOpen(line)
337 );
339​
340const FOOTNOTE_INDENT_AFTER_QUOTE = /^[ \t]? {0,3}$/;
341​
342/** End of a link destination's `)` from `start`, or -1 for titles and nested parentheses. */
343function linkDestinationEnd(text: string, start: number): number {
344 // Every scan stops at the next `(` or `<`, so the scans of one paragraph do not overlap.
345 let j = start;
346 if (text[j] === "<") {
347 for (j++; j < text.length && text[j] !== ">"; j++) {
348 if (text[j] === "<" || text[j] === "\n") return -1;
349 if (text[j] === "\\") j++;
350 }
351 return text[j + 1] === ")" ? j + 1 : -1;
352 }
353 for (; j < text.length; j++) {
354 const c = text[j]!;
355 if (c === ")") return j;
356 if (c === "(" || c === "<" || /\s/.test(c)) return -1;
357 if (c === "\\") j++;
358 }
359 return -1;
361​
362/** Finds matching footnote references in body prose, skipping escapes, code spans, inline math, HTML comments, and link destinations. */
363function extractFootnoteRefs(text: string, definedKeys: ReadonlySet<string>): string[] {
364 if (!text.includes("[^")) return [];
365 const refs: string[] = [];
366 // Scans that found no close mark where later ones would fail too, so no text is rescanned.
367 let mathUnclosedUntil = -1;
368 let commentUnclosed = false;
369 // Unmatched `[`; a `](` without one is literal text, not the start of a destination.
370 let openBrackets = 0;
371 // The current line's leading `>` markers and indentation, tracked forward.
372 let scanned = 0;
373 let prefixEnd = 0;
374 let quoteEnd = 0;
375 const isAtLineStart = (i: number) => {
376 for (; scanned < i; scanned++) {
377 const c = text[scanned];
378 if (c === "\n") prefixEnd = quoteEnd = scanned + 1;
379 else if (prefixEnd === scanned && (c === " " || c === "\t" || c === ">")) {
380 prefixEnd++;
381 if (c === ">") quoteEnd = prefixEnd;
382 }
383 }
384 return prefixEnd === i && FOOTNOTE_INDENT_AFTER_QUOTE.test(text.slice(quoteEnd, i));
385 };
386 for (let i = 0; i < text.length; i++) {
387 const ch = text[i];
388 if (ch === "\\") {
389 i++;
390 continue;
391 }
392 if (ch === "`") {
393 let ticks = 1;
394 while (text[i + ticks] === "`") ticks++;
395 let j = i + ticks;
396 let closed = -1;
397 while (j < text.length) {
398 if (text[j] === "`") {
399 let run = 1;
400 while (text[j + run] === "`") run++;
401 if (run === ticks) {
402 closed = j + run - 1;
403 break;
404 }
405 j += run;
406 continue;
407 }
408 j++;
409 }
410 if (closed !== -1) i = closed;
411 else i += ticks - 1;
412 continue;
413 }
414 if (ch === "$" && text[i + 1] !== "$" && i >= mathUnclosedUntil) {
415 const next = text[i + 1];
416 if (next !== undefined && next !== " " && next !== "\t" && next !== "\n") {
417 let j = i + 1;
418 let closed = -1;
419 while (j < text.length && text[j] !== "\n") {
420 if (text[j] === "\\") {
421 j += 2;
422 continue;
423 }
424 if (
425 text[j] === "$" &&
426 text[j + 1] !== "$" &&
427 text[j - 1] !== " " &&
428 text[j - 1] !== "\t"
429 ) {
430 closed = j;
431 break;
432 }
433 j++;
434 }
435 if (closed !== -1) {
436 i = closed;
437 continue;
438 }
439 mathUnclosedUntil = j;
440 }
441 }
442 if (ch === "<" && !commentUnclosed && text.startsWith("<!--", i)) {
443 const close = text.indexOf("-->", i + 4);
444 if (close !== -1) {
445 i = close + 2;
446 continue;
447 }
448 commentUnclosed = true;
449 }
450 if (ch === "[" && text[i + 1] !== "^") openBrackets++;
451 if (ch === "]" && openBrackets > 0) {
452 openBrackets--;
453 const end = text[i + 1] === "(" ? linkDestinationEnd(text, i + 2) : -1;
454 if (end !== -1) {
455 i = end;
456 continue;
457 }
458 }
459 if (ch === "[" && text[i + 1] === "^") {
460 let j = i + 2;
461 while (j < text.length) {
462 const c = text[j]!;
463 if (c === "]" || c === "[" || /\s/.test(c)) break;
464 j++;
465 }
466 if (j > i + 2 && text[j] === "]") {
467 const isDefAtLineStart = text[j + 1] === ":" && isAtLineStart(i);
468 if (!isDefAtLineStart) {
469 const label = text.slice(i + 2, j);
470 if (definedKeys.has(label.toLowerCase())) {
471 refs.push(label);
472 }
473 }
474 i = j;
475 }
476 }
477 }
478 return refs;
480​
481export interface MarkdownFootnotes {
482 /** One-line stub definitions (`[^id]: .`) so body chunks resolve footnote references. */
483 readonly stubs: string;
484 /** Real footnote definitions in document order for the trailing footnotes section. */
485 readonly definitions: string;
486 /** Where each of `definitions` sits in the file, so edits made in the section reach the file. */
487 readonly definitionSpans: readonly (readonly [offset: number, length: number])[];
488 /** Referenced footnote labels in document order for each chunk (empty when a chunk has none). */
489 readonly chunkRefs: readonly (readonly string[])[];
491​
492export interface SplitMarkdown {
493 readonly chunks: readonly MarkdownChunk[];
494 readonly definitions: string;
495 readonly footnotes?: MarkdownFootnotes | undefined;
497​
498/**
499 * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs
500 * that start a new top-level block. Leading frontmatter stays in the first piece. Link
501 * definitions and footnote definitions are collected so references resolve across pieces;
502 * duplicate heading slugs still restart per piece.
503 */
504export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown {
505 return splitMarkdownBlocks(text, targetChars);
507​
508function splitMarkdownBlocks(
509 text: string,
510 targetChars: number,
511 knownLines?: Map<number, FlowLineKind>,
512): SplitMarkdown {
513 const mayHaveFootnotes = text.includes("[^") && text.includes("]:");
514 const chunks: MarkdownChunk[] = [];
515 const chunkLineRanges: Array<readonly [start: number, end: number]> = [];
516 const definitions: string[] = [];
517 const omittedDefinitions = new Set<string>();
518 const capturedFootnoteKeys = new Set<string>();
519 const seenFootnoteKeys = new Set<string>();
520 const capturedFootnoteLabels: string[] = [];
521 const footnoteDefs: string[] = [];
522 const footnoteDefSpans: (readonly [offset: number, length: number])[] = [];
523 let activeFootnoteOffset = 0;
524 let chunkStartLine = 0;
525 let first = true;
526 let closes: ((line: string) => boolean) | null = null;
527 let ambiguousHtml = false;
528 let listFenceIndent = 0;
529 let afterBlankLine = false;
530 let definitionEnd = -1;
531 let pendingDefinitions: ReturnType<typeof readLinkDefinitions> | undefined;
532 let afterHeading = false;
533 // Indented code holds literal `[^x]`; an indented line under a list item continues the item.
534 let inIndentedCode = false;
535 let inList = false;
536 let openedStandaloneBlock = false;
537 // The outermost list item's content column; a line indented less is outside every item.
538 let listContentIndent = Infinity;
539 let listMarker = "";
540 let emptyListItem = false;
541 let paragraphOpen = false;
542 let inTable = false;
543 // Prose after a quote line may be its lazy continuation, which an underline cannot end.
544 let afterQuote = false;
545 let definitionChars = 0;
546 let footnoteChars = 0;
547 let footnoteCapExceeded = false;
548 let openWrappers = 0;
549 let heldCut = 0;
550 let inFootnoteDef = false;
551 let activeFootnoteLabel: string | null = null;
552 let activeFootnoteLines: string[] | null = null;
553 let pendingFootnoteBlanks: string[] = [];
554​
555 const finishFootnoteDef = () => {
556 if (activeFootnoteLabel !== null && activeFootnoteLines !== null) {
557 const block = activeFootnoteLines.join("\n").trimEnd();
558 if (footnoteChars + block.length < SHARED_FOOTNOTES_MAX_CHARS) {
559 capturedFootnoteKeys.add(activeFootnoteLabel.toLowerCase());
560 capturedFootnoteLabels.push(activeFootnoteLabel);
561 footnoteDefs.push(block);
562 footnoteDefSpans.push([activeFootnoteOffset, block.length]);
563 footnoteChars += block.length + 2;
564 } else {
565 footnoteCapExceeded = true;
566 }
567 }
568 inFootnoteDef = false;
569 activeFootnoteLabel = null;
570 activeFootnoteLines = null;
571 pendingFootnoteBlanks = [];
572 };
573​
574 const sourceLines: string[] = [];
575 const lineStarts: number[] = [];
576 for (let start = 0; start <= text.length;) {
577 const end = nextLineBreak(text, start);
578 sourceLines.push(text.slice(start, end));
579 lineStarts.push(start);
580 start = end + 1;
581 }
582 // Slices the source so each piece keeps its own line endings and the break after it.
583 const flush = (endLine: number) => {
584 const from = lineStarts[chunkStartLine]!;
585 const to = endLine < sourceLines.length ? lineStarts[endLine]! - 1 : text.length;
586 const separator = text[to];
587 const chunk = { text: text.slice(from, to), lines: endLine - chunkStartLine };
588 chunks.push(separator === "\n" || separator === "\r" ? { ...chunk, separator } : chunk);
589 if (mayHaveFootnotes) chunkLineRanges.push([chunkStartLine, endLine]);
590 chunkStartLine = endLine;
591 heldCut = 0;
592 };
593​
594 const isBodyLine = mayHaveFootnotes ? new Uint8Array(sourceLines.length) : null;
595​
596 let flowStart = 0;
597 let parsedThrough = 0;
598 let htmlStarts: Set<number> | undefined;
599 let parseBudget = HTML_PARSE_BUDGET_CHARS;
600 let afterClosedBlock = false;
601 let afterPlainProse = false;
602 const resetFlow = (start: number) => {
603 flowStart = start;
604 parsedThrough = start;
605 htmlStarts = undefined;
606 };
607 for (const [lineIndex, sourceLine] of sourceLines.entries()) {
608 const line = knownLines && first ? sourceLine.replace(/^\uFEFF/, "") : sourceLine;
609 const chars = lineStarts[lineIndex]! - lineStarts[chunkStartLine]!;
610 const blank = BLANK_LINE.test(line);
611 const whitespace = /^[ \t]*/.exec(line)![0];
612 const indent = indentationColumn(whitespace);
613 if (emptyListItem && (blank || indent < listContentIndent)) listContentIndent = Infinity;
614 emptyListItem = false;
615 const continued = whitespace.includes("\t")
616 ? " ".repeat(indent) + line.slice(whitespace.length)
617 : line;
618 if (closes && listFenceIndent && !blank && indent < listFenceIndent) {
619 closes = null;
620 listFenceIndent = 0;
621 afterHeading = true;
622 resetFlow(lineIndex);
623 }
624 const dedented = indent < listContentIndent;
625 let handledAsFootnote = false;
626 let interruptedFootnote = false;
627 let closedBlock = false;
628 let plainProse = false;
629 let setextHeading = false;
630​
631 if (closes !== null) {
632 if (closes(continued)) {
633 closes = null;
634 listFenceIndent = 0;
635 closedBlock = true;
636 resetFlow(lineIndex + 1);
637 }
638 } else if (first && FRONTMATTER_OPEN.test(line) && hasFrontmatterClose(sourceLines)) {
639 closes = (next) => {
640 openedStandaloneBlock = FRONTMATTER_CLOSE.test(next);
641 return openedStandaloneBlock;
642 };
643 } else if (lineIndex > definitionEnd) {
644 if (inFootnoteDef) {
645 if (BLANK_LINE.test(line)) {
646 pendingFootnoteBlanks.push(line);
647 handledAsFootnote = true;
648 } else if (pendingFootnoteBlanks.length > 0) {
649 if (FOOTNOTE_CONTINUATION_INDENT.test(line)) {
650 if (activeFootnoteLines !== null) {
651 activeFootnoteLines.push(...pendingFootnoteBlanks, line);
652 }
653 pendingFootnoteBlanks = [];
654 handledAsFootnote = true;
655 } else {
656 finishFootnoteDef();
657 afterBlankLine = true;
658 }
659 } else if (FOOTNOTE_CONTINUATION_INDENT.test(line) || !interruptsFootnoteDefinition(line)) {
660 if (activeFootnoteLines !== null) activeFootnoteLines.push(line);
661 handledAsFootnote = true;
662 } else {
663 finishFootnoteDef();
664 interruptedFootnote = true;
665 }
666 }
667​
668 if (!handledAsFootnote) {
669 if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0;
670 const startsDedentedBlock =
671 dedented && !blank && (first || afterBlankLine || afterHeading || afterClosedBlock);
672 // Outside an open container, four columns at a block boundary start indented code.
673 if (
674 knownLines &&
675 !ambiguousHtml &&
676 openWrappers === 0 &&
677 indent >= 4 &&
678 !blank &&
679 (startsDedentedBlock || knownLines.get(lineIndex) === "indented-code")
680 ) {
681 knownLines.set(lineIndex + 1, "indented-code");
682 }
683 const cutPoint =
684 !ambiguousHtml &&
685 chars >= targetChars &&
686 ((line.startsWith("#") && ATX_HEADING.test(line)) ||
687 (afterBlankLine && BLOCK_START.test(line) && !LIST_ITEM.test(line)) ||
688 (knownLines !== undefined && chars > 0 && startsDedentedBlock));
689 if (cutPoint && openWrappers === 0) flush(lineIndex);
690 else if (cutPoint) heldCut = lineIndex;
691​
692 if (isBodyLine !== null && !BLANK_LINE.test(line)) {
693 if (!FOOTNOTE_CONTINUATION_INDENT.test(line)) {
694 inIndentedCode = false;
695 inList = LIST_ITEM_START.test(line) || (inList && !afterBlankLine);
696 } else if (!inList && (first || afterBlankLine || afterHeading)) {
697 inIndentedCode = true;
698 }
699 }
700​
701 const fnMatch =
702 mayHaveFootnotes && line.includes("[^") ? FOOTNOTE_DEFINITION_START.exec(line) : null;
703 if (fnMatch) {
704 const label = fnMatch[1]!;
705 const key = label.toLowerCase();
706 inFootnoteDef = true;
707 if (!seenFootnoteKeys.has(key)) {
708 seenFootnoteKeys.add(key);
709 activeFootnoteLabel = label;
710 activeFootnoteLines = [line];
711 activeFootnoteOffset = lineStarts[lineIndex]!;
712 } else {
713 activeFootnoteLabel = null;
714 activeFootnoteLines = null;
715 }
716 pendingFootnoteBlanks = [];
717 if (dedented) listContentIndent = Infinity;
718 paragraphOpen = false;
719 openedStandaloneBlock = false;
720 handledAsFootnote = true;
721 } else {
722 const continuesTable: boolean =
723 paragraphOpen &&
724 (inTable ||
725 (line.includes("|") &&
726 sourceLines[lineIndex - 1]!.includes("|") &&
727 TABLE_DELIMITER.test(line)));
728 // An underline below a table row or a list item's lazy continuation is just text.
729 setextHeading =
730 !ambiguousHtml &&
731 paragraphOpen &&
732 !continuesTable &&
733 !afterQuote &&
734 listContentIndent === Infinity &&
735 SETEXT_UNDERLINE.test(line);
736 const afterStandaloneBlock = afterHeading && openedStandaloneBlock && dedented;
737 const thematicBreak = THEMATIC_BREAK.test(line);
738 const contentColumn = dedented ? 0 : listContentIndent;
739 const canStartBlock = indent - contentColumn <= 3;
740 const content = canStartBlock ? line.slice(whitespace.length) : "";
741 const item = thematicBreak ? null : LIST_ITEM.exec(content);
742 const marker = item?.[1];
743 let itemContent = item ? content.slice(item[0].length) : "";
744 const itemIsEmpty = BLANK_LINE.test(itemContent);
745 const markerKind = marker?.at(-1);
746 const continuesList =
747 dedented && listContentIndent !== Infinity && markerKind === listMarker;
748 const opensItem: boolean =
749 item !== null &&
750 (!paragraphOpen ||
751 continuesList ||
752 (!itemIsEmpty && (!/^\d/.test(marker!) || /^1[.)]$/.test(marker!))));
753 let startsIndentedCode = false;
754 let itemFenceIndent = 0;
755 if (item && opensItem) {
756 const markerEnd = indent + item[1]!.length;
757 const paddedColumn = indentationColumn(item[2]!, markerEnd);
758 emptyListItem = dedented && itemIsEmpty;
759 // Empty items and items starting with indented code use one column of padding.
760 startsIndentedCode = paddedColumn - markerEnd > 4;
761 if (dedented) {
762 listContentIndent = itemIsEmpty || startsIndentedCode ? markerEnd + 1 : paddedColumn;
763 listMarker = markerKind!;
764 }
765 const nestedMarkers = NESTED_LIST_MARKERS.exec(itemContent)?.[0] ?? "";
766 itemContent = itemContent.slice(nestedMarkers.length);
767 if (!startsIndentedCode)
768 itemFenceIndent = indentationColumn(nestedMarkers, paddedColumn);
769 } else if (
770 dedented &&
771 !blank &&
772 (!paragraphOpen || afterBlankLine || afterStandaloneBlock || opensNonParagraph(line))
773 ) {
774 // Dedented prose can still be a lazy continuation until a block boundary.
775 listContentIndent = Infinity;
776 }
777 const listCloser =
778 itemFenceIndent && FENCE_OPEN.test(itemContent) ? blockCloser(itemContent) : null;
779 listFenceIndent = listCloser ? itemFenceIndent : 0;
780 const closer = listCloser
781 ? (next: string) => listCloser(next.slice(itemFenceIndent))
782 : blockCloser(line);
783 openedStandaloneBlock =
784 Boolean(listCloser) ||
785 (FENCE_OPEN.test(line) && (dedented || /^ ?[`~]/.test(line))) ||
786 (line.startsWith("<") && SPANNING_BLOCKS.some(([open]) => open.test(line)));
787 closes = closer ?? null;
788 closedBlock = closer === null;
789 if (
790 closer === null ||
791 setextHeading ||
792 ATX_HEADING.test(line) ||
793 THEMATIC_BREAK.test(line)
794 ) {
795 resetFlow(lineIndex + 1);
796 } else if (closer === undefined && HTML_STANDALONE_TAG.test(line)) {
797 // Type-7 HTML cannot interrupt prose. Keep ambiguous tags beyond the parse
798 // budget with their following lines, as a cut could expose literal HTML as Markdown.
799 if (htmlStarts === undefined && lineIndex > flowStart) {
800 let end = flowStart;
801 let flowChars = 0;
802 const maxChars = Math.min(HTML_FLOW_MAX_CHARS, parseBudget);
803 for (; end < sourceLines.length; end++) {
804 const next = sourceLines[end]!;
805 flowChars += next.length + 1;
806 if (flowChars > maxChars || BLANK_LINE.test(next)) break;
807 // Include the boundary line, which can end a lazy container continuation.
808 if (
809 ATX_HEADING.test(next) ||
810 THEMATIC_BREAK.test(next) ||
811 blockCloser(next) !== undefined
812 ) {
813 end++;
814 break;
815 }
816 }
817 parsedThrough = end;
818 htmlStarts = new Set();
819 if (lineIndex < end) {
820 const flowText = sourceLines.slice(flowStart, end).join("\n");
821 parseBudget -= flowText.length;
822 const flow = flowParser.parse(flowText);
823 for (const node of flow.children) {
824 if (node.type === "html" && node.position) {
825 htmlStarts.add(flowStart + node.position.start.line - 1);
826 }
827 }
828 }
829 }
830 if (lineIndex === flowStart || htmlStarts?.has(lineIndex)) closes = closesAtBlankLine;
831 else if (lineIndex >= parsedThrough) ambiguousHtml = true;
832 }
833 if (knownLines && !ambiguousHtml && openWrappers === 0 && dedented && closes === null) {
834 // An ordered list can interrupt a paragraph only when it starts at 1.
835 if (afterPlainProse && item && !opensItem) {
836 knownLines.set(lineIndex + 1, "paragraph");
837 }
838 if (afterPlainProse && SETEXT_EQUALS.test(line)) closedBlock = true;
839 plainProse =
840 !item && (startsDedentedBlock || afterPlainProse) && PLAIN_PROSE.test(line);
841 }
842 let isDefinition = false;
843 // A definition cannot interrupt a paragraph, so it follows a blank line, a heading,
844 // a closing code fence or frontmatter, or another definition.
845 if (
846 !ambiguousHtml &&
847 (first ||
848 afterBlankLine ||
849 lineIndex === definitionEnd + 1 ||
850 afterHeading ||
851 interruptedFootnote)
852 ) {
853 let definition = pendingDefinitions?.get(lineIndex);
854 if (
855 !definition &&
856 definitionChars < SHARED_DEFINITIONS_MAX_CHARS &&
857 hasDefinitionLabel(sourceLines, lineIndex)
858 ) {
859 pendingDefinitions = readLinkDefinitions(sourceLines, lineIndex);
860 definition = pendingDefinitions.get(lineIndex);
861 }
862 if (definition) {
863 isDefinition = true;
864 definitionEnd = definition.end;
865 if (!omittedDefinitions.has(definition.identifier)) {
866 if (
867 definition.text !== undefined &&
868 definitionChars + definition.text.length < SHARED_DEFINITIONS_MAX_CHARS
869 ) {
870 definitions.push(definition.text);
871 definitionChars += definition.text.length + 1;
872 } else {
873 omittedDefinitions.add(definition.identifier);
874 }
875 }
876 }
877 }
878 paragraphOpen =
879 !blank &&
880 !isDefinition &&
881 !setextHeading &&
882 !(paragraphOpen && !dedented && SETEXT_UNDERLINE.test(content)) &&
883 closes === null &&
884 (canStartBlock || paragraphOpen) &&
885 (item && opensItem
886 ? !BLANK_LINE.test(itemContent) &&
887 !startsIndentedCode &&
888 !opensNonParagraph(itemContent)
889 : !opensNonParagraph(line));
890 inTable = continuesTable && paragraphOpen;
891 afterQuote = BLOCK_QUOTE.test(line) || (afterQuote && paragraphOpen);
892 if (
893 isBodyLine !== null &&
894 closes === null &&
895 !inIndentedCode &&
896 !isDefinition &&
897 !BLANK_LINE.test(line) &&
898 !isSpanningBlockOpen(line)
899 ) {
900 isBodyLine[lineIndex] = 1;
901 }
902 }
903 }
904 }
905​
906 if (closes === closesAtBlankLine)
907 openWrappers = Math.max(0, openWrappers + openedWrappers(line));
908 first = false;
909 // A piece too large to render goes back to the last cut a wrapper held.
910 if (
911 heldCut > chunkStartLine &&
912 lineStarts[lineIndex]! + line.length - lineStarts[chunkStartLine]! >
913 LARGE_MARKDOWN_CHUNK_MAX_CHARS
914 ) {
915 flush(heldCut);
916 openWrappers = 0;
917 }
918 afterBlankLine = blank;
919 afterClosedBlock = closedBlock;
920 afterPlainProse = plainProse;
921 if (afterBlankLine) {
922 ambiguousHtml = false;
923 resetFlow(lineIndex + 1);
924 }
925 afterHeading =
926 !handledAsFootnote &&
927 closes === null &&
928 (openedStandaloneBlock ||
929 setextHeading ||
930 ATX_HEADING.test(line) ||
931 THEMATIC_BREAK.test(line));
932 }
933 if (inFootnoteDef) finishFootnoteDef();
934 flush(sourceLines.length);
935​
936 let footnotes: MarkdownFootnotes | undefined;
937 if (
938 isBodyLine !== null &&
939 !footnoteCapExceeded &&
940 chunks.length > 1 &&
941 capturedFootnoteKeys.size > 0
942 ) {
943 let anyRef = false;
944 const chunkRefs: string[][] = chunkLineRanges.map(([start, end], index) => {
945 // Oversized chunks display as source, so their references have no anchors.
946 if (chunks[index]!.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS) return [];
947 const refs: string[] = [];
948 let block: string[] = [];
949 const flushBlock = () => {
950 if (block.length === 0) return;
951 refs.push(...extractFootnoteRefs(block.join("\n"), capturedFootnoteKeys));
952 block = [];
953 };
954 for (let i = start; i < end; i++) {
955 if (isBodyLine[i] === 1) block.push(sourceLines[i]!);
956 else flushBlock();
957 }
958 flushBlock();
959 if (refs.length > 0) anyRef = true;
960 return refs;
961 });
962 if (anyRef) {
963 footnotes = {
964 stubs: capturedFootnoteLabels.map((label) => `[^${label}]: .`).join("\n"),
965 definitions: footnoteDefs.join("\n\n"),
966 definitionSpans: footnoteDefSpans,
967 chunkRefs,
968 };
969 }
970 }
971​
972 return footnotes
973 ? { chunks, definitions: definitions.join("\n"), footnotes }
974 : { chunks, definitions: definitions.join("\n") };
976​
977export function joinMarkdownChunks(chunks: readonly MarkdownChunk[]): string {
978 return chunks
979 .map((chunk, index) =>
980 index + 1 < chunks.length ? `${chunk.text}${chunk.separator ?? "\n"}` : chunk.text,
981 )
982 .join("");
984​
985/** Prepends shared definitions in document order; source offsets shift by the prefix length. */
986export function withMarkdownDefinitions(text: string, definitions: string): string {
987 if (!definitions) return text;
988 const masked = maskMarkdownFrontmatter(text);
989 return masked.startsWith("\uFEFF")
990 ? `\uFEFF${definitions}\n\n${masked.slice(1)}`
991 : `${definitions}\n\n${masked}`;
993​
994export interface PreparedMarkdownChunk {
995 readonly text: string;
996 readonly offsetShift: number;
997 readonly footnotesMode?: "omit" | "omit-seeded" | undefined;
999​
1000/**
1001 * Prepares one chunk of a split Markdown document with shared link definitions and, when the
1002 * chunk references document footnotes, stub definitions plus prior references so footnote numbers
1003 * and backref IDs match the whole document.
1004 */
1005export function prepareMarkdownChunk(
1006 chunkText: string,
1007 chunkIndex: number,
1008 definitions: string,
1009 footnotes?: MarkdownFootnotes,
1010): PreparedMarkdownChunk {
1011 if (!footnotes) {
1012 return {
1013 text: withMarkdownDefinitions(chunkText, definitions),
1014 offsetShift: definitions ? definitions.length + 2 : 0,
1015 };
1017 const refsInChunk = footnotes.chunkRefs[chunkIndex];
1018 if (!refsInChunk || refsInChunk.length === 0) {
1019 return {
1020 text: withMarkdownDefinitions(chunkText, definitions),
1021 offsetShift: definitions ? definitions.length + 2 : 0,
1022 footnotesMode: "omit",
1023 };
1025 const priorRefs: string[] = [];
1026 for (let i = 0; i < chunkIndex; i++) {
1027 const refs = footnotes.chunkRefs[i];
1028 if (refs) priorRefs.push(...refs);
1030 const prefixParts: string[] = [];
1031 if (definitions) prefixParts.push(definitions);
1032 prefixParts.push(footnotes.stubs);
1033 if (priorRefs.length > 0) {
1034 prefixParts.push(priorRefs.map((label) => `[^${label}]`).join(" "));
1035 } else {
1036 // An HTML comment closes the last stub footnote so a chunk starting with 4-space indented code
1037 // cannot be absorbed as a continuation of that stub.
1038 prefixParts.push("<!-- -->");
1040 const prefix = prefixParts.join("\n\n");
1041 return {
1042 text: withMarkdownDefinitions(chunkText, prefix),
1043 offsetShift: prefix.length + 2,
1044 footnotesMode: priorRefs.length > 0 ? "omit-seeded" : "omit",
1045 };
1047​
1048export interface MarkdownFootnotesSection {
1049 readonly text: string;
1050 /** Maps an offset in `text` to the file, or null outside the footnote definitions. */
1051 readonly fileOffset: (offset: number) => number | null;
1053​
1054/** Builds the Markdown source for the single trailing footnotes section of a split document. */
1055export function buildMarkdownFootnotesSection(
1056 definitions: string,
1057 footnotes?: MarkdownFootnotes,
1058): MarkdownFootnotesSection | null {
1059 if (!footnotes || !footnotes.definitions) return null;
1060 const allRefs = footnotes.chunkRefs.flat();
1061 if (allRefs.length === 0) return null;
1062 const parts: string[] = [];
1063 if (definitions) parts.push(definitions);
1064 parts.push(allRefs.map((label) => `[^${label}]`).join(" "));
1065 parts.push(footnotes.definitions);
1066 const text = parts.join("\n\n");
1067 const { definitionSpans } = footnotes;
1068 return {
1069 text,
1070 fileOffset: (offset) => {
1071 let start = text.length - footnotes.definitions.length;
1072 for (const [fileStart, length] of definitionSpans) {
1073 if (offset < start) return null;
1074 if (offset < start + length) return fileStart + offset - start;
1075 start += length + 2;
1077 return null;
1078 },
1079 };
1081​
1082/** Maps a footnote backref (`fnref-<fnNumber>` / `fnref-<fnNumber>-<occurrence>`) to its chunk. */
1083export function findFootnoteRefChunkIndex(
1084 footnotes: MarkdownFootnotes,
1085 fnNumber: number,
1086 occurrence: number,
1087): number | null {
1088 if (fnNumber < 1 || occurrence < 1) return null;
1089 const numberByKey = new Map<string, number>();
1090 const countByNumber = new Map<number, number>();
1091 let nextNumber = 1;
1092 for (let chunkIndex = 0; chunkIndex < footnotes.chunkRefs.length; chunkIndex++) {
1093 const refs = footnotes.chunkRefs[chunkIndex];
1094 if (!refs) continue;
1095 for (const label of refs) {
1096 const key = label.toLowerCase();
1097 let num = numberByKey.get(key);
1098 if (num === undefined) {
1099 num = nextNumber++;
1100 numberByKey.set(key, num);
1102 const occ = (countByNumber.get(num) ?? 0) + 1;
1103 countByNumber.set(num, occ);
1104 if (num === fnNumber && occ === occurrence) {
1105 return chunkIndex;
1109 return null;