rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
use crate::lint_context::LintContext;
use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::utils::skip_context::is_table_line;

/// Rule MD076: Enforce consistent blank lines between list items
///
/// See [docs/md076.md](../../docs/md076.md) for full documentation and examples.
///
/// Enforces that the spacing between consecutive list items is consistent
/// within each list: either all gaps have a blank line (loose) or none do (tight).
///
/// ## Configuration
///
/// ```toml
/// [MD076]
/// style = "consistent"  # "loose", "tight", or "consistent" (default)
/// ```
///
/// - `"consistent"` — within each list, all gaps must use the same style (majority wins)
/// - `"loose"` — blank line required between every pair of items
/// - `"tight"` — no blank lines allowed between any items

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ListItemSpacingStyle {
    #[default]
    Consistent,
    Loose,
    Tight,
}

#[derive(Debug, Clone, Default)]
pub struct MD076Config {
    pub style: ListItemSpacingStyle,
    /// When true, blank lines around continuation paragraphs within a list item
    /// are permitted even in tight mode. This allows tight inter-item spacing
    /// while using blank lines to visually separate continuation content.
    pub allow_loose_continuation: bool,
}

#[derive(Debug, Clone, Default)]
pub struct MD076ListItemSpacing {
    config: MD076Config,
}

/// Classification of the spacing between two consecutive list items.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GapKind {
    /// No blank line between items.
    Tight,
    /// Blank line that is a genuine inter-item separator.
    Loose,
    /// Blank line required by another rule (MD031, MD058) after structural content.
    /// Excluded from consistency analysis — neither loose nor tight.
    Structural,
    /// Blank line after continuation content within a list item.
    /// Treated as `Structural` when `allow_loose_continuation` is enabled,
    /// or as `Loose` when disabled (default).
    ContinuationLoose,
}

/// Per-block analysis result shared by check() and fix().
struct BlockAnalysis {
    /// 1-indexed line numbers of items at this block's nesting level.
    items: Vec<usize>,
    /// Classification of each inter-item gap.
    gaps: Vec<GapKind>,
    /// Whether loose gaps are violations (should have blank lines removed).
    warn_loose_gaps: bool,
    /// Whether tight gaps are violations (should have blank lines inserted).
    warn_tight_gaps: bool,
}

impl MD076ListItemSpacing {
    pub fn new(style: ListItemSpacingStyle) -> Self {
        Self {
            config: MD076Config {
                style,
                allow_loose_continuation: false,
            },
        }
    }

    pub fn with_allow_loose_continuation(mut self, allow: bool) -> Self {
        self.config.allow_loose_continuation = allow;
        self
    }

    /// Check whether a line is effectively blank, accounting for blockquote markers.
    ///
    /// A line like `>` or `> ` is considered blank in blockquote context even though
    /// its raw content is non-empty.
    fn is_effectively_blank(ctx: &LintContext, line_num: usize) -> bool {
        if let Some(info) = ctx.line_info(line_num) {
            let content = info.content(ctx.content);
            if content.trim().is_empty() {
                return true;
            }
            // In a blockquote, a line containing only markers (e.g., ">", "> ") is blank
            if let Some(ref bq) = info.blockquote {
                return bq.content.trim().is_empty();
            }
            false
        } else {
            false
        }
    }

    /// Check whether a non-blank line is structural content (code block, table, HTML block,
    /// or blockquote) whose trailing blank line is required by other rules (MD031, MD058).
    fn is_structural_content(ctx: &LintContext, line_num: usize) -> bool {
        if let Some(info) = ctx.line_info(line_num) {
            // Inside a code block (includes the closing fence itself)
            if info.in_code_block {
                return true;
            }
            // Inside an HTML block
            if info.in_html_block {
                return true;
            }
            // Inside a blockquote
            if info.blockquote.is_some() {
                return true;
            }
            // A table row or separator
            let content = info.content(ctx.content);
            // Strip blockquote prefix and list continuation indent before checking table syntax
            let effective = if let Some(ref bq) = info.blockquote {
                bq.content.as_str()
            } else {
                content
            };
            if is_table_line(effective.trim_start()) {
                return true;
            }
        }
        false
    }

    /// Check whether a non-blank line is continuation content within a list item
    /// (indented prose that is not itself a list marker or structural content).
    ///
    /// `parent_content_col` is the content column of the parent list item marker
    /// (e.g., 2 for `- item`, 3 for `1. item`). Continuation must be indented
    /// to at least this column to belong to the parent item.
    fn is_continuation_content(ctx: &LintContext, line_num: usize, parent_content_col: usize) -> bool {
        let Some(info) = ctx.line_info(line_num) else {
            return false;
        };
        // Lines with a list marker are items, not continuation
        if info.list_item.is_some() {
            return false;
        }
        // Structural content is handled separately by is_structural_content
        if info.in_code_block
            || info.in_html_block
            || info.in_html_comment
            || info.in_front_matter
            || info.in_math_block
            || info.blockquote.is_some()
        {
            return false;
        }
        let content = info.content(ctx.content);
        if content.trim().is_empty() {
            return false;
        }
        // Continuation must be indented to at least the parent item's content column
        let indent = content.len() - content.trim_start().len();
        indent >= parent_content_col
    }

    /// Classify the inter-item gap between two consecutive items.
    ///
    /// Returns `Tight` if there is no blank line, `Loose` if there is a genuine
    /// inter-item separator blank, `Structural` if the only blank line is
    /// required by another rule (MD031/MD058) after structural content, or
    /// `ContinuationLoose` if the blank line follows continuation content
    /// within a list item.
    fn classify_gap(ctx: &LintContext, first: usize, next: usize) -> GapKind {
        if next <= first + 1 {
            return GapKind::Tight;
        }
        // The gap has a blank line only if the line immediately before the next item is blank.
        if !Self::is_effectively_blank(ctx, next - 1) {
            return GapKind::Tight;
        }
        // Walk backwards past blank lines to find the last non-blank content line.
        // If that line is structural content, the blank is required (not a separator).
        let mut scan = next - 1;
        while scan > first && Self::is_effectively_blank(ctx, scan) {
            scan -= 1;
        }
        // `scan` is now the last non-blank line before the next item
        if scan > first && Self::is_structural_content(ctx, scan) {
            return GapKind::Structural;
        }
        // Check if the last non-blank line is continuation content.
        // Use the first item's content column to verify proper indentation.
        let parent_content_col = ctx
            .line_info(first)
            .and_then(|li| li.list_item.as_ref())
            .map(|item| item.content_column)
            .unwrap_or(2);
        if scan > first && Self::is_continuation_content(ctx, scan, parent_content_col) {
            return GapKind::ContinuationLoose;
        }
        GapKind::Loose
    }

    /// Collect the 1-indexed line numbers of all inter-item blank lines in the gap.
    ///
    /// Walks backwards from the line before `next` collecting consecutive blank lines.
    /// These are the actual separator lines between items, not blank lines within
    /// multi-paragraph items. Structural blanks (after code blocks, tables, HTML blocks)
    /// are excluded.
    fn inter_item_blanks(ctx: &LintContext, first: usize, next: usize) -> Vec<usize> {
        let mut blanks = Vec::new();
        let mut line_num = next - 1;
        while line_num > first && Self::is_effectively_blank(ctx, line_num) {
            blanks.push(line_num);
            line_num -= 1;
        }
        // If the last non-blank line is structural content, these blanks are structural
        if line_num > first && Self::is_structural_content(ctx, line_num) {
            return Vec::new();
        }
        blanks.reverse();
        blanks
    }

    /// Analyze a single list block to determine which gaps need fixing.
    ///
    /// Returns `None` if the block has fewer than 2 items at its nesting level
    /// or if no gaps violate the configured style.
    fn analyze_block(
        ctx: &LintContext,
        block: &crate::lint_context::types::ListBlock,
        style: &ListItemSpacingStyle,
        allow_loose_continuation: bool,
    ) -> Option<BlockAnalysis> {
        // Only compare items at this block's own nesting level.
        // item_lines may include nested list items (higher marker_column) that belong
        // to a child list — those must not affect spacing analysis.
        let items: Vec<usize> = block
            .item_lines
            .iter()
            .copied()
            .filter(|&line_num| {
                ctx.line_info(line_num)
                    .and_then(|li| li.list_item.as_ref())
                    .map(|item| item.marker_column / 2 == block.nesting_level)
                    .unwrap_or(false)
            })
            .collect();

        if items.len() < 2 {
            return None;
        }

        // Classify each inter-item gap.
        let gaps: Vec<GapKind> = items.windows(2).map(|w| Self::classify_gap(ctx, w[0], w[1])).collect();

        // Structural gaps and (when allowed) continuation gaps are excluded
        // from consistency analysis — they should not influence whether the
        // list is considered loose or tight.
        let loose_count = gaps
            .iter()
            .filter(|&&g| g == GapKind::Loose || (g == GapKind::ContinuationLoose && !allow_loose_continuation))
            .count();
        let tight_count = gaps.iter().filter(|&&g| g == GapKind::Tight).count();

        let (warn_loose_gaps, warn_tight_gaps) = match style {
            ListItemSpacingStyle::Loose => (false, true),
            ListItemSpacingStyle::Tight => (true, false),
            ListItemSpacingStyle::Consistent => {
                if loose_count == 0 || tight_count == 0 {
                    return None; // Already consistent (structural gaps excluded)
                }
                // Majority wins; on a tie, prefer loose (warn tight).
                if loose_count >= tight_count {
                    (false, true)
                } else {
                    (true, false)
                }
            }
        };

        Some(BlockAnalysis {
            items,
            gaps,
            warn_loose_gaps,
            warn_tight_gaps,
        })
    }
}

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

    fn description(&self) -> &'static str {
        "List item spacing should be consistent"
    }

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

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        ctx.content.is_empty() || ctx.list_blocks.is_empty()
    }

    fn check(&self, ctx: &LintContext) -> LintResult {
        if ctx.content.is_empty() {
            return Ok(Vec::new());
        }

        let mut warnings = Vec::new();

        let allow_cont = self.config.allow_loose_continuation;

        for block in &ctx.list_blocks {
            let Some(analysis) = Self::analyze_block(ctx, block, &self.config.style, allow_cont) else {
                continue;
            };

            for (i, &gap) in analysis.gaps.iter().enumerate() {
                let is_loose_violation = match gap {
                    GapKind::Loose => analysis.warn_loose_gaps,
                    GapKind::ContinuationLoose => !allow_cont && analysis.warn_loose_gaps,
                    _ => false,
                };

                if is_loose_violation {
                    let blanks = Self::inter_item_blanks(ctx, analysis.items[i], analysis.items[i + 1]);
                    if let Some(&blank_line) = blanks.first() {
                        let line_content = ctx
                            .line_info(blank_line)
                            .map(|li| li.content(ctx.content))
                            .unwrap_or("");
                        warnings.push(LintWarning {
                            rule_name: Some(self.name().to_string()),
                            line: blank_line,
                            column: 1,
                            end_line: blank_line,
                            end_column: line_content.len() + 1,
                            message: "Unexpected blank line between list items".to_string(),
                            severity: Severity::Warning,
                            fix: None,
                        });
                    }
                } else if gap == GapKind::Tight && analysis.warn_tight_gaps {
                    let next_item = analysis.items[i + 1];
                    let line_content = ctx.line_info(next_item).map(|li| li.content(ctx.content)).unwrap_or("");
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: next_item,
                        column: 1,
                        end_line: next_item,
                        end_column: line_content.len() + 1,
                        message: "Missing blank line between list items".to_string(),
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
        if ctx.content.is_empty() {
            return Ok(ctx.content.to_string());
        }

        // Collect all inter-item blank lines to remove and lines to insert before.
        let mut insert_before: std::collections::HashSet<usize> = std::collections::HashSet::new();
        let mut remove_lines: std::collections::HashSet<usize> = std::collections::HashSet::new();

        let allow_cont = self.config.allow_loose_continuation;

        for block in &ctx.list_blocks {
            let Some(analysis) = Self::analyze_block(ctx, block, &self.config.style, allow_cont) else {
                continue;
            };

            for (i, &gap) in analysis.gaps.iter().enumerate() {
                let is_loose_violation = match gap {
                    GapKind::Loose => analysis.warn_loose_gaps,
                    GapKind::ContinuationLoose => !allow_cont && analysis.warn_loose_gaps,
                    _ => false,
                };

                if is_loose_violation {
                    for blank_line in Self::inter_item_blanks(ctx, analysis.items[i], analysis.items[i + 1]) {
                        remove_lines.insert(blank_line);
                    }
                } else if gap == GapKind::Tight && analysis.warn_tight_gaps {
                    insert_before.insert(analysis.items[i + 1]);
                }
            }
        }

        if insert_before.is_empty() && remove_lines.is_empty() {
            return Ok(ctx.content.to_string());
        }

        let lines = ctx.raw_lines();
        let mut result: Vec<String> = Vec::with_capacity(lines.len());

        for (i, line) in lines.iter().enumerate() {
            let line_num = i + 1;

            // Skip modifications for lines where the rule is disabled via inline config
            if ctx.is_rule_disabled(self.name(), line_num) {
                result.push((*line).to_string());
                continue;
            }

            if remove_lines.contains(&line_num) {
                continue;
            }

            if insert_before.contains(&line_num) {
                let bq_prefix = ctx.blockquote_prefix_for_blank_line(i);
                result.push(bq_prefix);
            }

            result.push((*line).to_string());
        }

        let mut output = result.join("\n");
        if ctx.content.ends_with('\n') {
            output.push('\n');
        }
        Ok(output)
    }

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

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let mut map = toml::map::Map::new();
        let style_str = match self.config.style {
            ListItemSpacingStyle::Consistent => "consistent",
            ListItemSpacingStyle::Loose => "loose",
            ListItemSpacingStyle::Tight => "tight",
        };
        map.insert("style".to_string(), toml::Value::String(style_str.to_string()));
        map.insert(
            "allow-loose-continuation".to_string(),
            toml::Value::Boolean(self.config.allow_loose_continuation),
        );
        Some((self.name().to_string(), toml::Value::Table(map)))
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let style = crate::config::get_rule_config_value::<String>(config, "MD076", "style")
            .unwrap_or_else(|| "consistent".to_string());
        let style = match style.as_str() {
            "loose" => ListItemSpacingStyle::Loose,
            "tight" => ListItemSpacingStyle::Tight,
            _ => ListItemSpacingStyle::Consistent,
        };
        let allow_loose_continuation =
            crate::config::get_rule_config_value::<bool>(config, "MD076", "allow-loose-continuation")
                .or_else(|| crate::config::get_rule_config_value::<bool>(config, "MD076", "allow_loose_continuation"))
                .unwrap_or(false);
        Box::new(Self::new(style).with_allow_loose_continuation(allow_loose_continuation))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn check(content: &str, style: ListItemSpacingStyle) -> Vec<LintWarning> {
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let rule = MD076ListItemSpacing::new(style);
        rule.check(&ctx).unwrap()
    }

    fn check_with_continuation(
        content: &str,
        style: ListItemSpacingStyle,
        allow_loose_continuation: bool,
    ) -> Vec<LintWarning> {
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let rule = MD076ListItemSpacing::new(style).with_allow_loose_continuation(allow_loose_continuation);
        rule.check(&ctx).unwrap()
    }

    fn fix(content: &str, style: ListItemSpacingStyle) -> String {
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let rule = MD076ListItemSpacing::new(style);
        rule.fix(&ctx).unwrap()
    }

    fn fix_with_continuation(content: &str, style: ListItemSpacingStyle, allow_loose_continuation: bool) -> String {
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let rule = MD076ListItemSpacing::new(style).with_allow_loose_continuation(allow_loose_continuation);
        rule.fix(&ctx).unwrap()
    }

    // ── Basic style detection ──────────────────────────────────────────

    #[test]
    fn tight_list_tight_style_no_warnings() {
        let content = "- Item 1\n- Item 2\n- Item 3\n";
        assert!(check(content, ListItemSpacingStyle::Tight).is_empty());
    }

    #[test]
    fn loose_list_loose_style_no_warnings() {
        let content = "- Item 1\n\n- Item 2\n\n- Item 3\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
    }

    #[test]
    fn tight_list_loose_style_warns() {
        let content = "- Item 1\n- Item 2\n- Item 3\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 2);
        assert!(warnings.iter().all(|w| w.message.contains("Missing")));
    }

    #[test]
    fn loose_list_tight_style_warns() {
        let content = "- Item 1\n\n- Item 2\n\n- Item 3\n";
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert_eq!(warnings.len(), 2);
        assert!(warnings.iter().all(|w| w.message.contains("Unexpected")));
    }

    // ── Consistent mode ────────────────────────────────────────────────

    #[test]
    fn consistent_all_tight_no_warnings() {
        let content = "- Item 1\n- Item 2\n- Item 3\n";
        assert!(check(content, ListItemSpacingStyle::Consistent).is_empty());
    }

    #[test]
    fn consistent_all_loose_no_warnings() {
        let content = "- Item 1\n\n- Item 2\n\n- Item 3\n";
        assert!(check(content, ListItemSpacingStyle::Consistent).is_empty());
    }

    #[test]
    fn consistent_mixed_majority_loose_warns_tight() {
        // 2 loose gaps, 1 tight gap → tight is minority → warn on tight
        let content = "- Item 1\n\n- Item 2\n- Item 3\n\n- Item 4\n";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("Missing"));
    }

    #[test]
    fn consistent_mixed_majority_tight_warns_loose() {
        // 1 loose gap, 2 tight gaps → loose is minority → warn on loose blank line
        let content = "- Item 1\n\n- Item 2\n- Item 3\n- Item 4\n";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("Unexpected"));
    }

    #[test]
    fn consistent_tie_prefers_loose() {
        let content = "- Item 1\n\n- Item 2\n- Item 3\n";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("Missing"));
    }

    // ── Edge cases ─────────────────────────────────────────────────────

    #[test]
    fn single_item_list_no_warnings() {
        let content = "- Only item\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
        assert!(check(content, ListItemSpacingStyle::Tight).is_empty());
        assert!(check(content, ListItemSpacingStyle::Consistent).is_empty());
    }

    #[test]
    fn empty_content_no_warnings() {
        assert!(check("", ListItemSpacingStyle::Consistent).is_empty());
    }

    #[test]
    fn ordered_list_tight_gaps_loose_style_warns() {
        let content = "1. First\n2. Second\n3. Third\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 2);
    }

    #[test]
    fn task_list_works() {
        let content = "- [x] Task 1\n- [ ] Task 2\n- [x] Task 3\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 2);
        let fixed = fix(content, ListItemSpacingStyle::Loose);
        assert_eq!(fixed, "- [x] Task 1\n\n- [ ] Task 2\n\n- [x] Task 3\n");
    }

    #[test]
    fn no_trailing_newline() {
        let content = "- Item 1\n- Item 2";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 1);
        let fixed = fix(content, ListItemSpacingStyle::Loose);
        assert_eq!(fixed, "- Item 1\n\n- Item 2");
    }

    #[test]
    fn two_separate_lists() {
        let content = "- A\n- B\n\nText\n\n1. One\n2. Two\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 2);
        let fixed = fix(content, ListItemSpacingStyle::Loose);
        assert_eq!(fixed, "- A\n\n- B\n\nText\n\n1. One\n\n2. Two\n");
    }

    #[test]
    fn no_list_content() {
        let content = "Just a paragraph.\n\nAnother paragraph.\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
        assert!(check(content, ListItemSpacingStyle::Tight).is_empty());
    }

    // ── Multi-line and continuation items ──────────────────────────────

    #[test]
    fn continuation_lines_tight_detected() {
        let content = "- Item 1\n  continuation\n- Item 2\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("Missing"));
    }

    #[test]
    fn continuation_lines_loose_detected() {
        let content = "- Item 1\n  continuation\n\n- Item 2\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("Unexpected"));
    }

    #[test]
    fn multi_paragraph_item_not_treated_as_inter_item_gap() {
        // Blank line between paragraphs within Item 1 must NOT trigger a warning.
        // Only the blank line immediately before Item 2 is an inter-item separator.
        let content = "- Item 1\n\n  Second paragraph\n\n- Item 2\n";
        // Both gaps are loose (blank before Item 2), so tight should warn once
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert_eq!(
            warnings.len(),
            1,
            "Should warn only on the inter-item blank, not the intra-item blank"
        );
        // The fix should remove only the inter-item blank (line 4), preserving the
        // multi-paragraph structure
        let fixed = fix(content, ListItemSpacingStyle::Tight);
        assert_eq!(fixed, "- Item 1\n\n  Second paragraph\n- Item 2\n");
    }

    #[test]
    fn multi_paragraph_item_loose_style_no_warnings() {
        // A loose list with multi-paragraph items is already loose — no warnings
        let content = "- Item 1\n\n  Second paragraph\n\n- Item 2\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
    }

    // ── Blockquote lists ───────────────────────────────────────────────

    #[test]
    fn blockquote_tight_list_loose_style_warns() {
        let content = "> - Item 1\n> - Item 2\n> - Item 3\n";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(warnings.len(), 2);
    }

    #[test]
    fn blockquote_loose_list_detected() {
        // A line with only `>` is effectively blank in blockquote context
        let content = "> - Item 1\n>\n> - Item 2\n";
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert_eq!(warnings.len(), 1, "Blockquote-only line should be detected as blank");
        assert!(warnings[0].message.contains("Unexpected"));
    }

    #[test]
    fn blockquote_loose_list_no_warnings_when_loose() {
        let content = "> - Item 1\n>\n> - Item 2\n";
        assert!(check(content, ListItemSpacingStyle::Loose).is_empty());
    }

    // ── Multiple blank lines ───────────────────────────────────────────

    #[test]
    fn multiple_blanks_all_removed() {
        let content = "- Item 1\n\n\n- Item 2\n";
        let fixed = fix(content, ListItemSpacingStyle::Tight);
        assert_eq!(fixed, "- Item 1\n- Item 2\n");
    }

    #[test]
    fn multiple_blanks_fix_is_idempotent() {
        let content = "- Item 1\n\n\n\n- Item 2\n";
        let fixed_once = fix(content, ListItemSpacingStyle::Tight);
        let fixed_twice = fix(&fixed_once, ListItemSpacingStyle::Tight);
        assert_eq!(fixed_once, fixed_twice);
        assert_eq!(fixed_once, "- Item 1\n- Item 2\n");
    }

    // ── Fix correctness ────────────────────────────────────────────────

    #[test]
    fn fix_adds_blank_lines() {
        let content = "- Item 1\n- Item 2\n- Item 3\n";
        let fixed = fix(content, ListItemSpacingStyle::Loose);
        assert_eq!(fixed, "- Item 1\n\n- Item 2\n\n- Item 3\n");
    }

    #[test]
    fn fix_removes_blank_lines() {
        let content = "- Item 1\n\n- Item 2\n\n- Item 3\n";
        let fixed = fix(content, ListItemSpacingStyle::Tight);
        assert_eq!(fixed, "- Item 1\n- Item 2\n- Item 3\n");
    }

    #[test]
    fn fix_consistent_adds_blank() {
        // 2 loose gaps, 1 tight gap → add blank before Item 3
        let content = "- Item 1\n\n- Item 2\n- Item 3\n\n- Item 4\n";
        let fixed = fix(content, ListItemSpacingStyle::Consistent);
        assert_eq!(fixed, "- Item 1\n\n- Item 2\n\n- Item 3\n\n- Item 4\n");
    }

    #[test]
    fn fix_idempotent_loose() {
        let content = "- Item 1\n- Item 2\n";
        let fixed_once = fix(content, ListItemSpacingStyle::Loose);
        let fixed_twice = fix(&fixed_once, ListItemSpacingStyle::Loose);
        assert_eq!(fixed_once, fixed_twice);
    }

    #[test]
    fn fix_idempotent_tight() {
        let content = "- Item 1\n\n- Item 2\n";
        let fixed_once = fix(content, ListItemSpacingStyle::Tight);
        let fixed_twice = fix(&fixed_once, ListItemSpacingStyle::Tight);
        assert_eq!(fixed_once, fixed_twice);
    }

    // ── Nested lists ───────────────────────────────────────────────────

    #[test]
    fn nested_list_does_not_affect_parent() {
        // Nested items should not trigger warnings for the parent list
        let content = "- Item 1\n  - Nested A\n  - Nested B\n- Item 2\n";
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert!(
            warnings.is_empty(),
            "Nested items should not cause parent-level warnings"
        );
    }

    // ── Structural blank lines (code blocks, tables, HTML) ──────────

    #[test]
    fn code_block_in_tight_list_no_false_positive() {
        // Blank line after closing fence is structural (required by MD031), not a separator
        let content = "\
- Item 1 with code:

  ```python
  print('hello')
  ```

- Item 2 simple.
- Item 3 simple.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank after code block should not make item 1 appear loose"
        );
    }

    #[test]
    fn table_in_tight_list_no_false_positive() {
        // Blank line after table is structural (required by MD058), not a separator
        let content = "\
- Item 1 with table:

  | Col 1 | Col 2 |
  |-------|-------|
  | A     | B     |

- Item 2 simple.
- Item 3 simple.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank after table should not make item 1 appear loose"
        );
    }

    #[test]
    fn html_block_in_tight_list_no_false_positive() {
        let content = "\
- Item 1 with HTML:

  <details>
  <summary>Click</summary>
  Content
  </details>

- Item 2 simple.
- Item 3 simple.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank after HTML block should not make item 1 appear loose"
        );
    }

    #[test]
    fn blockquote_in_tight_list_no_false_positive() {
        // Blank line around a blockquote in a list item is structural, not a separator
        let content = "\
- Item 1 with quote:

  > This is a blockquote
  > with multiple lines.

- Item 2 simple.
- Item 3 simple.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank around blockquote should not make item 1 appear loose"
        );
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Blockquote in tight list should not trigger a violation"
        );
    }

    #[test]
    fn blockquote_multiple_items_with_quotes_tight() {
        // Multiple items with blockquotes should all be treated as structural
        let content = "\
- Item 1:

  > Quote A

- Item 2:

  > Quote B

- Item 3 plain.
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Multiple items with blockquotes should remain tight"
        );
    }

    #[test]
    fn blockquote_mixed_with_genuine_loose_gap() {
        // A blockquote item followed by a genuine loose gap should still be detected
        let content = "\
- Item 1:

  > Quote

- Item 2 plain.

- Item 3 plain.
";
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert!(
            !warnings.is_empty(),
            "Genuine loose gap between Item 2 and Item 3 should be flagged"
        );
    }

    #[test]
    fn blockquote_single_line_in_tight_list() {
        let content = "\
- Item 1:

  > Single line quote.

- Item 2.
- Item 3.
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Single-line blockquote should be structural"
        );
    }

    #[test]
    fn blockquote_in_ordered_list_tight() {
        let content = "\
1. Item 1:

   > Quoted text in ordered list.

1. Item 2.
1. Item 3.
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Blockquote in ordered list should be structural"
        );
    }

    #[test]
    fn nested_blockquote_in_tight_list() {
        let content = "\
- Item 1:

  > Outer quote
  > > Nested quote

- Item 2.
- Item 3.
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Nested blockquote in tight list should be structural"
        );
    }

    #[test]
    fn blockquote_as_entire_item_is_loose() {
        // When a blockquote IS the item content (not nested within text),
        // a trailing blank line is a genuine loose gap, not structural.
        let content = "\
- > Quote is the entire item content.

- Item 2.
- Item 3.
";
        let warnings = check(content, ListItemSpacingStyle::Tight);
        assert!(
            !warnings.is_empty(),
            "Blank after blockquote-only item is a genuine loose gap"
        );
    }

    #[test]
    fn mixed_code_and_table_in_tight_list() {
        let content = "\
1. Item with code:

   ```markdown
   This is some Markdown
   ```

1. Simple item.
1. Item with table:

   | Col 1 | Col 2 |
   |:------|:------|
   | Row 1 | Row 1 |
   | Row 2 | Row 2 |
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Mix of code blocks and tables should not cause false positives"
        );
    }

    #[test]
    fn code_block_with_genuinely_loose_gaps_still_warns() {
        // Item 1 has structural blank (code block), items 2-3 have genuine blank separator
        // Items 2-3 are genuinely loose, item 3-4 is tight → inconsistent
        let content = "\
- Item 1:

  ```bash
  echo hi
  ```

- Item 2

- Item 3
- Item 4
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Genuine inconsistency with code blocks should still be flagged"
        );
    }

    #[test]
    fn all_items_have_code_blocks_no_warnings() {
        let content = "\
- Item 1:

  ```python
  print(1)
  ```

- Item 2:

  ```python
  print(2)
  ```

- Item 3:

  ```python
  print(3)
  ```
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "All items with code blocks should be consistently tight"
        );
    }

    #[test]
    fn tilde_fence_code_block_in_list() {
        let content = "\
- Item 1:

  ~~~
  code here
  ~~~

- Item 2 simple.
- Item 3 simple.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Tilde fences should be recognized as structural content"
        );
    }

    #[test]
    fn nested_list_with_code_block() {
        let content = "\
- Item 1
  - Nested with code:

    ```
    nested code
    ```

  - Nested simple.
- Item 2
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Nested list with code block should not cause false positives"
        );
    }

    #[test]
    fn tight_style_with_code_block_no_warnings() {
        let content = "\
- Item 1:

  ```
  code
  ```

- Item 2.
- Item 3.
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Tight style should not warn about structural blanks around code blocks"
        );
    }

    #[test]
    fn loose_style_with_code_block_missing_separator() {
        // Loose style requires blank line between every pair of items.
        // Items 2-3 have no blank → should warn
        let content = "\
- Item 1:

  ```
  code
  ```

- Item 2.
- Item 3.
";
        let warnings = check(content, ListItemSpacingStyle::Loose);
        assert_eq!(
            warnings.len(),
            1,
            "Loose style should still require blank between simple items"
        );
        assert!(warnings[0].message.contains("Missing"));
    }

    #[test]
    fn blockquote_list_with_code_block() {
        let content = "\
> - Item 1:
>
>   ```
>   code
>   ```
>
> - Item 2.
> - Item 3.
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Blockquote-prefixed list with code block should not cause false positives"
        );
    }

    // ── Indented code block (not fenced) in list item ─────────────────

    #[test]
    fn indented_code_block_in_list_no_false_positive() {
        // A 4-space indented code block inside a list item should be treated
        // as structural content, not trigger a loose gap detection.
        let content = "\
1. Item with indented code:

       some code here
       more code

1. Simple item
1. Another item
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank after indented code block should not make item 1 appear loose"
        );
    }

    // ── Code block in middle of item with text after ────────────────

    #[test]
    fn code_block_in_middle_of_item_text_after_is_genuinely_loose() {
        // When a code block is in the middle of an item and there's regular text
        // after it, a blank line before the next item IS a genuine separator (loose),
        // not structural. The last non-blank line before item 2 is "Some text after
        // the code block." which is NOT structural content.
        let content = "\
1. Item with code in middle:

   ```
   code
   ```

   Some text after the code block.

1. Simple item
1. Another item
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Blank line after regular text (not structural content) is a genuine loose gap"
        );
    }

    // ── Fix: tight mode preserves structural blanks ──────────────────

    #[test]
    fn tight_fix_preserves_structural_blanks_around_code_blocks() {
        // When style is tight, the fix should NOT remove structural blank lines
        // around code blocks inside list items. Those blanks are required by MD031.
        let content = "\
- Item 1:

  ```
  code
  ```

- Item 2.
- Item 3.
";
        let fixed = fix(content, ListItemSpacingStyle::Tight);
        assert_eq!(
            fixed, content,
            "Tight fix should not remove structural blanks around code blocks"
        );
    }

    // ── Issue #461: 4-space indented code block in loose list ──────────

    #[test]
    fn four_space_indented_fence_in_loose_list_no_false_positive() {
        // Reproduction case from issue #461 comment by @sisp.
        // The fenced code block uses 4-space indentation inside an ordered list.
        // The blank line after the closing fence is structural (required by MD031)
        // and must not create a false "Missing blank line" warning.
        let content = "\
1. First item

1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "Structural blank after 4-space indented code block should not cause false positive"
        );
    }

    #[test]
    fn four_space_indented_fence_tight_style_no_warnings() {
        let content = "\
1. First item
1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        assert!(
            check(content, ListItemSpacingStyle::Tight).is_empty(),
            "Tight style should not warn about structural blanks with 4-space fences"
        );
    }

    #[test]
    fn four_space_indented_fence_loose_style_no_warnings() {
        // All non-structural gaps are loose, structural gaps are excluded.
        let content = "\
1. First item

1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        assert!(
            check(content, ListItemSpacingStyle::Loose).is_empty(),
            "Loose style should not warn when structural gaps are the only non-loose gaps"
        );
    }

    #[test]
    fn structural_gap_with_genuine_inconsistency_still_warns() {
        // Item 1 has a structural code block. Items 2-3 are genuinely loose,
        // but items 3-4 are tight → genuine inconsistency should still warn.
        let content = "\
1. First item with code:

    ```json
    {\"key\": \"value\"}
    ```

1. Second item

1. Third item
1. Fourth item
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Genuine loose/tight inconsistency should still warn even with structural gaps"
        );
    }

    #[test]
    fn four_space_fence_fix_is_idempotent() {
        // Fix should not modify a list that has only structural gaps and
        // genuine loose gaps — it's already consistent.
        let content = "\
1. First item

1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        let fixed = fix(content, ListItemSpacingStyle::Consistent);
        assert_eq!(fixed, content, "Fix should be a no-op for lists with structural gaps");
        let fixed_twice = fix(&fixed, ListItemSpacingStyle::Consistent);
        assert_eq!(fixed, fixed_twice, "Fix should be idempotent");
    }

    #[test]
    fn four_space_fence_fix_does_not_insert_duplicate_blank() {
        // When tight style tries to fix, it should not insert a blank line
        // before item 3 when one already exists (structural).
        let content = "\
1. First item
1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        let fixed = fix(content, ListItemSpacingStyle::Tight);
        assert_eq!(fixed, content, "Tight fix should not modify structural blanks");
    }

    #[test]
    fn mkdocs_flavor_code_block_in_list_no_false_positive() {
        // MkDocs flavor with code block inside a list item.
        // Reported by @sisp in issue #461 comment.
        let content = "\
1. First item

1. Second item with code block:

    ```json
    {\"key\": \"value\"}
    ```

1. Third item
";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
        let rule = MD076ListItemSpacing::new(ListItemSpacingStyle::Consistent);
        let warnings = rule.check(&ctx).unwrap();
        assert!(
            warnings.is_empty(),
            "MkDocs flavor with structural code block blank should not produce false positive, got: {warnings:?}"
        );
    }

    // ── Issue #500: code block inside list item splits list blocks ─────

    #[test]
    fn code_block_in_second_item_detects_inconsistency() {
        // A code block inside item 2 must not split the list into separate blocks.
        // Items 1-2 are tight, items 3-4 are loose → inconsistent.
        let content = "\
# Test

- Lorem ipsum dolor sit amet.
- Lorem ipsum dolor sit amet.

    ```yaml
    hello: world
    ```

- Lorem ipsum dolor sit amet.

- Lorem ipsum dolor sit amet.
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Should detect inconsistent spacing when code block is inside a list item"
        );
    }

    #[test]
    fn code_block_in_item_all_tight_no_warnings() {
        // All non-structural gaps are tight → consistent, no warnings.
        let content = "\
- Item 1
- Item 2

    ```yaml
    hello: world
    ```

- Item 3
- Item 4
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "All tight gaps with structural code block should not warn"
        );
    }

    #[test]
    fn code_block_in_item_all_loose_no_warnings() {
        // All non-structural gaps are loose → consistent, no warnings.
        let content = "\
- Item 1

- Item 2

    ```yaml
    hello: world
    ```

- Item 3

- Item 4
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "All loose gaps with structural code block should not warn"
        );
    }

    #[test]
    fn code_block_in_ordered_list_detects_inconsistency() {
        let content = "\
1. First item
1. Second item

    ```json
    {\"key\": \"value\"}
    ```

1. Third item

1. Fourth item
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Ordered list with code block should still detect inconsistency"
        );
    }

    #[test]
    fn code_block_in_item_fix_adds_missing_blanks() {
        // Items 1-2 are tight, items 3-4 are loose → majority loose → fix adds blank before item 2
        let content = "\
- Item 1
- Item 2

    ```yaml
    code: here
    ```

- Item 3

- Item 4
";
        let fixed = fix(content, ListItemSpacingStyle::Consistent);
        assert!(
            fixed.contains("- Item 1\n\n- Item 2"),
            "Fix should add blank line between items 1 and 2"
        );
    }

    #[test]
    fn tilde_code_block_in_item_detects_inconsistency() {
        let content = "\
- Item 1
- Item 2

    ~~~
    code
    ~~~

- Item 3

- Item 4
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Tilde code block inside item should not prevent inconsistency detection"
        );
    }

    #[test]
    fn multiple_code_blocks_all_tight_no_warnings() {
        // All non-structural gaps are tight → consistent.
        let content = "\
- Item 1

    ```
    code1
    ```

- Item 2

    ```
    code2
    ```

- Item 3
- Item 4
";
        assert!(
            check(content, ListItemSpacingStyle::Consistent).is_empty(),
            "All non-structural gaps are tight, so list is consistent"
        );
    }

    #[test]
    fn code_block_with_mixed_genuine_gaps_warns() {
        // Items 1-2 structural, 2-3 loose, 3-4 tight → genuine inconsistency
        let content = "\
- Item 1

    ```
    code1
    ```

- Item 2

- Item 3
- Item 4
";
        let warnings = check(content, ListItemSpacingStyle::Consistent);
        assert!(
            !warnings.is_empty(),
            "Mixed genuine gaps (loose + tight) with structural code block should still warn"
        );
    }

    // ── allow-loose-continuation ─────────────────────────────────────

    #[test]
    fn continuation_loose_tight_style_default_warns() {
        // Default (allow_loose_continuation=false): blank lines around
        // continuation paragraphs are treated as loose gaps → violation
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.

  Continuation paragraph.

- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, false);
        assert!(
            !warnings.is_empty(),
            "Should warn about loose gaps when allow_loose_continuation is false"
        );
    }

    #[test]
    fn continuation_loose_tight_style_allowed_no_warnings() {
        // With allow_loose_continuation=true: blank lines around continuation
        // paragraphs are permitted even in tight mode
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.

  Continuation paragraph.

- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            warnings.is_empty(),
            "Should not warn when allow_loose_continuation is true, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_mixed_items_warns() {
        // Even with allow_loose_continuation, genuinely loose inter-item gaps
        // (blank line between items that have no continuation) should still warn
        let content = "\
- Item 1.

- Item 2.
- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            !warnings.is_empty(),
            "Genuine loose gaps should still warn even with allow_loose_continuation"
        );
    }

    #[test]
    fn continuation_loose_consistent_mode() {
        // In consistent mode with allow_loose_continuation, continuation gaps
        // should not count toward loose/tight consistency
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.
- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Consistent, true);
        assert!(
            warnings.is_empty(),
            "Continuation gaps should not affect consistency when allowed, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_fix_preserves_continuation_blanks() {
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.

  Continuation paragraph.

- Item 3.
";
        let fixed = fix_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert_eq!(fixed, content, "Fix should preserve continuation blank lines");
    }

    #[test]
    fn continuation_loose_fix_removes_genuine_loose_gaps() {
        let input = "\
- Item 1.

- Item 2.

- Item 3.
";
        let expected = "\
- Item 1.
- Item 2.
- Item 3.
";
        let fixed = fix_with_continuation(input, ListItemSpacingStyle::Tight, true);
        assert_eq!(fixed, expected);
    }

    #[test]
    fn continuation_loose_ordered_list() {
        let content = "\
1. Item 1.

   Continuation paragraph.

2. Item 2.

   Continuation paragraph.

3. Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            warnings.is_empty(),
            "Ordered list continuation should work too, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_disabled_by_default() {
        // Verify the constructor defaults to false
        let rule = MD076ListItemSpacing::new(ListItemSpacingStyle::Tight);
        assert!(!rule.config.allow_loose_continuation);
    }

    #[test]
    fn continuation_loose_ordered_under_indented_warns() {
        // Ordered list: "1. " has content_column=3, so 2-space indent
        // is under-indented and should NOT be treated as continuation
        let content = "\
1. Item 1.

  Under-indented text.

1. Item 2.
1. Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            !warnings.is_empty(),
            "Under-indented text should not be treated as continuation, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_mix_continuation_and_genuine_gaps() {
        // Some items have continuation (allowed), one gap is genuinely loose (not allowed)
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.

- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            !warnings.is_empty(),
            "Genuine loose gap between items 2-3 should warn even with continuation allowed"
        );
        // Only the genuine loose gap should warn, not the continuation gap
        assert_eq!(
            warnings.len(),
            1,
            "Expected exactly one warning for the genuine loose gap"
        );
    }

    #[test]
    fn continuation_loose_fix_mixed_preserves_continuation_removes_genuine() {
        // Fix should preserve continuation blanks but remove genuine loose gaps
        let input = "\
- Item 1.

  Continuation paragraph.

- Item 2.

- Item 3.
";
        let expected = "\
- Item 1.

  Continuation paragraph.

- Item 2.
- Item 3.
";
        let fixed = fix_with_continuation(input, ListItemSpacingStyle::Tight, true);
        assert_eq!(fixed, expected);
    }

    #[test]
    fn continuation_loose_after_code_block() {
        // Code block is structural, continuation after code block should also work
        let content = "\
- Item 1.

  ```python
  code
  ```

  Continuation after code.

- Item 2.
- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            warnings.is_empty(),
            "Code block + continuation should both be exempt, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_style_does_not_interfere() {
        // With style=loose, allow-loose-continuation shouldn't change behavior —
        // loose style already requires blank lines everywhere
        let content = "\
- Item 1.

  Continuation paragraph.

- Item 2.

  Continuation paragraph.

- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Loose, true);
        assert!(
            warnings.is_empty(),
            "Loose style with continuation should not warn, got: {warnings:?}"
        );
    }

    #[test]
    fn continuation_loose_tight_no_continuation_content() {
        // All items are simple (no continuation), tight style should work normally
        let content = "\
- Item 1.
- Item 2.
- Item 3.
";
        let warnings = check_with_continuation(content, ListItemSpacingStyle::Tight, true);
        assert!(
            warnings.is_empty(),
            "Simple tight list should pass with allow_loose_continuation, got: {warnings:?}"
        );
    }

    // ── Config schema ──────────────────────────────────────────────────

    #[test]
    fn default_config_section_provides_style_key() {
        let rule = MD076ListItemSpacing::new(ListItemSpacingStyle::Consistent);
        let section = rule.default_config_section();
        assert!(section.is_some());
        let (name, value) = section.unwrap();
        assert_eq!(name, "MD076");
        if let toml::Value::Table(map) = value {
            assert!(map.contains_key("style"));
            assert!(map.contains_key("allow-loose-continuation"));
        } else {
            panic!("Expected Table value from default_config_section");
        }
    }
}