xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / editor / highlight.rs 46 lines1.4 kB Raw
1use crate::ui::theme::pal;
2use rune::Span;
3
4pub fn spans(text: &str, ghost: Option<(usize, usize)>) -> Vec<Span> {
5    let p = pal();
6    let (mut out, mut pos, mut fence) = (vec![], 0, false);
7    for line in text.split_inclusive('\n') {
8        let body = line.trim_end_matches('\n');
9        let t = body.trim_start();
10        let heading = !fence && t.starts_with('#');
11        let muted = if t.starts_with("```") {
12            fence = !fence;
13            true
14        } else {
15            fence || t.starts_with("![") || t.starts_with("[![") || t.starts_with('>')
16        };
17        let span = Span::new(pos, pos + body.len());
18        if !body.is_empty() && heading {
19            out.push(span.color(p.strong).weight(500.0));
20        } else if !body.is_empty() && muted {
21            out.push(span.color(p.muted));
22        }
23
24        pos += line.len();
25    }
26    if let Some((a, b)) = ghost.filter(|(a, b)| a < b && *b <= text.len()) {
27        out.push(Span::new(a, b).color(p.faint).italic());
28    }
29    out
30}
31
32#[cfg(test)]
33mod tests {
34    #[test]
35    fn styles_headings_fences_and_images() {
36        let s = super::spans(
37            "# Title\ntext\n```\ncode\n```\n![a](b.png)\n",
38            Some((8, 12)),
39        );
40        let ranges: Vec<(u32, u32)> = s.iter().map(|s| (s.start, s.end)).collect();
41        assert_eq!(
42            ranges,
43            vec![(0, 7), (13, 16), (17, 21), (22, 25), (26, 37), (8, 12)]
44        );
45    }
46}