Skip to main content

devpage_core/
highlight.rs

1//! Syntax highlighting for fenced code blocks, done while the page renders.
2//!
3//! Code is wrapped in spans whose classes name syntax scopes (`hl-keyword`,
4//! `hl-string`…); the stylesheet colors those classes from theme tokens, so
5//! highlighting follows the light and dark themes like everything else. Mermaid
6//! blocks are left as plain text for `diagrams` to draw.
7
8use 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
18/// The languages bat ships, which include Swift, TypeScript, TOML and YAML
19/// besides syntect's defaults. Loaded once, on first use.
20static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(two_face::syntax::extra_newlines);
21
22const MERMAID: &str = "mermaid";
23
24pub struct Highlighter;
25
26/// `code` highlighted as `lang`, as the HTML that goes inside a `<code>`.
27pub 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    /// Only Mermaid blocks keep their language, so `diagrams` can find them; other
68    /// blocks carry no language label.
69    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('&', "&amp;")
93        .replace('<', "&lt;")
94        .replace('>', "&gt;")
95}