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