From 2c9253049436112fc7b16fca36e109debae77c6f Mon Sep 17 00:00:00 2001 From: Antoine Lambert Date: Fri, 23 Aug 2024 15:36:22 +0200 Subject: [PATCH] Ensure to strip any code block annotation after language name Some markdown files can contain extra code block annotations after the language name, separated by commas. Such extra annotations break code highlighting after processing by showdown-highlight as the language name ends up invalid and cannot be found by highlight.js. So ensure to strip these extra annotations to fix HTML rendering. --- lib/index.js | 7 ++++++- package.json | 3 ++- test/index.js | 15 ++++++++++++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/index.js b/lib/index.js index f965549..9e8b763 100644 --- a/lib/index.js +++ b/lib/index.js @@ -51,10 +51,15 @@ module.exports = function showdownHighlight({ pre = false, auto_detection = true const replacement = (wholeMatch, match, left, right) => { match = decodeHtml(match) - const lang = (left.match(/class=\"([^ \"]+)/) || [])[1] + let lang = (left.match(/class=\"([^ \"]+)/) || [])[1] if (!lang && !auto_detection) { return wholeMatch + } else if (lang && lang.indexOf(',') > 0) { + // ensure to strip any code block annotation line no_run for instance + const langNoAnnotation = lang.slice(0, lang.indexOf(',')); + left = left.replace(new RegExp(lang, 'g'), langNoAnnotation); + lang = langNoAnnotation; } if (left.includes(classAttr)) { diff --git a/package.json b/package.json index d8e8dac..98d34d9 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "obedm503 (https://obedm503.github.io)", "Ariel Shaqed (Scolnicov) (https://github.com/arielshaqed)", "Bruno de Araújo Alves (devbaraus) (https://github.com/devbaraus)", - "Sekyu Kwon (https://github.com/Phryxia)" + "Sekyu Kwon (https://github.com/Phryxia)", + "Antoine Lambert (https://github.com/anlambert)" ] } \ No newline at end of file diff --git a/test/index.js b/test/index.js index 912900b..bfd6d54 100644 --- a/test/index.js +++ b/test/index.js @@ -12,14 +12,21 @@ function sayHello (msg, who) { return \`\${who} says: msg\`; } sayHello("Hello World", "Johnny"); - \`\`\`` + const CODEBLOCK_WITHOUT_LANGUAGE = ` \`\`\` function sayHello (msg, who) { return \`\${who} says: msg\`; } sayHello("Hello World", "Johnny"); +\`\`\`` + + const CODEBLOCK_WITH_LANGUAGE_AND_ANNOTATION = ` +\`\`\`rust,no_run +fn do_amazing_thing() -> i32 { + unimplemented!() +} \`\`\`` // After requiring the module, use it as extension @@ -42,6 +49,12 @@ sayHello("Hello World", "Johnny"); t.expect(html.includes('class="hljs"')).toEqual(true); }); + t.should("work with code block language and annotation", () => { + let html = converter.makeHtml(CODEBLOCK_WITH_LANGUAGE_AND_ANNOTATION); + t.expect(html.includes('class="hljs rust language-rust"')).toEqual(true); + t.expect(html.includes("hljs-type")).toEqual(true); + }); + const converter_auto_disabled = new showdown.Converter({ extensions: [showdownHighlight({ auto_detection: false