1use crate::lint_context::ParsedListItem;
5use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
6use crate::utils::range_utils::byte_to_char_count;
7use crate::utils::regex_cache::ORDERED_LIST_MARKER_REGEX;
8use std::collections::HashMap;
9use toml;
10
11mod md029_config;
12pub use md029_config::ListStyle;
13pub(super) use md029_config::MD029Config;
14
15#[derive(Debug, Clone, Default)]
16pub struct MD029OrderedListPrefix {
17 config: MD029Config,
18}
19
20impl MD029OrderedListPrefix {
21 pub fn new(style: ListStyle) -> Self {
22 Self {
23 config: MD029Config { style },
24 }
25 }
26
27 pub fn from_config_struct(config: MD029Config) -> Self {
28 Self { config }
29 }
30
31 #[inline]
32 fn parse_marker_number(marker: &str) -> Option<usize> {
33 let num_part = if let Some(stripped) = marker.strip_suffix('.') {
35 stripped
36 } else {
37 marker
38 };
39 num_part.parse::<usize>().ok()
40 }
41
42 #[inline]
46 fn get_expected_number(&self, index: usize, detected_style: Option<ListStyle>, start_value: u64) -> usize {
47 let style = match self.config.style {
50 ListStyle::OneOrOrdered | ListStyle::Consistent => detected_style.unwrap_or(ListStyle::OneOne),
51 _ => self.config.style,
52 };
53
54 match style {
55 ListStyle::One | ListStyle::OneOne => 1,
56 ListStyle::Ordered => (start_value as usize) + index,
57 ListStyle::Ordered0 => index,
58 ListStyle::OneOrOrdered | ListStyle::Consistent => {
59 1
61 }
62 }
63 }
64
65 fn detect_list_style(items: &[ParsedListItem<'_>], start_value: u64) -> ListStyle {
68 if items.len() < 2 {
69 let first_num = Self::parse_marker_number(items[0].marker());
73 if first_num == Some(start_value as usize) {
74 return ListStyle::Ordered;
75 }
76 return ListStyle::OneOne;
77 }
78
79 let first_num = Self::parse_marker_number(items[0].marker());
80 let second_num = Self::parse_marker_number(items[1].marker());
81
82 if matches!((first_num, second_num), (Some(0), Some(1))) {
84 return ListStyle::Ordered0;
85 }
86
87 if first_num != Some(1) || second_num != Some(1) {
90 return ListStyle::Ordered;
91 }
92
93 let all_ones = items
96 .iter()
97 .all(|item| Self::parse_marker_number(item.marker()) == Some(1));
98
99 if all_ones {
100 ListStyle::OneOne
101 } else {
102 ListStyle::Ordered
103 }
104 }
105
106 fn check_commonmark_list_group(
110 &self,
111 ctx: &crate::lint_context::LintContext,
112 group: &[ParsedListItem<'_>],
113 warnings: &mut Vec<LintWarning>,
114 document_wide_style: Option<ListStyle>,
115 start_value: u64,
116 ) {
117 if group.is_empty() {
118 return;
119 }
120
121 type LevelGroups<'a> = HashMap<usize, Vec<ParsedListItem<'a>>>;
123 let mut level_groups: LevelGroups = HashMap::new();
124
125 for &list_item in group {
126 level_groups
127 .entry(list_item.marker_column())
128 .or_default()
129 .push(list_item);
130 }
131
132 let mut sorted_levels: Vec<_> = level_groups.into_iter().collect();
134 sorted_levels.sort_by_key(|(indent, _)| *indent);
135
136 for (_indent, mut items) in sorted_levels {
137 items.sort_by_key(|item| item.line_num());
139
140 if items.is_empty() {
141 continue;
142 }
143
144 let detected_style = if let Some(doc_style) = document_wide_style {
146 Some(doc_style)
147 } else if self.config.style == ListStyle::OneOrOrdered {
148 Some(Self::detect_list_style(&items, start_value))
149 } else {
150 None
151 };
152
153 for (idx, list_item) in items.iter().copied().enumerate() {
155 if let Some(actual_num) = Self::parse_marker_number(list_item.marker()) {
156 let expected_num = self.get_expected_number(idx, detected_style, start_value);
157
158 if actual_num != expected_num {
159 let line_num = list_item.line_num();
160 let line_info = list_item.line_info();
161 let marker_start = list_item.marker_byte_offset();
162 let number_len = if let Some(dot_pos) = list_item.marker().find('.') {
163 dot_pos
164 } else if let Some(paren_pos) = list_item.marker().find(')') {
165 paren_pos
166 } else {
167 list_item.marker().len()
168 };
169
170 let style_name = match detected_style.as_ref().unwrap_or(&ListStyle::Ordered) {
171 ListStyle::OneOne => "one",
172 ListStyle::Ordered => "ordered",
173 ListStyle::Ordered0 => "ordered0",
174 _ => "ordered",
175 };
176
177 let style_context = match self.config.style {
178 ListStyle::Consistent => format!("document style '{style_name}'"),
179 ListStyle::OneOrOrdered => format!("list style '{style_name}'"),
180 ListStyle::One | ListStyle::OneOne => "configured style 'one'".to_string(),
181 ListStyle::Ordered => "configured style 'ordered'".to_string(),
182 ListStyle::Ordered0 => "configured style 'ordered0'".to_string(),
183 };
184
185 let should_provide_fix =
191 start_value == 1 || matches!(self.config.style, ListStyle::One | ListStyle::OneOne);
192
193 let line_text = line_info.content(ctx.content);
196
197 warnings.push(LintWarning {
198 rule_name: Some(self.name().to_string()),
199 message: format!(
200 "Ordered list item number {actual_num} does not match {style_context} (expected {expected_num})"
201 ),
202 line: line_num,
203 column: byte_to_char_count(line_text, list_item.marker_column()),
204 end_line: line_num,
205 end_column: byte_to_char_count(line_text, list_item.marker_column() + number_len),
206 severity: Severity::Warning,
207 fix: if should_provide_fix {
208 Some(Fix::new(marker_start..marker_start + number_len, expected_num.to_string()))
209 } else {
210 None
211 },
212 });
213 }
214 }
215 }
216 }
217 }
218}
219
220impl Rule for MD029OrderedListPrefix {
221 fn name(&self) -> &'static str {
222 "MD029"
223 }
224
225 fn description(&self) -> &'static str {
226 "Ordered list marker value"
227 }
228
229 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
230 if ctx.content.is_empty() {
232 return Ok(Vec::new());
233 }
234
235 if (!ctx.content.contains('.') && !ctx.content.contains(')'))
237 || !ctx.content.lines().any(|line| ORDERED_LIST_MARKER_REGEX.is_match(line))
238 {
239 return Ok(Vec::new());
240 }
241
242 let mut warnings = Vec::new();
243
244 let list_groups = ctx.commonmark_ordered_lists();
248
249 if list_groups.is_empty() {
250 return Ok(Vec::new());
251 }
252
253 let document_wide_style = if self.config.style == ListStyle::Consistent {
255 let mut all_document_items = Vec::new();
257 for list in list_groups {
258 all_document_items.extend(list.items());
259 }
260 if !all_document_items.is_empty() {
262 Some(Self::detect_list_style(&all_document_items, 1))
263 } else {
264 None
265 }
266 } else {
267 None
268 };
269
270 for list in list_groups {
272 let items: Vec<_> = list.items().collect();
273 self.check_commonmark_list_group(ctx, &items, &mut warnings, document_wide_style, list.start_value());
274 }
275
276 warnings.sort_by_key(|w| (w.line, w.column));
278
279 Ok(warnings)
280 }
281
282 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
283 let warnings = self.check(ctx)?;
287 if warnings.is_empty() {
288 return Ok(ctx.content.to_string());
289 }
290 let warnings =
291 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
292 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings).map_err(LintError::InvalidInput)
293 }
294
295 fn category(&self) -> RuleCategory {
297 RuleCategory::List
298 }
299
300 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
302 ctx.content.is_empty() || !ctx.likely_has_lists()
303 }
304
305 fn as_any(&self) -> &dyn std::any::Any {
306 self
307 }
308
309 crate::impl_rule_config_methods!(MD029Config);
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn test_basic_functionality() {
318 let rule = MD029OrderedListPrefix::default();
320
321 let content = "1. First item\n2. Second item\n3. Third item";
323 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
324 let result = rule.check(&ctx).unwrap();
325 assert!(result.is_empty());
326
327 let content = "1. First item\n3. Third item\n5. Fifth item";
329 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
330 let result = rule.check(&ctx).unwrap();
331 assert_eq!(result.len(), 2); let rule = MD029OrderedListPrefix::new(ListStyle::OneOne);
335 let content = "1. First item\n2. Second item\n3. Third item";
336 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
337 let result = rule.check(&ctx).unwrap();
338 assert_eq!(result.len(), 2); let rule = MD029OrderedListPrefix::new(ListStyle::Ordered0);
342 let content = "0. First item\n1. Second item\n2. Third item";
343 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
344 let result = rule.check(&ctx).unwrap();
345 assert!(result.is_empty());
346 }
347
348 #[test]
349 fn test_redundant_computation_fix() {
350 let rule = MD029OrderedListPrefix::default();
355
356 let content = "1. First item\n3. Wrong number\n2. Another wrong number";
358 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
359
360 let result = rule.check(&ctx).unwrap();
362 assert_eq!(result.len(), 2); assert!(result[0].message.contains('3') && result[0].message.contains("expected 2"));
366 assert!(result[1].message.contains('2') && result[1].message.contains("expected 3"));
367 }
368
369 #[test]
370 fn test_performance_improvement() {
371 let rule = MD029OrderedListPrefix::default();
373
374 let mut content = String::from("1. Item 1\n"); for i in 2..=100 {
379 content.push_str(&format!("{}. Item {}\n", i * 5 - 5, i)); }
381
382 let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
383
384 let result = rule.check(&ctx).unwrap();
386 assert_eq!(result.len(), 99, "Should have warnings for items 2-100 (99 items)");
387
388 assert!(result[0].message.contains('5') && result[0].message.contains("expected 2"));
390 }
391
392 #[test]
393 fn test_one_or_ordered_with_all_ones() {
394 let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
396
397 let content = "1. First item\n1. Second item\n1. Third item";
398 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
399 let result = rule.check(&ctx).unwrap();
400 assert!(result.is_empty(), "All ones should be valid in OneOrOrdered mode");
401 }
402
403 #[test]
404 fn test_one_or_ordered_with_sequential() {
405 let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
407
408 let content = "1. First item\n2. Second item\n3. Third item";
409 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
410 let result = rule.check(&ctx).unwrap();
411 assert!(
412 result.is_empty(),
413 "Sequential numbering should be valid in OneOrOrdered mode"
414 );
415 }
416
417 #[test]
418 fn test_one_or_ordered_with_mixed_style() {
419 let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
421
422 let content = "1. First item\n2. Second item\n1. Third item";
423 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
424 let result = rule.check(&ctx).unwrap();
425 assert_eq!(result.len(), 1, "Mixed style should produce one warning");
426 assert!(result[0].message.contains('1') && result[0].message.contains("expected 3"));
427 }
428
429 #[test]
430 fn test_one_or_ordered_separate_lists() {
431 let rule = MD029OrderedListPrefix::new(ListStyle::OneOrOrdered);
433
434 let content = "# First list\n\n1. Item A\n1. Item B\n\n# Second list\n\n1. Item X\n2. Item Y\n3. Item Z";
435 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
436 let result = rule.check(&ctx).unwrap();
437 assert!(
438 result.is_empty(),
439 "Separate lists can use different styles in OneOrOrdered mode"
440 );
441 }
442
443 #[test]
446 fn test_check_and_fix_produce_identical_replacements() {
447 let rule = MD029OrderedListPrefix::default();
448
449 let inputs = [
450 "1. First\n3. Skip\n5. Skip\n",
451 "1. First\n3. Third\n2. Second\n",
452 "1. A\n\n3. B\n",
453 "- Unordered\n\n1. A\n3. B\n",
454 "1. A\n 1. Nested wrong\n 3. Nested\n2. B\n",
455 ];
456
457 for input in &inputs {
458 let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
459 let warnings = rule.check(&ctx).unwrap();
460 let fixed = rule.fix(&ctx).unwrap();
461
462 let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
464 let fixed_twice = rule.fix(&ctx2).unwrap();
465 assert_eq!(
466 fixed, fixed_twice,
467 "fix() is not idempotent for input: {input:?}\nfirst: {fixed:?}\nsecond: {fixed_twice:?}"
468 );
469
470 let warnings_after = rule.check(&ctx2).unwrap();
472 assert!(
473 warnings_after.is_empty(),
474 "check() should produce no warnings after fix() for input: {input:?}\nfixed: {fixed:?}\nremaining: {warnings_after:?}"
475 );
476
477 for warning in &warnings {
480 if let Some(ref fix) = warning.fix {
481 assert!(
482 fix.range.end <= input.len(),
483 "Fix range exceeds input length for {input:?}"
484 );
485 }
486 }
487 }
488 }
489
490 #[test]
492 fn test_fix_idempotent() {
493 let rule = MD029OrderedListPrefix::default();
494
495 let inputs = [
496 "1. A\n3. B\n5. C\n",
497 "# Intro\n\n1. First\n3. Third\n",
498 "1. A\n1. B\n1. C\n",
499 ];
500
501 for input in &inputs {
502 let ctx1 = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
503 let fixed_once = rule.fix(&ctx1).unwrap();
504 let ctx2 =
505 crate::lint_context::LintContext::new(&fixed_once, crate::config::MarkdownFlavor::Standard, None);
506 let fixed_twice = rule.fix(&ctx2).unwrap();
507 assert_eq!(fixed_once, fixed_twice, "fix() is not idempotent for input: {input:?}");
508 }
509 }
510
511 #[test]
514 fn test_pandoc_skips_example_list_markers() {
515 use crate::config::MarkdownFlavor;
516 use crate::lint_context::LintContext;
517 let rule = MD029OrderedListPrefix::default();
518 let content = "(@) First.\n(@good) Second.\n(@) Third.\n";
519 let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
520 let result = rule.check(&ctx).unwrap();
521 assert!(
522 result.is_empty(),
523 "MD029 should not flag (@)/(@label) example markers under Pandoc: {result:?}"
524 );
525 }
526
527 #[test]
530 fn test_pandoc_example_markers_do_not_break_real_ordered_list() {
531 use crate::config::MarkdownFlavor;
532 use crate::lint_context::LintContext;
533 let rule = MD029OrderedListPrefix::default();
534 let content = "1. Real first.\n\n(@) Example.\n\n2. Real second.\n";
535 let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
536 let result = rule.check(&ctx).unwrap();
537 assert!(
538 result.is_empty(),
539 "MD029 should validate the digit-prefixed sequence and skip the example marker: {result:?}"
540 );
541 }
542
543 #[test]
546 fn test_fix_preserves_non_default_start_value() {
547 let rule = MD029OrderedListPrefix::default();
548
549 let content = "11. First\n14. Fourth\n";
552 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
553 let warnings = rule.check(&ctx).unwrap();
554 assert!(!warnings.is_empty(), "Should produce warnings for misnumbered list");
556 assert!(
557 warnings.iter().all(|w| w.fix.is_none()),
558 "Should not provide auto-fix for lists starting at non-1 values"
559 );
560 let fixed = rule.fix(&ctx).unwrap();
562 assert_eq!(
563 fixed, content,
564 "Content should be unchanged when no fixes are available"
565 );
566 }
567
568 #[test]
569 fn test_md029_front_matter() {
570 let rule = MD029OrderedListPrefix::default();
571 let content = "---\n1. key: value\n3. key2: value2\n---\n1. Item 1\n2. Item 2\n";
572 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
573 let result = rule.check(&ctx).unwrap();
574 assert!(
575 result.is_empty(),
576 "Should not flag list-like items in front-matter: {result:?}"
577 );
578 }
579}