Skip to main content

rumdl_lib/rules/
md055_table_pipe_style.rs

1use crate::rule::{LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::utils::range_utils::calculate_line_range;
3use crate::utils::table_utils::{TableBlock, TableUtils};
4
5mod md055_config;
6use md055_config::MD055Config;
7
8/// Rule MD055: Table pipe style
9///
10/// See [docs/md055.md](../../docs/md055.md) for full documentation, configuration, and examples.
11///
12/// This rule enforces consistent use of leading and trailing pipe characters in Markdown tables,
13/// which improves readability and ensures uniform document styling.
14///
15/// ## Purpose
16///
17/// - **Consistency**: Ensures uniform table formatting throughout documents
18/// - **Readability**: Well-formatted tables are easier to read and understand
19/// - **Maintainability**: Consistent table syntax makes documents easier to maintain
20/// - **Compatibility**: Some Markdown processors handle different table styles differently
21///
22/// ## Configuration Options
23///
24/// The rule supports the following configuration options:
25///
26/// ```yaml
27/// MD055:
28///   style: "consistent"  # Can be "consistent", "leading_and_trailing", or "no_leading_or_trailing"
29/// ```
30///
31/// ### Style Options
32///
33/// - **consistent**: All tables must use the same style (default)
34/// - **leading_and_trailing**: All tables must have both leading and trailing pipes
35/// - **no_leading_or_trailing**: Tables must not have leading or trailing pipes
36///
37/// ## Examples
38///
39/// ### Leading and Trailing Pipes
40///
41/// ```markdown
42/// | Header 1 | Header 2 | Header 3 |
43/// |----------|----------|----------|
44/// | Cell 1   | Cell 2   | Cell 3   |
45/// | Cell 4   | Cell 5   | Cell 6   |
46/// ```
47///
48/// ### No Leading or Trailing Pipes
49///
50/// ```markdown
51/// Header 1 | Header 2 | Header 3
52/// ---------|----------|---------
53/// Cell 1   | Cell 2   | Cell 3
54/// Cell 4   | Cell 5   | Cell 6
55/// ```
56///
57/// ## Behavior Details
58///
59/// - The rule analyzes each table in the document to determine its pipe style
60/// - With "consistent" style, the first table's style is used as the standard for all others
61/// - The rule handles both the header row, separator row, and content rows
62/// - Tables inside code blocks are ignored
63///
64/// ## Fix Behavior
65///
66/// When applying automatic fixes, this rule:
67/// - Adds or removes leading and trailing pipes as needed
68/// - Preserves the content and alignment of table cells
69/// - Maintains proper spacing around pipe characters
70/// - Updates both header and content rows to match the required style
71///
72/// ## Performance Considerations
73///
74/// The rule includes performance optimizations:
75/// - Efficient table detection with quick checks before detailed analysis
76/// - Smart line-by-line processing to avoid redundant operations
77/// - Optimized string manipulation for pipe character handling
78///
79/// Enforces consistent use of leading and trailing pipe characters in tables
80#[derive(Debug, Default, Clone)]
81pub struct MD055TablePipeStyle {
82    config: MD055Config,
83}
84
85impl MD055TablePipeStyle {
86    pub fn new(style: String) -> Self {
87        Self {
88            config: MD055Config { style },
89        }
90    }
91
92    pub fn from_config_struct(config: MD055Config) -> Self {
93        Self { config }
94    }
95
96    /// Determine the most prevalent table style in a table block
97    fn determine_table_style(&self, table_block: &TableBlock, lines: &[&str]) -> Option<&'static str> {
98        let mut leading_and_trailing_count = 0;
99        let mut no_leading_or_trailing_count = 0;
100        let mut leading_only_count = 0;
101        let mut trailing_only_count = 0;
102
103        // Count style of header row (table line index 0)
104        let header_content = TableUtils::extract_table_row_content(lines[table_block.header_line], table_block, 0);
105        if let Some(style) = TableUtils::determine_pipe_style(header_content) {
106            match style {
107                "leading_and_trailing" => leading_and_trailing_count += 1,
108                "no_leading_or_trailing" => no_leading_or_trailing_count += 1,
109                "leading_only" => leading_only_count += 1,
110                "trailing_only" => trailing_only_count += 1,
111                _ => {}
112            }
113        }
114
115        // Count style of content rows (table line indices 2, 3, 4, ...)
116        for (i, &line_idx) in table_block.content_lines.iter().enumerate() {
117            let content = TableUtils::extract_table_row_content(lines[line_idx], table_block, 2 + i);
118            if let Some(style) = TableUtils::determine_pipe_style(content) {
119                match style {
120                    "leading_and_trailing" => leading_and_trailing_count += 1,
121                    "no_leading_or_trailing" => no_leading_or_trailing_count += 1,
122                    "leading_only" => leading_only_count += 1,
123                    "trailing_only" => trailing_only_count += 1,
124                    _ => {}
125                }
126            }
127        }
128
129        // Determine most prevalent style
130        // In case of tie, prefer leading_and_trailing (most common, widely supported)
131        let max_count = leading_and_trailing_count
132            .max(no_leading_or_trailing_count)
133            .max(leading_only_count)
134            .max(trailing_only_count);
135
136        if max_count > 0 {
137            if leading_and_trailing_count == max_count {
138                Some("leading_and_trailing")
139            } else if no_leading_or_trailing_count == max_count {
140                Some("no_leading_or_trailing")
141            } else if leading_only_count == max_count {
142                Some("leading_only")
143            } else if trailing_only_count == max_count {
144                Some("trailing_only")
145            } else {
146                None
147            }
148        } else {
149            None
150        }
151    }
152
153    /// Simple table row fix for tests - creates a dummy TableBlock without list context
154    #[cfg(test)]
155    fn fix_table_row(&self, line: &str, target_style: &str) -> String {
156        let dummy_block = TableBlock {
157            start_line: 0,
158            end_line: 0,
159            header_line: 0,
160            delimiter_line: 0,
161            content_lines: vec![],
162            list_context: None,
163        };
164        self.fix_table_row_with_context(line, target_style, &dummy_block, 0)
165    }
166
167    /// Fix a table row to match the target style, with full context for list tables
168    ///
169    /// This handles tables inside list items by stripping the list prefix,
170    /// fixing the table content, then restoring the appropriate prefix.
171    fn fix_table_row_with_context(
172        &self,
173        line: &str,
174        target_style: &str,
175        table_block: &TableBlock,
176        table_line_index: usize,
177    ) -> String {
178        // Extract blockquote prefix first
179        let (bq_prefix, after_bq) = TableUtils::extract_blockquote_prefix(line);
180
181        // Handle list context if present
182        if let Some(ref list_ctx) = table_block.list_context {
183            if table_line_index == 0 {
184                // Header line: strip list prefix (handles both markers and indentation)
185                let stripped = after_bq
186                    .strip_prefix(&list_ctx.list_prefix)
187                    .unwrap_or_else(|| TableUtils::extract_list_prefix(after_bq).1);
188                let fixed_content = self.fix_table_content(stripped.trim(), target_style);
189
190                // Restore prefixes: blockquote + list prefix + fixed content
191                let lp = &list_ctx.list_prefix;
192                if bq_prefix.is_empty() && lp.is_empty() {
193                    fixed_content
194                } else {
195                    format!("{bq_prefix}{lp}{fixed_content}")
196                }
197            } else {
198                // Continuation lines: strip indentation, then restore it
199                let content_indent = list_ctx.content_indent;
200                let stripped = TableUtils::extract_table_row_content(line, table_block, table_line_index);
201                let fixed_content = self.fix_table_content(stripped.trim(), target_style);
202
203                // Restore prefixes: blockquote + indentation + fixed content
204                let indent = " ".repeat(content_indent);
205                format!("{bq_prefix}{indent}{fixed_content}")
206            }
207        } else {
208            // No list context, just handle blockquote prefix
209            let fixed_content = self.fix_table_content(after_bq.trim(), target_style);
210            if bq_prefix.is_empty() {
211                fixed_content
212            } else {
213                format!("{bq_prefix}{fixed_content}")
214            }
215        }
216    }
217
218    /// Fix the table content (without any prefix handling)
219    fn fix_table_content(&self, trimmed: &str, target_style: &str) -> String {
220        if !trimmed.contains('|') {
221            return trimmed.to_string();
222        }
223
224        let has_leading = trimmed.starts_with('|');
225        let has_trailing = trimmed.ends_with('|');
226
227        match target_style {
228            "leading_and_trailing" => {
229                let mut result = trimmed.to_string();
230
231                // Add leading pipe if missing
232                if !has_leading {
233                    result = format!("| {result}");
234                }
235
236                // Add trailing pipe if missing
237                if !has_trailing {
238                    result = format!("{result} |");
239                }
240
241                result
242            }
243            "no_leading_or_trailing" => {
244                let mut result = trimmed;
245
246                // Remove leading pipe if present
247                if has_leading {
248                    result = result.strip_prefix('|').unwrap_or(result);
249                    result = result.trim_start();
250                }
251
252                // Remove trailing pipe if present
253                if has_trailing {
254                    result = result.strip_suffix('|').unwrap_or(result);
255                    result = result.trim_end();
256                }
257
258                result.to_string()
259            }
260            "leading_only" => {
261                let mut result = trimmed.to_string();
262
263                // Add leading pipe if missing
264                if !has_leading {
265                    result = format!("| {result}");
266                }
267
268                // Remove trailing pipe if present
269                if has_trailing {
270                    result = result.strip_suffix('|').unwrap_or(&result).trim_end().to_string();
271                }
272
273                result
274            }
275            "trailing_only" => {
276                let mut result = trimmed;
277
278                // Remove leading pipe if present
279                if has_leading {
280                    result = result.strip_prefix('|').unwrap_or(result).trim_start();
281                }
282
283                let mut result = result.to_string();
284
285                // Add trailing pipe if missing
286                if !has_trailing {
287                    result = format!("{result} |");
288                }
289
290                result
291            }
292            _ => trimmed.to_string(),
293        }
294    }
295}
296
297impl Rule for MD055TablePipeStyle {
298    fn name(&self) -> &'static str {
299        "MD055"
300    }
301
302    fn description(&self) -> &'static str {
303        "Table pipe style should be consistent"
304    }
305
306    fn category(&self) -> RuleCategory {
307        RuleCategory::Table
308    }
309
310    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
311        // Skip if no tables present (uses cached pipe count)
312        !ctx.likely_has_tables()
313    }
314
315    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
316        let line_index = &ctx.line_index;
317        let mut warnings = Vec::new();
318
319        // Early return handled by should_skip()
320
321        let lines = ctx.raw_lines();
322
323        // Get the configured style explicitly and validate it
324        let configured_style = match self.config.style.as_str() {
325            "leading_and_trailing" | "no_leading_or_trailing" | "leading_only" | "trailing_only" | "consistent" => {
326                self.config.style.as_str()
327            }
328            _ => {
329                // Invalid style provided, default to "leading_and_trailing"
330                "leading_and_trailing"
331            }
332        };
333
334        // Use pre-computed table blocks from context
335        let table_blocks = &ctx.table_blocks;
336
337        // Process each table block
338        for table_block in table_blocks {
339            // First pass: determine the table's style for "consistent" mode
340            // Count all rows to determine most prevalent style (prevalence-based approach)
341            let table_style = if configured_style == "consistent" {
342                self.determine_table_style(table_block, lines)
343            } else {
344                None
345            };
346
347            // Determine target style for this table
348            let target_style = if configured_style == "consistent" {
349                table_style.unwrap_or("leading_and_trailing")
350            } else {
351                configured_style
352            };
353
354            // Collect all table lines for processing
355            let all_line_indices: Vec<usize> = std::iter::once(table_block.header_line)
356                .chain(std::iter::once(table_block.delimiter_line))
357                .chain(table_block.content_lines.iter().copied())
358                .collect();
359
360            // Check each row and emit a per-row fix. Per-row fixes ensure that
361            // inline-disabling one row does not cause the fix on another row to
362            // overwrite the disabled row's content.
363            for (table_line_idx, &line_idx) in all_line_indices.iter().enumerate() {
364                let line = lines[line_idx];
365                // Extract content to properly check pipe style (handles list/blockquote prefixes)
366                let content = TableUtils::extract_table_row_content(line, table_block, table_line_idx);
367                if let Some(current_style) = TableUtils::determine_pipe_style(content) {
368                    // Only flag lines with actual style mismatches
369                    let needs_fixing = current_style != target_style;
370
371                    if needs_fixing {
372                        let (start_line, start_col, end_line, end_col) = calculate_line_range(line_idx + 1, line);
373
374                        let message = format!(
375                            "Table pipe style should be {}",
376                            match target_style {
377                                "leading_and_trailing" => "leading and trailing",
378                                "no_leading_or_trailing" => "no leading or trailing",
379                                "leading_only" => "leading only",
380                                "trailing_only" => "trailing only",
381                                _ => target_style,
382                            }
383                        );
384
385                        // Build a per-row fix so inline-disabled rows are not
386                        // overwritten by fixes on other rows in the same table.
387                        let fixed_line =
388                            self.fix_table_row_with_context(line, target_style, table_block, table_line_idx);
389                        let row_range =
390                            line_index.line_col_to_byte_range_with_length(line_idx + 1, 1, line.chars().count());
391
392                        warnings.push(LintWarning {
393                            rule_name: Some(self.name().to_string()),
394                            severity: Severity::Warning,
395                            message,
396                            line: start_line,
397                            column: start_col,
398                            end_line,
399                            end_column: end_col,
400                            fix: Some(crate::rule::Fix::new(row_range, fixed_line)),
401                        });
402                    }
403                }
404            }
405        }
406
407        Ok(warnings)
408    }
409
410    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
411        if self.should_skip(ctx) {
412            return Ok(ctx.content.to_string());
413        }
414        let warnings = self.check(ctx)?;
415        if warnings.is_empty() {
416            return Ok(ctx.content.to_string());
417        }
418        let warnings =
419            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
420        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings).map_err(LintError::InvalidInput)
421    }
422
423    fn as_any(&self) -> &dyn std::any::Any {
424        self
425    }
426
427    crate::impl_rule_config_methods!(MD055Config);
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    // === Issue #611: kebab-case config values ignored, fallback to leading-and-trailing ===
435    //
436    // All style names must work identically whether the user writes kebab-case
437    // (no-leading-or-trailing) or snake_case (no_leading_or_trailing) in config.
438
439    fn rule_from_toml_style(style: &str) -> MD055TablePipeStyle {
440        let config: md055_config::MD055Config =
441            toml::from_str(&format!("style = \"{style}\"")).expect("valid style value");
442        MD055TablePipeStyle::from_config_struct(config)
443    }
444
445    #[test]
446    fn test_no_leading_or_trailing_kebab_accepts_conforming_table() {
447        let rule = rule_from_toml_style("no-leading-or-trailing");
448        let content = "A | B\n--- | ---\n1 | 2";
449        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
450        let warnings = rule.check(&ctx).unwrap();
451        assert!(
452            warnings.is_empty(),
453            "no-leading-or-trailing should accept a table with no pipes: {warnings:?}"
454        );
455    }
456
457    #[test]
458    fn test_no_leading_or_trailing_kebab_rejects_nonconforming_table() {
459        let rule = rule_from_toml_style("no-leading-or-trailing");
460        let content = "| A | B |\n|---|---|\n| 1 | 2 |";
461        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
462        let warnings = rule.check(&ctx).unwrap();
463        assert_eq!(
464            warnings.len(),
465            3,
466            "no-leading-or-trailing should flag all 3 rows with pipes"
467        );
468        assert!(warnings.iter().all(|w| w.message.contains("no leading or trailing")));
469    }
470
471    #[test]
472    fn test_leading_only_kebab_accepts_conforming_table() {
473        let rule = rule_from_toml_style("leading-only");
474        let content = "| A | B\n|---|---\n| 1 | 2";
475        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
476        let warnings = rule.check(&ctx).unwrap();
477        assert!(
478            warnings.is_empty(),
479            "leading-only should accept a leading-only table: {warnings:?}"
480        );
481    }
482
483    #[test]
484    fn test_trailing_only_kebab_accepts_conforming_table() {
485        let rule = rule_from_toml_style("trailing-only");
486        let content = "A | B |\n---|---|\n1 | 2 |";
487        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
488        let warnings = rule.check(&ctx).unwrap();
489        assert!(
490            warnings.is_empty(),
491            "trailing-only should accept a trailing-only table: {warnings:?}"
492        );
493    }
494
495    #[test]
496    fn test_trailing_only_kebab_rejects_nonconforming_table() {
497        let rule = rule_from_toml_style("trailing-only");
498        // leading-and-trailing table must be flagged — proves the table is actually detected
499        let content = "| A | B |\n|---|---|\n| 1 | 2 |";
500        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
501        let warnings = rule.check(&ctx).unwrap();
502        assert_eq!(
503            warnings.len(),
504            3,
505            "trailing-only should flag all 3 rows that have leading pipes"
506        );
507        assert!(warnings.iter().all(|w| w.message.contains("trailing only")));
508    }
509
510    #[test]
511    fn test_leading_only_kebab_rejects_nonconforming_table() {
512        let rule = rule_from_toml_style("leading-only");
513        // trailing-only table must be flagged — proves the table is actually detected
514        let content = "A | B |\n---|---|\n1 | 2 |";
515        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
516        let warnings = rule.check(&ctx).unwrap();
517        assert_eq!(
518            warnings.len(),
519            3,
520            "leading-only should flag all 3 rows that have trailing pipes"
521        );
522        assert!(warnings.iter().all(|w| w.message.contains("leading only")));
523    }
524
525    #[test]
526    fn test_leading_and_trailing_kebab_accepts_conforming_table() {
527        let rule = rule_from_toml_style("leading-and-trailing");
528        let content = "| A | B |\n|---|---|\n| 1 | 2 |";
529        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
530        let warnings = rule.check(&ctx).unwrap();
531        assert!(
532            warnings.is_empty(),
533            "leading-and-trailing should accept a fully-piped table: {warnings:?}"
534        );
535    }
536
537    #[test]
538    fn test_kebab_and_snake_case_styles_are_equivalent() {
539        // For every style, kebab and snake_case forms must produce identical warnings —
540        // same count, same messages, same line numbers.
541        let pairs = [
542            ("no-leading-or-trailing", "no_leading_or_trailing"),
543            ("leading-only", "leading_only"),
544            ("trailing-only", "trailing_only"),
545            ("leading-and-trailing", "leading_and_trailing"),
546        ];
547        // Mixed table so every style produces at least one warning, exercising the message path.
548        let content = "| A | B |\n|---|---|\n| 1 | 2 |";
549        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
550
551        for (kebab, snake) in pairs {
552            let kebab_rule = rule_from_toml_style(kebab);
553            let snake_rule = rule_from_toml_style(snake);
554            let kebab_warnings = kebab_rule.check(&ctx).unwrap();
555            let snake_warnings = snake_rule.check(&ctx).unwrap();
556
557            assert_eq!(
558                kebab_warnings.len(),
559                snake_warnings.len(),
560                "'{kebab}' and '{snake}' must produce the same number of warnings"
561            );
562            for (i, (kw, sw)) in kebab_warnings.iter().zip(snake_warnings.iter()).enumerate() {
563                assert_eq!(
564                    kw.message, sw.message,
565                    "warning[{i}] message differs between '{kebab}' and '{snake}'"
566                );
567                assert_eq!(
568                    kw.line, sw.line,
569                    "warning[{i}] line differs between '{kebab}' and '{snake}'"
570                );
571            }
572        }
573    }
574
575    fn assert_fix_roundtrip_from_toml(style: &str, content: &str) {
576        let rule = rule_from_toml_style(style);
577        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
578        let fixed = rule.fix(&ctx).unwrap();
579        let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
580        let remaining = rule.check(&ctx2).unwrap();
581        assert!(
582            remaining.is_empty(),
583            "style '{style}': after fix(), check() should find 0 violations.\n\
584             Original: {content:?}\n\
585             Fixed:    {fixed:?}\n\
586             Remaining: {remaining:?}"
587        );
588    }
589
590    #[test]
591    fn test_roundtrip_kebab_no_leading_or_trailing() {
592        assert_fix_roundtrip_from_toml("no-leading-or-trailing", "| H1 | H2 |\n|---|---|\n| a | b |");
593    }
594
595    #[test]
596    fn test_roundtrip_kebab_leading_and_trailing() {
597        assert_fix_roundtrip_from_toml("leading-and-trailing", "H1 | H2\n---|---\na | b");
598    }
599
600    #[test]
601    fn test_roundtrip_kebab_leading_only() {
602        assert_fix_roundtrip_from_toml("leading-only", "| H1 | H2 |\n|---|---|\n| a | b |");
603    }
604
605    #[test]
606    fn test_roundtrip_kebab_trailing_only() {
607        assert_fix_roundtrip_from_toml("trailing-only", "| H1 | H2 |\n|---|---|\n| a | b |");
608    }
609
610    #[test]
611    fn test_md055_delimiter_row_handling() {
612        // Test with no_leading_or_trailing style
613        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
614
615        let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1   | Data 2   | Data 3   |";
616        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
617        let result = rule.fix(&ctx).unwrap();
618
619        // With the fixed implementation, the delimiter row should have pipes removed
620        // Spacing is preserved from original input
621        let expected = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1   | Data 2   | Data 3";
622
623        assert_eq!(result, expected);
624
625        // Test that the check method actually reports the delimiter row as an issue
626        let warnings = rule.check(&ctx).unwrap();
627        let delimiter_warning = &warnings[1]; // Second warning should be for delimiter row
628        assert_eq!(delimiter_warning.line, 2);
629        assert_eq!(
630            delimiter_warning.message,
631            "Table pipe style should be no leading or trailing"
632        );
633
634        // Test with leading_and_trailing style
635        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
636
637        let content = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1   | Data 2   | Data 3";
638        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
639        let result = rule.fix(&ctx).unwrap();
640
641        // The delimiter row should have pipes added
642        // Spacing is preserved from original input
643        let expected = "| Header 1 | Header 2 | Header 3 |\n| ----------|----------|---------- |\n| Data 1   | Data 2   | Data 3 |";
644
645        assert_eq!(result, expected);
646    }
647
648    #[test]
649    fn test_md055_check_finds_delimiter_row_issues() {
650        // Test that check() correctly identifies delimiter rows that don't match style
651        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
652
653        let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1   | Data 2   | Data 3   |";
654        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
655        let warnings = rule.check(&ctx).unwrap();
656
657        // Should have 3 warnings - header row, delimiter row, and data row
658        assert_eq!(warnings.len(), 3);
659
660        // Specifically verify the delimiter row warning (line 2)
661        let delimiter_warning = &warnings[1];
662        assert_eq!(delimiter_warning.line, 2);
663        assert_eq!(
664            delimiter_warning.message,
665            "Table pipe style should be no leading or trailing"
666        );
667    }
668
669    #[test]
670    fn test_md055_real_world_example() {
671        // Test with a real-world example having content before and after the table
672        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
673
674        let content = "# Table Example\n\nHere's a table with leading and trailing pipes:\n\n| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1   | Data 2   | Data 3   |\n| Data 4   | Data 5   | Data 6   |\n\nMore content after the table.";
675        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
676        let result = rule.fix(&ctx).unwrap();
677
678        // The table should be fixed, with pipes removed
679        // Spacing is preserved from original input
680        let expected = "# Table Example\n\nHere's a table with leading and trailing pipes:\n\nHeader 1 | Header 2 | Header 3\n----------|----------|----------\nData 1   | Data 2   | Data 3\nData 4   | Data 5   | Data 6\n\nMore content after the table.";
681
682        assert_eq!(result, expected);
683
684        // Ensure we get warnings for all table rows
685        let warnings = rule.check(&ctx).unwrap();
686        assert_eq!(warnings.len(), 4); // All four table rows should have warnings
687
688        // The line numbers should match the correct positions in the original content
689        assert_eq!(warnings[0].line, 5); // Header row
690        assert_eq!(warnings[1].line, 6); // Delimiter row
691        assert_eq!(warnings[2].line, 7); // Data row 1
692        assert_eq!(warnings[3].line, 8); // Data row 2
693    }
694
695    #[test]
696    fn test_md055_invalid_style() {
697        // Test with an invalid style setting
698        let rule = MD055TablePipeStyle::new("leading_or_trailing".to_string()); // Invalid style
699
700        let content = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1   | Data 2   | Data 3   |";
701        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
702        let result = rule.fix(&ctx).unwrap();
703
704        // Should default to "leading_and_trailing"
705        // Already has leading and trailing pipes, so no changes needed - spacing is preserved
706        let expected = "| Header 1 | Header 2 | Header 3 |\n|----------|----------|----------|\n| Data 1   | Data 2   | Data 3   |";
707
708        assert_eq!(result, expected);
709
710        // Now check a content that needs actual modification
711        let content = "Header 1 | Header 2 | Header 3\n----------|----------|----------\nData 1   | Data 2   | Data 3";
712        let ctx2 = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
713        let result = rule.fix(&ctx2).unwrap();
714
715        // Should add pipes to match the default "leading_and_trailing" style
716        // Spacing is preserved from original input
717        let expected = "| Header 1 | Header 2 | Header 3 |\n| ----------|----------|---------- |\n| Data 1   | Data 2   | Data 3 |";
718        assert_eq!(result, expected);
719
720        // Check that warning messages also work with the fallback style
721        let warnings = rule.check(&ctx2).unwrap();
722
723        // Since content doesn't have leading/trailing pipes but defaults to "leading_and_trailing",
724        // there should be warnings for all rows
725        assert_eq!(warnings.len(), 3);
726    }
727
728    #[test]
729    fn test_underflow_protection() {
730        // Test case to ensure no underflow when parts is empty
731        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
732
733        // Test with empty string (edge case)
734        let result = rule.fix_table_row("", "leading_and_trailing");
735        assert_eq!(result, "");
736
737        // Test with string that doesn't contain pipes
738        let result = rule.fix_table_row("no pipes here", "leading_and_trailing");
739        assert_eq!(result, "no pipes here");
740
741        // Test with minimal pipe content
742        let result = rule.fix_table_row("|", "leading_and_trailing");
743        // Should not panic and should handle gracefully
744        assert!(!result.is_empty());
745    }
746
747    // === Issue #305: Blockquote table tests ===
748
749    #[test]
750    fn test_fix_table_row_in_blockquote() {
751        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
752
753        // Blockquote table without leading pipe
754        let result = rule.fix_table_row("> H1 | H2", "leading_and_trailing");
755        assert_eq!(result, "> | H1 | H2 |");
756
757        // Blockquote table that already has pipes
758        let result = rule.fix_table_row("> | H1 | H2 |", "leading_and_trailing");
759        assert_eq!(result, "> | H1 | H2 |");
760
761        // Removing pipes from blockquote table
762        let result = rule.fix_table_row("> | H1 | H2 |", "no_leading_or_trailing");
763        assert_eq!(result, "> H1 | H2");
764    }
765
766    #[test]
767    fn test_fix_table_row_in_nested_blockquote() {
768        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
769
770        // Double-nested blockquote
771        let result = rule.fix_table_row(">> H1 | H2", "leading_and_trailing");
772        assert_eq!(result, ">> | H1 | H2 |");
773
774        // Triple-nested blockquote
775        let result = rule.fix_table_row(">>> H1 | H2", "leading_and_trailing");
776        assert_eq!(result, ">>> | H1 | H2 |");
777    }
778
779    #[test]
780    fn test_blockquote_table_full_document() {
781        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
782
783        // Full table in blockquote (2 columns, matching delimiter)
784        let content = "> H1 | H2\n> ----|----\n> a  | b";
785        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
786        let result = rule.fix(&ctx).unwrap();
787
788        // Each line should have the blockquote prefix preserved and pipes added
789        // The leading_and_trailing style adds "| " after blockquote prefix
790        assert!(
791            result.starts_with("> |"),
792            "Header should start with blockquote + pipe. Got:\n{result}"
793        );
794        // Delimiter row gets leading pipe added, so check for "> | ---" pattern
795        assert!(
796            result.contains("> | ----"),
797            "Delimiter should have blockquote prefix + leading pipe. Got:\n{result}"
798        );
799    }
800
801    #[test]
802    fn test_blockquote_table_no_leading_trailing() {
803        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
804
805        // Table with pipes that should be removed
806        let content = "> | H1 | H2 |\n> |----|----|---|\n> | a  | b |";
807        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
808        let result = rule.fix(&ctx).unwrap();
809
810        // Pipes should be removed but blockquote prefix preserved
811        let lines: Vec<&str> = result.lines().collect();
812        assert!(lines[0].starts_with("> "), "Line should start with blockquote prefix");
813        assert!(
814            !lines[0].starts_with("> |"),
815            "Leading pipe should be removed. Got: {}",
816            lines[0]
817        );
818    }
819
820    #[test]
821    fn test_mixed_regular_and_blockquote_tables() {
822        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
823
824        // Document with both regular and blockquote tables
825        let content = "H1 | H2\n---|---\na | b\n\n> H3 | H4\n> ---|---\n> c | d";
826        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
827        let result = rule.fix(&ctx).unwrap();
828
829        // Both tables should be fixed
830        assert!(result.contains("| H1 | H2 |"), "Regular table should have pipes added");
831        assert!(
832            result.contains("> | H3 | H4 |"),
833            "Blockquote table should have pipes added with prefix preserved"
834        );
835    }
836
837    // === Roundtrip safety tests ===
838
839    fn assert_fix_roundtrip(rule: &MD055TablePipeStyle, content: &str) {
840        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
841        let fixed = rule.fix(&ctx).unwrap();
842        let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
843        let remaining = rule.check(&ctx2).unwrap();
844        assert!(
845            remaining.is_empty(),
846            "After fix(), check() should find 0 violations.\nOriginal: {content:?}\nFixed: {fixed:?}\nRemaining: {remaining:?}"
847        );
848    }
849
850    #[test]
851    fn test_roundtrip_leading_and_trailing() {
852        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
853        assert_fix_roundtrip(&rule, "H1 | H2\n---|---\na | b");
854    }
855
856    #[test]
857    fn test_roundtrip_no_leading_or_trailing() {
858        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
859        assert_fix_roundtrip(&rule, "| H1 | H2 |\n|---|---|\n| a | b |");
860    }
861
862    #[test]
863    fn test_roundtrip_consistent_mode() {
864        let rule = MD055TablePipeStyle::default();
865        assert_fix_roundtrip(&rule, "| H1 | H2 |\n|---|---|\nCell 1 | Cell 2");
866    }
867
868    #[test]
869    fn test_roundtrip_blockquote_table() {
870        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
871        assert_fix_roundtrip(&rule, "> H1 | H2\n> ---|---\n> a | b");
872    }
873
874    #[test]
875    fn test_roundtrip_mixed_tables() {
876        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
877        assert_fix_roundtrip(&rule, "H1 | H2\n---|---\na | b\n\n> H3 | H4\n> ---|---\n> c | d");
878    }
879
880    #[test]
881    fn test_roundtrip_with_surrounding_content() {
882        let rule = MD055TablePipeStyle::new("no_leading_or_trailing".to_string());
883        assert_fix_roundtrip(&rule, "# Title\n\n| H1 | H2 |\n|---|---|\n| a | b |\n\nMore text.");
884    }
885
886    #[test]
887    fn test_roundtrip_clean_content() {
888        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
889        assert_fix_roundtrip(&rule, "| H1 | H2 |\n|---|---|\n| a | b |");
890    }
891
892    // === Pandoc construct reachability tests ===
893    //
894    // These tests document that MD055 does not flag Pandoc-specific constructs
895    // (grid tables, multi-line tables, line blocks, pipe-table captions) because
896    // `ctx.table_blocks` excludes them at the source:
897    //
898    // - Grid table delimiters use `+---+---+` (no `|`), so `is_delimiter_row`
899    //   returns false and no `TableBlock` is created.
900    // - Multi-line table separators (`----------`) have no `|`, same exclusion.
901    // - Line blocks (`| First line`) end without `|`, so `is_potential_table_row`
902    //   requires `valid_parts >= 2` but finds only 1 — excluded.
903    // - Pipe-table captions (`: caption`) have no `|` — excluded.
904    //
905    // No production guard is needed. These tests ensure that if `find_table_blocks`
906    // ever changes to include these constructs, the failure is visible.
907
908    #[test]
909    fn md055_pandoc_grid_tables_not_flagged() {
910        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
911        let content = "\
912+---+---+
913| a | b |
914+===+===+
915| 1 | 2 |
916+---+---+
917";
918        // Under Pandoc: grid tables are excluded from table_blocks (delimiter rows
919        // use `+` not `|`), so no warnings are emitted.
920        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
921        let result = rule.check(&ctx).unwrap();
922        assert!(
923            result.is_empty(),
924            "MD055 should not flag Pandoc grid tables (excluded by table_blocks): {result:?}"
925        );
926
927        // Under Standard: same content also produces no warnings because the
928        // `+---+---+` lines are not recognized as pipe-table delimiters.
929        let ctx_std = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
930        let result_std = rule.check(&ctx_std).unwrap();
931        assert!(
932            result_std.is_empty(),
933            "MD055 should not flag grid-table-like content under Standard either: {result_std:?}"
934        );
935    }
936
937    #[test]
938    fn md055_pandoc_multi_line_tables_not_flagged() {
939        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
940        // Multi-line table (Pandoc extension): separator line has no `|`.
941        let content = "\
942--------- ----------- ------
943Header 1   Header 2   Header 3
944--------- ----------- ------
945Cell 1     Cell 2     Cell 3
946--------- ----------- ------
947";
948        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
949        let result = rule.check(&ctx).unwrap();
950        assert!(
951            result.is_empty(),
952            "MD055 should not flag Pandoc multi-line tables: {result:?}"
953        );
954
955        let ctx_std = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
956        let result_std = rule.check(&ctx_std).unwrap();
957        assert!(
958            result_std.is_empty(),
959            "MD055 should not flag multi-line table content under Standard: {result_std:?}"
960        );
961    }
962
963    #[test]
964    fn md055_pandoc_line_blocks_not_flagged() {
965        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
966        // Pandoc line blocks: `| text` that starts with `|` but does not end with `|`.
967        // is_potential_table_row requires valid_parts >= 2 for non-outer-piped lines.
968        let content = "| First line\n| Second line\n";
969        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
970        let result = rule.check(&ctx).unwrap();
971        assert!(
972            result.is_empty(),
973            "MD055 should not treat Pandoc line blocks as tables: {result:?}"
974        );
975
976        let ctx_std = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
977        let result_std = rule.check(&ctx_std).unwrap();
978        assert!(
979            result_std.is_empty(),
980            "MD055 should not treat line-block-like content as tables under Standard: {result_std:?}"
981        );
982    }
983
984    #[test]
985    fn md055_pandoc_pipe_table_captions_not_flagged() {
986        let rule = MD055TablePipeStyle::new("leading_and_trailing".to_string());
987        // Pipe-table captions (`: caption`) have no `|`, so they are never included
988        // in table_blocks.
989        let content = "\
990| H1 | H2 |
991|----|-----|
992| a  | b  |
993
994: My table caption
995";
996        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
997        let result = rule.check(&ctx).unwrap();
998        assert!(
999            result.is_empty(),
1000            "MD055 should not flag the pipe-table caption line: {result:?}"
1001        );
1002
1003        // Under Standard: same table rows are correctly checked; caption line is ignored.
1004        let ctx_std = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1005        let result_std = rule.check(&ctx_std).unwrap();
1006        assert!(
1007            result_std.is_empty(),
1008            "MD055 already-valid table with caption should have no warnings under Standard: {result_std:?}"
1009        );
1010    }
1011}