mdo-cli 0.6.1

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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
//! Shared mdo rendering, temp-output, browser launch, and integration helpers.

use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeSet;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io;
#[cfg(unix)]
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, UNIX_EPOCH};

#[cfg(unix)]
use std::fs::OpenOptions;
#[cfg(unix)]
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};

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

#[cfg(target_os = "android")]
mod android;
pub mod file_manager;
mod highlight;
#[cfg(target_os = "windows")]
pub mod windows_setup;

const SIMPLE_CSS: &str = include_str!("../assets/simple.min.css");
const APP_DISPLAY_NAME: &str = "mdo";
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const SETUP_SAMPLE_FILE_NAME: &str = "welcome-to-open-as-html-with-mdo.md";
pub const SETUP_SAMPLE_MARKDOWN: &str = "\
# Welcome to the world of Open as HTML with mdo

If you are reading this in your browser, mdo rendered Markdown as HTML and
opened it successfully.

Next, right-click any `.md` file and choose **Open as HTML** to read it this way.
If you make mdo your default Markdown app, a double-click does the same.
";
const UNSAFE_TEMP_OUTPUT_STEM_CHARS: &[char] = &[
    '&', '^', '%', '(', ')', '!', '"', '\'', '<', '>', '|', ';', '`', '$', '\\', '/', ':',
];

// mdo keeps simple.css as the base stylesheet but softens the heading/body
// scale for generated documents. Users who prefer the unmodified vendored
// simple.css typography can pass assets/restore-simple-css.css with --css.
const MDO_DEFAULT_TYPOGRAPHY_CSS: &str = include_str!("../assets/mdo-default-typography.css");

// pulldown-cmark emits GFM alerts as blockquotes with a
// `markdown-alert-{kind}` class. Keep the presentation in the generated
// document so alerts also work for bare installs with no external assets.
// The plain `:root` and prefers-color-scheme rules keep alerts styled when
// JavaScript is disabled (the theme-toggle script never runs, so no
// data-theme attribute is ever set); the higher-specificity
// `:root[data-theme=...]` rules then follow the theme toggle rather than the
// OS preference once a reader has selected a manual theme.
const GFM_ALERTS_CSS: &str = r#"
:root{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
@media (prefers-color-scheme: dark){:root{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}}
:root[data-theme="light"]{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
:root[data-theme="dark"]{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}
blockquote[class^="markdown-alert-"]{--alert-color:var(--accent);border-left:.3rem solid var(--alert-color);background:var(--accent-bg);padding:.75rem 1rem}
blockquote.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)}
"#;

// ─── BEGIN THEME TOGGLE ────────────────────────────────────────────────
// Self-contained light/dark mode toggle. To remove this feature entirely:
//   1. Delete this block (down to "END THEME TOGGLE").
//   2. Delete the `{theme_toggle}` line and `theme_toggle = ...` arg in
//      `wrap_html5` below.
// Variable values mirror simple.css's @media (prefers-color-scheme: dark).
//
// Behavior notes:
// - OS theme is detected automatically and tracked live until the user makes
//   a manual choice; the manual choice persists via localStorage.
// - localStorage can throw on file:// pages in some browsers/configurations,
//   so every access is wrapped \u2014 the toggle still works for the current page
//   even when persistence is unavailable.
// - An in-memory `manual` flag (not the localStorage read) is the source of
//   truth for "the user made an explicit choice". It is initialized from the
//   saved value and set on every toggle click regardless of whether
//   localStorage.setItem succeeds, so a later prefers-color-scheme change
//   can never clobber an explicit choice just because persistence failed
//   (e.g. on file:// pages).
// - The button is a real <button> (keyboard focusable/activatable) with a
//   state-aware aria-label.
// - This <style> block is emitted before the --css override block, so custom
//   CSS can restyle or hide the toggle (e.g. `#theme-toggle{display:none}`)
//   and reclaim the reserved narrow-screen padding (`body{padding-top:0}`).
const THEME_TOGGLE: &str = r#"<style id="mdo-theme-toggle">
: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}
: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}
:root[data-theme="dark"] img,:root[data-theme="dark"] video{opacity:.8}
#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)}
@media (max-width:55rem){body{padding-top:2.75rem}}
@media print{#theme-toggle{display:none}}
</style>
<script>
(function(){
  var read=function(){try{return localStorage.getItem('theme')}catch(e){return null}};
  var apply=function(t){document.documentElement.dataset.theme=t;};
  var mq=matchMedia('(prefers-color-scheme: dark)');
  var saved=read();
  var manual=saved!==null;
  apply(saved||(mq.matches?'dark':'light'));
  document.addEventListener('DOMContentLoaded',function(){
    var b=document.createElement('button');
    b.id='theme-toggle';b.type='button';
    var sync=function(){
      var dark=document.documentElement.dataset.theme==='dark';
      b.textContent=dark?'\u2600':'\u263E';
      var label=dark?'Switch to light theme':'Switch to dark theme';
      b.title=label;
      b.setAttribute('aria-label',label);
    };
    b.onclick=function(){
      var next=document.documentElement.dataset.theme==='dark'?'light':'dark';
      apply(next);
      manual=true;
      try{localStorage.setItem('theme',next)}catch(e){}
      sync();
    };
    if(mq.addEventListener){
      mq.addEventListener('change',function(e){
        if(!manual){apply(e.matches?'dark':'light');sync();}
      });
    }
    document.body.appendChild(b);
    sync();
  });
})();
</script>
"#;
// ─── END THEME TOGGLE ──────────────────────────────────────────────────

pub fn derive_output(input: &Path) -> PathBuf {
    input.with_extension("html")
}

/// Stable per-source-path location under a private temp/cache dir, e.g.
/// `%TEMP%\mdo-<uid>\<hash>\<stem>.html`. Re-opening the same source
/// overwrites the same file rather than accumulating new ones.
pub fn temp_output_for(input: &Path) -> io::Result<PathBuf> {
    let canonical = fs::canonicalize(input).unwrap_or_else(|_| input.to_path_buf());
    let mut hasher = DefaultHasher::new();
    canonical.hash(&mut hasher);
    let hash = hasher.finish();

    let stem = input
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("document");
    let stem = sanitize_temp_output_stem(stem);

    let root = private_temp_root();
    ensure_private_dir(&root)?;

    let source_dir = root.join(format!("{:016x}", hash));
    ensure_private_dir(&source_dir)?;

    Ok(source_dir.join(format!("{stem}.html")))
}

fn sanitize_temp_output_stem(stem: &str) -> String {
    let mut sanitized = String::with_capacity(stem.len());

    for ch in stem.chars() {
        if ch.is_control() || UNSAFE_TEMP_OUTPUT_STEM_CHARS.contains(&ch) {
            sanitized.push('_');
        } else {
            sanitized.push(ch);
        }
    }

    if sanitized.chars().any(|ch| ch != '_') {
        sanitized
    } else {
        "document".to_string()
    }
}

fn private_temp_root() -> PathBuf {
    let mut p = std::env::temp_dir();
    #[cfg(unix)]
    p.push(format!("mdo-{}", unsafe { libc::geteuid() }));
    #[cfg(not(unix))]
    p.push("mdo");
    p
}

#[cfg(unix)]
fn ensure_private_dir(path: &Path) -> io::Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) => {
            let file_type = metadata.file_type();
            if file_type.is_symlink() || !file_type.is_dir() {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!("{path:?} exists but is not a directory"),
                ));
            }

            let uid = unsafe { libc::geteuid() };
            if metadata.uid() != uid {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    format!("{path:?} is not owned by the current user"),
                ));
            }

            let mode = metadata.permissions().mode();
            if mode & 0o077 != 0 {
                fs::set_permissions(path, fs::Permissions::from_mode(mode & !0o077))?;
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            let mut builder = fs::DirBuilder::new();
            builder.mode(0o700);
            if let Err(create_error) = builder.create(path) {
                if create_error.kind() == io::ErrorKind::AlreadyExists {
                    return ensure_private_dir(path);
                }

                return Err(create_error);
            }
        }
        Err(e) => return Err(e),
    }

    Ok(())
}

#[cfg(not(unix))]
fn ensure_private_dir(path: &Path) -> io::Result<()> {
    fs::create_dir_all(path)
}

/// 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())
}

/// Launch the platform's default handler for `path` (typically a web browser
/// for `.html`). Non-blocking — the spawned process runs independently.
pub fn launch_browser(path: &Path) -> std::io::Result<()> {
    #[cfg(target_os = "windows")]
    {
        // SECURITY: open via the Win32 ShellExecuteW API (through the `opener`
        // crate) rather than `cmd /C start`. `start` runs the path through
        // cmd.exe's command-line parser, so cmd metacharacters (`&`, `^`, …) —
        // which are legal in Windows filenames and reach us via the input
        // file's stem in temp_output_for — would be interpreted as commands
        // (e.g. opening `a&calc&.md` would launch calc.exe). ShellExecuteW
        // takes the path as a single typed argument, so those characters stay
        // inert. It is non-blocking, preserving the fire-and-forget behavior.
        opener::open(path).map_err(io::Error::other)?;
    }
    #[cfg(target_os = "macos")]
    {
        // `open` returns promptly once Launch Services accepts the request,
        // so waiting for it doesn't block on the browser itself — and a
        // nonzero exit (no handler for the file) must surface as a launch
        // failure rather than being discarded with the child handle.
        let status = std::process::Command::new("open").arg(path).status()?;
        if !status.success() {
            return Err(io::Error::other(format!("open exited with {status}")));
        }
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        launch_via_xdg_open(path)?;
    }
    Ok(())
}

/// Open `path` with the first available freedesktop opener. Falls back through
/// common launchers when `xdg-open` (xdg-utils) is not installed, and reaps the
/// launcher process in a detached thread so it does not linger as a zombie
/// during long `--watch` sessions.
///
/// Spawning an opener is not the same as launching a browser: `xdg-open` can
/// exist, start, and then exit nonzero because no browser handler is
/// configured. We therefore listen for each opener's exit for a short window
/// — a quick nonzero exit is an honest failure (and we fall through to the
/// next opener), while an opener still running after the window has almost
/// certainly handed off (or, in xdg-open's no-desktop fallback, IS the
/// browser), so we detach and call it success. We never block on the browser
/// itself beyond that window.
#[cfg(all(unix, not(target_os = "macos")))]
fn launch_via_xdg_open(path: &Path) -> std::io::Result<()> {
    const OPENERS: &[(&str, &[&str])] = &[
        ("xdg-open", &[]),
        ("gio", &["open"]),
        ("gnome-open", &[]),
        ("kde-open5", &[]),
        ("kde-open", &[]),
        ("wslview", &[]),
    ];
    const LAUNCH_FAILURE_WINDOW: Duration = Duration::from_secs(2);

    let mut last_failure: Option<String> = None;
    for (program, leading) in OPENERS {
        let mut command = std::process::Command::new(program);
        command.args(*leading).arg(path);
        let Ok(mut child) = command.spawn() else {
            continue; // not installed; try the next opener
        };

        // The waiting thread doubles as the reaper for the detached-success
        // case: it always waits the child to completion, we just stop
        // listening for the result after the failure window.
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = tx.send(child.wait());
        });

        match rx.recv_timeout(LAUNCH_FAILURE_WINDOW) {
            Ok(Ok(status)) if status.success() => return Ok(()),
            Ok(Ok(status)) => {
                last_failure = Some(format!("{program} exited with {status}"));
            }
            Ok(Err(e)) => {
                last_failure = Some(format!("failed waiting on {program}: {e}"));
            }
            // Still running after the window: it handed off to (or is) the
            // browser. The waiting thread reaps it eventually.
            Err(_) => return Ok(()),
        }
    }

    match last_failure {
        Some(failure) => Err(io::Error::other(failure)),
        None => Err(io::Error::new(
            io::ErrorKind::NotFound,
            "no desktop opener found (install xdg-utils)",
        )),
    }
}

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_with_diagnostics`.
///
/// 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
}

fn wrap_html5(
    body: &str,
    title: &str,
    base_href: Option<&str>,
    css_override: Option<&str>,
    highlight_css: Option<&str>,
    source_modified_unix_secs: Option<u64>,
) -> String {
    // `<base href>` makes relative image/link refs in the rendered HTML resolve
    // against the *source* directory even when the HTML lives elsewhere
    // (e.g. when --open writes to %TEMP%). Must come before any element that
    // references a URL, so we put it first inside <head>.
    let base_tag = match base_href {
        Some(href) => format!("<base href=\"{}\">\n", html_escape(href)),
        None => String::new(),
    };
    let css_override_block = css_override
        .filter(|css| !css.trim().is_empty())
        .map(|css| {
            format!(
                "<style id=\"mdo-css-override\">\n/* Custom CSS from --css */\n{}\n</style>\n",
                escape_style_end_tags(css)
            )
        })
        .unwrap_or_default();
    let mdo_default_typography = format!(
        "<style id=\"mdo-default-typography\">\n{}\n</style>\n",
        escape_style_end_tags(MDO_DEFAULT_TYPOGRAPHY_CSS)
    );
    let highlight_css = highlight_css.unwrap_or_default();
    // Provenance lives only in <meta name="generator">; the visible page
    // carries no mdo branding, version, or render timing (v0.6 quiet output).
    let generator = format!("{APP_DISPLAY_NAME} {APP_VERSION}");
    // Restrained source-freshness footer: the source file's filesystem
    // modification time, rendered as UTC with a machine-readable datetime.
    // The tiny inline script re-formats it in the reader's locale/timezone
    // when JavaScript is available. Omitted entirely when the timestamp is
    // missing or unreadable.
    let source_meta = source_modified_unix_secs
        .map(|secs| {
            let machine = utc_datetime_from_unix_secs(secs);
            let human = human_utc_datetime_from_unix_secs(secs);
            format!(
                "<footer class=\"mdo-source-meta\">Source modified: <time datetime=\"{machine}\">{human}</time></footer>\n\
                 <script>\n\
                 (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\
                 </script>\n",
                machine = html_escape(&machine),
                human = html_escape(&human),
            )
        })
        .unwrap_or_default();
    format!(
        "<!DOCTYPE html>\n\
         <html lang=\"en\">\n\
         <head>\n\
         <meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
         <meta name=\"generator\" content=\"{generator}\">\n\
         {base_tag}\
         <title>{title}</title>\n\
         <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\
         {theme_toggle}\
         {mdo_default_typography}\
         {css_override_block}\
         </head>\n\
         <body>\n\
         <main>\n{body}\n</main>\n\
         {source_meta}\
         </body>\n\
         </html>\n",
        generator = html_escape(&generator),
        base_tag = base_tag,
        title = html_escape(title),
        css = SIMPLE_CSS,
        gfm_alerts_css = GFM_ALERTS_CSS,
        highlight_css = highlight_css,
        theme_toggle = THEME_TOGGLE, // ← THEME TOGGLE injection point (delete this line to remove)
        mdo_default_typography = mdo_default_typography,
        css_override_block = css_override_block,
        body = body,
        source_meta = source_meta,
    )
}

fn escape_style_end_tags(css: &str) -> String {
    const STYLE_END_PREFIX: &[u8] = b"</style";

    let mut escaped = String::with_capacity(css.len());
    let bytes = css.as_bytes();
    let mut i = 0;

    while i < css.len() {
        if i + STYLE_END_PREFIX.len() <= css.len()
            && bytes[i..i + STYLE_END_PREFIX.len()].eq_ignore_ascii_case(STYLE_END_PREFIX)
        {
            escaped.push_str("<\\/style");
            i += STYLE_END_PREFIX.len();
        } else {
            let ch = css[i..]
                .chars()
                .next()
                .expect("index should always point at a char boundary");
            escaped.push(ch);
            i += ch.len_utf8();
        }
    }

    escaped
}

const MONTH_NAMES: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// The source file's mtime as seconds since the Unix epoch, or `None` when
/// the metadata is missing or unreadable (which must never block rendering).
fn source_modified_unix_secs(input: &Path) -> Option<u64> {
    fs::metadata(input)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|mtime| mtime.duration_since(UNIX_EPOCH).ok())
        .map(|elapsed| elapsed.as_secs())
}

/// ISO 8601 UTC datetime, e.g. `2026-07-14T17:42:05Z`, for `<time datetime>`.
fn utc_datetime_from_unix_secs(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let (year, month, day) = civil_from_days(days);
    let seconds_of_day = secs % 86_400;
    let hour = seconds_of_day / 3_600;
    let minute = (seconds_of_day % 3_600) / 60;
    let second = seconds_of_day % 60;

    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}

/// Readable UTC fallback text, e.g. `July 14, 2026, 5:42 PM UTC`, shown when
/// JavaScript cannot re-format the timestamp in the reader's locale.
fn human_utc_datetime_from_unix_secs(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let (year, month, day) = civil_from_days(days);
    let seconds_of_day = secs % 86_400;
    let hour24 = seconds_of_day / 3_600;
    let minute = (seconds_of_day % 3_600) / 60;
    let (hour12, meridiem) = match hour24 {
        0 => (12, "AM"),
        1..=11 => (hour24, "AM"),
        12 => (12, "PM"),
        _ => (hour24 - 12, "PM"),
    };
    let month_name = MONTH_NAMES[(month - 1) as usize];

    format!("{month_name} {day}, {year}, {hour12}:{minute:02} {meridiem} UTC")
}

fn civil_from_days(days_since_unix_epoch: i64) -> (i64, i64, i64) {
    // Howard Hinnant's civil-from-days algorithm, shifted for Unix epoch days.
    let z = days_since_unix_epoch + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = mp + if mp < 10 { 3 } else { -9 };
    let year = y + if month <= 2 { 1 } else { 0 };

    (year, month, day)
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Wall-clock time spent in each stage of one render workflow, reported to
/// stderr by `--verbose`. Stages that do not run for a given invocation
/// (`sanitize` under `--unsafe-html`, `assemble` under `--bare`) report zero.
#[derive(Default)]
struct StageTimings {
    read: Duration,
    markdown: Duration,
    sanitize: Duration,
    assemble: Duration,
    write: Duration,
}

/// Print per-stage and total timings for a completed render to STDERR only.
/// Performance diagnostics belong in the terminal: they never touch stdout
/// or the generated HTML (v0.6 quiet output). `total` is the wall-clock time
/// of the whole workflow, so it is always at least the sum of the stages.
fn report_render_timings(input: &Path, timings: &StageTimings, total: Duration) {
    let ms = |d: Duration| d.as_secs_f64() * 1000.0;
    eprintln!("⏱  Render workflow for {:?}:", input);
    eprintln!("   read     {:>10.3} ms", ms(timings.read));
    eprintln!("   markdown {:>10.3} ms", ms(timings.markdown));
    eprintln!("   sanitize {:>10.3} ms", ms(timings.sanitize));
    eprintln!("   assemble {:>10.3} ms", ms(timings.assemble));
    eprintln!("   write    {:>10.3} ms", ms(timings.write));
    eprintln!("   total    {:>10.3} ms", ms(total));
}

pub fn convert(
    input: &Path,
    output: &Path,
    bare: bool,
    unsafe_html: bool,
    private_output: bool,
) -> bool {
    convert_with_css_override(input, output, bare, unsafe_html, private_output, None)
}

pub fn convert_with_css_override(
    input: &Path,
    output: &Path,
    bare: bool,
    unsafe_html: bool,
    private_output: bool,
    css_override: Option<&Path>,
) -> bool {
    convert_with_diagnostics(
        input,
        output,
        bare,
        unsafe_html,
        private_output,
        css_override,
        false,
    )
}

/// Full render workflow with optional `--verbose` timing diagnostics.
///
/// The generated HTML is byte-identical whether or not `verbose` is set:
/// timings are measured around the existing stages and reported to stderr
/// only after a fully successful render.
pub fn convert_with_diagnostics(
    input: &Path,
    output: &Path,
    bare: bool,
    unsafe_html: bool,
    private_output: bool,
    css_override: Option<&Path>,
    verbose: bool,
) -> bool {
    let workflow_start = Instant::now();
    let mut timings = StageTimings::default();

    let stage_start = Instant::now();
    let markdown = match fs::read_to_string(input) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("❌ Failed to read {:?}: {}", input, e);
            return false;
        }
    };
    timings.read = stage_start.elapsed();

    let css_override = if bare {
        None
    } else {
        match css_override {
            Some(path) => {
                let stage_start = Instant::now();
                let css = fs::read_to_string(path);
                timings.read += stage_start.elapsed();
                match css {
                    Ok(css) => Some(css),
                    Err(e) => {
                        eprintln!("❌ Failed to read CSS override {:?}: {}", path, e);
                        return false;
                    }
                }
            }
            None => None,
        }
    };

    // Same splice loop as `safe_markdown_body`, instrumented for --verbose.
    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 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 bare {
        body
    } else {
        let stage_start = Instant::now();
        let fallback = 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(input)
                .ok()
                .and_then(|p| p.parent().map(Path::to_path_buf)),
            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(input),
        );
        timings.assemble = stage_start.elapsed();
        wrapped
    };

    let stage_start = Instant::now();
    if let Some(parent) = output.parent() {
        if !parent.as_os_str().is_empty() {
            if let Err(e) = fs::create_dir_all(parent) {
                eprintln!("❌ Failed to create {:?}: {}", parent, e);
                return false;
            }
        }
    }

    if let Err(e) = write_output_file(output, &final_html, private_output) {
        eprintln!("❌ Failed to write to {:?}: {}", output, e);
        false
    } else {
        timings.write = stage_start.elapsed();
        println!("✅ Converted {:?} → {:?}", input, output);
        if verbose {
            report_render_timings(input, &timings, workflow_start.elapsed());
        }
        true
    }
}

#[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)
}

pub fn open_setup_sample() -> io::Result<()> {
    let source = setup_sample_input_path()?;
    fs::write(&source, SETUP_SAMPLE_MARKDOWN)?;

    let output = temp_output_for(&source)?;
    if !convert(&source, &output, false, false, true) {
        return Err(io::Error::other("sample render failed"));
    }

    launch_browser(&output)?;
    Ok(())
}

fn setup_sample_input_path() -> io::Result<PathBuf> {
    let root = private_temp_root();
    ensure_private_dir(&root)?;

    let dir = root.join("setup");
    ensure_private_dir(&dir)?;
    Ok(dir.join(SETUP_SAMPLE_FILE_NAME))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::SystemTime;

    static NEXT_TEMP_FIXTURE_ID: AtomicU64 = AtomicU64::new(0);

    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 temp_output_stem_replaces_shell_metacharacters() {
        let input = unique_temp_input("a&calc&.md");
        let output = temp_output_for(&input).expect("temp path should be built");
        let file_name = output
            .file_name()
            .and_then(|s| s.to_str())
            .expect("temp path should end with unicode filename");

        assert_eq!(file_name, "a_calc_.html");
        assert!(!file_name.contains('&'));

        cleanup_temp_fixture(&input, &output);
    }

    #[test]
    fn temp_output_stem_keeps_readable_normal_names() {
        let input = unique_temp_input("résumé-draft_2026.md");
        let output = temp_output_for(&input).expect("temp path should be built");
        let file_name = output
            .file_name()
            .and_then(|s| s.to_str())
            .expect("temp path should end with unicode filename");

        assert_eq!(file_name, "résumé-draft_2026.html");

        cleanup_temp_fixture(&input, &output);
    }

    fn unique_temp_input(file_name: &str) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be after epoch")
            .as_nanos();
        let counter = NEXT_TEMP_FIXTURE_ID.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "mdo-unit-test-{}-{nonce}-{counter}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).expect("test temp dir should be created");
        let input = dir.join(file_name);
        fs::write(&input, "# Test\n").expect("test input should be written");
        input
    }

    fn cleanup_temp_fixture(input: &Path, output: &Path) {
        if let Some(parent) = output.parent() {
            let _ = fs::remove_dir_all(parent);
        }
        if let Some(parent) = input.parent() {
            let _ = fs::remove_dir_all(parent);
        }
    }

    #[test]
    fn formats_unix_timestamps_as_machine_utc_datetimes() {
        assert_eq!(utc_datetime_from_unix_secs(0), "1970-01-01T00:00:00Z");
        assert_eq!(
            utc_datetime_from_unix_secs(951_827_696),
            "2000-02-29T12:34:56Z"
        );
    }

    #[test]
    fn formats_unix_timestamps_as_readable_utc_datetimes() {
        // Midnight and noon exercise the 12-hour AM/PM edge cases.
        assert_eq!(
            human_utc_datetime_from_unix_secs(0),
            "January 1, 1970, 12:00 AM UTC"
        );
        assert_eq!(
            human_utc_datetime_from_unix_secs(951_827_696),
            "February 29, 2000, 12:34 PM UTC"
        );
        assert_eq!(
            human_utc_datetime_from_unix_secs(13 * 3_600 + 5 * 60),
            "January 1, 1970, 1:05 PM UTC"
        );
    }

    #[test]
    fn wrap_html5_keeps_generator_meta_without_visible_branding() {
        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(0));

        assert!(html.contains(&format!(
            "<meta name=\"generator\" content=\"mdo {APP_VERSION}\">"
        )));
        assert!(!html.contains("Generated by"));
        assert!(!html.contains("mdo-generated"));
    }

    #[test]
    fn wrap_html5_shows_source_modified_time_with_machine_datetime() {
        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(951_827_696));

        assert!(html.contains(
            "<footer class=\"mdo-source-meta\">Source modified: \
             <time datetime=\"2000-02-29T12:34:56Z\">February 29, 2000, 12:34 PM UTC</time></footer>"
        ));
    }

    #[test]
    fn wrap_html5_renders_without_source_modified_time() {
        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);

        assert!(html.contains("<main>\n<p>hi</p>\n</main>"));
        assert!(!html.contains("Source modified"));
        assert!(!html.contains("<footer"));
    }

    #[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 wrapped_document_styles_alerts_in_light_and_dark_palettes() {
        let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);

        // No-JS defaults: plain :root plus an OS dark-mode media query, so
        // alerts stay styled when the theme-toggle script never runs.
        assert!(html.contains("\n:root{--alert-note:"));
        assert!(html.contains("@media (prefers-color-scheme: dark){:root{--alert-note:"));
        // Manual theme-toggle overrides.
        assert!(html.contains(":root[data-theme=\"light\"]{--alert-note:"));
        assert!(html.contains(":root[data-theme=\"dark\"]{--alert-note:"));
        for kind in ["note", "tip", "important", "warning", "caution"] {
            assert!(html.contains(&format!("blockquote.markdown-alert-{kind}")));
        }
    }

    #[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");
    }

    #[test]
    fn css_override_escapes_style_end_tags() {
        let escaped = escape_style_end_tags("h1{} </STYLE><script>alert(1)</script>");

        assert!(escaped.contains("<\\/style><script>"));
        assert!(!escaped.to_ascii_lowercase().contains("</style><script>"));
    }

    // Unix-rooted paths like `/home/user/...` are NOT absolute on Windows
    // (no drive or UNC prefix), so `Url::from_directory_path` rejects them
    // there — every test using such a path must be `#[cfg(unix)]`-gated or
    // it panics under the Windows CI test job. Windows path forms get their
    // own `#[cfg(windows)]` tests below.
    #[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/");
    }

    #[test]
    fn setup_sample_contains_welcome_copy() {
        assert!(SETUP_SAMPLE_MARKDOWN.contains("# Welcome to the world of Open as HTML with mdo"));
        assert!(SETUP_SAMPLE_MARKDOWN.contains("opened it successfully"));
        assert_eq!(
            SETUP_SAMPLE_FILE_NAME,
            "welcome-to-open-as-html-with-mdo.md"
        );
    }
}