rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
/// Rule MD013: Line length
///
/// See [docs/md013.md](../../docs/md013.md) for full documentation, configuration, and examples.
use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::rule_config_serde::RuleConfig;
use crate::utils::mkdocs_admonitions;
use crate::utils::mkdocs_attr_list::is_standalone_attr_list;
use crate::utils::mkdocs_snippets::is_snippet_block_delimiter;
use crate::utils::mkdocs_tabs;
use crate::utils::range_utils::LineIndex;
use crate::utils::range_utils::calculate_excess_range;
use crate::utils::regex_cache::{IMAGE_REF_PATTERN, LINK_REF_PATTERN, URL_PATTERN};
use crate::utils::table_utils::TableUtils;
use crate::utils::text_reflow::{
    BlockquoteLineData, ReflowLengthMode, blockquote_continuation_style, dominant_blockquote_prefix,
    reflow_blockquote_content, split_into_sentences,
};
use pulldown_cmark::LinkType;
use toml;

mod helpers;
pub mod md013_config;
use crate::utils::is_template_directive_only;
use helpers::{
    extract_list_marker_and_content, has_hard_break, is_github_alert_marker, is_horizontal_rule, is_list_item,
    is_standalone_link_or_image_line, split_into_segments, trim_preserving_hard_break,
};
pub use md013_config::MD013Config;
use md013_config::{LengthMode, ReflowMode};

#[cfg(test)]
mod tests;
use unicode_width::UnicodeWidthStr;

#[derive(Clone, Default)]
pub struct MD013LineLength {
    pub(crate) config: MD013Config,
}

/// Blockquote paragraph line collected for reflow, with original line index for range computation.
struct CollectedBlockquoteLine {
    line_idx: usize,
    data: BlockquoteLineData,
}

impl MD013LineLength {
    pub fn new(line_length: usize, code_blocks: bool, tables: bool, headings: bool, strict: bool) -> Self {
        Self {
            config: MD013Config {
                line_length: crate::types::LineLength::new(line_length),
                code_blocks,
                tables,
                headings,
                paragraphs: true, // Default to true for backwards compatibility
                strict,
                reflow: false,
                reflow_mode: ReflowMode::default(),
                length_mode: LengthMode::default(),
                abbreviations: Vec::new(),
                require_sentence_capital: true,
            },
        }
    }

    pub fn from_config_struct(config: MD013Config) -> Self {
        Self { config }
    }

    /// Return a clone with code block checking disabled.
    /// Used for doc comment linting where code blocks are Rust code managed by rustfmt.
    pub fn with_code_blocks_disabled(&self) -> Self {
        let mut clone = self.clone();
        clone.config.code_blocks = false;
        clone
    }

    /// Convert MD013 LengthMode to text_reflow ReflowLengthMode
    fn reflow_length_mode(&self) -> ReflowLengthMode {
        match self.config.length_mode {
            LengthMode::Chars => ReflowLengthMode::Chars,
            LengthMode::Visual => ReflowLengthMode::Visual,
            LengthMode::Bytes => ReflowLengthMode::Bytes,
        }
    }

    fn should_ignore_line(
        &self,
        line: &str,
        _lines: &[&str],
        current_line: usize,
        ctx: &crate::lint_context::LintContext,
    ) -> bool {
        if self.config.strict {
            return false;
        }

        // Quick check for common patterns before expensive regex
        let trimmed = line.trim();

        // Only skip if the entire line is a URL (quick check first)
        if (trimmed.starts_with("http://") || trimmed.starts_with("https://")) && URL_PATTERN.is_match(trimmed) {
            return true;
        }

        // Only skip if the entire line is an image reference (quick check first)
        if trimmed.starts_with("![") && trimmed.ends_with(']') && IMAGE_REF_PATTERN.is_match(trimmed) {
            return true;
        }

        // Note: link reference definitions are handled as always-exempt (even in strict mode)
        // in the main check loop, so they don't need to be checked here.

        // Code blocks with long strings (only check if in code block)
        if ctx.line_info(current_line + 1).is_some_and(|info| info.in_code_block)
            && !trimmed.is_empty()
            && !line.contains(' ')
            && !line.contains('\t')
        {
            return true;
        }

        false
    }

    /// Check if rule should skip based on provided config (used for inline config support)
    fn should_skip_with_config(&self, ctx: &crate::lint_context::LintContext, config: &MD013Config) -> bool {
        // Skip if content is empty
        if ctx.content.is_empty() {
            return true;
        }

        // For sentence-per-line, semantic-line-breaks, or normalize mode, never skip based on line length
        if config.reflow
            && (config.reflow_mode == ReflowMode::SentencePerLine
                || config.reflow_mode == ReflowMode::SemanticLineBreaks
                || config.reflow_mode == ReflowMode::Normalize)
        {
            return false;
        }

        // Quick check: if total content is shorter than line limit, definitely skip
        if ctx.content.len() <= config.line_length.get() {
            return true;
        }

        // Skip if no line exceeds the limit
        !ctx.lines.iter().any(|line| line.byte_len > config.line_length.get())
    }
}

impl Rule for MD013LineLength {
    fn name(&self) -> &'static str {
        "MD013"
    }

    fn description(&self) -> &'static str {
        "Line length should not be excessive"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        // Use pre-parsed inline config from LintContext
        let config_override = ctx.inline_config().get_rule_config("MD013");

        // Apply configuration override if present
        let effective_config = if let Some(json_config) = config_override {
            if let Some(obj) = json_config.as_object() {
                let mut config = self.config.clone();
                if let Some(line_length) = obj.get("line_length").and_then(|v| v.as_u64()) {
                    config.line_length = crate::types::LineLength::new(line_length as usize);
                }
                if let Some(code_blocks) = obj.get("code_blocks").and_then(|v| v.as_bool()) {
                    config.code_blocks = code_blocks;
                }
                if let Some(tables) = obj.get("tables").and_then(|v| v.as_bool()) {
                    config.tables = tables;
                }
                if let Some(headings) = obj.get("headings").and_then(|v| v.as_bool()) {
                    config.headings = headings;
                }
                if let Some(strict) = obj.get("strict").and_then(|v| v.as_bool()) {
                    config.strict = strict;
                }
                if let Some(reflow) = obj.get("reflow").and_then(|v| v.as_bool()) {
                    config.reflow = reflow;
                }
                if let Some(reflow_mode) = obj.get("reflow_mode").and_then(|v| v.as_str()) {
                    config.reflow_mode = match reflow_mode {
                        "default" => ReflowMode::Default,
                        "normalize" => ReflowMode::Normalize,
                        "sentence-per-line" => ReflowMode::SentencePerLine,
                        "semantic-line-breaks" => ReflowMode::SemanticLineBreaks,
                        _ => ReflowMode::default(),
                    };
                }
                config
            } else {
                self.config.clone()
            }
        } else {
            self.config.clone()
        };

        // Fast early return using should_skip with EFFECTIVE config (after inline overrides)
        // But don't skip if we're in reflow mode with Normalize or SentencePerLine
        if self.should_skip_with_config(ctx, &effective_config)
            && !(effective_config.reflow
                && (effective_config.reflow_mode == ReflowMode::Normalize
                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
        {
            return Ok(Vec::new());
        }

        // Direct implementation without DocumentStructure
        let mut warnings = Vec::new();

        // Special handling: line_length = 0 means "no line length limit"
        // Skip all line length checks, but still allow reflow if enabled
        let skip_length_checks = effective_config.line_length.is_unlimited();

        // Pre-filter lines that could be problematic to avoid processing all lines
        let mut candidate_lines = Vec::new();
        if !skip_length_checks {
            for (line_idx, line_info) in ctx.lines.iter().enumerate() {
                // Skip front matter - it should never be linted
                if line_info.in_front_matter {
                    continue;
                }

                // Quick length check first
                if line_info.byte_len > effective_config.line_length.get() {
                    candidate_lines.push(line_idx);
                }
            }
        }

        // If no candidate lines and not in normalize or sentence-per-line mode, early return
        if candidate_lines.is_empty()
            && !(effective_config.reflow
                && (effective_config.reflow_mode == ReflowMode::Normalize
                    || effective_config.reflow_mode == ReflowMode::SentencePerLine
                    || effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
        {
            return Ok(warnings);
        }

        let lines = ctx.raw_lines();

        // Create a quick lookup set for heading lines
        // We need this for both the heading skip check AND the paragraphs check
        let heading_lines_set: std::collections::HashSet<usize> = ctx
            .lines
            .iter()
            .enumerate()
            .filter(|(_, line)| line.heading.is_some())
            .map(|(idx, _)| idx + 1)
            .collect();

        // Use pre-computed table blocks from context
        // We need this for both the table skip check AND the paragraphs check
        let table_blocks = &ctx.table_blocks;
        let mut table_lines_set = std::collections::HashSet::new();
        for table in table_blocks {
            table_lines_set.insert(table.header_line + 1);
            table_lines_set.insert(table.delimiter_line + 1);
            for &line in &table.content_lines {
                table_lines_set.insert(line + 1);
            }
        }

        // Process candidate lines for line length checks
        for &line_idx in &candidate_lines {
            let line_number = line_idx + 1;
            let line = lines[line_idx];

            // Calculate actual line length (used in warning messages)
            let effective_length = self.calculate_effective_length(line);

            // Use single line length limit for all content
            let line_limit = effective_config.line_length.get();

            // In non-strict mode, forgive the trailing non-whitespace run.
            // If the line only exceeds the limit because of a long token at the end
            // (URL, link chain, identifier), it passes. This matches markdownlint's
            // behavior: line.replace(/\S*$/u, "#")
            let check_length = if effective_config.strict {
                effective_length
            } else {
                match line.rfind(char::is_whitespace) {
                    Some(pos) => {
                        let ws_char = line[pos..].chars().next().unwrap();
                        let prefix_end = pos + ws_char.len_utf8();
                        self.calculate_string_length(&line[..prefix_end]) + 1
                    }
                    None => 1, // No whitespace — entire line is a single token
                }
            };

            // Skip lines where the check length is within the limit
            if check_length <= line_limit {
                continue;
            }

            // Semantic link understanding: suppress when excess comes entirely from inline URLs
            if !effective_config.strict {
                let text_only_length = self.calculate_text_only_length(effective_length, line_number, ctx);
                if text_only_length <= line_limit {
                    continue;
                }
            }

            // Skip mkdocstrings and pymdown blocks (already handled by LintContext)
            if ctx.lines[line_idx].in_mkdocstrings || ctx.lines[line_idx].in_pymdown_block {
                continue;
            }

            // Link reference definitions are always exempt, even in strict mode.
            // There's no way to shorten them without breaking the URL.
            // Also check after stripping list markers, since list items may
            // contain link ref defs as their content.
            {
                let trimmed = line.trim();
                if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
                    continue;
                }
                if is_list_item(trimmed) {
                    let (_, content) = extract_list_marker_and_content(trimmed);
                    let content_trimmed = content.trim();
                    if content_trimmed.starts_with('[')
                        && content_trimmed.contains("]:")
                        && LINK_REF_PATTERN.is_match(content_trimmed)
                    {
                        continue;
                    }
                }
            }

            // Skip various block types efficiently
            if !effective_config.strict {
                // Lines whose only content is a link/image are exempt.
                // After stripping list markers, blockquote markers, and emphasis,
                // if only a link or image remains, there is no way to shorten it.
                if is_standalone_link_or_image_line(line) {
                    continue;
                }

                // Skip setext heading underlines
                if !line.trim().is_empty() && line.trim().chars().all(|c| c == '=' || c == '-') {
                    continue;
                }

                // Skip block elements according to config flags
                // The flags mean: true = check these elements, false = skip these elements
                // So we skip when the flag is FALSE and the line is in that element type
                if (!effective_config.headings && heading_lines_set.contains(&line_number))
                    || (!effective_config.code_blocks
                        && ctx.line_info(line_number).is_some_and(|info| info.in_code_block))
                    || (!effective_config.tables && table_lines_set.contains(&line_number))
                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
                    || ctx.line_info(line_number).is_some_and(|info| info.in_pymdown_block)
                {
                    continue;
                }

                // Check if this is a paragraph/regular text line
                // If paragraphs = false, skip lines that are NOT in special blocks
                if !effective_config.paragraphs {
                    let is_special_block = heading_lines_set.contains(&line_number)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_code_block)
                        || table_lines_set.contains(&line_number)
                        || ctx.lines[line_number - 1].blockquote.is_some()
                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_block)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_html_comment)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_esm_block)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_expression)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_jsx_block)
                        || ctx.line_info(line_number).is_some_and(|info| info.in_mdx_comment)
                        || ctx
                            .line_info(line_number)
                            .is_some_and(|info| info.in_mkdocs_container());

                    // Skip regular paragraph text when paragraphs = false
                    if !is_special_block {
                        continue;
                    }
                }

                // Skip lines that are only a URL, image ref, or link ref
                if self.should_ignore_line(line, lines, line_idx, ctx) {
                    continue;
                }
            }

            // In sentence-per-line mode, check if this is a single long sentence
            // If so, emit a warning without a fix (user must manually rephrase)
            if effective_config.reflow_mode == ReflowMode::SentencePerLine {
                let sentences = split_into_sentences(line.trim());
                if sentences.len() == 1 {
                    // Single sentence that's too long - warn but don't auto-fix
                    let message = format!("Line length {effective_length} exceeds {line_limit} characters");

                    let (start_line, start_col, end_line, end_col) =
                        calculate_excess_range(line_number, line, line_limit);

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message,
                        line: start_line,
                        column: start_col,
                        end_line,
                        end_column: end_col,
                        severity: Severity::Warning,
                        fix: None, // No auto-fix for long single sentences
                    });
                    continue;
                }
                // Multiple sentences will be handled by paragraph-based reflow
                continue;
            }

            // In semantic-line-breaks mode, skip per-line checks —
            // all reflow is handled at the paragraph level with cascading splits
            if effective_config.reflow_mode == ReflowMode::SemanticLineBreaks {
                continue;
            }

            // Don't provide fix for individual lines when reflow is enabled
            // Paragraph-based fixes will be handled separately
            let fix = None;

            let message = format!("Line length {effective_length} exceeds {line_limit} characters");

            // Calculate precise character range for the excess portion
            let (start_line, start_col, end_line, end_col) = calculate_excess_range(line_number, line, line_limit);

            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                message,
                line: start_line,
                column: start_col,
                end_line,
                end_column: end_col,
                severity: Severity::Warning,
                fix,
            });
        }

        // If reflow is enabled, generate paragraph-based fixes
        if effective_config.reflow {
            let paragraph_warnings = self.generate_paragraph_fixes(ctx, &effective_config, lines);
            // Merge paragraph warnings with line warnings, removing duplicates
            for pw in paragraph_warnings {
                // Remove any line warnings that overlap with this paragraph
                warnings.retain(|w| w.line < pw.line || w.line > pw.end_line);
                warnings.push(pw);
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        // For CLI usage, apply fixes from warnings
        // LSP will use the warning-based fixes directly
        let warnings = self.check(ctx)?;
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());

        // If there are no fixes, return content unchanged
        if !warnings.iter().any(|w| w.fix.is_some()) {
            return Ok(ctx.content.to_string());
        }

        // Apply warning-based fixes
        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
            .map_err(|e| LintError::FixFailed(format!("Failed to apply fixes: {e}")))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Whitespace
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        self.should_skip_with_config(ctx, &self.config)
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let default_config = MD013Config::default();
        let json_value = serde_json::to_value(&default_config).ok()?;
        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;

        if let toml::Value::Table(table) = toml_value {
            if !table.is_empty() {
                Some((MD013Config::RULE_NAME.to_string(), toml::Value::Table(table)))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
        let mut aliases = std::collections::HashMap::new();
        aliases.insert("enable_reflow".to_string(), "reflow".to_string());
        aliases.insert("strict_sentences".to_string(), "require-sentence-capital".to_string());
        aliases.insert("strict-sentences".to_string(), "require-sentence-capital".to_string());
        Some(aliases)
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let mut rule_config = crate::rule_config_serde::load_rule_config::<MD013Config>(config);
        // Use global line_length if rule-specific config still has default value
        if rule_config.line_length.get() == 80 {
            rule_config.line_length = config.global.line_length;
        }
        Box::new(Self::from_config_struct(rule_config))
    }
}

impl MD013LineLength {
    fn is_blockquote_content_boundary(
        &self,
        content: &str,
        line_num: usize,
        ctx: &crate::lint_context::LintContext,
    ) -> bool {
        let trimmed = content.trim();

        trimmed.is_empty()
            || ctx.line_info(line_num).is_some_and(|info| {
                info.in_code_block
                    || info.in_front_matter
                    || info.in_html_block
                    || info.in_html_comment
                    || info.in_esm_block
                    || info.in_jsx_expression
                    || info.in_jsx_block
                    || info.in_mdx_comment
                    || info.in_mkdocstrings
                    || info.in_pymdown_block
                    || info.in_mkdocs_container()
                    || info.is_div_marker
            })
            || trimmed.starts_with('#')
            || trimmed.starts_with("```")
            || trimmed.starts_with("~~~")
            || trimmed.starts_with('>')
            || TableUtils::is_potential_table_row(content)
            || is_list_item(trimmed)
            || is_horizontal_rule(trimmed)
            || (trimmed.starts_with('[') && content.contains("]:"))
            || is_template_directive_only(content)
            || is_standalone_attr_list(content)
            || is_snippet_block_delimiter(content)
            || is_github_alert_marker(trimmed)
    }

    fn generate_blockquote_paragraph_fix(
        &self,
        ctx: &crate::lint_context::LintContext,
        config: &MD013Config,
        lines: &[&str],
        line_index: &LineIndex,
        start_idx: usize,
        line_ending: &str,
    ) -> (Option<LintWarning>, usize) {
        let Some(start_bq) = ctx.lines.get(start_idx).and_then(|line| line.blockquote.as_deref()) else {
            return (None, start_idx + 1);
        };
        let target_level = start_bq.nesting_level;

        let mut collected: Vec<CollectedBlockquoteLine> = Vec::new();
        let mut i = start_idx;

        while i < lines.len() {
            if !collected.is_empty() && has_hard_break(&collected[collected.len() - 1].data.content) {
                break;
            }

            let line_num = i + 1;
            if line_num > ctx.lines.len() {
                break;
            }

            if lines[i].trim().is_empty() {
                break;
            }

            let line_bq = ctx.lines[i].blockquote.as_deref();
            if let Some(bq) = line_bq {
                if bq.nesting_level != target_level {
                    break;
                }

                if self.is_blockquote_content_boundary(&bq.content, line_num, ctx) {
                    break;
                }

                collected.push(CollectedBlockquoteLine {
                    line_idx: i,
                    data: BlockquoteLineData::explicit(trim_preserving_hard_break(&bq.content), bq.prefix.clone()),
                });
                i += 1;
                continue;
            }

            let lazy_content = lines[i].trim_start();
            if self.is_blockquote_content_boundary(lazy_content, line_num, ctx) {
                break;
            }

            collected.push(CollectedBlockquoteLine {
                line_idx: i,
                data: BlockquoteLineData::lazy(trim_preserving_hard_break(lazy_content)),
            });
            i += 1;
        }

        if collected.is_empty() {
            return (None, start_idx + 1);
        }

        let next_idx = i;
        let paragraph_start = collected[0].line_idx;
        let end_line = collected[collected.len() - 1].line_idx;
        let line_data: Vec<BlockquoteLineData> = collected.iter().map(|l| l.data.clone()).collect();
        let paragraph_text = line_data
            .iter()
            .map(|d| d.content.as_str())
            .collect::<Vec<_>>()
            .join(" ");

        let contains_definition_list = line_data
            .iter()
            .any(|d| crate::utils::is_definition_list_item(&d.content));
        if contains_definition_list {
            return (None, next_idx);
        }

        let contains_snippets = line_data.iter().any(|d| is_snippet_block_delimiter(&d.content));
        if contains_snippets {
            return (None, next_idx);
        }

        let needs_reflow = match config.reflow_mode {
            ReflowMode::Normalize => line_data.len() > 1,
            ReflowMode::SentencePerLine => {
                let sentences = split_into_sentences(&paragraph_text);
                sentences.len() > 1 || line_data.len() > 1
            }
            ReflowMode::SemanticLineBreaks => {
                let sentences = split_into_sentences(&paragraph_text);
                sentences.len() > 1
                    || line_data.len() > 1
                    || collected
                        .iter()
                        .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get())
            }
            ReflowMode::Default => collected
                .iter()
                .any(|l| self.calculate_effective_length(lines[l.line_idx]) > config.line_length.get()),
        };

        if !needs_reflow {
            return (None, next_idx);
        }

        let fallback_prefix = start_bq.prefix.clone();
        let explicit_prefix = dominant_blockquote_prefix(&line_data, &fallback_prefix);
        let continuation_style = blockquote_continuation_style(&line_data);

        let reflow_line_length = if config.line_length.is_unlimited() {
            usize::MAX
        } else {
            config
                .line_length
                .get()
                .saturating_sub(self.calculate_string_length(&explicit_prefix))
                .max(1)
        };

        let reflow_options = crate::utils::text_reflow::ReflowOptions {
            line_length: reflow_line_length,
            break_on_sentences: true,
            preserve_breaks: false,
            sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
            semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
            abbreviations: config.abbreviations_for_reflow(),
            length_mode: self.reflow_length_mode(),
            attr_lists: ctx.flavor.supports_attr_lists(),
            require_sentence_capital: config.require_sentence_capital,
            max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
                Some(4)
            } else {
                None
            },
        };

        let reflowed_with_style =
            reflow_blockquote_content(&line_data, &explicit_prefix, continuation_style, &reflow_options);

        if reflowed_with_style.is_empty() {
            return (None, next_idx);
        }

        let reflowed_text = reflowed_with_style.join(line_ending);

        let start_range = line_index.whole_line_range(paragraph_start + 1);
        let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
            line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
        } else {
            line_index.whole_line_range(end_line + 1)
        };
        let byte_range = start_range.start..end_range.end;

        let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
            format!("{reflowed_text}{line_ending}")
        } else {
            reflowed_text
        };

        let original_text = &ctx.content[byte_range.clone()];
        if original_text == replacement {
            return (None, next_idx);
        }

        let (warning_line, warning_end_line) = match config.reflow_mode {
            ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
            ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => (paragraph_start + 1, end_line + 1),
            ReflowMode::Default => {
                let violating_line = collected
                    .iter()
                    .find(|line| self.calculate_effective_length(lines[line.line_idx]) > config.line_length.get())
                    .map(|line| line.line_idx + 1)
                    .unwrap_or(paragraph_start + 1);
                (violating_line, violating_line)
            }
        };

        let warning = LintWarning {
            rule_name: Some(self.name().to_string()),
            message: match config.reflow_mode {
                ReflowMode::Normalize => format!(
                    "Paragraph could be normalized to use line length of {} characters",
                    config.line_length.get()
                ),
                ReflowMode::SentencePerLine => {
                    let num_sentences = split_into_sentences(&paragraph_text).len();
                    if line_data.len() == 1 {
                        format!("Line contains {num_sentences} sentences (one sentence per line required)")
                    } else {
                        let num_lines = line_data.len();
                        format!(
                            "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
                        )
                    }
                }
                ReflowMode::SemanticLineBreaks => {
                    let num_sentences = split_into_sentences(&paragraph_text).len();
                    format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
                }
                ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
            },
            line: warning_line,
            column: 1,
            end_line: warning_end_line,
            end_column: lines[warning_end_line.saturating_sub(1)].len() + 1,
            severity: Severity::Warning,
            fix: Some(crate::rule::Fix {
                range: byte_range,
                replacement,
            }),
        };

        (Some(warning), next_idx)
    }

    /// Generate paragraph-based fixes
    fn generate_paragraph_fixes(
        &self,
        ctx: &crate::lint_context::LintContext,
        config: &MD013Config,
        lines: &[&str],
    ) -> Vec<LintWarning> {
        let mut warnings = Vec::new();
        let line_index = LineIndex::new(ctx.content);

        // Detect the content's line ending style to preserve it in replacements.
        // The LSP receives content from editors which may use CRLF (Windows).
        // Replacements must match the original line endings to avoid false positives.
        let line_ending = crate::utils::line_ending::detect_line_ending(ctx.content);

        let mut i = 0;
        while i < lines.len() {
            let line_num = i + 1;

            // Handle blockquote paragraphs with style-preserving reflow.
            if line_num > 0 && line_num <= ctx.lines.len() && ctx.lines[line_num - 1].blockquote.is_some() {
                let (warning, next_idx) =
                    self.generate_blockquote_paragraph_fix(ctx, config, lines, &line_index, i, line_ending);
                if let Some(warning) = warning {
                    warnings.push(warning);
                }
                i = next_idx;
                continue;
            }

            // Skip special structures (but NOT MkDocs containers - those get special handling)
            let should_skip_due_to_line_info = ctx.line_info(line_num).is_some_and(|info| {
                info.in_code_block
                    || info.in_front_matter
                    || info.in_html_block
                    || info.in_html_comment
                    || info.in_esm_block
                    || info.in_jsx_expression
                    || info.in_jsx_block
                    || info.in_mdx_comment
                    || info.in_mkdocstrings
                    || info.in_pymdown_block
            });

            // Skip link reference definitions but NOT footnote definitions.
            // Footnote definitions (`[^id]: prose`) contain reflowable text,
            // while link reference definitions (`[ref]: URL`) contain URLs
            // that cannot be shortened.
            let is_link_ref_def =
                lines[i].trim().starts_with('[') && !lines[i].trim().starts_with("[^") && lines[i].contains("]:");

            if should_skip_due_to_line_info
                || lines[i].trim().starts_with('#')
                || TableUtils::is_potential_table_row(lines[i])
                || lines[i].trim().is_empty()
                || is_horizontal_rule(lines[i].trim())
                || is_template_directive_only(lines[i])
                || is_link_ref_def
                || ctx.line_info(line_num).is_some_and(|info| info.is_div_marker)
            {
                i += 1;
                continue;
            }

            // Handle footnote definitions: `[^id]: prose text that can be reflowed`
            // Supports multi-paragraph footnotes with code blocks, blockquotes,
            // tables, and lists preserved verbatim.
            // Validate structure: must start with `[^`, contain `]:`, and the ID
            // must not contain `[` or `]` (prevents false matches on nested brackets)
            if lines[i].trim().starts_with("[^") && lines[i].contains("]:") && {
                let after_caret = &lines[i].trim()[2..];
                after_caret
                    .find("]:")
                    .is_some_and(|pos| pos > 0 && !after_caret[..pos].contains(['[', ']']))
            } {
                let footnote_start = i;
                let line = lines[i];

                // Extract the prefix `[^id]:`
                let Some(colon_pos) = line.find("]:") else {
                    i += 1;
                    continue;
                };
                let prefix_end = colon_pos + 2;
                let prefix = &line[..prefix_end];

                // Content starts after `]: ` (with optional space)
                let content_start = if line[prefix_end..].starts_with(' ') {
                    prefix_end + 1
                } else {
                    prefix_end
                };
                let first_content = &line[content_start..];

                // CommonMark footnotes use 4-space continuation indent
                const FN_INDENT: usize = 4;

                // --- Line classification for footnote content ---
                #[derive(Debug, Clone)]
                enum FnLineType {
                    Content(String),
                    Verbatim(String, usize), // preserved text, original indent
                    Empty,
                }

                // Helper: compute visual indent (tabs = 4 spaces)
                let visual_indent = |s: &str| -> usize {
                    s.chars()
                        .take_while(|c| c.is_whitespace())
                        .map(|c| if c == '\t' { 4 } else { 1 })
                        .sum::<usize>()
                };

                // Helper: check if a trimmed line is a fence marker (homogeneous chars)
                let is_fence = |s: &str| -> bool {
                    let t = s.trim();
                    let fence_char = t.chars().next();
                    matches!(fence_char, Some('`') | Some('~'))
                        && t.chars().take_while(|&c| c == fence_char.unwrap()).count() >= 3
                };

                // Helper: check if a trimmed line is a setext underline
                let is_setext_underline = |s: &str| -> bool {
                    let t = s.trim();
                    !t.is_empty()
                        && (t.chars().all(|c| c == '=' || c == ' ') || t.chars().all(|c| c == '-' || c == ' '))
                        && t.contains(['=', '-'])
                };

                // Deferred body: `[^id]:\n    content` — first line has no content,
                // actual content starts on the next indented line
                let deferred_body = first_content.trim().is_empty();

                // Collect all lines belonging to this footnote definition
                let mut fn_lines: Vec<FnLineType> = Vec::new();
                if !deferred_body {
                    fn_lines.push(FnLineType::Content(first_content.to_string()));
                }
                let mut last_consumed = i;
                i += 1;

                // Strip only the footnote continuation indent, preserving
                // internal indentation (e.g., code block body indent)
                let strip_fn_indent = |s: &str| -> String {
                    let mut chars = s.chars();
                    let mut stripped = 0;
                    while stripped < FN_INDENT {
                        match chars.next() {
                            Some('\t') => stripped += 4,
                            Some(c) if c.is_whitespace() => stripped += 1,
                            _ => break,
                        }
                    }
                    chars.as_str().to_string()
                };

                let mut in_fenced_code = false;
                let mut consecutive_blanks = 0u32;

                while i < lines.len() {
                    let next = lines[i];
                    let next_trimmed = next.trim();

                    // Blank line handling
                    if next_trimmed.is_empty() {
                        consecutive_blanks += 1;
                        // 2+ consecutive blanks terminate the footnote
                        if consecutive_blanks >= 2 {
                            break;
                        }

                        // Inside a fenced code block, blank lines are part of the code
                        if in_fenced_code {
                            consecutive_blanks = 0; // Don't count blanks inside code blocks
                            fn_lines.push(FnLineType::Verbatim(String::new(), 0));
                            last_consumed = i;
                            i += 1;
                            continue;
                        }

                        // Peek ahead: if next non-blank line is indented >= FN_INDENT,
                        // this blank is an internal paragraph separator
                        if i + 1 < lines.len() {
                            let peek = lines[i + 1];
                            let peek_indent = visual_indent(peek);
                            if !peek.trim().is_empty() && peek_indent >= FN_INDENT {
                                fn_lines.push(FnLineType::Empty);
                                last_consumed = i;
                                i += 1;
                                continue;
                            }
                        }
                        // No valid continuation after blank — end of footnote
                        break;
                    }

                    consecutive_blanks = 0;
                    let indent = visual_indent(next);

                    // Not indented enough — end of footnote
                    if indent < FN_INDENT {
                        break;
                    }

                    // Inside a fenced code block: everything is verbatim until closing fence
                    if in_fenced_code {
                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
                        if is_fence(next_trimmed) {
                            in_fenced_code = false;
                        }
                        last_consumed = i;
                        i += 1;
                        continue;
                    }

                    // Fence opener — start verbatim code block
                    if is_fence(next_trimmed) {
                        in_fenced_code = true;
                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
                        last_consumed = i;
                        i += 1;
                        continue;
                    }

                    // Indented code block: indent >= FN_INDENT + 4 (= 8 spaces)
                    if indent >= FN_INDENT + 4 {
                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
                        last_consumed = i;
                        i += 1;
                        continue;
                    }

                    // Structural content that must be preserved verbatim
                    if next_trimmed.starts_with('#')
                        || is_list_item(next_trimmed)
                        || next_trimmed.starts_with('>')
                        || TableUtils::is_potential_table_row(next_trimmed)
                        || is_setext_underline(next_trimmed)
                        || is_horizontal_rule(next_trimmed)
                        || crate::utils::mkdocs_footnotes::is_footnote_definition(next_trimmed)
                    {
                        // Preserve verbatim: blockquotes, tables, lists, setext
                        // underlines, and horizontal rules inside the footnote
                        if next_trimmed.starts_with('>')
                            || TableUtils::is_potential_table_row(next_trimmed)
                            || is_list_item(next_trimmed)
                            || is_setext_underline(next_trimmed)
                            || is_horizontal_rule(next_trimmed)
                        {
                            fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
                            last_consumed = i;
                            i += 1;
                            continue;
                        }
                        // Headings, new footnote defs, link refs — end the footnote
                        break;
                    }

                    // Link reference definitions inside footnotes are not reflowable
                    if next_trimmed.starts_with('[')
                        && !next_trimmed.starts_with("[^")
                        && next_trimmed.contains("]:")
                        && LINK_REF_PATTERN.is_match(next_trimmed)
                    {
                        fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
                        last_consumed = i;
                        i += 1;
                        continue;
                    }

                    // Regular prose content
                    fn_lines.push(FnLineType::Content(next_trimmed.to_string()));
                    last_consumed = i;
                    i += 1;
                }

                // Nothing collected or only empty lines
                if fn_lines.iter().all(|l| matches!(l, FnLineType::Empty)) || fn_lines.is_empty() {
                    continue;
                }

                // --- Group into blocks ---
                #[derive(Debug)]
                enum FnBlock {
                    Paragraph(Vec<String>),
                    Verbatim(Vec<(String, usize)>), // (content, indent) preserved as-is
                }

                let mut blocks: Vec<FnBlock> = Vec::new();
                let mut current_para: Vec<String> = Vec::new();
                let mut current_verbatim: Vec<(String, usize)> = Vec::new();

                for fl in &fn_lines {
                    match fl {
                        FnLineType::Content(s) => {
                            if !current_verbatim.is_empty() {
                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
                            }
                            current_para.push(s.clone());
                        }
                        FnLineType::Verbatim(s, indent) => {
                            if !current_para.is_empty() {
                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
                            }
                            current_verbatim.push((s.clone(), *indent));
                        }
                        FnLineType::Empty => {
                            if !current_para.is_empty() {
                                blocks.push(FnBlock::Paragraph(std::mem::take(&mut current_para)));
                            }
                            if !current_verbatim.is_empty() {
                                blocks.push(FnBlock::Verbatim(std::mem::take(&mut current_verbatim)));
                            }
                        }
                    }
                }
                if !current_para.is_empty() {
                    blocks.push(FnBlock::Paragraph(current_para));
                }
                if !current_verbatim.is_empty() {
                    blocks.push(FnBlock::Verbatim(current_verbatim));
                }

                // --- Reflow paragraphs and reconstruct ---
                let prefix_display_width = prefix.chars().count() + 1; // +1 for space
                let reflow_line_length = if config.line_length.is_unlimited() {
                    usize::MAX
                } else {
                    config
                        .line_length
                        .get()
                        .saturating_sub(FN_INDENT.max(prefix_display_width))
                        .max(20)
                };
                let reflow_options = crate::utils::text_reflow::ReflowOptions {
                    line_length: reflow_line_length,
                    break_on_sentences: true,
                    preserve_breaks: false,
                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
                    abbreviations: config.abbreviations_for_reflow(),
                    length_mode: self.reflow_length_mode(),
                    attr_lists: ctx.flavor.supports_attr_lists(),
                    require_sentence_capital: config.require_sentence_capital,
                    max_list_continuation_indent: None,
                };

                let indent_str = " ".repeat(FN_INDENT);
                let mut result_lines: Vec<String> = Vec::new();
                let mut is_first_block = true;

                for block in &blocks {
                    match block {
                        FnBlock::Paragraph(para_lines) => {
                            let paragraph_text = para_lines.join(" ");
                            let paragraph_text = paragraph_text.trim();
                            if paragraph_text.is_empty() {
                                continue;
                            }

                            let reflowed = crate::utils::text_reflow::reflow_line(paragraph_text, &reflow_options);
                            if reflowed.is_empty() {
                                continue;
                            }

                            // Blank line separator between blocks
                            if !result_lines.is_empty() {
                                result_lines.push(String::new());
                            }

                            for (idx, rline) in reflowed.iter().enumerate() {
                                if is_first_block && idx == 0 {
                                    result_lines.push(format!("{prefix} {rline}"));
                                } else {
                                    result_lines.push(format!("{indent_str}{rline}"));
                                }
                            }
                            is_first_block = false;
                        }
                        FnBlock::Verbatim(verb_lines) => {
                            // Blank line separator between blocks
                            if !result_lines.is_empty() {
                                result_lines.push(String::new());
                            }

                            if is_first_block {
                                // Verbatim as first block in a deferred-body footnote
                                if deferred_body {
                                    result_lines.push(prefix.to_string());
                                }
                                is_first_block = false;
                            }
                            for (content, _orig_indent) in verb_lines {
                                result_lines.push(format!("{indent_str}{content}"));
                            }
                        }
                    }
                }

                // If nothing was produced, skip
                if result_lines.is_empty() {
                    continue;
                }

                let reflowed_text = result_lines.join(line_ending);

                // Calculate byte range using last_consumed
                let start_range = line_index.whole_line_range(footnote_start + 1);
                let end_range = if last_consumed == lines.len() - 1 && !ctx.content.ends_with('\n') {
                    line_index.line_text_range(last_consumed + 1, 1, lines[last_consumed].len() + 1)
                } else {
                    line_index.whole_line_range(last_consumed + 1)
                };
                let byte_range = start_range.start..end_range.end;

                let replacement = if last_consumed < lines.len() - 1 || ctx.content.ends_with('\n') {
                    format!("{reflowed_text}{line_ending}")
                } else {
                    reflowed_text
                };

                let original_text = &ctx.content[byte_range.clone()];
                let max_length = (footnote_start..=last_consumed)
                    .map(|idx| self.calculate_effective_length(lines[idx]))
                    .max()
                    .unwrap_or(0);
                let line_limit = if config.line_length.is_unlimited() {
                    usize::MAX
                } else {
                    config.line_length.get()
                };
                if original_text != replacement && max_length > line_limit {
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: format!(
                            "Line length {} exceeds {} characters",
                            max_length,
                            config.line_length.get()
                        ),
                        line: footnote_start + 1,
                        column: 1,
                        end_line: last_consumed + 1,
                        end_column: lines[last_consumed].len() + 1,
                        severity: Severity::Warning,
                        fix: Some(crate::rule::Fix {
                            range: byte_range,
                            replacement,
                        }),
                    });
                }
                continue;
            }

            // Handle MkDocs container content (admonitions and tabs) with indent-preserving reflow
            if ctx.line_info(line_num).is_some_and(|info| info.in_mkdocs_container()) {
                // Skip admonition/tab marker lines — only reflow their indented content
                let current_line = lines[i];
                if mkdocs_admonitions::is_admonition_start(current_line) || mkdocs_tabs::is_tab_marker(current_line) {
                    i += 1;
                    continue;
                }

                let container_start = i;

                // Detect the actual indent level from the first content line
                // (supports nested admonitions with 8+ spaces)
                let first_line = lines[i];
                let base_indent_len = first_line.len() - first_line.trim_start().len();
                let base_indent: String = " ".repeat(base_indent_len);

                // Collect consecutive MkDocs container paragraph lines
                let mut container_lines: Vec<&str> = Vec::new();
                while i < lines.len() {
                    let current_line_num = i + 1;
                    let line_info = ctx.line_info(current_line_num);

                    // Stop if we leave the MkDocs container
                    if !line_info.is_some_and(|info| info.in_mkdocs_container()) {
                        break;
                    }

                    let line = lines[i];

                    // Stop at paragraph boundaries within the container
                    if line.trim().is_empty() {
                        break;
                    }

                    // Skip list items, code blocks, headings within containers
                    if is_list_item(line.trim())
                        || line.trim().starts_with("```")
                        || line.trim().starts_with("~~~")
                        || line.trim().starts_with('#')
                    {
                        break;
                    }

                    container_lines.push(line);
                    i += 1;
                }

                if container_lines.is_empty() {
                    // Must advance i to avoid infinite loop when we encounter
                    // non-paragraph content (code block, list, heading, empty line)
                    // at the start of an MkDocs container
                    i += 1;
                    continue;
                }

                // Strip the base indent from each line and join for reflow
                let stripped_lines: Vec<&str> = container_lines
                    .iter()
                    .map(|line| {
                        if line.starts_with(&base_indent) {
                            &line[base_indent_len..]
                        } else {
                            line.trim_start()
                        }
                    })
                    .collect();
                let paragraph_text = stripped_lines.join(" ");

                // Check if reflow is needed
                let needs_reflow = match config.reflow_mode {
                    ReflowMode::Normalize => container_lines.len() > 1,
                    ReflowMode::SentencePerLine => {
                        let sentences = split_into_sentences(&paragraph_text);
                        sentences.len() > 1 || container_lines.len() > 1
                    }
                    ReflowMode::SemanticLineBreaks => {
                        let sentences = split_into_sentences(&paragraph_text);
                        sentences.len() > 1
                            || container_lines.len() > 1
                            || container_lines
                                .iter()
                                .any(|line| self.calculate_effective_length(line) > config.line_length.get())
                    }
                    ReflowMode::Default => container_lines
                        .iter()
                        .any(|line| self.calculate_effective_length(line) > config.line_length.get()),
                };

                if !needs_reflow {
                    continue;
                }

                // Calculate byte range for this container paragraph
                let start_range = line_index.whole_line_range(container_start + 1);
                let end_line = container_start + container_lines.len() - 1;
                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
                } else {
                    line_index.whole_line_range(end_line + 1)
                };
                let byte_range = start_range.start..end_range.end;

                // Reflow with adjusted line length (accounting for the 4-space indent)
                let reflow_line_length = if config.line_length.is_unlimited() {
                    usize::MAX
                } else {
                    config.line_length.get().saturating_sub(base_indent_len).max(1)
                };
                let reflow_options = crate::utils::text_reflow::ReflowOptions {
                    line_length: reflow_line_length,
                    break_on_sentences: true,
                    preserve_breaks: false,
                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
                    abbreviations: config.abbreviations_for_reflow(),
                    length_mode: self.reflow_length_mode(),
                    attr_lists: ctx.flavor.supports_attr_lists(),
                    require_sentence_capital: config.require_sentence_capital,
                    max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
                        Some(4)
                    } else {
                        None
                    },
                };
                let reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);

                // Re-add the 4-space indent to each reflowed line
                let reflowed_with_indent: Vec<String> =
                    reflowed.iter().map(|line| format!("{base_indent}{line}")).collect();
                let reflowed_text = reflowed_with_indent.join(line_ending);

                // Preserve trailing newline
                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
                    format!("{reflowed_text}{line_ending}")
                } else {
                    reflowed_text
                };

                // Only generate a warning if the replacement is different
                let original_text = &ctx.content[byte_range.clone()];
                if original_text != replacement {
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: format!(
                            "Line length {} exceeds {} characters (in MkDocs container)",
                            container_lines.iter().map(|l| l.len()).max().unwrap_or(0),
                            config.line_length.get()
                        ),
                        line: container_start + 1,
                        column: 1,
                        end_line: end_line + 1,
                        end_column: lines[end_line].len() + 1,
                        severity: Severity::Warning,
                        fix: Some(crate::rule::Fix {
                            range: byte_range,
                            replacement,
                        }),
                    });
                }
                continue;
            }

            // Helper function to detect semantic line markers
            let is_semantic_line = |content: &str| -> bool {
                let trimmed = content.trim_start();
                let semantic_markers = [
                    "NOTE:",
                    "WARNING:",
                    "IMPORTANT:",
                    "CAUTION:",
                    "TIP:",
                    "DANGER:",
                    "HINT:",
                    "INFO:",
                ];
                semantic_markers.iter().any(|marker| trimmed.starts_with(marker))
            };

            // Helper function to detect fence markers (opening or closing)
            let is_fence_marker = |content: &str| -> bool {
                let trimmed = content.trim_start();
                trimmed.starts_with("```") || trimmed.starts_with("~~~")
            };

            // Check if this is a list item - handle it specially
            let trimmed = lines[i].trim();
            if is_list_item(trimmed) {
                // Collect the entire list item including continuation lines
                let list_start = i;
                let (marker, first_content) = extract_list_marker_and_content(lines[i]);
                let marker_len = marker.len();

                // Checkbox ([ ]/[x]/[X]) is inline content, not part of the list marker.
                // Use the base bullet/number marker width for continuation recognition
                // so that continuation lines at 2+ spaces are collected for "- [ ] " items.
                let base_marker_len = if marker.contains("[ ] ") || marker.contains("[x] ") || marker.contains("[X] ") {
                    marker.find('[').unwrap_or(marker_len)
                } else {
                    marker_len
                };

                // MkDocs flavor requires at least 4 spaces for list continuation
                // after a blank line (multi-paragraph list items). For non-blank
                // continuation (lines directly following the marker line), use
                // the natural marker width so that 2-space indent is recognized.
                let item_indent = ctx.lines[i].indent;
                let min_continuation_indent = if ctx.flavor.requires_strict_list_indent() {
                    // Use 4-space relative indent from the list item's nesting level
                    item_indent + (base_marker_len - item_indent).max(4)
                } else {
                    marker_len
                };
                let content_continuation_indent = base_marker_len;

                // Track lines and their types (content, code block, fence, nested list)
                #[derive(Clone)]
                enum LineType {
                    Content(String),
                    CodeBlock(String, usize),         // content and original indent
                    SemanticLine(String), // Lines starting with NOTE:, WARNING:, etc that should stay separate
                    SnippetLine(String),  // MkDocs Snippets delimiters (-8<-) that must stay on their own line
                    DivMarker(String),    // Quarto/Pandoc div markers (::: opening or closing)
                    AdmonitionHeader(String, usize), // header text (e.g. "!!! note") and original indent
                    AdmonitionContent(String, usize), // body content text and original indent
                    Empty,
                }

                let mut list_item_lines: Vec<LineType> = vec![LineType::Content(first_content)];
                i += 1;

                // Collect continuation lines using ctx.lines for metadata
                while i < lines.len() {
                    let line_info = &ctx.lines[i];

                    // Use pre-computed is_blank from ctx
                    if line_info.is_blank {
                        // Empty line - check if next line is indented (part of list item)
                        if i + 1 < lines.len() {
                            let next_info = &ctx.lines[i + 1];

                            // Check if next line is indented enough to be continuation
                            if !next_info.is_blank && next_info.indent >= min_continuation_indent {
                                // This blank line is between paragraphs/blocks in the list item
                                list_item_lines.push(LineType::Empty);
                                i += 1;
                                continue;
                            }
                        }
                        // No indented line after blank, end of list item
                        break;
                    }

                    // Use pre-computed indent from ctx
                    let indent = line_info.indent;

                    // Valid continuation must be indented at least content_continuation_indent.
                    // For non-blank continuation, use marker_len (e.g. 2 for "- ").
                    // MkDocs strict 4-space requirement applies only after blank lines.
                    if indent >= content_continuation_indent {
                        let trimmed = line_info.content(ctx.content).trim();

                        // Use pre-computed in_code_block from ctx
                        if line_info.in_code_block {
                            list_item_lines.push(LineType::CodeBlock(
                                line_info.content(ctx.content)[indent..].to_string(),
                                indent,
                            ));
                            i += 1;
                            continue;
                        }

                        // Check for MkDocs admonition lines inside list items.
                        // The flavor detection marks these with in_admonition, so we
                        // can classify them as admonition header or body content.
                        // All lines within an admonition (including code fence markers
                        // and code block content) stay as AdmonitionContent to preserve
                        // the admonition structure through the block builder.
                        if line_info.in_admonition {
                            let raw_content = line_info.content(ctx.content);
                            if mkdocs_admonitions::is_admonition_start(raw_content) {
                                let header_text = raw_content[indent..].trim_end().to_string();
                                list_item_lines.push(LineType::AdmonitionHeader(header_text, indent));
                            } else {
                                let body_text = raw_content[indent..].trim_end().to_string();
                                list_item_lines.push(LineType::AdmonitionContent(body_text, indent));
                            }
                            i += 1;
                            continue;
                        }

                        // Check if this is a SIBLING list item (breaks parent)
                        // Nested lists are indented >= marker_len and are PART of the parent item
                        // Siblings are at indent < marker_len (at or before parent marker)
                        if is_list_item(trimmed) && indent < marker_len {
                            // This is a sibling item at same or higher level - end parent item
                            break;
                        }

                        // Nested list items are always processed independently
                        // by the outer loop, so break when we encounter one.
                        // If a blank line was collected before this, uncollect it
                        // so the outer loop preserves the blank between parent and nested.
                        if is_list_item(trimmed) && indent >= marker_len {
                            if matches!(list_item_lines.last(), Some(LineType::Empty)) {
                                list_item_lines.pop();
                                i -= 1;
                            }
                            break;
                        }

                        // Normal continuation vs indented code block.
                        // Use min_continuation_indent for the threshold since
                        // code blocks start 4 spaces beyond the expected content
                        // level (which is min_continuation_indent for MkDocs).
                        if indent <= min_continuation_indent + 3 {
                            // Extract content (remove indentation and trailing whitespace)
                            // Preserve hard breaks (2 trailing spaces) while removing excessive whitespace
                            // See: https://github.com/rvben/rumdl/issues/76
                            let content = trim_preserving_hard_break(&line_info.content(ctx.content)[indent..]);

                            // Check if this is a div marker (::: opening or closing)
                            // These must be preserved on their own line, not merged into paragraphs
                            if line_info.is_div_marker {
                                list_item_lines.push(LineType::DivMarker(content));
                            }
                            // Check if this is a fence marker (opening or closing)
                            // These should be treated as code block lines, not paragraph content
                            else if is_fence_marker(&content) {
                                list_item_lines.push(LineType::CodeBlock(content, indent));
                            }
                            // Check if this is a semantic line (NOTE:, WARNING:, etc.)
                            else if is_semantic_line(&content) {
                                list_item_lines.push(LineType::SemanticLine(content));
                            }
                            // Check if this is a snippet block delimiter (-8<- or --8<--)
                            // These must be preserved on their own lines for MkDocs Snippets extension
                            else if is_snippet_block_delimiter(&content) {
                                list_item_lines.push(LineType::SnippetLine(content));
                            } else {
                                list_item_lines.push(LineType::Content(content));
                            }
                            i += 1;
                        } else {
                            // indent >= min_continuation_indent + 4: indented code block
                            list_item_lines.push(LineType::CodeBlock(
                                line_info.content(ctx.content)[indent..].to_string(),
                                indent,
                            ));
                            i += 1;
                        }
                    } else {
                        // Not indented enough, end of list item
                        break;
                    }
                }

                // Determine the output continuation indent.
                // Normalize/Default modes canonicalize to min_continuation_indent
                // (fixing over-indented continuation). Semantic/SentencePerLine
                // modes preserve the user's actual indent since they only fix
                // line breaking, not indentation.
                let indent_size = match config.reflow_mode {
                    ReflowMode::SemanticLineBreaks | ReflowMode::SentencePerLine => {
                        // Find indent of the first plain text continuation line,
                        // skipping the marker line (index 0), nested list items,
                        // code blocks, and blank lines.
                        list_item_lines
                            .iter()
                            .enumerate()
                            .skip(1)
                            .find_map(|(k, lt)| {
                                if matches!(lt, LineType::Content(_)) {
                                    Some(ctx.lines[list_start + k].indent)
                                } else {
                                    None
                                }
                            })
                            .unwrap_or(min_continuation_indent)
                    }
                    _ => min_continuation_indent,
                };
                // For checkbox items in mkdocs flavor, enforce minimum indent so
                // continuation lines use the structural list indent (4), not the
                // content-aligned indent (6) which Python-Markdown doesn't support
                let has_checkbox = base_marker_len < marker_len;
                let indent_size = if has_checkbox && ctx.flavor.requires_strict_list_indent() {
                    indent_size.max(min_continuation_indent)
                } else {
                    indent_size
                };
                let expected_indent = " ".repeat(indent_size);

                // Split list_item_lines into blocks (paragraphs, code blocks, nested lists, semantic lines, and HTML blocks)
                #[derive(Clone)]
                enum Block {
                    Paragraph(Vec<String>),
                    Code {
                        lines: Vec<(String, usize)>, // (content, indent) pairs
                        has_preceding_blank: bool,   // Whether there was a blank line before this block
                    },
                    SemanticLine(String), // Semantic markers like NOTE:, WARNING: that stay on their own line
                    SnippetLine(String),  // MkDocs Snippets delimiter that stays on its own line without extra spacing
                    DivMarker(String),    // Quarto/Pandoc div marker (::: opening or closing) preserved on its own line
                    Html {
                        lines: Vec<String>,        // HTML content preserved exactly as-is
                        has_preceding_blank: bool, // Whether there was a blank line before this block
                    },
                    Admonition {
                        header: String,                      // e.g. "!!! note" or "??? warning \"Title\""
                        header_indent: usize,                // original indent of the header line
                        content_lines: Vec<(String, usize)>, // (text, original_indent) pairs for body lines
                    },
                }

                // HTML tag detection helpers
                // Block-level HTML tags that should trigger HTML block detection
                const BLOCK_LEVEL_TAGS: &[&str] = &[
                    "div",
                    "details",
                    "summary",
                    "section",
                    "article",
                    "header",
                    "footer",
                    "nav",
                    "aside",
                    "main",
                    "table",
                    "thead",
                    "tbody",
                    "tfoot",
                    "tr",
                    "td",
                    "th",
                    "ul",
                    "ol",
                    "li",
                    "dl",
                    "dt",
                    "dd",
                    "pre",
                    "blockquote",
                    "figure",
                    "figcaption",
                    "form",
                    "fieldset",
                    "legend",
                    "hr",
                    "p",
                    "h1",
                    "h2",
                    "h3",
                    "h4",
                    "h5",
                    "h6",
                    "style",
                    "script",
                    "noscript",
                ];

                fn is_block_html_opening_tag(line: &str) -> Option<String> {
                    let trimmed = line.trim();

                    // Check for HTML comments
                    if trimmed.starts_with("<!--") {
                        return Some("!--".to_string());
                    }

                    // Check for opening tags
                    if trimmed.starts_with('<') && !trimmed.starts_with("</") && !trimmed.starts_with("<!") {
                        // Extract tag name from <tagname ...> or <tagname>
                        let after_bracket = &trimmed[1..];
                        if let Some(end) = after_bracket.find(|c: char| c.is_whitespace() || c == '>' || c == '/') {
                            let tag_name = after_bracket[..end].to_lowercase();

                            // Only treat as block if it's a known block-level tag
                            if BLOCK_LEVEL_TAGS.contains(&tag_name.as_str()) {
                                return Some(tag_name);
                            }
                        }
                    }
                    None
                }

                fn is_html_closing_tag(line: &str, tag_name: &str) -> bool {
                    let trimmed = line.trim();

                    // Special handling for HTML comments
                    if tag_name == "!--" {
                        return trimmed.ends_with("-->");
                    }

                    // Check for closing tags: </tagname> or </tagname ...>
                    trimmed.starts_with(&format!("</{tag_name}>"))
                        || trimmed.starts_with(&format!("</{tag_name}  "))
                        || (trimmed.starts_with("</") && trimmed[2..].trim_start().starts_with(tag_name))
                }

                fn is_self_closing_tag(line: &str) -> bool {
                    let trimmed = line.trim();
                    trimmed.ends_with("/>")
                }

                let mut blocks: Vec<Block> = Vec::new();
                let mut current_paragraph: Vec<String> = Vec::new();
                let mut current_code_block: Vec<(String, usize)> = Vec::new();
                let mut current_html_block: Vec<String> = Vec::new();
                let mut html_tag_stack: Vec<String> = Vec::new();
                let mut in_code = false;
                let mut in_html_block = false;
                let mut had_preceding_blank = false; // Track if we just saw an empty line
                let mut code_block_has_preceding_blank = false; // Track blank before current code block
                let mut html_block_has_preceding_blank = false; // Track blank before current HTML block

                // Track admonition context for block building
                let mut in_admonition_block = false;
                let mut admonition_header: Option<(String, usize)> = None; // (header_text, indent)
                let mut admonition_content: Vec<(String, usize)> = Vec::new();

                // Flush any pending admonition block into `blocks`
                let flush_admonition = |blocks: &mut Vec<Block>,
                                        in_admonition: &mut bool,
                                        header: &mut Option<(String, usize)>,
                                        content: &mut Vec<(String, usize)>| {
                    if *in_admonition {
                        if let Some((h, hi)) = header.take() {
                            blocks.push(Block::Admonition {
                                header: h,
                                header_indent: hi,
                                content_lines: std::mem::take(content),
                            });
                        }
                        *in_admonition = false;
                    }
                };

                for line in &list_item_lines {
                    match line {
                        LineType::Empty => {
                            if in_admonition_block {
                                // Blank lines inside admonitions separate paragraphs within the body
                                admonition_content.push((String::new(), 0));
                            } else if in_code {
                                current_code_block.push((String::new(), 0));
                            } else if in_html_block {
                                // Allow blank lines inside HTML blocks
                                current_html_block.push(String::new());
                            } else if !current_paragraph.is_empty() {
                                blocks.push(Block::Paragraph(current_paragraph.clone()));
                                current_paragraph.clear();
                            }
                            // Mark that we saw a blank line
                            had_preceding_blank = true;
                        }
                        LineType::Content(content) => {
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            // Check if we're currently in an HTML block
                            if in_html_block {
                                current_html_block.push(content.clone());

                                // Check if this line closes any open HTML tags
                                if let Some(last_tag) = html_tag_stack.last() {
                                    if is_html_closing_tag(content, last_tag) {
                                        html_tag_stack.pop();

                                        // If stack is empty, HTML block is complete
                                        if html_tag_stack.is_empty() {
                                            blocks.push(Block::Html {
                                                lines: current_html_block.clone(),
                                                has_preceding_blank: html_block_has_preceding_blank,
                                            });
                                            current_html_block.clear();
                                            in_html_block = false;
                                        }
                                    } else if let Some(new_tag) = is_block_html_opening_tag(content) {
                                        // Nested opening tag within HTML block
                                        if !is_self_closing_tag(content) {
                                            html_tag_stack.push(new_tag);
                                        }
                                    }
                                }
                                had_preceding_blank = false;
                            } else {
                                // Not in HTML block - check if this line starts one
                                if let Some(tag_name) = is_block_html_opening_tag(content) {
                                    // Flush current paragraph before starting HTML block
                                    if in_code {
                                        blocks.push(Block::Code {
                                            lines: current_code_block.clone(),
                                            has_preceding_blank: code_block_has_preceding_blank,
                                        });
                                        current_code_block.clear();
                                        in_code = false;
                                    } else if !current_paragraph.is_empty() {
                                        blocks.push(Block::Paragraph(current_paragraph.clone()));
                                        current_paragraph.clear();
                                    }

                                    // Start new HTML block
                                    in_html_block = true;
                                    html_block_has_preceding_blank = had_preceding_blank;
                                    current_html_block.push(content.clone());

                                    // Check if it's self-closing or needs a closing tag
                                    if is_self_closing_tag(content) {
                                        // Self-closing tag - complete the HTML block immediately
                                        blocks.push(Block::Html {
                                            lines: current_html_block.clone(),
                                            has_preceding_blank: html_block_has_preceding_blank,
                                        });
                                        current_html_block.clear();
                                        in_html_block = false;
                                    } else {
                                        // Regular opening tag - push to stack
                                        html_tag_stack.push(tag_name);
                                    }
                                } else {
                                    // Regular content line - add to paragraph
                                    if in_code {
                                        // Switching from code to content
                                        blocks.push(Block::Code {
                                            lines: current_code_block.clone(),
                                            has_preceding_blank: code_block_has_preceding_blank,
                                        });
                                        current_code_block.clear();
                                        in_code = false;
                                    }
                                    current_paragraph.push(content.clone());
                                }
                                had_preceding_blank = false; // Reset after content
                            }
                        }
                        LineType::CodeBlock(content, indent) => {
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            if in_html_block {
                                // Switching from HTML block to code (shouldn't happen normally, but handle it)
                                blocks.push(Block::Html {
                                    lines: current_html_block.clone(),
                                    has_preceding_blank: html_block_has_preceding_blank,
                                });
                                current_html_block.clear();
                                html_tag_stack.clear();
                                in_html_block = false;
                            }
                            if !in_code {
                                // Switching from content to code
                                if !current_paragraph.is_empty() {
                                    blocks.push(Block::Paragraph(current_paragraph.clone()));
                                    current_paragraph.clear();
                                }
                                in_code = true;
                                // Record whether there was a blank line before this code block
                                code_block_has_preceding_blank = had_preceding_blank;
                            }
                            current_code_block.push((content.clone(), *indent));
                            had_preceding_blank = false; // Reset after code
                        }
                        LineType::SemanticLine(content) => {
                            // Semantic lines are standalone - flush any current block and add as separate block
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            if in_code {
                                blocks.push(Block::Code {
                                    lines: current_code_block.clone(),
                                    has_preceding_blank: code_block_has_preceding_blank,
                                });
                                current_code_block.clear();
                                in_code = false;
                            } else if in_html_block {
                                blocks.push(Block::Html {
                                    lines: current_html_block.clone(),
                                    has_preceding_blank: html_block_has_preceding_blank,
                                });
                                current_html_block.clear();
                                html_tag_stack.clear();
                                in_html_block = false;
                            } else if !current_paragraph.is_empty() {
                                blocks.push(Block::Paragraph(current_paragraph.clone()));
                                current_paragraph.clear();
                            }
                            // Add semantic line as its own block
                            blocks.push(Block::SemanticLine(content.clone()));
                            had_preceding_blank = false; // Reset after semantic line
                        }
                        LineType::SnippetLine(content) => {
                            // Snippet delimiters (-8<-) are standalone - flush any current block and add as separate block
                            // Unlike semantic lines, snippet lines don't add extra blank lines around them
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            if in_code {
                                blocks.push(Block::Code {
                                    lines: current_code_block.clone(),
                                    has_preceding_blank: code_block_has_preceding_blank,
                                });
                                current_code_block.clear();
                                in_code = false;
                            } else if in_html_block {
                                blocks.push(Block::Html {
                                    lines: current_html_block.clone(),
                                    has_preceding_blank: html_block_has_preceding_blank,
                                });
                                current_html_block.clear();
                                html_tag_stack.clear();
                                in_html_block = false;
                            } else if !current_paragraph.is_empty() {
                                blocks.push(Block::Paragraph(current_paragraph.clone()));
                                current_paragraph.clear();
                            }
                            // Add snippet line as its own block
                            blocks.push(Block::SnippetLine(content.clone()));
                            had_preceding_blank = false;
                        }
                        LineType::DivMarker(content) => {
                            // Div markers (::: opening or closing) are standalone structural delimiters
                            // Flush any current block and add as separate block
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            if in_code {
                                blocks.push(Block::Code {
                                    lines: current_code_block.clone(),
                                    has_preceding_blank: code_block_has_preceding_blank,
                                });
                                current_code_block.clear();
                                in_code = false;
                            } else if in_html_block {
                                blocks.push(Block::Html {
                                    lines: current_html_block.clone(),
                                    has_preceding_blank: html_block_has_preceding_blank,
                                });
                                current_html_block.clear();
                                html_tag_stack.clear();
                                in_html_block = false;
                            } else if !current_paragraph.is_empty() {
                                blocks.push(Block::Paragraph(current_paragraph.clone()));
                                current_paragraph.clear();
                            }
                            blocks.push(Block::DivMarker(content.clone()));
                            had_preceding_blank = false;
                        }
                        LineType::AdmonitionHeader(header_text, indent) => {
                            flush_admonition(
                                &mut blocks,
                                &mut in_admonition_block,
                                &mut admonition_header,
                                &mut admonition_content,
                            );
                            // Flush other current blocks
                            if in_code {
                                blocks.push(Block::Code {
                                    lines: current_code_block.clone(),
                                    has_preceding_blank: code_block_has_preceding_blank,
                                });
                                current_code_block.clear();
                                in_code = false;
                            } else if in_html_block {
                                blocks.push(Block::Html {
                                    lines: current_html_block.clone(),
                                    has_preceding_blank: html_block_has_preceding_blank,
                                });
                                current_html_block.clear();
                                html_tag_stack.clear();
                                in_html_block = false;
                            } else if !current_paragraph.is_empty() {
                                blocks.push(Block::Paragraph(current_paragraph.clone()));
                                current_paragraph.clear();
                            }
                            // Start new admonition block
                            in_admonition_block = true;
                            admonition_header = Some((header_text.clone(), *indent));
                            admonition_content.clear();
                            had_preceding_blank = false;
                        }
                        LineType::AdmonitionContent(content, indent) => {
                            if in_admonition_block {
                                // Add to current admonition body
                                admonition_content.push((content.clone(), *indent));
                            } else {
                                // Admonition content without a header should not happen,
                                // but treat it as regular content to avoid data loss
                                current_paragraph.push(content.clone());
                            }
                            had_preceding_blank = false;
                        }
                    }
                }

                // Push all remaining pending blocks independently
                flush_admonition(
                    &mut blocks,
                    &mut in_admonition_block,
                    &mut admonition_header,
                    &mut admonition_content,
                );
                if in_code && !current_code_block.is_empty() {
                    blocks.push(Block::Code {
                        lines: current_code_block,
                        has_preceding_blank: code_block_has_preceding_blank,
                    });
                }
                if in_html_block && !current_html_block.is_empty() {
                    blocks.push(Block::Html {
                        lines: current_html_block,
                        has_preceding_blank: html_block_has_preceding_blank,
                    });
                }
                if !current_paragraph.is_empty() {
                    blocks.push(Block::Paragraph(current_paragraph));
                }

                // Helper: check if a line (raw source or stripped content) is exempt
                // from line-length checks. Link reference definitions are always exempt;
                // standalone link/image lines are exempt when strict mode is off.
                // Also checks content after stripping list markers, since list item
                // continuation lines may contain link ref defs.
                let is_exempt_line = |raw_line: &str| -> bool {
                    let trimmed = raw_line.trim();
                    // Link reference definitions: always exempt
                    if trimmed.starts_with('[') && trimmed.contains("]:") && LINK_REF_PATTERN.is_match(trimmed) {
                        return true;
                    }
                    // Also check after stripping list markers (for list item content)
                    if is_list_item(trimmed) {
                        let (_, content) = extract_list_marker_and_content(trimmed);
                        let content_trimmed = content.trim();
                        if content_trimmed.starts_with('[')
                            && content_trimmed.contains("]:")
                            && LINK_REF_PATTERN.is_match(content_trimmed)
                        {
                            return true;
                        }
                    }
                    // Standalone link/image lines: exempt when not strict
                    if !config.strict && is_standalone_link_or_image_line(raw_line) {
                        return true;
                    }
                    false
                };

                // Check if reflowing is needed (only for content paragraphs, not code blocks or nested lists)
                // Exclude link reference definitions and standalone link lines from content
                // so they don't pollute combined_content or trigger false reflow.
                let content_lines: Vec<String> = list_item_lines
                    .iter()
                    .filter_map(|line| {
                        if let LineType::Content(s) = line {
                            if is_exempt_line(s) {
                                return None;
                            }
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();

                // Check if we need to reflow this list item
                // We check the combined content to see if it exceeds length limits
                let combined_content = content_lines.join(" ").trim().to_string();

                // Helper to check if we should reflow in normalize mode
                let should_normalize = || {
                    // Don't normalize if the list item only contains nested lists, code blocks, or semantic lines
                    // DO normalize if it has plain text content that spans multiple lines
                    let has_code_blocks = blocks.iter().any(|b| matches!(b, Block::Code { .. }));
                    let has_semantic_lines = blocks.iter().any(|b| matches!(b, Block::SemanticLine(_)));
                    let has_snippet_lines = blocks.iter().any(|b| matches!(b, Block::SnippetLine(_)));
                    let has_div_markers = blocks.iter().any(|b| matches!(b, Block::DivMarker(_)));
                    let has_admonitions = blocks.iter().any(|b| matches!(b, Block::Admonition { .. }));
                    let has_paragraphs = blocks.iter().any(|b| matches!(b, Block::Paragraph(_)));

                    // If we have structural blocks but no paragraphs, don't normalize
                    if (has_code_blocks
                        || has_semantic_lines
                        || has_snippet_lines
                        || has_div_markers
                        || has_admonitions)
                        && !has_paragraphs
                    {
                        return false;
                    }

                    // If we have paragraphs, check if they span multiple lines or there are multiple blocks
                    if has_paragraphs {
                        // Count only paragraphs that contain at least one non-exempt line.
                        // Paragraphs consisting entirely of link ref defs or standalone links
                        // should not trigger normalization.
                        let paragraph_count = blocks
                            .iter()
                            .filter(|b| {
                                if let Block::Paragraph(para_lines) = b {
                                    !para_lines.iter().all(|line| is_exempt_line(line))
                                } else {
                                    false
                                }
                            })
                            .count();
                        if paragraph_count > 1 {
                            // Multiple non-exempt paragraph blocks should be normalized
                            return true;
                        }

                        // Single paragraph block: normalize if it has multiple content lines
                        if content_lines.len() > 1 {
                            return true;
                        }
                    }

                    false
                };

                let needs_reflow = match config.reflow_mode {
                    ReflowMode::Normalize => {
                        // Only reflow if:
                        // 1. Any non-exempt paragraph, when joined, exceeds the limit, OR
                        // 2. Any admonition content line exceeds the limit, OR
                        // 3. The list item should be normalized (has multi-line plain text)
                        let any_paragraph_exceeds = blocks.iter().any(|block| match block {
                            Block::Paragraph(para_lines) => {
                                if para_lines.iter().all(|line| is_exempt_line(line)) {
                                    return false;
                                }
                                let joined = para_lines.join(" ");
                                let with_marker = format!("{}{}", " ".repeat(indent_size), joined.trim());
                                self.calculate_effective_length(&with_marker) > config.line_length.get()
                            }
                            Block::Admonition {
                                content_lines,
                                header_indent,
                                ..
                            } => content_lines.iter().any(|(content, indent)| {
                                if content.is_empty() {
                                    return false;
                                }
                                let with_indent = format!("{}{}", " ".repeat(*indent.max(header_indent)), content);
                                self.calculate_effective_length(&with_indent) > config.line_length.get()
                            }),
                            _ => false,
                        });
                        if any_paragraph_exceeds {
                            true
                        } else {
                            should_normalize()
                        }
                    }
                    ReflowMode::SentencePerLine => {
                        // Check if list item has multiple sentences
                        let sentences = split_into_sentences(&combined_content);
                        sentences.len() > 1
                    }
                    ReflowMode::SemanticLineBreaks => {
                        let sentences = split_into_sentences(&combined_content);
                        sentences.len() > 1
                            || (list_start..i).any(|line_idx| {
                                let line = lines[line_idx];
                                let trimmed = line.trim();
                                if trimmed.is_empty() || is_exempt_line(line) {
                                    return false;
                                }
                                self.calculate_effective_length(line) > config.line_length.get()
                            })
                    }
                    ReflowMode::Default => {
                        // In default mode, only reflow if any individual non-exempt line exceeds limit
                        (list_start..i).any(|line_idx| {
                            let line = lines[line_idx];
                            let trimmed = line.trim();
                            // Skip blank lines and exempt lines
                            if trimmed.is_empty() || is_exempt_line(line) {
                                return false;
                            }
                            self.calculate_effective_length(line) > config.line_length.get()
                        })
                    }
                };

                if needs_reflow {
                    let start_range = line_index.whole_line_range(list_start + 1);
                    let end_line = i - 1;
                    let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
                        line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
                    } else {
                        line_index.whole_line_range(end_line + 1)
                    };
                    let byte_range = start_range.start..end_range.end;

                    // Reflow each block (paragraphs only, preserve code blocks)
                    // When line_length = 0 (no limit), use a very large value for reflow
                    let reflow_line_length = if config.line_length.is_unlimited() {
                        usize::MAX
                    } else {
                        config.line_length.get().saturating_sub(indent_size).max(1)
                    };
                    let reflow_options = crate::utils::text_reflow::ReflowOptions {
                        line_length: reflow_line_length,
                        break_on_sentences: true,
                        preserve_breaks: false,
                        sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
                        semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
                        abbreviations: config.abbreviations_for_reflow(),
                        length_mode: self.reflow_length_mode(),
                        attr_lists: ctx.flavor.supports_attr_lists(),
                        require_sentence_capital: config.require_sentence_capital,
                        max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
                            Some(4)
                        } else {
                            None
                        },
                    };

                    let mut result: Vec<String> = Vec::new();
                    let mut is_first_block = true;

                    for (block_idx, block) in blocks.iter().enumerate() {
                        match block {
                            Block::Paragraph(para_lines) => {
                                // If every line in this paragraph is exempt (link ref defs,
                                // standalone links), preserve the paragraph verbatim instead
                                // of reflowing it. Reflowing would corrupt link ref defs.
                                let all_exempt = para_lines.iter().all(|line| is_exempt_line(line));

                                if all_exempt {
                                    for (idx, line) in para_lines.iter().enumerate() {
                                        if is_first_block && idx == 0 {
                                            result.push(format!("{marker}{line}"));
                                            is_first_block = false;
                                        } else {
                                            result.push(format!("{expected_indent}{line}"));
                                        }
                                    }
                                } else {
                                    // Split the paragraph into segments at hard break boundaries
                                    // Each segment can be reflowed independently
                                    let segments = split_into_segments(para_lines);

                                    for (segment_idx, segment) in segments.iter().enumerate() {
                                        // Check if this segment ends with a hard break and what type
                                        let hard_break_type = segment.last().and_then(|line| {
                                            let line = line.strip_suffix('\r').unwrap_or(line);
                                            if line.ends_with('\\') {
                                                Some("\\")
                                            } else if line.ends_with("  ") {
                                                Some("  ")
                                            } else {
                                                None
                                            }
                                        });

                                        // Join and reflow the segment (removing the hard break marker for processing)
                                        let segment_for_reflow: Vec<String> = segment
                                            .iter()
                                            .map(|line| {
                                                // Strip hard break marker (2 spaces or backslash) for reflow processing
                                                if line.ends_with('\\') {
                                                    line[..line.len() - 1].trim_end().to_string()
                                                } else if line.ends_with("  ") {
                                                    line[..line.len() - 2].trim_end().to_string()
                                                } else {
                                                    line.clone()
                                                }
                                            })
                                            .collect();

                                        let segment_text = segment_for_reflow.join(" ").trim().to_string();
                                        if !segment_text.is_empty() {
                                            let reflowed =
                                                crate::utils::text_reflow::reflow_line(&segment_text, &reflow_options);

                                            if is_first_block && segment_idx == 0 {
                                                // First segment of first block starts with marker
                                                result.push(format!("{marker}{}", reflowed[0]));
                                                for line in reflowed.iter().skip(1) {
                                                    result.push(format!("{expected_indent}{line}"));
                                                }
                                                is_first_block = false;
                                            } else {
                                                // Subsequent segments
                                                for line in reflowed {
                                                    result.push(format!("{expected_indent}{line}"));
                                                }
                                            }

                                            // If this segment had a hard break, add it back to the last line
                                            // Preserve the original hard break format (backslash or two spaces)
                                            if let Some(break_marker) = hard_break_type
                                                && let Some(last_line) = result.last_mut()
                                            {
                                                last_line.push_str(break_marker);
                                            }
                                        }
                                    }
                                }

                                // Add blank line after paragraph block if there's a next block.
                                // Check if next block is a code block that doesn't want a preceding blank.
                                // Also don't add blank lines before snippet lines (they should stay tight).
                                // Only add if not already ending with one (avoids double blanks).
                                if block_idx < blocks.len() - 1 {
                                    let next_block = &blocks[block_idx + 1];
                                    let should_add_blank = match next_block {
                                        Block::Code {
                                            has_preceding_blank, ..
                                        } => *has_preceding_blank,
                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
                                        _ => true, // For all other blocks, add blank line
                                    };
                                    if should_add_blank && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true)
                                    {
                                        result.push(String::new());
                                    }
                                }
                            }
                            Block::Code {
                                lines: code_lines,
                                has_preceding_blank: _,
                            } => {
                                // Preserve code blocks as-is with original indentation
                                // NOTE: Blank line before code block is handled by the previous block
                                // (see paragraph block's logic above)

                                for (idx, (content, orig_indent)) in code_lines.iter().enumerate() {
                                    if is_first_block && idx == 0 {
                                        // First line of first block gets marker
                                        result.push(format!(
                                            "{marker}{}",
                                            " ".repeat(orig_indent - marker_len) + content
                                        ));
                                        is_first_block = false;
                                    } else if content.is_empty() {
                                        result.push(String::new());
                                    } else {
                                        result.push(format!("{}{}", " ".repeat(*orig_indent), content));
                                    }
                                }
                            }
                            Block::SemanticLine(content) => {
                                // Preserve semantic lines (NOTE:, WARNING:, etc.) as-is on their own line.
                                // Only add blank before if not already ending with one.
                                if !is_first_block && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true) {
                                    result.push(String::new());
                                }

                                if is_first_block {
                                    // First block starts with marker
                                    result.push(format!("{marker}{content}"));
                                    is_first_block = false;
                                } else {
                                    // Subsequent blocks use expected indent
                                    result.push(format!("{expected_indent}{content}"));
                                }

                                // Add blank line after semantic line if there's a next block.
                                // Only add if not already ending with one.
                                if block_idx < blocks.len() - 1 {
                                    let next_block = &blocks[block_idx + 1];
                                    let should_add_blank = match next_block {
                                        Block::Code {
                                            has_preceding_blank, ..
                                        } => *has_preceding_blank,
                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
                                        _ => true, // For all other blocks, add blank line
                                    };
                                    if should_add_blank && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true)
                                    {
                                        result.push(String::new());
                                    }
                                }
                            }
                            Block::SnippetLine(content) => {
                                // Preserve snippet delimiters (-8<-) as-is on their own line
                                // Unlike semantic lines, snippet lines don't add extra blank lines
                                if is_first_block {
                                    // First block starts with marker
                                    result.push(format!("{marker}{content}"));
                                    is_first_block = false;
                                } else {
                                    // Subsequent blocks use expected indent
                                    result.push(format!("{expected_indent}{content}"));
                                }
                                // No blank lines added before or after snippet delimiters
                            }
                            Block::DivMarker(content) => {
                                // Preserve div markers (::: opening or closing) as-is on their own line
                                if is_first_block {
                                    result.push(format!("{marker}{content}"));
                                    is_first_block = false;
                                } else {
                                    result.push(format!("{expected_indent}{content}"));
                                }
                            }
                            Block::Html {
                                lines: html_lines,
                                has_preceding_blank: _,
                            } => {
                                // Preserve HTML blocks exactly as-is with original indentation
                                // NOTE: Blank line before HTML block is handled by the previous block

                                for (idx, line) in html_lines.iter().enumerate() {
                                    if is_first_block && idx == 0 {
                                        // First line of first block gets marker
                                        result.push(format!("{marker}{line}"));
                                        is_first_block = false;
                                    } else if line.is_empty() {
                                        // Preserve blank lines inside HTML blocks
                                        result.push(String::new());
                                    } else {
                                        // Preserve lines with their original content (already includes indentation)
                                        result.push(format!("{expected_indent}{line}"));
                                    }
                                }

                                // Add blank line after HTML block if there's a next block.
                                // Only add if not already ending with one (avoids double blanks
                                // when the HTML block itself contained a trailing blank line).
                                if block_idx < blocks.len() - 1 {
                                    let next_block = &blocks[block_idx + 1];
                                    let should_add_blank = match next_block {
                                        Block::Code {
                                            has_preceding_blank, ..
                                        } => *has_preceding_blank,
                                        Block::Html {
                                            has_preceding_blank, ..
                                        } => *has_preceding_blank,
                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
                                        _ => true, // For all other blocks, add blank line
                                    };
                                    if should_add_blank && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true)
                                    {
                                        result.push(String::new());
                                    }
                                }
                            }
                            Block::Admonition {
                                header,
                                header_indent,
                                content_lines: admon_lines,
                            } => {
                                // Reconstruct admonition block with header at original indent
                                // and body content reflowed to fit within the line length limit

                                // Add blank line before admonition if not first block
                                if !is_first_block && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true) {
                                    result.push(String::new());
                                }

                                // Output the header at its original indent
                                let header_indent_str = " ".repeat(*header_indent);
                                if is_first_block {
                                    result.push(format!(
                                        "{marker}{}",
                                        " ".repeat(header_indent.saturating_sub(marker_len)) + header
                                    ));
                                    is_first_block = false;
                                } else {
                                    result.push(format!("{header_indent_str}{header}"));
                                }

                                // Derive body indent from the first non-empty content line's
                                // stored indent, falling back to header_indent + 4 for
                                // empty-body admonitions
                                let body_indent = admon_lines
                                    .iter()
                                    .find(|(content, _)| !content.is_empty())
                                    .map(|(_, indent)| *indent)
                                    .unwrap_or(header_indent + 4);
                                let body_indent_str = " ".repeat(body_indent);

                                // Collect body content into paragraphs separated by blank lines
                                let mut body_paragraphs: Vec<Vec<String>> = Vec::new();
                                let mut current_para: Vec<String> = Vec::new();

                                for (content, _orig_indent) in admon_lines {
                                    if content.is_empty() {
                                        if !current_para.is_empty() {
                                            body_paragraphs.push(current_para.clone());
                                            current_para.clear();
                                        }
                                    } else {
                                        current_para.push(content.clone());
                                    }
                                }
                                if !current_para.is_empty() {
                                    body_paragraphs.push(current_para);
                                }

                                // Reflow each paragraph in the body
                                for paragraph in &body_paragraphs {
                                    // Add blank line before each paragraph (including the first, after the header)
                                    result.push(String::new());

                                    let paragraph_text = paragraph.join(" ").trim().to_string();
                                    if paragraph_text.is_empty() {
                                        continue;
                                    }

                                    // Reflow with adjusted line length
                                    let admon_reflow_length = if config.line_length.is_unlimited() {
                                        usize::MAX
                                    } else {
                                        config.line_length.get().saturating_sub(body_indent).max(1)
                                    };

                                    let admon_reflow_options = crate::utils::text_reflow::ReflowOptions {
                                        line_length: admon_reflow_length,
                                        break_on_sentences: true,
                                        preserve_breaks: false,
                                        sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
                                        semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
                                        abbreviations: config.abbreviations_for_reflow(),
                                        length_mode: self.reflow_length_mode(),
                                        attr_lists: ctx.flavor.supports_attr_lists(),
                                        require_sentence_capital: config.require_sentence_capital,
                                        max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
                                            Some(4)
                                        } else {
                                            None
                                        },
                                    };

                                    let reflowed =
                                        crate::utils::text_reflow::reflow_line(&paragraph_text, &admon_reflow_options);
                                    for line in &reflowed {
                                        result.push(format!("{body_indent_str}{line}"));
                                    }
                                }

                                // Add blank line after admonition if there's a next block
                                if block_idx < blocks.len() - 1 {
                                    let next_block = &blocks[block_idx + 1];
                                    let should_add_blank = match next_block {
                                        Block::Code {
                                            has_preceding_blank, ..
                                        } => *has_preceding_blank,
                                        Block::SnippetLine(_) | Block::DivMarker(_) => false,
                                        _ => true,
                                    };
                                    if should_add_blank && result.last().map(|s: &String| !s.is_empty()).unwrap_or(true)
                                    {
                                        result.push(String::new());
                                    }
                                }
                            }
                        }
                    }

                    let reflowed_text = result.join(line_ending);

                    // Preserve trailing newline
                    let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
                        format!("{reflowed_text}{line_ending}")
                    } else {
                        reflowed_text
                    };

                    // Get the original text to compare
                    let original_text = &ctx.content[byte_range.clone()];

                    // Only generate a warning if the replacement is different from the original
                    if original_text != replacement {
                        // Generate an appropriate message based on why reflow is needed
                        let message = match config.reflow_mode {
                            ReflowMode::SentencePerLine => {
                                let num_sentences = split_into_sentences(&combined_content).len();
                                let num_lines = content_lines.len();
                                if num_lines == 1 {
                                    // Single line with multiple sentences
                                    format!("Line contains {num_sentences} sentences (one sentence per line required)")
                                } else {
                                    // Multiple lines - could be split sentences or mixed
                                    format!(
                                        "Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
                                    )
                                }
                            }
                            ReflowMode::SemanticLineBreaks => {
                                let num_sentences = split_into_sentences(&combined_content).len();
                                format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
                            }
                            ReflowMode::Normalize => {
                                // Find the longest non-exempt paragraph when joined
                                let max_para_length = blocks
                                    .iter()
                                    .filter_map(|block| {
                                        if let Block::Paragraph(para_lines) = block {
                                            if para_lines.iter().all(|line| is_exempt_line(line)) {
                                                return None;
                                            }
                                            let joined = para_lines.join(" ");
                                            let with_indent = format!("{}{}", " ".repeat(indent_size), joined.trim());
                                            Some(self.calculate_effective_length(&with_indent))
                                        } else {
                                            None
                                        }
                                    })
                                    .max()
                                    .unwrap_or(0);
                                if max_para_length > config.line_length.get() {
                                    format!(
                                        "Line length {} exceeds {} characters",
                                        max_para_length,
                                        config.line_length.get()
                                    )
                                } else {
                                    "Multi-line content can be normalized".to_string()
                                }
                            }
                            ReflowMode::Default => {
                                // Report the actual longest non-exempt line, not the combined content
                                let max_length = (list_start..i)
                                    .filter(|&line_idx| {
                                        let line = lines[line_idx];
                                        let trimmed = line.trim();
                                        !trimmed.is_empty() && !is_exempt_line(line)
                                    })
                                    .map(|line_idx| self.calculate_effective_length(lines[line_idx]))
                                    .max()
                                    .unwrap_or(0);
                                format!(
                                    "Line length {} exceeds {} characters",
                                    max_length,
                                    config.line_length.get()
                                )
                            }
                        };

                        warnings.push(LintWarning {
                            rule_name: Some(self.name().to_string()),
                            message,
                            line: list_start + 1,
                            column: 1,
                            end_line: end_line + 1,
                            end_column: lines[end_line].len() + 1,
                            severity: Severity::Warning,
                            fix: Some(crate::rule::Fix {
                                range: byte_range,
                                replacement,
                            }),
                        });
                    }
                }
                continue;
            }

            // Found start of a paragraph - collect all lines in it
            let paragraph_start = i;
            let mut paragraph_lines = vec![lines[i]];
            i += 1;

            while i < lines.len() {
                let next_line = lines[i];
                let next_line_num = i + 1;
                let next_trimmed = next_line.trim();

                // Stop at paragraph boundaries
                if next_trimmed.is_empty()
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_code_block)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_front_matter)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_block)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_html_comment)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_esm_block)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_expression)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_jsx_block)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.in_mdx_comment)
                    || ctx
                        .line_info(next_line_num)
                        .is_some_and(|info| info.in_mkdocs_container())
                    || (next_line_num > 0
                        && next_line_num <= ctx.lines.len()
                        && ctx.lines[next_line_num - 1].blockquote.is_some())
                    || next_trimmed.starts_with('#')
                    || TableUtils::is_potential_table_row(next_line)
                    || is_list_item(next_trimmed)
                    || is_horizontal_rule(next_trimmed)
                    || (next_trimmed.starts_with('[') && next_line.contains("]:"))
                    || is_template_directive_only(next_line)
                    || is_standalone_attr_list(next_line)
                    || is_snippet_block_delimiter(next_line)
                    || ctx.line_info(next_line_num).is_some_and(|info| info.is_div_marker)
                {
                    break;
                }

                // Check if the previous line ends with a hard break (2+ spaces or backslash)
                if i > 0 && has_hard_break(lines[i - 1]) {
                    // Don't include lines after hard breaks in the same paragraph
                    break;
                }

                paragraph_lines.push(next_line);
                i += 1;
            }

            // Combine paragraph lines into a single string for processing
            // This must be done BEFORE the needs_reflow check for sentence-per-line mode
            let paragraph_text = paragraph_lines.join(" ");

            // Skip reflowing if this paragraph contains definition list items
            // Definition lists are multi-line structures that should not be joined
            let contains_definition_list = paragraph_lines
                .iter()
                .any(|line| crate::utils::is_definition_list_item(line));

            if contains_definition_list {
                // Don't reflow definition lists - skip this paragraph
                i = paragraph_start + paragraph_lines.len();
                continue;
            }

            // Skip reflowing if this paragraph contains MkDocs Snippets markers
            // Snippets blocks (-8<- ... -8<-) should be preserved exactly
            let contains_snippets = paragraph_lines.iter().any(|line| is_snippet_block_delimiter(line));

            if contains_snippets {
                // Don't reflow Snippets blocks - skip this paragraph
                i = paragraph_start + paragraph_lines.len();
                continue;
            }

            // Check if this paragraph needs reflowing
            let needs_reflow = match config.reflow_mode {
                ReflowMode::Normalize => {
                    // In normalize mode, reflow multi-line paragraphs
                    paragraph_lines.len() > 1
                }
                ReflowMode::SentencePerLine => {
                    // In sentence-per-line mode, check if the JOINED paragraph has multiple sentences
                    // Note: we check the joined text because sentences can span multiple lines
                    let sentences = split_into_sentences(&paragraph_text);

                    // Always reflow if multiple sentences on one line
                    if sentences.len() > 1 {
                        true
                    } else if paragraph_lines.len() > 1 {
                        // For single-sentence paragraphs spanning multiple lines:
                        // Reflow if they COULD fit on one line (respecting line-length constraint)
                        if config.line_length.is_unlimited() {
                            // No line-length constraint - always join single sentences
                            true
                        } else {
                            // Only join if it fits within line-length
                            let effective_length = self.calculate_effective_length(&paragraph_text);
                            effective_length <= config.line_length.get()
                        }
                    } else {
                        false
                    }
                }
                ReflowMode::SemanticLineBreaks => {
                    let sentences = split_into_sentences(&paragraph_text);
                    // Reflow if multiple sentences, multiple lines, or any line exceeds limit
                    sentences.len() > 1
                        || paragraph_lines.len() > 1
                        || paragraph_lines
                            .iter()
                            .any(|line| self.calculate_effective_length(line) > config.line_length.get())
                }
                ReflowMode::Default => {
                    // In default mode, only reflow if lines exceed limit
                    paragraph_lines
                        .iter()
                        .any(|line| self.calculate_effective_length(line) > config.line_length.get())
                }
            };

            if needs_reflow {
                // Calculate byte range for this paragraph
                // Use whole_line_range for each line and combine
                let start_range = line_index.whole_line_range(paragraph_start + 1);
                let end_line = paragraph_start + paragraph_lines.len() - 1;

                // For the last line, we want to preserve any trailing newline
                let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
                    // Last line without trailing newline - use line_text_range
                    line_index.line_text_range(end_line + 1, 1, lines[end_line].len() + 1)
                } else {
                    // Not the last line or has trailing newline - use whole_line_range
                    line_index.whole_line_range(end_line + 1)
                };

                let byte_range = start_range.start..end_range.end;

                // Check if the paragraph ends with a hard break and what type
                let hard_break_type = paragraph_lines.last().and_then(|line| {
                    let line = line.strip_suffix('\r').unwrap_or(line);
                    if line.ends_with('\\') {
                        Some("\\")
                    } else if line.ends_with("  ") {
                        Some("  ")
                    } else {
                        None
                    }
                });

                // Reflow the paragraph
                // When line_length = 0 (no limit), use a very large value for reflow
                let reflow_line_length = if config.line_length.is_unlimited() {
                    usize::MAX
                } else {
                    config.line_length.get()
                };
                let reflow_options = crate::utils::text_reflow::ReflowOptions {
                    line_length: reflow_line_length,
                    break_on_sentences: true,
                    preserve_breaks: false,
                    sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
                    semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
                    abbreviations: config.abbreviations_for_reflow(),
                    length_mode: self.reflow_length_mode(),
                    attr_lists: ctx.flavor.supports_attr_lists(),
                    require_sentence_capital: config.require_sentence_capital,
                    max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
                        Some(4)
                    } else {
                        None
                    },
                };
                let mut reflowed = crate::utils::text_reflow::reflow_line(&paragraph_text, &reflow_options);

                // If the original paragraph ended with a hard break, preserve it
                // Preserve the original hard break format (backslash or two spaces)
                if let Some(break_marker) = hard_break_type
                    && !reflowed.is_empty()
                {
                    let last_idx = reflowed.len() - 1;
                    if !has_hard_break(&reflowed[last_idx]) {
                        reflowed[last_idx].push_str(break_marker);
                    }
                }

                let reflowed_text = reflowed.join(line_ending);

                // Preserve trailing newline if the original paragraph had one
                let replacement = if end_line < lines.len() - 1 || ctx.content.ends_with('\n') {
                    format!("{reflowed_text}{line_ending}")
                } else {
                    reflowed_text
                };

                // Get the original text to compare
                let original_text = &ctx.content[byte_range.clone()];

                // Only generate a warning if the replacement is different from the original
                if original_text != replacement {
                    // Create warning with actual fix
                    // In default mode, report the specific line that violates
                    // In normalize mode, report the whole paragraph
                    // In sentence-per-line mode, report the entire paragraph
                    let (warning_line, warning_end_line) = match config.reflow_mode {
                        ReflowMode::Normalize => (paragraph_start + 1, end_line + 1),
                        ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks => {
                            // Highlight the entire paragraph that needs reformatting
                            (paragraph_start + 1, paragraph_start + paragraph_lines.len())
                        }
                        ReflowMode::Default => {
                            // Find the first line that exceeds the limit
                            let mut violating_line = paragraph_start;
                            for (idx, line) in paragraph_lines.iter().enumerate() {
                                if self.calculate_effective_length(line) > config.line_length.get() {
                                    violating_line = paragraph_start + idx;
                                    break;
                                }
                            }
                            (violating_line + 1, violating_line + 1)
                        }
                    };

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: match config.reflow_mode {
                            ReflowMode::Normalize => format!(
                                "Paragraph could be normalized to use line length of {} characters",
                                config.line_length.get()
                            ),
                            ReflowMode::SentencePerLine => {
                                let num_sentences = split_into_sentences(&paragraph_text).len();
                                if paragraph_lines.len() == 1 {
                                    // Single line with multiple sentences
                                    format!("Line contains {num_sentences} sentences (one sentence per line required)")
                                } else {
                                    let num_lines = paragraph_lines.len();
                                    // Multiple lines - could be split sentences or mixed
                                    format!("Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)")
                                }
                            },
                            ReflowMode::SemanticLineBreaks => {
                                let num_sentences = split_into_sentences(&paragraph_text).len();
                                format!(
                                    "Paragraph should use semantic line breaks ({num_sentences} sentences)"
                                )
                            },
                            ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
                        },
                        line: warning_line,
                        column: 1,
                        end_line: warning_end_line,
                        end_column: lines[warning_end_line.saturating_sub(1)].len() + 1,
                        severity: Severity::Warning,
                        fix: Some(crate::rule::Fix {
                            range: byte_range,
                            replacement,
                        }),
                    });
                }
            }
        }

        warnings
    }

    /// Calculate string length based on the configured length mode
    fn calculate_string_length(&self, s: &str) -> usize {
        match self.config.length_mode {
            LengthMode::Chars => s.chars().count(),
            LengthMode::Visual => s.width(),
            LengthMode::Bytes => s.len(),
        }
    }

    /// Calculate effective line length
    ///
    /// Returns the actual display length of the line using the configured length mode.
    fn calculate_effective_length(&self, line: &str) -> usize {
        self.calculate_string_length(line)
    }

    /// Calculate line length with inline link/image URLs removed.
    ///
    /// For each inline link `[text](url)` or image `![alt](url)` on the line,
    /// computes the "savings" from removing the URL portion (keeping only `[text]`
    /// or `![alt]`). Returns `effective_length - total_savings`.
    ///
    /// Handles nested constructs (e.g., `[![img](url)](url)`) by only counting the
    /// outermost construct to avoid double-counting.
    fn calculate_text_only_length(
        &self,
        effective_length: usize,
        line_number: usize,
        ctx: &crate::lint_context::LintContext,
    ) -> usize {
        let line_range = ctx.line_index.line_content_range(line_number);
        let line_byte_end = line_range.end;

        // Collect inline links/images on this line: (byte_offset, byte_end, text_only_display_len)
        let mut constructs: Vec<(usize, usize, usize)> = Vec::new();

        // Binary search: links are sorted by byte_offset, so link.line is non-decreasing
        let link_start = ctx.links.partition_point(|l| l.line < line_number);
        for link in &ctx.links[link_start..] {
            if link.line != line_number {
                break;
            }
            if link.is_reference {
                continue;
            }
            if !matches!(link.link_type, LinkType::Inline) {
                continue;
            }
            if link.byte_end > line_byte_end {
                continue;
            }
            let text_only_len = 2 + self.calculate_string_length(&link.text);
            constructs.push((link.byte_offset, link.byte_end, text_only_len));
        }

        let img_start = ctx.images.partition_point(|i| i.line < line_number);
        for image in &ctx.images[img_start..] {
            if image.line != line_number {
                break;
            }
            if image.is_reference {
                continue;
            }
            if !matches!(image.link_type, LinkType::Inline) {
                continue;
            }
            if image.byte_end > line_byte_end {
                continue;
            }
            let text_only_len = 3 + self.calculate_string_length(&image.alt_text);
            constructs.push((image.byte_offset, image.byte_end, text_only_len));
        }

        if constructs.is_empty() {
            return effective_length;
        }

        // Sort by byte offset to handle overlapping/nested constructs
        constructs.sort_by_key(|&(start, _, _)| start);

        let mut total_savings: usize = 0;
        let mut last_end: usize = 0;

        for (start, end, text_only_len) in &constructs {
            // Skip constructs nested inside a previously counted one
            if *start < last_end {
                continue;
            }
            // Full construct length in configured length mode
            let full_source = &ctx.content[*start..*end];
            let full_len = self.calculate_string_length(full_source);
            total_savings += full_len.saturating_sub(*text_only_len);
            last_end = *end;
        }

        effective_length.saturating_sub(total_savings)
    }
}