aboutsummaryrefslogtreecommitdiff
path: root/code/src/syntax_highlight/mod.rs
blob: 62a2536f6d9382d65edf7df324e667415031c959 (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
pub mod grammar;
pub mod theme;

use crate::{markdown::render::escape, syntax_highlight::theme::theme};
use grammar::grammar_for;
use synoptic::{Highlighter, Token};

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();

    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>",
            }
        }
        out += "\n"
    }
    out
}