rumdl 0.2.62

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
use crate::config::MarkdownFlavor;
use crate::filtered_lines::FilteredLinesExt;
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::rule_config_serde::{FlavorOverrideNotice, option_is_explicit};
use crate::rules::code_fence_utils::CodeFenceStyle;
use crate::utils::range_utils::calculate_match_range;
use toml;

mod md048_config;
use md048_config::MD048Config;

/// Reports the MDG style override once per process; see [`FlavorOverrideNotice`].
static MDG_STYLE_OVERRIDE: FlavorOverrideNotice = FlavorOverrideNotice::new();

/// Parsed fence marker candidate on a single line.
#[derive(Debug, Clone, Copy)]
struct FenceMarker<'a> {
    /// Fence character (` or ~).
    fence_char: char,
    /// Length of the contiguous fence run.
    fence_len: usize,
    /// Byte index where the fence run starts.
    fence_start: usize,
    /// Remaining text after the fence run.
    rest: &'a str,
}

/// Parse a candidate fence marker line.
///
/// CommonMark only recognizes fenced code block markers when indented by at most
/// three spaces (outside container contexts). This parser enforces that bound and
/// returns the marker run and trailing text for further opening/closing checks.
#[inline]
fn parse_fence_marker(line: &str) -> Option<FenceMarker<'_>> {
    let bytes = line.as_bytes();
    let mut pos = 0usize;
    while pos < bytes.len() && bytes[pos] == b' ' {
        pos += 1;
    }
    if pos > 3 {
        return None;
    }

    let fence_char = match bytes.get(pos).copied() {
        Some(b'`') => '`',
        Some(b'~') => '~',
        _ => return None,
    };

    let marker = if fence_char == '`' { b'`' } else { b'~' };
    let mut end = pos;
    while end < bytes.len() && bytes[end] == marker {
        end += 1;
    }
    let fence_len = end - pos;
    if fence_len < 3 {
        return None;
    }

    Some(FenceMarker {
        fence_char,
        fence_len,
        fence_start: pos,
        rest: &line[end..],
    })
}

#[inline]
fn is_closing_fence(marker: FenceMarker<'_>, opening_fence_char: char, opening_fence_len: usize) -> bool {
    marker.fence_char == opening_fence_char && marker.fence_len >= opening_fence_len && marker.rest.trim().is_empty()
}

#[inline]
fn needs_fence_conversion(fence_char: char, target_style: CodeFenceStyle) -> bool {
    (fence_char == '`' && target_style == CodeFenceStyle::Tilde)
        || (fence_char == '~' && target_style == CodeFenceStyle::Backtick)
}

/// Rule MD048: Code fence style
///
/// See [docs/md048.md](../../docs/md048.md) for full documentation, configuration, and examples.
#[derive(Clone)]
pub struct MD048CodeFenceStyle {
    config: MD048Config,
    /// Whether `style` came from the configuration rather than from the
    /// default. MDG enforces backtick either way; this only decides whether the
    /// user is told that the style they asked for was not adopted.
    style_explicit: bool,
}

impl MD048CodeFenceStyle {
    pub fn new(style: CodeFenceStyle) -> Self {
        Self {
            config: MD048Config { style },
            style_explicit: true,
        }
    }

    pub fn from_config_struct(config: MD048Config) -> Self {
        Self {
            config,
            style_explicit: false,
        }
    }

    /// Resolve the fence style MD048 should converge on.
    ///
    /// A Gherkin Doc String is only ever a backtick fence, so a tilde fence can
    /// never be one, and a configuration demanding tilde fences cannot be
    /// satisfied in this flavor. MDG therefore always converges on backtick:
    /// `consistent` resolves to backtick rather than to whichever marker
    /// happens to be more common, and an explicit `tilde` is not adopted.
    fn effective_target_style(&self, ctx: &crate::lint_context::LintContext) -> CodeFenceStyle {
        if ctx.flavor == MarkdownFlavor::MDG {
            self.warn_once_about_overridden_style();
            return CodeFenceStyle::Backtick;
        }

        match self.config.style {
            CodeFenceStyle::Consistent => self.detect_style(ctx).unwrap_or(CodeFenceStyle::Backtick),
            style => style,
        }
    }

    /// Tell the user once that MDG did not adopt the style they configured.
    ///
    /// Only `tilde` is worth reporting: it is the one setting MDG cannot
    /// satisfy. `consistent` asks for no particular marker, and backtick is
    /// what MDG picks for it anyway.
    fn warn_once_about_overridden_style(&self) {
        if !self.style_explicit || self.config.style != CodeFenceStyle::Tilde {
            return;
        }

        MDG_STYLE_OVERRIDE.report(
            "MD048",
            "style",
            "tilde",
            "backtick",
            "a Gherkin Doc String is only ever a backtick fence",
        );
    }

    fn detect_style(&self, ctx: &crate::lint_context::LintContext) -> Option<CodeFenceStyle> {
        // Count occurrences of each fence style (prevalence-based approach)
        let mut backtick_count = 0;
        let mut tilde_count = 0;
        let mut in_code_block = false;
        let mut opening_fence_char = '`';
        let mut opening_fence_len = 0usize;

        for filtered_line in ctx.filtered_lines().skip_front_matter() {
            let i = filtered_line.line_num - 1;
            let line = filtered_line.content;
            // Skip lines inside Azure DevOps colon code fences — they are
            // opaque content and must not influence backtick/tilde style detection.
            if ctx.flavor.supports_colon_code_fences() && ctx.lines.get(i).is_some_and(|li| li.in_code_block) {
                continue;
            }

            // Skip lines inside MyST colon directives — they are structural
            // containers, not code fences.
            if ctx.flavor.supports_myst_directives() && ctx.lines.get(i).is_some_and(|li| li.in_myst_directive) {
                continue;
            }

            let Some(marker) = parse_fence_marker(line) else {
                continue;
            };

            // Skip MyST backtick directives (info string starts with {name})
            if ctx.flavor.supports_myst_directives()
                && marker.fence_char == '`'
                && marker.rest.trim_start().starts_with('{')
            {
                continue;
            }

            if !in_code_block {
                // Opening fence - count it
                if marker.fence_char == '`' {
                    backtick_count += 1;
                } else {
                    tilde_count += 1;
                }
                in_code_block = true;
                opening_fence_char = marker.fence_char;
                opening_fence_len = marker.fence_len;
            } else if is_closing_fence(marker, opening_fence_char, opening_fence_len) {
                in_code_block = false;
            }
        }

        // Use the most prevalent style
        // In case of a tie, prefer backticks (more common, widely supported)
        if backtick_count >= tilde_count && backtick_count > 0 {
            Some(CodeFenceStyle::Backtick)
        } else if tilde_count > 0 {
            Some(CodeFenceStyle::Tilde)
        } else {
            None
        }
    }
}

/// Find the maximum fence length using `target_char` within the body of a fenced block.
///
/// Scans from the line after `opening_line` until the matching closing fence
/// (same `opening_char`, length >= `opening_fence_len`, no trailing content).
/// Returns the maximum number of consecutive `target_char` characters found at
/// the start of any interior bare fence line (after stripping leading whitespace).
///
/// This is used to compute the minimum fence length needed when converting a
/// fence from one style to another so that nesting remains unambiguous.
/// For example, converting a `~~~` outer fence that contains ```` ``` ```` inner
/// fences to backtick style requires using ```` ```` ```` (4 backticks) so that
/// the inner 3-backtick bare fences cannot inadvertently close the outer block.
///
/// Only bare interior sequences (no trailing content) are counted. Per CommonMark
/// spec section 4.5, a closing fence must be followed only by optional whitespace —
/// lines with info strings (e.g. `` ```rust ``) can never be closing fences, so
/// they never create ambiguity regardless of the outer fence's style.
fn max_inner_fence_length_of_char(
    lines: &[&str],
    opening_line: usize,
    opening_fence_len: usize,
    opening_char: char,
    target_char: char,
) -> usize {
    let mut max_len = 0usize;

    for line in lines.iter().skip(opening_line + 1) {
        let Some(marker) = parse_fence_marker(line) else {
            continue;
        };

        // Stop at the closing fence of the outer block.
        if is_closing_fence(marker, opening_char, opening_fence_len) {
            break;
        }

        // Count only bare sequences (no info string). Lines with info strings
        // can never be closing fences per CommonMark and pose no ambiguity risk.
        if marker.fence_char == target_char && marker.rest.trim().is_empty() {
            max_len = max_len.max(marker.fence_len);
        }
    }

    max_len
}

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

    fn description(&self) -> &'static str {
        "Code fence style should be consistent"
    }

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

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let mut warnings = Vec::new();

        let target_style = self.effective_target_style(ctx);

        let lines = ctx.raw_lines();
        let mut in_code_block = false;
        let mut code_block_fence_char = '`';
        let mut code_block_fence_len = 0usize;
        // The fence length to use when writing the converted/lengthened closing fence.
        // May be longer than the original when inner fences require disambiguation by length.
        let mut converted_fence_len = 0usize;
        // True when the opening fence was already the correct style but its length is
        // ambiguous (interior has same-style fences of equal or greater length).
        let mut needs_lengthening = false;

        for filtered_line in ctx.filtered_lines().skip_front_matter() {
            let line_num = filtered_line.line_num - 1;
            let line = filtered_line.content;
            // Skip lines inside Azure DevOps colon code fences.
            if ctx.flavor.supports_colon_code_fences() && ctx.lines.get(line_num).is_some_and(|li| li.in_code_block) {
                continue;
            }

            // Skip lines inside MyST colon directives.
            if ctx.flavor.supports_myst_directives() && ctx.lines.get(line_num).is_some_and(|li| li.in_myst_directive) {
                continue;
            }

            let Some(marker) = parse_fence_marker(line) else {
                continue;
            };

            // Skip MyST backtick directives (info string starts with {name})
            if ctx.flavor.supports_myst_directives()
                && !in_code_block
                && marker.fence_char == '`'
                && marker.rest.trim_start().starts_with('{')
            {
                continue;
            }
            let fence_char = marker.fence_char;
            let fence_len = marker.fence_len;

            if !in_code_block {
                in_code_block = true;
                code_block_fence_char = fence_char;
                code_block_fence_len = fence_len;

                let needs_conversion = needs_fence_conversion(fence_char, target_style);

                if needs_conversion {
                    let target_char = if target_style == CodeFenceStyle::Backtick {
                        '`'
                    } else {
                        '~'
                    };

                    // Compute how many target_char characters the converted fence needs.
                    // Must be strictly greater than any inner bare fence of the target style.
                    let prefix = &line[..marker.fence_start];
                    let info = marker.rest;
                    let max_inner = max_inner_fence_length_of_char(lines, line_num, fence_len, fence_char, target_char);
                    converted_fence_len = fence_len.max(max_inner + 1);
                    needs_lengthening = false;

                    let replacement = format!("{prefix}{}{info}", target_char.to_string().repeat(converted_fence_len));

                    let fence_start = marker.fence_start;
                    let fence_end = fence_start + fence_len;
                    let (start_line, start_col, end_line, end_col) =
                        calculate_match_range(line_num + 1, line, fence_start, fence_end - fence_start);

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: format!(
                            "Code fence style: use {} instead of {}",
                            if target_style == CodeFenceStyle::Backtick {
                                "```"
                            } else {
                                "~~~"
                            },
                            if fence_char == '`' { "```" } else { "~~~" }
                        ),
                        line: start_line,
                        column: start_col,
                        end_line,
                        end_column: end_col,
                        severity: Severity::Warning,
                        fix: Some(Fix::new(
                            ctx.line_column_byte_range_with_length(line_num + 1, 1, line.len()),
                            replacement,
                        )),
                    });
                } else {
                    // No character conversion is required.
                    // Check for fence-length ambiguity:
                    // if the interior contains same-style bare fences of equal or greater
                    // length, the outer fence cannot be distinguished from an inner
                    // closing fence and must be made longer.
                    let prefix = &line[..marker.fence_start];
                    let info = marker.rest;
                    let max_inner = max_inner_fence_length_of_char(lines, line_num, fence_len, fence_char, fence_char);
                    if max_inner >= fence_len {
                        converted_fence_len = max_inner + 1;
                        needs_lengthening = true;

                        let replacement =
                            format!("{prefix}{}{info}", fence_char.to_string().repeat(converted_fence_len));

                        let fence_start = marker.fence_start;
                        let fence_end = fence_start + fence_len;
                        let (start_line, start_col, end_line, end_col) =
                            calculate_match_range(line_num + 1, line, fence_start, fence_end - fence_start);

                        warnings.push(LintWarning {
                            rule_name: Some(self.name().to_string()),
                            message: format!(
                                "Code fence length is ambiguous: outer fence ({fence_len} {}) \
                                 contains interior fence sequences of equal length; \
                                 use {converted_fence_len}",
                                if fence_char == '`' { "backticks" } else { "tildes" },
                            ),
                            line: start_line,
                            column: start_col,
                            end_line,
                            end_column: end_col,
                            severity: Severity::Warning,
                            fix: Some(Fix::new(
                                ctx.line_column_byte_range_with_length(line_num + 1, 1, line.len()),
                                replacement,
                            )),
                        });
                    } else {
                        converted_fence_len = fence_len;
                        needs_lengthening = false;
                    }
                }
            } else {
                // Inside a code block — check if this is the closing fence.
                let is_closing = is_closing_fence(marker, code_block_fence_char, code_block_fence_len);

                if is_closing {
                    let needs_conversion = needs_fence_conversion(fence_char, target_style);

                    if needs_conversion || needs_lengthening {
                        let target_char = if needs_conversion {
                            if target_style == CodeFenceStyle::Backtick {
                                '`'
                            } else {
                                '~'
                            }
                        } else {
                            fence_char
                        };

                        let prefix = &line[..marker.fence_start];
                        let replacement = format!(
                            "{prefix}{}{}",
                            target_char.to_string().repeat(converted_fence_len),
                            marker.rest
                        );

                        let fence_start = marker.fence_start;
                        let fence_end = fence_start + fence_len;
                        let (start_line, start_col, end_line, end_col) =
                            calculate_match_range(line_num + 1, line, fence_start, fence_end - fence_start);

                        let message = if needs_conversion {
                            format!(
                                "Code fence style: use {} instead of {}",
                                if target_style == CodeFenceStyle::Backtick {
                                    "```"
                                } else {
                                    "~~~"
                                },
                                if fence_char == '`' { "```" } else { "~~~" }
                            )
                        } else {
                            format!(
                                "Code fence length is ambiguous: closing fence ({fence_len} {}) \
                                 must match the lengthened outer fence; use {converted_fence_len}",
                                if fence_char == '`' { "backticks" } else { "tildes" },
                            )
                        };

                        warnings.push(LintWarning {
                            rule_name: Some(self.name().to_string()),
                            message,
                            line: start_line,
                            column: start_col,
                            end_line,
                            end_column: end_col,
                            severity: Severity::Warning,
                            fix: Some(Fix::new(
                                ctx.line_column_byte_range_with_length(line_num + 1, 1, line.len()),
                                replacement,
                            )),
                        });
                    }

                    in_code_block = false;
                    code_block_fence_len = 0;
                    converted_fence_len = 0;
                    needs_lengthening = false;
                }
                // Lines inside the block that are not the closing fence are left alone.
            }
        }

        Ok(warnings)
    }

    /// Check if this rule should be skipped for performance
    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Skip if content is empty or has no code fence markers
        ctx.content.is_empty() || (!ctx.likely_has_code() && !ctx.has_char('~'))
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        if self.should_skip(ctx) {
            return Ok(ctx.content.to_string());
        }
        let warnings = self.check(ctx)?;
        if warnings.is_empty() {
            return Ok(ctx.content.to_string());
        }
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
            .map_err(crate::rule::LintError::InvalidInput)
    }

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

    crate::impl_rule_config_sections!(MD048Config);

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD048Config>(config);
        let style_explicit = option_is_explicit(config, "MD048", "style");

        Box::new(Self {
            config: rule_config,
            style_explicit,
        })
    }
}

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

    #[test]
    fn test_backtick_style_with_backticks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "```\ncode\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_backtick_style_with_tildes() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~\ncode\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 2); // Opening and closing fence
        assert!(result[0].message.contains("use ``` instead of ~~~"));
        assert_eq!(result[0].line, 1);
        assert_eq!(result[1].line, 3);
    }

    #[test]
    fn test_tilde_style_with_tildes() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "~~~\ncode\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_tilde_style_with_backticks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "```\ncode\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 2); // Opening and closing fence
        assert!(result[0].message.contains("use ~~~ instead of ```"));
    }

    #[test]
    fn test_mdg_overrides_tilde_style_to_backtick() {
        // A Gherkin Doc String is only ever a backtick fence, so a
        // configuration demanding tilde fences cannot be satisfied in this
        // flavor. MDG does not adopt it: a Doc String keeps its backticks and a
        // tilde fence is still corrected into one.
        let backticks = "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a JSON payload\n\n  ```json\n  {\"ok\": true}\n  ```";
        let tildes =
            "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n  ~~~text\n  example\n  ~~~";

        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let ctx = LintContext::new(backticks, crate::config::MarkdownFlavor::MDG, None);
        assert!(rule.check(&ctx).unwrap().is_empty());
        assert_eq!(rule.fix(&ctx).unwrap(), backticks);

        let ctx = LintContext::new(tildes, crate::config::MarkdownFlavor::MDG, None);
        assert_eq!(rule.check(&ctx).unwrap().len(), 2, "the opening and closing fence");
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed,
            "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n  ```text\n  example\n  ```"
        );

        let fixed_ctx = LintContext::new(&fixed, crate::config::MarkdownFlavor::MDG, None);
        assert!(rule.check(&fixed_ctx).unwrap().is_empty());
        assert_eq!(rule.fix(&fixed_ctx).unwrap(), fixed, "MDG fix should be idempotent");

        // Standard honours `tilde` exactly as before, in both directions.
        let standard_ctx = LintContext::new(backticks, crate::config::MarkdownFlavor::Standard, None);
        assert_eq!(rule.check(&standard_ctx).unwrap().len(), 2);
        assert!(rule.fix(&standard_ctx).unwrap().contains("~~~json"));

        let standard_ctx = LintContext::new(tildes, crate::config::MarkdownFlavor::Standard, None);
        assert!(rule.check(&standard_ctx).unwrap().is_empty());
        assert_eq!(rule.fix(&standard_ctx).unwrap(), tildes);
    }

    #[test]
    fn test_mdg_applies_backtick_style() {
        // The explicit backtick style is the one MDG can satisfy, so it is
        // applied unchanged.
        let tildes =
            "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n  ~~~text\n  example\n  ~~~";

        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let ctx = LintContext::new(tildes, crate::config::MarkdownFlavor::MDG, None);
        assert_eq!(rule.check(&ctx).unwrap().len(), 2, "the opening and closing fence");
        assert_eq!(
            rule.fix(&ctx).unwrap(),
            "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n  ```text\n  example\n  ```"
        );
    }

    #[test]
    fn test_mdg_tilde_style_still_disambiguates_fence_length() {
        // The override decides which marker MD048 converges on; it does not
        // touch the length arithmetic that keeps a converted outer fence from
        // being closed by an interior one.
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n~~~\n```rust\ncode\n```\n~~~";

        let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
        let fixed = rule.fix(&mdg_ctx).unwrap();
        assert_eq!(
            fixed,
            "# Feature: Checkout\n\n## Scenario: Purchase\n\n* Given a rendered example\n\n````\n```rust\ncode\n```\n````"
        );

        let fixed_ctx = LintContext::new(&fixed, crate::config::MarkdownFlavor::MDG, None);
        assert!(rule.check(&fixed_ctx).unwrap().is_empty());

        // Standard honours `tilde`: the outer fence is already a tilde fence,
        // so nothing is converted or lengthened.
        let standard_ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        assert!(rule.check(&standard_ctx).unwrap().is_empty());
        assert_eq!(rule.fix(&standard_ctx).unwrap(), content);
    }

    #[test]
    fn test_from_config_records_whether_style_was_configured() {
        // The MDG override applies either way, but the warning is only for a
        // style the user actually asked for, so a configured style has to be
        // told apart from a defaulted one.
        use crate::config::Config;
        use std::collections::BTreeMap;

        let mut values = BTreeMap::new();
        values.insert("style".to_string(), toml::Value::String("tilde".to_string()));
        let mut config = Config::default();
        config.rules.insert(
            "MD048".to_string(),
            crate::config::RuleConfig { severity: None, values },
        );

        let configured = MD048CodeFenceStyle::from_config(&config);
        let configured = configured.as_any().downcast_ref::<MD048CodeFenceStyle>().unwrap();
        assert_eq!(configured.config.style, CodeFenceStyle::Tilde);
        assert!(configured.style_explicit);

        let defaulted = MD048CodeFenceStyle::from_config(&Config::default());
        let defaulted = defaulted.as_any().downcast_ref::<MD048CodeFenceStyle>().unwrap();
        assert!(!defaulted.style_explicit);

        // The override does not depend on the warning: a defaulted `tilde` is
        // enforced as backtick just the same.
        let tilde = MD048CodeFenceStyle::from_config_struct(MD048Config {
            style: CodeFenceStyle::Tilde,
        });
        let content = "# Feature: F\n\n~~~text\nexample\n~~~";
        let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
        assert_eq!(tilde.fix(&mdg_ctx).unwrap(), "# Feature: F\n\n```text\nexample\n```");
    }

    #[test]
    fn test_mdg_consistent_fence_style_ignores_tilde_prevalence() {
        // Standard resolves `consistent` by prevalence (tilde wins here); MDG
        // always resolves it to backtick.
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let content = "# Feature: Checkout\n\n~~~text\nfirst example\n~~~\n\n~~~text\nsecond example\n~~~\n\n## Scenario: Purchase\n\n* Given a JSON payload\n\n  ```json\n  {\"ok\": true}\n  ```";

        let standard_ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        assert_eq!(rule.detect_style(&standard_ctx), Some(CodeFenceStyle::Tilde));

        let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
        let warnings = rule.check(&mdg_ctx).unwrap();
        assert_eq!(warnings.len(), 4, "two tilde blocks, each with two fence lines");
        assert!(
            warnings
                .iter()
                .all(|warning| warning.message.contains("use ``` instead of ~~~"))
        );

        let fixed = rule.fix(&mdg_ctx).unwrap();
        assert!(!fixed.contains("~~~"), "MDG must convert every fence: {fixed:?}");

        let fixed_ctx = LintContext::new(&fixed, crate::config::MarkdownFlavor::MDG, None);
        assert!(rule.check(&fixed_ctx).unwrap().is_empty());
        assert_eq!(rule.fix(&fixed_ctx).unwrap(), fixed, "MDG fix should be idempotent");
    }

    #[test]
    fn test_consistent_style_tie_prefers_backtick() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        // One backtick fence and one tilde fence - tie should prefer backticks
        let content = "```\ncode\n```\n\n~~~\nmore code\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Backticks win due to tie-breaker, so tildes should be flagged
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 5);
        assert_eq!(result[1].line, 7);
    }

    #[test]
    fn test_consistent_style_tilde_most_prevalent() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        // Two tilde fences and one backtick fence - tildes are most prevalent
        let content = "~~~\ncode\n~~~\n\n```\nmore code\n```\n\n~~~\neven more\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Tildes are most prevalent, so backticks should be flagged
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 5);
        assert_eq!(result[1].line, 7);
    }

    #[test]
    fn test_detect_style_backtick() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let ctx = LintContext::new("```\ncode\n```", crate::config::MarkdownFlavor::Standard, None);
        let style = rule.detect_style(&ctx);

        assert_eq!(style, Some(CodeFenceStyle::Backtick));
    }

    #[test]
    fn test_detect_style_tilde() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let ctx = LintContext::new("~~~\ncode\n~~~", crate::config::MarkdownFlavor::Standard, None);
        let style = rule.detect_style(&ctx);

        assert_eq!(style, Some(CodeFenceStyle::Tilde));
    }

    #[test]
    fn test_detect_style_none() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let ctx = LintContext::new("No code fences here", crate::config::MarkdownFlavor::Standard, None);
        let style = rule.detect_style(&ctx);

        assert_eq!(style, None);
    }

    #[test]
    fn test_fix_backticks_to_tildes() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "```\ncode\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "~~~\ncode\n~~~");
    }

    #[test]
    fn test_fix_tildes_to_backticks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~\ncode\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "```\ncode\n```");
    }

    #[test]
    fn test_fix_preserves_fence_length() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "````\ncode with backtick\n```\ncode\n````";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "~~~~\ncode with backtick\n```\ncode\n~~~~");
    }

    #[test]
    fn test_fix_preserves_language_info() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~rust\nfn main() {}\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "```rust\nfn main() {}\n```");
    }

    #[test]
    fn test_indented_code_fences() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "  ```\n  code\n  ```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_fix_indented_fences() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "  ```\n  code\n  ```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "  ~~~\n  code\n  ~~~");
    }

    #[test]
    fn test_nested_fences_not_changed() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "```\ncode with ``` inside\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "~~~\ncode with ``` inside\n~~~");
    }

    #[test]
    fn test_multiple_code_blocks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~\ncode1\n~~~\n\nText\n\n~~~python\ncode2\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 4); // 2 opening + 2 closing fences
    }

    #[test]
    fn test_empty_content() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_preserve_trailing_newline() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~\ncode\n~~~\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "```\ncode\n```\n");
    }

    #[test]
    fn test_no_trailing_newline() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~\ncode\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "```\ncode\n```");
    }

    #[test]
    fn test_default_config() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let (name, _config) = rule.default_config_section().unwrap();
        assert_eq!(name, "MD048");
    }

    /// Tilde outer fence containing backtick inner fence: converting to backtick
    /// style must use a longer fence (4 backticks) to preserve valid nesting.
    #[test]
    fn test_tilde_outer_with_backtick_inner_uses_longer_fence() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~text\n```rust\ncode\n```\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // The outer fence must be 4 backticks to disambiguate from the inner 3-backtick fences.
        assert_eq!(fixed, "````text\n```rust\ncode\n```\n````");
    }

    /// check() warns about the outer tilde fences and the fix replacements use the
    /// correct (longer) fence length.
    #[test]
    fn test_check_tilde_outer_with_backtick_inner_warns_with_correct_replacement() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~text\n```rust\ncode\n```\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        // Only the outer tilde fences are warned about; inner backtick fences are untouched.
        assert_eq!(warnings.len(), 2);
        let open_fix = warnings[0].fix.as_ref().unwrap();
        let close_fix = warnings[1].fix.as_ref().unwrap();
        assert_eq!(open_fix.replacement, "````text");
        assert_eq!(close_fix.replacement, "````");
    }

    /// When the inner backtick fences use 4 backticks, the outer converted fence
    /// must use at least 5.
    #[test]
    fn test_tilde_outer_with_longer_backtick_inner() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~text\n````rust\ncode\n````\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "`````text\n````rust\ncode\n````\n`````");
    }

    /// Backtick outer fence containing tilde inner fence: converting to tilde
    /// style must use a longer tilde fence.
    #[test]
    fn test_backtick_outer_with_tilde_inner_uses_longer_fence() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "```text\n~~~rust\ncode\n~~~\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "~~~~text\n~~~rust\ncode\n~~~\n~~~~");
    }

    // -----------------------------------------------------------------------
    // Fence-length ambiguity detection
    // -----------------------------------------------------------------------

    /// A backtick block containing only an info-string interior sequence (not bare)
    /// is NOT ambiguous: info-string sequences cannot be closing fences per CommonMark,
    /// so the bare ``` at line 3 is simply the closing fence — no lengthening needed.
    #[test]
    fn test_info_string_interior_not_ambiguous() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // line 0: ```text   ← opens block (len=3, info="text")
        // line 1: ```rust   ← interior content, has info "rust" → cannot close outer
        // line 2: code
        // line 3: ```       ← bare, len=3 >= 3 → closes block 1 (per CommonMark)
        // line 4: ```       ← orphaned second block
        let content = "```text\n```rust\ncode\n```\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        // No ambiguity: ```rust cannot close the outer, and the bare ``` IS the
        // unambiguous closing fence. No lengthening needed.
        assert_eq!(warnings.len(), 0, "expected 0 warnings, got {warnings:?}");
    }

    /// fix() leaves a block with only info-string interior sequences unchanged.
    #[test]
    fn test_info_string_interior_fix_unchanged() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "```text\n```rust\ncode\n```\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // No conversion needed (already backtick), no lengthening needed → unchanged.
        assert_eq!(fixed, content);
    }

    /// Same for tilde style: an info-string tilde interior is not ambiguous.
    #[test]
    fn test_tilde_info_string_interior_not_ambiguous() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "~~~text\n~~~rust\ncode\n~~~\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // ~~~rust cannot close outer (has info); ~~~ IS the closing fence → unchanged.
        assert_eq!(fixed, content);
    }

    /// No warning when the outer fence is already longer than any interior fence.
    #[test]
    fn test_no_ambiguity_when_outer_is_longer() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "````text\n```rust\ncode\n```\n````";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        assert_eq!(
            warnings.len(),
            0,
            "should have no warnings when outer is already longer"
        );
    }

    /// An outer block containing a longer info-string sequence and a bare closing
    /// fence is not ambiguous: the bare closing fence closes the outer normally,
    /// and the info-string sequence is just content.
    #[test]
    fn test_longer_info_string_interior_not_ambiguous() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // line 0: ```text    ← opens block (len=3, info="text")
        // line 1: `````rust  ← interior, 5 backticks with info → cannot close outer
        // line 2: code
        // line 3: `````      ← bare, len=5 >= 3, no info → closes block 1
        // line 4: ```        ← orphaned second block
        let content = "```text\n`````rust\ncode\n`````\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // `````rust cannot close the outer. ````` IS the closing fence. No lengthening.
        assert_eq!(fixed, content);
    }

    /// Consistent style: info-string interior sequences are not ambiguous.
    #[test]
    fn test_info_string_interior_consistent_style_no_warning() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let content = "```text\n```rust\ncode\n```\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        assert_eq!(warnings.len(), 0);
    }

    // -----------------------------------------------------------------------
    // Cross-style conversion: bare-only inner sequence counting
    // -----------------------------------------------------------------------

    /// Cross-style conversion where outer has NO info string: interior info-string
    /// sequences are not counted, only bare sequences are.
    #[test]
    fn test_cross_style_bare_inner_requires_lengthening() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // Outer tilde fence (no info). Interior has a 5-backtick info-string sequence
        // AND a 3-backtick bare sequence. Only the bare sequence (len=3) is counted
        // → outer becomes 4, not 6.
        let content = "~~~\n`````rust\ncode\n```\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // 4 backticks (bare seq len=3 → 3+1=4). The 5-backtick info-string seq is
        // not counted since it cannot be a closing fence.
        assert_eq!(fixed, "````\n`````rust\ncode\n```\n````");
    }

    /// Cross-style conversion where outer HAS an info string but interior has only
    /// info-string sequences: no bare inner sequences means no lengthening needed.
    /// The outer converts at its natural length.
    #[test]
    fn test_cross_style_info_only_interior_no_lengthening() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // Outer tilde fence (info "text"). Interior has only info-string backtick
        // sequences — no bare closing sequence. Info-string sequences cannot be
        // closing fences, so no lengthening is needed → outer converts at len=3.
        let content = "~~~text\n```rust\nexample\n```rust\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "```text\n```rust\nexample\n```rust\n```");
    }

    /// Same-style block where outer has an info string but interior contains only
    /// bare sequences SHORTER than the outer fence: no ambiguity, no warning.
    #[test]
    fn test_same_style_info_outer_shorter_bare_interior_no_warning() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // Outer is 4 backticks with info "text". Interior shows raw fence syntax
        // (3-backtick bare lines). These are shorter than outer (3 < 4) so they
        // cannot close the outer block → no ambiguity.
        let content = "````text\n```\nshowing raw fence\n```\n````";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        assert_eq!(
            warnings.len(),
            0,
            "shorter bare interior sequences cannot close a 4-backtick outer"
        );
    }

    /// Same-style block where outer has NO info string and interior has shorter
    /// bare sequences: no ambiguity, no warning.
    #[test]
    fn test_same_style_no_info_outer_shorter_bare_interior_no_warning() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        // Outer is 4 backticks (no info). Interior has 3-backtick bare sequences.
        // 3 < 4 → they cannot close the outer block → no ambiguity.
        let content = "````\n```\nsome code\n```\n````";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        assert_eq!(
            warnings.len(),
            0,
            "shorter bare interior sequences cannot close a 4-backtick outer (no info)"
        );
    }

    /// Regression: over-indented inner same-style sequence (4 spaces) is content,
    /// not a closing fence, and must not trigger ambiguity warnings.
    #[test]
    fn test_overindented_inner_sequence_not_ambiguous() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "```text\n    ```\ncode\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(warnings.len(), 0, "over-indented inner fence should not warn");
        assert_eq!(fixed, content, "over-indented inner fence should remain unchanged");
    }

    /// Regression: when converting outer style, over-indented same-style content
    /// lines must not be mistaken for an outer closing fence.
    #[test]
    fn test_conversion_ignores_overindented_inner_sequence_for_closing_detection() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        let content = "~~~text\n    ~~~\n```rust\ncode\n```\n~~~";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "````text\n    ~~~\n```rust\ncode\n```\n````");
    }

    /// CommonMark: a top-level fence marker indented 4 spaces is an indented code
    /// block line, not a fenced code block marker, so MD048 should ignore it.
    #[test]
    fn test_top_level_four_space_fence_marker_is_ignored() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        let content = "    ```\n    code\n    ```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(warnings.len(), 0);
        assert_eq!(fixed, content);
    }

    // -----------------------------------------------------------------------
    // Roundtrip safety tests: fix() output must produce 0 violations
    // -----------------------------------------------------------------------

    /// Helper: apply fix, then re-check and assert zero violations remain.
    fn assert_fix_roundtrip(rule: &MD048CodeFenceStyle, content: &str) {
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
        let remaining = rule.check(&ctx2).unwrap();
        assert!(
            remaining.is_empty(),
            "After fix, expected 0 violations but got {}.\nOriginal:\n{content}\nFixed:\n{fixed}\nRemaining: {remaining:?}",
            remaining.len(),
        );
    }

    #[test]
    fn test_roundtrip_backticks_to_tildes() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        assert_fix_roundtrip(&rule, "```\ncode\n```");
    }

    #[test]
    fn test_roundtrip_tildes_to_backticks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~\ncode\n~~~");
    }

    #[test]
    fn test_roundtrip_mixed_fences_consistent() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        assert_fix_roundtrip(&rule, "```\ncode\n```\n\n~~~\nmore code\n~~~");
    }

    #[test]
    fn test_roundtrip_with_info_string() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~rust\nfn main() {}\n~~~");
    }

    #[test]
    fn test_roundtrip_longer_fences() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        assert_fix_roundtrip(&rule, "`````\ncode\n`````");
    }

    #[test]
    fn test_roundtrip_nested_inner_fences() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~text\n```rust\ncode\n```\n~~~");
    }

    #[test]
    fn test_roundtrip_indented_fences() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        assert_fix_roundtrip(&rule, "  ```\n  code\n  ```");
    }

    #[test]
    fn test_roundtrip_multiple_blocks() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~\ncode1\n~~~\n\nText\n\n~~~python\ncode2\n~~~");
    }

    #[test]
    fn test_roundtrip_fence_length_ambiguity() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~\n`````rust\ncode\n```\n~~~");
    }

    #[test]
    fn test_roundtrip_trailing_newline() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~\ncode\n~~~\n");
    }

    #[test]
    fn test_roundtrip_tilde_outer_longer_backtick_inner() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Backtick);
        assert_fix_roundtrip(&rule, "~~~text\n````rust\ncode\n````\n~~~");
    }

    #[test]
    fn test_roundtrip_backtick_outer_tilde_inner() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Tilde);
        assert_fix_roundtrip(&rule, "```text\n~~~rust\ncode\n~~~\n```");
    }

    #[test]
    fn test_roundtrip_consistent_tilde_prevalent() {
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        assert_fix_roundtrip(&rule, "~~~\ncode\n~~~\n\n```\nmore code\n```\n\n~~~\neven more\n~~~");
    }

    /// The combined MD013+MD048 fix must be idempotent: applying the fix twice
    /// must produce the same result as applying it once, and must not introduce
    /// double blank lines (MD012).
    #[test]
    fn test_fix_idempotent_no_double_blanks_with_nested_fences() {
        use crate::fix_coordinator::FixCoordinator;
        use crate::rules::Rule;
        use crate::rules::md013_line_length::MD013LineLength;

        // This is the exact pattern that caused double blank lines when MD048 and
        // MD013 were applied together: a tilde outer fence with an inner backtick
        // fence inside a list item that is too long.
        let content = "\
- **edition**: Rust edition to use by default for the code snippets. Default is `\"2015\"`. \
Individual code blocks can be controlled with the `edition2015`, `edition2018`, `edition2021` \
or `edition2024` annotations, such as:

  ~~~text
  ```rust,edition2015
  // This only works in 2015.
  let try = true;
  ```
  ~~~

### Build options
";
        let rules: Vec<Box<dyn Rule>> = vec![
            Box::new(MD013LineLength::new(80, false, false, false, true)),
            Box::new(MD048CodeFenceStyle::new(CodeFenceStyle::Backtick)),
        ];

        let mut first_pass = content.to_string();
        let coordinator = FixCoordinator::new();
        coordinator
            .apply_fixes_iterative(&rules, &[], &mut first_pass, &Default::default(), 10, None)
            .expect("fix should not fail");

        // No double blank lines after first pass.
        let lines: Vec<&str> = first_pass.lines().collect();
        for i in 0..lines.len().saturating_sub(1) {
            assert!(
                !(lines[i].is_empty() && lines[i + 1].is_empty()),
                "Double blank at lines {},{} after first pass:\n{first_pass}",
                i + 1,
                i + 2
            );
        }

        // Second pass must produce identical output (idempotent).
        let mut second_pass = first_pass.clone();
        let rules2: Vec<Box<dyn Rule>> = vec![
            Box::new(MD013LineLength::new(80, false, false, false, true)),
            Box::new(MD048CodeFenceStyle::new(CodeFenceStyle::Backtick)),
        ];
        let coordinator2 = FixCoordinator::new();
        coordinator2
            .apply_fixes_iterative(&rules2, &[], &mut second_pass, &Default::default(), 10, None)
            .expect("fix should not fail");

        assert_eq!(
            first_pass, second_pass,
            "Fix is not idempotent:\nFirst pass:\n{first_pass}\nSecond pass:\n{second_pass}"
        );
    }

    #[test]
    fn test_front_matter_fence_does_not_drive_style_detection() {
        // A complete fence pair inside front matter must not influence consistent
        // style detection. The only real (body) fence is tilde, so the document is
        // self-consistent; counting the front-matter backtick pair would flip the
        // detected style to backtick and wrongly flag the body.
        let rule = MD048CodeFenceStyle::new(CodeFenceStyle::Consistent);
        let content = "---\ndescription: |\n  ```\n  code\n  ```\n---\n\n~~~python\nprint(\"hi\")\n~~~\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "front-matter fence must not drive style detection, got: {result:?}"
        );
    }
}