edamame 0.1.5

A fast TUI Markdown editor and viewer
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
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
use std::borrow::Cow;
use std::collections::hash_map::RandomState;
use std::collections::{HashMap, HashSet};
use std::hash::BuildHasher;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use anyhow::{Context, Result};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use pulldown_cmark::{
    html as cmark_html, CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd,
};

use super::runner::{write_atomically, ExportOutcome, Exported};
use crate::diagram;
use crate::document::parsed_doc::{gfm_slug, uniquify_slug};
use crate::image::normalize_svg;
use crate::markdown::highlight::{self, TokenClass};
use crate::markdown::parser::post_pass::is_html_comment_only;
use images::{local_image, ImageResolver};

mod images;

pub use images::ImageHandling;

/// The compiled-in stylesheet, used for [`Stylesheet::Builtin`].
pub const BUILTIN_STYLESHEET: &str = include_str!("../../config/export/default.css");

/// Source of the CSS embedded in the generated HTML document.
#[derive(Debug, Clone)]
pub enum Stylesheet {
    /// The bundled `config/export/default.css`.
    Builtin,
    /// Read a user CSS file at export time.
    Path(PathBuf),
    /// CSS verbatim.  Tests and embeddings only — the binary builds `Builtin` / `Path`.
    #[allow(dead_code)]
    Inline(String),
}

impl Stylesheet {
    /// Parse `[export.html].stylesheet`: the sentinel `"builtin"`, or a filesystem path.
    pub fn from_config_value(value: &str) -> Self {
        if value.eq_ignore_ascii_case("builtin") {
            Self::Builtin
        } else {
            Self::Path(PathBuf::from(value))
        }
    }

    fn load(&self) -> Result<String> {
        match self {
            Self::Builtin => Ok(BUILTIN_STYLESHEET.to_owned()),
            Self::Path(p) => std::fs::read_to_string(p)
                .with_context(|| format!("Failed to read stylesheet: {}", p.display())),
            Self::Inline(s) => Ok(s.clone()),
        }
    }
}

/// Options passed to [`render_html`] / [`spawn_html_export`].
#[derive(Debug, Clone)]
pub struct HtmlExportOptions {
    /// Source of the embedded CSS.
    pub stylesheet: Stylesheet,
    /// What happens to each `<img src>`, Markdown image or raw HTML alike: see
    /// [`ImageHandling`].
    pub images: ImageHandling,
    /// Resolves relative image paths, and bounds them: see [`images::local_image`].  `None`
    /// means no local image is embedded.
    pub source_dir: Option<PathBuf>,
    /// Canonical paths *outside* `source_dir` the user agreed to embed, as listed by
    /// [`outside_images`].  An out-of-folder image not on this list stays a plain link.
    pub approved_outside: Vec<PathBuf>,
    /// `<title>` text; `None` falls back to `"Document"`.
    pub title: Option<String>,
    /// Render *figures* — fenced ```mermaid code blocks and `$$...$$` display math — to SVG
    /// embedded in a `<figure>` (`mermaid-diagram` / `math-formula`), each falling back to its
    /// source form on failure so the source is never lost.  Independent of this flag, inline `$…$`
    /// is always emitted as literal source, matching the terminal preview.
    pub render_figures: bool,
}

impl Default for HtmlExportOptions {
    fn default() -> Self {
        Self {
            stylesheet: Stylesheet::Builtin,
            images: ImageHandling::Link,
            source_dir: None,
            approved_outside: Vec::new(),
            title: None,
            render_figures: true,
        }
    }
}

/// Render `markdown` to a standalone HTML document, mirroring the in-app renderer's parser
/// options so an export looks like the terminal preview.
///
/// **The serialized body passes through [`sanitize_body`] before anything edamame generated is
/// added to it.**  Raw HTML in the document survives only as far as the allowlist lets it, so
/// attacker-controlled Markdown cannot inject `<script>`, event handlers, or a code-running link.
/// Figures are rendered as placeholders and swapped in afterwards ([`Figures`]), so the sanitizer
/// never sees — and can never be asked to permit — the markup edamame writes itself.
pub fn render_html(markdown: &str, opts: &HtmlExportOptions) -> Result<String> {
    render(markdown, opts).map(|rendered| rendered.html)
}

/// A rendered export, and how many images it left out ([`ImageResolver::left_out`]).
pub(super) struct Rendered {
    pub(super) html: String,
    pub(super) images_left_out: usize,
}

/// [`render_html`], also reporting how many images were left out, for the export workers.
pub(super) fn render(markdown: &str, opts: &HtmlExportOptions) -> Result<Rendered> {
    // Collected so the rewrite passes can mutate events in place.
    let mut events: Vec<Event> = Parser::new_ext(markdown, parser_options(markdown)).collect();

    // Before `replace_math`, which turns heading math into plain text: the slug reads the
    // `InlineMath` events the in-app parser sees.
    assign_heading_ids(&mut events);

    let mut figures = Figures::new();
    if opts.render_figures {
        events = replace_mermaid_with_figure(events, &mut figures);
    }
    // Always run, so inline `$…$` and (with figures off) display math
    // collapse to literal source rather than a bare `<span class="math">`.
    events = replace_math(events, opts.render_figures, &mut figures);
    // Last, so the `math` fallback blocks `replace_math` emits pass through it like any other.
    events = highlight_code_blocks(events);

    let mut body = String::new();
    cmark_html::push_html(&mut body, events.into_iter());
    let images = Arc::new(ImageResolver::new(
        opts.images,
        opts.source_dir.as_deref(),
        &opts.approved_outside,
    ));
    let hook = Arc::clone(&images);
    let body = figures.insert_into(&sanitize_body(&body, move |src| hook.resolve(src)));

    let css = opts.stylesheet.load()?;
    let title = opts.title.as_deref().unwrap_or("Document");

    let html = 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\
         <title>{title}</title>\n\
         <style>\n{css}\n</style>\n\
         </head>\n\
         <body>\n\
         <main class=\"markdown-body\">\n\
         {body}\n\
         </main>\n\
         </body>\n\
         </html>\n",
        title = html_escape(title),
    );
    Ok(Rendered {
        html,
        images_left_out: images.left_out(),
    })
}

/// Render `markdown` to `target` on a worker thread, invoking the closure there with the outcome.
///
/// **The caller must run [`crate::export::preflight`] first** — this clobbers an existing
/// `target`.
pub fn spawn_html_export(
    markdown: String,
    target: PathBuf,
    opts: HtmlExportOptions,
    on_done: impl FnOnce(ExportOutcome) + Send + 'static,
) {
    std::thread::spawn(move || {
        let result = render_and_write(&markdown, &target, &opts).map(|images_left_out| Exported {
            path: target.clone(),
            images_left_out,
        });
        on_done(result.map_err(|e| format!("{e:#}")));
    });
}

/// Render and write `target`, returning how many images were left out.
fn render_and_write(markdown: &str, target: &Path, opts: &HtmlExportOptions) -> Result<usize> {
    let rendered = render(markdown, opts)?;
    write_atomically(target, rendered.html.as_bytes())
        .with_context(|| format!("Failed to write export: {}", target.display()))?;
    Ok(rendered.images_left_out)
}

/// The parser options every export pass uses, so [`outside_images`] sees exactly the images
/// [`render_html`] would.
fn parser_options(markdown: &str) -> Options {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_SMART_PUNCTUATION);
    // Recognize math so `$$…$$` reaches `replace_math` as `Event::DisplayMath` (rendered to a
    // figure) rather than surviving as literal text.  `replace_math` always runs when this is on —
    // even with figures disabled — so inline `$…$` and un-rendered display math collapse back to
    // their literal source instead of pulldown's `<span class="math">` wrapper.
    options.insert(Options::ENABLE_MATH);
    // Without the frontmatter extension a `---` block parses as a thematic break plus a setext
    // H2, and the export opens with the YAML keys as its loudest heading.  It is gated on *this*
    // document's opening delimiter, through the shared `metadata_options_for`: the extensions are
    // not anchored to the document start on their own, so leaving them on unconditionally would
    // let a mid-document `---` claim the section under it — and the writer emits nothing for a
    // metadata block, so that section would vanish from the export silently.
    options |= crate::markdown::parse_offsets::metadata_options_for(markdown);

    options
}

// ── Heading anchors ───────────────────────────────────────────────────────

/// Give every heading the `id` a `[x](#fragment)` link names, so in-document links work in the
/// export.  pulldown-cmark's writer emits an `id` only when the event carries one, and without
/// `ENABLE_HEADING_ATTRIBUTES` none does — every heading came out bare and every `#anchor` link
/// went nowhere.
///
/// The slug is the one `ParsedDoc::heading_anchors` keys the in-app jump on — [`gfm_slug`] over
/// the same plain text `inlines_to_plain` builds, deduplicated by [`uniquify_slug`] — so a
/// fragment that resolves in edamame resolves in the export.  Unlike the in-app table, which
/// indexes top-level blocks only, a heading nested in a list or quote gets an id too, as on
/// GitHub.  A nested heading also takes its slug's count, so where it shares text with a later
/// top-level heading the fragment can name a different heading in each: `- # Intro` then
/// `# Intro` exports as `intro` / `intro-1`, while edamame jumps `#intro` to the top-level one.
fn assign_heading_ids(events: &mut [Event<'_>]) {
    let mut counts: HashMap<String, usize> = HashMap::new();
    let mut i = 0;
    while i < events.len() {
        if !matches!(events[i], Event::Start(Tag::Heading { .. })) {
            i += 1;
            continue;
        }
        let mut text = String::new();
        let mut j = i + 1;
        while let Some(event) = events.get(j) {
            match event {
                Event::End(TagEnd::Heading(_)) => break,
                Event::Text(t) | Event::Code(t) => text.push_str(t),
                Event::InlineMath(m) => text.push_str(&literal_math(m, false)),
                Event::DisplayMath(m) => text.push_str(&literal_math(m, true)),
                Event::SoftBreak => text.push(' '),
                Event::HardBreak => text.push('\n'),
                // The in-app parser keeps non-comment inline HTML as text.
                Event::InlineHtml(h) if !is_html_comment_only(h) => text.push_str(h),
                _ => {}
            }
            j += 1;
        }
        let base = gfm_slug(&text);
        if !base.is_empty() {
            let slug = uniquify_slug(&base, &mut counts);
            if let Event::Start(Tag::Heading { id, .. }) = &mut events[i] {
                *id = Some(CowStr::Boxed(slug.into_boxed_str()));
            }
        }
        i = j + 1;
    }
}

// ── Sanitization ──────────────────────────────────────────────────────────

/// URL schemes that run code when a browser follows or loads them.  The list is closed: these
/// three are the only schemes a browser executes.  `data:` is additionally allowed on `img src`,
/// where it can only ever be an image (see [`sanitize_body`]).
const BLOCKED_URL_SCHEMES: &[&str] = &["javascript", "vbscript", "data"];

/// Clean the serialized body with `ammonia`'s allowlist, extended for what Markdown and README
/// HTML produce.
///
/// * **Tags and attributes.**  ammonia's defaults (`details`/`summary`, `kbd`, `sub`/`sup`,
///   `img` with `width`/`height`, tables, …) plus: `id`, `class` and `align` anywhere (heading
///   anchors, footnotes, code-block languages, `<p align="center">`); `name` on `a`; `open` on
///   `details`; a *checkbox* `input` for task lists; and `style` on `th`/`td`, filtered down to
///   `text-align`, for table column alignment.  None of these can run anything: the export
///   carries no script for `id`/`class` to steer, and every other CSS property — the ones that
///   fetch (`url()`) or overlay the page — is dropped.  `<script>` and `<style>` are removed
///   with their contents; comments are dropped, and any other unlisted tag is removed with its
///   content kept.
/// * **URL schemes — a denylist expressed as an allowlist.**  ammonia only takes an allowlist,
///   and a fixed one would break every app link (`obsidian:`, `zotero:`, `vscode:`, `file:`)
///   it didn't anticipate.  So the list handed to it is every scheme-shaped token in the body
///   ([`url_schemes_in`]) minus [`BLOCKED_URL_SCHEMES`].  The safety argument rests only on the
///   subtraction: ammonia parses each URL as a browser would (stripping tab/newline, decoding
///   entities, lowercasing the scheme), and a parsed `javascript` is never in the set however
///   the source spelled it.  A link whose scheme is refused loses its `href` and stays as text.
/// * **`data:` on `img src` only.**  `data` is in the allowlist for the self-contained export's
///   embedded images, and the attribute filter strips it from every other URL attribute.  Inside
///   `<img>` even `data:image/svg+xml` is inert: a browser runs no script and loads no resource
///   in an SVG used as an image.
/// * **`img_src` decides every surviving `<img src>`** — `Some` to write that value, `None` to
///   remove it.  It runs on attributes that already passed the checks above, so it can only
///   narrow them, and it is the one place image references are handled ([`ImageResolver`]).
fn sanitize_body<F>(html: &str, img_src: F) -> String
where
    F: for<'u> Fn(&'u str) -> Option<Cow<'u, str>> + Send + Sync + 'static,
{
    let schemes = url_schemes_in(html);
    let mut builder = ammonia::Builder::default();
    builder
        .url_schemes(schemes.iter().map(String::as_str).collect())
        .add_url_schemes(["data"])
        // ammonia's default adds `rel="noopener noreferrer"` to every `<a>`; that guards
        // `target="_blank"`, which isn't allowed here, and would clutter every footnote link.
        .link_rel(None)
        .add_generic_attributes(["id", "class", "align"])
        .add_tag_attributes("a", ["name"])
        .add_tag_attributes("details", ["open"])
        .add_tags(["input"])
        .add_tag_attributes("input", ["checked", "disabled"])
        .add_tag_attribute_values("input", "type", ["checkbox"])
        .add_tag_attributes("th", ["style"])
        .add_tag_attributes("td", ["style"])
        .filter_style_properties(HashSet::from(["text-align"]))
        .attribute_filter(move |element, attribute, value| {
            if (element, attribute) == ("img", "src") {
                return img_src(value);
            }
            let is_url_attribute = matches!(attribute, "href" | "src" | "xlink:href" | "cite");
            if is_url_attribute && has_data_scheme(value) {
                None
            } else {
                Some(Cow::Borrowed(value))
            }
        });
    builder.clean(html).to_string()
}

/// Every lowercased, scheme-shaped token (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`) followed
/// by a `:` anywhere in `html`, minus [`BLOCKED_URL_SCHEMES`].  Deliberately over-inclusive —
/// words before a colon in prose land here too — because extra entries only widen what
/// [`sanitize_body`] *permits*, and the blocked schemes are the safety boundary.
fn url_schemes_in(html: &str) -> HashSet<String> {
    let is_scheme_char = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.');
    let bytes = html.as_bytes();
    let mut schemes = HashSet::new();
    for (colon, _) in html.match_indices(':') {
        let start = bytes[..colon]
            .iter()
            .rposition(|&b| !is_scheme_char(b))
            .map_or(0, |i| i + 1);
        // Leading digits / `+-.` are not part of a scheme: skip to the first letter.
        let Some(first_alpha) = bytes[start..colon].iter().position(u8::is_ascii_alphabetic) else {
            continue;
        };
        let scheme = html[start + first_alpha..colon].to_ascii_lowercase();
        if !BLOCKED_URL_SCHEMES.contains(&scheme.as_str()) {
            schemes.insert(scheme);
        }
    }
    schemes
}

/// Whether a URL attribute value is a `data:` URL as a browser parses it: ASCII tab and newline
/// removed anywhere, leading C0 controls and spaces trimmed, scheme case-insensitive.
fn has_data_scheme(value: &str) -> bool {
    let normalized: String = value
        .trim_start_matches(|c: char| c <= ' ')
        .chars()
        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
        .take(5)
        .collect();
    normalized.eq_ignore_ascii_case("data:")
}

// ── Figures ───────────────────────────────────────────────────────────────

/// Figure markup edamame generates, held out of the body until it has been sanitized.
///
/// Each figure enters the event stream as a placeholder element,
/// `<div class="edamame-figure-{nonce}-{n}"></div>`, which [`sanitize_body`] serializes back
/// verbatim, and [`insert_into`](Self::insert_into) swaps the markup in afterwards.  Two properties keep the swap in element context:
///
/// * **The nonce is random per export**, so a document cannot spell a placeholder itself.
/// * **The placeholder contains `"` and `<`.**  Where the real one lands outside element content —
///   swallowed by a document's unclosed `<p title="`, say — the sanitizer escapes or drops it
///   (`&quot;` in an attribute value, `&lt;` in text), so it no longer matches and the figure is
///   left out rather than spliced into an attribute.
struct Figures {
    /// `<div class="edamame-figure-{nonce}-`; the index and [`PLACEHOLDER_CLOSE`] follow.
    open: String,
    html: Vec<String>,
}

/// The tail of a [`Figures`] placeholder after its index.
const PLACEHOLDER_CLOSE: &str = "\"></div>";

impl Figures {
    fn new() -> Self {
        // `RandomState` is seeded from the OS RNG; two hashes give a 128-bit nonce with no
        // extra dependency.  It only has to be unguessable to a document written in advance.
        let nonce = (
            RandomState::new().hash_one(0u8),
            RandomState::new().hash_one(1u8),
        );
        Self {
            open: format!(
                "<div class=\"edamame-figure-{:016x}{:016x}-",
                nonce.0, nonce.1
            ),
            html: Vec::new(),
        }
    }

    /// Hold `html` back and return the placeholder event standing in for it.
    fn placeholder(&mut self, html: String) -> Event<'static> {
        let token = format!("{}{}{PLACEHOLDER_CLOSE}", self.open, self.html.len());
        self.html.push(html);
        Event::Html(CowStr::Boxed(token.into_boxed_str()))
    }

    /// Replace each placeholder in the sanitized `body` with its figure.
    fn insert_into(&self, body: &str) -> String {
        if self.html.is_empty() {
            return body.to_owned();
        }
        let mut out =
            String::with_capacity(body.len() + self.html.iter().map(String::len).sum::<usize>());
        let mut rest = body;
        while let Some(pos) = rest.find(&self.open) {
            out.push_str(&rest[..pos]);
            let after = &rest[pos + self.open.len()..];
            let digits = after.bytes().take_while(u8::is_ascii_digit).count();
            let figure = after[..digits]
                .parse::<usize>()
                .ok()
                .filter(|_| after[digits..].starts_with(PLACEHOLDER_CLOSE))
                .and_then(|i| self.html.get(i));
            match figure {
                Some(html) => {
                    out.push_str(html);
                    rest = &after[digits + PLACEHOLDER_CLOSE.len()..];
                }
                None => {
                    out.push_str(&self.open);
                    rest = after;
                }
            }
        }
        out.push_str(rest);
        out
    }
}

/// `<figure class="{class}">` around an `<img>` whose source is `svg`, normalized and embedded as
/// a `data:image/svg+xml` URI, or `None` if usvg rejects it.
///
/// **The SVG goes in as an `<img>`, never inline.**  Inline `<svg>` can carry `<script>`,
/// `foreignObject`, and `on*=` handlers; an SVG loaded as an image runs no script and fetches
/// nothing, by browser design.  [`normalize_svg`] is the second layer — it re-serializes through
/// usvg's tree, which cannot express any of that — and it converts text to paths, without which
/// a formula's KaTeX glyphs would not display in a browser at all.
fn svg_figure(svg: &str, class: &str, alt: &str) -> Option<String> {
    let svg = normalize_svg(svg).ok()?;
    Some(format!(
        "<figure class=\"{class}\"><img alt=\"{alt}\" src=\"data:image/svg+xml;base64,{}\"></figure>",
        BASE64.encode(svg)
    ))
}

// ── Mermaid diagrams ──────────────────────────────────────────────────────

/// Replace each mermaid fence with a [`Figures`] placeholder for its [`svg_figure`], preserving the
/// original events on render failure so the diagram source is never lost.
///
/// Language matching is case-insensitive, like the in-app `promote_diagram_code_blocks`.
fn replace_mermaid_with_figure<'a>(
    events: Vec<Event<'a>>,
    figures: &mut Figures,
) -> Vec<Event<'a>> {
    let mut out: Vec<Event<'_>> = Vec::with_capacity(events.len());
    let mut iter = events.into_iter();
    while let Some(event) = iter.next() {
        let lang = match &event {
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang)))
                if lang.as_ref().eq_ignore_ascii_case("mermaid") =>
            {
                Some(lang.clone())
            }
            _ => None,
        };
        if lang.is_none() {
            out.push(event);
            continue;
        }
        // Collect Text events to the matching end, then either emit a placeholder or replay
        // the originals for the default serializer's fallback.
        let mut buffered: Vec<Event<'_>> = vec![event];
        let mut source = String::new();
        for inner in iter.by_ref() {
            match inner {
                Event::End(TagEnd::CodeBlock) => {
                    buffered.push(Event::End(TagEnd::CodeBlock));
                    break;
                }
                Event::Text(ref t) => {
                    source.push_str(t);
                    buffered.push(inner);
                }
                other => {
                    // Shouldn't occur inside a fenced code block; treat as text and preserve.
                    buffered.push(other);
                }
            }
        }
        match render_mermaid_figure(&source) {
            Some(html) => out.push(figures.placeholder(html)),
            None => {
                // Fall back to the code block; a per-diagram failure is not fatal to the export.
                out.extend(buffered);
            }
        }
    }
    out
}

/// Syntax-highlight each fenced code block whose info string names a known language, replacing
/// its `Text` events with one `Event::Html` of escaped text and `<span class="hl-…">` runs
/// ([`highlighted_code_html`]).  The `Start` / `End` events are kept, so pulldown still writes
/// the `<pre><code class="language-…">` wrapper.
///
/// Uses the in-app tokenizer — same language lookup, same caps, same seven classes — so the
/// export colors what the terminal colors.  A block the highlighter declines (unknown
/// language, over a cap, a grammar error) keeps its original events and exports plain.
///
/// The emitted markup still passes through [`sanitize_body`], whose allowlist already
/// permits `span` and `class`; every byte of code text is escaped here regardless.
fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
    let mut out: Vec<Event<'_>> = Vec::with_capacity(events.len());
    let mut iter = events.into_iter();
    while let Some(event) = iter.next() {
        let lang = match &event {
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang))) if !lang.is_empty() => {
                lang.clone()
            }
            _ => {
                out.push(event);
                continue;
            }
        };
        out.push(event);
        let mut buffered: Vec<Event<'_>> = Vec::new();
        let mut source = String::new();
        let mut end = None;
        for inner in iter.by_ref() {
            match inner {
                Event::End(TagEnd::CodeBlock) => {
                    end = Some(inner);
                    break;
                }
                Event::Text(ref t) => {
                    source.push_str(t);
                    buffered.push(inner);
                }
                other => buffered.push(other),
            }
        }
        // Anything but text inside the fence is unexpected; leave such a block as it was.
        let all_text = buffered.iter().all(|e| matches!(e, Event::Text(_)));
        match all_text
            .then(|| highlighted_code_html(&lang, &source))
            .flatten()
        {
            Some(html) => out.push(Event::Html(CowStr::Boxed(html.into_boxed_str()))),
            None => out.extend(buffered),
        }
        out.extend(end);
    }
    out
}

/// The escaped, span-wrapped body of one code block, or `None` when the highlighter has
/// nothing to say about it.
///
/// Lines are split exactly as `Renderer::render_code_block` splits them, so the token rows
/// line up with the text they describe.  [`highlight::highlight_block_unbudgeted`] compiles a
/// cold grammar on this thread rather than deferring to the background worker: the export
/// runs on its own worker thread, with no frame budget to protect, and must not come out
/// plain just because the editor hasn't displayed that language yet.
fn highlighted_code_html(lang: &str, source: &str) -> Option<String> {
    let mut lines: Vec<&str> = source.split('\n').collect();
    let trailing_newline = lines.last() == Some(&"");
    if trailing_newline {
        lines.pop();
    }
    let tokens = highlight::highlight_block_unbudgeted(Some(lang), &lines);
    if tokens.is_empty() {
        return None;
    }
    let mut html = String::with_capacity(source.len() * 2);
    for (i, line) in lines.iter().enumerate() {
        // Token ranges are char indices; `byte[c]` is char `c`'s byte offset, with the
        // line's length appended so a range ending at the last char maps too.
        let byte: Vec<usize> = line
            .char_indices()
            .map(|(b, _)| b)
            .chain([line.len()])
            .collect();
        let chars = byte.len() - 1;
        let mut col = 0;
        for token in tokens.get(i).map(Vec::as_slice).unwrap_or(&[]) {
            let start = token.range.start.min(chars);
            let end = token.range.end.min(chars);
            if start < col || start >= end {
                continue;
            }
            push_html_escaped(&mut html, &line[byte[col]..byte[start]]);
            html.push_str("<span class=\"");
            html.push_str(token_css_class(token.class));
            html.push_str("\">");
            push_html_escaped(&mut html, &line[byte[start]..byte[end]]);
            html.push_str("</span>");
            col = end;
        }
        push_html_escaped(&mut html, &line[byte[col]..]);
        if i + 1 < lines.len() || trailing_newline {
            html.push('\n');
        }
    }
    Some(html)
}

/// The stylesheet class for a token — one per [`TokenClass`], styled in
/// `config/export/default.css`.
fn token_css_class(class: TokenClass) -> &'static str {
    match class {
        TokenClass::Keyword => "hl-keyword",
        TokenClass::String => "hl-string",
        TokenClass::Comment => "hl-comment",
        TokenClass::Number => "hl-number",
        TokenClass::Type => "hl-type",
        TokenClass::Function => "hl-function",
        TokenClass::Attribute => "hl-attribute",
    }
}

/// Render mermaid `source` to a `<figure class="mermaid-diagram">`, or `None` on any failure.
fn render_mermaid_figure(source: &str) -> Option<String> {
    let svg = diagram::render_mermaid_svg(source).ok()?;
    svg_figure(&svg, "mermaid-diagram", "mermaid diagram")
}

// ── Display math ──────────────────────────────────────────────────────────

/// Rewrite math events in the stream, mirroring the terminal's promotion
/// rules (`markdown::parser::post_pass::promote_display_math_paragraphs`):
///
/// * A paragraph whose body is **only** display math (one or more
///   `$$…$$`, plus whitespace and breaks) is a *figure* paragraph: the
///   enclosing `<p>` is dropped (a block-level figure/code block can't nest
///   in `<p>`) and each formula becomes its own block.  With figures on it
///   becomes an SVG `<figure class="math-formula">`; with figures off,
///   or on a render failure, it becomes a fenced `math` code block
///   (`push_display_math_source_block`) — the styled, padded box mermaid's
///   non-inlined fallback gets, delimiters removed — never loose `$$…$$`
///   text.
/// * Everywhere else — inline `$…$`, display math mixed with other
///   inlines, or math in a heading / list item — the math collapses to
///   its literal `$…$` / `$$…$$` source, exactly as the terminal shows
///   un-promoted math.
///
/// Enabling `Options::ENABLE_MATH` is what makes these events exist, so
/// this pass must run whenever that option is set — otherwise pulldown's
/// HTML writer would emit a bare `<span class="math">` wrapper (no KaTeX /
/// MathJax ships with the export, so it would render as raw source anyway,
/// only less predictably).
///
/// The figure goes through [`svg_figure`], like mermaid's, so RaTeX's
/// output reaches the export only as a normalized SVG inside an `<img>`.
fn replace_math<'a>(
    events: Vec<Event<'a>>,
    render_figures: bool,
    figures: &mut Figures,
) -> Vec<Event<'a>> {
    let mut out: Vec<Event<'_>> = Vec::with_capacity(events.len());
    let mut iter = events.into_iter();
    while let Some(event) = iter.next() {
        match event {
            Event::Start(Tag::Paragraph) => {
                // Buffer the paragraph body up to its close (paragraphs
                // never nest in CommonMark, so the first End wins).
                let mut body: Vec<Event<'_>> = Vec::new();
                for inner in iter.by_ref() {
                    if matches!(inner, Event::End(TagEnd::Paragraph)) {
                        break;
                    }
                    body.push(inner);
                }
                if is_display_math_only(&body) {
                    // A figure paragraph: drop the enclosing `<p>` (a
                    // block-level `<figure>` / `<pre>` can't nest in `<p>`)
                    // and emit one block per formula — an SVG
                    // `<figure>` when figures are on and the render
                    // succeeds, otherwise a fenced `math` code block (the
                    // export peer of the in-app figures-off `math` block,
                    // and the parallel of mermaid's non-inlined code-block
                    // fallback).  Whitespace text and breaks were only
                    // separators between formulas — drop them with the `<p>`.
                    for inner in body {
                        if let Event::DisplayMath(source) = inner {
                            if render_figures {
                                push_display_math_figure(&mut out, &source, figures);
                            } else {
                                push_display_math_source_block(&mut out, &source);
                            }
                        }
                    }
                } else {
                    out.push(Event::Start(Tag::Paragraph));
                    for inner in body {
                        push_math_as_literal(&mut out, inner);
                    }
                    out.push(Event::End(TagEnd::Paragraph));
                }
            }
            other => push_math_as_literal(&mut out, other),
        }
    }
    out
}

/// True when `body` (a buffered paragraph's inner events) holds at least
/// one display formula and nothing but display math, whitespace text, and
/// line breaks — the same shape `collect_display_math_only` recognises in
/// the terminal promotion pass.
fn is_display_math_only(body: &[Event<'_>]) -> bool {
    let mut saw_display = false;
    for ev in body {
        match ev {
            Event::DisplayMath(_) => saw_display = true,
            Event::Text(t) if t.trim().is_empty() => {}
            Event::SoftBreak | Event::HardBreak => {}
            _ => return false,
        }
    }
    saw_display
}

/// Push `event`, converting any math to its literal source text
/// (`$…$` / `$$…$$`) and passing everything else through untouched.
fn push_math_as_literal<'a>(out: &mut Vec<Event<'a>>, event: Event<'a>) {
    match event {
        Event::InlineMath(source) => out.push(Event::Text(literal_math(&source, false))),
        Event::DisplayMath(source) => out.push(Event::Text(literal_math(&source, true))),
        other => out.push(other),
    }
}

/// Emit one display formula as a [`Figures`] placeholder for a `<figure class="math-formula">`,
/// or fall back to a fenced `math` code block ([`push_display_math_source_block`]) on render
/// failure — the same styled, padded box a non-inlined mermaid diagram gets, not loose `$$…$$`
/// text.
fn push_display_math_figure(out: &mut Vec<Event<'_>>, source: &str, figures: &mut Figures) {
    match render_math_figure(source) {
        Some(html) => out.push(figures.placeholder(html)),
        None => push_display_math_source_block(out, source),
    }
}

/// Emit one display formula as a fenced `math` code block — the styled,
/// padded box mermaid's non-inlined fallback produces (`<pre><code
/// class="language-math">`, painted by the existing code-block rules), with
/// the `$$` delimiters removed: pulldown already strips them from
/// `Event::DisplayMath`, and the one surrounding newline on each side (the
/// `$$` sitting on their own lines) is trimmed the way the in-app
/// figures-off `math` block does.  Used whenever a display formula is *not*
/// rendered — figures off, or a render failure — so it reads as a
/// formula rather than as source text stranded in a paragraph.
///
/// Emitted as real code-block events, not raw `Event::Html`, so pulldown's
/// writer HTML-escapes the body: no LaTeX can inject markup into the
/// exported file, the same guarantee `literal_math` gives.
fn push_display_math_source_block(out: &mut Vec<Event<'_>>, source: &str) {
    let trimmed = source.strip_prefix('\n').unwrap_or(source);
    let body = trimmed.strip_suffix('\n').unwrap_or(trimmed);
    out.push(Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(
        CowStr::Borrowed("math"),
    ))));
    out.push(Event::Text(CowStr::Boxed(
        body.to_string().into_boxed_str(),
    )));
    out.push(Event::End(TagEnd::CodeBlock));
}

/// The literal source form of a math span — `$source$` (inline) or
/// `$$source$$` (display) — as an owned `CowStr`.  Emitted as an
/// `Event::Text`, so pulldown's writer HTML-escapes it: the delimiters and
/// LaTeX read back verbatim, exactly as the terminal shows un-rendered
/// math.
fn literal_math(source: &str, display: bool) -> CowStr<'static> {
    let delim = if display { "$$" } else { "$" };
    CowStr::Boxed(format!("{delim}{source}{delim}").into_boxed_str())
}

/// Reference cell height (px) the exporter renders display math at.  The
/// in-app raster sizes off the *terminal's* real cell height; the exporter
/// has none, so it passes this instead — larger than the 16 px terminal
/// default so a formula reads at a comfortable display size in the browser
/// rather than at the cramped ~1-line size a 16 px cell gives.  It sets the
/// SVG's intrinsic size, which is the size the browser shows it at.
/// `diagram::render_latex_svg` scales the formula from it exactly as the
/// TUI path does, so the export tracks the in-app look, only bigger.
const HTML_EXPORT_MATH_CELL_PX: u16 = 24;

/// Render display-math `source` to a `<figure class="math-formula">`, or
/// `None` on any failure (so the caller falls back to a code block).
/// Glyphs are drawn opaque black for a light document background.
fn render_math_figure(source: &str) -> Option<String> {
    let svg = diagram::render_latex_svg(
        source,
        [0, 0, 0, 255],
        Some((HTML_EXPORT_MATH_CELL_PX, HTML_EXPORT_MATH_CELL_PX)),
    )
    .ok()?;
    svg_figure(&svg, "math-formula", "math formula")
}

// ── Out-of-folder images ──────────────────────────────────────────────────

/// The local images `markdown` references that an embedding export would read from *outside*
/// `source_dir`: through `..`, by absolute path or `file:` URL, or via a symlink leading out.
/// Canonical, deduped, in document order.  The export modal lists these and asks before embedding
/// any of them, since the exported file is typically shared and an out-of-folder image may be one
/// the document's author has no business seeing — see `docs/dev/security-invariants.md`.
///
/// Read off the sanitized body through the same `img src` hook [`render_html`] resolves images
/// with, so raw-HTML `<img>` tags are listed exactly like Markdown images, and nothing is listed
/// that the export would not reach.
pub fn outside_images(markdown: &str, source_dir: &Path) -> Vec<PathBuf> {
    let mut body = String::new();
    cmark_html::push_html(
        &mut body,
        Parser::new_ext(markdown, parser_options(markdown)),
    );
    let sources = Arc::new(Mutex::new(Vec::<String>::new()));
    let record = Arc::clone(&sources);
    sanitize_body(&body, move |src| {
        record
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(src.to_owned());
        Some(Cow::Borrowed(src))
    });
    let sources = std::mem::take(&mut *sources.lock().unwrap_or_else(|e| e.into_inner()));

    let canon_dir = source_dir.canonicalize().ok();
    let mut out: Vec<PathBuf> = Vec::new();
    for src in sources {
        if let Some(image) = local_image(&src, source_dir, canon_dir.as_deref()) {
            if !image.inside && !out.contains(&image.canonical) {
                out.push(image.canonical);
            }
        }
    }
    out
}

// ── HTML escaping ─────────────────────────────────────────────────────────

/// Escape the five XML metacharacters.  For `<title>` and highlighted code
/// ([`push_html_escaped`]); the rest of the body is escaped by `pulldown_cmark::html`.
fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    push_html_escaped(&mut out, s);
    out
}

/// [`html_escape`], appending to `out` rather than allocating.
fn push_html_escaped(out: &mut String, s: &str) {
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(ch),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::tempdir;

    fn opts_inline_css() -> HtmlExportOptions {
        HtmlExportOptions {
            stylesheet: Stylesheet::Inline("body { color: red; }".into()),
            ..HtmlExportOptions::default()
        }
    }

    #[test]
    fn renders_basic_markdown() {
        let html = render_html("# Hello\n\nWorld", &opts_inline_css()).unwrap();
        assert!(html.contains("<h1 id=\"hello\">Hello</h1>"));
        assert!(html.contains("<p>World</p>"));
    }

    #[test]
    fn fenced_code_with_a_known_language_is_highlighted() {
        let md = "```rust\nfn main() { let s = \"<b>\"; } // done\n```\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            html.contains(
                "<pre><code class=\"language-rust\"><span class=\"hl-keyword\">fn</span>"
            ),
            "wrapper kept and keyword classified:\n{html}"
        );
        assert!(
            html.contains("<span class=\"hl-function\">main</span>"),
            "{html}"
        );
        assert!(
            html.contains("<span class=\"hl-comment\">// done</span>"),
            "{html}"
        );
        // Code text stays escaped inside a token span.
        assert!(html.contains("&lt;b&gt;"), "{html}");
        assert!(!html.contains("<b>"), "{html}");
        // The block's line structure is unchanged: one line, then the closing tag.
        assert!(html.contains("// done</span>\n</code></pre>"), "{html}");
    }

    /// Token ranges are char indices; a multi-byte char must not shift the spans after it.
    #[test]
    fn non_ascii_code_keeps_token_boundaries() {
        let md = "```rust\nlet é = \"ü→\"; // ñ\n```\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            html.contains("<span class=\"hl-string\">\"ü→\"</span>"),
            "{html}"
        );
        assert!(
            html.contains("<span class=\"hl-comment\">// ñ</span>\n</code>"),
            "{html}"
        );
    }

    #[test]
    fn multi_line_code_keeps_every_line_and_blank_lines() {
        let md = "```python\ndef f():\n\n    return 1\n```\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            html.contains(
                "<span class=\"hl-keyword\">def</span> <span class=\"hl-function\">f</span>"
            ),
            "{html}"
        );
        assert!(
            html.contains(":\n\n    <span class=\"hl-keyword\">return</span> "),
            "{html}"
        );
        assert!(
            html.contains("<span class=\"hl-number\">1</span>\n</code></pre>"),
            "{html}"
        );
    }

    #[test]
    fn unknown_language_and_unlabeled_code_export_plain() {
        let md = "```no-such-lang\nfn x\n```\n\n```\nfn y\n```\n\n    fn z\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(!html.contains("hl-"), "{html}");
        assert!(html.contains("<pre><code class=\"language-no-such-lang\">fn x\n</code></pre>"));
        assert!(html.contains("<pre><code>fn y\n</code></pre>"), "{html}");
        assert!(html.contains("<pre><code>fn z\n</code></pre>"), "{html}");
    }

    /// Raw HTML in the document can't smuggle markup into a highlighted block: the text is
    /// escaped before any span is written, and the sanitizer still runs over the result.
    #[test]
    fn highlighted_code_cannot_inject_markup() {
        let md = "```html\n<script>alert(1)</script><img src=x onerror=alert(1)>\n```\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("hl-"), "html should highlight:\n{html}");
        assert!(!html.contains("<script"), "{html}");
        assert!(!html.contains("<img"), "{html}");
        assert!(html.contains("&lt;"), "{html}");
    }

    #[test]
    fn builtin_stylesheet_styles_every_token_class() {
        for class in [
            TokenClass::Keyword,
            TokenClass::String,
            TokenClass::Comment,
            TokenClass::Number,
            TokenClass::Type,
            TokenClass::Function,
            TokenClass::Attribute,
        ] {
            let selector = format!(".{} ", token_css_class(class));
            assert!(
                BUILTIN_STYLESHEET.contains(&selector),
                "default.css has no rule for {selector}"
            );
        }
    }

    /// Without the extension the export reproduces the rule-plus-setext-H2 misparse.
    #[test]
    fn frontmatter_is_omitted_from_the_export() {
        let md = "---\ntitle: Foo\ndate: 2026-01-01\n---\n\n# Heading\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("<h1 id=\"heading\">Heading</h1>"));
        assert!(!html.contains("title: Foo"), "got: {html}");
        assert!(!html.contains("<h2>"), "got: {html}");
    }

    /// The writer emits *nothing* for a metadata block, so an unanchored extension would drop a
    /// section a mid-document `---` pair brackets — silently, and only in the export.
    #[test]
    fn a_mid_document_rule_pair_is_not_dropped_from_the_export() {
        let md = "Intro.\n\n---\n## Section 2\n\nText.\n\n---\n## Section 3\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("Section 2"), "got: {html}");
        assert!(html.contains("Text."), "got: {html}");
        assert!(html.contains("Section 3"), "got: {html}");
    }

    /// The export's gate must be the renderer's, or the two disagree about what frontmatter is.
    #[test]
    fn a_toml_opening_file_does_not_drop_a_later_dash_pair() {
        let md = "+++\na = 1\n+++\n\n---\nSection\n---\n\nEnd.\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(!html.contains("a = 1"), "got: {html}");
        assert!(html.contains("Section"), "got: {html}");
    }

    #[test]
    fn renders_gfm_table() {
        let md = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("<table>"));
        assert!(html.contains("<th>a</th>"));
        assert!(html.contains("<td>1</td>"));
    }

    #[test]
    fn renders_task_list_and_strikethrough() {
        let md = "- [x] done\n- [ ] todo\n\n~~gone~~";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("type=\"checkbox\""));
        assert!(html.contains("<del>gone</del>"));
    }

    #[test]
    fn strips_raw_html_block() {
        let md = "text\n\n<script>alert('x')</script>\n\nmore";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            !html.contains("<script>") && !html.contains("alert"),
            "raw <script> must be stripped with its contents — got:\n{html}"
        );
        assert!(html.contains("more"));
    }

    #[test]
    fn strips_raw_html_inline() {
        let md = "a <b onclick=\"x\">inline</b> c";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            !html.contains("onclick"),
            "inline HTML event handlers must be stripped — got:\n{html}"
        );
        assert!(
            html.contains("<b>inline</b>"),
            "the tag itself is allowed:\n{html}"
        );
    }

    /// The raw HTML READMEs lean on survives the sanitizer.
    #[test]
    fn keeps_readme_html() {
        let md = "<p align=\"center\"><img src=\"logo.png\" width=\"120\" alt=\"logo\"></p>\n\n\
                  <details open><summary>More</summary>\n\nHidden *text*.\n\n</details>\n\n\
                  Press <kbd>Ctrl</kbd>+<kbd>S</kbd>, H<sub>2</sub>O, x<sup>2</sup>,<br>next line.\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        for needle in [
            "<p align=\"center\">",
            "width=\"120\"",
            "src=\"logo.png\"",
            "<details open=\"\">",
            "<summary>More</summary>",
            "<em>text</em>",
            "<kbd>Ctrl</kbd>",
            "<sub>2</sub>",
            "<sup>2</sup>",
            "<br>",
        ] {
            assert!(html.contains(needle), "missing {needle}:\n{html}");
        }
    }

    /// `<style>` is dropped with its rules, and inline styles are dropped except the
    /// `text-align` pulldown writes for table column alignment.
    #[test]
    fn strips_css_except_table_alignment() {
        let md = "<style>body { background: url(https://t.example/x) }</style>\n\n\
                  <p style=\"position: fixed; background: url(https://t.example/y)\">p</p>\n\n\
                  | a | b |\n|:-:|--:|\n| 1 | 2 |\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            !html.contains("t.example"),
            "no CSS fetch may survive:\n{html}"
        );
        assert!(!html.contains("position"), "{html}");
        assert!(html.contains("text-align:center"), "{html}");
        assert!(html.contains("text-align:right"), "{html}");
    }

    #[test]
    fn task_list_checkboxes_survive() {
        let md = "- [x] done\n- [ ] todo\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert_eq!(html.matches("type=\"checkbox\"").count(), 2, "{html}");
        assert!(html.contains("checked"), "{html}");
        assert!(html.contains("disabled"), "{html}");
    }

    #[test]
    fn footnotes_keep_their_anchors() {
        let md = "Claim.[^1]\n\n[^1]: Source.\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("class=\"footnote-reference\""), "{html}");
        assert!(html.contains("href=\"#1\""), "{html}");
        assert!(html.contains("id=\"1\""), "{html}");
    }

    #[test]
    fn escapes_title() {
        let mut opts = opts_inline_css();
        opts.title = Some("A <script>x</script> & B".into());
        let html = render_html("", &opts).unwrap();
        assert!(html.contains("<title>A &lt;script&gt;x&lt;/script&gt; &amp; B</title>"));
        assert!(!html.contains("<title>A <script>"));
    }

    #[test]
    fn embeds_builtin_stylesheet() {
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Builtin,
            ..HtmlExportOptions::default()
        };
        let html = render_html("hi", &opts).unwrap();
        assert!(html.contains("markdown-body"));
        assert!(html.contains("<style>"));
    }

    #[test]
    fn footnotes_render_with_bracket_convention() {
        // The bundled CSS adds the `[ ]` brackets by targeting this exact markup.
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Builtin,
            ..HtmlExportOptions::default()
        };
        let html = render_html("Claim.[^1]\n\n[^1]: Source.\n", &opts).unwrap();
        assert!(
            html.contains("<sup class=\"footnote-reference\"><a href=\"#1\">1</a></sup>"),
            "expected footnote-reference markup, got:\n{html}"
        );
        assert!(
            html.contains("sup.footnote-reference a::before { content: \"[\"; }"),
            "builtin CSS must add the opening bracket"
        );
        assert!(
            html.contains("sup.footnote-reference a::after { content: \"]\"; }"),
            "builtin CSS must add the closing bracket"
        );
    }

    #[test]
    fn stylesheet_from_config_value_parses() {
        assert!(matches!(
            Stylesheet::from_config_value("builtin"),
            Stylesheet::Builtin
        ));
        assert!(matches!(
            Stylesheet::from_config_value("BUILTIN"),
            Stylesheet::Builtin
        ));
        match Stylesheet::from_config_value("/etc/custom.css") {
            Stylesheet::Path(p) => assert_eq!(p, PathBuf::from("/etc/custom.css")),
            other => panic!("expected Path, got {other:?}"),
        }
    }

    #[test]
    fn stylesheet_path_read_failure_surfaces_error() {
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Path(PathBuf::from("/this/does/not/exist.css")),
            ..HtmlExportOptions::default()
        };
        let err = render_html("hi", &opts).unwrap_err();
        assert!(format!("{err:#}").contains("stylesheet"));
    }

    #[test]
    fn inline_images_embeds_local_png() {
        // 1x1 transparent PNG
        const ONE_PX_PNG: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,
            0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let dir = tempdir().unwrap();
        let img_path = dir.path().join("pixel.png");
        let mut f = std::fs::File::create(&img_path).unwrap();
        f.write_all(ONE_PX_PNG).unwrap();
        drop(f);

        let md = "![pixel](pixel.png)";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            images: ImageHandling::Embed,
            source_dir: Some(dir.path().to_path_buf()),
            approved_outside: Vec::new(),
            title: None,
            render_figures: false,
        };
        let html = render_html(md, &opts).unwrap();
        assert!(
            html.contains("src=\"data:image/png;base64,"),
            "expected base64 data URI, got:\n{html}"
        );
        assert!(!html.contains("src=\"pixel.png\""));
    }

    #[test]
    fn inline_images_leaves_remote_urls_untouched() {
        let md = "![cat](https://example.com/cat.png)";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            images: ImageHandling::Embed,
            source_dir: Some(PathBuf::from("/tmp")),
            approved_outside: Vec::new(),
            title: None,
            render_figures: false,
        };
        let html = render_html(md, &opts).unwrap();
        assert!(html.contains("src=\"https://example.com/cat.png\""));
    }

    #[test]
    fn inline_images_disabled_by_default() {
        let md = "![x](local.png)";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("src=\"local.png\""));
    }

    // ── Vuln 2: link-scheme sanitization ──────────────────────────────

    #[test]
    fn neutralizes_javascript_link_scheme() {
        let md = "[click](javascript:alert(document.cookie))";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            !html.contains("javascript:"),
            "javascript: href must be neutralized — got:\n{html}"
        );
        // The link loses its target, not its text.
        assert!(html.contains(">click</a>"), "{html}");
        assert!(!html.contains("href"), "{html}");
    }

    /// Every spelling a browser would still parse as a code-running scheme is refused.
    #[test]
    fn neutralizes_obfuscated_script_schemes() {
        let md = "[a](JaVaScRiPt:alert(1)) <a href=\"java&#9;script:alert(1)\">b</a> [c](vbscript:msgbox) \
                  [d](&#106;avascript:alert(1)) \
                  <a href=\"&#x6A;avascript:alert(1)\">e</a> <a href=\" javascript:alert(1)\">f</a> \
                  <a href=\"java&#10;script:alert(1)\">g</a>";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(!html.contains("href"), "no href may survive:\n{html}");
        for text in ["a", "b", "c", "d", "e", "f", "g"] {
            assert!(
                html.contains(&format!(">{text}</a>")),
                "{text} lost:\n{html}"
            );
        }
    }

    #[test]
    fn neutralizes_data_html_link_scheme() {
        let md = "[x](data:text/html;base64,PHNjcmlwdD4=) \
                  <a href=\"data:text/html,<script>alert(1)</script>\">y</a> \
                  <a href=\"data:image/svg+xml,x\">z</a>";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            !html.contains("data:"),
            "data: link must be neutralized:\n{html}"
        );
    }

    /// `data:` survives on `img src`, where a browser can only treat it as an image.
    #[test]
    fn keeps_data_image_sources() {
        let md = "<img src=\"data:image/png;base64,iVBORw0KGgo=\" alt=\"a\">";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(
            html.contains("src=\"data:image/png;base64,iVBORw0KGgo=\""),
            "{html}"
        );
    }

    #[test]
    fn preserves_link_schemes_and_relative_targets() {
        let md = "[a](https://example.com) [b](mailto:x@y.z) [c](./page.md) [d](#anchor) \
                  [e](foo/bar:baz) [f](file:///home/me/notes.md) [g](obsidian://open?vault=v) \
                  [h](vscode://file/src/main.rs) [i](zotero://select/items/ABC) \
                  <a href=\"x-devonthink-item://123\">j</a>";
        let html = render_html(md, &opts_inline_css()).unwrap();
        for href in [
            "https://example.com",
            "mailto:x@y.z",
            "./page.md",
            "#anchor",
            // A colon after a path segment is not a scheme.
            "foo/bar:baz",
            "file:///home/me/notes.md",
            "obsidian://open?vault=v",
            "vscode://file/src/main.rs",
            "zotero://select/items/ABC",
            "x-devonthink-item://123",
        ] {
            assert!(
                html.contains(&format!("href=\"{href}\"")),
                "{href} lost:\n{html}"
            );
        }
    }

    #[test]
    fn url_schemes_in_collects_scheme_tokens_minus_the_blocked_ones() {
        let found = url_schemes_in(
            "<a href=\"Obsidian://x\">a</a> 12:30 x-dt.item+1:y JavaScript: vbscript: data: 9file:z",
        );
        for scheme in ["obsidian", "x-dt.item+1", "file"] {
            assert!(found.contains(scheme), "{scheme} missing from {found:?}");
        }
        for scheme in BLOCKED_URL_SCHEMES {
            assert!(!found.contains(*scheme), "{scheme} must never be allowed");
        }
        assert!(
            !found.contains("12"),
            "a scheme starts with a letter: {found:?}"
        );
    }

    #[test]
    fn has_data_scheme_reads_urls_as_a_browser_does() {
        assert!(has_data_scheme("data:text/html,x"));
        assert!(has_data_scheme("  DATA:text/html,x"));
        assert!(has_data_scheme("\u{1}da\tta:x"));
        assert!(has_data_scheme("d\na\rta:x"));
        assert!(!has_data_scheme("dat"));
        assert!(!has_data_scheme("./data:x"));
        assert!(!has_data_scheme("https://data:x"));
    }

    // ── Heading anchors ────────────────────────────────────────────────

    /// The bug this fixed: headings exported without an `id`, so every `#anchor` link was dead.
    #[test]
    fn headings_carry_the_gfm_slug_an_anchor_link_names() {
        let md = "[Go](#getting-started)\n\n## Getting Started\n\n## Getting Started\n\n\
                  ### The `--doctor` *flag*\n\n# !!!\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(html.contains("href=\"#getting-started\""), "{html}");
        assert!(html.contains("<h2 id=\"getting-started\">"), "{html}");
        assert!(html.contains("<h2 id=\"getting-started-1\">"), "{html}");
        assert!(html.contains("<h3 id=\"the---doctor-flag\">"), "{html}");
        // A heading with nothing to slug gets no id rather than an empty one.
        assert!(html.contains("<h1>!!!</h1>"), "{html}");
    }

    /// The export's slugs are the in-app jump table's, so a fragment that works in edamame
    /// works in the exported file.
    #[test]
    fn heading_ids_match_the_in_app_anchor_table() {
        let md =
            "# Intro\n\n## Math $x^2$ and <kbd>K</kbd>\n\n## Intro\n\n## Note[^1]\n\n[^1]: n\n";
        let html = render_html(md, &opts_inline_css()).unwrap();
        let theme = crate::config::Theme::default();
        let parsed = crate::document::ParsedDoc::build(md, &theme, false, 4);
        for slug in parsed.heading_anchors.keys() {
            assert!(
                html.contains(&format!("id=\"{slug}\"")),
                "{slug} missing:\n{html}"
            );
        }
        assert_eq!(parsed.heading_anchors.len(), 4);
    }

    // ── Figures ────────────────────────────────────────────────────────

    /// A document cannot forge a figure placeholder: the nonce differs per export.
    #[test]
    fn figure_placeholders_cannot_be_forged() {
        let mut figures = Figures::new();
        let Event::Html(token) = figures.placeholder("<figure>F</figure>".into()) else {
            panic!("placeholder is raw HTML");
        };
        let forged = format!("{}0{PLACEHOLDER_CLOSE}", Figures::new().open);
        let body = format!("{forged}{token}");
        assert_eq!(
            figures.insert_into(&body),
            format!("{forged}<figure>F</figure>")
        );
    }

    /// The real placeholder, swallowed by an unclosed attribute in the document, is dropped
    /// rather than spliced into the attribute value (where the figure's `"` would break out).
    #[test]
    fn figure_placeholders_stay_out_of_attribute_values() {
        let mut figures = Figures::new();
        let Event::Html(token) = figures.placeholder("<figure>F</figure>".into()) else {
            panic!("placeholder is raw HTML");
        };
        let body = format!("<div title=\"\n{token}\n<p class=\"a\">after</p>");
        let html = figures.insert_into(&sanitize_body(&body, |src| Some(Cow::Borrowed(src))));
        assert!(!html.contains("<figure>"), "{html}");
    }

    #[test]
    fn figure_placeholders_survive_sanitization() {
        let mut figures = Figures::new();
        let Event::Html(token) = figures.placeholder("<figure>F</figure>".into()) else {
            panic!("placeholder is raw HTML");
        };
        let body = format!("<ul><li>a\n{token}</li></ul>");
        assert_eq!(
            figures.insert_into(&sanitize_body(&body, |src| Some(Cow::Borrowed(src)))),
            "<ul><li>a\n<figure>F</figure></li></ul>"
        );
    }

    /// The `data:image/svg+xml` payload of the first figure in `html`, decoded.
    fn first_figure_svg(html: &str) -> Option<String> {
        let marker = "src=\"data:image/svg+xml;base64,";
        let start = html.find(marker)? + marker.len();
        let end = start + html[start..].find('"')?;
        let bytes = BASE64.decode(&html.as_bytes()[start..end]).ok()?;
        String::from_utf8(bytes).ok()
    }

    // ── Vuln 3: mermaid export carries no raw SVG / script ─────────────

    #[test]
    fn mermaid_export_never_emits_raw_svg_or_script() {
        // Holds whether or not the live renderer is available: a success embeds a normalized SVG
        // as an `<img>`, a failure falls back to an escaped code block.
        let md = "```mermaid\nflowchart TD\n  A[\"<script>alert(1)</script>\"] --> B\n```";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            render_figures: true,
            ..HtmlExportOptions::default()
        };
        let html = render_html(md, &opts).unwrap();
        assert!(
            !html.contains("<svg"),
            "no inline SVG may reach the export:\n{html}"
        );
        assert!(!html.contains("foreignObject"));
        assert!(
            !html.contains("<script>"),
            "no executable <script> may reach the export:\n{html}"
        );
        if let Some(svg) = first_figure_svg(&html) {
            assert!(!svg.contains("<script"), "{svg}");
            assert!(!svg.contains("foreignObject"), "{svg}");
            assert!(!svg.contains("<text"), "text must be outlined:\n{svg}");
        }
    }

    // ── Display math ───────────────────────────────────────────────────

    /// A `$$...$$` paragraph exports as a `math-formula` figure — an SVG `<img>`, the same
    /// treatment mermaid gets — when figures are on.  The KaTeX faces are bundled into the shared
    /// fontdb, so this renders in CI without system fonts.
    #[test]
    fn display_math_exports_as_an_svg_figure() {
        let md = "$$\nx^2 + y^2 = z^2\n$$\n";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            render_figures: true,
            ..HtmlExportOptions::default()
        };
        let html = render_html(md, &opts).unwrap();
        assert!(
            html.contains("<figure class=\"math-formula\">"),
            "expected a math-formula figure:\n{html}"
        );
        let svg = first_figure_svg(&html).expect("formula is an SVG data URI");
        // Glyphs are outlined: a browser has no KaTeX fonts to draw `<text>` with.
        assert!(!svg.contains("<text"), "text must be outlined:\n{svg}");
        assert!(svg.contains("<path"), "{svg}");
        // Embedded as an image, never inlined as SVG / math markup.
        assert!(!html.contains("<svg"), "no inline SVG:\n{html}");
        assert!(
            !html.contains("class=\"math math-"),
            "pulldown's math span must not survive:\n{html}"
        );
    }

    /// The exported formula is sized from `HTML_EXPORT_MATH_CELL_PX`, not the bare 16 px
    /// terminal-cell fallback, so a display equation reads at a comfortable size in the browser
    /// instead of a cramped ~1-line one.  The SVG's intrinsic height is what the browser shows.
    #[test]
    fn exported_display_math_is_rendered_large_enough_to_read() {
        let md = "$$\nx^2 + y^2 = z^2\n$$\n";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            render_figures: true,
            ..HtmlExportOptions::default()
        };
        let html = render_html(md, &opts).unwrap();
        let svg = first_figure_svg(&html).expect("formula is an SVG data URI");
        let attr = "height=\"";
        let start = svg.find(attr).expect("svg height") + attr.len();
        let h: f32 = svg[start..start + svg[start..].find('"').unwrap()]
            .parse()
            .expect("numeric height");
        // A single-line display formula at the 24 px reference cell
        // (`HTML_EXPORT_MATH_CELL_PX`) is tens of pixels tall —
        // comfortably past the ~18 px a 16 px-cell fallback gave, and
        // nowhere near runaway.
        assert!(
            (28.0..=160.0).contains(&h),
            "exported formula height {h}px out of range"
        );
    }

    /// With figures disabled, a display-math paragraph renders as a
    /// fenced `math` code block — the same styled, padded box mermaid's
    /// non-inlined fallback gets — with the `$$` delimiters removed, never
    /// loose `$$...$$` text in a paragraph and never a bare math span.
    #[test]
    fn display_math_off_renders_as_a_math_code_block() {
        let md = "$$\na + b\n$$\n";
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            render_figures: false,
            ..HtmlExportOptions::default()
        };
        let html = render_html(md, &opts).unwrap();
        // Same box as a non-inlined mermaid diagram: a `<pre><code
        // class="language-math">` block, painted by the existing code-block
        // CSS — not a `<figure>`, not a math span, not literal `$$`.
        assert!(
            html.contains("<pre><code class=\"language-math\">"),
            "expected a math code block:\n{html}"
        );
        assert!(html.contains("a + b"), "formula body kept:\n{html}");
        assert!(!html.contains("$$"), "delimiters must be stripped:\n{html}");
        assert!(!html.contains("<figure"), "no figure when off:\n{html}");
        assert!(
            !html.contains("class=\"math math-"),
            "no math span:\n{html}"
        );
    }

    /// A display formula that can't be rendered (here: over the
    /// `MAX_LATEX_SOURCE_BYTES` cap, so `render_latex_svg` refuses it)
    /// falls back to the same `math` code block, not loose `$$...$$` text —
    /// figures on, but the render fails.
    #[test]
    fn oversized_display_math_falls_back_to_a_code_block() {
        let huge = "1+".repeat(64 * 1024); // well past MAX_LATEX_SOURCE_BYTES
        let md = format!("$$\n{huge}1\n$$\n");
        let opts = HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            render_figures: true,
            ..HtmlExportOptions::default()
        };
        let html = render_html(&md, &opts).unwrap();
        assert!(
            html.contains("<pre><code class=\"language-math\">"),
            "render failure must fall back to a math code block, not a figure or literal text"
        );
        assert!(
            !html.contains("data:image/png"),
            "no PNG when the render failed:\n{}",
            &html[..html.len().min(400)]
        );
    }

    /// Inline `$...$` math always stays literal source (delimiters kept),
    /// matching the terminal preview — regardless of the figures toggle.
    #[test]
    fn inline_math_stays_literal_source() {
        let md = "Solve $a^2 + b^2$ please.\n";
        for render_figures in [true, false] {
            let opts = HtmlExportOptions {
                stylesheet: Stylesheet::Inline(String::new()),
                render_figures,
                ..HtmlExportOptions::default()
            };
            let html = render_html(md, &opts).unwrap();
            assert!(
                html.contains("$a^2 + b^2$"),
                "inline math must read back as literal source (figures={render_figures}):\n{html}"
            );
            assert!(
                !html.contains("class=\"math math-"),
                "no math span (figures={render_figures}):\n{html}"
            );
        }
    }

    // ── Vuln 4: image inlining stays within the source tree ────────────

    fn write_one_px_png(path: &Path) {
        const ONE_PX_PNG: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,
            0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        std::fs::write(path, ONE_PX_PNG).unwrap();
    }

    fn inline_opts(source: &Path, approved_outside: Vec<PathBuf>) -> HtmlExportOptions {
        HtmlExportOptions {
            stylesheet: Stylesheet::Inline(String::new()),
            images: ImageHandling::Embed,
            source_dir: Some(source.to_path_buf()),
            approved_outside,
            render_figures: false,
            ..HtmlExportOptions::default()
        }
    }

    /// A shared root holding `secret.png` beside a `docs/` source folder.
    fn root_with_docs() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let root = tempdir().unwrap();
        let secret = root.path().join("secret.png");
        write_one_px_png(&secret);
        let source = root.path().join("docs");
        std::fs::create_dir(&source).unwrap();
        (root, secret.canonicalize().unwrap(), source)
    }

    #[test]
    fn inline_images_skips_an_unapproved_absolute_path() {
        let (_root, secret, source) = root_with_docs();
        let md = format!("![x]({})", secret.display());
        let html = render_html(&md, &inline_opts(&source, Vec::new())).unwrap();
        assert!(
            !html.contains("data:image/png"),
            "an unapproved out-of-folder path must not be inlined:\n{html}"
        );
    }

    #[test]
    fn inline_images_skips_unapproved_parent_traversal() {
        let (_root, _secret, source) = root_with_docs();
        let html = render_html("![x](../secret.png)", &inline_opts(&source, Vec::new())).unwrap();
        assert!(
            !html.contains("data:image/png"),
            "unapproved ../ traversal must not be inlined:\n{html}"
        );
        assert!(
            html.contains("src=\"../secret.png\""),
            "left as a link:\n{html}"
        );
    }

    #[test]
    fn inline_images_embeds_an_approved_outside_image() {
        let (_root, secret, source) = root_with_docs();
        let opts = inline_opts(&source, vec![secret]);
        let html = render_html("![x](../secret.png)", &opts).unwrap();
        assert!(html.contains("src=\"data:image/png;base64,"), "{html}");
    }

    /// Approval covers the listed file only, not everything outside the folder.
    #[test]
    fn approval_does_not_extend_to_an_unlisted_outside_image() {
        let (root, secret, source) = root_with_docs();
        write_one_px_png(&root.path().join("other.png"));
        let md = "![a](../secret.png) ![b](../other.png)";
        let html = render_html(md, &inline_opts(&source, vec![secret])).unwrap();
        assert_eq!(html.matches("data:image/png").count(), 1, "{html}");
        assert!(html.contains("src=\"../other.png\""), "{html}");
    }

    #[test]
    fn outside_images_lists_parent_and_absolute_references_once() {
        let (_root, secret, source) = root_with_docs();
        write_one_px_png(&source.join("inside.png"));
        let md = format!(
            "![a](../secret.png) ![b]({}) ![c](inside.png) ![d](../docs/inside.png) \
             ![e](../missing.png) ![f](https://example.com/x.png)",
            secret.display()
        );
        assert_eq!(outside_images(&md, &source), vec![secret]);
    }

    #[test]
    fn outside_images_ignores_non_image_files() {
        let root = tempdir().unwrap();
        std::fs::write(root.path().join("notes.txt"), "private").unwrap();
        let source = root.path().join("docs");
        std::fs::create_dir(&source).unwrap();
        assert!(outside_images("![x](../notes.txt)", &source).is_empty());
    }

    /// A symlink inside the folder that leads out counts as outside, so it is listed for approval
    /// rather than embedded silently.
    #[cfg(unix)]
    #[test]
    fn outside_images_sees_through_a_symlink_leading_out() {
        let (_root, secret, source) = root_with_docs();
        std::os::unix::fs::symlink(&secret, source.join("link.png")).unwrap();
        assert_eq!(outside_images("![x](link.png)", &source), vec![secret]);
        let html = render_html("![x](link.png)", &inline_opts(&source, Vec::new())).unwrap();
        assert!(!html.contains("data:image/png"), "{html}");
    }

    // ── Raw-HTML images and sealed (custom-export) handling ────────────

    #[test]
    fn raw_html_images_are_listed_and_embedded_like_markdown_ones() {
        let (_root, secret, source) = root_with_docs();
        write_one_px_png(&source.join("inside.png"));
        let md = "<img src=\"../secret.png\" width=\"10\"> <img src=\"inside.png\">";
        assert_eq!(outside_images(md, &source), vec![secret.clone()]);

        let html = render_html(md, &inline_opts(&source, Vec::new())).unwrap();
        assert_eq!(
            html.matches("data:image/png").count(),
            1,
            "inside only:\n{html}"
        );
        assert!(
            html.contains("src=\"../secret.png\""),
            "left as a link:\n{html}"
        );

        let html = render_html(md, &inline_opts(&source, vec![secret])).unwrap();
        assert_eq!(html.matches("data:image/png").count(), 2, "{html}");
    }

    /// A reference is read as a browser would: percent-escapes decoded, query dropped.
    #[test]
    fn embedded_paths_are_percent_decoded() {
        let dir = tempdir().unwrap();
        write_one_px_png(&dir.path().join("my pic.png"));
        let md = "![a](<my pic.png>) ![b](my%20pic.png?v=1)";
        let html = render_html(md, &inline_opts(dir.path(), Vec::new())).unwrap();
        assert_eq!(html.matches("data:image/png").count(), 2, "{html}");
    }

    /// `path` in a form that works as a Markdown destination on every platform: forward slashes,
    /// without the `\\?\` prefix Windows' `canonicalize` adds (`\\` and `\?` are Markdown escapes).
    fn slash_path(path: &Path) -> String {
        let s = path.display().to_string();
        s.strip_prefix(r"\\?\").unwrap_or(&s).replace('\\', "/")
    }

    /// `path` as a `file:` URL: `file:///abs` on Unix, `file:///C:/abs` on Windows.
    fn file_url(path: &Path) -> String {
        let s = slash_path(path);
        format!("file://{}{s}", if s.starts_with('/') { "" } else { "/" })
    }

    fn sealed_opts(source: &Path, approved_outside: Vec<PathBuf>) -> HtmlExportOptions {
        HtmlExportOptions {
            images: ImageHandling::Sealed {
                fetch_remote: false,
            },
            ..inline_opts(source, approved_outside)
        }
    }

    /// The hole this closes: a converter reads every `<img src>` itself, so a sealed export
    /// leaves it none that wasn't approved — no out-of-folder path, `file:` URL, remote URL, or
    /// SVG `data:` URI.  Only embedded images and raster `data:` URIs remain.
    #[test]
    fn a_sealed_export_leaves_no_reference_for_a_converter_to_follow() {
        let (_root, secret, source) = root_with_docs();
        write_one_px_png(&source.join("inside.png"));
        let md = format!(
            "![a](inside.png) ![b](../secret.png) ![c]({abs}) ![d]({url}) \
             <img src=\"../secret.png\"> ![e](https://example.com/x.png) ![f](missing.png) \
             ![g](data:image/png;base64,iVBORw0KGgo=) ![h](data:image/svg+xml;base64,PHN2Zz4=) \
             ![i](ftp://example.com/x.png)",
            abs = slash_path(&secret),
            url = file_url(&secret),
        );
        let rendered = render(&md, &sealed_opts(&source, Vec::new())).unwrap();
        // b, c, d, the raw `<img>`, e, f, h and i: everything but the two kept below.
        assert_eq!(rendered.images_left_out, 8);
        let html = rendered.html;
        let srcs: Vec<&str> = html
            .split("src=\"")
            .skip(1)
            .map(|rest| &rest[..rest.find('"').unwrap()])
            .collect();
        assert_eq!(
            srcs.len(),
            2,
            "only the inside image and the raster data URI:\n{html}"
        );
        assert!(
            srcs.iter().all(|s| s.starts_with("data:image/png;base64,")),
            "{srcs:?}"
        );
        assert!(
            srcs.contains(&"data:image/png;base64,iVBORw0KGgo="),
            "{srcs:?}"
        );
        assert!(
            !html.contains("secret") && !html.contains("example.com"),
            "{html}"
        );
        // Alt text survives, so the reader still sees something was there.
        assert!(html.contains("alt=\"b\""), "{html}");
    }

    #[test]
    fn a_sealed_export_embeds_approved_outside_images() {
        let (_root, secret, source) = root_with_docs();
        let md = format!("![a](../secret.png) ![b]({})", file_url(&secret));
        let html = render_html(&md, &sealed_opts(&source, vec![secret])).unwrap();
        assert_eq!(html.matches("data:image/png;base64,").count(), 2, "{html}");
    }

    /// Only a sealed export removes images, so only it reports any left out: the same document
    /// exported as HTML leaves each one as a link instead.
    #[test]
    fn only_a_sealed_export_reports_images_left_out() {
        let (_root, _secret, source) = root_with_docs();
        let md = "![a](../secret.png) ![b](https://example.com/x.png) ![c](missing.png)";
        let left_out = |opts| render(md, &opts).unwrap().images_left_out;
        assert_eq!(left_out(sealed_opts(&source, Vec::new())), 3);
        assert_eq!(left_out(inline_opts(&source, Vec::new())), 0);
        assert_eq!(
            left_out(HtmlExportOptions {
                images: ImageHandling::Link,
                ..inline_opts(&source, Vec::new())
            }),
            0
        );
    }

    /// An SVG whose `<image>` names `target`, a real file: if the SVG pipeline ever read local
    /// files again, the embedded output would carry it as an `<image>` with its bytes inlined.
    fn svg_referencing(target: &Path) -> String {
        write_one_px_png(target);
        format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="4" height="4"><rect width="4" height="4"/><image width="4" height="4" xlink:href="{}"/></svg>"#,
            slash_path(target)
        )
    }

    /// The first embedded SVG in `html`, decoded.
    fn embedded_svg(html: &str) -> String {
        let marker = "src=\"data:image/svg+xml;base64,";
        let start = html.find(marker).expect("svg embedded") + marker.len();
        let end = start + html[start..].find('"').unwrap();
        String::from_utf8(BASE64.decode(&html[start..end]).unwrap()).unwrap()
    }

    /// An embedded SVG is re-serialized, so it can't carry a reference to a local file into the
    /// converter (or the browser), and the file it names is not read into it either.
    #[test]
    fn embedded_svg_is_normalized() {
        let dir = tempdir().unwrap();
        let svg = svg_referencing(&dir.path().join("secret.png"));
        std::fs::write(dir.path().join("pic.svg"), svg).unwrap();
        for opts in [
            inline_opts(dir.path(), Vec::new()),
            sealed_opts(dir.path(), Vec::new()),
        ] {
            let svg = embedded_svg(&render_html("![x](pic.svg)", &opts).unwrap());
            assert!(svg.contains("<path"), "{svg}");
            assert!(!svg.contains("<image") && !svg.contains("secret"), "{svg}");
        }
    }

    /// The extension doesn't type the bytes: an SVG named `.png` is embedded as a normalized SVG,
    /// never as `image/png`, which a converter could still parse as SVG and follow references in.
    /// The same goes for a `data:` URI declaring a raster type over SVG content.
    #[test]
    fn a_disguised_svg_is_typed_by_its_content() {
        let dir = tempdir().unwrap();
        let svg = svg_referencing(&dir.path().join("secret.png"));
        std::fs::write(dir.path().join("pic.png"), &svg).unwrap();
        let md = format!(
            "![x](pic.png) ![y](data:image/png;base64,{})",
            BASE64.encode(&svg)
        );
        for opts in [
            inline_opts(dir.path(), Vec::new()),
            sealed_opts(dir.path(), Vec::new()),
        ] {
            let html = render_html(&md, &opts).unwrap();
            let embedded = embedded_svg(&html);
            assert!(
                !embedded.contains("<image") && !embedded.contains("secret"),
                "{embedded}"
            );
            assert_eq!(html.matches("data:image/svg+xml").count(), 1, "{html}");
        }
        let html = render_html(&md, &sealed_opts(dir.path(), Vec::new())).unwrap();
        assert!(!html.contains("data:image/png"), "{html}");
    }

    /// WeasyPrint embeds the target of `<a rel="attachment">` / `<link rel="attachment">` into
    /// the PDF, a file read no image rule sees.  Neither may survive: `rel` is not on the `<a>`
    /// allowlist and `<link>` is not an allowed tag.
    #[test]
    fn no_attachment_link_reaches_a_converter() {
        let md = "<a rel=\"attachment\" href=\"../secret.txt\">a</a>\n\n\
                  <link rel=\"attachment\" href=\"../secret.txt\">";
        let html = render_html(md, &opts_inline_css()).unwrap();
        assert!(!html.contains("rel="), "{html}");
        assert!(!html.contains("<link"), "{html}");
    }

    #[test]
    fn spawn_html_export_writes_file_and_reports_success() {
        use std::sync::mpsc;
        let dir = tempdir().unwrap();
        let target = dir.path().join("out.html");
        let (tx, rx) = mpsc::channel();
        spawn_html_export(
            "# hi\n".into(),
            target.clone(),
            HtmlExportOptions {
                stylesheet: Stylesheet::Inline("body{}".into()),
                ..HtmlExportOptions::default()
            },
            move |outcome| {
                tx.send(outcome).unwrap();
            },
        );
        let outcome = rx.recv().unwrap();
        assert_eq!(outcome.unwrap().path, target);
        let written = std::fs::read_to_string(&target).unwrap();
        assert!(written.contains("<h1 id=\"hi\">hi</h1>"));
    }
}