use lazy_static::lazy_static; use syntect::easy::HighlightLines; use syntect::highlighting::{Style, ThemeSet}; use syntect::parsing::SyntaxSet; use syntect::util::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 { 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!( "{}", style.foreground.r, style.foreground.g, style.foreground.b, span ); } } return Some(o); }