From 6ef81940b89cf52c9c5f9074adaa88d57f2b00d0 Mon Sep 17 00:00:00 2001 From: Christoph Grabo Date: Tue, 6 Oct 2020 19:03:27 +0200 Subject: [PATCH] Add language class to code tag class attribute is only added if a language is available. It uses the format "language-xxx" as per commonmark spec: https://spec.commonmark.org/0.29/#example-112 ff. --- components/rendering/src/markdown.rs | 20 +++++++++++++++++++- components/rendering/tests/markdown.rs | 4 ++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/components/rendering/src/markdown.rs b/components/rendering/src/markdown.rs index ff419fbd..b60dc0ed 100644 --- a/components/rendering/src/markdown.rs +++ b/components/rendering/src/markdown.rs @@ -203,7 +203,19 @@ pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result { + let mut language = None; + match kind { + CodeBlockKind::Fenced(fence_info) => { + let fence_info = fence::FenceSettings::new(fence_info); + language = fence_info.language; + }, + _ => {} + }; if !context.config.highlight_code { + if let Some(lang) = language { + let html = format!(r#"
"#, lang);
+                                return Event::Html(html.into());
+                            }
                             return Event::Html("
".into());
                         }
 
@@ -227,7 +239,13 @@ pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result");
+                        if let Some(lang) = language {
+                            html.push_str(r#""#);
+                        } else {
+                            html.push_str("");
+                        }
                         Event::Html(html.into())
                     }
                     Event::End(Tag::CodeBlock(_)) => {
diff --git a/components/rendering/tests/markdown.rs b/components/rendering/tests/markdown.rs
index e37f9212..d1dcfdfd 100644
--- a/components/rendering/tests/markdown.rs
+++ b/components/rendering/tests/markdown.rs
@@ -53,7 +53,7 @@ fn can_highlight_code_block_with_lang() {
     let res = render_content("```python\nlist.append(1)\n```", &context).unwrap();
     assert_eq!(
         res.body,
-        "
\nlist.append(1)\n
" + "
\nlist.append(1)\n
" ); } @@ -68,7 +68,7 @@ fn can_higlight_code_block_with_unknown_lang() { // defaults to plain text assert_eq!( res.body, - "
\nlist.append(1)\n
" + "
\nlist.append(1)\n
" ); }