mdbook-lint-rulesets 0.12.0

Modular rulesets for mdbook-lint - standard and mdBook-specific linting rules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! MD060: Table column style
//!
//! This rule checks that table column delimiter segments use a consistent style.
//! Styles include:
//! - `aligned` - leading/trailing spaces maintain column width alignment
//! - `compact` - no extra spaces around content
//! - `tight` - single-space padding around content

use mdbook_lint_core::error::Result;
use mdbook_lint_core::rule::{Rule, RuleCategory, RuleMetadata};
use mdbook_lint_core::{
    Document,
    violation::{Severity, Violation},
};

/// Rule to check table column style consistency
pub struct MD060 {
    /// Preferred table column style
    style: ColumnStyle,
}

/// Table column style options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ColumnStyle {
    /// Leading/trailing spaces maintain column width alignment
    Aligned,
    /// No extra spaces around content
    Compact,
    /// Single-space padding around content
    Tight,
    /// Any style is allowed (consistency not enforced)
    Any,
    /// Detect from first usage and enforce consistency
    Consistent,
}

impl MD060 {
    /// Create a new MD060 rule with consistent style detection
    pub fn new() -> Self {
        Self {
            style: ColumnStyle::Consistent,
        }
    }

    /// Create a new MD060 rule with specific style preference
    #[allow(dead_code)]
    pub fn with_style(style: ColumnStyle) -> Self {
        Self { style }
    }

    /// Create MD060 from configuration
    pub fn from_config(config: &toml::Value) -> Self {
        let mut rule = Self::new();

        if let Some(style_str) = config.get("style").and_then(|v| v.as_str()) {
            rule.style = match style_str.to_lowercase().as_str() {
                "aligned" => ColumnStyle::Aligned,
                "compact" => ColumnStyle::Compact,
                "tight" => ColumnStyle::Tight,
                "any" => ColumnStyle::Any,
                "consistent" => ColumnStyle::Consistent,
                _ => ColumnStyle::Consistent, // Default fallback
            };
        }

        rule
    }

    /// Get code block ranges to exclude from checking
    fn get_code_block_ranges(&self, lines: &[&str]) -> Vec<bool> {
        let mut in_code_block = vec![false; lines.len()];
        let mut in_fenced_block = false;

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Check for fenced code blocks
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_fenced_block = !in_fenced_block;
                in_code_block[i] = true;
                continue;
            }

            if in_fenced_block {
                in_code_block[i] = true;
            }
        }

        in_code_block
    }

    /// Check if a line is a table separator (like |---|---|)
    fn is_table_separator(&self, line: &str) -> bool {
        let trimmed = line.trim();
        if !trimmed.contains('|') {
            return false;
        }

        // Remove pipes and check if remaining chars are only - : and whitespace
        let without_pipes = trimmed.replace('|', "");
        without_pipes
            .chars()
            .all(|c| c == '-' || c == ':' || c.is_whitespace())
    }

    /// Find table blocks in the document
    fn find_table_blocks(&self, lines: &[&str], in_code_block: &[bool]) -> Vec<(usize, usize)> {
        let mut table_blocks = Vec::new();
        let mut i = 0;

        while i < lines.len() {
            // Skip code blocks
            if in_code_block[i] {
                i += 1;
                continue;
            }

            // Look for a line with pipes that could be a table header
            let line = lines[i].trim();
            if !line.contains('|') {
                i += 1;
                continue;
            }

            // Check if next line is a separator (indicates valid table)
            if i + 1 < lines.len() && self.is_table_separator(lines[i + 1]) {
                let start = i;
                // Find the end of the table
                i += 2; // Skip header and separator
                while i < lines.len() && !in_code_block[i] {
                    let row = lines[i].trim();
                    if row.is_empty() || !row.contains('|') {
                        break;
                    }
                    // Stop if we hit another separator (would indicate a new table)
                    if self.is_table_separator(row) {
                        break;
                    }
                    i += 1;
                }
                table_blocks.push((start, i - 1));
            } else {
                i += 1;
            }
        }

        table_blocks
    }

    /// Parse a table row into cells
    fn parse_cells(&self, line: &str) -> Vec<String> {
        let trimmed = line.trim();

        // Handle leading/trailing pipes
        let content = if let Some(stripped) = trimmed.strip_prefix('|') {
            if let Some(inner) = stripped.strip_suffix('|') {
                inner
            } else {
                stripped
            }
        } else if let Some(stripped) = trimmed.strip_suffix('|') {
            stripped
        } else {
            trimmed
        };

        content.split('|').map(|s| s.to_string()).collect()
    }

    /// Detect the column style of a cell
    fn detect_cell_style(&self, cell: &str) -> Option<ColumnStyle> {
        if cell.is_empty() {
            return None;
        }

        let trimmed = cell.trim();
        if trimmed.is_empty() {
            // Cell contains only whitespace - could be empty cell
            return None;
        }

        let leading_spaces = cell.len() - cell.trim_start().len();
        let trailing_spaces = cell.len() - cell.trim_end().len();

        if leading_spaces == 0 && trailing_spaces == 0 {
            // No padding at all: |Value|
            Some(ColumnStyle::Compact)
        } else if leading_spaces >= 1 {
            // Has leading space - considered "tight" (readable style)
            // We don't distinguish aligned vs tight at cell level since
            // aligned tables have variable trailing space per column width
            Some(ColumnStyle::Tight)
        } else {
            // Edge case: trailing but no leading space
            Some(ColumnStyle::Tight)
        }
    }

    /// Check if a table uses aligned style (variable trailing spaces for column alignment)
    fn is_table_aligned(&self, lines: &[&str], start: usize, end: usize) -> bool {
        let mut max_trailing_spaces = 0;

        for line in lines.iter().take(end + 1).skip(start) {
            if self.is_table_separator(line) {
                continue;
            }

            let cells = self.parse_cells(line);
            for cell in &cells {
                let trimmed = cell.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let trailing_spaces = cell.len() - cell.trim_end().len();
                if trailing_spaces > max_trailing_spaces {
                    max_trailing_spaces = trailing_spaces;
                }
            }
        }

        // If any cell has more than 1 trailing space, consider it aligned style
        max_trailing_spaces > 1
    }

    /// Analyze a table to detect its column style
    fn analyze_table_style(&self, lines: &[&str], start: usize, end: usize) -> Option<ColumnStyle> {
        // First check if this is an aligned table (has extra trailing spaces)
        if self.is_table_aligned(lines, start, end) {
            return Some(ColumnStyle::Aligned);
        }

        // Otherwise detect from first cell
        for line in lines.iter().take(end + 1).skip(start) {
            // Skip separator rows
            if self.is_table_separator(line) {
                continue;
            }

            let cells = self.parse_cells(line);
            for cell in &cells {
                if let Some(style) = self.detect_cell_style(cell) {
                    return Some(style);
                }
            }
        }

        None
    }

    /// Check a table for style violations
    fn check_table(
        &self,
        lines: &[&str],
        start: usize,
        end: usize,
        expected_style: ColumnStyle,
    ) -> Vec<Violation> {
        let mut violations = Vec::new();

        for (line_idx, line) in lines.iter().enumerate().take(end + 1).skip(start) {
            let line_number = line_idx + 1;

            // Skip separator rows
            if self.is_table_separator(line) {
                continue;
            }

            let cells = self.parse_cells(line);
            for (col_idx, cell) in cells.iter().enumerate() {
                if let Some(cell_style) = self.detect_cell_style(cell) {
                    // Aligned style is compatible with tight (aligned tables have varying padding)
                    // So we only flag when:
                    // - expected is compact but found tight/aligned
                    // - expected is tight but found compact
                    // - expected is aligned but found compact
                    let is_compatible = match (expected_style, cell_style) {
                        (ColumnStyle::Any, _) => true,
                        (ColumnStyle::Consistent, _) => true,
                        (ColumnStyle::Aligned, ColumnStyle::Tight) => true, // Aligned includes tight cells
                        (ColumnStyle::Aligned, ColumnStyle::Aligned) => true,
                        (ColumnStyle::Tight, ColumnStyle::Tight) => true,
                        (ColumnStyle::Compact, ColumnStyle::Compact) => true,
                        _ => false,
                    };

                    if !is_compatible {
                        let expected_desc = match expected_style {
                            ColumnStyle::Aligned => "aligned",
                            ColumnStyle::Compact => "compact",
                            ColumnStyle::Tight => "tight",
                            ColumnStyle::Any | ColumnStyle::Consistent => continue,
                        };
                        let found_desc = match cell_style {
                            ColumnStyle::Aligned => "aligned",
                            ColumnStyle::Compact => "compact",
                            ColumnStyle::Tight => "tight",
                            ColumnStyle::Any | ColumnStyle::Consistent => continue,
                        };

                        violations.push(self.create_violation(
                            format!(
                                "Table column style inconsistent - expected '{expected_desc}' but found '{found_desc}' in column {}",
                                col_idx + 1
                            ),
                            line_number,
                            1,
                            Severity::Warning,
                        ));
                        // Only report one violation per row to avoid noise
                        break;
                    }
                }
            }
        }

        violations
    }
}

impl Default for MD060 {
    fn default() -> Self {
        Self::new()
    }
}

impl Rule for MD060 {
    fn id(&self) -> &'static str {
        "MD060"
    }

    fn name(&self) -> &'static str {
        "table-column-style"
    }

    fn description(&self) -> &'static str {
        "Table column style should be consistent"
    }

    fn metadata(&self) -> RuleMetadata {
        RuleMetadata::stable(RuleCategory::Formatting).introduced_in("mdbook-lint v0.5.0")
    }

    fn can_fix(&self) -> bool {
        false // Style changes are complex and better done manually
    }

    fn check_with_ast<'a>(
        &self,
        document: &Document,
        _ast: Option<&'a comrak::nodes::AstNode<'a>>,
    ) -> Result<Vec<Violation>> {
        // If style is Any, nothing to check
        if self.style == ColumnStyle::Any {
            return Ok(Vec::new());
        }

        let mut violations = Vec::new();
        let lines: Vec<&str> = document.content.lines().collect();
        let in_code_block = self.get_code_block_ranges(&lines);

        // Find all table blocks
        let table_blocks = self.find_table_blocks(&lines, &in_code_block);

        let mut document_style: Option<ColumnStyle> = match self.style {
            ColumnStyle::Aligned => Some(ColumnStyle::Aligned),
            ColumnStyle::Compact => Some(ColumnStyle::Compact),
            ColumnStyle::Tight => Some(ColumnStyle::Tight),
            ColumnStyle::Consistent => None, // Detect from first table
            ColumnStyle::Any => return Ok(Vec::new()),
        };

        // Process each table
        for (start, end) in table_blocks {
            // Detect style from first table if using Consistent mode
            if document_style.is_none() {
                document_style = self.analyze_table_style(&lines, start, end);
            }

            if let Some(expected_style) = document_style {
                let table_violations = self.check_table(&lines, start, end, expected_style);
                violations.extend(table_violations);
            }
        }

        Ok(violations)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mdbook_lint_core::rule::Rule;
    use std::path::PathBuf;

    fn create_test_document(content: &str) -> Document {
        Document::new(content.to_string(), PathBuf::from("test.md")).unwrap()
    }

    #[test]
    fn test_md060_consistent_tight_style() {
        // Tight style: single space on each side of content
        let content = r#"| A | B | C |
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_consistent_compact_style() {
        // Compact style: no spaces around content
        let content = r#"|A|B|C|
|---|---|---|
|1|2|3|
|4|5|6|
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_consistent_aligned_style() {
        // Aligned style: extra spaces for column alignment
        let content = r#"| Column 1   | Col 2 | Column 3     |
|------------|-------|--------------|
| Value 1    | V2    | Value 3      |
| V4         | Val 5 | V6           |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_mixed_styles_violation() {
        // First row is tight, data row mixes compact and tight
        let content = r#"| A | B |
|---|---|
|1| 2 |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rule_id, "MD060");
        assert!(violations[0].message.contains("inconsistent"));
    }

    #[test]
    fn test_md060_enforced_tight_style() {
        // Compact style content should fail when tight is required
        let content = r#"|A|B|
|---|---|
|1|2|
"#;

        let document = create_test_document(content);
        let rule = MD060::with_style(ColumnStyle::Tight);
        let violations = rule.check(&document).unwrap();
        // Compact style violates tight requirement
        assert!(!violations.is_empty());
    }

    #[test]
    fn test_md060_enforced_compact_style() {
        // Tight style content should fail when compact is required
        let content = r#"| A | B |
|---|---|
| 1 | 2 |
"#;

        let document = create_test_document(content);
        let rule = MD060::with_style(ColumnStyle::Compact);
        let violations = rule.check(&document).unwrap();
        // Tight style violates compact requirement
        assert!(!violations.is_empty());
    }

    #[test]
    fn test_md060_any_style_no_violations() {
        // Mixed styles should be OK when Any is set
        let content = r#"| A | B |
|---|---|
|1| 2 |
"#;

        let document = create_test_document(content);
        let rule = MD060::with_style(ColumnStyle::Any);
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_multiple_tables_consistent() {
        // Both tables use tight style
        let content = r#"| A | B |
|---|---|
| 1 | 2 |

Some text.

| C | D |
|---|---|
| 3 | 4 |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_multiple_tables_inconsistent() {
        // First table tight, second table compact
        let content = r#"| A | B |
|---|---|
| 1 | 2 |

Some text.

|C|D|
|---|---|
|3|4|
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        // Second table has different style from first
        assert!(!violations.is_empty());
    }

    #[test]
    fn test_md060_code_blocks_ignored() {
        // Table inside code block should be ignored
        let content = r#"| A | B |
|---|---|
| 1 | 2 |

```
|X|Y|
|---|---|
|a|b|
```

| C | D |
|---|---|
| 3 | 4 |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_no_tables() {
        let content = r#"# Heading

This is just regular text without any tables.

Some more content.
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_from_config() {
        let config = toml::toml! {
            style = "compact"
        };

        let rule = MD060::from_config(&config);
        assert_eq!(rule.style, ColumnStyle::Compact);
    }

    #[test]
    fn test_md060_from_config_aligned() {
        let config = toml::toml! {
            style = "aligned"
        };

        let rule = MD060::from_config(&config);
        assert_eq!(rule.style, ColumnStyle::Aligned);
    }

    #[test]
    fn test_md060_from_config_tight() {
        let config = toml::toml! {
            style = "tight"
        };

        let rule = MD060::from_config(&config);
        assert_eq!(rule.style, ColumnStyle::Tight);
    }

    #[test]
    fn test_md060_from_config_any() {
        let config = toml::toml! {
            style = "any"
        };

        let rule = MD060::from_config(&config);
        assert_eq!(rule.style, ColumnStyle::Any);
    }

    #[test]
    fn test_md060_from_config_invalid_defaults_to_consistent() {
        let config = toml::toml! {
            style = "invalid_style"
        };

        let rule = MD060::from_config(&config);
        assert_eq!(rule.style, ColumnStyle::Consistent);
    }

    #[test]
    fn test_md060_separator_with_alignment() {
        // Separator rows with alignment markers should not affect style detection
        let content = r#"| A | B |
|:--|--:|
| 1 | 2 |
"#;

        let document = create_test_document(content);
        let rule = MD060::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md060_can_fix() {
        let rule = MD060::new();
        assert!(!Rule::can_fix(&rule));
    }
}