| 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 | */ |
| 10 | import { headerIsMarkdown } from "./headerIsMarkdown"; |
| 11 | |
| 12 | export 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)/)) |
| 15 | return source; |
| 16 | |
| 17 | let nestCount = 0; |
| 18 | const lines = source.split("\n"); |
| 19 | const trimmedLines = lines.map((l) => l.trim()); |
| 20 | |
| 21 | for (let i = 0; i < trimmedLines.length; i++) { |
| 22 | const line = trimmedLines[i]; |
| 23 | |
| 24 | if (nestCount > 0) { |
| 25 | // Inside a markdown block |
| 26 | if (line.match(/^`+$/)) { |
| 27 | // Ending a block with just backticks (```) |
| 28 | nestCount--; |
| 29 | if (nestCount === 0) { |
| 30 | lines[i] = "~~~"; // End of markdown block |
| 31 | } |
| 32 | } else if (line.startsWith("```")) { |
| 33 | // Going into a nested codeblock |
| 34 | nestCount++; |
| 35 | } |
| 36 | } else { |
| 37 | // Not inside a markdown block yet |
| 38 | if (line.startsWith("```")) { |
| 39 | const header = line.replaceAll("`", ""); |
| 40 | |
| 41 | // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants) |
| 42 | const isMarkdown = headerIsMarkdown(header); |
| 43 | |
| 44 | if (isMarkdown) { |
| 45 | nestCount = 1; |
| 46 | lines[i] = lines[i].replaceAll("`", "~"); |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return lines.join("\n"); |
| 53 | }; |