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

markdownChunks.ts

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