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
pub mod types;
pub use types::*;
mod element_parsers;
mod flavor_detection;
mod heading_detection;
mod line_computation;
mod link_parser;
mod list_blocks;
#[cfg(test)]
mod tests;
use crate::config::MarkdownFlavor;
use crate::inline_config::InlineConfig;
use crate::rules::front_matter_utils::FrontMatterUtils;
use crate::utils::code_block_utils::{CodeBlockDetail, CodeBlockUtils};
use crate::utils::range_utils::byte_to_char_count;
use std::collections::HashMap;
use std::ops::Range;
use std::path::{Path, PathBuf};
/// Macro for profiling sections - only active in non-WASM builds
#[cfg(not(target_arch = "wasm32"))]
macro_rules! profile_section {
($name:expr, $profile:expr, $code:expr) => {{
let start = std::time::Instant::now();
let result = $code;
if $profile {
eprintln!("[PROFILE] {}: {:?}", $name, start.elapsed());
}
result
}};
}
fn build_commonmark_ordered_lists(
lines: &[LineInfo],
line_to_list: &crate::utils::code_block_utils::LineToListMap,
list_start_values: &crate::utils::code_block_utils::ListStartValues,
) -> Vec<CommonMarkOrderedListInfo> {
let mut grouped_lines: HashMap<usize, Vec<usize>> = HashMap::new();
for (&line_num, &list_id) in line_to_list {
let is_ordered_item = line_num
.checked_sub(1)
.and_then(|index| lines.get(index))
.and_then(|line| line.list_item.as_deref())
.is_some_and(|item| item.is_ordered);
if is_ordered_item {
grouped_lines.entry(list_id).or_default().push(line_num);
}
}
let mut lists: Vec<_> = grouped_lines
.into_iter()
.map(|(list_id, mut item_lines)| {
item_lines.sort_unstable();
CommonMarkOrderedListInfo {
start_value: list_start_values.get(&list_id).copied().unwrap_or(1),
item_lines,
}
})
.collect();
lists.sort_by_key(|list| list.item_lines.first().copied().unwrap_or(0));
lists
}
#[cfg(target_arch = "wasm32")]
macro_rules! profile_section {
($name:expr, $profile:expr, $code:expr) => {{ $code }};
}
/// Grouped byte ranges for skip context detection
/// Used to reduce parameter count in internal functions
pub(super) struct SkipByteRanges<'a> {
pub(super) html_comment_ranges: &'a [crate::utils::skip_context::ByteRange],
pub(super) autodoc_ranges: &'a [crate::utils::skip_context::ByteRange],
pub(super) pandoc_div_ranges: &'a [crate::utils::skip_context::ByteRange],
pub(super) pymdown_block_ranges: &'a [crate::utils::skip_context::ByteRange],
}
use std::sync::{Arc, OnceLock};
/// Map from line byte offset to list item data: (is_ordered, marker, marker_column, content_column, number)
pub(super) type ListItemMap = std::collections::HashMap<usize, (bool, String, usize, usize, Option<usize>)>;
/// Type alias for byte ranges used in JSX expression and MDX comment detection
pub(super) type ByteRanges = Vec<(usize, usize)>;
pub struct LintContext<'a> {
pub content: &'a str,
content_lines: Vec<&'a str>, // Pre-split lines from content (avoids repeated allocations)
pub line_offsets: Vec<usize>,
pub code_blocks: Vec<(usize, usize)>, // Cached code block ranges (not including inline code spans)
pub code_block_details: Vec<CodeBlockDetail>, // Per-block metadata (fenced/indented, info string)
pub strong_spans: Vec<crate::utils::code_block_utils::StrongSpanDetail>, // Pre-computed strong emphasis spans
line_to_list: crate::utils::code_block_utils::LineToListMap, // Private CommonMark membership input
list_start_values: crate::utils::code_block_utils::ListStartValues, // Private CommonMark start-value input
commonmark_ordered_lists_cache: OnceLock<Vec<CommonMarkOrderedListInfo>>, // Lazy source-ordered view
pub lines: Vec<LineInfo>, // Pre-computed line information
blockquote_headings: Vec<Option<Box<HeadingInfo>>>, // Container headings, parallel to `lines`
links: Vec<ParsedLink<'a>>, // Pre-parsed links
images: Vec<ParsedImage<'a>>, // Pre-parsed images
broken_links: Vec<BrokenLinkInfo>, // Broken/undefined references
footnote_refs: Vec<FootnoteRef>, // Pre-parsed footnote references
reference_defs: Vec<ReferenceDef>, // Reference definitions
reference_defs_map: HashMap<String, usize>, // O(1) lookup by lowercase ID -> index in reference_defs
code_spans_cache: OnceLock<Arc<Vec<CodeSpan>>>, // Lazy-loaded inline code spans
math_spans_cache: OnceLock<Arc<Vec<MathSpan>>>, // Lazy-loaded math spans ($...$ and $$...$$)
math_byte_ranges_cache: OnceLock<Vec<(usize, usize)>>, // Lazy-loaded math byte ranges for is_in_math_context
pub list_blocks: Vec<ListBlock>, // Pre-parsed list blocks
pub char_frequency: CharFrequency, // Character frequency analysis
html_tags_cache: OnceLock<Arc<Vec<HtmlTag>>>, // Lazy-loaded HTML tags
jsx_component_tags_cache: OnceLock<Arc<Vec<HtmlTag>>>, // Lazy-loaded JSX component tags (shares the html_tags parse)
emphasis_spans_cache: OnceLock<Arc<Vec<EmphasisSpan>>>, // Lazy-loaded emphasis spans
bare_urls_cache: OnceLock<Arc<Vec<BareUrl>>>, // Lazy-loaded bare URLs
has_mixed_list_nesting_cache: OnceLock<bool>, // Cached result for mixed ordered/unordered list nesting detection
html_comment_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed HTML comment ranges
pub table_blocks: Vec<crate::utils::table_utils::TableBlock>, // Pre-computed table blocks
line_index: crate::utils::range_utils::LineIndex<'a>, // Pre-computed source-location index
jinja_ranges: Vec<(usize, usize)>, // Pre-computed Jinja template ranges ({{ }}, {% %})
pub flavor: MarkdownFlavor, // Markdown flavor being used
source_file: Option<PathBuf>, // Source file path (capability exposed through `source_file()`)
jsx_expression_ranges: Vec<(usize, usize)>, // Pre-computed JSX expression ranges (MDX: {expression})
mdx_comment_ranges: Vec<(usize, usize)>, // Pre-computed MDX comment ranges ({/* ... */})
citation_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc/Quarto citation ranges (@key, [@key])
pandoc_div_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc/Quarto div block ranges (::: ... :::)
colon_fence_details: Vec<CodeBlockDetail>, // Pre-computed Azure DevOps colon code fences (:::lang ... :::)
inline_footnote_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc inline footnote ranges (^[...])
pandoc_header_slugs: std::collections::HashSet<String>, // Pre-computed Pandoc implicit header reference slugs
example_list_marker_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc example-list marker ranges (@) / (@label)
example_reference_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc example reference ranges (@label) inline
sub_super_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc subscript (~x~) and superscript (^x^) ranges
inline_code_attr_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc inline code attribute ranges (`code`{.lang})
bracketed_span_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc bracketed span ranges ([text]{attrs})
line_block_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc line block ranges (| text)
pipe_table_caption_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc pipe-table caption ranges (: caption)
pandoc_metadata_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc YAML metadata block ranges (--- ... --- or ...)
grid_table_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc grid-table ranges (+---+---+)
multi_line_table_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc multi-line table ranges
shortcode_ranges: Vec<(usize, usize)>, // Pre-computed Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
link_title_ranges: Vec<(usize, usize)>, // Pre-computed sorted link title byte ranges
code_span_byte_ranges: Vec<(usize, usize)>, // Pre-computed code span byte ranges from pulldown-cmark
inline_config: InlineConfig, // Parsed inline configuration comments for rule disabling
obsidian_comment_ranges: Vec<(usize, usize)>, // Pre-computed Obsidian comment ranges (%%...%%)
unterminated_html_comment: Option<usize>, // Byte offset of a `<!--` with no `-->`
unterminated_obsidian_comment: Option<usize>, // Byte offset of a `%%` with no closing `%%`
lazy_cont_lines_cache: OnceLock<Arc<Vec<LazyContLine>>>, // Lazy-loaded lazy continuation lines
myst_directive_ranges: Vec<(usize, usize)>, // Pre-computed MyST colon directive byte ranges (:::{name} ... :::)
myst_comment_ranges: Vec<(usize, usize)>, // Pre-computed MyST comment byte ranges (% comment)
myst_role_ranges: Vec<(usize, usize)>, // Pre-computed MyST role byte ranges ({role}`content`)
front_matter_end: usize, // 1-indexed line where front matter ends, 0 if none
}
/// The byte ranges this document's flavor really holds as code.
///
/// An inline directive written inside one of these configures nothing, so there
/// is nothing to report about it. The answer is read off a full context rather
/// than scanned out of the text, which is what keeps it identical to the one
/// `InlineConfig` was built from: a MkDocs admonition body is indented but is
/// structure, and a scan of the text alone reads it as an indented code block.
///
/// Building a context costs a parse, so callers filter with it only once they
/// hold something to filter.
pub fn code_block_ranges(content: &str, flavor: MarkdownFlavor) -> Vec<(usize, usize)> {
LintContext::new(content, flavor, None).code_blocks
}
impl<'a> LintContext<'a> {
/// The native source path available to filesystem-aware rules.
///
/// Virtual adapters intentionally leave this unset even when they provide a
/// logical path for configuration matching.
pub fn source_file(&self) -> Option<&Path> {
self.source_file.as_deref()
}
pub fn new(content: &'a str, flavor: MarkdownFlavor, source_file: Option<PathBuf>) -> Self {
#[cfg(not(target_arch = "wasm32"))]
let profile = std::env::var("RUMDL_PROFILE_QUADRATIC").is_ok();
let line_offsets = profile_section!("Line offsets", profile, {
let mut offsets = vec![0];
for (i, c) in content.char_indices() {
if c == '\n' {
offsets.push(i + 1);
}
}
offsets
});
// Compute content_lines once for all functions that need it
let content_lines: Vec<&str> = content.lines().collect();
// Detect front matter boundaries once for all functions that need it.
// This is the single allowed call site; rules read the cached value
// via front_matter_end_line().
#[allow(clippy::disallowed_methods)]
let front_matter_end = FrontMatterUtils::get_front_matter_end_line(content);
// Detect code blocks and code spans once and cache them
let parse_result = profile_section!(
"Code blocks",
profile,
CodeBlockUtils::detect_code_blocks_and_spans(content)
);
let mut code_blocks = parse_result.code_blocks;
let code_span_ranges = parse_result.code_spans;
let code_block_details = parse_result.code_block_details;
let strong_spans = parse_result.strong_spans;
let line_to_list = parse_result.line_to_list;
let list_start_values = parse_result.list_start_values;
let html_blocks = parse_result.html_blocks;
// Container structure the parser cannot see. Computed from the line text
// alone, so it is available here, before the line info it corrects.
let containers = profile_section!(
"Container lines",
profile,
flavor_detection::detect_container_lines(&content_lines, flavor)
);
// Pre-compute HTML comment ranges ONCE for all operations.
// Code-span and code-block ranges are passed so `<!--`/`-->` inside code
// are treated as literal text, not comment delimiters that could pair
// across code regions on different lines. An indented block over
// container content is the parser reading a MkDocs admonition or a
// `<div markdown>` body as code, and a comment written there is a real
// comment, so only the parts of such a block that a fence really does
// hold as code are kept.
let comment_code_block_ranges: Vec<(usize, usize)> = code_block_details
.iter()
.flat_map(|detail| {
if detail.is_fenced {
return vec![(detail.start, detail.end)];
}
let start_line = line_offsets
.partition_point(|&offset| offset <= detail.start)
.saturating_sub(1);
let end_line = line_offsets.partition_point(|&offset| offset < detail.end);
containers
.code_line_spans_in(start_line..end_line)
.into_iter()
.map(|span| {
let start = line_offsets[span.start].max(detail.start);
let end = line_offsets
.get(span.end)
.copied()
.unwrap_or(content.len())
.min(detail.end);
(start, end)
})
.collect()
})
.collect();
// Front matter is data, not markdown: a `<!--` in a YAML value would
// otherwise pair with a `-->` in the body and hide everything between
// them from every rule. `front_matter_end` is the 1-indexed closing
// delimiter line, so the body starts at the line after it, and a
// document without front matter starts at byte 0.
let body_start = line_offsets.get(front_matter_end).copied().unwrap_or(content.len());
let html_comment_scan = profile_section!(
"HTML comment ranges",
profile,
crate::utils::skip_context::scan_html_comments(
content,
&code_span_ranges,
&comment_code_block_ranges,
body_start
)
);
let mut html_comment_ranges = html_comment_scan.ranges;
let unterminated_html_comment = html_comment_scan.unterminated;
// Pre-compute autodoc block ranges (avoids O(n^2) scaling)
// Detected for all flavors except AzureDevOps, where `:::` denotes code fences
// rather than autodoc directives.
let autodoc_ranges = profile_section!("Autodoc block ranges", profile, {
if flavor.supports_colon_code_fences() || flavor.supports_myst_directives() {
Vec::new()
} else {
crate::utils::mkdocstrings_refs::detect_autodoc_block_ranges(content)
}
});
// Pre-compute Pandoc/Quarto div block ranges for Pandoc-compatible flavors
let pandoc_div_ranges = profile_section!("Pandoc div ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_div_block_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute PyMdown Blocks ranges for MkDocs flavor (/// ... ///)
let pymdown_block_ranges = profile_section!("PyMdown block ranges", profile, {
if flavor == MarkdownFlavor::MkDocs {
crate::utils::pymdown_blocks::detect_block_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute line information AND emphasis spans (without headings/blockquotes yet)
// Emphasis spans are captured during the same pulldown-cmark parse as list detection
let skip_ranges = SkipByteRanges {
html_comment_ranges: &html_comment_ranges,
autodoc_ranges: &autodoc_ranges,
pandoc_div_ranges: &pandoc_div_ranges,
pymdown_block_ranges: &pymdown_block_ranges,
};
let (mut lines, emphasis_spans) = profile_section!(
"Basic line info",
profile,
line_computation::compute_basic_line_info(
content,
&content_lines,
&line_offsets,
&code_blocks,
flavor,
&skip_ranges,
front_matter_end,
)
);
// Detect HTML blocks BEFORE heading detection
profile_section!(
"HTML blocks",
profile,
heading_detection::detect_html_blocks(content, &mut lines)
);
// Detect ESM import/export blocks in MDX files BEFORE heading detection
profile_section!(
"ESM blocks",
profile,
flavor_detection::detect_esm_blocks(content, &mut lines, flavor)
);
// Detect JSX component blocks in MDX files (e.g. <Tabs>...</Tabs>)
profile_section!(
"JSX block detection",
profile,
flavor_detection::detect_jsx_blocks(content, &mut lines, flavor)
);
// Detect JSX expressions and MDX comments in MDX files
let (jsx_expression_ranges, mdx_comment_ranges) = profile_section!(
"JSX/MDX detection",
profile,
flavor_detection::detect_jsx_and_mdx_comments(content, &mut lines, flavor, &code_blocks)
);
// Detect `<div markdown>`-style HTML blocks (grid cards, etc.) regardless of flavor.
// The `markdown` attribute is an explicit, author-supplied signal; recognizing it
// in all flavors keeps `rumdl fmt` from mangling Material grid cards when the
// MkDocs flavor isn't active.
profile_section!(
"Markdown-in-HTML blocks",
profile,
flavor_detection::detect_markdown_html_blocks(&mut lines, &containers)
);
// Detect MkDocs-specific constructs (admonitions, tabs, definition lists)
profile_section!(
"MkDocs constructs",
profile,
flavor_detection::detect_mkdocs_line_info(&content_lines, &mut lines, flavor, &containers)
);
// Detect footnote definitions and correct false code block detection.
// With ENABLE_FOOTNOTES, pulldown-cmark correctly parses multi-line
// footnotes, but the code block detector may still mark 4-space-indented
// footnote continuation lines as indented code blocks.
profile_section!(
"Footnote definitions",
profile,
detect_footnote_definitions(content, &mut lines, &line_offsets)
);
// Filter code_blocks to remove false positives from footnote continuation content.
// Same pattern as MkDocs/JSX corrections below.
{
let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
for &(start, end) in &code_blocks {
let start_line = line_offsets
.partition_point(|&offset| offset <= start)
.saturating_sub(1);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
let mut sub_start: Option<usize> = None;
for (i, &offset) in line_offsets[start_line..end_line]
.iter()
.enumerate()
.map(|(j, o)| (j + start_line, o))
{
let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
if is_real_code && sub_start.is_none() {
let byte_start = if i == start_line { start } else { offset };
sub_start = Some(byte_start);
} else if !is_real_code && sub_start.is_some() {
new_code_blocks.push((sub_start.unwrap(), offset));
sub_start = None;
}
}
if let Some(s) = sub_start {
new_code_blocks.push((s, end));
}
}
code_blocks = new_code_blocks;
}
// Filter code_blocks to remove false positives from MkDocs admonition/tab content
// and `<div markdown>` HTML blocks (grid cards).
// pulldown-cmark treats 4-space-indented content as indented code blocks, but inside
// these containers this is regular markdown content. detect_mkdocs_line_info and
// detect_markdown_html_blocks already corrected LineInfo.in_code_block for these lines,
// but the code_blocks byte ranges are still stale. We split ranges rather than using
// all-or-nothing removal, so fenced code blocks within the containers are preserved.
let has_markdown_html = lines.iter().any(|l| l.in_mkdocs_html_markdown);
if flavor == MarkdownFlavor::MkDocs || has_markdown_html {
let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
for &(start, end) in &code_blocks {
let start_line = line_offsets
.partition_point(|&offset| offset <= start)
.saturating_sub(1);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
// Walk lines in this range, collecting sub-ranges where in_code_block is true
let mut sub_start: Option<usize> = None;
for (i, &offset) in line_offsets[start_line..end_line]
.iter()
.enumerate()
.map(|(j, o)| (j + start_line, o))
{
let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
if is_real_code && sub_start.is_none() {
let byte_start = if i == start_line { start } else { offset };
sub_start = Some(byte_start);
} else if !is_real_code && sub_start.is_some() {
new_code_blocks.push((sub_start.unwrap(), offset));
sub_start = None;
}
}
if let Some(s) = sub_start {
new_code_blocks.push((s, end));
}
}
code_blocks = new_code_blocks;
}
// Filter code_blocks for MDX JSX blocks (same pattern as MkDocs above).
// detect_jsx_blocks already corrected LineInfo.in_code_block for indented content
// inside JSX component blocks, but code_blocks byte ranges need updating too.
if flavor.supports_jsx() {
let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
for &(start, end) in &code_blocks {
let start_line = line_offsets
.partition_point(|&offset| offset <= start)
.saturating_sub(1);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
let mut sub_start: Option<usize> = None;
for (i, &offset) in line_offsets[start_line..end_line]
.iter()
.enumerate()
.map(|(j, o)| (j + start_line, o))
{
let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
if is_real_code && sub_start.is_none() {
let byte_start = if i == start_line { start } else { offset };
sub_start = Some(byte_start);
} else if !is_real_code && sub_start.is_some() {
new_code_blocks.push((sub_start.unwrap(), offset));
sub_start = None;
}
}
if let Some(s) = sub_start {
new_code_blocks.push((s, end));
}
}
code_blocks = new_code_blocks;
// Add byte ranges for fenced code blocks nested inside a JSX component.
// pulldown-cmark classifies the whole component as one HTML block and
// emits no code-block range for the fence, so the split loop above
// (which can only narrow existing ranges) never adds it. Derive the
// ranges from the per-line in_code_block flags detect_jsx_blocks set,
// so byte-range consumers (e.g. MD011, MD044) skip the fence content.
let mut jsx_fence_ranges: Vec<(usize, usize)> = Vec::new();
let mut run: Option<(usize, usize)> = None;
for line in &lines {
if line.in_jsx_block && line.in_code_block {
let line_end = line.byte_offset + line.byte_len;
match &mut run {
Some((_, end)) => *end = line_end,
None => run = Some((line.byte_offset, line_end)),
}
} else if let Some(r) = run.take() {
jsx_fence_ranges.push(r);
}
}
if let Some(r) = run.take() {
jsx_fence_ranges.push(r);
}
if !jsx_fence_ranges.is_empty() {
code_blocks.extend(jsx_fence_ranges);
code_blocks.sort_by_key(|&(start, _)| start);
}
}
// Detect Azure DevOps colon code fences and extend code_blocks so that
// all byte-range consumers correctly skip their content.
let colon_fence_details = profile_section!(
"Azure colon fence detection",
profile,
flavor_detection::detect_azure_colon_fences(content, &mut lines, flavor)
);
if !colon_fence_details.is_empty() {
code_blocks.extend(colon_fence_details.iter().map(|fence| (fence.start, fence.end)));
code_blocks.sort_by_key(|&(start, _)| start);
}
// Detect MyST colon directives (:::{name} ... :::) — these are structural
// containers, NOT code blocks. Content inside is linted as markdown.
let myst_directive_ranges = profile_section!(
"MyST colon directives",
profile,
flavor_detection::detect_myst_colon_directives(content, &mut lines, flavor)
);
// Detect MyST % comments
let myst_comment_ranges = profile_section!(
"MyST comments",
profile,
flavor_detection::detect_myst_comments(content, &mut lines, flavor)
);
// Detect MyST backtick directives (```{name}) and clear in_code_block for
// content-bearing directives so their body is linted as markdown.
profile_section!(
"MyST backtick directives",
profile,
flavor_detection::detect_myst_backtick_directives(
content,
&mut lines,
flavor,
&code_block_details,
&line_offsets
)
);
// Filter code_blocks to remove false positives from MyST content-bearing directives.
// Same pattern as MkDocs admonition filtering.
if flavor.supports_myst_directives() {
let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
for &(start, end) in &code_blocks {
let start_line = line_offsets
.partition_point(|&offset| offset <= start)
.saturating_sub(1);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
let mut sub_start: Option<usize> = None;
for (i, &offset) in line_offsets[start_line..end_line]
.iter()
.enumerate()
.map(|(j, o)| (j + start_line, o))
{
let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
if is_real_code && sub_start.is_none() {
let byte_start = if i == start_line { start } else { offset };
sub_start = Some(byte_start);
} else if !is_real_code && sub_start.is_some() {
new_code_blocks.push((sub_start.unwrap(), offset));
sub_start = None;
}
}
if let Some(s) = sub_start {
new_code_blocks.push((s, end));
}
}
code_blocks = new_code_blocks;
}
// Detect kramdown constructs (extension blocks, IALs, ALDs) in kramdown flavor
profile_section!(
"Kramdown constructs",
profile,
flavor_detection::detect_kramdown_line_info(content, &mut lines, flavor)
);
// Layer 1: Sanitize content-derived fields inside kramdown extension blocks
// so downstream heading detection and collection builders never see them.
// This must run BEFORE detect_headings_and_blockquotes to prevent headings
// from being populated inside extension blocks.
for line in &mut lines {
if line.in_kramdown_extension_block {
line.list_item = None;
line.is_horizontal_rule = false;
line.blockquote = None;
line.is_kramdown_block_ial = false;
}
}
// Detect Obsidian comments (%%...%%) in Obsidian flavor
let obsidian_comment_scan = profile_section!(
"Obsidian comments",
profile,
flavor_detection::detect_obsidian_comments(
content,
&mut lines,
flavor,
&code_span_ranges,
&html_comment_ranges,
body_start
)
);
let mut obsidian_comment_ranges = obsidian_comment_scan.ranges;
let mut unterminated_obsidian_comment = obsidian_comment_scan.unterminated;
// An Obsidian comment hides the text it wraps, so a `<!--` inside one is
// not a comment opener. The HTML scan cannot know that yet - detecting
// Obsidian comments needs its ranges - so the opener it reported is
// re-resolved here, now that the comments that hide it are known.
let unterminated_html_comment = crate::utils::skip_context::unterminated_html_comment_outside(
unterminated_html_comment,
&obsidian_comment_ranges,
content,
&code_span_ranges,
&comment_code_block_ranges,
body_start,
);
// An unclosed `<!--` that opens an HTML block comments out the rest of
// that block, so the text below it is not content any rule should judge.
// Without this the block-structure rules and the comment-aware rules
// disagree about the same lines: the parser reports no list inside the
// block, while a bare URL there is still flagged.
//
// The opener stays reported either way. This governs what the rest of
// the linter sees, not whether the missing closer is raised.
//
// It waits for the re-resolution above because an opener a `%%` pair
// hides is not an opener, and giving that one a range would hide the
// rest of the note from every rule.
if let Some(range) = unterminated_html_comment.and_then(|opener| {
crate::utils::skip_context::unterminated_comment_range(opener, &html_blocks)
.or_else(|| container_comment_range(opener, &containers, &lines, content))
}) {
// Every complete comment starts before the unclosed opener, so this
// keeps the ranges sorted for the binary searches over them.
html_comment_ranges.push(range);
// The line flags are computed before the Obsidian comments are
// known, so they predate this range. Recomputing them through the
// same helper keeps `is_in_html_comment` and the per-line flag
// answering alike, which is the agreement this range exists to
// create.
for line in &mut lines {
let text = line.content(content);
let content_start = line.byte_offset + line.indent;
let content_end = line.byte_offset + text.trim_end().len();
line.in_html_comment = crate::utils::skip_context::is_line_entirely_in_html_comment(
&html_comment_ranges,
content_start,
content_end,
);
line.in_obsidian_comment = false;
}
// The `%%` delimiters the block covers are comment text, so a
// delimiter below the block opens a comment rather than closing the
// one those appeared to open. Only a rescan pairs them correctly;
// dropping the ranges that start inside the block would leave the
// delimiter below it paired with nothing and unreported.
//
// This is the mirror of the re-resolution above, and it needs no
// second round: the block starts at or after the opener, so the
// pairing before the opener is what it already was, and the opener
// resolved against it cannot change.
let obsidian_rescan = flavor_detection::detect_obsidian_comments(
content,
&mut lines,
flavor,
&code_span_ranges,
&html_comment_ranges,
body_start,
);
obsidian_comment_ranges = obsidian_rescan.ranges;
unterminated_obsidian_comment = obsidian_rescan.unterminated;
}
// Detect MyST role syntax ({role}`content`)
let myst_role_ranges = profile_section!(
"MyST roles",
profile,
flavor_detection::detect_myst_role_ranges(content, &lines, flavor, &code_blocks)
);
// Run pulldown-cmark parse for links, images, and link byte ranges in a single pass.
// Link byte ranges are needed for heading detection; links/images are finalized later
// after code_spans are available.
let pulldown_result = profile_section!(
"Links, images & link ranges",
profile,
link_parser::parse_links_images_pulldown(content, &lines, &code_blocks, flavor, &html_comment_ranges)
);
// Now detect headings and blockquotes
let mut blockquote_headings = profile_section!(
"Headings & blockquotes",
profile,
heading_detection::detect_headings_and_blockquotes(
&content_lines,
&mut lines,
flavor,
&html_comment_ranges,
&pulldown_result.link_byte_ranges,
front_matter_end,
)
);
// Clear headings that were detected inside kramdown extension blocks
for line in &mut lines {
if line.in_kramdown_extension_block {
line.heading = None;
}
}
for (line, heading) in lines.iter().zip(&mut blockquote_headings) {
if line.in_kramdown_extension_block {
*heading = None;
}
}
// A run of `-`, `*` or `_` is a thematic break only because of the block it
// sits in, and that block is known only now: the passes above are what mark
// an HTML comment, an HTML block, a math block, an MDX or Obsidian comment,
// and the colon fences a flavor reads as code. The flag was computed from the
// line text before any of them ran, so it is settled here against the answers
// they produced, the way the kramdown sanitization above settles its own.
//
// Left alone deliberately: containers whose body IS markdown (Pandoc divs,
// MkDocs admonitions and tabs, PyMdown blocks, MyST directives) render a
// thematic break written in them.
for line in &mut lines {
if line.is_horizontal_rule
&& (line.in_code_block
|| line.in_html_block
|| line.in_html_comment
|| line.in_math_block
|| line.in_mdx_comment
|| line.in_obsidian_comment)
{
line.is_horizontal_rule = false;
}
}
// Parse code spans early so we can exclude them from link/image parsing
let mut code_spans = profile_section!(
"Code spans",
profile,
element_parsers::build_code_spans_from_ranges(content, &lines, &code_span_ranges)
);
// Supplement code spans for MkDocs container content that pulldown-cmark missed.
// pulldown-cmark treats 4-space-indented MkDocs content as indented code blocks,
// so backtick code spans within admonitions/tabs/markdown HTML are invisible to it.
if flavor == MarkdownFlavor::MkDocs {
let extra = profile_section!(
"MkDocs code spans",
profile,
element_parsers::scan_mkdocs_container_code_spans(content, &lines, &code_span_ranges,)
);
if !extra.is_empty() {
code_spans.extend(extra);
code_spans.sort_by_key(|span| span.byte_offset);
}
}
// Supplement code spans for MDX JSX component body content that pulldown-cmark missed.
// pulldown-cmark treats JSX component opening tags (e.g. `<ParamField>`) as HTML block
// starters, so backtick code spans within component bodies are invisible to the initial
// parse.
if flavor == MarkdownFlavor::MDX {
let extra = profile_section!(
"MDX JSX code spans",
profile,
element_parsers::scan_jsx_block_code_spans(content, &lines, &code_span_ranges)
);
if !extra.is_empty() {
code_spans.extend(extra);
code_spans.sort_by_key(|span| span.byte_offset);
}
}
// Mark lines that are continuations of multi-line code spans
// This is needed for parse_list_blocks to correctly handle list items with multi-line code spans
for span in &code_spans {
if span.end_line > span.line {
// Mark lines after the first line as continuations
for line_num in (span.line + 1)..=span.end_line {
if let Some(line_info) = lines.get_mut(line_num - 1) {
line_info.in_code_span_continuation = true;
}
}
}
}
// Finalize links and images: filter by code_spans and run regex fallbacks
let (links, images, broken_links, footnote_refs) = profile_section!(
"Links & images finalize",
profile,
link_parser::finalize_links_and_images(
content,
&lines,
&code_blocks,
&code_spans,
flavor,
&html_comment_ranges,
pulldown_result
)
);
let reference_defs = profile_section!(
"Reference defs",
profile,
link_parser::parse_reference_defs(content, &lines)
);
let list_blocks = profile_section!("List blocks", profile, list_blocks::parse_list_blocks(content, &lines));
// Compute character frequency for fast content analysis
let char_frequency = profile_section!(
"Char frequency",
profile,
line_computation::compute_char_frequency(content)
);
// Pre-compute table blocks for rules that need them (MD013, MD055, MD056, MD058, MD060)
let table_blocks = profile_section!(
"Table blocks",
profile,
crate::utils::table_utils::TableUtils::find_table_blocks_with_code_info(
content,
&code_blocks,
&code_spans,
&html_comment_ranges,
flavor,
)
);
// Layer 2: Filter pre-computed collections to exclude items inside kramdown extension blocks.
// Rules that iterate these collections automatically skip kramdown content.
let links = links
.into_iter()
.filter(|link| !lines.get(link.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
.collect::<Vec<_>>();
let images = images
.into_iter()
.filter(|img| !lines.get(img.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
.collect::<Vec<_>>();
let broken_links = broken_links
.into_iter()
.filter(|bl| {
// BrokenLinkInfo has span but no line field; find line from byte offset
let line_idx = line_offsets
.partition_point(|&offset| offset <= bl.span.start)
.saturating_sub(1);
!lines.get(line_idx).is_some_and(|l| l.in_kramdown_extension_block)
})
.collect::<Vec<_>>();
let footnote_refs = footnote_refs
.into_iter()
.filter(|fr| !lines.get(fr.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
.collect::<Vec<_>>();
let reference_defs = reference_defs
.into_iter()
.filter(|def| !lines.get(def.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
.collect::<Vec<_>>();
let list_blocks = list_blocks
.into_iter()
.filter(|block| {
!lines
.get(block.start_line - 1)
.is_some_and(|l| l.in_kramdown_extension_block)
})
.collect::<Vec<_>>();
let table_blocks = table_blocks
.into_iter()
.filter(|block| {
// TableBlock.start_line is 0-indexed
!lines
.get(block.start_line)
.is_some_and(|l| l.in_kramdown_extension_block)
})
.collect::<Vec<_>>();
let emphasis_spans = emphasis_spans
.into_iter()
.filter(|span| !lines.get(span.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
.collect::<Vec<_>>();
// Mark lines covered by a list or table block so is_in_list_block /
// is_in_table_block are O(1) reads (mirrors in_html_block) instead of
// scanning the whole block vector on every call.
for block in &list_blocks {
// ListBlock line numbers are 1-indexed.
for line_num in block.start_line..=block.end_line {
if let Some(li) = lines.get_mut(line_num - 1) {
li.in_list_block = true;
}
}
}
for block in &table_blocks {
// TableBlock line numbers are 0-indexed.
for idx in block.start_line..=block.end_line {
if let Some(li) = lines.get_mut(idx) {
li.in_table_block = true;
}
}
}
// Rebuild reference_defs_map after filtering
let reference_defs_map: HashMap<String, usize> = reference_defs
.iter()
.enumerate()
.map(|(idx, def)| (def.id.to_lowercase(), idx))
.collect();
// Pre-compute sorted link title byte ranges for binary search
let link_title_ranges: Vec<(usize, usize)> = reference_defs
.iter()
.filter_map(|def| match (def.title_byte_start, def.title_byte_end) {
(Some(start), Some(end)) => Some((start, end)),
_ => None,
})
.collect();
// Reuse already-computed line_offsets and code_blocks instead of re-detecting
let line_index = profile_section!(
"Line index",
profile,
crate::utils::range_utils::LineIndex::with_line_starts_and_code_blocks(
content,
line_offsets.clone(),
&code_blocks,
)
);
// Pre-compute Jinja template ranges once for all rules (eliminates O(n*m) in MD011)
let jinja_ranges = profile_section!(
"Jinja ranges",
profile,
crate::utils::jinja_utils::find_jinja_ranges(content)
);
// Pre-compute Pandoc/Quarto citation ranges for Pandoc-compatible flavors
let citation_ranges = profile_section!("Citation ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::find_citation_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc inline footnote ranges for Pandoc-compatible flavors
let inline_footnote_ranges = profile_section!("Inline footnote ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_inline_footnote_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc implicit header reference slugs for Pandoc-compatible flavors
let pandoc_header_slugs = profile_section!("Pandoc header slugs", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::collect_pandoc_header_slugs(content)
} else {
std::collections::HashSet::new()
}
});
// Pre-compute Pandoc example-list marker ranges for Pandoc-compatible flavors
let example_list_marker_ranges = profile_section!("Example list markers", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_example_list_marker_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc example reference ranges for Pandoc-compatible flavors
let example_reference_ranges = profile_section!("Example references", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_example_reference_ranges(content, &example_list_marker_ranges)
} else {
Vec::new()
}
});
// Pre-compute Pandoc subscript (~x~) and superscript (^x^) ranges
let sub_super_ranges = profile_section!("Subscript/superscript ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_subscript_superscript_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc inline code attribute ranges (`code`{.lang}) for Pandoc-compatible flavors
let inline_code_attr_ranges = profile_section!("Inline code attribute ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_inline_code_attr_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc bracketed span ranges ([text]{attrs}) for Pandoc-compatible flavors
let bracketed_span_ranges = profile_section!("Bracketed span ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_bracketed_span_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc line block ranges (| text) for Pandoc-compatible flavors
let line_block_ranges = profile_section!("Line block ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_line_block_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc pipe-table caption ranges (: caption) for Pandoc-compatible flavors
let pipe_table_caption_ranges = profile_section!("Pipe-table caption ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_pipe_table_caption_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc YAML metadata block ranges (--- ... --- or ...) for Pandoc-compatible flavors
let pandoc_metadata_ranges = profile_section!("Pandoc metadata ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_yaml_metadata_block_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc grid-table ranges (+---+---+) for Pandoc-compatible flavors
let grid_table_ranges = profile_section!("Grid table ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_grid_table_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Pandoc multi-line table ranges for Pandoc-compatible flavors
let multi_line_table_ranges = profile_section!("Multi-line table ranges", profile, {
if flavor.is_pandoc_compatible() {
crate::utils::pandoc::detect_multi_line_table_ranges(content)
} else {
Vec::new()
}
});
// Pre-compute Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
let shortcode_ranges = profile_section!("Shortcode ranges", profile, {
use crate::utils::regex_cache::HUGO_SHORTCODE_REGEX;
let mut ranges = Vec::new();
for mat in HUGO_SHORTCODE_REGEX.find_iter(content) {
ranges.push((mat.start(), mat.end()));
}
ranges
});
let inline_config = InlineConfig::from_content_with_code_blocks(content, &code_blocks);
Self {
content,
content_lines,
line_offsets,
code_blocks,
code_block_details,
strong_spans,
line_to_list,
list_start_values,
commonmark_ordered_lists_cache: OnceLock::new(),
lines,
blockquote_headings,
links,
images,
broken_links,
footnote_refs,
reference_defs,
reference_defs_map,
code_spans_cache: OnceLock::from(Arc::new(code_spans)),
math_spans_cache: OnceLock::new(), // Lazy-loaded on first access
math_byte_ranges_cache: OnceLock::new(), // Lazy-loaded on first access
list_blocks,
char_frequency,
html_tags_cache: OnceLock::new(),
jsx_component_tags_cache: OnceLock::new(),
emphasis_spans_cache: OnceLock::from(Arc::new(emphasis_spans)),
bare_urls_cache: OnceLock::new(),
has_mixed_list_nesting_cache: OnceLock::new(),
html_comment_ranges,
table_blocks,
line_index,
jinja_ranges,
flavor,
source_file,
jsx_expression_ranges,
mdx_comment_ranges,
citation_ranges,
pandoc_div_ranges,
colon_fence_details,
inline_footnote_ranges,
pandoc_header_slugs,
example_list_marker_ranges,
example_reference_ranges,
sub_super_ranges,
inline_code_attr_ranges,
bracketed_span_ranges,
line_block_ranges,
pipe_table_caption_ranges,
pandoc_metadata_ranges,
grid_table_ranges,
multi_line_table_ranges,
shortcode_ranges,
link_title_ranges,
code_span_byte_ranges: code_span_ranges,
inline_config,
obsidian_comment_ranges,
unterminated_html_comment,
unterminated_obsidian_comment,
lazy_cont_lines_cache: OnceLock::new(),
myst_directive_ranges,
myst_comment_ranges,
myst_role_ranges,
front_matter_end,
}
}
/// The 1-indexed line number where front matter ends (the closing
/// delimiter line), or 0 when the document has no front matter.
/// Computed once in `new()`; rules must use this instead of re-scanning
/// the content with `FrontMatterUtils`.
pub fn front_matter_end_line(&self) -> usize {
self.front_matter_end
}
/// Binary search for whether `pos` falls inside any range in a sorted, non-overlapping
/// slice of `(start, end)` byte ranges. O(log n) instead of O(n).
#[inline]
fn binary_search_ranges(ranges: &[(usize, usize)], pos: usize) -> bool {
// Find the rightmost range whose start <= pos
let idx = ranges.partition_point(|&(start, _)| start <= pos);
// If idx == 0, no range starts at or before pos
idx > 0 && pos < ranges[idx - 1].1
}
/// Check if a byte position is within a code span. O(log n).
pub fn is_in_code_span_byte(&self, pos: usize) -> bool {
Self::binary_search_ranges(&self.code_span_byte_ranges, pos)
}
/// Check if `pos` is inside any link byte range. O(log n).
pub fn is_in_link(&self, pos: usize) -> bool {
self.link_containing(pos).is_some() || self.image_containing(pos).is_some() || self.is_in_reference_def(pos)
}
/// Check if `pos`` is within a bare URL
pub fn is_in_bare_url(&self, pos: usize) -> bool {
let bare_urls = self.bare_urls();
// Binary search (sorted by byte_offset) for the candidate containing byte_pos
let idx = bare_urls.partition_point(|url| url.byte_offset <= pos);
idx > 0 && pos < bare_urls[idx - 1].byte_end
}
/// Get parsed inline configuration state.
pub fn inline_config(&self) -> &InlineConfig {
&self.inline_config
}
/// Azure DevOps colon code fences (`:::lang … :::`), each with its byte range
/// and the opener's info string. These are detected outside the CommonMark
/// parse, so they never appear in `code_block_details`. Empty for all other
/// flavors.
pub fn colon_fence_details(&self) -> &[CodeBlockDetail] {
&self.colon_fence_details
}
/// Get pre-split content lines, avoiding repeated `content.lines().collect()` allocations.
///
/// Lines are 0-indexed (line 0 corresponds to line number 1 in the document).
pub fn raw_lines(&self) -> &[&'a str] {
&self.content_lines
}
/// Check if a rule is disabled at a specific line number (1-indexed)
///
/// This method checks both persistent disable comments (<!-- rumdl-disable -->)
/// and line-specific comments (<!-- rumdl-disable-line -->, <!-- rumdl-disable-next-line -->).
pub fn is_rule_disabled(&self, rule_name: &str, line_number: usize) -> bool {
self.inline_config.is_rule_disabled(rule_name, line_number)
}
/// Get code spans - computed lazily on first access
pub fn code_spans(&self) -> Arc<Vec<CodeSpan>> {
Arc::clone(
self.code_spans_cache
.get_or_init(|| Arc::new(element_parsers::parse_code_spans(self.content, &self.lines))),
)
}
/// Math byte ranges (`$...$` inline and `$$...$$` display), computed once and
/// cached. Used by `is_in_math_context`; without the cache that helper
/// rescanned the whole document on every call.
pub fn math_byte_ranges(&self) -> &[(usize, usize)] {
self.math_byte_ranges_cache
.get_or_init(|| crate::utils::skip_context::math_byte_ranges(self.content))
}
/// Get math spans - computed lazily on first access
pub fn math_spans(&self) -> Arc<Vec<MathSpan>> {
Arc::clone(
self.math_spans_cache
.get_or_init(|| Arc::new(element_parsers::parse_math_spans(self.content, &self.lines))),
)
}
/// Check if a byte position is within a math span (inline $...$ or display $$...$$)
pub fn is_in_math_span(&self, byte_pos: usize) -> bool {
let math_spans = self.math_spans();
// Binary search: find the last span whose byte_offset <= byte_pos
let idx = math_spans.partition_point(|span| span.byte_offset <= byte_pos);
idx > 0 && byte_pos < math_spans[idx - 1].byte_end
}
/// Get HTML comment ranges - pre-computed during LintContext construction
pub fn html_comment_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
&self.html_comment_ranges
}
/// Byte offset of a `<!--` that no `-->` closes, if the document has one.
///
/// Everything after it is inside the comment as far as the parser is
/// concerned, so no rule sees that text.
pub fn unterminated_html_comment(&self) -> Option<usize> {
self.unterminated_html_comment
}
/// Byte offset of a `%%` that no second `%%` closes, if the document has
/// one. Always `None` outside the Obsidian flavor, where `%%` is ordinary
/// text rather than a comment delimiter.
pub fn unterminated_obsidian_comment(&self) -> Option<usize> {
self.unterminated_obsidian_comment
}
/// Check if a byte position is inside an Obsidian comment
///
/// Returns false for non-Obsidian flavors.
pub fn is_in_obsidian_comment(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.obsidian_comment_ranges, byte_pos)
}
/// Check if a line/column position is inside an Obsidian comment
///
/// Line number is 1-indexed, column is 1-indexed.
/// Returns false for non-Obsidian flavors.
pub fn is_position_in_obsidian_comment(&self, line_num: usize, col: usize) -> bool {
if self.obsidian_comment_ranges.is_empty() {
return false;
}
// Convert line/column (1-indexed, char-based) to byte position
let byte_pos = self.line_index.line_col_to_byte_range(line_num, col).start;
self.is_in_obsidian_comment(byte_pos)
}
/// Get byte ranges of MyST colon directive blocks
pub fn myst_directive_ranges(&self) -> &[(usize, usize)] {
&self.myst_directive_ranges
}
/// Check if a byte position is inside a MyST role (`{role}`content``)
pub fn is_in_myst_role(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.myst_role_ranges, byte_pos)
}
/// Check if a byte position is inside a MyST comment (`% comment`)
pub fn is_in_myst_comment(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.myst_comment_ranges, byte_pos)
}
/// Check if a line (1-indexed) is a MyST colon-fence directive opener (`:::{name} ...`).
///
/// The text after `{name}` on an opener is the directive's argument (an opaque
/// path, URL, or label), not markdown prose. Rules that reformat prose should
/// skip these lines. Returns false for non-MyST flavors and for directive body
/// or closer lines.
pub fn is_myst_colon_directive_opener_line(&self, line_num: usize) -> bool {
if !self.flavor.supports_myst_directives() {
return false;
}
self.lines.get(line_num.wrapping_sub(1)).is_some_and(|info| {
info.in_myst_directive
&& flavor_detection::myst_colon_directive_opener(info.content(self.content)).is_some()
})
}
/// Drop tags that live inside kramdown extension blocks, preserving order.
fn filter_kramdown_tags(&self, tags: Vec<HtmlTag>) -> Vec<HtmlTag> {
tags.into_iter()
.filter(|tag| {
!self
.lines
.get(tag.line - 1)
.is_some_and(|l| l.in_kramdown_extension_block)
})
.collect()
}
/// Get HTML tags - computed lazily on first access.
///
/// JSX component tags (e.g. `<Card .../>`) are excluded so HTML-specific rules
/// keep ignoring them; use [`Self::jsx_component_tags`] to access those. The
/// single underlying parse populates both caches at once.
pub fn html_tags(&self) -> Arc<Vec<HtmlTag>> {
Arc::clone(self.html_tags_cache.get_or_init(|| {
let (html_tags, jsx_component_tags) =
element_parsers::parse_html_tags(self.content, &self.lines, &self.code_blocks, self.flavor);
// Populate the JSX-component cache from the same parse so it is built once.
let _ = self
.jsx_component_tags_cache
.set(Arc::new(self.filter_kramdown_tags(jsx_component_tags)));
Arc::new(self.filter_kramdown_tags(html_tags))
}))
}
/// Get JSX component tags (e.g. `<Card .../>`) - computed lazily, sharing the
/// HTML-tag parse. Always empty for flavors without JSX support.
pub fn jsx_component_tags(&self) -> Arc<Vec<HtmlTag>> {
if let Some(cached) = self.jsx_component_tags_cache.get() {
return Arc::clone(cached);
}
// Trigger the shared parse, which also fills jsx_component_tags_cache.
let _ = self.html_tags();
Arc::clone(
self.jsx_component_tags_cache
.get()
.expect("html_tags() populates jsx_component_tags_cache"),
)
}
/// Get emphasis spans - pre-computed during construction
pub fn emphasis_spans(&self) -> Arc<Vec<EmphasisSpan>> {
Arc::clone(
self.emphasis_spans_cache
.get()
.expect("emphasis_spans_cache initialized during construction"),
)
}
/// Get bare URLs - computed lazily on first access
pub fn bare_urls(&self) -> Arc<Vec<BareUrl>> {
Arc::clone(self.bare_urls_cache.get_or_init(|| {
Arc::new(element_parsers::parse_bare_urls(
self.content,
&self.lines,
&self.code_blocks,
))
}))
}
/// Get lazy continuation lines - computed lazily on first access
pub fn lazy_continuation_lines(&self) -> Arc<Vec<LazyContLine>> {
Arc::clone(self.lazy_cont_lines_cache.get_or_init(|| {
Arc::new(element_parsers::detect_lazy_continuation_lines(
self.content,
&self.lines,
&self.line_offsets,
))
}))
}
/// Check if document has mixed ordered/unordered list nesting.
/// Result is cached after first computation (document-level invariant).
/// This is used by MD007 for smart style auto-detection.
pub fn has_mixed_list_nesting(&self) -> bool {
*self
.has_mixed_list_nesting_cache
.get_or_init(|| self.compute_mixed_list_nesting())
}
/// Internal computation for mixed list nesting (only called once per LintContext).
fn compute_mixed_list_nesting(&self) -> bool {
// Track parent list items by their marker position and type
// Using marker_column instead of indent because it works correctly
// for blockquoted content where indent doesn't account for the prefix
// Stack stores: (marker_column, is_ordered)
let mut stack: Vec<(usize, bool)> = Vec::new();
let mut last_was_blank = false;
for line_info in &self.lines {
// Skip non-content lines (code blocks, frontmatter, HTML comments, etc.)
if line_info.in_code_block
|| line_info.in_front_matter
|| line_info.in_mkdocstrings
|| line_info.in_html_comment
|| line_info.in_mdx_comment
|| line_info.in_esm_block
{
continue;
}
// OPTIMIZATION: Use pre-computed is_blank instead of content().trim()
if line_info.is_blank {
last_was_blank = true;
continue;
}
if let Some(list_item) = &line_info.list_item {
// Normalize column 1 to column 0 (consistent with MD007 check function)
let current_pos = if list_item.marker_column == 1 {
0
} else {
list_item.marker_column
};
// If there was a blank line and this item is at root level, reset stack
if last_was_blank && current_pos == 0 {
stack.clear();
}
last_was_blank = false;
// Pop items at same or greater position (they're siblings or deeper, not parents)
while let Some(&(pos, _)) = stack.last() {
if pos >= current_pos {
stack.pop();
} else {
break;
}
}
// Check if immediate parent has different type - this is mixed nesting
if let Some(&(_, parent_is_ordered)) = stack.last()
&& parent_is_ordered != list_item.is_ordered
{
return true; // Found mixed nesting - early exit
}
stack.push((current_pos, list_item.is_ordered));
} else {
// Non-list line (but not blank) - could be paragraph or other content
last_was_blank = false;
}
}
false
}
/// Map a byte offset to (line, column).
///
/// The column is a 1-indexed *character* offset within the line (rumdl's
/// diagnostic convention), not a byte offset, so it is correct on lines
/// containing multi-byte UTF-8 characters.
pub fn offset_to_line_col(&self, offset: usize) -> (usize, usize) {
match self.line_offsets.binary_search(&offset) {
Ok(line) => (line + 1, 1),
Err(line) => {
let line_start = self.line_offsets.get(line.wrapping_sub(1)).copied().unwrap_or(0);
// Convert the byte offset within the line to a character column.
let col = byte_to_char_count(&self.content[line_start..], offset.saturating_sub(line_start));
(line, col)
}
}
}
/// Return the byte offset at which a 1-indexed source line starts.
///
/// This is the inverse-facing half of [`Self::offset_to_line_col`]. Keeping
/// both conversions on the document prevents rules from depending on the
/// line-index representation or reconstructing it independently.
pub fn line_start_byte(&self, line_number: usize) -> Option<usize> {
self.line_index.get_line_start_byte(line_number)
}
/// Return an empty byte range at a 1-indexed line and character column.
///
/// Columns are character offsets, not UTF-8 byte offsets. Positions past
/// the end of a line clamp to the end of its content; missing lines clamp to
/// the end of the document.
pub fn line_column_byte_range(&self, line_number: usize, column: usize) -> Range<usize> {
self.line_index.line_col_to_byte_range(line_number, column)
}
/// Return a byte range beginning at a 1-indexed line and character column.
///
/// `length` is measured in characters. The result never crosses the line's
/// content boundary and excludes its line ending.
pub fn line_column_byte_range_with_length(&self, line_number: usize, column: usize, length: usize) -> Range<usize> {
self.line_index
.line_col_to_byte_range_with_length(line_number, column, length)
}
/// Return the byte range of a complete 1-indexed line, including its line
/// ending when one is present.
pub fn whole_line_byte_range(&self, line_number: usize) -> Range<usize> {
self.line_index.whole_line_range(line_number)
}
/// Return the byte range between two 1-indexed character columns on a line.
///
/// The range excludes the line ending and clamps both columns to valid
/// character boundaries in the line content.
pub fn line_text_byte_range(&self, line_number: usize, start_column: usize, end_column: usize) -> Range<usize> {
self.line_index.line_text_range(line_number, start_column, end_column)
}
/// Return the byte range of a 1-indexed line's content, excluding its line
/// ending.
pub fn line_content_byte_range(&self, line_number: usize) -> Range<usize> {
self.line_index.line_content_range(line_number)
}
/// Return the byte range spanning complete 1-indexed lines, inclusive.
pub fn line_span_byte_range(&self, start_line: usize, end_line: usize) -> Range<usize> {
self.line_index.multi_line_range(start_line, end_line)
}
/// Check if a position is within a code block or code span. O(log n).
pub fn is_in_code_block_or_span(&self, pos: usize) -> bool {
// Check code blocks first (already uses binary search internally)
if CodeBlockUtils::is_in_code_block_or_span(&self.code_blocks, pos) {
return true;
}
// Check inline code spans via binary search
self.is_byte_offset_in_code_span(pos)
}
/// Get line information by line number (1-indexed)
pub fn line_info(&self, line_num: usize) -> Option<&LineInfo> {
if line_num > 0 {
self.lines.get(line_num - 1)
} else {
None
}
}
/// Parsed links in document order.
pub fn links(&self) -> &[ParsedLink<'a>] {
&self.links
}
/// Parsed images in document order.
pub fn images(&self) -> &[ParsedImage<'a>] {
&self.images
}
/// Broken or undefined reference links in document order.
pub fn broken_links(&self) -> &[BrokenLinkInfo] {
&self.broken_links
}
/// Parsed footnote references in document order.
pub fn footnote_references(&self) -> &[FootnoteRef] {
&self.footnote_refs
}
/// Parsed reference definitions in document order.
pub fn reference_definitions(&self) -> &[ReferenceDef] {
&self.reference_defs
}
/// Links whose opening delimiter starts on `line_number` (1-indexed).
pub fn links_on_line(&self, line_number: usize) -> &[ParsedLink<'a>] {
let start = self.links.partition_point(|link| link.line < line_number);
let end = self.links.partition_point(|link| link.line <= line_number);
&self.links[start..end]
}
/// Images whose opening delimiter starts on `line_number` (1-indexed).
pub fn images_on_line(&self, line_number: usize) -> &[ParsedImage<'a>] {
let start = self.images.partition_point(|image| image.line < line_number);
let end = self.images.partition_point(|image| image.line <= line_number);
&self.images[start..end]
}
/// Find the link that starts at an exact byte offset. O(log n).
pub fn link_starting_at(&self, byte_offset: usize) -> Option<&ParsedLink<'a>> {
self.links
.binary_search_by_key(&byte_offset, |link| link.byte_offset)
.ok()
.map(|index| &self.links[index])
}
/// Find the image that starts at an exact byte offset. O(log n).
pub fn image_starting_at(&self, byte_offset: usize) -> Option<&ParsedImage<'a>> {
self.images
.binary_search_by_key(&byte_offset, |image| image.byte_offset)
.ok()
.map(|index| &self.images[index])
}
/// Find the parsed link containing `byte_offset`. O(log n).
pub fn link_containing(&self, byte_offset: usize) -> Option<&ParsedLink<'a>> {
let index = self.links.partition_point(|link| link.byte_offset <= byte_offset);
self.links
.get(index.checked_sub(1)?)
.filter(|link| byte_offset < link.byte_end)
}
/// Find the parsed image containing `byte_offset`. O(log n).
pub fn image_containing(&self, byte_offset: usize) -> Option<&ParsedImage<'a>> {
let index = self.images.partition_point(|image| image.byte_offset <= byte_offset);
self.images
.get(index.checked_sub(1)?)
.filter(|image| byte_offset < image.byte_end)
}
/// Links that start at or before `byte_offset`, in document order. O(log n).
pub fn links_starting_before_or_at(&self, byte_offset: usize) -> &[ParsedLink<'a>] {
let end = self.links.partition_point(|link| link.byte_offset <= byte_offset);
&self.links[..end]
}
/// Find a reference definition by its case-insensitive identifier.
pub fn reference_definition(&self, ref_id: &str) -> Option<&ReferenceDef> {
let normalized_id = ref_id.to_lowercase();
self.reference_defs_map
.get(&normalized_id)
.map(|&index| &self.reference_defs[index])
}
/// Get URL for a reference link/image by its ID (O(1) lookup via HashMap)
pub fn get_reference_url(&self, ref_id: &str) -> Option<&str> {
self.reference_definition(ref_id)
.map(|definition| definition.url.as_str())
}
/// Check if a line is part of a list block
pub fn is_in_list_block(&self, line_num: usize) -> bool {
if line_num == 0 || line_num > self.lines.len() {
return false;
}
self.lines[line_num - 1].in_list_block
}
/// Check if a line is within an HTML block
pub fn is_in_html_block(&self, line_num: usize) -> bool {
if line_num == 0 || line_num > self.lines.len() {
return false;
}
self.lines[line_num - 1].in_html_block
}
/// Check if a 1-indexed line number is inside a GFM table block.
///
/// Returns `true` for the header line, delimiter line, and all body rows.
/// `TableBlock` spans are stored 0-indexed; this helper accepts the
/// 1-indexed line numbers used elsewhere in the rule API.
pub fn is_in_table_block(&self, line_num: usize) -> bool {
if line_num == 0 || line_num > self.lines.len() {
return false;
}
self.lines[line_num - 1].in_table_block
}
/// Check if a line and column is within a code span
pub fn is_in_code_span(&self, line_num: usize, col: usize) -> bool {
if line_num == 0 || line_num > self.lines.len() {
return false;
}
// Use the code spans cache to check
// Note: col is 1-indexed from caller, but span.start_col and span.end_col are 0-indexed
// Convert col to 0-indexed for comparison
let col_0indexed = if col > 0 { col - 1 } else { 0 };
let code_spans = self.code_spans();
code_spans.iter().any(|span| {
// Check if line is within the span's line range
if line_num < span.line || line_num > span.end_line {
return false;
}
if span.line == span.end_line {
// Single-line span: check column bounds
col_0indexed >= span.start_col && col_0indexed < span.end_col
} else if line_num == span.line {
// First line of multi-line span: anything after start_col is in span
col_0indexed >= span.start_col
} else if line_num == span.end_line {
// Last line of multi-line span: anything before end_col is in span
col_0indexed < span.end_col
} else {
// Middle line of multi-line span: entire line is in span
true
}
})
}
/// Check if a byte offset is within a code span. O(log n).
#[inline]
pub fn is_byte_offset_in_code_span(&self, byte_offset: usize) -> bool {
let code_spans = self.code_spans();
let idx = code_spans.partition_point(|span| span.byte_offset <= byte_offset);
idx > 0 && byte_offset < code_spans[idx - 1].byte_end
}
/// Check if a byte position is within a reference definition. O(log n).
#[inline]
pub fn is_in_reference_def(&self, byte_pos: usize) -> bool {
let idx = self.reference_defs.partition_point(|rd| rd.byte_offset <= byte_pos);
idx > 0 && byte_pos < self.reference_defs[idx - 1].byte_end
}
/// Check if a byte position is within an HTML comment. O(log n).
#[inline]
pub fn is_in_html_comment(&self, byte_pos: usize) -> bool {
let idx = self.html_comment_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.html_comment_ranges[idx - 1].end
}
/// Check if a byte position is within an HTML tag (including multiline tags).
/// Uses the pre-parsed html_tags which correctly handles tags spanning multiple lines. O(log n).
#[inline]
pub fn is_in_html_tag(&self, byte_pos: usize) -> bool {
let tags = self.html_tags();
let idx = tags.partition_point(|tag| tag.byte_offset <= byte_pos);
idx > 0 && byte_pos < tags[idx - 1].byte_end
}
/// Check if a byte position is within a JSX component tag (e.g. `<Card .../>`),
/// including its attribute values and multiline tags. Always false for flavors
/// without JSX support. O(log n).
#[inline]
pub fn is_in_jsx_component_tag(&self, byte_pos: usize) -> bool {
if !self.flavor.supports_jsx() {
return false;
}
let tags = self.jsx_component_tags();
let idx = tags.partition_point(|tag| tag.byte_offset <= byte_pos);
idx > 0 && byte_pos < tags[idx - 1].byte_end
}
/// Check if a byte position is within a Jinja template ({{ }} or {% %}). O(log n).
pub fn is_in_jinja_range(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.jinja_ranges, byte_pos)
}
/// Check if a byte position is within a JSX expression (MDX: {expression}). O(log n).
#[inline]
pub fn is_in_jsx_expression(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.jsx_expression_ranges, byte_pos)
}
/// Check if a byte position is within an MDX comment ({/* ... */}). O(log n).
#[inline]
pub fn is_in_mdx_comment(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.mdx_comment_ranges, byte_pos)
}
/// Check if a byte position is within a Pandoc/Quarto citation (`@key` or `[@key]`).
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_citation(&self, byte_pos: usize) -> bool {
let idx = self.citation_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.citation_ranges[idx - 1].end
}
/// Pre-computed Pandoc/Quarto citation ranges.
#[inline]
pub fn citation_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
&self.citation_ranges
}
/// Check if a byte position is within a Pandoc/Quarto div block (`::: ... :::`).
/// Active for Pandoc-compatible flavors. O(log n) via binary search over sorted ranges.
#[inline]
pub fn is_in_div_block(&self, byte_pos: usize) -> bool {
let idx = self.pandoc_div_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.pandoc_div_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc inline footnote (`^[note text]`).
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_inline_footnote(&self, byte_pos: usize) -> bool {
let idx = self.inline_footnote_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.inline_footnote_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc example-list marker (`(@)` /
/// `(@label)` at line start). Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_example_list_marker(&self, byte_pos: usize) -> bool {
let idx = self.example_list_marker_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.example_list_marker_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc example reference (`(@label)`
/// inline). Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_example_reference(&self, byte_pos: usize) -> bool {
let idx = self.example_reference_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.example_reference_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc subscript (`~x~`) or
/// superscript (`^x^`) span. Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_subscript_or_superscript(&self, byte_pos: usize) -> bool {
let idx = self.sub_super_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.sub_super_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc inline-code attribute block
/// (`{.lang}` immediately following `` `code` ``). Active for Pandoc-compatible
/// flavors. O(log n).
#[inline]
pub fn is_in_inline_code_attr(&self, byte_pos: usize) -> bool {
let idx = self.inline_code_attr_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.inline_code_attr_ranges[idx - 1].end
}
/// Check if a byte position is within a Pandoc bracketed span (`[text]{attrs}`).
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_bracketed_span(&self, byte_pos: usize) -> bool {
let idx = self.bracketed_span_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.bracketed_span_ranges[idx - 1].end
}
/// Returns true if `byte_pos` falls inside a Pandoc line block (`| text`).
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_line_block(&self, byte_pos: usize) -> bool {
let idx = self.line_block_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.line_block_ranges[idx - 1].end
}
/// Returns true if `byte_pos` falls inside a Pandoc pipe-table caption
/// (`: caption` adjacent to a pipe table). Active for Pandoc-compatible
/// flavors. O(log n).
#[inline]
pub fn is_in_pipe_table_caption(&self, byte_pos: usize) -> bool {
let idx = self.pipe_table_caption_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.pipe_table_caption_ranges[idx - 1].end
}
/// Returns true if `byte_pos` falls inside a Pandoc YAML metadata block.
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_pandoc_metadata(&self, byte_pos: usize) -> bool {
let idx = self.pandoc_metadata_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.pandoc_metadata_ranges[idx - 1].end
}
/// Returns true if `byte_pos` falls inside a Pandoc grid table.
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_grid_table(&self, byte_pos: usize) -> bool {
let idx = self.grid_table_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.grid_table_ranges[idx - 1].end
}
/// Returns true if `byte_pos` falls inside a Pandoc multi-line table.
/// Active for Pandoc-compatible flavors. O(log n).
#[inline]
pub fn is_in_multi_line_table(&self, byte_pos: usize) -> bool {
let idx = self.multi_line_table_ranges.partition_point(|r| r.start <= byte_pos);
idx > 0 && byte_pos < self.multi_line_table_ranges[idx - 1].end
}
/// Returns true if `link_text`, after Pandoc slugification, matches a heading
/// in the document. Returns false for non-Pandoc-compatible flavors because
/// the `pandoc_header_slugs` set is empty when the pre-pass detector is gated
/// off. Use this when the caller has raw bracketed text (`[Section name]`).
pub fn matches_implicit_header_reference(&self, link_text: &str) -> bool {
let slug = crate::utils::pandoc::pandoc_header_slug(link_text);
self.pandoc_header_slugs.contains(&slug)
}
/// Returns true if `slug` (already in Pandoc-slug form) matches a heading
/// in the document. Returns false for non-Pandoc-compatible flavors because
/// the `pandoc_header_slugs` set is empty when the pre-pass detector is gated
/// off. Use this when the caller already has a slug (e.g. the fragment of a
/// URL after `#`). O(1).
#[inline]
pub fn has_pandoc_slug(&self, slug: &str) -> bool {
self.pandoc_header_slugs.contains(slug)
}
/// Check if a byte position is within a Hugo/Quarto shortcode ({{< ... >}} or {{% ... %}}). O(log n).
#[inline]
pub fn is_in_shortcode(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.shortcode_ranges, byte_pos)
}
/// Pre-computed Hugo/Quarto shortcode ranges.
#[inline]
pub fn shortcode_ranges(&self) -> &[(usize, usize)] {
&self.shortcode_ranges
}
/// Check if a byte position is within a link reference definition title. O(log n).
pub fn is_in_link_title(&self, byte_pos: usize) -> bool {
Self::binary_search_ranges(&self.link_title_ranges, byte_pos)
}
/// Check if content has any instances of a specific character (fast)
pub fn has_char(&self, ch: char) -> bool {
match ch {
'#' => self.char_frequency.hash_count > 0,
'*' => self.char_frequency.asterisk_count > 0,
'_' => self.char_frequency.underscore_count > 0,
'-' => self.char_frequency.hyphen_count > 0,
'+' => self.char_frequency.plus_count > 0,
'>' => self.char_frequency.gt_count > 0,
'|' => self.char_frequency.pipe_count > 0,
'[' => self.char_frequency.bracket_count > 0,
'`' => self.char_frequency.backtick_count > 0,
'<' => self.char_frequency.lt_count > 0,
'!' => self.char_frequency.exclamation_count > 0,
'\n' => self.char_frequency.newline_count > 0,
_ => self.content.contains(ch), // Fallback for other characters
}
}
/// Get count of a specific character (fast)
pub fn char_count(&self, ch: char) -> usize {
match ch {
'#' => self.char_frequency.hash_count,
'*' => self.char_frequency.asterisk_count,
'_' => self.char_frequency.underscore_count,
'-' => self.char_frequency.hyphen_count,
'+' => self.char_frequency.plus_count,
'>' => self.char_frequency.gt_count,
'|' => self.char_frequency.pipe_count,
'[' => self.char_frequency.bracket_count,
'`' => self.char_frequency.backtick_count,
'<' => self.char_frequency.lt_count,
'!' => self.char_frequency.exclamation_count,
'\n' => self.char_frequency.newline_count,
_ => self.content.matches(ch).count(), // Fallback for other characters
}
}
/// Check if content likely contains headings (fast)
pub fn likely_has_headings(&self) -> bool {
self.char_frequency.hash_count > 0 || self.char_frequency.hyphen_count > 2 || self.content.contains('=') // Setext H1 underlines use '='
}
/// Check if content likely contains lists (fast)
pub fn likely_has_lists(&self) -> bool {
self.char_frequency.asterisk_count > 0
|| self.char_frequency.hyphen_count > 0
|| self.char_frequency.plus_count > 0
}
/// Check if content likely contains emphasis (fast)
pub fn likely_has_emphasis(&self) -> bool {
self.char_frequency.asterisk_count > 1 || self.char_frequency.underscore_count > 1
}
/// Check if content likely contains tables (fast)
pub fn likely_has_tables(&self) -> bool {
self.char_frequency.pipe_count > 2
}
/// Check if content likely contains blockquotes (fast)
pub fn likely_has_blockquotes(&self) -> bool {
self.char_frequency.gt_count > 0
}
/// Check if content likely contains code (fast)
pub fn likely_has_code(&self) -> bool {
self.char_frequency.backtick_count > 0
}
/// Check if content likely contains links or images (fast)
pub fn likely_has_links_or_images(&self) -> bool {
self.char_frequency.bracket_count > 0 || self.char_frequency.exclamation_count > 0
}
/// Check if content likely contains HTML (fast)
pub fn likely_has_html(&self) -> bool {
self.char_frequency.lt_count > 0
}
/// Get the blockquote prefix for inserting a blank line at the given line index.
/// Returns the prefix without trailing content (e.g., ">" or ">>").
/// This is needed because blank lines inside blockquotes must preserve the blockquote structure.
/// Returns an empty string if the line is not inside a blockquote.
pub fn blockquote_prefix_for_blank_line(&self, line_idx: usize) -> String {
if let Some(line_info) = self.lines.get(line_idx)
&& let Some(ref bq) = line_info.blockquote
{
bq.prefix.trim_end().to_string()
} else {
String::new()
}
}
/// Find the line index for a given byte offset using binary search.
/// Returns (line_index, line_number, column) where:
/// - line_index is the 0-based index in the lines array
/// - line_number is the 1-based line number
/// - column is the 0-based *character* offset within that line
///
/// The column is a character offset rather than a byte offset so that the
/// `start_col`/`end_col` it feeds into match rumdl's diagnostic convention
/// (columns are character positions). On lines with multi-byte UTF-8
/// characters the two differ; reporting bytes would mis-position highlights.
#[inline]
fn find_line_for_offset(lines: &[LineInfo], content: &str, byte_offset: usize) -> (usize, usize, usize) {
// Binary search to find the line containing this byte offset
let idx = match lines.binary_search_by(|line| {
if byte_offset < line.byte_offset {
std::cmp::Ordering::Greater
} else if byte_offset > line.byte_offset + line.byte_len {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Equal
}
}) {
Ok(idx) => idx,
Err(idx) => idx.saturating_sub(1),
};
let line = &lines[idx];
let line_num = idx + 1;
let byte_col = byte_offset.saturating_sub(line.byte_offset);
// Convert the byte offset within the line to a 0-based character column.
// `byte_to_char_count` returns a 1-based value, so subtract 1.
let col = byte_to_char_count(line.content(content), byte_col) - 1;
(idx, line_num, col)
}
/// Check if a byte offset is within a code span using binary search
#[inline]
fn is_offset_in_code_span(code_spans: &[CodeSpan], offset: usize) -> bool {
// Since spans are sorted by byte_offset, use partition_point for binary search
let idx = code_spans.partition_point(|span| span.byte_offset <= offset);
// Check the span that starts at or before our offset
if idx > 0 {
let span = &code_spans[idx - 1];
if offset >= span.byte_offset && offset < span.byte_end {
return true;
}
}
false
}
/// Get an iterator over valid headings (skipping invalid ones like `#NoSpace`)
///
/// Valid headings have proper spacing after the `#` markers (or are level > 1).
/// This is the standard iterator for rules that need to process headings.
///
/// # Examples
///
/// ```
/// use rumdl_lib::lint_context::LintContext;
/// use rumdl_lib::config::MarkdownFlavor;
///
/// let content = "# Valid Heading\n#NoSpace\n## Another Valid";
/// let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
///
/// for heading in ctx.valid_headings() {
/// println!("Line {}: {} (level {})", heading.line_num, heading.heading.text, heading.heading.level);
/// }
/// // Only prints valid headings, skips `#NoSpace`
/// ```
#[must_use]
pub fn valid_headings(&self) -> ValidHeadingsIter<'_> {
ValidHeadingsIter::new(&self.lines)
}
/// Check if the document contains any valid CommonMark headings
///
/// Returns `true` if there is at least one heading with proper space after `#`.
#[must_use]
pub fn has_valid_headings(&self) -> bool {
self.lines
.iter()
.any(|line| line.heading.as_ref().is_some_and(|h| h.is_valid))
}
/// Iterate over every parsed list item in source order.
#[must_use]
pub fn list_items(&self) -> ParsedListItemsIter<'_> {
ParsedListItemsIter::new(&self.lines)
}
/// Return the parsed list item on a 1-indexed source line, if any.
#[must_use]
pub fn list_item_on_line(&self, line_num: usize) -> Option<ParsedListItem<'_>> {
let line_info = self.lines.get(line_num.checked_sub(1)?)?;
Some(ParsedListItem::new(
line_num,
line_info.list_item.as_deref()?,
line_info,
))
}
/// Borrow the document's parsed list blocks and their item iterators.
#[must_use]
pub fn parsed_list_blocks(&self) -> ParsedListBlocks<'_> {
ParsedListBlocks::new(&self.list_blocks, &self.lines)
}
/// The item lines of `block` grouped into the lists they form, one group
/// per list as CommonMark nests them, in source order, so siblings can be
/// compared without the nested items that sit between them.
#[must_use]
pub fn list_block_item_groups(&self, block: &ListBlock) -> Vec<Vec<usize>> {
list_blocks::item_lines_by_list(self.content, &self.lines, block)
}
/// Whether the document contains any parsed list items.
#[must_use]
pub fn has_list_items(&self) -> bool {
self.lines.iter().any(|line| line.list_item.is_some())
}
/// Whether the document contains any parsed unordered-list items.
#[must_use]
pub fn has_unordered_list_items(&self) -> bool {
self.lines
.iter()
.any(|line| line.list_item.as_ref().is_some_and(|item| !item.is_ordered))
}
/// Borrow ordered lists using the membership and start values determined by CommonMark.
#[must_use]
pub fn commonmark_ordered_lists(&self) -> CommonMarkOrderedLists<'_> {
let lists = self
.commonmark_ordered_lists_cache
.get_or_init(|| build_commonmark_ordered_lists(&self.lines, &self.line_to_list, &self.list_start_values));
CommonMarkOrderedLists::new(lists, &self.lines)
}
/// Iterate over every heading recognized in the rendered document.
///
/// This includes top-level ATX and Setext headings, ATX headings nested in
/// blockquotes, and malformed top-level ATX headings retained for
/// diagnostics. Code blocks, front matter, raw HTML blocks, and
/// flavor-specific non-Markdown regions are excluded during parsing;
/// explicitly Markdown-enabled HTML containers remain eligible.
#[must_use]
pub fn headings(&self) -> ParsedHeadingsIter<'_> {
ParsedHeadingsIter::new(&self.lines, &self.blockquote_headings)
}
/// Return the parsed heading on a 1-indexed source line, if any.
#[must_use]
pub fn heading_on_line(&self, line_num: usize) -> Option<ParsedHeading<'_>> {
let idx = line_num.checked_sub(1)?;
let line_info = self.lines.get(idx)?;
let (heading, blockquote_depth) = match line_info.heading.as_deref() {
Some(heading) => (heading, 0),
None => (
self.blockquote_headings.get(idx)?.as_deref()?,
line_info.blockquote.as_ref().map_or(0, |bq| bq.nesting_level),
),
};
Some(ParsedHeading {
line_num,
heading,
line_info,
blockquote_depth,
})
}
}
/// The range an unclosed `<!--` hides when it opens a block the parser missed.
///
/// A MkDocs admonition or a `<div markdown>` body is rendered as markdown in its
/// own right, so a `<!--` starting one of its lines opens an HTML block there
/// just as it would at the top level. The parser has no notion of either
/// container, reads the body as indented code or as a lazy paragraph
/// continuation, and so reports no block for the opener to run to the end of.
///
/// The block ends where the container's body ends, which is what CommonMark
/// gives an unclosed comment in any other container. An opener that is not the
/// first thing on its line is inline HTML and opens nothing, here as anywhere.
fn container_comment_range(
opener: usize,
containers: &flavor_detection::ContainerLines,
lines: &[types::LineInfo],
content: &str,
) -> Option<crate::utils::skip_context::ByteRange> {
let line_index = lines
.partition_point(|line| line.byte_offset <= opener)
.checked_sub(1)?;
let line = lines.get(line_index)?;
if line.byte_offset + line.indent != opener {
return None;
}
if !containers.is_container_body(line_index) {
return None;
}
let end_line = lines.get(containers.body_end_line(line_index)?)?;
Some(crate::utils::skip_context::ByteRange {
start: opener,
end: (end_line.byte_offset + end_line.byte_len).min(content.len()),
})
}
/// Detect footnote definitions and mark their continuation lines.
///
/// Uses pulldown-cmark to find footnote definition ranges and fenced code
/// blocks within them, then:
/// 1. Sets `in_footnote_definition = true` on all lines within
/// 2. Clears `in_code_block = false` on continuation lines that were
/// misidentified as indented code blocks (but preserves real fenced
/// code blocks within footnotes)
fn detect_footnote_definitions(content: &str, lines: &mut [types::LineInfo], line_offsets: &[usize]) {
use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag, TagEnd};
let options = crate::utils::rumdl_parser_options();
let parser = Parser::new_ext(content, options).into_offset_iter();
// Collect footnote ranges and fenced code block ranges within them
let mut footnote_ranges: Vec<(usize, usize)> = Vec::new();
let mut fenced_code_ranges: Vec<(usize, usize)> = Vec::new();
let mut in_footnote = false;
for (event, range) in parser {
match event {
Event::Start(Tag::FootnoteDefinition(_)) => {
in_footnote = true;
footnote_ranges.push((range.start, range.end));
}
Event::End(TagEnd::FootnoteDefinition) => {
in_footnote = false;
}
Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(_))) if in_footnote => {
fenced_code_ranges.push((range.start, range.end));
}
_ => {}
}
}
let byte_to_line = |byte_offset: usize| -> usize {
line_offsets
.partition_point(|&offset| offset <= byte_offset)
.saturating_sub(1)
};
// Mark footnote definition lines
for &(start, end) in &footnote_ranges {
let start_line = byte_to_line(start);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
for line in &mut lines[start_line..end_line] {
line.in_footnote_definition = true;
line.in_code_block = false;
}
}
// Restore in_code_block for fenced code blocks within footnotes
for &(start, end) in &fenced_code_ranges {
let start_line = byte_to_line(start);
let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
for line in &mut lines[start_line..end_line] {
line.in_code_block = true;
}
}
}