rumdl_lib/rules/md060_table_format/
mod.rs

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/// Rule MD060: Table Column Alignment
25///
26/// See [docs/md060.md](../../docs/md060.md) for full documentation, configuration, and examples.
27///
28/// This rule enforces consistent column alignment in Markdown tables for improved readability
29/// in source form. When enabled, it ensures table columns are properly aligned with appropriate
30/// padding.
31///
32/// ## Purpose
33///
34/// - **Readability**: Aligned tables are significantly easier to read in source form
35/// - **Maintainability**: Properly formatted tables are easier to edit and review
36/// - **Consistency**: Ensures uniform table formatting throughout documents
37/// - **Developer Experience**: Makes working with tables in plain text more pleasant
38///
39/// ## Configuration Options
40///
41/// The rule supports the following configuration options:
42///
43/// ```toml
44/// [MD013]
45/// line-length = 100  # MD060 inherits this by default
46///
47/// [MD060]
48/// enabled = false      # Default: opt-in for conservative adoption
49/// style = "aligned"    # Can be "aligned", "compact", "tight", or "any"
50/// max-width = 0        # Default: inherit from MD013's line-length
51/// ```
52///
53/// ### Style Options
54///
55/// - **aligned**: Columns are padded with spaces for visual alignment (default)
56/// - **compact**: Minimal spacing with single spaces
57/// - **tight**: No spacing, pipes directly adjacent to content
58/// - **any**: Preserve existing formatting style
59///
60/// ### Max Width (auto-compact threshold)
61///
62/// Controls when tables automatically switch from aligned to compact formatting:
63///
64/// - **`max-width = 0`** (default): Inherits from MD013's `line-length` setting (default 80)
65/// - **`max-width = N`**: Explicit threshold, independent of MD013
66///
67/// When a table's aligned width would exceed this limit, MD060 automatically
68/// uses compact formatting instead to prevent excessively long lines. This matches
69/// the behavior of Prettier's table formatting.
70///
71/// #### Examples
72///
73/// ```toml
74/// # Inherit from MD013 (recommended)
75/// [MD013]
76/// line-length = 100
77///
78/// [MD060]
79/// style = "aligned"
80/// max-width = 0  # Tables exceeding 100 chars will be compacted
81/// ```
82///
83/// ```toml
84/// # Explicit threshold
85/// [MD060]
86/// style = "aligned"
87/// max-width = 120  # Independent of MD013
88/// ```
89///
90/// ## Examples
91///
92/// ### Aligned Style (Good)
93///
94/// ```markdown
95/// | Name  | Age | City      |
96/// |-------|-----|-----------|
97/// | Alice | 30  | Seattle   |
98/// | Bob   | 25  | Portland  |
99/// ```
100///
101/// ### Unaligned (Bad)
102///
103/// ```markdown
104/// | Name | Age | City |
105/// |---|---|---|
106/// | Alice | 30 | Seattle |
107/// | Bob | 25 | Portland |
108/// ```
109///
110/// ## Unicode Support
111///
112/// This rule properly handles:
113/// - **CJK Characters**: Chinese, Japanese, Korean characters are correctly measured as double-width
114/// - **Basic Emoji**: Most emoji are handled correctly
115/// - **Inline Code**: Pipes in inline code blocks are properly masked
116///
117/// ## Known Limitations
118///
119/// **Complex Unicode Sequences**: Tables containing certain Unicode characters are automatically
120/// skipped to prevent alignment corruption. These include:
121/// - Zero-Width Joiner (ZWJ) emoji: πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦, πŸ‘©β€πŸ’»
122/// - Zero-Width Space (ZWS): Invisible word break opportunities
123/// - Zero-Width Non-Joiner (ZWNJ): Ligature prevention marks
124/// - Word Joiner (WJ): Non-breaking invisible characters
125///
126/// These characters have inconsistent or zero display widths across terminals and fonts,
127/// making accurate alignment impossible. The rule preserves these tables as-is rather than
128/// risk corrupting them.
129///
130/// This is an honest limitation of terminal display technology, similar to what other tools
131/// like markdownlint experience.
132///
133/// ## Fix Behavior
134///
135/// When applying automatic fixes, this rule:
136/// - Calculates proper display width for each column using Unicode width measurements
137/// - Pads cells with trailing spaces to align columns
138/// - Preserves cell content exactly (only spacing is modified)
139/// - Respects alignment indicators in delimiter rows (`:---`, `:---:`, `---:`)
140/// - Automatically switches to compact mode for tables exceeding max_width
141/// - Skips tables with ZWJ emoji to prevent corruption
142#[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, // Default MD013 line_length
167        }
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    /// Get the effective max width for table formatting.
178    ///
179    /// - If `max_width` is 0, inherits from MD013's `line_length`
180    /// - Otherwise, uses the explicitly configured `max_width`
181    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    /// Check if text contains characters that break Unicode width calculations
190    ///
191    /// Tables with these characters are skipped to avoid alignment corruption:
192    /// - Zero-Width Joiner (ZWJ, U+200D): Complex emoji like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦
193    /// - Zero-Width Space (ZWS, U+200B): Invisible word break opportunity
194    /// - Zero-Width Non-Joiner (ZWNJ, U+200C): Prevents ligature formation
195    /// - Word Joiner (WJ, U+2060): Prevents line breaks without taking space
196    ///
197    /// These characters have inconsistent display widths across terminals,
198    /// making accurate alignment impossible.
199    fn contains_problematic_chars(text: &str) -> bool {
200        text.contains('\u{200D}')  // ZWJ
201            || text.contains('\u{200B}')  // ZWS
202            || text.contains('\u{200C}')  // ZWNJ
203            || text.contains('\u{2060}') // Word Joiner
204    }
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            // A delimiter cell must contain at least one dash
255            // Empty cells are not delimiter cells
256            !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            // Save delimiter row for later processing, but don't use it for width calculation
287            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        // GFM requires delimiter rows to have at least 3 dashes per column.
303        // To ensure visual alignment, all columns must be at least width 3.
304        let mut final_widths: Vec<usize> = column_widths.iter().map(|&w| w.max(3)).collect();
305
306        // Adjust column widths to accommodate alignment indicators (colons) in delimiter row
307        // This ensures the delimiter row has the same length as content rows
308        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                    // Minimum width needed: 3 dashes + colons
317                    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                    // Delimiter rows use the same cell format as content rows: | content |
343                    // The "content" is dashes, possibly with colons for alignment
344                    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)); // Minimum 3 dashes
353                    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                    // Add spaces around delimiter content, just like content cells
364                    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                    // Apply alignment based on column's alignment indicator
371                    let alignment = column_alignments.get(i).copied().unwrap_or(ColumnAlignment::Left);
372                    match alignment {
373                        ColumnAlignment::Left => {
374                            // Left: content on left, padding on right
375                            format!(" {trimmed}{} ", " ".repeat(padding))
376                        }
377                        ColumnAlignment::Center => {
378                            // Center: split padding on both sides
379                            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                            // Right: padding on left, content on right
385                            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                // Parse column alignments from delimiter row (always at index 1)
471                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                // Calculate aligned table width: 1 (leading pipe) + num_columns * 3 (| cell |) + sum(column_widths)
508                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                // Auto-compact: if aligned table exceeds max width, use compact formatting instead
513                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                    // Parse column alignments from delimiter row (always at index 1)
521                    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        // Verify all rows have equal length in aligned mode
715        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        // Table is already compact, should stay compact
801        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        // Table is aligned, should stay aligned
808        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        // Test with very short column content to ensure minimum width of 3
857        // GFM requires at least 3 dashes in delimiter rows
858        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        // Verify minimum width is enforced
868        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        // Default max_width = 0, which inherits from default MD013 line_length = 80
875        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        // Table that would be 85 chars when aligned (exceeds 80)
883        // Formula: 1 + (3 * 3) + (20 + 20 + 30) = 1 + 9 + 70 = 80 chars
884        // But with actual content padding it will exceed
885        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        // Should use compact formatting (single spaces)
891        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        // Verify it's compact (no extra padding)
896        let lines: Vec<&str> = fixed.lines().collect();
897        // In compact mode, lines can have different lengths
898        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        // Explicit max_width = 50
904        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); // MD013 setting doesn't matter
910
911        // Table that would exceed 50 chars when aligned
912        // Column widths: 25 + 25 + 25 = 75 chars
913        // Formula: 1 + (3 * 3) + 75 = 85 chars (exceeds 50)
914        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        // Should use compact formatting (single spaces, no extra padding)
920        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        // Verify it's compact (lines have different lengths)
927        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        // max_width = 100, table will be under this
934        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        // Small table that fits well under 100 chars
942        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        // Should use aligned formatting (all lines same length)
948        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        // Verify the width calculation formula: 1 + (num_columns * 3) + sum(column_widths)
959        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        // Create a table where we know exact column widths: 5 + 5 + 5 = 15
967        // Expected aligned width: 1 + (3 * 3) + 15 = 1 + 9 + 15 = 25 chars
968        // This is under 30, so should stay aligned
969        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        // Should be aligned
975        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); // Verify formula
979
980        // Now test with threshold = 24 (just under aligned width)
981        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        // Should be compact now (25 > 24)
991        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        // Very wide table with many columns
1005        // 8 columns with widths of 12 chars each = 96 chars
1006        // Formula: 1 + (8 * 3) + 96 = 121 chars (exceeds 80)
1007        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        // Should be compact (table would be way over 80 chars aligned)
1013        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        // max_width = 0 should inherit from MD013's line_length
1020        let config = MD060Config {
1021            enabled: true,
1022            style: "aligned".to_string(),
1023            max_width: LineLength::from_const(0), // Inherit
1024        };
1025
1026        // Test with different MD013 line_length values
1027        let rule_80 = MD060TableFormat::from_config_struct(config.clone(), 80);
1028        let rule_120 = MD060TableFormat::from_config_struct(config.clone(), 120);
1029
1030        // Medium-sized table
1031        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        // With 80 char limit, likely compacts
1035        let _fixed_80 = rule_80.fix(&ctx).unwrap();
1036
1037        // With 120 char limit, likely stays aligned
1038        let fixed_120 = rule_120.fix(&ctx).unwrap();
1039
1040        // Verify 120 is aligned (all lines same length)
1041        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        // Create table that's exactly at the threshold
1049        // Formula: 1 + (num_columns * 3) + sum(column_widths) = max_width
1050        // For 2 columns with widths 5 and 5: 1 + 6 + 10 = 17
1051        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        // At threshold (17 <= 17), should stay aligned
1064        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        // Now test with threshold = 16 (just under)
1070        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        // Should compact (17 > 16)
1080        assert!(fixed_compact.contains("| AAAAA | BBBBB |"));
1081        assert!(fixed_compact.contains("| --- | --- |"));
1082    }
1083
1084    #[test]
1085    fn test_md060_auto_compact_warning_message() {
1086        // Verify that auto-compact generates an informative warning
1087        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        // Table that will be auto-compacted (exceeds 50 chars when aligned)
1095        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        // Should generate warnings with auto-compact message
1101        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        // Verify the warning message includes the width and threshold
1111        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        // Verify that regular alignment (not auto-compact) generates normal warning
1119        let config = MD060Config {
1120            enabled: true,
1121            style: "aligned".to_string(),
1122            max_width: LineLength::from_const(100), // Large enough to not trigger auto-compact
1123        };
1124        let rule = MD060TableFormat::from_config_struct(config, 80);
1125
1126        // Small misaligned table
1127        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        // Should generate warnings
1133        assert!(!warnings.is_empty(), "Should generate warnings");
1134
1135        // Verify it's the standard alignment message, not auto-compact
1136        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}