wit / src / markdown.rs 206 commits
23-11-2026
522 lines 18 kB
  1use crate::html::{
  2    data_uri, escape_str, find_file, follow_links, icon, image_type, path_href, percent_encode,
  3    resolve_path,
  4};
  5use crate::repo_info::{RefInfo, RepoInfo};
  6
  7use pulldown_cmark::{
  8    BlockQuoteKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd, html::push_html,
  9};
 10use std::collections::{HashMap, HashSet};
 11
 12const PAGE_IDS: [&str; 7] = [
 13    "header",
 14    "site_path",
 15    "ref-menu",
 16    "ref-branches",
 17    "ref-tags",
 18    "view-source",
 19    "view-rendered",
 20];
 21
 22const NUMBERED_PAGE_IDS: [&str; 2] = ["ref-more-", "release-"];
 23
 24struct RawHeading {
 25    start: usize,
 26    level: u8,
 27    open_end: usize,
 28    close: usize,
 29    close_end: usize,
 30    has_id: bool,
 31    text: String,
 32    label: String,
 33}
 34
 35pub fn is_markdown(name: &str) -> bool {
 36    name == "README"
 37        || name
 38            .rsplit_once('.')
 39            .is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("md"))
 40}
 41
 42pub fn write_markdown(
 43    body: &mut String,
 44    class: &str,
 45    repo: &RepoInfo,
 46    git_ref: &RefInfo,
 47    base: &str,
 48    repo_root: &str,
 49    content: &[u8],
 50) {
 51    let text = String::from_utf8_lossy(content);
 52    let options = Options::ENABLE_TABLES
 53        | Options::ENABLE_STRIKETHROUGH
 54        | Options::ENABLE_TASKLISTS
 55        | Options::ENABLE_FOOTNOTES
 56        | Options::ENABLE_GFM;
 57    let parsed = Parser::new_ext(&text, options).map(|mut event| {
 58        match &mut event {
 59            Event::Start(Tag::Link {
 60                link_type,
 61                dest_url,
 62                ..
 63            }) if *link_type != LinkType::Email => {
 64                if let Some(url) = link_target(git_ref, base, repo_root, dest_url) {
 65                    *dest_url = url.into();
 66                }
 67            }
 68            Event::Start(Tag::Image { dest_url, .. }) => {
 69                if let Some(url) = image_data(repo, git_ref, base, dest_url) {
 70                    *dest_url = url.into();
 71                }
 72            }
 73            Event::Html(html) | Event::InlineHtml(html) => {
 74                *html = rewrite_html(html, repo, git_ref, base, repo_root).into();
 75            }
 76            _ => {}
 77        }
 78        event
 79    });
 80    let mut events: Vec<Event> = Vec::new();
 81    let mut html: Option<String> = None;
 82    for event in parsed {
 83        if let Event::Html(line) = &event {
 84            html.get_or_insert_default().push_str(line);
 85            continue;
 86        }
 87        events.extend(html.take().map(|block| Event::Html(block.into())));
 88        events.push(event);
 89    }
 90    events.extend(html.map(|block| Event::Html(block.into())));
 91    let (events, footnote_ids) = gather_footnotes(events);
 92    let mut ids = heading_ids(&events, footnote_ids).into_iter();
 93    let mut html_events = Vec::with_capacity(events.len());
 94    let mut heading_end: Option<String> = None;
 95    for event in events {
 96        match event {
 97            Event::Start(Tag::Heading {
 98                level,
 99                classes,
100                attrs,
101                ..
102            }) => {
103                let (id, label) = ids.next().unwrap_or_default();
104                let level = lower_level(level);
105                if id.is_empty() {
106                    html_events.push(Event::Start(Tag::Heading {
107                        level,
108                        id: None,
109                        classes,
110                        attrs,
111                    }));
112                } else {
113                    let n = level as usize;
114                    html_events.push(Event::Html(
115                        format!("<div class=\"markdown-heading\"><h{n} id=\"{id}\">").into(),
116                    ));
117                    heading_end = Some(format!("</h{n}>{}</div>\n", anchor_link(&id, &label)));
118                }
119            }
120            Event::End(TagEnd::Heading(level)) => html_events.push(match heading_end.take() {
121                Some(end) => Event::Html(end.into()),
122                None => Event::End(TagEnd::Heading(lower_level(level))),
123            }),
124            Event::Start(Tag::BlockQuote(Some(kind))) => {
125                let (name, label, icon_name) = match kind {
126                    BlockQuoteKind::Note => ("note", "Note", "info"),
127                    BlockQuoteKind::Tip => ("tip", "Tip", "light-bulb"),
128                    BlockQuoteKind::Important => ("important", "Important", "report"),
129                    BlockQuoteKind::Warning => ("warning", "Warning", "alert"),
130                    BlockQuoteKind::Caution => ("caution", "Caution", "stop"),
131                };
132                html_events.push(Event::Html(
133                    format!(
134                        "<blockquote class=\"markdown-alert markdown-alert-{name}\">\n<p class=\"markdown-alert-title\">{}{label}</p>\n",
135                        icon(icon_name)
136                    )
137                    .into(),
138                ));
139            }
140            Event::Html(html) => {
141                let lower = html.to_ascii_lowercase();
142                let mut linked = String::with_capacity(html.len());
143                let mut copied = 0;
144                for heading in raw_headings(&html) {
145                    let (id, label) = if heading.has_id {
146                        Default::default()
147                    } else {
148                        ids.next().unwrap_or_default()
149                    };
150                    let in_summary = lower[..heading.start].rfind("<summary")
151                        > lower[..heading.start].rfind("</summary");
152                    let wrap = !id.is_empty() && !in_summary;
153                    let n = (heading.level + 1).min(6);
154                    linked.push_str(&html[copied..heading.start]);
155                    if wrap {
156                        linked.push_str("<div class=\"markdown-heading\">");
157                    }
158                    linked.push_str(&format!(
159                        "<h{n}{}",
160                        &html[heading.start + 3..heading.open_end]
161                    ));
162                    if !id.is_empty() {
163                        linked.push_str(&format!(" id=\"{id}\""));
164                    }
165                    linked.push_str(&format!(
166                        ">{}</h{n}>",
167                        &html[heading.open_end + 1..heading.close]
168                    ));
169                    if !id.is_empty() {
170                        linked.push_str(&anchor_link(&id, &label));
171                    }
172                    if wrap {
173                        linked.push_str("</div>");
174                    }
175                    copied = heading.close_end;
176                }
177                linked.push_str(&html[copied..]);
178                html_events.push(Event::Html(linked.into()));
179            }
180            _ => html_events.push(event),
181        }
182    }
183    body.push_str(&format!("<div class=\"{class}\">"));
184    push_html(body, html_events.into_iter());
185    body.push_str("</div>\n");
186}
187
188fn gather_footnotes(events: Vec<Event<'_>>) -> (Vec<Event<'_>>, Vec<String>) {
189    let mut main = Vec::with_capacity(events.len());
190    let mut definitions: HashMap<String, Vec<Event>> = HashMap::new();
191    let mut referenced: Vec<(String, usize)> = Vec::new();
192    let mut definition: Option<(String, Vec<Event>)> = None;
193    for event in events {
194        let event = match event {
195            Event::Start(Tag::FootnoteDefinition(label)) => {
196                definition = Some((label.to_string(), Vec::new()));
197                continue;
198            }
199            Event::End(TagEnd::FootnoteDefinition) => {
200                if let Some((label, body)) = definition.take() {
201                    definitions.entry(label).or_insert(body);
202                }
203                continue;
204            }
205            Event::FootnoteReference(label) => {
206                let number = match referenced.iter().position(|(seen, _)| *seen == *label) {
207                    Some(i) => {
208                        referenced[i].1 += 1;
209                        i + 1
210                    }
211                    None => {
212                        referenced.push((label.to_string(), 1));
213                        referenced.len()
214                    }
215                };
216                let count = referenced[number - 1].1;
217                Event::InlineHtml(
218                    format!(
219                        "<sup class=\"footnote-reference\" id=\"{}\"><a href=\"#{}\">[{number}]</a></sup>",
220                        escape_str(&footnote_ref_id(&label, count)),
221                        percent_encode(&format!("fn-{label}"))
222                    )
223                    .into(),
224                )
225            }
226            event => event,
227        };
228        match &mut definition {
229            Some((_, body)) => body.push(event),
230            None => main.push(event),
231        }
232    }
233    let mut ids = Vec::new();
234    if referenced.is_empty() {
235        return (main, ids);
236    }
237    main.push(Event::Html("<section class=\"footnotes\">\n<ol>\n".into()));
238    for (label, count) in referenced {
239        ids.push(format!("fn-{label}"));
240        ids.extend((1..=count).map(|k| footnote_ref_id(&label, k)));
241        let mut body = definitions.remove(&label).unwrap_or_default();
242        let arrows: String = (1..=count)
243            .map(|k| {
244                let number = if k == 1 {
245                    String::new()
246                } else {
247                    format!("<sup>{k}</sup>")
248                };
249                format!(
250                    " <a href=\"#{}\" class=\"footnote-backref\">↩\u{FE0E}{number}</a>",
251                    percent_encode(&footnote_ref_id(&label, k))
252                )
253            })
254            .collect();
255        let at = if matches!(body.last(), Some(Event::End(TagEnd::Paragraph))) {
256            body.len() - 1
257        } else {
258            body.len()
259        };
260        body.insert(at, Event::InlineHtml(arrows.into()));
261        main.push(Event::Html(
262            format!("<li id=\"{}\">\n", escape_str(&format!("fn-{label}"))).into(),
263        ));
264        main.extend(body);
265        main.push(Event::Html("</li>\n".into()));
266    }
267    main.push(Event::Html("</ol>\n</section>\n".into()));
268    (main, ids)
269}
270
271fn footnote_ref_id(label: &str, k: usize) -> String {
272    if k == 1 {
273        format!("fnref-{label}")
274    } else {
275        format!("fnref-{label}-{k}")
276    }
277}
278
279fn heading_ids(events: &[Event], footnote_ids: Vec<String>) -> Vec<(String, String)> {
280    let mut used: HashSet<String> = PAGE_IDS
281        .iter()
282        .map(|id| id.to_string())
283        .chain(footnote_ids)
284        .collect();
285    let mut texts = Vec::new();
286    let mut heading: Option<String> = None;
287    for event in events {
288        match event {
289            Event::Start(Tag::Heading { .. }) => heading = Some(String::new()),
290            Event::Text(text) | Event::Code(text) => {
291                if let Some(heading) = &mut heading {
292                    heading.push_str(text);
293                }
294            }
295            Event::End(TagEnd::Heading(_)) => texts.extend(heading.take().map(|text| {
296                let label = escape_str(&text);
297                (text, label)
298            })),
299            Event::Html(html) => texts.extend(
300                raw_headings(html)
301                    .into_iter()
302                    .filter(|heading| !heading.has_id)
303                    .map(|heading| (heading.text, heading.label)),
304            ),
305            _ => {}
306        }
307    }
308    texts
309        .into_iter()
310        .map(|(text, label)| {
311            let slug: String = text
312                .to_lowercase()
313                .chars()
314                .filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_'))
315                .map(|c| if c == ' ' { '-' } else { c })
316                .collect();
317            let mut id = slug.clone();
318            let mut n = 0;
319            while !slug.is_empty() && (used.contains(&id) || numbered_page_id(&id)) {
320                n += 1;
321                id = format!("{slug}-{n}");
322            }
323            used.insert(id.clone());
324            (id, label)
325        })
326        .collect()
327}
328
329fn numbered_page_id(id: &str) -> bool {
330    NUMBERED_PAGE_IDS.iter().any(|prefix| {
331        id.strip_prefix(prefix)
332            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
333    })
334}
335
336fn is_entity(rest: &str) -> bool {
337    rest.split_once(';').is_some_and(|(name, _)| {
338        !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')
339    })
340}
341
342fn lower_level(level: HeadingLevel) -> HeadingLevel {
343    HeadingLevel::try_from(level as usize + 1).unwrap_or(HeadingLevel::H6)
344}
345
346fn raw_headings(html: &str) -> Vec<RawHeading> {
347    let lower = html.to_ascii_lowercase();
348    let bytes = lower.as_bytes();
349    let mut headings = Vec::new();
350    let mut from = 0;
351    while let Some(i) = lower[from..].find("<h") {
352        let start = from + i;
353        from = start + 2;
354        let Some(&level @ b'1'..=b'6') = bytes.get(from) else {
355            continue;
356        };
357        if !bytes
358            .get(from + 1)
359            .is_some_and(|b| *b == b'>' || b.is_ascii_whitespace())
360        {
361            continue;
362        }
363        let Some(open_end) = lower[from..].find('>').map(|i| from + i) else {
364            break;
365        };
366        let close_tag = format!("</h{}", level as char);
367        let Some(close) = lower[open_end..].find(&close_tag).map(|i| open_end + i) else {
368            break;
369        };
370        let Some(close_end) = lower[close..].find('>').map(|i| close + i + 1) else {
371            break;
372        };
373        from = close;
374        let has_id = lower[start..open_end]
375            .split_whitespace()
376            .any(|attr| attr.starts_with("id="));
377        let inner = &html[open_end + 1..close];
378        let mut label = String::new();
379        let mut in_tag = false;
380        for (at, c) in inner.char_indices() {
381            if in_tag {
382                in_tag = c != '>';
383            } else if c == '<' {
384                in_tag = true;
385            } else if c == '&' && is_entity(&inner[at + 1..]) {
386                label.push('&');
387            } else {
388                label.push_str(&escape_str(&c.to_string()));
389            }
390        }
391        let mut text = String::new();
392        let mut until = None;
393        for c in inner.chars() {
394            match until {
395                Some(end) if c == end => until = None,
396                Some(';') if !c.is_ascii_alphanumeric() && c != '#' => {
397                    until = None;
398                    text.push(c);
399                }
400                Some(_) => {}
401                None if c == '<' => until = Some('>'),
402                None if c == '&' => until = Some(';'),
403                None => text.push(c),
404            }
405        }
406        headings.push(RawHeading {
407            start,
408            level: level - b'0',
409            open_end,
410            close,
411            close_end,
412            has_id,
413            text: text.trim().to_string(),
414            label: label.trim().to_string(),
415        });
416    }
417    headings
418}
419
420fn anchor_link(id: &str, label: &str) -> String {
421    format!(
422        "<a class=\"anchor\" href=\"#{id}\" aria-label=\"{label}, link to this section\">{}</a>",
423        icon("link")
424    )
425}
426
427fn rewrite_html(
428    html: &str,
429    repo: &RepoInfo,
430    git_ref: &RefInfo,
431    base: &str,
432    repo_root: &str,
433) -> String {
434    let bytes = html.as_bytes();
435    let mut rewritten = String::with_capacity(html.len());
436    let mut copied = 0;
437    for i in 1..bytes.len() {
438        if i < copied || !bytes[i - 1].is_ascii_whitespace() {
439            continue;
440        }
441        let starts = |attr: &str| {
442            bytes[i..]
443                .get(..attr.len())
444                .is_some_and(|b| b.eq_ignore_ascii_case(attr.as_bytes()))
445        };
446        let (is_src, start) = if starts("src=") {
447            (true, i + 4)
448        } else if starts("href=") {
449            (false, i + 5)
450        } else {
451            continue;
452        };
453        let Some(&quote) = bytes.get(start).filter(|&&q| q == b'"' || q == b'\'') else {
454            continue;
455        };
456        let Some(len) = html[start + 1..].find(quote as char) else {
457            continue;
458        };
459        let value = &html[start + 1..start + 1 + len];
460        let target = if is_src {
461            image_data(repo, git_ref, base, value)
462        } else {
463            link_target(git_ref, base, repo_root, value)
464        };
465        if let Some(target) = target {
466            rewritten.push_str(&html[copied..start + 1]);
467            rewritten.push_str(&escape_str(&target));
468            copied = start + 1 + len;
469        }
470    }
471    rewritten.push_str(&html[copied..]);
472    rewritten
473}
474
475fn link_target(git_ref: &RefInfo, base: &str, repo_root: &str, url: &str) -> Option<String> {
476    let path = repo_path(base, url.split(['?', '#']).next()?)?;
477    let fragment = url
478        .split_once('#')
479        .map(|(_, fragment)| format!("#{fragment}"))
480        .unwrap_or_default();
481    Some(format!(
482        "{}{fragment}",
483        path_href(git_ref, repo_root, &path)?
484    ))
485}
486
487fn image_data(repo: &RepoInfo, git_ref: &RefInfo, base: &str, url: &str) -> Option<String> {
488    let path = repo_path(base, url.split(['?', '#']).next()?)?;
489    let path = follow_links(git_ref, &path)?;
490    let mime = image_type(&path)?;
491    let blob = repo.git.find_blob(find_file(git_ref, &path)?.blob?).ok()?;
492    Some(data_uri(mime, blob.content()))
493}
494
495fn repo_path(base: &str, url: &str) -> Option<String> {
496    if url.is_empty() || url.starts_with("//") || url.split('/').next()?.contains(':') {
497        return None;
498    }
499    let url = percent_decode(url)?;
500    resolve_path(if url.starts_with('/') { "" } else { base }, &url)
501}
502
503fn percent_decode(s: &str) -> Option<String> {
504    let mut bytes = Vec::with_capacity(s.len());
505    let mut i = 0;
506    while i < s.len() {
507        let hex = s
508            .get(i + 1..i + 3)
509            .filter(|hex| s.as_bytes()[i] == b'%' && hex.bytes().all(|b| b.is_ascii_hexdigit()));
510        match hex.and_then(|hex| u8::from_str_radix(hex, 16).ok()) {
511            Some(byte) => {
512                bytes.push(byte);
513                i += 3;
514            }
515            None => {
516                bytes.push(s.as_bytes()[i]);
517                i += 1;
518            }
519        }
520    }
521    String::from_utf8(bytes).ok()
522}