rumdl_lib/rules/
md021_no_multiple_space_closed_atx.rs1use 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
9const 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 for (line_num, line_info) in ctx.lines.iter().enumerate() {
81 if let Some(heading) = &line_info.heading {
82 if line_info.visual_indent >= 4 {
84 continue;
85 }
86
87 if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) && heading.has_closing_sequence {
89 let line = line_info.content(ctx.content);
90
91 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 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_column_byte_range_with_length(start_line, 1, line.len()),
133 replacement,
134 )),
135 });
136 }
137 }
138 }
139 }
140
141 Ok(warnings)
142 }
143
144 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
145 if self.should_skip(ctx) {
146 return Ok(ctx.content.to_string());
147 }
148 let warnings = self.check(ctx)?;
149 if warnings.is_empty() {
150 return Ok(ctx.content.to_string());
151 }
152 let warnings =
153 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
154 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings).map_err(LintError::InvalidInput)
155 }
156
157 fn category(&self) -> RuleCategory {
159 RuleCategory::Heading
160 }
161
162 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
164 ctx.content.is_empty() || !ctx.likely_has_headings()
165 }
166
167 fn as_any(&self) -> &dyn std::any::Any {
168 self
169 }
170
171 fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
172 where
173 Self: Sized,
174 {
175 Box::new(MD021NoMultipleSpaceClosedAtx::new())
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use crate::lint_context::LintContext;
183
184 #[test]
185 fn test_basic_functionality() {
186 let rule = MD021NoMultipleSpaceClosedAtx;
187
188 let content = "# Heading 1 #\n## Heading 2 ##\n### Heading 3 ###";
190 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
191 let result = rule.check(&ctx).unwrap();
192 assert!(result.is_empty());
193
194 let content = "# Heading 1 #\n## Heading 2 ##\n### Heading 3 ###";
196 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
197 let result = rule.check(&ctx).unwrap();
198 assert_eq!(result.len(), 2); assert_eq!(result[0].line, 1);
200 assert_eq!(result[1].line, 3);
201 }
202}