ndg-commonmark 2.9.0

Flavored CommonMark processor for Nix-related projects, with support for CommonMark, GFM, and Nixpkgs extensions.
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
#![allow(
  clippy::expect_used,
  clippy::unwrap_used,
  clippy::panic,
  reason = "Fine in tests"
)]
/// Check if HTML output contains all expected substrings or exact fragments.
/// If `exact` is true, requires the fragment to appear exactly as-is (including
/// order). If `exact` is false, checks for substring presence.
fn assert_html_contains(html: &str, expected: &[&str]) {
  for &needle in expected {
    assert!(
      html.contains(needle),
      "Expected HTML to contain '{needle}', but it did not.\nFull \
       HTML:\n{html}"
    );
  }
}

fn ndg_html(md: &str) -> String {
  let options = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(options);
  processor.render(md).html
}

fn ndg_full_result(
  md: &str,
) -> (String, Vec<ndg_commonmark::Header>, Option<String>) {
  let options = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(options);
  let result = processor.render(md);
  (result.html, result.headers, result.title)
}

#[test]
fn test_admonition_note() {
  let md = "::: {.note}\nThis is a note.\n:::";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<div class="admonition note""#,
    r#"<p class="admonition-title">Note</p>"#,
    "This is a note.",
  ]);
}

#[test]
fn test_admonition_attribute_order_id_before_class() {
  let md = "::: {#important-warning .warning}\nWatch out.\n:::";
  let html = ndg_html(md);

  assert_html_contains(&html, &[
    r#"<div class="admonition warning" id="important-warning">"#,
    r#"<p class="admonition-title">Warning</p>"#,
    "Watch out.",
  ]);
}

#[test]
fn test_admonition_prefers_known_type_in_multiple_classes() {
  let md = "::: {.admonition .warning #important-warning}\nWatch out.\n:::";
  let html = ndg_html(md);

  assert_html_contains(&html, &[
    r#"<div class="admonition warning" id="important-warning">"#,
    r#"<p class="admonition-title">Warning</p>"#,
    "Watch out.",
  ]);
}

#[test]
fn test_indented_admonition_stays_inside_list_item() {
  let md = "1. First item

   ::: {.note}
   This note belongs to the first item.
   :::

2. Second item";
  let html = ndg_html(md);

  assert!(
    html.contains(r"<ol>") && html.contains("First item"),
    "ordered list should render normally. Got:\n{html}"
  );
  assert!(
    html.contains(r#"<div class="admonition note">"#),
    "indented admonition should render. Got:\n{html}"
  );
  assert!(
    !html.contains("<pre><code>This note belongs"),
    "admonition content should not be treated as an indented code block. \
     Got:\n{html}"
  );
  assert!(
    html.contains("Second item"),
    "following list item numbering should continue after admonition. \
     Got:\n{html}"
  );
}

#[test]
fn test_role_command() {
  let md = "{command}`ls -l`";
  let html = ndg_html(md);
  assert_html_contains(&html, &[r#"<code class="command">ls -l</code>"#]);
}

#[test]
fn test_role_option() {
  let md = "{option}`services.nginx.enable`";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<a class="option-reference" href="options.html#option-services.nginx.enable"><code class="nixos-option">services.nginx.enable</code></a>"#,
  ]);
}

#[test]
fn test_command_prompt() {
  let md = "`$ echo hi`";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<code class="terminal"><span class="prompt">$</span> echo hi</code>"#,
  ]);
}

#[test]
fn test_repl_prompt() {
  let md = "`nix-repl> 1 + 1`";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<code class="nix-repl"><span class="prompt">nix-repl&gt;</span> 1 + 1</code>"#,
  ]);
}

#[test]
fn test_inline_anchor() {
  let md = "Go here []{#target}.";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"Go here <span id="target" class="nixos-anchor"></span>."#,
  ]);
}

#[test]
fn test_list_item_with_anchor() {
  let md = "- []{#item1} Item 1";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<span id="item1" class="nixos-anchor"></span> Item 1"#,
  ]);
}

#[test]
fn test_explicit_header_anchor() {
  let md = "## Section {#sec}";
  let html = ndg_html(md);
  assert!(
    html.contains(r#"<h2 id="sec">"#) && html.contains("Section</h2>"),
    "Expected HTML to contain <h2 id=\"sec\">...Section</h2>, got:\n{html}"
  );
}

// Edge case: header with anchor and trailing whitespace
#[test]
fn test_explicit_header_anchor_trailing_whitespace() {
  let md = "###   Weird Header   {#weird-anchor}   ";
  let html = ndg_html(md);
  assert!(
    html.contains(r#"<h3 id="weird-anchor">"#) && html.contains("Weird Header"),
    "Expected HTML to contain <h3 id=\"weird-anchor\">...Weird Header..., \
     got:\n{html}"
  );
}

// Edge case: header with anchor and special characters
#[test]
fn test_explicit_header_anchor_special_chars() {
  let md = "## Header! With @Special #Chars {#special_123}";
  let html = ndg_html(md);
  assert!(
    html.contains(r#"<h2 id="special_123">"#)
      && html.contains("Header! With @Special #Chars"),
    "Expected HTML to contain <h2 id=\"special_123\">...Header! With @Special \
     #Chars..., got:\n{html}"
  );
}

// Test auto-generated header IDs (headers without explicit {#id} syntax)
#[test]
fn test_auto_generated_header_id() {
  let md = "## My Section Title";
  let html = ndg_html(md);
  assert!(
    html.contains(r#"<h2 id="my-section-title">My Section Title</h2>"#),
    "Expected header to have auto-generated id=\"my-section-title\", \
     got:\n{html}"
  );
}

#[test]
fn test_auto_generated_header_id_with_special_chars() {
  let md = "## Hello World! (2024)";
  let html = ndg_html(md);
  // Special chars get replaced with dashes, leading/trailing dashes trimmed
  assert!(
    html.contains(r#"<h2 id="hello-world---2024">"#),
    "Expected header to have slugified ID, got:\n{html}"
  );
}

#[test]
fn test_auto_generated_header_id_with_inline_formatting() {
  let md = "## Hello **World** and `code`";
  let html = ndg_html(md);
  // ID should be based on text content only, stripping HTML tags
  assert!(
    html.contains(r#"id="hello-world-and-code""#),
    "Expected ID based on text content only, got:\n{html}"
  );
}

#[test]
fn test_setext_heading_with_explicit_anchor_keeps_level() {
  let md = "Release Notes {#release-notes}\n=============";
  let (html, headers, _) = ndg_full_result(md);

  assert!(
    html.contains(r#"<h1 id="release-notes">Release Notes</h1>"#),
    "setext heading anchor should render on h1. Got:\n{html}"
  );
  assert!(
    headers
      .iter()
      .any(|header| header.level == 1 && header.id == "release-notes"),
    "setext heading anchor should be extracted as h1. Got:\n{headers:?}"
  );
}

// Edge case: inline anchor at start of line
#[test]
fn test_inline_anchor_start_of_line() {
  let md = "[]{#start-anchor}This line starts with an anchor.";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<span id="start-anchor" class="nixos-anchor"></span>This line starts with an anchor."#,
  ]);
}

// Edge case: inline anchor at end of line
#[test]
fn test_inline_anchor_end_of_line() {
  let md = "This line ends with an anchor.[]{#end-anchor}";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"This line ends with an anchor.<span id="end-anchor" class="nixos-anchor"></span>"#,
  ]);
}

#[test]
fn test_figure_block() {
  let md = "::: {.figure #fig1}\n# Figure Title\nFigure content\n:::";
  let html = ndg_html(md);
  // Accept admonition-style figure rendering
  assert!(
    html.contains(r#"<div class="admonition figure" id="fig1">"#)
      && html.contains(r#"<p class="admonition-title">Figure</p>"#)
      && html.contains("Figure Title")
      && html.contains("Figure content"),
    "Expected HTML to contain admonition-style figure, got:\n{html}"
  );
}

#[test]
fn test_definition_list() {
  let md = "Term\n:   Definition";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    "<dl>",
    "<dt>Term</dt>",
    "<dd>Definition</dd>",
    "</dl>",
  ]);
}

#[test]
fn test_option_reference() {
  let md = "`foo.bar.baz`";
  let html = ndg_html(md);
  // Option references may be rendered as <code> or as a link depending on
  // context
  assert!(
    html.contains(r"<code>foo.bar.baz</code>")
      || html.contains(r"option-foo-bar-baz"),
    "Expected option reference in HTML, got:\n{html}"
  );
}

#[test]
fn test_myst_role_markup() {
  let md = r"{command}`foo`";
  let html = ndg_commonmark::process_role_markup(md, None, true, None);
  assert_html_contains(&html, &[r#"<code class="command">foo</code>"#]);
}

#[test]
fn test_manpage_role_with_url() {
  use std::{fs::File, io::Write};

  use tempfile::tempdir;

  let md = r"{manpage}`cat(1)`";
  let dir = tempdir().unwrap();
  let json_path = dir.path().join("manpage-urls.json");
  let mut file = File::create(&json_path).unwrap();
  write!(
        file,
        r#"{{"cat(1)": "https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html"}}"#
    )
    .unwrap();

  let opts = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    manpage_urls_path: Some(json_path.to_str().unwrap().to_string()),
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(opts);

  let html = ndg_commonmark::process_role_markup(
    md,
    processor.manpage_urls(),
    true,
    None,
  );
  assert_html_contains(&html, &[
    r#"<a href="https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html" class="manpage-reference">cat(1)</a>"#,
  ]);
}

#[test]
fn test_manpage_role_without_url() {
  use std::{fs::File, io::Write};

  use tempfile::tempdir;

  let md = r"{manpage}`doesnotexist(1)`";
  let dir = tempdir().unwrap();
  let json_path = dir.path().join("manpage-urls.json");
  let mut file = File::create(&json_path).unwrap();
  write!(
        file,
        r#"{{"cat(1)": "https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html"}}"#
    )
    .unwrap();

  let opts = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    manpage_urls_path: Some(json_path.to_str().unwrap().to_string()),
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(opts);

  let html = ndg_commonmark::process_role_markup(
    md,
    processor.manpage_urls(),
    true,
    None,
  );
  assert_html_contains(&html, &[
    r#"<span class="manpage-reference">doesnotexist(1)</span>"#,
  ]);
}

#[test]
fn test_role_markup_in_lists() {
  let md = r"- {command}`nixos-rebuild switch`
- {env}`HOME`
- {file}`/etc/nixos/configuration.nix`
- {option}`services.nginx.enable`
- {var}`pkgs`
- {manpage}`nix.conf(5)`";
  let html = ndg_commonmark::process_role_markup(md, None, true, None);

  // Test that all role types are processed correctly
  assert_html_contains(&html, &[
    r#"<code class="command">nixos-rebuild switch</code>"#,
    r#"<code class="env-var">HOME</code>"#,
    r#"<code class="file-path">/etc/nixos/configuration.nix</code>"#,
    r#"<a class="option-reference" href="options.html#option-services.nginx.enable"><code class="nixos-option">services.nginx.enable</code></a>"#,
    r#"<code class="nix-var">pkgs</code>"#,
    r#"<span class="manpage-reference">nix.conf(5)</span>"#,
  ]);

  // Test that no double-processing occurs
  assert!(
    !html.contains("&lt;a href"),
    "No nested anchor tags should be present"
  );
  assert!(
    !html.contains("href=\"<a href"),
    "No nested href attributes should be present"
  );
}

#[test]
fn test_role_markup_edge_cases() {
  // Test role with special characters
  let md = r"{file}`/path/with-dashes_and.dots`";
  let html = ndg_commonmark::process_role_markup(md, None, true, None);
  assert_html_contains(&html, &[
    r#"<code class="file-path">/path/with-dashes_and.dots</code>"#,
  ]);

  // Test role with spaces
  let md = r"{command}`ls -la | grep test`";
  let html = ndg_commonmark::process_role_markup(md, None, true, None);
  assert_html_contains(&html, &[
    r#"<code class="command">ls -la | grep test</code>"#,
  ]);

  // Test unknown role type
  let md = r"{unknown}`content`";
  let html = ndg_commonmark::process_role_markup(md, None, true, None);
  assert_html_contains(&html, &[
    r#"<span class="unknown-markup">content</span>"#,
  ]);
}

#[test]
fn test_reported_issue_regression() {
  // This test verifies the exact issue reported by the user
  let md = r"- {command}`nixos-rebuild switch`
- {env}`HOME`
- {file}`/etc/nixos/configuration.nix`
- {option}`services.nginx.enable`
- {var}`pkgs`
- {manpage}`nix.conf(5)`";
  let html = ndg_html(md);

  // Verify correct HTML structure with proper list items
  assert_html_contains(&html, &[
    r#"<li><code class="command">nixos-rebuild switch</code></li>"#,
    r#"<li><code class="env-var">HOME</code></li>"#,
    r#"<li><code class="file-path">/etc/nixos/configuration.nix</code></li>"#,
    r#"<li><a class="option-reference" href="options.html#option-services.nginx.enable"><code class="nixos-option">services.nginx.enable</code></a></li>"#,
    r#"<li><code class="nix-var">pkgs</code></li>"#,
    r#"<li><span class="manpage-reference">nix.conf(5)</span></li>"#,
  ]);

  // Verify no malformed HTML patterns
  assert!(
    !html.contains(r#"<a class="option-reference""><li></li>"#),
    "Option reference should not break list structure"
  );
  assert!(
    !html.contains(r#"href="<a href"#),
    "No nested anchor tags in href attributes"
  );
  assert!(
    !html.contains(r#"</a>"><li></li>"#),
    "No empty list items after option references"
  );
}

#[test]
fn test_autolink() {
  let md = "Visit https://example.com for info.";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<a href="https://example.com">https://example.com</a>"#,
  ]);
}

#[test]
fn test_myst_autolink_bracket() {
  // MyST-style autolink: [](https://google.com)
  let md = "Try [](https://google.com) for search.";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    r#"<a href="https://google.com">https://google.com</a>"#,
  ]);
}

#[test]
fn test_auto_link_options_enabled() {
  // Test that {option} roles are converted to links when auto_link_options is
  // true
  let md = r"Use {option}`services.nginx.enable` to configure nginx.";
  let opts = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    auto_link_options: true,
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(opts);
  let html = processor.render(md).html;

  assert_html_contains(&html, &[
    r#"<a class="option-reference" href="options.html#option-services.nginx.enable"><code class="nixos-option">services.nginx.enable</code></a>"#,
  ]);
}

#[test]
fn test_auto_link_options_disabled() {
  // Test that {option} roles are NOT converted to links when auto_link_options
  // is false
  let md = r"Use {option}`services.nginx.enable` to configure nginx.";
  let opts = ndg_commonmark::MarkdownOptions {
    highlight_code: false,
    auto_link_options: false,
    ..Default::default()
  };
  let processor = ndg_commonmark::MarkdownProcessor::new(opts);
  let html = processor.render(md).html;

  // Should render as plain code, not as a link
  assert!(
    html.contains(r"<code>services.nginx.enable</code>"),
    "Expected plain code element when auto_link_options is false. Got:\n{html}"
  );
  assert!(
    !html.contains(r#"<a class="option-reference""#),
    "Should not contain option-reference link when auto_link_options is \
     false. Got:\n{html}"
  );
}

#[test]
fn test_option_anchor_link_empty() {
  // Test [](#opt-services-nginx-enable) -> link to options.html with filled
  // text
  let md = r"See [](#opt-services-nginx-enable) for details.";
  let html = ndg_html(md);

  assert_html_contains(&html, &[
    r#"<a href="options.html#opt-services-nginx-enable">services.nginx.enable</a>"#,
  ]);
}

#[test]
fn test_option_anchor_link_with_text() {
  // Test [custom text](#opt-services-nginx-enable) -> link with custom text
  let md = r"See [the nginx option](#opt-services-nginx-enable) for details.";
  let html = ndg_html(md);

  assert_html_contains(&html, &[
    r#"<a href="options.html#opt-services-nginx-enable">the nginx option</a>"#,
  ]);
}

#[test]
fn test_option_anchor_link_complex() {
  // Test multiple option anchor links
  let md = r"Configure [](#opt-services-nginx-enable) and [](#opt-services-nginx-virtualHosts).";
  let html = ndg_html(md);

  assert_html_contains(&html, &[
    r#"<a href="options.html#opt-services-nginx-enable">services.nginx.enable</a>"#,
    r#"<a href="options.html#opt-services-nginx-virtualHosts">services.nginx.virtualHosts</a>"#,
  ]);
}

#[test]
fn test_option_anchor_link_not_opt_prefix() {
  // Test that non-opt anchors are not transformed
  let md = r"See [](#getting-started) for details.";
  let html = ndg_html(md);

  // Should NOT be transformed to options.html
  assert!(
    !html.contains("options.html"),
    "Non-opt anchors should not be transformed. Got:\n{html}"
  );
  assert_html_contains(&html, &[
    r##"<a href="#getting-started">Getting Started</a>"##,
  ]);
}

#[test]
fn test_header_extraction() {
  let md = "# Title\n\n## Section {#sec}\n### Subsection";
  let (_html, headers, title) = ndg_full_result(md);
  assert_eq!(title.as_deref(), Some("Title"));
  assert_eq!(headers[0].text, "Title");
  assert_eq!(headers[0].level, 1);
  assert_eq!(headers[1].id, "sec");
  assert_eq!(headers[2].level, 3);
}

#[test]
fn test_raw_inline_anchor() {
  let md = "[]{#anchor}";
  let html = ndg_html(md);
  assert!(
    html.contains(r#"<span id="anchor" class="nixos-anchor"></span>"#),
    "Expected HTML to contain raw inline anchor, got:\n{html}"
  );
}

#[test]
fn test_block_and_inline_code() {
  let md = "Here is `inline code`.\n\n```\nblock code\n```";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    "<code>inline code</code>",
    "<pre><code>block code",
  ]);
}

#[test]
fn test_tables_footnotes_strikethrough_tasklists() {
  let md = "\
| A | B |\n|---|---|\n| 1 | 2 |\n\nHere is a footnote.[^1]\n\n[^1]: Footnote \
            text.\n\n~~strikethrough~~\n\n- [x] Task done\n- [ ] Task not done";
  let html = ndg_html(md);
  assert_html_contains(&html, &[
    "<table>",
    "<del>strikethrough</del>",
    "Footnote text",
    r#"<input type="checkbox" checked="" disabled="">"#,
    r#"<input type="checkbox" disabled="">"#,
  ]);
}

#[test]
fn test_footnotes_various_cases() {
  let md = "\
Here is a footnote.[^1]

Here is another footnote.[^note2]

Here is an inline footnote.^[This is inline.]

[^1]: Footnote one text.
[^note2]: Footnote two text.
";
  let html = ndg_html(md);
  assert!(
    html.contains("Footnote one text.")
      && html.contains("Footnote two text.")
      && html.contains("This is inline.")
      && html.contains("footnote")
      && html.contains("fnref")
      && html.contains("data-footnote-backref"),
    "Expected HTML to contain all footnote texts and footnote references. \
     Got:\n{html}"
  );

  // Test missing footnote definition (should render a link or marker)
  let md_missing = "Reference to missing footnote.[^missing]";
  let html_missing = ndg_html(md_missing);
  assert!(
    html_missing.contains("missing"),
    "Expected HTML to mention missing footnote reference. Got:\n{html_missing}"
  );
}

// "Sütten ağızı yanan yoğurdu üfleyerek yermiş", or, transated:
// "Once bitten, twice shy"
// Test that role markup is NOT processed inside code blocks. I got bitten by
// this bug. Never again.

#[test]
fn test_role_markup_not_processed_in_code_blocks() {
  // Test that role markup is NOT processed inside fenced code blocks
  let md = r"Here is a code block with role markup:

```
{command}`ls -la`                    # Terminal command
{file}`/etc/nixos/configuration.nix` # File path
{option}`services.nginx.enable`      # NixOS option
```

Normal text after.";

  let html = ndg_html(md);

  // Role markup should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<code class="command">"#),
    "Role markup should NOT be processed inside fenced code blocks. \
     Got:\n{html}"
  );
  assert!(
    !html.contains(r#"<code class="file-path">"#),
    "Role markup should NOT be processed inside fenced code blocks. \
     Got:\n{html}"
  );
  assert!(
    !html.contains(r#"<a class="option-reference""#),
    "Role markup should NOT be processed inside fenced code blocks. \
     Got:\n{html}"
  );

  // The literal text should still be present
  assert!(
    html.contains("{command}`ls -la`")
      && html.contains("{file}`/etc/nixos/configuration.nix`"),
    "Literal role markup text should be preserved in code blocks. Got:\n{html}"
  );
}

#[test]
fn test_role_markup_not_processed_in_inline_code() {
  // Test that role markup is NOT processed inside inline code
  let md = r"Here is `{command}`inline`` code with role markup.";

  let html = ndg_html(md);

  // Role markup should NOT be processed inside inline code
  assert!(
    !html.contains(r#"<code class="command">"#),
    "Role markup should NOT be processed inside inline code. Got:\n{html}"
  );

  // The literal text should still be present
  assert!(
    html.contains("{command}"),
    "Literal role markup text should be preserved in inline code. Got:\n{html}"
  );
}

#[test]
fn test_admonitions_not_processed_in_code_blocks() {
  // Test that admonitions are NOT processed inside code blocks
  let md = r"```
::: {.note}
This should not be processed as an admonition
:::
```";

  let html = ndg_html(md);

  // Admonitions should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<div class="admonition">"#),
    "Admonitions should NOT be processed inside code blocks. Got:\n{html}"
  );

  // The literal text should still be present
  assert!(
    html.contains("::: {.note}"),
    "Literal admonition text should be preserved in code blocks. Got:\n{html}"
  );
}

#[test]
fn test_github_callouts_not_processed_in_code_blocks() {
  // Test that GitHub callouts are NOT processed inside code blocks
  let md = r"```
> [!NOTE]
> This should not be processed as a callout
```";

  let html = ndg_html(md);

  // GitHub callouts should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<div class="admonition">"#),
    "GitHub callouts should NOT be processed inside code blocks. Got:\n{html}"
  );

  // The literal text should still be present (HTML-escaped in code blocks)
  assert!(
    html.contains("&gt; [!NOTE]"),
    "Literal GitHub callout text should be preserved in code blocks. \
     Got:\n{html}"
  );
}

#[test]
fn test_inline_anchors_not_processed_in_code_blocks() {
  // Test that inline anchors are NOT processed inside code blocks
  let md = r"```
    []{#anchor1} Some content
    More []{#anchor2} content
```";

  let html = ndg_html(md);

  // Inline anchors should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<span class="nixos-anchor""#),
    "Inline anchors should NOT be processed inside code blocks. Got:\n{html}"
  );

  // The literal text should still be present (HTML-escaped in code blocks)
  assert!(
    html.contains("[]{#anchor1}") && html.contains("[]{#anchor2}"),
    "Literal inline anchor text should be preserved in code blocks. \
     Got:\n{html}"
  );
}

#[test]
fn test_comprehensive_code_block_preservation() {
  // Test that ALL types of NDG-specific syntax are NOT processed inside code
  // blocks
  let md = r#"````
{command}`ls -la`                    # Role markup
{file}`/etc/nixos/configuration.nix`
{option}`services.nginx.enable`
{env}`HOME`
{var}`myVariable`
{manpage}`man(1)`
{incomplete-role}                    # Incomplete role markup

::: {.note}                          # Admonitions
This should not be an admonition
:::

> [!WARNING]                         # GitHub callouts
> This should not be a callout

[]{#anchor1} Content                 # Inline anchors
More []{#anchor2} content

`$ echo "command prompt"`            # Command prompts
`nix-repl> 1 + 1`                   # REPL prompts

Term                                 # Definition lists
:   Definition

https://example.com                  # Autolinks
https://nixos.org/downloads

```{=include=}                       # File includes
path/to/file1.md
path/to/file2.md
```
````"#;

  let html = ndg_html(md);

  // Role markup should NOT be processed
  assert!(
    !html.contains(r#"<code class="command">"#)
      && !html.contains(r#"<code class="file-path">"#)
      && !html.contains(r#"<a class="option-reference""#)
      && !html.contains(r#"<code class="env-var">"#)
      && !html.contains(r#"<code class="nix-var">"#)
      && !html.contains(r#"<span class="manpage-reference">"#),
    "Role markup should NOT be processed inside code blocks. Got:\n{html}"
  );

  // Admonitions should NOT be processed
  assert!(
    !html.contains(r#"<div class="admonition">"#),
    "Admonitions should NOT be processed inside code blocks. Got:\n{html}"
  );

  // GitHub callouts should NOT be processed
  assert!(
    !html.contains(r#"<div class="admonition">"#),
    "GitHub callouts should NOT be processed inside code blocks. Got:\n{html}"
  );

  // Inline anchors should NOT be processed
  assert!(
    !html.contains(r#"<span class="nixos-anchor""#),
    "Inline anchors should NOT be processed inside code blocks. Got:\n{html}"
  );

  // Command/REPL prompts should NOT be processed
  assert!(
    !html.contains(r#"<span class="prompt">"#),
    "Command/REPL prompts should NOT be processed inside code blocks. \
     Got:\n{html}"
  );

  // Definition lists should NOT be processed
  assert!(
    !html.contains("<dl>") && !html.contains("<dt>") && !html.contains("<dd>"),
    "Definition lists should NOT be processed inside code blocks. Got:\n{html}"
  );

  // Autolinks should NOT be processed
  assert!(
    !html.contains(r#"<a href="https://example.com""#)
      && !html.contains(r#"<a href="https://nixos.org""#),
    "Autolinks should NOT be processed inside code blocks. Got:\n{html}"
  );

  // File includes should NOT be processed
  assert!(
    !html.contains("<!-- ndg: could not include file:")
      && html.contains("```{=include=}")
      && html.contains("path/to/file1.md"),
    "File includes should NOT be processed inside code blocks. Got:\n{html}"
  );

  // All literal text should be preserved
  assert!(
    html.contains("{command}`ls -la`")
      && html.contains("{incomplete-role}")
      && html.contains("::: {.note}")
      && html.contains("&gt; [!WARNING]")
      && html.contains("[]{#anchor1}")
      && html.contains("`$ echo \"command prompt\"`")
      && html.contains("Term")
      && html.contains(":   Definition")
      && html.contains("https://example.com")
      && html.contains("https://nixos.org"),
    "Literal text should be preserved in code blocks. Got:\n{html}"
  );
}

#[test]
fn test_command_prompts_not_processed_in_code_blocks() {
  // Test that command and REPL prompts are NOT processed inside code blocks
  let md = r#"```
`$ echo "this should not be processed"`
`nix-repl> 1 + 1`
```"#;

  let html = ndg_html(md);

  // Command/REPL prompts should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<span class="prompt">"#),
    "Command/REPL prompts should NOT be processed inside code blocks. \
     Got:\n{html}"
  );

  // The literal text should still be present (HTML-escaped in code blocks)
  assert!(
    html.contains("`$ echo \"this should not be processed\"`")
      && html.contains("`nix-repl&gt; 1 + 1`"),
    "Literal prompt text should be preserved in code blocks. Got:\n{html}"
  );
}

#[test]
fn test_incomplete_role_markup_bug() {
  // Test incomplete role markup like {var} without content
  let md =
    r"Here is incomplete role markup: {var} and complete: {var}`content`";
  let html = ndg_html(md);

  // Both should be processed correctly - incomplete should be left as-is
  assert!(
    html.contains("{var}")
      && html.contains(r#"<code class="nix-var">content</code>"#),
    "Incomplete role markup should be preserved, complete should be \
     processed. Got:\n{html}"
  );
}

#[test]
fn test_incomplete_role_markup_with_empty_content() {
  // Test that incomplete role markup with empty content is preserved as literal
  // text
  let md = r"Empty option: {option}``";
  let html = ndg_html(md);

  // Should preserve the entire incomplete markup as literal text
  assert!(
    html.contains("{option}``"),
    "Incomplete role markup with empty content should be preserved as literal \
     text. Got:\n{html}"
  );

  // Should not create empty code elements
  assert!(
    !html.contains("<code></code>"),
    "Empty option with double backticks should not generate empty code tags. \
     Got:\n{html}"
  );

  // Test standalone incomplete roles
  let test_cases = vec!["{var}", "{command}", "{file}", "{unknown}"];

  for case in test_cases {
    let html = ndg_html(case);
    assert!(
      !html.contains("<code>") && !html.contains('`'),
      "Incomplete role markup {case} should not generate code tags or \
       backticks. Got:\n{html}"
    );
    assert!(
      html.contains(case),
      "Should preserve literal {case} text. Got:\n{html}"
    );
  }
}

#[test]
fn test_markdown_parsing_inside_admonitions() {
  // Test that Markdown features are correctly parsed inside admonitions
  let md = r"::: {.note}
This is **bold** text and *italic* text.

Here is `inline code` and {var}`myVariable`.

- List item 1
- List item 2

## Header inside admonition

[Link text](https://example.com)
:::";

  let html = ndg_html(md);

  // Debug output can be enabled if needed
  // println!("DEBUG: Admonition HTML output:");
  // println!("{}", html);

  // Should contain properly parsed Markdown elements
  assert!(
    html.contains("<strong>bold</strong>") && html.contains("<em>italic</em>"),
    "Bold and italic text should be parsed inside admonitions. Got:\n{html}"
  );

  assert!(
    html.contains(r"<code>inline code</code>"),
    "Inline code should be parsed inside admonitions. Got:\n{html}"
  );

  assert!(
    html.contains(r#"<code class="nix-var">myVariable</code>"#),
    "Role markup should be parsed inside admonitions. Got:\n{html}"
  );

  assert!(
    html.contains("<ul>") && html.contains("<li>List item 1</li>"),
    "Lists should be parsed inside admonitions. Got:\n{html}"
  );

  assert!(
    html.contains("<h2") && html.contains(">Header inside admonition</h2>"),
    "Headers should be parsed inside admonitions. Got:\n{html}"
  );

  assert!(
    html.contains(r#"<a href="https://example.com">Link text</a>"#),
    "Links should be parsed inside admonitions. Got:\n{html}"
  );
}

#[test]
fn test_markdown_parsing_inside_github_callouts() {
  // Test that Markdown features are correctly parsed inside GitHub callouts
  let md = r"> [!NOTE]
> This is **bold** text and *italic* text.
>
> Here is `inline code` and {var}`myVariable`.
>
> - List item 1
> - List item 2";

  let html = ndg_html(md);

  // Should contain properly parsed Markdown elements
  assert!(
    html.contains("<strong>bold</strong>") && html.contains("<em>italic</em>"),
    "Bold and italic text should be parsed inside GitHub callouts. \
     Got:\n{html}"
  );

  assert!(
    html.contains(r"<code>inline code</code>"),
    "Inline code should be parsed inside GitHub callouts. Got:\n{html}"
  );

  assert!(
    html.contains(r#"<code class="nix-var">myVariable</code>"#),
    "Role markup should be parsed inside GitHub callouts. Got:\n{html}"
  );

  assert!(
    html.contains("<ul>") && html.contains("<li>List item 1</li>"),
    "Lists should be parsed inside GitHub callouts. Got:\n{html}"
  );
}

#[test]
fn test_markdown_parsing_inside_figures() {
  // Test that Markdown features are correctly parsed inside figures
  let md = r"::: {.figure #sample-figure}

# Figure Caption with **bold** text

This is *italic* text and `inline code`.

Here is {var}`myVariable` role markup.

![Alt text](image.png)
:::";

  let html = ndg_html(md);

  // Should contain properly parsed Markdown elements
  assert!(
    html.contains("<strong>bold</strong>") && html.contains("<em>italic</em>"),
    "Bold and italic text should be parsed inside figures. Got:\n{html}"
  );

  assert!(
    html.contains(r"<code>inline code</code>"),
    "Inline code should be parsed inside figures. Got:\n{html}"
  );

  assert!(
    html.contains(r#"<code class="nix-var">myVariable</code>"#),
    "Role markup should be parsed inside figures. Got:\n{html}"
  );

  assert!(
    html.contains(r#"<img src="image.png" alt="Alt text""#),
    "Images should be parsed inside figures. Got:\n{html}"
  );
}

#[test]
fn test_public_extension_api() {
  // Test that the public extension functions work correctly for third-party use

  // Test GFM extensions (currently a placeholder)
  #[cfg(feature = "gfm")]
  {
    let md = "# Test\n\nSome **bold** text.";
    let result = ndg_commonmark::apply_gfm_extensions(md);
    // Currently a no-op, should return unchanged
    assert_eq!(result, md);
  }

  // Test Nixpkgs extensions with file includes
  #[cfg(feature = "nixpkgs")]
  {
    use std::fs;

    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    let file1_path = dir.path().join("test1.md");
    let file2_path = dir.path().join("test2.md");

    // Create test files
    fs::write(&file1_path, "# Included File 1\nContent from file 1.").unwrap();
    fs::write(&file2_path, "## Included File 2\nContent from file 2.").unwrap();

    // Test file inclusion
    let md = format!(
      r"# Main Document

```{{=include=}}
{}
{}
```

End of document.",
      file1_path.file_name().unwrap().to_str().unwrap(),
      file2_path.file_name().unwrap().to_str().unwrap()
    );

    let (result, _included_files) =
      ndg_commonmark::process_file_includes(&md, dir.path(), 0)
        .expect("File include processing failed");

    // Should include both files
    assert!(result.contains("# Included File 1"));
    assert!(result.contains("Content from file 1."));
    assert!(result.contains("## Included File 2"));
    assert!(result.contains("Content from file 2."));
    assert!(result.contains("End of document."));
    assert!(!result.contains("```{=include=}"));
  }

  // Test that file includes respect code block boundaries
  #[cfg(feature = "nixpkgs")]
  {
    let md = r"````
```{=include=}
some/file.md
```
````";

    let (result, _included_files) =
      ndg_commonmark::process_file_includes(md, std::path::Path::new("."), 0)
        .expect("file inclusion failed");

    // Should NOT process includes inside code blocks
    assert!(result.contains("```{=include=}"));
    assert!(result.contains("some/file.md"));
    assert!(!result.contains("<!-- ndg: could not include file:"));
  }

  // Test with the main processor to verify integration
  #[cfg(feature = "nixpkgs")]
  {
    let options = ndg_commonmark::MarkdownOptions {
      nixpkgs: true,
      highlight_code: false,
      ..Default::default()
    };
    let processor = ndg_commonmark::MarkdownProcessor::new(options);

    let simple_md = r"```{=include=}
test1.md
```";
    let result = processor.render(simple_md);

    // Should show include processing (file not found)
    assert!(result.html.contains("<!-- ndg: could not include file:"));
  }
}

#[test]
fn test_file_includes_not_processed_in_code_blocks() {
  // Test that file includes are NOT processed inside code blocks
  let md = r"````
```{=include=}
path/to/file1.md
path/to/file2.md
```
````";

  let html = ndg_html(md);

  // File includes should NOT be processed inside code blocks
  // Content should be preserved as plain text without syntax highlighting
  assert!(
    html.contains("```{=include=}")
      && html.contains("path/to/file1.md")
      && html.contains("<pre><code>"),
    "File include syntax should be preserved in code blocks as plain text. \
     Got:\n{html}"
  );
}

#[test]
fn test_bracketed_span_is_rendered() {
  let md = "This has [marked text]{#target .first .second key=\"value\"}.";
  let html = ndg_html(md);

  assert!(
    html.contains(
      r#"This has <span id="target" class="first second" key="value">marked text</span>."#
    ),
    "bracketed span should render as a span with attributes. Got:\n{html}"
  );
}

#[test]
fn test_bracketed_span_not_processed_in_code() {
  let md = "`[marked text]{.class}`";
  let html = ndg_html(md);

  assert!(
    html.contains(r"<code>[marked text]{.class}</code>"),
    "bracketed span syntax should be preserved in inline code. Got:\n{html}"
  );
}

#[test]
fn test_options_include_block_renders_json_options() {
  use std::fs;

  use tempfile::tempdir;

  let dir = tempdir().expect("create temp dir");
  fs::write(
    dir.path().join("options.json"),
    r#"{
      "services.nginx.enable": {
        "type": "boolean",
        "description": "Whether to enable nginx."
      }
    }"#,
  )
  .expect("write options include");

  let md = "```{=include=} options\nid-prefix: opt-\nlist-id: \
            configuration-variable-list\nsource: options.json\n```";
  let options = ndg_commonmark::MarkdownOptions {
    nixpkgs: true,
    highlight_code: false,
    ..Default::default()
  };
  let processor =
    ndg_commonmark::MarkdownProcessor::new(options).with_base_dir(dir.path());
  let html = processor.render(md).html;

  assert!(
    html.contains(r#"<div class="option" id="option-services.nginx.enable">"#)
      && html.contains("services.nginx.enable")
      && html.contains(
        r#"<div class="option-type">Type: <code>boolean</code></div>"#
      )
      && html.contains("Whether to enable nginx."),
    "options include should render option documentation. Got:\n{html}"
  );
}

#[test]
fn test_include_auto_id_prefix_adds_heading_ids() {
  use std::fs;

  use tempfile::tempdir;

  let dir = tempdir().expect("create temp dir");
  fs::write(
    dir.path().join("generated.md"),
    "# Generated Section\n\n## Existing Anchor {#custom-id}\n\n```\n# Not a \
     heading\n```",
  )
  .expect("write generated include");

  let md = "```{=include=} auto-id-prefix=treefmt\ngenerated.md\n```";
  let options = ndg_commonmark::MarkdownOptions {
    nixpkgs: true,
    highlight_code: false,
    ..Default::default()
  };
  let processor =
    ndg_commonmark::MarkdownProcessor::new(options).with_base_dir(dir.path());
  let result = processor.render(md);

  assert!(
    result
      .html
      .contains(r#"<h1 id="treefmt-1-1">Generated Section</h1>"#),
    "auto-id-prefix should add prefixed heading id. Got:\n{}",
    result.html
  );
  assert!(
    result
      .html
      .contains(r#"<h2 id="custom-id">Existing Anchor</h2>"#),
    "auto-id-prefix should not override explicit heading anchors. Got:\n{}",
    result.html
  );
  assert!(
    !result.html.contains("treefmt-not-a-heading"),
    "auto-id-prefix should not process headings inside code blocks. Got:\n{}",
    result.html
  );
  assert!(
    result
      .headers
      .iter()
      .any(|header| header.id == "treefmt-1-1"),
    "auto-id-prefix should be visible to extracted headers. Got:\n{:?}",
    result.headers
  );
}

#[test]
fn test_absolute_file_include_is_processed() {
  use std::fs;

  use tempfile::tempdir;

  let dir = tempdir().expect("create temp dir");
  let included = dir.path().join("generated.md");
  fs::write(&included, "# Generated\n\nContent from generated file.")
    .expect("write generated include");

  let md = format!("```{{=include=}}\n{}\n```", included.display());
  let options = ndg_commonmark::MarkdownOptions {
    nixpkgs: true,
    highlight_code: false,
    ..Default::default()
  };
  let processor =
    ndg_commonmark::MarkdownProcessor::new(options).with_base_dir(dir.path());
  let html = processor.render(&md).html;

  assert!(
    html.contains("Generated") && html.contains("Content from generated file."),
    "absolute include path should be rendered. Got:\n{html}"
  );
  assert!(
    !html.contains("could not include file"),
    "absolute include path should not be rejected. Got:\n{html}"
  );
}

#[test]
fn test_unclosed_admonition_in_include_stops_at_file_boundary() {
  use std::fs;

  use tempfile::tempdir;

  let dir = tempdir().expect("create temp dir");
  fs::write(
    dir.path().join("first.md"),
    "# First\n\n::: {.warning}\nThis warning is not closed.\n",
  )
  .expect("write first include");
  fs::write(
    dir.path().join("second.md"),
    "# Second\n\nThis must not be inside the warning.\n",
  )
  .expect("write second include");

  let md = "```{=include=}\nfirst.md\nsecond.md\n```";
  let options = ndg_commonmark::MarkdownOptions {
    nixpkgs: true,
    highlight_code: false,
    ..Default::default()
  };
  let processor =
    ndg_commonmark::MarkdownProcessor::new(options).with_base_dir(dir.path());
  let html = processor.render(md).html;

  let second_heading = html
    .find("<h1 id=\"second\">Second</h1>")
    .expect("second include should render as a separate heading");
  let warning_close = html
    .find("</div>\n<h1 id=\"second\">Second</h1>")
    .expect("admonition should close before the next included file");

  assert!(
    warning_close < second_heading,
    "unclosed admonition should be limited to its include file. Got:\n{html}"
  );
  assert!(
    !html.contains("ndg:include-boundary"),
    "internal include boundary marker should not leak into output. \
     Got:\n{html}"
  );
}

#[test]
fn test_simple_nested_file_includes() {
  // Test simple case with file includes inside code blocks
  let md = r"````
```{=include=}
path/to/file1.md
```
````";

  let html = ndg_html(md);

  // File includes should NOT be processed inside code blocks
  assert!(
    !html.contains("<!-- ndg: could not include file:")
      && html.contains("```{=include=}")
      && html.contains("path/to/file1.md"),
    "File include syntax should be preserved in nested code blocks. \
     Got:\n{html}"
  );
}

#[test]
fn test_autolinks_not_processed_in_code_blocks() {
  // Test that autolinks are NOT processed inside code blocks
  let md = r"```markdown
Visit https://nixos.org for more information.
Also check https://example.com/test
```";

  let html = ndg_html(md);

  // Autolinks should NOT be processed inside code blocks
  assert!(
    !html.contains(r#"<a href="https://nixos.org""#)
      && !html.contains(r#"<a href="https://example.com""#),
    "Autolinks should NOT be processed inside code blocks. Got:\n{html}"
  );

  // The literal URLs should still be present
  assert!(
    html.contains("https://nixos.org")
      && html.contains("https://example.com/test"),
    "Literal URLs should be preserved in code blocks. Got:\n{html}"
  );
}

#[test]
fn test_myst_autolinks_not_processed_in_inline_code() {
  let md = r"Use `[](#opt-services-nginx-enable)` literally.";
  let html = ndg_html(md);

  assert!(
    html.contains(r"<code>[](#opt-services-nginx-enable)</code>"),
    "MyST autolinks should be preserved inside inline code. Got:\n{html}"
  );
  assert!(
    !html.contains(r#"<a href="options.html#opt-services-nginx-enable""#),
    "Inline code should not be converted to an option link. Got:\n{html}"
  );
}

#[test]
#[should_panic(expected = "Maximum include recursion depth")]
fn test_file_include_recursion_depth_limit() {
  use std::fs;

  use tempfile::tempdir;

  let dir = tempdir().unwrap();

  // Create files that include each other in a cycle
  let file_a = dir.path().join("a.md");
  let file_b = dir.path().join("b.md");

  fs::write(&file_a, "File A\n```{=include=}\nb.md\n```").unwrap();
  fs::write(&file_b, "File B\n```{=include=}\na.md\n```").unwrap();

  let md = "Start\n```{=include=}\na.md\n```";

  // This should panic due to recursion depth limit
  let (_result, _files) =
    ndg_commonmark::process_file_includes(md, dir.path(), 0)
      .expect("file inclusion failed");
}

#[test]
fn test_nested_admonitions_with_longer_outer_fence() {
  let md = r":::: {.warning}
Outer warning.

::: {.note}
Inner note.
:::

Back to outer warning.
::::";
  let html = ndg_html(md);

  assert!(
    html.contains(r#"<div class="admonition warning">"#),
    "outer admonition should render. Got:\n{html}"
  );
  assert!(
    html.contains(r#"<div class="admonition note">"#),
    "inner admonition should render. Got:\n{html}"
  );
  assert!(
    html.contains("Outer warning.")
      && html.contains("Inner note.")
      && html.contains("Back to outer warning."),
    "nested admonition content should be preserved. Got:\n{html}"
  );
}

#[test]
fn test_admonition_headings_are_not_extracted_for_toc() {
  let md = r"# Parent

::: {.example}
## Example Heading {#example-heading}

Example content.
:::

## Next Section {#next-section}";
  let (_html, headers, _title) = ndg_full_result(md);

  assert!(
    headers.iter().any(|h| h.id == "parent"),
    "parent heading should be extracted. Got: {headers:?}"
  );
  assert!(
    headers.iter().any(|h| h.id == "next-section"),
    "following section heading should be extracted. Got: {headers:?}"
  );
  assert!(
    headers.iter().all(|h| h.id != "example-heading"),
    "heading inside admonition should not be extracted. Got: {headers:?}"
  );
}

#[test]
fn test_github_callout_multiline_content() {
  // Regression test for lazy continuation syntax in GitHub callouts
  // We test with the initial README bit from NDG's documentation that actually
  // made me aware of the issue. It is not *too* comprehensive, but it does the
  // job.
  let md = r"> [!NOTE]
> CLI flags always take precedence over config file settings. For instance, if
> your config file has `search.enable = false`, but you run
> `ndg html --config search.enable=true`, search will be enabled.";

  let html = ndg_html(md);

  // Verify the admonition div exists
  assert!(
    html.contains(r#"<div class="admonition note">"#),
    "Expected admonition div. Got:\n{html}"
  );

  // Verify ALL expected content is present in the HTML
  // We don't extract the admonition scope because that's fragile with nested
  // HTML. Instead, we verify the expected fragments exist and the admonition
  // structure is correct.
  let expected_fragments = [
    "CLI flags always take precedence over config file settings",
    "For instance, if",
    "your config file has",
    "<code>search.enable = false</code>",
    "but you run",
    "<code>ndg html --config search.enable=true</code>",
    "search will be enabled",
  ];

  for fragment in &expected_fragments {
    assert!(
      html.contains(fragment),
      "Expected fragment '{fragment}' to be in the HTML, but it was \
       not.\nFull HTML:\n{html}"
    );
  }
}

#[test]
fn test_github_callout_lazy_continuation() {
  // Test that lazy continuation (lines without >) works correctly
  let md = r"> [!WARNING]
> This is the first line.
This line has no > prefix but should still be included.
And this one too.

This empty line above should end the callout.";

  let html = ndg_html(md);

  // Extract admonition content
  let start = html
    .find(r#"<div class="admonition warning">"#)
    .expect("admonition div not found");
  let end = html[start..].find("</div>").expect("closing div not found");
  let admonition_content = &html[start..start + end + 6];

  // Verify content that SHOULD be inside
  assert!(
    admonition_content.contains("This is the first line."),
    "First line should be in admonition. Got:\n{admonition_content}"
  );
  assert!(
    admonition_content.contains("This line has no &gt; prefix"),
    "Lazy continuation line should be in admonition. \
     Got:\n{admonition_content}"
  );
  assert!(
    admonition_content.contains("And this one too."),
    "Second lazy line should be in admonition. Got:\n{admonition_content}"
  );

  // Verify content that should NOT be inside
  assert!(
    !admonition_content.contains("This empty line above"),
    "Content after blank line should NOT be in admonition. \
     Got:\n{admonition_content}"
  );

  // Verify the excluded content exists elsewhere in HTML
  assert!(
    html.contains("This empty line above"),
    "Content after blank line should exist in HTML. Got:\n{html}"
  );
}

#[test]
fn test_github_callout_stops_at_blank_line() {
  // Test that blank lines properly terminate callouts
  let md = r"> [!TIP]
> Line 1
> Line 2

Outside the callout.";

  let html = ndg_html(md);

  let start = html
    .find(r#"<div class="admonition tip">"#)
    .expect("admonition div not found");
  let end = html[start..].find("</div>").expect("closing div not found");
  let admonition_content = &html[start..start + end + 6];

  assert!(
    admonition_content.contains("Line 1")
      && admonition_content.contains("Line 2"),
    "Lines 1-2 should be inside admonition. Got:\n{admonition_content}"
  );

  assert!(
    !admonition_content.contains("Outside the callout"),
    "Content after blank line should NOT be in admonition. \
     Got:\n{admonition_content}"
  );
}

#[test]
fn test_github_callout_stops_at_new_block() {
  // Test that new block elements (headers, code fences) terminate callouts
  let md = r"> [!CAUTION]
> This is in the callout.
> Still in callout.

# New Header

Not in callout anymore.";

  let html = ndg_html(md);

  let start = html
    .find(r#"<div class="admonition caution">"#)
    .expect("admonition div not found");
  let end = html[start..].find("</div>").expect("closing div not found");
  let admonition_content = &html[start..start + end + 6];

  assert!(
    admonition_content.contains("This is in the callout"),
    "Callout content should be inside. Got:\n{admonition_content}"
  );

  assert!(
    !admonition_content.contains("New Header")
      && !admonition_content.contains("Not in callout"),
    "Header and following content should NOT be in admonition. \
     Got:\n{admonition_content}"
  );
}

#[test]
fn test_tip_eof_header_on_same_line_as_closing() {
  let md = "::: {.tip}\nThis is a tip.\n:::# Title {#ch-example}";
  let (html, headers, _title) = ndg_full_result(md);

  assert!(
    html.contains("id=\"ch-example\""),
    "Header should have id='ch-example' when on same line as closing :::. \
     Got:\n{html}"
  );

  assert!(
    headers.iter().any(|h| h.id == "ch-example"),
    "Headers should include 'ch-example'. Got: {headers:?}"
  );

  assert!(
    html.contains("<h1"),
    "Header should be rendered as h1, not plain text. Got:\n{html}"
  );
}

#[test]
fn test_admonition_closing_with_trailing_content() {
  let md = "::: {.tip}\nTip content.\n::: some trailing content";
  let html = ndg_html(md);

  assert!(
    html.contains("some trailing content"),
    "Content after ::: on same line should be preserved. Got:\n{html}"
  );
}

#[test]
fn test_multiple_admonitions_with_trailing_headers() {
  let md = r"::: {.tip}
Some tip
:::
# Foo {#ch-foo}

::: {.tip}
Another tip
:::
# Bar {#ch-bar}";

  let (html, headers, _title) = ndg_full_result(md);

  // verify both headers are extracted correctly
  assert!(
    headers.iter().any(|h| h.id == "ch-foo"),
    "Headers should include 'ch-foo'. Got: {headers:?}"
  );

  assert!(
    headers.iter().any(|h| h.id == "ch-bar"),
    "Headers should include 'ch-bar'. Got: {headers:?}"
  );

  // verify both headers render correctly
  assert!(
    html.contains("id=\"ch-foo\"") && html.contains("<h1"),
    "First header should be rendered correctly. Got:\n{html}"
  );

  assert!(
    html.contains("id=\"ch-bar\"") && html.contains("<h1"),
    "Second header should be rendered correctly. Got:\n{html}"
  );
}

#[test]
fn test_admonition_eof_followed_by_header() {
  let md = "::: {.tip}\nThis is a tip.\n:::\n# Title {#ch-example}";
  let (html, headers, _title) = ndg_full_result(md);

  assert!(
    html.contains("id=\"ch-example\""),
    "Header should have id='ch-example' when after closing ::: on new line. \
     Got:\n{html}"
  );

  assert!(
    headers.iter().any(|h| h.id == "ch-example"),
    "Headers should include 'ch-example'. Got: {headers:?}"
  );

  assert!(
    html.contains("<h1"),
    "Header should be rendered as h1. Got:\n{html}"
  );
}

mod cross_page_links {
  use ndg_commonmark::rewrite_cross_page_anchor_links;
  use rustc_hash::FxHashMap;

  fn registry() -> FxHashMap<String, (String, String)> {
    let mut m = FxHashMap::default();
    m.insert(
      "sec-install".to_string(),
      ("install.html".to_string(), "Installation".to_string()),
    );
    m.insert(
      "sec-deps".to_string(),
      ("install.html".to_string(), "Dependencies".to_string()),
    );
    m.insert(
      "sec-intro".to_string(),
      ("guide/intro.html".to_string(), "Introduction".to_string()),
    );
    m
  }

  #[test]
  fn rewrites_href_to_other_page() {
    let html = r##"<p><a href="#sec-install">Installation</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "index.html", &registry());
    assert!(
      result.contains("href=\"install.html#sec-install\""),
      "expected cross-page href, got: {result}"
    );
    assert!(
      result.contains(">Installation<"),
      "text preserved: {result}"
    );
  }

  #[test]
  fn does_not_rewrite_same_page_anchor() {
    let html = r##"<p><a href="#sec-intro">Introduction</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "guide/intro.html", &registry());
    assert!(
      result.contains("href=\"#sec-intro\""),
      "same-page href must stay bare: {result}"
    );
  }

  #[test]
  fn fills_title_when_text_is_humanized_slug() {
    // "Install" is what humanize_anchor produces for "#sec-install"
    // (the sec- prefix is stripped before title-casing)
    let html = r##"<p><a href="#sec-install">Install</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "index.html", &registry());
    assert!(
      result.contains(">Installation<"),
      "humanized slug should be replaced with real title: {result}"
    );
  }

  #[test]
  fn preserves_user_written_text_on_cross_page() {
    let html = r##"<p><a href="#sec-install">see here</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "index.html", &registry());
    assert!(
      result.contains(">see here<"),
      "user text must be preserved: {result}"
    );
    assert!(
      result.contains("install.html#sec-install"),
      "href must still be rewritten: {result}"
    );
  }

  #[test]
  fn unknown_anchor_left_unchanged() {
    let html = r##"<p><a href="#unknown-id">Unknown</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "index.html", &registry());
    assert!(
      result.contains("href=\"#unknown-id\""),
      "unknown anchor href must be unchanged: {result}"
    );
  }

  #[test]
  fn computes_relative_path_across_directories() {
    // current page is in a subdirectory; target is at root
    let html = r##"<p><a href="#sec-install">Install</a></p>"##;
    let result =
      rewrite_cross_page_anchor_links(html, "guide/intro.html", &registry());
    assert!(
      result.contains("href=\"../install.html#sec-install\""),
      "needs ../ to navigate up to root: {result}"
    );
  }

  #[test]
  fn empty_registry_returns_html_unchanged() {
    let html = r##"<p><a href="#sec-install">text</a></p>"##;
    let result = rewrite_cross_page_anchor_links(
      html,
      "index.html",
      &FxHashMap::default(),
    );
    assert_eq!(result, html);
  }
}