1use 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#[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 fn is_consistent_mode(&self) -> bool {
34 self.config.style == HeadingStyle::Consistent
36 }
37
38 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 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 if !heading.is_valid {
51 continue;
52 }
53
54 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 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 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)) }
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 let target_style = self.get_target_style(ctx);
108
109 for (line_num, line_info) in ctx.lines.iter().enumerate() {
111 if let Some(heading) = &line_info.heading {
112 if !heading.is_valid {
114 continue;
115 }
116
117 let level = heading.level;
118
119 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 let expected_style = match target_style {
134 HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
135 if level > 2 {
136 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 if level == 1 {
148 HeadingStyle::Setext1
149 } else {
150 HeadingStyle::Setext2
151 }
152 } else {
153 HeadingStyle::Atx
155 }
156 }
157 HeadingStyle::SetextWithAtxClosed => {
158 if level <= 2 {
159 if level == 1 {
161 HeadingStyle::Setext1
162 } else {
163 HeadingStyle::Setext2
164 }
165 } else {
166 HeadingStyle::AtxClosed
168 }
169 }
170 _ => target_style,
171 };
172
173 if current_style != expected_style {
174 let fix = {
176 use crate::rules::heading_utils::HeadingUtils;
177
178 let converted_heading =
180 HeadingUtils::convert_heading_style(&heading.raw_text, level as u32, expected_style);
181
182 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 let range = ctx.line_index.line_content_range(line_num + 1);
189
190 Some(crate::rule::Fix::new(range, final_heading))
191 };
192
193 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 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 warnings.is_empty() {
242 return Ok(ctx.content.to_string());
243 }
244
245 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 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 if ctx.content.is_empty() || !ctx.likely_has_headings() {
270 return true;
271 }
272 !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 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 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 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 assert!(
362 result.is_empty(),
363 "No warnings expected for consistent ATX style, found: {result:?}"
364 );
365
366 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 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 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 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 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 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 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 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 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 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}