rumdl_lib/rules/
md010_no_hard_tabs.rs

1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::rule_config_serde::RuleConfig;
3/// Rule MD010: No tabs
4///
5/// See [docs/md010.md](../../docs/md010.md) for full documentation, configuration, and examples.
6use crate::utils::range_utils::calculate_match_range;
7use crate::utils::regex_cache::{HTML_COMMENT_END, HTML_COMMENT_START};
8
9mod md010_config;
10use md010_config::MD010Config;
11
12// HTML comment patterns are now imported from regex_cache
13
14/// Rule MD010: Hard tabs
15#[derive(Clone, Default)]
16pub struct MD010NoHardTabs {
17    config: MD010Config,
18}
19
20impl MD010NoHardTabs {
21    pub fn new(spaces_per_tab: usize) -> Self {
22        Self {
23            config: MD010Config {
24                spaces_per_tab: crate::types::PositiveUsize::from_const(spaces_per_tab),
25            },
26        }
27    }
28
29    pub const fn from_config_struct(config: MD010Config) -> Self {
30        Self { config }
31    }
32
33    // Identify lines that are part of HTML comments
34    fn find_html_comment_lines(lines: &[&str]) -> Vec<bool> {
35        let mut in_html_comment = false;
36        let mut html_comment_lines = vec![false; lines.len()];
37
38        for (i, line) in lines.iter().enumerate() {
39            // Check if this line has a comment start
40            let has_comment_start = HTML_COMMENT_START.is_match(line);
41            // Check if this line has a comment end
42            let has_comment_end = HTML_COMMENT_END.is_match(line);
43
44            if has_comment_start && !has_comment_end && !in_html_comment {
45                // Comment starts on this line and doesn't end
46                in_html_comment = true;
47                html_comment_lines[i] = true;
48            } else if has_comment_end && in_html_comment {
49                // Comment ends on this line
50                html_comment_lines[i] = true;
51                in_html_comment = false;
52            } else if has_comment_start && has_comment_end {
53                // Both start and end on the same line
54                html_comment_lines[i] = true;
55            } else if in_html_comment {
56                // We're inside a multi-line comment
57                html_comment_lines[i] = true;
58            }
59        }
60
61        html_comment_lines
62    }
63
64    fn count_leading_tabs(line: &str) -> usize {
65        let mut count = 0;
66        for c in line.chars() {
67            if c == '\t' {
68                count += 1;
69            } else {
70                break;
71            }
72        }
73        count
74    }
75
76    fn find_and_group_tabs(line: &str) -> Vec<(usize, usize)> {
77        let mut groups = Vec::new();
78        let mut current_group_start: Option<usize> = None;
79        let mut last_tab_pos = 0;
80
81        for (i, c) in line.chars().enumerate() {
82            if c == '\t' {
83                if let Some(start) = current_group_start {
84                    // We're in a group - check if this tab is consecutive
85                    if i == last_tab_pos + 1 {
86                        // Consecutive tab, continue the group
87                        last_tab_pos = i;
88                    } else {
89                        // Gap found, save current group and start new one
90                        groups.push((start, last_tab_pos + 1));
91                        current_group_start = Some(i);
92                        last_tab_pos = i;
93                    }
94                } else {
95                    // Start a new group
96                    current_group_start = Some(i);
97                    last_tab_pos = i;
98                }
99            }
100        }
101
102        // Add the last group if there is one
103        if let Some(start) = current_group_start {
104            groups.push((start, last_tab_pos + 1));
105        }
106
107        groups
108    }
109
110    /// Find lines that are inside fenced code blocks (``` or ~~~)
111    /// Returns a Vec<bool> where index i indicates if line i is inside a fenced code block
112    fn find_fenced_code_block_lines(lines: &[&str]) -> Vec<bool> {
113        let mut in_fenced_block = false;
114        let mut fence_char: Option<char> = None;
115        let mut result = vec![false; lines.len()];
116
117        for (i, line) in lines.iter().enumerate() {
118            let trimmed = line.trim_start();
119
120            if !in_fenced_block {
121                // Check for opening fence (``` or ~~~)
122                if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
123                    in_fenced_block = true;
124                    fence_char = Some(trimmed.chars().next().unwrap());
125                    result[i] = true; // Mark the fence line itself as "in fenced block"
126                }
127            } else {
128                result[i] = true;
129                // Check for closing fence (must match opening fence char)
130                if let Some(fc) = fence_char {
131                    let fence_str: String = std::iter::repeat_n(fc, 3).collect();
132                    if trimmed.starts_with(&fence_str) && trimmed.trim() == fence_str {
133                        in_fenced_block = false;
134                        fence_char = None;
135                    }
136                }
137            }
138        }
139
140        result
141    }
142}
143
144impl Rule for MD010NoHardTabs {
145    fn name(&self) -> &'static str {
146        "MD010"
147    }
148
149    fn description(&self) -> &'static str {
150        "No tabs"
151    }
152
153    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
154        let content = ctx.content;
155        let _line_index = &ctx.line_index;
156
157        let mut warnings = Vec::new();
158        let lines: Vec<&str> = content.lines().collect();
159
160        // Pre-compute which lines are part of HTML comments
161        let html_comment_lines = Self::find_html_comment_lines(&lines);
162
163        // Pre-compute which lines are inside fenced code blocks (``` or ~~~)
164        // We only skip fenced code blocks - code has its own formatting rules
165        // (e.g., Makefiles require tabs, Go uses tabs by convention)
166        // We still flag tab-indented content because it might be accidental
167        let fenced_code_block_lines = Self::find_fenced_code_block_lines(&lines);
168
169        for (line_num, &line) in lines.iter().enumerate() {
170            // Skip if in HTML comment
171            if html_comment_lines[line_num] {
172                continue;
173            }
174
175            // Skip if in fenced code block - code has its own formatting rules
176            if fenced_code_block_lines[line_num] {
177                continue;
178            }
179
180            // Process tabs directly without intermediate collection
181            let tab_groups = Self::find_and_group_tabs(line);
182            if tab_groups.is_empty() {
183                continue;
184            }
185
186            let leading_tabs = Self::count_leading_tabs(line);
187
188            // Generate warning for each group of consecutive tabs
189            for (start_pos, end_pos) in tab_groups {
190                let tab_count = end_pos - start_pos;
191                let is_leading = start_pos < leading_tabs;
192
193                // Calculate precise character range for the tab group
194                let (start_line, start_col, end_line, end_col) =
195                    calculate_match_range(line_num + 1, line, start_pos, tab_count);
196
197                let message = if line.trim().is_empty() {
198                    if tab_count == 1 {
199                        "Empty line contains tab".to_string()
200                    } else {
201                        format!("Empty line contains {tab_count} tabs")
202                    }
203                } else if is_leading {
204                    if tab_count == 1 {
205                        format!(
206                            "Found leading tab, use {} spaces instead",
207                            self.config.spaces_per_tab.get()
208                        )
209                    } else {
210                        format!(
211                            "Found {} leading tabs, use {} spaces instead",
212                            tab_count,
213                            tab_count * self.config.spaces_per_tab.get()
214                        )
215                    }
216                } else if tab_count == 1 {
217                    "Found tab for alignment, use spaces instead".to_string()
218                } else {
219                    format!("Found {tab_count} tabs for alignment, use spaces instead")
220                };
221
222                warnings.push(LintWarning {
223                    rule_name: Some(self.name().to_string()),
224                    line: start_line,
225                    column: start_col,
226                    end_line,
227                    end_column: end_col,
228                    message,
229                    severity: Severity::Warning,
230                    fix: Some(Fix {
231                        range: _line_index.line_col_to_byte_range_with_length(line_num + 1, start_pos + 1, tab_count),
232                        replacement: " ".repeat(tab_count * self.config.spaces_per_tab.get()),
233                    }),
234                });
235            }
236        }
237
238        Ok(warnings)
239    }
240
241    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
242        let content = ctx.content;
243
244        let mut result = String::new();
245        let lines: Vec<&str> = content.lines().collect();
246
247        // Pre-compute which lines are part of HTML comments
248        let html_comment_lines = Self::find_html_comment_lines(&lines);
249
250        // Pre-compute which lines are inside fenced code blocks
251        // Only skip fenced code blocks - code has its own formatting rules
252        // (e.g., Makefiles require tabs, Go uses tabs by convention)
253        let fenced_code_block_lines = Self::find_fenced_code_block_lines(&lines);
254
255        for (i, line) in lines.iter().enumerate() {
256            if html_comment_lines[i] {
257                // Preserve HTML comments as they are
258                result.push_str(line);
259            } else if fenced_code_block_lines[i] {
260                // Preserve fenced code blocks as-is - code has its own formatting rules
261                result.push_str(line);
262            } else {
263                // Replace tabs with spaces in regular markdown content
264                // (including tab-indented content which might be accidental)
265                result.push_str(&line.replace('\t', &" ".repeat(self.config.spaces_per_tab.get())));
266            }
267
268            // Add newline if not the last line without a newline
269            if i < lines.len() - 1 || content.ends_with('\n') {
270                result.push('\n');
271            }
272        }
273
274        Ok(result)
275    }
276
277    fn as_any(&self) -> &dyn std::any::Any {
278        self
279    }
280
281    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
282        // Skip if content is empty or has no tabs
283        ctx.content.is_empty() || !ctx.has_char('\t')
284    }
285
286    fn category(&self) -> RuleCategory {
287        RuleCategory::Whitespace
288    }
289
290    fn default_config_section(&self) -> Option<(String, toml::Value)> {
291        let default_config = MD010Config::default();
292        let json_value = serde_json::to_value(&default_config).ok()?;
293        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
294
295        if let toml::Value::Table(table) = toml_value {
296            if !table.is_empty() {
297                Some((MD010Config::RULE_NAME.to_string(), toml::Value::Table(table)))
298            } else {
299                None
300            }
301        } else {
302            None
303        }
304    }
305
306    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
307    where
308        Self: Sized,
309    {
310        let rule_config = crate::rule_config_serde::load_rule_config::<MD010Config>(config);
311        Box::new(Self::from_config_struct(rule_config))
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::lint_context::LintContext;
319    use crate::rule::Rule;
320
321    #[test]
322    fn test_no_tabs() {
323        let rule = MD010NoHardTabs::default();
324        let content = "This is a line\nAnother line\nNo tabs here";
325        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
326        let result = rule.check(&ctx).unwrap();
327        assert!(result.is_empty());
328    }
329
330    #[test]
331    fn test_single_tab() {
332        let rule = MD010NoHardTabs::default();
333        let content = "Line with\ttab";
334        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
335        let result = rule.check(&ctx).unwrap();
336        assert_eq!(result.len(), 1);
337        assert_eq!(result[0].line, 1);
338        assert_eq!(result[0].column, 10);
339        assert_eq!(result[0].message, "Found tab for alignment, use spaces instead");
340    }
341
342    #[test]
343    fn test_leading_tabs() {
344        let rule = MD010NoHardTabs::default();
345        let content = "\tIndented line\n\t\tDouble indented";
346        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
347        let result = rule.check(&ctx).unwrap();
348        assert_eq!(result.len(), 2);
349        assert_eq!(result[0].line, 1);
350        assert_eq!(result[0].message, "Found leading tab, use 4 spaces instead");
351        assert_eq!(result[1].line, 2);
352        assert_eq!(result[1].message, "Found 2 leading tabs, use 8 spaces instead");
353    }
354
355    #[test]
356    fn test_fix_tabs() {
357        let rule = MD010NoHardTabs::default();
358        let content = "\tIndented\nNormal\tline\nNo tabs";
359        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
360        let fixed = rule.fix(&ctx).unwrap();
361        assert_eq!(fixed, "    Indented\nNormal    line\nNo tabs");
362    }
363
364    #[test]
365    fn test_custom_spaces_per_tab() {
366        let rule = MD010NoHardTabs::new(4);
367        let content = "\tIndented";
368        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
369        let fixed = rule.fix(&ctx).unwrap();
370        assert_eq!(fixed, "    Indented");
371    }
372
373    #[test]
374    fn test_code_blocks_always_ignored() {
375        let rule = MD010NoHardTabs::default();
376        let content = "Normal\tline\n```\nCode\twith\ttab\n```\nAnother\tline";
377        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
378        let result = rule.check(&ctx).unwrap();
379        // Should only flag tabs outside code blocks - code has its own formatting rules
380        assert_eq!(result.len(), 2);
381        assert_eq!(result[0].line, 1);
382        assert_eq!(result[1].line, 5);
383
384        let fixed = rule.fix(&ctx).unwrap();
385        assert_eq!(fixed, "Normal    line\n```\nCode\twith\ttab\n```\nAnother    line");
386    }
387
388    #[test]
389    fn test_code_blocks_never_checked() {
390        let rule = MD010NoHardTabs::default();
391        let content = "```\nCode\twith\ttab\n```";
392        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
393        let result = rule.check(&ctx).unwrap();
394        // Should never flag tabs in code blocks - code has its own formatting rules
395        // (e.g., Makefiles require tabs, Go uses tabs by convention)
396        assert_eq!(result.len(), 0);
397    }
398
399    #[test]
400    fn test_html_comments_ignored() {
401        let rule = MD010NoHardTabs::default();
402        let content = "Normal\tline\n<!-- HTML\twith\ttab -->\nAnother\tline";
403        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
404        let result = rule.check(&ctx).unwrap();
405        // Should not flag tabs in HTML comments
406        assert_eq!(result.len(), 2);
407        assert_eq!(result[0].line, 1);
408        assert_eq!(result[1].line, 3);
409    }
410
411    #[test]
412    fn test_multiline_html_comments() {
413        let rule = MD010NoHardTabs::default();
414        let content = "Before\n<!--\nMultiline\twith\ttabs\ncomment\t-->\nAfter\ttab";
415        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
416        let result = rule.check(&ctx).unwrap();
417        // Should only flag the tab after the comment
418        assert_eq!(result.len(), 1);
419        assert_eq!(result[0].line, 5);
420    }
421
422    #[test]
423    fn test_empty_lines_with_tabs() {
424        let rule = MD010NoHardTabs::default();
425        let content = "Normal line\n\t\t\n\t\nAnother line";
426        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
427        let result = rule.check(&ctx).unwrap();
428        assert_eq!(result.len(), 2);
429        assert_eq!(result[0].message, "Empty line contains 2 tabs");
430        assert_eq!(result[1].message, "Empty line contains tab");
431    }
432
433    #[test]
434    fn test_mixed_tabs_and_spaces() {
435        let rule = MD010NoHardTabs::default();
436        let content = " \tMixed indentation\n\t Mixed again";
437        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
438        let result = rule.check(&ctx).unwrap();
439        assert_eq!(result.len(), 2);
440    }
441
442    #[test]
443    fn test_consecutive_tabs() {
444        let rule = MD010NoHardTabs::default();
445        let content = "Text\t\t\tthree tabs\tand\tanother";
446        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
447        let result = rule.check(&ctx).unwrap();
448        // Should group consecutive tabs
449        assert_eq!(result.len(), 3);
450        assert_eq!(result[0].message, "Found 3 tabs for alignment, use spaces instead");
451    }
452
453    #[test]
454    fn test_find_and_group_tabs() {
455        // Test finding and grouping tabs in one pass
456        let groups = MD010NoHardTabs::find_and_group_tabs("a\tb\tc");
457        assert_eq!(groups, vec![(1, 2), (3, 4)]);
458
459        let groups = MD010NoHardTabs::find_and_group_tabs("\t\tabc");
460        assert_eq!(groups, vec![(0, 2)]);
461
462        let groups = MD010NoHardTabs::find_and_group_tabs("no tabs");
463        assert!(groups.is_empty());
464
465        // Test with consecutive and non-consecutive tabs
466        let groups = MD010NoHardTabs::find_and_group_tabs("\t\t\ta\t\tb");
467        assert_eq!(groups, vec![(0, 3), (4, 6)]);
468
469        let groups = MD010NoHardTabs::find_and_group_tabs("\ta\tb\tc");
470        assert_eq!(groups, vec![(0, 1), (2, 3), (4, 5)]);
471    }
472
473    #[test]
474    fn test_count_leading_tabs() {
475        assert_eq!(MD010NoHardTabs::count_leading_tabs("\t\tcode"), 2);
476        assert_eq!(MD010NoHardTabs::count_leading_tabs(" \tcode"), 0);
477        assert_eq!(MD010NoHardTabs::count_leading_tabs("no tabs"), 0);
478        assert_eq!(MD010NoHardTabs::count_leading_tabs("\t"), 1);
479    }
480
481    #[test]
482    fn test_default_config() {
483        let rule = MD010NoHardTabs::default();
484        let config = rule.default_config_section();
485        assert!(config.is_some());
486        let (name, _value) = config.unwrap();
487        assert_eq!(name, "MD010");
488    }
489
490    #[test]
491    fn test_from_config() {
492        // Test that custom config values are properly loaded
493        let custom_spaces = 8;
494        let rule = MD010NoHardTabs::new(custom_spaces);
495        let content = "\tTab";
496        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
497        let fixed = rule.fix(&ctx).unwrap();
498        assert_eq!(fixed, "        Tab");
499
500        // Code blocks are always ignored
501        let content_with_code = "```\n\tTab in code\n```";
502        let ctx = LintContext::new(content_with_code, crate::config::MarkdownFlavor::Standard, None);
503        let result = rule.check(&ctx).unwrap();
504        // Tabs in code blocks are never flagged
505        assert!(result.is_empty());
506    }
507
508    #[test]
509    fn test_performance_large_document() {
510        let rule = MD010NoHardTabs::default();
511        let mut content = String::new();
512        for i in 0..1000 {
513            content.push_str(&format!("Line {i}\twith\ttabs\n"));
514        }
515        let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
516        let result = rule.check(&ctx).unwrap();
517        assert_eq!(result.len(), 2000);
518    }
519
520    #[test]
521    fn test_preserve_content() {
522        let rule = MD010NoHardTabs::default();
523        let content = "**Bold**\ttext\n*Italic*\ttext\n[Link](url)\ttab";
524        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
525        let fixed = rule.fix(&ctx).unwrap();
526        assert_eq!(fixed, "**Bold**    text\n*Italic*    text\n[Link](url)    tab");
527    }
528
529    #[test]
530    fn test_edge_cases() {
531        let rule = MD010NoHardTabs::default();
532
533        // Tab at end of line
534        let content = "Text\t";
535        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
536        let result = rule.check(&ctx).unwrap();
537        assert_eq!(result.len(), 1);
538
539        // Only tabs
540        let content = "\t\t\t";
541        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
542        let result = rule.check(&ctx).unwrap();
543        assert_eq!(result.len(), 1);
544        assert_eq!(result[0].message, "Empty line contains 3 tabs");
545    }
546
547    #[test]
548    fn test_code_blocks_always_preserved_in_fix() {
549        let rule = MD010NoHardTabs::default();
550
551        let content = "Text\twith\ttab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore\ttabs";
552        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
553        let fixed = rule.fix(&ctx).unwrap();
554
555        // Tabs in code blocks are preserved - code has its own formatting rules
556        // (e.g., Makefiles require tabs, Go uses tabs by convention)
557        let expected = "Text    with    tab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore    tabs";
558        assert_eq!(fixed, expected);
559    }
560
561    #[test]
562    fn test_find_html_comment_lines() {
563        let lines = vec!["Normal", "<!-- Start", "Middle", "End -->", "After"];
564        let result = MD010NoHardTabs::find_html_comment_lines(&lines);
565        assert_eq!(result, vec![false, true, true, true, false]);
566
567        let lines = vec!["<!-- Single line comment -->", "Normal"];
568        let result = MD010NoHardTabs::find_html_comment_lines(&lines);
569        assert_eq!(result, vec![true, false]);
570    }
571}