highlighter_target_html/
lib.rs

1use highlighter_core::Token;
2
3fn html_escape(str: String) -> String {
4    let mut new_str = String::new();
5
6    for char in str.chars() {
7        match char {
8            '>' => new_str.push_str(">"),
9            '<' => new_str.push_str("&lt;"),
10            '&' => new_str.push_str("&amp;"),
11            '\'' => new_str.push_str("&#39;"),
12            '"' => new_str.push_str("&quot;"),
13            _ => new_str.push(char),
14        }
15    }
16
17    new_str
18}
19
20/// An HTML target for Highlighter.
21/// 
22/// TODO: add a beautify option.
23#[derive(Clone, Debug, PartialEq)]
24pub struct HighlighterTargetHtml {
25    /// The prefix to use for outputted HTML.  Defaults to "".
26    html_prefix: String,
27
28    /// The prefix to use for outputted HTML.  Defaults to "".
29    html_suffix: String,
30
31    /// The prefix used for CSS class names.
32    /// 
33    /// Defaults to `scope-`.
34    class_prefix: String,
35}
36
37impl HighlighterTargetHtml {
38    /// Creates a new, default HTML target.
39    pub fn new() -> Self {
40        Self { html_prefix: String::new(), html_suffix: String::new(), class_prefix: "scope-".to_owned() }
41    }
42
43    /// Returns this HTML target, with the provided HTML prefix.
44    pub fn with_html_prefix<Str: Into<String>>(mut self, html_prefix: Str) -> Self {
45        self.html_prefix = html_prefix.into();
46        self
47    }
48
49    /// Returns this HTML target, with the provided HTML suffix.
50    pub fn with_html_suffix<Str: Into<String>>(mut self, html_suffix: Str) -> Self {
51        self.html_suffix = html_suffix.into();
52        self
53    }
54
55    /// Returns this HTML target, with the provided class prefix.
56    pub fn with_class_prefix<Str: Into<String>>(mut self, class_prefix: Str) -> Self {
57        self.class_prefix = class_prefix.into();
58        self
59    }
60
61    /// Builds the given tokens into a string of HTML.
62    pub fn build(&self, tokens: Vec<Token>) -> String {
63        let mut str = String::new();
64
65        for token in tokens {
66            str.push_str(&format!("<span class=\"{}{}\">{}</span>", self.class_prefix, token.scope.kebab_case(), html_escape(token.value)));
67        }
68
69        str
70    }
71}