Open History to see the last commit
1// About one screen of rendered Markdown; parsing costs up to ~40 ms per KB with tables and math.
2const CHUNK_TARGET_CHARS = 4 * 1024;
3// A chunk past this (one huge fence or HTML block) is too slow to parse at once; show source.
4export const LARGE_MARKDOWN_CHUNK_MAX_CHARS = 128 * 1024;
5// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
6const FENCE_OPEN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
7const ATX_HEADING = /^#{1,6}(?:[ \t]|\r?$)/;
8// A thematic break, or a "---" setext underline; no paragraph stays open after either. A lone
9// "===" is paragraph text unless it underlines one, so it is left out.
10const THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
11// A column-0 paragraph, quote or table after a blank line closes any open list, quote or table.
12const BLOCK_START = /^[\p{L}\p{N}`[!|>]/u;
13const ORDERED_ITEM = /^\d{1,9}[.)](?:[ \t]|\r?$)/;
14// CommonMark HTML blocks of types 1-5 and display math run past blank lines until their closer.
15const SPANNING_BLOCKS: ReadonlyArray<readonly [open: RegExp, close: RegExp]> = [
16 [/^ {0,3}<(?:script|pre|style|textarea)(?=[\s>]|$)/i, /<\/(?:script|pre|style|textarea)>/i],
17 [/^ {0,3}<!--/, /-->/],
18 [/^ {0,3}<\?/, /\?>/],
19 [/^ {0,3}<!\[CDATA\[/, /\]\]>/],
20 [/^ {0,3}<![A-Za-z]/, />/],
21 [/^ {0,3}\$\$/, /\$\$/],
22];
23
24// A tag name, not an autolink such as <https://example.com>.
25const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/;
26
27/** Returns how to recognize the end of a block that `line` opens, or null for none. */
28function blockCloser(line: string): ((line: string) => boolean) | null {
29 const fence = FENCE_OPEN.exec(line)?.[1];
30 if (fence) {
31 return (next) => {
32 const closer = FENCE_OPEN.exec(next)?.[1];
33 return (
34 closer !== undefined &&
35 closer[0] === fence[0] &&
36 closer.length >= fence.length &&
37 !next.trim().slice(closer.length)
38 );
39 };
40 }
41 for (const [open, close] of SPANNING_BLOCKS) {
42 const opener = open.exec(line)?.[0];
43 if (opener === undefined) continue;
44 return close.test(line.slice(opener.length)) ? null : (next) => close.test(next);
45 }
46 // Other HTML blocks (CommonMark types 6 and 7) run until a blank line.
47 return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null;
48}
49
50export interface MarkdownChunk {
51 readonly text: string;
52 readonly lines: number;
53}
54
55const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/;
56const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/;
57// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one.
58const FRONTMATTER_MAX_LINES = 1000;
59
60// A one-line link reference definition; footnotes are left alone so each piece does not grow
61// a footnote section.
62const LINK_DEFINITION =
63 /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/;
64// Definitions past this are not repeated into every piece; their parse cost would outweigh links.
65const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024;
66
67export interface SplitMarkdown {
68 readonly chunks: readonly MarkdownChunk[];
69 readonly definitions: string;
70}
71
72/**
73 * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs
74 * that start a new top-level block. Leading frontmatter stays in the first piece. Link
75 * definitions are collected so every piece can resolve them; footnotes resolve only inside their
76 * own piece, and duplicate heading slugs restart per piece.
77 */
78export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown {
79 const chunks: MarkdownChunk[] = [];
80 const definitions: string[] = [];
81 let lines: string[] = [];
82 let first = true;
83 let chars = 0;
84 let closes: ((line: string) => boolean) | null = null;
85 let afterBlankLine = false;
86 let afterDefinition = false;
87 let afterHeading = false;
88 let definitionChars = 0;
89 const flush = () => {
90 chunks.push({ text: lines.join("\n"), lines: lines.length });
91 lines = [];
92 chars = 0;
93 };
94 for (const line of text.split("\n")) {
95 if (closes !== null) {
96 if (closes(line)) closes = null;
97 } else if (first && FRONTMATTER_OPEN.test(line)) {
98 let seen = 0;
99 closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES;
100 } else {
101 const cut =
102 chars >= targetChars &&
103 (ATX_HEADING.test(line) ||
104 (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line)));
105 if (cut) flush();
106 closes = blockCloser(line);
107 // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or
108 // another definition.
109 const definition: boolean =
110 (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line);
111 afterDefinition = definition;
112 if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) {
113 definitions.push(line.trim());
114 definitionChars += line.length + 1;
115 }
116 }
117 first = false;
118 lines.push(line);
119 chars += line.length + 1;
120 afterBlankLine = line.trim() === "";
121 afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line));
122 }
123 flush();
124 return { chunks, definitions: definitions.join("\n") };
125}
126
127/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */
128export function withMarkdownDefinitions(text: string, definitions: string): string {
129 return definitions ? `${text}\n\n${definitions}` : text;
130}