Skip to main content

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_or(HeadingStyle::Atx, |(style, _)| style)
91    }
92}
93
94impl Rule for MD003HeadingStyle {
95    fn name(&self) -> &'static str {
96        "MD003"
97    }
98
99    fn description(&self) -> &'static str {
100        "Heading style"
101    }
102
103    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
104        let mut result = Vec::new();
105
106        // Get the target style using cached heading information
107        let target_style = self.get_target_style(ctx);
108
109        // Process headings using cached heading information
110        for (line_num, line_info) in ctx.lines.iter().enumerate() {
111            if let Some(heading) = &line_info.heading {
112                // Skip invalid headings (e.g., `#NoSpace` which lacks required space after #)
113                if !heading.is_valid {
114                    continue;
115                }
116
117                let level = heading.level;
118
119                // Map the cached heading style to the rule's HeadingStyle
120                let current_style = match heading.style {
121                    crate::lint_context::HeadingStyle::ATX => {
122                        if heading.has_closing_sequence {
123                            HeadingStyle::AtxClosed
124                        } else {
125                            HeadingStyle::Atx
126                        }
127                    }
128                    crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
129                    crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
130                };
131
132                // Determine expected style based on level and target
133                let expected_style = match target_style {
134                    HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
135                        if level > 2 {
136                            // Setext only supports levels 1-2, so levels 3+ must be ATX
137                            HeadingStyle::Atx
138                        } else if level == 1 {
139                            HeadingStyle::Setext1
140                        } else {
141                            HeadingStyle::Setext2
142                        }
143                    }
144                    HeadingStyle::SetextWithAtx => {
145                        if level <= 2 {
146                            // Use Setext for h1/h2
147                            if level == 1 {
148                                HeadingStyle::Setext1
149                            } else {
150                                HeadingStyle::Setext2
151                            }
152                        } else {
153                            // Use ATX for h3-h6
154                            HeadingStyle::Atx
155                        }
156                    }
157                    HeadingStyle::SetextWithAtxClosed => {
158                        if level <= 2 {
159                            // Use Setext for h1/h2
160                            if level == 1 {
161                                HeadingStyle::Setext1
162                            } else {
163                                HeadingStyle::Setext2
164                            }
165                        } else {
166                            // Use ATX closed for h3-h6
167                            HeadingStyle::AtxClosed
168                        }
169                    }
170                    _ => target_style,
171                };
172
173                if current_style != expected_style {
174                    // Generate fix for this heading
175                    let fix = {
176                        use crate::rules::heading_utils::HeadingUtils;
177
178                        // Convert heading to target style, preserving inline attribute lists
179                        let converted_heading =
180                            HeadingUtils::convert_heading_style(&heading.raw_text, level as u32, expected_style);
181
182                        // Preserve original indentation (including tabs)
183                        let line = line_info.content(ctx.content);
184                        let original_indent = &line[..line_info.indent];
185                        let final_heading = format!("{original_indent}{converted_heading}");
186
187                        // Calculate the correct range for the heading
188                        let range = ctx.line_index.line_content_range(line_num + 1);
189
190                        Some(crate::rule::Fix::new(range, final_heading))
191                    };
192
193                    // Calculate precise character range for the heading marker
194                    let (start_line, start_col, end_line, end_col) =
195                        calculate_heading_range(line_num + 1, line_info.content(ctx.content));
196
197                    result.push(LintWarning {
198                        rule_name: Some(self.name().to_string()),
199                        line: start_line,
200                        column: start_col,
201                        end_line,
202                        end_column: end_col,
203                        message: format!(
204                            "Heading style should be {}, found {}",
205                            match expected_style {
206                                HeadingStyle::Atx => "# Heading",
207                                HeadingStyle::AtxClosed => "# Heading #",
208                                HeadingStyle::Setext1 => "Heading\n=======",
209                                HeadingStyle::Setext2 => "Heading\n-------",
210                                HeadingStyle::Consistent => "consistent with the first heading",
211                                HeadingStyle::SetextWithAtx => "setext-with-atx style",
212                                HeadingStyle::SetextWithAtxClosed => "setext-with-atx-closed style",
213                            },
214                            match current_style {
215                                HeadingStyle::Atx => "# Heading",
216                                HeadingStyle::AtxClosed => "# Heading #",
217                                HeadingStyle::Setext1 => "Heading (underlined with =)",
218                                HeadingStyle::Setext2 => "Heading (underlined with -)",
219                                HeadingStyle::Consistent => "consistent style",
220                                HeadingStyle::SetextWithAtx => "setext-with-atx style",
221                                HeadingStyle::SetextWithAtxClosed => "setext-with-atx-closed style",
222                            }
223                        ),
224                        severity: Severity::Warning,
225                        fix,
226                    });
227                }
228            }
229        }
230
231        Ok(result)
232    }
233
234    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
235        // Get all warnings with their fixes
236        let warnings = self.check(ctx)?;
237        let warnings =
238            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
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_fix_preserves_attribute_lists() {
413        // ATX closed heading with attribute list, converted to ATX
414        let rule = MD003HeadingStyle::new(HeadingStyle::Atx);
415        let content = "# Heading { #custom-id .class } #";
416        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
417
418        // Should flag: found ATX closed, expected ATX
419        let warnings = rule.check(&ctx).unwrap();
420        assert_eq!(warnings.len(), 1);
421        let fix = warnings[0].fix.as_ref().expect("Should have a fix");
422        assert!(
423            fix.replacement.contains("{ #custom-id .class }"),
424            "check() fix should preserve attribute list, got: {}",
425            fix.replacement
426        );
427
428        // Verify fix() also preserves attribute list
429        let fixed = rule.fix(&ctx).unwrap();
430        assert!(
431            fixed.contains("{ #custom-id .class }"),
432            "fix() should preserve attribute list, got: {fixed}"
433        );
434        assert!(
435            !fixed.contains(" #\n") && !fixed.ends_with(" #"),
436            "fix() should remove ATX closed trailing hashes, got: {fixed}"
437        );
438    }
439
440    #[test]
441    fn test_setext_with_atx_closed_style() {
442        let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtxClosed);
443        // Setext for h1/h2, ATX closed for h3-h6
444        let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3 ###\n\n#### Heading 4 ####";
445        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
446        let result = rule.check(&ctx).unwrap();
447        assert!(
448            result.is_empty(),
449            "SetextWithAtxClosed style should accept setext for h1/h2 and ATX closed for h3+"
450        );
451
452        // Test incorrect usage - regular ATX for h3+
453        let content_wrong = "Heading 1\n=========\n\n### Heading 3\n\n#### Heading 4";
454        let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard, None);
455        let result_wrong = rule.check(&ctx_wrong).unwrap();
456        assert_eq!(
457            result_wrong.len(),
458            2,
459            "Should flag non-closed ATX headings for h3+ with setext_with_atx_closed style"
460        );
461    }
462}