Skip to content

Commit

Permalink
Add language class to code tag
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
asaaki authored and Keats committed Dec 14, 2020
1 parent bc3a41f commit 6ef8194
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
20 changes: 19 additions & 1 deletion components/rendering/src/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,19 @@ pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Render
}
}
Event::Start(Tag::CodeBlock(ref kind)) => {
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#"<pre><code class="language-{}">"#, lang);
return Event::Html(html.into());
}
return Event::Html("<pre><code>".into());
}

Expand All @@ -227,7 +239,13 @@ pub fn markdown_to_html(content: &str, context: &RenderContext) -> Result<Render
};
let snippet = start_highlighted_html_snippet(theme);
let mut html = snippet.0;
html.push_str("<code>");
if let Some(lang) = language {
html.push_str(r#"<code class="language-"#);
html.push_str(lang);
html.push_str(r#"">"#);
} else {
html.push_str("<code>");
}
Event::Html(html.into())
}
Event::End(Tag::CodeBlock(_)) => {
Expand Down
4 changes: 2 additions & 2 deletions components/rendering/tests/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
"<pre style=\"background-color:#2b303b;\">\n<code><span style=\"color:#c0c5ce;\">list.</span><span style=\"color:#bf616a;\">append</span><span style=\"color:#c0c5ce;\">(</span><span style=\"color:#d08770;\">1</span><span style=\"color:#c0c5ce;\">)\n</span></code></pre>"
"<pre style=\"background-color:#2b303b;\">\n<code class=\"language-python\"><span style=\"color:#c0c5ce;\">list.</span><span style=\"color:#bf616a;\">append</span><span style=\"color:#c0c5ce;\">(</span><span style=\"color:#d08770;\">1</span><span style=\"color:#c0c5ce;\">)\n</span></code></pre>"
);
}

Expand All @@ -68,7 +68,7 @@ fn can_higlight_code_block_with_unknown_lang() {
// defaults to plain text
assert_eq!(
res.body,
"<pre style=\"background-color:#2b303b;\">\n<code><span style=\"color:#c0c5ce;\">list.append(1)\n</span></code></pre>"
"<pre style=\"background-color:#2b303b;\">\n<code class=\"language-yolo\"><span style=\"color:#c0c5ce;\">list.append(1)\n</span></code></pre>"
);
}

Expand Down

0 comments on commit 6ef8194

Please sign in to comment.