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