diff options
author | metamuffin <metamuffin@disroot.org> | 2022-09-26 14:14:58 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2022-09-26 14:14:58 +0200 |
commit | 15d78464ba9a717a71e1dc47a4101c8b13ec6581 (patch) | |
tree | 43def89ffd6e9c2ff80e7f7eeecec6fcf18c4e92 /code/src/syntax_highlight/mod.rs | |
parent | 0a18eae178a23e7f7bfd88c37502e5e8c1fdf64a (diff) | |
download | metamuffin-blog-15d78464ba9a717a71e1dc47a4101c8b13ec6581.tar metamuffin-blog-15d78464ba9a717a71e1dc47a4101c8b13ec6581.tar.bz2 metamuffin-blog-15d78464ba9a717a71e1dc47a4101c8b13ec6581.tar.zst |
syntax highlighting with syntect
Diffstat (limited to 'code/src/syntax_highlight/mod.rs')
-rw-r--r-- | code/src/syntax_highlight/mod.rs | 44 |
1 files changed, 23 insertions, 21 deletions
diff --git a/code/src/syntax_highlight/mod.rs b/code/src/syntax_highlight/mod.rs index 62a2536..86b689a 100644 --- a/code/src/syntax_highlight/mod.rs +++ b/code/src/syntax_highlight/mod.rs @@ -1,27 +1,29 @@ -pub mod grammar; -pub mod theme; -use crate::{markdown::render::escape, syntax_highlight::theme::theme}; -use grammar::grammar_for; -use synoptic::{Highlighter, Token}; +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}; -pub fn syntax_highlight(lang: &str, source: &str) -> String { - let mut h = Highlighter::new(); - for (kind, regex) in grammar_for(lang) { - h.join(regex, kind).unwrap(); - } - let highlighting = h.run(source); - let mut out = String::new(); +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)"]); - for (_c, row) in highlighting.iter().enumerate() { - for tok in row { - match tok { - Token::Start(kind) => out += &format!("<span style=\"color:{}\">", theme(kind)), - Token::Text(text) => out += &escape(text), - Token::End(_kind) => out += "</span>", - } + 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 + ); } - out += "\n" } - out + return Some(o); } |