Elffuss BraidHub

kikocis/continue public

c55965a9627b · 1.5 KiBRawPermalink
1/*
2 This is a patch for outputing markdown code that contains codeblocks
3
4 It notices markdown blocks, keeps track of when that specific block is closed,
5 and uses ~~~ instead of ``` for that block
6
7 Note, this was benchmarked at sub-millisecond
8
9 // TODO support github-specific markdown as well, edge case
10*/
11export const patchNestedMarkdown = (source: string): string => {
12 if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
13 // const start = Date.now();
14 let nestCount = 0;
15 const lines = source.split("\n");
16 const trimmedLines = lines.map((l) => l.trim());
17 for (let i = 0; i < trimmedLines.length; i++) {
18 const line = trimmedLines[i];
19 if (nestCount) {
20 if (line.match(/^`+$/)) {
21 // Ending a block
22 if (nestCount === 1) lines[i] = "~~~"; // End of markdown block
23 nestCount--;
24 } else if (line.startsWith("```")) {
25 // Going into a nested codeblock
26 nestCount++;
27 }
28 } else {
29 // Enter the markdown block, start tracking nesting
30 if (line.startsWith("```")) {
31 const header = line.replaceAll("`", "");
32 const file = header.split(" ")[0];
33
34 if (file) {
35 const ext = file.split(".").at(-1);
36 if (ext === "md" || ext === "markdown") {
37 nestCount = 1;
38 lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
39 }
40 }
41 }
42 }
43 }
44 const out = lines.join("\n");
45 // console.log(`patched in ${Date.now() - start}ms`);
46 return out;
47};