1use crate::rule::{LintResult, LintWarning, Rule, RuleCategory, Severity};
7use crate::rule_config_serde::RuleConfig;
8use crate::rules::list_utils::ListType;
9use crate::utils::range_utils::calculate_match_range;
10use toml;
11
12mod md030_config;
13use md030_config::MD030Config;
14
15#[derive(Clone, Default)]
16pub struct MD030ListMarkerSpace {
17 config: MD030Config,
18}
19
20impl MD030ListMarkerSpace {
21 pub fn new(ul_single: usize, ul_multi: usize, ol_single: usize, ol_multi: usize) -> Self {
22 Self {
23 config: MD030Config {
24 ul_single: crate::types::PositiveUsize::new(ul_single)
25 .unwrap_or(crate::types::PositiveUsize::from_const(1)),
26 ul_multi: crate::types::PositiveUsize::new(ul_multi)
27 .unwrap_or(crate::types::PositiveUsize::from_const(1)),
28 ol_single: crate::types::PositiveUsize::new(ol_single)
29 .unwrap_or(crate::types::PositiveUsize::from_const(1)),
30 ol_multi: crate::types::PositiveUsize::new(ol_multi)
31 .unwrap_or(crate::types::PositiveUsize::from_const(1)),
32 },
33 }
34 }
35
36 pub fn from_config_struct(config: MD030Config) -> Self {
37 Self { config }
38 }
39
40 pub fn get_expected_spaces(&self, list_type: ListType, is_multi: bool) -> usize {
41 match (list_type, is_multi) {
42 (ListType::Unordered, false) => self.config.ul_single.get(),
43 (ListType::Unordered, true) => self.config.ul_multi.get(),
44 (ListType::Ordered, false) => self.config.ol_single.get(),
45 (ListType::Ordered, true) => self.config.ol_multi.get(),
46 }
47 }
48}
49
50impl Rule for MD030ListMarkerSpace {
51 fn name(&self) -> &'static str {
52 "MD030"
53 }
54
55 fn description(&self) -> &'static str {
56 "Spaces after list markers should be consistent"
57 }
58
59 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
60 let mut warnings = Vec::new();
61
62 if self.should_skip(ctx) {
64 return Ok(warnings);
65 }
66
67 let mut list_item_lines = Vec::new();
69 for (line_num, line_info) in ctx.lines.iter().enumerate() {
70 if line_info.list_item.is_some() && !line_info.in_code_block {
71 list_item_lines.push(line_num + 1);
72 }
73 }
74
75 let lines: Vec<&str> = ctx.content.lines().collect();
77 let mut in_blockquote = false;
78
79 for line_num in list_item_lines {
80 let line = lines[line_num - 1];
81
82 if line.starts_with(" ") || line.starts_with("\t") {
84 continue;
85 }
86
87 let mut l = line;
89 while l.trim_start().starts_with('>') {
90 l = l.trim_start().trim_start_matches('>').trim_start();
91 in_blockquote = true;
92 }
93 if in_blockquote {
94 in_blockquote = false;
95 continue;
96 }
97
98 if let Some(line_info) = ctx.line_info(line_num)
100 && let Some(list_info) = &line_info.list_item
101 {
102 let list_type = if list_info.is_ordered {
103 ListType::Ordered
104 } else {
105 ListType::Unordered
106 };
107
108 let marker_end = list_info.marker_column + list_info.marker.len();
110 let actual_spaces = list_info.content_column.saturating_sub(marker_end);
111
112 let is_multi_line = self.is_multi_line_list_item(ctx, line_num, &lines);
114 let expected_spaces = self.get_expected_spaces(list_type, is_multi_line);
115
116 if actual_spaces != expected_spaces {
120 let whitespace_start_pos = marker_end;
122 let whitespace_len = actual_spaces;
123
124 let (start_line, start_col, end_line, end_col) =
126 calculate_match_range(line_num, line, whitespace_start_pos, whitespace_len);
127
128 let correct_spaces = " ".repeat(expected_spaces);
130
131 let line_start_byte = ctx.line_offsets.get(line_num - 1).copied().unwrap_or(0);
133 let whitespace_start_byte = line_start_byte + whitespace_start_pos;
134 let whitespace_end_byte = whitespace_start_byte + whitespace_len;
135
136 let fix = Some(crate::rule::Fix {
137 range: whitespace_start_byte..whitespace_end_byte,
138 replacement: correct_spaces,
139 });
140
141 let message =
143 format!("Spaces after list markers (Expected: {expected_spaces}; Actual: {actual_spaces})");
144
145 warnings.push(LintWarning {
146 rule_name: Some(self.name().to_string()),
147 severity: Severity::Warning,
148 line: start_line,
149 column: start_col,
150 end_line,
151 end_column: end_col,
152 message,
153 fix,
154 });
155 }
156 }
157 }
158 Ok(warnings)
159 }
160
161 fn category(&self) -> RuleCategory {
162 RuleCategory::List
163 }
164
165 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
166 if ctx.content.is_empty() {
167 return true;
168 }
169
170 let bytes = ctx.content.as_bytes();
172 !bytes.contains(&b'*')
173 && !bytes.contains(&b'-')
174 && !bytes.contains(&b'+')
175 && !bytes.iter().any(|&b| b.is_ascii_digit())
176 }
177
178 fn as_any(&self) -> &dyn std::any::Any {
179 self
180 }
181
182 fn default_config_section(&self) -> Option<(String, toml::Value)> {
183 let default_config = MD030Config::default();
184 let json_value = serde_json::to_value(&default_config).ok()?;
185 let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;
186
187 if let toml::Value::Table(table) = toml_value {
188 if !table.is_empty() {
189 Some((MD030Config::RULE_NAME.to_string(), toml::Value::Table(table)))
190 } else {
191 None
192 }
193 } else {
194 None
195 }
196 }
197
198 fn from_config(config: &crate::config::Config) -> Box<dyn Rule> {
199 let rule_config = crate::rule_config_serde::load_rule_config::<MD030Config>(config);
200 Box::new(Self::from_config_struct(rule_config))
201 }
202
203 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, crate::rule::LintError> {
204 let content = ctx.content;
205
206 if self.should_skip(ctx) {
208 return Ok(content.to_string());
209 }
210
211 let lines: Vec<&str> = content.lines().collect();
213 let mut result_lines = Vec::with_capacity(lines.len());
214
215 let mut needs_check = vec![false; lines.len()];
217 for (line_idx, line_info) in ctx.lines.iter().enumerate() {
218 if line_info.list_item.is_some() && !line_info.in_code_block {
219 needs_check[line_idx] = true;
220 }
221 }
222
223 for (line_idx, line) in lines.iter().enumerate() {
224 let line_num = line_idx + 1;
225
226 if !needs_check[line_idx] {
228 result_lines.push(line.to_string());
229 continue;
230 }
231
232 if self.is_indented_code_block(line, line_idx, &lines) {
238 result_lines.push(line.to_string());
239 continue;
240 }
241
242 if line.trim_start().starts_with('>') {
244 result_lines.push(line.to_string());
245 continue;
246 }
247
248 let is_multi_line = self.is_multi_line_list_item(ctx, line_num, &lines);
250 if let Some(fixed_line) = self.try_fix_list_marker_spacing_with_context(line, is_multi_line) {
251 result_lines.push(fixed_line);
252 } else {
253 result_lines.push(line.to_string());
254 }
255 }
256
257 let result = result_lines.join("\n");
259 if content.ends_with('\n') && !result.ends_with('\n') {
260 Ok(result + "\n")
261 } else {
262 Ok(result)
263 }
264 }
265}
266
267impl MD030ListMarkerSpace {
268 fn is_multi_line_list_item(&self, ctx: &crate::lint_context::LintContext, line_num: usize, lines: &[&str]) -> bool {
270 let current_line_info = match ctx.line_info(line_num) {
272 Some(info) if info.list_item.is_some() => info,
273 _ => return false,
274 };
275
276 let current_list = current_line_info.list_item.as_ref().unwrap();
277
278 for next_line_num in (line_num + 1)..=lines.len() {
280 if let Some(next_line_info) = ctx.line_info(next_line_num) {
281 if let Some(next_list) = &next_line_info.list_item {
283 if next_list.marker_column <= current_list.marker_column {
284 break; }
286 return true;
288 }
289
290 let line_content = lines.get(next_line_num - 1).unwrap_or(&"");
293 if !line_content.trim().is_empty() {
294 let expected_continuation_indent = current_list.content_column;
295 let actual_indent = line_content.len() - line_content.trim_start().len();
296
297 if actual_indent < expected_continuation_indent {
298 break; }
300
301 if actual_indent >= expected_continuation_indent {
303 return true;
304 }
305 }
306
307 }
309 }
310
311 false
312 }
313
314 fn fix_marker_spacing(
316 &self,
317 marker: &str,
318 after_marker: &str,
319 indent: &str,
320 is_multi_line: bool,
321 is_ordered: bool,
322 ) -> Option<String> {
323 if after_marker.starts_with('\t') {
327 return None;
328 }
329
330 if after_marker.starts_with(" ") {
332 let content = after_marker.trim_start_matches(' ');
333 if !content.is_empty() {
334 let spaces = if is_ordered {
336 if is_multi_line {
337 " ".repeat(self.config.ol_multi.get())
338 } else {
339 " ".repeat(self.config.ol_single.get())
340 }
341 } else if is_multi_line {
342 " ".repeat(self.config.ul_multi.get())
343 } else {
344 " ".repeat(self.config.ul_single.get())
345 };
346 return Some(format!("{indent}{marker}{spaces}{content}"));
347 }
348 }
349 None
350 }
351
352 fn try_fix_list_marker_spacing_with_context(&self, line: &str, is_multi_line: bool) -> Option<String> {
354 let trimmed = line.trim_start();
355 let indent = &line[..line.len() - trimmed.len()];
356
357 for marker in &["*", "-", "+"] {
359 if let Some(after_marker) = trimmed.strip_prefix(marker) {
360 if let Some(fixed) = self.fix_marker_spacing(marker, after_marker, indent, is_multi_line, false) {
361 return Some(fixed);
362 }
363 break; }
365 }
366
367 if let Some(dot_pos) = trimmed.find('.') {
369 let before_dot = &trimmed[..dot_pos];
370 if before_dot.chars().all(|c| c.is_ascii_digit()) && !before_dot.is_empty() {
371 let after_dot = &trimmed[dot_pos + 1..];
372 let marker = format!("{before_dot}.");
373 if let Some(fixed) = self.fix_marker_spacing(&marker, after_dot, indent, is_multi_line, true) {
374 return Some(fixed);
375 }
376 }
377 }
378
379 None
380 }
381
382 fn is_indented_code_block(&self, line: &str, line_idx: usize, lines: &[&str]) -> bool {
386 if !line.starts_with(" ") && !line.starts_with('\t') {
388 return false;
389 }
390
391 if line_idx == 0 {
393 return false;
394 }
395
396 if self.has_blank_line_before_indented_block(line_idx, lines) {
398 return true;
399 }
400
401 false
402 }
403
404 fn has_blank_line_before_indented_block(&self, line_idx: usize, lines: &[&str]) -> bool {
406 let mut current_idx = line_idx;
408
409 while current_idx > 0 {
411 let current_line = lines[current_idx];
412 let prev_line = lines[current_idx - 1];
413
414 if !current_line.starts_with(" ") && !current_line.starts_with('\t') {
416 break;
417 }
418
419 if !prev_line.starts_with(" ") && !prev_line.starts_with('\t') {
421 return prev_line.trim().is_empty();
422 }
423
424 current_idx -= 1;
425 }
426
427 false
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use crate::lint_context::LintContext;
435
436 #[test]
437 fn test_basic_functionality() {
438 let rule = MD030ListMarkerSpace::default();
439 let content = "* Item 1\n* Item 2\n * Nested item\n1. Ordered item";
440 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
441 let result = rule.check(&ctx).unwrap();
442 assert!(
443 result.is_empty(),
444 "Correctly spaced list markers should not generate warnings"
445 );
446 let content = "* Item 1 (too many spaces)\n* Item 2\n1. Ordered item (too many spaces)";
447 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
448 let result = rule.check(&ctx).unwrap();
449 assert_eq!(
451 result.len(),
452 2,
453 "Should flag lines with too many spaces after list marker"
454 );
455 for warning in result {
456 assert!(
457 warning.message.starts_with("Spaces after list markers (Expected:")
458 && warning.message.contains("Actual:"),
459 "Warning message should include expected and actual values, got: '{}'",
460 warning.message
461 );
462 }
463 }
464}