Open History to see the last commit
1// Definitions, footnotes, raw HTML, container directives and display math can tie blocks together.
2const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m;
3const FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/;
4// After a blank line these still continue the previous block: a list item or indented content.
5const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
6
7/**
8 * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it
9 * would inside the whole text. Returns null when the text uses syntax that spans blocks.
10 */
11export function splitMarkdownBlocks(text: string): string[] | null {
12 if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;
13 const blocks: string[] = [];
14 let blockStart = 0;
15 let lineStart = 0;
16 let fence: string | null = null;
17 let fenceIndent = 0;
18 let afterBlankLine = false;
19 for (const line of text.split("\n")) {
20 const opener = FENCE_PATTERN.exec(line)?.[1];
21 if (fence !== null) {
22 // A line left of an indented fence may end the list item holding it, which isn't tracked.
23 if (/\S/.test(line.slice(0, fenceIndent))) break;
24 if (
25 opener &&
26 opener[0] === fence[0] &&
27 opener.length >= fence.length &&
28 line.trim() === opener
29 ) {
30 fence = null;
31 }
32 } else if (line.trim() === "") {
33 afterBlankLine = true;
34 } else {
35 if (afterBlankLine && lineStart > blockStart && !CONTINUATION_PATTERN.test(line)) {
36 blocks.push(text.slice(blockStart, lineStart));
37 blockStart = lineStart;
38 }
39 afterBlankLine = false;
40 fence = opener ?? null;
41 if (opener) fenceIndent = line.indexOf(opener);
42 }
43 lineStart += line.length + 1;
44 }
45 blocks.push(text.slice(blockStart));
46 return blocks;
47}