rumdl_lib/rules/
md003_heading_style.rs

1//!
2//! Rule MD003: Heading style
3//!
4//! See [docs/md003.md](../../docs/md003.md) for full documentation, configuration, and examples.
5
6use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::rule_config_serde::RuleConfig;
8use crate::rules::heading_utils::HeadingStyle;
9use crate::utils::range_utils::calculate_heading_range;
10use toml;
11
12mod md003_config;
13use md003_config::MD003Config;
14
15/// Rule MD003: Heading style
16#[derive(Clone, Default)]
17pub struct MD003HeadingStyle {
18    config: MD003Config,
19}
20
21impl MD003HeadingStyle {
22    pub fn new(style: HeadingStyle) -> Self {
23        Self {
24            config: MD003Config { style },
25        }
26    }
27
28    pub fn from_config_struct(config: MD003Config) -> Self {
29        Self { config }
30    }
31
32    /// Check if we should use consistent mode (detect first style)
33    fn is_consistent_mode(&self) -> bool {
34        // Check for the Consistent variant explicitly
35        self.config.style == HeadingStyle::Consistent
36    }
37
38    /// Gets the target heading style based on configuration and document content
39    fn get_target_style(&self, ctx: &crate::lint_context::LintContext) -> HeadingStyle {
40        if !self.is_consistent_mode() {
41            return self.config.style;
42        }
43
44        // Find the first heading from cached info
45        for line_info in &ctx.lines {
46            if let Some(heading) = &line_info.heading {
47                // Map from LintContext heading style to rules heading style
48                return match heading.style {
49                    crate::lint_context::HeadingStyle::ATX => {
50                        if heading.has_closing_sequence {
51                            HeadingStyle::AtxClosed
52                        } else {
53                            HeadingStyle::Atx
54                        }
55                    }
56                    crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
57                    crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
58                };
59            }
60        }
61
62        // Default to ATX if no headings found
63        HeadingStyle::Atx
64    }
65}
66
67impl Rule for MD003HeadingStyle {
68    fn name(&self) -> &'static str {
69        "MD003"
70    }
71
72    fn description(&self) -> &'static str {
73        "Heading style"
74    }
75
76    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
77        let mut result = Vec::new();
78
79        // Get the target style using cached heading information
80        let target_style = self.get_target_style(ctx);
81
82        // Create LineIndex once outside the loop
83        let line_index = crate::utils::range_utils::LineIndex::new(ctx.content.to_string());
84
85        // Process headings using cached heading information
86        for (line_num, line_info) in ctx.lines.iter().enumerate() {
87            if let Some(heading) = &line_info.heading {
88                let level = heading.level;
89
90                // Map the cached heading style to the rule's HeadingStyle
91                let current_style = match heading.style {
92                    crate::lint_context::HeadingStyle::ATX => {
93                        if heading.has_closing_sequence {
94                            HeadingStyle::AtxClosed
95                        } else {
96                            HeadingStyle::Atx
97                        }
98                    }
99                    crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
100                    crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
101                };
102
103                // Determine expected style based on level and target
104                let expected_style = match target_style {
105                    HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
106                        if level > 2 {
107                            // Setext only supports levels 1-2, so levels 3+ must be ATX
108                            HeadingStyle::Atx
109                        } else if level == 1 {
110                            HeadingStyle::Setext1
111                        } else {
112                            HeadingStyle::Setext2
113                        }
114                    }
115                    HeadingStyle::SetextWithAtx => {
116                        if level <= 2 {
117                            // Use Setext for h1/h2
118                            if level == 1 {
119                                HeadingStyle::Setext1
120                            } else {
121                                HeadingStyle::Setext2
122                            }
123                        } else {
124                            // Use ATX for h3-h6
125                            HeadingStyle::Atx
126                        }
127                    }
128                    HeadingStyle::SetextWithAtxClosed => {
129                        if level <= 2 {
130                            // Use Setext for h1/h2
131                            if level == 1 {
132                                HeadingStyle::Setext1
133                            } else {
134                                HeadingStyle::Setext2
135                            }
136                        } else {
137                            // Use ATX closed for h3-h6
138                            HeadingStyle::AtxClosed
139                        }
140                    }
141                    _ => target_style,
142                };
143
144                if current_style != expected_style {
145                    // Generate fix for this heading
146                    let fix = {
147                        use crate::rules::heading_utils::HeadingUtils;
148
149                        // Convert heading to target style
150                        let converted_heading =
151                            HeadingUtils::convert_heading_style(&heading.text, level as u32, expected_style);
152
153                        // Add indentation
154                        let final_heading = format!("{}{}", " ".repeat(line_info.indent), converted_heading);
155
156                        // Calculate the correct range for the heading
157                        let range = line_index.line_content_range(line_num + 1);
158
159                        Some(crate::rule::Fix {
160                            range,
161                            replacement: final_heading,
162                        })
163                    };
164
165                    // Calculate precise character range for the heading marker
166                    let (start_line, start_col, end_line, end_col) =
167                        calculate_heading_range(line_num + 1, &line_info.content);
168
169                    result.push(LintWarning {
170                        rule_name: Some(self.name()),
171                        line: start_line,
172                        column: start_col,
173                        end_line,
174                        end_column: end_col,
175                        message: format!(
176                            "Heading style should be {}, found {}",
177                            match expected_style {
178                                HeadingStyle::Atx => "# Heading",
179                                HeadingStyle::AtxClosed => "# Heading #",
180                                HeadingStyle::Setext1 => "Heading\n=======",
181                                HeadingStyle::Setext2 => "Heading\n-------",
182                                HeadingStyle::Consistent => "consistent with the first heading",
183                                HeadingStyle::SetextWithAtx => "setext_with_atx style",
184                                HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
185                            },
186                            match current_style {
187                                HeadingStyle::Atx => "# Heading",
188                                HeadingStyle::AtxClosed => "# Heading #",
189                                HeadingStyle::Setext1 => "Heading (underlined with =)",
190                                HeadingStyle::Setext2 => "Heading (underlined with -)",
191                                HeadingStyle::Consistent => "consistent style",
192                                HeadingStyle::SetextWithAtx => "setext_with_atx style",
193                                HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
194                            }
195                        ),
196                        severity: Severity::Warning,
197                        fix,
198                    });
199                }
200            }
201        }
202
203        Ok(result)
204    }
205
206    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
207        // Get all warnings with their fixes
208        let warnings = self.check(ctx)?;
209
210        // If no warnings, return original content
211        if warnings.is_empty() {
212            return Ok(ctx.content.to_string());
213        }
214
215        // Collect all fixes and sort by range start (descending) to apply from end to beginning
216        let mut fixes: Vec<_> = warnings
217            .iter()
218            .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
219            .collect();
220        fixes.sort_by(|a, b| b.0.cmp(&a.0));
221
222        // Apply fixes from end to beginning to preserve byte offsets
223        let mut result = ctx.content.to_string();
224        for (start, end, replacement) in fixes {
225            if start < result.len() && end <= result.len() && start <= end {
226                result.replace_range(start..end, replacement);
227            }
228        }
229
230        Ok(result)
231    }
232
233    fn category(&self) -> RuleCategory {
234        RuleCategory::Heading
235    }
236
237    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
238        // Skip if content is empty or has no headings
239        ctx.content.is_empty() || !ctx.lines.iter().any(|line| line.heading.is_some())
240    }
241
242    fn as_any(&self) -> &dyn std::any::Any {
243        self
244    }
245
246    fn default_config_section(&self) -> Option<(String, toml::Value)> {
247        let default_config = MD003Config::default();
248        let json_value = serde_json::to_value(&default_config).ok()?;
249        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
250
251        if let toml::Value::Table(table) = toml_value {
252            if !table.is_empty() {
253                Some((MD003Config::RULE_NAME.to_string(), toml::Value::Table(table)))
254            } else {
255                None
256            }
257        } else {
258            None
259        }
260    }
261
262    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
263    where
264        Self: Sized,
265    {
266        let rule_config = crate::rule_config_serde::load_rule_config::<MD003Config>(config);
267        Box::new(Self::from_config_struct(rule_config))
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::lint_context::LintContext;
275
276    #[test]
277    fn test_atx_heading_style() {
278        let rule = MD003HeadingStyle::default();
279        let content = "# Heading 1\n## Heading 2\n### Heading 3";
280        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
281        let result = rule.check(&ctx).unwrap();
282        assert!(result.is_empty());
283    }
284
285    #[test]
286    fn test_setext_heading_style() {
287        let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
288        let content = "Heading 1\n=========\n\nHeading 2\n---------";
289        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
290        let result = rule.check(&ctx).unwrap();
291        assert!(result.is_empty());
292    }
293
294    #[test]
295    fn test_front_matter() {
296        let rule = MD003HeadingStyle::default();
297        let content = "---\ntitle: Test\n---\n\n# Heading 1\n## Heading 2";
298
299        // Test should detect headings and apply consistent style
300        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
301        let result = rule.check(&ctx).unwrap();
302        assert!(
303            result.is_empty(),
304            "No warnings expected for content with front matter, found: {result:?}"
305        );
306    }
307
308    #[test]
309    fn test_consistent_heading_style() {
310        // Default rule uses Atx which serves as our "consistent" mode
311        let rule = MD003HeadingStyle::default();
312        let content = "# Heading 1\n## Heading 2\n### Heading 3";
313        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
314        let result = rule.check(&ctx).unwrap();
315        assert!(result.is_empty());
316    }
317
318    #[test]
319    fn test_with_different_styles() {
320        // Test with consistent style (ATX)
321        let rule = MD003HeadingStyle::new(HeadingStyle::Consistent);
322        let content = "# Heading 1\n## Heading 2\n### Heading 3";
323        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
324        let result = rule.check(&ctx).unwrap();
325
326        // Make test more resilient
327        assert!(
328            result.is_empty(),
329            "No warnings expected for consistent ATX style, found: {result:?}"
330        );
331
332        // Test with incorrect style
333        let rule = MD003HeadingStyle::new(HeadingStyle::Atx);
334        let content = "# Heading 1 #\nHeading 2\n-----\n### Heading 3";
335        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
336        let result = rule.check(&ctx).unwrap();
337        assert!(
338            !result.is_empty(),
339            "Should have warnings for inconsistent heading styles"
340        );
341
342        // Test with setext style
343        let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
344        let content = "Heading 1\n=========\nHeading 2\n---------\n### Heading 3";
345        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
346        let result = rule.check(&ctx).unwrap();
347        // The level 3 heading can't be setext, so it's valid as ATX
348        assert!(
349            result.is_empty(),
350            "No warnings expected for setext style with ATX for level 3, found: {result:?}"
351        );
352    }
353
354    #[test]
355    fn test_setext_with_atx_style() {
356        let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtx);
357        // Setext for h1/h2, ATX for h3-h6
358        let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3\n\n#### Heading 4";
359        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
360        let result = rule.check(&ctx).unwrap();
361        assert!(
362            result.is_empty(),
363            "SesetxtWithAtx style should accept setext for h1/h2 and ATX for h3+"
364        );
365
366        // Test incorrect usage - ATX for h1/h2
367        let content_wrong = "# Heading 1\n## Heading 2\n### Heading 3";
368        let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard);
369        let result_wrong = rule.check(&ctx_wrong).unwrap();
370        assert_eq!(
371            result_wrong.len(),
372            2,
373            "Should flag ATX headings for h1/h2 with setext_with_atx style"
374        );
375    }
376
377    #[test]
378    fn test_setext_with_atx_closed_style() {
379        let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtxClosed);
380        // Setext for h1/h2, ATX closed for h3-h6
381        let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3 ###\n\n#### Heading 4 ####";
382        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
383        let result = rule.check(&ctx).unwrap();
384        assert!(
385            result.is_empty(),
386            "SetextWithAtxClosed style should accept setext for h1/h2 and ATX closed for h3+"
387        );
388
389        // Test incorrect usage - regular ATX for h3+
390        let content_wrong = "Heading 1\n=========\n\n### Heading 3\n\n#### Heading 4";
391        let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard);
392        let result_wrong = rule.check(&ctx_wrong).unwrap();
393        assert_eq!(
394            result_wrong.len(),
395            2,
396            "Should flag non-closed ATX headings for h3+ with setext_with_atx_closed style"
397        );
398    }
399}