Open History to see the last commit
1import { githubHeadingSlug } from "./markdownFragments";
2
3// Footnotes, raw HTML, container directives and display math can tie blocks together.
4const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:<[A-Za-z!?/]|:::|\$\$|\\\[)|\[\^/m;
5// Link definitions apply document-wide, even inside quotes or list items and with multiline labels.
6const REFERENCE_DEFINITION_PATTERN =
7 /^[ \t]*(?:(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t]))[ \t]*)*\[(?:\\[\s\S]|[^[\]\\])+\]:/m;
8// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
9const FENCE_PATTERN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
10const BLANK_LINE_PATTERN = /^[ \t]*$/;
11// After a blank line these still continue the previous block: a list item or indented content.
12const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
13// Claude insight fences render as one callout, so they stay in one block until the closing rule.
14const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
15const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
16// An ATX heading, also inside a list item or blockquote; group 1 is its text.
17const ATX_HEADING_PATTERN =
18 /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
19// Setext headings may span a paragraph and containers, so leave their parsing to the renderer.
20const SETEXT_UNDERLINE_PATTERN =
21 /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/;
22
23/**
24 * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it
25 * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as
26 * headings with the same slug, whose ids are numbered across the whole text.
27 */
28export function splitMarkdownBlocks(text: string): string[] | null {
29 // remark-parse strips a leading BOM before recognizing the first heading.
30 if (
31 text.startsWith("\ufeff") ||
32 text.includes("\r") ||
33 DOCUMENT_WIDE_SYNTAX.test(text) ||
34 REFERENCE_DEFINITION_PATTERN.test(text)
35 )
36 return null;
37 const blocks: string[] = [];
38 let blockStart = 0;
39 let lineStart = 0;
40 let fence: string | null = null;
41 let fenceIndent = 0;
42 let afterBlankLine = false;
43 let insightIndent: string | null = null;
44 const headingKeys = new Set<string>();
45 const needsWholeHeading = (headingText: string | undefined) => {
46 if (headingText === undefined) return false;
47 // Inline syntax and path/directive colons need the renderer before their slug is known.
48 if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true;
49 const key = githubHeadingSlug(headingText);
50 if (!key) return false;
51 if (headingKeys.has(key)) return true;
52 headingKeys.add(key);
53 return false;
54 };
55 const headingNeedsWholeDocument = (line: string, mayUnderline = true) =>
56 (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) ||
57 needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]);
58 // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break.
59 let afterContentLine = false;
60 for (const line of text.split("\n")) {
61 const opener = FENCE_PATTERN.exec(line)?.[1];
62 const mayUnderline = afterContentLine;
63 afterContentLine = false;
64 if (fence !== null) {
65 // A line left of an indented fence may end the list item holding it, which isn't tracked.
66 if (/\S/.test(line.slice(0, fenceIndent))) {
67 const rest = text.slice(lineStart).split("\n");
68 for (const restLine of rest) {
69 if (headingNeedsWholeDocument(restLine)) return null;
70 }
71 break;
72 }
73 if (
74 opener &&
75 opener[0] === fence[0] &&
76 opener.length >= fence.length &&
77 BLANK_LINE_PATTERN.test(line.slice(line.indexOf(opener) + opener.length))
78 ) {
79 fence = null;
80 }
81 } else if (insightIndent !== null && INSIGHT_CLOSE_PATTERN.exec(line)?.[1] === insightIndent) {
82 insightIndent = null;
83 afterBlankLine = false;
84 } else if (BLANK_LINE_PATTERN.test(line)) {
85 afterBlankLine = true;
86 } else {
87 if (headingNeedsWholeDocument(line, mayUnderline)) return null;
88 afterContentLine = opener === undefined;
89 if (
90 afterBlankLine &&
91 insightIndent === null &&
92 lineStart > blockStart &&
93 !CONTINUATION_PATTERN.test(line) &&
94 // A block starting with a BOM would treat it as the document's leading one.
95 !line.startsWith("\ufeff")
96 ) {
97 blocks.push(text.slice(blockStart, lineStart));
98 blockStart = lineStart;
99 }
100 afterBlankLine = false;
101 if (insightIndent === null) insightIndent = INSIGHT_OPEN_PATTERN.exec(line)?.[1] ?? null;
102 fence = opener ?? null;
103 if (opener) fenceIndent = line.indexOf(opener);
104 }
105 lineStart += line.length + 1;
106 }
107 blocks.push(text.slice(blockStart));
108 return blocks;
109}