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;
3// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
4const FENCE_PATTERN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
5// After a blank line these still continue the previous block: a list item or indented content.
6const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
7// Claude insight fences render as one callout, so they stay in one block until the closing rule.
8const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
9const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
10
11/**
12 * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it
13 * would inside the whole text. Returns null when the text uses syntax that spans blocks.
14 */
15export function splitMarkdownBlocks(text: string): string[] | null {
16 if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;
17 const blocks: string[] = [];
18 let blockStart = 0;
19 let lineStart = 0;
20 let fence: string | null = null;
21 let fenceIndent = 0;
22 let afterBlankLine = false;
23 let insightIndent: string | null = null;
24 for (const line of text.split("\n")) {
25 const opener = FENCE_PATTERN.exec(line)?.[1];
26 if (fence !== null) {
27 // A line left of an indented fence may end the list item holding it, which isn't tracked.
28 if (/\S/.test(line.slice(0, fenceIndent))) break;
29 if (
30 opener &&
31 opener[0] === fence[0] &&
32 opener.length >= fence.length &&
33 line.trim() === opener
34 ) {
35 fence = null;
36 }
37 } else if (insightIndent !== null && INSIGHT_CLOSE_PATTERN.exec(line)?.[1] === insightIndent) {
38 insightIndent = null;
39 afterBlankLine = false;
40 } else if (line.trim() === "") {
41 afterBlankLine = true;
42 } else {
43 if (
44 afterBlankLine &&
45 insightIndent === null &&
46 lineStart > blockStart &&
47 !CONTINUATION_PATTERN.test(line)
48 ) {
49 blocks.push(text.slice(blockStart, lineStart));
50 blockStart = lineStart;
51 }
52 afterBlankLine = false;
53 if (insightIndent === null) insightIndent = INSIGHT_OPEN_PATTERN.exec(line)?.[1] ?? null;
54 fence = opener ?? null;
55 if (opener) fenceIndent = line.indexOf(opener);
56 }
57 lineStart += line.length + 1;
58 }
59 blocks.push(text.slice(blockStart));
60 return blocks;
61}