79 lines
2.1 KiB
Rust
79 lines
2.1 KiB
Rust
use std::collections::HashMap;
|
|
|
|
use chroma_syntaxis::highlight;
|
|
use comrak::adapters::SyntaxHighlighterAdapter;
|
|
|
|
pub struct ChromaSyntaxisAdapter<'a> {
|
|
highlight_names: &'a [&'a str],
|
|
}
|
|
impl SyntaxHighlighterAdapter for ChromaSyntaxisAdapter<'_> {
|
|
fn highlight(&self, lang: Option<&str>, code: &str) -> String {
|
|
match lang {
|
|
Some(lang) => highlight(lang, code, self.highlight_names),
|
|
None => code.to_string(),
|
|
}
|
|
}
|
|
|
|
fn build_pre_tag(&self, _attributes: &HashMap<String, String>) -> String {
|
|
String::from("<pre>")
|
|
}
|
|
|
|
fn build_code_tag(&self, attributes: &HashMap<String, String>) -> String {
|
|
let mut s = String::from("<code");
|
|
|
|
for (k, v) in attributes {
|
|
s.push(' ');
|
|
s.push_str(k);
|
|
s.push('=');
|
|
s.push('"');
|
|
s.push_str(v);
|
|
s.push('"');
|
|
}
|
|
|
|
s.push('>');
|
|
s
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use chroma_syntaxis::built_in::{register_builtin_languages, COMMON_HIGHLIGHT_NAMES};
|
|
use comrak::{markdown_to_html_with_plugins, ComrakOptions, ComrakPlugins};
|
|
|
|
use crate::ChromaSyntaxisAdapter;
|
|
|
|
#[test]
|
|
fn highlight_rust() {
|
|
register_builtin_languages();
|
|
|
|
let highlighter = ChromaSyntaxisAdapter {
|
|
highlight_names: COMMON_HIGHLIGHT_NAMES,
|
|
};
|
|
let mut plugins = ComrakPlugins::default();
|
|
plugins.render.codefence_syntax_highlighter = Some(&highlighter);
|
|
|
|
let input = r#"Hello :)
|
|
|
|
Here is some code:
|
|
|
|
```rust
|
|
fn main() {
|
|
println!("Hello, world!")
|
|
}
|
|
```"#;
|
|
|
|
let output = markdown_to_html_with_plugins(input, &ComrakOptions::default(), &plugins);
|
|
|
|
assert_eq!(
|
|
output,
|
|
r#"<p>Hello :)</p>
|
|
<p>Here is some code:</p>
|
|
<pre><code class="language-rust"><span class="keyword">fn</span> <span class="function">main</span><span class="punctuation bracket">()</span> {
|
|
<span class="function macro">println!</span><span class="punctuation bracket">(</span><span class="string">"Hello, world!"</span><span class="punctuation bracket">)</span>
|
|
}
|
|
</code></pre>
|
|
"#
|
|
);
|
|
}
|
|
}
|