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 _line_index = &ctx.line_index;
155
156 let mut warnings = Vec::new();
157 let lines = ctx.raw_lines();
158
159 let html_comment_lines = Self::find_html_comment_lines(lines);
161
162 let fenced_code_block_lines = Self::find_fenced_code_block_lines(lines);
167
168 for (line_num, &line) in lines.iter().enumerate() {
169 if html_comment_lines[line_num] {
171 continue;
172 }
173
174 if fenced_code_block_lines[line_num] {
176 continue;
177 }
178
179 if ctx.line_info(line_num + 1).is_some_and(|info| info.in_pymdown_block) {
181 continue;
182 }
183
184 let tab_groups = Self::find_and_group_tabs(line);
186 if tab_groups.is_empty() {
187 continue;
188 }
189
190 let leading_tabs = Self::count_leading_tabs(line);
191
192 for (start_pos, end_pos) in tab_groups {
194 let tab_count = end_pos - start_pos;
195 let is_leading = start_pos < leading_tabs;
196
197 let (start_line, start_col, end_line, end_col) =
199 calculate_match_range(line_num + 1, line, start_pos, tab_count);
200
201 let message = if line.trim().is_empty() {
202 if tab_count == 1 {
203 "Empty line contains tab".to_string()
204 } else {
205 format!("Empty line contains {tab_count} tabs")
206 }
207 } else if is_leading {
208 if tab_count == 1 {
209 format!(
210 "Found leading tab, use {} spaces instead",
211 self.config.spaces_per_tab.get()
212 )
213 } else {
214 format!(
215 "Found {} leading tabs, use {} spaces instead",
216 tab_count,
217 tab_count * self.config.spaces_per_tab.get()
218 )
219 }
220 } else if tab_count == 1 {
221 "Found tab for alignment, use spaces instead".to_string()
222 } else {
223 format!("Found {tab_count} tabs for alignment, use spaces instead")
224 };
225
226 warnings.push(LintWarning {
227 rule_name: Some(self.name().to_string()),
228 line: start_line,
229 column: start_col,
230 end_line,
231 end_column: end_col,
232 message,
233 severity: Severity::Warning,
234 fix: Some(Fix {
235 range: _line_index.line_col_to_byte_range_with_length(line_num + 1, start_pos + 1, tab_count),
236 replacement: " ".repeat(tab_count * self.config.spaces_per_tab.get()),
237 }),
238 });
239 }
240 }
241
242 Ok(warnings)
243 }
244
245 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
246 let content = ctx.content;
247
248 let mut result = String::new();
249 let lines = ctx.raw_lines();
250
251 let html_comment_lines = Self::find_html_comment_lines(lines);
253
254 let fenced_code_block_lines = Self::find_fenced_code_block_lines(lines);
258
259 for (i, line) in lines.iter().enumerate() {
260 if html_comment_lines[i] {
261 result.push_str(line);
263 } else if fenced_code_block_lines[i] {
264 result.push_str(line);
266 } else {
267 result.push_str(&line.replace('\t', &" ".repeat(self.config.spaces_per_tab.get())));
270 }
271
272 if i < lines.len() - 1 || content.ends_with('\n') {
274 result.push('\n');
275 }
276 }
277
278 Ok(result)
279 }
280
281 fn as_any(&self) -> &dyn std::any::Any {
282 self
283 }
284
285 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
286 ctx.content.is_empty() || !ctx.has_char('\t')
288 }
289
290 fn category(&self) -> RuleCategory {
291 RuleCategory::Whitespace
292 }
293
294 fn default_config_section(&self) -> Option<(String, toml::Value)> {
295 let default_config = MD010Config::default();
296 let json_value = serde_json::to_value(&default_config).ok()?;
297 let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
298
299 if let toml::Value::Table(table) = toml_value {
300 if !table.is_empty() {
301 Some((MD010Config::RULE_NAME.to_string(), toml::Value::Table(table)))
302 } else {
303 None
304 }
305 } else {
306 None
307 }
308 }
309
310 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
311 where
312 Self: Sized,
313 {
314 let rule_config = crate::rule_config_serde::load_rule_config::<MD010Config>(config);
315 Box::new(Self::from_config_struct(rule_config))
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::lint_context::LintContext;
323 use crate::rule::Rule;
324
325 #[test]
326 fn test_no_tabs() {
327 let rule = MD010NoHardTabs::default();
328 let content = "This is a line\nAnother line\nNo tabs here";
329 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
330 let result = rule.check(&ctx).unwrap();
331 assert!(result.is_empty());
332 }
333
334 #[test]
335 fn test_single_tab() {
336 let rule = MD010NoHardTabs::default();
337 let content = "Line with\ttab";
338 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
339 let result = rule.check(&ctx).unwrap();
340 assert_eq!(result.len(), 1);
341 assert_eq!(result[0].line, 1);
342 assert_eq!(result[0].column, 10);
343 assert_eq!(result[0].message, "Found tab for alignment, use spaces instead");
344 }
345
346 #[test]
347 fn test_leading_tabs() {
348 let rule = MD010NoHardTabs::default();
349 let content = "\tIndented line\n\t\tDouble indented";
350 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
351 let result = rule.check(&ctx).unwrap();
352 assert_eq!(result.len(), 2);
353 assert_eq!(result[0].line, 1);
354 assert_eq!(result[0].message, "Found leading tab, use 4 spaces instead");
355 assert_eq!(result[1].line, 2);
356 assert_eq!(result[1].message, "Found 2 leading tabs, use 8 spaces instead");
357 }
358
359 #[test]
360 fn test_fix_tabs() {
361 let rule = MD010NoHardTabs::default();
362 let content = "\tIndented\nNormal\tline\nNo tabs";
363 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
364 let fixed = rule.fix(&ctx).unwrap();
365 assert_eq!(fixed, " Indented\nNormal line\nNo tabs");
366 }
367
368 #[test]
369 fn test_custom_spaces_per_tab() {
370 let rule = MD010NoHardTabs::new(4);
371 let content = "\tIndented";
372 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
373 let fixed = rule.fix(&ctx).unwrap();
374 assert_eq!(fixed, " Indented");
375 }
376
377 #[test]
378 fn test_code_blocks_always_ignored() {
379 let rule = MD010NoHardTabs::default();
380 let content = "Normal\tline\n```\nCode\twith\ttab\n```\nAnother\tline";
381 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
382 let result = rule.check(&ctx).unwrap();
383 assert_eq!(result.len(), 2);
385 assert_eq!(result[0].line, 1);
386 assert_eq!(result[1].line, 5);
387
388 let fixed = rule.fix(&ctx).unwrap();
389 assert_eq!(fixed, "Normal line\n```\nCode\twith\ttab\n```\nAnother line");
390 }
391
392 #[test]
393 fn test_code_blocks_never_checked() {
394 let rule = MD010NoHardTabs::default();
395 let content = "```\nCode\twith\ttab\n```";
396 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
397 let result = rule.check(&ctx).unwrap();
398 assert_eq!(result.len(), 0);
401 }
402
403 #[test]
404 fn test_html_comments_ignored() {
405 let rule = MD010NoHardTabs::default();
406 let content = "Normal\tline\n<!-- HTML\twith\ttab -->\nAnother\tline";
407 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
408 let result = rule.check(&ctx).unwrap();
409 assert_eq!(result.len(), 2);
411 assert_eq!(result[0].line, 1);
412 assert_eq!(result[1].line, 3);
413 }
414
415 #[test]
416 fn test_multiline_html_comments() {
417 let rule = MD010NoHardTabs::default();
418 let content = "Before\n<!--\nMultiline\twith\ttabs\ncomment\t-->\nAfter\ttab";
419 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
420 let result = rule.check(&ctx).unwrap();
421 assert_eq!(result.len(), 1);
423 assert_eq!(result[0].line, 5);
424 }
425
426 #[test]
427 fn test_empty_lines_with_tabs() {
428 let rule = MD010NoHardTabs::default();
429 let content = "Normal line\n\t\t\n\t\nAnother line";
430 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
431 let result = rule.check(&ctx).unwrap();
432 assert_eq!(result.len(), 2);
433 assert_eq!(result[0].message, "Empty line contains 2 tabs");
434 assert_eq!(result[1].message, "Empty line contains tab");
435 }
436
437 #[test]
438 fn test_mixed_tabs_and_spaces() {
439 let rule = MD010NoHardTabs::default();
440 let content = " \tMixed indentation\n\t Mixed again";
441 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
442 let result = rule.check(&ctx).unwrap();
443 assert_eq!(result.len(), 2);
444 }
445
446 #[test]
447 fn test_consecutive_tabs() {
448 let rule = MD010NoHardTabs::default();
449 let content = "Text\t\t\tthree tabs\tand\tanother";
450 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
451 let result = rule.check(&ctx).unwrap();
452 assert_eq!(result.len(), 3);
454 assert_eq!(result[0].message, "Found 3 tabs for alignment, use spaces instead");
455 }
456
457 #[test]
458 fn test_find_and_group_tabs() {
459 let groups = MD010NoHardTabs::find_and_group_tabs("a\tb\tc");
461 assert_eq!(groups, vec![(1, 2), (3, 4)]);
462
463 let groups = MD010NoHardTabs::find_and_group_tabs("\t\tabc");
464 assert_eq!(groups, vec![(0, 2)]);
465
466 let groups = MD010NoHardTabs::find_and_group_tabs("no tabs");
467 assert!(groups.is_empty());
468
469 let groups = MD010NoHardTabs::find_and_group_tabs("\t\t\ta\t\tb");
471 assert_eq!(groups, vec![(0, 3), (4, 6)]);
472
473 let groups = MD010NoHardTabs::find_and_group_tabs("\ta\tb\tc");
474 assert_eq!(groups, vec![(0, 1), (2, 3), (4, 5)]);
475 }
476
477 #[test]
478 fn test_count_leading_tabs() {
479 assert_eq!(MD010NoHardTabs::count_leading_tabs("\t\tcode"), 2);
480 assert_eq!(MD010NoHardTabs::count_leading_tabs(" \tcode"), 0);
481 assert_eq!(MD010NoHardTabs::count_leading_tabs("no tabs"), 0);
482 assert_eq!(MD010NoHardTabs::count_leading_tabs("\t"), 1);
483 }
484
485 #[test]
486 fn test_default_config() {
487 let rule = MD010NoHardTabs::default();
488 let config = rule.default_config_section();
489 assert!(config.is_some());
490 let (name, _value) = config.unwrap();
491 assert_eq!(name, "MD010");
492 }
493
494 #[test]
495 fn test_from_config() {
496 let custom_spaces = 8;
498 let rule = MD010NoHardTabs::new(custom_spaces);
499 let content = "\tTab";
500 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
501 let fixed = rule.fix(&ctx).unwrap();
502 assert_eq!(fixed, " Tab");
503
504 let content_with_code = "```\n\tTab in code\n```";
506 let ctx = LintContext::new(content_with_code, crate::config::MarkdownFlavor::Standard, None);
507 let result = rule.check(&ctx).unwrap();
508 assert!(result.is_empty());
510 }
511
512 #[test]
513 fn test_performance_large_document() {
514 let rule = MD010NoHardTabs::default();
515 let mut content = String::new();
516 for i in 0..1000 {
517 content.push_str(&format!("Line {i}\twith\ttabs\n"));
518 }
519 let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
520 let result = rule.check(&ctx).unwrap();
521 assert_eq!(result.len(), 2000);
522 }
523
524 #[test]
525 fn test_preserve_content() {
526 let rule = MD010NoHardTabs::default();
527 let content = "**Bold**\ttext\n*Italic*\ttext\n[Link](url)\ttab";
528 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
529 let fixed = rule.fix(&ctx).unwrap();
530 assert_eq!(fixed, "**Bold** text\n*Italic* text\n[Link](url) tab");
531 }
532
533 #[test]
534 fn test_edge_cases() {
535 let rule = MD010NoHardTabs::default();
536
537 let content = "Text\t";
539 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
540 let result = rule.check(&ctx).unwrap();
541 assert_eq!(result.len(), 1);
542
543 let content = "\t\t\t";
545 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
546 let result = rule.check(&ctx).unwrap();
547 assert_eq!(result.len(), 1);
548 assert_eq!(result[0].message, "Empty line contains 3 tabs");
549 }
550
551 #[test]
552 fn test_code_blocks_always_preserved_in_fix() {
553 let rule = MD010NoHardTabs::default();
554
555 let content = "Text\twith\ttab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore\ttabs";
556 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
557 let fixed = rule.fix(&ctx).unwrap();
558
559 let expected = "Text with tab\n```makefile\ntarget:\n\tcommand\n\tanother\n```\nMore tabs";
562 assert_eq!(fixed, expected);
563 }
564
565 #[test]
566 fn test_find_html_comment_lines() {
567 let lines = vec!["Normal", "<!-- Start", "Middle", "End -->", "After"];
568 let result = MD010NoHardTabs::find_html_comment_lines(&lines);
569 assert_eq!(result, vec![false, true, true, true, false]);
570
571 let lines = vec!["<!-- Single line comment -->", "Normal"];
572 let result = MD010NoHardTabs::find_html_comment_lines(&lines);
573 assert_eq!(result, vec![true, false]);
574 }
575}