From d650c5c3b8e56874998309c00a9957bad3eccfe4 Mon Sep 17 00:00:00 2001 From: videogame hacker Date: Thu, 26 May 2022 16:08:17 +0200 Subject: [PATCH] Initial commit --- .gitignore | 2 ++ Cargo.toml | 8 ++++++ src/lib.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0325629 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "chroma-syntaxis-comrak" +version = "0.1.0" +edition = "2021" + +[dependencies] +chroma-syntaxis = { git = "https://git.lavender.software/charlotte/chroma-syntaxis.git", features = ["built-in"] } +comrak = "0.12.1" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..a08be03 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,78 @@ +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::from("
")
+    }
+
+    fn build_code_tag(&self, attributes: &HashMap) -> String {
+        let mut s = String::from("');
+        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#"

Hello :)

+

Here is some code:

+
fn main() {
+    println!("Hello, world!")
+}
+
+"# + ); + } +}