mdo-cli 0.6.2

A simple Rust CLI to convert Markdown to HTML5 (styled with simple.css), with optional file watching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
//! Render pipeline: the path from Markdown source to an HTML fragment -
//! parsing, syntax-highlight splicing, sanitizing, title derivation, in
//! that order, sanitized once, after splicing - plus the single deep
//! workflow entry point (convert) that reads the source, renders, and
//! writes the page with per-worker private-output safeguards.

use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::io;
#[cfg(unix)]
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

#[cfg(unix)]
use std::fs::OpenOptions;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;

use pulldown_cmark::Options;
use url::Url;

use crate::highlight;
use crate::page::{source_modified_unix_secs, wrap_html5};

/// Build a `file://` URL for a directory, suitable for use as `<base href>`.
///
/// Delegates to [`Url::from_directory_path`], which correctly
/// percent-encodes reserved and non-ASCII characters (spaces, `#`, `%`, `?`,
/// Unicode, …) and handles Windows drive letters, UNC paths, and the
/// `\\?\`/`\\?\UNC\` extended-length prefixes that `fs::canonicalize`
/// produces — a hand-rolled string transform got all of this subtly wrong
/// (e.g. a literal `#` in a directory name would truncate the URL when a
/// browser parsed it as a fragment). Always includes a trailing slash so
/// relative refs resolve correctly against the directory.
///
/// Returns `None` if `dir` can't be represented as a `file://` URL (notably:
/// relative paths). Callers should fall back to omitting the `<base href>`
/// tag entirely rather than emit a broken URL.
fn dir_to_file_url(dir: &Path) -> Option<String> {
    Url::from_directory_path(dir)
        .ok()
        .map(|url| url.to_string())
}

fn markdown_options() -> Options {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_GFM);

    options
}

fn markdown_to_html(
    markdown: &str,
    placeholder_discriminator: u64,
    plain_fences: &BTreeSet<usize>,
) -> highlight::RenderedMarkdown {
    // Front matter is stripped here, before parsing, by the same
    // `yaml_front_matter` splitter that title derivation uses, so one set of
    // acceptance rules governs both. Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
    // is deliberately NOT enabled: pulldown-cmark 0.13 recognizes metadata
    // blocks anywhere at indent 0, not just at document start, which silently
    // swallows mid-document text framed by `---` lines.
    let markdown = yaml_front_matter(markdown)
        .map(|(_, body)| body)
        .unwrap_or(markdown);

    highlight::render(
        markdown,
        markdown_options(),
        placeholder_discriminator,
        plain_fences,
    )
}

/// Upper bound on placeholder-collision retries. A collision requires
/// document text that normalizes into the current placeholder token, so more
/// than a couple of retries only happens with adversarial input; past the cap
/// the document renders with highlighting disabled rather than looping.
const MAX_PLACEHOLDER_RETRIES: u32 = 16;

/// Shared render/process/splice loop behind [`safe_markdown_body`] and
/// [`convert`].
///
/// Highlighted spans are generated by mdo from escaped code text and spliced
/// into the raw renderer output only after all placeholders have been
/// validated. `process` (usually ammonia) then handles the completed document,
/// including generated markup, so no string insertion happens beyond the
/// sanitizer boundary. The loop is guaranteed to terminate:
///
/// - a destroyed placeholder can never survive under any discriminator, so
///   its fence is added to the strictly growing `plain_fences` set and
///   rendered as an ordinary escaped code block instead;
/// - collisions retry with a fresh discriminator at most
///   [`MAX_PLACEHOLDER_RETRIES`] times, after which every fence is rendered
///   plain, leaving nothing to splice.
fn spliced_markdown_body(
    markdown: &str,
    mut render: impl FnMut(&str, u64, &BTreeSet<usize>) -> highlight::RenderedMarkdown,
    mut process: impl FnMut(&str) -> String,
) -> (String, Option<&'static str>) {
    let mut discriminator = 0_u64;
    let mut collision_retries = 0_u32;
    let mut plain_fences = BTreeSet::new();

    loop {
        let rendered = render(markdown, discriminator, &plain_fences);
        match rendered.finish(rendered.raw_html().to_string()) {
            Ok(body) => return (process(&body), rendered.css()),
            Err(highlight::SpliceError::Destroyed(fences)) => {
                plain_fences.extend(fences);
            }
            Err(highlight::SpliceError::Collision) => {
                collision_retries += 1;
                if collision_retries > MAX_PLACEHOLDER_RETRIES {
                    plain_fences.extend(0..rendered.fence_count());
                }
                discriminator += 1;
            }
        }
    }
}

/// Render and sanitize Markdown, splicing generated highlighting before the
/// completed document crosses the sanitizer boundary.
fn safe_markdown_body(markdown: &str) -> (String, Option<&'static str>) {
    spliced_markdown_body(markdown, markdown_to_html, sanitize_html)
}

fn sanitize_html(html: &str) -> String {
    ammonia::Builder::default()
        // The global "class" allowance is intentional: user-authored class
        // names are inert here because classes only select styles from mdo's
        // own generated stylesheet. Highlight safety does not rest on this
        // allowlist either: highlighted markup is generated from escaped code
        // text, spliced before sanitization, and then cleaned with the rest of
        // the document.
        .add_generic_attributes(&["class", "id"])
        .add_tags(&["input"])
        .add_tag_attributes("input", &["checked", "type"])
        .add_tag_attribute_values("input", "checked", &[""])
        .add_tag_attribute_values("input", "type", &["checkbox"])
        .set_tag_attribute_value("input", "disabled", "")
        .clean(html)
        .to_string()
}

/// Render Markdown supplied in memory as a complete, self-contained HTML page.
///
/// This is the platform-neutral entry point used by the Android application.
/// Raw HTML is always sanitized, matching the safe default of the desktop CLI.
/// `fallback_title` is used only when the document has no top-level heading.
pub fn render_markdown_document(
    markdown: &str,
    fallback_title: &str,
    source_modified_unix_secs: Option<u64>,
) -> String {
    let (body, highlight_css) = safe_markdown_body(markdown);
    let title = derive_title(markdown, fallback_title);
    wrap_html5(
        &body,
        &title,
        None,
        None,
        highlight_css,
        source_modified_unix_secs,
    )
}

fn derive_title(markdown: &str, fallback: &str) -> String {
    if let Some(title) = front_matter_title(markdown) {
        return title;
    }

    // A valid metadata block is not document content. Exclude it from the
    // existing H1 search even when it has no usable title key.
    let markdown = yaml_front_matter(markdown)
        .map(|(_, document)| document)
        .unwrap_or(markdown);

    // Strip fenced code blocks first so a heading — whether an ATX `# ` line or
    // a raw <h1> — inside a ``` or ~~~ block is never mistaken for the title.
    let without_fences = strip_code_fences(markdown);
    for line in without_fences.lines() {
        let trimmed = line.trim_start();
        if let Some(rest) = trimmed.trim_end().strip_prefix("# ") {
            return rest.trim().to_string();
        }
    }
    if let Some(title) = derive_raw_html_h1_title(&without_fences) {
        return title;
    }
    fallback.to_string()
}

/// Extract a simple scalar `title:` from a complete YAML-style metadata block
/// at the start of the document.
///
/// pulldown-cmark deliberately recognizes the block delimiters without
/// interpreting YAML. mdo follows that narrow behavior: it reads only an
/// unindented `title` key and does not add a general-purpose YAML parser (and
/// its dependency/security surface) merely to title the generated page.
fn front_matter_title(markdown: &str) -> Option<String> {
    let (metadata, _) = yaml_front_matter(markdown)?;
    let mut title = None;
    for line in metadata.lines() {
        if line.starts_with(char::is_whitespace) {
            continue;
        }
        if let Some((key, value)) = line.split_once(':') {
            if key == "title" {
                let value = unquote_front_matter_scalar(value.trim());
                if !value.is_empty() {
                    title = Some(value.to_string());
                }
            }
        }
    }

    title
}

/// Split a complete YAML-style metadata block from the document body. The
/// returned metadata excludes delimiters.
///
/// This splitter is the single source of truth for front-matter recognition
/// (both hiding the block from rendered output and title extraction), and its
/// acceptance rules are deliberately conservative and GitHub-like:
///
/// - the opening `---` must be the very first line of the document;
/// - the closing delimiter is `---` or `...` on its own line — trailing
///   spaces are allowed but tabs are not;
/// - the block must be non-empty and its first line must not be blank.
///   GitHub and pulldown-cmark both reject blocks whose first content line is
///   blank, so treating them as front matter here would hide visible content
///   and let e.g. `---\n\ntitle: fake\n---` spoof the page title.
fn yaml_front_matter(markdown: &str) -> Option<(&str, &str)> {
    fn delimiter(line: &str) -> Option<&str> {
        let line = line.trim_end_matches(['\r', '\n']).trim_end_matches(' ');
        (line == "---" || line == "...").then_some(line)
    }

    let first_line_end = markdown.find('\n').unwrap_or(markdown.len());
    if delimiter(&markdown[..first_line_end]) != Some("---") || first_line_end == markdown.len() {
        return None;
    }

    let metadata_start = first_line_end + 1;
    let remainder = &markdown[metadata_start..];
    let mut consumed = 0;
    // split_inclusive also yields a final segment without a trailing newline,
    // so a closing delimiter at end-of-input is found by the loop as well.
    for segment in remainder.split_inclusive('\n') {
        if delimiter(segment).is_some() {
            let metadata = &remainder[..consumed];
            let first_content_line = metadata.lines().next()?;
            if first_content_line.trim().is_empty() {
                return None;
            }
            return Some((metadata, &remainder[consumed + segment.len()..]));
        }
        consumed += segment.len();
    }

    None
}

fn unquote_front_matter_scalar(value: &str) -> &str {
    if value.len() < 2 {
        return value;
    }

    let bytes = value.as_bytes();
    if matches!(
        (bytes[0], bytes[value.len() - 1]),
        (b'\'', b'\'') | (b'"', b'"')
    ) {
        &value[1..value.len() - 1]
    } else {
        value
    }
}

/// Return `markdown` with fenced code blocks (``` or ~~~) removed, so title
/// detection never reads inside code samples.
fn strip_code_fences(markdown: &str) -> String {
    let mut out = String::with_capacity(markdown.len());
    let mut fence: Option<char> = None;
    for line in markdown.lines() {
        if let Some(marker) = code_fence_marker(line.trim_start()) {
            match fence {
                Some(open) if open == marker => fence = None,
                Some(_) => {}
                None => fence = Some(marker),
            }
            continue;
        }
        if fence.is_some() {
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// Detect a code-fence line, returning its marker char when the line starts
/// with at least three backticks or tildes. This is a pragmatic subset of
/// CommonMark (it does not bound the indent or require the closing fence to be
/// at least as long), which is sufficient for title detection.
fn code_fence_marker(trimmed_start: &str) -> Option<char> {
    if trimmed_start.starts_with("```") {
        Some('`')
    } else if trimmed_start.starts_with("~~~") {
        Some('~')
    } else {
        None
    }
}

fn derive_raw_html_h1_title(markdown: &str) -> Option<String> {
    let lower = markdown.to_ascii_lowercase();
    let mut search_start = 0;

    while let Some(offset) = lower[search_start..].find("<h1") {
        let start = search_start + offset;
        let after_tag_name = start + 3;
        let next = lower.as_bytes().get(after_tag_name).copied();
        if !matches!(
            next,
            Some(b'>') | Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')
        ) {
            search_start = after_tag_name;
            continue;
        }

        let content_start = start + markdown[start..].find('>')? + 1;
        let content_end = content_start + lower[content_start..].find("</h1>")?;
        let title = strip_html_tags(&markdown[content_start..content_end])
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ");
        if !title.is_empty() {
            return Some(title);
        }

        search_start = content_end + 5;
    }

    None
}

fn strip_html_tags(input: &str) -> String {
    let mut output = String::with_capacity(input.len());
    let mut in_tag = false;

    for ch in input.chars() {
        match ch {
            '<' => in_tag = true,
            '>' if in_tag => in_tag = false,
            _ if !in_tag => output.push(ch),
            _ => {}
        }
    }

    output
}

/// Wall-clock time spent in each stage of one render workflow, plus the
/// workflow's total. Reported to stderr by the CLI's `--verbose` output.
/// Stages that do not run for a given invocation (`sanitize` under
/// `--unsafe-html`, `assemble` under `--bare`) report zero.
#[derive(Debug, Default)]
pub struct StageTimings {
    pub read: Duration,
    pub markdown: Duration,
    pub sanitize: Duration,
    pub assemble: Duration,
    pub write: Duration,
    /// Wall-clock time of the whole workflow, always at least the sum of
    /// the stages.
    pub total: Duration,
}

/// One render request for [`convert`]: a Markdown input, a destination, and
/// the render options. `verbose` is deliberately absent — diagnostics are
/// the caller's presentation concern, and [`ConvertOutcome::timings`]
/// carries everything a caller needs to print them.
#[derive(Debug)]
pub struct ConvertRequest<'a> {
    /// The Markdown source file.
    pub input: &'a Path,
    /// The HTML file to write; created when missing, overwritten when
    /// present.
    pub output: &'a Path,
    /// Emit only the HTML fragment (no `<html>`, `<head>`, `<body>`, no CSS).
    pub bare: bool,
    /// Preserve raw HTML from the Markdown source instead of sanitizing it.
    pub unsafe_html: bool,
    /// Write the output file readable only by the current user.
    pub private_output: bool,
    /// Custom CSS appended after mdo's default styling. Read from disk here
    /// and ignored under `bare`, because bare output emits no CSS.
    pub css_override: Option<&'a Path>,
}

/// What a successful [`convert`] wrote: the output file plus the workflow's
/// stage-by-stage timing record.
#[derive(Debug)]
pub struct ConvertOutcome {
    /// The output file that was written.
    pub output: PathBuf,
    /// Wall-clock timing record for the completed workflow.
    pub timings: StageTimings,
}

/// Why a [`convert`] workflow failed, typed per failure site with the
/// underlying `io::Error` and the path it concerns, so callers keep printing
/// their own messages instead of the library doing it for them.
#[derive(Debug)]
pub enum RenderError {
    /// Reading the Markdown input file failed.
    Read { path: PathBuf, source: io::Error },
    /// Reading the `--css` override file failed.
    ReadCssOverride { path: PathBuf, source: io::Error },
    /// Creating the output file's parent directory failed.
    CreateOutputDir { path: PathBuf, source: io::Error },
    /// Writing the rendered HTML file failed.
    Write { path: PathBuf, source: io::Error },
}

impl fmt::Display for RenderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (action, path, source) = match self {
            RenderError::Read { path, source } => ("failed to read", path, source),
            RenderError::ReadCssOverride { path, source } => {
                ("failed to read CSS override", path, source)
            }
            RenderError::CreateOutputDir { path, source } => ("failed to create", path, source),
            RenderError::Write { path, source } => ("failed to write", path, source),
        };
        write!(f, "{} {}: {}", action, path.display(), source)
    }
}

impl std::error::Error for RenderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(match self {
            RenderError::Read { source, .. }
            | RenderError::ReadCssOverride { source, .. }
            | RenderError::CreateOutputDir { source, .. }
            | RenderError::Write { source, .. } => source,
        })
    }
}

/// Render one Markdown file to HTML: the render pipeline's single deep
/// entry point.
///
/// The workflow: read the source (and any CSS override), render and splice
/// highlighting, sanitize (unless `unsafe_html`), assemble the page (unless
/// `bare`), create the output's parent directory when missing, then write
/// the file (O_NOFOLLOW, mode 0o600 under `private_output`). The workflow
/// prints nothing itself — success carries a [`ConvertOutcome`] with the
/// written file and timing record, failure a typed [`RenderError`] — so the
/// same workflow serves the CLI, the setup sample, and any other host, and
/// the generated HTML is byte-identical everywhere it is invoked from.
pub fn convert(request: ConvertRequest) -> Result<ConvertOutcome, RenderError> {
    let workflow_start = Instant::now();
    let mut timings = StageTimings::default();

    let stage_start = Instant::now();
    let markdown = fs::read_to_string(request.input).map_err(|source| RenderError::Read {
        path: request.input.to_path_buf(),
        source,
    })?;
    timings.read = stage_start.elapsed();

    let css_override = if request.bare {
        None
    } else {
        match request.css_override {
            Some(path) => {
                let stage_start = Instant::now();
                let css =
                    fs::read_to_string(path).map_err(|source| RenderError::ReadCssOverride {
                        path: path.to_path_buf(),
                        source,
                    })?;
                timings.read += stage_start.elapsed();
                Some(css)
            }
            None => None,
        }
    };

    // Same splice loop as `safe_markdown_body`, instrumented for the
    // outcome's timing record.
    let (body, highlight_css) = spliced_markdown_body(
        &markdown,
        |markdown, discriminator, plain_fences| {
            let stage_start = Instant::now();
            let rendered = markdown_to_html(markdown, discriminator, plain_fences);
            timings.markdown += stage_start.elapsed();
            rendered
        },
        |html| {
            if request.unsafe_html {
                html.to_string()
            } else {
                let sanitize_start = Instant::now();
                let sanitized = sanitize_html(html);
                timings.sanitize += sanitize_start.elapsed();
                sanitized
            }
        },
    );

    let final_html = if request.bare {
        body
    } else {
        let stage_start = Instant::now();
        let fallback = request
            .input
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Document");
        let title = derive_title(&markdown, fallback);

        // Only inject <base href> when the output lives in a different
        // directory from the source — otherwise relative refs already
        // resolve correctly and a base tag would just add noise.
        let base_href = match (
            fs::canonicalize(request.input)
                .ok()
                .and_then(|p| p.parent().map(Path::to_path_buf)),
            request
                .output
                .parent()
                .and_then(|p| fs::canonicalize(p).ok()),
        ) {
            (Some(in_dir), Some(out_dir)) if in_dir != out_dir => dir_to_file_url(&in_dir),
            _ => None,
        };

        let wrapped = wrap_html5(
            &body,
            &title,
            base_href.as_deref(),
            css_override.as_deref(),
            highlight_css,
            source_modified_unix_secs(request.input),
        );
        timings.assemble = stage_start.elapsed();
        wrapped
    };

    let stage_start = Instant::now();
    if let Some(parent) = request.output.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|source| RenderError::CreateOutputDir {
                path: parent.to_path_buf(),
                source,
            })?;
        }
    }

    write_output_file(request.output, &final_html, request.private_output).map_err(|source| {
        RenderError::Write {
            path: request.output.to_path_buf(),
            source,
        }
    })?;
    timings.write = stage_start.elapsed();
    timings.total = workflow_start.elapsed();

    Ok(ConvertOutcome {
        output: request.output.to_path_buf(),
        timings,
    })
}

#[cfg(unix)]
fn write_output_file(output: &Path, contents: &str, private_output: bool) -> io::Result<()> {
    let mut options = OpenOptions::new();
    options
        .write(true)
        .create(true)
        .truncate(true)
        .custom_flags(libc::O_NOFOLLOW);

    if private_output {
        options.mode(0o600);
    }

    let mut file = options.open(output)?;
    file.write_all(contents.as_bytes())
}

#[cfg(not(unix))]
fn write_output_file(output: &Path, contents: &str, _private_output: bool) -> io::Result<()> {
    fs::write(output, contents)
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    fn rendered_markdown_html(markdown: &str) -> String {
        let rendered = markdown_to_html(markdown, 0, &BTreeSet::new());
        rendered
            .finish(rendered.raw_html().to_string())
            .expect("unsanitized renderer should preserve its unique placeholders")
    }

    #[test]
    fn in_memory_render_uses_shared_safe_document_pipeline() {
        let html = render_markdown_document(
            "# Phone note\n\nHello **Android**.\n\n<script>alert('no')</script>",
            "fallback.md",
            None,
        );

        assert!(html.contains("<title>Phone note</title>"));
        assert!(html.contains("<strong>Android</strong>"));
        assert!(html.contains("<meta name=\"generator\" content=\"mdo "));
        assert!(!html.contains("<script>alert('no')</script>"));
    }

    #[test]
    fn markdown_extensions_keep_their_existing_html() {
        let markdown = "~~gone~~\n\n\
                        | A | B |\n\
                        | - | - |\n\
                        | 1 | 2 |\n\n\
                        Footnote[^one].\n\n\
                        [^one]: Detail\n\n\
                        - [x] done\n\
                        - [ ] later\n";
        let expected = "<p><del>gone</del></p>\n\
                        <table><thead><tr><th>A</th><th>B</th></tr></thead><tbody>\n\
                        <tr><td>1</td><td>2</td></tr>\n\
                        </tbody></table>\n\
                        <p>Footnote<sup class=\"footnote-reference\"><a href=\"#one\">1</a></sup>.</p>\n\
                        <div class=\"footnote-definition\" id=\"one\"><sup class=\"footnote-definition-label\">1</sup>\n\
                        <p>Detail</p>\n\
                        </div>\n\
                        <ul>\n\
                        <li><input disabled=\"\" type=\"checkbox\" checked=\"\"/>\n\
                        done</li>\n\
                        <li><input disabled=\"\" type=\"checkbox\"/>\n\
                        later</li>\n\
                        </ul>\n";

        assert_eq!(rendered_markdown_html(markdown), expected);
    }

    #[test]
    fn gfm_alerts_render_all_supported_classes_and_survive_sanitizing() {
        for kind in ["note", "tip", "important", "warning", "caution"] {
            let markdown = format!("> [!{}]\n> Alert text\n", kind.to_uppercase());
            let raw = rendered_markdown_html(&markdown);
            let class = format!("class=\"markdown-alert-{kind}\"");

            assert!(raw.contains(&class), "{raw}");
            assert!(!raw.contains("[!"), "{raw}");
            assert!(sanitize_html(&raw).contains(&class), "{raw}");
        }
    }

    #[test]
    fn yaml_front_matter_is_hidden_and_supplies_document_title() {
        let markdown =
            "---\ntitle: 'Front Matter Title'\nauthor: Example\n...\n\n# Heading Title\n";
        let body = rendered_markdown_html(markdown);

        assert_eq!(body, "<h1>Heading Title</h1>\n");
        assert_eq!(derive_title(markdown, "fallback"), "Front Matter Title");

        let document = render_markdown_document(markdown, "fallback", None);
        assert!(document.contains("<title>Front Matter Title</title>"));
        assert!(!document.contains("author: Example"));
    }

    #[test]
    fn mid_document_metadata_style_blocks_are_rendered_not_swallowed() {
        let markdown = "# Top\n\nintro\n\n---\nnot a heading\n---\n\ntail\n";
        let html = rendered_markdown_html(markdown);

        assert!(html.contains("not a heading"), "{html}");
        assert!(html.contains("tail"), "{html}");
        assert_eq!(derive_title(markdown, "fallback"), "Top");
    }

    #[test]
    fn blank_first_line_block_is_not_front_matter() {
        // GitHub and pulldown-cmark reject metadata blocks whose first content
        // line is blank; accepting one here would hide visible text and let it
        // spoof the page title.
        let markdown = "---\n\ntitle: fake\n---\n\n# Real Heading\n";
        let html = rendered_markdown_html(markdown);

        assert!(html.contains("title: fake"), "{html}");
        assert_eq!(derive_title(markdown, "fallback"), "Real Heading");

        // An empty block is likewise not front matter.
        assert!(yaml_front_matter("---\n---\n# Heading\n").is_none());
    }

    #[test]
    fn front_matter_title_supports_colons_and_double_quotes() {
        let markdown = "---\ntitle: \"Project: Alpha\"\n---\n\n# Heading\n";
        assert_eq!(derive_title(markdown, "fallback"), "Project: Alpha");
    }

    #[test]
    fn missing_empty_or_unclosed_front_matter_title_uses_existing_fallbacks() {
        assert_eq!(
            derive_title("---\nauthor: Example\n---\n\n# Heading\n", "fallback"),
            "Heading"
        );
        assert_eq!(
            derive_title("---\ntitle: \n---\n", "Fallback Title"),
            "Fallback Title"
        );
        assert_eq!(
            derive_title("---\ntitle: Incomplete\n# Real Heading\n", "fallback"),
            "Real Heading"
        );
        assert_eq!(
            derive_title(
                "---\ndescription: |\n# Metadata, not a heading\n---\n\n# Real Heading\n",
                "fallback"
            ),
            "Real Heading"
        );
    }

    #[test]
    fn smart_punctuation_is_not_enabled() {
        let html = rendered_markdown_html("-- --- ... \"straight\" 'quotes'\n");

        assert_eq!(html, "<p>-- --- ... \"straight\" 'quotes'</p>\n");
        assert!(!html.contains(['–', '—', '…', '“', '”', '‘', '’']));
    }

    #[test]
    fn recognized_fences_are_highlighted_with_both_theme_palettes() {
        let markdown = "```rust\nfn main() { let html = \"<script>x</script>\"; }\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert!(html.contains(
            "<pre class=\"mdo-highlight mdo-syntect-code\"><code class=\"language-rust\">"
        ));
        assert!(html.contains("mdo-syntect-keyword"), "{html}");
        assert!(html.contains(":root[data-theme=\"light\"] .mdo-syntect-code"));
        assert!(html.contains(":root[data-theme=\"dark\"] .mdo-syntect-code"));
        assert!(!html.contains("<script>x</script>"));
        assert!(html.contains("&lt;script&gt;"));
    }

    #[test]
    fn unknown_fences_remain_plain_and_do_not_add_theme_css() {
        let markdown = "```not-a-real-language\n<unsafe> & plain\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert!(html.contains(
            "<pre><code class=\"language-not-a-real-language\">&lt;unsafe&gt; &amp; plain\n</code></pre>"
        ));
        assert!(!html.contains("mdo-highlight"));
        assert!(!html.contains("Syntax highlighting generated by syntect"));
    }

    #[test]
    fn pages_without_code_do_not_add_highlight_css() {
        let html = render_markdown_document("# Just prose\n", "fallback", None);
        assert!(!html.contains("Syntax highlighting generated by syntect"));
        assert!(!html.contains("mdo-syntect-"));

        let unlabeled = render_markdown_document("```\nplain code\n```\n", "fallback", None);
        assert!(unlabeled.contains("<pre><code>plain code\n</code></pre>"));
        assert!(!unlabeled.contains("Syntax highlighting generated by syntect"));
    }

    #[test]
    fn literal_placeholder_spoof_does_not_capture_generated_markup() {
        let spoof = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
        let markdown = format!("`{spoof}`\n\n```rust\nlet answer = 42;\n```\n");
        let html = render_markdown_document(&markdown, "fallback", None);

        assert!(html.contains(spoof));
        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
    }

    #[test]
    fn entity_normalized_placeholder_spoof_cannot_capture_generated_markup() {
        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
        let markdown = format!("{encoded}\n\n```rust\nlet answer = 42;\n```\n");
        let html = render_markdown_document(&markdown, "fallback", None);

        assert!(html.contains(normalized), "{html}");
        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
    }

    #[test]
    fn attribute_normalized_placeholder_cannot_receive_generated_markup() {
        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
        let markdown = format!(
            "<span title=\"{encoded}\">probe</span>\n\n```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n"
        );
        let html = render_markdown_document(&markdown, "fallback", None);

        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
        assert!(!html.contains("title=\"<pre"), "{html}");
        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_0__"));
        assert!(!html.contains("__MDO_HIGHLIGHT_PLACEHOLDER_1_1__"));
    }

    #[test]
    fn normalized_spoof_cannot_mask_a_sanitizer_destroyed_placeholder() {
        let normalized = "__MDO_HIGHLIGHT_PLACEHOLDER_0_0__";
        let encoded = "&#95;&#95;MDO&#95;HIGHLIGHT&#95;PLACEHOLDER&#95;0&#95;0&#95;&#95;";
        let markdown = format!(
            "<span title=\"{encoded}\">probe</span>\n\n<style>\n\n```rust\nfn main() {{}}\n```\n"
        );
        let html = render_markdown_document(&markdown, "fallback", None);

        assert!(html.contains(&format!("title=\"{normalized}\"")), "{html}");
        assert!(!html.contains("title=\"<pre"), "{html}");
        assert!(!html.contains("<pre class=\"mdo-highlight "), "{html}");
        assert!(!html.contains("<code class=\"language-rust\""), "{html}");
    }

    #[test]
    fn unclosed_style_before_fence_terminates_without_post_sanitize_splice() {
        // Inline `<style>` never closes, so ammonia swallows and strips all
        // subsequent markup. Highlight splicing happens before that single
        // sanitizer pass, so this terminates without a placeholder retry.
        let markdown = "before <style> after\n\n```rust\nfn main() {}\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert!(html.contains("before"));
        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
        assert!(!html.contains("mdo-highlight"));
    }

    #[test]
    fn unclosed_script_before_fence_terminates_without_post_sanitize_splice() {
        let markdown = "before <script> after\n\n```rust\nfn main() {}\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert!(html.contains("before"));
        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
        assert!(!html.contains("mdo-highlight"));
    }

    #[test]
    fn sanitizer_drops_only_highlight_markup_after_unclosed_style() {
        // The first fence precedes the unclosed <style>, so its generated
        // markup survives sanitization. Only the second fence is swallowed.
        let markdown =
            "```rust\nlet first = 1;\n```\n\ntext <style> text\n\n```rust\nlet second = 2;\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 1);
        assert!(html.contains("let"), "{html}");
        assert!(html.contains("first"), "{html}");
        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
    }

    #[test]
    fn multiple_highlighted_blocks_splice_once_each() {
        let markdown = "```rust\nlet one = 1;\n```\n\n```python\nprint(2)\n```\n";
        let html = render_markdown_document(markdown, "fallback", None);

        assert_eq!(html.matches("<pre class=\"mdo-highlight ").count(), 2);
        assert!(html.contains("language-rust"));
        assert!(html.contains("language-python"));
        assert!(!html.contains("MDO_HIGHLIGHT_PLACEHOLDER"));
    }

    #[test]
    fn raw_user_html_still_crosses_the_ammonia_boundary() {
        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";
        let html = render_markdown_document(markdown, "fallback", None);

        assert!(!html.contains("onclick=\"alert(1)\""));
        assert!(!html.contains("<script>bad()</script>"));
        assert!(html.contains(">user</span>"));
        assert!(!html.contains("<b>code</b>"));
        assert!(html.contains("&lt;b&gt;"));
    }

    #[test]
    fn title_can_come_from_raw_html_h1() {
        let title = derive_title(
            r#"<section><h1 class="hero-title">Project <span>Home</span></h1></section>"#,
            "fallback",
        );

        assert_eq!(title, "Project Home");
    }

    #[test]
    fn derive_title_ignores_headings_in_code_fences() {
        let markdown = "```sh\n# not a title\n```\n\n# Real Title\n";
        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
    }

    #[test]
    fn derive_title_falls_back_when_only_heading_is_fenced() {
        let markdown = "~~~\n# fenced heading\n~~~\n";
        assert_eq!(derive_title(markdown, "Fallback Title"), "Fallback Title");
    }

    #[test]
    fn derive_title_ignores_raw_html_h1_inside_code_fence() {
        let markdown = "```html\n<h1>Not the title</h1>\n```\n\n# Real Title\n";
        assert_eq!(derive_title(markdown, "fallback"), "Real Title");
    }

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_adds_trailing_slash() {
        let url =
            dir_to_file_url(Path::new("/home/user/docs")).expect("absolute path should convert");
        assert!(url.ends_with('/'));
        assert_eq!(url, "file:///home/user/docs/");
    }

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_spaces() {
        let url = dir_to_file_url(Path::new("/home/user/my docs")).expect("should convert");
        assert_eq!(url, "file:///home/user/my%20docs/");
    }

    // `#` is a legal Windows filename character but is not exercised there
    // because these are pure-path conversions, not filesystem operations —
    // gating still keeps the Windows suite focused on Windows-specific forms
    // (drive letters, UNC, `\\?\`) covered below.

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_hash() {
        let url = dir_to_file_url(Path::new("/home/user/docs#1")).expect("should convert");
        assert_eq!(url, "file:///home/user/docs%231/");
    }

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_percent() {
        let url = dir_to_file_url(Path::new("/home/user/50%done")).expect("should convert");
        assert_eq!(url, "file:///home/user/50%25done/");
    }

    // `?` is invalid in Windows filenames, so this case can't arise there.

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_question_mark() {
        let url = dir_to_file_url(Path::new("/home/user/docs?draft")).expect("should convert");
        assert_eq!(url, "file:///home/user/docs%3Fdraft/");
    }

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_unicode_accented() {
        let url = dir_to_file_url(Path::new("/home/user/résumé")).expect("should convert");
        assert_eq!(url, "file:///home/user/r%C3%A9sum%C3%A9/");
    }

    #[cfg(unix)]
    #[test]
    fn dir_to_file_url_encodes_unicode_cjk() {
        let url = dir_to_file_url(Path::new("/home/user/日本語")).expect("should convert");
        assert_eq!(url, "file:///home/user/%E6%97%A5%E6%9C%AC%E8%AA%9E/");
    }

    #[test]
    fn dir_to_file_url_returns_none_for_relative_path() {
        assert_eq!(dir_to_file_url(Path::new("relative/dir")), None);
    }

    #[cfg(windows)]
    #[test]
    fn dir_to_file_url_windows_drive_letter() {
        let url = dir_to_file_url(Path::new(r"C:\foo\bar")).expect("should convert");
        assert_eq!(url, "file:///C:/foo/bar/");
    }

    #[cfg(windows)]
    #[test]
    fn dir_to_file_url_windows_drive_letter_with_space() {
        let url = dir_to_file_url(Path::new(r"C:\Program Files\mdo")).expect("should convert");
        assert_eq!(url, "file:///C:/Program%20Files/mdo/");
    }

    // `fs::canonicalize` on Windows produces the `\\?\` extended-length
    // prefix; browsers don't understand `file:////?/C:/...`, so this must
    // normalize to the same form as the plain drive-letter case.

    #[cfg(windows)]
    #[test]
    fn dir_to_file_url_windows_extended_length_prefix() {
        let url = dir_to_file_url(Path::new(r"\\?\C:\foo\bar")).expect("should convert");
        assert_eq!(url, "file:///C:/foo/bar/");
    }

    #[cfg(windows)]
    #[test]
    fn dir_to_file_url_windows_unc_path() {
        let url = dir_to_file_url(Path::new(r"\\server\share\dir")).expect("should convert");
        assert_eq!(url, "file://server/share/dir/");
    }
}