Debian Codegraph @

examples/syntax_highlighter.rs

raw
1 //! This example shows how to implement a syntax highlighter plugin.
2
3 use comrak::adapters::SyntaxHighlighterAdapter;
4 use comrak::{Options, markdown_to_html_with_plugins, options};
5 use std::borrow::Cow;
6 use std::collections::HashMap;
7 use std::fmt::{self, Write};
8
9 #[derive(Debug, Copy, Clone)]
10 pub struct PotatoSyntaxAdapter {
11 potato_size: i32,
12 }
13
14 impl PotatoSyntaxAdapter {
15 pub fn new(potato_size: i32) -> Self {
16 PotatoSyntaxAdapter { potato_size }
17 }
18 }
19
20 impl SyntaxHighlighterAdapter for PotatoSyntaxAdapter {
21 fn write_highlighted(
22 &self,
23 output: &mut dyn Write,
24 lang: Option<&str>,
25 code: &str,
26 ) -> fmt::Result {
27 write!(
28 output,
29 "<span class=\"potato-{}\">{}</span><span class=\"size-{}\">potato</span>",
30 lang.unwrap(),
31 code,
32 self.potato_size
33 )
34 }
35
36 fn write_pre_tag(
37 &self,
38 output: &mut dyn Write,
39 attributes: HashMap<&'static str, Cow<str>>,
40 ) -> fmt::Result {
41 if attributes.contains_key("lang") {
42 write!(output, "<pre lang=\"{}\">", attributes["lang"])
43 } else {
44 output.write_str("<pre>")
45 }
46 }
47
48 fn write_code_tag(
49 &self,
50 output: &mut dyn Write,
51 attributes: HashMap<&'static str, Cow<str>>,
52 ) -> fmt::Result {
53 if attributes.contains_key("class") {
54 write!(output, "<code class=\"{}\">", attributes["class"])
55 } else {
56 output.write_str("<code>")
57 }
58 }
59 }
60
61 fn main() {
62 let adapter = PotatoSyntaxAdapter::new(42);
63 let options = Options::default();
64 let mut plugins = options::Plugins::default();
65
66 plugins.render.codefence_syntax_highlighter = Some(&adapter);
67
68 let input = concat!("```Rust\n", "fn main<'a>();\n", "```");
69
70 let formatted = markdown_to_html_with_plugins(input, &options, &plugins);
71
72 println!("{}", formatted);
73 }