devpage_core/
highlight.rs1use std::borrow::Cow;
9use std::collections::HashMap;
10use std::fmt;
11use std::sync::LazyLock;
12
13use comrak::adapters::SyntaxHighlighterAdapter;
14use syntect::html::{ClassStyle, ClassedHTMLGenerator};
15use syntect::parsing::SyntaxSet;
16use syntect::util::LinesWithEndings;
17
18static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(two_face::syntax::extra_newlines);
21
22const MERMAID: &str = "mermaid";
23
24pub struct Highlighter;
25
26pub fn highlight(lang: &str, code: &str) -> String {
28 let mut html = String::new();
29 let _ = Highlighter.write_highlighted(&mut html, Some(lang), code);
30 html
31}
32
33impl SyntaxHighlighterAdapter for Highlighter {
34 fn write_highlighted(
35 &self,
36 output: &mut dyn fmt::Write,
37 lang: Option<&str>,
38 code: &str,
39 ) -> fmt::Result {
40 let lang = lang
41 .and_then(|info| info.split_whitespace().next())
42 .unwrap_or("");
43 match SYNTAXES
44 .find_syntax_by_token(lang)
45 .filter(|_| lang != MERMAID)
46 {
47 Some(syntax) => {
48 let mut html = ClassedHTMLGenerator::new_with_class_style(
49 syntax,
50 &SYNTAXES,
51 ClassStyle::SpacedPrefixed { prefix: "hl-" },
52 );
53 for line in LinesWithEndings::from(code) {
54 if html
55 .parse_html_for_line_which_includes_newline(line)
56 .is_err()
57 {
58 return output.write_str(&escape(code));
59 }
60 }
61 output.write_str(&html.finalize())
62 }
63 None => output.write_str(&escape(code)),
64 }
65 }
66
67 fn write_pre_tag(
70 &self,
71 output: &mut dyn fmt::Write,
72 attributes: HashMap<&'static str, Cow<'_, str>>,
73 ) -> fmt::Result {
74 match attributes.get("lang") {
75 Some(lang) if lang.split_whitespace().next() == Some(MERMAID) => {
76 output.write_str("<pre lang=\"mermaid\">")
77 }
78 _ => output.write_str("<pre>"),
79 }
80 }
81
82 fn write_code_tag(
83 &self,
84 output: &mut dyn fmt::Write,
85 _attributes: HashMap<&'static str, Cow<'_, str>>,
86 ) -> fmt::Result {
87 output.write_str("<code>")
88 }
89}
90
91fn escape(text: &str) -> String {
92 text.replace('&', "&")
93 .replace('<', "<")
94 .replace('>', ">")
95}