Skip to main content

mdo_cli/
lib.rs

1//! Shared mdo rendering, temp-output, browser launch, and integration helpers.
2
3use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeSet;
5use std::fs;
6use std::hash::{Hash, Hasher};
7use std::io;
8#[cfg(unix)]
9use std::io::Write;
10use std::path::{Path, PathBuf};
11use std::time::{Duration, Instant, UNIX_EPOCH};
12
13#[cfg(unix)]
14use std::fs::OpenOptions;
15#[cfg(unix)]
16use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
17
18use pulldown_cmark::Options;
19use url::Url;
20
21#[cfg(target_os = "android")]
22mod android;
23pub mod file_manager;
24mod highlight;
25#[cfg(target_os = "windows")]
26pub mod windows_setup;
27
28const SIMPLE_CSS: &str = include_str!("../assets/simple.min.css");
29const APP_DISPLAY_NAME: &str = "mdo";
30const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
31pub const SETUP_SAMPLE_FILE_NAME: &str = "welcome-to-open-as-html-with-mdo.md";
32pub const SETUP_SAMPLE_MARKDOWN: &str = "\
33# Welcome to the world of Open as HTML with mdo
34
35If you are reading this in your browser, mdo rendered Markdown as HTML and
36opened it successfully.
37
38Next, right-click any `.md` file and choose **Open as HTML** to read it this way.
39If you make mdo your default Markdown app, a double-click does the same.
40";
41const UNSAFE_TEMP_OUTPUT_STEM_CHARS: &[char] = &[
42    '&', '^', '%', '(', ')', '!', '"', '\'', '<', '>', '|', ';', '`', '$', '\\', '/', ':',
43];
44
45// mdo keeps simple.css as the base stylesheet but softens the heading/body
46// scale for generated documents. Users who prefer the unmodified vendored
47// simple.css typography can pass assets/restore-simple-css.css with --css.
48const MDO_DEFAULT_TYPOGRAPHY_CSS: &str = include_str!("../assets/mdo-default-typography.css");
49
50// pulldown-cmark emits GFM alerts as blockquotes with a
51// `markdown-alert-{kind}` class. Keep the presentation in the generated
52// document so alerts also work for bare installs with no external assets.
53// The plain `:root` and prefers-color-scheme rules keep alerts styled when
54// JavaScript is disabled (the theme-toggle script never runs, so no
55// data-theme attribute is ever set); the higher-specificity
56// `:root[data-theme=...]` rules then follow the theme toggle rather than the
57// OS preference once a reader has selected a manual theme.
58const GFM_ALERTS_CSS: &str = r#"
59:root{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
60@media (prefers-color-scheme: dark){:root{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}}
61:root[data-theme="light"]{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
62:root[data-theme="dark"]{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}
63blockquote[class^="markdown-alert-"]{--alert-color:var(--accent);border-left:.3rem solid var(--alert-color);background:var(--accent-bg);padding:.75rem 1rem}
64blockquote.markdown-alert-note{--alert-color:var(--alert-note)}blockquote.markdown-alert-tip{--alert-color:var(--alert-tip)}blockquote.markdown-alert-important{--alert-color:var(--alert-important)}blockquote.markdown-alert-warning{--alert-color:var(--alert-warning)}blockquote.markdown-alert-caution{--alert-color:var(--alert-caution)}
65"#;
66
67// ─── BEGIN THEME TOGGLE ────────────────────────────────────────────────
68// Self-contained light/dark mode toggle. To remove this feature entirely:
69//   1. Delete this block (down to "END THEME TOGGLE").
70//   2. Delete the `{theme_toggle}` line and `theme_toggle = ...` arg in
71//      `wrap_html5` below.
72// Variable values mirror simple.css's @media (prefers-color-scheme: dark).
73//
74// Behavior notes:
75// - OS theme is detected automatically and tracked live until the user makes
76//   a manual choice; the manual choice persists via localStorage.
77// - localStorage can throw on file:// pages in some browsers/configurations,
78//   so every access is wrapped \u2014 the toggle still works for the current page
79//   even when persistence is unavailable.
80// - An in-memory `manual` flag (not the localStorage read) is the source of
81//   truth for "the user made an explicit choice". It is initialized from the
82//   saved value and set on every toggle click regardless of whether
83//   localStorage.setItem succeeds, so a later prefers-color-scheme change
84//   can never clobber an explicit choice just because persistence failed
85//   (e.g. on file:// pages).
86// - The button is a real <button> (keyboard focusable/activatable) with a
87//   state-aware aria-label.
88// - This <style> block is emitted before the --css override block, so custom
89//   CSS can restyle or hide the toggle (e.g. `#theme-toggle{display:none}`)
90//   and reclaim the reserved narrow-screen padding (`body{padding-top:0}`).
91const THEME_TOGGLE: &str = r#"<style id="mdo-theme-toggle">
92:root[data-theme="light"]{color-scheme:light;--bg:#fff;--accent-bg:#f5f7ff;--text:#212121;--text-light:#585858;--accent:#0d47a1;--accent-hover:#1266e2;--accent-text:var(--bg);--code:#d81b60;--preformatted:#444;--disabled:#efefef}
93:root[data-theme="dark"]{color-scheme:dark;--bg:#212121;--accent-bg:#2b2b2b;--text:#dcdcdc;--text-light:#ababab;--accent:#ffb300;--accent-hover:#ffe099;--accent-text:var(--bg);--code:#f06292;--preformatted:#ccc;--disabled:#111}
94:root[data-theme="dark"] img,:root[data-theme="dark"] video{opacity:.8}
95#theme-toggle{position:fixed;top:.75rem;right:.75rem;z-index:1000;padding:.25rem .6rem;font-size:1rem;line-height:1;cursor:pointer;border-radius:var(--standard-border-radius);border:var(--border-width) solid var(--border);background:var(--accent-bg);color:var(--text)}
96@media (max-width:55rem){body{padding-top:2.75rem}}
97@media print{#theme-toggle{display:none}}
98</style>
99<script>
100(function(){
101  var read=function(){try{return localStorage.getItem('theme')}catch(e){return null}};
102  var apply=function(t){document.documentElement.dataset.theme=t;};
103  var mq=matchMedia('(prefers-color-scheme: dark)');
104  var saved=read();
105  var manual=saved!==null;
106  apply(saved||(mq.matches?'dark':'light'));
107  document.addEventListener('DOMContentLoaded',function(){
108    var b=document.createElement('button');
109    b.id='theme-toggle';b.type='button';
110    var sync=function(){
111      var dark=document.documentElement.dataset.theme==='dark';
112      b.textContent=dark?'\u2600':'\u263E';
113      var label=dark?'Switch to light theme':'Switch to dark theme';
114      b.title=label;
115      b.setAttribute('aria-label',label);
116    };
117    b.onclick=function(){
118      var next=document.documentElement.dataset.theme==='dark'?'light':'dark';
119      apply(next);
120      manual=true;
121      try{localStorage.setItem('theme',next)}catch(e){}
122      sync();
123    };
124    if(mq.addEventListener){
125      mq.addEventListener('change',function(e){
126        if(!manual){apply(e.matches?'dark':'light');sync();}
127      });
128    }
129    document.body.appendChild(b);
130    sync();
131  });
132})();
133</script>
134"#;
135// ─── END THEME TOGGLE ──────────────────────────────────────────────────
136
137pub fn derive_output(input: &Path) -> PathBuf {
138    input.with_extension("html")
139}
140
141/// Stable per-source-path location under a private temp/cache dir, e.g.
142/// `%TEMP%\mdo-<uid>\<hash>\<stem>.html`. Re-opening the same source
143/// overwrites the same file rather than accumulating new ones.
144pub fn temp_output_for(input: &Path) -> io::Result<PathBuf> {
145    let canonical = fs::canonicalize(input).unwrap_or_else(|_| input.to_path_buf());
146    let mut hasher = DefaultHasher::new();
147    canonical.hash(&mut hasher);
148    let hash = hasher.finish();
149
150    let stem = input
151        .file_stem()
152        .and_then(|s| s.to_str())
153        .unwrap_or("document");
154    let stem = sanitize_temp_output_stem(stem);
155
156    let root = private_temp_root();
157    ensure_private_dir(&root)?;
158
159    let source_dir = root.join(format!("{:016x}", hash));
160    ensure_private_dir(&source_dir)?;
161
162    Ok(source_dir.join(format!("{stem}.html")))
163}
164
165fn sanitize_temp_output_stem(stem: &str) -> String {
166    let mut sanitized = String::with_capacity(stem.len());
167
168    for ch in stem.chars() {
169        if ch.is_control() || UNSAFE_TEMP_OUTPUT_STEM_CHARS.contains(&ch) {
170            sanitized.push('_');
171        } else {
172            sanitized.push(ch);
173        }
174    }
175
176    if sanitized.chars().any(|ch| ch != '_') {
177        sanitized
178    } else {
179        "document".to_string()
180    }
181}
182
183fn private_temp_root() -> PathBuf {
184    let mut p = std::env::temp_dir();
185    #[cfg(unix)]
186    p.push(format!("mdo-{}", unsafe { libc::geteuid() }));
187    #[cfg(not(unix))]
188    p.push("mdo");
189    p
190}
191
192#[cfg(unix)]
193fn ensure_private_dir(path: &Path) -> io::Result<()> {
194    match fs::symlink_metadata(path) {
195        Ok(metadata) => {
196            let file_type = metadata.file_type();
197            if file_type.is_symlink() || !file_type.is_dir() {
198                return Err(io::Error::new(
199                    io::ErrorKind::AlreadyExists,
200                    format!("{path:?} exists but is not a directory"),
201                ));
202            }
203
204            let uid = unsafe { libc::geteuid() };
205            if metadata.uid() != uid {
206                return Err(io::Error::new(
207                    io::ErrorKind::PermissionDenied,
208                    format!("{path:?} is not owned by the current user"),
209                ));
210            }
211
212            let mode = metadata.permissions().mode();
213            if mode & 0o077 != 0 {
214                fs::set_permissions(path, fs::Permissions::from_mode(mode & !0o077))?;
215            }
216        }
217        Err(e) if e.kind() == io::ErrorKind::NotFound => {
218            let mut builder = fs::DirBuilder::new();
219            builder.mode(0o700);
220            if let Err(create_error) = builder.create(path) {
221                if create_error.kind() == io::ErrorKind::AlreadyExists {
222                    return ensure_private_dir(path);
223                }
224
225                return Err(create_error);
226            }
227        }
228        Err(e) => return Err(e),
229    }
230
231    Ok(())
232}
233
234#[cfg(not(unix))]
235fn ensure_private_dir(path: &Path) -> io::Result<()> {
236    fs::create_dir_all(path)
237}
238
239/// Build a `file://` URL for a directory, suitable for use as `<base href>`.
240///
241/// Delegates to [`Url::from_directory_path`], which correctly
242/// percent-encodes reserved and non-ASCII characters (spaces, `#`, `%`, `?`,
243/// Unicode, …) and handles Windows drive letters, UNC paths, and the
244/// `\\?\`/`\\?\UNC\` extended-length prefixes that `fs::canonicalize`
245/// produces — a hand-rolled string transform got all of this subtly wrong
246/// (e.g. a literal `#` in a directory name would truncate the URL when a
247/// browser parsed it as a fragment). Always includes a trailing slash so
248/// relative refs resolve correctly against the directory.
249///
250/// Returns `None` if `dir` can't be represented as a `file://` URL (notably:
251/// relative paths). Callers should fall back to omitting the `<base href>`
252/// tag entirely rather than emit a broken URL.
253fn dir_to_file_url(dir: &Path) -> Option<String> {
254    Url::from_directory_path(dir)
255        .ok()
256        .map(|url| url.to_string())
257}
258
259/// Launch the platform's default handler for `path` (typically a web browser
260/// for `.html`). Non-blocking — the spawned process runs independently.
261pub fn launch_browser(path: &Path) -> std::io::Result<()> {
262    #[cfg(target_os = "windows")]
263    {
264        // SECURITY: open via the Win32 ShellExecuteW API (through the `opener`
265        // crate) rather than `cmd /C start`. `start` runs the path through
266        // cmd.exe's command-line parser, so cmd metacharacters (`&`, `^`, …) —
267        // which are legal in Windows filenames and reach us via the input
268        // file's stem in temp_output_for — would be interpreted as commands
269        // (e.g. opening `a&calc&.md` would launch calc.exe). ShellExecuteW
270        // takes the path as a single typed argument, so those characters stay
271        // inert. It is non-blocking, preserving the fire-and-forget behavior.
272        opener::open(path).map_err(io::Error::other)?;
273    }
274    #[cfg(target_os = "macos")]
275    {
276        // `open` returns promptly once Launch Services accepts the request,
277        // so waiting for it doesn't block on the browser itself — and a
278        // nonzero exit (no handler for the file) must surface as a launch
279        // failure rather than being discarded with the child handle.
280        let status = std::process::Command::new("open").arg(path).status()?;
281        if !status.success() {
282            return Err(io::Error::other(format!("open exited with {status}")));
283        }
284    }
285    #[cfg(all(unix, not(target_os = "macos")))]
286    {
287        launch_via_xdg_open(path)?;
288    }
289    Ok(())
290}
291
292/// Open `path` with the first available freedesktop opener. Falls back through
293/// common launchers when `xdg-open` (xdg-utils) is not installed, and reaps the
294/// launcher process in a detached thread so it does not linger as a zombie
295/// during long `--watch` sessions.
296///
297/// Spawning an opener is not the same as launching a browser: `xdg-open` can
298/// exist, start, and then exit nonzero because no browser handler is
299/// configured. We therefore listen for each opener's exit for a short window
300/// — a quick nonzero exit is an honest failure (and we fall through to the
301/// next opener), while an opener still running after the window has almost
302/// certainly handed off (or, in xdg-open's no-desktop fallback, IS the
303/// browser), so we detach and call it success. We never block on the browser
304/// itself beyond that window.
305#[cfg(all(unix, not(target_os = "macos")))]
306fn launch_via_xdg_open(path: &Path) -> std::io::Result<()> {
307    const OPENERS: &[(&str, &[&str])] = &[
308        ("xdg-open", &[]),
309        ("gio", &["open"]),
310        ("gnome-open", &[]),
311        ("kde-open5", &[]),
312        ("kde-open", &[]),
313        ("wslview", &[]),
314    ];
315    const LAUNCH_FAILURE_WINDOW: Duration = Duration::from_secs(2);
316
317    let mut last_failure: Option<String> = None;
318    for (program, leading) in OPENERS {
319        let mut command = std::process::Command::new(program);
320        command.args(*leading).arg(path);
321        let Ok(mut child) = command.spawn() else {
322            continue; // not installed; try the next opener
323        };
324
325        // The waiting thread doubles as the reaper for the detached-success
326        // case: it always waits the child to completion, we just stop
327        // listening for the result after the failure window.
328        let (tx, rx) = std::sync::mpsc::channel();
329        std::thread::spawn(move || {
330            let _ = tx.send(child.wait());
331        });
332
333        match rx.recv_timeout(LAUNCH_FAILURE_WINDOW) {
334            Ok(Ok(status)) if status.success() => return Ok(()),
335            Ok(Ok(status)) => {
336                last_failure = Some(format!("{program} exited with {status}"));
337            }
338            Ok(Err(e)) => {
339                last_failure = Some(format!("failed waiting on {program}: {e}"));
340            }
341            // Still running after the window: it handed off to (or is) the
342            // browser. The waiting thread reaps it eventually.
343            Err(_) => return Ok(()),
344        }
345    }
346
347    match last_failure {
348        Some(failure) => Err(io::Error::other(failure)),
349        None => Err(io::Error::new(
350            io::ErrorKind::NotFound,
351            "no desktop opener found (install xdg-utils)",
352        )),
353    }
354}
355
356fn markdown_options() -> Options {
357    let mut options = Options::empty();
358    options.insert(Options::ENABLE_STRIKETHROUGH);
359    options.insert(Options::ENABLE_TABLES);
360    options.insert(Options::ENABLE_FOOTNOTES);
361    options.insert(Options::ENABLE_TASKLISTS);
362    options.insert(Options::ENABLE_GFM);
363
364    options
365}
366
367fn markdown_to_html(
368    markdown: &str,
369    placeholder_discriminator: u64,
370    plain_fences: &BTreeSet<usize>,
371) -> highlight::RenderedMarkdown {
372    // Front matter is stripped here, before parsing, by the same
373    // `yaml_front_matter` splitter that title derivation uses, so one set of
374    // acceptance rules governs both. Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
375    // is deliberately NOT enabled: pulldown-cmark 0.13 recognizes metadata
376    // blocks anywhere at indent 0, not just at document start, which silently
377    // swallows mid-document text framed by `---` lines.
378    let markdown = yaml_front_matter(markdown)
379        .map(|(_, body)| body)
380        .unwrap_or(markdown);
381
382    highlight::render(
383        markdown,
384        markdown_options(),
385        placeholder_discriminator,
386        plain_fences,
387    )
388}
389
390/// Upper bound on placeholder-collision retries. A collision requires
391/// document text that normalizes into the current placeholder token, so more
392/// than a couple of retries only happens with adversarial input; past the cap
393/// the document renders with highlighting disabled rather than looping.
394const MAX_PLACEHOLDER_RETRIES: u32 = 16;
395
396/// Shared render/process/splice loop behind [`safe_markdown_body`] and
397/// `convert_with_diagnostics`.
398///
399/// Highlighted spans are generated by mdo from escaped code text and spliced
400/// into the raw renderer output only after all placeholders have been
401/// validated. `process` (usually ammonia) then handles the completed document,
402/// including generated markup, so no string insertion happens beyond the
403/// sanitizer boundary. The loop is guaranteed to terminate:
404///
405/// - a destroyed placeholder can never survive under any discriminator, so
406///   its fence is added to the strictly growing `plain_fences` set and
407///   rendered as an ordinary escaped code block instead;
408/// - collisions retry with a fresh discriminator at most
409///   [`MAX_PLACEHOLDER_RETRIES`] times, after which every fence is rendered
410///   plain, leaving nothing to splice.
411fn spliced_markdown_body(
412    markdown: &str,
413    mut render: impl FnMut(&str, u64, &BTreeSet<usize>) -> highlight::RenderedMarkdown,
414    mut process: impl FnMut(&str) -> String,
415) -> (String, Option<&'static str>) {
416    let mut discriminator = 0_u64;
417    let mut collision_retries = 0_u32;
418    let mut plain_fences = BTreeSet::new();
419
420    loop {
421        let rendered = render(markdown, discriminator, &plain_fences);
422        match rendered.finish(rendered.raw_html().to_string()) {
423            Ok(body) => return (process(&body), rendered.css()),
424            Err(highlight::SpliceError::Destroyed(fences)) => {
425                plain_fences.extend(fences);
426            }
427            Err(highlight::SpliceError::Collision) => {
428                collision_retries += 1;
429                if collision_retries > MAX_PLACEHOLDER_RETRIES {
430                    plain_fences.extend(0..rendered.fence_count());
431                }
432                discriminator += 1;
433            }
434        }
435    }
436}
437
438/// Render and sanitize Markdown, splicing generated highlighting before the
439/// completed document crosses the sanitizer boundary.
440fn safe_markdown_body(markdown: &str) -> (String, Option<&'static str>) {
441    spliced_markdown_body(markdown, markdown_to_html, sanitize_html)
442}
443
444fn sanitize_html(html: &str) -> String {
445    ammonia::Builder::default()
446        // The global "class" allowance is intentional: user-authored class
447        // names are inert here because classes only select styles from mdo's
448        // own generated stylesheet. Highlight safety does not rest on this
449        // allowlist either: highlighted markup is generated from escaped code
450        // text, spliced before sanitization, and then cleaned with the rest of
451        // the document.
452        .add_generic_attributes(&["class", "id"])
453        .add_tags(&["input"])
454        .add_tag_attributes("input", &["checked", "type"])
455        .add_tag_attribute_values("input", "checked", &[""])
456        .add_tag_attribute_values("input", "type", &["checkbox"])
457        .set_tag_attribute_value("input", "disabled", "")
458        .clean(html)
459        .to_string()
460}
461
462/// Render Markdown supplied in memory as a complete, self-contained HTML page.
463///
464/// This is the platform-neutral entry point used by the Android application.
465/// Raw HTML is always sanitized, matching the safe default of the desktop CLI.
466/// `fallback_title` is used only when the document has no top-level heading.
467pub fn render_markdown_document(
468    markdown: &str,
469    fallback_title: &str,
470    source_modified_unix_secs: Option<u64>,
471) -> String {
472    let (body, highlight_css) = safe_markdown_body(markdown);
473    let title = derive_title(markdown, fallback_title);
474    wrap_html5(
475        &body,
476        &title,
477        None,
478        None,
479        highlight_css,
480        source_modified_unix_secs,
481    )
482}
483
484fn derive_title(markdown: &str, fallback: &str) -> String {
485    if let Some(title) = front_matter_title(markdown) {
486        return title;
487    }
488
489    // A valid metadata block is not document content. Exclude it from the
490    // existing H1 search even when it has no usable title key.
491    let markdown = yaml_front_matter(markdown)
492        .map(|(_, document)| document)
493        .unwrap_or(markdown);
494
495    // Strip fenced code blocks first so a heading — whether an ATX `# ` line or
496    // a raw <h1> — inside a ``` or ~~~ block is never mistaken for the title.
497    let without_fences = strip_code_fences(markdown);
498    for line in without_fences.lines() {
499        let trimmed = line.trim_start();
500        if let Some(rest) = trimmed.trim_end().strip_prefix("# ") {
501            return rest.trim().to_string();
502        }
503    }
504    if let Some(title) = derive_raw_html_h1_title(&without_fences) {
505        return title;
506    }
507    fallback.to_string()
508}
509
510/// Extract a simple scalar `title:` from a complete YAML-style metadata block
511/// at the start of the document.
512///
513/// pulldown-cmark deliberately recognizes the block delimiters without
514/// interpreting YAML. mdo follows that narrow behavior: it reads only an
515/// unindented `title` key and does not add a general-purpose YAML parser (and
516/// its dependency/security surface) merely to title the generated page.
517fn front_matter_title(markdown: &str) -> Option<String> {
518    let (metadata, _) = yaml_front_matter(markdown)?;
519    let mut title = None;
520    for line in metadata.lines() {
521        if line.starts_with(char::is_whitespace) {
522            continue;
523        }
524        if let Some((key, value)) = line.split_once(':') {
525            if key == "title" {
526                let value = unquote_front_matter_scalar(value.trim());
527                if !value.is_empty() {
528                    title = Some(value.to_string());
529                }
530            }
531        }
532    }
533
534    title
535}
536
537/// Split a complete YAML-style metadata block from the document body. The
538/// returned metadata excludes delimiters.
539///
540/// This splitter is the single source of truth for front-matter recognition
541/// (both hiding the block from rendered output and title extraction), and its
542/// acceptance rules are deliberately conservative and GitHub-like:
543///
544/// - the opening `---` must be the very first line of the document;
545/// - the closing delimiter is `---` or `...` on its own line — trailing
546///   spaces are allowed but tabs are not;
547/// - the block must be non-empty and its first line must not be blank.
548///   GitHub and pulldown-cmark both reject blocks whose first content line is
549///   blank, so treating them as front matter here would hide visible content
550///   and let e.g. `---\n\ntitle: fake\n---` spoof the page title.
551fn yaml_front_matter(markdown: &str) -> Option<(&str, &str)> {
552    fn delimiter(line: &str) -> Option<&str> {
553        let line = line.trim_end_matches(['\r', '\n']).trim_end_matches(' ');
554        (line == "---" || line == "...").then_some(line)
555    }
556
557    let first_line_end = markdown.find('\n').unwrap_or(markdown.len());
558    if delimiter(&markdown[..first_line_end]) != Some("---") || first_line_end == markdown.len() {
559        return None;
560    }
561
562    let metadata_start = first_line_end + 1;
563    let remainder = &markdown[metadata_start..];
564    let mut consumed = 0;
565    // split_inclusive also yields a final segment without a trailing newline,
566    // so a closing delimiter at end-of-input is found by the loop as well.
567    for segment in remainder.split_inclusive('\n') {
568        if delimiter(segment).is_some() {
569            let metadata = &remainder[..consumed];
570            let first_content_line = metadata.lines().next()?;
571            if first_content_line.trim().is_empty() {
572                return None;
573            }
574            return Some((metadata, &remainder[consumed + segment.len()..]));
575        }
576        consumed += segment.len();
577    }
578
579    None
580}
581
582fn unquote_front_matter_scalar(value: &str) -> &str {
583    if value.len() < 2 {
584        return value;
585    }
586
587    let bytes = value.as_bytes();
588    if matches!(
589        (bytes[0], bytes[value.len() - 1]),
590        (b'\'', b'\'') | (b'"', b'"')
591    ) {
592        &value[1..value.len() - 1]
593    } else {
594        value
595    }
596}
597
598/// Return `markdown` with fenced code blocks (``` or ~~~) removed, so title
599/// detection never reads inside code samples.
600fn strip_code_fences(markdown: &str) -> String {
601    let mut out = String::with_capacity(markdown.len());
602    let mut fence: Option<char> = None;
603    for line in markdown.lines() {
604        if let Some(marker) = code_fence_marker(line.trim_start()) {
605            match fence {
606                Some(open) if open == marker => fence = None,
607                Some(_) => {}
608                None => fence = Some(marker),
609            }
610            continue;
611        }
612        if fence.is_some() {
613            continue;
614        }
615        out.push_str(line);
616        out.push('\n');
617    }
618    out
619}
620
621/// Detect a code-fence line, returning its marker char when the line starts
622/// with at least three backticks or tildes. This is a pragmatic subset of
623/// CommonMark (it does not bound the indent or require the closing fence to be
624/// at least as long), which is sufficient for title detection.
625fn code_fence_marker(trimmed_start: &str) -> Option<char> {
626    if trimmed_start.starts_with("```") {
627        Some('`')
628    } else if trimmed_start.starts_with("~~~") {
629        Some('~')
630    } else {
631        None
632    }
633}
634
635fn derive_raw_html_h1_title(markdown: &str) -> Option<String> {
636    let lower = markdown.to_ascii_lowercase();
637    let mut search_start = 0;
638
639    while let Some(offset) = lower[search_start..].find("<h1") {
640        let start = search_start + offset;
641        let after_tag_name = start + 3;
642        let next = lower.as_bytes().get(after_tag_name).copied();
643        if !matches!(
644            next,
645            Some(b'>') | Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')
646        ) {
647            search_start = after_tag_name;
648            continue;
649        }
650
651        let content_start = start + markdown[start..].find('>')? + 1;
652        let content_end = content_start + lower[content_start..].find("</h1>")?;
653        let title = strip_html_tags(&markdown[content_start..content_end])
654            .split_whitespace()
655            .collect::<Vec<_>>()
656            .join(" ");
657        if !title.is_empty() {
658            return Some(title);
659        }
660
661        search_start = content_end + 5;
662    }
663
664    None
665}
666
667fn strip_html_tags(input: &str) -> String {
668    let mut output = String::with_capacity(input.len());
669    let mut in_tag = false;
670
671    for ch in input.chars() {
672        match ch {
673            '<' => in_tag = true,
674            '>' if in_tag => in_tag = false,
675            _ if !in_tag => output.push(ch),
676            _ => {}
677        }
678    }
679
680    output
681}
682
683fn wrap_html5(
684    body: &str,
685    title: &str,
686    base_href: Option<&str>,
687    css_override: Option<&str>,
688    highlight_css: Option<&str>,
689    source_modified_unix_secs: Option<u64>,
690) -> String {
691    // `<base href>` makes relative image/link refs in the rendered HTML resolve
692    // against the *source* directory even when the HTML lives elsewhere
693    // (e.g. when --open writes to %TEMP%). Must come before any element that
694    // references a URL, so we put it first inside <head>.
695    let base_tag = match base_href {
696        Some(href) => format!("<base href=\"{}\">\n", html_escape(href)),
697        None => String::new(),
698    };
699    let css_override_block = css_override
700        .filter(|css| !css.trim().is_empty())
701        .map(|css| {
702            format!(
703                "<style id=\"mdo-css-override\">\n/* Custom CSS from --css */\n{}\n</style>\n",
704                escape_style_end_tags(css)
705            )
706        })
707        .unwrap_or_default();
708    let mdo_default_typography = format!(
709        "<style id=\"mdo-default-typography\">\n{}\n</style>\n",
710        escape_style_end_tags(MDO_DEFAULT_TYPOGRAPHY_CSS)
711    );
712    let highlight_css = highlight_css.unwrap_or_default();
713    // Provenance lives only in <meta name="generator">; the visible page
714    // carries no mdo branding, version, or render timing (v0.6 quiet output).
715    let generator = format!("{APP_DISPLAY_NAME} {APP_VERSION}");
716    // Restrained source-freshness footer: the source file's filesystem
717    // modification time, rendered as UTC with a machine-readable datetime.
718    // The tiny inline script re-formats it in the reader's locale/timezone
719    // when JavaScript is available. Omitted entirely when the timestamp is
720    // missing or unreadable.
721    let source_meta = source_modified_unix_secs
722        .map(|secs| {
723            let machine = utc_datetime_from_unix_secs(secs);
724            let human = human_utc_datetime_from_unix_secs(secs);
725            format!(
726                "<footer class=\"mdo-source-meta\">Source modified: <time datetime=\"{machine}\">{human}</time></footer>\n\
727                 <script>\n\
728                 (function(){{var t=document.querySelector('.mdo-source-meta time');if(!t)return;var d=new Date(t.getAttribute('datetime'));if(isNaN(d))return;try{{t.textContent=d.toLocaleString(undefined,{{year:'numeric',month:'long',day:'numeric',hour:'numeric',minute:'2-digit'}});}}catch(e){{}}}})();\n\
729                 </script>\n",
730                machine = html_escape(&machine),
731                human = html_escape(&human),
732            )
733        })
734        .unwrap_or_default();
735    format!(
736        "<!DOCTYPE html>\n\
737         <html lang=\"en\">\n\
738         <head>\n\
739         <meta charset=\"utf-8\">\n\
740         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
741         <meta name=\"generator\" content=\"{generator}\">\n\
742         {base_tag}\
743         <title>{title}</title>\n\
744         <style>\n{css}\n{gfm_alerts_css}\n{highlight_css}\n.mdo-source-meta{{margin-top:3rem;border:0;padding:1rem 0 1.5rem;font-size:.8rem;line-height:1.4;color:var(--text-light);text-align:center}}\n</style>\n\
745         {theme_toggle}\
746         {mdo_default_typography}\
747         {css_override_block}\
748         </head>\n\
749         <body>\n\
750         <main>\n{body}\n</main>\n\
751         {source_meta}\
752         </body>\n\
753         </html>\n",
754        generator = html_escape(&generator),
755        base_tag = base_tag,
756        title = html_escape(title),
757        css = SIMPLE_CSS,
758        gfm_alerts_css = GFM_ALERTS_CSS,
759        highlight_css = highlight_css,
760        theme_toggle = THEME_TOGGLE, // ← THEME TOGGLE injection point (delete this line to remove)
761        mdo_default_typography = mdo_default_typography,
762        css_override_block = css_override_block,
763        body = body,
764        source_meta = source_meta,
765    )
766}
767
768fn escape_style_end_tags(css: &str) -> String {
769    const STYLE_END_PREFIX: &[u8] = b"</style";
770
771    let mut escaped = String::with_capacity(css.len());
772    let bytes = css.as_bytes();
773    let mut i = 0;
774
775    while i < css.len() {
776        if i + STYLE_END_PREFIX.len() <= css.len()
777            && bytes[i..i + STYLE_END_PREFIX.len()].eq_ignore_ascii_case(STYLE_END_PREFIX)
778        {
779            escaped.push_str("<\\/style");
780            i += STYLE_END_PREFIX.len();
781        } else {
782            let ch = css[i..]
783                .chars()
784                .next()
785                .expect("index should always point at a char boundary");
786            escaped.push(ch);
787            i += ch.len_utf8();
788        }
789    }
790
791    escaped
792}
793
794const MONTH_NAMES: [&str; 12] = [
795    "January",
796    "February",
797    "March",
798    "April",
799    "May",
800    "June",
801    "July",
802    "August",
803    "September",
804    "October",
805    "November",
806    "December",
807];
808
809/// The source file's mtime as seconds since the Unix epoch, or `None` when
810/// the metadata is missing or unreadable (which must never block rendering).
811fn source_modified_unix_secs(input: &Path) -> Option<u64> {
812    fs::metadata(input)
813        .and_then(|metadata| metadata.modified())
814        .ok()
815        .and_then(|mtime| mtime.duration_since(UNIX_EPOCH).ok())
816        .map(|elapsed| elapsed.as_secs())
817}
818
819/// ISO 8601 UTC datetime, e.g. `2026-07-14T17:42:05Z`, for `<time datetime>`.
820fn utc_datetime_from_unix_secs(secs: u64) -> String {
821    let days = (secs / 86_400) as i64;
822    let (year, month, day) = civil_from_days(days);
823    let seconds_of_day = secs % 86_400;
824    let hour = seconds_of_day / 3_600;
825    let minute = (seconds_of_day % 3_600) / 60;
826    let second = seconds_of_day % 60;
827
828    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
829}
830
831/// Readable UTC fallback text, e.g. `July 14, 2026, 5:42 PM UTC`, shown when
832/// JavaScript cannot re-format the timestamp in the reader's locale.
833fn human_utc_datetime_from_unix_secs(secs: u64) -> String {
834    let days = (secs / 86_400) as i64;
835    let (year, month, day) = civil_from_days(days);
836    let seconds_of_day = secs % 86_400;
837    let hour24 = seconds_of_day / 3_600;
838    let minute = (seconds_of_day % 3_600) / 60;
839    let (hour12, meridiem) = match hour24 {
840        0 => (12, "AM"),
841        1..=11 => (hour24, "AM"),
842        12 => (12, "PM"),
843        _ => (hour24 - 12, "PM"),
844    };
845    let month_name = MONTH_NAMES[(month - 1) as usize];
846
847    format!("{month_name} {day}, {year}, {hour12}:{minute:02} {meridiem} UTC")
848}
849
850fn civil_from_days(days_since_unix_epoch: i64) -> (i64, i64, i64) {
851    // Howard Hinnant's civil-from-days algorithm, shifted for Unix epoch days.
852    let z = days_since_unix_epoch + 719_468;
853    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
854    let doe = z - era * 146_097;
855    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
856    let y = yoe + era * 400;
857    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
858    let mp = (5 * doy + 2) / 153;
859    let day = doy - (153 * mp + 2) / 5 + 1;
860    let month = mp + if mp < 10 { 3 } else { -9 };
861    let year = y + if month <= 2 { 1 } else { 0 };
862
863    (year, month, day)
864}
865
866fn html_escape(s: &str) -> String {
867    s.replace('&', "&amp;")
868        .replace('<', "&lt;")
869        .replace('>', "&gt;")
870        .replace('"', "&quot;")
871}
872
873/// Wall-clock time spent in each stage of one render workflow, reported to
874/// stderr by `--verbose`. Stages that do not run for a given invocation
875/// (`sanitize` under `--unsafe-html`, `assemble` under `--bare`) report zero.
876#[derive(Default)]
877struct StageTimings {
878    read: Duration,
879    markdown: Duration,
880    sanitize: Duration,
881    assemble: Duration,
882    write: Duration,
883}
884
885/// Print per-stage and total timings for a completed render to STDERR only.
886/// Performance diagnostics belong in the terminal: they never touch stdout
887/// or the generated HTML (v0.6 quiet output). `total` is the wall-clock time
888/// of the whole workflow, so it is always at least the sum of the stages.
889fn report_render_timings(input: &Path, timings: &StageTimings, total: Duration) {
890    let ms = |d: Duration| d.as_secs_f64() * 1000.0;
891    eprintln!("⏱  Render workflow for {:?}:", input);
892    eprintln!("   read     {:>10.3} ms", ms(timings.read));
893    eprintln!("   markdown {:>10.3} ms", ms(timings.markdown));
894    eprintln!("   sanitize {:>10.3} ms", ms(timings.sanitize));
895    eprintln!("   assemble {:>10.3} ms", ms(timings.assemble));
896    eprintln!("   write    {:>10.3} ms", ms(timings.write));
897    eprintln!("   total    {:>10.3} ms", ms(total));
898}
899
900pub fn convert(
901    input: &Path,
902    output: &Path,
903    bare: bool,
904    unsafe_html: bool,
905    private_output: bool,
906) -> bool {
907    convert_with_css_override(input, output, bare, unsafe_html, private_output, None)
908}
909
910pub fn convert_with_css_override(
911    input: &Path,
912    output: &Path,
913    bare: bool,
914    unsafe_html: bool,
915    private_output: bool,
916    css_override: Option<&Path>,
917) -> bool {
918    convert_with_diagnostics(
919        input,
920        output,
921        bare,
922        unsafe_html,
923        private_output,
924        css_override,
925        false,
926    )
927}
928
929/// Full render workflow with optional `--verbose` timing diagnostics.
930///
931/// The generated HTML is byte-identical whether or not `verbose` is set:
932/// timings are measured around the existing stages and reported to stderr
933/// only after a fully successful render.
934pub fn convert_with_diagnostics(
935    input: &Path,
936    output: &Path,
937    bare: bool,
938    unsafe_html: bool,
939    private_output: bool,
940    css_override: Option<&Path>,
941    verbose: bool,
942) -> bool {
943    let workflow_start = Instant::now();
944    let mut timings = StageTimings::default();
945
946    let stage_start = Instant::now();
947    let markdown = match fs::read_to_string(input) {
948        Ok(s) => s,
949        Err(e) => {
950            eprintln!("❌ Failed to read {:?}: {}", input, e);
951            return false;
952        }
953    };
954    timings.read = stage_start.elapsed();
955
956    let css_override = if bare {
957        None
958    } else {
959        match css_override {
960            Some(path) => {
961                let stage_start = Instant::now();
962                let css = fs::read_to_string(path);
963                timings.read += stage_start.elapsed();
964                match css {
965                    Ok(css) => Some(css),
966                    Err(e) => {
967                        eprintln!("❌ Failed to read CSS override {:?}: {}", path, e);
968                        return false;
969                    }
970                }
971            }
972            None => None,
973        }
974    };
975
976    // Same splice loop as `safe_markdown_body`, instrumented for --verbose.
977    let (body, highlight_css) = spliced_markdown_body(
978        &markdown,
979        |markdown, discriminator, plain_fences| {
980            let stage_start = Instant::now();
981            let rendered = markdown_to_html(markdown, discriminator, plain_fences);
982            timings.markdown += stage_start.elapsed();
983            rendered
984        },
985        |html| {
986            if unsafe_html {
987                html.to_string()
988            } else {
989                let sanitize_start = Instant::now();
990                let sanitized = sanitize_html(html);
991                timings.sanitize += sanitize_start.elapsed();
992                sanitized
993            }
994        },
995    );
996
997    let final_html = if bare {
998        body
999    } else {
1000        let stage_start = Instant::now();
1001        let fallback = input
1002            .file_stem()
1003            .and_then(|s| s.to_str())
1004            .unwrap_or("Document");
1005        let title = derive_title(&markdown, fallback);
1006
1007        // Only inject <base href> when the output lives in a different
1008        // directory from the source — otherwise relative refs already
1009        // resolve correctly and a base tag would just add noise.
1010        let base_href = match (
1011            fs::canonicalize(input)
1012                .ok()
1013                .and_then(|p| p.parent().map(Path::to_path_buf)),
1014            output.parent().and_then(|p| fs::canonicalize(p).ok()),
1015        ) {
1016            (Some(in_dir), Some(out_dir)) if in_dir != out_dir => dir_to_file_url(&in_dir),
1017            _ => None,
1018        };
1019
1020        let wrapped = wrap_html5(
1021            &body,
1022            &title,
1023            base_href.as_deref(),
1024            css_override.as_deref(),
1025            highlight_css,
1026            source_modified_unix_secs(input),
1027        );
1028        timings.assemble = stage_start.elapsed();
1029        wrapped
1030    };
1031
1032    let stage_start = Instant::now();
1033    if let Some(parent) = output.parent() {
1034        if !parent.as_os_str().is_empty() {
1035            if let Err(e) = fs::create_dir_all(parent) {
1036                eprintln!("❌ Failed to create {:?}: {}", parent, e);
1037                return false;
1038            }
1039        }
1040    }
1041
1042    if let Err(e) = write_output_file(output, &final_html, private_output) {
1043        eprintln!("❌ Failed to write to {:?}: {}", output, e);
1044        false
1045    } else {
1046        timings.write = stage_start.elapsed();
1047        println!("✅ Converted {:?} → {:?}", input, output);
1048        if verbose {
1049            report_render_timings(input, &timings, workflow_start.elapsed());
1050        }
1051        true
1052    }
1053}
1054
1055#[cfg(unix)]
1056fn write_output_file(output: &Path, contents: &str, private_output: bool) -> io::Result<()> {
1057    let mut options = OpenOptions::new();
1058    options
1059        .write(true)
1060        .create(true)
1061        .truncate(true)
1062        .custom_flags(libc::O_NOFOLLOW);
1063
1064    if private_output {
1065        options.mode(0o600);
1066    }
1067
1068    let mut file = options.open(output)?;
1069    file.write_all(contents.as_bytes())
1070}
1071
1072#[cfg(not(unix))]
1073fn write_output_file(output: &Path, contents: &str, _private_output: bool) -> io::Result<()> {
1074    fs::write(output, contents)
1075}
1076
1077pub fn open_setup_sample() -> io::Result<()> {
1078    let source = setup_sample_input_path()?;
1079    fs::write(&source, SETUP_SAMPLE_MARKDOWN)?;
1080
1081    let output = temp_output_for(&source)?;
1082    if !convert(&source, &output, false, false, true) {
1083        return Err(io::Error::other("sample render failed"));
1084    }
1085
1086    launch_browser(&output)?;
1087    Ok(())
1088}
1089
1090fn setup_sample_input_path() -> io::Result<PathBuf> {
1091    let root = private_temp_root();
1092    ensure_private_dir(&root)?;
1093
1094    let dir = root.join("setup");
1095    ensure_private_dir(&dir)?;
1096    Ok(dir.join(SETUP_SAMPLE_FILE_NAME))
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101    use super::*;
1102    use std::sync::atomic::{AtomicU64, Ordering};
1103    use std::time::SystemTime;
1104
1105    static NEXT_TEMP_FIXTURE_ID: AtomicU64 = AtomicU64::new(0);
1106
1107    fn rendered_markdown_html(markdown: &str) -> String {
1108        let rendered = markdown_to_html(markdown, 0, &BTreeSet::new());
1109        rendered
1110            .finish(rendered.raw_html().to_string())
1111            .expect("unsanitized renderer should preserve its unique placeholders")
1112    }
1113
1114    #[test]
1115    fn temp_output_stem_replaces_shell_metacharacters() {
1116        let input = unique_temp_input("a&calc&.md");
1117        let output = temp_output_for(&input).expect("temp path should be built");
1118        let file_name = output
1119            .file_name()
1120            .and_then(|s| s.to_str())
1121            .expect("temp path should end with unicode filename");
1122
1123        assert_eq!(file_name, "a_calc_.html");
1124        assert!(!file_name.contains('&'));
1125
1126        cleanup_temp_fixture(&input, &output);
1127    }
1128
1129    #[test]
1130    fn temp_output_stem_keeps_readable_normal_names() {
1131        let input = unique_temp_input("résumé-draft_2026.md");
1132        let output = temp_output_for(&input).expect("temp path should be built");
1133        let file_name = output
1134            .file_name()
1135            .and_then(|s| s.to_str())
1136            .expect("temp path should end with unicode filename");
1137
1138        assert_eq!(file_name, "résumé-draft_2026.html");
1139
1140        cleanup_temp_fixture(&input, &output);
1141    }
1142
1143    fn unique_temp_input(file_name: &str) -> PathBuf {
1144        let nonce = SystemTime::now()
1145            .duration_since(UNIX_EPOCH)
1146            .expect("system time should be after epoch")
1147            .as_nanos();
1148        let counter = NEXT_TEMP_FIXTURE_ID.fetch_add(1, Ordering::Relaxed);
1149        let dir = std::env::temp_dir().join(format!(
1150            "mdo-unit-test-{}-{nonce}-{counter}",
1151            std::process::id()
1152        ));
1153        fs::create_dir_all(&dir).expect("test temp dir should be created");
1154        let input = dir.join(file_name);
1155        fs::write(&input, "# Test\n").expect("test input should be written");
1156        input
1157    }
1158
1159    fn cleanup_temp_fixture(input: &Path, output: &Path) {
1160        if let Some(parent) = output.parent() {
1161            let _ = fs::remove_dir_all(parent);
1162        }
1163        if let Some(parent) = input.parent() {
1164            let _ = fs::remove_dir_all(parent);
1165        }
1166    }
1167
1168    #[test]
1169    fn formats_unix_timestamps_as_machine_utc_datetimes() {
1170        assert_eq!(utc_datetime_from_unix_secs(0), "1970-01-01T00:00:00Z");
1171        assert_eq!(
1172            utc_datetime_from_unix_secs(951_827_696),
1173            "2000-02-29T12:34:56Z"
1174        );
1175    }
1176
1177    #[test]
1178    fn formats_unix_timestamps_as_readable_utc_datetimes() {
1179        // Midnight and noon exercise the 12-hour AM/PM edge cases.
1180        assert_eq!(
1181            human_utc_datetime_from_unix_secs(0),
1182            "January 1, 1970, 12:00 AM UTC"
1183        );
1184        assert_eq!(
1185            human_utc_datetime_from_unix_secs(951_827_696),
1186            "February 29, 2000, 12:34 PM UTC"
1187        );
1188        assert_eq!(
1189            human_utc_datetime_from_unix_secs(13 * 3_600 + 5 * 60),
1190            "January 1, 1970, 1:05 PM UTC"
1191        );
1192    }
1193
1194    #[test]
1195    fn wrap_html5_keeps_generator_meta_without_visible_branding() {
1196        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(0));
1197
1198        assert!(html.contains(&format!(
1199            "<meta name=\"generator\" content=\"mdo {APP_VERSION}\">"
1200        )));
1201        assert!(!html.contains("Generated by"));
1202        assert!(!html.contains("mdo-generated"));
1203    }
1204
1205    #[test]
1206    fn wrap_html5_shows_source_modified_time_with_machine_datetime() {
1207        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(951_827_696));
1208
1209        assert!(html.contains(
1210            "<footer class=\"mdo-source-meta\">Source modified: \
1211             <time datetime=\"2000-02-29T12:34:56Z\">February 29, 2000, 12:34 PM UTC</time></footer>"
1212        ));
1213    }
1214
1215    #[test]
1216    fn wrap_html5_renders_without_source_modified_time() {
1217        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
1218
1219        assert!(html.contains("<main>\n<p>hi</p>\n</main>"));
1220        assert!(!html.contains("Source modified"));
1221        assert!(!html.contains("<footer"));
1222    }
1223
1224    #[test]
1225    fn in_memory_render_uses_shared_safe_document_pipeline() {
1226        let html = render_markdown_document(
1227            "# Phone note\n\nHello **Android**.\n\n<script>alert('no')</script>",
1228            "fallback.md",
1229            None,
1230        );
1231
1232        assert!(html.contains("<title>Phone note</title>"));
1233        assert!(html.contains("<strong>Android</strong>"));
1234        assert!(html.contains("<meta name=\"generator\" content=\"mdo "));
1235        assert!(!html.contains("<script>alert('no')</script>"));
1236    }
1237
1238    #[test]
1239    fn markdown_extensions_keep_their_existing_html() {
1240        let markdown = "~~gone~~\n\n\
1241                        | A | B |\n\
1242                        | - | - |\n\
1243                        | 1 | 2 |\n\n\
1244                        Footnote[^one].\n\n\
1245                        [^one]: Detail\n\n\
1246                        - [x] done\n\
1247                        - [ ] later\n";
1248        let expected = "<p><del>gone</del></p>\n\
1249                        <table><thead><tr><th>A</th><th>B</th></tr></thead><tbody>\n\
1250                        <tr><td>1</td><td>2</td></tr>\n\
1251                        </tbody></table>\n\
1252                        <p>Footnote<sup class=\"footnote-reference\"><a href=\"#one\">1</a></sup>.</p>\n\
1253                        <div class=\"footnote-definition\" id=\"one\"><sup class=\"footnote-definition-label\">1</sup>\n\
1254                        <p>Detail</p>\n\
1255                        </div>\n\
1256                        <ul>\n\
1257                        <li><input disabled=\"\" type=\"checkbox\" checked=\"\"/>\n\
1258                        done</li>\n\
1259                        <li><input disabled=\"\" type=\"checkbox\"/>\n\
1260                        later</li>\n\
1261                        </ul>\n";
1262
1263        assert_eq!(rendered_markdown_html(markdown), expected);
1264    }
1265
1266    #[test]
1267    fn gfm_alerts_render_all_supported_classes_and_survive_sanitizing() {
1268        for kind in ["note", "tip", "important", "warning", "caution"] {
1269            let markdown = format!("> [!{}]\n> Alert text\n", kind.to_uppercase());
1270            let raw = rendered_markdown_html(&markdown);
1271            let class = format!("class=\"markdown-alert-{kind}\"");
1272
1273            assert!(raw.contains(&class), "{raw}");
1274            assert!(!raw.contains("[!"), "{raw}");
1275            assert!(sanitize_html(&raw).contains(&class), "{raw}");
1276        }
1277    }
1278
1279    #[test]
1280    fn wrapped_document_styles_alerts_in_light_and_dark_palettes() {
1281        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
1282
1283        // No-JS defaults: plain :root plus an OS dark-mode media query, so
1284        // alerts stay styled when the theme-toggle script never runs.
1285        assert!(html.contains("\n:root{--alert-note:"));
1286        assert!(html.contains("@media (prefers-color-scheme: dark){:root{--alert-note:"));
1287        // Manual theme-toggle overrides.
1288        assert!(html.contains(":root[data-theme=\"light\"]{--alert-note:"));
1289        assert!(html.contains(":root[data-theme=\"dark\"]{--alert-note:"));
1290        for kind in ["note", "tip", "important", "warning", "caution"] {
1291            assert!(html.contains(&format!("blockquote.markdown-alert-{kind}")));
1292        }
1293    }
1294
1295    #[test]
1296    fn yaml_front_matter_is_hidden_and_supplies_document_title() {
1297        let markdown =
1298            "---\ntitle: 'Front Matter Title'\nauthor: Example\n...\n\n# Heading Title\n";
1299        let body = rendered_markdown_html(markdown);
1300
1301        assert_eq!(body, "<h1>Heading Title</h1>\n");
1302        assert_eq!(derive_title(markdown, "fallback"), "Front Matter Title");
1303
1304        let document = render_markdown_document(markdown, "fallback", None);
1305        assert!(document.contains("<title>Front Matter Title</title>"));
1306        assert!(!document.contains("author: Example"));
1307    }
1308
1309    #[test]
1310    fn mid_document_metadata_style_blocks_are_rendered_not_swallowed() {
1311        let markdown = "# Top\n\nintro\n\n---\nnot a heading\n---\n\ntail\n";
1312        let html = rendered_markdown_html(markdown);
1313
1314        assert!(html.contains("not a heading"), "{html}");
1315        assert!(html.contains("tail"), "{html}");
1316        assert_eq!(derive_title(markdown, "fallback"), "Top");
1317    }
1318
1319    #[test]
1320    fn blank_first_line_block_is_not_front_matter() {
1321        // GitHub and pulldown-cmark reject metadata blocks whose first content
1322        // line is blank; accepting one here would hide visible text and let it
1323        // spoof the page title.
1324        let markdown = "---\n\ntitle: fake\n---\n\n# Real Heading\n";
1325        let html = rendered_markdown_html(markdown);
1326
1327        assert!(html.contains("title: fake"), "{html}");
1328        assert_eq!(derive_title(markdown, "fallback"), "Real Heading");
1329
1330        // An empty block is likewise not front matter.
1331        assert!(yaml_front_matter("---\n---\n# Heading\n").is_none());
1332    }
1333
1334    #[test]
1335    fn front_matter_title_supports_colons_and_double_quotes() {
1336        let markdown = "---\ntitle: \"Project: Alpha\"\n---\n\n# Heading\n";
1337        assert_eq!(derive_title(markdown, "fallback"), "Project: Alpha");
1338    }
1339
1340    #[test]
1341    fn missing_empty_or_unclosed_front_matter_title_uses_existing_fallbacks() {
1342        assert_eq!(
1343            derive_title("---\nauthor: Example\n---\n\n# Heading\n", "fallback"),
1344            "Heading"
1345        );
1346        assert_eq!(
1347            derive_title("---\ntitle: \n---\n", "Fallback Title"),
1348            "Fallback Title"
1349        );
1350        assert_eq!(
1351            derive_title("---\ntitle: Incomplete\n# Real Heading\n", "fallback"),
1352            "Real Heading"
1353        );
1354        assert_eq!(
1355            derive_title(
1356                "---\ndescription: |\n# Metadata, not a heading\n---\n\n# Real Heading\n",
1357                "fallback"
1358            ),
1359            "Real Heading"
1360        );
1361    }
1362
1363    #[test]
1364    fn smart_punctuation_is_not_enabled() {
1365        let html = rendered_markdown_html("-- --- ... \"straight\" 'quotes'\n");
1366
1367        assert_eq!(html, "<p>-- --- ... \"straight\" 'quotes'</p>\n");
1368        assert!(!html.contains(['–', '—', '…', '“', '”', '‘', '’']));
1369    }
1370
1371    #[test]
1372    fn recognized_fences_are_highlighted_with_both_theme_palettes() {
1373        let markdown = "```rust\nfn main() { let html = \"<script>x</script>\"; }\n```\n";
1374        let html = render_markdown_document(markdown, "fallback", None);
1375
1376        assert!(html.contains(
1377            "<pre class=\"mdo-highlight mdo-syntect-code\"><code class=\"language-rust\">"
1378        ));
1379        assert!(html.contains("mdo-syntect-keyword"), "{html}");
1380        assert!(html.contains(":root[data-theme=\"light\"] .mdo-syntect-code"));
1381        assert!(html.contains(":root[data-theme=\"dark\"] .mdo-syntect-code"));
1382        assert!(!html.contains("<script>x</script>"));
1383        assert!(html.contains("&lt;script&gt;"));
1384    }
1385
1386    #[test]
1387    fn unknown_fences_remain_plain_and_do_not_add_theme_css() {
1388        let markdown = "```not-a-real-language\n<unsafe> & plain\n```\n";
1389        let html = render_markdown_document(markdown, "fallback", None);
1390
1391        assert!(html.contains(
1392            "<pre><code class=\"language-not-a-real-language\">&lt;unsafe&gt; &amp; plain\n</code></pre>"
1393        ));
1394        assert!(!html.contains("mdo-highlight"));
1395        assert!(!html.contains("Syntax highlighting generated by syntect"));
1396    }
1397
1398    #[test]
1399    fn pages_without_code_do_not_add_highlight_css() {
1400        let html = render_markdown_document("# Just prose\n", "fallback", None);
1401        assert!(!html.contains("Syntax highlighting generated by syntect"));
1402        assert!(!html.contains("mdo-syntect-"));
1403
1404        let unlabeled = render_markdown_document("```\nplain code\n```\n", "fallback", None);
1405        assert!(unlabeled.contains("<pre><code>plain code\n</code></pre>"));
1406        assert!(!unlabeled.contains("Syntax highlighting generated by syntect"));
1407    }
1408
1409    #[test]
1410    fn literal_placeholder_spoof_does_not_capture_generated_markup() {
1411        let spoof = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
1412        let markdown = format!("`{spoof}`\n\n```rust\nlet answer = 42;\n```\n");
1413        let html = render_markdown_document(&markdown, "fallback", None);
1414
1415        assert!(html.contains(spoof));
1416        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
1417        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
1418    }
1419
1420    #[test]
1421    fn entity_normalized_placeholder_spoof_cannot_capture_generated_markup() {
1422        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
1423        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
1424        let markdown = format!("{encoded}\n\n```rust\nlet answer = 42;\n```\n");
1425        let html = render_markdown_document(&markdown, "fallback", None);
1426
1427        assert!(html.contains(normalized), "{html}");
1428        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
1429        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
1430    }
1431
1432    #[test]
1433    fn attribute_normalized_placeholder_cannot_receive_generated_markup() {
1434        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
1435        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
1436        let markdown = format!(
1437            "<span title=\"{encoded}\">probe</span>\n\n```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n"
1438        );
1439        let html = render_markdown_document(&markdown, "fallback", None);
1440
1441        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
1442        assert!(!html.contains("title=\"<pre"), "{html}");
1443        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
1444        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
1445        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_1__"));
1446    }
1447
1448    #[test]
1449    fn normalized_spoof_cannot_mask_a_sanitizer_destroyed_placeholder() {
1450        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
1451        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
1452        let markdown = format!(
1453            "<span title=\"{encoded}\">probe</span>\n\n<style>\n\n```rust\nfn main() {{}}\n```\n"
1454        );
1455        let html = render_markdown_document(&markdown, "fallback", None);
1456
1457        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
1458        assert!(!html.contains("title=\"<pre"), "{html}");
1459        assert!(!html.contains("<pre class=\"mdo-highlight "), "{html}");
1460        assert!(!html.contains("<code class=\"language-rust\""), "{html}");
1461    }
1462
1463    #[test]
1464    fn unclosed_style_before_fence_terminates_without_post_sanitize_splice() {
1465        // Inline `<style>` never closes, so ammonia swallows and strips all
1466        // subsequent markup. Highlight splicing happens before that single
1467        // sanitizer pass, so this terminates without a placeholder retry.
1468        let markdown = "before <style> after\n\n```rust\nfn main() {}\n```\n";
1469        let html = render_markdown_document(markdown, "fallback", None);
1470
1471        assert!(html.contains("before"));
1472        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
1473        assert!(!html.contains("mdo-highlight"));
1474    }
1475
1476    #[test]
1477    fn unclosed_script_before_fence_terminates_without_post_sanitize_splice() {
1478        let markdown = "before <script> after\n\n```rust\nfn main() {}\n```\n";
1479        let html = render_markdown_document(markdown, "fallback", None);
1480
1481        assert!(html.contains("before"));
1482        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
1483        assert!(!html.contains("mdo-highlight"));
1484    }
1485
1486    #[test]
1487    fn sanitizer_drops_only_highlight_markup_after_unclosed_style() {
1488        // The first fence precedes the unclosed <style>, so its generated
1489        // markup survives sanitization. Only the second fence is swallowed.
1490        let markdown =
1491            "```rust\nlet first = 1;\n```\n\ntext <style> text\n\n```rust\nlet second = 2;\n```\n";
1492        let html = render_markdown_document(markdown, "fallback", None);
1493
1494        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
1495        assert!(html.contains("let"), "{html}");
1496        assert!(html.contains("first"), "{html}");
1497        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
1498    }
1499
1500    #[test]
1501    fn multiple_highlighted_blocks_splice_once_each() {
1502        let markdown = "```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n";
1503        let html = render_markdown_document(markdown, "fallback", None);
1504
1505        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
1506        assert!(html.contains("language-rust"));
1507        assert!(html.contains("language-python"));
1508        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
1509    }
1510
1511    #[test]
1512    fn raw_user_html_still_crosses_the_ammonia_boundary() {
1513        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";
1514        let html = render_markdown_document(markdown, "fallback", None);
1515
1516        assert!(!html.contains("onclick=\"alert(1)\""));
1517        assert!(!html.contains("<script>bad()</script>"));
1518        assert!(html.contains(">user</span>"));
1519        assert!(!html.contains("<b>code</b>"));
1520        assert!(html.contains("&lt;b&gt;"));
1521    }
1522
1523    #[test]
1524    fn title_can_come_from_raw_html_h1() {
1525        let title = derive_title(
1526            r#"<section><h1 class="hero-title">Project <span>Home</span></h1></section>"#,
1527            "fallback",
1528        );
1529
1530        assert_eq!(title, "Project Home");
1531    }
1532
1533    #[test]
1534    fn derive_title_ignores_headings_in_code_fences() {
1535        let markdown = "```sh\n# not a title\n```\n\n# Real Title\n";
1536        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
1537    }
1538
1539    #[test]
1540    fn derive_title_falls_back_when_only_heading_is_fenced() {
1541        let markdown = "~~~\n# fenced heading\n~~~\n";
1542        assert_eq!(derive_title(markdown, "Fallback Title"), "Fallback Title");
1543    }
1544
1545    #[test]
1546    fn derive_title_ignores_raw_html_h1_inside_code_fence() {
1547        let markdown = "```html\n<h1>Not the title</h1>\n```\n\n# Real Title\n";
1548        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
1549    }
1550
1551    #[test]
1552    fn css_override_escapes_style_end_tags() {
1553        let escaped = escape_style_end_tags("h1{} </STYLE><script>alert(1)</script>");
1554
1555        assert!(escaped.contains("<\\/style><script>"));
1556        assert!(!escaped.to_ascii_lowercase().contains("</style><script>"));
1557    }
1558
1559    // Unix-rooted paths like `/home/user/...` are NOT absolute on Windows
1560    // (no drive or UNC prefix), so `Url::from_directory_path` rejects them
1561    // there — every test using such a path must be `#[cfg(unix)]`-gated or
1562    // it panics under the Windows CI test job. Windows path forms get their
1563    // own `#[cfg(windows)]` tests below.
1564    #[cfg(unix)]
1565    #[test]
1566    fn dir_to_file_url_adds_trailing_slash() {
1567        let url =
1568            dir_to_file_url(Path::new("/home/user/docs")).expect("absolute path should convert");
1569        assert!(url.ends_with('/'));
1570        assert_eq!(url, "file:///home/user/docs/");
1571    }
1572
1573    #[cfg(unix)]
1574    #[test]
1575    fn dir_to_file_url_encodes_spaces() {
1576        let url = dir_to_file_url(Path::new("/home/user/my docs")).expect("should convert");
1577        assert_eq!(url, "file:///home/user/my%20docs/");
1578    }
1579
1580    // `#` is a legal Windows filename character but is not exercised there
1581    // because these are pure-path conversions, not filesystem operations —
1582    // gating still keeps the Windows suite focused on Windows-specific forms
1583    // (drive letters, UNC, `\\?\`) covered below.
1584    #[cfg(unix)]
1585    #[test]
1586    fn dir_to_file_url_encodes_hash() {
1587        let url = dir_to_file_url(Path::new("/home/user/docs#1")).expect("should convert");
1588        assert_eq!(url, "file:///home/user/docs%231/");
1589    }
1590
1591    #[cfg(unix)]
1592    #[test]
1593    fn dir_to_file_url_encodes_percent() {
1594        let url = dir_to_file_url(Path::new("/home/user/50%done")).expect("should convert");
1595        assert_eq!(url, "file:///home/user/50%25done/");
1596    }
1597
1598    // `?` is invalid in Windows filenames, so this case can't arise there.
1599    #[cfg(unix)]
1600    #[test]
1601    fn dir_to_file_url_encodes_question_mark() {
1602        let url = dir_to_file_url(Path::new("/home/user/docs?draft")).expect("should convert");
1603        assert_eq!(url, "file:///home/user/docs%3Fdraft/");
1604    }
1605
1606    #[cfg(unix)]
1607    #[test]
1608    fn dir_to_file_url_encodes_unicode_accented() {
1609        let url = dir_to_file_url(Path::new("/home/user/résumé")).expect("should convert");
1610        assert_eq!(url, "file:///home/user/r%C3%A9sum%C3%A9/");
1611    }
1612
1613    #[cfg(unix)]
1614    #[test]
1615    fn dir_to_file_url_encodes_unicode_cjk() {
1616        let url = dir_to_file_url(Path::new("/home/user/日本語")).expect("should convert");
1617        assert_eq!(url, "file:///home/user/%E6%97%A5%E6%9C%AC%E8%AA%9E/");
1618    }
1619
1620    #[test]
1621    fn dir_to_file_url_returns_none_for_relative_path() {
1622        assert_eq!(dir_to_file_url(Path::new("relative/dir")), None);
1623    }
1624
1625    #[cfg(windows)]
1626    #[test]
1627    fn dir_to_file_url_windows_drive_letter() {
1628        let url = dir_to_file_url(Path::new(r"C:\foo\bar")).expect("should convert");
1629        assert_eq!(url, "file:///C:/foo/bar/");
1630    }
1631
1632    #[cfg(windows)]
1633    #[test]
1634    fn dir_to_file_url_windows_drive_letter_with_space() {
1635        let url = dir_to_file_url(Path::new(r"C:\Program Files\mdo")).expect("should convert");
1636        assert_eq!(url, "file:///C:/Program%20Files/mdo/");
1637    }
1638
1639    // `fs::canonicalize` on Windows produces the `\\?\` extended-length
1640    // prefix; browsers don't understand `file:////?/C:/...`, so this must
1641    // normalize to the same form as the plain drive-letter case.
1642    #[cfg(windows)]
1643    #[test]
1644    fn dir_to_file_url_windows_extended_length_prefix() {
1645        let url = dir_to_file_url(Path::new(r"\\?\C:\foo\bar")).expect("should convert");
1646        assert_eq!(url, "file:///C:/foo/bar/");
1647    }
1648
1649    #[cfg(windows)]
1650    #[test]
1651    fn dir_to_file_url_windows_unc_path() {
1652        let url = dir_to_file_url(Path::new(r"\\server\share\dir")).expect("should convert");
1653        assert_eq!(url, "file://server/share/dir/");
1654    }
1655
1656    #[test]
1657    fn setup_sample_contains_welcome_copy() {
1658        assert!(SETUP_SAMPLE_MARKDOWN.contains("# Welcome to the world of Open as HTML with mdo"));
1659        assert!(SETUP_SAMPLE_MARKDOWN.contains("opened it successfully"));
1660        assert_eq!(
1661            SETUP_SAMPLE_FILE_NAME,
1662            "welcome-to-open-as-html-with-mdo.md"
1663        );
1664    }
1665}