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