1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
/// Rule MD013: Line length
///
/// See [docs/md013.md](../../docs/md013.md) for full documentation, configuration, and examples.
use crate::lint_context::column_at;
use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
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::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, blockquote_continuation_style, code_span_crosses_last_break, code_span_runs_into_indentation,
dominant_blockquote_prefix, is_self_contained_display_math_line, join_sentence_lines, join_soft_break_lines,
reflow_blockquote_content, split_into_sentences, trim_breakable_whitespace,
};
use pulldown_cmark::LinkType;
use toml;
mod block_builder;
mod helpers;
pub mod md013_config;
use crate::rules::md030_list_marker_space::MD030Config;
use crate::utils::html_block::opens_tag_line_html_block;
use crate::utils::is_template_directive_only;
use crate::utils::list_indent_shift::is_lazy_continuation;
use block_builder::{Block, BlockBuilder};
use helpers::{
extract_list_marker_and_content, has_hard_break, holds_only_container_markers, is_github_alert_marker,
is_horizontal_rule, is_html_only_line, is_list_item, is_setext_heading_text_line, is_setext_underline_content,
is_standalone_link_or_image_line, is_unwrappable_line, item_owns_lines_from, markers_padded_with_tab,
may_be_link_ref_def, source_list_marker, split_into_segments, standalone_link_ends_paragraph,
trim_preserving_hard_break,
};
pub use md013_config::MD013Config;
use md013_config::{CjkSoftBreak, LengthMode, ReflowMode};
#[cfg(test)]
mod tests;
use unicode_width::UnicodeWidthStr;
#[derive(Clone, Default)]
pub struct MD013LineLength {
pub(crate) config: MD013Config,
/// MD030 list-marker spacing, applied when reflowing list items so the rewrite
/// uses the configured post-marker spacing rather than a hard-coded single
/// space. Defaults to MD030's defaults (a single space everywhere), which
/// reproduces the previous behaviour exactly. See [`MD030Config::expected_spaces`].
pub(crate) list_spacing: MD030Config,
}
/// Blockquote paragraph line collected for reflow, with original line index for range computation.
struct CollectedBlockquoteLine {
line_idx: usize,
data: BlockquoteLineData,
}
/// A deliberately conservative MDG step candidate.
///
/// Gherkin keywords are localized, so recognizing the word after the marker is
/// not reliable without the complete dialect table. MDG represents steps as
/// unordered Markdown list items; withholding reflow from all such items in the
/// flavor is safer than splitting a step and changing its Gherkin text.
fn is_potential_mdg_step(ctx: &crate::lint_context::LintContext, line_num: usize) -> bool {
let Some(item) = ctx.list_item_on_line(line_num) else {
return false;
};
!item.is_ordered() && matches!(item.marker_char(), Some('*' | '-' | '+'))
}
/// One flag per line of the document: whether a GFM reader takes the line for
/// part of a table, the header line, the delimiter row under it, or a body
/// row after that, up to a blank line or the next block.
///
/// GFM tables need no pipes (`head` over `---:` is a one-cell table), and
/// rumdl's own table detection, which feeds the table rules, wants pipes and
/// leaves such tables to the paragraph collectors. This reads the delimiter
/// row by the GFM grammar instead, in whatever container the line sits:
/// a delimiter row holds no `>`, so stripping every leading `>` and space
/// leaves the row itself.
fn gfm_table_lines(ctx: &crate::lint_context::LintContext) -> Vec<bool> {
let lines = &ctx.lines;
let text = |idx: usize| lines[idx].content(ctx.content).trim_start_matches([' ', '\t', '>']);
// The `>` markers and the width of the whole run of markers and
// whitespace a line starts with.
let prefix = |idx: usize| {
let content = lines[idx].content(ctx.content);
let lead = &content[..content.len() - text(idx).len()];
(lead.matches('>').count(), lead.len())
};
let opaque = |idx: usize| {
let line = &lines[idx];
line.in_code_block || line.in_html_block || line.in_front_matter || line.in_math_block
};
let mut flags = vec![false; lines.len()];
for idx in 1..lines.len() {
let header = idx - 1;
if flags[header]
|| opaque(header)
|| lines[header].heading.is_some()
|| text(header).is_empty()
|| !crate::utils::text_reflow::is_table_delimiter_row(text(idx))
{
continue;
}
flags[header] = true;
flags[idx] = true;
// A body row sits in the delimiter row's container: a line with
// another number of `>` markers, or short of the delimiter row's
// column, is a lazy line, which only a paragraph takes in.
let (quotes, column) = prefix(idx);
for (body, flag) in flags.iter_mut().enumerate().skip(idx + 1) {
let (body_quotes, body_column) = prefix(body);
if opaque(body)
|| lines[body].list_item.is_some()
|| lines[body].heading.is_some()
|| text(body).is_empty()
|| body_quotes != quotes
|| body_column < column
{
break;
}
*flag = true;
}
}
flags
}
/// Whether line `line_num` (1-based) is touched on either boundary by a code
/// span crossing more than one line: a span containing the newline that ends
/// the line before it, or the newline that ends it.
///
/// A renderer reads the line break inside a code span as one space, so such a
/// line is code however it is spelled, and a `$$...$$` expression on it is no
/// display block. A span that begins and ends on the line itself does not
/// matter. `flags` holds one entry per line of the document, indexed here by
/// the 1-based line number, and comes from
/// [`crate::utils::text_reflow::lines_touching_multiline_code_span`], which
/// reads code spans on their own rather than alongside math delimiters: a
/// `$$...$$` pair closes wherever the next `$$` sits, backtick or not, so a
/// backtick between them that in fact opens a span reaching past the line
/// needs a parser that isn't also deciding where the math closes.
fn line_touches_multiline_code_span(flags: &[bool], line_num: usize) -> bool {
line_num
.checked_sub(1)
.and_then(|idx| flags.get(idx))
.copied()
.unwrap_or(false)
}
/// How many bytes of indentation to strip from the 0-indexed continuation
/// line `idx` of a container whose content starts at `content_col`, given
/// that the line is indented `indent`.
///
/// Outside a code span the whole indentation renders as nothing. A code span
/// crossing into the line keeps every character past the container's content
/// column, so only the container's own indentation goes.
fn continuation_indent_to_strip(
ctx: &crate::lint_context::LintContext,
idx: usize,
indent: usize,
content_col: usize,
) -> usize {
if ctx.is_in_code_span_byte_with_or_without_math(ctx.lines[idx].byte_offset) {
indent.min(content_col)
} else {
indent
}
}
/// The content column of the deepest list item enclosing the item on the
/// 0-indexed line `item_idx` that a line indented `indent` still reaches, or 0
/// when it reaches none.
///
/// A lazy continuation line falls short of the innermost item, but it matches
/// every enclosing item out to that one, so their indentation is container
/// indentation and never part of a code span crossing into the line.
fn enclosing_item_content_col_reached(ctx: &crate::lint_context::LintContext, item_idx: usize, indent: usize) -> usize {
let mut limit = ctx.lines[item_idx]
.list_item
.as_ref()
.map_or(0, |item| item.marker_column);
for j in (0..item_idx).rev() {
if limit == 0 {
break;
}
let info = &ctx.lines[j];
if let Some(item) = &info.list_item {
if item.marker_column < limit {
// Enclosing items are met innermost first, and every one
// further out has a smaller content column, so the first one
// reached is the deepest.
if item.content_column <= indent {
return item.content_column;
}
limit = item.marker_column;
}
} else if !info.is_blank && info.indent < limit && !is_lazy_continuation(ctx, j) {
// A line short of the marker column that continues no paragraph
// ended every item that could have enclosed this one.
break;
}
}
0
}
/// `trimmed`, the text of the 0-indexed line `idx` with its end trimmed, with
/// that end restored when a code span crosses the line break after it: the
/// span keeps every character before the break, so the whitespace there is
/// code, and no hard break.
fn restore_code_span_line_end(ctx: &crate::lint_context::LintContext, idx: usize, trimmed: String) -> String {
if !line_ends_in_code_span(ctx, idx) {
return trimmed;
}
let raw = source_line_without_cr(ctx, idx);
let ending = &raw[raw.trim_end_matches([' ', '\t']).len()..];
format!("{}{ending}", trimmed.trim_end_matches([' ', '\t']))
}
/// The text of the 0-indexed blockquote line `idx` after its `>` markers, as a
/// block of the quote whose content starts `content_col` bytes into the quote's
/// content holds it: trimmed at both ends, except where a code span crosses
/// the line break at either end.
///
/// The parsed `content` starts after all of the whitespace following the last
/// `>`, but the quote itself takes only the one optional space after it, and
/// the block inside it only up to its content column. A code span crossing
/// into the line keeps the rest.
fn blockquote_continuation_line(
ctx: &crate::lint_context::LintContext,
idx: usize,
bq: &crate::lint_context::types::BlockquoteInfo,
content_col: usize,
) -> String {
let mut text = trim_preserving_hard_break(&bq.content);
if ctx.is_in_code_span_byte_with_or_without_math(ctx.lines[idx].byte_offset) {
let indent = &bq.prefix[blockquote_content_start(&bq.prefix)..];
text.insert_str(0, &indent[content_col.min(indent.len())..]);
}
restore_code_span_line_end(ctx, idx, text)
}
/// Where the quote's own content starts in a blockquote `prefix`: after the
/// last `>` and the one optional space following it.
fn blockquote_content_start(prefix: &str) -> usize {
let after_marker = prefix.rfind('>').map_or(0, |pos| pos + 1);
after_marker + usize::from(prefix[after_marker..].starts_with(' '))
}
/// Whether a code span crosses the line break ending the 0-indexed line `idx`.
fn line_ends_in_code_span(ctx: &crate::lint_context::LintContext, idx: usize) -> bool {
ctx.is_in_code_span_byte_with_or_without_math(ctx.lines[idx].byte_offset + source_line_without_cr(ctx, idx).len())
}
fn source_line_without_cr<'a>(ctx: &'a crate::lint_context::LintContext, idx: usize) -> &'a str {
let raw = ctx.lines[idx].content(ctx.content);
raw.strip_suffix('\r').unwrap_or(raw)
}
/// Whether any of the lines `start_idx..=end_idx` (0-indexed) is a definition
/// list's term, a definition's marker line holding its text, or a line of a
/// definition the parser opens on a colon touching its text.
///
/// The container reflow paths join these into prose: a term is absorbed into
/// the text around it, and a marker loses the spacing that sets the
/// definition's content column. A definition's later paragraph is prose at
/// the definition's indentation, which the paths keep, and a list or
/// blockquote nested inside a definition holds none of these lines, so both
/// still reflow. The lines of a definition opened on a colon touching its
/// text are prose holding inline constructs the context does not report, so
/// they are kept as written too.
fn holds_definition_list(ctx: &crate::lint_context::LintContext, start_idx: usize, end_idx: usize) -> bool {
(start_idx..=end_idx).any(|idx| {
let line_num = idx + 1;
ctx.is_definition_term(line_num)
|| ctx.in_colon_definition(line_num)
|| ctx
.definition_text_at(line_num)
.is_some_and(|text| text.start_line == line_num && text.marker_prefix_len.is_some())
})
}
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,
code_spans: true,
tables,
headings,
math_blocks: true,
bracket_display_math: false,
paragraphs: true, // Default to true for backwards compatibility
blockquotes: true, // Default to true for backwards compatibility
strict,
stern: false,
heading_line_length: None,
code_block_line_length: None,
reflow: false,
reflow_mode: ReflowMode::default(),
length_mode: LengthMode::default(),
abbreviations: Vec::new(),
require_sentence_capital: true,
ignore_link_urls: true,
atomic_spans: true,
reflow_break_link_text: false,
reflow_length_exemptions: false,
cjk_soft_break: CjkSoftBreak::default(),
},
list_spacing: MD030Config::default(),
}
}
pub fn from_config_struct(config: MD013Config) -> Self {
Self {
config,
list_spacing: MD030Config::default(),
}
}
/// 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
/// Normalized set of reference labels defined in the document.
///
/// Passed to reflow so a bare shortcut reference (`[text]`) is treated as an
/// atomic link only when its label is actually defined; an undefined
/// bracketed run reflows as literal prose.
fn defined_reference_labels(ctx: &crate::lint_context::LintContext) -> std::collections::HashSet<String> {
ctx.reference_definitions()
.iter()
.map(|d| crate::utils::text_reflow::normalize_reference_label(&d.id))
.collect()
}
/// Build the reflow options shared by every MD013 fix path.
///
/// `line_length` varies per call site (some subtract a list-marker or
/// blockquote prefix); every other field is derived uniformly from the
/// effective config and the document flavor. Callers that need a different
/// `max_list_continuation_indent` override it via struct update.
fn reflow_options(
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
line_length: usize,
) -> crate::utils::text_reflow::ReflowOptions {
crate::utils::text_reflow::ReflowOptions {
line_length,
break_on_sentences: true,
preserve_breaks: false,
sentence_per_line: config.reflow_mode == ReflowMode::SentencePerLine,
sentence_pack: config.reflow_mode == ReflowMode::SentencePack,
first_line_length: None,
semantic_line_breaks: config.reflow_mode == ReflowMode::SemanticLineBreaks,
abbreviations: config.abbreviations_for_reflow(),
length_mode: config.reflow_length_mode(),
attr_lists: ctx.flavor.supports_attr_lists(),
myst_roles: ctx.flavor.supports_myst_roles(),
require_sentence_capital: config.require_sentence_capital,
max_list_continuation_indent: if ctx.flavor.requires_strict_list_indent() {
Some(4)
} else {
None
},
defined_references: Some(Self::defined_reference_labels(ctx)),
atomic_spans: config.atomic_spans,
// Container emitters add a continuation prefix. Only the plain
// paragraph path can prove that no literal indentation is added.
wrap_code_spans: false,
break_link_text: config.reflow_break_link_text,
length_exemptions: config.length_exemptions_for_reflow(),
cjk_soft_break: config.cjk_soft_break,
}
}
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::SentencePack
|| config.reflow_mode == ReflowMode::SemanticLineBreaks
|| config.reflow_mode == ReflowMode::Normalize)
{
return false;
}
// Use the smallest applicable budget across line/heading/code-block
// contexts so a stricter context-specific limit doesn't get masked by
// the document-wide budget.
let min_limit = config.min_effective_line_length();
if min_limit.is_unlimited() {
return true;
}
let min_limit_bytes = min_limit.get();
// Quick check: if total content is shorter than the smallest line limit,
// definitely skip.
if ctx.content.len() <= min_limit_bytes {
return true;
}
// Skip if no line exceeds the smallest applicable limit.
!ctx.lines.iter().any(|line| line.byte_len > min_limit_bytes)
}
fn join_paragraph_lines<S: AsRef<str>>(lines: &[S], config: &MD013Config) -> String {
if config.reflow_mode == ReflowMode::SentencePerLine {
join_sentence_lines(lines, config.cjk_soft_break, &config.abbreviations_for_reflow())
} else {
join_soft_break_lines(lines, config.cjk_soft_break)
}
}
fn normalize_mode_needs_reflow<'a, I>(&self, lines: I, config: &MD013Config) -> bool
where
I: IntoIterator<Item = &'a str>,
{
let mut line_count = 0;
let check_length = !config.line_length.is_unlimited();
for line in lines {
line_count += 1;
if check_length && self.calculate_effective_length(line) > config.line_length.get() {
return true;
}
}
line_count > 1
}
}
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(serde_json::Value::as_u64) {
config.line_length = crate::types::LineLength::new(line_length as usize);
}
if let Some(code_blocks) = obj.get("code_blocks").and_then(serde_json::Value::as_bool) {
config.code_blocks = code_blocks;
}
if let Some(code_spans) = obj.get("code_spans").and_then(serde_json::Value::as_bool) {
config.code_spans = code_spans;
}
if let Some(tables) = obj.get("tables").and_then(serde_json::Value::as_bool) {
config.tables = tables;
}
if let Some(headings) = obj.get("headings").and_then(serde_json::Value::as_bool) {
config.headings = headings;
}
if let Some(math_blocks) = obj
.get("math_blocks")
.or_else(|| obj.get("math-blocks"))
.and_then(serde_json::Value::as_bool)
{
config.math_blocks = math_blocks;
}
if let Some(enabled) = obj
.get("bracket_display_math")
.or_else(|| obj.get("bracket-display-math"))
.and_then(serde_json::Value::as_bool)
{
config.bracket_display_math = enabled;
}
if let Some(blockquotes) = obj.get("blockquotes").and_then(serde_json::Value::as_bool) {
config.blockquotes = blockquotes;
}
if let Some(strict) = obj.get("strict").and_then(serde_json::Value::as_bool) {
config.strict = strict;
}
if let Some(stern) = obj.get("stern").and_then(serde_json::Value::as_bool) {
config.stern = stern;
}
if let Some(v) = obj
.get("ignore_link_urls")
.or_else(|| obj.get("ignore-link-urls"))
.or_else(|| obj.get("semantic_link_understanding"))
.or_else(|| obj.get("semantic-link-understanding"))
.and_then(serde_json::Value::as_bool)
{
config.ignore_link_urls = v;
}
if let Some(reflow) = obj.get("reflow").and_then(serde_json::Value::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,
"sentence-pack" | "sentence_pack" => ReflowMode::SentencePack,
"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::SentencePack
|| 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.
// Use the smallest applicable budget across line/heading/code-block contexts
// so candidates aren't dropped when a stricter context-specific budget applies.
let prefilter_limit = effective_config.min_effective_line_length();
let prefilter_skip = prefilter_limit.is_unlimited();
let mut candidate_lines = Vec::new();
if !skip_length_checks && !prefilter_skip {
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 > prefilter_limit.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::SentencePack
|| effective_config.reflow_mode == ReflowMode::SentencePerLine
|| effective_config.reflow_mode == ReflowMode::SemanticLineBreaks))
{
return Ok(warnings);
}
let lines = ctx.raw_lines();
// Whether a 1-indexed line is part of a heading. A setext heading's text
// is the whole paragraph its underline ends, and the parser records the
// heading itself only on the last of those lines, so the earlier ones
// are recognized through `is_setext_heading_text`. Both are O(1)
// per-line fields, so check them directly at each use site instead of
// materializing a full-document HashSet (an extra O(n) pass and
// allocation on a rule that runs on virtually every file).
let is_heading_line_num = |line_number: usize| -> bool {
line_number
.checked_sub(1)
.and_then(|idx| ctx.lines.get(idx))
.is_some_and(|line| line.heading.is_some() || line.is_setext_heading_text)
};
// 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);
}
}
let defined_references = Self::defined_reference_labels(ctx);
// Process candidate lines for line length checks
'line_loop: 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);
// Pick the context-specific limit: heading > code-block > paragraph.
// Headings dominate over code-block context if a setext underline ever
// overlaps a fenced range (defensive — these are mutually exclusive in
// practice, but the explicit ordering documents intent).
let is_heading_line = is_heading_line_num(line_number);
let in_code_block = ctx.line_info(line_number).is_some_and(|info| info.in_code_block);
let line_limit = if is_heading_line {
effective_config.effective_heading_line_length().get()
} else if in_code_block {
effective_config.effective_code_block_line_length().get()
} else {
effective_config.line_length.get()
};
// A context-specific limit of 0 means "unlimited for this context".
if line_limit == 0 {
continue;
}
// Stern mode: like default, but the trailing-token forgiveness is
// disabled — a line with whitespace that exceeds the limit is a
// violation even if the excess is the final token. The "unwrappable"
// line exemption (single token, optionally prefixed by # or >) is
// still honored. Strict overrides stern entirely.
if effective_config.stern && !effective_config.strict && is_unwrappable_line(line) {
continue;
}
// Trailing-token forgiveness: only in default mode (not strict, not stern).
// 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_config.stern {
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;
}
// Ignore inline link/image URLs: suppress when excess comes entirely from inline URLs.
// Disabled by `strict` (all forgiveness off) and by `ignore_link_urls = false`
// (count link/image URLs toward the line length so such lines are flagged).
if !effective_config.strict && effective_config.ignore_link_urls {
let length_without_urls = self.length_without_inline_link_urls(effective_length, line_number, ctx);
if length_without_urls <= line_limit {
continue;
}
}
// Inline code spans cannot be wrapped, so reflow cannot shorten a line
// whose excess length is one. When code-span checking is disabled,
// suppress a violation that would fit once inline code spans are excluded.
if !effective_config.code_spans {
let code_span_width: usize = ctx
.code_spans()
.iter()
.filter(|span| span.line == line_number && span.end_line == line_number)
.map(|span| self.calculate_string_length(&ctx.content[span.byte_offset..span.byte_end]))
.sum();
if effective_length.saturating_sub(code_span_width) <= 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;
}
// Skip MyST comments (% comment) — structural lines, not prose
if ctx.lines[line_idx].is_myst_comment {
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(ctx, line_number) {
continue;
}
// Lines consisting entirely of HTML tags are exempt.
// Badge lines, images with attributes, and similar inline HTML
// are long due to URLs in attributes and can't be meaningfully shortened.
if is_html_only_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 && is_heading_line_num(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))
|| (!effective_config.math_blocks && self.line_is_display_math(line_number, ctx, &effective_config))
|| 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
// Blockquote content is treated as paragraph text, so it's not
// included in the special blocks list here.
if !effective_config.paragraphs {
let is_special_block = is_heading_line_num(line_number)
|| ctx.line_info(line_number).is_some_and(|info| info.in_code_block)
|| 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(super::super::lint_context::types::LineInfo::in_mkdocs_container);
// Skip regular paragraph text when paragraphs = false
if !is_special_block {
continue;
}
}
// Skip blockquote lines when blockquotes = false.
// Also skip lazy continuation lines that belong to a blockquote
// (lines without `>` prefix that follow a blockquote line).
if !effective_config.blockquotes {
if ctx.lines[line_number - 1].blockquote.is_some() {
continue;
}
// Check for lazy continuation: scan backwards through
// non-blank lines to find if this paragraph started with
// a blockquote marker
if !line.trim().is_empty() {
let mut scan = line_number.saturating_sub(2);
loop {
if ctx.lines[scan].blockquote.is_some() {
// Found a blockquote ancestor — this is a lazy continuation
continue 'line_loop;
}
if lines[scan].trim().is_empty() || scan == 0 {
break;
}
scan -= 1;
}
}
}
// 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(),
Some(&defined_references),
effective_config.require_sentence_capital,
effective_config.cjk_soft_break,
);
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;
}
// Sentence packing is checked against the actual paragraph replacement.
// An indivisible sentence may exceed the soft budget without a warning.
if effective_config.reflow
&& effective_config.reflow_mode == ReflowMode::SentencePack
&& !is_heading_line
&& !in_code_block
&& !table_lines_set.contains(&line_number)
&& !self.line_is_display_math(line_number, ctx, &effective_config)
{
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);
let table_lines = gfm_table_lines(ctx);
// Merge paragraph warnings with line warnings, removing duplicates
for mut pw in paragraph_warnings {
if ctx.flavor == crate::config::MarkdownFlavor::MDG
&& (pw.line..=pw.end_line).any(|line_number| is_potential_mdg_step(ctx, line_number))
{
// Keep reporting the excessive line, but do not offer a fix
// whose replacement would split a Gherkin step across lines.
pw.fix = None;
}
if (pw.line..=pw.end_line).any(|line_number| {
let idx = line_number - 1;
table_lines.get(idx).copied().unwrap_or(false) && !ctx.lines[idx].in_table_block
}) {
// A table rumdl's table detection does not see is no
// paragraph to reformat: rewrapping its header or joining
// its rows would turn it back into prose, or into a
// different table. The line warnings stand as they would
// for any table.
continue;
}
// 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)
}
crate::impl_rule_config_sections!(MD013Config);
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());
// Kept in step with the `alias` attributes on `MD013Config::ignore_link_urls`.
// Serde accepts these spellings, so a config using one is honored; without
// them here the key validator reports a documented, working key as unknown.
aliases.insert(
"semantic-link-understanding".to_string(),
"ignore-link-urls".to_string(),
);
aliases.insert(
"semantic_link_understanding".to_string(),
"ignore-link-urls".to_string(),
);
Some(aliases)
}
fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
where
Self: Sized,
{
let rule_config = MD013Config::from_document_config(config);
let mut rule = Self::from_config_struct(rule_config);
// Pull list-marker spacing from MD030 (via the shared serde config loader)
// so reflow rewrites list items with the configured spacing rather than a
// hard-coded single space.
rule.list_spacing = crate::rule_config_serde::load_rule_config::<MD030Config>(config);
Box::new(rule)
}
}
impl MD013LineLength {
/// True when `line_num` (1-indexed) sits inside a `$$` span covering more
/// than one line, as seen by the byte-level math parser.
fn line_in_multiline_math_span(&self, line_num: usize, ctx: &crate::lint_context::LintContext) -> bool {
ctx.math_spans()
.iter()
.any(|span| span.is_display && span.end_line > span.line && (span.line..=span.end_line).contains(&line_num))
}
/// True when `line_num` (1-indexed) holds nothing but display math, whether
/// that is one line of a multi-line block, a delimiter line, or a whole line
/// that is a single complete `$$...$$` span. This is what `math-blocks =
/// false` exempts from the length check.
///
/// rumdl models math twice and the two models miss different containers, so
/// this consults both. `math_spans()` is byte-level and sees a block opened on
/// a list marker line (`- $$`), which the line-level map cannot because that
/// line does not begin with `$$`. `LineInfo::in_math_block` is line-level and
/// sees a four-space-indented block inside a footnote, which the byte-level
/// parser reads as an indented code block. Taking the union only ever adds
/// coverage: neither signal fires on ordinary prose, and an unmatched `$$`
/// opener is flagged by neither, so a stray delimiter cannot exempt the rest
/// of the document.
fn line_is_display_math(
&self,
line_num: usize,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
) -> bool {
self.line_holds_only_multiline_math(line_num, ctx)
|| ctx.line_info(line_num).is_some_and(|info| info.in_math_block)
|| (config.bracket_display_math
&& ctx
.bracket_display_math_lines()
.multiline
.get(line_num.saturating_sub(1))
.copied()
.unwrap_or(false))
|| (config.bracket_display_math
&& ctx
.bracket_display_math_lines()
.standalone
.get(line_num.saturating_sub(1))
.copied()
.unwrap_or(false))
}
/// True when a multi-line `$$` span covers `line_num` (1-indexed) and the line
/// holds nothing besides that math.
///
/// A delimiter line can carry Markdown outside the delimiter: `$$ trailing
/// prose` closes a block and then continues in prose, and `leading prose $$`
/// opens one at the end of a sentence. That prose is ordinary text and counts
/// toward the line's length like any other, so exempting the whole line would
/// hide arbitrarily long prose behind a delimiter. The line-level map already
/// leaves such mixed lines unflagged; this is the byte-level half of the same
/// judgement.
fn line_holds_only_multiline_math(&self, line_num: usize, ctx: &crate::lint_context::LintContext) -> bool {
let Some(info) = ctx.line_info(line_num) else {
return false;
};
let line = info.content(ctx.content);
ctx.math_spans().iter().any(|span| {
if !span.is_display || span.end_line <= span.line || !(span.line..=span.end_line).contains(&line_num) {
return false;
}
if line_num == span.line {
let before = line.get(..span.byte_offset.saturating_sub(info.byte_offset));
if !before.is_none_or(|before| Self::only_structure_precedes_math(before, info)) {
return false;
}
}
if line_num == span.end_line {
let after = line.get(span.byte_end.saturating_sub(info.byte_offset)..);
if !after.is_none_or(|after| after.trim().is_empty()) {
return false;
}
}
true
})
}
/// True when the text before a block's opening delimiter is only the structure
/// the block sits in: indentation, a blockquote marker, or the list marker
/// introducing it. Such a block still owns its whole line.
fn only_structure_precedes_math(before: &str, info: &crate::lint_context::LineInfo) -> bool {
let after_marker =
crate::utils::blockquote::parse_blockquote_prefix(before).map_or(before, |prefix| prefix.content);
if after_marker.trim().is_empty() {
return true;
}
info.list_item.as_ref().is_some_and(|item| {
let mut chars = before.chars();
chars.by_ref().take(item.content_column).count() == item.content_column && chars.as_str().trim().is_empty()
})
}
/// True when `line_num` (1-indexed) falls inside a display-math block that
/// spans more than one line.
///
/// Line breaks carry meaning inside such a block: a TeX `%` comment runs to
/// the end of its line, so joining the lines pulls whatever followed on later
/// lines into the comment and drops it from the rendered equation, which can
/// also leave an environment unclosed. Reflow therefore leaves these blocks
/// alone regardless of the `math_blocks` setting, which governs only whether
/// their length is reported.
///
/// This is `line_is_display_math` minus the case of a whole line that is one
/// complete `$$...$$` span, which
/// [`crate::utils::text_reflow::is_self_contained_display_math_line`]
/// recognizes. Such a line is a block of its own: it has no internal line
/// breaks to lose, and reflow keeps it on the line it was written on
/// through that recognizer rather than through this one.
fn line_in_multiline_math_block(
&self,
line_num: usize,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
) -> bool {
self.line_in_multiline_math_span(line_num, ctx)
|| ctx.line_info(line_num).is_some_and(|info| {
info.in_math_block && !is_self_contained_display_math_line(info.content(ctx.content))
})
|| (config.bracket_display_math
&& ctx
.bracket_display_math_lines()
.multiline
.get(line_num.saturating_sub(1))
.copied()
.unwrap_or(false))
}
fn line_is_standalone_bracket_math(
&self,
line_num: usize,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
) -> bool {
config.bracket_display_math
&& ctx
.bracket_display_math_lines()
.standalone
.get(line_num.saturating_sub(1))
.copied()
.unwrap_or(false)
}
/// True when `line_num` (1-based) sits inside a structure whose lines must be
/// preserved verbatim (code block, front matter, HTML/JSX/MDX block, MkDocs
/// container, div marker, multi-line math block, ...). Used to keep blockquote
/// reflow from touching quoted-looking text embedded in such structures.
fn line_in_verbatim_context(
&self,
line_num: usize,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
) -> bool {
if self.line_in_multiline_math_block(line_num, ctx, config) {
return true;
}
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
})
}
fn is_blockquote_content_boundary(
&self,
content: &str,
line_num: usize,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
) -> bool {
// A code span still open at the end of the line above proves the
// parser read on into this one, whatever it starts with.
if line_num >= 2 && line_ends_in_code_span(ctx, line_num - 2) {
return false;
}
let trimmed = content.trim();
trimmed.is_empty()
|| self.line_in_verbatim_context(line_num, ctx, config)
|| trimmed.starts_with('#')
|| trimmed.starts_with("```")
|| trimmed.starts_with("~~~")
|| trimmed.starts_with('>')
|| TableUtils::is_potential_table_row_with_flavor(content, ctx.flavor)
// A GFM table's rows run on without pipes until a blank line or
// another block, so a quoted row can hold nothing a table needs.
|| ctx.lines.get(line_num - 1).is_some_and(|line| line.in_table_block)
|| is_list_item(trimmed)
|| is_horizontal_rule(content)
// A setext underline ends the quoted paragraph. The text decides
// it: under quoted paragraph text the run is an underline, a dash
// run anywhere else is a thematic break, and stopping at an equals
// run that is neither only leaves text unreflowed.
|| is_setext_underline_content(content)
|| (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)
|| is_html_only_line(content)
|| self.line_is_standalone_bracket_math(line_num, ctx, config)
|| standalone_link_ends_paragraph(ctx, line_num, config)
}
fn generate_blockquote_paragraph_fix(
&self,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
lines: &[&str],
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 defined_references = Self::defined_reference_labels(ctx);
let mut collected: Vec<CollectedBlockquoteLine> = Vec::new();
let mut i = start_idx;
while i < lines.len() {
if let Some(last) = collected.last()
&& has_hard_break(&last.data.content)
&& !line_ends_in_code_span(ctx, last.line_idx)
{
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, config) {
break;
}
collected.push(CollectedBlockquoteLine {
line_idx: i,
data: BlockquoteLineData::explicit(blockquote_continuation_line(ctx, i, bq, 0), bq.prefix.clone()),
});
i += 1;
continue;
}
let lazy_content = lines[i].trim_start();
if self.is_blockquote_content_boundary(lazy_content, line_num, ctx, config) {
break;
}
// A lazy line has no container indentation of its own, so a code
// span crossing into it keeps all of its leading whitespace.
let strip = continuation_indent_to_strip(ctx, i, lines[i].len() - lazy_content.len(), 0);
collected.push(CollectedBlockquoteLine {
line_idx: i,
data: BlockquoteLineData::lazy(restore_code_span_line_end(
ctx,
i,
trim_preserving_hard_break(&lines[i][strip..]),
)),
});
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 pieces: Vec<&str> = line_data.iter().map(|d| d.content.as_str()).collect();
if code_span_runs_into_indentation(&pieces) {
return (None, next_idx);
}
let paragraph_text = Self::join_paragraph_lines(&pieces, config);
// A colon-led line with a line of the paragraph before it opens a
// definition, and joining the lines would flatten the definition list
// into prose. The paragraph's first line is prose whatever it starts
// with, since a definition needs a term on the line before it.
let contains_definition_list = line_data
.iter()
.skip(1)
.any(|d| crate::utils::text_reflow::is_definition_list_marker(&d.content));
if contains_definition_list || holds_definition_list(ctx, paragraph_start, end_line) {
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::SentencePack => true,
ReflowMode::Normalize => {
self.normalize_mode_needs_reflow(line_data.iter().map(|d| d.content.as_str()), config)
}
ReflowMode::SentencePerLine => {
let sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
sentences.len() > 1 || line_data.len() > 1
}
ReflowMode::SemanticLineBreaks => {
let sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
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 mut reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
if config.reflow_mode == ReflowMode::SentencePack
&& continuation_style == crate::utils::text_reflow::BlockquoteContinuationStyle::Lazy
&& !config.line_length.is_unlimited()
{
reflow_options.line_length = config.line_length.get();
reflow_options.first_line_length = Some(reflow_line_length);
}
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 = ctx.whole_line_byte_range(paragraph_start + 1);
let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
ctx.line_text_byte_range(end_line + 1, 1, lines[end_line].len() + 1)
} else {
ctx.whole_line_byte_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 | ReflowMode::SentencePack => {
(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_or(paragraph_start + 1, |line| line.line_idx + 1);
(violating_line, violating_line)
}
};
let warning = LintWarning {
rule_name: Some(self.name().to_string()),
message: match config.reflow_mode {
ReflowMode::SentencePack => "Paragraph should pack complete sentences".to_string(),
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(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.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(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.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)].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(byte_range, replacement)),
};
(Some(warning), next_idx)
}
/// Reflow a single list item that lives inside a blockquote.
///
/// The blockquote paragraph reflow treats a list marker as a content boundary,
/// so `> - long item ...` is never wrapped even though the identical top-level
/// item is. This handles that case: it collects one tight, prose-only list item
/// at the starting blockquote level, reflows the item body to the configured
/// width, and re-emits it with the blockquote prefix preserved and continuation
/// lines aligned under the list content.
///
/// Sibling and nested list items end collection and are reflowed independently
/// by the caller's outer loop (a nested item carries its indent folded into the
/// blockquote prefix, so it reflows correctly on its own). Items that are not
/// simple tight prose - those embedding a code block, table, fence, or hard
/// break - are left untouched (`None`) and the cursor still advances past the
/// whole item so its inner lines are never reprocessed as loose prose.
fn generate_blockquote_list_item_fix(
&self,
ctx: &crate::lint_context::LintContext,
config: &MD013Config,
lines: &[&str],
start_idx: usize,
line_ending: &str,
// One entry per document line, true where a code span crosses one of the
// line's boundaries. The caller reads them off one pass over the document
// and shares them across every item, so an item costs no pass of its own.
code_span_touches: &[bool],
) -> (Option<LintWarning>, usize) {
use crate::utils::blockquote::effective_indent_in_blockquote;
let Some(start_bq) = ctx.lines.get(start_idx).and_then(|line| line.blockquote.as_deref()) else {
return (None, start_idx + 1);
};
let defined_references = Self::defined_reference_labels(ctx);
// A `>`-prefixed line can be marked as a blockquote even inside a fenced code
// block (or other verbatim structure); such content must never be reflowed.
if self.line_in_verbatim_context(start_idx + 1, ctx, config) {
return (None, start_idx + 1);
}
let target_level = start_bq.nesting_level;
// The marker line carries the canonical blockquote prefix: its content begins
// with the list marker, so no list indent has been folded into the prefix.
let bq_prefix = start_bq.prefix.clone();
// A thematic break opens with what looks like a bullet marker (`- - -`).
// It is not a list item, and reflowing it as prose destroys the break.
// The top-level reflow path applies the same exemption.
if is_horizontal_rule(&start_bq.content) {
return (None, start_idx + 1);
}
let (marker, first_body) = extract_list_marker_and_content(&start_bq.content);
if marker.is_empty() {
return (None, start_idx + 1);
}
let marker_width = marker.chars().count();
// Continuation lines of a checkbox item align under the bullet+checkbox, but
// are recognized from the bullet width, matching the top-level list reflow.
let base_marker_width = ["[ ] ", "[x] ", "[X] "]
.iter()
.find_map(|cb| marker.find(*cb))
.unwrap_or(marker_width);
// Collect the item: the marker line plus its tight prose continuation lines.
// `end_idx` always tracks the last consumed line so the cursor advances past
// the entire item, even when it turns out to be too complex to reflow safely.
// The item's content column within the quote's content, which a code
// span crossing into a continuation line leaves in place.
let item_content_col = ctx.lines[start_idx].list_item.as_ref().map_or(0, |item| {
item.content_column
.saturating_sub(blockquote_content_start(&start_bq.prefix))
});
let ends_with_hard_break = |piece: &str, idx: usize| has_hard_break(piece) && !line_ends_in_code_span(ctx, idx);
let first_piece = restore_code_span_line_end(ctx, start_idx, trim_preserving_hard_break(&first_body));
let mut simple = !ends_with_hard_break(&first_piece, start_idx);
let mut body_pieces: Vec<String> = vec![first_piece];
let mut end_idx = start_idx;
let mut i = start_idx + 1;
while i < lines.len() {
let Some(bq) = ctx.lines[i].blockquote.as_deref() else {
// A blank line ends the item.
if lines[i].trim().is_empty() {
break;
}
// A lazy continuation (no `>` marker) is too ambiguous to reflow
// safely. Consume the whole lazy run into this item's span and leave
// the item untouched, so the caller does not reflow the continuation
// in isolation and leave the marker line partially fixed.
simple = false;
while i < lines.len() && ctx.lines[i].blockquote.is_none() && !lines[i].trim().is_empty() {
end_idx = i;
i += 1;
}
break;
};
if bq.nesting_level != target_level {
break;
}
let content = bq.content.as_str();
if content.trim().is_empty() {
// Blank quoted line ends the tight paragraph. A following indented
// paragraph (loose item) is reflowed on its own by the prose path.
break;
}
// A code span still open at the end of the line above proves the
// parser read on into this line, so it is text of this item however
// it is spelled and however far it is indented.
let continues_code_span = line_ends_in_code_span(ctx, i - 1);
let eff_indent = effective_indent_in_blockquote(lines[i], target_level, 0);
if eff_indent < base_marker_width && !continues_code_span {
// Dedented: a sibling list item or text outside this item. Stop here
// and let the outer loop classify it.
break;
}
if is_list_item(content) && !continues_code_span {
// A nested list item: its own item, handled independently. A
// line a code span runs on into is text of this item instead.
break;
}
// An embedded structure (code block, table, fence, nested quote, ...)
// means the item is not simple prose: keep consuming so the cursor clears
// the whole structure, but do not produce a fix.
if self.is_blockquote_content_boundary(content, i + 1, ctx, config) {
simple = false;
}
// A line short of the item's content column continues its paragraph
// lazily, and the item takes none of its indentation.
let content_col_reached = if eff_indent >= item_content_col {
item_content_col
} else {
0
};
let piece = blockquote_continuation_line(ctx, i, bq, content_col_reached);
if ends_with_hard_break(&piece, i) {
simple = false;
}
body_pieces.push(piece);
end_idx = i;
i += 1;
}
let next_idx = end_idx + 1;
if !simple || holds_definition_list(ctx, start_idx, end_idx) || code_span_runs_into_indentation(&body_pieces) {
return (None, next_idx);
}
let exceeds_limit =
|| (start_idx..=end_idx).any(|idx| self.calculate_effective_length(lines[idx]) > config.line_length.get());
let body_text = Self::join_paragraph_lines(&body_pieces, config);
let body_text = trim_breakable_whitespace(&body_text);
// A body line that is one whole `$$...$$` expression renders as a display
// block, so it holds a line of its own and the prose on either side of it
// is reflowed separately. So does a link reference definition opening the
// body, which ends at its line: text joined onto its destination would turn
// it into visible text. Each segment carries whether it is such a line,
// kept as written. A line touched by a code span crossing one of its
// boundaries is code, not a display block. The pieces are the consecutive
// lines from `start_idx`, one piece each.
let body_segments: Vec<(bool, Vec<&str>)> = {
let mut segments: Vec<(bool, Vec<&str>)> = Vec::new();
let mut current: Vec<&str> = Vec::new();
let mut in_leading_definitions = true;
for (offset, piece) in body_pieces.iter().enumerate() {
in_leading_definitions &= may_be_link_ref_def(piece);
let is_display_math = (is_self_contained_display_math_line(piece)
|| self.line_is_standalone_bracket_math(start_idx + offset + 1, ctx, config))
&& !line_touches_multiline_code_span(code_span_touches, start_idx + offset + 1);
if in_leading_definitions || is_display_math {
if !current.is_empty() {
segments.push((false, std::mem::take(&mut current)));
}
segments.push((true, vec![piece.trim_start()]));
} else {
current.push(piece.as_str());
}
}
if !current.is_empty() {
segments.push((false, current));
}
segments
};
let holds_own_line = body_segments.iter().any(|(own_line, _)| *own_line);
// Some bodies cannot be shortened and must stay verbatim, matching the
// exemptions the top-level list reflow applies: link reference definitions
// always, and (in non-strict mode) standalone links/images and HTML-only
// lines. Reflowing a link reference definition would split it after the
// colon/URL and break the definition.
let is_link_ref_def =
body_text.starts_with('[') && body_text.contains("]:") && LINK_REF_PATTERN.is_match(body_text);
let raw_marker_line = lines[start_idx];
let body_is_unwrappable = is_link_ref_def
|| standalone_link_ends_paragraph(ctx, start_idx + 1, config)
|| (!config.strict && is_html_only_line(raw_marker_line));
if body_is_unwrappable {
return (None, next_idx);
}
let needs_reflow = match config.reflow_mode {
ReflowMode::SentencePack => true,
ReflowMode::Normalize => body_pieces.len() > 1 || exceeds_limit(),
ReflowMode::Default => exceeds_limit(),
ReflowMode::SentencePerLine => {
split_into_sentences(
body_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len()
> 1
|| body_pieces.len() > 1
}
ReflowMode::SemanticLineBreaks => {
split_into_sentences(
body_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len()
> 1
|| exceeds_limit()
}
};
if !needs_reflow {
return (None, next_idx);
}
// Apply MD030 list-marker spacing in the spacing-normalizing modes, mirroring
// the top-level list reflow: derive the post-marker spacing from MD030 and let
// the continuation indent follow the resulting content width. Default MD030 (a
// single space) leaves the marker unchanged. MkDocs keeps its rigid indent.
let (marker, marker_width) = if matches!(config.reflow_mode, ReflowMode::Default | ReflowMode::Normalize)
&& !ctx.flavor.requires_strict_list_indent()
{
let is_ordered = marker.starts_with(|c: char| c.is_ascii_digit());
// Bullet/number portion only (e.g. `-`, `1.`); the checkbox is content.
let bullet = marker.split(' ').next().unwrap_or("");
let bullet_len = bullet.chars().count();
let checkbox_tail = &marker[base_marker_width..];
// Decide single- vs multi-line spacing from the rewritten shape. This path
// only handles a single tight prose paragraph (structural or multi-paragraph
// items set `simple = false` and bail out above), so the emitted item stays
// multi-line solely when the joined body wraps past one line. A multi-line
// *source* that collapses onto the marker line must use MD030's single-line
// spacing, matching the top-level reflow. The wrap test measures at the
// single-line content column so it does not depend on the spacing chosen here.
let single_col = self.calculate_string_length(&bq_prefix)
+ bullet_len
+ self.list_spacing.expected_spaces(is_ordered, false, bullet_len)
+ checkbox_tail.chars().count();
// A display-math line or a definition always holds a line of its own,
// so an item that carries one spans several lines whatever the joined
// body measures.
let is_multi = holds_own_line
|| (!body_text.is_empty()
&& self.calculate_effective_length(&format!("{}{body_text}", " ".repeat(single_col)))
> config.line_length.effective_limit());
let spaces = self.list_spacing.expected_spaces(is_ordered, is_multi, bullet_len);
let new_marker = format!("{bullet}{}{checkbox_tail}", " ".repeat(spaces));
let width = new_marker.chars().count();
(new_marker, width)
} else {
(marker, marker_width)
};
// The fix rewrites only this paragraph, so every later line of the quote
// keeps its indentation. A marker that moves the item's content column past
// one of them changes the block that line belongs to: `> 7. b` beside
// `> - item` opens a list after the item, and beside `> - item` a list
// nested in it. Such an item keeps its marker as written.
let (marker, marker_width) = match source_list_marker(&start_bq.content) {
Some(source) => {
let source_col = if item_content_col > 0 {
item_content_col
} else {
source.content_col
};
let (low, high) = (source_col.min(marker_width), source_col.max(marker_width));
let moves_a_later_line = ctx.lines[next_idx..]
.iter()
.zip(&lines[next_idx..])
.map_while(|(info, line)| {
info.blockquote
.as_deref()
.filter(|bq| bq.nesting_level >= target_level)
.map(|bq| (bq, line))
})
.any(|(bq, line)| {
let indent = effective_indent_in_blockquote(line, target_level, 0);
bq.nesting_level == target_level
&& !bq.content.trim().is_empty()
&& (low..high).contains(&indent)
});
if moves_a_later_line {
(source.text, source.content_col)
} else {
(marker, marker_width)
}
}
None => (marker, marker_width),
};
let prefix_width = self.calculate_string_length(&bq_prefix) + self.calculate_string_length(&marker);
let reflow_line_length = if config.line_length.is_unlimited() {
usize::MAX
} else {
config.line_length.get().saturating_sub(prefix_width).max(1)
};
let reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
// A segment holding a line of its own is emitted as written; a prose
// segment is joined and reflowed on its own, so the prose above and below
// it wraps within its own paragraph.
let mut reflowed: Vec<String> = Vec::new();
let mut rewritten_sentence_count = 0;
for (own_line, segment) in &body_segments {
if *own_line {
reflowed.push(segment[0].to_string());
continue;
}
let segment_text = Self::join_paragraph_lines(segment, config);
let segment_text = trim_breakable_whitespace(&segment_text);
if segment_text.is_empty() {
continue;
}
let segment_reflowed = crate::utils::text_reflow::reflow_line(segment_text, &reflow_options);
if matches!(
config.reflow_mode,
ReflowMode::SentencePerLine | ReflowMode::SemanticLineBreaks
) && segment_reflowed.iter().map(String::as_str).ne(segment.iter().copied())
{
rewritten_sentence_count += split_into_sentences(
segment_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len();
}
reflowed.extend(segment_reflowed);
}
if reflowed.is_empty() {
return (None, next_idx);
}
let continuation_indent = " ".repeat(marker_width);
let reflowed_text = reflowed
.iter()
.enumerate()
.map(|(idx, line)| {
if idx == 0 {
format!("{bq_prefix}{marker}{line}")
} else {
format!("{bq_prefix}{continuation_indent}{line}")
}
})
.collect::<Vec<_>>()
.join(line_ending);
let start_range = ctx.whole_line_byte_range(start_idx + 1);
let end_range = if end_idx == lines.len() - 1 && !ctx.content.ends_with('\n') {
ctx.line_text_byte_range(end_idx + 1, 1, lines[end_idx].len() + 1)
} else {
ctx.whole_line_byte_range(end_idx + 1)
};
let byte_range = start_range.start..end_range.end;
let replacement = if end_idx < 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 message = match config.reflow_mode {
ReflowMode::SentencePack => "List item should pack complete sentences".to_string(),
ReflowMode::Normalize => format!(
"Paragraph could be normalized to use line length of {} characters",
config.line_length.get()
),
ReflowMode::SentencePerLine => {
let num_sentences = rewritten_sentence_count;
format!("List item should have one sentence per line (found {num_sentences} sentences)")
}
ReflowMode::SemanticLineBreaks => {
let num_sentences = rewritten_sentence_count;
format!("List item should use semantic line breaks ({num_sentences} sentences)")
}
ReflowMode::Default => format!("Line length exceeds {} characters", config.line_length.get()),
};
let warning = LintWarning {
rule_name: Some(self.name().to_string()),
message,
line: start_idx + 1,
column: 1,
end_line: end_idx + 1,
end_column: lines[end_idx].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(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 defined_references = Self::defined_reference_labels(ctx);
// A line touched by a code span crossing one of its boundaries is code
// however it is spelled, so a `$$...$$` expression on one is no display
// block.
let code_span_touches = crate::utils::text_reflow::lines_touching_multiline_code_span(ctx.content);
// The line-based list index can end an item early at table-like lazy
// continuation text. CommonMark still owns later indented paragraphs
// in that item, so retain their indentation using the parsed ranges.
let mut parsed_items = Vec::new();
if ctx.flavor == crate::config::MarkdownFlavor::Standard {
let mut depth = 0usize;
for (event, range) in
pulldown_cmark::Parser::new_ext(ctx.content, crate::utils::rumdl_parser_options()).into_offset_iter()
{
match event {
pulldown_cmark::Event::Start(pulldown_cmark::Tag::Item) => {
if depth == 0 {
parsed_items.push(range);
}
depth += 1;
}
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::Item) => depth -= 1,
_ => {}
}
}
}
let in_list = |line_idx: usize| {
let offset = ctx.lines[line_idx].byte_offset;
let idx = parsed_items.partition_point(|range| range.start <= offset);
ctx.is_in_list_block(line_idx + 1) || (idx > 0 && parsed_items[idx - 1].contains(&offset))
};
// 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;
// No paragraph starts on a line a code span runs on into. A
// collector that leaves the paragraph above as written stops short
// of the rest of it, and reflowing that rest on its own would
// rewrite the whitespace the span holds.
if i > 0 && line_ends_in_code_span(ctx, i - 1) {
i += 1;
continue;
}
// Handle blockquote paragraphs with style-preserving reflow.
// Skip blockquotes when blockquotes=false or paragraphs=false
if line_num > 0 && line_num <= ctx.lines.len() && ctx.lines[line_num - 1].blockquote.is_some() {
if !config.blockquotes || !config.paragraphs {
// Skip past all blockquote lines (explicit and lazy continuations).
// A lazy continuation is a non-blank line without `>` that follows
// a blockquote line and isn't a structural element.
let mut saw_explicit_bq = false;
while i < lines.len() && i < ctx.lines.len() {
if ctx.lines[i].blockquote.is_some() {
saw_explicit_bq = true;
i += 1;
} else if saw_explicit_bq
&& !lines[i].trim().is_empty()
&& !lines[i].trim_start().starts_with('#')
&& !lines[i].trim_start().starts_with('>')
{
// Lazy continuation of preceding blockquote
i += 1;
} else {
break;
}
}
continue;
}
// A list item inside the blockquote needs list-aware reflow (marker +
// continuation indent); plain prose goes through the paragraph path.
let is_bq_list_item = ctx.lines[i]
.blockquote
.as_deref()
.is_some_and(|bq| is_list_item(&bq.content));
let (warning, next_idx) = if is_bq_list_item {
self.generate_blockquote_list_item_fix(ctx, config, lines, i, line_ending, &code_span_touches)
} else {
self.generate_blockquote_paragraph_fix(ctx, config, lines, 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
|| info.in_table_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 = may_be_link_ref_def(lines[i]);
// A setext heading is a heading, not a paragraph: skip every line of
// its text and its underline together, the way an ATX heading is
// skipped just below. Reflowing any part rewrites the document's
// structure - joining the underline onto the text demotes the
// heading to prose, and rewrapping the text moves words across the
// heading boundary. The text spans the whole paragraph the underline
// ends, so walk the flag to the end of it; the line after the last
// text line is the underline.
if is_setext_heading_text_line(ctx, line_num) {
while i < lines.len() && is_setext_heading_text_line(ctx, i + 1) {
i += 1;
}
i += 1;
continue;
}
// A line of an HTML block is HTML wherever the block opens, a list
// item's marker line included, and that item holds no paragraph
// to reflow until the block ends.
if should_skip_due_to_line_info
|| ctx.line_holds_html_block(i)
|| lines[i].trim().starts_with('#')
|| TableUtils::is_potential_table_row_with_flavor(lines[i], ctx.flavor)
|| lines[i].trim().is_empty()
|| is_horizontal_rule(lines[i])
|| is_template_directive_only(lines[i])
|| is_link_ref_def
|| ctx.line_info(line_num).is_some_and(|info| info.is_div_marker)
|| is_html_only_line(lines[i])
|| standalone_link_ends_paragraph(ctx, line_num, config)
{
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, usize), // text, 0-based line index
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(), footnote_start));
}
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, unless a code span
// still open at the end of the line above runs on into this
// one, which makes it lazy text of the same paragraph.
let continues_code_span = line_ends_in_code_span(ctx, i - 1);
if indent < FN_INDENT && !continues_code_span {
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;
}
// The checks below stop at what starts a block of its own.
// A code span still open at the end of the line above proves
// the parser read on into this one, so it is prose however it
// is spelled.
if !continues_code_span {
// 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;
}
// A multi-line display-math block is verbatim: its line breaks
// carry meaning (see `line_in_multiline_math_block`).
if self.line_in_multiline_math_block(i + 1, ctx, config) {
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_with_flavor(next_trimmed, ctx.flavor)
|| 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_with_flavor(next_trimmed, ctx.flavor)
|| 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;
}
// HTML-only lines inside footnotes are not reflowable
if is_html_only_line(next_trimmed) {
fn_lines.push(FnLineType::Verbatim(strip_fn_indent(next), indent));
last_consumed = i;
i += 1;
continue;
}
}
// Regular prose content. A code span crossing into the line
// keeps the indentation past the footnote's own, which leaves
// the footnote as written; a lazy line has none taken off. A
// hard break at the end stays, so the paragraph keeps it.
let text = if !ctx.is_in_code_span_byte_with_or_without_math(ctx.lines[i].byte_offset) {
trim_preserving_hard_break(next.trim_start())
} else if indent >= FN_INDENT {
trim_preserving_hard_break(&strip_fn_indent(next))
} else {
trim_preserving_hard_break(next)
};
fn_lines.push(FnLineType::Content(restore_code_span_line_end(ctx, i, text), i));
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;
}
// The footnote is rebuilt with a fixed indent and its paragraphs
// joined, which a definition list inside it does not survive.
if holds_definition_list(ctx, footnote_start, last_consumed) {
continue;
}
// This collector trims prose line ends. Leave hard-break footnotes
// intact rather than losing their break markers while packing.
if config.reflow_mode == ReflowMode::SentencePack
&& lines[footnote_start..=last_consumed]
.iter()
.any(|line| has_hard_break(line))
{
continue;
}
// --- Group into blocks ---
#[derive(Debug)]
enum FnBlock {
Paragraph(Vec<(String, usize)>), // (text, 1-based line number)
Verbatim(Vec<(String, usize)>), // (content, indent) preserved as-is
}
// Each block carries whether a blank line comes before it in the
// source. Only those get one in the rebuild: a line right after a
// paragraph that cannot interrupt it (`7. b`, `[a]: b`, `<span>`)
// is text of that paragraph, which a blank line would cut off.
let mut blocks: Vec<(bool, FnBlock)> = Vec::new();
let mut current_para: Vec<(String, usize)> = Vec::new();
let mut current_verbatim: Vec<(String, usize)> = Vec::new();
let mut blank_before = false;
for fl in &fn_lines {
match fl {
FnLineType::Content(s, idx) => {
if !current_verbatim.is_empty() {
let verbatim = std::mem::take(&mut current_verbatim);
blocks.push((std::mem::take(&mut blank_before), FnBlock::Verbatim(verbatim)));
}
current_para.push((s.clone(), idx + 1));
}
FnLineType::Verbatim(s, indent) => {
if !current_para.is_empty() {
let para = std::mem::take(&mut current_para);
blocks.push((std::mem::take(&mut blank_before), FnBlock::Paragraph(para)));
}
current_verbatim.push((s.clone(), *indent));
}
FnLineType::Empty => {
if !current_para.is_empty() {
let para = std::mem::take(&mut current_para);
blocks.push((blank_before, FnBlock::Paragraph(para)));
}
if !current_verbatim.is_empty() {
let verbatim = std::mem::take(&mut current_verbatim);
blocks.push((blank_before, FnBlock::Verbatim(verbatim)));
}
blank_before = true;
}
}
}
if !current_para.is_empty() {
blocks.push((blank_before, FnBlock::Paragraph(current_para)));
}
if !current_verbatim.is_empty() {
blocks.push((blank_before, FnBlock::Verbatim(current_verbatim)));
}
let span_runs_into_indentation = |block: &FnBlock| match block {
FnBlock::Paragraph(lines) => {
code_span_runs_into_indentation(&lines.iter().map(|(text, _)| text).collect::<Vec<_>>())
}
FnBlock::Verbatim(_) => false,
};
if blocks.iter().any(|(_, block)| span_runs_into_indentation(block)) {
continue;
}
// --- 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 if config.reflow_mode == ReflowMode::SentencePack {
config.line_length.get().saturating_sub(FN_INDENT).max(1)
} else {
config
.line_length
.get()
.saturating_sub(FN_INDENT.max(prefix_display_width))
.max(20)
};
// Footnote continuation uses a fixed 4-space indent, so list
// continuation capping does not apply here.
let mut reflow_options = crate::utils::text_reflow::ReflowOptions {
max_list_continuation_indent: None,
..Self::reflow_options(ctx, config, reflow_line_length)
};
let indent_str = " ".repeat(FN_INDENT);
let mut result_lines: Vec<String> = Vec::new();
let mut is_first_block = true;
for (blank_before, block) in &blocks {
match block {
FnBlock::Paragraph(para_lines) => {
// A hard break ends a line of the paragraph wherever
// reflow puts it, so the text between two of them is
// reflowed on its own and the break follows its last
// line. Trailing spaces a code span carries across the
// line break are code, not a hard break.
let ends_with_hard_break = |line: &str, line_num: usize| {
has_hard_break(line) && !line_ends_in_code_span(ctx, line_num - 1)
};
let mut reflowed: Vec<String> = Vec::new();
for (segment_idx, segment) in split_into_segments(para_lines, ends_with_hard_break)
.into_iter()
.enumerate()
{
let break_marker = segment.last().and_then(|(line, line_num)| {
if !ends_with_hard_break(line, *line_num) {
None
} else if line.ends_with('\\') {
Some("\\")
} else {
Some(" ")
}
});
let texts: Vec<&str> = segment
.iter()
.map(|(line, line_num)| {
if ends_with_hard_break(line, *line_num) {
line.strip_suffix('\\').unwrap_or(line).trim_end_matches([' ', '\t'])
} else {
line.as_str()
}
})
.collect();
let segment_text = Self::join_paragraph_lines(&texts, config);
let segment_text = trim_breakable_whitespace(&segment_text);
if segment_text.is_empty() {
continue;
}
reflow_options.first_line_length = if config.reflow_mode == ReflowMode::SentencePack
&& is_first_block
&& segment_idx == 0
&& !config.line_length.is_unlimited()
{
Some(
config
.line_length
.effective_limit()
.saturating_sub(self.calculate_string_length(prefix) + 1)
.max(1),
)
} else {
None
};
reflowed.extend(crate::utils::text_reflow::reflow_line(segment_text, &reflow_options));
if let Some(break_marker) = break_marker
&& let Some(last) = reflowed.last_mut()
{
last.push_str(break_marker);
}
}
if reflowed.is_empty() {
continue;
}
if *blank_before && !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) => {
if *blank_before && !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 = ctx.whole_line_byte_range(footnote_start + 1);
let end_range = if last_consumed == lines.len() - 1 && !ctx.content.ends_with('\n') {
ctx.line_text_byte_range(last_consumed + 1, 1, lines[last_consumed].len() + 1)
} else {
ctx.whole_line_byte_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
&& (matches!(
config.reflow_mode,
ReflowMode::SentencePerLine | ReflowMode::SentencePack | ReflowMode::SemanticLineBreaks
) || max_length > line_limit)
{
warnings.push(LintWarning {
rule_name: Some(self.name().to_string()),
message: if config.reflow_mode == ReflowMode::SentencePack {
"Footnote should pack complete sentences".to_string()
} else if config.reflow_mode == ReflowMode::SentencePerLine {
"Footnote should have one sentence per line".to_string()
} else if config.reflow_mode == ReflowMode::SemanticLineBreaks {
"Footnote should use semantic line breaks".to_string()
} else {
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].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(byte_range, replacement)),
});
}
continue;
}
// Handle MkDocs container content (admonitions and tabs) with indent-preserving reflow
if ctx
.line_info(line_num)
.is_some_and(super::super::lint_context::types::LineInfo::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). Python-Markdown
// expands a tab to the next multiple of four columns, so the indent
// is measured in columns and re-emitted as that many spaces.
let first_line = lines[i];
let base_prefix = &first_line[..first_line.len() - first_line.trim_start_matches([' ', '\t']).len()];
let base_indent_len = column_at(first_line, base_prefix.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(super::super::lint_context::types::LineInfo::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, HTML-only lines within containers
if is_list_item(line.trim())
|| line.trim().starts_with("```")
|| line.trim().starts_with("~~~")
|| line.trim().starts_with('#')
|| is_html_only_line(line)
{
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 let Some(rest) = line.strip_prefix(base_prefix) {
rest
} else {
line.trim_start()
}
})
.collect();
if code_span_runs_into_indentation(&stripped_lines) {
continue;
}
let paragraph_text = Self::join_paragraph_lines(&stripped_lines, config);
// Check if reflow is needed
let needs_reflow = match config.reflow_mode {
ReflowMode::SentencePack => true,
ReflowMode::Normalize => self.normalize_mode_needs_reflow(container_lines.iter().copied(), config),
ReflowMode::SentencePerLine => {
let sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
sentences.len() > 1 || container_lines.len() > 1
}
ReflowMode::SemanticLineBreaks => {
let sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
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 = ctx.whole_line_byte_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') {
ctx.line_text_byte_range(end_line + 1, 1, lines[end_line].len() + 1)
} else {
ctx.whole_line_byte_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 = Self::reflow_options(ctx, config, reflow_line_length);
let reflowed = crate::utils::text_reflow::reflow_line(¶graph_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: if config.reflow_mode == ReflowMode::SentencePack {
"Paragraph should pack complete sentences".to_string()
} else {
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].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(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("~~~")
};
// A list item whose marker line holds nothing but the marker has no
// text to reflow there. The line after it is the item's content only
// when indented to the content column; otherwise the item is empty
// and that line starts a block of its own. Either way it is reflowed
// on its own, and never joined onto the marker.
let trimmed = lines[i].trim();
if ctx.lines[i]
.list_item
.as_ref()
.is_some_and(|item| item.marker == trimmed)
{
i += 1;
continue;
}
// Check if this is a list item - handle it specially
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();
// The normalized marker above is what gets re-emitted; the source marker
// is where the item's content actually starts. Nested blocks move by the
// difference between the two content columns, so the shift must be
// measured against the source, not against the normalized width.
let source_marker = source_list_marker(lines[i]);
let source_content_col = source_marker.as_ref().map_or(marker_len, |m| m.content_col);
// Where the parser puts the item's content, which is what a
// continuation line's indentation is measured against.
let item_content_col = ctx.lines[i]
.list_item
.as_ref()
.map_or(source_content_col, |item| item.content_column);
let first_content = restore_code_span_line_end(ctx, i, first_content);
// 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.
//
// The marker above keeps one padding space, and the item's content
// starts past all of it, so a line is measured against the column
// the padding as written reaches. A line short of that column
// after a blank line is not in the item.
let item_indent = ctx.lines[i].indent;
let source_padding = item_content_col.saturating_sub(base_marker_len);
// The thresholds above are byte offsets into the marker line. A
// tab there reaches further than its one byte, so a line belongs
// to the item only when its indentation reaches as many columns
// as the content does. The bytes must reach the content as well:
// lines are stripped and re-emitted by bytes, so a tab-indented
// line that reaches it only by width is left to the outer loop,
// which keeps it as written.
let tab_widening = ctx.lines[i]
.list_item
.as_ref()
.map_or(0, |item| column_at(lines[i], item.content_column) - item.content_column);
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 + source_padding
};
let content_continuation_indent = base_marker_len + source_padding;
let min_continuation_column = min_continuation_indent + tab_widening;
let content_continuation_column = content_continuation_indent + tab_widening;
// Track lines and their types (content, code block, fence, nested list)
#[derive(Clone)]
enum LineType {
Content(String, usize), // content and 1-indexed line number
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
Table(String, usize), // GFM table row, preserved verbatim with original indent
Empty,
}
let start_idx = i;
// A marker line holding a second marker opens an item of its own,
// and the line info describes only the outer one. The inner
// item's content column is the indentation a code span crossing
// into a continuation line leaves out, so it cannot be told here.
let opens_nested_item = is_list_item(first_content.trim_start());
// A marker line whose content is one whole `$$...$$` expression
// renders as a display block, so it keeps the line it was written
// on and the prose under it starts a paragraph of its own. The
// code-block carrier re-emits it unchanged after the marker.
//
// The marker keeps one padding space and leaves the rest at the
// head of the content, and the carrier writes the marker as the
// author spelled it, padding included. The carrier therefore
// holds the content with its leading whitespace off, so the
// padding is written once.
//
// A marker that cannot interrupt a paragraph, such as an
// ordered one not starting at one, can sit inside a code span
// the paragraph above opened, and its content is code then.
// The marker line can just as well be the one that opens the
// span, closing on a line still to come.
let mut list_item_lines: Vec<LineType> = if (is_self_contained_display_math_line(&first_content)
|| self.line_is_standalone_bracket_math(i + 1, ctx, config))
&& !line_touches_multiline_code_span(&code_span_touches, i + 1)
{
vec![LineType::CodeBlock(first_content.trim_start().to_string(), marker_len)]
} else {
vec![LineType::Content(first_content, i + 1)]
};
i += 1;
let mut leave_as_written = false;
// Collect continuation lines using ctx.lines for metadata
while i < lines.len() {
let line_info = &ctx.lines[i];
// An invalid fence can be a lazy continuation of this
// paragraph. Re-indenting or joining it changes how GFM
// renderers recognize neighboring bare autolinks. Keep
// the item as written unless the line continues a code span.
if !line_info.in_code_block
&& line_info.visual_indent < content_continuation_column
&& is_fence_marker(lines[i])
&& !line_ends_in_code_span(ctx, i - 1)
{
leave_as_written = true;
}
// 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
&& next_info.visual_indent >= min_continuation_column
{
// 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 && line_info.visual_indent >= content_continuation_column {
// A line kept on its own is re-indented with spaces, and
// implementations disagree on how much of a tab the
// item's indentation consumes, so an item holding a line
// indented with a tab is left as written.
leave_as_written |= line_info.content(ctx.content)[..indent].contains('\t');
let trimmed = line_info.content(ctx.content).trim();
// Check for MkDocs admonition lines inside list items BEFORE
// checking in_code_block. Lines inside code blocks within
// admonitions have both in_admonition and in_code_block set;
// admonition membership takes priority so the entire admonition
// structure (including embedded code blocks) is preserved.
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_matches([' ', '\t']).to_string();
list_item_lines.push(LineType::AdmonitionHeader(header_text, indent));
} else {
let body_text = raw_content[indent..].trim_end_matches([' ', '\t']).to_string();
list_item_lines.push(LineType::AdmonitionContent(body_text, indent));
}
i += 1;
continue;
}
// 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;
}
// A multi-line display-math block inside the item is verbatim:
// its line breaks carry meaning (see
// `line_in_multiline_math_block`), so reuse the code-block
// carrier to re-emit it unchanged. A reader without math
// can see a code span crossing into this line from the
// prose above, and reflowing that prose on its own would
// rewrite the whitespace the span holds.
if self.line_in_multiline_math_block(i + 1, ctx, config) {
leave_as_written |= line_ends_in_code_span(ctx, i - 1);
list_item_lines.push(LineType::CodeBlock(
line_info.content(ctx.content)[indent..].to_string(),
indent,
));
i += 1;
continue;
}
// A blockquote nested inside the list item is reflowed by the
// blockquote-aware path (it preserves the `>` prefix, including the
// list indent), not as list-item prose. Collecting it as Content
// would strip the markers and reflow `>` as words, collapsing the
// blank `>` line and dropping `>` from wrapped continuations. End
// the item here so the outer loop routes the blockquote line to
// generate_blockquote_paragraph_fix. Uncollect a pending blank so
// the separator between the list prose and the blockquote survives.
if line_info.blockquote.is_some() {
if matches!(list_item_lines.last(), Some(LineType::Empty)) {
list_item_lines.pop();
i -= 1;
}
break;
}
// 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)
// The parser also recognizes an item whose marker line holds
// nothing else, which `is_list_item` does not. A line a code
// span runs on into continues the paragraph that span is in,
// whatever marker it starts with.
let starts_item = !line_ends_in_code_span(ctx, i - 1)
&& (is_list_item(trimmed) || line_info.list_item.is_some());
if starts_item && 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 starts_item && 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).
// An indented code block cannot interrupt a paragraph, so
// a line under the item's prose continues that paragraph
// however deep it is indented.
if indent <= min_continuation_indent + 3
|| matches!(list_item_lines.last(), Some(LineType::Content(..)))
{
// 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 strip = continuation_indent_to_strip(ctx, i, indent, item_content_col);
let content = restore_code_span_line_end(
ctx,
i,
trim_preserving_hard_break(&line_info.content(ctx.content)[strip..]),
);
// An underline under the item's paragraph text makes
// that text a setext heading. The parser records no
// heading for one whose text starts on the marker
// line, so the collector cannot tell its lines from
// prose, and rewrapping them would end the heading
// elsewhere or join the underline into its text.
leave_as_written |= is_setext_underline_content(&content)
&& matches!(list_item_lines.last(), Some(LineType::Content(..)));
// A line a code span crosses into or out of is text of
// the paragraph that span is in, whatever block its
// text alone would open. Kept on its own line, it
// would be written back past an indentation the span
// already holds part of.
if line_ends_in_code_span(ctx, i - 1) || line_ends_in_code_span(ctx, i) {
list_item_lines.push(LineType::Content(content, i + 1));
}
// Check if this is a div marker (::: opening or closing)
// These must be preserved on their own line, not merged into paragraphs
else if line_info.is_div_marker {
list_item_lines.push(LineType::DivMarker(content));
}
// A fence marker opens or closes a code block, a
// heading is a block of its own, its setext text lines
// and underline included, and a line that is one whole
// `$$...$$` expression renders as a display block.
// Each keeps the line it was written on, so the
// code-block carrier re-emits it unchanged between the
// prose above and below. A line touched by a code span
// crossing one of its boundaries is code, not such a
// block.
else if is_fence_marker(&content)
|| line_info.heading.is_some()
|| line_info.is_setext_heading_text
|| (is_setext_underline_content(&content) && ctx.lines[i - 1].is_setext_heading_text)
|| ((is_self_contained_display_math_line(&content)
|| self.line_is_standalone_bracket_math(i + 1, ctx, config))
&& !line_touches_multiline_code_span(&code_span_touches, i + 1))
{
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));
}
// Check if this is a GFM table row. Tables nested inside list
// items must be preserved verbatim — joining them with prose
// breaks the column structure.
//
// `is_potential_table_row` is intentionally permissive at the
// row level: any line with `|` and 2+ cells qualifies. To avoid
// misclassifying prose continuation lines that contain a literal
// pipe (e.g. "use grep | sort to ..."), require one of:
// - the row is pipe-bordered (`| ... |`), the canonical form
// for tables nested in lists; or
// - the next line is a delimiter row (this is a header); or
// - the previous classified line was already a Table (this is
// a continuation row).
//
// A row the table detection found is a row whatever it holds:
// GFM runs the rows on without pipes until a blank line or
// another block.
else if line_info.in_table_block
|| TableUtils::is_potential_table_row_with_flavor(&content, ctx.flavor) && {
let pipe_bordered =
content.trim().starts_with('|') && content.trim().ends_with('|');
let next_is_delim = ctx
.lines
.get(i + 1)
.is_some_and(|next| TableUtils::is_delimiter_row(next.content(ctx.content)));
let prev_was_table = matches!(list_item_lines.last(), Some(LineType::Table(..)));
pipe_bordered || next_is_delim || prev_was_table
}
{
list_item_lines.push(LineType::Table(content, indent));
} else {
list_item_lines.push(LineType::Content(content, i + 1));
}
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 if matches!(list_item_lines.last(), Some(LineType::Content(..)))
&& line_info.visual_indent < content_continuation_column
&& is_lazy_continuation(ctx, i)
{
// A lazy continuation line continues the item's open
// paragraph, so it is reflowed with it. Reflowed on its own at
// its source column, a wrap could start a line with a marker
// such as `2)` that opens a list there, where no paragraph of
// the matched containers is open for it to continue. Only the
// indentation of the enclosing items the line still reaches is
// stripped, so a code span running into the rest leaves the
// item as written.
//
// A lazy line that is one whole tag would open a type-7
// HTML block outside the item. Such a block cannot
// interrupt a paragraph, so CommonMark keeps the line in
// the item, but markdown-rs and comrak end the item before
// it. Indenting the line or joining it into the paragraph
// changes how one of the two readings renders, so the item
// is left as written.
leave_as_written |= opens_tag_line_html_block(line_info.content(ctx.content).trim_start());
let strip = continuation_indent_to_strip(
ctx,
i,
indent,
enclosing_item_content_col_reached(ctx, list_start, indent),
);
let content = restore_code_span_line_end(
ctx,
i,
trim_preserving_hard_break(&line_info.content(ctx.content)[strip..]),
);
list_item_lines.push(LineType::Content(content, i + 1));
i += 1;
} else {
// Not indented enough, end of list item
break;
}
}
// A code span crossing out of the item's last line runs on into
// a line the item does not collect. Its paragraph continues past
// where the item ends, and reflowing the part inside the item
// would rewrite the whitespace the span holds.
leave_as_written |= line_ends_in_code_span(ctx, i - 1);
leave_as_written |= opens_nested_item && (start_idx..i - 1).any(|idx| line_ends_in_code_span(ctx, idx));
// Each run of content lines is one paragraph of the item.
//
// When a tab pads a marker on the item's first line, the
// readers disagree on how far past the content column each
// later line sits, so a line one of them takes for a block of
// its own (a quote, a heading) is paragraph text to the other.
// A code span then crosses into that line in one reading
// only, and reflowing the paragraph above it would rewrite
// the whitespace the span holds there.
let readers_split_blocks = markers_padded_with_tab(lines[start_idx]);
leave_as_written |= list_item_lines
.chunk_by(|a, b| matches!((a, b), (LineType::Content(..), LineType::Content(..))))
.any(|run| {
let mut texts: Vec<&str> = run
.iter()
.filter_map(|line| match line {
LineType::Content(text, _) => Some(text.as_str()),
_ => None,
})
.collect();
if code_span_runs_into_indentation(&texts) {
return true;
}
let Some(LineType::Content(_, last_line_num)) = run.last() else {
return false;
};
let next_line = lines
.get(*last_line_num)
.map(|line| line.trim_start_matches([' ', '\t']));
readers_split_blocks
&& next_line.is_some_and(|next| {
texts.push(next);
!next.is_empty() && code_span_crosses_last_break(&texts)
})
});
// The item a marker line opens inside this one has a content
// column of its own. A paragraph after a blank line belongs to
// that inner item when it reaches the inner column and to this
// item when it does not, so it is written back at the column of
// the item it is in. Paragraphs of both items cannot share one
// indentation, so an item holding both is left as written.
// Held as the inner marker's width, which is how far the inner
// column sits past this item's, and the indentation the first
// such paragraph was written at.
let nested_paragraph = source_marker.as_ref().filter(|_| opens_nested_item).and_then(|outer| {
let inner = source_list_marker(&lines[start_idx][outer.text.len()..])?;
let nested_col = outer.content_col + inner.content_col;
let indents: Vec<usize> = list_item_lines
.iter()
.skip_while(|line| !matches!(line, LineType::Empty))
.filter_map(|line| match line {
LineType::Content(_, line_num) => Some(ctx.lines[line_num - 1].indent),
_ => None,
})
.collect();
leave_as_written |= indents.iter().any(|&indent| indent < nested_col)
&& indents.iter().any(|&indent| indent >= nested_col);
let first = *indents.first()?;
(first >= nested_col).then_some((inner.content_col, first))
});
if leave_as_written {
// Left as written, the item renders as its author saw it.
continue;
}
// 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 | ReflowMode::SentencePack => {
// Find indent of the first plain text continuation line,
// skipping the marker line (index 0), nested list items,
// code blocks, blank lines, and lazy lines, whose indent
// falls short of the item's content. Every paragraph of
// the item is written at this indent, and one after a
// blank line indented four or more past the content is
// a code block, so a continuation line indented that
// deep sets no indent.
list_item_lines
.iter()
.skip(1)
.find_map(|lt| match lt {
LineType::Content(_, line_num)
if (content_continuation_indent..content_continuation_column + 4)
.contains(&ctx.lines[line_num - 1].indent) =>
{
Some(ctx.lines[line_num - 1].indent)
}
_ => None,
})
.unwrap_or(min_continuation_indent)
}
_ => min_continuation_indent,
};
let indent_size = match (config.reflow_mode, nested_paragraph) {
(
ReflowMode::SemanticLineBreaks | ReflowMode::SentencePerLine | ReflowMode::SentencePack,
Some((_, written)),
) => written,
_ => indent_size,
};
// 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
};
// Split list_item_lines into blocks (paragraphs, code blocks, nested lists, semantic lines, and HTML blocks)
let mut builder = BlockBuilder::new_with_start_line(start_idx + 1);
for line in &list_item_lines {
match line {
LineType::Empty => builder.feed_blank_line(),
LineType::Content(content, line_num) => {
builder.feed_content(content, ctx.lines[line_num - 1].indent)
}
LineType::CodeBlock(content, indent) => builder.feed_code_line(content, *indent),
LineType::SemanticLine(content) => builder.feed_semantic_line(content),
LineType::SnippetLine(content) => builder.feed_snippet_line(content),
LineType::DivMarker(content) => builder.feed_div_marker(content),
LineType::AdmonitionHeader(header_text, indent) => {
builder.feed_admonition_header(header_text, *indent)
}
LineType::AdmonitionContent(content, indent) => {
builder.feed_admonition_content(content, *indent)
}
LineType::Table(content, indent) => builder.feed_table_line(content, *indent),
}
}
let blocks = builder.finalize();
// 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, line_num: usize| -> 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 standalone_link_ends_paragraph(ctx, line_num, config) {
return true;
}
// HTML-only lines: exempt when not strict
if !config.strict && is_html_only_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_num) = line {
if is_exempt_line(s, *line_num) {
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 =
trim_breakable_whitespace(&Self::join_paragraph_lines(&content_lines, config)).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_tables = blocks.iter().any(|b| matches!(b, Block::Table { .. }));
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_tables)
&& !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 { lines: para_lines, .. } = b {
!para_lines
.iter()
.all(|(line, line_num)| is_exempt_line(line, *line_num))
} 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
};
// Integrate MD030 list-marker spacing (and MD007's text-aligned
// continuation). In Default/Normalize modes — the modes that already
// canonicalize spacing/indent — derive the number of spaces after the
// marker from the configured MD030 values instead of forcing a single
// space, then align continuation lines to the resulting content column.
// Sentence/Semantic modes only adjust line breaks, so they keep the
// marker spacing and indentation already present in the source.
//
// Re-spacing the marker moves the item's content column, so it is only
// safe when this fix rewrites every line the item owns. Nested lists,
// nested blockquotes, and blocks after a tab-indented continuation are
// left to the outer loop and keep their source indentation; an item that owns
// any of them keeps its source marker and content column, and MD030
// re-spaces it together with everything it owns.
// The MkDocs flavor enforces a rigid structural indent (4 spaces,
// capped via max_list_continuation_indent) that Python-Markdown
// requires; leave its specialized handling untouched.
//
// A content column moved left can reach the first line after the
// item, which stopped short of the written column and so ended
// the item. That line would join the item, so the marker keeps
// its spacing then.
//
// A tab after the marker reaches the next tab stop for
// CommonMark, while markdown-rs counts it as one space of
// padding. Only the marker as written keeps both readings of
// where the item's lines belong, so it is kept.
let rewrites_whole_item = !item_owns_lines_from(ctx, lines, list_start, i);
let next_line_column = ctx.lines[i..]
.iter()
.find(|line| !line.is_blank)
.map(|line| line.visual_indent);
let respaced = if matches!(config.reflow_mode, ReflowMode::Default | ReflowMode::Normalize)
&& !ctx.flavor.requires_strict_list_indent()
&& rewrites_whole_item
&& let Some(li) = ctx.lines[list_start].list_item.as_deref()
{
let bullet_len = li.marker.len();
// The checkbox (e.g. `[ ] `) is content, not part of the list
// marker MD030 governs; carry it over verbatim after the spacing.
let checkbox_tail = marker[base_marker_len..].to_string();
let indent_prefix = &marker[..item_indent];
// Decide single- vs multi-line spacing from the *rewritten* shape,
// not the source. A multi-line source is not enough: plain prose
// continuation collapses onto the marker line during reflow, so a
// two-line bullet that fits becomes a single physical line and must
// use MD030's single-line spacing (otherwise MD013 emits a result
// that MD030 immediately rewrites). The emitted item stays
// multi-line only when reflow cannot collapse it:
// - the prose wraps past the line length, or
// - a structural block remains (code, table, admonition, semantic
// line, snippet, div marker, HTML) that is not joinable prose, or
// - more than one paragraph remains (blank-separated).
// The wrap test uses the single-line content column so it is
// independent of the spacing we are about to choose (avoiding a
// circular result). `ol-align-column` ignores this flag entirely in
// expected_spaces(), so ordered lists are unaffected.
//
// This is the rewritten-shape counterpart of MD030's
// `is_multi_line_list_item` (which keys off the *source*). The two
// are related but technically distinct and intentionally separate;
// if the notion of "multi-line" changes in one, revisit the other.
let single_col = item_indent
+ bullet_len
+ self.list_spacing.expected_spaces(li.is_ordered, false, bullet_len)
+ checkbox_tail.len();
let prose_wraps = !combined_content.is_empty()
&& self.calculate_effective_length(&format!("{}{combined_content}", " ".repeat(single_col)))
> config.line_length.effective_limit();
let has_structural_block = blocks.iter().any(|b| !matches!(b, Block::Paragraph { .. }));
let multiple_paragraphs =
blocks.iter().filter(|b| matches!(b, Block::Paragraph { .. })).count() > 1;
let is_multi = prose_wraps || has_structural_block || multiple_paragraphs;
let spaces = self.list_spacing.expected_spaces(li.is_ordered, is_multi, bullet_len);
let new_marker = format!("{indent_prefix}{}{}{checkbox_tail}", li.marker, " ".repeat(spaces));
let new_col = new_marker.chars().count();
let shift = new_col as isize - source_content_col as isize;
Some((new_marker, new_col, shift))
} else {
None
}
.filter(|(_, new_col, _)| {
tab_widening == 0
&& next_line_column.is_none_or(|column| !(*new_col..source_content_col).contains(&column))
});
let (marker, indent_size, code_indent_shift) = respaced.unwrap_or_else(|| {
// The item is emitted exactly as written and the lines it owns
// never move. Re-emitting the normalized marker here would narrow
// the content column while leaving those lines behind. MkDocs
// keeps its structural continuation indent; elsewhere a line
// stays inside the item at the column the parser gives it.
let marker = source_marker.map_or(marker, |m| m.text);
let indent_size = if matches!(config.reflow_mode, ReflowMode::Default | ReflowMode::Normalize)
&& !ctx.flavor.requires_strict_list_indent()
{
item_content_col + tab_widening
} else {
indent_size
};
(marker, indent_size, 0isize)
});
let indent_size = match (config.reflow_mode, nested_paragraph) {
(ReflowMode::Default | ReflowMode::Normalize, Some((inner_marker_width, _))) => {
indent_size + inner_marker_width
}
_ => indent_size,
};
let expected_indent = " ".repeat(indent_size);
// A colon-led line with a line of its paragraph before it opens a
// definition and makes the item a definition list. Joining the
// lines flattens that into prose, so the item is left as the
// author wrote it. The first line of each paragraph is prose
// whatever it starts with, since a definition needs a term on
// the line before it. Content lines arrive with the item's own
// indentation already off, which is what the marker's
// indentation is counted from.
let contains_definition_list = blocks.iter().any(|block| match block {
Block::Paragraph { lines: para_lines, .. } => para_lines
.iter()
.skip(1)
.any(|(line, _)| crate::utils::text_reflow::is_definition_list_marker(line)),
_ => false,
});
let needs_reflow = !contains_definition_list
&& !holds_definition_list(ctx, list_start, i - 1)
&& match config.reflow_mode {
ReflowMode::SentencePack => true,
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 { lines: para_lines, .. } => {
if para_lines
.iter()
.all(|(line, line_num)| is_exempt_line(line, *line_num))
{
return false;
}
let joined = Self::join_paragraph_lines(
¶_lines.iter().map(|(l, _)| l.as_str()).collect::<Vec<_>>(),
config,
);
let with_marker =
format!("{}{}", " ".repeat(indent_size), trim_breakable_whitespace(&joined));
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,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
sentences.len() > 1
}
ReflowMode::SemanticLineBreaks => {
let sentences = split_into_sentences(
&combined_content,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
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, line_idx + 1) {
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, line_idx + 1) {
return false;
}
self.calculate_effective_length(line) > config.line_length.get()
})
}
};
if needs_reflow {
let start_range = ctx.whole_line_byte_range(list_start + 1);
let end_line = i - 1;
let end_range = if end_line == lines.len() - 1 && !ctx.content.ends_with('\n') {
ctx.line_text_byte_range(end_line + 1, 1, lines[end_line].len() + 1)
} else {
ctx.whole_line_byte_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 mut reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
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 { lines: 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, line_num)| is_exempt_line(line, *line_num));
// Link reference definitions opening the paragraph are
// also kept as written: a definition ends at its line,
// so text joined onto its destination would turn it
// into visible text. Only what follows is reflowed.
let verbatim = if all_exempt {
para_lines.len()
} else {
para_lines
.iter()
.take_while(|(line, _)| may_be_link_ref_def(line))
.count()
};
let (verbatim_lines, prose_lines) = para_lines.split_at(verbatim);
for (line, _) in verbatim_lines {
if is_first_block {
// The item's first line still carries the
// marker padding past its first space, which
// `marker` already accounts for.
result.push(format!("{marker}{}", line.trim_start()));
is_first_block = false;
} else {
result.push(format!("{expected_indent}{line}"));
}
}
if !prose_lines.is_empty() {
// Split the paragraph into segments at hard break boundaries
// Each segment can be reflowed independently
// Trailing spaces that a code span carries across
// the line break are code, not a hard break.
let ends_with_hard_break = |line: &str, line_num: usize| {
has_hard_break(line) && !line_ends_in_code_span(ctx, line_num - 1)
};
let segments = split_into_segments(prose_lines, ends_with_hard_break);
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, line_num)| {
let line = line.strip_suffix('\r').unwrap_or(line);
if !ends_with_hard_break(line, *line_num) {
None
} else 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, line_num)| {
// Strip hard break marker (2 spaces or backslash) for reflow processing
if !ends_with_hard_break(line, *line_num) {
line.clone()
} else if line.ends_with('\\') {
line[..line.len() - 1].trim_end_matches([' ', '\t']).to_string()
} else if line.ends_with(" ") {
line[..line.len() - 2].trim_end_matches([' ', '\t']).to_string()
} else {
line.clone()
}
})
.collect();
let segment_text = trim_breakable_whitespace(&Self::join_paragraph_lines(
&segment_for_reflow,
config,
))
.to_string();
if !segment_text.is_empty() {
reflow_options.first_line_length = if config.reflow_mode
== ReflowMode::SentencePack
&& is_first_block
&& segment_idx == 0
&& !config.line_length.is_unlimited()
{
Some(
config
.line_length
.effective_limit()
.saturating_sub(self.calculate_string_length(&marker))
.max(1),
)
} else {
None
};
let mut reflowed =
crate::utils::text_reflow::reflow_line(&segment_text, &reflow_options);
if is_first_block && segment_idx == 0 {
// An item's text can open containers of its own
// (`- > quote`, `- - nested`). A line holding only
// their markers opens them empty, and the text
// after it then sits outside them, so the markers
// keep their first word even when it overflows.
while reflowed.len() > 1 && holds_only_container_markers(&reflowed[0]) {
let next = reflowed.remove(1);
reflowed[0] = format!("{} {next}", reflowed[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);
}
}
}
}
// Separate the next block as the source did. Only add a
// blank line if not already ending with one (avoids double blanks).
if blocks.get(block_idx + 1).is_some_and(Block::wants_preceding_blank)
&& result.last().is_none_or(|s: &String| !s.is_empty())
{
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.as_str()
));
is_first_block = false;
} else if content.is_empty() {
result.push(String::new());
} else {
// Shift nested code with the marker so it stays
// aligned under content when MD030 widens spacing.
result.push(format!(
"{}{}",
" ".repeat((*orig_indent as isize + code_indent_shift).max(0) as usize),
content
));
}
}
}
Block::SemanticLine {
content,
has_preceding_blank,
has_following_blank,
} => {
// Preserve semantic lines (NOTE:, WARNING:, etc.) as-is on their own line.
// Without a blank line around it the marker line continues the
// paragraph it sits in, so a blank line is written only where the
// source had one; adding one would split that paragraph in two.
if *has_preceding_blank
&& !is_first_block
&& result.last().is_none_or(|s: &String| !s.is_empty())
{
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}"));
}
if *has_following_blank && block_idx < blocks.len() - 1 {
result.push(String::new());
}
}
Block::SnippetLine { content, .. } | Block::DivMarker { content, .. } => {
// Snippet delimiters (-8<-) and div markers (::: opening or
// closing) keep their own line, and the blank line the
// source had after one.
if is_first_block {
result.push(format!("{marker}{content}"));
is_first_block = false;
} else {
result.push(format!("{expected_indent}{content}"));
}
if blocks.get(block_idx + 1).is_some_and(Block::wants_preceding_blank) {
result.push(String::new());
}
}
Block::Html {
lines: html_lines,
has_preceding_blank: _,
} => {
// HTML text keeps its indentation past the item's content
// column, which is part of the block (inside a `<pre>`,
// visibly), so it moves with the marker like code does.
// NOTE: Blank line before HTML block is handled by the previous block
for (idx, (line, orig_indent)) 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 {
result.push(format!(
"{}{line}",
" ".repeat((*orig_indent as isize + code_indent_shift).max(0) as usize)
));
}
}
// 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 blocks.get(block_idx + 1).is_some_and(Block::wants_preceding_blank)
&& result.last().is_none_or(|s: &String| !s.is_empty())
{
result.push(String::new());
}
}
Block::Table {
lines: table_lines,
has_preceding_blank: _,
} => {
// Preserve table rows verbatim with their original indentation.
// Reflowing rows would corrupt column alignment and inject `|`
// characters mid-paragraph (issue #590).
// The leading blank line is emitted by the previous block.
for (idx, (content, orig_indent)) in table_lines.iter().enumerate() {
if is_first_block && idx == 0 {
// First line of first block gets the list marker
result.push(format!(
"{marker}{}",
" ".repeat(orig_indent.saturating_sub(marker_len)) + content.as_str()
));
is_first_block = false;
} else {
// Shift nested table rows with the marker so they
// stay aligned when MD030 widens marker spacing.
result.push(format!(
"{}{}",
" ".repeat((*orig_indent as isize + code_indent_shift).max(0) as usize),
content
));
}
}
// Add blank line after table block if there's a next block.
if blocks.get(block_idx + 1).is_some_and(Block::wants_preceding_blank)
&& result.last().is_none_or(|s: &String| !s.is_empty())
{
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().is_none_or(|s: &String| !s.is_empty()) {
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.as_str()
));
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_or(header_indent + 4, |(_, indent)| *indent);
let body_indent_str = " ".repeat(body_indent);
// Segment body content into code blocks (verbatim) and
// text paragraphs (reflowable), separated by blank lines.
// Code lines store (content, orig_indent) to reconstruct
// internal indentation relative to body_indent.
enum AdmonSegment {
Text(Vec<String>),
Code(Vec<(String, usize)>),
}
let mut segments: Vec<AdmonSegment> = Vec::new();
let mut current_text: Vec<String> = Vec::new();
let mut current_code: Vec<(String, usize)> = Vec::new();
let mut in_admon_code = false;
// Track the opening fence character so closing fences
// must match (backticks close backticks, tildes close tildes)
let mut fence_char: char = '`';
// Opening fences: ``` or ~~~ followed by optional info string
let get_opening_fence = |s: &str| -> Option<(char, usize)> {
let t = s.trim_start();
if t.starts_with("```") {
Some(('`', t.bytes().take_while(|&b| b == b'`').count()))
} else if t.starts_with("~~~") {
Some(('~', t.bytes().take_while(|&b| b == b'~').count()))
} else {
None
}
};
// Closing fences: ONLY fence chars + optional trailing spaces
let get_closing_fence = |s: &str| -> Option<(char, usize)> {
let t = s.trim();
if t.starts_with("```") && t.bytes().all(|b| b == b'`') {
Some(('`', t.len()))
} else if t.starts_with("~~~") && t.bytes().all(|b| b == b'~') {
Some(('~', t.len()))
} else {
None
}
};
let mut fence_len: usize = 3;
for (content, orig_indent) in admon_lines {
if in_admon_code {
// Closing fence must use the same character, be
// at least as long, and have no info string
if let Some((ch, len)) = get_closing_fence(content)
&& ch == fence_char
&& len >= fence_len
{
current_code.push((content.clone(), *orig_indent));
in_admon_code = false;
segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
continue;
}
current_code.push((content.clone(), *orig_indent));
} else if let Some((ch, len)) = get_opening_fence(content) {
if !current_text.is_empty() {
segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
}
in_admon_code = true;
fence_char = ch;
fence_len = len;
current_code.push((content.clone(), *orig_indent));
} else if content.is_empty() {
if !current_text.is_empty() {
segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
}
} else {
current_text.push(content.clone());
}
}
if in_admon_code && !current_code.is_empty() {
segments.push(AdmonSegment::Code(std::mem::take(&mut current_code)));
}
if !current_text.is_empty() {
segments.push(AdmonSegment::Text(std::mem::take(&mut current_text)));
}
// Build reflow options once for all text segments
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 = Self::reflow_options(ctx, config, admon_reflow_length);
// Output each segment
for segment in &segments {
// Blank line before each segment (after the header or previous segment)
result.push(String::new());
match segment {
AdmonSegment::Code(lines) => {
for (line, orig_indent) in lines {
if line.is_empty() {
// Preserve blank lines inside code blocks
result.push(String::new());
} else {
// Reconstruct with body_indent + any extra
// indentation the line had beyond body_indent
let extra = orig_indent.saturating_sub(body_indent);
let indent_str = " ".repeat(body_indent + extra);
result.push(format!("{indent_str}{line}"));
}
}
}
AdmonSegment::Text(lines) => {
let paragraph_text =
trim_breakable_whitespace(&Self::join_paragraph_lines(lines, config))
.to_string();
if paragraph_text.is_empty() {
continue;
}
let reflowed = crate::utils::text_reflow::reflow_line(
¶graph_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 blocks.get(block_idx + 1).is_some_and(Block::wants_preceding_blank)
&& result.last().is_none_or(|s: &String| !s.is_empty())
{
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()];
// Physical-line-length scan, shared by the Normalize-mode gate and its
// message. The list-item reflow preserves code blocks, HTML blocks,
// admonition headers, fence markers, semantic markers, and snippet/div
// markers verbatim; only paragraph content and admonition bodies are
// restructured. Only those lines drive the length warning, so that
// preserved-but-overlong content does not keep the paragraph-level
// warning alive when the reflow would not fix that line.
let should_count_for_length = |line_idx: usize| -> bool {
let line = lines[line_idx];
let trimmed = line.trim();
if trimmed.is_empty() || is_exempt_line(line, line_idx + 1) {
return false;
}
let info = &ctx.lines[line_idx];
if info.in_code_block || info.in_html_block {
return false;
}
if info.in_admonition && mkdocs_admonitions::is_admonition_start(line) {
return false;
}
if is_fence_marker(line) || is_semantic_line(line) {
return false;
}
if is_snippet_block_delimiter(line) {
return false;
}
if line.trim_start().starts_with(":::") {
return false;
}
true
};
let max_physical_length = (list_start..i)
.filter(|&idx| should_count_for_length(idx))
.map(|idx| self.calculate_effective_length(lines[idx]))
.max()
.unwrap_or(0);
// `line-length = 0` means "no limit", so no physical line can be
// "over"; the message below then describes a structural join rather
// than a length violation.
let any_paragraph_line_over =
!config.line_length.is_unlimited() && max_physical_length > config.line_length.get();
// Normalize mode reflows list-item prose just like paragraphs:
// joining continuation lines and re-wrapping to `line-length`.
// `prose_changed` is true only when the reflow alters the words or
// line breaks, not when it would merely re-indent continuation
// lines or trim trailing whitespace. Comparing the texts with each
// line's leading and trailing whitespace removed isolates "did the
// words/line breaks change" from "did the surrounding whitespace
// change". Continuation indentation is MD077's responsibility and
// trailing whitespace is MD009's; an MD013 warning for either would
// both duplicate those rules and resurface a persistent advisory on
// already-fitting items that users disable MD013 fixing to avoid.
let prose_changed = {
let stripped = |text: &str| text.lines().map(str::trim).collect::<Vec<_>>().join("\n");
stripped(original_text) != stripped(&replacement)
};
// Warn when the reflow rewraps prose (the normalize feature for
// list items), or when a physical line genuinely exceeds the limit
// and the reflow can change something (a true length violation,
// even if all that changes is the continuation indent). A line that
// is already optimal in both respects produces no warning.
let gate_ok = prose_changed || (any_paragraph_line_over && original_text != replacement);
if gate_ok {
// Generate an appropriate message based on why reflow is needed
let message = match config.reflow_mode {
ReflowMode::SentencePack => "List item should pack complete sentences".to_string(),
ReflowMode::SentencePerLine => {
let num_sentences = split_into_sentences(
&combined_content,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.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,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len();
format!("Paragraph should use semantic line breaks ({num_sentences} sentences)")
}
ReflowMode::Normalize => {
// When a physical line genuinely exceeds the limit, report
// it as a length violation. Otherwise the reflow is a
// structural normalization (joining/re-wrapping multi-line
// content that already fits), mirroring the paragraph path.
if any_paragraph_line_over {
format!(
"Line length {} exceeds {} characters",
max_physical_length,
config.line_length.get()
)
} else {
format!(
"List item could be normalized to use line length of {} characters",
config.line_length.get()
)
}
}
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, line_idx + 1)
})
.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].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(byte_range, replacement)),
});
}
}
continue;
}
// A definition's text reflows below, inside the definition. The rest
// of a definition list is left as written: a term is one line of its
// own, and a line holding a definition's marker but none of its text
// opens a block the definition nests (a list, a quote, a code block)
// or leaves the text for the lines below it.
let definition_text = ctx.definition_text_at(line_num).cloned();
if definition_text.is_none() && ctx.is_in_definition_list(line_num) {
i += 1;
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();
// The checks below read one line at a time, and some of what
// they stop at only looks like a block start. A code span still
// open at the end of the line above proves the parser read on,
// and reflowing the paragraph without the rest of the span
// would rewrite the whitespace the span holds.
if line_ends_in_code_span(ctx, i - 1) {
paragraph_lines.push(next_line);
i += 1;
continue;
}
// 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_holds_html_block(i)
// Retain source boundaries before fence-like lines, even
// when a backtick in the info string makes the fence invalid.
// Joining these lines can change neighboring GFM autolinks.
|| (ctx.lines[i].visual_indent <= 3
&& (next_trimmed.starts_with("```") || next_trimmed.starts_with("~~~")))
|| 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(super::super::lint_context::types::LineInfo::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('#')
// A setext heading ends the paragraph before it. The flag is
// set on every line of the heading's text, so the paragraph
// stops at the first of them and absorbs no heading text.
// That also protects the underline, which can only follow the
// last text line, so absorbing the construct and joining it
// into prose is unreachable from here. `is_horizontal_rule`
// below catches a `---` underline only by coincidence (3+
// dashes are also a thematic break); `=` and short `-` runs
// have no such overlap.
|| is_setext_heading_text_line(ctx, next_line_num)
|| TableUtils::is_potential_table_row_with_flavor(next_line, ctx.flavor)
|| (is_list_item(next_trimmed)
&& (in_list(paragraph_start) || {
// Only an ordered marker numbered one interrupts a
// top-level paragraph. Treating a wrapped `7.` or
// `819)` as a new item adds list indentation inside
// any code span that continues onto the next line.
let digits = next_trimmed.bytes().take_while(u8::is_ascii_digit).count();
digits == 0 || next_trimmed[..digits].trim_start_matches('0') == "1"
}))
|| is_horizontal_rule(next_line)
|| (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)
|| is_html_only_line(next_line)
|| self.line_in_multiline_math_block(next_line_num, ctx, config)
// A line that is one whole `$$...$$` expression renders as a
// display block, so it ends the paragraph above it and is
// reflowed on its own. A line touched by a code span crossing
// one of its boundaries is code, not such a block.
|| ((is_self_contained_display_math_line(next_line)
|| self.line_is_standalone_bracket_math(next_line_num, ctx, config))
&& !line_touches_multiline_code_span(&code_span_touches, next_line_num))
|| standalone_link_ends_paragraph(ctx, next_line_num, config)
// A definition's text ends where the parser ends it.
|| definition_text
.as_ref()
.is_some_and(|text| next_line_num > text.end_line)
{
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;
}
// Compute the common leading indent of all non-empty paragraph lines,
// but only when those lines are structurally inside a list block.
// Indented continuation lines that follow a nested list arrive here
// with their structural indentation intact (e.g. 2 spaces for a
// top-level list item). Stripping the indent before reflow and
// re-applying it afterward prevents the fixer from moving those
// lines to column 0.
//
// The list-block guard is essential: top-level paragraphs that happen
// to start with spaces (insignificant in Markdown) must NOT have those
// spaces preserved or injected by the fixer.
//
// A lazy line falls short of the content of the item the paragraph
// starts in, so its indentation does not count: the reflowed lines
// belong to the item.
let common_indent: String = if in_list(paragraph_start) {
let indent_of = |l: &str| l.len() - l.trim_start().len();
let item_content_col = ctx.lines[..paragraph_start].iter().rev().find_map(|info| {
info.list_item
.as_ref()
// Even an empty marker without source padding has a
// content column one space beyond the marker. Lazy
// lines short of it cannot reduce the paragraph indent.
.map(|item| item.content_column.max(item.marker_column + item.marker.len() + 1))
.filter(|&col| col <= indent_of(paragraph_lines[0]))
});
let min_len = paragraph_lines
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| indent_of(l))
.filter(|&indent| item_content_col.is_none_or(|col| indent >= col))
.min()
.unwrap_or(0);
paragraph_lines
.iter()
.find(|l| !l.trim().is_empty())
.map(|l| l[..min_len].to_string())
.unwrap_or_default()
} else {
String::new()
};
// What the reflowed lines are written after. A definition's text
// starting on its marker line keeps the marker and the spacing the
// author gave it, and its other lines are indented to where the text
// starts, which is the definition's content column, or to four
// columns when that is less. Text starting on a later line, a later
// paragraph of the definition or the part after a hard break, keeps
// the indentation its first line has. Everything else takes the
// common indent: the first line and the rest alike.
let (first_prefix, rest_indent) = match &definition_text {
Some(text) => {
let indent_width = |line: &str| {
crate::utils::calculate_indentation_width_default(&line[..line.len() - line.trim_start().len()])
};
let text_lines = &lines[text.start_line - 1..text.end_line];
let marker_prefix = text.marker_prefix_len.map(|len| &text_lines[0][..len]);
// The colon takes one column, and a tab after it reaches the
// next tab stop. The other lines take at least four columns
// even after a narrower marker (`: text`): they continue the
// paragraph at any indentation in CommonMark, but
// Python-Markdown keeps a line indented less than four in the
// definition only when no other definition follows it
// directly, and otherwise reads the text as terms of a new
// list.
let continuation = match marker_prefix {
Some(prefix) => {
crate::utils::calculate_indentation_width_default(&prefix.replacen(':', " ", 1)).max(4)
}
None => indent_width(text_lines[0]),
};
// A hard break splits the text into parts reflowed one at a
// time. With a line after the break indented less than the
// continuation, reflowing one part would leave the parts
// indented differently, and Python-Markdown ends the
// definition at the first line indented less than the lines
// before it, so the text is left as written.
let split_by_hard_break = text_lines[..text_lines.len() - 1]
.iter()
.any(|line| has_hard_break(line));
if split_by_hard_break && text_lines[1..].iter().any(|line| indent_width(line) < continuation) {
i = paragraph_start + paragraph_lines.len();
continue;
}
match marker_prefix.filter(|_| text.start_line == paragraph_start + 1) {
Some(prefix) => (prefix.to_string(), " ".repeat(continuation)),
None => {
let first_line = lines[paragraph_start];
let indent = &first_line[..first_line.len() - first_line.trim_start().len()];
(indent.to_string(), indent.to_string())
}
}
}
None => (common_indent.clone(), common_indent.clone()),
};
// Combine paragraph lines into a single string for processing.
// This must be done BEFORE the needs_reflow check for sentence-per-line mode.
let stripped: Vec<&str> = if definition_text.is_some() {
paragraph_lines
.iter()
.enumerate()
.map(|(idx, l)| {
if idx == 0 {
&l[first_prefix.len()..]
} else {
l.trim_start()
}
})
.collect()
} else {
paragraph_lines
.iter()
.map(|l| {
if l.starts_with(common_indent.as_str()) {
&l[common_indent.len()..]
} else {
l.trim_start()
}
})
.collect()
};
if code_span_runs_into_indentation(&stripped) {
i = paragraph_start + paragraph_lines.len();
continue;
}
let paragraph_text = Self::join_paragraph_lines(&stripped, config);
// A colon-led line with a line of the paragraph before it opens a
// definition, and joining the lines would flatten the definition
// list into prose, so the paragraph is skipped. Its first line is
// prose whatever it starts with, since a definition needs a term on
// the line before it. The indentation a marker is allowed is
// counted from the block's own content, so a list item's
// indentation comes off first. A paragraph holding a line of a
// definition the parser opens on a colon touching its text is
// skipped too when its inline constructs differ between the two
// readings, since the context reports only the parser's.
let contains_definition_list = paragraph_lines.iter().skip(1).any(|line| {
let content = line.strip_prefix(rest_indent.as_str()).unwrap_or(line.trim_start());
crate::utils::text_reflow::is_definition_list_marker(content)
}) || (paragraph_start..paragraph_start + paragraph_lines.len())
.any(|idx| ctx.in_colon_definition(idx + 1));
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;
}
// Leave a line of a multi-line display-math block as it is, where
// joining lines would corrupt the equation (see
// `line_in_multiline_math_block`). Only the first line has to be
// asked about: such a line ends the paragraph above it, so a
// paragraph reaching here holds one only when it starts on one.
//
// Only that line is passed over, not the rest of what was collected
// with it: prose written directly under the closing delimiter is an
// ordinary paragraph and still reflows.
if self.line_in_multiline_math_block(paragraph_start + 1, ctx, config) {
i = paragraph_start + 1;
continue;
}
// A line that is one whole `$$...$$` expression is a display block:
// it keeps the line it was written on, and the prose under it is an
// ordinary paragraph that still reflows. The line above ended at
// this one, so a paragraph reaching here holds one only when it
// starts on one. A paragraph can start on a line touched by a code
// span crossing one of its boundaries, under a hard break the span
// holds, and its first line is code then.
if (is_self_contained_display_math_line(lines[paragraph_start])
|| self.line_is_standalone_bracket_math(paragraph_start + 1, ctx, config))
&& !line_touches_multiline_code_span(&code_span_touches, paragraph_start + 1)
{
i = paragraph_start + 1;
continue;
}
// Check if this paragraph needs reflowing
let needs_reflow = match config.reflow_mode {
ReflowMode::SentencePack => true,
ReflowMode::Normalize => self.normalize_mode_needs_reflow(paragraph_lines.iter().copied(), config),
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(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
// 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.
// paragraph_text has the prefix stripped, so add back
// the prefix of the first line, the one line the
// joined sentence is written on.
let effective_length =
self.calculate_effective_length(¶graph_text) + first_prefix.len();
effective_length <= config.line_length.get()
}
} else {
false
}
}
ReflowMode::SemanticLineBreaks => {
let sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
);
// 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 = ctx.whole_line_byte_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
ctx.line_text_byte_range(end_line + 1, 1, lines[end_line].len() + 1)
} else {
// Not the last line or has trailing newline - use whole_line_range
ctx.whole_line_byte_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().saturating_sub(rest_indent.len()).max(1)
};
let mut reflow_options = Self::reflow_options(ctx, config, reflow_line_length);
reflow_options.wrap_code_spans = first_prefix.is_empty() && rest_indent.is_empty();
if config.reflow_mode == ReflowMode::SentencePack && !config.line_length.is_unlimited() {
reflow_options.first_line_length = Some(
config
.line_length
.effective_limit()
.saturating_sub(self.calculate_string_length(&first_prefix))
.max(1),
);
}
let mut reflowed = crate::utils::text_reflow::reflow_line(¶graph_text, &reflow_options);
// Re-apply the prefix to each non-empty reflowed line so that the
// replacement preserves the original structural indentation.
for (idx, line) in reflowed.iter_mut().enumerate() {
let prefix = if idx == 0 { &first_prefix } else { &rest_indent };
if !line.is_empty() && !prefix.is_empty() {
*line = format!("{prefix}{line}");
}
}
// 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 {
// Determine which line ranges and messages to report based on the reflow mode.
let warnings_to_report: Vec<(usize, usize, String)> = match config.reflow_mode {
ReflowMode::SentencePack => vec![(
paragraph_start + 1,
end_line + 1,
"Paragraph should pack complete sentences".to_string(),
)],
ReflowMode::Default => {
// In default mode, report a warning for *every* line in the paragraph
// that exceeds the limit. Each warning will carry the same paragraph-level
// fix, making all of them auto-fixable.
paragraph_lines
.iter()
.enumerate()
.filter(|(_, line)| self.calculate_effective_length(line) > config.line_length.get())
.map(|(idx, _)| {
let violating_line = paragraph_start + idx + 1;
(
violating_line,
violating_line,
format!("Line length exceeds {} characters", config.line_length.get()),
)
})
.collect()
}
ReflowMode::Normalize => {
// In normalize mode, report the whole paragraph as needing normalization.
vec![(
paragraph_start + 1,
end_line + 1,
format!(
"Paragraph could be normalized to use line length of {} characters",
config.line_length.get()
),
)]
}
ReflowMode::SentencePerLine => {
// In sentence-per-line mode, highlight the entire paragraph that needs reformatting.
let num_sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len();
let message = if paragraph_lines.len() == 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
let num_lines = paragraph_lines.len();
format!(
"Paragraph should have one sentence per line (found {num_sentences} sentences across {num_lines} lines)"
)
};
vec![(paragraph_start + 1, paragraph_start + paragraph_lines.len(), message)]
}
ReflowMode::SemanticLineBreaks => {
// In semantic-line-breaks mode, highlight the entire paragraph.
let num_sentences = split_into_sentences(
¶graph_text,
Some(&defined_references),
config.require_sentence_capital,
config.cjk_soft_break,
)
.len();
vec![(
paragraph_start + 1,
paragraph_start + paragraph_lines.len(),
format!("Paragraph should use semantic line breaks ({num_sentences} sentences)"),
)]
}
};
// Generate the actual lint warnings. All warnings for this paragraph
// share the same paragraph-level fix.
for (w_start, w_end, msg) in warnings_to_report {
warnings.push(LintWarning {
rule_name: Some(self.name().to_string()),
message: msg,
line: w_start,
column: 1,
end_line: w_end,
end_column: lines[w_end.saturating_sub(1)].chars().count() + 1,
severity: Severity::Warning,
fix: Some(crate::rule::Fix::new(byte_range.clone(), replacement.clone())),
});
}
}
}
}
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 `` 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., `[](url)`) by only counting the
/// outermost construct to avoid double-counting.
fn length_without_inline_link_urls(
&self,
effective_length: usize,
line_number: usize,
ctx: &crate::lint_context::LintContext,
) -> usize {
let line_range = ctx.line_content_byte_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();
for link in ctx.links_on_line(line_number) {
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));
}
for image in ctx.images_on_line(line_number) {
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)
}
}