Skip to main content

rumdl_lib/rules/
md021_no_multiple_space_closed_atx.rs

1/// Rule MD021: No multiple spaces inside closed ATX heading
2///
3/// See [docs/md021.md](../../docs/md021.md) for full documentation, configuration, and examples.
4use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use crate::utils::range_utils::calculate_line_range;
6use regex::Regex;
7use std::sync::LazyLock;
8
9// Regex patterns
10const CLOSED_ATX_MULTIPLE_SPACE_PATTERN_STR: &str = r"^(\s*)(#+)(\s+)(.*?)(\s+)(#+)\s*$";
11static CLOSED_ATX_MULTIPLE_SPACE_PATTERN: LazyLock<Regex> =
12    LazyLock::new(|| Regex::new(CLOSED_ATX_MULTIPLE_SPACE_PATTERN_STR).unwrap());
13
14#[derive(Clone)]
15pub struct MD021NoMultipleSpaceClosedAtx;
16
17impl Default for MD021NoMultipleSpaceClosedAtx {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl MD021NoMultipleSpaceClosedAtx {
24    pub fn new() -> Self {
25        Self
26    }
27
28    fn is_closed_atx_heading_with_multiple_spaces(&self, line: &str) -> bool {
29        if let Some(captures) = CLOSED_ATX_MULTIPLE_SPACE_PATTERN.captures(line) {
30            let start_spaces = captures.get(3).unwrap().as_str().len();
31            let end_spaces = captures.get(5).unwrap().as_str().len();
32            start_spaces > 1 || end_spaces > 1
33        } else {
34            false
35        }
36    }
37
38    fn fix_closed_atx_heading(&self, line: &str) -> String {
39        if let Some(captures) = CLOSED_ATX_MULTIPLE_SPACE_PATTERN.captures(line) {
40            let indentation = &captures[1];
41            let opening_hashes = &captures[2];
42            let content = &captures[4];
43            let closing_hashes = &captures[6];
44            format!(
45                "{}{} {} {}",
46                indentation,
47                opening_hashes,
48                content.trim(),
49                closing_hashes
50            )
51        } else {
52            line.to_string()
53        }
54    }
55
56    fn count_spaces(&self, line: &str) -> (usize, usize) {
57        if let Some(captures) = CLOSED_ATX_MULTIPLE_SPACE_PATTERN.captures(line) {
58            let start_spaces = captures.get(3).unwrap().as_str().len();
59            let end_spaces = captures.get(5).unwrap().as_str().len();
60            (start_spaces, end_spaces)
61        } else {
62            (0, 0)
63        }
64    }
65}
66
67impl Rule for MD021NoMultipleSpaceClosedAtx {
68    fn name(&self) -> &'static str {
69        "MD021"
70    }
71
72    fn description(&self) -> &'static str {
73        "Multiple spaces inside hashes on closed heading"
74    }
75
76    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
77        let mut warnings = Vec::new();
78
79        // Check all closed ATX headings from cached info
80        for (line_num, line_info) in ctx.lines.iter().enumerate() {
81            if let Some(heading) = &line_info.heading {
82                // Skip headings indented 4+ spaces (they're code blocks)
83                if line_info.visual_indent >= 4 {
84                    continue;
85                }
86
87                // Only check closed ATX headings
88                if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) && heading.has_closing_sequence {
89                    let line = line_info.content(ctx.content);
90
91                    // Check if line matches closed ATX pattern with multiple spaces
92                    if self.is_closed_atx_heading_with_multiple_spaces(line) {
93                        let captures = CLOSED_ATX_MULTIPLE_SPACE_PATTERN.captures(line).unwrap();
94                        let _indentation = captures.get(1).unwrap();
95                        let opening_hashes = captures.get(2).unwrap();
96                        let (start_spaces, end_spaces) = self.count_spaces(line);
97
98                        let message = if start_spaces > 1 && end_spaces > 1 {
99                            format!(
100                                "Multiple spaces ({} at start, {} at end) inside hashes on closed heading (with {} at start and end)",
101                                start_spaces,
102                                end_spaces,
103                                "#".repeat(opening_hashes.as_str().len())
104                            )
105                        } else if start_spaces > 1 {
106                            format!(
107                                "Multiple spaces ({}) after {} at start of closed heading",
108                                start_spaces,
109                                "#".repeat(opening_hashes.as_str().len())
110                            )
111                        } else {
112                            format!(
113                                "Multiple spaces ({}) before {} at end of closed heading",
114                                end_spaces,
115                                "#".repeat(opening_hashes.as_str().len())
116                            )
117                        };
118
119                        // Replace the entire line with the fixed version
120                        let (start_line, start_col, end_line, end_col) = calculate_line_range(line_num + 1, line);
121                        let replacement = self.fix_closed_atx_heading(line);
122
123                        warnings.push(LintWarning {
124                            rule_name: Some(self.name().to_string()),
125                            message,
126                            line: start_line,
127                            column: start_col,
128                            end_line,
129                            end_column: end_col,
130                            severity: Severity::Warning,
131                            fix: Some(Fix::new(
132                                ctx.line_index
133                                    .line_col_to_byte_range_with_length(start_line, 1, line.len()),
134                                replacement,
135                            )),
136                        });
137                    }
138                }
139            }
140        }
141
142        Ok(warnings)
143    }
144
145    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
146        if self.should_skip(ctx) {
147            return Ok(ctx.content.to_string());
148        }
149        let warnings = self.check(ctx)?;
150        if warnings.is_empty() {
151            return Ok(ctx.content.to_string());
152        }
153        let warnings =
154            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
155        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings).map_err(LintError::InvalidInput)
156    }
157
158    /// Get the category of this rule for selective processing
159    fn category(&self) -> RuleCategory {
160        RuleCategory::Heading
161    }
162
163    /// Check if this rule should be skipped
164    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
165        ctx.content.is_empty() || !ctx.likely_has_headings()
166    }
167
168    fn as_any(&self) -> &dyn std::any::Any {
169        self
170    }
171
172    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
173    where
174        Self: Sized,
175    {
176        Box::new(MD021NoMultipleSpaceClosedAtx::new())
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::lint_context::LintContext;
184
185    #[test]
186    fn test_basic_functionality() {
187        let rule = MD021NoMultipleSpaceClosedAtx;
188
189        // Test with correct spacing
190        let content = "# Heading 1 #\n## Heading 2 ##\n### Heading 3 ###";
191        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
192        let result = rule.check(&ctx).unwrap();
193        assert!(result.is_empty());
194
195        // Test with multiple spaces
196        let content = "#  Heading 1 #\n## Heading 2 ##\n### Heading 3  ###";
197        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
198        let result = rule.check(&ctx).unwrap();
199        assert_eq!(result.len(), 2); // Should flag the two headings with multiple spaces
200        assert_eq!(result[0].line, 1);
201        assert_eq!(result[1].line, 3);
202    }
203}