1use crate::rule::{LintError, LintResult, LintWarning, Rule, Severity};
2use crate::utils::range_utils::calculate_line_range;
3use crate::utils::table_utils::TableUtils;
4use unicode_width::UnicodeWidthStr;
5
6mod md060_config;
7use crate::md013_line_length::MD013Config;
8use md060_config::MD060Config;
9
10#[derive(Debug, Clone, Copy, PartialEq)]
11enum ColumnAlignment {
12 Left,
13 Center,
14 Right,
15}
16
17#[derive(Debug, Clone)]
18struct TableFormatResult {
19 lines: Vec<String>,
20 auto_compacted: bool,
21 aligned_width: Option<usize>,
22}
23
24#[derive(Debug, Clone)]
143pub struct MD060TableFormat {
144 config: MD060Config,
145 md013_line_length: usize,
146}
147
148impl Default for MD060TableFormat {
149 fn default() -> Self {
150 Self {
151 config: MD060Config::default(),
152 md013_line_length: 80,
153 }
154 }
155}
156
157impl MD060TableFormat {
158 pub fn new(enabled: bool, style: String) -> Self {
159 use crate::types::LineLength;
160 Self {
161 config: MD060Config {
162 enabled,
163 style,
164 max_width: LineLength::from_const(0),
165 },
166 md013_line_length: 80, }
168 }
169
170 pub fn from_config_struct(config: MD060Config, md013_line_length: usize) -> Self {
171 Self {
172 config,
173 md013_line_length,
174 }
175 }
176
177 fn effective_max_width(&self) -> usize {
182 if self.config.max_width.is_unlimited() {
183 self.md013_line_length
184 } else {
185 self.config.max_width.get()
186 }
187 }
188
189 fn contains_problematic_chars(text: &str) -> bool {
200 text.contains('\u{200D}') || text.contains('\u{200B}') || text.contains('\u{200C}') || text.contains('\u{2060}') }
205
206 fn calculate_cell_display_width(cell_content: &str) -> usize {
207 let masked = TableUtils::mask_pipes_in_inline_code(cell_content);
208 masked.trim().width()
209 }
210
211 fn parse_table_row(line: &str) -> Vec<String> {
212 let trimmed = line.trim();
213 let masked = TableUtils::mask_pipes_for_table_parsing(trimmed);
214
215 let has_leading = masked.starts_with('|');
216 let has_trailing = masked.ends_with('|');
217
218 let mut masked_content = masked.as_str();
219 let mut orig_content = trimmed;
220
221 if has_leading {
222 masked_content = &masked_content[1..];
223 orig_content = &orig_content[1..];
224 }
225 if has_trailing && !masked_content.is_empty() {
226 masked_content = &masked_content[..masked_content.len() - 1];
227 orig_content = &orig_content[..orig_content.len() - 1];
228 }
229
230 let masked_parts: Vec<&str> = masked_content.split('|').collect();
231 let mut cells = Vec::new();
232 let mut pos = 0;
233
234 for masked_cell in masked_parts {
235 let cell_len = masked_cell.len();
236 let orig_cell = if pos + cell_len <= orig_content.len() {
237 &orig_content[pos..pos + cell_len]
238 } else {
239 masked_cell
240 };
241 cells.push(orig_cell.to_string());
242 pos += cell_len + 1;
243 }
244
245 cells
246 }
247
248 fn is_delimiter_row(row: &[String]) -> bool {
249 if row.is_empty() {
250 return false;
251 }
252 row.iter().all(|cell| {
253 let trimmed = cell.trim();
254 !trimmed.is_empty()
257 && trimmed.contains('-')
258 && trimmed.chars().all(|c| c == '-' || c == ':' || c.is_whitespace())
259 })
260 }
261
262 fn parse_column_alignments(delimiter_row: &[String]) -> Vec<ColumnAlignment> {
263 delimiter_row
264 .iter()
265 .map(|cell| {
266 let trimmed = cell.trim();
267 let has_left_colon = trimmed.starts_with(':');
268 let has_right_colon = trimmed.ends_with(':');
269
270 match (has_left_colon, has_right_colon) {
271 (true, true) => ColumnAlignment::Center,
272 (false, true) => ColumnAlignment::Right,
273 _ => ColumnAlignment::Left,
274 }
275 })
276 .collect()
277 }
278
279 fn calculate_column_widths(table_lines: &[&str]) -> Vec<usize> {
280 let mut column_widths = Vec::new();
281 let mut delimiter_cells: Option<Vec<String>> = None;
282
283 for line in table_lines {
284 let cells = Self::parse_table_row(line);
285
286 if Self::is_delimiter_row(&cells) {
288 delimiter_cells = Some(cells);
289 continue;
290 }
291
292 for (i, cell) in cells.iter().enumerate() {
293 let width = Self::calculate_cell_display_width(cell);
294 if i >= column_widths.len() {
295 column_widths.push(width);
296 } else {
297 column_widths[i] = column_widths[i].max(width);
298 }
299 }
300 }
301
302 let mut final_widths: Vec<usize> = column_widths.iter().map(|&w| w.max(3)).collect();
305
306 if let Some(delimiter_cells) = delimiter_cells {
309 for (i, cell) in delimiter_cells.iter().enumerate() {
310 if i < final_widths.len() {
311 let trimmed = cell.trim();
312 let has_left_colon = trimmed.starts_with(':');
313 let has_right_colon = trimmed.ends_with(':');
314 let colon_count = (has_left_colon as usize) + (has_right_colon as usize);
315
316 let min_width_for_delimiter = 3 + colon_count;
318 final_widths[i] = final_widths[i].max(min_width_for_delimiter);
319 }
320 }
321 }
322
323 final_widths
324 }
325
326 fn format_table_row(
327 cells: &[String],
328 column_widths: &[usize],
329 column_alignments: &[ColumnAlignment],
330 is_delimiter: bool,
331 ) -> String {
332 let formatted_cells: Vec<String> = cells
333 .iter()
334 .enumerate()
335 .map(|(i, cell)| {
336 let target_width = column_widths.get(i).copied().unwrap_or(0);
337 if is_delimiter {
338 let trimmed = cell.trim();
339 let has_left_colon = trimmed.starts_with(':');
340 let has_right_colon = trimmed.ends_with(':');
341
342 let dash_count = if has_left_colon && has_right_colon {
345 target_width.saturating_sub(2)
346 } else if has_left_colon || has_right_colon {
347 target_width.saturating_sub(1)
348 } else {
349 target_width
350 };
351
352 let dashes = "-".repeat(dash_count.max(3)); let delimiter_content = if has_left_colon && has_right_colon {
354 format!(":{dashes}:")
355 } else if has_left_colon {
356 format!(":{dashes}")
357 } else if has_right_colon {
358 format!("{dashes}:")
359 } else {
360 dashes
361 };
362
363 format!(" {delimiter_content} ")
365 } else {
366 let trimmed = cell.trim();
367 let current_width = Self::calculate_cell_display_width(cell);
368 let padding = target_width.saturating_sub(current_width);
369
370 let alignment = column_alignments.get(i).copied().unwrap_or(ColumnAlignment::Left);
372 match alignment {
373 ColumnAlignment::Left => {
374 format!(" {trimmed}{} ", " ".repeat(padding))
376 }
377 ColumnAlignment::Center => {
378 let left_padding = padding / 2;
380 let right_padding = padding - left_padding;
381 format!(" {}{trimmed}{} ", " ".repeat(left_padding), " ".repeat(right_padding))
382 }
383 ColumnAlignment::Right => {
384 format!(" {}{trimmed} ", " ".repeat(padding))
386 }
387 }
388 }
389 })
390 .collect();
391
392 format!("|{}|", formatted_cells.join("|"))
393 }
394
395 fn format_table_compact(cells: &[String]) -> String {
396 let formatted_cells: Vec<String> = cells.iter().map(|cell| format!(" {} ", cell.trim())).collect();
397 format!("|{}|", formatted_cells.join("|"))
398 }
399
400 fn format_table_tight(cells: &[String]) -> String {
401 let formatted_cells: Vec<String> = cells.iter().map(|cell| cell.trim().to_string()).collect();
402 format!("|{}|", formatted_cells.join("|"))
403 }
404
405 fn detect_table_style(table_lines: &[&str]) -> Option<String> {
406 if table_lines.is_empty() {
407 return None;
408 }
409
410 let first_line = table_lines[0];
411 let cells = Self::parse_table_row(first_line);
412
413 if cells.is_empty() {
414 return None;
415 }
416
417 let has_no_padding = cells.iter().all(|cell| !cell.starts_with(' ') && !cell.ends_with(' '));
418
419 let has_single_space = cells.iter().all(|cell| {
420 let trimmed = cell.trim();
421 cell == &format!(" {trimmed} ")
422 });
423
424 if has_no_padding {
425 Some("tight".to_string())
426 } else if has_single_space {
427 Some("compact".to_string())
428 } else {
429 Some("aligned".to_string())
430 }
431 }
432
433 fn fix_table_block(
434 &self,
435 lines: &[&str],
436 table_block: &crate::utils::table_utils::TableBlock,
437 ) -> TableFormatResult {
438 let mut result = Vec::new();
439 let mut auto_compacted = false;
440 let mut aligned_width = None;
441
442 let table_lines: Vec<&str> = std::iter::once(lines[table_block.header_line])
443 .chain(std::iter::once(lines[table_block.delimiter_line]))
444 .chain(table_block.content_lines.iter().map(|&idx| lines[idx]))
445 .collect();
446
447 if table_lines.iter().any(|line| Self::contains_problematic_chars(line)) {
448 return TableFormatResult {
449 lines: table_lines.iter().map(|s| s.to_string()).collect(),
450 auto_compacted: false,
451 aligned_width: None,
452 };
453 }
454
455 let style = self.config.style.as_str();
456
457 match style {
458 "any" => {
459 let detected_style = Self::detect_table_style(&table_lines);
460 if detected_style.is_none() {
461 return TableFormatResult {
462 lines: table_lines.iter().map(|s| s.to_string()).collect(),
463 auto_compacted: false,
464 aligned_width: None,
465 };
466 }
467
468 let target_style = detected_style.unwrap();
469
470 let delimiter_cells = Self::parse_table_row(table_lines[1]);
472 let column_alignments = Self::parse_column_alignments(&delimiter_cells);
473
474 for line in &table_lines {
475 let cells = Self::parse_table_row(line);
476 match target_style.as_str() {
477 "tight" => result.push(Self::format_table_tight(&cells)),
478 "compact" => result.push(Self::format_table_compact(&cells)),
479 _ => {
480 let column_widths = Self::calculate_column_widths(&table_lines);
481 let is_delimiter = Self::is_delimiter_row(&cells);
482 result.push(Self::format_table_row(
483 &cells,
484 &column_widths,
485 &column_alignments,
486 is_delimiter,
487 ));
488 }
489 }
490 }
491 }
492 "compact" => {
493 for line in table_lines {
494 let cells = Self::parse_table_row(line);
495 result.push(Self::format_table_compact(&cells));
496 }
497 }
498 "tight" => {
499 for line in table_lines {
500 let cells = Self::parse_table_row(line);
501 result.push(Self::format_table_tight(&cells));
502 }
503 }
504 "aligned" => {
505 let column_widths = Self::calculate_column_widths(&table_lines);
506
507 let num_columns = column_widths.len();
509 let calc_aligned_width = 1 + (num_columns * 3) + column_widths.iter().sum::<usize>();
510 aligned_width = Some(calc_aligned_width);
511
512 if calc_aligned_width > self.effective_max_width() {
514 auto_compacted = true;
515 for line in table_lines {
516 let cells = Self::parse_table_row(line);
517 result.push(Self::format_table_compact(&cells));
518 }
519 } else {
520 let delimiter_cells = Self::parse_table_row(table_lines[1]);
522 let column_alignments = Self::parse_column_alignments(&delimiter_cells);
523
524 for line in table_lines {
525 let cells = Self::parse_table_row(line);
526 let is_delimiter = Self::is_delimiter_row(&cells);
527 result.push(Self::format_table_row(
528 &cells,
529 &column_widths,
530 &column_alignments,
531 is_delimiter,
532 ));
533 }
534 }
535 }
536 _ => {
537 return TableFormatResult {
538 lines: table_lines.iter().map(|s| s.to_string()).collect(),
539 auto_compacted: false,
540 aligned_width: None,
541 };
542 }
543 }
544
545 TableFormatResult {
546 lines: result,
547 auto_compacted,
548 aligned_width,
549 }
550 }
551}
552
553impl Rule for MD060TableFormat {
554 fn name(&self) -> &'static str {
555 "MD060"
556 }
557
558 fn description(&self) -> &'static str {
559 "Table columns should be consistently aligned"
560 }
561
562 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
563 !self.config.enabled || !ctx.likely_has_tables()
564 }
565
566 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
567 if !self.config.enabled {
568 return Ok(Vec::new());
569 }
570
571 let content = ctx.content;
572 let line_index = &ctx.line_index;
573 let mut warnings = Vec::new();
574
575 let lines: Vec<&str> = content.lines().collect();
576 let table_blocks = &ctx.table_blocks;
577
578 for table_block in table_blocks {
579 let format_result = self.fix_table_block(&lines, table_block);
580
581 let table_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
582 .chain(std::iter::once(table_block.delimiter_line))
583 .chain(table_block.content_lines.iter().copied())
584 .collect();
585
586 for (i, &line_idx) in table_line_indices.iter().enumerate() {
587 let original = lines[line_idx];
588 let fixed = &format_result.lines[i];
589
590 if original != fixed {
591 let (start_line, start_col, end_line, end_col) = calculate_line_range(line_idx + 1, original);
592
593 let message = if format_result.auto_compacted {
594 if let Some(width) = format_result.aligned_width {
595 format!(
596 "Table too wide for aligned formatting ({} chars > max-width: {})",
597 width,
598 self.effective_max_width()
599 )
600 } else {
601 "Table too wide for aligned formatting".to_string()
602 }
603 } else {
604 "Table columns should be aligned".to_string()
605 };
606
607 warnings.push(LintWarning {
608 rule_name: Some(self.name().to_string()),
609 severity: Severity::Warning,
610 message,
611 line: start_line,
612 column: start_col,
613 end_line,
614 end_column: end_col,
615 fix: Some(crate::rule::Fix {
616 range: line_index.whole_line_range(line_idx + 1),
617 replacement: if line_idx < lines.len() - 1 {
618 format!("{fixed}\n")
619 } else {
620 fixed.clone()
621 },
622 }),
623 });
624 }
625 }
626 }
627
628 Ok(warnings)
629 }
630
631 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
632 if !self.config.enabled {
633 return Ok(ctx.content.to_string());
634 }
635
636 let content = ctx.content;
637 let lines: Vec<&str> = content.lines().collect();
638 let table_blocks = &ctx.table_blocks;
639
640 let mut result_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
641
642 for table_block in table_blocks {
643 let format_result = self.fix_table_block(&lines, table_block);
644
645 let table_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
646 .chain(std::iter::once(table_block.delimiter_line))
647 .chain(table_block.content_lines.iter().copied())
648 .collect();
649
650 for (i, &line_idx) in table_line_indices.iter().enumerate() {
651 result_lines[line_idx] = format_result.lines[i].clone();
652 }
653 }
654
655 let mut fixed = result_lines.join("\n");
656 if content.ends_with('\n') && !fixed.ends_with('\n') {
657 fixed.push('\n');
658 }
659 Ok(fixed)
660 }
661
662 fn as_any(&self) -> &dyn std::any::Any {
663 self
664 }
665
666 fn default_config_section(&self) -> Option<(String, toml::Value)> {
667 let json_value = serde_json::to_value(&self.config).ok()?;
668 Some((
669 self.name().to_string(),
670 crate::rule_config_serde::json_to_toml_value(&json_value)?,
671 ))
672 }
673
674 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
675 where
676 Self: Sized,
677 {
678 let rule_config = crate::rule_config_serde::load_rule_config::<MD060Config>(config);
679 let md013_config = crate::rule_config_serde::load_rule_config::<MD013Config>(config);
680 Box::new(Self::from_config_struct(rule_config, md013_config.line_length.get()))
681 }
682}
683
684#[cfg(test)]
685mod tests {
686 use super::*;
687 use crate::lint_context::LintContext;
688 use crate::types::LineLength;
689
690 #[test]
691 fn test_md060_disabled_by_default() {
692 let rule = MD060TableFormat::default();
693 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
694 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
695
696 let warnings = rule.check(&ctx).unwrap();
697 assert_eq!(warnings.len(), 0);
698
699 let fixed = rule.fix(&ctx).unwrap();
700 assert_eq!(fixed, content);
701 }
702
703 #[test]
704 fn test_md060_align_simple_ascii_table() {
705 let rule = MD060TableFormat::new(true, "aligned".to_string());
706
707 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
708 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
709
710 let fixed = rule.fix(&ctx).unwrap();
711 let expected = "| Name | Age |\n| ----- | --- |\n| Alice | 30 |";
712 assert_eq!(fixed, expected);
713
714 let lines: Vec<&str> = fixed.lines().collect();
716 assert_eq!(lines[0].len(), lines[1].len());
717 assert_eq!(lines[1].len(), lines[2].len());
718 }
719
720 #[test]
721 fn test_md060_cjk_characters_aligned_correctly() {
722 let rule = MD060TableFormat::new(true, "aligned".to_string());
723
724 let content = "| Name | Age |\n|---|---|\n| δΈζ | 30 |";
725 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
726
727 let fixed = rule.fix(&ctx).unwrap();
728
729 let lines: Vec<&str> = fixed.lines().collect();
730 let cells_line1 = MD060TableFormat::parse_table_row(lines[0]);
731 let cells_line3 = MD060TableFormat::parse_table_row(lines[2]);
732
733 let width1 = MD060TableFormat::calculate_cell_display_width(&cells_line1[0]);
734 let width3 = MD060TableFormat::calculate_cell_display_width(&cells_line3[0]);
735
736 assert_eq!(width1, width3);
737 }
738
739 #[test]
740 fn test_md060_basic_emoji() {
741 let rule = MD060TableFormat::new(true, "aligned".to_string());
742
743 let content = "| Status | Name |\n|---|---|\n| β
| Test |";
744 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
745
746 let fixed = rule.fix(&ctx).unwrap();
747 assert!(fixed.contains("Status"));
748 }
749
750 #[test]
751 fn test_md060_zwj_emoji_skipped() {
752 let rule = MD060TableFormat::new(true, "aligned".to_string());
753
754 let content = "| Emoji | Name |\n|---|---|\n| π¨βπ©βπ§βπ¦ | Family |";
755 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
756
757 let fixed = rule.fix(&ctx).unwrap();
758 assert_eq!(fixed, content);
759 }
760
761 #[test]
762 fn test_md060_inline_code_with_pipes() {
763 let rule = MD060TableFormat::new(true, "aligned".to_string());
764
765 let content = "| Pattern | Regex |\n|---|---|\n| Time | `[0-9]|[0-9]` |";
766 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
767
768 let fixed = rule.fix(&ctx).unwrap();
769 assert!(fixed.contains("`[0-9]|[0-9]`"));
770 }
771
772 #[test]
773 fn test_md060_compact_style() {
774 let rule = MD060TableFormat::new(true, "compact".to_string());
775
776 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
777 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
778
779 let fixed = rule.fix(&ctx).unwrap();
780 let expected = "| Name | Age |\n| --- | --- |\n| Alice | 30 |";
781 assert_eq!(fixed, expected);
782 }
783
784 #[test]
785 fn test_md060_tight_style() {
786 let rule = MD060TableFormat::new(true, "tight".to_string());
787
788 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
789 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
790
791 let fixed = rule.fix(&ctx).unwrap();
792 let expected = "|Name|Age|\n|---|---|\n|Alice|30|";
793 assert_eq!(fixed, expected);
794 }
795
796 #[test]
797 fn test_md060_any_style_consistency() {
798 let rule = MD060TableFormat::new(true, "any".to_string());
799
800 let content = "| Name | Age |\n| --- | --- |\n| Alice | 30 |";
802 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
803
804 let fixed = rule.fix(&ctx).unwrap();
805 assert_eq!(fixed, content);
806
807 let content_aligned = "| Name | Age |\n| ----- | --- |\n| Alice | 30 |";
809 let ctx_aligned = LintContext::new(content_aligned, crate::config::MarkdownFlavor::Standard);
810
811 let fixed_aligned = rule.fix(&ctx_aligned).unwrap();
812 assert_eq!(fixed_aligned, content_aligned);
813 }
814
815 #[test]
816 fn test_md060_empty_cells() {
817 let rule = MD060TableFormat::new(true, "aligned".to_string());
818
819 let content = "| A | B |\n|---|---|\n| | X |";
820 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
821
822 let fixed = rule.fix(&ctx).unwrap();
823 assert!(fixed.contains("|"));
824 }
825
826 #[test]
827 fn test_md060_mixed_content() {
828 let rule = MD060TableFormat::new(true, "aligned".to_string());
829
830 let content = "| Name | Age | City |\n|---|---|---|\n| δΈζ | 30 | NYC |";
831 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
832
833 let fixed = rule.fix(&ctx).unwrap();
834 assert!(fixed.contains("δΈζ"));
835 assert!(fixed.contains("NYC"));
836 }
837
838 #[test]
839 fn test_md060_preserve_alignment_indicators() {
840 let rule = MD060TableFormat::new(true, "aligned".to_string());
841
842 let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
843 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
844
845 let fixed = rule.fix(&ctx).unwrap();
846
847 assert!(fixed.contains(":---"), "Should contain left alignment");
848 assert!(fixed.contains(":----:"), "Should contain center alignment");
849 assert!(fixed.contains("----:"), "Should contain right alignment");
850 }
851
852 #[test]
853 fn test_md060_minimum_column_width() {
854 let rule = MD060TableFormat::new(true, "aligned".to_string());
855
856 let content = "| ID | Name |\n|-|-|\n| 1 | A |";
859 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
860
861 let fixed = rule.fix(&ctx).unwrap();
862
863 let lines: Vec<&str> = fixed.lines().collect();
864 assert_eq!(lines[0].len(), lines[1].len());
865 assert_eq!(lines[1].len(), lines[2].len());
866
867 assert!(fixed.contains("ID "), "Short content should be padded");
869 assert!(fixed.contains("---"), "Delimiter should have at least 3 dashes");
870 }
871
872 #[test]
873 fn test_md060_auto_compact_exceeds_default_threshold() {
874 let config = MD060Config {
876 enabled: true,
877 style: "aligned".to_string(),
878 max_width: LineLength::from_const(0),
879 };
880 let rule = MD060TableFormat::from_config_struct(config, 80);
881
882 let content = "| Very Long Column Header | Another Long Header | Third Very Long Header Column |\n|---|---|---|\n| Short | Data | Here |";
886 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
887
888 let fixed = rule.fix(&ctx).unwrap();
889
890 assert!(fixed.contains("| Very Long Column Header | Another Long Header | Third Very Long Header Column |"));
892 assert!(fixed.contains("| --- | --- | --- |"));
893 assert!(fixed.contains("| Short | Data | Here |"));
894
895 let lines: Vec<&str> = fixed.lines().collect();
897 assert!(lines[0].len() != lines[1].len() || lines[1].len() != lines[2].len());
899 }
900
901 #[test]
902 fn test_md060_auto_compact_exceeds_explicit_threshold() {
903 let config = MD060Config {
905 enabled: true,
906 style: "aligned".to_string(),
907 max_width: LineLength::from_const(50),
908 };
909 let rule = MD060TableFormat::from_config_struct(config, 80); let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| Data | Data | Data |";
915 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
916
917 let fixed = rule.fix(&ctx).unwrap();
918
919 assert!(
921 fixed.contains("| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |")
922 );
923 assert!(fixed.contains("| --- | --- | --- |"));
924 assert!(fixed.contains("| Data | Data | Data |"));
925
926 let lines: Vec<&str> = fixed.lines().collect();
928 assert!(lines[0].len() != lines[2].len());
929 }
930
931 #[test]
932 fn test_md060_stays_aligned_under_threshold() {
933 let config = MD060Config {
935 enabled: true,
936 style: "aligned".to_string(),
937 max_width: LineLength::from_const(100),
938 };
939 let rule = MD060TableFormat::from_config_struct(config, 80);
940
941 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
943 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
944
945 let fixed = rule.fix(&ctx).unwrap();
946
947 let expected = "| Name | Age |\n| ----- | --- |\n| Alice | 30 |";
949 assert_eq!(fixed, expected);
950
951 let lines: Vec<&str> = fixed.lines().collect();
952 assert_eq!(lines[0].len(), lines[1].len());
953 assert_eq!(lines[1].len(), lines[2].len());
954 }
955
956 #[test]
957 fn test_md060_width_calculation_formula() {
958 let config = MD060Config {
960 enabled: true,
961 style: "aligned".to_string(),
962 max_width: LineLength::from_const(0),
963 };
964 let rule = MD060TableFormat::from_config_struct(config, 30);
965
966 let content = "| AAAAA | BBBBB | CCCCC |\n|---|---|---|\n| AAAAA | BBBBB | CCCCC |";
970 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
971
972 let fixed = rule.fix(&ctx).unwrap();
973
974 let lines: Vec<&str> = fixed.lines().collect();
976 assert_eq!(lines[0].len(), lines[1].len());
977 assert_eq!(lines[1].len(), lines[2].len());
978 assert_eq!(lines[0].len(), 25); let config_tight = MD060Config {
982 enabled: true,
983 style: "aligned".to_string(),
984 max_width: LineLength::from_const(24),
985 };
986 let rule_tight = MD060TableFormat::from_config_struct(config_tight, 80);
987
988 let fixed_compact = rule_tight.fix(&ctx).unwrap();
989
990 assert!(fixed_compact.contains("| AAAAA | BBBBB | CCCCC |"));
992 assert!(fixed_compact.contains("| --- | --- | --- |"));
993 }
994
995 #[test]
996 fn test_md060_very_wide_table_auto_compacts() {
997 let config = MD060Config {
998 enabled: true,
999 style: "aligned".to_string(),
1000 max_width: LineLength::from_const(0),
1001 };
1002 let rule = MD060TableFormat::from_config_struct(config, 80);
1003
1004 let content = "| Column One A | Column Two B | Column Three | Column Four D | Column Five E | Column Six FG | Column Seven | Column Eight |\n|---|---|---|---|---|---|---|---|\n| A | B | C | D | E | F | G | H |";
1008 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
1009
1010 let fixed = rule.fix(&ctx).unwrap();
1011
1012 assert!(fixed.contains("| Column One A | Column Two B | Column Three | Column Four D | Column Five E | Column Six FG | Column Seven | Column Eight |"));
1014 assert!(fixed.contains("| --- | --- | --- | --- | --- | --- | --- | --- |"));
1015 }
1016
1017 #[test]
1018 fn test_md060_inherit_from_md013_line_length() {
1019 let config = MD060Config {
1021 enabled: true,
1022 style: "aligned".to_string(),
1023 max_width: LineLength::from_const(0), };
1025
1026 let rule_80 = MD060TableFormat::from_config_struct(config.clone(), 80);
1028 let rule_120 = MD060TableFormat::from_config_struct(config.clone(), 120);
1029
1030 let content = "| Column Header A | Column Header B | Column Header C |\n|---|---|---|\n| Some Data | More Data | Even More |";
1032 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
1033
1034 let _fixed_80 = rule_80.fix(&ctx).unwrap();
1036
1037 let fixed_120 = rule_120.fix(&ctx).unwrap();
1039
1040 let lines_120: Vec<&str> = fixed_120.lines().collect();
1042 assert_eq!(lines_120[0].len(), lines_120[1].len());
1043 assert_eq!(lines_120[1].len(), lines_120[2].len());
1044 }
1045
1046 #[test]
1047 fn test_md060_edge_case_exactly_at_threshold() {
1048 let config = MD060Config {
1052 enabled: true,
1053 style: "aligned".to_string(),
1054 max_width: LineLength::from_const(17),
1055 };
1056 let rule = MD060TableFormat::from_config_struct(config, 80);
1057
1058 let content = "| AAAAA | BBBBB |\n|---|---|\n| AAAAA | BBBBB |";
1059 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
1060
1061 let fixed = rule.fix(&ctx).unwrap();
1062
1063 let lines: Vec<&str> = fixed.lines().collect();
1065 assert_eq!(lines[0].len(), 17);
1066 assert_eq!(lines[0].len(), lines[1].len());
1067 assert_eq!(lines[1].len(), lines[2].len());
1068
1069 let config_under = MD060Config {
1071 enabled: true,
1072 style: "aligned".to_string(),
1073 max_width: LineLength::from_const(16),
1074 };
1075 let rule_under = MD060TableFormat::from_config_struct(config_under, 80);
1076
1077 let fixed_compact = rule_under.fix(&ctx).unwrap();
1078
1079 assert!(fixed_compact.contains("| AAAAA | BBBBB |"));
1081 assert!(fixed_compact.contains("| --- | --- |"));
1082 }
1083
1084 #[test]
1085 fn test_md060_auto_compact_warning_message() {
1086 let config = MD060Config {
1088 enabled: true,
1089 style: "aligned".to_string(),
1090 max_width: LineLength::from_const(50),
1091 };
1092 let rule = MD060TableFormat::from_config_struct(config, 80);
1093
1094 let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| Data | Data | Data |";
1096 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
1097
1098 let warnings = rule.check(&ctx).unwrap();
1099
1100 assert!(!warnings.is_empty(), "Should generate warnings");
1102
1103 let auto_compact_warnings: Vec<_> = warnings
1104 .iter()
1105 .filter(|w| w.message.contains("too wide for aligned formatting"))
1106 .collect();
1107
1108 assert!(!auto_compact_warnings.is_empty(), "Should have auto-compact warning");
1109
1110 let first_warning = auto_compact_warnings[0];
1112 assert!(first_warning.message.contains("85 chars > max-width: 50"));
1113 assert!(first_warning.message.contains("Table too wide for aligned formatting"));
1114 }
1115
1116 #[test]
1117 fn test_md060_regular_alignment_warning_message() {
1118 let config = MD060Config {
1120 enabled: true,
1121 style: "aligned".to_string(),
1122 max_width: LineLength::from_const(100), };
1124 let rule = MD060TableFormat::from_config_struct(config, 80);
1125
1126 let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1128 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
1129
1130 let warnings = rule.check(&ctx).unwrap();
1131
1132 assert!(!warnings.is_empty(), "Should generate warnings");
1134
1135 assert!(warnings[0].message.contains("Table columns should be aligned"));
1137 assert!(!warnings[0].message.contains("too wide"));
1138 assert!(!warnings[0].message.contains("max-width"));
1139 }
1140}