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