index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / markdown.rs
-rw-r--r-- blob b0baca650e3bf5a7202bd329a6e0e074ef1bc18b 3940 bytes (plain)
1
use std::collections::HashMap;
2
3
use pulldown_cmark::{CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html};
4
5
use crate::syntax_highlight;
6
7
pub fn render(raw: &str) -> String {
8
    let events: Vec<Event> = Parser::new_ext(raw, Options::all()).collect();
9
    let events = link_headings(events);
10
    let events = highlight_code_blocks(events);
11
12
    let mut out = String::new();
13
    html::push_html(&mut out, events.into_iter());
14
    out
15
}
16
17
fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
18
    let mut output = Vec::with_capacity(events.len());
19
    let mut code_lang: Option<String> = None;
20
    let mut code_buf = String::new();
21
22
    for event in events {
23
        match event {
24
            Event::Start(Tag::CodeBlock(kind)) => {
25
                let lang = match kind {
26
                    CodeBlockKind::Fenced(lang) => {
27
                        lang.split_whitespace().next().unwrap_or("").to_string()
28
                    }
29
                    CodeBlockKind::Indented => String::new(),
30
                };
31
                code_lang = Some(lang);
32
                code_buf.clear();
33
            }
34
            Event::Text(text) if code_lang.is_some() => {
35
                code_buf.push_str(&text);
36
            }
37
            Event::End(TagEnd::CodeBlock) => {
38
                if let Some(lang) = code_lang.take() {
39
                    let highlighted = syntax_highlight::highlight_block(&code_buf, &lang);
40
                    output.push(Event::Html(CowStr::from(highlighted)));
41
                }
42
            }
43
            other => output.push(other),
44
        }
45
    }
46
47
    output
48
}
49
50
fn link_headings(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
51
    let mut output = Vec::with_capacity(events.len());
52
    let mut seen: HashMap<String, usize> = HashMap::new();
53
    let mut i = 0;
54
55
    while i < events.len() {
56
        if let Event::Start(Tag::Heading {
57
            level,
58
            classes,
59
            attrs,
60
            id: None,
61
        }) = &events[i]
62
        {
63
            let level = *level;
64
            let classes = classes.clone();
65
            let attrs = attrs.clone();
66
67
            let mut j = i + 1;
68
            let mut text = String::new();
69
            while j < events.len() {
70
                match &events[j] {
71
                    Event::End(TagEnd::Heading(_)) => break,
72
                    Event::Text(t) | Event::Code(t) => text.push_str(t),
73
                    _ => {}
74
                }
75
                j += 1;
76
            }
77
78
            let mut slug = slugify(&text);
79
            if slug.is_empty() {
80
                slug = "section".to_string();
81
            }
82
            let count = seen.entry(slug.clone()).or_insert(0);
83
            if *count > 0 {
84
                slug = format!("{slug}-{count}");
85
            }
86
            *count += 1;
87
88
            output.push(Event::Start(Tag::Heading {
89
                level,
90
                id: Some(CowStr::from(slug.clone())),
91
                classes,
92
                attrs,
93
            }));
94
            output.push(Event::Start(Tag::Link {
95
                link_type: LinkType::Inline,
96
                dest_url: CowStr::from(format!("#{slug}")),
97
                title: CowStr::from(""),
98
                id: CowStr::from(""),
99
            }));
100
101
            output.extend_from_slice(&events[i + 1..j]);
102
            output.push(Event::End(TagEnd::Link));
103
            output.push(events[j].clone()); // End(Heading)
104
            i = j + 1;
105
        } else {
106
            output.push(events[i].clone());
107
            i += 1;
108
        }
109
    }
110
111
    output
112
}
113
114
fn slugify(text: &str) -> String {
115
    let mut slug = String::new();
116
    let mut last_was_dash = false;
117
118
    for c in text.to_lowercase().chars() {
119
        if c.is_alphanumeric() {
120
            slug.push(c);
121
            last_was_dash = false;
122
        } else if !last_was_dash {
123
            slug.push('-');
124
            last_was_dash = true;
125
        }
126
    }
127
128
    slug.trim_matches('-').to_string()
129
}