carbon_lib/utils/
html.rs

1use carbon_dump::SYNTAX_SET;
2use std::ops::Deref;
3use syntect::{
4    easy::HighlightLines,
5    highlighting::Theme,
6    html::{
7        append_highlighted_html_for_styled_line, start_highlighted_html_snippet, styled_line_to_highlighted_html,
8        IncludeBackground,
9    },
10    parsing::SyntaxReference,
11    util::LinesWithEndings,
12};
13
14pub fn html_render_line(s: &str, syntax: &SyntaxReference, theme: &Theme) -> String {
15    let mut highlighter = HighlightLines::new(syntax, theme);
16    let (mut output, bg) = start_highlighted_html_snippet(theme);
17    for line in LinesWithEndings::from(s) {
18        let regions = highlighter.highlight(line, SYNTAX_SET.deref());
19        append_highlighted_html_for_styled_line(&regions[..], IncludeBackground::IfDifferent(bg), &mut output);
20    }
21    output.push_str("</pre>\n");
22    output
23}
24
25pub fn html_render_line_number(s: &str, syntax: &SyntaxReference, theme: &Theme) -> String {
26    let all = format!("{}", s.lines().count()).len();
27    let mut line_number = 1;
28    let mut highlighter = HighlightLines::new(syntax, theme);
29    let (mut output, bg) = start_highlighted_html_snippet(theme);
30    for line in LinesWithEndings::from(s) {
31        let regions = highlighter.highlight(line, SYNTAX_SET.deref());
32        let color = theme.settings.foreground.unwrap();
33        let line = format!(
34            r#"<span style="color:#{:02X}{:02X}{:02X};"> {:>width$} </span>{}"#,
35            color.r,
36            color.g,
37            color.b,
38            line_number,
39            styled_line_to_highlighted_html(&regions[..], IncludeBackground::IfDifferent(bg)),
40            width = all
41        );
42        line_number += 1;
43        output.push_str(&line)
44    }
45    output.push_str("</pre>\n");
46    output
47}
48
49pub fn html_fancy_box(s: &str, title: &Option<String>) -> String {
50    format!(
51        r#"<div class="carbon">
52        <div class="controls"><div class="circle red"></div><div class="circle yellow"></div><div class="circle green"></div>{}</div>
53        <div class="content">{}</div></div>"#,
54        match title {
55            Some(s) => {
56                format!(r#"<div class="title">{}</div>"#, s)
57            }
58            None => {
59                String::new()
60            }
61        },
62        s
63    )
64}