From 2c46b7476bc7a25f25458246090fef2ec28e5ac1 Mon Sep 17 00:00:00 2001 From: Shantur Rathore Date: Tue, 28 Oct 2025 16:48:50 +0000 Subject: [PATCH] Broaden code fence detection and default to text --- src/lib/markdown.ts | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/lib/markdown.ts b/src/lib/markdown.ts index ba9b6d85..ad1e2376 100644 --- a/src/lib/markdown.ts +++ b/src/lib/markdown.ts @@ -81,14 +81,15 @@ function resolveLanguage(token: string): { canonical: string | null; raw: string async function ensureLanguages(content: string) { // Parse code fences to extract language tokens - const codeBlockRegex = /```(\w*[#.\-+\w]*)/g + // Updated regex to capture optional language tokens and handle trailing annotations + const codeBlockRegex = /```[ \t]*([A-Za-z0-9_.+#-]+)?[^`]*?```/g const foundLanguages = new Set() let match while ((match = codeBlockRegex.exec(content)) !== null) { const langToken = match[1] - if (langToken) { - foundLanguages.add(langToken) + if (langToken && langToken.trim()) { + foundLanguages.add(langToken.trim()) } } @@ -97,6 +98,11 @@ async function ensureLanguages(content: string) { const { canonical, raw } = resolveLanguage(token) const langKey = canonical || raw + // Skip "text" and aliases since Shiki handles plain text already + if (langKey === "text" || raw === "text") { + continue + } + // Skip if already loaded or queued if (loadedLanguages.has(langKey) || queuedLanguages.has(langKey)) { continue @@ -156,11 +162,14 @@ function setupRenderer(isDark: boolean) { renderer.code = (code: string, lang: string | undefined) => { const encodedCode = encodeURIComponent(code) - const escapedLang = lang ? escapeHtml(lang) : "" + + // Use "text" as default when no language is specified + const resolvedLang = lang && lang.trim() ? lang.trim() : "text" + const escapedLang = escapeHtml(resolvedLang) const header = `
- ${escapedLang || ""} + ${escapedLang}
` - if (!lang || !highlighter) { + // Skip highlighting for "text" language or when highlighter is not available + if (resolvedLang === "text" || !highlighter) { return `
${header}
${escapeHtml(code)}
` } // Resolve language and check if it's loaded - const { canonical, raw } = resolveLanguage(lang) + const { canonical, raw } = resolveLanguage(resolvedLang) const langKey = canonical || raw + // Skip highlighting for "text" aliases + if (langKey === "text" || raw === "text") { + return `
${header}
${escapeHtml(code)}
` + } + // Use highlighting if language is loaded, otherwise fall back to plain code if (loadedLanguages.has(langKey)) { try {