1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::rule_config_serde::RuleConfig;
3use 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#[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 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 let has_comment_start = HTML_COMMENT_START.is_match(line);
41 let has_comment_end = HTML_COMMENT_END.is_match(line);
43
44 if has_comment_start && !has_comment_end && !in_html_comment {
45 in_html_comment = true;
47 html_comment_lines[i] = true;
48 } else if has_comment_end && in_html_comment {
49 html_comment_lines[i] = true;
51 in_html_comment = false;
52 } else if has_comment_start && has_comment_end {
53 html_comment_lines[i] = true;
55 } else if in_html_comment {
56 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 if i == last_tab_pos + 1 {
86 last_tab_pos = i;
88 } else {
89 groups.push((start, last_tab_pos + 1));
91 current_group_start = Some(i);
92 last_tab_pos = i;
93 }
94 } else {
95 current_group_start = Some(i);
97 last_tab_pos = i;
98 }
99 }
100 }
101
102 if let Some(start) = current_group_start {
104 groups.push((start, last_tab_pos + 1));
105 }
106
107 groups
108 }
109
110 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 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
123 in_fenced_block = true;
124 fence_char = Some(trimmed.chars().next().unwrap());
125 result[i] = true; }
127 } else {
128 result[i] = true;
129 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 let html_comment_lines = Self::find_html_comment_lines(&lines);
162
163 let fenced_code_block_lines = Self::find_fenced_code_block_lines(&lines);
168
169 for (line_num, &line) in lines.iter().enumerate() {
170 if html_comment_lines[line_num] {
172 continue;
173 }
174
175 if fenced_code_block_lines[line_num] {
177 continue;
178 }
179
180 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 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 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 let html_comment_lines = Self::find_html_comment_lines(&lines);
249
250 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 result.push_str(line);
259 } else if fenced_code_block_lines[i] {
260 result.push_str(line);
262 } else {
263 result.push_str(&line.replace('\t', &" ".repeat(self.config.spaces_per_tab.get())));
266 }
267
268 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}