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