1use crate::rule::{LintError, LintResult, LintWarning, Rule, Severity};
2use crate::utils::range_utils::calculate_line_range;
3use crate::utils::table_utils::{TableBlock, TableUtils};
4
5mod md055_config;
6use md055_config::MD055Config;
7
8#[derive(Debug, Default, Clone)]
81pub struct MD055TablePipeStyle {
82 config: MD055Config,
83}
84
85impl MD055TablePipeStyle {
86 pub fn new(style: String) -> Self {
87 Self {
88 config: MD055Config { style },
89 }
90 }
91
92 pub fn from_config_struct(config: MD055Config) -> Self {
93 Self { config }
94 }
95
96 fn determine_table_style(&self, table_block: &TableBlock, lines: &[&str]) -> Option<&'static str> {
98 let mut leading_and_trailing_count = 0;
99 let mut no_leading_or_trailing_count = 0;
100 let mut leading_only_count = 0;
101 let mut trailing_only_count = 0;
102
103 let header_content = TableUtils::extract_table_row_content(lines[table_block.header_line], table_block, 0);
105 if let Some(style) = TableUtils::determine_pipe_style(header_content) {
106 match style {
107 "leading_and_trailing" => leading_and_trailing_count += 1,
108 "no_leading_or_trailing" => no_leading_or_trailing_count += 1,
109 "leading_only" => leading_only_count += 1,
110 "trailing_only" => trailing_only_count += 1,
111 _ => {}
112 }
113 }
114
115 for (i, &line_idx) in table_block.content_lines.iter().enumerate() {
117 let content = TableUtils::extract_table_row_content(lines[line_idx], table_block, 2 + i);
118 if let Some(style) = TableUtils::determine_pipe_style(content) {
119 match style {
120 "leading_and_trailing" => leading_and_trailing_count += 1,
121 "no_leading_or_trailing" => no_leading_or_trailing_count += 1,
122 "leading_only" => leading_only_count += 1,
123 "trailing_only" => trailing_only_count += 1,
124 _ => {}
125 }
126 }
127 }
128
129 let max_count = leading_and_trailing_count
132 .max(no_leading_or_trailing_count)
133 .max(leading_only_count)
134 .max(trailing_only_count);
135
136 if max_count > 0 {
137 if leading_and_trailing_count == max_count {
138 Some("leading_and_trailing")
139 } else if no_leading_or_trailing_count == max_count {
140 Some("no_leading_or_trailing")
141 } else if leading_only_count == max_count {
142 Some("leading_only")
143 } else if trailing_only_count == max_count {
144 Some("trailing_only")
145 } else {
146 None
147 }
148 } else {
149 None
150 }
151 }
152
153 #[cfg(test)]
155 fn fix_table_row(&self, line: &str, target_style: &str) -> String {
156 let dummy_block = TableBlock {
157 start_line: 0,
158 end_line: 0,
159 header_line: 0,
160 delimiter_line: 0,
161 content_lines: vec![],
162 list_context: None,
163 };
164 self.fix_table_row_with_context(line, target_style, &dummy_block, 0)
165 }
166
167 fn fix_table_row_with_context(
172 &self,
173 line: &str,
174 target_style: &str,
175 table_block: &TableBlock,
176 table_line_index: usize,
177 ) -> String {
178 let (bq_prefix, after_bq) = TableUtils::extract_blockquote_prefix(line);
180
181 if let Some(ref list_ctx) = table_block.list_context {
183 if table_line_index == 0 {
184 let stripped = after_bq
186 .strip_prefix(&list_ctx.list_prefix)
187 .unwrap_or_else(|| TableUtils::extract_list_prefix(after_bq).1);
188 let fixed_content = self.fix_table_content(stripped.trim(), target_style);
189
190 let lp = &list_ctx.list_prefix;
192 if bq_prefix.is_empty() && lp.is_empty() {
193 fixed_content
194 } else {
195 format!("{bq_prefix}{lp}{fixed_content}")
196 }
197 } else {
198 let content_indent = list_ctx.content_indent;
200 let stripped = TableUtils::extract_table_row_content(line, table_block, table_line_index);
201 let fixed_content = self.fix_table_content(stripped.trim(), target_style);
202
203 let indent = " ".repeat(content_indent);
205 format!("{bq_prefix}{indent}{fixed_content}")
206 }
207 } else {
208 let fixed_content = self.fix_table_content(after_bq.trim(), target_style);
210 if bq_prefix.is_empty() {
211 fixed_content
212 } else {
213 format!("{bq_prefix}{fixed_content}")
214 }
215 }
216 }
217
218 fn fix_table_content(&self, trimmed: &str, target_style: &str) -> String {
220 if !trimmed.contains('|') {
221 return trimmed.to_string();
222 }
223
224 let has_leading = trimmed.starts_with('|');
225 let has_trailing = trimmed.ends_with('|');
226
227 match target_style {
228 "leading_and_trailing" => {
229 let mut result = trimmed.to_string();
230
231 if !has_leading {
233 result = format!("| {result}");
234 }
235
236 if !has_trailing {
238 result = format!("{result} |");
239 }
240
241 result
242 }
243 "no_leading_or_trailing" => {
244 let mut result = trimmed;
245
246 if has_leading {
248 result = result.strip_prefix('|').unwrap_or(result);
249 result = result.trim_start();
250 }
251
252 if has_trailing {
254 result = result.strip_suffix('|').unwrap_or(result);
255 result = result.trim_end();
256 }
257
258 result.to_string()
259 }
260 "leading_only" => {
261 let mut result = trimmed.to_string();
262
263 if !has_leading {
265 result = format!("| {result}");
266 }
267
268 if has_trailing {
270 result = result.strip_suffix('|').unwrap_or(&result).trim_end().to_string();
271 }
272
273 result
274 }
275 "trailing_only" => {
276 let mut result = trimmed;
277
278 if has_leading {
280 result = result.strip_prefix('|').unwrap_or(result).trim_start();
281 }
282
283 let mut result = result.to_string();
284
285 if !has_trailing {
287 result = format!("{result} |");
288 }
289
290 result
291 }
292 _ => trimmed.to_string(),
293 }
294 }
295}
296
297impl Rule for MD055TablePipeStyle {
298 fn name(&self) -> &'static str {
299 "MD055"
300 }
301
302 fn description(&self) -> &'static str {
303 "Table pipe style should be consistent"
304 }
305
306 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
307 !ctx.likely_has_tables()
309 }
310
311 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
312 let content = ctx.content;
313 let line_index = &ctx.line_index;
314 let mut warnings = Vec::new();
315
316 let lines: Vec<&str> = content.lines().collect();
319
320 let configured_style = match self.config.style.as_str() {
322 "leading_and_trailing" | "no_leading_or_trailing" | "leading_only" | "trailing_only" | "consistent" => {
323 self.config.style.as_str()
324 }
325 _ => {
326 "leading_and_trailing"
328 }
329 };
330
331 let table_blocks = &ctx.table_blocks;
333
334 for table_block in table_blocks {
336 let table_style = if configured_style == "consistent" {
339 self.determine_table_style(table_block, &lines)
340 } else {
341 None
342 };
343
344 let target_style = if configured_style == "consistent" {
346 table_style.unwrap_or("leading_and_trailing")
347 } else {
348 configured_style
349 };
350
351 let all_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
353 .chain(std::iter::once(table_block.delimiter_line))
354 .chain(table_block.content_lines.iter().copied())
355 .collect();
356
357 let table_start_line = table_block.start_line + 1; let table_end_line = table_block.end_line + 1; let mut fixed_table_lines: Vec<String> = Vec::with_capacity(all_line_indices.len());
364 for (table_line_idx, &line_idx) in all_line_indices.iter().enumerate() {
365 let line = lines[line_idx];
366 let fixed_line = self.fix_table_row_with_context(line, target_style, table_block, table_line_idx);
367 if line_idx < lines.len() - 1 {
368 fixed_table_lines.push(format!("{fixed_line}\n"));
369 } else {
370 fixed_table_lines.push(fixed_line);
371 }
372 }
373 let table_replacement = fixed_table_lines.concat();
374 let table_range = line_index.multi_line_range(table_start_line, table_end_line);
375
376 for (table_line_idx, &line_idx) in all_line_indices.iter().enumerate() {
378 let line = lines[line_idx];
379 let content = TableUtils::extract_table_row_content(line, table_block, table_line_idx);
381 if let Some(current_style) = TableUtils::determine_pipe_style(content) {
382 let needs_fixing = current_style != target_style;
384
385 if needs_fixing {
386 let (start_line, start_col, end_line, end_col) = calculate_line_range(line_idx + 1, line);
387
388 let message = format!(
389 "Table pipe style should be {}",
390 match target_style {
391 "leading_and_trailing" => "leading and trailing",
392 "no_leading_or_trailing" => "no leading or trailing",
393 "leading_only" => "leading only",
394 "trailing_only" => "trailing only",
395 _ => target_style,
396 }
397 );
398
399 warnings.push(LintWarning {
402 rule_name: Some(self.name().to_string()),
403 severity: Severity::Warning,
404 message,
405 line: start_line,
406 column: start_col,
407 end_line,
408 end_column: end_col,
409 fix: Some(crate::rule::Fix {
410 range: table_range.clone(),
411 replacement: table_replacement.clone(),
412 }),
413 });
414 }
415 }
416 }
417 }
418
419 Ok(warnings)
420 }
421
422 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
423 let content = ctx.content;
424 let lines: Vec<&str> = content.lines().collect();
425
426 let configured_style = match self.config.style.as_str() {
428 "leading_and_trailing" | "no_leading_or_trailing" | "leading_only" | "trailing_only" | "consistent" => {
429 self.config.style.as_str()
430 }
431 _ => {
432 "leading_and_trailing"
434 }
435 };
436
437 let table_blocks = &ctx.table_blocks;
439
440 let mut result_lines = lines.iter().map(|&s| s.to_string()).collect::<Vec<String>>();
442
443 for table_block in table_blocks {
445 let table_style = if configured_style == "consistent" {
448 self.determine_table_style(table_block, &lines)
449 } else {
450 None
451 };
452
453 let target_style = if configured_style == "consistent" {
455 table_style.unwrap_or("leading_and_trailing")
456 } else {
457 configured_style
458 };
459
460 let all_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
462 .chain(std::iter::once(table_block.delimiter_line))
463 .chain(table_block.content_lines.iter().copied())
464 .collect();
465
466 for (table_line_idx, &line_idx) in all_line_indices.iter().enumerate() {
467 let line = lines[line_idx];
468 let fixed_line = self.fix_table_row_with_context(line, target_style, table_block, table_line_idx);
469 result_lines[line_idx] = fixed_line;
470 }
471 }
472
473 let mut fixed = result_lines.join("\n");
474 if content.ends_with('\n') && !fixed.ends_with('\n') {
476 fixed.push('\n');
477 }
478 Ok(fixed)
479 }
480
481 fn as_any(&self) -> &dyn std::any::Any {
482 self
483 }
484
485 fn default_config_section(&self) -> Option<(String, toml::Value)> {
486 let json_value = serde_json::to_value(&self.config).ok()?;
487 Some((
488 self.name().to_string(),
489 crate::rule_config_serde::json_to_toml_value(&json_value)?,
490 ))
491 }
492
493 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
494 where
495 Self: Sized,
496 {
497 let rule_config = crate::rule_config_serde::load_rule_config::<MD055Config>(config);
498 Box::new(Self::from_config_struct(rule_config))
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505
506 #[test]
507 fn test_md055_delimiter_row_handling() {
508 let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
510
511 let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |";
512 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
513 let result = rule.fix(&ctx).unwrap();
514
515 let expected = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1 | Data 2 | Data 3";
518
519 assert_eq!(result, expected);
520
521 let warnings = rule.check(&ctx).unwrap();
523 let delimiter_warning = &warnings[1]; assert_eq!(delimiter_warning.line, 2);
525 assert_eq!(
526 delimiter_warning.message,
527 "Table pipe style should be no leading or trailing"
528 );
529
530 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
532
533 let content = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1 | Data 2 | Data 3";
534 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
535 let result = rule.fix(&ctx).unwrap();
536
537 let expected = "| Header 1 | Header 2 | Header 3 |\n| ----------|----------|---------- |\n| Data 1 | Data 2 | Data 3 |";
540
541 assert_eq!(result, expected);
542 }
543
544 #[test]
545 fn test_md055_check_finds_delimiter_row_issues() {
546 let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
548
549 let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |";
550 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
551 let warnings = rule.check(&ctx).unwrap();
552
553 assert_eq!(warnings.len(), 3);
555
556 let delimiter_warning = &warnings[1];
558 assert_eq!(delimiter_warning.line, 2);
559 assert_eq!(
560 delimiter_warning.message,
561 "Table pipe style should be no leading or trailing"
562 );
563 }
564
565 #[test]
566 fn test_md055_real_world_example() {
567 let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
569
570 let content = "# Table Example\n\nHere's a table with leading and trailing pipes:\n\n| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |\n| Data 4 | Data 5 | Data 6 |\n\nMore content after the table.";
571 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
572 let result = rule.fix(&ctx).unwrap();
573
574 let expected = "# Table Example\n\nHere's a table with leading and trailing pipes:\n\nHeader 1 | Header 2 | Header 3\n----------|----------|----------\nData 1 | Data 2 | Data 3\nData 4 | Data 5 | Data 6\n\nMore content after the table.";
577
578 assert_eq!(result, expected);
579
580 let warnings = rule.check(&ctx).unwrap();
582 assert_eq!(warnings.len(), 4); assert_eq!(warnings[0].line, 5); assert_eq!(warnings[1].line, 6); assert_eq!(warnings[2].line, 7); assert_eq!(warnings[3].line, 8); }
590
591 #[test]
592 fn test_md055_invalid_style() {
593 let rule = MD055TablePipeStyle::new("leading_or_trailing".to_string()); let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |";
597 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
598 let result = rule.fix(&ctx).unwrap();
599
600 let expected = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1 | Data 2 | Data 3 |";
603
604 assert_eq!(result, expected);
605
606 let content = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1 | Data 2 | Data 3";
608 let ctx2 = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
609 let result = rule.fix(&ctx2).unwrap();
610
611 let expected = "| Header 1 | Header 2 | Header 3 |\n| ----------|----------|---------- |\n| Data 1 | Data 2 | Data 3 |";
614 assert_eq!(result, expected);
615
616 let warnings = rule.check(&ctx2).unwrap();
618
619 assert_eq!(warnings.len(), 3);
622 }
623
624 #[test]
625 fn test_underflow_protection() {
626 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
628
629 let result = rule.fix_table_row("", "leading_and_trailing");
631 assert_eq!(result, "");
632
633 let result = rule.fix_table_row("no pipes here", "leading_and_trailing");
635 assert_eq!(result, "no pipes here");
636
637 let result = rule.fix_table_row("|", "leading_and_trailing");
639 assert!(!result.is_empty());
641 }
642
643 #[test]
646 fn test_fix_table_row_in_blockquote() {
647 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
648
649 let result = rule.fix_table_row("> H1 | H2", "leading_and_trailing");
651 assert_eq!(result, "> | H1 | H2 |");
652
653 let result = rule.fix_table_row("> | H1 | H2 |", "leading_and_trailing");
655 assert_eq!(result, "> | H1 | H2 |");
656
657 let result = rule.fix_table_row("> | H1 | H2 |", "no_leading_or_trailing");
659 assert_eq!(result, "> H1 | H2");
660 }
661
662 #[test]
663 fn test_fix_table_row_in_nested_blockquote() {
664 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
665
666 let result = rule.fix_table_row(">> H1 | H2", "leading_and_trailing");
668 assert_eq!(result, ">> | H1 | H2 |");
669
670 let result = rule.fix_table_row(">>> H1 | H2", "leading_and_trailing");
672 assert_eq!(result, ">>> | H1 | H2 |");
673 }
674
675 #[test]
676 fn test_blockquote_table_full_document() {
677 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
678
679 let content = "> H1 | H2\n> ----|----\n> a | b";
681 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
682 let result = rule.fix(&ctx).unwrap();
683
684 assert!(
687 result.starts_with("> |"),
688 "Header should start with blockquote + pipe. Got:\n{result}"
689 );
690 assert!(
692 result.contains("> | ----"),
693 "Delimiter should have blockquote prefix + leading pipe. Got:\n{result}"
694 );
695 }
696
697 #[test]
698 fn test_blockquote_table_no_leading_trailing() {
699 let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
700
701 let content = "> | H1 | H2 |\n> |----|----|---|\n> | a | b |";
703 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
704 let result = rule.fix(&ctx).unwrap();
705
706 let lines: Vec<&str> = result.lines().collect();
708 assert!(lines[0].starts_with("> "), "Line should start with blockquote prefix");
709 assert!(
710 !lines[0].starts_with("> |"),
711 "Leading pipe should be removed. Got: {}",
712 lines[0]
713 );
714 }
715
716 #[test]
717 fn test_mixed_regular_and_blockquote_tables() {
718 let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
719
720 let content = "H1 | H2\n---|---\na | b\n\n> H3 | H4\n> ---|---\n> c | d";
722 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
723 let result = rule.fix(&ctx).unwrap();
724
725 assert!(result.contains("| H1 | H2 |"), "Regular table should have pipes added");
727 assert!(
728 result.contains("> | H3 | H4 |"),
729 "Blockquote table should have pipes added with prefix preserved"
730 );
731 }
732}