Elffuss BraidHub

kikocis/continue public

cb66032ac113 · 1.6 KiBRawPermalink
1/*
2 This is a patch for outputing markdown code that contains codeblocks
3
4 It notices markdown blocks (including GitHub-specific variants),
5 keeps track of when that specific block is closed,
6 and uses ~~~ instead of ``` for that block
7
8 Note, this was benchmarked at sub-millisecond
9*/
10import { headerIsMarkdown } from './headerIsMarkdown';
11
12export const patchNestedMarkdown = (source: string): string => {
13 // Early return if no markdown codeblock pattern is found (including GitHub variants)
14 if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) return source;
15
16 let nestCount = 0;
17 const lines = source.split("\n");
18 const trimmedLines = lines.map((l) => l.trim());
19
20 for (let i = 0; i < trimmedLines.length; i++) {
21 const line = trimmedLines[i];
22
23 if (nestCount > 0) {
24 // Inside a markdown block
25 if (line.match(/^`+$/)) {
26 // Ending a block with just backticks (```)
27 nestCount--;
28 if (nestCount === 0) {
29 lines[i] = "~~~"; // End of markdown block
30 }
31 } else if (line.startsWith("```")) {
32 // Going into a nested codeblock
33 nestCount++;
34 }
35 } else {
36 // Not inside a markdown block yet
37 if (line.startsWith("```")) {
38 const header = line.replaceAll("`", "");
39
40 // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants)
41 const isMarkdown = headerIsMarkdown(header);
42
43 if (isMarkdown) {
44 nestCount = 1;
45 lines[i] = lines[i].replaceAll("`", "~");
46 }
47 }
48 }
49 }
50
51 return lines.join("\n");
52};