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 for line_info in &ctx.lines {
46 if let Some(heading) = &line_info.heading {
47 return match heading.style {
49 crate::lint_context::HeadingStyle::ATX => {
50 if heading.has_closing_sequence {
51 HeadingStyle::AtxClosed
52 } else {
53 HeadingStyle::Atx
54 }
55 }
56 crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
57 crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
58 };
59 }
60 }
61
62 HeadingStyle::Atx
64 }
65}
66
67impl Rule for MD003HeadingStyle {
68 fn name(&self) -> &'static str {
69 "MD003"
70 }
71
72 fn description(&self) -> &'static str {
73 "Heading style"
74 }
75
76 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
77 let mut result = Vec::new();
78
79 let target_style = self.get_target_style(ctx);
81
82 let line_index = crate::utils::range_utils::LineIndex::new(ctx.content.to_string());
84
85 for (line_num, line_info) in ctx.lines.iter().enumerate() {
87 if let Some(heading) = &line_info.heading {
88 let level = heading.level;
89
90 let current_style = match heading.style {
92 crate::lint_context::HeadingStyle::ATX => {
93 if heading.has_closing_sequence {
94 HeadingStyle::AtxClosed
95 } else {
96 HeadingStyle::Atx
97 }
98 }
99 crate::lint_context::HeadingStyle::Setext1 => HeadingStyle::Setext1,
100 crate::lint_context::HeadingStyle::Setext2 => HeadingStyle::Setext2,
101 };
102
103 let expected_style = match target_style {
105 HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
106 if level > 2 {
107 HeadingStyle::Atx
109 } else if level == 1 {
110 HeadingStyle::Setext1
111 } else {
112 HeadingStyle::Setext2
113 }
114 }
115 HeadingStyle::SetextWithAtx => {
116 if level <= 2 {
117 if level == 1 {
119 HeadingStyle::Setext1
120 } else {
121 HeadingStyle::Setext2
122 }
123 } else {
124 HeadingStyle::Atx
126 }
127 }
128 HeadingStyle::SetextWithAtxClosed => {
129 if level <= 2 {
130 if level == 1 {
132 HeadingStyle::Setext1
133 } else {
134 HeadingStyle::Setext2
135 }
136 } else {
137 HeadingStyle::AtxClosed
139 }
140 }
141 _ => target_style,
142 };
143
144 if current_style != expected_style {
145 let fix = {
147 use crate::rules::heading_utils::HeadingUtils;
148
149 let converted_heading =
151 HeadingUtils::convert_heading_style(&heading.text, level as u32, expected_style);
152
153 let final_heading = format!("{}{}", " ".repeat(line_info.indent), converted_heading);
155
156 let range = line_index.line_content_range(line_num + 1);
158
159 Some(crate::rule::Fix {
160 range,
161 replacement: final_heading,
162 })
163 };
164
165 let (start_line, start_col, end_line, end_col) =
167 calculate_heading_range(line_num + 1, &line_info.content);
168
169 result.push(LintWarning {
170 rule_name: Some(self.name()),
171 line: start_line,
172 column: start_col,
173 end_line,
174 end_column: end_col,
175 message: format!(
176 "Heading style should be {}, found {}",
177 match expected_style {
178 HeadingStyle::Atx => "# Heading",
179 HeadingStyle::AtxClosed => "# Heading #",
180 HeadingStyle::Setext1 => "Heading\n=======",
181 HeadingStyle::Setext2 => "Heading\n-------",
182 HeadingStyle::Consistent => "consistent with the first heading",
183 HeadingStyle::SetextWithAtx => "setext_with_atx style",
184 HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
185 },
186 match current_style {
187 HeadingStyle::Atx => "# Heading",
188 HeadingStyle::AtxClosed => "# Heading #",
189 HeadingStyle::Setext1 => "Heading (underlined with =)",
190 HeadingStyle::Setext2 => "Heading (underlined with -)",
191 HeadingStyle::Consistent => "consistent style",
192 HeadingStyle::SetextWithAtx => "setext_with_atx style",
193 HeadingStyle::SetextWithAtxClosed => "setext_with_atx_closed style",
194 }
195 ),
196 severity: Severity::Warning,
197 fix,
198 });
199 }
200 }
201 }
202
203 Ok(result)
204 }
205
206 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
207 let warnings = self.check(ctx)?;
209
210 if warnings.is_empty() {
212 return Ok(ctx.content.to_string());
213 }
214
215 let mut fixes: Vec<_> = warnings
217 .iter()
218 .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
219 .collect();
220 fixes.sort_by(|a, b| b.0.cmp(&a.0));
221
222 let mut result = ctx.content.to_string();
224 for (start, end, replacement) in fixes {
225 if start < result.len() && end <= result.len() && start <= end {
226 result.replace_range(start..end, replacement);
227 }
228 }
229
230 Ok(result)
231 }
232
233 fn category(&self) -> RuleCategory {
234 RuleCategory::Heading
235 }
236
237 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
238 ctx.content.is_empty() || !ctx.lines.iter().any(|line| line.heading.is_some())
240 }
241
242 fn as_any(&self) -> &dyn std::any::Any {
243 self
244 }
245
246 fn default_config_section(&self) -> Option<(String, toml::Value)> {
247 let default_config = MD003Config::default();
248 let json_value = serde_json::to_value(&default_config).ok()?;
249 let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
250
251 if let toml::Value::Table(table) = toml_value {
252 if !table.is_empty() {
253 Some((MD003Config::RULE_NAME.to_string(), toml::Value::Table(table)))
254 } else {
255 None
256 }
257 } else {
258 None
259 }
260 }
261
262 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
263 where
264 Self: Sized,
265 {
266 let rule_config = crate::rule_config_serde::load_rule_config::<MD003Config>(config);
267 Box::new(Self::from_config_struct(rule_config))
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274 use crate::lint_context::LintContext;
275
276 #[test]
277 fn test_atx_heading_style() {
278 let rule = MD003HeadingStyle::default();
279 let content = "# Heading 1\n## Heading 2\n### Heading 3";
280 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
281 let result = rule.check(&ctx).unwrap();
282 assert!(result.is_empty());
283 }
284
285 #[test]
286 fn test_setext_heading_style() {
287 let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
288 let content = "Heading 1\n=========\n\nHeading 2\n---------";
289 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
290 let result = rule.check(&ctx).unwrap();
291 assert!(result.is_empty());
292 }
293
294 #[test]
295 fn test_front_matter() {
296 let rule = MD003HeadingStyle::default();
297 let content = "---\ntitle: Test\n---\n\n# Heading 1\n## Heading 2";
298
299 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
301 let result = rule.check(&ctx).unwrap();
302 assert!(
303 result.is_empty(),
304 "No warnings expected for content with front matter, found: {result:?}"
305 );
306 }
307
308 #[test]
309 fn test_consistent_heading_style() {
310 let rule = MD003HeadingStyle::default();
312 let content = "# Heading 1\n## Heading 2\n### Heading 3";
313 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
314 let result = rule.check(&ctx).unwrap();
315 assert!(result.is_empty());
316 }
317
318 #[test]
319 fn test_with_different_styles() {
320 let rule = MD003HeadingStyle::new(HeadingStyle::Consistent);
322 let content = "# Heading 1\n## Heading 2\n### Heading 3";
323 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
324 let result = rule.check(&ctx).unwrap();
325
326 assert!(
328 result.is_empty(),
329 "No warnings expected for consistent ATX style, found: {result:?}"
330 );
331
332 let rule = MD003HeadingStyle::new(HeadingStyle::Atx);
334 let content = "# Heading 1 #\nHeading 2\n-----\n### Heading 3";
335 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
336 let result = rule.check(&ctx).unwrap();
337 assert!(
338 !result.is_empty(),
339 "Should have warnings for inconsistent heading styles"
340 );
341
342 let rule = MD003HeadingStyle::new(HeadingStyle::Setext1);
344 let content = "Heading 1\n=========\nHeading 2\n---------\n### Heading 3";
345 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
346 let result = rule.check(&ctx).unwrap();
347 assert!(
349 result.is_empty(),
350 "No warnings expected for setext style with ATX for level 3, found: {result:?}"
351 );
352 }
353
354 #[test]
355 fn test_setext_with_atx_style() {
356 let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtx);
357 let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3\n\n#### Heading 4";
359 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
360 let result = rule.check(&ctx).unwrap();
361 assert!(
362 result.is_empty(),
363 "SesetxtWithAtx style should accept setext for h1/h2 and ATX for h3+"
364 );
365
366 let content_wrong = "# Heading 1\n## Heading 2\n### Heading 3";
368 let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard);
369 let result_wrong = rule.check(&ctx_wrong).unwrap();
370 assert_eq!(
371 result_wrong.len(),
372 2,
373 "Should flag ATX headings for h1/h2 with setext_with_atx style"
374 );
375 }
376
377 #[test]
378 fn test_setext_with_atx_closed_style() {
379 let rule = MD003HeadingStyle::new(HeadingStyle::SetextWithAtxClosed);
380 let content = "Heading 1\n=========\n\nHeading 2\n---------\n\n### Heading 3 ###\n\n#### Heading 4 ####";
382 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
383 let result = rule.check(&ctx).unwrap();
384 assert!(
385 result.is_empty(),
386 "SetextWithAtxClosed style should accept setext for h1/h2 and ATX closed for h3+"
387 );
388
389 let content_wrong = "Heading 1\n=========\n\n### Heading 3\n\n#### Heading 4";
391 let ctx_wrong = LintContext::new(content_wrong, crate::config::MarkdownFlavor::Standard);
392 let result_wrong = rule.check(&ctx_wrong).unwrap();
393 assert_eq!(
394 result_wrong.len(),
395 2,
396 "Should flag non-closed ATX headings for h3+ with setext_with_atx_closed style"
397 );
398 }
399}