//! Syntax highlighting and Markdown rendering for the web browser. //! //! Highlighting emits syntect scope classes (`hl-keyword`, `hl-string`, ...) rather than //! inline styles, so the page's `style-src 'self'` policy holds; the site stylesheet colours them. use std::sync::LazyLock; use std::time::{Duration, Instant}; use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd}; use syntect::html::{ClassStyle, ClassedHTMLGenerator}; use syntect::parsing::{SyntaxReference, SyntaxSet}; use syntect::util::LinesWithEndings; /// Files larger than this are shown as plain escaped text. pub const HIGHLIGHT_LIMIT: usize = 512 << 10; /// The most time one file or code block may spend being highlighted. const HIGHLIGHT_BUDGET: Duration = Duration::from_secs(2); const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" }; static SYNTAXES: LazyLock = LazyLock::new(SyntaxSet::load_defaults_newlines); /// Load the syntax definitions ahead of the first request. pub fn warm_up() { LazyLock::force(&SYNTAXES); } /// The syntax for a file, by extension, whole file name, then shebang or modeline. fn syntax_for(path: &str, first_line: &str) -> Option<&'static SyntaxReference> { let file = path.rsplit('/').next().unwrap_or(path); let ext = file.rsplit_once('.').map_or(file, |(_, ext)| ext); SYNTAXES .find_syntax_by_extension(ext) .or_else(|| SYNTAXES.find_syntax_by_extension(file)) .or_else(|| SYNTAXES.find_syntax_by_first_line(first_line)) } /// The syntax named by a Markdown fence such as ```rust or ```py. fn syntax_for_fence(lang: &str) -> Option<&'static SyntaxReference> { let lang = lang.split([',', ' ', '{']).next().unwrap_or("").trim(); if lang.is_empty() { return None; } SYNTAXES.find_syntax_by_token(lang) } fn highlight_with(code: &str, syntax: Option<&'static SyntaxReference>) -> String { highlight_within(code, syntax, HIGHLIGHT_BUDGET) } /// Highlight, or give up and show plain text once `budget` is spent. Some grammars are slow on /// some input, and nothing else bounds this work: it runs outside git's deadlines and holds a /// render slot until it ends. fn highlight_within(code: &str, syntax: Option<&'static SyntaxReference>, budget: Duration) -> String { let plain = || html_escape::encode_text(code).into_owned(); let Some(syntax) = syntax.filter(|_| code.len() <= HIGHLIGHT_LIMIT) else { return plain() }; let deadline = Instant::now() + budget; let mut generator = ClassedHTMLGenerator::new_with_class_style(syntax, &SYNTAXES, CLASSES); for line in LinesWithEndings::from(code) { if Instant::now() >= deadline || generator.parse_html_for_line_which_includes_newline(line).is_err() { return plain(); } } generator.finalize() } /// A file's contents as highlighted HTML, ready to go inside `
`.
pub fn highlight(path: &str, code: &str) -> String {
    highlight_with(code, syntax_for(path, code.lines().next().unwrap_or("")))
}

/// True for files the browser renders as Markdown by default.
pub fn is_markdown(path: &str) -> bool {
    let lower = path.to_ascii_lowercase();
    [".md", ".markdown", ".mdown", ".mkd"].iter().any(|ext| lower.ends_with(ext))
}

/// Where a link or image in a Markdown file points.
pub enum Target {
    /// Kept as written: web, mail and in-page links.
    External(String),
    /// A repository path as bytes, decoded once and normalised against the file's directory.
    Repo(Vec),
    /// Anything else (other schemes, paths escaping the repository): dropped.
    Blocked,
}

/// Resolve a link written in a Markdown file that lives in `dir` (bytes, as git stores it).
/// Each path segment is percent-decoded once, so `My%20File.md` names `My File.md`; a segment
/// that decodes to something no file name can hold (a `/` or NUL) is dropped.
pub fn resolve_link(dir: &[u8], target: &str) -> Target {
    let lower = target.to_ascii_lowercase();
    if lower.starts_with("http://")
        || lower.starts_with("https://")
        || lower.starts_with("mailto:")
        || target.starts_with('#')
    {
        return Target::External(target.to_string());
    }
    let path = target.split(['#', '?']).next().unwrap_or("");
    // A colon before any slash means a scheme (javascript:, data:, ...).
    if path.split('/').next().is_some_and(|first| first.contains(':')) {
        return Target::Blocked;
    }
    let mut parts: Vec> = if path.starts_with('/') {
        Vec::new()
    } else {
        dir.split(|b| *b == b'/').filter(|p| !p.is_empty()).map(<[u8]>::to_vec).collect()
    };
    for raw in path.split('/') {
        let part = gitv_core::percent_decode(raw);
        match part.as_slice() {
            b"" | b"." => {}
            b".." => {
                if parts.pop().is_none() {
                    return Target::Blocked;
                }
            }
            part if part.contains(&b'/') || part.contains(&0) => return Target::Blocked,
            _ => parts.push(part),
        }
    }
    Target::Repo(parts.join(&b'/'))
}

/// Render Markdown to HTML. Raw HTML in the source is escaped, fenced code is highlighted, and
/// `link(path, is_image)` turns repository paths into URLs.
pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String) -> String {
    // Heading attributes stay off: `# Title {onclick=… #main}` would let a file set any
    // attribute, id or class on the page.
    let options =
        Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
    let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> {
        match resolve_link(dir, &dest) {
            Target::External(url) if url.starts_with('#') => format!("#md-{}", &url[1..]).into(),
            Target::External(url) => url.into(),
            Target::Repo(path) => {
                let mut url = link(&path, image);
                if let Some((_, fragment)) = dest.split_once('#') {
                    url.push('#');
                    if !image && is_markdown(&String::from_utf8_lossy(&path)) {
                        url.push_str("md-");
                    }
                    url.push_str(fragment);
                }
                url.into()
            }
            Target::Blocked => "#".into(),
        }
    };
    let mut events = Vec::new();
    let mut fence: Option<(Option<&'static SyntaxReference>, String)> = None;
    for event in Parser::new_ext(source, options) {
        if let Some((_, code)) = fence.as_mut() {
            match event {
                Event::Text(text) => code.push_str(&text),
                Event::End(TagEnd::CodeBlock) => {
                    let (syntax, code) = fence.take().unwrap_or_default();
                    events.push(Event::Html(
                        format!("
{}
\n", highlight_with(&code, syntax)).into(), )); } _ => {} } continue; } events.push(match event { Event::Start(Tag::CodeBlock(kind)) => { let syntax = match kind { CodeBlockKind::Fenced(lang) => syntax_for_fence(&lang), CodeBlockKind::Indented => None, }; fence = Some((syntax, String::new())); continue; } // Never pass the file's own HTML through: show it as text instead. Event::Html(raw) | Event::InlineHtml(raw) => Event::Text(raw), Event::Start(Tag::Link { link_type, dest_url, title, id }) => { Event::Start(Tag::Link { link_type, dest_url: rewrite(dest_url, false), title, id }) } Event::Start(Tag::Image { link_type, dest_url, title, id }) => { Event::Start(Tag::Image { link_type, dest_url: rewrite(dest_url, true), title, id }) } other => other, }); } // Derive anchors from visible heading text. Prefix them so document headings cannot // shadow page navigation. Duplicate headings get stable suffixes. let mut used = std::collections::HashSet::new(); let mut suffixes = std::collections::HashMap::new(); let mut heading = None; for index in 0..events.len() { match &events[index] { Event::Start(Tag::Heading { .. }) => heading = Some((index, String::new())), Event::Text(text) | Event::Code(text) => { if let Some((_, title)) = &mut heading { title.push_str(text); } } Event::End(TagEnd::Heading(_)) => { if let Some((start, title)) = heading.take() { let base: String = title .to_lowercase() .chars() .filter_map(|c| { if c.is_whitespace() { Some('-') } else if c.is_alphanumeric() || matches!(c, '-' | '_') { Some(c) } else { None } }) .collect(); let base = format!("md-{base}"); let mut id = base.clone(); let suffix = suffixes.entry(base.clone()).or_insert(0usize); while !used.insert(id.clone()) { *suffix += 1; id = format!("{base}-{suffix}"); } if let Event::Start(Tag::Heading { id: target, .. }) = &mut events[start] { *target = Some(id.into()); } } } _ => {} } } let mut out = String::new(); pulldown_cmark::html::push_html(&mut out, events.into_iter()); out } #[cfg(test)] mod tests { use super::*; fn link(path: &[u8], image: bool) -> String { format!("/{}?path={}", if image { "raw" } else { "blob" }, String::from_utf8_lossy(path)) } #[test] fn escapes_raw_html() { let html = markdown("hi \n\n
", b"", &link); assert!(!html.contains("Title {onclick=alert(1) #main .skip style=x}")); assert!(!html.contains(" onclick=")); } #[test] fn blocks_dangerous_links() { let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", b"docs", &link); assert!(!html.contains("javascript:"), "{html}"); assert!(!html.contains("passwd"), "{html}"); } #[test] fn rewrites_relative_links_and_images() { let html = markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", b"docs", &link); assert!(html.contains("href=\"/blob?path=docs/guide.md#md-top\""), "{html}"); assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}"); assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}"); assert!(html.contains("href=\"https://x.dev\""), "{html}"); } #[test] fn link_destinations_are_decoded_once() { let repo = |dir: &[u8], target: &str| match resolve_link(dir, target) { Target::Repo(path) => Some(path), _ => None, }; assert_eq!(repo(b"docs", "My%20File.md"), Some(b"docs/My File.md".to_vec())); assert_eq!(repo(b"docs", "a+b.md"), Some(b"docs/a+b.md".to_vec()), "a plus is a plus"); assert_eq!(repo(b"docs", "100%25.md"), Some(b"docs/100%.md".to_vec())); assert_eq!(repo(b"caf\xe9", "x.md"), Some(b"caf\xe9/x.md".to_vec()), "the folder keeps its bytes"); assert_eq!(repo(b"a/b", "%2E%2E/c"), Some(b"a/c".to_vec()), "an encoded .. is still .."); assert_eq!(repo(b"", "a%2Fb"), None, "no file name contains a slash"); assert_eq!(repo(b"", "a%00b"), None); } #[test] fn highlighting_past_its_budget_falls_back_to_plain_text() { let syntax = syntax_for("x.rs", ""); assert!(highlight_within("fn main() {}\n", syntax, Duration::from_secs(60)).contains("hl-")); assert_eq!(highlight_within("fn \n", syntax, Duration::ZERO), "fn <b>\n"); } #[test] fn highlights_fenced_code_and_files() { let html = markdown("```rust\nfn main() {}\n```", b"", &link); assert!(html.contains("
") && html.contains("hl-"), "{html}");
        assert!(highlight("x.py", "def f(): pass\n").contains("hl-"));
        assert!(highlight("run", "#!/bin/sh\necho hi\n").contains("hl-"));
        assert_eq!(highlight("notes.unknownext", ""), "<b>");
    }
}