Skip to main content

rumdl_lib/rules/
md060_table_format.rs

1use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::utils::range_utils::calculate_line_range;
3use crate::utils::regex_cache::BLOCKQUOTE_PREFIX_RE;
4use crate::utils::table_utils::TableUtils;
5use unicode_width::UnicodeWidthStr;
6
7mod md060_config;
8use crate::md013_line_length::MD013Config;
9pub use md060_config::ColumnAlign;
10pub use md060_config::MD060Config;
11
12/// Identifies the type of row in a table for formatting purposes.
13#[derive(Debug, Clone, Copy, PartialEq)]
14enum RowType {
15    /// The first row containing column headers
16    Header,
17    /// The second row containing delimiter dashes (e.g., `|---|---|`)
18    Delimiter,
19    /// Data rows following the delimiter
20    Body,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq)]
24enum ColumnAlignment {
25    Left,
26    Center,
27    Right,
28}
29
30#[derive(Debug, Clone)]
31struct TableFormatResult {
32    lines: Vec<String>,
33    auto_compacted: bool,
34    aligned_width: Option<usize>,
35}
36
37/// Formatting options for a single table row.
38#[derive(Debug, Clone, Copy)]
39struct RowFormatOptions {
40    /// The type of row being formatted
41    row_type: RowType,
42    /// Whether to use compact delimiter style (no spaces around dashes)
43    compact_delimiter: bool,
44    /// Global column alignment override
45    column_align: ColumnAlign,
46    /// Header-specific column alignment (overrides column_align for header)
47    column_align_header: Option<ColumnAlign>,
48    /// Body-specific column alignment (overrides column_align for body)
49    column_align_body: Option<ColumnAlign>,
50}
51
52/// Rule MD060: Table Column Alignment
53///
54/// See [docs/md060.md](../../docs/md060.md) for full documentation, configuration, and examples.
55///
56/// This rule enforces consistent column alignment in Markdown tables for improved readability
57/// in source form. When enabled, it ensures table columns are properly aligned with appropriate
58/// padding.
59///
60/// ## Purpose
61///
62/// - **Readability**: Aligned tables are significantly easier to read in source form
63/// - **Maintainability**: Properly formatted tables are easier to edit and review
64/// - **Consistency**: Ensures uniform table formatting throughout documents
65/// - **Developer Experience**: Makes working with tables in plain text more pleasant
66///
67/// ## Configuration Options
68///
69/// The rule supports the following configuration options:
70///
71/// ```toml
72/// [MD013]
73/// line-length = 100  # MD060 inherits this by default
74///
75/// [MD060]
76/// enabled = false      # Default: opt-in for conservative adoption
77/// style = "aligned"    # Can be "aligned", "compact", "tight", or "any"
78/// max-width = 0        # Default: inherit from MD013's line-length
79/// ```
80///
81/// ### Style Options
82///
83/// - **aligned**: Columns are padded with spaces for visual alignment (default)
84/// - **compact**: Minimal spacing with single spaces
85/// - **tight**: No spacing, pipes directly adjacent to content
86/// - **any**: Preserve existing formatting style
87///
88/// ### Max Width (auto-compact threshold)
89///
90/// Controls when tables automatically switch from aligned to compact formatting:
91///
92/// - **`max-width = 0`** (default): Smart inheritance from MD013
93/// - **`max-width = N`**: Explicit threshold, independent of MD013
94///
95/// When `max-width = 0`:
96/// - If MD013 is disabled β†’ unlimited (no auto-compact)
97/// - If MD013.tables = false β†’ unlimited (no auto-compact)
98/// - If MD013.line_length = 0 β†’ unlimited (no auto-compact)
99/// - Otherwise β†’ inherits MD013's line-length
100///
101/// This matches the behavior of Prettier's table formatting.
102///
103/// #### Examples
104///
105/// ```toml
106/// # Inherit from MD013 (recommended)
107/// [MD013]
108/// line-length = 100
109///
110/// [MD060]
111/// style = "aligned"
112/// max-width = 0  # Tables exceeding 100 chars will be compacted
113/// ```
114///
115/// ```toml
116/// # Explicit threshold
117/// [MD060]
118/// style = "aligned"
119/// max-width = 120  # Independent of MD013
120/// ```
121///
122/// ## Examples
123///
124/// ### Aligned Style (Good)
125///
126/// ```markdown
127/// | Name  | Age | City      |
128/// |-------|-----|-----------|
129/// | Alice | 30  | Seattle   |
130/// | Bob   | 25  | Portland  |
131/// ```
132///
133/// ### Unaligned (Bad)
134///
135/// ```markdown
136/// | Name | Age | City |
137/// |---|---|---|
138/// | Alice | 30 | Seattle |
139/// | Bob | 25 | Portland |
140/// ```
141///
142/// ## Unicode Support
143///
144/// This rule properly handles:
145/// - **CJK Characters**: Chinese, Japanese, Korean characters are correctly measured as double-width
146/// - **Basic Emoji**: Most emoji are handled correctly
147/// - **Inline Code**: Pipes in inline code blocks are properly masked
148///
149/// ## Known Limitations
150///
151/// **Complex Unicode Sequences**: Tables containing certain Unicode characters are automatically
152/// skipped to prevent alignment corruption. These include:
153/// - Zero-Width Joiner (ZWJ) emoji: πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦, πŸ‘©β€πŸ’»
154/// - Zero-Width Space (ZWS): Invisible word break opportunities
155/// - Zero-Width Non-Joiner (ZWNJ): Ligature prevention marks
156/// - Word Joiner (WJ): Non-breaking invisible characters
157///
158/// These characters have inconsistent or zero display widths across terminals and fonts,
159/// making accurate alignment impossible. The rule preserves these tables as-is rather than
160/// risk corrupting them.
161///
162/// This is an honest limitation of terminal display technology, similar to what other tools
163/// like markdownlint experience.
164///
165/// ## Fix Behavior
166///
167/// When applying automatic fixes, this rule:
168/// - Calculates proper display width for each column using Unicode width measurements
169/// - Pads cells with trailing spaces to align columns
170/// - Preserves cell content exactly (only spacing is modified)
171/// - Respects alignment indicators in delimiter rows (`:---`, `:---:`, `---:`)
172/// - Automatically switches to compact mode for tables exceeding max_width
173/// - Skips tables with ZWJ emoji to prevent corruption
174#[derive(Debug, Clone, Default)]
175pub struct MD060TableFormat {
176    config: MD060Config,
177    md013_config: MD013Config,
178    md013_disabled: bool,
179}
180
181impl MD060TableFormat {
182    pub fn new(enabled: bool, style: String) -> Self {
183        use crate::types::LineLength;
184        Self {
185            config: MD060Config {
186                enabled,
187                style,
188                max_width: LineLength::from_const(0),
189                column_align: ColumnAlign::Auto,
190                column_align_header: None,
191                column_align_body: None,
192                loose_last_column: false,
193                aligned_delimiter: false,
194            },
195            md013_config: MD013Config::default(),
196            md013_disabled: false,
197        }
198    }
199
200    pub fn from_config_struct(config: MD060Config, md013_config: MD013Config, md013_disabled: bool) -> Self {
201        Self {
202            config,
203            md013_config,
204            md013_disabled,
205        }
206    }
207
208    /// Get the effective max width for table formatting.
209    ///
210    /// Priority order:
211    /// 1. Explicit `max_width > 0` always takes precedence
212    /// 2. When `max_width = 0` (inherit mode), check MD013 configuration:
213    ///    - If MD013 is globally disabled β†’ unlimited
214    ///    - If `MD013.tables = false` β†’ unlimited
215    ///    - If `MD013.line_length = 0` β†’ unlimited
216    ///    - Otherwise β†’ inherit MD013's line_length
217    fn effective_max_width(&self) -> usize {
218        // Explicit max_width always takes precedence
219        if !self.config.max_width.is_unlimited() {
220            return self.config.max_width.get();
221        }
222
223        // max_width = 0 means "inherit" - but inherit UNLIMITED if:
224        // 1. MD013 is globally disabled
225        // 2. MD013.tables = false (user doesn't care about table line length)
226        // 3. MD013.line_length = 0 (no line length limit at all)
227        if self.md013_disabled || !self.md013_config.tables || self.md013_config.line_length.is_unlimited() {
228            return usize::MAX; // Unlimited
229        }
230
231        // Otherwise inherit MD013's line-length
232        self.md013_config.line_length.get()
233    }
234
235    /// Check if text contains characters that break Unicode width calculations
236    ///
237    /// Tables with these characters are skipped to avoid alignment corruption:
238    /// - Zero-Width Joiner (ZWJ, U+200D): Complex emoji like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦
239    /// - Zero-Width Space (ZWS, U+200B): Invisible word break opportunity
240    /// - Zero-Width Non-Joiner (ZWNJ, U+200C): Prevents ligature formation
241    /// - Word Joiner (WJ, U+2060): Prevents line breaks without taking space
242    ///
243    /// These characters have inconsistent display widths across terminals,
244    /// making accurate alignment impossible.
245    fn contains_problematic_chars(text: &str) -> bool {
246        text.contains('\u{200D}')  // ZWJ
247            || text.contains('\u{200B}')  // ZWS
248            || text.contains('\u{200C}')  // ZWNJ
249            || text.contains('\u{2060}') // Word Joiner
250    }
251
252    fn calculate_cell_display_width(cell_content: &str) -> usize {
253        let masked = TableUtils::mask_pipes_in_inline_code(cell_content);
254        masked.trim().width()
255    }
256
257    /// Parse a table row into cells using Standard flavor (default behavior).
258    /// Used for tests and backward compatibility.
259    #[cfg(test)]
260    fn parse_table_row(line: &str) -> Vec<String> {
261        TableUtils::split_table_row(line)
262    }
263
264    /// Parse a table row into cells, respecting flavor-specific behavior.
265    ///
266    /// Pipes inside code spans are treated as content, not cell delimiters.
267    fn parse_table_row_with_flavor(line: &str, flavor: crate::config::MarkdownFlavor) -> Vec<String> {
268        TableUtils::split_table_row_with_flavor(line, flavor)
269    }
270
271    fn is_delimiter_row(row: &[String]) -> bool {
272        if row.is_empty() {
273            return false;
274        }
275        row.iter().all(|cell| {
276            let trimmed = cell.trim();
277            // A delimiter cell must contain at least one dash
278            // Empty cells are not delimiter cells
279            !trimmed.is_empty()
280                && trimmed.contains('-')
281                && trimmed.chars().all(|c| c == '-' || c == ':' || c.is_whitespace())
282        })
283    }
284
285    /// Extract blockquote prefix from a line (e.g., "> " or ">> ").
286    /// Returns (prefix, content_without_prefix).
287    fn extract_blockquote_prefix(line: &str) -> (&str, &str) {
288        if let Some(m) = BLOCKQUOTE_PREFIX_RE.find(line) {
289            (&line[..m.end()], &line[m.end()..])
290        } else {
291            ("", line)
292        }
293    }
294
295    fn parse_column_alignments(delimiter_row: &[String]) -> Vec<ColumnAlignment> {
296        delimiter_row
297            .iter()
298            .map(|cell| {
299                let trimmed = cell.trim();
300                let has_left_colon = trimmed.starts_with(':');
301                let has_right_colon = trimmed.ends_with(':');
302
303                match (has_left_colon, has_right_colon) {
304                    (true, true) => ColumnAlignment::Center,
305                    (false, true) => ColumnAlignment::Right,
306                    _ => ColumnAlignment::Left,
307                }
308            })
309            .collect()
310    }
311
312    fn calculate_column_widths(
313        table_lines: &[&str],
314        flavor: crate::config::MarkdownFlavor,
315        loose_last_column: bool,
316    ) -> Vec<usize> {
317        let mut column_widths = Vec::new();
318        let mut delimiter_cells: Option<Vec<String>> = None;
319        let mut is_header = true;
320        let mut header_last_col_width: Option<usize> = None;
321
322        for line in table_lines {
323            let cells = Self::parse_table_row_with_flavor(line, flavor);
324
325            // Save delimiter row for later processing, but don't use it for width calculation
326            if Self::is_delimiter_row(&cells) {
327                delimiter_cells = Some(cells);
328                is_header = false;
329                continue;
330            }
331
332            for (i, cell) in cells.iter().enumerate() {
333                let width = Self::calculate_cell_display_width(cell);
334                if i >= column_widths.len() {
335                    column_widths.push(width);
336                } else {
337                    column_widths[i] = column_widths[i].max(width);
338                }
339            }
340
341            // Record the header row's last column width
342            if is_header && !cells.is_empty() {
343                let last_idx = cells.len() - 1;
344                header_last_col_width = Some(Self::calculate_cell_display_width(&cells[last_idx]));
345                is_header = false;
346            }
347        }
348
349        // When loose, cap the last column width at the header's width
350        if loose_last_column
351            && let Some(header_width) = header_last_col_width
352            && let Some(last) = column_widths.last_mut()
353        {
354            *last = header_width;
355        }
356
357        // GFM requires delimiter rows to have at least 3 dashes per column.
358        // To ensure visual alignment, all columns must be at least width 3.
359        let mut final_widths: Vec<usize> = column_widths.iter().map(|&w| w.max(3)).collect();
360
361        // Adjust column widths to accommodate alignment indicators (colons) in delimiter row
362        // This ensures the delimiter row has the same length as content rows
363        if let Some(delimiter_cells) = delimiter_cells {
364            for (i, cell) in delimiter_cells.iter().enumerate() {
365                if i < final_widths.len() {
366                    let trimmed = cell.trim();
367                    let has_left_colon = trimmed.starts_with(':');
368                    let has_right_colon = trimmed.ends_with(':');
369                    let colon_count = (has_left_colon as usize) + (has_right_colon as usize);
370
371                    // Minimum width needed: 3 dashes + colons
372                    let min_width_for_delimiter = 3 + colon_count;
373                    final_widths[i] = final_widths[i].max(min_width_for_delimiter);
374                }
375            }
376        }
377
378        final_widths
379    }
380
381    fn format_table_row(
382        cells: &[String],
383        column_widths: &[usize],
384        column_alignments: &[ColumnAlignment],
385        options: &RowFormatOptions,
386    ) -> String {
387        let formatted_cells: Vec<String> = cells
388            .iter()
389            .enumerate()
390            .map(|(i, cell)| {
391                let target_width = column_widths.get(i).copied().unwrap_or(0);
392
393                match options.row_type {
394                    RowType::Delimiter => {
395                        let trimmed = cell.trim();
396                        let has_left_colon = trimmed.starts_with(':');
397                        let has_right_colon = trimmed.ends_with(':');
398
399                        // Delimiter rows use the same cell format as content rows: | content |
400                        // The "content" is dashes, possibly with colons for alignment
401                        // For compact_delimiter mode, we don't add spaces, so we need 2 extra dashes
402                        let extra_width = if options.compact_delimiter { 2 } else { 0 };
403                        let dash_count = if has_left_colon && has_right_colon {
404                            (target_width + extra_width).saturating_sub(2)
405                        } else if has_left_colon || has_right_colon {
406                            (target_width + extra_width).saturating_sub(1)
407                        } else {
408                            target_width + extra_width
409                        };
410
411                        let dashes = "-".repeat(dash_count.max(3)); // Minimum 3 dashes
412                        let delimiter_content = if has_left_colon && has_right_colon {
413                            format!(":{dashes}:")
414                        } else if has_left_colon {
415                            format!(":{dashes}")
416                        } else if has_right_colon {
417                            format!("{dashes}:")
418                        } else {
419                            dashes
420                        };
421
422                        // Add spaces around delimiter content unless compact_delimiter mode
423                        if options.compact_delimiter {
424                            delimiter_content
425                        } else {
426                            format!(" {delimiter_content} ")
427                        }
428                    }
429                    RowType::Header | RowType::Body => {
430                        let trimmed = cell.trim();
431                        let current_width = Self::calculate_cell_display_width(cell);
432                        let padding = target_width.saturating_sub(current_width);
433
434                        // Determine which alignment to use based on row type
435                        let effective_align = match options.row_type {
436                            RowType::Header => options.column_align_header.unwrap_or(options.column_align),
437                            RowType::Body => options.column_align_body.unwrap_or(options.column_align),
438                            RowType::Delimiter => unreachable!(),
439                        };
440
441                        // Apply alignment: use override if specified, otherwise use delimiter indicators
442                        let alignment = match effective_align {
443                            ColumnAlign::Auto => column_alignments.get(i).copied().unwrap_or(ColumnAlignment::Left),
444                            ColumnAlign::Left => ColumnAlignment::Left,
445                            ColumnAlign::Center => ColumnAlignment::Center,
446                            ColumnAlign::Right => ColumnAlignment::Right,
447                        };
448
449                        match alignment {
450                            ColumnAlignment::Left => {
451                                // Left: content on left, padding on right
452                                format!(" {trimmed}{} ", " ".repeat(padding))
453                            }
454                            ColumnAlignment::Center => {
455                                // Center: split padding on both sides
456                                let left_padding = padding / 2;
457                                let right_padding = padding - left_padding;
458                                format!(" {}{trimmed}{} ", " ".repeat(left_padding), " ".repeat(right_padding))
459                            }
460                            ColumnAlignment::Right => {
461                                // Right: padding on left, content on right
462                                format!(" {}{trimmed} ", " ".repeat(padding))
463                            }
464                        }
465                    }
466                }
467            })
468            .collect();
469
470        format!("|{}|", formatted_cells.join("|"))
471    }
472
473    fn format_table_compact(cells: &[String]) -> String {
474        // An empty compact cell is a single space between pipes (`| |`),
475        // matching mdformat's canonical form. This keeps rumdl's output stable
476        // when both tools format the same file.
477        let formatted_cells: Vec<String> = cells
478            .iter()
479            .map(|cell| match cell.trim() {
480                "" => " ".to_string(),
481                trimmed => format!(" {trimmed} "),
482            })
483            .collect();
484        format!("|{}|", formatted_cells.join("|"))
485    }
486
487    fn format_table_tight(cells: &[String]) -> String {
488        let formatted_cells: Vec<String> = cells.iter().map(|cell| cell.trim().to_string()).collect();
489        format!("|{}|", formatted_cells.join("|"))
490    }
491
492    /// Format a delimiter row whose pipe positions align with the header pipe
493    /// positions, used by `compact` / `tight` styles when `aligned_delimiter`
494    /// is enabled. Body rows remain unchanged (compact or tight).
495    ///
496    /// `header_widths` is the display width of each header cell's trimmed
497    /// content. Each delimiter cell receives that many dashes (minus one for
498    /// each colon present), preserving `:---`, `---:`, `:---:` markers.
499    /// `compact` controls whether to surround the dashes with single spaces.
500    fn format_delimiter_aligned_to_header(delim_cells: &[String], header_widths: &[usize], compact: bool) -> String {
501        let formatted_cells: Vec<String> = delim_cells
502            .iter()
503            .enumerate()
504            .map(|(i, cell)| {
505                let target_width = header_widths.get(i).copied().unwrap_or(0);
506                let trimmed = cell.trim();
507                let has_left_colon = trimmed.starts_with(':');
508                let has_right_colon = trimmed.ends_with(':');
509                let colon_count = usize::from(has_left_colon) + usize::from(has_right_colon);
510
511                // GFM minimum: at least one dash per delimiter cell.
512                let dash_count = target_width.saturating_sub(colon_count).max(1);
513                let dashes = "-".repeat(dash_count);
514                let delimiter_content = match (has_left_colon, has_right_colon) {
515                    (true, true) => format!(":{dashes}:"),
516                    (true, false) => format!(":{dashes}"),
517                    (false, true) => format!("{dashes}:"),
518                    (false, false) => dashes,
519                };
520                if compact {
521                    format!(" {delimiter_content} ")
522                } else {
523                    delimiter_content
524                }
525            })
526            .collect();
527
528        format!("|{}|", formatted_cells.join("|"))
529    }
530
531    /// Returns display widths of each header cell's trimmed content.
532    /// Used when `aligned_delimiter` is on to size the delimiter row.
533    fn header_cell_widths(header_cells: &[String]) -> Vec<usize> {
534        header_cells
535            .iter()
536            .map(|c| Self::calculate_cell_display_width(c))
537            .collect()
538    }
539
540    /// Checks if a table is already aligned with consistent column widths
541    /// and the delimiter row style matches the target style.
542    ///
543    /// A table is considered "already aligned" if:
544    /// 1. All rows have the same display length
545    /// 2. Each column has consistent cell width across all rows
546    /// 3. The delimiter row has valid minimum widths (at least 3 chars per cell)
547    /// 4. The delimiter row style matches the target style (compact_delimiter parameter)
548    ///
549    /// The `compact_delimiter` parameter indicates whether the target style is "aligned-no-space"
550    /// (true = no spaces around dashes, false = spaces around dashes).
551    fn is_table_already_aligned(
552        table_lines: &[&str],
553        flavor: crate::config::MarkdownFlavor,
554        compact_delimiter: bool,
555    ) -> bool {
556        if table_lines.len() < 2 {
557            return false;
558        }
559
560        // Check 1: All rows must have the same display width
561        // Use .width() instead of .len() to handle CJK characters correctly
562        // (CJK chars are 3 bytes but 2 display columns)
563        let first_width = UnicodeWidthStr::width(table_lines[0]);
564        if !table_lines
565            .iter()
566            .all(|line| UnicodeWidthStr::width(*line) == first_width)
567        {
568            return false;
569        }
570
571        // Parse all rows and check column count consistency
572        let parsed: Vec<Vec<String>> = table_lines
573            .iter()
574            .map(|line| Self::parse_table_row_with_flavor(line, flavor))
575            .collect();
576
577        if parsed.is_empty() {
578            return false;
579        }
580
581        let num_columns = parsed[0].len();
582        if !parsed.iter().all(|row| row.len() == num_columns) {
583            return false;
584        }
585
586        // Check delimiter row has valid minimum widths (3 chars: at least one dash + optional colons)
587        // Delimiter row is always at index 1
588        if let Some(delimiter_row) = parsed.get(1) {
589            if !Self::is_delimiter_row(delimiter_row) {
590                return false;
591            }
592            // Check each delimiter cell has at least one dash (minimum valid is "---" or ":--" etc)
593            for cell in delimiter_row {
594                let trimmed = cell.trim();
595                let dash_count = trimmed.chars().filter(|&c| c == '-').count();
596                if dash_count < 1 {
597                    return false;
598                }
599            }
600
601            // Check if delimiter row style matches the target style
602            // compact_delimiter=true means "aligned-no-space" (no spaces around dashes)
603            // compact_delimiter=false means "aligned" (spaces around dashes)
604            let delimiter_has_spaces = delimiter_row
605                .iter()
606                .all(|cell| cell.starts_with(' ') && cell.ends_with(' '));
607
608            // If target is compact (no spaces) but current has spaces, not aligned
609            // If target is spaced but current has no spaces, not aligned
610            if compact_delimiter && delimiter_has_spaces {
611                return false;
612            }
613            if !compact_delimiter && !delimiter_has_spaces {
614                return false;
615            }
616        }
617
618        // Check each column has consistent width across all content rows
619        // Use cell.width() to get display width INCLUDING padding, not trimmed content
620        // This correctly handles CJK characters (display width 2, byte length 3)
621        for col_idx in 0..num_columns {
622            let mut widths = Vec::new();
623            for (row_idx, row) in parsed.iter().enumerate() {
624                // Skip delimiter row for content width check
625                if row_idx == 1 {
626                    continue;
627                }
628                if let Some(cell) = row.get(col_idx) {
629                    widths.push(cell.width());
630                }
631            }
632            // All content cells in this column should have the same display width
633            if !widths.is_empty() && !widths.iter().all(|&w| w == widths[0]) {
634                return false;
635            }
636        }
637
638        // Check 5: Content padding distribution matches column alignment
639        // For center-aligned columns, content must be centered (left/right padding differ by at most 1)
640        // For right-aligned columns, content must be right-aligned (left padding >= right padding)
641        // Padding is counted in space characters (always 1 byte each), so byte-length arithmetic is safe.
642        if let Some(delimiter_row) = parsed.get(1) {
643            let alignments = Self::parse_column_alignments(delimiter_row);
644            for (col_idx, alignment) in alignments.iter().enumerate() {
645                if *alignment == ColumnAlignment::Left {
646                    continue;
647                }
648                for (row_idx, row) in parsed.iter().enumerate() {
649                    // Skip delimiter row
650                    if row_idx == 1 {
651                        continue;
652                    }
653                    if let Some(cell) = row.get(col_idx) {
654                        if cell.trim().is_empty() {
655                            continue;
656                        }
657                        // Count leading/trailing space characters (always ASCII, so byte length = char count)
658                        let left_pad = cell.len() - cell.trim_start().len();
659                        let right_pad = cell.len() - cell.trim_end().len();
660
661                        match alignment {
662                            ColumnAlignment::Center => {
663                                // Center: left and right padding must differ by at most 1
664                                if left_pad.abs_diff(right_pad) > 1 {
665                                    return false;
666                                }
667                            }
668                            ColumnAlignment::Right => {
669                                // Right: content pushed right means more padding on the left
670                                if left_pad < right_pad {
671                                    return false;
672                                }
673                            }
674                            ColumnAlignment::Left => unreachable!(),
675                        }
676                    }
677                }
678            }
679        }
680
681        true
682    }
683
684    fn detect_table_style(table_lines: &[&str], flavor: crate::config::MarkdownFlavor) -> Option<String> {
685        if table_lines.is_empty() {
686            return None;
687        }
688
689        // Check all rows (except delimiter) to determine consistent style
690        // A table is only "tight" or "compact" if ALL rows follow that pattern
691        let mut is_tight = true;
692        let mut is_compact = true;
693
694        for line in table_lines {
695            let cells = Self::parse_table_row_with_flavor(line, flavor);
696
697            if cells.is_empty() {
698                continue;
699            }
700
701            // Skip delimiter rows when detecting style
702            if Self::is_delimiter_row(&cells) {
703                continue;
704            }
705
706            // Check if this row has no padding
707            let row_has_no_padding = cells.iter().all(|cell| !cell.starts_with(' ') && !cell.ends_with(' '));
708
709            // Compact rows pad every cell with one space on each side. An
710            // empty compact cell is the special case `" "` (single space
711            // between pipes), matching mdformat's canonical empty cell.
712            let row_has_single_space = cells.iter().all(|cell| match cell.trim() {
713                "" => cell == " ",
714                trimmed => cell == &format!(" {trimmed} "),
715            });
716
717            // If any row doesn't match tight, the table isn't tight
718            if !row_has_no_padding {
719                is_tight = false;
720            }
721
722            // If any row doesn't match compact, the table isn't compact
723            if !row_has_single_space {
724                is_compact = false;
725            }
726
727            // Early exit: if neither tight nor compact, it must be aligned
728            if !is_tight && !is_compact {
729                return Some("aligned".to_string());
730            }
731        }
732
733        // Return the most restrictive style that matches
734        if is_tight {
735            Some("tight".to_string())
736        } else if is_compact {
737            Some("compact".to_string())
738        } else {
739            Some("aligned".to_string())
740        }
741    }
742
743    fn fix_table_block(
744        &self,
745        lines: &[&str],
746        table_block: &crate::utils::table_utils::TableBlock,
747        flavor: crate::config::MarkdownFlavor,
748    ) -> TableFormatResult {
749        let mut result = Vec::new();
750        let mut auto_compacted = false;
751        let mut aligned_width = None;
752
753        let table_lines: Vec<&str> = std::iter::once(lines[table_block.header_line])
754            .chain(std::iter::once(lines[table_block.delimiter_line]))
755            .chain(table_block.content_lines.iter().map(|&idx| lines[idx]))
756            .collect();
757
758        if table_lines.iter().any(|line| Self::contains_problematic_chars(line)) {
759            return TableFormatResult {
760                lines: table_lines.iter().map(std::string::ToString::to_string).collect(),
761                auto_compacted: false,
762                aligned_width: None,
763            };
764        }
765
766        // Extract blockquote prefix from the header line (first line of table)
767        // All lines in the same table should have the same blockquote level
768        let (blockquote_prefix, _) = Self::extract_blockquote_prefix(table_lines[0]);
769
770        // Extract list prefix if present (for tables inside list items)
771        let list_context = &table_block.list_context;
772        let (list_prefix, continuation_indent) = if let Some(ctx) = list_context {
773            (ctx.list_prefix.as_str(), " ".repeat(ctx.content_indent))
774        } else {
775            ("", String::new())
776        };
777
778        // Strip blockquote prefix and list prefix from all lines for processing
779        let stripped_lines: Vec<&str> = table_lines
780            .iter()
781            .enumerate()
782            .map(|(i, line)| {
783                let after_blockquote = Self::extract_blockquote_prefix(line).1;
784                if list_context.is_some() {
785                    if i == 0 {
786                        // Header line: strip list prefix (handles both markers and indentation)
787                        after_blockquote.strip_prefix(list_prefix).unwrap_or_else(|| {
788                            crate::utils::table_utils::TableUtils::extract_list_prefix(after_blockquote).1
789                        })
790                    } else {
791                        // Continuation lines: strip expected indentation
792                        after_blockquote
793                            .strip_prefix(&continuation_indent)
794                            .unwrap_or(after_blockquote.trim_start())
795                    }
796                } else {
797                    after_blockquote
798                }
799            })
800            .collect();
801
802        let style = self.config.style.as_str();
803
804        match style {
805            "any" => {
806                let detected_style = Self::detect_table_style(&stripped_lines, flavor);
807                if detected_style.is_none() {
808                    return TableFormatResult {
809                        lines: table_lines.iter().map(std::string::ToString::to_string).collect(),
810                        auto_compacted: false,
811                        aligned_width: None,
812                    };
813                }
814
815                let target_style = detected_style.unwrap();
816
817                // Parse column alignments from delimiter row (always at index 1)
818                let delimiter_cells = Self::parse_table_row_with_flavor(stripped_lines[1], flavor);
819                let column_alignments = Self::parse_column_alignments(&delimiter_cells);
820
821                for (row_idx, line) in stripped_lines.iter().enumerate() {
822                    let cells = Self::parse_table_row_with_flavor(line, flavor);
823                    match target_style.as_str() {
824                        "tight" => result.push(Self::format_table_tight(&cells)),
825                        "compact" => result.push(Self::format_table_compact(&cells)),
826                        _ => {
827                            let column_widths =
828                                Self::calculate_column_widths(&stripped_lines, flavor, self.config.loose_last_column);
829                            let row_type = match row_idx {
830                                0 => RowType::Header,
831                                1 => RowType::Delimiter,
832                                _ => RowType::Body,
833                            };
834                            let options = RowFormatOptions {
835                                row_type,
836                                compact_delimiter: false,
837                                column_align: self.config.column_align,
838                                column_align_header: self.config.column_align_header,
839                                column_align_body: self.config.column_align_body,
840                            };
841                            result.push(Self::format_table_row(
842                                &cells,
843                                &column_widths,
844                                &column_alignments,
845                                &options,
846                            ));
847                        }
848                    }
849                }
850            }
851            "compact" | "tight" => {
852                let compact = style == "compact";
853                let header_widths = if self.config.aligned_delimiter && stripped_lines.len() >= 2 {
854                    let header_cells = Self::parse_table_row_with_flavor(stripped_lines[0], flavor);
855                    Some(Self::header_cell_widths(&header_cells))
856                } else {
857                    None
858                };
859
860                for (row_idx, line) in stripped_lines.iter().enumerate() {
861                    let cells = Self::parse_table_row_with_flavor(line, flavor);
862                    if row_idx == 1
863                        && let Some(widths) = &header_widths
864                    {
865                        result.push(Self::format_delimiter_aligned_to_header(&cells, widths, compact));
866                        continue;
867                    }
868                    result.push(if compact {
869                        Self::format_table_compact(&cells)
870                    } else {
871                        Self::format_table_tight(&cells)
872                    });
873                }
874            }
875            "aligned" | "aligned-no-space" => {
876                let compact_delimiter = style == "aligned-no-space";
877
878                // Determine if we need to reformat: skip if table is already aligned
879                // UNLESS any alignment or formatting options require reformatting
880                let needs_reformat = self.config.column_align != ColumnAlign::Auto
881                    || self.config.column_align_header.is_some()
882                    || self.config.column_align_body.is_some()
883                    || self.config.loose_last_column;
884
885                if !needs_reformat && Self::is_table_already_aligned(&stripped_lines, flavor, compact_delimiter) {
886                    return TableFormatResult {
887                        lines: table_lines.iter().map(std::string::ToString::to_string).collect(),
888                        auto_compacted: false,
889                        aligned_width: None,
890                    };
891                }
892
893                let column_widths =
894                    Self::calculate_column_widths(&stripped_lines, flavor, self.config.loose_last_column);
895
896                // Calculate aligned table width: 1 (leading pipe) + num_columns * 3 (| cell |) + sum(column_widths)
897                let num_columns = column_widths.len();
898                let calc_aligned_width = 1 + (num_columns * 3) + column_widths.iter().sum::<usize>();
899                aligned_width = Some(calc_aligned_width);
900
901                // Auto-compact: if aligned table exceeds max width, use compact formatting instead.
902                // The effective output style is now `compact`, so honor `aligned-delimiter`
903                // exactly as the explicit `compact` style does: align the delimiter row's pipes
904                // to the header column widths while body rows stay compact.
905                if calc_aligned_width > self.effective_max_width() {
906                    auto_compacted = true;
907                    let header_widths = if self.config.aligned_delimiter && stripped_lines.len() >= 2 {
908                        let header_cells = Self::parse_table_row_with_flavor(stripped_lines[0], flavor);
909                        Some(Self::header_cell_widths(&header_cells))
910                    } else {
911                        None
912                    };
913                    for (row_idx, line) in stripped_lines.iter().enumerate() {
914                        let cells = Self::parse_table_row_with_flavor(line, flavor);
915                        if row_idx == 1
916                            && let Some(widths) = &header_widths
917                        {
918                            // Auto-compact always produces the single-space compact form.
919                            result.push(Self::format_delimiter_aligned_to_header(&cells, widths, true));
920                            continue;
921                        }
922                        result.push(Self::format_table_compact(&cells));
923                    }
924                } else {
925                    // Parse column alignments from delimiter row (always at index 1)
926                    let delimiter_cells = Self::parse_table_row_with_flavor(stripped_lines[1], flavor);
927                    let column_alignments = Self::parse_column_alignments(&delimiter_cells);
928
929                    for (row_idx, line) in stripped_lines.iter().enumerate() {
930                        let cells = Self::parse_table_row_with_flavor(line, flavor);
931                        let row_type = match row_idx {
932                            0 => RowType::Header,
933                            1 => RowType::Delimiter,
934                            _ => RowType::Body,
935                        };
936                        let options = RowFormatOptions {
937                            row_type,
938                            compact_delimiter,
939                            column_align: self.config.column_align,
940                            column_align_header: self.config.column_align_header,
941                            column_align_body: self.config.column_align_body,
942                        };
943                        result.push(Self::format_table_row(
944                            &cells,
945                            &column_widths,
946                            &column_alignments,
947                            &options,
948                        ));
949                    }
950                }
951            }
952            _ => {
953                return TableFormatResult {
954                    lines: table_lines.iter().map(std::string::ToString::to_string).collect(),
955                    auto_compacted: false,
956                    aligned_width: None,
957                };
958            }
959        }
960
961        // Re-add blockquote prefix and list prefix to all formatted lines
962        let prefixed_result: Vec<String> = result
963            .into_iter()
964            .enumerate()
965            .map(|(i, line)| {
966                if list_context.is_some() {
967                    if i == 0 {
968                        // Header line: add list prefix
969                        format!("{blockquote_prefix}{list_prefix}{line}")
970                    } else {
971                        // Continuation lines: add indentation
972                        format!("{blockquote_prefix}{continuation_indent}{line}")
973                    }
974                } else {
975                    format!("{blockquote_prefix}{line}")
976                }
977            })
978            .collect();
979
980        TableFormatResult {
981            lines: prefixed_result,
982            auto_compacted,
983            aligned_width,
984        }
985    }
986}
987
988impl Rule for MD060TableFormat {
989    fn name(&self) -> &'static str {
990        "MD060"
991    }
992
993    fn description(&self) -> &'static str {
994        "Table columns should be consistently aligned"
995    }
996
997    fn category(&self) -> RuleCategory {
998        RuleCategory::Table
999    }
1000
1001    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
1002        !ctx.likely_has_tables()
1003    }
1004
1005    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
1006        let mut warnings = Vec::new();
1007
1008        let lines = ctx.raw_lines();
1009        let table_blocks = &ctx.table_blocks;
1010
1011        for table_block in table_blocks {
1012            let format_result = self.fix_table_block(lines, table_block, ctx.flavor);
1013
1014            let table_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
1015                .chain(std::iter::once(table_block.delimiter_line))
1016                .chain(table_block.content_lines.iter().copied())
1017                .collect();
1018
1019            // Build the whole-table fix once for all warnings in this table
1020            // This ensures that applying Quick Fix on any row fixes the entire table
1021            let table_start_line = table_block.start_line + 1; // Convert to 1-indexed
1022            let table_end_line = table_block.end_line + 1; // Convert to 1-indexed
1023
1024            // Build the complete fixed table content
1025            let mut fixed_table_lines: Vec<String> = Vec::with_capacity(table_line_indices.len());
1026            for (i, &line_idx) in table_line_indices.iter().enumerate() {
1027                let fixed_line = &format_result.lines[i];
1028                // Add newline for all lines except the last if the original didn't have one
1029                if line_idx < lines.len() - 1 {
1030                    fixed_table_lines.push(format!("{fixed_line}\n"));
1031                } else {
1032                    fixed_table_lines.push(fixed_line.clone());
1033                }
1034            }
1035            let table_replacement = fixed_table_lines.concat();
1036            let table_range = ctx.line_span_byte_range(table_start_line, table_end_line);
1037
1038            for (i, &line_idx) in table_line_indices.iter().enumerate() {
1039                let original = lines[line_idx];
1040                let fixed = &format_result.lines[i];
1041
1042                if original != fixed {
1043                    let (start_line, start_col, end_line, end_col) = calculate_line_range(line_idx + 1, original);
1044
1045                    let message = if format_result.auto_compacted {
1046                        if let Some(width) = format_result.aligned_width {
1047                            format!(
1048                                "Table too wide for aligned formatting ({} chars > max-width: {})",
1049                                width,
1050                                self.effective_max_width()
1051                            )
1052                        } else {
1053                            "Table too wide for aligned formatting".to_string()
1054                        }
1055                    } else {
1056                        "Table columns should be aligned".to_string()
1057                    };
1058
1059                    // Each warning uses the same whole-table fix
1060                    // This ensures Quick Fix on any row aligns the entire table
1061                    warnings.push(LintWarning {
1062                        rule_name: Some(self.name().to_string()),
1063                        severity: Severity::Warning,
1064                        message,
1065                        line: start_line,
1066                        column: start_col,
1067                        end_line,
1068                        end_column: end_col,
1069                        fix: Some(crate::rule::Fix::new(table_range.clone(), table_replacement.clone())),
1070                    });
1071                }
1072            }
1073        }
1074
1075        Ok(warnings)
1076    }
1077
1078    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
1079        let content = ctx.content;
1080        let lines = ctx.raw_lines();
1081        let table_blocks = &ctx.table_blocks;
1082
1083        // Nothing to format when there are no tables; return the content verbatim
1084        // so non-table documents are never altered.
1085        if table_blocks.is_empty() {
1086            return Ok(content.to_string());
1087        }
1088
1089        let mut result_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
1090
1091        for table_block in table_blocks {
1092            let format_result = self.fix_table_block(lines, table_block, ctx.flavor);
1093
1094            let table_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
1095                .chain(std::iter::once(table_block.delimiter_line))
1096                .chain(table_block.content_lines.iter().copied())
1097                .collect();
1098
1099            // Check if any line in this table has the rule disabled via inline config;
1100            // if so, skip fixing the entire table to avoid partial formatting
1101            let any_disabled = table_line_indices
1102                .iter()
1103                .any(|&line_idx| ctx.inline_config().is_rule_disabled(self.name(), line_idx + 1));
1104
1105            if any_disabled {
1106                continue;
1107            }
1108
1109            for (i, &line_idx) in table_line_indices.iter().enumerate() {
1110                result_lines[line_idx].clone_from(&format_result.lines[i]);
1111            }
1112        }
1113
1114        let mut fixed = result_lines.join("\n");
1115        // `raw_lines()` drops the trailing empty line, so `join("\n")` collapses a
1116        // run of trailing blank lines down to a single newline. Restore the
1117        // original trailing-newline run exactly so trailing blank lines are
1118        // preserved and the fix is idempotent.
1119        let original_trailing_newlines = content.len() - content.trim_end_matches('\n').len();
1120        fixed.truncate(fixed.trim_end_matches('\n').len());
1121        fixed.push_str(&"\n".repeat(original_trailing_newlines));
1122        Ok(fixed)
1123    }
1124
1125    fn as_any(&self) -> &dyn std::any::Any {
1126        self
1127    }
1128
1129    crate::impl_rule_config_sections!(MD060Config);
1130
1131    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
1132    where
1133        Self: Sized,
1134    {
1135        let rule_config = crate::rule_config_serde::load_rule_config::<MD060Config>(config);
1136        let md013_config = crate::rule_config_serde::load_rule_config::<MD013Config>(config);
1137
1138        // Check if MD013 is globally disabled
1139        let md013_disabled = config.global.disable.iter().any(|r| r == "MD013");
1140
1141        Box::new(Self::from_config_struct(rule_config, md013_config, md013_disabled))
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148    use crate::lint_context::LintContext;
1149    use crate::types::LineLength;
1150
1151    /// Helper to create an MD013Config with a specific line length for testing
1152    fn md013_with_line_length(line_length: usize) -> MD013Config {
1153        MD013Config {
1154            line_length: LineLength::from_const(line_length),
1155            tables: true, // Default: tables are checked
1156            ..Default::default()
1157        }
1158    }
1159
1160    #[test]
1161    fn test_md060_align_simple_ascii_table() {
1162        let rule = MD060TableFormat::new(true, "aligned".to_string());
1163
1164        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1165        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1166
1167        let fixed = rule.fix(&ctx).unwrap();
1168        let expected = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |";
1169        assert_eq!(fixed, expected);
1170
1171        // Verify all rows have equal length in aligned mode
1172        let lines: Vec<&str> = fixed.lines().collect();
1173        assert_eq!(lines[0].len(), lines[1].len());
1174        assert_eq!(lines[1].len(), lines[2].len());
1175    }
1176
1177    #[test]
1178    fn test_md060_cjk_characters_aligned_correctly() {
1179        let rule = MD060TableFormat::new(true, "aligned".to_string());
1180
1181        let content = "| Name | Age |\n|---|---|\n| δΈ­ζ–‡ | 30 |";
1182        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1183
1184        let fixed = rule.fix(&ctx).unwrap();
1185
1186        let lines: Vec<&str> = fixed.lines().collect();
1187        let cells_line1 = MD060TableFormat::parse_table_row(lines[0]);
1188        let cells_line3 = MD060TableFormat::parse_table_row(lines[2]);
1189
1190        let width1 = MD060TableFormat::calculate_cell_display_width(&cells_line1[0]);
1191        let width3 = MD060TableFormat::calculate_cell_display_width(&cells_line3[0]);
1192
1193        assert_eq!(width1, width3);
1194    }
1195
1196    #[test]
1197    fn test_md060_basic_emoji() {
1198        let rule = MD060TableFormat::new(true, "aligned".to_string());
1199
1200        let content = "| Status | Name |\n|---|---|\n| βœ… | Test |";
1201        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1202
1203        let fixed = rule.fix(&ctx).unwrap();
1204        assert!(fixed.contains("Status"));
1205    }
1206
1207    #[test]
1208    fn test_md060_zwj_emoji_skipped() {
1209        let rule = MD060TableFormat::new(true, "aligned".to_string());
1210
1211        let content = "| Emoji | Name |\n|---|---|\n| πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ | Family |";
1212        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1213
1214        let fixed = rule.fix(&ctx).unwrap();
1215        assert_eq!(fixed, content);
1216    }
1217
1218    #[test]
1219    fn test_md060_inline_code_with_escaped_pipes() {
1220        // Pipes inside code spans are treated as content, not cell delimiters.
1221        // Escaped pipes (\|) are also supported outside code spans.
1222        let rule = MD060TableFormat::new(true, "aligned".to_string());
1223
1224        // CORRECT: `[0-9]\|[0-9]` - the \| is escaped, stays as content (2 columns)
1225        let content = "| Pattern | Regex |\n|---|---|\n| Time | `[0-9]\\|[0-9]` |";
1226        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1227
1228        let fixed = rule.fix(&ctx).unwrap();
1229        assert!(fixed.contains(r"`[0-9]\|[0-9]`"), "Escaped pipes should be preserved");
1230    }
1231
1232    #[test]
1233    fn test_md060_compact_style() {
1234        let rule = MD060TableFormat::new(true, "compact".to_string());
1235
1236        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1237        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1238
1239        let fixed = rule.fix(&ctx).unwrap();
1240        let expected = "| Name | Age |\n| --- | --- |\n| Alice | 30 |";
1241        assert_eq!(fixed, expected);
1242    }
1243
1244    #[test]
1245    fn test_md060_tight_style() {
1246        let rule = MD060TableFormat::new(true, "tight".to_string());
1247
1248        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1249        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1250
1251        let fixed = rule.fix(&ctx).unwrap();
1252        let expected = "|Name|Age|\n|---|---|\n|Alice|30|";
1253        assert_eq!(fixed, expected);
1254    }
1255
1256    #[test]
1257    fn test_md060_aligned_no_space_style() {
1258        // Issue #277: aligned-no-space style has no spaces in delimiter row
1259        let rule = MD060TableFormat::new(true, "aligned-no-space".to_string());
1260
1261        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1262        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1263
1264        let fixed = rule.fix(&ctx).unwrap();
1265
1266        // Content rows have spaces, delimiter row does not
1267        let lines: Vec<&str> = fixed.lines().collect();
1268        assert_eq!(lines[0], "| Name  | Age |", "Header should have spaces around content");
1269        assert_eq!(
1270            lines[1], "|-------|-----|",
1271            "Delimiter should have NO spaces around dashes"
1272        );
1273        assert_eq!(lines[2], "| Alice | 30  |", "Content should have spaces around content");
1274
1275        // All rows should have equal length
1276        assert_eq!(lines[0].len(), lines[1].len());
1277        assert_eq!(lines[1].len(), lines[2].len());
1278    }
1279
1280    #[test]
1281    fn test_md060_aligned_no_space_preserves_alignment_indicators() {
1282        // Alignment indicators (:) should be preserved
1283        let rule = MD060TableFormat::new(true, "aligned-no-space".to_string());
1284
1285        let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
1286        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1287
1288        let fixed = rule.fix(&ctx).unwrap();
1289        let lines: Vec<&str> = fixed.lines().collect();
1290
1291        // Verify alignment indicators are preserved without spaces around them
1292        assert!(
1293            fixed.contains("|:"),
1294            "Should have left alignment indicator adjacent to pipe"
1295        );
1296        assert!(
1297            fixed.contains(":|"),
1298            "Should have right alignment indicator adjacent to pipe"
1299        );
1300        // Check for center alignment - the exact dash count depends on column width
1301        assert!(
1302            lines[1].contains(":---") && lines[1].contains("---:"),
1303            "Should have center alignment colons"
1304        );
1305    }
1306
1307    #[test]
1308    fn test_md060_aligned_no_space_three_column_table() {
1309        // Test the exact format from issue #277
1310        let rule = MD060TableFormat::new(true, "aligned-no-space".to_string());
1311
1312        let content = "| Header 1 | Header 2 | Header 3 |\n|---|---|---|\n| Row 1, Col 1 | Row 1, Col 2 | Row 1, Col 3 |\n| Row 2, Col 1 | Row 2, Col 2 | Row 2, Col 3 |";
1313        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1314
1315        let fixed = rule.fix(&ctx).unwrap();
1316        let lines: Vec<&str> = fixed.lines().collect();
1317
1318        // Verify delimiter row format: |--------------|--------------|--------------|
1319        assert!(lines[1].starts_with("|---"), "Delimiter should start with |---");
1320        assert!(lines[1].ends_with("---|"), "Delimiter should end with ---|");
1321        assert!(!lines[1].contains("| -"), "Delimiter should NOT have space after pipe");
1322        assert!(!lines[1].contains("- |"), "Delimiter should NOT have space before pipe");
1323    }
1324
1325    #[test]
1326    fn test_md060_aligned_no_space_auto_compacts_wide_tables() {
1327        // Auto-compact should work with aligned-no-space when table exceeds max-width
1328        let config = MD060Config {
1329            enabled: true,
1330            style: "aligned-no-space".to_string(),
1331            max_width: LineLength::from_const(50),
1332            column_align: ColumnAlign::Auto,
1333            column_align_header: None,
1334            column_align_body: None,
1335            loose_last_column: false,
1336            aligned_delimiter: false,
1337        };
1338        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1339
1340        // Wide table that exceeds 50 chars when aligned
1341        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| x | y | z |";
1342        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1343
1344        let fixed = rule.fix(&ctx).unwrap();
1345
1346        // Should auto-compact to compact style (not aligned-no-space)
1347        assert!(
1348            fixed.contains("| --- |"),
1349            "Should be compact format when exceeding max-width"
1350        );
1351    }
1352
1353    #[test]
1354    fn test_md060_aligned_no_space_cjk_characters() {
1355        // CJK characters should be handled correctly
1356        let rule = MD060TableFormat::new(true, "aligned-no-space".to_string());
1357
1358        let content = "| Name | City |\n|---|---|\n| δΈ­ζ–‡ | 東京 |";
1359        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1360
1361        let fixed = rule.fix(&ctx).unwrap();
1362        let lines: Vec<&str> = fixed.lines().collect();
1363
1364        // All rows should have equal DISPLAY width (not byte length)
1365        // CJK characters are double-width, so byte length differs from display width
1366        use unicode_width::UnicodeWidthStr;
1367        assert_eq!(
1368            lines[0].width(),
1369            lines[1].width(),
1370            "Header and delimiter should have same display width"
1371        );
1372        assert_eq!(
1373            lines[1].width(),
1374            lines[2].width(),
1375            "Delimiter and content should have same display width"
1376        );
1377
1378        // Delimiter should have no spaces
1379        assert!(!lines[1].contains("| -"), "Delimiter should NOT have space after pipe");
1380    }
1381
1382    #[test]
1383    fn test_md060_aligned_no_space_minimum_width() {
1384        // Minimum column width (3 dashes) should be respected
1385        let rule = MD060TableFormat::new(true, "aligned-no-space".to_string());
1386
1387        let content = "| A | B |\n|-|-|\n| 1 | 2 |";
1388        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1389
1390        let fixed = rule.fix(&ctx).unwrap();
1391        let lines: Vec<&str> = fixed.lines().collect();
1392
1393        // Should have at least 3 dashes per column (GFM requirement)
1394        assert!(lines[1].contains("---"), "Should have minimum 3 dashes");
1395        // All rows should have equal length
1396        assert_eq!(lines[0].len(), lines[1].len());
1397        assert_eq!(lines[1].len(), lines[2].len());
1398    }
1399
1400    #[test]
1401    fn test_md060_any_style_consistency() {
1402        let rule = MD060TableFormat::new(true, "any".to_string());
1403
1404        // Table is already compact, should stay compact
1405        let content = "| Name | Age |\n| --- | --- |\n| Alice | 30 |";
1406        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1407
1408        let fixed = rule.fix(&ctx).unwrap();
1409        assert_eq!(fixed, content);
1410
1411        // Table is aligned, should stay aligned
1412        let content_aligned = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |";
1413        let ctx_aligned = LintContext::new(content_aligned, crate::config::MarkdownFlavor::Standard, None);
1414
1415        let fixed_aligned = rule.fix(&ctx_aligned).unwrap();
1416        assert_eq!(fixed_aligned, content_aligned);
1417    }
1418
1419    #[test]
1420    fn test_md060_empty_cells() {
1421        let rule = MD060TableFormat::new(true, "aligned".to_string());
1422
1423        let content = "| A | B |\n|---|---|\n|  | X |";
1424        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1425
1426        let fixed = rule.fix(&ctx).unwrap();
1427        assert!(fixed.contains('|'));
1428    }
1429
1430    #[test]
1431    fn test_md060_mixed_content() {
1432        let rule = MD060TableFormat::new(true, "aligned".to_string());
1433
1434        let content = "| Name | Age | City |\n|---|---|---|\n| δΈ­ζ–‡ | 30 | NYC |";
1435        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1436
1437        let fixed = rule.fix(&ctx).unwrap();
1438        assert!(fixed.contains("δΈ­ζ–‡"));
1439        assert!(fixed.contains("NYC"));
1440    }
1441
1442    #[test]
1443    fn test_md060_preserve_alignment_indicators() {
1444        let rule = MD060TableFormat::new(true, "aligned".to_string());
1445
1446        let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
1447        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1448
1449        let fixed = rule.fix(&ctx).unwrap();
1450
1451        assert!(fixed.contains(":---"), "Should contain left alignment");
1452        assert!(fixed.contains(":----:"), "Should contain center alignment");
1453        assert!(fixed.contains("----:"), "Should contain right alignment");
1454    }
1455
1456    #[test]
1457    fn test_md060_minimum_column_width() {
1458        let rule = MD060TableFormat::new(true, "aligned".to_string());
1459
1460        // Test with very short column content to ensure minimum width of 3
1461        // GFM requires at least 3 dashes in delimiter rows
1462        let content = "| ID | Name |\n|-|-|\n| 1 | A |";
1463        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1464
1465        let fixed = rule.fix(&ctx).unwrap();
1466
1467        let lines: Vec<&str> = fixed.lines().collect();
1468        assert_eq!(lines[0].len(), lines[1].len());
1469        assert_eq!(lines[1].len(), lines[2].len());
1470
1471        // Verify minimum width is enforced
1472        assert!(fixed.contains("ID "), "Short content should be padded");
1473        assert!(fixed.contains("---"), "Delimiter should have at least 3 dashes");
1474    }
1475
1476    #[test]
1477    fn test_md060_auto_compact_exceeds_default_threshold() {
1478        // Default max_width = 0, which inherits from default MD013 line_length = 80
1479        let config = MD060Config {
1480            enabled: true,
1481            style: "aligned".to_string(),
1482            max_width: LineLength::from_const(0),
1483            column_align: ColumnAlign::Auto,
1484            column_align_header: None,
1485            column_align_body: None,
1486            loose_last_column: false,
1487            aligned_delimiter: false,
1488        };
1489        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1490
1491        // Table that would be 85 chars when aligned (exceeds 80)
1492        // Formula: 1 + (3 * 3) + (20 + 20 + 30) = 1 + 9 + 70 = 80 chars
1493        // But with actual content padding it will exceed
1494        let content = "| Very Long Column Header | Another Long Header | Third Very Long Header Column |\n|---|---|---|\n| Short | Data | Here |";
1495        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1496
1497        let fixed = rule.fix(&ctx).unwrap();
1498
1499        // Should use compact formatting (single spaces)
1500        assert!(fixed.contains("| Very Long Column Header | Another Long Header | Third Very Long Header Column |"));
1501        assert!(fixed.contains("| --- | --- | --- |"));
1502        assert!(fixed.contains("| Short | Data | Here |"));
1503
1504        // Verify it's compact (no extra padding)
1505        let lines: Vec<&str> = fixed.lines().collect();
1506        // In compact mode, lines can have different lengths
1507        assert!(lines[0].len() != lines[1].len() || lines[1].len() != lines[2].len());
1508    }
1509
1510    #[test]
1511    fn test_md060_auto_compact_exceeds_explicit_threshold() {
1512        // Explicit max_width = 50
1513        let config = MD060Config {
1514            enabled: true,
1515            style: "aligned".to_string(),
1516            max_width: LineLength::from_const(50),
1517            column_align: ColumnAlign::Auto,
1518            column_align_header: None,
1519            column_align_body: None,
1520            loose_last_column: false,
1521            aligned_delimiter: false,
1522        };
1523        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false); // MD013 setting doesn't matter
1524
1525        // Table that would exceed 50 chars when aligned
1526        // Column widths: 25 + 25 + 25 = 75 chars
1527        // Formula: 1 + (3 * 3) + 75 = 85 chars (exceeds 50)
1528        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| Data | Data | Data |";
1529        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1530
1531        let fixed = rule.fix(&ctx).unwrap();
1532
1533        // Should use compact formatting (single spaces, no extra padding)
1534        assert!(
1535            fixed.contains("| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |")
1536        );
1537        assert!(fixed.contains("| --- | --- | --- |"));
1538        assert!(fixed.contains("| Data | Data | Data |"));
1539
1540        // Verify it's compact (lines have different lengths)
1541        let lines: Vec<&str> = fixed.lines().collect();
1542        assert!(lines[0].len() != lines[2].len());
1543    }
1544
1545    #[test]
1546    fn test_md060_stays_aligned_under_threshold() {
1547        // max_width = 100, table will be under this
1548        let config = MD060Config {
1549            enabled: true,
1550            style: "aligned".to_string(),
1551            max_width: LineLength::from_const(100),
1552            column_align: ColumnAlign::Auto,
1553            column_align_header: None,
1554            column_align_body: None,
1555            loose_last_column: false,
1556            aligned_delimiter: false,
1557        };
1558        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1559
1560        // Small table that fits well under 100 chars
1561        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1562        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1563
1564        let fixed = rule.fix(&ctx).unwrap();
1565
1566        // Should use aligned formatting (all lines same length)
1567        let expected = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |";
1568        assert_eq!(fixed, expected);
1569
1570        let lines: Vec<&str> = fixed.lines().collect();
1571        assert_eq!(lines[0].len(), lines[1].len());
1572        assert_eq!(lines[1].len(), lines[2].len());
1573    }
1574
1575    #[test]
1576    fn test_md060_width_calculation_formula() {
1577        // Verify the width calculation formula: 1 + (num_columns * 3) + sum(column_widths)
1578        let config = MD060Config {
1579            enabled: true,
1580            style: "aligned".to_string(),
1581            max_width: LineLength::from_const(0),
1582            column_align: ColumnAlign::Auto,
1583            column_align_header: None,
1584            column_align_body: None,
1585            loose_last_column: false,
1586            aligned_delimiter: false,
1587        };
1588        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(30), false);
1589
1590        // Create a table where we know exact column widths: 5 + 5 + 5 = 15
1591        // Expected aligned width: 1 + (3 * 3) + 15 = 1 + 9 + 15 = 25 chars
1592        // This is under 30, so should stay aligned
1593        let content = "| AAAAA | BBBBB | CCCCC |\n|---|---|---|\n| AAAAA | BBBBB | CCCCC |";
1594        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1595
1596        let fixed = rule.fix(&ctx).unwrap();
1597
1598        // Should be aligned
1599        let lines: Vec<&str> = fixed.lines().collect();
1600        assert_eq!(lines[0].len(), lines[1].len());
1601        assert_eq!(lines[1].len(), lines[2].len());
1602        assert_eq!(lines[0].len(), 25); // Verify formula
1603
1604        // Now test with threshold = 24 (just under aligned width)
1605        let config_tight = MD060Config {
1606            enabled: true,
1607            style: "aligned".to_string(),
1608            max_width: LineLength::from_const(24),
1609            column_align: ColumnAlign::Auto,
1610            column_align_header: None,
1611            column_align_body: None,
1612            loose_last_column: false,
1613            aligned_delimiter: false,
1614        };
1615        let rule_tight = MD060TableFormat::from_config_struct(config_tight, md013_with_line_length(80), false);
1616
1617        let fixed_compact = rule_tight.fix(&ctx).unwrap();
1618
1619        // Should be compact now (25 > 24)
1620        assert!(fixed_compact.contains("| AAAAA | BBBBB | CCCCC |"));
1621        assert!(fixed_compact.contains("| --- | --- | --- |"));
1622    }
1623
1624    #[test]
1625    fn test_md060_very_wide_table_auto_compacts() {
1626        let config = MD060Config {
1627            enabled: true,
1628            style: "aligned".to_string(),
1629            max_width: LineLength::from_const(0),
1630            column_align: ColumnAlign::Auto,
1631            column_align_header: None,
1632            column_align_body: None,
1633            loose_last_column: false,
1634            aligned_delimiter: false,
1635        };
1636        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1637
1638        // Very wide table with many columns
1639        // 8 columns with widths of 12 chars each = 96 chars
1640        // Formula: 1 + (8 * 3) + 96 = 121 chars (exceeds 80)
1641        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 |";
1642        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1643
1644        let fixed = rule.fix(&ctx).unwrap();
1645
1646        // Should be compact (table would be way over 80 chars aligned)
1647        assert!(fixed.contains("| Column One A | Column Two B | Column Three | Column Four D | Column Five E | Column Six FG | Column Seven | Column Eight |"));
1648        assert!(fixed.contains("| --- | --- | --- | --- | --- | --- | --- | --- |"));
1649    }
1650
1651    #[test]
1652    fn test_md060_inherit_from_md013_line_length() {
1653        // max_width = 0 should inherit from MD013's line_length
1654        let config = MD060Config {
1655            enabled: true,
1656            style: "aligned".to_string(),
1657            max_width: LineLength::from_const(0), // Inherit
1658            column_align: ColumnAlign::Auto,
1659            column_align_header: None,
1660            column_align_body: None,
1661            loose_last_column: false,
1662            aligned_delimiter: false,
1663        };
1664
1665        // Test with different MD013 line_length values
1666        let rule_80 = MD060TableFormat::from_config_struct(config.clone(), md013_with_line_length(80), false);
1667        let rule_120 = MD060TableFormat::from_config_struct(config.clone(), md013_with_line_length(120), false);
1668
1669        // Medium-sized table
1670        let content = "| Column Header A | Column Header B | Column Header C |\n|---|---|---|\n| Some Data | More Data | Even More |";
1671        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1672
1673        // With 80 char limit, likely compacts
1674        let _fixed_80 = rule_80.fix(&ctx).unwrap();
1675
1676        // With 120 char limit, likely stays aligned
1677        let fixed_120 = rule_120.fix(&ctx).unwrap();
1678
1679        // Verify 120 is aligned (all lines same length)
1680        let lines_120: Vec<&str> = fixed_120.lines().collect();
1681        assert_eq!(lines_120[0].len(), lines_120[1].len());
1682        assert_eq!(lines_120[1].len(), lines_120[2].len());
1683    }
1684
1685    #[test]
1686    fn test_md060_edge_case_exactly_at_threshold() {
1687        // Create table that's exactly at the threshold
1688        // Formula: 1 + (num_columns * 3) + sum(column_widths) = max_width
1689        // For 2 columns with widths 5 and 5: 1 + 6 + 10 = 17
1690        let config = MD060Config {
1691            enabled: true,
1692            style: "aligned".to_string(),
1693            max_width: LineLength::from_const(17),
1694            column_align: ColumnAlign::Auto,
1695            column_align_header: None,
1696            column_align_body: None,
1697            loose_last_column: false,
1698            aligned_delimiter: false,
1699        };
1700        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1701
1702        let content = "| AAAAA | BBBBB |\n|---|---|\n| AAAAA | BBBBB |";
1703        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1704
1705        let fixed = rule.fix(&ctx).unwrap();
1706
1707        // At threshold (17 <= 17), should stay aligned
1708        let lines: Vec<&str> = fixed.lines().collect();
1709        assert_eq!(lines[0].len(), 17);
1710        assert_eq!(lines[0].len(), lines[1].len());
1711        assert_eq!(lines[1].len(), lines[2].len());
1712
1713        // Now test with threshold = 16 (just under)
1714        let config_under = MD060Config {
1715            enabled: true,
1716            style: "aligned".to_string(),
1717            max_width: LineLength::from_const(16),
1718            column_align: ColumnAlign::Auto,
1719            column_align_header: None,
1720            column_align_body: None,
1721            loose_last_column: false,
1722            aligned_delimiter: false,
1723        };
1724        let rule_under = MD060TableFormat::from_config_struct(config_under, md013_with_line_length(80), false);
1725
1726        let fixed_compact = rule_under.fix(&ctx).unwrap();
1727
1728        // Should compact (17 > 16)
1729        assert!(fixed_compact.contains("| AAAAA | BBBBB |"));
1730        assert!(fixed_compact.contains("| --- | --- |"));
1731    }
1732
1733    #[test]
1734    fn test_md060_auto_compact_warning_message() {
1735        // Verify that auto-compact generates an informative warning
1736        let config = MD060Config {
1737            enabled: true,
1738            style: "aligned".to_string(),
1739            max_width: LineLength::from_const(50),
1740            column_align: ColumnAlign::Auto,
1741            column_align_header: None,
1742            column_align_body: None,
1743            loose_last_column: false,
1744            aligned_delimiter: false,
1745        };
1746        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1747
1748        // Table that will be auto-compacted (exceeds 50 chars when aligned)
1749        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| Data | Data | Data |";
1750        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1751
1752        let warnings = rule.check(&ctx).unwrap();
1753
1754        // Should generate warnings with auto-compact message
1755        assert!(!warnings.is_empty(), "Should generate warnings");
1756
1757        let auto_compact_warnings: Vec<_> = warnings
1758            .iter()
1759            .filter(|w| w.message.contains("too wide for aligned formatting"))
1760            .collect();
1761
1762        assert!(!auto_compact_warnings.is_empty(), "Should have auto-compact warning");
1763
1764        // Verify the warning message includes the width and threshold
1765        let first_warning = auto_compact_warnings[0];
1766        assert!(first_warning.message.contains("85 chars > max-width: 50"));
1767        assert!(first_warning.message.contains("Table too wide for aligned formatting"));
1768    }
1769
1770    #[test]
1771    fn test_md060_issue_129_detect_style_from_all_rows() {
1772        // Issue #129: detect_table_style should check all rows, not just the first row
1773        // If header row has single-space padding but content rows have extra padding,
1774        // the table should be detected as "aligned" and preserved
1775        let rule = MD060TableFormat::new(true, "any".to_string());
1776
1777        // Table where header looks compact but content is aligned
1778        let content = "| a long heading | another long heading |\n\
1779                       | -------------- | -------------------- |\n\
1780                       | a              | 1                    |\n\
1781                       | b b            | 2                    |\n\
1782                       | c c c          | 3                    |";
1783        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1784
1785        let fixed = rule.fix(&ctx).unwrap();
1786
1787        // Should preserve the aligned formatting of content rows
1788        assert!(
1789            fixed.contains("| a              | 1                    |"),
1790            "Should preserve aligned padding in first content row"
1791        );
1792        assert!(
1793            fixed.contains("| b b            | 2                    |"),
1794            "Should preserve aligned padding in second content row"
1795        );
1796        assert!(
1797            fixed.contains("| c c c          | 3                    |"),
1798            "Should preserve aligned padding in third content row"
1799        );
1800
1801        // Entire table should remain unchanged because it's already properly aligned
1802        assert_eq!(fixed, content, "Table should be detected as aligned and preserved");
1803    }
1804
1805    #[test]
1806    fn test_md060_regular_alignment_warning_message() {
1807        // Verify that regular alignment (not auto-compact) generates normal warning
1808        let config = MD060Config {
1809            enabled: true,
1810            style: "aligned".to_string(),
1811            max_width: LineLength::from_const(100), // Large enough to not trigger auto-compact
1812            column_align: ColumnAlign::Auto,
1813            column_align_header: None,
1814            column_align_body: None,
1815            loose_last_column: false,
1816            aligned_delimiter: false,
1817        };
1818        let rule = MD060TableFormat::from_config_struct(config, md013_with_line_length(80), false);
1819
1820        // Small misaligned table
1821        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |";
1822        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1823
1824        let warnings = rule.check(&ctx).unwrap();
1825
1826        // Should generate warnings
1827        assert!(!warnings.is_empty(), "Should generate warnings");
1828
1829        // Verify it's the standard alignment message, not auto-compact
1830        assert!(warnings[0].message.contains("Table columns should be aligned"));
1831        assert!(!warnings[0].message.contains("too wide"));
1832        assert!(!warnings[0].message.contains("max-width"));
1833    }
1834
1835    // === Issue #219: Unlimited table width tests ===
1836
1837    #[test]
1838    fn test_md060_unlimited_when_md013_disabled() {
1839        // When MD013 is globally disabled, max_width should be unlimited
1840        let config = MD060Config {
1841            enabled: true,
1842            style: "aligned".to_string(),
1843            max_width: LineLength::from_const(0), // Inherit
1844            column_align: ColumnAlign::Auto,
1845            column_align_header: None,
1846            column_align_body: None,
1847            loose_last_column: false,
1848            aligned_delimiter: false,
1849        };
1850        let md013_config = MD013Config::default();
1851        let rule = MD060TableFormat::from_config_struct(config, md013_config, true /* disabled */);
1852
1853        // Very wide table that would normally exceed 80 chars
1854        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| data | data | data |";
1855        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1856        let fixed = rule.fix(&ctx).unwrap();
1857
1858        // Should be aligned (not compacted) since MD013 is disabled
1859        let lines: Vec<&str> = fixed.lines().collect();
1860        // In aligned mode, all lines have the same length
1861        assert_eq!(
1862            lines[0].len(),
1863            lines[1].len(),
1864            "Table should be aligned when MD013 is disabled"
1865        );
1866    }
1867
1868    #[test]
1869    fn test_md060_unlimited_when_md013_tables_false() {
1870        // When MD013.tables = false, max_width should be unlimited
1871        let config = MD060Config {
1872            enabled: true,
1873            style: "aligned".to_string(),
1874            max_width: LineLength::from_const(0),
1875            column_align: ColumnAlign::Auto,
1876            column_align_header: None,
1877            column_align_body: None,
1878            loose_last_column: false,
1879            aligned_delimiter: false,
1880        };
1881        let md013_config = MD013Config {
1882            tables: false, // User doesn't care about table line length
1883            line_length: LineLength::from_const(80),
1884            ..Default::default()
1885        };
1886        let rule = MD060TableFormat::from_config_struct(config, md013_config, false);
1887
1888        // Wide table that would exceed 80 chars
1889        let content = "| Very Long Header A | Very Long Header B | Very Long Header C |\n|---|---|---|\n| x | y | z |";
1890        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1891        let fixed = rule.fix(&ctx).unwrap();
1892
1893        // Should be aligned (no auto-compact since tables=false)
1894        let lines: Vec<&str> = fixed.lines().collect();
1895        assert_eq!(
1896            lines[0].len(),
1897            lines[1].len(),
1898            "Table should be aligned when MD013.tables=false"
1899        );
1900    }
1901
1902    #[test]
1903    fn test_md060_unlimited_when_md013_line_length_zero() {
1904        // When MD013.line_length = 0, max_width should be unlimited
1905        let config = MD060Config {
1906            enabled: true,
1907            style: "aligned".to_string(),
1908            max_width: LineLength::from_const(0),
1909            column_align: ColumnAlign::Auto,
1910            column_align_header: None,
1911            column_align_body: None,
1912            loose_last_column: false,
1913            aligned_delimiter: false,
1914        };
1915        let md013_config = MD013Config {
1916            tables: true,
1917            line_length: LineLength::from_const(0), // No limit
1918            ..Default::default()
1919        };
1920        let rule = MD060TableFormat::from_config_struct(config, md013_config, false);
1921
1922        // Wide table
1923        let content = "| Very Long Header | Another Long Header | Third Long Header |\n|---|---|---|\n| x | y | z |";
1924        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1925        let fixed = rule.fix(&ctx).unwrap();
1926
1927        // Should be aligned
1928        let lines: Vec<&str> = fixed.lines().collect();
1929        assert_eq!(
1930            lines[0].len(),
1931            lines[1].len(),
1932            "Table should be aligned when MD013.line_length=0"
1933        );
1934    }
1935
1936    #[test]
1937    fn test_md060_explicit_max_width_overrides_md013_settings() {
1938        // Explicit max_width should always take precedence
1939        let config = MD060Config {
1940            enabled: true,
1941            style: "aligned".to_string(),
1942            max_width: LineLength::from_const(50), // Explicit limit
1943            column_align: ColumnAlign::Auto,
1944            column_align_header: None,
1945            column_align_body: None,
1946            loose_last_column: false,
1947            aligned_delimiter: false,
1948        };
1949        let md013_config = MD013Config {
1950            tables: false,                          // This would make it unlimited...
1951            line_length: LineLength::from_const(0), // ...and this too
1952            ..Default::default()
1953        };
1954        let rule = MD060TableFormat::from_config_struct(config, md013_config, false);
1955
1956        // Wide table that exceeds explicit 50-char limit
1957        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| x | y | z |";
1958        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1959        let fixed = rule.fix(&ctx).unwrap();
1960
1961        // Should be compact (explicit max_width = 50 overrides MD013 settings)
1962        assert!(
1963            fixed.contains("| --- |"),
1964            "Should be compact format due to explicit max_width"
1965        );
1966    }
1967
1968    #[test]
1969    fn test_md060_inherits_md013_line_length_when_tables_enabled() {
1970        // When MD013.tables = true and MD013.line_length is set, inherit that limit
1971        let config = MD060Config {
1972            enabled: true,
1973            style: "aligned".to_string(),
1974            max_width: LineLength::from_const(0), // Inherit
1975            column_align: ColumnAlign::Auto,
1976            column_align_header: None,
1977            column_align_body: None,
1978            loose_last_column: false,
1979            aligned_delimiter: false,
1980        };
1981        let md013_config = MD013Config {
1982            tables: true,
1983            line_length: LineLength::from_const(50), // 50 char limit
1984            ..Default::default()
1985        };
1986        let rule = MD060TableFormat::from_config_struct(config, md013_config, false);
1987
1988        // Wide table that exceeds 50 chars
1989        let content = "| Very Long Column Header A | Very Long Column Header B | Very Long Column Header C |\n|---|---|---|\n| x | y | z |";
1990        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1991        let fixed = rule.fix(&ctx).unwrap();
1992
1993        // Should be compact (inherited 50-char limit from MD013)
1994        assert!(
1995            fixed.contains("| --- |"),
1996            "Should be compact format when inheriting MD013 limit"
1997        );
1998    }
1999
2000    // === Issue #311: aligned-no-space style tests ===
2001
2002    #[test]
2003    fn test_aligned_no_space_reformats_spaced_delimiter() {
2004        // Table with "aligned" style (spaces around dashes) should be reformatted
2005        // when target style is "aligned-no-space"
2006        let config = MD060Config {
2007            enabled: true,
2008            style: "aligned-no-space".to_string(),
2009            max_width: LineLength::from_const(0),
2010            column_align: ColumnAlign::Auto,
2011            column_align_header: None,
2012            column_align_body: None,
2013            loose_last_column: false,
2014            aligned_delimiter: false,
2015        };
2016        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2017
2018        // Input: aligned table with spaces around dashes
2019        let content = "| Header 1 | Header 2 |\n| -------- | -------- |\n| Cell 1   | Cell 2   |";
2020        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2021        let fixed = rule.fix(&ctx).unwrap();
2022
2023        // Should have no spaces around dashes in delimiter row
2024        // The dashes may be longer to match column width, but should have no spaces
2025        assert!(
2026            !fixed.contains("| ----"),
2027            "Delimiter should NOT have spaces after pipe. Got:\n{fixed}"
2028        );
2029        assert!(
2030            !fixed.contains("---- |"),
2031            "Delimiter should NOT have spaces before pipe. Got:\n{fixed}"
2032        );
2033        // Verify it has the compact delimiter format (dashes touching pipes)
2034        assert!(
2035            fixed.contains("|----"),
2036            "Delimiter should have dashes touching the leading pipe. Got:\n{fixed}"
2037        );
2038    }
2039
2040    #[test]
2041    fn test_aligned_reformats_compact_delimiter() {
2042        // Table with "aligned-no-space" style (no spaces around dashes) should be reformatted
2043        // when target style is "aligned"
2044        let config = MD060Config {
2045            enabled: true,
2046            style: "aligned".to_string(),
2047            max_width: LineLength::from_const(0),
2048            column_align: ColumnAlign::Auto,
2049            column_align_header: None,
2050            column_align_body: None,
2051            loose_last_column: false,
2052            aligned_delimiter: false,
2053        };
2054        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2055
2056        // Input: aligned-no-space table (no spaces around dashes)
2057        let content = "| Header 1 | Header 2 |\n|----------|----------|\n| Cell 1   | Cell 2   |";
2058        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2059        let fixed = rule.fix(&ctx).unwrap();
2060
2061        // Should have spaces around dashes in delimiter row
2062        assert!(
2063            fixed.contains("| -------- | -------- |") || fixed.contains("| ---------- | ---------- |"),
2064            "Delimiter should have spaces around dashes. Got:\n{fixed}"
2065        );
2066    }
2067
2068    #[test]
2069    fn test_aligned_no_space_preserves_matching_table() {
2070        // Table already in "aligned-no-space" style should be preserved
2071        let config = MD060Config {
2072            enabled: true,
2073            style: "aligned-no-space".to_string(),
2074            max_width: LineLength::from_const(0),
2075            column_align: ColumnAlign::Auto,
2076            column_align_header: None,
2077            column_align_body: None,
2078            loose_last_column: false,
2079            aligned_delimiter: false,
2080        };
2081        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2082
2083        // Input: already in aligned-no-space style
2084        let content = "| Header 1 | Header 2 |\n|----------|----------|\n| Cell 1   | Cell 2   |";
2085        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2086        let fixed = rule.fix(&ctx).unwrap();
2087
2088        // Should be preserved as-is
2089        assert_eq!(
2090            fixed, content,
2091            "Table already in aligned-no-space style should be preserved"
2092        );
2093    }
2094
2095    #[test]
2096    fn test_aligned_preserves_matching_table() {
2097        // Table already in "aligned" style should be preserved
2098        let config = MD060Config {
2099            enabled: true,
2100            style: "aligned".to_string(),
2101            max_width: LineLength::from_const(0),
2102            column_align: ColumnAlign::Auto,
2103            column_align_header: None,
2104            column_align_body: None,
2105            loose_last_column: false,
2106            aligned_delimiter: false,
2107        };
2108        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2109
2110        // Input: already in aligned style
2111        let content = "| Header 1 | Header 2 |\n| -------- | -------- |\n| Cell 1   | Cell 2   |";
2112        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2113        let fixed = rule.fix(&ctx).unwrap();
2114
2115        // Should be preserved as-is
2116        assert_eq!(fixed, content, "Table already in aligned style should be preserved");
2117    }
2118
2119    #[test]
2120    fn test_cjk_table_display_width_consistency() {
2121        // Test that is_table_already_aligned correctly uses display width, not byte length
2122        // CJK characters have display width of 2, but byte length of 3 in UTF-8
2123        //
2124        // This table is NOT aligned because line lengths differ
2125        // (CJK chars take 3 bytes in UTF-8 but only 2 columns in display)
2126        let table_lines = vec!["| 名前 | Age |", "|------|-----|", "| η”°δΈ­ | 25  |"];
2127
2128        // First check is raw line length equality (byte-based), which fails
2129        let is_aligned =
2130            MD060TableFormat::is_table_already_aligned(&table_lines, crate::config::MarkdownFlavor::Standard, false);
2131        assert!(
2132            !is_aligned,
2133            "Table with uneven raw line lengths should NOT be considered aligned"
2134        );
2135    }
2136
2137    #[test]
2138    fn test_cjk_width_calculation_in_aligned_check() {
2139        // calculate_cell_display_width trims content before calculating width
2140        // Verify CJK width is correctly calculated (2 per character)
2141        let cjk_width = MD060TableFormat::calculate_cell_display_width("名前");
2142        assert_eq!(cjk_width, 4, "Two CJK characters should have display width 4");
2143
2144        let ascii_width = MD060TableFormat::calculate_cell_display_width("Age");
2145        assert_eq!(ascii_width, 3, "Three ASCII characters should have display width 3");
2146
2147        // Test that spacing is trimmed before width calculation
2148        let padded_cjk = MD060TableFormat::calculate_cell_display_width(" 名前 ");
2149        assert_eq!(padded_cjk, 4, "Padded CJK should have same width after trim");
2150
2151        // Test mixed content
2152        let mixed = MD060TableFormat::calculate_cell_display_width(" ζ—₯本θͺžABC ");
2153        // 3 CJK chars (width 6) + 3 ASCII (width 3) = 9
2154        assert_eq!(mixed, 9, "Mixed CJK/ASCII content");
2155    }
2156
2157    // === Issue #317: column-align option tests ===
2158
2159    #[test]
2160    fn test_md060_column_align_left() {
2161        // Default/explicit left alignment
2162        let config = MD060Config {
2163            enabled: true,
2164            style: "aligned".to_string(),
2165            max_width: LineLength::from_const(0),
2166            column_align: ColumnAlign::Left,
2167            column_align_header: None,
2168            column_align_body: None,
2169            loose_last_column: false,
2170            aligned_delimiter: false,
2171        };
2172        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2173
2174        let content = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | Seattle |\n| Bob | 25 | Portland |";
2175        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2176
2177        let fixed = rule.fix(&ctx).unwrap();
2178        let lines: Vec<&str> = fixed.lines().collect();
2179
2180        // Left aligned: content on left, padding on right
2181        assert!(
2182            lines[2].contains("| Alice "),
2183            "Content should be left-aligned (Alice should have trailing padding)"
2184        );
2185        assert!(
2186            lines[3].contains("| Bob   "),
2187            "Content should be left-aligned (Bob should have trailing padding)"
2188        );
2189    }
2190
2191    #[test]
2192    fn test_md060_column_align_center() {
2193        // Center alignment forces all columns to center
2194        let config = MD060Config {
2195            enabled: true,
2196            style: "aligned".to_string(),
2197            max_width: LineLength::from_const(0),
2198            column_align: ColumnAlign::Center,
2199            column_align_header: None,
2200            column_align_body: None,
2201            loose_last_column: false,
2202            aligned_delimiter: false,
2203        };
2204        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2205
2206        let content = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | Seattle |\n| Bob | 25 | Portland |";
2207        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2208
2209        let fixed = rule.fix(&ctx).unwrap();
2210        let lines: Vec<&str> = fixed.lines().collect();
2211
2212        // Center aligned: padding split on both sides
2213        // "Bob" (3 chars) in "Name" column (5 chars) = 2 padding total, 1 left, 1 right
2214        assert!(
2215            lines[3].contains("|  Bob  |"),
2216            "Bob should be centered with padding on both sides. Got: {}",
2217            lines[3]
2218        );
2219    }
2220
2221    #[test]
2222    fn test_md060_column_align_right() {
2223        // Right alignment forces all columns to right-align
2224        let config = MD060Config {
2225            enabled: true,
2226            style: "aligned".to_string(),
2227            max_width: LineLength::from_const(0),
2228            column_align: ColumnAlign::Right,
2229            column_align_header: None,
2230            column_align_body: None,
2231            loose_last_column: false,
2232            aligned_delimiter: false,
2233        };
2234        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2235
2236        let content = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | Seattle |\n| Bob | 25 | Portland |";
2237        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2238
2239        let fixed = rule.fix(&ctx).unwrap();
2240        let lines: Vec<&str> = fixed.lines().collect();
2241
2242        // Right aligned: padding on left, content on right
2243        assert!(
2244            lines[3].contains("|   Bob |"),
2245            "Bob should be right-aligned with padding on left. Got: {}",
2246            lines[3]
2247        );
2248    }
2249
2250    #[test]
2251    fn test_md060_column_align_auto_respects_delimiter() {
2252        // Auto mode (default) should respect delimiter row alignment indicators
2253        let config = MD060Config {
2254            enabled: true,
2255            style: "aligned".to_string(),
2256            max_width: LineLength::from_const(0),
2257            column_align: ColumnAlign::Auto,
2258            column_align_header: None,
2259            column_align_body: None,
2260            loose_last_column: false,
2261            aligned_delimiter: false,
2262        };
2263        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2264
2265        // Left, center, right columns via delimiter indicators
2266        let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
2267        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2268
2269        let fixed = rule.fix(&ctx).unwrap();
2270
2271        // Verify alignment is applied per-column based on delimiter
2272        assert!(fixed.contains("| A "), "Left column should be left-aligned");
2273        // Center and right columns with longer content in header
2274        let lines: Vec<&str> = fixed.lines().collect();
2275        // The content row should have B centered and C right-aligned
2276        // B (1 char) in "Center" (6 chars) = 5 padding, ~2 left, ~3 right
2277        // C (1 char) in "Right" (5 chars) = 4 padding, all on left
2278        assert!(
2279            lines[2].contains(" C |"),
2280            "Right column should be right-aligned. Got: {}",
2281            lines[2]
2282        );
2283    }
2284
2285    #[test]
2286    fn test_md060_column_align_overrides_delimiter_indicators() {
2287        // column-align should override delimiter row indicators
2288        let config = MD060Config {
2289            enabled: true,
2290            style: "aligned".to_string(),
2291            max_width: LineLength::from_const(0),
2292            column_align: ColumnAlign::Right, // Override all to right
2293            column_align_header: None,
2294            column_align_body: None,
2295            loose_last_column: false,
2296            aligned_delimiter: false,
2297        };
2298        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2299
2300        // Delimiter says left, center, right - but we override all to right
2301        let content = "| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |";
2302        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2303
2304        let fixed = rule.fix(&ctx).unwrap();
2305        let lines: Vec<&str> = fixed.lines().collect();
2306
2307        // ALL columns should be right-aligned despite delimiter indicators
2308        // "A" in "Left" column (4 chars minimum due to header length) should be right-aligned
2309        assert!(
2310            lines[2].contains("    A |") || lines[2].contains("   A |"),
2311            "Even left-indicated column should be right-aligned. Got: {}",
2312            lines[2]
2313        );
2314    }
2315
2316    #[test]
2317    fn test_md060_column_align_with_aligned_no_space() {
2318        // column-align should work with aligned-no-space style
2319        let config = MD060Config {
2320            enabled: true,
2321            style: "aligned-no-space".to_string(),
2322            max_width: LineLength::from_const(0),
2323            column_align: ColumnAlign::Center,
2324            column_align_header: None,
2325            column_align_body: None,
2326            loose_last_column: false,
2327            aligned_delimiter: false,
2328        };
2329        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2330
2331        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |\n| Bob | 25 |";
2332        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2333
2334        let fixed = rule.fix(&ctx).unwrap();
2335        let lines: Vec<&str> = fixed.lines().collect();
2336
2337        // Delimiter row should have no spaces (aligned-no-space)
2338        assert!(
2339            lines[1].contains("|---"),
2340            "Delimiter should have no spaces in aligned-no-space style. Got: {}",
2341            lines[1]
2342        );
2343        // Content should still be centered
2344        assert!(
2345            lines[3].contains("|  Bob  |"),
2346            "Content should be centered. Got: {}",
2347            lines[3]
2348        );
2349    }
2350
2351    #[test]
2352    fn test_md060_column_align_config_parsing() {
2353        // Test that column-align config is correctly parsed
2354        let toml_str = r#"
2355enabled = true
2356style = "aligned"
2357column-align = "center"
2358"#;
2359        let config: MD060Config = toml::from_str(toml_str).expect("Should parse config");
2360        assert_eq!(config.column_align, ColumnAlign::Center);
2361
2362        let toml_str = r#"
2363enabled = true
2364style = "aligned"
2365column-align = "right"
2366"#;
2367        let config: MD060Config = toml::from_str(toml_str).expect("Should parse config");
2368        assert_eq!(config.column_align, ColumnAlign::Right);
2369
2370        let toml_str = r#"
2371enabled = true
2372style = "aligned"
2373column-align = "left"
2374"#;
2375        let config: MD060Config = toml::from_str(toml_str).expect("Should parse config");
2376        assert_eq!(config.column_align, ColumnAlign::Left);
2377
2378        let toml_str = r#"
2379enabled = true
2380style = "aligned"
2381column-align = "auto"
2382"#;
2383        let config: MD060Config = toml::from_str(toml_str).expect("Should parse config");
2384        assert_eq!(config.column_align, ColumnAlign::Auto);
2385    }
2386
2387    #[test]
2388    fn test_md060_column_align_default_is_auto() {
2389        // Without column-align specified, default should be Auto
2390        let toml_str = r#"
2391enabled = true
2392style = "aligned"
2393"#;
2394        let config: MD060Config = toml::from_str(toml_str).expect("Should parse config");
2395        assert_eq!(config.column_align, ColumnAlign::Auto);
2396    }
2397
2398    #[test]
2399    fn test_md060_column_align_reformats_already_aligned_table() {
2400        // A table that is already aligned (left) should be reformatted when column-align=right
2401        let config = MD060Config {
2402            enabled: true,
2403            style: "aligned".to_string(),
2404            max_width: LineLength::from_const(0),
2405            column_align: ColumnAlign::Right,
2406            column_align_header: None,
2407            column_align_body: None,
2408            loose_last_column: false,
2409            aligned_delimiter: false,
2410        };
2411        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2412
2413        // This table is already properly aligned with left alignment
2414        let content = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |\n| Bob   | 25  |";
2415        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2416
2417        let fixed = rule.fix(&ctx).unwrap();
2418        let lines: Vec<&str> = fixed.lines().collect();
2419
2420        // Should be reformatted with right alignment
2421        assert!(
2422            lines[2].contains("| Alice |") && lines[2].contains("|  30 |"),
2423            "Already aligned table should be reformatted with right alignment. Got: {}",
2424            lines[2]
2425        );
2426        assert!(
2427            lines[3].contains("|   Bob |") || lines[3].contains("|  Bob |"),
2428            "Bob should be right-aligned. Got: {}",
2429            lines[3]
2430        );
2431    }
2432
2433    #[test]
2434    fn test_md060_column_align_with_cjk_characters() {
2435        // CJK characters have double display width - centering should account for this
2436        let config = MD060Config {
2437            enabled: true,
2438            style: "aligned".to_string(),
2439            max_width: LineLength::from_const(0),
2440            column_align: ColumnAlign::Center,
2441            column_align_header: None,
2442            column_align_body: None,
2443            loose_last_column: false,
2444            aligned_delimiter: false,
2445        };
2446        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2447
2448        let content = "| Name | City |\n|---|---|\n| Alice | 東京 |\n| Bob | LA |";
2449        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2450
2451        let fixed = rule.fix(&ctx).unwrap();
2452
2453        // Both Alice and Bob should be centered, and 東京 should be properly aligned
2454        // considering its double-width display
2455        assert!(fixed.contains("Bob"), "Table should contain Bob");
2456        assert!(fixed.contains("東京"), "Table should contain 東京");
2457    }
2458
2459    #[test]
2460    fn test_md060_column_align_ignored_for_compact_style() {
2461        // column-align should have no effect on compact style (minimal padding)
2462        let config = MD060Config {
2463            enabled: true,
2464            style: "compact".to_string(),
2465            max_width: LineLength::from_const(0),
2466            column_align: ColumnAlign::Right, // This should be ignored
2467            column_align_header: None,
2468            column_align_body: None,
2469            loose_last_column: false,
2470            aligned_delimiter: false,
2471        };
2472        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2473
2474        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |\n| Bob | 25 |";
2475        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2476
2477        let fixed = rule.fix(&ctx).unwrap();
2478
2479        // Compact style: single space padding, no alignment
2480        assert!(
2481            fixed.contains("| Alice |"),
2482            "Compact style should have single space padding, not alignment. Got: {fixed}"
2483        );
2484    }
2485
2486    #[test]
2487    fn test_md060_column_align_ignored_for_tight_style() {
2488        // column-align should have no effect on tight style (no padding)
2489        let config = MD060Config {
2490            enabled: true,
2491            style: "tight".to_string(),
2492            max_width: LineLength::from_const(0),
2493            column_align: ColumnAlign::Center, // This should be ignored
2494            column_align_header: None,
2495            column_align_body: None,
2496            loose_last_column: false,
2497            aligned_delimiter: false,
2498        };
2499        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2500
2501        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |\n| Bob | 25 |";
2502        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2503
2504        let fixed = rule.fix(&ctx).unwrap();
2505
2506        // Tight style: no spaces at all
2507        assert!(
2508            fixed.contains("|Alice|"),
2509            "Tight style should have no spaces. Got: {fixed}"
2510        );
2511    }
2512
2513    #[test]
2514    fn test_md060_column_align_with_empty_cells() {
2515        // Empty cells should be handled correctly with centering
2516        let config = MD060Config {
2517            enabled: true,
2518            style: "aligned".to_string(),
2519            max_width: LineLength::from_const(0),
2520            column_align: ColumnAlign::Center,
2521            column_align_header: None,
2522            column_align_body: None,
2523            loose_last_column: false,
2524            aligned_delimiter: false,
2525        };
2526        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2527
2528        let content = "| Name | Age |\n|---|---|\n| Alice | 30 |\n|  | 25 |";
2529        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2530
2531        let fixed = rule.fix(&ctx).unwrap();
2532        let lines: Vec<&str> = fixed.lines().collect();
2533
2534        // Empty cell should have all padding (centered empty string)
2535        assert!(
2536            lines[3].contains("|       |") || lines[3].contains("|      |"),
2537            "Empty cell should be padded correctly. Got: {}",
2538            lines[3]
2539        );
2540    }
2541
2542    #[test]
2543    fn test_md060_column_align_auto_preserves_already_aligned() {
2544        // With column-align=auto (default), already aligned tables should be preserved
2545        let config = MD060Config {
2546            enabled: true,
2547            style: "aligned".to_string(),
2548            max_width: LineLength::from_const(0),
2549            column_align: ColumnAlign::Auto,
2550            column_align_header: None,
2551            column_align_body: None,
2552            loose_last_column: false,
2553            aligned_delimiter: false,
2554        };
2555        let rule = MD060TableFormat::from_config_struct(config, MD013Config::default(), false);
2556
2557        // This table is already properly aligned
2558        let content = "| Name  | Age |\n| ----- | --- |\n| Alice | 30  |\n| Bob   | 25  |";
2559        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2560
2561        let fixed = rule.fix(&ctx).unwrap();
2562
2563        // Should be preserved as-is
2564        assert_eq!(
2565            fixed, content,
2566            "Already aligned table should be preserved with column-align=auto"
2567        );
2568    }
2569
2570    #[test]
2571    fn test_cjk_table_display_aligned_not_flagged() {
2572        // Verify that alignment detection uses display width (.width()), not byte
2573        // length (.len()). CJK chars are 3 bytes but 2 display columns, so a
2574        // visually aligned table must not be flagged as misaligned.
2575        use crate::config::MarkdownFlavor;
2576
2577        // This table is display-aligned: "Hello " and "δ½ ε₯½  " are both 6 display columns wide
2578        let table_lines: Vec<&str> = vec![
2579            "| Header | Name |",
2580            "| ------ | ---- |",
2581            "| Hello  | Test |",
2582            "| δ½ ε₯½   | Test |",
2583        ];
2584
2585        let result = MD060TableFormat::is_table_already_aligned(&table_lines, MarkdownFlavor::Standard, false);
2586        assert!(
2587            result,
2588            "Table with CJK characters that is display-aligned should be recognized as aligned"
2589        );
2590    }
2591
2592    #[test]
2593    fn test_cjk_table_not_reformatted_when_aligned() {
2594        // End-to-end test: a display-aligned CJK table should not trigger MD060
2595        let rule = MD060TableFormat::new(true, "aligned".to_string());
2596        // Build a table that is already correctly aligned (display-width)
2597        let content = "| Header | Name |\n| ------ | ---- |\n| Hello  | Test |\n| δ½ ε₯½   | Test |\n";
2598        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2599
2600        // If the table is display-aligned, MD060 should preserve it as-is
2601        let fixed = rule.fix(&ctx).unwrap();
2602        assert_eq!(fixed, content, "Display-aligned CJK table should not be reformatted");
2603    }
2604
2605    // === Pandoc construct reachability tests ===
2606    //
2607    // These tests document that MD060 does not flag Pandoc-specific constructs
2608    // because `ctx.table_blocks` excludes them at the source:
2609    //
2610    // - Grid table delimiters use `+---+---+` (no `|`), so `is_delimiter_row`
2611    //   returns false and no `TableBlock` is created.
2612    // - Multi-line table separators have no `|`, same exclusion.
2613    // - Line blocks (`| First line`) end without `|`; `is_potential_table_row`
2614    //   requires `valid_parts >= 2` for non-outer-piped lines (only 1 found).
2615    // - Pipe-table captions (`: caption`) have no `|` β€” excluded.
2616    //
2617    // No production guard is needed. If `find_table_blocks` ever changes to
2618    // include these constructs, these tests will surface that.
2619
2620    #[test]
2621    fn md060_pandoc_grid_tables_not_flagged() {
2622        let rule = MD060TableFormat::new(true, "aligned".to_string());
2623        let content = "\
2624+---+---+
2625| a | b |
2626+===+===+
2627| 1 | 2 |
2628+---+---+
2629";
2630        // Grid table delimiters (`+===+===+`) contain no `|`, so `is_delimiter_row`
2631        // returns false and no TableBlock is created β€” MD060 has nothing to check.
2632        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
2633        let result = rule.check(&ctx).unwrap();
2634        assert!(
2635            result.is_empty(),
2636            "MD060 should not flag Pandoc grid tables (excluded by table_blocks): {result:?}"
2637        );
2638
2639        let ctx_std = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2640        let result_std = rule.check(&ctx_std).unwrap();
2641        assert!(
2642            result_std.is_empty(),
2643            "MD060 should not flag grid-table-like content under Standard: {result_std:?}"
2644        );
2645    }
2646
2647    #[test]
2648    fn md060_pandoc_multi_line_tables_not_flagged() {
2649        let rule = MD060TableFormat::new(true, "aligned".to_string());
2650        let content = "\
2651--------- -----------
2652Header 1   Header 2
2653--------- -----------
2654Cell 1     Cell 2
2655--------- -----------
2656";
2657        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
2658        let result = rule.check(&ctx).unwrap();
2659        assert!(
2660            result.is_empty(),
2661            "MD060 should not flag Pandoc multi-line tables: {result:?}"
2662        );
2663
2664        let ctx_std = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2665        let result_std = rule.check(&ctx_std).unwrap();
2666        assert!(
2667            result_std.is_empty(),
2668            "MD060 should not flag multi-line table content under Standard: {result_std:?}"
2669        );
2670    }
2671
2672    #[test]
2673    fn md060_pandoc_line_blocks_not_flagged() {
2674        let rule = MD060TableFormat::new(true, "aligned".to_string());
2675        // Pandoc line blocks start with `|` but do not end with `|`.
2676        let content = "| First line\n| Second line\n";
2677        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
2678        let result = rule.check(&ctx).unwrap();
2679        assert!(
2680            result.is_empty(),
2681            "MD060 should not treat Pandoc line blocks as tables: {result:?}"
2682        );
2683
2684        let ctx_std = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2685        let result_std = rule.check(&ctx_std).unwrap();
2686        assert!(
2687            result_std.is_empty(),
2688            "MD060 should not treat line-block-like content as tables under Standard: {result_std:?}"
2689        );
2690    }
2691
2692    #[test]
2693    fn md060_pandoc_pipe_table_captions_not_flagged() {
2694        let rule = MD060TableFormat::new(true, "aligned".to_string());
2695        // Pipe-table captions (`: caption`) have no `|` and are excluded from table_blocks.
2696        // Use a fully aligned table so that MD060 does not flag the pipe rows themselves.
2697        let content = "\
2698| H1 | H2 |
2699| -- | -- |
2700| a  | b  |
2701
2702: My table caption
2703";
2704        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
2705        let result = rule.check(&ctx).unwrap();
2706        assert!(
2707            result.is_empty(),
2708            "MD060 should not flag the pipe-table caption line: {result:?}"
2709        );
2710
2711        let ctx_std = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2712        let result_std = rule.check(&ctx_std).unwrap();
2713        assert!(
2714            result_std.is_empty(),
2715            "MD060 already-aligned table with caption should have no warnings under Standard: {result_std:?}"
2716        );
2717    }
2718
2719    #[test]
2720    fn test_fix_preserves_trailing_blank_lines_and_is_idempotent() {
2721        // Regression: the fix reconstructed content via raw_lines().join("\n"),
2722        // which dropped trailing blank lines one per pass (non-idempotent) and
2723        // altered documents with no tables at all.
2724        let rule = MD060TableFormat::new(true, "aligned".to_string());
2725
2726        // No table: content must be returned byte-for-byte unchanged.
2727        for input in ["# \n\n\n\n", "text\n\n\n", "no trailing newline", "only blanks\n\n"] {
2728            let ctx = LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
2729            assert_eq!(
2730                rule.fix(&ctx).unwrap(),
2731                input,
2732                "MD060 must not alter table-free content: {input:?}"
2733            );
2734        }
2735
2736        // Table followed by trailing blank lines: the table is formatted but the
2737        // trailing blanks survive, and a second pass is a no-op.
2738        let with_table = "| a | b |\n|---|---|\n| 1 | 2 |\n\n\n";
2739        let ctx = LintContext::new(with_table, crate::config::MarkdownFlavor::Standard, None);
2740        let once = rule.fix(&ctx).unwrap();
2741        assert!(
2742            once.ends_with("\n\n\n"),
2743            "trailing blank lines must be preserved, got: {once:?}"
2744        );
2745        let ctx2 = LintContext::new(&once, crate::config::MarkdownFlavor::Standard, None);
2746        let twice = rule.fix(&ctx2).unwrap();
2747        assert_eq!(once, twice, "MD060 fix must be idempotent with trailing blank lines");
2748    }
2749}