aboutsummaryrefslogtreecommitdiff
path: root/code/src/syntax_highlight/mod.rs
blob: 86b689a3d80e34faec1bba6c1972bf40eb307ab7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use crate::markdown::render::escape;
use lazy_static::lazy_static;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Style, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};

lazy_static! {
    static ref PS: SyntaxSet = SyntaxSet::load_defaults_newlines();
    static ref TS: ThemeSet = ThemeSet::load_defaults();
}

pub fn syntax_highlight(lang: &str, source: &str) -> Option<String> {
    let syntax = PS.find_syntax_by_extension(lang)?;
    let mut h = HighlightLines::new(syntax, &TS.themes["Solarized (dark)"]);

    let mut o = String::new();
    for line in LinesWithEndings::from(source) {
        let ranges: Vec<(Style, &str)> = h.highlight_line(line, &PS).unwrap();
        for (style, span) in ranges {
            o += &format!(
                "<span style=\"color: #{:02x}{:02x}{:02x}\">{}</span>",
                style.foreground.r, style.foreground.g, style.foreground.b, span
            );
        }
    }
    return Some(o);
}