Skip to main content

mdo_cli/
render.rs

1//! Render pipeline: the path from Markdown source to an HTML fragment -
2//! parsing, syntax-highlight splicing, sanitizing, title derivation, in
3//! that order, sanitized once, after splicing - plus the single deep
4//! workflow entry point (convert) that reads the source, renders, and
5//! writes the page with per-worker private-output safeguards.
6
7use std::collections::BTreeSet;
8use std::fmt;
9use std::fs;
10use std::io;
11#[cfg(unix)]
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::time::{Duration, Instant};
15
16#[cfg(unix)]
17use std::fs::OpenOptions;
18#[cfg(unix)]
19use std::os::unix::fs::OpenOptionsExt;
20
21use pulldown_cmark::Options;
22use url::Url;
23
24use crate::highlight;
25use crate::page::{source_modified_unix_secs, wrap_html5};
26
27/// Build a `file://` URL for a directory, suitable for use as `<base href>`.
28///
29/// Delegates to [`Url::from_directory_path`], which correctly
30/// percent-encodes reserved and non-ASCII characters (spaces, `#`, `%`, `?`,
31/// Unicode, …) and handles Windows drive letters, UNC paths, and the
32/// `\\?\`/`\\?\UNC\` extended-length prefixes that `fs::canonicalize`
33/// produces — a hand-rolled string transform got all of this subtly wrong
34/// (e.g. a literal `#` in a directory name would truncate the URL when a
35/// browser parsed it as a fragment). Always includes a trailing slash so
36/// relative refs resolve correctly against the directory.
37///
38/// Returns `None` if `dir` can't be represented as a `file://` URL (notably:
39/// relative paths). Callers should fall back to omitting the `<base href>`
40/// tag entirely rather than emit a broken URL.
41fn dir_to_file_url(dir: &Path) -> Option<String> {
42    Url::from_directory_path(dir)
43        .ok()
44        .map(|url| url.to_string())
45}
46
47fn markdown_options() -> Options {
48    let mut options = Options::empty();
49    options.insert(Options::ENABLE_STRIKETHROUGH);
50    options.insert(Options::ENABLE_TABLES);
51    options.insert(Options::ENABLE_FOOTNOTES);
52    options.insert(Options::ENABLE_TASKLISTS);
53    options.insert(Options::ENABLE_GFM);
54
55    options
56}
57
58fn markdown_to_html(
59    markdown: &str,
60    placeholder_discriminator: u64,
61    plain_fences: &BTreeSet<usize>,
62) -> highlight::RenderedMarkdown {
63    // Front matter is stripped here, before parsing, by the same
64    // `yaml_front_matter` splitter that title derivation uses, so one set of
65    // acceptance rules governs both. Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
66    // is deliberately NOT enabled: pulldown-cmark 0.13 recognizes metadata
67    // blocks anywhere at indent 0, not just at document start, which silently
68    // swallows mid-document text framed by `---` lines.
69    let markdown = yaml_front_matter(markdown)
70        .map(|(_, body)| body)
71        .unwrap_or(markdown);
72
73    highlight::render(
74        markdown,
75        markdown_options(),
76        placeholder_discriminator,
77        plain_fences,
78    )
79}
80
81/// Upper bound on placeholder-collision retries. A collision requires
82/// document text that normalizes into the current placeholder token, so more
83/// than a couple of retries only happens with adversarial input; past the cap
84/// the document renders with highlighting disabled rather than looping.
85const MAX_PLACEHOLDER_RETRIES: u32 = 16;
86
87/// Shared render/process/splice loop behind [`safe_markdown_body`] and
88/// [`convert`].
89///
90/// Highlighted spans are generated by mdo from escaped code text and spliced
91/// into the raw renderer output only after all placeholders have been
92/// validated. `process` (usually ammonia) then handles the completed document,
93/// including generated markup, so no string insertion happens beyond the
94/// sanitizer boundary. The loop is guaranteed to terminate:
95///
96/// - a destroyed placeholder can never survive under any discriminator, so
97///   its fence is added to the strictly growing `plain_fences` set and
98///   rendered as an ordinary escaped code block instead;
99/// - collisions retry with a fresh discriminator at most
100///   [`MAX_PLACEHOLDER_RETRIES`] times, after which every fence is rendered
101///   plain, leaving nothing to splice.
102fn spliced_markdown_body(
103    markdown: &str,
104    mut render: impl FnMut(&str, u64, &BTreeSet<usize>) -> highlight::RenderedMarkdown,
105    mut process: impl FnMut(&str) -> String,
106) -> (String, Option<&'static str>) {
107    let mut discriminator = 0_u64;
108    let mut collision_retries = 0_u32;
109    let mut plain_fences = BTreeSet::new();
110
111    loop {
112        let rendered = render(markdown, discriminator, &plain_fences);
113        match rendered.finish(rendered.raw_html().to_string()) {
114            Ok(body) => return (process(&body), rendered.css()),
115            Err(highlight::SpliceError::Destroyed(fences)) => {
116                plain_fences.extend(fences);
117            }
118            Err(highlight::SpliceError::Collision) => {
119                collision_retries += 1;
120                if collision_retries > MAX_PLACEHOLDER_RETRIES {
121                    plain_fences.extend(0..rendered.fence_count());
122                }
123                discriminator += 1;
124            }
125        }
126    }
127}
128
129/// Render and sanitize Markdown, splicing generated highlighting before the
130/// completed document crosses the sanitizer boundary.
131fn safe_markdown_body(markdown: &str) -> (String, Option<&'static str>) {
132    spliced_markdown_body(markdown, markdown_to_html, sanitize_html)
133}
134
135fn sanitize_html(html: &str) -> String {
136    ammonia::Builder::default()
137        // The global "class" allowance is intentional: user-authored class
138        // names are inert here because classes only select styles from mdo's
139        // own generated stylesheet. Highlight safety does not rest on this
140        // allowlist either: highlighted markup is generated from escaped code
141        // text, spliced before sanitization, and then cleaned with the rest of
142        // the document.
143        .add_generic_attributes(&["class", "id"])
144        .add_tags(&["input"])
145        .add_tag_attributes("input", &["checked", "type"])
146        .add_tag_attribute_values("input", "checked", &[""])
147        .add_tag_attribute_values("input", "type", &["checkbox"])
148        .set_tag_attribute_value("input", "disabled", "")
149        .clean(html)
150        .to_string()
151}
152
153/// Render Markdown supplied in memory as a complete, self-contained HTML page.
154///
155/// This is the platform-neutral entry point used by the Android application.
156/// Raw HTML is always sanitized, matching the safe default of the desktop CLI.
157/// `fallback_title` is used only when the document has no top-level heading.
158pub fn render_markdown_document(
159    markdown: &str,
160    fallback_title: &str,
161    source_modified_unix_secs: Option<u64>,
162) -> String {
163    let (body, highlight_css) = safe_markdown_body(markdown);
164    let title = derive_title(markdown, fallback_title);
165    wrap_html5(
166        &body,
167        &title,
168        None,
169        None,
170        highlight_css,
171        source_modified_unix_secs,
172    )
173}
174
175fn derive_title(markdown: &str, fallback: &str) -> String {
176    if let Some(title) = front_matter_title(markdown) {
177        return title;
178    }
179
180    // A valid metadata block is not document content. Exclude it from the
181    // existing H1 search even when it has no usable title key.
182    let markdown = yaml_front_matter(markdown)
183        .map(|(_, document)| document)
184        .unwrap_or(markdown);
185
186    // Strip fenced code blocks first so a heading — whether an ATX `# ` line or
187    // a raw <h1> — inside a ``` or ~~~ block is never mistaken for the title.
188    let without_fences = strip_code_fences(markdown);
189    for line in without_fences.lines() {
190        let trimmed = line.trim_start();
191        if let Some(rest) = trimmed.trim_end().strip_prefix("# ") {
192            return rest.trim().to_string();
193        }
194    }
195    if let Some(title) = derive_raw_html_h1_title(&without_fences) {
196        return title;
197    }
198    fallback.to_string()
199}
200
201/// Extract a simple scalar `title:` from a complete YAML-style metadata block
202/// at the start of the document.
203///
204/// pulldown-cmark deliberately recognizes the block delimiters without
205/// interpreting YAML. mdo follows that narrow behavior: it reads only an
206/// unindented `title` key and does not add a general-purpose YAML parser (and
207/// its dependency/security surface) merely to title the generated page.
208fn front_matter_title(markdown: &str) -> Option<String> {
209    let (metadata, _) = yaml_front_matter(markdown)?;
210    let mut title = None;
211    for line in metadata.lines() {
212        if line.starts_with(char::is_whitespace) {
213            continue;
214        }
215        if let Some((key, value)) = line.split_once(':') {
216            if key == "title" {
217                let value = unquote_front_matter_scalar(value.trim());
218                if !value.is_empty() {
219                    title = Some(value.to_string());
220                }
221            }
222        }
223    }
224
225    title
226}
227
228/// Split a complete YAML-style metadata block from the document body. The
229/// returned metadata excludes delimiters.
230///
231/// This splitter is the single source of truth for front-matter recognition
232/// (both hiding the block from rendered output and title extraction), and its
233/// acceptance rules are deliberately conservative and GitHub-like:
234///
235/// - the opening `---` must be the very first line of the document;
236/// - the closing delimiter is `---` or `...` on its own line — trailing
237///   spaces are allowed but tabs are not;
238/// - the block must be non-empty and its first line must not be blank.
239///   GitHub and pulldown-cmark both reject blocks whose first content line is
240///   blank, so treating them as front matter here would hide visible content
241///   and let e.g. `---\n\ntitle: fake\n---` spoof the page title.
242fn yaml_front_matter(markdown: &str) -> Option<(&str, &str)> {
243    fn delimiter(line: &str) -> Option<&str> {
244        let line = line.trim_end_matches(['\r', '\n']).trim_end_matches(' ');
245        (line == "---" || line == "...").then_some(line)
246    }
247
248    let first_line_end = markdown.find('\n').unwrap_or(markdown.len());
249    if delimiter(&markdown[..first_line_end]) != Some("---") || first_line_end == markdown.len() {
250        return None;
251    }
252
253    let metadata_start = first_line_end + 1;
254    let remainder = &markdown[metadata_start..];
255    let mut consumed = 0;
256    // split_inclusive also yields a final segment without a trailing newline,
257    // so a closing delimiter at end-of-input is found by the loop as well.
258    for segment in remainder.split_inclusive('\n') {
259        if delimiter(segment).is_some() {
260            let metadata = &remainder[..consumed];
261            let first_content_line = metadata.lines().next()?;
262            if first_content_line.trim().is_empty() {
263                return None;
264            }
265            return Some((metadata, &remainder[consumed + segment.len()..]));
266        }
267        consumed += segment.len();
268    }
269
270    None
271}
272
273fn unquote_front_matter_scalar(value: &str) -> &str {
274    if value.len() < 2 {
275        return value;
276    }
277
278    let bytes = value.as_bytes();
279    if matches!(
280        (bytes[0], bytes[value.len() - 1]),
281        (b'\'', b'\'') | (b'"', b'"')
282    ) {
283        &value[1..value.len() - 1]
284    } else {
285        value
286    }
287}
288
289/// Return `markdown` with fenced code blocks (``` or ~~~) removed, so title
290/// detection never reads inside code samples.
291fn strip_code_fences(markdown: &str) -> String {
292    let mut out = String::with_capacity(markdown.len());
293    let mut fence: Option<char> = None;
294    for line in markdown.lines() {
295        if let Some(marker) = code_fence_marker(line.trim_start()) {
296            match fence {
297                Some(open) if open == marker => fence = None,
298                Some(_) => {}
299                None => fence = Some(marker),
300            }
301            continue;
302        }
303        if fence.is_some() {
304            continue;
305        }
306        out.push_str(line);
307        out.push('\n');
308    }
309    out
310}
311
312/// Detect a code-fence line, returning its marker char when the line starts
313/// with at least three backticks or tildes. This is a pragmatic subset of
314/// CommonMark (it does not bound the indent or require the closing fence to be
315/// at least as long), which is sufficient for title detection.
316fn code_fence_marker(trimmed_start: &str) -> Option<char> {
317    if trimmed_start.starts_with("```") {
318        Some('`')
319    } else if trimmed_start.starts_with("~~~") {
320        Some('~')
321    } else {
322        None
323    }
324}
325
326fn derive_raw_html_h1_title(markdown: &str) -> Option<String> {
327    let lower = markdown.to_ascii_lowercase();
328    let mut search_start = 0;
329
330    while let Some(offset) = lower[search_start..].find("<h1") {
331        let start = search_start + offset;
332        let after_tag_name = start + 3;
333        let next = lower.as_bytes().get(after_tag_name).copied();
334        if !matches!(
335            next,
336            Some(b'>') | Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')
337        ) {
338            search_start = after_tag_name;
339            continue;
340        }
341
342        let content_start = start + markdown[start..].find('>')? + 1;
343        let content_end = content_start + lower[content_start..].find("</h1>")?;
344        let title = strip_html_tags(&markdown[content_start..content_end])
345            .split_whitespace()
346            .collect::<Vec<_>>()
347            .join(" ");
348        if !title.is_empty() {
349            return Some(title);
350        }
351
352        search_start = content_end + 5;
353    }
354
355    None
356}
357
358fn strip_html_tags(input: &str) -> String {
359    let mut output = String::with_capacity(input.len());
360    let mut in_tag = false;
361
362    for ch in input.chars() {
363        match ch {
364            '<' => in_tag = true,
365            '>' if in_tag => in_tag = false,
366            _ if !in_tag => output.push(ch),
367            _ => {}
368        }
369    }
370
371    output
372}
373
374/// Wall-clock time spent in each stage of one render workflow, plus the
375/// workflow's total. Reported to stderr by the CLI's `--verbose` output.
376/// Stages that do not run for a given invocation (`sanitize` under
377/// `--unsafe-html`, `assemble` under `--bare`) report zero.
378#[derive(Debug, Default)]
379pub struct StageTimings {
380    pub read: Duration,
381    pub markdown: Duration,
382    pub sanitize: Duration,
383    pub assemble: Duration,
384    pub write: Duration,
385    /// Wall-clock time of the whole workflow, always at least the sum of
386    /// the stages.
387    pub total: Duration,
388}
389
390/// One render request for [`convert`]: a Markdown input, a destination, and
391/// the render options. `verbose` is deliberately absent — diagnostics are
392/// the caller's presentation concern, and [`ConvertOutcome::timings`]
393/// carries everything a caller needs to print them.
394#[derive(Debug)]
395pub struct ConvertRequest<'a> {
396    /// The Markdown source file.
397    pub input: &'a Path,
398    /// The HTML file to write; created when missing, overwritten when
399    /// present.
400    pub output: &'a Path,
401    /// Emit only the HTML fragment (no `<html>`, `<head>`, `<body>`, no CSS).
402    pub bare: bool,
403    /// Preserve raw HTML from the Markdown source instead of sanitizing it.
404    pub unsafe_html: bool,
405    /// Write the output file readable only by the current user.
406    pub private_output: bool,
407    /// Custom CSS appended after mdo's default styling. Read from disk here
408    /// and ignored under `bare`, because bare output emits no CSS.
409    pub css_override: Option<&'a Path>,
410}
411
412/// What a successful [`convert`] wrote: the output file plus the workflow's
413/// stage-by-stage timing record.
414#[derive(Debug)]
415pub struct ConvertOutcome {
416    /// The output file that was written.
417    pub output: PathBuf,
418    /// Wall-clock timing record for the completed workflow.
419    pub timings: StageTimings,
420}
421
422/// Why a [`convert`] workflow failed, typed per failure site with the
423/// underlying `io::Error` and the path it concerns, so callers keep printing
424/// their own messages instead of the library doing it for them.
425#[derive(Debug)]
426pub enum RenderError {
427    /// Reading the Markdown input file failed.
428    Read { path: PathBuf, source: io::Error },
429    /// Reading the `--css` override file failed.
430    ReadCssOverride { path: PathBuf, source: io::Error },
431    /// Creating the output file's parent directory failed.
432    CreateOutputDir { path: PathBuf, source: io::Error },
433    /// Writing the rendered HTML file failed.
434    Write { path: PathBuf, source: io::Error },
435}
436
437impl fmt::Display for RenderError {
438    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439        let (action, path, source) = match self {
440            RenderError::Read { path, source } => ("failed to read", path, source),
441            RenderError::ReadCssOverride { path, source } => {
442                ("failed to read CSS override", path, source)
443            }
444            RenderError::CreateOutputDir { path, source } => ("failed to create", path, source),
445            RenderError::Write { path, source } => ("failed to write", path, source),
446        };
447        write!(f, "{} {}: {}", action, path.display(), source)
448    }
449}
450
451impl std::error::Error for RenderError {
452    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
453        Some(match self {
454            RenderError::Read { source, .. }
455            | RenderError::ReadCssOverride { source, .. }
456            | RenderError::CreateOutputDir { source, .. }
457            | RenderError::Write { source, .. } => source,
458        })
459    }
460}
461
462/// Render one Markdown file to HTML: the render pipeline's single deep
463/// entry point.
464///
465/// The workflow: read the source (and any CSS override), render and splice
466/// highlighting, sanitize (unless `unsafe_html`), assemble the page (unless
467/// `bare`), create the output's parent directory when missing, then write
468/// the file (O_NOFOLLOW, mode 0o600 under `private_output`). The workflow
469/// prints nothing itself — success carries a [`ConvertOutcome`] with the
470/// written file and timing record, failure a typed [`RenderError`] — so the
471/// same workflow serves the CLI, the setup sample, and any other host, and
472/// the generated HTML is byte-identical everywhere it is invoked from.
473pub fn convert(request: ConvertRequest) -> Result<ConvertOutcome, RenderError> {
474    let workflow_start = Instant::now();
475    let mut timings = StageTimings::default();
476
477    let stage_start = Instant::now();
478    let markdown = fs::read_to_string(request.input).map_err(|source| RenderError::Read {
479        path: request.input.to_path_buf(),
480        source,
481    })?;
482    timings.read = stage_start.elapsed();
483
484    let css_override = if request.bare {
485        None
486    } else {
487        match request.css_override {
488            Some(path) => {
489                let stage_start = Instant::now();
490                let css =
491                    fs::read_to_string(path).map_err(|source| RenderError::ReadCssOverride {
492                        path: path.to_path_buf(),
493                        source,
494                    })?;
495                timings.read += stage_start.elapsed();
496                Some(css)
497            }
498            None => None,
499        }
500    };
501
502    // Same splice loop as `safe_markdown_body`, instrumented for the
503    // outcome's timing record.
504    let (body, highlight_css) = spliced_markdown_body(
505        &markdown,
506        |markdown, discriminator, plain_fences| {
507            let stage_start = Instant::now();
508            let rendered = markdown_to_html(markdown, discriminator, plain_fences);
509            timings.markdown += stage_start.elapsed();
510            rendered
511        },
512        |html| {
513            if request.unsafe_html {
514                html.to_string()
515            } else {
516                let sanitize_start = Instant::now();
517                let sanitized = sanitize_html(html);
518                timings.sanitize += sanitize_start.elapsed();
519                sanitized
520            }
521        },
522    );
523
524    let final_html = if request.bare {
525        body
526    } else {
527        let stage_start = Instant::now();
528        let fallback = request
529            .input
530            .file_stem()
531            .and_then(|s| s.to_str())
532            .unwrap_or("Document");
533        let title = derive_title(&markdown, fallback);
534
535        // Only inject <base href> when the output lives in a different
536        // directory from the source — otherwise relative refs already
537        // resolve correctly and a base tag would just add noise.
538        let base_href = match (
539            fs::canonicalize(request.input)
540                .ok()
541                .and_then(|p| p.parent().map(Path::to_path_buf)),
542            request
543                .output
544                .parent()
545                .and_then(|p| fs::canonicalize(p).ok()),
546        ) {
547            (Some(in_dir), Some(out_dir)) if in_dir != out_dir => dir_to_file_url(&in_dir),
548            _ => None,
549        };
550
551        let wrapped = wrap_html5(
552            &body,
553            &title,
554            base_href.as_deref(),
555            css_override.as_deref(),
556            highlight_css,
557            source_modified_unix_secs(request.input),
558        );
559        timings.assemble = stage_start.elapsed();
560        wrapped
561    };
562
563    let stage_start = Instant::now();
564    if let Some(parent) = request.output.parent() {
565        if !parent.as_os_str().is_empty() {
566            fs::create_dir_all(parent).map_err(|source| RenderError::CreateOutputDir {
567                path: parent.to_path_buf(),
568                source,
569            })?;
570        }
571    }
572
573    write_output_file(request.output, &final_html, request.private_output).map_err(|source| {
574        RenderError::Write {
575            path: request.output.to_path_buf(),
576            source,
577        }
578    })?;
579    timings.write = stage_start.elapsed();
580    timings.total = workflow_start.elapsed();
581
582    Ok(ConvertOutcome {
583        output: request.output.to_path_buf(),
584        timings,
585    })
586}
587
588#[cfg(unix)]
589fn write_output_file(output: &Path, contents: &str, private_output: bool) -> io::Result<()> {
590    let mut options = OpenOptions::new();
591    options
592        .write(true)
593        .create(true)
594        .truncate(true)
595        .custom_flags(libc::O_NOFOLLOW);
596
597    if private_output {
598        options.mode(0o600);
599    }
600
601    let mut file = options.open(output)?;
602    file.write_all(contents.as_bytes())
603}
604
605#[cfg(not(unix))]
606fn write_output_file(output: &Path, contents: &str, _private_output: bool) -> io::Result<()> {
607    fs::write(output, contents)
608}
609#[cfg(test)]
610mod tests {
611    use super::*;
612    use std::collections::BTreeSet;
613
614    fn rendered_markdown_html(markdown: &str) -> String {
615        let rendered = markdown_to_html(markdown, 0, &BTreeSet::new());
616        rendered
617            .finish(rendered.raw_html().to_string())
618            .expect("unsanitized renderer should preserve its unique placeholders")
619    }
620
621    #[test]
622    fn in_memory_render_uses_shared_safe_document_pipeline() {
623        let html = render_markdown_document(
624            "# Phone note\n\nHello **Android**.\n\n<script>alert('no')</script>",
625            "fallback.md",
626            None,
627        );
628
629        assert!(html.contains("<title>Phone note</title>"));
630        assert!(html.contains("<strong>Android</strong>"));
631        assert!(html.contains("<meta name=\"generator\" content=\"mdo "));
632        assert!(!html.contains("<script>alert('no')</script>"));
633    }
634
635    #[test]
636    fn markdown_extensions_keep_their_existing_html() {
637        let markdown = "~~gone~~\n\n\
638                        | A | B |\n\
639                        | - | - |\n\
640                        | 1 | 2 |\n\n\
641                        Footnote[^one].\n\n\
642                        [^one]: Detail\n\n\
643                        - [x] done\n\
644                        - [ ] later\n";
645        let expected = "<p><del>gone</del></p>\n\
646                        <table><thead><tr><th>A</th><th>B</th></tr></thead><tbody>\n\
647                        <tr><td>1</td><td>2</td></tr>\n\
648                        </tbody></table>\n\
649                        <p>Footnote<sup class=\"footnote-reference\"><a href=\"#one\">1</a></sup>.</p>\n\
650                        <div class=\"footnote-definition\" id=\"one\"><sup class=\"footnote-definition-label\">1</sup>\n\
651                        <p>Detail</p>\n\
652                        </div>\n\
653                        <ul>\n\
654                        <li><input disabled=\"\" type=\"checkbox\" checked=\"\"/>\n\
655                        done</li>\n\
656                        <li><input disabled=\"\" type=\"checkbox\"/>\n\
657                        later</li>\n\
658                        </ul>\n";
659
660        assert_eq!(rendered_markdown_html(markdown), expected);
661    }
662
663    #[test]
664    fn gfm_alerts_render_all_supported_classes_and_survive_sanitizing() {
665        for kind in ["note", "tip", "important", "warning", "caution"] {
666            let markdown = format!("> [!{}]\n> Alert text\n", kind.to_uppercase());
667            let raw = rendered_markdown_html(&markdown);
668            let class = format!("class=\"markdown-alert-{kind}\"");
669
670            assert!(raw.contains(&class), "{raw}");
671            assert!(!raw.contains("[!"), "{raw}");
672            assert!(sanitize_html(&raw).contains(&class), "{raw}");
673        }
674    }
675
676    #[test]
677    fn yaml_front_matter_is_hidden_and_supplies_document_title() {
678        let markdown =
679            "---\ntitle: 'Front Matter Title'\nauthor: Example\n...\n\n# Heading Title\n";
680        let body = rendered_markdown_html(markdown);
681
682        assert_eq!(body, "<h1>Heading Title</h1>\n");
683        assert_eq!(derive_title(markdown, "fallback"), "Front Matter Title");
684
685        let document = render_markdown_document(markdown, "fallback", None);
686        assert!(document.contains("<title>Front Matter Title</title>"));
687        assert!(!document.contains("author: Example"));
688    }
689
690    #[test]
691    fn mid_document_metadata_style_blocks_are_rendered_not_swallowed() {
692        let markdown = "# Top\n\nintro\n\n---\nnot a heading\n---\n\ntail\n";
693        let html = rendered_markdown_html(markdown);
694
695        assert!(html.contains("not a heading"), "{html}");
696        assert!(html.contains("tail"), "{html}");
697        assert_eq!(derive_title(markdown, "fallback"), "Top");
698    }
699
700    #[test]
701    fn blank_first_line_block_is_not_front_matter() {
702        // GitHub and pulldown-cmark reject metadata blocks whose first content
703        // line is blank; accepting one here would hide visible text and let it
704        // spoof the page title.
705        let markdown = "---\n\ntitle: fake\n---\n\n# Real Heading\n";
706        let html = rendered_markdown_html(markdown);
707
708        assert!(html.contains("title: fake"), "{html}");
709        assert_eq!(derive_title(markdown, "fallback"), "Real Heading");
710
711        // An empty block is likewise not front matter.
712        assert!(yaml_front_matter("---\n---\n# Heading\n").is_none());
713    }
714
715    #[test]
716    fn front_matter_title_supports_colons_and_double_quotes() {
717        let markdown = "---\ntitle: \"Project: Alpha\"\n---\n\n# Heading\n";
718        assert_eq!(derive_title(markdown, "fallback"), "Project: Alpha");
719    }
720
721    #[test]
722    fn missing_empty_or_unclosed_front_matter_title_uses_existing_fallbacks() {
723        assert_eq!(
724            derive_title("---\nauthor: Example\n---\n\n# Heading\n", "fallback"),
725            "Heading"
726        );
727        assert_eq!(
728            derive_title("---\ntitle: \n---\n", "Fallback Title"),
729            "Fallback Title"
730        );
731        assert_eq!(
732            derive_title("---\ntitle: Incomplete\n# Real Heading\n", "fallback"),
733            "Real Heading"
734        );
735        assert_eq!(
736            derive_title(
737                "---\ndescription: |\n# Metadata, not a heading\n---\n\n# Real Heading\n",
738                "fallback"
739            ),
740            "Real Heading"
741        );
742    }
743
744    #[test]
745    fn smart_punctuation_is_not_enabled() {
746        let html = rendered_markdown_html("-- --- ... \"straight\" 'quotes'\n");
747
748        assert_eq!(html, "<p>-- --- ... \"straight\" 'quotes'</p>\n");
749        assert!(!html.contains(['–', '—', '…', '“', '”', '‘', '’']));
750    }
751
752    #[test]
753    fn recognized_fences_are_highlighted_with_both_theme_palettes() {
754        let markdown = "```rust\nfn main() { let html = \"<script>x</script>\"; }\n```\n";
755        let html = render_markdown_document(markdown, "fallback", None);
756
757        assert!(html.contains(
758            "<pre class=\"mdo-highlight mdo-syntect-code\"><code class=\"language-rust\">"
759        ));
760        assert!(html.contains("mdo-syntect-keyword"), "{html}");
761        assert!(html.contains(":root[data-theme=\"light\"] .mdo-syntect-code"));
762        assert!(html.contains(":root[data-theme=\"dark\"] .mdo-syntect-code"));
763        assert!(!html.contains("<script>x</script>"));
764        assert!(html.contains("&lt;script&gt;"));
765    }
766
767    #[test]
768    fn unknown_fences_remain_plain_and_do_not_add_theme_css() {
769        let markdown = "```not-a-real-language\n<unsafe> & plain\n```\n";
770        let html = render_markdown_document(markdown, "fallback", None);
771
772        assert!(html.contains(
773            "<pre><code class=\"language-not-a-real-language\">&lt;unsafe&gt; &amp; plain\n</code></pre>"
774        ));
775        assert!(!html.contains("mdo-highlight"));
776        assert!(!html.contains("Syntax highlighting generated by syntect"));
777    }
778
779    #[test]
780    fn pages_without_code_do_not_add_highlight_css() {
781        let html = render_markdown_document("# Just prose\n", "fallback", None);
782        assert!(!html.contains("Syntax highlighting generated by syntect"));
783        assert!(!html.contains("mdo-syntect-"));
784
785        let unlabeled = render_markdown_document("```\nplain code\n```\n", "fallback", None);
786        assert!(unlabeled.contains("<pre><code>plain code\n</code></pre>"));
787        assert!(!unlabeled.contains("Syntax highlighting generated by syntect"));
788    }
789
790    #[test]
791    fn literal_placeholder_spoof_does_not_capture_generated_markup() {
792        let spoof = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
793        let markdown = format!("`{spoof}`\n\n```rust\nlet answer = 42;\n```\n");
794        let html = render_markdown_document(&markdown, "fallback", None);
795
796        assert!(html.contains(spoof));
797        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
798        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
799    }
800
801    #[test]
802    fn entity_normalized_placeholder_spoof_cannot_capture_generated_markup() {
803        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
804        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
805        let markdown = format!("{encoded}\n\n```rust\nlet answer = 42;\n```\n");
806        let html = render_markdown_document(&markdown, "fallback", None);
807
808        assert!(html.contains(normalized), "{html}");
809        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
810        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
811    }
812
813    #[test]
814    fn attribute_normalized_placeholder_cannot_receive_generated_markup() {
815        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
816        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
817        let markdown = format!(
818            "<span title=\"{encoded}\">probe</span>\n\n```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n"
819        );
820        let html = render_markdown_document(&markdown, "fallback", None);
821
822        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
823        assert!(!html.contains("title=\"<pre"), "{html}");
824        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
825        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
826        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_1__"));
827    }
828
829    #[test]
830    fn normalized_spoof_cannot_mask_a_sanitizer_destroyed_placeholder() {
831        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
832        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
833        let markdown = format!(
834            "<span title=\"{encoded}\">probe</span>\n\n<style>\n\n```rust\nfn main() {{}}\n```\n"
835        );
836        let html = render_markdown_document(&markdown, "fallback", None);
837
838        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
839        assert!(!html.contains("title=\"<pre"), "{html}");
840        assert!(!html.contains("<pre class=\"mdo-highlight "), "{html}");
841        assert!(!html.contains("<code class=\"language-rust\""), "{html}");
842    }
843
844    #[test]
845    fn unclosed_style_before_fence_terminates_without_post_sanitize_splice() {
846        // Inline `<style>` never closes, so ammonia swallows and strips all
847        // subsequent markup. Highlight splicing happens before that single
848        // sanitizer pass, so this terminates without a placeholder retry.
849        let markdown = "before <style> after\n\n```rust\nfn main() {}\n```\n";
850        let html = render_markdown_document(markdown, "fallback", None);
851
852        assert!(html.contains("before"));
853        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
854        assert!(!html.contains("mdo-highlight"));
855    }
856
857    #[test]
858    fn unclosed_script_before_fence_terminates_without_post_sanitize_splice() {
859        let markdown = "before <script> after\n\n```rust\nfn main() {}\n```\n";
860        let html = render_markdown_document(markdown, "fallback", None);
861
862        assert!(html.contains("before"));
863        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
864        assert!(!html.contains("mdo-highlight"));
865    }
866
867    #[test]
868    fn sanitizer_drops_only_highlight_markup_after_unclosed_style() {
869        // The first fence precedes the unclosed <style>, so its generated
870        // markup survives sanitization. Only the second fence is swallowed.
871        let markdown =
872            "```rust\nlet first = 1;\n```\n\ntext <style> text\n\n```rust\nlet second = 2;\n```\n";
873        let html = render_markdown_document(markdown, "fallback", None);
874
875        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
876        assert!(html.contains("let"), "{html}");
877        assert!(html.contains("first"), "{html}");
878        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
879    }
880
881    #[test]
882    fn multiple_highlighted_blocks_splice_once_each() {
883        let markdown = "```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n";
884        let html = render_markdown_document(markdown, "fallback", None);
885
886        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
887        assert!(html.contains("language-rust"));
888        assert!(html.contains("language-python"));
889        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
890    }
891
892    #[test]
893    fn raw_user_html_still_crosses_the_ammonia_boundary() {
894        let markdown = "<div onclick=\"alert(1)\"><script>bad()</script><span class=\"mdo-syntect-keyword\">user</span></div>\n\n```rust\nlet safe = \"<b>code</b>\";\n```\n";
895        let html = render_markdown_document(markdown, "fallback", None);
896
897        assert!(!html.contains("onclick=\"alert(1)\""));
898        assert!(!html.contains("<script>bad()</script>"));
899        assert!(html.contains(">user</span>"));
900        assert!(!html.contains("<b>code</b>"));
901        assert!(html.contains("&lt;b&gt;"));
902    }
903
904    #[test]
905    fn title_can_come_from_raw_html_h1() {
906        let title = derive_title(
907            r#"<section><h1 class="hero-title">Project <span>Home</span></h1></section>"#,
908            "fallback",
909        );
910
911        assert_eq!(title, "Project Home");
912    }
913
914    #[test]
915    fn derive_title_ignores_headings_in_code_fences() {
916        let markdown = "```sh\n# not a title\n```\n\n# Real Title\n";
917        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
918    }
919
920    #[test]
921    fn derive_title_falls_back_when_only_heading_is_fenced() {
922        let markdown = "~~~\n# fenced heading\n~~~\n";
923        assert_eq!(derive_title(markdown, "Fallback Title"), "Fallback Title");
924    }
925
926    #[test]
927    fn derive_title_ignores_raw_html_h1_inside_code_fence() {
928        let markdown = "```html\n<h1>Not the title</h1>\n```\n\n# Real Title\n";
929        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
930    }
931
932    #[cfg(unix)]
933    #[test]
934    fn dir_to_file_url_adds_trailing_slash() {
935        let url =
936            dir_to_file_url(Path::new("/home/user/docs")).expect("absolute path should convert");
937        assert!(url.ends_with('/'));
938        assert_eq!(url, "file:///home/user/docs/");
939    }
940
941    #[cfg(unix)]
942    #[test]
943    fn dir_to_file_url_encodes_spaces() {
944        let url = dir_to_file_url(Path::new("/home/user/my docs")).expect("should convert");
945        assert_eq!(url, "file:///home/user/my%20docs/");
946    }
947
948    // `#` is a legal Windows filename character but is not exercised there
949    // because these are pure-path conversions, not filesystem operations —
950    // gating still keeps the Windows suite focused on Windows-specific forms
951    // (drive letters, UNC, `\\?\`) covered below.
952
953    #[cfg(unix)]
954    #[test]
955    fn dir_to_file_url_encodes_hash() {
956        let url = dir_to_file_url(Path::new("/home/user/docs#1")).expect("should convert");
957        assert_eq!(url, "file:///home/user/docs%231/");
958    }
959
960    #[cfg(unix)]
961    #[test]
962    fn dir_to_file_url_encodes_percent() {
963        let url = dir_to_file_url(Path::new("/home/user/50%done")).expect("should convert");
964        assert_eq!(url, "file:///home/user/50%25done/");
965    }
966
967    // `?` is invalid in Windows filenames, so this case can't arise there.
968
969    #[cfg(unix)]
970    #[test]
971    fn dir_to_file_url_encodes_question_mark() {
972        let url = dir_to_file_url(Path::new("/home/user/docs?draft")).expect("should convert");
973        assert_eq!(url, "file:///home/user/docs%3Fdraft/");
974    }
975
976    #[cfg(unix)]
977    #[test]
978    fn dir_to_file_url_encodes_unicode_accented() {
979        let url = dir_to_file_url(Path::new("/home/user/résumé")).expect("should convert");
980        assert_eq!(url, "file:///home/user/r%C3%A9sum%C3%A9/");
981    }
982
983    #[cfg(unix)]
984    #[test]
985    fn dir_to_file_url_encodes_unicode_cjk() {
986        let url = dir_to_file_url(Path::new("/home/user/日本語")).expect("should convert");
987        assert_eq!(url, "file:///home/user/%E6%97%A5%E6%9C%AC%E8%AA%9E/");
988    }
989
990    #[test]
991    fn dir_to_file_url_returns_none_for_relative_path() {
992        assert_eq!(dir_to_file_url(Path::new("relative/dir")), None);
993    }
994
995    #[cfg(windows)]
996    #[test]
997    fn dir_to_file_url_windows_drive_letter() {
998        let url = dir_to_file_url(Path::new(r"C:\foo\bar")).expect("should convert");
999        assert_eq!(url, "file:///C:/foo/bar/");
1000    }
1001
1002    #[cfg(windows)]
1003    #[test]
1004    fn dir_to_file_url_windows_drive_letter_with_space() {
1005        let url = dir_to_file_url(Path::new(r"C:\Program Files\mdo")).expect("should convert");
1006        assert_eq!(url, "file:///C:/Program%20Files/mdo/");
1007    }
1008
1009    // `fs::canonicalize` on Windows produces the `\\?\` extended-length
1010    // prefix; browsers don't understand `file:////?/C:/...`, so this must
1011    // normalize to the same form as the plain drive-letter case.
1012
1013    #[cfg(windows)]
1014    #[test]
1015    fn dir_to_file_url_windows_extended_length_prefix() {
1016        let url = dir_to_file_url(Path::new(r"\\?\C:\foo\bar")).expect("should convert");
1017        assert_eq!(url, "file:///C:/foo/bar/");
1018    }
1019
1020    #[cfg(windows)]
1021    #[test]
1022    fn dir_to_file_url_windows_unc_path() {
1023        let url = dir_to_file_url(Path::new(r"\\server\share\dir")).expect("should convert");
1024        assert_eq!(url, "file://server/share/dir/");
1025    }
1026}