The best way to control Claude Code, Codex and more from any computer or phone

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