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        // Count all heading styles to determine most prevalent (prevalence-based approach)
45        let mut style_counts = std::collections::HashMap::new();
46
47        for line_info in &ctx.lines {
48            if let Some(heading) = &line_info.heading {
49                // Skip invalid headings (e.g., `#NoSpace` which lacks required space after #)
50                if !heading.is_valid {
51                    continue;
52                }
53
54                // Map from LintContext heading style to rules heading style and count
55                let style = match heading.style {
56                    crate::lint_context::HeadingStyle::ATX => {
57                        if heading.has_closing_sequence {
58                            HeadingStyle::AtxClosed
59                        } else {
60                            HeadingStyle::Atx
61                        }
62                    }
63                    crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
64                    crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
65                };
66                *style_counts.entry(style).or_insert(0) += 1;
67            }
68        }
69
70        // Return most prevalent style
71        // In case of tie, prefer ATX as the default (deterministic tiebreaker)
72        style_counts
73            .into_iter()
74            .max_by(|(style_a, count_a), (style_b, count_b)| {
75                match count_a.cmp(count_b) {
76                    std::cmp::Ordering::Equal => {
77                        // Tiebreaker: prefer ATX (most common), then Setext1, then Setext2, then AtxClosed
78                        let priority = |s: &HeadingStyle| match s {
79                            HeadingStyle::Atx => 0,
80                            HeadingStyle::Setext1 => 1,
81                            HeadingStyle::Setext2 => 2,
82                            HeadingStyle::AtxClosed => 3,
83                            _ => 4,
84                        };
85                        priority(style_b).cmp(&priority(style_a)) // Reverse for min priority wins
86                    }
87                    other => other,
88                }
89            })
90            .map(|(style, _)| style)
91            .unwrap_or(HeadingStyle::Atx)
92    }
93}
94
95impl Rule for MD003HeadingStyle {
96    fn name(&self) -> &'static str {
97        "MD003"
98    }
99
100    fn description(&self) -> &'static str {
101        "Heading style"
102    }
103
104    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
105        let mut result = Vec::new();
106
107        // Get the target style using cached heading information
108        let target_style = self.get_target_style(ctx);
109
110        // Process headings using cached heading information
111        for (line_num, line_info) in ctx.lines.iter().enumerate() {
112            if let Some(heading) = &line_info.heading {
113                // Skip invalid headings (e.g., `#NoSpace` which lacks required space after #)
114                if !heading.is_valid {
115                    continue;
116                }
117
118                let level = heading.level;
119
120                // Map the cached heading style to the rule's HeadingStyle
121                let current_style = match heading.style {
122                    crate::lint_context::HeadingStyle::ATX => {
123                        if heading.has_closing_sequence {
124                            HeadingStyle::AtxClosed
125                        } else {
126                            HeadingStyle::Atx
127                        }
128                    }
129                    crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
130                    crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
131                };
132
133                // Determine expected style based on level and target
134                let expected_style = match target_style {
135                    HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
136                        if level > 2 {
137                            // Setext only supports levels 1-2, so levels 3+ must be ATX
138                            HeadingStyle::Atx
139                        } else if level == 1 {
140                            HeadingStyle::Setext1
141                        } else {
142                            HeadingStyle::Setext2
143                        }
144                    }
145                    HeadingStyle::SetextWithAtx => {
146                        if level <= 2 {
147                            // Use Setext for h1/h2
148                            if level == 1 {
149                                HeadingStyle::Setext1
150                            } else {
151                                HeadingStyle::Setext2
152                            }
153                        } else {
154                            // Use ATX for h3-h6
155                            HeadingStyle::Atx
156                        }
157                    }
158                    HeadingStyle::SetextWithAtxClosed => {
159                        if level <= 2 {
160                            // Use Setext for h1/h2
161                            if level == 1 {
162                                HeadingStyle::Setext1
163                            } else {
164                                HeadingStyle::Setext2
165                            }
166                        } else {
167                            // Use ATX closed for h3-h6
168                            HeadingStyle::AtxClosed
169                        }
170                    }
171                    _ => target_style,
172                };
173
174                if current_style != expected_style {
175                    // Generate fix for this heading
176                    let fix = {
177                        use crate::rules::heading_utils::HeadingUtils;
178
179                        // Convert heading to target style
180                        let converted_heading =
181                            HeadingUtils::convert_heading_style(&heading.text, level as u32, expected_style);
182
183                        // Add indentation
184                        let final_heading = format!("{}{}", " ".repeat(line_info.indent), converted_heading);
185
186                        // Calculate the correct range for the heading
187                        let range = ctx.line_index.line_content_range(line_num + 1);
188
189                        Some(crate::rule::Fix {
190                            range,
191                            replacement: final_heading,
192                        })
193                    };
194
195                    // Calculate precise character range for the heading marker
196                    let (start_line, start_col, end_line, end_col) =
197                        calculate_heading_range(line_num + 1, line_info.content(ctx.content));
198
199                    result.push(LintWarning {
200                        rule_name: Some(self.name().to_string()),
201                        line: start_line,
202                        column: start_col,
203                        end_line,
204                        end_column: end_col,
205                        message: format!(
206                            "Heading style should be {}, found {}",
207                            match expected_style {
208                                HeadingStyle::Atx => "# Heading",
209                                HeadingStyle::AtxClosed => "# Heading #",
210                                HeadingStyle::Setext1 => "Heading\n=======",
211                                HeadingStyle::Setext2 => "Heading\n-------",
212                                HeadingStyle::Consistent => "consistent with the first heading",
213                                HeadingStyle::SetextWithAtx => "setext_with_atx style",
214                                HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
215                            },
216                            match current_style {
217                                HeadingStyle::Atx => "# Heading",
218                                HeadingStyle::AtxClosed => "# Heading #",
219                                HeadingStyle::Setext1 => "Heading (underlined with =)",
220                                HeadingStyle::Setext2 => "Heading (underlined with -)",
221                                HeadingStyle::Consistent => "consistent style",
222                                HeadingStyle::SetextWithAtx => "setext_with_atx style",
223                                HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
224                            }
225                        ),
226                        severity: Severity::Warning,
227                        fix,
228                    });
229                }
230            }
231        }
232
233        Ok(result)
234    }
235
236    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
237        // Get all warnings with their fixes
238        let warnings = self.check(ctx)?;
239
240        // If no warnings, return original content
241        if warnings.is_empty() {
242            return Ok(ctx.content.to_string());
243        }
244
245        // Collect all fixes and sort by range start (descending) to apply from end to beginning
246        let mut fixes: Vec<_> = warnings
247            .iter()
248            .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
249            .collect();
250        fixes.sort_by(|a, b| b.0.cmp(&a.0));
251
252        // Apply fixes from end to beginning to preserve byte offsets
253        let mut result = ctx.content.to_string();
254        for (start, end, replacement) in fixes {
255            if start < result.len() && end <= result.len() && start <= end {
256                result.replace_range(start..end, replacement);
257            }
258        }
259
260        Ok(result)
261    }
262
263    fn category(&self) -> RuleCategory {
264        RuleCategory::Heading
265    }
266
267    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
268        // Fast path: check if document likely has headings using character frequency
269        if ctx.content.is_empty() || !ctx.likely_has_headings() {
270            return true;
271        }
272        // Verify headings actually exist (handles false positives from character frequency)
273        !ctx.lines.iter().any(|line| line.heading.is_some())
274    }
275
276    fn as_any(&self) -> &dyn std::any::Any {
277        self
278    }
279
280    fn default_config_section(&self) -> Option<(String, toml::Value)> {
281        let default_config = MD003Config::default();
282        let json_value = serde_json::to_value(&default_config).ok()?;
283        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
284
285        if let toml::Value::Table(table) = toml_value {
286            if !table.is_empty() {
287                Some((MD003Config::RULE_NAME.to_string(), toml::Value::Table(table)))
288            } else {
289                None
290            }
291        } else {
292            None
293        }
294    }
295
296    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
297    where
298        Self: Sized,
299    {
300        let rule_config = crate::rule_config_serde::load_rule_config::<MD003Config>(config);
301        Box::new(Self::from_config_struct(rule_config))
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use crate::lint_context::LintContext;
309
310    #[test]
311    fn test_atx_heading_style() {
312        let rule = MD003HeadingStyle::default();
313        let content = "# Heading 1\n## Heading 2\n### Heading 3";
314        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
315        let result = rule.check(&ctx).unwrap();
316        assert!(result.is_empty());
317    }
318
319    #[test]
320    fn test_setext_heading_style() {
321        let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
322        let content = "Heading 1\n=========\n\nHeading 2\n---------";
323        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
324        let result = rule.check(&ctx).unwrap();
325        assert!(result.is_empty());
326    }
327
328    #[test]
329    fn test_front_matter() {
330        let rule = MD003HeadingStyle::default();
331        let content = "---\ntitle: Test\n---\n\n# Heading 1\n## Heading 2";
332
333        // Test should detect headings and apply consistent style
334        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
335        let result = rule.check(&ctx).unwrap();
336        assert!(
337            result.is_empty(),
338            "No warnings expected for content with front matter, found: {result:?}"
339        );
340    }
341
342    #[test]
343    fn test_consistent_heading_style() {
344        // Default rule uses Atx which serves as our "consistent" mode
345        let rule = MD003HeadingStyle::default();
346        let content = "# Heading 1\n## Heading 2\n### Heading 3";
347        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
348        let result = rule.check(&ctx).unwrap();
349        assert!(result.is_empty());
350    }
351
352    #[test]
353    fn test_with_different_styles() {
354        // Test with consistent style (ATX)
355        let rule = MD003HeadingStyle::new(HeadingStyle::Consistent);
356        let content = "# Heading 1\n## Heading 2\n### Heading 3";
357        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
358        let result = rule.check(&ctx).unwrap();
359
360        // Make test more resilient
361        assert!(
362            result.is_empty(),
363            "No warnings expected for consistent ATX style, found: {result:?}"
364        );
365
366        // Test with incorrect style
367        let rule = MD003HeadingStyle::new(HeadingStyle::Atx);
368        let content = "# Heading 1 #\nHeading 2\n-----\n### Heading 3";
369        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
370        let result = rule.check(&ctx).unwrap();
371        assert!(
372            !result.is_empty(),
373            "Should have warnings for inconsistent heading styles"
374        );
375
376        // Test with setext style
377        let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
378        let content = "Heading 1\n=========\nHeading 2\n---------\n### Heading 3";
379        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
380        let result = rule.check(&ctx).unwrap();
381        // The level 3 heading can't be setext, so it's valid as ATX
382        assert!(
383            result.is_empty(),
384            "No warnings expected for setext style with ATX for level 3, found: {result:?}"
385        );
386    }
387
388    #[test]
389    fn test_setext_with_atx_style() {
390        let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtx);
391        // Setext for h1/h2, ATX for h3-h6
392        let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3\n\n#### Heading 4";
393        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
394        let result = rule.check(&ctx).unwrap();
395        assert!(
396            result.is_empty(),
397            "SesetxtWithAtx style should accept setext for h1/h2 and ATX for h3+"
398        );
399
400        // Test incorrect usage - ATX for h1/h2
401        let content_wrong = "# Heading 1\n## Heading 2\n### Heading 3";
402        let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard, None);
403        let result_wrong = rule.check(&ctx_wrong).unwrap();
404        assert_eq!(
405            result_wrong.len(),
406            2,
407            "Should flag ATX headings for h1/h2 with setext_with_atx style"
408        );
409    }
410
411    #[test]
412    fn test_setext_with_atx_closed_style() {
413        let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtxClosed);
414        // Setext for h1/h2, ATX closed for h3-h6
415        let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3 ###\n\n#### Heading 4 ####";
416        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
417        let result = rule.check(&ctx).unwrap();
418        assert!(
419            result.is_empty(),
420            "SetextWithAtxClosed style should accept setext for h1/h2 and ATX closed for h3+"
421        );
422
423        // Test incorrect usage - regular ATX for h3+
424        let content_wrong = "Heading 1\n=========\n\n### Heading 3\n\n#### Heading 4";
425        let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard, None);
426        let result_wrong = rule.check(&ctx_wrong).unwrap();
427        assert_eq!(
428            result_wrong.len(),
429            2,
430            "Should flag non-closed ATX headings for h3+ with setext_with_atx_closed style"
431        );
432    }
433}