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 afterBlankLine = false;
18 for (const line of text.split("\n")) {
19 const opener = FENCE_PATTERN.exec(line)?.[1];
20 if (fence !== null) {
21 if (
22 opener &&
23 opener[0] === fence[0] &&
24 opener.length >= fence.length &&
25 line.trim() === opener
26 ) {
27 fence = null;
28 }
29 } else if (line.trim() === "") {
30 afterBlankLine = true;
31 } else {
32 if (afterBlankLine && lineStart > blockStart && !CONTINUATION_PATTERN.test(line)) {
33 blocks.push(text.slice(blockStart, lineStart));
34 blockStart = lineStart;
35 }
36 afterBlankLine = false;
37 fence = opener ?? null;
38 }
39 lineStart += line.length + 1;
40 }
41 blocks.push(text.slice(blockStart));
42 return blocks;
43}