Strip code fences from markdown rendering in terminal output

This commit is contained in:
Chris Wanstrath 2026-02-20 08:45:28 -08:00
parent 7c5746e268
commit 3e423a3b37
2 changed files with 20 additions and 1 deletions

View File

@ -1,7 +1,10 @@
export function renderMarkdown(text: string): string {
// Strip code fences (``` and ```language) — we're already in a terminal
let result = text.replace(/^```\w*\n?/gm, "")
// Extract code spans first so their contents aren't processed as bold/italic
const codeSpans: string[] = []
let result = text.replace(/`([^`]+)`/g, (_, code) => {
result = result.replace(/`([^`]+)`/g, (_, code) => {
codeSpans.push(code)
return `\x00CODE${codeSpans.length - 1}\x00`
})

View File

@ -16,3 +16,19 @@ for (const line of lines) {
console.log(` ${renderMarkdown(line)}`)
console.log()
}
// Code fence tests
console.log("--- Code fence tests ---")
const fenceTests = [
"Here is some code:\n```typescript\nconst x = 1\n```\nDone.",
"```\nhello\n```",
"```js\nconsole.log('hi')\n```",
]
for (const test of fenceTests) {
console.log("INPUT:")
console.log(test)
console.log("OUTPUT:")
console.log(renderMarkdown(test))
console.log()
}