Skip to content

Commit

Permalink
Add syntax highlighting.
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanpallant committed Nov 21, 2024
1 parent 21b943c commit 9f6c018
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,11 @@ pub fn generate_deck(

let md_content = md_content.replace("---", "## NO_HEADING");
let slide_adapter = plugins::SlideAdapter::new();
let syntax_highlighter = plugins::SyntaxHighlighter::new();
let options = comrak::Options::default();
let mut plugins = comrak::Plugins::default();
plugins.render.heading_adapter = Some(&slide_adapter);
plugins.render.codefence_syntax_highlighter = Some(&syntax_highlighter);
let html = comrak::markdown_to_html_with_plugins(&md_content, &options, &plugins);

let generated = generated.replace("$CONTENT", &html);
Expand Down
3 changes: 3 additions & 0 deletions src/plugins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
//! comrak plugins we need
mod slides;
mod syntax;

pub use slides::SlideAdapter;
pub use syntax::SyntaxHighlighter;
53 changes: 53 additions & 0 deletions src/plugins/syntax.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! Our Syntax Highlighting code,
//!
//! A comrak plugin for adding syntax highlighting classes to code blocks.
pub struct SyntaxHighlighter();

impl SyntaxHighlighter {
pub fn new() -> SyntaxHighlighter {
SyntaxHighlighter()
}
}

impl comrak::adapters::SyntaxHighlighterAdapter for SyntaxHighlighter {
fn write_pre_tag(
&self,
output: &mut dyn std::io::Write,
attributes: std::collections::HashMap<String, String>,
) -> std::io::Result<()> {
println!("Pre Attr: {:?}", attributes);
writeln!(output, "<pre>")?;
Ok(())
}

fn write_code_tag(
&self,
output: &mut dyn std::io::Write,
attributes: std::collections::HashMap<String, String>,
) -> std::io::Result<()> {
println!("Code Attr: {:?}", attributes);
let mut lang_class = "";
if let Some(class) = attributes.get("class") {
if let Some(lang) = class.strip_prefix("language-") {
lang_class = lang;
}
}
writeln!(
output,
r#"<code data-trim data-noescape class="{lang_class}">"#
)?;
Ok(())
}

fn write_highlighted(
&self,
output: &mut dyn std::io::Write,
lang: Option<&str>,
code: &str,
) -> std::io::Result<()> {
println!("Got lang {:?}", lang);
writeln!(output, "{}", code)?;
Ok(())
}
}

0 comments on commit 9f6c018

Please sign in to comment.