rumdl 0.2.76

A fast Markdown linter and formatter written in Rust
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
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
use super::*;

#[test]
fn link_target_policy_accepts_canonical_working_directory_paths() {
    let base = std::env::current_dir().expect("test process should have a working directory");
    let working_root = base.join("workspace");
    let canonical_root = base.join("canonical-workspace");
    let roots = [working_root.as_path(), canonical_root.as_path()];
    let canonical_target = canonical_root.join("docs").join("b.md");
    let canonical_extensionless_target = canonical_root.join("docs").join("b");

    let policy = LinkTargetPolicy::from_paths_with_roots(["docs/b.md"], true, roots);

    assert_eq!(
        policy.resolve_supplied(&canonical_target),
        Some(canonical_target.clone())
    );
    assert_eq!(
        policy.resolve_supplied(&canonical_extensionless_target),
        Some(canonical_target.clone())
    );

    let working_target = working_root.join("docs").join("b.md");
    let absolute_policy = LinkTargetPolicy::from_paths_with_roots([working_target], true, roots);
    assert!(absolute_policy.contains(&canonical_target));
}

#[test]
fn test_empty_content() {
    let ctx = LintContext::new("", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.content, "");
    assert_eq!(ctx.line_offsets, vec![0]);
    assert_eq!(ctx.offset_to_line_col(0), (1, 1));
    assert_eq!(ctx.lines.len(), 0);
}

#[test]
fn test_single_line() {
    let ctx = LintContext::new("# Hello", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.content, "# Hello");
    assert_eq!(ctx.line_offsets, vec![0]);
    assert_eq!(ctx.offset_to_line_col(0), (1, 1));
    assert_eq!(ctx.offset_to_line_col(3), (1, 4));
}

/// CommonMark 4.2: one to six `#`s open an ATX heading only when a space, a tab
/// or the end of the line follows them. Anything else is paragraph text, and
/// the parser records the missing space for the ATX-spacing rules alone.
#[test]
fn only_a_commonmark_atx_opening_records_a_heading() {
    let heading_level = |content: &str| {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let line = &ctx.lines[0];
        (
            line.heading.as_ref().map(|heading| heading.level),
            line.atx_missing_space,
        )
    };
    let missing = |level| Some(AtxMissingSpace { level });

    assert_eq!(heading_level("# Title\n"), (Some(1), None));
    assert_eq!(heading_level("#\tTitle\n"), (Some(1), None));
    assert_eq!(heading_level("#\n"), (Some(1), None));
    assert_eq!(heading_level("###### Six\n"), (Some(6), None));
    assert_eq!(heading_level("#Title\n"), (None, missing(1)));
    assert_eq!(heading_level("#title\n"), (None, missing(1)));
    assert_eq!(heading_level("##x\n"), (None, missing(2)));
    // NBSP is not the space CommonMark requires, after the `#`s or before them
    assert_eq!(heading_level("#\u{a0}Title\n"), (None, missing(1)));
    assert_eq!(heading_level("\u{a0}# Title\n"), (None, None));
    // Seven `#`s are paragraph text with no heading to repair
    assert_eq!(heading_level("#######\n"), (None, None));
    assert_eq!(heading_level("#######x\n"), (None, None));
}

#[test]
fn a_blockquote_atx_heading_may_be_empty() {
    for (content, level) in [("> #\n", 1), (">> ##\n", 2), ("> #  \n", 1)] {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let heading = ctx.heading_on_line(1).map(|parsed| parsed.heading);
        assert_eq!(heading.map(|heading| heading.level), Some(level), "{content:?}");
        assert_eq!(heading.map(|heading| heading.text.as_str()), Some(""), "{content:?}");
    }
    let ctx = LintContext::new("> #x\n", MarkdownFlavor::Standard, None);
    assert!(ctx.heading_on_line(1).is_none());
}

/// A no-space `#` line is paragraph text, so a setext underline below it makes
/// it (and every line of its paragraph) setext heading text.
#[test]
fn a_no_space_line_is_setext_heading_text() {
    let ctx = LintContext::new("#hashtag\n---\n", MarkdownFlavor::Standard, None);
    let heading = ctx.lines[0].heading.as_deref().expect("setext heading");
    assert_eq!((heading.level, heading.text.as_str()), (2, "#hashtag"));
    assert!(matches!(heading.style, HeadingStyle::Setext2));
    assert_eq!(ctx.lines[0].atx_missing_space, None);

    let ctx = LintContext::new("#Hashtag\nmore\n===\n", MarkdownFlavor::Standard, None);
    let heading = ctx.lines[1].heading.as_deref().expect("setext heading");
    assert_eq!((heading.level, heading.text_lines), (1, 2));
    assert!(ctx.lines[0].is_setext_heading_text);
    assert_eq!(ctx.lines[0].atx_missing_space, None);
}

/// A no-space `#` line under a list item is lazy paragraph continuation, not a
/// heading that ends the list.
#[test]
fn a_no_space_line_continues_a_list_item() {
    let ctx = LintContext::new("- a\n#Todo\n- b\n", MarkdownFlavor::Standard, None);
    assert!(ctx.lines[1].heading.is_none());
    assert_eq!(ctx.list_blocks.len(), 1, "{:?}", ctx.list_blocks);
    let control = LintContext::new("- a\n# todo\n- b\n", MarkdownFlavor::Standard, None);
    assert_eq!(control.list_blocks.len(), 2, "{:?}", control.list_blocks);
}

#[test]
fn parsed_headings_cover_document_and_blockquote_semantics() {
    let content = "# Top\nSetext {#setext}\n=====\n> ## Quoted ## {#quoted}\n>> ### Nested\n#lowercase\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let headings: Vec<_> = ctx.headings().collect();
    assert_eq!(headings.len(), 4);
    assert_eq!(
        headings
            .iter()
            .map(|parsed| (parsed.line_num, parsed.heading.text.as_str(), parsed.blockquote_depth))
            .collect::<Vec<_>>(),
        vec![(1, "Top", 0), (2, "Setext", 0), (4, "Quoted", 1), (5, "Nested", 2),]
    );

    assert!(headings[1].is_setext());
    assert!(headings[2].is_blockquote());
    assert_eq!(headings[2].heading.custom_id.as_deref(), Some("quoted"));
    assert!(headings[2].heading.has_closing_sequence);
    assert_eq!(headings[2].heading.closing_sequence, "##");
    assert_eq!(headings[2].text_byte_range(content), 34..40);
    assert_eq!(&content[headings[2].text_byte_range(content)], "Quoted");
    assert_eq!(&content[headings[1].text_byte_range(content)], "Setext");
    assert!(ctx.lines[5].heading.is_none());
    assert_eq!(ctx.lines[5].atx_missing_space, Some(AtxMissingSpace { level: 1 }));
    assert!(
        headings
            .iter()
            .all(|heading| heading.heading.text_lines == 1 && heading.first_line_num() == heading.line_num)
    );
    assert!(std::ptr::eq(headings[0].first_line_info(), headings[0].line_info));

    let top_level_valid_lines: Vec<_> = ctx.valid_headings().map(|heading| heading.line_num).collect();
    assert_eq!(top_level_valid_lines, vec![1, 2]);
    assert_eq!(ctx.heading_on_line(4).map(|heading| heading.blockquote_depth), Some(1));
    assert!(ctx.heading_on_line(3).is_none());
    assert!(ctx.heading_on_line(0).is_none());
}

#[test]
fn parsed_headings_exclude_non_markdown_regions() {
    let content =
        "---\ntitle: '# Front matter'\n---\n\n```md\n> ## Code\n```\n\n<div>\n> ## Raw HTML\n</div>\n\n# Visible\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let headings: Vec<_> = ctx
        .headings()
        .map(|heading| (heading.line_num, heading.heading.text.as_str()))
        .collect();
    assert_eq!(headings, vec![(13, "Visible")]);
}

#[test]
fn parsed_blockquote_headings_include_markdown_enabled_html() {
    let content = "<div markdown>\n> ## Rendered\n</div>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let headings: Vec<_> = ctx
        .headings()
        .map(|heading| {
            (
                heading.line_num,
                heading.heading.text.as_str(),
                heading.blockquote_depth,
            )
        })
        .collect();
    assert_eq!(headings, vec![(2, "Rendered", 1)]);
}

#[test]
fn parsed_blockquote_headings_respect_mkdocs_snippet_markers() {
    let content = "> # -8<- [start:section]\n> # Actual\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let headings: Vec<_> = ctx
        .headings()
        .map(|heading| (heading.line_num, heading.heading.text.as_str()))
        .collect();
    assert_eq!(headings, vec![(2, "Actual")]);
}

/// A quoted line inside a block whose body is not Markdown holds no heading.
#[test]
fn parsed_blockquote_headings_exclude_opaque_bodies_and_comments() {
    for (content, flavor) in [
        ("$$\n> # Equation\n$$\n", MarkdownFlavor::Standard),
        ("%%\n> # Hidden\n%%\n", MarkdownFlavor::Obsidian),
        ("> <!--\n> # Hidden\n> -->\n", MarkdownFlavor::Standard),
        ("Text <!--\n> # Hidden\n-->\n", MarkdownFlavor::Standard),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        assert_eq!(ctx.headings().count(), 0, "{flavor:?} {content:?}");
    }
    // Paired control: the same quoted line outside those blocks is a heading.
    let ctx = LintContext::new("> # Shown\n", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.headings().count(), 1);
}

/// Every setext heading `ctx.headings()` reports, as `(line, text, level,
/// blockquote depth)`.
fn setext_headings(content: &str, flavor: MarkdownFlavor) -> Vec<(usize, String, u8, usize)> {
    LintContext::new(content, flavor, None)
        .headings()
        .filter(super::types::ParsedHeading::is_setext)
        .map(|heading| {
            (
                heading.line_num,
                heading.heading.text.clone(),
                heading.heading.level,
                heading.blockquote_depth,
            )
        })
        .collect()
}

/// A setext text line is any paragraph text, whatever character it opens with.
/// Each row's expectation is the CommonMark reference renderer's.
#[test]
fn setext_text_line_is_any_paragraph_text() {
    for (content, text, level) in [
        ("*Label*\n===\n", "*Label*", 1),
        ("**Practice**\n---\n", "**Practice**", 2),
        ("+x\n===\n", "+x", 1),
        ("-x\n---\n", "-x", 2),
        ("2024 plans\n===\n", "2024 plans", 1),
        ("<span>Title</span>\n===\n", "<span>Title</span>", 1),
        ("<https://example.com>\n---\n", "<https://example.com>", 2),
        // A `=` run with nothing above it is paragraph text, which a `-` run
        // then underlines.
        ("===\n---\n", "===", 2),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(1, text.to_string(), level, 0)],
            "{content:?}"
        );
    }

    // `2.` cannot interrupt a paragraph, so it is the paragraph's second line
    // and the heading's text is both lines, recorded on the line the underline
    // sits under.
    assert_eq!(
        setext_headings("Intro\n2. foo\n===\n", MarkdownFlavor::Standard),
        vec![(2, "Intro 2. foo".to_string(), 1, 0)]
    );
    // A run that underlines a heading ends its paragraph, so the break below it
    // underlines nothing.
    assert_eq!(
        setext_headings("Title\n===\n---\n", MarkdownFlavor::Standard),
        vec![(1, "Title".to_string(), 1, 0)]
    );
}

/// The lines of an HTML block are raw HTML rather than a paragraph, so a run
/// written inside one underlines nothing. A tag alone on its line opens a block
/// where no paragraph runs into it, and the block runs to a blank line or to the
/// end of the container holding it. Each row's expectation is the CommonMark
/// reference renderer's, and pandoc's CommonMark reader agrees.
#[test]
fn setext_underline_inside_an_html_block_is_html() {
    for content in [
        "<span>\n===\n",
        "Intro\n\n<span class=\"x\">\n---\n",
        "</span>\n===\n",
        "<span/>\n===\n",
        "  <a href=\"x\">\n===\n",
        "<span>\nTitle\n===\n",
        "<span>\n> Title\n> ===\n",
        "> <span>\n> Title\n> ===\n",
        "> <div>\n> Title\n> ===\n",
        "> <pre>\n> Title\n> ===\n",
        "- <span>\n  Title\n  ===\n",
        "- <div>\n  Title\n  ===\n",
        "[^a]: <span>\n    Title\n    ===\n\nRef[^a]\n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
    for (content, line, text, depth) in [
        // Text after the tag on its line makes it inline content.
        ("<span> x\n===\n", 1, "<span> x", 0),
        // A blank line ends the block.
        ("<span>\n\nTitle\n===\n", 3, "Title", 0),
        ("> <span>\n\n> Title\n> ===\n", 3, "Title", 1),
        // The text of an HTML block opens no list item, so the heading below the
        // block sits at the top level rather than in a lazy item paragraph.
        ("<div>\n- a\n\n  Title\n===\n", 4, "Title", 0),
        // Front matter is not Markdown, so a tag written in it opens no block
        // over the lines after it ends.
        ("---\nhtml: |\n\n  <span>\n---\nTitle\n===\n", 6, "Title", 0),
        // A block opening on the line after another one ends can open containers
        // of its own, so the item holds the heading written inside it.
        ("<pre>\n</pre>\n10. <div>\n\n    Title\n    ===\n", 5, "Title", 0),
        // A tag naming no block-level element reads like paragraph text, yet it
        // opens an HTML block, which ends with the container holding it. So the
        // text below the container starts a paragraph of its own rather than
        // continuing one lazily.
        ("> <span>\nTitle\n===\n", 2, "Title", 0),
        ("- <span>\nTitle\n===\n", 2, "Title", 0),
        ("[^a]: <span>\nTitle\n===\n\nRef[^a]\n", 2, "Title", 0),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(line, text.to_string(), 1, depth)],
            "{content:?}"
        );
    }
    // A tag cannot interrupt a paragraph, so the paragraph runs on through it
    // into the heading.
    assert_eq!(
        setext_headings("Intro\n<span>\n===\n", MarkdownFlavor::Standard).len(),
        1
    );

    // An Obsidian comment is not Markdown either, while elsewhere `%%` is text
    // and the tag below it opens a block running through the underline.
    let content = "%%\n\n<span>\n%%\nTitle\n===\n";
    assert_eq!(
        setext_headings(content, MarkdownFlavor::Obsidian),
        vec![(5, "Title".to_string(), 1, 0)]
    );
    assert!(setext_headings(content, MarkdownFlavor::Standard).is_empty());

    // A flavor's own fence holds code, so a tag written inside it opens no
    // block over the lines below the fence. Where the same bytes carry no
    // fence, the tag is Markdown and opens a block running through the
    // underline.
    let content = "::: note\n\n<span>\n:::\nTitle\n===\n";
    assert_eq!(
        setext_headings(content, MarkdownFlavor::AzureDevOps),
        vec![(5, "Title".to_string(), 1, 0)]
    );
    assert!(setext_headings(content, MarkdownFlavor::Standard).is_empty());
}

/// A list item's text is not the paragraph a run below the item could
/// underline: the run is a lazy continuation of the item's paragraph.
#[test]
fn setext_underline_below_a_list_item_is_paragraph_text() {
    for content in [
        "- item\n===\n",
        "* * x\n===\n",
        "1) item\n===\n",
        "Intro\n1. foo\n===\n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
}

/// CommonMark 5.2: a list item starting with a blank line cannot interrupt a
/// paragraph, so a bare `-` under prose is the paragraph's underline and a bare
/// `*`, `+`, `1.` or `1)` is its text. Each row's expectation is pulldown-cmark's,
/// and pandoc's CommonMark reader agrees.
#[test]
fn empty_list_item_under_a_paragraph_opens_nothing() {
    for (content, line, depth) in [
        ("Title\n- \n", 1, 0),
        ("Title\n-\t\n", 1, 0),
        ("Title\n  -   \n", 1, 0),
        ("Title\n- \n  x\n", 1, 0),
        ("> Title\n> - \n", 1, 1),
        ("- a\n\n  Title\n  - \n", 3, 0),
        ("[^a]: intro\n\n    Title\n    - \n\nRef[^a]\n", 3, 0),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(line, "Title".to_string(), 2, depth)],
            "{content:?}"
        );
    }
    for content in [
        "Title\n* \n",
        "Title\n+ \n",
        "Title\n1. \n",
        "Title\n1) \n",
        // The first `-` has content, an empty item of its own, so it opens a list.
        "Title\n- - \n",
        // A blank line ends the paragraph, so the item below it opens.
        "Title\n\n- \n",
        // A sibling item interrupts no paragraph, and sits outside the first.
        "- Title\n- \n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
    // The bare `*` continues the paragraph, and the underline below makes a
    // heading of both lines, recorded on the line the underline sits under.
    assert_eq!(
        setext_headings("Title\n* \n===\n", MarkdownFlavor::Standard),
        vec![(2, "Title *".to_string(), 1, 0)]
    );
}

/// A setext underline makes a heading of the whole paragraph above it. The
/// heading is recorded on the paragraph's last line with the text of every
/// line, joined at the soft breaks by the space each renders as, and every text
/// line is marked as holding heading text.
#[test]
fn setext_heading_text_is_the_whole_paragraph() {
    let content = "Intro.\n\nFirst line\nsecond line\n===\n\nBody.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let headings: Vec<_> = ctx.headings().collect();
    assert_eq!(headings.len(), 1);
    let heading = &headings[0];
    assert_eq!((heading.first_line_num(), heading.line_num), (3, 4));
    assert_eq!(heading.heading.text_lines, 2);
    assert_eq!(heading.heading.text, "First line second line");
    assert_eq!(heading.heading.raw_text, "First line second line");
    assert_eq!(heading.heading.slug_text, "First line second line");
    assert_eq!(heading.heading.content_column, 0);
    assert_eq!(heading.first_line_info().byte_offset, 8);
    assert_eq!(heading.line_info.byte_offset, 19);
    assert_eq!(&content[heading.text_byte_range(content)], "First line\nsecond line");
    let text_lines: Vec<bool> = ctx.lines.iter().map(|line| line.is_setext_heading_text).collect();
    assert_eq!(text_lines, vec![false, false, true, true, false, false, false]);
    assert!(
        ctx.lines[2].heading.is_none(),
        "the heading is recorded on the last line"
    );
    assert!(ctx.heading_on_line(3).is_none());
    assert_eq!(ctx.heading_on_line(4).map(|heading| heading.first_line_num()), Some(3));
    let valid: Vec<_> = ctx
        .valid_headings()
        .map(|heading| {
            (
                heading.first_line_num(),
                heading.line_num,
                heading.first_line_info().byte_offset,
            )
        })
        .collect();
    assert_eq!(valid, vec![(3, 4, 8)]);

    // Three lines, a level 2 underline.
    assert_eq!(
        setext_headings("One\ntwo\nthree\n---\n", MarkdownFlavor::Standard),
        vec![(3, "One two three".to_string(), 2, 0)]
    );
    // A hard line break renders as a break, not as text: the backslash goes
    // with the line ending, and two trailing spaces are trimmed with it. An
    // escaped backslash pair is text and stays.
    assert_eq!(
        setext_headings("Foo\\\nBar\n===\n", MarkdownFlavor::Standard),
        vec![(2, "Foo Bar".to_string(), 1, 0)]
    );
    assert_eq!(
        setext_headings("Foo  \nBar\n===\n", MarkdownFlavor::Standard),
        vec![(2, "Foo Bar".to_string(), 1, 0)]
    );
    assert_eq!(
        setext_headings("Foo\\\\\nBar\n===\n", MarkdownFlavor::Standard),
        vec![(2, "Foo\\\\ Bar".to_string(), 1, 0)]
    );
    // A lazy continuation line is part of the paragraph a list item holds, and
    // the underline indented into the item makes a heading of the whole of it.
    assert_eq!(
        setext_headings("1. a\n\n   First\nsecond\n   ===\n", MarkdownFlavor::Standard),
        vec![(4, "First second".to_string(), 1, 0)]
    );

    // The text starts where the first line's does and ends before the
    // attribute list a custom ID sits in.
    let content = "  First\nsecond {#custom}\n===\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let heading = ctx.heading_on_line(2).expect("a heading on the last text line");
    assert_eq!(heading.heading.text, "First second");
    assert_eq!(heading.heading.custom_id.as_deref(), Some("custom"));
    assert_eq!(heading.heading.content_column, 2);
    assert_eq!(&content[heading.text_byte_range(content)], "First\nsecond");
}

/// The link reference definitions a paragraph opens with are not its text
/// (CommonMark 4.7), so the heading an underline makes starts below them, and a
/// run under definitions alone underlines nothing: it is the text of the
/// paragraph they open, however it reads. Each row's expectation is the
/// CommonMark reference renderer's.
#[test]
fn link_reference_definitions_above_the_text_stay_outside_the_heading() {
    let content = "[ref]: /url\nHeading\n=======\n\n[ref]\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let headings: Vec<_> = ctx.headings().collect();
    assert_eq!(headings.len(), 1);
    assert_eq!((headings[0].first_line_num(), headings[0].line_num), (2, 2));
    assert_eq!(headings[0].heading.text, "Heading");
    assert_eq!(headings[0].heading.text_lines, 1);
    assert_eq!(&content[headings[0].text_byte_range(content)], "Heading");
    let text_lines: Vec<bool> = ctx.lines.iter().map(|line| line.is_setext_heading_text).collect();
    assert_eq!(text_lines, vec![false, true, false, false, false]);

    for (content, expected) in [
        // Several definitions: one with a title, one indented.
        (
            "[a]: /a\n[b]: /b \"t\"\nHeading\n===\n",
            vec![(3, "Heading".to_string(), 1, 0)],
        ),
        (
            "[a]: /a\n    [b]: /b\nHeading\n===\n",
            vec![(3, "Heading".to_string(), 1, 0)],
        ),
        // A title on the line below a definition belongs to it; a line that
        // merely starts with one is paragraph text.
        (
            "[foo]: /url\n\"title\"\nHeading\n===\n",
            vec![(3, "Heading".to_string(), 1, 0)],
        ),
        (
            "[foo]: /url\n\"title\" ok\nHeading\n===\n",
            vec![(3, "\"title\" ok Heading".to_string(), 1, 0)],
        ),
        // The destination, and the title after it, may follow the label on
        // the lines below it, indented or not. A label whose destination line
        // reads as no destination defines nothing, and it all stays text.
        ("[foo]:\n/url\nTitle\n===\n", vec![(3, "Title".to_string(), 1, 0)]),
        ("[foo]:\n/url \"t\"\nTitle\n===\n", vec![(3, "Title".to_string(), 1, 0)]),
        (
            "[foo]:\n/url\n\"t\"\nTitle\n===\n",
            vec![(4, "Title".to_string(), 1, 0)],
        ),
        (
            "[foo]:\n  /url\n  \"t\"\nTitle\n===\n",
            vec![(4, "Title".to_string(), 1, 0)],
        ),
        ("[foo]:\n<a b>\nTitle\n===\n", vec![(3, "Title".to_string(), 1, 0)]),
        ("[a]: /a\n[b]:\n/b\nTitle\n===\n", vec![(4, "Title".to_string(), 1, 0)]),
        (
            "[foo]:\n/url\n\"t\" ok\nTitle\n===\n",
            vec![(4, "\"t\" ok Title".to_string(), 1, 0)],
        ),
        (
            "[foo]:\n/url \"t\" ok\nTitle\n===\n",
            vec![(3, "[foo]: /url \"t\" ok Title".to_string(), 1, 0)],
        ),
        ("[foo]:\n===\n", vec![(1, "[foo]:".to_string(), 1, 0)]),
        ("[foo]:\n/url\n\"t\"\n===\n", vec![]),
        ("[foo]:\n/url\n===\nBar\n---\n", vec![(4, "=== Bar".to_string(), 2, 0)]),
        // Definitions written inside a list item or a blockquote.
        (
            "- [foo]: /url\n  Heading\n  ===\n",
            vec![(2, "Heading".to_string(), 1, 0)],
        ),
        (
            "> [ref]: /url\n> Heading\n> ===\n",
            vec![(2, "Heading".to_string(), 1, 1)],
        ),
        // A run under definitions alone is paragraph text, whatever it reads,
        // and the paragraph runs on below it.
        ("[foo]: /url\n===\n[foo]\n", vec![]),
        ("[foo]: /url\n---\n", vec![]),
        ("[foo]: /url\n===\nBar\n---\n", vec![(3, "=== Bar".to_string(), 2, 0)]),
        ("[foo]: /url\n---\nBar\n===\n", vec![(3, "--- Bar".to_string(), 1, 0)]),
        // A footnote definition holds its body, and its label line is not
        // the text of a heading.
        ("[^a]: note\nHeading\n===\n", vec![]),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            expected,
            "{content:?}"
        );
    }
}

/// A backslash ending a line before the last is a hard line break, which
/// renders as the break rather than as text, so it goes with the line ending
/// it marks. A backslash inside a code span is code, and a backslash followed
/// by a space is text, since the space is what ends the line. Each row's
/// expectation is the CommonMark reference renderer's.
#[test]
fn a_hard_break_backslash_goes_with_the_line_ending_it_marks() {
    for (content, text) in [
        ("Foo\\\nBar\n===\n", "Foo Bar"),
        ("Foo\\\r\nBar\r\n===\r\n", "Foo Bar"),
        ("Foo `a\\\nb` tail\n===\n", "Foo `a\\ b` tail"),
        ("Foo\\ \nBar\n===\n", "Foo\\ Bar"),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(2, text.to_string(), 1, 0)],
            "{content:?}"
        );
    }
}

/// The text range of a heading ends where its display text ends: before the
/// attribute list a custom ID sits in and before an anchor element, on an
/// earlier line when the last line holds nothing else, and for an ATX heading
/// before its closing sequence. An anchor element written inside the text keeps
/// the range on the source, so it ends on a character boundary whatever the
/// anchor holds.
#[test]
fn the_text_range_ends_where_the_display_text_ends() {
    for (content, text, source_text) in [
        ("Title.\n{#id}\n===\n", "Title.", "Title."),
        ("Title.\n<a name=\"x\"></a>\n===\n", "Title.", "Title."),
        ("Title.\nmore {#id}\n===\n", "Title. more", "Title.\nmore"),
        ("> Title.\n> {#id}\n> ===\n", "Title.", "Title."),
        ("# Foo. ##\n", "Foo.", "Foo."),
        ("# Foo ## {#id}\n", "Foo", "Foo"),
        ("# Title. <a id=\"y\"></a>\n", "Title.", "Title."),
        ("# Foo <a id=\"x\"></a> ##\n", "Foo", "Foo"),
        ("# <a id=\"x\"></a> Foo\n", "Foo", "Foo"),
        (
            "# Foo <a id=\"\u{1f4a5}\"></a> bar.\n",
            "Foo bar.",
            "Foo <a id=\"\u{1f4a5}\"></a> bar.",
        ),
    ] {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let heading = ctx.headings().next().expect("a heading");
        assert_eq!(heading.heading.text, text, "{content:?}");
        assert_eq!(&content[heading.text_byte_range(content)], source_text, "{content:?}");
    }
}

/// A code block, an HTML block or indented code written inside a list item, a
/// footnote or a blockquote leaves the container open below it, so an underline
/// indented to the container's edge makes a heading there. Each row's
/// expectation is pulldown-cmark's.
#[test]
fn setext_headings_below_a_block_inside_a_container() {
    for (content, line, depth) in [
        ("10. item\n\n    ```\n    code\n    ```\n\n    Title\n    ===\n", 7, 0),
        ("10. item\n    ```\n    code\n    ```\n    Title\n    ===\n", 5, 0),
        ("10. ```\n    code\n    ```\n\n    Title\n    ===\n", 5, 0),
        ("10. item\n\n        code\n\n    Title\n    ===\n", 5, 0),
        ("10. item\n\n    <div>\n    x\n    </div>\n\n    Title\n    ===\n", 7, 0),
        ("- item\n\n  ```\n  code\n  ```\n\n  Title\n  ===\n", 7, 0),
        (
            "[^a]: intro\n\n    ```\n    code\n    ```\n\n    Title\n    ===\n\nRef[^a]\n",
            7,
            0,
        ),
        (
            "> 10. a\n>\n>     ```\n>     c\n>     ```\n>\n>     Title\n>     ===\n",
            7,
            1,
        ),
        // The text of a code block opens no list item, so the heading below the
        // block sits at the top level rather than in a lazy item paragraph.
        ("```\n- a\n  ```\n\n  Title\n===\n", 5, 0),
        // A code block starting on the line after another one ends can open
        // containers of its own, so the item holds the heading written inside it.
        ("~~~\nx\n~~~\n10. ```\n    c\n    ```\n\n    Title\n    ===\n", 8, 0),
        ("~~~\nx\n~~~\n10. ```\n    - a\n    ```\n\n    Title\n    ===\n", 8, 0),
        ("    x\n10. ```\n    c\n    ```\n\n    Title\n    ===\n", 6, 0),
        (
            "~~~\nx\n~~~\n> 10. ```\n>     c\n>     ```\n>\n>     Title\n>     ===\n",
            8,
            1,
        ),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(line, "Title".to_string(), 1, depth)],
            "{content:?}"
        );
    }
    for content in [
        // An underline outside the item is lazy.
        "10. item\n\n    ```\n    code\n    ```\n\n    Title\n===\n",
        "~~~\nx\n~~~\n- ```\n  c\n  ```\n\n  Title\n===\n",
        // Four columns past the item's edge are indented code.
        "10. item\n\n    ```\n    code\n    ```\n\n        Title\n        ===\n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
}

/// CommonMark 4.3 lets a setext underline be indented three spaces. A fourth
/// makes it paragraph text, except where indentation means something else.
#[test]
fn setext_underline_indent_is_limited_to_three_spaces() {
    let heading = vec![(1, "Foo".to_string(), 1, 0)];
    assert_eq!(setext_headings("Foo\n   ===\n", MarkdownFlavor::Standard), heading);
    assert!(setext_headings("Foo\n    ===\n", MarkdownFlavor::Standard).is_empty());
    // The tab reaches column eight, six past the item's content.
    assert!(setext_headings("- item\n\n  Heading\n\t    ===\n", MarkdownFlavor::Standard).is_empty());
    // MDX has no indented code, and markdown-rs lifts the limit with it.
    assert_eq!(setext_headings("Foo\n    ===\n", MarkdownFlavor::MDX), heading);
    // An admonition body is indented four columns, and its headings with it.
    assert_eq!(
        setext_headings("!!! note\n    Foo\n    ===\n", MarkdownFlavor::MkDocs),
        vec![(2, "Foo".to_string(), 1, 0)]
    );
}

/// A container's marker line is structure, so the paragraph below it is the
/// container's own, and a heading made of that paragraph holds no marker text.
/// Each row's expectation is the flavor's own renderer's reading: the opener of
/// a MkDocs admonition or content tab, a PyMdown block fence and a MyST colon
/// fence are no part of the body they hold, like a Pandoc div fence.
#[test]
fn container_marker_lines_hold_no_setext_text() {
    for (content, flavor, line, text, text_lines) in [
        ("!!! note\n    Foo\n    ===\n", MarkdownFlavor::MkDocs, 2, "Foo", 1),
        (
            "!!! note\n    First\n    second\n    ===\n",
            MarkdownFlavor::MkDocs,
            3,
            "First second",
            2,
        ),
        (
            "!!! note\n    !!! tip\n        Foo\n        ===\n",
            MarkdownFlavor::MkDocs,
            3,
            "Foo",
            1,
        ),
        ("=== \"Tab\"\n    Foo\n    ===\n", MarkdownFlavor::MkDocs, 2, "Foo", 1),
        ("/// note\nFoo\n===\n///\n", MarkdownFlavor::MkDocs, 2, "Foo", 1),
        (
            "/// outer\n/// inner\nFoo\n///\nBar\n===\n///\n",
            MarkdownFlavor::MkDocs,
            5,
            "Bar",
            1,
        ),
        (":::{note}\nFoo\n===\n:::\n", MarkdownFlavor::MyST, 2, "Foo", 1),
        (
            "::::{note}\n:::{tip}\nFoo\n:::\nBar\n===\n::::\n",
            MarkdownFlavor::MyST,
            5,
            "Bar",
            1,
        ),
        ("::: {.note}\nFoo\n===\n:::\n", MarkdownFlavor::Pandoc, 2, "Foo", 1),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        let headings: Vec<_> = ctx
            .headings()
            .filter(super::types::ParsedHeading::is_setext)
            .map(|heading| {
                (
                    heading.line_num,
                    heading.heading.text.clone(),
                    heading.heading.text_lines,
                )
            })
            .collect();
        assert_eq!(headings, vec![(line, text.to_string(), text_lines)], "{content:?}");
    }
    for (content, flavor, markers) in [
        (
            "!!! note\n    Foo\n    ===\n",
            MarkdownFlavor::MkDocs,
            vec![true, false, false],
        ),
        ("=== \"Tab\"\n    Foo\n", MarkdownFlavor::MkDocs, vec![true, false]),
        ("/// note\nFoo\n///\n", MarkdownFlavor::MkDocs, vec![true, false, true]),
        (":::{note}\nFoo\n:::\n", MarkdownFlavor::MyST, vec![true, false, true]),
        // A fence inside a code block is code, and a `:::` div fence is
        // `is_div_marker`.
        (
            "/// note\n```\n///\n```\n",
            MarkdownFlavor::MkDocs,
            vec![true, false, false, false],
        ),
        (
            "::: {.note}\nFoo\n:::\n",
            MarkdownFlavor::Pandoc,
            vec![false, false, false],
        ),
        ("!!! note\n    Foo\n", MarkdownFlavor::Standard, vec![false, false]),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        let flags: Vec<bool> = ctx.lines.iter().map(|line| line.is_container_marker).collect();
        assert_eq!(flags, markers, "{content:?}");
    }
}

/// A footnote definition's body is a container whose edge sits four columns
/// past the container holding the definition, re-entered by indentation. Each
/// row's expectation is pulldown-cmark's, and pandoc's CommonMark reader agrees.
#[test]
fn setext_headings_inside_footnote_definitions() {
    for (content, line, level) in [
        ("[^a]: intro\n\n    Heading\n    ===\n", 3, 1),
        ("[^a]: intro\n\n    Heading\n       ===\n", 3, 1),
        ("[^a]: intro\n\n    Heading\n    ---\n", 3, 2),
        ("[^a]: intro\n\n\tHeading\n\t===\n", 3, 1),
        // A tab reaches the next multiple of four, which is the body's edge.
        ("[^a]: intro\n\n    Heading\n\t===\n", 3, 1),
        // The edge is measured from the definition's container, not its label.
        ("  [^a]: intro\n\n    Heading\n     ===\n", 3, 1),
        ("- [^a]: intro\n\n      Heading\n      ===\n", 3, 1),
        // A definition interrupts a paragraph.
        ("Para\n[^a]: intro\n\n    Heading\n    ===\n", 4, 1),
        // A label written inside a body starts a body with the same edge.
        ("[^a]: intro\n\n    [^b]: x\n\n    Heading\n    ===\n", 5, 1),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(line, "Heading".to_string(), level, 0)],
            "{content:?}"
        );
    }

    // A label cannot hold an unescaped bracket, so this line opens no definition
    // and is the text of the heading.
    assert_eq!(
        setext_headings("[^a[b]: Heading\n===\n", MarkdownFlavor::Standard),
        vec![(1, "[^a[b]: Heading".to_string(), 1, 0)]
    );

    // The `>` takes one column of the tab after it, so a body opened in this
    // quote starts four columns past the quote's edge, at column 6.
    for content in [
        ">\t[^a]: intro\n>\n>\t  Heading\n>\t  ===\n",
        ">\t[^a]: intro\n>\n>\t     Heading\n>\t     ===\n",
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(3, "Heading".to_string(), 1, 1)],
            "{content:?}"
        );
    }

    for content in [
        // A heading starting on the label line sits inside the body the label
        // opens, where no ATX marker can be written, so none is recorded.
        "[^a]: Heading\n    ===\n",
        "> [^a]: Heading\n>     ===\n",
        // An underline that does not reach the body's edge is lazy.
        "[^a]: Heading\n===\n",
        "[^a]: intro\n\n    Heading\n===\n",
        "[^a]: intro\n\n    Heading\n   ===\n",
        "  [^a]: intro\n\n    Heading\n   ===\n",
        // Four columns past the body's edge make it paragraph text.
        "[^a]: intro\n\n    Heading\n        ===\n",
        "[^a]: intro\n\n\tHeading\n\t    ===\n",
        // Four columns past the edge of a body opened in a tab-indented quote
        // are indented code.
        ">\t[^a]: intro\n>\n>\t      Heading\n>\t      ===\n",
        // The body of an indented label shares the edge of the body holding it,
        // so four columns further in are paragraph text or indented code.
        "[^a]: intro\n\n    [^b]: x\n        Heading\n        ===\n",
        "[^a]: intro\n\n    [^b]: x\n\n        Heading\n        ===\n",
        // An unindented line closes the body.
        "[^a]: intro\n\nHeading\n    ===\n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
}

/// A `>` alone is a blank line inside its blockquote: it closes the blockquotes
/// it does not re-enter and leaves the list items and footnotes around it open,
/// which the reference renderer and pandoc agree on.
#[test]
fn setext_headings_after_a_blank_line_inside_a_blockquote() {
    for (content, line, depth) in [
        ("> - intro\n>\n>     Heading\n>     ===\n", 3, 1),
        ("> [^a]: intro\n>\n>     Heading\n>     ===\n", 3, 1),
        // The blank line closes the blockquote nested in the item, which holds on.
        ("> - a\n>   > b\n>\n>     Heading\n>     ===\n", 4, 1),
        ("> - a\n>   > b\n>\n>   > Heading\n>   > ===\n", 4, 2),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(line, "Heading".to_string(), 1, depth)],
            "{content:?}"
        );
    }
    // Four columns past the item's edge are indented code.
    assert!(
        setext_headings(
            "> - intro\n>\n>         Heading\n>         ===\n",
            MarkdownFlavor::Standard
        )
        .is_empty()
    );
}

/// A setext heading inside a blockquote is reported at its depth, with columns
/// that locate its text on the quoted line.
#[test]
fn setext_headings_inside_blockquotes() {
    let content = "> Title\n> ===\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let headings: Vec<_> = ctx.headings().collect();
    assert_eq!(headings.len(), 1);
    let heading = &headings[0];
    assert_eq!((heading.line_num, heading.blockquote_depth), (1, 1));
    assert_eq!(heading.heading.style, HeadingStyle::Setext1);
    assert_eq!(heading.heading.text, "Title");
    assert_eq!(heading.heading.marker, "===");
    assert_eq!((heading.heading.marker_column, heading.heading.content_column), (2, 2));
    assert_eq!(heading.text_byte_range(content), 2..7);
    assert!(
        ctx.lines[0].heading.is_none(),
        "a quoted heading is not a top-level one"
    );

    // The heading is the whole quoted paragraph, a lazy continuation line
    // included, recorded on its last line at the paragraph's depth.
    assert_eq!(
        setext_headings("> First\n> second\n> ===\n", MarkdownFlavor::Standard),
        vec![(2, "First second".to_string(), 1, 1)]
    );
    assert_eq!(
        setext_headings("> First\nmiddle\n> last\n> ===\n", MarkdownFlavor::Standard),
        vec![(3, "First middle last".to_string(), 1, 1)]
    );
    let content = "> First\n> second\n> ===\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let heading = ctx.heading_on_line(2).expect("a heading on the last text line");
    assert_eq!((heading.first_line_num(), heading.heading.text_lines), (1, 2));
    assert_eq!(&content[heading.text_byte_range(content)], "First\n> second");
    assert!(
        ctx.lines.iter().all(|line| !line.is_setext_heading_text),
        "a quoted heading is reported through headings(), not per line"
    );

    assert_eq!(
        setext_headings("> > Deep\n> > ---\n", MarkdownFlavor::Standard),
        vec![(1, "Deep".to_string(), 2, 2)]
    );
    assert_eq!(
        setext_headings("> Title\n>    ===\n", MarkdownFlavor::Standard),
        vec![(1, "Title".to_string(), 1, 1)]
    );
    // The `>` takes one column of a tab after it as its space, and the rest of
    // the tab indents the text, so these underlines sit three columns or fewer
    // past the quote's edge.
    for content in [">\tTitle\n>\t ===\n", " > Title\n >\t ===\n"] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::Standard),
            vec![(1, "Title".to_string(), 1, 1)],
            "{content:?}"
        );
    }
    assert_eq!(
        setext_headings("> > Title\n> >\t  ===\n", MarkdownFlavor::Standard),
        vec![(1, "Title".to_string(), 1, 2)]
    );

    for content in [
        // The two columns of the tab the `>` leaves over, and the two spaces,
        // put the underline four columns past the quote's edge.
        "> Title\n>\t  ===\n",
        ">\t> Title\n>\t>\t  ===\n",
        "> Title\n>\t\t===\n",
        // `> ---` re-enters only the outer quote, so it is a break there.
        "> > Deep\n> ---\n",
        // An underline cannot be a lazy continuation line.
        "> Quoted\n===\n",
        "> Quoted\n---\n",
        // Four spaces past the quote's edge make it paragraph text.
        "> Title\n>     ===\n",
        // Indented code is no paragraph to underline.
        ">     Foo\n> ===\n",
        // These are headings in CommonMark, and none is modeled: a lazy text
        // line carries fewer `>` than the paragraph it continues, so its own
        // depth is not the heading's, and a heading whose first line carries
        // a list marker is not recorded at any depth.
        "> First\nsecond\n> ===\n",
        "> > First\n> second\n> > ===\n",
        "> - item\n>   ---\n",
        "- First\n  second\n  ===\n",
    ] {
        assert!(
            setext_headings(content, MarkdownFlavor::Standard).is_empty(),
            "{content:?}"
        );
    }
}

/// A JSX flow element ends the paragraph above it; a JSX text element is part
/// of the paragraph holding it.
#[test]
fn setext_underline_and_mdx_jsx_elements() {
    assert!(setext_headings("Text\n<Card />\n===\n", MarkdownFlavor::MDX).is_empty());
    assert_eq!(
        setext_headings("Para\n<Card />\nText\n===\n", MarkdownFlavor::MDX),
        vec![(3, "Text".to_string(), 1, 0)]
    );
    assert_eq!(
        setext_headings("Heading <Badge>new</Badge>\n---\n", MarkdownFlavor::MDX),
        vec![(1, "Heading <Badge>new</Badge>".to_string(), 2, 0)]
    );

    // A flow element's children are Markdown blocks of their own, while its tag
    // lines end the paragraph beside them. Each row's expectation is markdown-rs's,
    // and remark-mdx agrees.
    assert_eq!(
        setext_headings("<Card>\ntext\n===\n</Card>\n", MarkdownFlavor::MDX),
        vec![(2, "text".to_string(), 1, 0)]
    );
    assert_eq!(
        setext_headings("<Card\n  title=\"x\"\n>\ntext\n===\n</Card>\n", MarkdownFlavor::MDX),
        vec![(4, "text".to_string(), 1, 0)]
    );
    for content in [
        "<Card>{x}\ntext\n===\n</Card>\n",
        "<Card><Inner />\ntext\n===\n</Card>\n",
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::MDX),
            vec![(2, "text".to_string(), 1, 0)],
            "{content:?}"
        );
    }
    for content in [
        "<Outer>\n<Inner>\ntext\n</Inner>\n===\n</Outer>\n",
        "<Outer>\ntext\n<Inner />\n===\n</Outer>\n",
        "<Card>{x}\n===\n</Card>\n",
        // The element ends no container, so an underline outside the item is a
        // lazy continuation of the item's text.
        "- <Card />\n  text\n===\n",
    ] {
        assert!(setext_headings(content, MarkdownFlavor::MDX).is_empty(), "{content:?}");
    }
    assert_eq!(
        setext_headings("- <Card />\n  text\n  ===\n", MarkdownFlavor::MDX),
        vec![(2, "text".to_string(), 1, 0)]
    );
}

/// An expression alone on its lines is a flow block of its own in MDX, so the
/// `===` below it opens a paragraph, while an expression sharing its line with
/// text is inline content of the heading. Each row's expectation is
/// remark-mdx's.
#[test]
fn setext_underline_below_an_mdx_flow_expression() {
    for content in [
        "{x}\n===\n",
        "  {x}\n===\n",
        "Intro\n\n{\n  x\n}\n===\n",
        "{[\n  1,\n]}\n===\n",
        "{/* c */}\n===\n",
        "text\n{x}\n===\n",
        "> {x}\n> ===\n",
        "<Card>\n{x}\n===\n</Card>\n",
        "{x}<Card />\n===\n",
        // The expression ends no container, so an underline outside the item is
        // a lazy continuation of the item's text.
        "- {x}\n  text\n===\n",
    ] {
        assert!(setext_headings(content, MarkdownFlavor::MDX).is_empty(), "{content:?}");
    }
    for (content, line, text) in [
        ("{x}\ntext\n===\n", 2, "text"),
        ("<Card>\n{x}\ntext\n===\n</Card>\n", 3, "text"),
        ("<Card>{x}\n{y}</Card>\ntext\n===\n", 3, "text"),
        ("- {x}\n  text\n  ===\n", 2, "text"),
        ("{x} and text\n===\n", 1, "{x} and text"),
        ("{x} {y}\n===\n", 1, "{x} {y}"),
    ] {
        assert_eq!(
            setext_headings(content, MarkdownFlavor::MDX),
            vec![(line, text.to_string(), 1, 0)],
            "{content:?}"
        );
    }
}

/// `:::` opens a div in Pandoc, and is paragraph text where nothing gives it
/// a meaning.
#[test]
fn setext_underline_below_a_colon_fence_depends_on_the_flavor() {
    let content = "::: note\n---\n\n# H\n";
    assert!(setext_headings(content, MarkdownFlavor::Pandoc).is_empty());
    assert_eq!(
        setext_headings(content, MarkdownFlavor::Standard),
        vec![(1, "::: note".to_string(), 2, 0)]
    );
}

#[test]
fn test_multi_line() {
    let content = "# Title\n\nSecond line\nThird line";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.line_offsets, vec![0, 8, 9, 21]);
    // Test offset to line/col
    assert_eq!(ctx.offset_to_line_col(0), (1, 1)); // start
    assert_eq!(ctx.offset_to_line_col(8), (2, 1)); // start of blank line
    assert_eq!(ctx.offset_to_line_col(9), (3, 1)); // start of 'Second line'
    assert_eq!(ctx.offset_to_line_col(15), (3, 7)); // middle of 'Second line'
    assert_eq!(ctx.offset_to_line_col(21), (4, 1)); // start of 'Third line'
}

#[test]
fn test_line_info() {
    let content = "# Title\n    indented\n\ncode:\n```rust\nfn main() {}\n```";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Test line info
    assert_eq!(ctx.lines.len(), 7);

    // Line 1: "# Title"
    let line1 = &ctx.lines[0];
    assert_eq!(line1.content(ctx.content), "# Title");
    assert_eq!(line1.byte_offset, 0);
    assert_eq!(line1.indent, 0);
    assert!(!line1.is_blank);
    assert!(!line1.in_code_block);
    assert!(line1.list_item.is_none());

    // Line 2: "    indented"
    let line2 = &ctx.lines[1];
    assert_eq!(line2.content(ctx.content), "    indented");
    assert_eq!(line2.byte_offset, 8);
    assert_eq!(line2.indent, 4);
    assert!(!line2.is_blank);

    // Line 3: "" (blank)
    let line3 = &ctx.lines[2];
    assert_eq!(line3.content(ctx.content), "");
    assert!(line3.is_blank);

    // Test helper methods
    assert_eq!(ctx.line_info(1).map(|l| l.indent), Some(0));
    assert_eq!(ctx.line_info(2).map(|l| l.indent), Some(4));
    assert_eq!(ctx.line_info(1).map(|l| l.byte_offset), Some(0));
    assert_eq!(ctx.line_info(2).map(|l| l.byte_offset), Some(8));
}

#[test]
fn test_list_item_detection() {
    let content = "- Unordered item\n  * Nested item\n1. Ordered item\n   2) Nested ordered\n\nNot a list";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Line 1: "- Unordered item"
    let line1 = &ctx.lines[0];
    assert!(line1.list_item.is_some());
    let list1 = line1.list_item.as_ref().unwrap();
    assert_eq!(list1.marker, "-");
    assert!(!list1.is_ordered);
    assert_eq!(list1.marker_column, 0);
    assert_eq!(list1.content_column, 2);

    // Line 2: "  * Nested item"
    let line2 = &ctx.lines[1];
    assert!(line2.list_item.is_some());
    let list2 = line2.list_item.as_ref().unwrap();
    assert_eq!(list2.marker, "*");
    assert_eq!(list2.marker_column, 2);

    // Line 3: "1. Ordered item"
    let line3 = &ctx.lines[2];
    assert!(line3.list_item.is_some());
    let list3 = line3.list_item.as_ref().unwrap();
    assert_eq!(list3.marker, "1.");
    assert!(list3.is_ordered);
    assert_eq!(list3.number, Some(1));

    // Line 6: "Not a list"
    let line6 = &ctx.lines[5];
    assert!(line6.list_item.is_none());
}

#[test]
fn parsed_list_views_preserve_existing_cache_semantics() {
    let fixtures = [
        (
            MarkdownFlavor::Standard,
            "- root\n  1. ordered child\n     continuation\n  * sibling\n\n> 10. quoted\n>     - nested\n\nparagraph\n\t- tabbed\n\n    - indented code\n",
        ),
        (
            MarkdownFlavor::MkDocs,
            "!!! note\n    - item\n        + nested\n\n=== tab\n    1. ordered\n       - child\n",
        ),
        (
            MarkdownFlavor::Kramdown,
            "{::nomarkdown}\n- hidden\n{:/nomarkdown}\n\n- visible\n  - child\n",
        ),
        (MarkdownFlavor::AzureDevOps, ":::python\n- code\n:::\n\n> - visible\n"),
    ];

    for (flavor, content) in fixtures {
        let ctx = LintContext::new(content, flavor, None);
        let raw_items: Vec<_> = ctx
            .lines
            .iter()
            .enumerate()
            .filter_map(|(idx, line)| {
                line.list_item.as_deref().map(|item| {
                    (
                        idx + 1,
                        item.marker.as_str(),
                        item.is_ordered,
                        item.number,
                        item.marker_column,
                        item.content_column,
                        line.blockquote.as_ref().map_or(0, |bq| bq.nesting_level),
                        line.blockquote.as_ref().map_or(0, |bq| bq.prefix.len()),
                    )
                })
            })
            .collect();
        let parsed_items: Vec<_> = ctx
            .list_items()
            .map(|item| {
                (
                    item.line_num(),
                    item.marker(),
                    item.is_ordered(),
                    item.number(),
                    item.marker_column(),
                    item.content_column(),
                    item.blockquote_depth(),
                    item.blockquote_prefix_len(),
                )
            })
            .collect();
        assert_eq!(parsed_items, raw_items, "list item view drifted for {flavor:?}");

        for line_num in 0..=ctx.lines.len() + 1 {
            let raw = line_num
                .checked_sub(1)
                .and_then(|idx| ctx.lines.get(idx))
                .and_then(|line| line.list_item.as_deref());
            let parsed = ctx.list_item_on_line(line_num);
            assert_eq!(parsed.is_some(), raw.is_some(), "lookup drifted at line {line_num}");
            if let (Some(parsed), Some(raw)) = (parsed, raw) {
                assert_eq!(parsed.marker(), raw.marker);
                assert_eq!(
                    parsed.marker_byte_offset(),
                    parsed.line_info().byte_offset + raw.marker_column
                );
            }
        }

        let parsed_blocks = ctx.parsed_list_blocks();
        assert_eq!(parsed_blocks.len(), ctx.list_blocks.len());
        assert_eq!(parsed_blocks.is_empty(), ctx.list_blocks.is_empty());
        for (index, (parsed, raw)) in parsed_blocks.into_iter().zip(&ctx.list_blocks).enumerate() {
            assert_eq!(
                parsed_blocks.get(index).map(ParsedListBlock::start_line),
                Some(raw.start_line)
            );
            assert_eq!(parsed.start_line(), raw.start_line);
            assert_eq!(parsed.end_line(), raw.end_line);
            assert_eq!(parsed.is_ordered(), raw.is_ordered);
            assert_eq!(parsed.marker(), raw.marker.as_deref());
            assert_eq!(parsed.blockquote_prefix(), raw.blockquote_prefix);
            assert_eq!(parsed.nesting_level(), raw.nesting_level);
            assert_eq!(parsed.max_marker_width(), raw.max_marker_width);
            assert_eq!(
                parsed.items().map(ParsedListItem::line_num).collect::<Vec<_>>(),
                raw.item_lines
                    .iter()
                    .copied()
                    .filter(|line| ctx.list_item_on_line(*line).is_some())
                    .collect::<Vec<_>>()
            );
        }
        assert!(parsed_blocks.get(parsed_blocks.len()).is_none());
        assert_eq!(ctx.has_list_items(), !raw_items.is_empty());
        assert_eq!(ctx.has_unordered_list_items(), raw_items.iter().any(|item| !item.2));
    }
}

#[test]
fn parsed_list_block_items_keep_source_order_and_container_depth() {
    let content = "- root\n  - child\n> 1. quoted\n>    + nested\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(
        ctx.list_items()
            .map(|item| (item.line_num(), item.marker(), item.blockquote_depth()))
            .collect::<Vec<_>>(),
        vec![(1, "-", 0), (2, "-", 0), (3, "1.", 1), (4, "+", 1)]
    );
    let block_lines: Vec<Vec<_>> = ctx
        .parsed_list_blocks()
        .into_iter()
        .map(|block| block.items().map(ParsedListItem::line_num).collect())
        .collect();
    assert_eq!(block_lines, vec![vec![1, 2, 3, 4]]);
}

#[test]
fn list_block_item_groups_split_a_block_into_its_lists() {
    // One block holds every level; the groups are the lists inside it, one
    // per run of items at a level, closed by the next shallower item, so the
    // children of `a` and the children of `b` are different lists even though
    // they sit at the same level. A tab and two spaces put `b1x` on column
    // 6, level 3, as six spaces would, and the level skipped on the way down
    // still closes on the way back up.
    let content = "- a\n  - a1\n  - a2\n- b\n  - b1\n\t  - b1x\n  - b2\n- c\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.list_blocks.len(), 1, "{:?}", ctx.list_blocks);
    let groups: Vec<Vec<usize>> = ctx
        .list_blocks
        .iter()
        .flat_map(|block| ctx.list_block_item_groups(block))
        .collect();
    assert_eq!(groups, vec![vec![1, 4, 8], vec![2, 3], vec![5, 7], vec![6]]);
}

#[test]
fn list_block_item_groups_split_on_a_marker_type_change() {
    // Two items at one level are in the same list only when their markers
    // are of one type: the same bullet character, or ordered markers with
    // the same delimiter. A change starts a new list at that level, nested
    // or not, even though the tracker keeps consecutive items of both kinds
    // in one block. Ordered markers may count up freely.
    let groups = |content: &str| -> Vec<Vec<usize>> {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.list_blocks.len(), 1, "{content:?}: {:?}", ctx.list_blocks);
        ctx.list_blocks
            .iter()
            .flat_map(|block| ctx.list_block_item_groups(block))
            .collect()
    };
    for content in [
        "- p\n  - a\n  - b\n  * c\n\n  * d\n",
        "- p\n  - a\n  - b\n  + c\n\n  + d\n",
        "- p\n  1. a\n  2. b\n  1) c\n\n  2) d\n",
        "- p\n  - a\n  - b\n  1. c\n\n  2. d\n",
        "- p\n  1. a\n  2. b\n  - c\n\n  - d\n",
    ] {
        assert_eq!(groups(content), vec![vec![1], vec![2, 3], vec![4, 6]], "{content:?}");
    }
    assert_eq!(groups("- a\n- b\n* c\n\n* d\n"), vec![vec![1, 2], vec![3, 5]]);
    assert_eq!(groups("1. a\n2. b\n1) c\n\n2) d\n"), vec![vec![1, 2], vec![3, 5]]);
    // Controls: one type throughout is one list.
    for content in [
        "- p\n  - a\n  - b\n  - c\n\n  - d\n",
        "- p\n  1. a\n  2. b\n  7. c\n\n  4. d\n",
        "- p\n  1) a\n  2) b\n  3) c\n\n  4) d\n",
    ] {
        assert_eq!(groups(content), vec![vec![1], vec![2, 3, 4, 6]], "{content:?}");
    }
    assert_eq!(groups("- a\n- b\n- c\n\n- d\n"), vec![vec![1, 2, 3, 5]]);
}

#[test]
fn list_block_item_groups_read_ancestry_from_columns() {
    // An item is nested in the open list's latest item when it starts at or
    // right of that item's content column, and a sibling when it starts left
    // of it but not left of the column the list lives in. Siblings may sit at
    // different indents, so a sibling and a nested list can share a marker
    // column and still be different lists; the level is not the column.
    let groups = |content: &str| -> Vec<Vec<usize>> {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.list_blocks.len(), 1, "{content:?}: {:?}", ctx.list_blocks);
        ctx.list_blocks
            .iter()
            .flat_map(|block| ctx.list_block_item_groups(block))
            .collect()
    };
    // The siblings at column 2 sit left of the parent's content column 3, so
    // they are the parent's siblings, not more items of the child list at
    // column 3.
    assert_eq!(
        groups(" - parent\n   - child a\n   - child b\n\n  - sibling a\n\n  - sibling b\n"),
        vec![vec![1, 5, 7], vec![2, 3]]
    );
    // Siblings at indents 0 to 3 are one list, at the top and nested.
    assert_eq!(groups("  - first\n- second\n"), vec![vec![1, 2]]);
    assert_eq!(groups("- a\n - b\n  - c\n   - d\n"), vec![vec![1, 2, 3, 4]]);
    assert_eq!(groups("- a\n    - b\n  - c\n"), vec![vec![1], vec![2, 3]]);
    // Ordered markers of different widths are siblings when the wider one
    // starts left of the content column.
    assert_eq!(groups("9. a\n10. b\n\n11. c\n"), vec![vec![1, 2, 4]]);
    // An item at or right of the content column is nested, however deep.
    assert_eq!(groups("- a\n\n    - b\n"), vec![vec![1], vec![3]]);
    assert_eq!(
        groups("* parent\n    - child a\n    - child b\n  * sibling\n"),
        vec![vec![1], vec![2, 3], vec![4]]
    );
    // A blockquote starting inside the item's content nests its list there;
    // one starting left of the content column ends the list, and an item
    // after it starts another.
    assert_eq!(groups("- a\n  > - b\n  > - c\n- d\n"), vec![vec![1, 4], vec![2, 3]]);
    assert_eq!(groups("> - a\n>   > - b\n> - c\n"), vec![vec![1, 3], vec![2]]);
    assert_eq!(groups("1. a\n> - b\n2. c\n"), vec![vec![1], vec![2], vec![3]]);
    assert_eq!(groups("> - a\n>> - b\n"), vec![vec![1], vec![2]]);
    // Columns inside a blockquote count from the quote's content, so the
    // indent before the `>` and the space after it change nothing: the child
    // items at quote-relative column 2 are nested in a parent whose content
    // starts at 2, and an item at column 1 is the parent's sibling.
    assert_eq!(
        groups(" > - parent\n>   - child a\n>\n>   - child b\n"),
        vec![vec![1], vec![2, 4]]
    );
    assert_eq!(groups("  > - a\n>   - b\n>  - c\n"), vec![vec![1, 3], vec![2]]);
    assert_eq!(groups(">- a\n> - b\n"), vec![vec![1, 2]]);
    assert_eq!(groups("> - a\n>- b\n"), vec![vec![1, 2]]);
    assert_eq!(groups("> - a\n>\t- b\n"), vec![vec![1], vec![2]]);
    assert_eq!(groups("- a\n  > - b\n   > - c\n- e\n"), vec![vec![1, 4], vec![2, 3]]);
}

#[test]
fn list_block_item_groups_close_a_nested_list_on_ancestor_content() {
    // Content that belongs to the parent item, sitting left of the nested
    // items' content column, ends the nested list; a later nested list under
    // the same parent is a different list. A paragraph line directly under
    // an item continues it lazily wherever it starts, so it closes nothing.
    let groups = |content: &str| -> Vec<Vec<usize>> {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.list_blocks.len(), 1, "{content:?}: {:?}", ctx.list_blocks);
        ctx.list_blocks
            .iter()
            .flat_map(|block| ctx.list_block_item_groups(block))
            .collect()
    };
    // Paragraph at the parent's content column between two nested lists.
    assert_eq!(
        groups("- p\n  - a\n  - b\n\n  With:\n\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3], vec![7, 9]]
    );
    // Content indented to the nested items' content column continues them.
    assert_eq!(
        groups("- p\n  - a\n\n    More about a.\n\n  - b\n"),
        vec![vec![1], vec![2, 6]]
    );
    // A lazy continuation line starts wherever it likes.
    assert_eq!(groups("- p\n  - a\nlazy tail of a\n  - b\n"), vec![vec![1], vec![2, 4]]);
    // Ancestor content also closes every list deeper than the one it ends.
    assert_eq!(
        groups("- p\n  - a\n    - a1\n\n  With:\n\n  - b\n    - b1\n"),
        vec![vec![1], vec![2], vec![3], vec![7], vec![8]]
    );
    // Inside a blockquote the same columns are measured after the marker.
    assert_eq!(
        groups("> - p\n>   - a\n>   - b\n>\n>   With:\n>\n>   - c\n>   - d\n"),
        vec![vec![1], vec![2, 3], vec![7, 8]]
    );
    // What interrupts a paragraph needs no blank line before it to end the
    // nested list: an HTML comment or instruction opener, and a blockquote
    // (a `>` with nothing after it opens one under an unquoted list; it is
    // a blank line only to a list at its own quote depth).
    assert_eq!(
        groups("- p\n  - a\n  - b\n  <!-- parent comment -->\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3], vec![5, 7]]
    );
    assert_eq!(
        groups("- p\n  - a\n  - b\n  <?php echo 1; ?>\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3], vec![5, 7]]
    );
    assert_eq!(
        groups("- p\n  - a\n  - b\n  >\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3], vec![5, 7]]
    );
    assert_eq!(
        groups("> - p\n>   - a\n>   - b\n>   >\n>   - c\n>\n>   - d\n"),
        vec![vec![1], vec![2, 3], vec![5, 7]]
    );
    // A comment that opens inside an item's paragraph continues that
    // paragraph across the lines it covers; only an opener at line start
    // is a block.
    assert_eq!(
        groups("- p\n  - a\n  - b <!-- start\n  continues\n  -->\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3, 6, 8]]
    );
    // Lazy continuation needs an open paragraph. A bare `>` inside the
    // nested item and an empty item leave none, so the dedented text after
    // them is the parent's and ends the nested list; a quoted paragraph is
    // one, and the text continues it.
    assert_eq!(
        groups("- p\n  - a\n    >\n  parent\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2], vec![5, 7]]
    );
    assert_eq!(
        groups("- p\n  - a\n  -\n  text\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 3], vec![5, 7]]
    );
    assert_eq!(
        groups("- p\n  - a\n    > quote\n  parent\n  - c\n\n  - d\n"),
        vec![vec![1], vec![2, 5, 7]]
    );
    // An item whose own text opens a block (a fence, a heading, a thematic
    // break, an HTML block, indented code) opens no paragraph either, so
    // dedented text after it ends the nested list; a nested item's text is a
    // paragraph and continues.
    for (content, second_list) in [
        ("- p\n  - a\n  - ```\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - # h\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - ***\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  -     code\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - <div>\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - - # h\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - -\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - >\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - >     code\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        ("- p\n  - a\n  - 1. ```\n  more\n  - c\n\n  - d\n", vec![5, 7]),
        (
            "- p\n  - a\n  - | h |\n    | --- |\n  more\n  - c\n\n  - d\n",
            vec![6, 8],
        ),
        ("- p\n  - a\n  - <!-- c\n  more\n  -->\n  - c\n\n  - d\n", vec![6, 8]),
    ] {
        assert_eq!(groups(content), vec![vec![1], vec![2, 3], second_list], "{content:?}");
    }
    for content in [
        "- p\n  - a\n  - - b1\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  -    text\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  - #tag\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  - ```lang`bad\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  - > text\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  - - text\n  more\n  - c\n\n  - d\n",
        "- p\n  - a\n  - 1234567890. x\n  more\n  - c\n\n  - d\n",
    ] {
        assert_eq!(groups(content), vec![vec![1], vec![2, 3, 5, 7]], "{content:?}");
    }
}

#[test]
fn list_block_item_groups_end_with_the_item_that_holds_their_blockquote() {
    // A list inside a blockquote inside an item lives in that item: a line
    // whose `>` sits left of the item's content is not in the item, so it
    // ends the item and every list nested in it, however the columns inside
    // the quote compare. A line with fewer quote markers than the list ends
    // its blockquote unless it lazily continues a paragraph, a blank line
    // included, and items in the next blockquote are another list. A blank
    // line or bare `>` at the list's own depth is only the spacing between
    // its items.
    let groups = |content: &str| -> Vec<Vec<usize>> {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.list_blocks.len(), 1, "{content:?}: {:?}", ctx.list_blocks);
        ctx.list_blocks
            .iter()
            .flat_map(|block| ctx.list_block_item_groups(block))
            .collect()
    };
    // The `>` at column 0 leaves `p`; the quote inside `p` measured its
    // items from column 0 too, so the columns alone would read `c` as a
    // sibling of `b2`.
    assert_eq!(
        groups("- p\n  >- b1\n  >\n  >- b2\n>- c\n>- d\n"),
        vec![vec![1], vec![2, 4], vec![5, 6]]
    );
    assert_eq!(groups("- p\n  >- b   x\n>- c   x\n"), vec![vec![1], vec![2], vec![3]]);
    assert_eq!(groups("- p\n  > - b1\n>\n  > - b2\n"), vec![vec![1], vec![2], vec![4]]);
    // A blank line ends the blockquote; a bare `>` at its depth does not.
    assert_eq!(groups("- p\n  > - b1\n\n  > - b2\n"), vec![vec![1], vec![2], vec![4]]);
    assert_eq!(
        groups("- p\n  > - b1\n  > - b2\n\n  > - b3\n"),
        vec![vec![1], vec![2, 3], vec![5]]
    );
    assert_eq!(
        groups("> - a\n>   - b\n>   - c\n\n>   - d\n"),
        vec![vec![1], vec![2, 3], vec![5]]
    );
    assert_eq!(groups("> - a\n>   - b\n>\n>   - c\n"), vec![vec![1], vec![2, 4]]);
    assert_eq!(
        groups("- p\n  > > - x\n  >\n  > > - y\n"),
        vec![vec![1], vec![2], vec![4]]
    );
    assert_eq!(groups("- p\n  > > - x\n  > >\n  > > - y\n"), vec![vec![1], vec![2, 4]]);
    // Paragraph text with fewer markers continues the quoted item lazily.
    assert_eq!(groups("- p\n  > - b1\n  lazy\n  > - b2\n"), vec![vec![1], vec![2, 4]]);
    assert_eq!(groups("- p\n  >- b1\ntext\n  >- b2\n"), vec![vec![1], vec![2, 4]]);
    // After the blockquote, an item at the holding item's content column
    // starts a new list in that item; a deeper `>` left of the quoted item's
    // content starts a blockquote beside it, and its list is nested in `p`.
    assert_eq!(groups("- p\n  > - b1\n  - q\n"), vec![vec![1], vec![2], vec![3]]);
    assert_eq!(groups("- p\n  > - a\n  >> - b\n"), vec![vec![1], vec![2], vec![3]]);
}

#[test]
fn list_block_item_groups_close_the_list_at_the_block_level_too() {
    // A fence, an HTML block or a blank line that ends a blockquote closes
    // the list at the block's own level the way it closes a nested one; the
    // tracker keeps the items on both sides in one block, so a later item
    // starts a new list at that level instead of nesting in the item the
    // line ended, and an item that would nest in the ended item is a
    // sibling of the item after it. A lazy paragraph line and content at
    // the item's content column continue the item.
    let groups = |content: &str| -> Vec<Vec<usize>> {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.list_blocks.len(), 1, "{content:?}: {:?}", ctx.list_blocks);
        ctx.list_blocks
            .iter()
            .flat_map(|block| ctx.list_block_item_groups(block))
            .collect()
    };
    assert_eq!(groups("- p\n```\n```\n- q\n"), vec![vec![1], vec![4]]);
    assert_eq!(groups("- p\n<!-- x -->\n- q\n"), vec![vec![1], vec![3]]);
    assert_eq!(groups("- p\n```\n```\n  - b\n- c\n"), vec![vec![1], vec![4, 5]]);
    assert_eq!(groups("- p\n<!-- x -->\n  - b\n- c\n"), vec![vec![1], vec![3, 4]]);
    assert_eq!(
        groups("- p\n```\n```\n  > - b\n  lazy\n> - c\n"),
        vec![vec![1], vec![4, 6]]
    );
    assert_eq!(groups("> - a\n> - b\n\n> - c\n"), vec![vec![1, 2], vec![4]]);
    // Controls: the item continues through a lazy line and indented content.
    assert_eq!(groups("- p\nlazy\n- q\n"), vec![vec![1, 3]]);
    assert_eq!(groups("- p\n\n  more\n- q\n"), vec![vec![1, 4]]);
    assert_eq!(groups("- p\n\n  ```\n  ```\n- q\n"), vec![vec![1, 5]]);
}

#[test]
fn commonmark_ordered_lists_preserve_raw_membership_and_start_values() {
    let fixtures = [
        (
            MarkdownFlavor::Standard,
            "11. outer\n     1. nested\n     2. nested\n12. outer\n\nparagraph\n\n1. restart\n2. restart\n\n> 7. quoted\n> 8. quoted\n",
        ),
        (
            MarkdownFlavor::MkDocs,
            "1. outer\n    9. nested\n    10. nested\n2. outer\n\n!!! note\n    4. inside\n    5. inside\n",
        ),
        (
            MarkdownFlavor::Pandoc,
            "(@example) example marker\n\n3) parenthesized\n4) parenthesized\n\n1. ordinary\n",
        ),
    ];

    for (flavor, content) in fixtures {
        let ctx = LintContext::new(content, flavor, None);
        assert!(ctx.commonmark_ordered_lists_cache.get().is_none());
        let raw = crate::utils::code_block_utils::CodeBlockUtils::detect_code_blocks_and_spans(content);
        let mut groups: std::collections::HashMap<usize, Vec<usize>> = std::collections::HashMap::new();

        for line_num in 1..=ctx.lines.len() {
            if ctx.list_item_on_line(line_num).is_some_and(ParsedListItem::is_ordered)
                && let Some(&list_id) = raw.line_to_list.get(&line_num)
            {
                groups.entry(list_id).or_default().push(line_num);
            }
        }

        let mut expected: Vec<_> = groups
            .into_iter()
            .map(|(list_id, mut item_lines)| {
                item_lines.sort_unstable();
                (raw.list_start_values.get(&list_id).copied().unwrap_or(1), item_lines)
            })
            .collect();
        expected.sort_by_key(|(_, lines)| lines.first().copied().unwrap_or(0));

        let lists = ctx.commonmark_ordered_lists();
        assert!(ctx.commonmark_ordered_lists_cache.get().is_some());
        let actual: Vec<_> = lists
            .into_iter()
            .map(|list| {
                (
                    list.start_value(),
                    list.items().map(ParsedListItem::line_num).collect::<Vec<_>>(),
                )
            })
            .collect();
        assert_eq!(actual, expected, "CommonMark grouping drifted for {flavor:?}");
        assert_eq!(lists.len(), expected.len());
        assert_eq!(lists.is_empty(), expected.is_empty());
        for (index, expected_list) in expected.iter().enumerate() {
            let list = lists.get(index).expect("index comes from expected list collection");
            assert_eq!(list.start_value(), expected_list.0);
        }
        assert!(lists.get(lists.len()).is_none());
    }
}

#[test]
fn commonmark_ordered_lists_keep_nested_groups_source_ordered() {
    let content = "11. outer\n     1. nested\n     2. nested\n12. outer\n\ntext\n\n1. restart\n2. restart\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let groups: Vec<_> = ctx
        .commonmark_ordered_lists()
        .into_iter()
        .map(|list| {
            (
                list.start_value(),
                list.items().map(ParsedListItem::line_num).collect::<Vec<_>>(),
            )
        })
        .collect();

    assert_eq!(groups, vec![(11, vec![1, 4]), (1, vec![2, 3]), (1, vec![8, 9])]);
}

#[test]
fn test_offset_to_line_col_edge_cases() {
    let content = "a\nb\nc";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    // line_offsets: [0, 2, 4]
    assert_eq!(ctx.offset_to_line_col(0), (1, 1)); // 'a'
    assert_eq!(ctx.offset_to_line_col(1), (1, 2)); // after 'a'
    assert_eq!(ctx.offset_to_line_col(2), (2, 1)); // 'b'
    assert_eq!(ctx.offset_to_line_col(3), (2, 2)); // after 'b'
    assert_eq!(ctx.offset_to_line_col(4), (3, 1)); // 'c'
    assert_eq!(ctx.offset_to_line_col(5), (3, 2)); // after 'c'
}

#[test]
fn test_offset_to_line_col_non_ascii() {
    // Issue #670: the column is a character offset, not a byte offset.
    // "你好x": 你=bytes 0-2, 好=bytes 3-5, x=byte 6.
    let content = "你好x";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.offset_to_line_col(0), (1, 1)); // ä½  -> char column 1
    assert_eq!(ctx.offset_to_line_col(3), (1, 2)); // 好 -> char column 2
    assert_eq!(ctx.offset_to_line_col(6), (1, 3)); // x  -> char column 3 (not byte 7)
}

#[test]
fn source_location_queries_define_utf8_crlf_and_eof_boundaries() {
    let content = "éx\r\n中\nlast";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.line_start_byte(1), Some(0));
    assert_eq!(ctx.line_start_byte(2), Some(5));
    assert_eq!(ctx.line_start_byte(3), Some(9));
    assert_eq!(ctx.line_start_byte(0), None);
    assert_eq!(ctx.line_start_byte(4), None);

    assert_eq!(ctx.line_column_byte_range(1, 2), 2..2);
    assert_eq!(ctx.line_column_byte_range_with_length(1, 1, 2), 0..3);
    assert_eq!(ctx.line_text_byte_range(2, 1, 2), 5..8);

    assert_eq!(ctx.line_content_byte_range(1), 0..3);
    assert_eq!(ctx.whole_line_byte_range(1), 0..5);
    assert_eq!(ctx.line_span_byte_range(1, 2), 0..9);
    assert_eq!(ctx.line_content_byte_range(3), 9..13);
    assert_eq!(ctx.whole_line_byte_range(3), 9..13);

    let eof = content.len();
    assert_eq!(ctx.line_column_byte_range(99, 99), eof..eof);
    assert_eq!(ctx.line_content_byte_range(99), eof..eof);
}

#[test]
fn test_mdx_esm_blocks() {
    let content = r##"import {Chart} from './snowfall.js'
export const year = 2023

# Last year's snowfall

In {year}, the snowfall was above average.
It was followed by a warm spring which caused
flood conditions in many of the nearby rivers.

<Chart color="#fcb32c" year={year} />
"##;

    let ctx = LintContext::new(content, MarkdownFlavor::MDX, None);

    // Check that lines 1 and 2 are marked as ESM blocks
    assert_eq!(ctx.lines.len(), 10);
    assert!(ctx.lines[0].in_esm_block, "Line 1 (import) should be in_esm_block");
    assert!(ctx.lines[1].in_esm_block, "Line 2 (export) should be in_esm_block");
    assert!(!ctx.lines[2].in_esm_block, "Line 3 (blank) should NOT be in_esm_block");
    assert!(
        !ctx.lines[3].in_esm_block,
        "Line 4 (heading) should NOT be in_esm_block"
    );
    assert!(!ctx.lines[4].in_esm_block, "Line 5 (blank) should NOT be in_esm_block");
    assert!(!ctx.lines[5].in_esm_block, "Line 6 (text) should NOT be in_esm_block");
}

#[test]
fn test_mdx_esm_blocks_not_detected_in_standard_flavor() {
    let content = r#"import {Chart} from './snowfall.js'
export const year = 2023

# Last year's snowfall
"#;

    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // ESM blocks should NOT be detected in Standard flavor
    assert!(
        !ctx.lines[0].in_esm_block,
        "Line 1 should NOT be in_esm_block in Standard flavor"
    );
    assert!(
        !ctx.lines[1].in_esm_block,
        "Line 2 should NOT be in_esm_block in Standard flavor"
    );
}

#[test]
fn test_blockquote_with_indented_content() {
    // Lines with `>` followed by heavily-indented content should be detected as blockquotes.
    // The content inside the blockquote may also be detected as a code block (which is correct),
    // but for MD046 purposes, we need to know the line is inside a blockquote.
    let content = r#"# Heading

>      -S socket-path
>                    More text
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Line 3 (index 2) should be detected as blockquote
    assert!(
        ctx.lines.get(2).is_some_and(|l| l.blockquote.is_some()),
        "Line 3 should be a blockquote"
    );
    // Line 4 (index 3) should also be blockquote
    assert!(
        ctx.lines.get(3).is_some_and(|l| l.blockquote.is_some()),
        "Line 4 should be a blockquote"
    );

    // Verify blockquote content is correctly parsed
    // Note: spaces_after includes the spaces between `>` and content
    let bq3 = ctx.lines.get(2).unwrap().blockquote.as_ref().unwrap();
    assert_eq!(bq3.content, "-S socket-path");
    assert_eq!(bq3.nesting_level, 1);
    // 6 spaces after the `>` marker
    assert!(bq3.has_multiple_spaces_after_marker);

    let bq4 = ctx.lines.get(3).unwrap().blockquote.as_ref().unwrap();
    assert_eq!(bq4.content, "More text");
    assert_eq!(bq4.nesting_level, 1);
}

#[test]
fn test_blockquote_spaced_nested_markers_are_detected() {
    let content = r#"> > Nested quote content
> > Additional line
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let bq1 = ctx.lines.first().unwrap().blockquote.as_ref().unwrap();
    assert_eq!(bq1.nesting_level, 2);
    assert_eq!(bq1.prefix, "> > ");
    assert_eq!(bq1.content, "Nested quote content");

    let bq2 = ctx.lines.get(1).unwrap().blockquote.as_ref().unwrap();
    assert_eq!(bq2.nesting_level, 2);
    assert_eq!(bq2.prefix, "> > ");
    assert_eq!(bq2.content, "Additional line");
}

#[test]
fn test_ref_def_with_angle_bracket_destination_containing_space() {
    // CommonMark §6.6 admits <...>-form destinations that contain spaces.
    // Without this, the auto-fix output `[id]: <./has space.md>` (which
    // `format_url_destination` chooses for whitespace-bearing URLs) silently
    // disappears from `ctx.reference_definitions()` on the next parse, breaking
    // dedup in MD054 and ref-def discovery in MD053/MD057.
    let content = "[docs]: <./has space.md>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        ctx.reference_definitions().len(),
        1,
        "angle-bracket destination must parse"
    );
    assert_eq!(ctx.reference_definitions()[0].id, "docs");
    assert_eq!(
        ctx.reference_definitions()[0].url,
        "./has space.md",
        "URL should be the destination content, not the angle-bracketed form"
    );
    assert_eq!(ctx.reference_definitions()[0].title, None);
}

#[test]
fn test_ref_def_with_angle_bracket_destination_and_title() {
    // The optional title still parses after an angle-bracket destination.
    let content = "[docs]: <./has space.md> \"Help me\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].url, "./has space.md");
    assert_eq!(ctx.reference_definitions()[0].title.as_deref(), Some("Help me"));
}

#[test]
fn test_ref_def_multiline_title_on_next_line() {
    // CommonMark §4.7: a reference definition's title may sit on the line
    // immediately after the destination. The whole definition - including the
    // title line - is one reference definition.
    let content = "[ref]: https://example.com\n  \"the title\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title.as_deref(), Some("the title"));
    // The byte range and is_in_reference_def cover the continuation title line.
    let quote = content.find('"').unwrap();
    assert!(
        ctx.is_in_reference_def(quote),
        "title line should be inside the ref def"
    );
    // The title byte range spans the delimiters exactly, and byte_end reaches
    // the end of the continuation line (the byte before its newline).
    let def = &ctx.reference_definitions()[0];
    assert_eq!(
        def.title_byte_start,
        Some(quote),
        "title_byte_start is the opening quote"
    );
    assert_eq!(
        def.title_byte_end,
        Some(quote + "\"the title\"".len()),
        "title_byte_end is one past the closing quote"
    );
    assert_eq!(
        def.byte_end,
        content.trim_end_matches('\n').len(),
        "byte_end reaches end of title line"
    );
}

#[test]
fn test_ref_def_single_quote_and_paren_title_on_next_line() {
    for content in [
        "[ref]: https://example.com\n  'the title'\n",
        "[ref]: https://example.com\n  (the title)\n",
    ] {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert_eq!(ctx.reference_definitions().len(), 1, "input: {content:?}");
        assert_eq!(
            ctx.reference_definitions()[0].title.as_deref(),
            Some("the title"),
            "input: {content:?}"
        );
    }
}

#[test]
fn test_ref_def_blank_line_breaks_multiline_title() {
    // A blank line between the destination and a quoted line means the quoted
    // line is a separate paragraph, not the definition's title.
    let content = "[ref]: https://example.com\n\n\"not a title\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title, None);
    let quote = content.find('"').unwrap();
    assert!(
        !ctx.is_in_reference_def(quote),
        "a blank-separated quoted line is not part of the ref def"
    );
}

#[test]
fn test_ref_def_non_title_next_line_not_consumed() {
    // The line after the destination is only a title if it is *only* a quoted
    // or parenthesised title; ordinary prose is a separate paragraph.
    let content = "[ref]: https://example.com\nordinary paragraph text\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title, None);
    let para = content.find("ordinary").unwrap();
    assert!(
        !ctx.is_in_reference_def(para),
        "a following paragraph is not part of the ref def"
    );
}

#[test]
fn test_ref_def_inline_title_unaffected_by_lookahead() {
    // A definition that already has its title on the destination line is
    // unchanged; the next line is not pulled in.
    let content = "[ref]: https://example.com \"inline\"\n\"separate\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title.as_deref(), Some("inline"));
    let sep = content.find("\"separate\"").unwrap();
    assert!(
        !ctx.is_in_reference_def(sep),
        "the inline-title def must not absorb the next line"
    );
}

#[test]
fn test_ref_def_multiline_title_in_blockquote() {
    // A reference definition inside a blockquote may also carry its title on
    // the following (still blockquoted) line.
    let content = "> [ref]: https://example.com\n>  \"the title\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title.as_deref(), Some("the title"));
}

#[test]
fn test_ref_def_paren_title_with_escaped_parens() {
    // CommonMark §4.7 paren-form titles may contain `(`/`)` only when
    // backslash-escaped. Both pulldown-cmark and the rumdl ref-def regex
    // unescape the captured title (per CommonMark §6.1) so downstream rules
    // see the same value regardless of which path produced it.
    let content = "[docs]: https://example.com (title \\(x\\))\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].url, "https://example.com");
    assert_eq!(
        ctx.reference_definitions()[0].title.as_deref(),
        Some("title (x)"),
        "title must be unescaped to match pulldown-cmark's parsed value"
    );
}

#[test]
fn test_mkdocs_admonition_link_with_paren_title() {
    // pulldown-cmark treats indented MkDocs admonition content as a code block,
    // so the inline link is recovered by the regex fallback in
    // `parse_links_images_pulldown`. The fallback must recognize all three
    // CommonMark §6.7 title delimiter forms — including `(...)` — otherwise
    // a link like `[doc](url (title))` is parsed with title=None and MD054
    // auto-fix silently strips the title when rewriting the link.
    let content = "!!! note\n    See [doc](https://example.com (paren title)) here.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    let link = ctx
        .links()
        .iter()
        .find(|l| l.url == "https://example.com")
        .expect("MkDocs fallback must surface the link");
    assert_eq!(
        link.title.as_deref(),
        Some("paren title"),
        "paren-form title must be captured by the MkDocs link fallback"
    );
}

#[test]
fn test_mkdocs_admonition_image_with_paren_title() {
    // Mirror of the link test for images.
    let content = "!!! note\n    See ![alt](https://example.com/x.png (paren title)) here.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    let img = ctx
        .images()
        .iter()
        .find(|i| i.url == "https://example.com/x.png")
        .expect("MkDocs fallback must surface the image");
    assert_eq!(
        img.title.as_deref(),
        Some("paren title"),
        "paren-form title must be captured by the MkDocs image fallback"
    );
}

#[test]
fn parsed_link_queries_preserve_document_order_and_half_open_ranges() {
    let content = "[one](a)\n![pic](b) and [two](c)\n\n[Docs]: ./guide.md\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(
        ctx.links_on_line(1)
            .iter()
            .map(|link| link.text.as_ref())
            .collect::<Vec<_>>(),
        ["one"]
    );
    assert_eq!(
        ctx.links_on_line(2)
            .iter()
            .map(|link| link.text.as_ref())
            .collect::<Vec<_>>(),
        ["two"]
    );
    assert!(ctx.links_on_line(3).is_empty());
    assert_eq!(
        ctx.images_on_line(2)
            .iter()
            .map(|image| image.alt_text.as_ref())
            .collect::<Vec<_>>(),
        ["pic"]
    );

    let first_link_start = content.find("[one]").unwrap();
    let second_link_start = content.find("[two]").unwrap();
    let image_start = content.find("![pic]").unwrap();

    let first_link = ctx.link_starting_at(first_link_start).unwrap();
    assert!(std::ptr::eq(ctx.link_containing(first_link_start).unwrap(), first_link));
    assert!(std::ptr::eq(
        ctx.link_containing(first_link.byte_end - 1).unwrap(),
        first_link
    ));
    assert!(ctx.link_containing(first_link.byte_end).is_none());
    assert_eq!(ctx.links_starting_before_or_at(second_link_start).len(), 2);

    let image = ctx.image_starting_at(image_start).unwrap();
    assert!(std::ptr::eq(ctx.image_containing(image_start).unwrap(), image));
    assert!(std::ptr::eq(ctx.image_containing(image.byte_end - 1).unwrap(), image));
    assert!(ctx.image_containing(image.byte_end).is_none());

    let definition = ctx.reference_definition("DOCS").unwrap();
    assert_eq!(definition.url, "./guide.md");
    assert_eq!(ctx.get_reference_url("docs"), Some("./guide.md"));
}

#[test]
fn parsed_links_remain_ordered_after_regex_fallbacks() {
    // Undefined reference links are appended after the pulldown-cmark pass.
    // Queries rely on the final collections being restored to document order.
    let content = "\
# Document

See [undefined-ref] for details.

Some text with [another-undef-ref] here.

Short text [link](https://example.com/a-very-long-destination).
";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(
        ctx.links()
            .windows(2)
            .all(|pair| { (pair[0].line, pair[0].byte_offset) <= (pair[1].line, pair[1].byte_offset) })
    );
    assert!(
        ctx.images()
            .windows(2)
            .all(|pair| { (pair[0].line, pair[0].byte_offset) <= (pair[1].line, pair[1].byte_offset) })
    );
}

#[test]
fn test_wiki_embed_has_no_alt_text() {
    // A wiki embed has no alt-text slot: `![[note]]` transcludes the target and
    // the pipe in `![[image.png|300]]` sets the rendered dimensions. Reading the
    // pipe portion as alt text made MD045 accept `![[a.png|300]]` and report
    // `![[a.png]]`, neither of which the author can act on.
    for (content, url) in [
        ("![[image.png]]\n", "image.png"),
        ("![[image.png|300]]\n", "image.png"),
        ("![[image.png|Some description]]\n", "image.png"),
        ("![[subfolder/image.png|640x480]]\n", "subfolder/image.png"),
    ] {
        for flavor in [MarkdownFlavor::Obsidian, MarkdownFlavor::Standard] {
            let ctx = LintContext::new(content, flavor, None);
            assert_eq!(ctx.images().len(), 1, "{flavor:?}: {content:?}");
            assert_eq!(ctx.images()[0].url, url, "{flavor:?}: {content:?}");
            assert_eq!(
                ctx.images()[0].alt_text,
                "",
                "{flavor:?}: {content:?} has no alt-text slot"
            );
        }
    }
}

/// The text of the first link in `content`, parsed with the standard flavor.
fn first_link_text(content: &str) -> String {
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    ctx.links()
        .first()
        .unwrap_or_else(|| panic!("the link must be parsed: {content:?}"))
        .text
        .to_string()
}

#[test]
fn test_label_holding_an_unmatched_backtick_reads_to_its_bracket() {
    // One backtick opens nothing, because no second run closes it. A scan that
    // toggles a code-span flag per backtick reads the rest of the link as code
    // and finds no bracket at all.
    let content = "[literal `](missing.md \"See ](./existing.md)\")\n";
    assert_eq!(first_link_text(content), "literal `");
}

#[test]
fn test_label_holding_inline_html_reads_to_its_bracket() {
    // The bracket inside the attribute is HTML, not the opener of a nested
    // label, so it must not raise the depth a bracket scan counts.
    let content = "[<i title=\"[\">text</i>](missing.md)\n";
    assert_eq!(first_link_text(content), "<i title=\"[\">text</i>");
}

#[test]
fn test_label_holding_a_two_backtick_code_span_reads_to_its_bracket() {
    // The code span holds a bracket and a paren of its own, and it wraps onto
    // another line. Neither ends the label.
    let content = "[``a\n](./exists.md)``](exists.md)\n";
    assert_eq!(first_link_text(content), "``a\n](./exists.md)``");
}

#[test]
fn test_label_holding_an_escaped_bracket_reads_to_its_bracket() {
    // An escaped bracket is text. The label ends at the next unescaped one, and
    // the text keeps the backslash as written.
    let content = "[a\\]b](url)\n";
    assert_eq!(first_link_text(content), "a\\]b");
}

#[test]
fn test_label_holding_a_nested_image_reads_to_its_bracket() {
    let content = "[![alt](x.png)](y.md)\n";
    assert_eq!(first_link_text(content), "![alt](x.png)");
}

#[test]
fn test_label_holding_a_collapsed_reference_image_reads_to_its_bracket() {
    // The parse's range for a collapsed image stops at the bracket closing its
    // description and leaves out the `[]` after it, so the label's own bracket
    // lies past where the image's events reach.
    let content = "[![alt][]](target1.md)\n\n[alt]: exists.png\n";
    assert_eq!(first_link_text(content), "![alt][]");
}

#[test]
fn test_label_holding_a_collapsed_reference_image_between_text_reads_to_its_bracket() {
    // A control for test_label_holding_a_collapsed_reference_image_reads_to_its_bracket:
    // the text after the image reaches past the image's own range, so the
    // label's end is found from that text and holds whatever the collapsed
    // image's range covers. A failure here is in the bracket scan rather than
    // in how far a collapsed image reaches.
    let content = "[before ![alt][] after](target4.md)\n\n[alt]: exists.png\n";
    assert_eq!(first_link_text(content), "before ![alt][] after");
}

#[test]
fn test_label_ending_in_whitespace_after_a_collapsed_reference_image_reads_to_its_bracket() {
    // A control for test_label_holding_a_collapsed_reference_image_reads_to_its_bracket:
    // the space after the image is text that reaches past the image's own
    // range, so the label's end is found from it and holds whatever the
    // collapsed image's range covers. A failure here is in the bracket scan
    // rather than in how far a collapsed image reaches.
    let content = "[![alt][] ](t.md)\n\n[alt]: exists.png\n";
    assert_eq!(first_link_text(content), "![alt][] ");
}

#[test]
fn test_reference_label_holding_a_collapsed_reference_image_reads_to_its_bracket() {
    let content = "[![alt][]][ref]\n\n[alt]: exists.png\n[ref]: target5.md\n";
    assert_eq!(first_link_text(content), "![alt][]");
}

#[test]
fn test_an_empty_label_reads_as_empty() {
    let content = "[](url)\n";
    assert_eq!(first_link_text(content), "");
}

#[test]
fn test_a_label_wrapping_onto_an_indented_line_keeps_the_break_and_the_indent() {
    // The text is the source between the brackets, so the newline and the
    // continuation line's indent are part of it.
    let content = "- [wrapped\n  text](./gone.md)\n";
    assert_eq!(first_link_text(content), "wrapped\n  text");
}

#[test]
fn test_a_label_ending_in_whitespace_reads_to_its_bracket() {
    // The inline events stop at the last content, so the trailing spaces on the
    // continuation line lie between the last event and the bracket.
    let content = "[   \n  ](url)\n";
    assert_eq!(first_link_text(content), "   \n  ");
}

#[test]
fn test_a_label_wrapping_inside_a_blockquote_keeps_the_marker() {
    // The continuation line's blockquote marker sits in the label's source span
    // and no event covers it.
    let content = "> [a\n>   ](url)\n";
    assert_eq!(first_link_text(content), "a\n>   ");
}

#[test]
fn test_wikilink_text_survives_a_nested_image() {
    // A wikilink is the only link whose text is the concatenation of its parse
    // events rather than the source between its brackets, so the nested image's
    // events must leave the text accumulated so far in place.
    let content = "[[Target|Display ![alt](x.png) more]]\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    let link = ctx
        .links()
        .iter()
        .find(|l| l.url == "Target")
        .expect("the wikilink must be parsed");
    assert_eq!(link.text, "Display alt more");
}

#[test]
fn test_ref_def_angle_bracket_destination_with_escaped_brackets() {
    // CommonMark §6.6 angle-bracket destinations admit `\<` and `\>` so the
    // round-trip from `format_url_destination` (which emits `<a\<b\>c>` when
    // a URL contains `<` or `>`) is recovered on the next parse instead of
    // silently dropping the def out of `ctx.reference_definitions()`.
    let content = "[id]: <a\\<b\\>c>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        ctx.reference_definitions().len(),
        1,
        "escaped angle-bracket destination must round-trip through the regex"
    );
    assert_eq!(ctx.reference_definitions()[0].id, "id");
    assert_eq!(ctx.reference_definitions()[0].title, None);
}

#[test]
fn test_ref_def_label_with_escaped_closing_bracket() {
    // CommonMark ends a link label at the first right bracket that is *not*
    // backslash-escaped, so `ref1\[\]` and `ref2\]` are single labels. A label
    // scan that stops at any `]` drops these definitions entirely, which makes
    // MD034 lint the destination as prose and hides them from MD053.
    //
    // The stored id keeps its backslashes: label normalization case-folds and
    // collapses whitespace but does not unescape, and pulldown-cmark reports
    // the raw id, so both sides must agree for reference matching to work.
    let content = "[ref1\\[\\]]: https://example.com/ref1\n[ref2\\]]: https://example.com/ref2\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let ids: Vec<&str> = ctx.reference_definitions().iter().map(|d| d.id.as_str()).collect();
    assert_eq!(
        ids,
        vec!["ref1\\[\\]", "ref2\\]"],
        "an escaped `]` must not terminate the label scan"
    );
    assert_eq!(ctx.reference_definitions()[0].url, "https://example.com/ref1");
    assert_eq!(ctx.reference_definitions()[1].url, "https://example.com/ref2");
}

#[test]
fn test_ref_def_double_quoted_title_with_escaped_quote() {
    // Title delimiter `"` may appear inside the title only when backslash-escaped;
    // `format_title` produces this form whenever the unescaped title contains `"`,
    // so the regex must accept it or the freshly generated def disappears from
    // the next pass and MD053/MD057/dedup all break. The captured title is
    // unescaped (CommonMark §6.1) so it matches pulldown-cmark's parsed value.
    let content = "[id]: https://example.com \"he said \\\"hi\\\"\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].url, "https://example.com");
    assert_eq!(
        ctx.reference_definitions()[0].title.as_deref(),
        Some("he said \"hi\""),
        "title must be unescaped to match pulldown-cmark's parsed value"
    );
}

#[test]
fn test_ref_def_single_quoted_title_with_escaped_quote() {
    let content = "[id]: https://example.com 'it\\'s fine'\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].url, "https://example.com");
    assert_eq!(
        ctx.reference_definitions()[0].title.as_deref(),
        Some("it's fine"),
        "title must be unescaped to match pulldown-cmark's parsed value"
    );
}

#[test]
fn test_ref_def_url_unescapes_backslash_escapes() {
    // CommonMark §6.1: a backslash before any ASCII punctuation character
    // produces the literal character; the backslash itself is removed. The
    // rumdl regex fallback must apply this transform so `ctx.reference_definitions()[i].url`
    // matches what pulldown-cmark exposes via `Tag::Link`/`Tag::Image`. Without
    // this, MD053/MD054/MD057 would see `https://e.com/path\(1\)` while the
    // parser sees `https://e.com/path(1)`, and any rule that copies the value
    // back into the document would corrupt it.
    let content = "[id]: https://e.com/path\\(1\\)\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(
        ctx.reference_definitions()[0].url,
        "https://e.com/path(1)",
        "URL must be unescaped per CommonMark §6.1"
    );
}

#[test]
fn test_ref_def_unescape_preserves_non_punctuation_backslash() {
    // CommonMark §6.1 explicitly limits the escape to ASCII punctuation. A
    // backslash followed by a letter, digit, or whitespace is preserved
    // verbatim (the backslash stays in the output). Verifying this guards
    // against an over-eager unescape that would silently drop backslashes
    // from URL paths and titles.
    let content = "[id]: https://e.com/p\\ath \"a\\b c\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(
        ctx.reference_definitions()[0].url,
        "https://e.com/p\\ath",
        "backslash before non-punctuation must remain in URL"
    );
    assert_eq!(
        ctx.reference_definitions()[0].title.as_deref(),
        Some("a\\b c"),
        "backslash before non-punctuation must remain in title"
    );
}

#[test]
fn test_footnote_definitions_not_parsed_as_reference_defs() {
    // Footnote definitions use [^id]: syntax and should NOT be parsed as reference definitions
    let content = r#"# Title

A footnote[^1].

[^1]: This is the footnote content.

[^note]: Another footnote with [link](https://example.com).

[regular]: ./path.md "A real reference definition"
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should only have one reference definition (the regular one)
    assert_eq!(
        ctx.reference_definitions().len(),
        1,
        "Footnotes should not be parsed as reference definitions"
    );

    // The only reference def should be the regular one
    assert_eq!(ctx.reference_definitions()[0].id, "regular");
    assert_eq!(ctx.reference_definitions()[0].url, "./path.md");
    assert_eq!(
        ctx.reference_definitions()[0].title,
        Some("A real reference definition".to_string())
    );
}

#[test]
fn test_footnote_with_inline_link_not_misidentified() {
    // Regression test for issue #286: footnote containing an inline link
    // was incorrectly parsed as a reference definition with URL "[link](url)"
    let content = r#"# Title

A footnote[^1].

[^1]: [link](https://www.google.com).
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should have no reference definitions
    assert!(
        ctx.reference_definitions().is_empty(),
        "Footnote with inline link should not create a reference definition"
    );
}

#[test]
fn test_various_footnote_formats_excluded() {
    // Test various footnote ID formats are all excluded
    let content = r#"[^1]: Numeric footnote
[^note]: Named footnote
[^a]: Single char footnote
[^long-footnote-name]: Long named footnote
[^123abc]: Mixed alphanumeric

[ref1]: ./file1.md
[ref2]: ./file2.md
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should only have the two regular reference definitions
    assert_eq!(
        ctx.reference_definitions().len(),
        2,
        "Only regular reference definitions should be parsed"
    );

    let ids: Vec<&str> = ctx.reference_definitions().iter().map(|r| r.id.as_str()).collect();
    assert!(ids.contains(&"ref1"));
    assert!(ids.contains(&"ref2"));
    assert!(!ids.iter().any(|id| id.starts_with('^')));
}

// =========================================================================
// Tests for has_char and char_count methods
// =========================================================================

#[test]
fn test_has_char_tracked_characters() {
    // Test all 12 tracked characters
    let content =
        "# Heading\n* list item\n_emphasis_ and -hyphen-\n+ plus\n> quote\n| table |\n[link]\n`code`\n<html>\n!image";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // All tracked characters should be detected
    assert!(ctx.has_char('#'), "Should detect hash");
    assert!(ctx.has_char('*'), "Should detect asterisk");
    assert!(ctx.has_char('_'), "Should detect underscore");
    assert!(ctx.has_char('-'), "Should detect hyphen");
    assert!(ctx.has_char('+'), "Should detect plus");
    assert!(ctx.has_char('>'), "Should detect gt");
    assert!(ctx.has_char('|'), "Should detect pipe");
    assert!(ctx.has_char('['), "Should detect bracket");
    assert!(ctx.has_char('`'), "Should detect backtick");
    assert!(ctx.has_char('<'), "Should detect lt");
    assert!(ctx.has_char('!'), "Should detect exclamation");
    assert!(ctx.has_char('\n'), "Should detect newline");
}

#[test]
fn test_has_char_absent_characters() {
    let content = "Simple text without special chars";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // None of the tracked characters should be present
    assert!(!ctx.has_char('#'), "Should not detect hash");
    assert!(!ctx.has_char('*'), "Should not detect asterisk");
    assert!(!ctx.has_char('_'), "Should not detect underscore");
    assert!(!ctx.has_char('-'), "Should not detect hyphen");
    assert!(!ctx.has_char('+'), "Should not detect plus");
    assert!(!ctx.has_char('>'), "Should not detect gt");
    assert!(!ctx.has_char('|'), "Should not detect pipe");
    assert!(!ctx.has_char('['), "Should not detect bracket");
    assert!(!ctx.has_char('`'), "Should not detect backtick");
    assert!(!ctx.has_char('<'), "Should not detect lt");
    assert!(!ctx.has_char('!'), "Should not detect exclamation");
    // Note: single line content has no newlines
    assert!(!ctx.has_char('\n'), "Should not detect newline in single line");
}

#[test]
fn test_has_char_fallback_for_untracked() {
    let content = "Text with @mention and $dollar and %percent";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Untracked characters should fall back to content.contains()
    assert!(ctx.has_char('@'), "Should detect @ via fallback");
    assert!(ctx.has_char('$'), "Should detect $ via fallback");
    assert!(ctx.has_char('%'), "Should detect % via fallback");
    assert!(!ctx.has_char('^'), "Should not detect absent ^ via fallback");
}

#[test]
fn test_char_count_tracked_characters() {
    let content =
        "## Heading ##\n***bold***\n__emphasis__\n---\n+++\n>> nested\n|| table ||\n[[link]]\n``code``\n<<html>>\n!!";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Count each tracked character
    assert_eq!(ctx.char_count('#'), 4, "Should count 4 hashes");
    assert_eq!(ctx.char_count('*'), 6, "Should count 6 asterisks");
    assert_eq!(ctx.char_count('_'), 4, "Should count 4 underscores");
    assert_eq!(ctx.char_count('-'), 3, "Should count 3 hyphens");
    assert_eq!(ctx.char_count('+'), 3, "Should count 3 pluses");
    assert_eq!(ctx.char_count('>'), 4, "Should count 4 gt (2 nested + 2 in <<html>>)");
    assert_eq!(ctx.char_count('|'), 4, "Should count 4 pipes");
    assert_eq!(ctx.char_count('['), 2, "Should count 2 brackets");
    assert_eq!(ctx.char_count('`'), 4, "Should count 4 backticks");
    assert_eq!(ctx.char_count('<'), 2, "Should count 2 lt");
    assert_eq!(ctx.char_count('!'), 2, "Should count 2 exclamations");
    assert_eq!(ctx.char_count('\n'), 10, "Should count 10 newlines");
}

#[test]
fn test_char_count_zero_for_absent() {
    let content = "Plain text";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.char_count('#'), 0);
    assert_eq!(ctx.char_count('*'), 0);
    assert_eq!(ctx.char_count('_'), 0);
    assert_eq!(ctx.char_count('\n'), 0);
}

#[test]
fn test_char_count_fallback_for_untracked() {
    let content = "@@@ $$ %%%";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.char_count('@'), 3, "Should count 3 @ via fallback");
    assert_eq!(ctx.char_count('$'), 2, "Should count 2 $ via fallback");
    assert_eq!(ctx.char_count('%'), 3, "Should count 3 % via fallback");
    assert_eq!(ctx.char_count('^'), 0, "Should count 0 for absent char");
}

#[test]
fn test_char_count_empty_content() {
    let ctx = LintContext::new("", MarkdownFlavor::Standard, None);

    assert_eq!(ctx.char_count('#'), 0);
    assert_eq!(ctx.char_count('*'), 0);
    assert_eq!(ctx.char_count('@'), 0);
    assert!(!ctx.has_char('#'));
    assert!(!ctx.has_char('@'));
}

// =========================================================================
// Tests for is_in_html_tag method
// =========================================================================

#[test]
fn test_is_in_html_tag_simple() {
    let content = "<div>content</div>";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Inside opening tag
    assert!(ctx.is_in_html_tag(0), "Position 0 (<) should be in tag");
    assert!(ctx.is_in_html_tag(1), "Position 1 (d) should be in tag");
    assert!(ctx.is_in_html_tag(4), "Position 4 (>) should be in tag");

    // Outside tag (in content)
    assert!(!ctx.is_in_html_tag(5), "Position 5 (c) should not be in tag");
    assert!(!ctx.is_in_html_tag(10), "Position 10 (t) should not be in tag");

    // Inside closing tag
    assert!(ctx.is_in_html_tag(12), "Position 12 (<) should be in tag");
    assert!(ctx.is_in_html_tag(17), "Position 17 (>) should be in tag");
}

#[test]
fn test_is_in_html_tag_self_closing() {
    let content = "Text <br/> more text";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Before tag
    assert!(!ctx.is_in_html_tag(0), "Position 0 should not be in tag");
    assert!(!ctx.is_in_html_tag(4), "Position 4 (space) should not be in tag");

    // Inside self-closing tag
    assert!(ctx.is_in_html_tag(5), "Position 5 (<) should be in tag");
    assert!(ctx.is_in_html_tag(8), "Position 8 (/) should be in tag");
    assert!(ctx.is_in_html_tag(9), "Position 9 (>) should be in tag");

    // After tag
    assert!(!ctx.is_in_html_tag(10), "Position 10 (space) should not be in tag");
}

#[test]
fn test_is_in_html_tag_with_attributes() {
    let content = r#"<a href="url" class="link">text</a>"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // All positions inside opening tag with attributes
    assert!(ctx.is_in_html_tag(0), "Start of tag");
    assert!(ctx.is_in_html_tag(10), "Inside href attribute");
    assert!(ctx.is_in_html_tag(20), "Inside class attribute");
    assert!(ctx.is_in_html_tag(26), "End of opening tag");

    // Content between tags
    assert!(!ctx.is_in_html_tag(27), "Start of content");
    assert!(!ctx.is_in_html_tag(30), "End of content");

    // Closing tag
    assert!(ctx.is_in_html_tag(31), "Start of closing tag");
}

#[test]
fn test_is_in_html_tag_multiline() {
    let content = "<div\n  class=\"test\"\n>\ncontent\n</div>";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Opening tag spans multiple lines
    assert!(ctx.is_in_html_tag(0), "Start of multiline tag");
    assert!(ctx.is_in_html_tag(5), "After first newline in tag");
    assert!(ctx.is_in_html_tag(15), "Inside attribute");

    // After closing > of opening tag
    let closing_bracket_pos = content.find(">\n").unwrap();
    assert!(!ctx.is_in_html_tag(closing_bracket_pos + 2), "Content after tag");
}

#[test]
fn test_is_in_html_tag_with_url_attributes() {
    // Tags with URLs in attributes contain '/' which must not be treated as self-closing
    let content = r#"<input name="fields[url]" value="https://www.example.com">"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let tags = ctx.html_tags();

    assert_eq!(tags.len(), 1, "Should detect one HTML tag");
    assert_eq!(tags[0].tag_name, "input");
    assert!(!tags[0].is_self_closing);
    assert!(ctx.is_in_html_tag(35), "URL position should be inside HTML tag");
}

#[test]
fn test_is_in_html_tag_self_closing_with_slash() {
    let content = "<br />";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let tags = ctx.html_tags();

    assert_eq!(tags.len(), 1);
    assert_eq!(tags[0].tag_name, "br");
    assert!(tags[0].is_self_closing);
}

#[test]
fn test_html_tags_respect_backslash_escaped_openers() {
    // CommonMark §6.1: an odd number of backslashes escapes the `<`, while an
    // even number escapes in pairs and leaves it active as markup.
    for content in [r"\<x-keyboard>", r"\\\<x-keyboard>"] {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        assert!(ctx.html_tags().is_empty(), "escaped opener in {content:?}");
    }

    for content in [r"<x-keyboard>", r"\\<x-keyboard>", r"\\\\<x-keyboard>"] {
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let tags = ctx.html_tags();
        assert_eq!(tags.len(), 1, "active opener in {content:?}");
        assert_eq!(tags[0].tag_name, "x-keyboard");
    }
}

#[test]
fn test_is_in_html_tag_nested_angle_brackets() {
    // Hugo shortcodes: <a href="{{< ref ... >}}"> contain nested '<'
    let content = r#"<a href="{{< ref "../common-parameters" >}}">"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let tags = ctx.html_tags();

    // The regex handles nested '<' by matching the shortest valid tag
    assert!(!tags.is_empty(), "Should detect at least one tag fragment");
}

#[test]
fn test_html_tag_window_ends_inside_multibyte_char() {
    // Issue #757: an unterminated HTML-like tag (`<a...` with no closing `>`) whose
    // 4096-byte search window ends inside a multi-byte UTF-8 character must not panic.
    // `<a` (2 bytes) + 4093 * 'a' (4093 bytes) puts byte 4096 inside the following
    // 'çš„' (bytes 4095..4098), which previously panicked when slicing the window.
    let content = format!("<a{}çš„", "a".repeat(4093));
    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);
    let _ = ctx.html_tags(); // must not panic

    // A closing '>' beyond the window boundary, still landing inside a multi-byte char.
    let content2 = format!("<a {}çš„>", "b".repeat(5000));
    let ctx2 = LintContext::new(&content2, MarkdownFlavor::Standard, None);
    let _ = ctx2.html_tags(); // must not panic
}

#[test]
fn test_is_in_html_tag_no_tags() {
    let content = "Plain text without any HTML";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // No position should be in an HTML tag
    for i in 0..content.len() {
        assert!(!ctx.is_in_html_tag(i), "Position {i} should not be in tag");
    }
}

// =========================================================================
// Tests for is_in_jinja_range method
// =========================================================================

#[test]
fn test_is_in_jinja_range_expression() {
    let content = "Hello {{ name }}!";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Before Jinja
    assert!(!ctx.is_in_jinja_range(0), "H should not be in Jinja");
    assert!(!ctx.is_in_jinja_range(5), "Space before Jinja should not be in Jinja");

    // Inside Jinja expression (positions 6-15 for "{{ name }}")
    assert!(ctx.is_in_jinja_range(6), "First brace should be in Jinja");
    assert!(ctx.is_in_jinja_range(7), "Second brace should be in Jinja");
    assert!(ctx.is_in_jinja_range(10), "name should be in Jinja");
    assert!(ctx.is_in_jinja_range(14), "Closing brace should be in Jinja");
    assert!(ctx.is_in_jinja_range(15), "Second closing brace should be in Jinja");

    // After Jinja
    assert!(!ctx.is_in_jinja_range(16), "! should not be in Jinja");
}

#[test]
fn test_is_in_jinja_range_statement() {
    let content = "{% if condition %}content{% endif %}";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Inside opening statement
    assert!(ctx.is_in_jinja_range(0), "Start of Jinja statement");
    assert!(ctx.is_in_jinja_range(5), "condition should be in Jinja");
    assert!(ctx.is_in_jinja_range(17), "End of opening statement");

    // Content between
    assert!(!ctx.is_in_jinja_range(18), "content should not be in Jinja");

    // Inside closing statement
    assert!(ctx.is_in_jinja_range(25), "Start of endif");
    assert!(ctx.is_in_jinja_range(32), "endif should be in Jinja");
}

#[test]
fn test_is_in_jinja_range_multiple() {
    let content = "{{ a }} and {{ b }}";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // First Jinja expression
    assert!(ctx.is_in_jinja_range(0));
    assert!(ctx.is_in_jinja_range(3));
    assert!(ctx.is_in_jinja_range(6));

    // Between expressions
    assert!(!ctx.is_in_jinja_range(8));
    assert!(!ctx.is_in_jinja_range(11));

    // Second Jinja expression
    assert!(ctx.is_in_jinja_range(12));
    assert!(ctx.is_in_jinja_range(15));
    assert!(ctx.is_in_jinja_range(18));
}

#[test]
fn test_is_in_jinja_range_no_jinja() {
    let content = "Plain text with single braces but not Jinja";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // No position should be in Jinja
    for i in 0..content.len() {
        assert!(!ctx.is_in_jinja_range(i), "Position {i} should not be in Jinja");
    }
}

// =========================================================================
// Tests for is_in_link_title method
// =========================================================================

#[test]
fn test_is_in_link_title_with_title() {
    let content = r#"[ref]: https://example.com "Title text"

Some content."#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Verify we have a reference def with title
    assert_eq!(ctx.reference_definitions().len(), 1);
    let def = &ctx.reference_definitions()[0];
    assert!(def.title_byte_start.is_some());
    assert!(def.title_byte_end.is_some());

    let title_start = def.title_byte_start.unwrap();
    let title_end = def.title_byte_end.unwrap();

    // Before title (in URL)
    assert!(!ctx.is_in_link_title(10), "URL should not be in title");

    // Inside title
    assert!(ctx.is_in_link_title(title_start), "Title start should be in title");
    assert!(
        ctx.is_in_link_title(title_start + 5),
        "Middle of title should be in title"
    );
    assert!(ctx.is_in_link_title(title_end - 1), "End of title should be in title");

    // After title
    assert!(
        !ctx.is_in_link_title(title_end),
        "After title end should not be in title"
    );
}

#[test]
fn test_is_in_link_title_without_title() {
    let content = "[ref]: https://example.com\n\nSome content.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Reference def without title
    assert_eq!(ctx.reference_definitions().len(), 1);
    let def = &ctx.reference_definitions()[0];
    assert!(def.title_byte_start.is_none());
    assert!(def.title_byte_end.is_none());

    // No position should be in a title
    for i in 0..content.len() {
        assert!(!ctx.is_in_link_title(i), "Position {i} should not be in title");
    }
}

#[test]
fn test_is_in_link_title_multiple_refs() {
    let content = r#"[ref1]: /url1 "Title One"
[ref2]: /url2
[ref3]: /url3 "Title Three"
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should have 3 reference defs
    assert_eq!(ctx.reference_definitions().len(), 3);

    // ref1 has title
    let ref1 = ctx.reference_definitions().iter().find(|r| r.id == "ref1").unwrap();
    assert!(ref1.title_byte_start.is_some());

    // ref2 has no title
    let ref2 = ctx.reference_definitions().iter().find(|r| r.id == "ref2").unwrap();
    assert!(ref2.title_byte_start.is_none());

    // ref3 has title
    let ref3 = ctx.reference_definitions().iter().find(|r| r.id == "ref3").unwrap();
    assert!(ref3.title_byte_start.is_some());

    // Check positions in ref1's title
    if let (Some(start), Some(end)) = (ref1.title_byte_start, ref1.title_byte_end) {
        assert!(ctx.is_in_link_title(start + 1));
        assert!(!ctx.is_in_link_title(end + 5));
    }

    // Check positions in ref3's title
    if let (Some(start), Some(_end)) = (ref3.title_byte_start, ref3.title_byte_end) {
        assert!(ctx.is_in_link_title(start + 1));
    }
}

#[test]
fn test_is_in_link_title_single_quotes() {
    let content = "[ref]: /url 'Single quoted title'\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.reference_definitions().len(), 1);
    let def = &ctx.reference_definitions()[0];

    if let (Some(start), Some(end)) = (def.title_byte_start, def.title_byte_end) {
        assert!(ctx.is_in_link_title(start));
        assert!(ctx.is_in_link_title(start + 5));
        assert!(!ctx.is_in_link_title(end));
    }
}

#[test]
fn test_is_in_link_title_parentheses() {
    // Note: The reference def parser may not support parenthesized titles
    // This test verifies the is_in_link_title method works when titles exist
    let content = "[ref]: /url (Parenthesized title)\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Parser behavior: may or may not parse parenthesized titles
    // We test that is_in_link_title correctly reflects whatever was parsed
    if ctx.reference_definitions().is_empty() {
        // Parser didn't recognize this as a reference def
        for i in 0..content.len() {
            assert!(!ctx.is_in_link_title(i));
        }
    } else {
        let def = &ctx.reference_definitions()[0];
        if let (Some(start), Some(end)) = (def.title_byte_start, def.title_byte_end) {
            assert!(ctx.is_in_link_title(start));
            assert!(ctx.is_in_link_title(start + 5));
            assert!(!ctx.is_in_link_title(end));
        } else {
            // Title wasn't parsed, so no position should be in title
            for i in 0..content.len() {
                assert!(!ctx.is_in_link_title(i));
            }
        }
    }
}

#[test]
fn test_is_in_link_title_no_refs() {
    let content = "Just plain text without any reference definitions.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.reference_definitions().is_empty());

    for i in 0..content.len() {
        assert!(!ctx.is_in_link_title(i));
    }
}

// =========================================================================
// Math span tests (Issue #289)
// =========================================================================

#[test]
fn test_math_spans_inline() {
    let content = "Text with inline math $[f](x)$ in it.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1, "Should detect one inline math span");

    let span = &math_spans[0];
    assert!(!span.is_display, "Should be inline math, not display");
    assert_eq!(span.content, "[f](x)", "Content should be extracted correctly");
}

#[test]
fn test_math_spans_display_single_line() {
    let content = "$$X(\\zeta) = \\mathcal Z [x](\\zeta)$$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1, "Should detect one display math span");

    let span = &math_spans[0];
    assert!(span.is_display, "Should be display math");
    assert!(
        span.content.contains("[x](\\zeta)"),
        "Content should contain the link-like pattern"
    );
}

#[test]
fn test_math_spans_display_multiline() {
    let content = "Before\n\n$$\n[x](\\zeta) = \\sum_k x(k)\n$$\n\nAfter";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1, "Should detect one display math span");

    let span = &math_spans[0];
    assert!(span.is_display, "Should be display math");
}

#[test]
fn test_is_in_math_span() {
    let content = "Text $[f](x)$ more text";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Position inside the math span
    let math_start = content.find('$').unwrap();
    let math_end = content.rfind('$').unwrap() + 1;

    assert!(
        ctx.is_in_math_span(math_start + 1),
        "Position inside math span should return true"
    );
    assert!(
        ctx.is_in_math_span(math_start + 3),
        "Position inside math span should return true"
    );

    // Position outside the math span
    assert!(!ctx.is_in_math_span(0), "Position before math span should return false");
    assert!(
        !ctx.is_in_math_span(math_end + 1),
        "Position after math span should return false"
    );
}

#[test]
fn test_math_spans_mixed_with_code() {
    let content = "Math $[f](x)$ and code `[g](y)` mixed";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    let code_spans = ctx.code_spans();

    assert_eq!(math_spans.len(), 1, "Should have one math span");
    assert_eq!(code_spans.len(), 1, "Should have one code span");

    // Verify math span content
    assert_eq!(math_spans[0].content, "[f](x)");
    // Verify code span content
    assert_eq!(code_spans[0].content, "[g](y)");
}

#[test]
fn test_math_spans_no_math() {
    let content = "Regular text without any math at all.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert!(math_spans.is_empty(), "Should have no math spans");
}

#[test]
fn test_math_spans_multiple() {
    let content = "First $a$ and second $b$ and display $$c$$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 3, "Should detect three math spans");

    // Two inline, one display
    let inline_count = math_spans.iter().filter(|s| !s.is_display).count();
    let display_count = math_spans.iter().filter(|s| s.is_display).count();

    assert_eq!(inline_count, 2, "Should have two inline math spans");
    assert_eq!(display_count, 1, "Should have one display math span");
}

#[test]
fn test_is_in_math_span_boundary_positions() {
    // Test exact boundary positions: $[f](x)$
    // Byte positions:                0123456789
    let content = "$[f](x)$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1, "Should have one math span");

    let span = &math_spans[0];

    // Position at opening $ should be in span (byte 0)
    assert!(
        ctx.is_in_math_span(span.byte_offset),
        "Start position should be in span"
    );

    // Position just inside should be in span
    assert!(
        ctx.is_in_math_span(span.byte_offset + 1),
        "Position after start should be in span"
    );

    // Position at closing $ should be in span (exclusive end means we check byte_end - 1)
    assert!(
        ctx.is_in_math_span(span.byte_end - 1),
        "Position at end-1 should be in span"
    );

    // Position at byte_end should NOT be in span (exclusive end)
    assert!(
        !ctx.is_in_math_span(span.byte_end),
        "Position at byte_end should NOT be in span (exclusive)"
    );
}

#[test]
fn test_math_spans_at_document_start() {
    let content = "$x$ text";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1);
    assert_eq!(math_spans[0].byte_offset, 0, "Math should start at byte 0");
}

#[test]
fn test_math_spans_at_document_end() {
    let content = "text $x$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    assert_eq!(math_spans.len(), 1);
    assert_eq!(math_spans[0].byte_end, content.len(), "Math should end at document end");
}

#[test]
fn test_math_spans_consecutive() {
    let content = "$a$$b$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    // pulldown-cmark should parse these as separate spans
    assert!(!math_spans.is_empty(), "Should detect at least one math span");

    // All positions should be in some math span
    for i in 0..content.len() {
        assert!(ctx.is_in_math_span(i), "Position {i} should be in a math span");
    }
}

#[test]
fn test_math_spans_currency_not_math() {
    // Unbalanced $ should not create math spans
    let content = "Price is $100";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let math_spans = ctx.math_spans();
    // pulldown-cmark requires balanced delimiters for math
    // $100 alone is not math
    assert!(
        math_spans.is_empty() || !math_spans.iter().any(|s| s.content.contains("100")),
        "Unbalanced $ should not create math span containing 100"
    );
}

// =========================================================================
// Tests for O(1) reference definition lookups via HashMap
// =========================================================================

#[test]
fn test_reference_lookup_o1_basic() {
    let content = r#"[ref1]: /url1
[REF2]: /url2 "Title"
[Ref3]: /url3

Use [link][ref1] and [link][REF2]."#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Verify we have 3 reference defs
    assert_eq!(ctx.reference_definitions().len(), 3);

    // Test get_reference_url with various cases
    assert_eq!(ctx.get_reference_url("ref1"), Some("/url1"));
    assert_eq!(ctx.get_reference_url("REF1"), Some("/url1")); // case insensitive
    assert_eq!(ctx.get_reference_url("Ref1"), Some("/url1")); // case insensitive
    assert_eq!(ctx.get_reference_url("ref2"), Some("/url2"));
    assert_eq!(ctx.get_reference_url("REF2"), Some("/url2"));
    assert_eq!(ctx.get_reference_url("ref3"), Some("/url3"));
    assert_eq!(ctx.get_reference_url("nonexistent"), None);
}

#[test]
fn test_reference_lookup_o1_empty_content() {
    let content = "No references here.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.reference_definitions().is_empty());
    assert_eq!(ctx.get_reference_url("anything"), None);
}

#[test]
fn test_reference_lookup_o1_special_characters_in_id() {
    let content = r#"[ref-with-dash]: /url1
[ref_with_underscore]: /url2
[ref.with.dots]: /url3
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.get_reference_url("ref-with-dash"), Some("/url1"));
    assert_eq!(ctx.get_reference_url("ref_with_underscore"), Some("/url2"));
    assert_eq!(ctx.get_reference_url("ref.with.dots"), Some("/url3"));
}

#[test]
fn test_reference_lookup_o1_unicode_id() {
    let content = r#"[日本語]: /japanese
[émoji]: /emoji
"#;
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(ctx.get_reference_url("日本語"), Some("/japanese"));
    assert_eq!(ctx.get_reference_url("émoji"), Some("/emoji"));
    assert_eq!(ctx.get_reference_url("ÉMOJI"), Some("/emoji")); // uppercase
}

#[test]
fn test_is_in_link_title_multiple_ranges_binary_search() {
    // Three reference defs with titles — verifies binary search works across all three
    let content = "[a]: /url1 \"Title A\"\n[b]: /url2 \"Title B\"\n[c]: /url3 \"Title C\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 3, "Should have 3 reference defs");

    // Position inside first title should return true
    if let (Some(start), Some(end)) = (
        ctx.reference_definitions()[0].title_byte_start,
        ctx.reference_definitions()[0].title_byte_end,
    ) {
        assert!(ctx.is_in_link_title(start + 1), "Inside first title should return true");
        // Position at exclusive end should return false
        assert!(!ctx.is_in_link_title(end), "At exclusive end should return false");
    }

    // Position between titles (in URL area of def B, before its title) should return false
    if let (Some(end_a), Some(start_b)) = (
        ctx.reference_definitions()[0].title_byte_end,
        ctx.reference_definitions()[1].title_byte_start,
    ) && end_a + 1 < start_b
    {
        assert!(!ctx.is_in_link_title(end_a + 1), "Between titles should return false");
    }

    // Position inside third title should return true
    if let Some(start) = ctx.reference_definitions()[2].title_byte_start {
        assert!(ctx.is_in_link_title(start + 1), "Inside third title should return true");
    }
}

#[test]
fn test_is_in_math_span_between_two_spans() {
    // Position in text between two math spans should return false
    let content = "$a$ text $b$";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let math_spans = ctx.math_spans();
    if math_spans.len() >= 2 {
        let between = math_spans[0].byte_end + 1;
        assert!(
            !ctx.is_in_math_span(between),
            "Position between math spans should return false"
        );
    }
}

// =========================================================================
// Tests for code span and HTML tag detection at boundaries
// =========================================================================

#[test]
fn test_code_span_at_line_start() {
    let content = "Line one\n`code` end\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let spans = ctx.code_spans();
    let line2_spans: Vec<_> = spans.iter().filter(|s| s.line == 2).collect();
    assert!(!line2_spans.is_empty(), "Should detect code span on line 2");
    assert_eq!(line2_spans[0].start_col, 0, "Code span should start at column 0");
}

#[test]
fn test_html_tag_at_byte_zero() {
    let content = "<br/> text";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let tags = ctx.html_tags();
    assert!(!tags.is_empty(), "Should detect HTML tag at byte 0");
    assert_eq!(tags[0].line, 1, "Tag at byte 0 should be on line 1");
}

// =========================================================================
// HTML block detection: CommonMark Type-1 blank-line handling
// =========================================================================
//
// Per CommonMark §4.6, Type-1 HTML blocks open with <pre, <script, <style,
// or <textarea and run until the matching end tag (or EOF). Blank lines do
// not terminate these blocks. Type 6/7 blocks (e.g. <div>, <p>) terminate
// at the first blank line.

#[test]
fn test_html_block_pre_with_blank_line_marks_all_inner_lines() {
    // Reproduces issue #578: a <pre> containing a blank line.
    let content = "# Heading\n\n<pre>\n\nhello  world\n</pre>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.is_in_html_block(3), "line 3 (`<pre>`) should be in html block");
    assert!(
        ctx.is_in_html_block(4),
        "line 4 (blank inside pre) should be in html block"
    );
    assert!(
        ctx.is_in_html_block(5),
        "line 5 (`hello  world`) should be in html block"
    );
    assert!(ctx.is_in_html_block(6), "line 6 (`</pre>`) should be in html block");
}

#[test]
fn test_html_block_textarea_with_blank_line_marks_all_inner_lines() {
    let content = "<textarea>\n\ninner  content\n</textarea>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.is_in_html_block(1), "line 1 (`<textarea>`) should be in html block");
    assert!(ctx.is_in_html_block(2), "line 2 (blank) should be in html block");
    assert!(
        ctx.is_in_html_block(3),
        "line 3 (inner content) should be in html block"
    );
    assert!(
        ctx.is_in_html_block(4),
        "line 4 (`</textarea>`) should be in html block"
    );
}

#[test]
fn test_html_block_long_pre_exceeds_arbitrary_line_cap() {
    // A <pre> with 120 inner lines (no blanks) must mark every inner line,
    // regardless of any internal line cap.
    let mut content = String::from("<pre>\n");
    for i in 0..120 {
        content.push_str(&format!("inner line {i}\n"));
    }
    content.push_str("</pre>\n");

    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);

    // 1-indexed: line 1 = <pre>, lines 2..=121 = inner, line 122 = </pre>.
    for line_num in 1..=122 {
        assert!(
            ctx.is_in_html_block(line_num),
            "line {line_num} of a 122-line <pre> block should be marked in_html_block",
        );
    }
}

#[test]
fn test_html_block_div_still_terminates_on_blank_line() {
    // Type-6 guardrail: <div> is not Type-1 and must terminate at blank line.
    let content = "<div>\ninner\n\nafter blank\n</div>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.is_in_html_block(1), "line 1 (`<div>`) should be in html block");
    assert!(ctx.is_in_html_block(2), "line 2 (inner) should be in html block");
    assert!(
        !ctx.is_in_html_block(4),
        "line 4 (`after blank`) must NOT be in html block"
    );
}

#[test]
fn test_html_block_unclosed_pre_extends_to_eof() {
    // Per CommonMark, an unclosed Type-1 block extends to end of document.
    let content = "<pre>\nline a\n\nline b\nline c\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    for line_num in 1..=5 {
        assert!(
            ctx.is_in_html_block(line_num),
            "line {line_num} of an unclosed <pre> should extend to EOF",
        );
    }
}

#[test]
fn test_html_block_nested_pre_with_split_closing_tag_ends_with_outer_block() {
    // Prettier wraps a long closing tag as `</pre\n>`, which no single-line
    // search for `</pre>` can match. Inside an already-open <table> block that
    // must not matter: the <pre> is block content, not a second block, so the
    // whole thing ends at the blank line that ends the <table>.
    let content = "<table>\n<tr><td>\n<pre>\nx</pre\n>\n</td></tr>\n</table>\n\nafter\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(
        ctx.is_in_html_block(3),
        "line 3 (`<pre>`) is content of the <table> block"
    );
    assert!(ctx.is_in_html_block(7), "line 7 (`</table>`) is still in the block");
    assert!(
        !ctx.is_in_html_block(9),
        "line 9 (`after`) must be ordinary markdown: the <table> block ended at the blank line"
    );
}

#[test]
fn test_html_block_top_level_pre_with_split_closing_tag_still_extends_to_eof() {
    // Guardrail for the case above. A Type-1 block that is NOT nested has
    // nothing else to close it, so CommonMark really does run it to EOF when
    // the end tag is split across lines. Narrowing that would be a regression.
    let content = "<pre>\nx</pre\n>\n\nafter\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    for line_num in 1..=5 {
        assert!(
            ctx.is_in_html_block(line_num),
            "line {line_num} of a top-level <pre> with a split end tag should reach EOF",
        );
    }
}

#[test]
fn test_html_block_nested_pre_does_not_outlive_a_type_6_parent() {
    // The same shape without a split tag: a <div> ends at its blank line even
    // though the <pre> it contains was never closed at all.
    let content = "<div>\n<pre>\nx\n</div>\n\nafter\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(
        ctx.is_in_html_block(2),
        "line 2 (`<pre>`) is content of the <div> block"
    );
    assert!(
        !ctx.is_in_html_block(6),
        "line 6 (`after`) must be ordinary markdown: the <div> block ended at the blank line"
    );
}

// ---------------------------------------------------------------------------
// Pulldown-cmark gives the same empty CowStr for both "no title" and "explicit
// empty title" (`""`/`''`/`()`). The link parser now rescans the source span
// to recover the distinction so MD054's auto-fix can't silently drop the
// delimiters when converting `[t](url "")` to autolink.
// ---------------------------------------------------------------------------

#[test]
fn test_link_no_title_yields_none() {
    let ctx = LintContext::new("[t](https://x.com)\n", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert!(ctx.links()[0].title.is_none(), "no title delimiter must be None");
}

#[test]
fn test_link_explicit_empty_double_quote_title_yields_some_empty() {
    let ctx = LintContext::new(r#"[t](https://x.com "")"#, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert_eq!(
        ctx.links()[0].title.as_deref(),
        Some(""),
        "`\"\"` must be preserved as Some(\"\"), not collapsed to None"
    );
}

#[test]
fn test_link_explicit_empty_single_quote_title_yields_some_empty() {
    let ctx = LintContext::new("[t](https://x.com '')\n", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert_eq!(ctx.links()[0].title.as_deref(), Some(""));
}

#[test]
fn test_link_explicit_empty_paren_title_yields_some_empty() {
    let ctx = LintContext::new("[t](https://x.com ())\n", MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert_eq!(ctx.links()[0].title.as_deref(), Some(""));
}

#[test]
fn test_image_explicit_empty_title_yields_some_empty() {
    let ctx = LintContext::new(r#"![alt](https://x.com/img.png "")"#, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.images().len(), 1);
    assert_eq!(ctx.images()[0].title.as_deref(), Some(""));
}

#[test]
fn test_link_non_empty_title_is_unaffected() {
    let ctx = LintContext::new(r#"[t](https://x.com "real")"#, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert_eq!(ctx.links()[0].title.as_deref(), Some("real"));
}

#[test]
fn test_link_title_with_trailing_whitespace_inside_parens() {
    // CommonMark allows whitespace between the closing title delimiter and
    // the link's closing `)`. The detector must skip that whitespace so it
    // still recognizes the explicit-empty-title pair.
    let ctx = LintContext::new(r#"[t](https://x.com ""    )"#, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1);
    assert_eq!(ctx.links()[0].title.as_deref(), Some(""));
}

#[test]
fn test_reference_link_empty_title_in_definition() {
    // Reference links carry their title in the *definition*, parsed by the
    // REF_DEF_PATTERN regex (which already distinguishes `Some("")` from
    // `None` via `cap.get(...)`); make sure that path keeps working.
    let content = "[t][r]\n\n[r]: https://x.com \"\"\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.reference_definitions().len(), 1);
    assert_eq!(ctx.reference_definitions()[0].title.as_deref(), Some(""));
}

// ---------------------------------------------------------------------------
// Markdown inside an HTML block is not markdown: CommonMark renders it as
// literal text. Pulldown-cmark reports no links there, but the regex fallback
// used to re-add reference links (and reference images) while dropping inline
// ones, so the same construct was visible or invisible depending on which
// syntax the author picked.
// ---------------------------------------------------------------------------

#[test]
fn test_reference_link_in_an_html_block_is_not_parsed() {
    let content = "<details>\n<summary>[link][ref]</summary>\n</details>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(
        ctx.links().is_empty(),
        "a reference link inside an HTML block renders literally, so it is not a link: {:?}",
        ctx.links()
    );
}

#[test]
fn test_inline_link_in_an_html_block_is_not_parsed() {
    // The matched control for the test above: same position, same rendering,
    // and this half was already correct.
    let content = "<details>\n<summary>[link](https://example.com)</summary>\n</details>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(ctx.links().is_empty(), "unexpected links: {:?}", ctx.links());
}

#[test]
fn test_reference_image_in_an_html_block_is_not_parsed() {
    let content = "<details>\n<summary>![alt][img]</summary>\n</details>\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(
        ctx.images().is_empty(),
        "a reference image inside an HTML block renders literally: {:?}",
        ctx.images()
    );
}

#[test]
fn test_reference_link_in_a_markdown_attribute_block_is_still_parsed() {
    // The `markdown` attribute is what MkDocs, kramdown and Jekyll use to say
    // the body IS markdown. Those lines carry `in_html_block` as well, so
    // suppressing on that flag alone would take real links with it.
    let content = "<div class=\"note\" markdown=\"1\">\n[link][ref]\n</div>\n\n[ref]: https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        ctx.links().len(),
        1,
        "the body of a markdown=\"1\" block holds real markdown: {:?}",
        ctx.links()
    );
    assert_eq!(ctx.links()[0].line, 2);
    assert!(ctx.links()[0].is_reference);
}

#[test]
fn test_reference_image_in_a_markdown_attribute_block_is_still_parsed() {
    let content = "<div class=\"note\" markdown=\"1\">\n![alt][img]\n</div>\n\n[img]: https://example.com/i.png\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        ctx.images().len(),
        1,
        "the body of a markdown=\"1\" block holds real markdown: {:?}",
        ctx.images()
    );
    assert_eq!(ctx.images()[0].line, 2);
}

#[test]
fn test_reference_link_after_an_html_block_is_still_parsed() {
    // The suppression is per line, not "everything below the first tag".
    let content = "<details>\n<summary>[dead][ref]</summary>\n</details>\n\n[live][ref]\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.links().len(), 1, "unexpected links: {:?}", ctx.links());
    assert_eq!(ctx.links()[0].text, "live");
}

#[test]
fn test_pandoc_flavor_detects_div_blocks() {
    let content = "::: {.callout-note}\nA note.\n:::\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    assert!(
        ctx.is_in_div_block(content.find(":::").unwrap()),
        "Pandoc flavor should detect div block ranges"
    );
}

#[test]
fn test_pandoc_flavor_detects_citations() {
    let content = "See [@smith2020] for details.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("[@smith2020]").unwrap() + 1;
    assert!(ctx.is_in_citation(pos), "Pandoc flavor should detect citation ranges");
}

#[test]
fn test_pandoc_flavor_detects_inline_footnotes() {
    let content = "Text ^[note here] more.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("^[").unwrap() + 1;
    assert!(
        ctx.is_in_inline_footnote(pos),
        "Pandoc flavor should detect inline footnote ranges"
    );
}

#[test]
fn test_standard_flavor_skips_inline_footnotes() {
    let content = "Text ^[note here] more.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("^[").unwrap() + 1;
    assert!(
        !ctx.is_in_inline_footnote(pos),
        "Standard flavor should not detect inline footnote ranges"
    );
}

#[test]
fn test_pandoc_flavor_resolves_implicit_header_reference() {
    let content = "# My Section\n\nSee [My Section] for details.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    assert!(ctx.matches_implicit_header_reference("My Section"));
    assert!(!ctx.matches_implicit_header_reference("Nonexistent"));
}

#[test]
fn test_standard_flavor_does_not_resolve_implicit_header_reference() {
    let content = "# My Section\n\nSee [My Section] for details.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(!ctx.matches_implicit_header_reference("My Section"));
}

#[test]
fn test_pandoc_flavor_detects_example_list_markers() {
    use crate::config::MarkdownFlavor;
    let content = "(@) First item.\n(@good) Second item.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("(@)").unwrap();
    assert!(ctx.is_in_example_list_marker(pos));
    let pos2 = content.find("(@good)").unwrap();
    assert!(ctx.is_in_example_list_marker(pos2));
}

#[test]
fn test_pandoc_flavor_detects_example_references() {
    use crate::config::MarkdownFlavor;
    let content = "(@good) First.\n\nAs shown in (@good), it works.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let ref_pos = content.rfind("(@good)").unwrap();
    assert!(ctx.is_in_example_reference(ref_pos));
    // The line-start marker is NOT a reference (filtered out).
    let marker_pos = content.find("(@good)").unwrap();
    assert!(!ctx.is_in_example_reference(marker_pos));
}

#[test]
fn test_standard_flavor_skips_example_lists() {
    use crate::config::MarkdownFlavor;
    let content = "(@) First.\nAs shown in (@good), it works.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("(@)").unwrap();
    assert!(!ctx.is_in_example_list_marker(pos));
    let ref_pos = content.find("(@good)").unwrap();
    assert!(!ctx.is_in_example_reference(ref_pos));
}

#[test]
fn test_pandoc_flavor_detects_subscript() {
    use crate::config::MarkdownFlavor;
    let content = "H~2~O is water.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("~2~").unwrap() + 1;
    assert!(ctx.is_in_subscript_or_superscript(pos));
}

#[test]
fn test_pandoc_flavor_detects_superscript() {
    use crate::config::MarkdownFlavor;
    let content = "2^10^ is 1024.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("^10^").unwrap() + 1;
    assert!(ctx.is_in_subscript_or_superscript(pos));
}

#[test]
fn test_pandoc_flavor_does_not_match_strikethrough() {
    use crate::config::MarkdownFlavor;
    let content = "This is ~~struck~~.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("~~struck~~").unwrap() + 2;
    assert!(!ctx.is_in_subscript_or_superscript(pos));
}

#[test]
fn test_standard_flavor_skips_sub_super() {
    use crate::config::MarkdownFlavor;
    let content = "H~2~O and 2^10^.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("~2~").unwrap() + 1;
    assert!(!ctx.is_in_subscript_or_superscript(pos));
}

#[test]
fn test_pandoc_flavor_detects_inline_code_attribute() {
    use crate::config::MarkdownFlavor;
    let content = "Use `print()`{.python} for output.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("{.python}").unwrap() + 1;
    assert!(ctx.is_in_inline_code_attr(pos));
}

#[test]
fn test_pandoc_flavor_skips_bare_brace_block() {
    use crate::config::MarkdownFlavor;
    // A `{...}` not preceded by `` `code` `` is not an inline-code attribute.
    let content = "Use {.example} for the class.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("{.example}").unwrap() + 1;
    assert!(!ctx.is_in_inline_code_attr(pos));
}

#[test]
fn test_standard_flavor_skips_inline_code_attribute() {
    use crate::config::MarkdownFlavor;
    let content = "Use `print()`{.python} for output.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("{.python}").unwrap() + 1;
    assert!(!ctx.is_in_inline_code_attr(pos));
}

#[test]
fn test_pandoc_flavor_detects_bracketed_span() {
    use crate::config::MarkdownFlavor;
    let content = "This is [some text]{.smallcaps} here.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("[some text]").unwrap();
    assert!(ctx.is_in_bracketed_span(pos));
}

#[test]
fn test_pandoc_flavor_skips_link() {
    use crate::config::MarkdownFlavor;
    let content = "A [link](http://example.com) here.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("[link]").unwrap();
    assert!(!ctx.is_in_bracketed_span(pos));
}

#[test]
fn test_standard_flavor_skips_bracketed_span() {
    use crate::config::MarkdownFlavor;
    let content = "This is [some text]{.smallcaps} here.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("[some text]").unwrap();
    assert!(!ctx.is_in_bracketed_span(pos));
}

#[test]
fn test_pandoc_flavor_detects_line_block() {
    use crate::config::MarkdownFlavor;
    let content = "| The Lord of the Rings\n| by J.R.R. Tolkien\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("Lord").unwrap();
    assert!(ctx.is_in_line_block(pos));
}

#[test]
fn test_pandoc_flavor_line_block_does_not_match_pipe_table() {
    use crate::config::MarkdownFlavor;
    let content = "| col1 | col2 |\n|------|------|\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("col1").unwrap();
    assert!(!ctx.is_in_line_block(pos));
}

#[test]
fn test_standard_flavor_skips_line_block() {
    use crate::config::MarkdownFlavor;
    let content = "| The Lord of the Rings\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("Lord").unwrap();
    assert!(!ctx.is_in_line_block(pos));
}

#[test]
fn test_pandoc_flavor_line_block_continuation_is_in_block() {
    // The continuation line (whitespace-indented, no leading pipe) belongs
    // to the active block, so a position inside it must report true.
    use crate::config::MarkdownFlavor;
    let content = "| First line\n  continuation here\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("continuation").unwrap();
    assert!(ctx.is_in_line_block(pos));
}

#[test]
fn test_pandoc_flavor_detects_pipe_table_caption_below() {
    use crate::config::MarkdownFlavor;
    let content = "\
| col1 | col2 |
|------|------|
| a    | b    |

: My caption
";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("My caption").unwrap();
    assert!(ctx.is_in_pipe_table_caption(pos));
}

#[test]
fn test_pandoc_flavor_definition_term_is_not_pipe_table_caption() {
    use crate::config::MarkdownFlavor;
    let content = "Term\n: definition\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("definition").unwrap();
    assert!(!ctx.is_in_pipe_table_caption(pos));
}

#[test]
fn test_standard_flavor_skips_pipe_table_caption() {
    use crate::config::MarkdownFlavor;
    let content = "\
| col1 |
|------|
| a    |

: Caption
";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("Caption").unwrap();
    assert!(!ctx.is_in_pipe_table_caption(pos));
}

#[test]
fn test_pandoc_flavor_detects_pipe_table_caption_above() {
    use crate::config::MarkdownFlavor;
    let content = "\
: Caption first

| col1 | col2 |
|------|------|
| a    | b    |
";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("Caption first").unwrap();
    assert!(ctx.is_in_pipe_table_caption(pos));
}

#[test]
fn test_pandoc_flavor_detects_metadata_block_at_start() {
    use crate::config::MarkdownFlavor;
    let content = "---\ntitle: Doc\n---\n\nBody.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("title").unwrap();
    assert!(ctx.is_in_pandoc_metadata(pos));
    let body_pos = content.find("Body").unwrap();
    assert!(!ctx.is_in_pandoc_metadata(body_pos));
}

#[test]
fn test_pandoc_flavor_detects_mid_document_metadata() {
    use crate::config::MarkdownFlavor;
    let content = "Intro.\n\n---\nauthor: X\n---\n\nBody.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find("author").unwrap();
    assert!(ctx.is_in_pandoc_metadata(pos));
}

#[test]
fn test_standard_flavor_skips_pandoc_metadata() {
    use crate::config::MarkdownFlavor;
    let content = "---\ntitle: Doc\n---\n\nBody.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("title").unwrap();
    assert!(!ctx.is_in_pandoc_metadata(pos));
}

#[test]
fn test_pandoc_flavor_detects_grid_table() {
    use crate::config::MarkdownFlavor;
    let content = "\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
+---+---+
";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let pos = content.find('a').unwrap();
    assert!(ctx.is_in_grid_table(pos));
}

#[test]
fn test_pandoc_flavor_grid_table_excludes_surrounding_text() {
    use crate::config::MarkdownFlavor;
    let content = "Before.\n\n+---+---+\n| a | b |\n+---+---+\n\nAfter.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let before_pos = content.find("Before").unwrap();
    let after_pos = content.find("After").unwrap();
    assert!(!ctx.is_in_grid_table(before_pos));
    assert!(!ctx.is_in_grid_table(after_pos));
}

#[test]
fn test_standard_flavor_skips_grid_table() {
    use crate::config::MarkdownFlavor;
    let content = "+---+---+\n| a | b |\n+---+---+\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find('a').unwrap();
    assert!(!ctx.is_in_grid_table(pos));
}

#[test]
fn test_pandoc_flavor_detects_multi_line_table() {
    use crate::config::MarkdownFlavor;
    let content = "\
-------------------------------------------------------------
 Centered   Default           Right Left
  Header    Aligned         Aligned Aligned
----------- ------- --------------- -------------------------
   First    row                12.0 Example of a row that
                                    spans multiple lines.

  Second    row                 5.0 Here's another one. Note
                                    the blank line between
                                    rows.
-------------------------------------------------------------
";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    // The entire content should be detected as a single multi-line table.
    let first_pos = content.find("First").unwrap();
    let second_pos = content.find("Second").unwrap();
    assert!(ctx.is_in_multi_line_table(first_pos));
    assert!(ctx.is_in_multi_line_table(second_pos));
    // The detection covers byte 0 (the top border) through content.len().
    assert!(ctx.is_in_multi_line_table(0));
}

#[test]
fn test_pandoc_flavor_multi_line_table_excludes_surrounding_text() {
    use crate::config::MarkdownFlavor;
    let content = "\
Before text.

-------------------------------------------------------------
 Centered   Default           Right Left
  Header    Aligned         Aligned Aligned
----------- ------- --------------- -------------------------
   First    row                12.0 Example.
-------------------------------------------------------------

After text.
";
    let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
    let before_pos = content.find("Before").unwrap();
    let after_pos = content.find("After").unwrap();
    let inside_pos = content.find("First").unwrap();
    assert!(!ctx.is_in_multi_line_table(before_pos));
    assert!(!ctx.is_in_multi_line_table(after_pos));
    assert!(ctx.is_in_multi_line_table(inside_pos));
}

#[test]
fn test_standard_flavor_skips_multi_line_table() {
    use crate::config::MarkdownFlavor;
    let content = "\
-------------------------------------------------------------
 Centered   Default           Right Left
  Header    Aligned         Aligned Aligned
----------- ------- --------------- -------------------------
   First    row                12.0 Example.
-------------------------------------------------------------
";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let pos = content.find("First").unwrap();
    assert!(!ctx.is_in_multi_line_table(pos));
}

#[test]
fn test_front_matter_is_not_scanned_for_html_comments() {
    // A `<!--` in a YAML value is data. Pairing it with a `-->` in the body
    // would mark the heading between them as commented out, hiding it from
    // every rule.
    let content = "---\nauthor: \"a <!-- b\"\n---\n\n# Title\n\nText --> text\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(
        ctx.html_comment_ranges().is_empty(),
        "got: {:?}",
        ctx.html_comment_ranges()
    );
    assert!(ctx.unterminated_html_comment().is_none());
}

#[test]
fn test_html_comment_in_the_body_is_found_after_front_matter() {
    let content = "---\nauthor: \"a <!-- b\"\n---\n\n<!-- a body comment -->\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let ranges = ctx.html_comment_ranges();
    assert_eq!(ranges.len(), 1);
    assert_eq!(ranges[0].start, content.find("<!-- a body").unwrap());
}

#[test]
fn test_unterminated_html_comment_offset() {
    let content = "# Title\n\n<!-- never closed\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let opener = content.find("<!--").unwrap();
    assert_eq!(ctx.unterminated_html_comment(), Some(opener));
    // The opener starts an HTML block, so it comments out the rest of it. The
    // range is what keeps the comment-aware rules agreeing with the parser,
    // which reports no headings or lists inside that block either.
    let ranges = ctx.html_comment_ranges();
    assert_eq!(ranges.len(), 1, "got: {ranges:?}");
    assert_eq!((ranges[0].start, ranges[0].end), (opener, content.len()));
}

#[test]
fn test_unterminated_inline_html_comment_has_no_range() {
    // Mid-paragraph there is no comment for `<!--` to open: CommonMark renders
    // it literally, so the text after it is published and stays visible to
    // every rule.
    let content = "# Title\n\nSome prose <!-- never closed\n\nMore text.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(ctx.unterminated_html_comment(), Some(content.find("<!--").unwrap()));
    assert!(
        ctx.html_comment_ranges().is_empty(),
        "an inline opener hides nothing, got: {:?}",
        ctx.html_comment_ranges()
    );
}

#[test]
fn test_unterminated_html_comment_range_stops_at_its_container() {
    // The block ends with the blockquote, not at the end of the document, so
    // the paragraph below it is ordinary content.
    let content = "> <!-- never closed\n> inside\n\nVisible text.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let ranges = ctx.html_comment_ranges();
    assert_eq!(ranges.len(), 1, "got: {ranges:?}");
    assert_eq!(ranges[0].start, content.find("<!--").unwrap());
    assert!(
        ranges[0].end < content.find("Visible").unwrap(),
        "range {:?} should stop before the text after the quote",
        ranges[0]
    );
}

#[test]
fn test_html_opener_a_closed_obsidian_pair_hides_gets_no_range() {
    use crate::config::MarkdownFlavor;
    // The `<!--` sits between a pair of `%%`, so Obsidian removes it before
    // anything parses it as an opener. Giving it a block range would close the
    // Obsidian comment nowhere and hide the rest of the note from every rule.
    let content = "%% note\n<!-- hidden\n%%\n\nVisible text.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert_eq!(ctx.unterminated_html_comment(), None);
    assert_eq!(ctx.unterminated_obsidian_comment(), None);
    assert!(
        ctx.html_comment_ranges().is_empty(),
        "got: {:?}",
        ctx.html_comment_ranges()
    );
    let visible = content.find("Visible").unwrap();
    assert!(!ctx.is_in_html_comment(visible));
    assert!(!ctx.is_in_obsidian_comment(visible));
}

#[test]
fn test_obsidian_delimiters_inside_an_unclosed_html_block_are_comment_text() {
    use crate::config::MarkdownFlavor;
    // The block covers the `%%`, so it opens no Obsidian comment. Both scans
    // have to agree here, or the document reports a second unclosed comment
    // for a delimiter that renders as nothing.
    let content = "<!-- an aside\n\n%% a note\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert_eq!(ctx.unterminated_html_comment(), Some(0));
    assert_eq!(ctx.unterminated_obsidian_comment(), None);
    assert!(ctx.is_in_html_comment(content.find("%%").unwrap()));
    assert!(!ctx.is_in_obsidian_comment(content.find("%%").unwrap()));
}

#[test]
fn test_the_comment_syntax_that_opens_first_hides_the_other() {
    use crate::config::MarkdownFlavor;
    // The HTML scan cannot see the `%%` delimiters, so it reports a comment
    // running from the hidden `<!--` to the `-->` below, over the closing `%%`.
    // The `%%` opens first, which makes the `<!--` comment text.
    let content = "%% note <!-- hidden %%\n\n<!-- closed -->\n\nVisible text.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert_eq!(ctx.unterminated_obsidian_comment(), None);
    assert!(ctx.is_in_obsidian_comment(content.find("hidden").unwrap()));
    let visible = content.find("Visible").unwrap();
    assert!(!ctx.is_in_obsidian_comment(visible));
}

#[test]
fn test_obsidian_delimiter_behind_a_comment_on_the_same_line_is_comment_text() {
    use crate::config::MarkdownFlavor;
    // A comment can start and end partway along a line, so whether a `%%` is
    // hidden is a question about bytes, not about whole lines.
    let content = "text <!-- %% --> tail\n\n%% a note\n\nBelow.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    let hidden = content.find("%%").unwrap();
    let opener = content.rfind("%%").unwrap();
    assert!(!ctx.is_in_obsidian_comment(hidden));
    assert_eq!(ctx.unterminated_obsidian_comment(), Some(opener));
    assert!(ctx.is_in_obsidian_comment(content.find("Below.").unwrap()));
}

#[test]
fn test_obsidian_comments_are_repaired_around_an_unclosed_html_block() {
    use crate::config::MarkdownFlavor;
    // The `%%` the block hides looks like the closer for the one below it. It
    // is comment text, so the one below opens a comment that nothing closes,
    // and everything after it is hidden.
    let content = "> <!-- an aside\n> %% hidden\n\n%% a note\n\nBelow.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    let opener = content.rfind("%%").unwrap();
    assert_eq!(ctx.unterminated_html_comment(), Some(content.find("<!--").unwrap()));
    assert_eq!(ctx.unterminated_obsidian_comment(), Some(opener));
    assert!(ctx.is_in_html_comment(content.find("%% hidden").unwrap()));
    assert!(ctx.is_in_obsidian_comment(content.find("Below.").unwrap()));
}

#[test]
fn test_unterminated_obsidian_comment_offset() {
    let content = "# Title\n\n%% never closed\n";
    let obsidian = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert_eq!(
        obsidian.unterminated_obsidian_comment(),
        Some(content.find("%%").unwrap())
    );

    let standard = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        standard.unterminated_obsidian_comment(),
        None,
        "%% is ordinary text outside the Obsidian flavor"
    );
}

#[test]
fn test_front_matter_is_not_scanned_for_obsidian_comments() {
    // A `%%` in a YAML value is part of the value. Treating it as a delimiter
    // opened a comment that ran to the end of the note, hiding the body from
    // every rule.
    let content = "---\ntitle: \"50%% off\"\n---\n\n# Title\n\nText\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert_eq!(ctx.unterminated_obsidian_comment(), None);
    assert!(!ctx.is_in_obsidian_comment(content.find("# Title").unwrap()));
    assert!(!ctx.is_in_obsidian_comment(content.find("Text").unwrap()));
}

#[test]
fn test_obsidian_comment_in_the_body_is_found_after_front_matter() {
    let content = "---\ntitle: \"50%% off\"\n---\n\nText %% a note %% more\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
    assert!(ctx.is_in_obsidian_comment(content.find("a note").unwrap()));
    assert!(!ctx.is_in_obsidian_comment(content.find("more").unwrap()));
}

#[test]
fn test_delimiters_in_an_indented_code_block_are_not_comment_delimiters() {
    // The parser reports a real indented code block here, so both delimiters are
    // sample text. Pairing them would hide the paragraph between them from every
    // rule while the page shows it.
    let content = "Intro text.\n\n    <!-- open\n\nMiddle text.\n\n    --> close\n\nEnd.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(
        ctx.html_comment_ranges().is_empty(),
        "got: {:?}",
        ctx.html_comment_ranges()
    );
    assert!(!ctx.is_in_html_comment(content.find("Middle").unwrap()));
    assert_eq!(ctx.unterminated_html_comment(), None);
}

#[test]
fn test_unclosed_comment_in_an_admonition_hides_the_rest_of_its_body() {
    // The admonition body is markdown in its own right, so the `<!--` opens a
    // block there. The parser has no admonitions and reports none, which left
    // the line below the opener visible to every rule.
    let content = "!!! note\n    <!-- hidden\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert_eq!(ctx.unterminated_html_comment(), Some(content.find("<!--").unwrap()));
    assert!(ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

#[test]
fn test_unclosed_comment_in_an_admonition_stops_at_the_next_admonition() {
    // A marker at the same indent opens a sibling container, so it is not part
    // of the body the comment hides.
    let content = "!!! note\n    <!-- hidden\n    hidden text\n\n!!! warning\n    visible text\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert!(ctx.is_in_html_comment(content.find("hidden text").unwrap()));
    assert!(!ctx.is_in_html_comment(content.find("visible text").unwrap()));
}

#[test]
fn test_unclosed_comment_in_a_markdown_html_block_hides_the_rest_of_it() {
    // The `markdown` attribute makes the body markdown in every flavor, so the
    // opener behaves the same as it does in an admonition.
    let content = "<div markdown>\n\n    <!-- hidden\n    visit https://example.com\n\n</div>\n\nAfter.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert!(ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
    assert!(!ctx.is_in_html_comment(content.find("After.").unwrap()));
}

#[test]
fn test_an_admonition_comment_is_read_across_a_blank_line_after_the_marker() {
    // With a blank line after the marker the parser calls the body an indented
    // code block, which is the same container content by another misreading.
    let content = "!!! note\n\n    <!-- hidden\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert!(ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

#[test]
fn test_a_comment_indented_inside_an_admonition_is_still_a_comment() {
    // The exemption the container gets is what keeps a closed comment written
    // at the body indent from being read as code.
    let content = "!!! note\n\n    <!-- a note -->\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert!(ctx.is_in_html_comment(content.find("a note").unwrap()));
    assert!(!ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

#[test]
fn test_an_opener_partway_through_an_admonition_line_opens_nothing() {
    // Inline HTML renders literally, in a container as anywhere else, so the
    // text after it is published rather than hidden.
    let content = "!!! note\n    Some text <!-- never closed\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert_eq!(ctx.unterminated_html_comment(), Some(content.find("<!--").unwrap()));
    assert!(!ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

#[test]
fn test_delimiters_in_a_fence_inside_an_admonition_are_not_comment_delimiters() {
    // The body is markdown, but a fence written in it is a real code block, so
    // the sample opener it holds neither opens a comment nor is left dangling.
    let content = "!!! note\n\n    ```\n    <!-- a sample opener\n    ```\n\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert_eq!(ctx.unterminated_html_comment(), None);
    assert!(!ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

#[test]
fn test_an_unclosed_comment_in_an_admonition_hides_a_fence_below_it() {
    // Once the comment opens, the fence markers are raw HTML rather than a code
    // block, so the block runs on to the end of the body as it does at the top
    // level.
    let content = "!!! note\n    <!-- hidden\n    ```\n    code\n    ```\n    visit https://example.com\n";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);
    assert!(ctx.is_in_html_comment(content.find("code").unwrap()));
    assert!(ctx.is_in_html_comment(content.find("https://example.com").unwrap()));
}

/// Line number (1-indexed) of the only line carrying `is_horizontal_rule`, or
/// `None` when no line does.
fn horizontal_rule_line(ctx: &LintContext) -> Option<usize> {
    let marked: Vec<usize> = ctx
        .lines
        .iter()
        .enumerate()
        .filter(|(_, line)| line.is_horizontal_rule)
        .map(|(i, _)| i + 1)
        .collect();
    assert!(marked.len() <= 1, "expected at most one marked line, got {marked:?}");
    marked.first().copied()
}

#[test]
fn test_a_break_in_a_block_that_hides_its_content_is_not_a_horizontal_rule() {
    // The markers are computed from the line text, before the passes that know
    // which block the line belongs to have run.
    for (content, flavor) in [
        ("Text.\n\n<!--\n***\n-->\n\nMore.\n", MarkdownFlavor::Standard),
        ("Text.\n\n<div>\n***\n</div>\n\nMore.\n", MarkdownFlavor::Standard),
        ("Text.\n\n$$\n***\n$$\n\nMore.\n", MarkdownFlavor::Standard),
        ("Text.\n\n::: mermaid\n***\n:::\n\nMore.\n", MarkdownFlavor::AzureDevOps),
        ("Text.\n\n{/*\n***\n*/}\n\nMore.\n", MarkdownFlavor::MDX),
        ("Text.\n\n%%\n***\n%%\n\nMore.\n", MarkdownFlavor::Obsidian),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        assert_eq!(
            horizontal_rule_line(&ctx),
            None,
            "line 4 was still a horizontal rule in {content:?} ({flavor:?})"
        );
    }
}

#[test]
fn test_a_break_in_a_container_whose_body_is_markdown_stays_a_horizontal_rule() {
    // These containers render their body as markdown, so a break written in one
    // is a real break and the sweep above must leave it alone.
    for (content, flavor) in [
        ("Text.\n\n***\n\nMore.\n", MarkdownFlavor::Standard),
        ("::: note\nText.\n***\nMore.\n:::\n", MarkdownFlavor::Pandoc),
        ("<Tabs>\nText.\n***\nMore.\n</Tabs>\n", MarkdownFlavor::MDX),
        ("/// note\nText.\n***\nMore.\n///\n", MarkdownFlavor::MkDocs),
        ("> Text.\n> ***\n> More.\n", MarkdownFlavor::Standard),
        // A `markdown` attribute takes effect for content a blank line separates
        // from the tag, which is also where rumdl starts linting the body.
        (
            "<div markdown>\n\nText.\n***\nMore.\n\n</div>\n",
            MarkdownFlavor::Standard,
        ),
        (
            "<div markdown>\n\nText.\n***\nMore.\n\n</div>\n",
            MarkdownFlavor::MkDocs,
        ),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        assert!(
            horizontal_rule_line(&ctx).is_some(),
            "the break stopped being a horizontal rule in {content:?} ({flavor:?})"
        );
    }
}

#[test]
fn test_a_break_written_flush_against_an_html_tag_is_raw_html() {
    // Without the blank line the `markdown` attribute needs, the body is a plain
    // HTML block: no other rule reads it as markdown (a heading there draws no
    // MD022, mixed list markers no MD004), so a break there is not one either.
    for (content, flavor) in [
        ("<div markdown>\nText.\n***\nMore.\n</div>\n", MarkdownFlavor::Standard),
        (
            "<div markdown=\"1\">\nText.\n***\nMore.\n</div>\n",
            MarkdownFlavor::MkDocs,
        ),
    ] {
        let ctx = LintContext::new(content, flavor, None);
        assert_eq!(
            horizontal_rule_line(&ctx),
            None,
            "the raw HTML was still a horizontal rule in {content:?} ({flavor:?})"
        );
    }
}

#[test]
fn heading_slug_text_keeps_the_whitespace_an_anchor_element_leaves() {
    // `text` is what the heading displays, trimmed as CommonMark does.
    // `slug_text` is what a slug is generated from: the same text with every
    // space an anchor element left behind, which GitHub and kramdown turn into
    // a hyphen. All three heading kinds carry both.
    let content = "# Alpha <a id=\"x\"></a>\n\nBeta <a id=\"y\"></a>\n---\n\n> ## Foo <a id=\"z\"></a> Bar\n\n#### Plain {#custom}\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let headings: Vec<_> = ctx
        .headings()
        .map(|parsed| {
            (
                parsed.heading.text.as_str(),
                parsed.heading.slug_text.as_str(),
                parsed.heading.custom_id.as_deref(),
            )
        })
        .collect();
    assert_eq!(
        headings,
        vec![
            ("Alpha", "Alpha ", None),
            ("Beta", "Beta ", None),
            ("Foo Bar", "Foo  Bar", None),
            ("Plain", "Plain", Some("custom")),
        ]
    );
}

fn definition_list_lines(ctx: &LintContext) -> Vec<bool> {
    (1..=ctx.lines.len())
        .map(|line| ctx.is_in_definition_list(line))
        .collect()
}

#[test]
fn a_definition_list_ends_with_its_last_definition() {
    // The parser's own range for the list runs on over the paragraph after
    // it; the list ends where its last definition does.
    let content = "Term\n:   Aliquam metus.\n\n    Duis mollis.\n\nAfter the list.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert_eq!(definition_list_lines(&ctx), [true, true, true, true, false, false]);
    assert_eq!(
        (1..=6).map(|line| ctx.is_definition_term(line)).collect::<Vec<_>>(),
        [true, false, false, false, false, false]
    );
    assert_eq!(
        ctx.definition_text_at(2),
        Some(&DefinitionText {
            start_line: 2,
            end_line: 2,
            marker_prefix_len: Some(4),
        })
    );
    assert_eq!(ctx.definition_text_at(3), None);
    assert_eq!(
        ctx.definition_text_at(4),
        Some(&DefinitionText {
            start_line: 4,
            end_line: 4,
            marker_prefix_len: None,
        })
    );
}

#[test]
fn a_colon_touching_its_text_opens_no_definition() {
    // `:warning:` and a `:::` fence closing a div are definitions to
    // pulldown-cmark alone, so neither they nor the lines above them count.
    let content = "T\n:warning: x\n\n::: {.note}\nBody\n:::\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(definition_list_lines(&ctx), [false; 6]);
    assert!((1..=6).all(|line| !ctx.is_definition_term(line) && ctx.definition_text_at(line).is_none()));

    // In a list holding both kinds, only the whitespace-marked definition and
    // its term count, and the list's extent starts at that term.
    let mixed = "A\n:x\n\nB\n:   y\n";
    let ctx = LintContext::new(mixed, MarkdownFlavor::Standard, None);
    assert_eq!(definition_list_lines(&ctx), [false, false, false, true, true]);
    assert!(!ctx.is_definition_term(1));
    assert!(ctx.is_definition_term(4));
    assert!(ctx.definition_text_at(2).is_none());
    assert_eq!(
        ctx.definition_text_at(5).map(|text| text.marker_prefix_len),
        Some(Some(4))
    );
}

#[test]
fn definition_texts_are_found_in_containers_and_after_a_tab() {
    // The marker prefix is everything before the text on the marker line,
    // container prefix included; a text starting on a later line has none.
    let content =
        "> Term\n> :\tQuoted.\n\n- Item\n\n  Term\n\n  :   Listed,\n  lazily continued.\n\nTerm\n:\n    Deferred.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    assert!(ctx.is_definition_term(1));
    assert_eq!(
        ctx.definition_text_at(2),
        Some(&DefinitionText {
            start_line: 2,
            end_line: 2,
            marker_prefix_len: Some(4),
        })
    );
    assert!(ctx.is_definition_term(6));
    assert_eq!(
        ctx.definition_text_at(9),
        Some(&DefinitionText {
            start_line: 8,
            end_line: 9,
            marker_prefix_len: Some(6),
        })
    );
    assert!(ctx.is_definition_term(11));
    assert!(ctx.is_in_definition_list(12));
    assert_eq!(ctx.definition_text_at(12), None);
    assert_eq!(
        ctx.definition_text_at(13),
        Some(&DefinitionText {
            start_line: 13,
            end_line: 13,
            marker_prefix_len: None,
        })
    );
}

#[test]
fn a_list_nested_before_the_first_kept_term_still_counts() {
    // The list nested in the colon-touching definition is found before the
    // only item its enclosing list keeps.
    let content = "A\n:x\n\n    B\n    :   nested\n\nC\n:   kept\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        definition_list_lines(&ctx),
        [false, false, false, true, true, false, true, true]
    );
    assert_eq!(
        ctx.definition_text_at(5).map(|text| text.marker_prefix_len),
        Some(Some(8))
    );
}

#[test]
fn a_term_whose_colon_touches_its_text_is_free_between_definition_items() {
    let content = "A\n: valid\n\nB is prose.\n\n:x\n\nC\n: valid\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(
        definition_list_lines(&ctx),
        [true, true, false, false, false, false, false, true, true]
    );
    assert!(!ctx.is_definition_term(4));
}

#[test]
fn a_definition_continues_after_a_list_nested_in_it() {
    let content = "Term\n:   Outer.\n\n    Inner\n    :   nested\n\n    Back in the outer definition.\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    assert_eq!(definition_list_lines(&ctx), [true; 7]);
}