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(|(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 let target_style = self.get_target_style(ctx);
109
110 for (line_num, line_info) in ctx.lines.iter().enumerate() {
112 if let Some(heading) = &line_info.heading {
113 if !heading.is_valid {
115 continue;
116 }
117
118 let level = heading.level;
119
120 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 let expected_style = match target_style {
135 HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
136 if level > 2 {
137 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 if level == 1 {
149 HeadingStyle::Setext1
150 } else {
151 HeadingStyle::Setext2
152 }
153 } else {
154 HeadingStyle::Atx
156 }
157 }
158 HeadingStyle::SetextWithAtxClosed => {
159 if level <= 2 {
160 if level == 1 {
162 HeadingStyle::Setext1
163 } else {
164 HeadingStyle::Setext2
165 }
166 } else {
167 HeadingStyle::AtxClosed
169 }
170 }
171 _ => target_style,
172 };
173
174 if current_style != expected_style {
175 let fix = {
177 use crate::rules::heading_utils::HeadingUtils;
178
179 let converted_heading =
181 HeadingUtils::convert_heading_style(&heading.text, level as u32, expected_style);
182
183 let final_heading = format!("{}{}", " ".repeat(line_info.indent), converted_heading);
185
186 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 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 let warnings = self.check(ctx)?;
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_setext_with_atx_closed_style() {
413 let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtxClosed);
414 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 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}