rumdl 0.2.60

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
use crate::filtered_lines::FilteredLinesExt;
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
/// Rule MD010: No tabs
///
/// See [docs/md010.md](../../docs/md010.md) for full documentation, configuration, and examples.
use crate::utils::range_utils::calculate_match_range;

pub mod md010_config;
pub use md010_config::MD010Config;

/// Rule MD010: Hard tabs
#[derive(Clone, Default)]
pub struct MD010NoHardTabs {
    config: MD010Config,
}

impl MD010NoHardTabs {
    pub fn new(spaces_per_tab: usize) -> Self {
        Self {
            config: MD010Config {
                spaces_per_tab: crate::types::PositiveUsize::from_const(spaces_per_tab),
                code_blocks: false,
                ..Default::default()
            },
        }
    }

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

    fn count_leading_tabs(line: &str) -> usize {
        let mut count = 0;
        for c in line.chars() {
            if c == '\t' {
                count += 1;
            } else {
                break;
            }
        }
        count
    }

    /// The language an info string declares, or `""` when it declares none.
    ///
    /// Normally that is the first whitespace-separated word, so
    /// ```` ```makefile title="Makefile" ```` gives `makefile`. Two flavors write
    /// a language inside braces instead, and each is read only where it is real
    /// syntax: a Pandoc code-attribute block names it as the first `.class`
    /// (`{#id .makefile}` gives `makefile`), and a Quarto executable chunk names
    /// its engine (`{r, echo=FALSE}` gives `r`).
    fn fence_language(info_string: &str, flavor: crate::config::MarkdownFlavor) -> std::borrow::Cow<'_, str> {
        let info = info_string.trim();

        if flavor.is_pandoc_compatible()
            && let Some(class) = crate::utils::pandoc::pandoc_code_class_lang(info)
        {
            return std::borrow::Cow::Borrowed(class);
        }

        if flavor == crate::config::MarkdownFlavor::Quarto
            && crate::utils::quarto_chunks::is_executable_chunk(info)
            && let Some(header) = crate::utils::quarto_chunks::parse_inline_chunk_header(info)
        {
            return std::borrow::Cow::Owned(header.engine);
        }

        std::borrow::Cow::Borrowed(info.split_whitespace().next().unwrap_or(""))
    }

    /// Lines (1-indexed) belonging to a code block whose language is listed in
    /// `ignore-code-languages`.
    ///
    /// Covers CommonMark fences plus the Azure DevOps colon fences the parser
    /// never sees. An indented code block has no info string and can never match.
    fn ignored_language_lines(&self, ctx: &crate::lint_context::LintContext) -> std::collections::HashSet<usize> {
        let mut ignored = std::collections::HashSet::new();

        for detail in ctx.code_block_details.iter().chain(ctx.colon_fence_details()) {
            let label = Self::fence_language(&detail.info_string, ctx.flavor);
            if label.is_empty()
                || !self
                    .config
                    .ignore_code_languages
                    .iter()
                    .any(|listed| listed.eq_ignore_ascii_case(label.as_ref()))
            {
                continue;
            }

            let start_line = ctx
                .line_offsets
                .partition_point(|&off| off <= detail.start)
                .saturating_sub(1);
            let end_byte = detail.end.saturating_sub(1);
            let end_line = ctx
                .line_offsets
                .partition_point(|&off| off <= end_byte)
                .saturating_sub(1);
            for line in start_line..=end_line {
                ignored.insert(line + 1);
            }
        }

        ignored
    }

    fn find_and_group_tabs(line: &str) -> Vec<(usize, usize)> {
        let mut groups = Vec::new();
        let mut current_group_start: Option<usize> = None;
        let mut last_tab_pos = 0;

        for (i, c) in line.chars().enumerate() {
            if c == '\t' {
                if let Some(start) = current_group_start {
                    // We're in a group - check if this tab is consecutive
                    if i == last_tab_pos + 1 {
                        // Consecutive tab, continue the group
                        last_tab_pos = i;
                    } else {
                        // Gap found, save current group and start new one
                        groups.push((start, last_tab_pos + 1));
                        current_group_start = Some(i);
                        last_tab_pos = i;
                    }
                } else {
                    // Start a new group
                    current_group_start = Some(i);
                    last_tab_pos = i;
                }
            }
        }

        // Add the last group if there is one
        if let Some(start) = current_group_start {
            groups.push((start, last_tab_pos + 1));
        }

        groups
    }
}

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

    fn description(&self) -> &'static str {
        "No tabs"
    }

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

        let mut filtered = ctx
            .filtered_lines()
            .skip_front_matter()
            .skip_html_comments()
            .skip_mdx_comments()
            .skip_html_blocks()
            .skip_pymdown_blocks()
            .skip_mkdocstrings()
            .skip_esm_blocks();

        if !self.config.code_blocks {
            filtered = filtered.skip_code_blocks();
        }

        // Testing code-blocks here only avoids building a set that cannot matter:
        // with it false the walk has already dropped every code block line.
        let ignored_lines = if self.config.code_blocks && !self.config.ignore_code_languages.is_empty() {
            self.ignored_language_lines(ctx)
        } else {
            std::collections::HashSet::new()
        };

        for filtered_line in filtered {
            if ignored_lines.contains(&filtered_line.line_num) {
                continue;
            }
            let line_num = filtered_line.line_num - 1;
            let line = filtered_line.content;

            // Process tabs directly without intermediate collection
            let tab_groups = Self::find_and_group_tabs(line);
            if tab_groups.is_empty() {
                continue;
            }

            let leading_tabs = Self::count_leading_tabs(line);

            // Generate warning for each group of consecutive tabs
            for (start_pos, end_pos) in tab_groups {
                let tab_count = end_pos - start_pos;
                let is_leading = start_pos < leading_tabs;

                // Calculate precise character range for the tab group
                let (start_line, start_col, end_line, end_col) =
                    calculate_match_range(line_num + 1, line, start_pos, tab_count);

                let message = if line.trim().is_empty() {
                    if tab_count == 1 {
                        "Empty line contains tab".to_string()
                    } else {
                        format!("Empty line contains {tab_count} tabs")
                    }
                } else if is_leading {
                    if tab_count == 1 {
                        format!(
                            "Found leading tab, use {} spaces instead",
                            self.config.spaces_per_tab.get()
                        )
                    } else {
                        format!(
                            "Found {} leading tabs, use {} spaces instead",
                            tab_count,
                            tab_count * self.config.spaces_per_tab.get()
                        )
                    }
                } else if tab_count == 1 {
                    "Found tab for alignment, use spaces instead".to_string()
                } else {
                    format!("Found {tab_count} tabs for alignment, use spaces instead")
                };

                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line: start_line,
                    column: start_col,
                    end_line,
                    end_column: end_col,
                    message,
                    severity: Severity::Warning,
                    fix: Some(Fix::new(
                        ctx.line_column_byte_range_with_length(line_num + 1, start_pos + 1, tab_count),
                        " ".repeat(tab_count * self.config.spaces_per_tab.get()),
                    )),
                });
            }
        }

        Ok(warnings)
    }

    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
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Skip if content is empty or has no tabs
        ctx.content.is_empty() || !ctx.has_char('\t')
    }

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

    crate::impl_rule_config_methods!(MD010Config);
}

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

    #[test]
    fn test_no_tabs() {
        let rule = MD010NoHardTabs::default();
        let content = "This is a line\nAnother line\nNo tabs here";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_single_tab() {
        let rule = MD010NoHardTabs::default();
        let content = "Line with\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[0].column, 10);
        assert_eq!(result[0].message, "Found tab for alignment, use spaces instead");
    }

    #[test]
    fn test_leading_tabs_skipped_in_indented_code_by_default() {
        // Both lines start with a tab at column 0: parsed as an indented code block.
        // Default code_blocks=false skips tabs in indented code blocks.
        let content = "\tIndented line\n\t\tDouble indented";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::default();
        let result_off = rule_off.check(&ctx).unwrap();
        assert!(
            result_off.is_empty(),
            "indented code block skipped by default, got {result_off:?}"
        );
        assert_eq!(
            rule_off.fix(&ctx).unwrap(),
            "\tIndented line\n\t\tDouble indented",
            "fix must preserve indented code block content"
        );

        // code_blocks=true: tabs inside indented code blocks are flagged.
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let result_on = rule_on.check(&ctx).unwrap();
        assert_eq!(result_on.len(), 2, "got {result_on:?}");
        assert_eq!(result_on[0].line, 1);
        assert_eq!(result_on[0].message, "Found leading tab, use 4 spaces instead");
        assert_eq!(result_on[1].line, 2);
        assert_eq!(result_on[1].message, "Found 2 leading tabs, use 8 spaces instead");
        assert_eq!(rule_on.fix(&ctx).unwrap(), "    Indented line\n        Double indented");
    }

    #[test]
    fn test_fix_tabs() {
        // Line 1 starts with a tab at column 0 -> indented code block, skipped by default.
        // Line 2 has a mid-line tab (alignment) -> flagged and fixed.
        let content = "\tIndented\nNormal\tline\nNo tabs";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::default();
        let warnings_off = rule_off.check(&ctx).unwrap();
        assert_eq!(warnings_off.len(), 1, "got {warnings_off:?}");
        assert_eq!(warnings_off[0].line, 2);
        assert_eq!(warnings_off[0].message, "Found tab for alignment, use spaces instead");
        assert_eq!(
            rule_off.fix(&ctx).unwrap(),
            "\tIndented\nNormal    line\nNo tabs",
            "indented code block line preserved; alignment tab fixed"
        );

        // code_blocks=true: line 1 is also flagged.
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let warnings_on = rule_on.check(&ctx).unwrap();
        assert_eq!(warnings_on.len(), 2, "got {warnings_on:?}");
        assert_eq!(warnings_on[0].line, 1);
        assert_eq!(warnings_on[1].line, 2);
        assert_eq!(rule_on.fix(&ctx).unwrap(), "    Indented\nNormal    line\nNo tabs");
    }

    #[test]
    fn test_custom_spaces_per_tab() {
        // Single tab at column 0 -> indented code block, skipped by default.
        let content = "\tIndented";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::new(4);
        assert!(
            rule_off.check(&ctx).unwrap().is_empty(),
            "indented code block skipped by default"
        );
        assert_eq!(
            rule_off.fix(&ctx).unwrap(),
            "\tIndented",
            "indented code block preserved by default"
        );

        // code_blocks=true: tab is flagged and fixed.
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        assert_eq!(rule_on.check(&ctx).unwrap().len(), 1);
        assert_eq!(rule_on.fix(&ctx).unwrap(), "    Indented");
    }

    #[test]
    fn test_fenced_code_block_tabs_skipped_by_default() {
        let rule = MD010NoHardTabs::default();
        let content = "Normal\tline\n```\nCode\twith\ttab\n```\nAnother\tline";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // By default (code_blocks=false) tabs inside code blocks are skipped
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[1].line, 5);

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Normal    line\n```\nCode\twith\ttab\n```\nAnother    line");
    }

    #[test]
    fn test_fenced_only_content_skipped_by_default() {
        let rule = MD010NoHardTabs::default();
        let content = "```\nCode\twith\ttab\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // By default (code_blocks=false) tabs in fenced code blocks are skipped
        // (e.g., Makefiles require tabs, Go uses tabs by convention)
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_html_comments_ignored() {
        let rule = MD010NoHardTabs::default();
        let content = "Normal\tline\n<!-- HTML\twith\ttab -->\nAnother\tline";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should not flag tabs in HTML comments
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[1].line, 3);
    }

    #[test]
    fn test_multiline_html_comments() {
        let rule = MD010NoHardTabs::default();
        let content = "Before\n<!--\nMultiline\twith\ttabs\ncomment\t-->\nAfter\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should only flag the tab after the comment
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 5);
    }

    #[test]
    fn test_empty_lines_with_tabs() {
        let rule = MD010NoHardTabs::default();
        let content = "Normal line\n\t\t\n\t\nAnother line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].message, "Empty line contains 2 tabs");
        assert_eq!(result[1].message, "Empty line contains tab");
    }

    #[test]
    fn test_mixed_tabs_and_spaces() {
        // " \t..." (space then tab) and "\t ..." (tab then space): both parsed as
        // indented code blocks by the shared spec-compliant flag.
        // Default code_blocks=false skips them.
        let content = " \tMixed indentation\n\t Mixed again";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::default();
        let result_off = rule_off.check(&ctx).unwrap();
        assert!(
            result_off.is_empty(),
            "indented code block lines skipped, got {result_off:?}"
        );
        assert_eq!(
            rule_off.fix(&ctx).unwrap(),
            " \tMixed indentation\n\t Mixed again",
            "content preserved unchanged"
        );

        // code_blocks=true: both lines flagged.
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let result_on = rule_on.check(&ctx).unwrap();
        assert_eq!(result_on.len(), 2, "got {result_on:?}");
        assert_eq!(rule_on.fix(&ctx).unwrap(), "     Mixed indentation\n     Mixed again");
    }

    #[test]
    fn test_consecutive_tabs() {
        let rule = MD010NoHardTabs::default();
        let content = "Text\t\t\tthree tabs\tand\tanother";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should group consecutive tabs
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].message, "Found 3 tabs for alignment, use spaces instead");
    }

    #[test]
    fn test_find_and_group_tabs() {
        // Test finding and grouping tabs in one pass
        let groups = MD010NoHardTabs::find_and_group_tabs("a\tb\tc");
        assert_eq!(groups, vec![(1, 2), (3, 4)]);

        let groups = MD010NoHardTabs::find_and_group_tabs("\t\tabc");
        assert_eq!(groups, vec![(0, 2)]);

        let groups = MD010NoHardTabs::find_and_group_tabs("no tabs");
        assert!(groups.is_empty());

        // Test with consecutive and non-consecutive tabs
        let groups = MD010NoHardTabs::find_and_group_tabs("\t\t\ta\t\tb");
        assert_eq!(groups, vec![(0, 3), (4, 6)]);

        let groups = MD010NoHardTabs::find_and_group_tabs("\ta\tb\tc");
        assert_eq!(groups, vec![(0, 1), (2, 3), (4, 5)]);
    }

    #[test]
    fn test_count_leading_tabs() {
        assert_eq!(MD010NoHardTabs::count_leading_tabs("\t\tcode"), 2);
        assert_eq!(MD010NoHardTabs::count_leading_tabs(" \tcode"), 0);
        assert_eq!(MD010NoHardTabs::count_leading_tabs("no tabs"), 0);
        assert_eq!(MD010NoHardTabs::count_leading_tabs("\t"), 1);
    }

    #[test]
    fn test_default_config() {
        let rule = MD010NoHardTabs::default();
        let config = rule.default_config_section();
        assert!(config.is_some());
        let (name, _value) = config.unwrap();
        assert_eq!(name, "MD010");
    }

    #[test]
    fn test_from_config() {
        // "\tTab" at column 0 -> indented code block, skipped by default (code_blocks=false).
        let content_plain = "\tTab";
        let ctx_plain = LintContext::new(content_plain, crate::config::MarkdownFlavor::Standard, None);
        let rule_8_off = MD010NoHardTabs::new(8); // spaces_per_tab=8, code_blocks=false
        assert!(
            rule_8_off.check(&ctx_plain).unwrap().is_empty(),
            "indented code block skipped"
        );
        assert_eq!(
            rule_8_off.fix(&ctx_plain).unwrap(),
            "\tTab",
            "content preserved unchanged"
        );

        // code_blocks=true: the tab is flagged and replaced with 8 spaces.
        let rule_8_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(8),
            code_blocks: true,
            ..Default::default()
        });
        assert_eq!(rule_8_on.check(&ctx_plain).unwrap().len(), 1);
        assert_eq!(rule_8_on.fix(&ctx_plain).unwrap(), "        Tab");

        // Fenced code block: tab skipped by default.
        let content_fenced = "```\n\tTab in code\n```";
        let ctx_fenced = LintContext::new(content_fenced, crate::config::MarkdownFlavor::Standard, None);
        assert!(
            rule_8_off.check(&ctx_fenced).unwrap().is_empty(),
            "fenced code block skipped"
        );
        assert_eq!(rule_8_off.fix(&ctx_fenced).unwrap(), "```\n\tTab in code\n```");

        // code_blocks=true: tab inside fence is flagged.
        let result_on = rule_8_on.check(&ctx_fenced).unwrap();
        assert_eq!(result_on.len(), 1, "got {result_on:?}");
        assert_eq!(result_on[0].line, 2);
        assert_eq!(rule_8_on.fix(&ctx_fenced).unwrap(), "```\n        Tab in code\n```");
    }

    #[test]
    fn test_performance_large_document() {
        let rule = MD010NoHardTabs::default();
        let mut content = String::new();
        for i in 0..1000 {
            content.push_str(&format!("Line {i}\twith\ttabs\n"));
        }
        let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2000);
    }

    #[test]
    fn test_preserve_content() {
        let rule = MD010NoHardTabs::default();
        let content = "**Bold**\ttext\n*Italic*\ttext\n[Link](url)\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "**Bold**    text\n*Italic*    text\n[Link](url)    tab");
    }

    #[test]
    fn test_edge_cases() {
        let rule = MD010NoHardTabs::default();

        // Tab at end of line
        let content = "Text\t";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);

        // Only tabs
        let content = "\t\t\t";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].message, "Empty line contains 3 tabs");
    }

    #[test]
    fn test_fenced_code_block_tabs_preserved_in_fix_by_default() {
        let rule = MD010NoHardTabs::default();

        let content = "Text\twith\ttab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore\ttabs";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // By default (code_blocks=false) tabs in fenced code blocks are preserved
        // (e.g., Makefiles require tabs, Go uses tabs by convention)
        let expected = "Text    with    tab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore    tabs";
        assert_eq!(fixed, expected);
    }

    #[test]
    fn test_tilde_fence_longer_than_3() {
        let rule = MD010NoHardTabs::default();
        // 5-tilde fenced code block should be recognized and tabs inside should be skipped
        let content = "~~~~~\ncode\twith\ttab\n~~~~~\ntext\twith\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only tabs on line 4 (outside the code block) should be flagged
        assert_eq!(
            result.len(),
            2,
            "Expected 2 warnings but got {}: {:?}",
            result.len(),
            result
        );
        assert_eq!(result[0].line, 4);
        assert_eq!(result[1].line, 4);
    }

    #[test]
    fn test_backtick_fence_longer_than_3() {
        let rule = MD010NoHardTabs::default();
        // 5-backtick fenced code block
        let content = "`````\ncode\twith\ttab\n`````\ntext\twith\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            2,
            "Expected 2 warnings but got {}: {:?}",
            result.len(),
            result
        );
        assert_eq!(result[0].line, 4);
        assert_eq!(result[1].line, 4);
    }

    #[test]
    fn test_indented_code_block_tabs_skipped_by_default() {
        // "    code\twith\ttab" is indented with 4 spaces -> indented code block.
        // Default code_blocks=false skips it; only the tab on the normal line is flagged.
        let content = "    code\twith\ttab\n\nNormal\ttext";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::default();
        let result_off = rule_off.check(&ctx).unwrap();
        assert_eq!(
            result_off.len(),
            1,
            "expected 1 warning (only normal-text tab), got {}: {:?}",
            result_off.len(),
            result_off
        );
        assert_eq!(result_off[0].line, 3);
        assert_eq!(result_off[0].message, "Found tab for alignment, use spaces instead");

        // code_blocks=true: all 3 tabs flagged (2 on line 1, 1 on line 3).
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let result_on = rule_on.check(&ctx).unwrap();
        assert_eq!(
            result_on.len(),
            3,
            "expected 3 warnings with code_blocks=true, got {}: {:?}",
            result_on.len(),
            result_on
        );
        assert_eq!(result_on[0].line, 1);
        assert_eq!(result_on[1].line, 1);
        assert_eq!(result_on[2].line, 3);
    }

    #[test]
    fn test_html_comment_end_then_start_same_line() {
        let rule = MD010NoHardTabs::default();
        // Tabs inside consecutive HTML comments should not be flagged
        let content =
            "<!-- first comment\nend --> text <!-- second comment\n\ttabbed content inside second comment\n-->";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Expected 0 warnings but got {}: {:?}",
            result.len(),
            result
        );
    }

    #[test]
    fn test_fix_tilde_fence_longer_than_3() {
        let rule = MD010NoHardTabs::default();
        let content = "~~~~~\ncode\twith\ttab\n~~~~~\ntext\twith\ttab";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Tabs inside code block preserved, tabs outside replaced
        assert_eq!(fixed, "~~~~~\ncode\twith\ttab\n~~~~~\ntext    with    tab");
    }

    #[test]
    fn test_fix_indented_code_block_tabs_replaced() {
        // Default code_blocks=false: indented code block tabs preserved, normal-text tab fixed.
        let content = "    code\twith\ttab\n\nNormal\ttext";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule_off = MD010NoHardTabs::default();
        assert_eq!(
            rule_off.fix(&ctx).unwrap(),
            "    code\twith\ttab\n\nNormal    text",
            "indented code block preserved; only normal-text tab fixed"
        );

        // code_blocks=true: all tabs replaced including those in the indented code block.
        let rule_on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        assert_eq!(
            rule_on.fix(&ctx).unwrap(),
            "    code    with    tab\n\nNormal    text",
            "all tabs replaced with code_blocks=true"
        );
    }

    #[test]
    fn test_issue_630_default_skips_both_code_blocks() {
        // Default code_blocks = false: tabs skipped in BOTH block types.
        let rule = MD010NoHardTabs::default();
        let content = "Foo bar\n\n    for range 100 {\n    \tfoo()\n    }\n\nThis is a fenced\n\n```\nfor range 100 {\n\tfoo()\n}\n```\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "both code blocks skipped, got {result:?}");
    }

    #[test]
    fn test_issue_630_code_blocks_true_flags_both() {
        // code_blocks = true: tabs flagged in BOTH block types.
        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let content = "Foo bar\n\n    for range 100 {\n    \tfoo()\n    }\n\nThis is a fenced\n\n```\nfor range 100 {\n\tfoo()\n}\n```\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Line 4 "    \tfoo()": one alignment tab group inside the indented block.
        // Line 11 "\tfoo()": one leading tab group inside the fenced block.
        assert_eq!(result.len(), 2, "got {result:?}");
        assert_eq!(result[0].line, 4);
        assert_eq!(result[1].line, 11);
    }

    #[test]
    fn test_code_blocks_toggle_fenced() {
        let content = "Normal\tline\n```\nCode\twith\ttab\n```\nAnother\tline";

        // Default false: only the two tab groups outside the fence.
        let off = MD010NoHardTabs::default();
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let r_off = off.check(&ctx).unwrap();
        assert_eq!(r_off.len(), 2, "got {r_off:?}");
        assert_eq!(r_off[0].line, 1);
        assert_eq!(r_off[1].line, 5);
        assert_eq!(
            off.fix(&ctx).unwrap(),
            "Normal    line\n```\nCode\twith\ttab\n```\nAnother    line"
        );

        // true: also the two groups on the fenced content line.
        let on = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ..Default::default()
        });
        let r_on = on.check(&ctx).unwrap();
        assert_eq!(r_on.len(), 4, "got {r_on:?}");
        assert_eq!(r_on[0].line, 1);
        assert_eq!(r_on[1].line, 3);
        assert_eq!(r_on[2].line, 3);
        assert_eq!(r_on[3].line, 5);
        assert_eq!(
            on.fix(&ctx).unwrap(),
            "Normal    line\n```\nCode    with    tab\n```\nAnother    line"
        );
    }

    #[test]
    fn test_code_blocks_toggle_makefile_fence_preserved_by_default() {
        let content = "Text\twith\ttab\n```makefile\ntarget:\n\tcommand\n```\nMore\ttabs";
        let off = MD010NoHardTabs::default();
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        // Default preserves the Makefile recipe tab; only prose tabs fixed.
        assert_eq!(
            off.fix(&ctx).unwrap(),
            "Text    with    tab\n```makefile\ntarget:\n\tcommand\n```\nMore    tabs"
        );
    }

    #[test]
    fn test_ignore_code_languages_skips_a_listed_fence() {
        // code-blocks = true opts into checking tabs inside fences, but a tab in a
        // Makefile recipe is required syntax rather than a formatting mistake.
        let content = "Text\twith\ttab\n```makefile\ntarget:\n\tcommand\n```\n```sh\necho\thello\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            spaces_per_tab: crate::types::PositiveUsize::from_const(4),
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
        });

        let result = rule.check(&ctx).unwrap();
        let lines: Vec<usize> = result.iter().map(|w| w.line).collect();
        assert_eq!(
            lines,
            vec![1, 1, 7],
            "the makefile recipe tab on line 4 must be skipped, got {result:?}"
        );
        assert_eq!(
            rule.fix(&ctx).unwrap(),
            "Text    with    tab\n```makefile\ntarget:\n\tcommand\n```\n```sh\necho    hello\n```"
        );
    }

    #[test]
    fn test_ignore_code_languages_matches_the_label_case_insensitively() {
        // ```Makefile and ```makefile name the same language.
        let content = "```Makefile\ntarget:\n\tcommand\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert!(
            rule.check(&ctx).unwrap().is_empty(),
            "an uppercase fence label must match a lowercase configured language"
        );
    }

    #[test]
    fn test_ignore_code_languages_matches_only_the_first_info_string_word() {
        // The label is the first word, so attributes after it do not defeat the match.
        let labelled = "```makefile title=\"Makefile\"\ntarget:\n\tcommand\n```";
        let ctx = LintContext::new(labelled, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert!(
            rule.check(&ctx).unwrap().is_empty(),
            "a fence carrying attributes after its language must still match"
        );

        // A different language on the same shape is still reported, so the match is
        // not simply accepting every labelled fence.
        let other = "```shell title=\"Makefile\"\ntarget:\n\tcommand\n```";
        let other_ctx = LintContext::new(other, crate::config::MarkdownFlavor::Standard, None);
        assert_eq!(
            rule.check(&other_ctx).unwrap().len(),
            1,
            "an unlisted language must still be reported"
        );
    }

    #[test]
    fn test_ignore_code_languages_cannot_match_an_indented_code_block() {
        // An indented code block has no info string, so it has no language to list.
        // Documented in docs/md010.md as a real gap.
        let content = "Text.\n\n    target:\n    \tcommand\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert_eq!(
            rule.check(&ctx).unwrap().len(),
            1,
            "an indented block carries no language, so the list cannot exempt it"
        );
    }

    #[test]
    fn test_ignore_code_languages_is_inert_without_code_blocks() {
        // With code-blocks at its default the whole block is already skipped, so the
        // list changes nothing in either direction.
        let content = "```makefile\ntarget:\n\tcommand\n```\n```sh\necho\thello\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert!(
            rule.check(&ctx).unwrap().is_empty(),
            "listing a language must not start checking blocks that code-blocks skips"
        );
    }

    #[test]
    fn test_ignore_code_languages_matches_a_pandoc_class_attribute() {
        // Pandoc declares a fence's language as the first `.class` of its attribute
        // block, so ```{.makefile} names the same language as ```makefile.
        let content = "```{.makefile}\ntarget:\n\tcommand\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert!(
            rule.check(&ctx).unwrap().is_empty(),
            "the first .class of a Pandoc attribute block is the fence language"
        );

        // An unlisted class on the same shape is still reported.
        let other = "```{.shell}\ntarget:\n\tcommand\n```";
        let other_ctx = LintContext::new(other, crate::config::MarkdownFlavor::Pandoc, None);
        assert_eq!(
            rule.check(&other_ctx).unwrap().len(),
            1,
            "an unlisted class must still be reported"
        );
    }

    #[test]
    fn test_ignore_code_languages_class_attribute_needs_a_pandoc_compatible_flavor() {
        // Under `standard` braces are not attribute syntax, so the label stays raw
        // and cannot match a bare language name.
        let content = "```{.makefile}\ntarget:\n\tcommand\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        assert_eq!(
            rule.check(&ctx).unwrap().len(),
            1,
            "attribute syntax must only be read under a Pandoc-compatible flavor"
        );
    }

    #[test]
    fn test_ignore_code_languages_matches_a_quarto_exec_chunk() {
        // A Quarto executable chunk names its engine inside the braces.
        let content = "```{r}\nx <- 1\n\tindented\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);

        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["r".to_string()],
            ..Default::default()
        });

        assert!(
            rule.check(&ctx).unwrap().is_empty(),
            "a `{{r}}` chunk declares language r"
        );

        // A chunk for a different engine is still reported.
        let python = "```{python}\nx = 1\n\tindented\n```";
        let python_ctx = LintContext::new(python, crate::config::MarkdownFlavor::Quarto, None);
        assert_eq!(
            rule.check(&python_ctx).unwrap().len(),
            1,
            "an unlisted engine must still be reported"
        );
    }

    #[test]
    fn test_ignore_code_languages_matches_an_azure_colon_fence() {
        // Azure DevOps colon fences carry their language on the opener.
        let rule = MD010NoHardTabs::from_config_struct(MD010Config {
            code_blocks: true,
            ignore_code_languages: vec!["makefile".to_string()],
            ..Default::default()
        });

        for content in [
            ":::makefile\ntarget:\n\tcommand\n:::",
            "::: makefile\ntarget:\n\tcommand\n:::",
        ] {
            let ctx = LintContext::new(content, crate::config::MarkdownFlavor::AzureDevOps, None);
            assert!(
                rule.check(&ctx).unwrap().is_empty(),
                "a colon fence's language must be honoured, got {:?} for {content:?}",
                rule.check(&ctx).unwrap()
            );
        }

        // An unlisted colon fence language is still reported.
        let other = ":::mermaid\nflowchart LR\n\tA --> B\n:::";
        let other_ctx = LintContext::new(other, crate::config::MarkdownFlavor::AzureDevOps, None);
        assert_eq!(
            rule.check(&other_ctx).unwrap().len(),
            1,
            "an unlisted colon fence language must still be reported"
        );
    }

    #[test]
    fn test_tabs_in_front_matter_are_not_flagged() {
        // Hard tabs inside YAML front matter are metadata, not Markdown body,
        // and must not be reported.
        let rule = MD010NoHardTabs::default();
        let content = "---\ntitle:\t\"Tabbed value\"\n---\n\n# Heading\n\nBody text.\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "tabs inside front matter must not be flagged, got: {result:?}"
        );
    }
}