rumdl 0.1.88

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
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
use rumdl_lib::config::MarkdownFlavor;
use rumdl_lib::lint_context::LintContext;
use rumdl_lib::rule::Rule;
use rumdl_lib::rules::{ColumnAlign, MD013Config, MD060Config, MD060TableFormat};
use rumdl_lib::types::LineLength;
use unicode_width::UnicodeWidthStr;

#[test]
fn test_md060_align_simple_ascii_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(warnings.len(), 3, "Should warn about all three rows");

    let fixed = rule.fix(&ctx).unwrap();
    let expected = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |";
    assert_eq!(fixed, expected);

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_cjk_characters() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Age |\n|---|---|\n| 中文 | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("中文"), "CJK characters should be preserved");

    // Verify all rows have equal display width in aligned mode (not byte length!)
    // CJK characters take more bytes but should have same display width
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].width(), lines[1].width(), "Display widths should match");
    assert_eq!(lines[1].width(), lines[2].width(), "Display widths should match");

    let content2 = "| Name | City |\n|---|---|\n| Alice | 東京 |";
    let ctx2 = LintContext::new(content2, MarkdownFlavor::Standard, None);
    let fixed2 = rule.fix(&ctx2).unwrap();
    assert!(fixed2.contains("東京"), "Japanese characters should be preserved");

    // Verify all rows have equal display width in aligned mode
    let lines2: Vec<&str> = fixed2.lines().collect();
    assert_eq!(lines2[0].width(), lines2[1].width(), "Display widths should match");
    assert_eq!(lines2[1].width(), lines2[2].width(), "Display widths should match");
}

#[test]
fn test_md060_basic_emoji() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Status | Name |\n|---|---|\n| ✅ | Test |\n| ❌ | Fail |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains(""), "Basic emoji should be preserved");
    assert!(fixed.contains(""), "Basic emoji should be preserved");
    assert!(fixed.contains("Test"));
    assert!(fixed.contains("Fail"));

    // Verify all rows have equal display width in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4);
    assert_eq!(lines[0].width(), lines[1].width(), "Display widths should match");
    assert_eq!(lines[1].width(), lines[2].width(), "Display widths should match");
    assert_eq!(lines[2].width(), lines[3].width(), "Display widths should match");
}

#[test]
fn test_md060_zwj_emoji_skipped() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Emoji | Name |\n|---|---|\n| 👨‍👩‍👧‍👦 | Family |\n| 👩‍💻 | Developer |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(
        warnings.len(),
        0,
        "Tables with ZWJ emoji should be skipped (no warnings)"
    );

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(fixed, content, "Tables with ZWJ emoji should not be modified");
}

#[test]
fn test_md060_inline_code_with_escaped_pipes() {
    // In GFM tables, bare pipes in inline code STILL act as cell delimiters.
    // To include a literal pipe in table content (even in code), escape it with \|

    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // WRONG: `[0-9]|[0-9]` - the | splits cells (3 columns total)
    // CORRECT: `[0-9]\|[0-9]` - the \| is escaped, stays as content (2 columns)
    let content = "| Pattern | Regex |\n|---|---|\n| Time | `[0-9]\\|[0-9]` |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // The escaped pipe \| should be preserved in the output
    assert!(
        fixed.contains(r"`[0-9]\|[0-9]`"),
        "Escaped pipes in inline code should be preserved"
    );

    // Verify all rows have equal length in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_complex_regex_with_escaped_pipes() {
    // In GFM tables, bare pipes in inline code STILL act as cell delimiters.
    // Regex patterns with | must escape the pipe character with \|

    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // CORRECT: Pipes escaped with \| stay as content
    let content =
        "| Challenge | Solution |\n|---|---|\n| Hour:minute:second | `^([0-1]?\\d\\|2[0-3]):[0-5]\\d:[0-5]\\d$` |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // The escaped pipe \| should be preserved
    assert!(
        fixed.contains(r"`^([0-1]?\d\|2[0-3]):[0-5]\d:[0-5]\d$`"),
        "Complex regex with escaped pipes should be preserved"
    );

    // Verify all rows have equal length in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_compact_style() {
    let rule = MD060TableFormat::new(true, "compact".to_string());

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let expected = "| Name | Age |\n| --- | --- |\n| Alice | 30 |";
    assert_eq!(fixed, expected);

    let lines: Vec<&str> = fixed.lines().collect();
    assert!(lines[0].len() < 20, "Compact style should be short");
}

#[test]
fn test_md060_max_width_fallback() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| VeryLongColumnName | AnotherLongColumn | ThirdColumn |\n|---|---|---|\n| Data | Data | Data |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    assert!(
        fixed.lines().all(|line| line.len() <= 80),
        "Wide tables should fall back to compact mode"
    );
}

#[test]
fn test_md060_empty_cells() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| A | B | C |\n|---|---|---|\n|  | X |  |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains('|'), "Table structure should be preserved");

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3, "All rows should be present");

    // Verify all rows have equal length in aligned mode
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_mixed_content() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Age | City | Status |\n|---|---|---|---|\n| 中文 | 30 | NYC | ✅ |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("中文"), "CJK should be preserved");
    assert!(fixed.contains("NYC"), "ASCII should be preserved");
    assert!(fixed.contains(""), "Emoji should be preserved");

    // Verify all rows have equal display width in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].width(), lines[1].width(), "Display widths should match");
    assert_eq!(lines[1].width(), lines[2].width(), "Display widths should match");
}

#[test]
fn test_md060_preserve_alignment_indicators() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // Now with alignment support: A is left-aligned, B is center-aligned, C is right-aligned
    let expected = "| Left | Center | Right |\n| :--- | :----: | ----: |\n| A    |   B    |     C |";
    assert_eq!(fixed, expected);

    // Verify all rows have equal length in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());

    // Verify delimiter row format with spaces
    assert!(lines[1].contains(" :--- "), "Left alignment should have spaces");
    assert!(lines[1].contains(" :----: "), "Center alignment should have spaces");
    assert!(lines[1].contains(" ----: "), "Right alignment should have spaces");
}

#[test]
fn test_md060_table_with_trailing_newline() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.ends_with('\n'), "Trailing newline should be preserved");
}

#[test]
fn test_md060_multiple_tables() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Use ACTUALLY misaligned tables (different row lengths within each table)
    let content = "# First Table\n\n| A | B |\n|---|---|\n| 1 | 2222 |\n\n# Second Table\n\n| X | Y | Z |\n|---|---|---|\n| aaaa | b | c |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("# First Table"));
    assert!(fixed.contains("# Second Table"));

    let warnings = rule.check(&ctx).unwrap();
    assert!(warnings.len() >= 6, "Should warn about both tables");
}

#[test]
fn test_md060_table_without_content_rows() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Header 1 | Header 2 |\n|---|---|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("Header 1"));
    assert!(fixed.contains("Header 2"));
}

#[test]
fn test_md060_none_style() {
    let rule = MD060TableFormat::new(true, "none".to_string());

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(warnings.len(), 0, "None style should not produce warnings");

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(fixed, content, "None style should not modify content");
}

#[test]
fn test_md060_single_column_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Column |\n|---|\n| Value1 |\n| Value2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("Column"));
    assert!(fixed.contains("Value1"));
    assert!(fixed.contains("Value2"));
}

#[test]
fn test_md060_table_in_context() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content =
        "# Documentation\n\nSome text before.\n\n| Name | Age |\n|---|---|\n| Alice | 30 |\n\nSome text after.";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("# Documentation"));
    assert!(fixed.contains("Some text before."));
    assert!(fixed.contains("Some text after."));
    assert!(fixed.contains("| Name  | Age |"));

    // Extract just the table lines for row length equality check
    let lines: Vec<&str> = fixed.lines().collect();
    let table_lines: Vec<&str> = lines
        .iter()
        .skip_while(|line| !line.starts_with('|'))
        .take_while(|line| line.starts_with('|'))
        .copied()
        .collect();
    assert_eq!(table_lines[0].len(), table_lines[1].len());
    assert_eq!(table_lines[1].len(), table_lines[2].len());
}

#[test]
fn test_md060_warning_messages() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(warnings.len(), 3);

    for warning in &warnings {
        assert_eq!(warning.message, "Table columns should be aligned");
        assert_eq!(warning.rule_name, Some("MD060".to_string()));
        assert!(warning.fix.is_some(), "Each warning should have a fix");
    }
}

#[test]
fn test_md060_escaped_pipes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Pattern | Description |\n|---|---|\n| `a\\|b` | Or operator |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains("`a\\|b`"), "Escaped pipes should be preserved");
}

#[test]
fn test_md060_very_long_content() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let long_text = "A".repeat(100);
    let content = format!("| Col1 | Col2 |\n|---|---|\n| {long_text} | B |");
    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    assert!(fixed.contains(&long_text), "Long content should be preserved");
}

#[test]
fn test_md060_minimum_column_width() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test with very short column content (1-2 chars) to ensure minimum width of 3
    // This is required because GFM mandates at least 3 dashes in delimiter rows
    let content = "| ID | First Name | Last Name | Department |\n|-|-|-|-|\n| 1 | John | Doe | Engineering |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // All lines should have equal length when properly aligned
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3);
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should be same length"
    );
    assert_eq!(
        lines[1].len(),
        lines[2].len(),
        "Delimiter and content should be same length"
    );

    // Check that short columns (like "ID" and "1") are padded to at least width 3
    assert!(
        lines[0].contains("ID  "),
        "Short header 'ID' should be padded to minimum width"
    );
    assert!(lines[1].contains("---"), "Delimiter should have at least 3 dashes");
    assert!(
        lines[2].contains("1  "),
        "Short content '1' should be padded to minimum width"
    );

    // Verify the specific problematic case from the test file
    assert!(
        lines[0].starts_with("| ID "),
        "First column should be properly aligned with minimum width 3"
    );
}

#[test]
fn test_md060_minimum_width_with_alignment_indicators() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test minimum width with alignment indicators
    let content = "| A | B | C |\n|:---|---:|:---:|\n| X | Y | Z |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());

    // Verify alignment indicators are preserved
    assert!(lines[1].contains(":---"), "Left alignment should be preserved");
    assert!(lines[1].contains("---:"), "Right alignment should be preserved");
    assert!(lines[1].contains(":---:"), "Center alignment should be preserved");
}

#[test]
fn test_md060_empty_header_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "|||\n|-|-|\n|lorem|ipsum|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // Empty headers should be formatted with proper spacing
    let expected = "|       |       |\n| ----- | ----- |\n| lorem | ipsum |";
    assert_eq!(fixed, expected, "Empty header table should be formatted");

    // Verify all rows have equal length in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3);
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_delimiter_width_does_not_affect_alignment() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // The first delimiter has many dashes, but that shouldn't affect column width
    let content = "|lorem|ipsum|\n|--------------|-|\n|dolor|sit|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // Column width should be based on content (lorem/dolor), not delimiter dashes
    let expected = "| lorem | ipsum |\n| ----- | ----- |\n| dolor | sit   |";
    assert_eq!(
        fixed, expected,
        "Delimiter row width should not affect column alignment"
    );

    // Verify all rows have equal length in aligned mode
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3);
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_content_alignment_left() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Left |\n|:-----|\n| A |\n| BB |\n| CCC |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
    assert_eq!(lines[3].len(), lines[4].len());

    // Content should be left-aligned (padding on right)
    // Column width is 4 (from "Left"), so padding for each:
    // A (1 char): padding=3 → "| A    |" (boundary + A + 3 spaces + boundary)
    // BB (2 chars): padding=2 → "| BB   |"
    // CCC (3 chars): padding=1 → "| CCC  |"
    assert!(
        lines[2].contains("| A    |"),
        "Single char should be left-aligned with padding on right"
    );
    assert!(
        lines[3].contains("| BB   |"),
        "Two chars should be left-aligned with padding on right"
    );
    assert!(
        lines[4].contains("| CCC  |"),
        "Three chars should be left-aligned with padding on right"
    );
}

#[test]
fn test_md060_content_alignment_center() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Center |\n|:------:|\n| A |\n| BB |\n| CCC |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
    assert_eq!(lines[3].len(), lines[4].len());

    // Content should be center-aligned (padding split on both sides)
    // Format: "| <boundary><left_pad><content><right_pad><boundary> |"
    // For "A" in width 6: padding=5, left=2, right=3 → "| <1><2>A<3><1> |" = "|   A    |"
    // For "BB" in width 6: padding=4, left=2, right=2 → "| <1><2>BB<2><1> |" = "|   BB   |"
    // For "CCC" in width 6: padding=3, left=1, right=2 → "| <1><1>CCC<2><1> |" = "|  CCC   |"
    assert!(
        lines[2].contains("|   A    |"),
        "Single char should be center-aligned, got: {}",
        lines[2]
    );
    assert!(
        lines[3].contains("|   BB   |"),
        "Two chars should be center-aligned, got: {}",
        lines[3]
    );
    assert!(
        lines[4].contains("|  CCC   |"),
        "Three chars should be center-aligned, got: {}",
        lines[4]
    );
}

#[test]
fn test_md060_content_alignment_right() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Right |\n|------:|\n| A |\n| BB |\n| CCC |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
    assert_eq!(lines[3].len(), lines[4].len());

    // Content should be right-aligned (padding on left)
    // Format: "| <boundary><padding><content><boundary> |" where boundary+padding creates visual right alignment
    assert!(
        lines[2].contains("|     A |"),
        "Single char should be right-aligned with padding on left, got: {}",
        lines[2]
    );
    assert!(
        lines[3].contains("|    BB |"),
        "Two chars should be right-aligned with padding on left, got: {}",
        lines[3]
    );
    assert!(
        lines[4].contains("|   CCC |"),
        "Three chars should be right-aligned with padding on left, got: {}",
        lines[4]
    );
}

#[test]
fn test_md060_mixed_column_alignments() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |\n| AA | BB | CC |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());

    // Parse the content rows to check alignment
    let row1 = lines[2];
    let row2 = lines[3];

    // First column (left-aligned): padding on right
    assert!(
        row1.starts_with("| A "),
        "First column should be left-aligned in row 1, got: {row1}",
    );
    assert!(
        row2.starts_with("| AA"),
        "First column should be left-aligned in row 2, got: {row2}",
    );

    // Third column (right-aligned): padding on left
    // For "Right" column (width ~5) with content "C" (1 char), expect boundary + 4 padding + C + boundary
    assert!(
        row1.contains("|     C |"),
        "Third column should be right-aligned in row 1, got: {row1}",
    );
    assert!(
        row1.ends_with("|     C |"),
        "Third column should be at end of row 1, got: {row1}",
    );
    // For content "CC" (2 chars), expect boundary + 3 padding + CC + boundary
    assert!(
        row2.contains("|    CC |"),
        "Third column should be right-aligned in row 2, got: {row2}",
    );
    assert!(
        row2.ends_with("|    CC |"),
        "Third column should be at end of row 2, got: {row2}",
    );
}

#[test]
fn test_md060_tables_in_html_comments_should_not_be_formatted() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "# Normal table\n\n| A | B |\n|---|---|\n| C | D |\n\n<!-- Commented table\n| X | Y |\n|---|---|\n| Z | W |\n-->\n\n| E | F |\n|---|---|\n| G | H |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();

    // Should only warn about the two tables outside comments (lines 3-5 and 13-15)
    // That's 3 lines for first table + 3 lines for last table = 6 warnings
    let non_comment_warnings: Vec<_> = warnings
        .iter()
        .filter(|w| {
            let line = w.line;
            // Lines 3-5 are the first table, lines 13-15 are the last table
            (3..=5).contains(&line) || (13..=15).contains(&line)
        })
        .collect();

    assert_eq!(
        non_comment_warnings.len(),
        warnings.len(),
        "Should only warn about tables outside HTML comments. Got {} warnings total, expected 6",
        warnings.len()
    );

    let fixed = rule.fix(&ctx).unwrap();

    // The commented table should remain unformatted
    assert!(fixed.contains("| X | Y |"), "Commented table should not be modified");
    assert!(fixed.contains("| Z | W |"), "Commented table should not be modified");

    // The normal tables should be formatted
    assert!(
        fixed.contains("| A | B |") || fixed.contains("| A   | B   |"),
        "Normal table should be formatted"
    );
    assert!(
        fixed.contains("| E | F |") || fixed.contains("| E   | F   |"),
        "Normal table should be formatted"
    );
}

// ============================================================================
// CRITICAL EDGE CASE TESTS (Top 10 from comprehensive analysis)
// ============================================================================

#[test]
fn test_md060_zero_width_characters() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test Zero Width Space (U+200B), Zero Width Non-Joiner (U+200C), Word Joiner (U+2060)
    let content = "| Name | Status |\n|---|---|\n| Test\u{200B}Word | Active\u{200C}User |\n| Word\u{2060}Join | OK |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(
        warnings.len(),
        0,
        "Tables with zero-width characters should be skipped (no warnings)"
    );

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(
        fixed, content,
        "Tables with zero-width characters should not be modified"
    );

    // Verify characters are preserved in original form
    assert!(
        fixed.contains("Test\u{200B}Word"),
        "Zero Width Space should be preserved"
    );
    assert!(
        fixed.contains("Active\u{200C}User"),
        "Zero Width Non-Joiner should be preserved"
    );
    assert!(fixed.contains("Word\u{2060}Join"), "Word Joiner should be preserved");
}

#[test]
fn test_md060_rtl_text_arabic() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test Arabic text (RTL)
    let content = "| Name | City |\n|---|---|\n| أحمد | القاهرة |\n| محمد | دبي |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Arabic text should be preserved
    assert!(fixed.contains("أحمد"), "Arabic name should be preserved");
    assert!(fixed.contains("القاهرة"), "Arabic city should be preserved");
    assert!(fixed.contains("محمد"), "Arabic name should be preserved");
    assert!(fixed.contains("دبي"), "Arabic city should be preserved");

    // All lines should have equal display width
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(
        lines[0].width(),
        lines[1].width(),
        "Display widths should match for RTL text"
    );
    assert_eq!(
        lines[1].width(),
        lines[2].width(),
        "Display widths should match for RTL text"
    );
    assert_eq!(
        lines[2].width(),
        lines[3].width(),
        "Display widths should match for RTL text"
    );
}

#[test]
fn test_md060_rtl_text_hebrew() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test Hebrew text (RTL)
    let content = "| שם | עיר |\n|---|---|\n| דוד | תל אביב |\n| שרה | ירושלים |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Hebrew text should be preserved
    assert!(fixed.contains("דוד"), "Hebrew name should be preserved");
    assert!(fixed.contains("תל אביב"), "Hebrew city should be preserved");
    assert!(fixed.contains("שרה"), "Hebrew name should be preserved");
    assert!(fixed.contains("ירושלים"), "Hebrew city should be preserved");

    // All lines should have equal display width
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(
        lines[0].width(),
        lines[1].width(),
        "Display widths should match for RTL text"
    );
    assert_eq!(
        lines[1].width(),
        lines[2].width(),
        "Display widths should match for RTL text"
    );
    assert_eq!(
        lines[2].width(),
        lines[3].width(),
        "Display widths should match for RTL text"
    );
}

#[test]
fn test_md060_mismatched_column_counts_more_in_header() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Header has 4 columns, delimiter has 3, content has 2
    let content = "| A | B | C | D |\n|---|---|---|\n| X | Y |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // This should not panic or crash
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Should handle mismatched column counts gracefully");

    let fixed = result.unwrap();
    // The implementation should handle this gracefully, either by:
    // 1. Not formatting the table at all (safest)
    // 2. Formatting based on delimiter row column count
    // 3. Formatting based on max column count
    // We just verify it doesn't panic
    assert!(
        fixed.contains('A') || fixed.contains('X'),
        "Content should be preserved"
    );
}

#[test]
fn test_md060_mismatched_column_counts_more_in_content() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Header has 2 columns, delimiter has 2, content has 4
    let content = "| A | B |\n|---|---|\n| X | Y | Z | W |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // This should not panic or crash
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Should handle mismatched column counts gracefully");

    let fixed = result.unwrap();
    assert!(
        fixed.contains('A') || fixed.contains('X'),
        "Content should be preserved"
    );
}

#[test]
fn test_md060_escaped_pipes_outside_code() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test escaped pipes in regular text (not in inline code)
    let content = "| Operator | Example |\n|---|---|\n| OR | a \\| b |\n| Pipe | x \\| y \\| z |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Escaped pipes should be preserved in the cell content
    assert!(fixed.contains("\\|"), "Escaped pipes should be preserved");

    // Verify table structure is maintained - should have 4 lines
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4, "All rows should be present");

    // Verify the escaped pipes are in the correct cells (not split into separate columns)
    assert!(
        lines[2].contains("a \\| b"),
        "First escaped pipe example should be in single cell, got: {}",
        lines[2]
    );
    assert!(
        lines[3].contains("x \\| y \\| z"),
        "Second escaped pipe example should be in single cell, got: {}",
        lines[3]
    );

    // All lines should have equal length in aligned mode
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
}

#[test]
fn test_md060_combining_characters_diacritics() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test combining diacritical marks (café, São Paulo, etc.)
    let content = "| City | Country |\n|---|---|\n| café | français |\n| São Paulo | Brasil |\n| Zürich | Schweiz |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Combining characters should be preserved
    assert!(fixed.contains("café"), "Café with combining acute should be preserved");
    assert!(fixed.contains("São"), "São with combining tilde should be preserved");
    assert!(
        fixed.contains("Zürich"),
        "Zürich with combining umlaut should be preserved"
    );

    // All lines should have proper display width
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(
        lines[0].width(),
        lines[1].width(),
        "Display widths should match with diacritics"
    );
    assert_eq!(
        lines[1].width(),
        lines[2].width(),
        "Display widths should match with diacritics"
    );
}

#[test]
fn test_md060_skin_tone_modifiers() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test emoji with skin tone modifiers (these are complex grapheme clusters)
    let content = "| User | Avatar |\n|---|---|\n| Alice | 👍🏻 |\n| Bob | 👋🏿 |\n| Carol | 🤝🏽 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // This might be skipped like ZWJ emoji due to measurement complexity
    let fixed = rule.fix(&ctx).unwrap();

    // Skin tone modifiers should be preserved
    assert!(fixed.contains("👍🏻"), "Emoji with light skin tone should be preserved");
    assert!(fixed.contains("👋🏿"), "Emoji with dark skin tone should be preserved");
    assert!(fixed.contains("🤝🏽"), "Emoji with medium skin tone should be preserved");
}

#[test]
fn test_md060_flag_emojis() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test flag emojis (regional indicator symbols)
    let content = "| Country | Flag |\n|---|---|\n| USA | 🇺🇸 |\n| Japan | 🇯🇵 |\n| France | 🇫🇷 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Flag emojis should be preserved
    assert!(fixed.contains("🇺🇸"), "US flag should be preserved");
    assert!(fixed.contains("🇯🇵"), "Japan flag should be preserved");
    assert!(fixed.contains("🇫🇷"), "France flag should be preserved");
}

#[test]
fn test_md060_tables_in_blockquotes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test tables inside blockquotes
    let content = "> | Name | Age |\n> |---|---|\n> | Alice | 30 |\n\nNormal text\n\n| X | Y |\n|---|---|\n| A | B |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Blockquote should be preserved
    assert!(fixed.starts_with("> "), "Blockquote markers should be preserved");

    // Both tables should be present
    assert!(
        fixed.contains("Alice") || fixed.contains("Name"),
        "Table in blockquote should be present"
    );
    assert!(
        fixed.contains('A') && fixed.contains('B'),
        "Normal table should be present"
    );
}

#[test]
fn test_md060_tables_in_nested_blockquotes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test tables inside nested blockquotes (>> prefix)
    let content = ">> | Col1 | Col2 |\n>> |---|---|\n>> | A | B |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should preserve the >> prefix
    assert!(lines[0].starts_with(">> "), "Header should preserve >> prefix");
    assert!(lines[1].starts_with(">> "), "Delimiter should preserve >> prefix");
    assert!(lines[2].starts_with(">> "), "Content should preserve >> prefix");
}

#[test]
fn test_md060_tables_in_deeply_nested_blockquotes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test tables inside deeply nested blockquotes (>>> prefix)
    let content = ">>> | X | Y | Z |\n>>> |---|---|---|\n>>> | 1 | 2 | 3 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should preserve the >>> prefix
    for (i, line) in lines.iter().enumerate() {
        assert!(
            line.starts_with(">>> "),
            "Line {i} should preserve >>> prefix, got: {line}"
        );
    }
}

#[test]
fn test_md060_blockquote_table_all_styles() {
    // Test that all formatting styles preserve blockquote prefix
    let content = "> | A | B |\n> |---|---|\n> | 1 | 2 |";

    for style in ["aligned", "compact", "tight"] {
        let rule = MD060TableFormat::new(true, style.to_string());
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

        let fixed = rule.fix(&ctx).unwrap();
        let lines: Vec<&str> = fixed.lines().collect();

        for (i, line) in lines.iter().enumerate() {
            assert!(
                line.starts_with("> "),
                "Style '{style}' line {i} should preserve '> ' prefix, got: {line}"
            );
        }
    }
}

#[test]
fn test_md060_blockquote_table_compact_prefix() {
    let rule = MD060TableFormat::new(true, "compact".to_string());

    // Blockquote with no space after > (valid but unusual)
    let content = ">| A | B |\n>|---|---|\n>| 1 | 2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Should preserve the >| prefix style (no space)
    for (i, line) in lines.iter().enumerate() {
        assert!(line.starts_with('>'), "Line {i} should start with >, got: {line}");
    }
}

#[test]
fn test_md060_blockquote_table_preserves_alignment() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table with alignment indicators inside blockquote
    let content = "> | Left | Center | Right |\n> |:---|:---:|---:|\n> | A | B | C |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Verify blockquote prefix is preserved
    assert!(fixed.starts_with("> "), "Should start with blockquote prefix");

    // Verify alignment indicators are preserved
    assert!(fixed.contains(":---"), "Left alignment should be preserved");
    assert!(fixed.contains("---:"), "Right alignment should be preserved");
}

#[test]
fn test_md060_multiple_blockquote_tables() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Two separate tables in same blockquote (separated by blank blockquote line)
    let content = "> | A | B |\n> |---|---|\n> | 1 | 2 |\n>\n> | X | Y |\n> |---|---|\n> | 3 | 4 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All non-empty lines should have blockquote prefix
    for (i, line) in lines.iter().enumerate() {
        if !line.is_empty() {
            assert!(
                line.starts_with('>'),
                "Line {i} should have blockquote prefix, got: {line}"
            );
        }
    }

    // Both tables should have content preserved
    assert!(
        fixed.contains('1') && fixed.contains('2'),
        "First table content preserved"
    );
    assert!(
        fixed.contains('3') && fixed.contains('4'),
        "Second table content preserved"
    );
}

#[test]
fn test_md060_adjacent_tables_without_blank_line() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test two tables directly adjacent (no blank line between)
    // This is technically invalid Markdown but shouldn't crash
    let content = "| A | B |\n|---|---|\n| 1 | 2 |\n| C | D |\n|---|---|\n| 3 | 4 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Adjacent tables should not cause crash");

    let fixed = result.unwrap();
    // Content should be preserved in some form
    assert!(
        fixed.contains('1') && fixed.contains('2'),
        "First table content should be preserved"
    );
    assert!(
        fixed.contains('3') && fixed.contains('4'),
        "Second table content should be preserved"
    );
}

#[test]
fn test_md060_maximum_column_count_stress() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test with 100 columns to check performance and memory handling
    let columns = 100;
    let header_row = format!(
        "| {} |",
        (0..columns).map(|i| format!("C{i}")).collect::<Vec<_>>().join(" | ")
    );
    let delimiter_row = format!("| {} |", vec!["---"; columns].join(" | "));
    let content_row = format!(
        "| {} |",
        (0..columns).map(|i| i.to_string()).collect::<Vec<_>>().join(" | ")
    );

    let content = format!("{header_row}\n{delimiter_row}\n{content_row}");
    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);

    // This should complete in reasonable time and not crash
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Should handle 100 columns without crashing");

    let fixed = result.unwrap();
    // Verify some columns are present
    assert!(fixed.contains("C0"), "First column should be present");
    assert!(fixed.contains("C99"), "Last column should be present");
}

#[test]
fn test_md060_fix_idempotency() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test that fix(fix(x)) == fix(x)
    let content = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | NYC |\n| Bob | 25 | LA |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed_once = rule.fix(&ctx).unwrap();

    // Apply fix again on the already-fixed content
    let ctx2 = LintContext::new(&fixed_once, MarkdownFlavor::Standard, None);
    let fixed_twice = rule.fix(&ctx2).unwrap();

    assert_eq!(
        fixed_once, fixed_twice,
        "Applying fix twice should produce the same result as applying it once (idempotency)"
    );

    // Verify no warnings on already-formatted table
    let warnings = rule.check(&ctx2).unwrap();
    assert_eq!(warnings.len(), 0, "Already-formatted table should produce no warnings");
}

// ============================================================================
// ADDITIONAL CRITICAL/HIGH PRIORITY EDGE CASES
// ============================================================================

// STRUCTURE EDGE CASES

#[test]
fn test_md060_completely_empty_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table with all empty cells
    let content = "| | | |\n|---|---|---|\n| | | |\n| | | |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Empty table should not crash");

    let fixed = result.unwrap();
    // All lines should have equal length
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4);
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
}

#[test]
fn test_md060_table_with_no_delimiter() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Invalid table: missing delimiter row
    let content = "| Name | Age |\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic - this won't be detected as a table by the parser
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Missing delimiter should not crash");
}

#[test]
fn test_md060_single_row_table_header_only() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table with just header and delimiter, no content
    let content = "| Column A | Column B | Column C |\n|---|---|---|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should format correctly even without content rows
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 2);
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should have equal length"
    );

    assert!(fixed.contains("Column A"));
    assert!(fixed.contains("Column B"));
    assert!(fixed.contains("Column C"));
}

#[test]
fn test_md060_varying_column_counts_per_row() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Each row has different number of columns (malformed table)
    let content = "| A | B | C | D |\n|---|---|\n| X |\n| Y | Z | W | V | U |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Varying column counts should not crash");
}

#[test]
fn test_md060_delimiter_with_no_dashes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Invalid delimiter row with only colons (edge case)
    let content = "| A | B |\n|:::|:::|\n| X | Y |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should handle gracefully (likely won't be detected as valid table)
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Invalid delimiter should not crash");
}

// UNICODE COMPLEXITY EDGE CASES

#[test]
fn test_md060_bidirectional_text_mixed_ltr_rtl() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Mix of LTR (English) and RTL (Arabic) in same table
    let content = "| English | العربية |\n|---|---|\n| Hello | مرحبا |\n| World | عالم |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Content should be preserved
    assert!(fixed.contains("English"));
    assert!(fixed.contains("العربية"));
    assert!(fixed.contains("Hello"));
    assert!(fixed.contains("مرحبا"));

    // All lines should have equal display width
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].width(), lines[1].width());
    assert_eq!(lines[1].width(), lines[2].width());
    assert_eq!(lines[2].width(), lines[3].width());
}

#[test]
fn test_md060_unicode_variation_selectors() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Variation selectors change glyph appearance (text vs emoji style)
    // U+FE0E = text style, U+FE0F = emoji style
    let content = "| Char | Style |\n|---|---|\n| ☺︎ | Text |\n| ☺️ | Emoji |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Content should be preserved
    assert!(fixed.contains("Text"));
    assert!(fixed.contains("Emoji"));

    // Should handle variation selectors without crashing
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4);
}

#[test]
fn test_md060_unicode_control_characters() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test with various control characters that might cause issues
    // U+0000 = NULL, U+0001 = SOH, U+001F = Unit Separator
    let content = "| Name | Value |\n|---|---|\n| Test\u{0001} | Data |\n| Item | Info\u{001F} |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Control characters should not crash formatting");
}

#[test]
fn test_md060_unicode_normalization_issues() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Same visual character in different normalization forms (NFD vs NFC)
    // é can be: U+00E9 (precomposed) or U+0065 U+0301 (e + combining acute)
    let content = "| NFC | NFD |\n|---|---|\n| café | cafe\u{0301} |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Both forms should be preserved
    assert!(fixed.contains("café"));

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3);
}

#[test]
fn test_md060_mixed_emoji_types() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Mix basic emoji, emoji with modifiers, and multi-codepoint emoji
    let content = "| Type | Example |\n|---|---|\n| Basic | 😀 |\n| Gender | 👨 |\n| Number | #️⃣ |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // All emoji should be preserved
    assert!(fixed.contains("😀"));
    assert!(fixed.contains("👨"));

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 5);
}

// PERFORMANCE AND STRESS TESTS

#[test]
fn test_md060_extremely_wide_single_cell() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Single cell with 10000 characters
    let long_text = "A".repeat(10000);
    let content = format!("| Short | Long |\n|---|---|\n| X | {long_text} |");
    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);

    // Should complete without timeout or excessive memory
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Extremely wide cell should not crash");

    let fixed = result.unwrap();
    assert!(fixed.contains(&long_text), "Long text should be preserved");
}

#[test]
fn test_md060_many_rows_stress() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table with 1000 rows
    let mut lines = vec!["| ID | Name | Value |".to_string(), "|---|---|---|".to_string()];
    for i in 0..1000 {
        lines.push(format!("| {i} | Row{i} | Data{i} |"));
    }
    let content = lines.join("\n");
    let ctx = LintContext::new(&content, MarkdownFlavor::Standard, None);

    // Should complete in reasonable time
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "1000 rows should not crash");

    let fixed = result.unwrap();
    assert!(fixed.contains("Row0"));
    assert!(fixed.contains("Row999"));
}

#[test]
fn test_md060_deeply_nested_inline_code() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Per GFM spec, inline code does NOT protect pipes from being cell delimiters.
    // To have literal pipes in table cells, use backslash-escaped pipes (\|).
    // This test verifies escaped pipes inside inline code are preserved during formatting.
    let content = "| Code | Description |\n|---|---|\n| `a\\|b` | Simple |\n| `x\\|y\\|z` | Multiple |\n| `{a\\|b}\\|{c\\|d}` | Complex |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Escaped pipes inside inline code should be preserved
    assert!(fixed.contains("`a\\|b`"));
    assert!(fixed.contains("`x\\|y\\|z`"));
    assert!(fixed.contains("`{a\\|b}\\|{c\\|d}`"));

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

// MIXED CONTENT EDGE CASES

#[test]
fn test_md060_table_with_links() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Link |\n|---|---|\n| GitHub | [Link](https://github.com) |\n| Google | [Search](https://google.com) |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Links should be preserved
    assert!(fixed.contains("[Link](https://github.com)"));
    assert!(fixed.contains("[Search](https://google.com)"));

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
}

#[test]
fn test_md060_table_with_html_entities() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Symbol | HTML |\n|---|---|\n| Less than | &lt; |\n| Greater | &gt; |\n| Ampersand | &amp; |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // HTML entities should be preserved
    assert!(fixed.contains("&lt;"));
    assert!(fixed.contains("&gt;"));
    assert!(fixed.contains("&amp;"));
}

#[test]
fn test_md060_table_with_bold_and_italic() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content =
        "| Text | Style |\n|---|---|\n| **Bold** | Strong |\n| *Italic* | Emphasis |\n| ***Both*** | Combined |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Markdown formatting should be preserved
    assert!(fixed.contains("**Bold**"));
    assert!(fixed.contains("*Italic*"));
    assert!(fixed.contains("***Both***"));
}

#[test]
fn test_md060_table_with_strikethrough() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Status | Item |\n|---|---|\n| Done | ~~Old~~ |\n| Active | Current |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Strikethrough should be preserved
    assert!(fixed.contains("~~Old~~"));
}

// WHITESPACE EDGE CASES

#[test]
fn test_md060_cells_with_leading_trailing_spaces() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Cells with intentional spaces (though they'll be trimmed in output)
    let content = "| Name | Value |\n|---|---|\n|   Spaced   |   Data   |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Content should be trimmed and padded correctly
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_cells_with_tabs() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Value |\n|---|---|\n| Tab\there | Data |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Tabs should be preserved in cell content
    assert!(fixed.contains("Tab\there"));
}

#[test]
fn test_md060_cells_with_newline_escape() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Cells with literal \n (not actual newlines)
    let content = "| Pattern | Example |\n|---|---|\n| Newline | Line\\nBreak |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Escaped newline should be preserved
    assert!(fixed.contains("Line\\nBreak"));
}

// DELIMITER ROW VARIATIONS

#[test]
fn test_md060_delimiter_with_many_dashes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Delimiter rows with varying dash counts
    let content = "| A | B | C |\n|----------|---|---------------------------|\n| X | Y | Z |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should normalize to consistent delimiter format
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_all_alignment_combinations() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Test all possible alignment combinations in one table
    let content =
        "| Default | Left | Right | Center |\n|---|:---|---:|:---:|\n| A | B | C | D |\n| AA | BB | CC | DD |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();

    // Verify all alignment indicators are present (checking delimiter row specifically)
    let delimiter_row = lines[1];
    assert!(
        delimiter_row.contains("---") || delimiter_row.contains("----"),
        "Default alignment should have dashes"
    );
    assert!(
        delimiter_row.contains(":---") || delimiter_row.contains(":----"),
        "Left alignment should have colon-dashes"
    );
    assert!(
        delimiter_row.contains("---:") || delimiter_row.contains("----:"),
        "Right alignment should have dashes-colon"
    );
    // Center alignment can have various dash counts between colons
    assert!(
        delimiter_row.chars().filter(|&c| c == ':').count() >= 4,
        "Should have at least 4 colons (2 for center, 1 for left, 1 for right)"
    );

    // All lines should have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
}

// EDGE CASE COMBINATIONS

#[test]
fn test_md060_unicode_in_aligned_columns() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Different Unicode widths with alignment indicators
    let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | 中 | 1 |\n| AAA | 中中中 | 111 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();

    // All lines should have equal display width
    assert_eq!(lines[0].width(), lines[1].width());
    assert_eq!(lines[1].width(), lines[2].width());
    assert_eq!(lines[2].width(), lines[3].width());

    // Chinese characters should be preserved
    assert!(fixed.contains(""));
    assert!(fixed.contains("中中中"));
}

#[test]
fn test_md060_empty_and_whitespace_only_cells_mixed() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| A | B | C |\n|---|---|---|\n|  |   | X |\n| Y |  |  |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should handle empty cells correctly
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());

    assert!(fixed.contains('X'));
    assert!(fixed.contains('Y'));
}

// ISSUE #164: Already-aligned tables with short separators should not be reformatted

#[test]
fn test_md060_issue_164_already_aligned_short_separators() {
    // This is the exact example from issue #164
    // Tables with 3-character separators that are already aligned should pass
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| a   |  b  |   c |\n| :-- | :-: | --: |\n| 1   |  2  |   3 |\n| 10  | 20  |  30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should produce NO warnings - table is already aligned
    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(
        warnings.len(),
        0,
        "Already-aligned table with short (3-char) separators should not produce warnings"
    );

    // Should NOT modify the content - preserve as-is
    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(
        fixed, content,
        "Already-aligned table should be preserved exactly as-is"
    );

    // Verify all rows have consistent length
    let lines: Vec<&str> = fixed.lines().collect();
    let first_len = lines[0].len();
    assert!(
        lines.iter().all(|line| line.len() == first_len),
        "All rows should maintain consistent length"
    );

    // Verify short separators are preserved (not expanded to 4+ chars)
    assert!(
        fixed.contains("| :-- | :-: | --: |"),
        "Short separator format should be preserved"
    );
}

#[test]
fn test_md060_issue_164_misaligned_short_separators_detected() {
    // Contrast case: tables with short separators but NOT aligned should be detected
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Misaligned table - inconsistent column widths
    let content = "| a |  b  | c |\n| :-- | :-: | --: |\n| 1 |  2  |   3 |\n| 10 | 20 |  30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should produce warnings - table is NOT aligned
    let warnings = rule.check(&ctx).unwrap();
    assert!(
        !warnings.is_empty(),
        "Misaligned table should produce warnings even with short separators"
    );
}

// ============================================================================
// MKDOCS FLAVOR TESTS (Issue #165)
//
// In MkDocs/Python-Markdown, pipes inside inline code are NOT cell delimiters.
// This differs from GFM where pipes inside backticks ARE cell delimiters.
// ============================================================================

#[test]
fn test_md060_mkdocs_flavor_pipes_in_code_spans_issue_165() {
    // Issue #165: Tables with pipes inside inline code should work correctly
    // with MkDocs flavor. The pipe in `x | y` should NOT be treated as a
    // cell delimiter.
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // This is the exact example from issue #165
    let content = "| Type | Example |\n| - | - |\n| Union | `x | y` |\n| Dict | `dict` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    // Should recognize this as a 2-column table and format it correctly
    let fixed = rule.fix(&ctx).unwrap();

    // The inline code `x | y` should be preserved as a single cell
    assert!(
        fixed.contains("`x | y`"),
        "Inline code with pipe should be preserved as single cell content, got: {fixed}"
    );

    // Should be properly aligned with 2 columns, not corrupted into 3+
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4, "Should have 4 lines");

    // All lines should have equal length when aligned
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should match: '{}' vs '{}'",
        lines[0],
        lines[1]
    );
    assert_eq!(
        lines[1].len(),
        lines[2].len(),
        "Delimiter and content should match: '{}' vs '{}'",
        lines[1],
        lines[2]
    );
    assert_eq!(
        lines[2].len(),
        lines[3].len(),
        "Content rows should match: '{}' vs '{}'",
        lines[2],
        lines[3]
    );
}

#[test]
fn test_md060_mkdocs_flavor_various_code_spans_with_pipes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Multiple rows with pipes in inline code
    let content =
        "| Type | Syntax |\n| - | - |\n| Union | `A | B` |\n| Optional | `T | None` |\n| Multiple | `a | b | c` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let fixed = rule.fix(&ctx).unwrap();

    // All inline code content should be preserved
    assert!(fixed.contains("`A | B`"), "Union type should be preserved");
    assert!(fixed.contains("`T | None`"), "Optional type should be preserved");
    assert!(fixed.contains("`a | b | c`"), "Multiple pipes should be preserved");

    // Should have 5 lines total
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 5, "Should have 5 lines");

    // All lines should have equal length
    for i in 0..lines.len() - 1 {
        assert_eq!(
            lines[i].len(),
            lines[i + 1].len(),
            "Lines {} and {} should have same length",
            i,
            i + 1
        );
    }
}

#[test]
fn test_md060_mkdocs_flavor_no_false_positives() {
    // With MkDocs flavor, tables with pipes in inline code should be parsed correctly
    // as 2 columns, not 3 columns. The pipe in `x | y` is NOT a cell delimiter.
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Use a table that would be already aligned if parsed correctly as 2 columns
    let content = "| Type  | Example  |\n| ----- | -------- |\n| Union | `x | y`  |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    // Check should produce no warnings because table is aligned with consistent columns
    let warnings = rule.check(&ctx).unwrap();

    // Should have no warnings for a well-formatted 2-column table
    assert!(
        warnings.is_empty(),
        "Should have no warnings for aligned 2-column table with MkDocs flavor, got: {:?}",
        warnings.iter().map(|w| &w.message).collect::<Vec<_>>()
    );
}

#[test]
fn test_md060_mkdocs_flavor_fix_preserves_inline_code_pipes() {
    // With MkDocs flavor, fixing a table should preserve pipes inside inline code
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Type | Example |\n|-|-|\n| Union | `x | y` |\n| Dict | `dict` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let fixed = rule.fix(&ctx).unwrap();

    // The inline code content must be preserved intact (not split into separate cells)
    assert!(
        fixed.contains("`x | y`"),
        "Inline code content should be preserved intact, got: {fixed}"
    );

    // Verify the table structure: Each data row should have 2 content columns
    // If the pipe in `x | y` was wrongly treated as a delimiter, we'd see corrupted rows
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4, "Table should have 4 lines");

    // The Union row should contain the intact inline code
    let union_row = lines[2];
    assert!(
        union_row.contains("`x | y`"),
        "Union row should contain intact inline code, got: {union_row}"
    );
}

#[test]
fn test_md060_mkdocs_flavor_compact_style() {
    let rule = MD060TableFormat::new(true, "compact".to_string());

    let content = "| Type | Example |\n|-|-|\n| Union | `x | y` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should format to compact style while preserving inline code
    assert!(
        fixed.contains("`x | y`"),
        "Inline code should be preserved in compact mode"
    );

    // Should have compact formatting (single spaces)
    assert!(fixed.contains("| Type | Example |") || fixed.contains("| Type | Example |"));
}

#[test]
fn test_md060_mkdocs_flavor_tight_style() {
    let rule = MD060TableFormat::new(true, "tight".to_string());

    let content = "| Type | Example |\n|-|-|\n| Union | `x | y` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should format to tight style while preserving inline code
    assert!(
        fixed.contains("`x | y`"),
        "Inline code should be preserved in tight mode"
    );

    // Should have tight formatting (no spaces)
    assert!(fixed.contains("|Type|"), "Should have tight formatting");
}

#[test]
fn test_md060_standard_flavor_pipes_in_code_are_delimiters() {
    // Verify that Standard/GFM flavor still treats pipes in code as delimiters
    // (this is the correct GFM behavior)
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Type | Example |\n|-|-|\n| Union | `x | y` |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // In GFM, `x | y` is split into `x and y` as separate cells
    // So the inline code is NOT preserved as a unit
    // The table will be treated as having 3 columns
    let _lines: Vec<&str> = fixed.lines().collect();

    // The behavior here depends on how the rule handles mismatched columns
    // but it should NOT preserve `x | y` as a single cell
    // (unless escaped as `x \| y`)
}

#[test]
fn test_md060_mkdocs_flavor_escaped_and_inline_code_pipes() {
    // Test combination of escaped pipes and pipes in inline code
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Type | Example |\n|-|-|\n| Escaped | a \\| b |\n| Code | `x | y` |";
    let ctx = LintContext::new(content, MarkdownFlavor::MkDocs, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Both should be preserved correctly
    assert!(fixed.contains("a \\| b"), "Escaped pipe should be preserved");
    assert!(fixed.contains("`x | y`"), "Inline code pipe should be preserved");

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4, "Should have 4 lines");
}

// ============================================================================
// LOOSE LAST COLUMN FEATURE TESTS (#356)
// ============================================================================

/// Helper to create MD013Config with default values
fn default_md013_config() -> MD013Config {
    MD013Config::default()
}

#[test]
fn test_md060_loose_last_column_basic() {
    // Test that loose-last-column caps last column width at header text width
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // Input: header "Description" is 11 chars, body has "Short" (5 chars) and long text (26 chars)
    // Last column width is capped at header width (11)
    // Body "Short" → padded to 11 → same length as header
    // Body "A much longer description" → extends beyond header (26 > 11)
    let content = "| Name | Description |\n|---|---|\n| Foo | Short |\n| Bar | A much longer description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header and delimiter should still be aligned
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should be same length"
    );

    // Body row with "Short" should be padded to header width → same length as header
    assert_eq!(
        lines[2].len(),
        lines[0].len(),
        "Body row with short content should be padded to header width"
    );

    // Body row with long content should extend beyond header
    assert!(
        lines[3].len() > lines[0].len(),
        "Body row with long content ({} chars) should extend beyond header ({} chars)",
        lines[3].len(),
        lines[0].len()
    );
}

#[test]
fn test_md060_loose_last_column_disabled_by_default() {
    // Test that loose-last-column is disabled by default
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name | Description |\n|---|---|\n| Foo | Short |\n| Bar | Longer text |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // All rows should have equal length (default behavior)
    assert_eq!(lines[0].len(), lines[1].len(), "Header and delimiter should match");
    assert_eq!(
        lines[1].len(),
        lines[2].len(),
        "Delimiter and first body row should match"
    );
    assert_eq!(lines[2].len(), lines[3].len(), "Body rows should match");
}

#[test]
fn test_md060_loose_last_column_header_delimiter_still_aligned() {
    // Test that header and delimiter remain aligned even with loose-last-column
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| ID | Name | Description |\n|---|---|---|\n| 1 | A | X |\n| 2 | B | Y |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header and delimiter MUST still be aligned
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should be same length even with loose-last-column"
    );
}

#[test]
fn test_md060_loose_last_column_multiple_columns() {
    // Test loose-last-column with multiple columns
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | Short |\n| 1 | 2 | 3 | Longer text here |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Verify table structure: should have 4 lines
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 4, "Should have 4 lines");

    // Non-last columns should be present in all rows
    assert!(fixed.contains("| A "), "Header A should be in output");
    assert!(fixed.contains("| B "), "Header B should be in output");
    assert!(fixed.contains("| C "), "Header C should be in output");
    assert!(fixed.contains("| D "), "Header D should be in output");

    // Body content should be preserved
    assert!(fixed.contains("Short"), "Short text should be in output");
    assert!(fixed.contains("Longer text here"), "Long text should be in output");
}

#[test]
fn test_md060_loose_last_column_single_column_table() {
    // Edge case: Single column table with loose-last-column
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Description |\n|---|\n| Short |\n| A much longer description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    // Should not panic
    let result = rule.fix(&ctx);
    assert!(result.is_ok(), "Single column with loose-last-column should not crash");

    let fixed = result.unwrap();
    assert!(fixed.contains("Short"), "Short text should be preserved");
    assert!(
        fixed.contains("A much longer description"),
        "Long text should be preserved"
    );
}

// ============================================================================
// COLUMN ALIGN HEADER/BODY FEATURE TESTS (#348)
// ============================================================================

#[test]
fn test_md060_column_align_header_basic() {
    // Test column-align-header overrides global column-align for header only
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Left,                // Body will be left-aligned
        column_align_header: Some(ColumnAlign::Center), // Header is centered
        column_align_body: None,
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // Use content where "A" needs centering in a wider column
    let content = "| A | B |\n|---|---|\n| Long | Text |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    assert_eq!(lines.len(), 3, "Should have 3 lines");

    // Header "A" should be centered in a column wide enough for "Long"
    // Centering means space on left AND right: "| A    |" becomes "|  A   |" (or similar)
    let header = lines[0];
    let body = lines[2];

    // Find the first cell content position
    // In centered header, "A" should have space before it (after the pipe)
    // In left-aligned body, "Long" should be right after the pipe with space after
    assert!(
        header.contains("|  ") || header.contains("| A "),
        "Header should show centering pattern, got: {header}"
    );
    assert!(
        body.starts_with("| Long"),
        "Body should be left-aligned (content right after pipe), got: {body}"
    );
}

#[test]
fn test_md060_column_align_body_basic() {
    // Test column-align-body overrides global column-align for body rows only
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Left, // Header will be left-aligned
        column_align_header: None,
        column_align_body: Some(ColumnAlign::Right), // Body is right-aligned
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // Use content where body "A" needs right-aligning in a wider column
    let content = "| Long | Text |\n|---|---|\n| A | B |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    assert_eq!(lines.len(), 3, "Should have 3 lines");

    let header = lines[0];
    let body = lines[2];

    // Header "Long" should be left-aligned (right after pipe)
    assert!(
        header.starts_with("| Long"),
        "Header should be left-aligned, got: {header}"
    );

    // Body "A" should be right-aligned (space before content, content before pipe)
    // Right-alignment means: "|    A |" pattern (spaces, then content, then space, then pipe)
    assert!(
        body.contains("  A |") || body.contains(" A |"),
        "Body should be right-aligned with padding before 'A', got: {body}"
    );
}

#[test]
fn test_md060_column_align_header_and_body_different() {
    // Test different alignments for header and body
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,                // Fall back to auto
        column_align_header: Some(ColumnAlign::Center), // Header centered
        column_align_body: Some(ColumnAlign::Left),     // Body left-aligned
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| ColumnA | ColumnB |\n|---|---|\n| X | Y |\n| XX | YY |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    assert_eq!(lines.len(), 4, "Should have 4 lines");

    // Header (line 0) should be centered
    // Body (lines 2, 3) should be left-aligned
    // All lines should still have equal length
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
    assert_eq!(lines[2].len(), lines[3].len());
}

#[test]
fn test_md060_column_align_header_only_set() {
    // Test when only column-align-header is set (body falls back to column-align)
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Right,             // Body and default
        column_align_header: Some(ColumnAlign::Left), // Header left
        column_align_body: None,                      // Body uses column_align (Right)
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| A | B |\n|---|---|\n| X | Y |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Verify the table is properly formatted
    assert_eq!(lines.len(), 3);
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_column_align_body_only_set() {
    // Test when only column-align-body is set (header falls back to column-align)
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Left,              // Header and default
        column_align_header: None,                    // Header uses column_align (Left)
        column_align_body: Some(ColumnAlign::Center), // Body centered
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Value |\n|---|---|\n| Key | 42 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    assert_eq!(lines.len(), 3);
    assert_eq!(lines[0].len(), lines[1].len());
    assert_eq!(lines[1].len(), lines[2].len());
}

#[test]
fn test_md060_column_align_auto_with_header_body_override() {
    // Test that Auto alignment respects delimiter markers while header/body overrides work
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,                // Use delimiter markers
        column_align_header: Some(ColumnAlign::Center), // Override header to center
        column_align_body: None,                        // Body uses Auto (delimiter markers)
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // Delimiter says: left, center, right
    let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Delimiter markers should be preserved
    assert!(fixed.contains(":---"), "Left alignment marker should be preserved");
    assert!(fixed.contains("---:"), "Right alignment marker should be preserved");

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines.len(), 3);
}

#[test]
fn test_md060_column_align_all_combinations() {
    // Test all combinations of ColumnAlign values
    for header_align in [
        Some(ColumnAlign::Left),
        Some(ColumnAlign::Center),
        Some(ColumnAlign::Right),
        None,
    ] {
        for body_align in [
            Some(ColumnAlign::Left),
            Some(ColumnAlign::Center),
            Some(ColumnAlign::Right),
            None,
        ] {
            let config = MD060Config {
                enabled: true,
                style: "aligned".to_string(),
                max_width: LineLength::from_const(0),
                column_align: ColumnAlign::Auto,
                column_align_header: header_align,
                column_align_body: body_align,
                loose_last_column: false,
                aligned_delimiter: false,
            };
            let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

            let content = "| A | B |\n|---|---|\n| X | Y |";
            let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

            // Should not panic for any combination
            let result = rule.fix(&ctx);
            assert!(
                result.is_ok(),
                "Should not panic for header={header_align:?}, body={body_align:?}"
            );
        }
    }
}

// ============================================================================
// COMBINED FEATURES TESTS
// ============================================================================

#[test]
fn test_md060_loose_last_column_with_header_body_alignment() {
    // Test both features together
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: Some(ColumnAlign::Center),
        column_align_body: Some(ColumnAlign::Left),
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Description |\n|---|---|\n| A | Short |\n| B | A very long description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header and delimiter should still be aligned
    assert_eq!(lines[0].len(), lines[1].len(), "Header and delimiter should match");

    // Content should be preserved
    assert!(fixed.contains("Short"), "Short text preserved");
    assert!(fixed.contains("A very long description"), "Long text preserved");
}

#[test]
fn test_md060_features_idempotency() {
    // Test that applying fix twice with new features produces same result
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: Some(ColumnAlign::Center),
        column_align_body: Some(ColumnAlign::Left),
        loose_last_column: false, // Keep strict for idempotency test
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config.clone(), default_md013_config(), false);

    let content = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | NYC |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed_once = rule.fix(&ctx).unwrap();

    let ctx2 = LintContext::new(&fixed_once, MarkdownFlavor::Standard, None);
    let rule2 = MD060TableFormat::from_config_struct(config, default_md013_config(), false);
    let fixed_twice = rule2.fix(&ctx2).unwrap();

    assert_eq!(fixed_once, fixed_twice, "Applying fix twice should produce same result");
}

// ============================================================================
// EXPERT-LEVEL TESTS WITH EXACT OUTPUT ASSERTIONS
// ============================================================================

#[test]
fn test_md060_loose_last_column_exact_output() {
    // Verify exact output for loose-last-column feature
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| A | B |\n|---|---|\n| X | Short |\n| Y | Much longer text |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Column widths: A=3 (GFM min), B=header "B" (1) → capped at 1 → GFM min 3
    // Body cells wider than 3 extend beyond the header width (saturating_sub = 0)
    // Header: "| A   | B   |" (both padded to GFM min 3)
    // Body1:  "| X   | Short |" (B: 5 > 3, no padding)
    // Body2:  "| Y   | Much longer text |" (B: 16 > 3, no padding)
    let expected = "| A   | B   |\n| --- | --- |\n| X   | Short |\n| Y   | Much longer text |";
    assert_eq!(
        fixed, expected,
        "Loose last column should cap last column width at header text width"
    );
}

#[test]
fn test_md060_loose_last_column_empty_cell() {
    // Edge case: empty cell in last column with loose-last-column
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| A | Description |\n|---|---|\n| X |  |\n| Y | Has content |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Empty cell should be padded to header width → same length as header
    assert_eq!(
        lines[2].len(),
        lines[0].len(),
        "Row with empty last cell should be padded to header width"
    );

    // "Has content" (11 chars) matches "Description" (11 chars) → same length
    assert_eq!(
        lines[3].len(),
        lines[0].len(),
        "Row with content matching header width should equal header length"
    );
}

#[test]
fn test_md060_loose_last_column_preserves_alignment_markers() {
    // Verify alignment markers in delimiter are preserved with loose-last-column
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Left | Right |\n|:---|---:|\n| A | B |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Alignment markers should be preserved
    assert!(fixed.contains(":---"), "Left alignment marker should be preserved");
    assert!(
        fixed.contains("---:") || fixed.contains("-:"),
        "Right alignment marker should be preserved"
    );
}

#[test]
fn test_md060_column_align_header_center_exact() {
    // Verify exact centering behavior for header
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Left,
        column_align_header: Some(ColumnAlign::Center),
        column_align_body: None, // Uses column_align (Left)
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // "A" (1 char) needs to be centered in column wide enough for "Long" (4 chars)
    let content = "| A |\n|---|\n| Long |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header "A" should be centered: spaces on both sides
    // For 4-char column width, "A" centered = " A  " or "  A " (depending on even/odd handling)
    let header = lines[0];
    let a_pos = header.find('A').expect("A should be in header");
    let pipe_after_a = header[a_pos..].find('|').expect("Pipe should follow A");

    // Check there's space before A (after first pipe)
    let first_pipe = header.find('|').unwrap();
    let chars_before_a = a_pos - first_pipe - 1;
    let chars_after_a = pipe_after_a - 1;

    assert!(
        chars_before_a > 0,
        "Centered header should have space before 'A', got {chars_before_a} chars before"
    );
    assert!(
        chars_after_a > 0,
        "Centered header should have space after 'A', got {chars_after_a} chars after"
    );

    // Body should be left-aligned: "Long" right after pipe
    let body = lines[2];
    assert!(
        body.contains("| Long"),
        "Body should be left-aligned with 'Long' right after pipe, got: {body}"
    );
}

#[test]
fn test_md060_column_align_body_right_exact() {
    // Verify exact right-alignment behavior for body
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Left,
        column_align_header: None, // Uses column_align (Left)
        column_align_body: Some(ColumnAlign::Right),
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // "X" (1 char) needs to be right-aligned in column wide enough for "Long" (4 chars)
    let content = "| Long |\n|---|\n| X |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header should be left-aligned
    let header = lines[0];
    assert!(
        header.contains("| Long"),
        "Header should be left-aligned, got: {header}"
    );

    // Body "X" should be right-aligned: spaces before, then X, then space, then pipe
    let body = lines[2];
    // Right-aligned "X" in 4-char column = "   X" -> "|    X |"
    // Find X position relative to the cell boundaries
    let x_pos = body.find('X').expect("X should be in body");
    let first_pipe = body.find('|').unwrap();
    let chars_before_x = x_pos - first_pipe - 1;

    assert!(
        chars_before_x >= 3,
        "Right-aligned body should have multiple spaces before 'X', got {chars_before_x} chars before. Line: {body}"
    );
}

#[test]
fn test_md060_delimiter_unaffected_by_column_align() {
    // Verify delimiter row is NOT affected by column-align settings
    // Delimiter should always use dashes, not be "aligned" with spaces
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Center,
        column_align_header: Some(ColumnAlign::Right),
        column_align_body: Some(ColumnAlign::Left),
        loose_last_column: false,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| A | B |\n|---|---|\n| X | Y |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    let delimiter = lines[1];

    // Delimiter should contain only pipes, dashes, colons, and spaces
    // It should NOT have content alignment applied
    assert!(
        !delimiter.contains('A') && !delimiter.contains('B') && !delimiter.contains('X') && !delimiter.contains('Y'),
        "Delimiter should not contain cell content, got: {delimiter}"
    );

    // Delimiter should have dashes
    assert!(
        delimiter.contains("---"),
        "Delimiter should contain dashes, got: {delimiter}"
    );
}

#[test]
fn test_md060_loose_last_column_with_cjk() {
    // Edge case: CJK characters in last column with loose-last-column
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    // CJK chars are double-width
    let content = "| A | Name |\n|---|---|\n| X | 中文 |\n| Y | English |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();

    // Should not panic and should preserve content
    assert!(fixed.contains("中文"), "CJK content should be preserved");
    assert!(fixed.contains("English"), "ASCII content should be preserved");

    let lines: Vec<&str> = fixed.lines().collect();
    // With loose last column, body rows can differ in length
    // CJK row might be different length than English row due to display width differences
    assert_eq!(lines.len(), 4, "Should have 4 lines");
}

// --- Continuation table tests (tables on lines after the list marker) ---

#[test]
fn test_md060_unordered_list_continuation_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "- Test\n  | c1 | c2 |\n  |-|-|\n  | foo | bar |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    // The table must remain indented under the list item
    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "- Test", "List item text unchanged");
    assert!(
        lines[1].starts_with("  "),
        "Header line must preserve 2-space indentation, got: {:?}",
        lines[1]
    );
    assert!(
        lines[2].starts_with("  "),
        "Delimiter line must preserve 2-space indentation, got: {:?}",
        lines[2]
    );
    assert!(
        lines[3].starts_with("  "),
        "Data line must preserve 2-space indentation, got: {:?}",
        lines[3]
    );

    // Verify table content is still valid after fixing
    assert!(lines[1].contains("c1"));
    assert!(lines[1].contains("c2"));
    assert!(lines[3].contains("foo"));
    assert!(lines[3].contains("bar"));
}

#[test]
fn test_md060_ordered_list_continuation_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "1. Text\n   | h1 | h2 |\n   |---|---|\n   | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "1. Text");
    assert!(
        lines[1].starts_with("   "),
        "Header must have 3-space indent for ordered list, got: {:?}",
        lines[1]
    );
    assert!(
        lines[2].starts_with("   "),
        "Delimiter must have 3-space indent, got: {:?}",
        lines[2]
    );
    assert!(
        lines[3].starts_with("   "),
        "Data row must have 3-space indent, got: {:?}",
        lines[3]
    );
}

#[test]
fn test_md060_nested_list_continuation_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "- Outer\n  - Inner\n    | h1 | h2 |\n    |---|---|\n    | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "- Outer");
    assert_eq!(lines[1], "  - Inner");
    assert!(
        lines[2].starts_with("    "),
        "Nested table header must have 4-space indent, got: {:?}",
        lines[2]
    );
    assert!(
        lines[3].starts_with("    "),
        "Nested table delimiter must have 4-space indent, got: {:?}",
        lines[3]
    );
    assert!(
        lines[4].starts_with("    "),
        "Nested table data must have 4-space indent, got: {:?}",
        lines[4]
    );
}

#[test]
fn test_md060_non_list_indented_table_no_list_context() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Indented table that is NOT under a list item should not get list context
    let content = "Some text\n| h1 | h2 |\n|---|---|\n| d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "Some text");
    // Table should not be indented — no list context
    assert!(
        !lines[1].starts_with(' '),
        "Non-list table should not get indentation, got: {:?}",
        lines[1]
    );
}

#[test]
fn test_md060_same_line_list_table_no_regression() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Existing same-line list table should still work
    let content = "- | h1 | h2 |\n  |---|---|\n  | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    // Header line should start with "- "
    assert!(
        lines[0].starts_with("- "),
        "Same-line list table header must keep marker, got: {:?}",
        lines[0]
    );
    // Continuation lines should keep indentation
    assert!(
        lines[1].starts_with("  "),
        "Same-line list table delimiter must keep indent, got: {:?}",
        lines[1]
    );
    assert!(
        lines[2].starts_with("  "),
        "Same-line list table data must keep indent, got: {:?}",
        lines[2]
    );
}

#[test]
fn test_md060_continuation_table_idempotency() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "- Test\n  | c1 | c2 |\n  |-|-|\n  | foo | bar |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed1 = rule.fix(&ctx).unwrap();

    // Apply fix a second time — should produce identical output
    let ctx2 = LintContext::new(&fixed1, MarkdownFlavor::Standard, None);
    let fixed2 = rule.fix(&ctx2).unwrap();

    assert_eq!(
        fixed1, fixed2,
        "Fix must be idempotent:\n  first:  {fixed1:?}\n  second: {fixed2:?}",
    );
}

#[test]
fn test_md060_blank_line_between_text_and_continuation_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // A blank line between list text and table — the table is still inside the list item
    // per CommonMark (lazy continuation)
    let content = "- Text\n\n  | h1 | h2 |\n  |---|---|\n  | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    // Table lines should preserve indentation
    assert!(
        lines[2].starts_with("  "),
        "Table after blank line should keep indent, got: {:?}",
        lines[2]
    );
    assert!(
        lines[3].starts_with("  "),
        "Delimiter after blank line should keep indent, got: {:?}",
        lines[3]
    );
    assert!(
        lines[4].starts_with("  "),
        "Data after blank line should keep indent, got: {:?}",
        lines[4]
    );
}

#[test]
fn test_md060_nested_list_table_at_parent_level() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table belongs to the parent list item (indent=2), not the child (indent=4)
    let content = "- Parent\n  - Child\n\n  | h1 | h2 |\n  |---|---|\n  | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "- Parent");
    assert_eq!(lines[1], "  - Child");
    // Table at parent indent level (2 spaces) must be preserved
    assert!(
        lines[3].starts_with("  "),
        "Table at parent level must keep 2-space indent, got: {:?}",
        lines[3]
    );
    assert!(
        lines[4].starts_with("  "),
        "Delimiter at parent level must keep 2-space indent, got: {:?}",
        lines[4]
    );
    assert!(
        lines[5].starts_with("  "),
        "Data at parent level must keep 2-space indent, got: {:?}",
        lines[5]
    );
}

#[test]
fn test_md060_deeply_indented_not_code_block() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // 3 extra spaces beyond content indent (2) = 5 total. NOT a code block (need 4+ extra = 6+)
    let content = "- Item\n     | h1 | h2 |\n     |---|---|\n     | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    // Should still be treated as a list table, normalized to content indent (2 spaces)
    assert!(
        lines[1].starts_with("  "),
        "Table should be normalized to content indent, got: {:?}",
        lines[1]
    );
}

#[test]
fn test_md060_code_block_boundary_not_treated_as_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // 4 extra spaces beyond content indent (2) = 6 total → this is a code block, not a table
    let content = "- Item\n      | h1 | h2 |\n      |---|---|\n      | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    // The "table" is actually a code block — should NOT be reformatted as a list table
    // (It should remain as-is or be treated as a plain table without list context)
    let lines: Vec<&str> = fixed.lines().collect();
    // Should NOT have exactly 2-space indent (that would mean we incorrectly treated it as list table)
    // It should either remain at 6 spaces (code block, untouched) or be at 0 (plain table)
    let header_indent = lines[1].len() - lines[1].trim_start().len();
    assert_ne!(
        header_indent, 2,
        "Code-block-depth content should not get list table treatment, got indent: {header_indent}",
    );
}

#[test]
fn test_md060_mixed_ordered_unordered_nested_continuation() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Ordered parent (indent=3) with unordered child (indent=5)
    // Table at parent level (indent=3)
    let content = "1. Ordered\n   - Unordered\n\n   | h1 | h2 |\n   |---|---|\n   | d1 | d2 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    let lines: Vec<&str> = fixed.lines().collect();
    assert_eq!(lines[0], "1. Ordered");
    // Table at ordered list level must preserve 3-space indent
    assert!(
        lines[3].starts_with("   "),
        "Table at ordered list level must keep 3-space indent, got: {:?}",
        lines[3]
    );
}

#[test]
fn test_md060_atx_heading_with_pipe_not_misidentified_as_table() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // ATX headings containing pipes should not be reformatted as table rows
    let content = "#### heading|with pipe\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let warnings = rule.check(&ctx).unwrap();
    assert!(
        warnings.is_empty(),
        "ATX heading with pipe should not trigger MD060, got {warnings:?}"
    );

    // Fix should be idempotent (no changes)
    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(fixed, content, "ATX heading with pipe should not be modified");
}

#[test]
fn test_md060_atx_heading_with_pipe_idempotent() {
    // Reproduces the proptest failure: heading with unicode and pipe
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "#### ®aAA|ᯗ\n";
    let ctx1 = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed1 = rule.fix(&ctx1).unwrap();

    let ctx2 = LintContext::new(&fixed1, MarkdownFlavor::Standard, None);
    let fixed2 = rule.fix(&ctx2).unwrap();

    assert_eq!(fixed1, fixed2, "Fix must be idempotent for heading with unicode pipe");
}

#[test]
fn test_md060_heading_adjacent_to_table_not_absorbed() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // A heading with a pipe immediately before a real table should not be
    // absorbed into the table
    let content = "## Section|A\n\n| Col1 | Col2 |\n| ---- | ---- |\n| a    | b    |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    // The heading line must remain unchanged
    assert!(
        fixed.starts_with("## Section|A\n"),
        "Heading must not be reformatted, got: {fixed:?}"
    );
}

// Issue #426: Center-aligned delimiter with left-aligned content should trigger reformatting
#[test]
fn test_md060_center_aligned_delimiter_triggers_reformatting() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table where delimiter says center but content is left-aligned
    let content = "| Header  |\n|:-------:|\n| content |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let warnings = rule.check(&ctx).unwrap();

    // Should warn because content is not centered despite center-aligned delimiter
    assert!(
        !warnings.is_empty(),
        "Center-aligned delimiter with left-aligned content should trigger a warning"
    );

    let fixed = rule.fix(&ctx).unwrap();
    // After fix, content should be centered
    let lines: Vec<&str> = fixed.lines().collect();
    let content_line = lines[2];
    // The cell should have balanced padding (center-aligned)
    let trimmed = content_line.trim_start_matches('|');
    let cell = trimmed.split('|').next().unwrap();
    let left_spaces = cell.len() - cell.trim_start().len();
    let right_spaces = cell.len() - cell.trim_end().len();
    let diff = left_spaces.abs_diff(right_spaces);
    assert!(
        diff <= 1,
        "Center-aligned content should have balanced padding (diff={diff}): {fixed:?}"
    );
}

#[test]
fn test_md060_right_aligned_delimiter_triggers_reformatting() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table where delimiter says right but content is left-aligned
    let content = "| Header |\n| ------:|\n| data   |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let warnings = rule.check(&ctx).unwrap();

    assert!(
        !warnings.is_empty(),
        "Right-aligned delimiter with left-aligned content should trigger a warning"
    );

    let fixed = rule.fix(&ctx).unwrap();
    // After fix, content should be right-aligned
    let lines: Vec<&str> = fixed.lines().collect();
    let content_line = lines[2];
    let trimmed = content_line.trim_start_matches('|');
    let cell = trimmed.split('|').next().unwrap();
    let left_spaces = cell.len() - cell.trim_start().len();
    let right_spaces = cell.len() - cell.trim_end().len();
    assert!(
        left_spaces >= right_spaces,
        "Right-aligned content should have left_pad >= right_pad (left={left_spaces}, right={right_spaces}): {fixed:?}"
    );
}

#[test]
fn test_md060_already_centered_content_passes() {
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    // Table with centered content that matches center alignment
    let content = "| Header  |\n|:-------:|\n| content |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    // Run check on the fixed output - should have no warnings
    let ctx2 = LintContext::new(&fixed, MarkdownFlavor::Standard, None);
    let warnings = rule.check(&ctx2).unwrap();
    assert!(
        warnings.is_empty(),
        "Already-centered content should not trigger warnings. Fixed content:\n{fixed}\nWarnings: {warnings:?}"
    );
}

#[test]
fn test_md060_center_aligned_hyphen_content() {
    // The reported case from issue #426: content with hyphens in center-aligned column
    let rule = MD060TableFormat::new(true, "aligned".to_string());

    let content = "| Name   | Value |\n|:------:|:-----:|\n| alpha  | one   |\n| beta-2 | two   |\n";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let fixed = rule.fix(&ctx).unwrap();

    // Verify the fix is idempotent (re-fixing doesn't change anything)
    let ctx2 = LintContext::new(&fixed, MarkdownFlavor::Standard, None);
    let fixed2 = rule.fix(&ctx2).unwrap();
    assert_eq!(
        fixed, fixed2,
        "Center alignment fix should be idempotent.\nFirst fix:\n{fixed}\nSecond fix:\n{fixed2}"
    );
}

// ==================== FollowHeader mode tests ====================

#[test]
fn test_md060_loose_last_column_header_caps_width() {
    // Header/delimiter width should be based on header text only, not body cells
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Desc |\n|---|---|\n| A | Short |\n| B | A much longer description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header should use "Desc" width (4), not "A much longer description" width
    // So header should be shorter than the longest body row
    assert!(
        lines[0].len() < lines[3].len(),
        "Header ({} chars) should be shorter than body row with long content ({} chars) in follow-header mode",
        lines[0].len(),
        lines[3].len()
    );

    // Header and delimiter should have the same length
    assert_eq!(
        lines[0].len(),
        lines[1].len(),
        "Header and delimiter should have the same length"
    );
}

#[test]
fn test_md060_loose_last_column_body_shorter_than_header() {
    // When body cell is shorter than header, body is padded to header width
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Description |\n|---|---|\n| A | Hi |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header should contain "Description" at its natural width
    assert!(lines[0].contains("Description"), "Header should contain 'Description'");

    // Body row should be padded to header width → same length as header
    assert_eq!(
        lines[2].len(),
        lines[0].len(),
        "Body row with short content should be padded to header width"
    );
}

#[test]
fn test_md060_loose_last_column_three_columns_exact_output() {
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content =
        "| Name | Status | Desc |\n|---|---|---|\n| Foo | OK | Short |\n| Bar | Err | A much longer description here |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header and delimiter should match and use "Desc" (4 chars) for last column
    assert_eq!(lines[0], "| Name | Status | Desc |");
    assert_eq!(lines[1], "| ---- | ------ | ---- |");

    // Body rows should have unpadded last column
    assert_eq!(lines[2], "| Foo  | OK     | Short |");
    assert_eq!(lines[3], "| Bar  | Err    | A much longer description here |");
}

#[test]
fn test_md060_loose_last_column_idempotent() {
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Desc |\n|---|---|\n| A | Short |\n| B | A much longer description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let ctx2 = LintContext::new(&fixed, MarkdownFlavor::Standard, None);
    let fixed2 = rule.fix(&ctx2).unwrap();

    assert_eq!(
        fixed, fixed2,
        "Loose last column fix should be idempotent.\nFirst:\n{fixed}\nSecond:\n{fixed2}"
    );
}

#[test]
fn test_md060_loose_last_column_single_column_follow_header() {
    // Edge case: single column table
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Header |\n|---|\n| Short |\n| A very long body cell |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header width should be based on "Header" (6 chars), not "A very long body cell"
    assert_eq!(lines[0], "| Header |");
    assert_eq!(lines[1], "| ------ |");
}

#[test]
fn test_md060_loose_last_column_with_alignment_markers_follow() {
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Desc |\n|:---|---:|\n| A | Short |\n| B | Very long content |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Alignment markers should be preserved
    assert!(
        lines[1].contains(":---"),
        "Left alignment marker should be preserved in delimiter"
    );
    assert!(
        lines[1].contains("---:"),
        "Right alignment marker should be preserved in delimiter"
    );
}

#[test]
fn test_md060_loose_last_column_cjk_follow_header() {
    // CJK characters have display width 2
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Info |\n|---|---|\n| A | 日本語のテキスト |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Header should use "Info" width, not the wider CJK body content
    assert_eq!(lines[0], "| Name | Info |");
}

#[test]
fn test_md060_loose_last_column_aligned_no_space_style() {
    // Verify loose-last-column works with aligned-no-space delimiter style
    let config = MD060Config {
        enabled: true,
        style: "aligned-no-space".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content =
        "| Name | Status | Desc |\n|---|---|---|\n| Foo | OK | Short |\n| Bar | Err | A much longer description |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // aligned-no-space: delimiter has no spaces around dashes
    assert_eq!(lines[0], "| Name | Status | Desc |");
    assert_eq!(lines[1], "|------|--------|------|");
    assert_eq!(lines[2], "| Foo  | OK     | Short |");
    assert_eq!(lines[3], "| Bar  | Err    | A much longer description |");
}

#[test]
fn test_md060_loose_last_column_all_body_shorter_than_header() {
    // When ALL body cells are shorter than header, output matches loose=false
    let content = "| Name | Description |\n|---|---|\n| A | Hi |\n| B | Hey |";

    let config_loose = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let config_strict = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: false,
        aligned_delimiter: false,
    };

    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
    let rule_loose = MD060TableFormat::from_config_struct(config_loose, default_md013_config(), false);
    let rule_strict = MD060TableFormat::from_config_struct(config_strict, default_md013_config(), false);

    let fixed_loose = rule_loose.fix(&ctx).unwrap();
    let fixed_strict = rule_strict.fix(&ctx).unwrap();

    // When no body cell exceeds header width, loose is a no-op
    assert_eq!(
        fixed_loose, fixed_strict,
        "Loose should produce identical output to strict when no body cell exceeds header width.\nLoose:\n{fixed_loose}\nStrict:\n{fixed_strict}"
    );
}

#[test]
fn test_md060_loose_last_column_header_only_table() {
    // Table with header and delimiter but no body rows
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Description |\n|---|---|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    assert_eq!(lines.len(), 2);
    assert_eq!(lines[0], "| Name | Description |");
    assert_eq!(lines[1], "| ---- | ----------- |");
    assert_eq!(lines[0].len(), lines[1].len(), "Header and delimiter should match");
}

#[test]
fn test_md060_loose_last_column_empty_header_last_col() {
    // Edge case: empty header cell in last column, body has content
    let config = MD060Config {
        enabled: true,
        style: "aligned".to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: true,
        aligned_delimiter: false,
    };
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name |  |\n|---|---|\n| A | Some content |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let lines: Vec<&str> = fixed.lines().collect();

    // Empty header = 0 width → GFM min 3. Body "Some content" = 12 → extends beyond
    assert_eq!(lines[0].len(), lines[1].len(), "Header and delimiter should match");
    assert!(
        lines[2].len() > lines[0].len(),
        "Body row with content should extend beyond empty-header column"
    );
}

// ============================================================================
// ALIGNED DELIMITER OPTION TESTS (#589 — markdownlint compatibility)
// ============================================================================

fn md060_config_with_aligned_delimiter(style: &str, aligned_delimiter: bool) -> MD060Config {
    MD060Config {
        enabled: true,
        style: style.to_string(),
        max_width: LineLength::from_const(0),
        column_align: ColumnAlign::Auto,
        column_align_header: None,
        column_align_body: None,
        loose_last_column: false,
        aligned_delimiter,
    }
}

#[test]
fn test_md060_compact_aligned_delimiter_pads_dashes_to_header_width() {
    // From markdownlint MD060 docs: compact + aligned_delimiter pads delimiter
    // dashes to match header content widths, body rows stay compact.
    let config = md060_config_with_aligned_delimiter("compact", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Character | Meaning |\n| --- | --- |\n| Y | Yes |\n| N | No |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let expected = "| Character | Meaning |\n| --------- | ------- |\n| Y | Yes |\n| N | No |";
    assert_eq!(
        fixed, expected,
        "compact + aligned_delimiter pads delimiter dashes to header text widths and leaves body compact"
    );
}

#[test]
fn test_md060_compact_aligned_delimiter_default_false_unchanged() {
    // When aligned_delimiter is false (default), compact stays width-agnostic.
    let config = md060_config_with_aligned_delimiter("compact", false);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Character | Meaning |\n| --- | --- |\n| Y | Yes |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let expected = "| Character | Meaning |\n| --- | --- |\n| Y | Yes |";
    assert_eq!(fixed, expected, "compact without aligned_delimiter is unchanged");
}

#[test]
fn test_md060_tight_aligned_delimiter_pads_dashes_to_header_width() {
    let config = md060_config_with_aligned_delimiter("tight", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "|Character|Meaning|\n|-|-|\n|Y|Yes|\n|N|No|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    let expected = "|Character|Meaning|\n|---------|-------|\n|Y|Yes|\n|N|No|";
    assert_eq!(
        fixed, expected,
        "tight + aligned_delimiter pads delimiter dashes to header widths with no surrounding spaces"
    );
}

#[test]
fn test_md060_compact_aligned_delimiter_idempotent() {
    // A correctly-formatted compact + aligned_delimiter table must not be re-flagged or re-formatted.
    let config = md060_config_with_aligned_delimiter("compact", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Character | Meaning |\n| --------- | ------- |\n| Y | Yes |\n| N | No |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(
        warnings.len(),
        0,
        "Already-correct compact + aligned_delimiter table should produce no warnings"
    );

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(fixed, content, "Fix on already-correct table is a no-op");
}

#[test]
fn test_md060_tight_aligned_delimiter_idempotent() {
    let config = md060_config_with_aligned_delimiter("tight", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "|Character|Meaning|\n|---------|-------|\n|Y|Yes|\n|N|No|";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert_eq!(
        warnings.len(),
        0,
        "Already-correct tight + aligned_delimiter table should produce no warnings"
    );

    let fixed = rule.fix(&ctx).unwrap();
    assert_eq!(fixed, content, "Fix on already-correct table is a no-op");
}

#[test]
fn test_md060_compact_aligned_delimiter_preserves_alignment_markers() {
    // ":---", "---:", and ":---:" markers must be preserved when padding to header widths.
    let config = md060_config_with_aligned_delimiter("compact", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Character | Number | Meaning |\n| :- | -: | :-: |\n| Y | 1 | Yes |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed = rule.fix(&ctx).unwrap();
    // "Character" = 9 cols → ":--------" (1 colon + 8 dashes), "Number" = 6 cols → "-----:" (5 dashes + 1 colon),
    // "Meaning" = 7 cols → ":-----:" (colon + 5 dashes + colon).
    let expected = "| Character | Number | Meaning |\n| :-------- | -----: | :-----: |\n| Y | 1 | Yes |";
    assert_eq!(
        fixed, expected,
        "Alignment markers preserved when padding delimiter cells to header widths"
    );
}

#[test]
fn test_md060_compact_aligned_delimiter_flags_misaligned_delimiter() {
    // A delimiter row whose pipes don't match the header pipe positions should be flagged.
    let config = md060_config_with_aligned_delimiter("compact", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Character | Meaning |\n| --- | --- |\n| Y | Yes |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let warnings = rule.check(&ctx).unwrap();
    assert!(
        !warnings.is_empty(),
        "Misaligned delimiter row must produce at least one warning under aligned_delimiter"
    );
}

#[test]
fn test_md060_aligned_style_ignores_aligned_delimiter() {
    // The "aligned" style already enforces delimiter alignment; aligned_delimiter is a no-op.
    let config = md060_config_with_aligned_delimiter("aligned", true);
    let rule = MD060TableFormat::from_config_struct(config, default_md013_config(), false);

    let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
    let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

    let fixed_with = rule.fix(&ctx).unwrap();

    let config_off = md060_config_with_aligned_delimiter("aligned", false);
    let rule_off = MD060TableFormat::from_config_struct(config_off, default_md013_config(), false);
    let fixed_without = rule_off.fix(&ctx).unwrap();

    assert_eq!(
        fixed_with, fixed_without,
        "aligned style ignores aligned_delimiter (already implies it)"
    );
}