mdbook-lint-rulesets 0.14.2

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
//! MD005: List item indentation consistency
//!
//! This rule checks that list items have consistent indentation throughout the document.

use comrak::nodes::{AstNode, NodeValue};
use mdbook_lint_core::error::Result;
use mdbook_lint_core::rule::{AstRule, RuleCategory, RuleMetadata};
use mdbook_lint_core::{
    Document,
    violation::{Fix, Position, Severity, Violation},
};

/// Rule to check for consistent list item indentation
pub struct MD005;

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

    fn name(&self) -> &'static str {
        "list-indent"
    }

    fn description(&self) -> &'static str {
        "List item indentation should be consistent"
    }

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

    fn can_fix(&self) -> bool {
        true
    }

    fn check_ast<'a>(&self, document: &Document, ast: &'a AstNode<'a>) -> Result<Vec<Violation>> {
        let mut violations = Vec::new();

        // Find all list nodes
        for node in ast.descendants() {
            if let NodeValue::List(list_data) = &node.data.borrow().value {
                // Check indentation consistency within this list
                violations.extend(self.check_list_indentation(document, node, list_data)?);
            }
        }

        Ok(violations)
    }
}

impl MD005 {
    /// Check indentation consistency within a single list
    fn check_list_indentation<'a>(
        &self,
        document: &Document,
        list_node: &'a AstNode<'a>,
        _list_data: &comrak::nodes::NodeList,
    ) -> Result<Vec<Violation>> {
        let mut violations = Vec::new();
        let mut expected_indent: Option<usize> = None;

        // Iterate through list items
        for child in list_node.children() {
            if let NodeValue::Item(_) = &child.data.borrow().value
                && let Some((line_num, _)) = document.node_position(child)
                && let Some(line) = document.lines.get(line_num - 1)
            {
                let actual_indent = self.get_line_indentation(line);

                // Set expected indentation from first item
                if expected_indent.is_none() {
                    expected_indent = Some(actual_indent);
                } else if let Some(expected) = expected_indent
                    && actual_indent != expected
                {
                    // Check if this item's indentation matches
                    // Create fix by adjusting indentation to match expected
                    let spaces_to_adjust = actual_indent.abs_diff(expected);

                    let fixed_line = if actual_indent > expected {
                        // Remove extra spaces
                        format!("{}\n", &line[spaces_to_adjust..])
                    } else {
                        // Add missing spaces
                        format!("{}{}\n", " ".repeat(spaces_to_adjust), line)
                    };

                    let fix = Fix {
                        description: format!(
                            "Adjust indentation from {} to {} spaces",
                            actual_indent, expected
                        ),
                        replacement: Some(fixed_line),
                        start: Position {
                            line: line_num,
                            column: 1,
                        },
                        end: Position {
                            line: line_num,
                            column: line.len() + 1,
                        },
                    };

                    violations.push(self.create_violation_with_fix(
                        format!(
                            "List item indentation inconsistent: expected {expected} spaces, found {actual_indent}"
                        ),
                        line_num,
                        1,
                        Severity::Warning,
                        fix,
                    ));
                }
            }
        }

        Ok(violations)
    }

    /// Get the indentation level (number of leading spaces/tabs) of a line
    fn get_line_indentation(&self, line: &str) -> usize {
        let mut indent = 0;
        for ch in line.chars() {
            match ch {
                ' ' => indent += 1,
                '\t' => indent += 4, // Count tabs as 4 spaces
                _ => break,
            }
        }
        indent
    }
}

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

    #[test]
    fn test_md005_no_violations() {
        let content = r#"# Consistent List Indentation

These lists have consistent indentation:

- Item 1
- Item 2
- Item 3

1. First item
2. Second item
3. Third item

Nested lists with consistent indentation:

- Top level
  - Nested item 1
  - Nested item 2
    - Deeply nested 1
    - Deeply nested 2
- Back to top level
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md005_inconsistent_indentation() {
        let content = r#"# Inconsistent List Indentation

This list has inconsistent indentation at the same level:

- Item 1
- Item 2
 - Item 3 (inconsistent - 1 space instead of 0)
- Item 4
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // Should detect inconsistent indentation in the main list
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("expected 0 spaces, found 1"));
    }

    #[test]
    fn test_md005_ordered_list_inconsistent() {
        let content = r#"# Inconsistent Ordered List

1. First item
 2. Second item (wrong indentation)
1. Third item
  3. Fourth item (wrong again)
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 2);
        assert!(violations[0].message.contains("expected 0 spaces, found 1"));
        assert!(violations[1].message.contains("expected 0 spaces, found 2"));
    }

    #[test]
    fn test_md005_mixed_spaces_tabs() {
        let content = "# Mixed Spaces and Tabs\n\n- Item 1\n\t- Item 2 (tab indented)\n    - Item 3 (space indented)\n";
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // Should detect inconsistency between tab (4 spaces) and 4 actual spaces
        // Note: tabs are converted to 4 spaces for comparison
        assert_eq!(violations.len(), 0); // Both should be equivalent to 4 spaces
    }

    #[test]
    fn test_md005_separate_lists() {
        let content = r#"# Separate Lists

First list:
- Item A
- Item B

Second list with different indentation (should be OK):
  - Item X
  - Item Y

Third list:
1. Item 1
1. Item 2
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // Each list can have its own indentation style
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md005_nested_lists_independent() {
        let content = r#"# Nested Lists

- Top level item 1
- Top level item 2
  - Nested item A
   - Nested item B (inconsistent with nested level)
  - Nested item C
- Top level item 3
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // Should detect inconsistency in the nested list
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("expected 2 spaces, found 3"));
    }

    #[test]
    fn test_md005_empty_list() {
        let content = r#"# Empty or Single Item Lists

- Single item

1. Another single item

Some text here.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // No violations for single-item lists
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md005_complex_nesting() {
        let content = r#"# Complex Nesting

- Level 1 item 1
  - Level 2 item 1
    - Level 3 item 1
    - Level 3 item 2
  - Level 2 item 2
   - Level 2 item 3 (wrong indentation)
- Level 1 item 2
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        // Should detect the inconsistent level 2 item
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("expected 2 spaces, found 3"));
    }

    #[test]
    fn test_get_line_indentation() {
        let rule = MD005;

        assert_eq!(rule.get_line_indentation("- No indentation"), 0);
        assert_eq!(rule.get_line_indentation("  - Two spaces"), 2);
        assert_eq!(rule.get_line_indentation("    - Four spaces"), 4);
        assert_eq!(rule.get_line_indentation("\t- One tab"), 4);
        assert_eq!(rule.get_line_indentation("\t  - Tab plus two spaces"), 6);
        assert_eq!(rule.get_line_indentation("      - Six spaces"), 6);
    }

    #[test]
    fn test_md005_fix_add_indentation() {
        // Note: This test is about list item indentation consistency.
        // The third line "Item 3" isn't a list item, so it won't be fixed by MD005.
        // Let's use a proper list item instead:
        let content = r#"# Inconsistent List

  - Item 1
  - Item 2
- Item 3 (wrong indentation)"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.description, "Adjust indentation from 0 to 2 spaces");
        assert_eq!(
            fix.replacement,
            Some("  - Item 3 (wrong indentation)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_remove_indentation() {
        // MD005 checks consistency within a single list level
        // Items at different nesting levels are separate lists
        let content = r#"# Inconsistent List

- Item 1
- Item 2
 - Item 3 (inconsistent at same level)"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.description, "Adjust indentation from 1 to 0 spaces");
        assert_eq!(
            fix.replacement,
            Some("- Item 3 (inconsistent at same level)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_ordered_list() {
        let content = r#"# Inconsistent Ordered List

1. First item
 2. Second item (wrong indentation)
1. Third item"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.description, "Adjust indentation from 1 to 0 spaces");
        assert_eq!(
            fix.replacement,
            Some("2. Second item (wrong indentation)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_nested_lists() {
        let content = r#"# Nested Lists

- Top level item 1
- Top level item 2
  - Nested item A
   - Nested item B (inconsistent)"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.description, "Adjust indentation from 3 to 2 spaces");
        assert_eq!(
            fix.replacement,
            Some("  - Nested item B (inconsistent)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_multiple_violations() {
        let content = r#"# Multiple Issues

- Item 1
 - Item 2 (1 space)
  - Item 3 (2 spaces)
   - Item 4 (3 spaces)"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 3);

        // All should have fixes
        for violation in &violations {
            assert!(violation.fix.is_some());
        }

        // Check each fix
        assert_eq!(
            violations[0].fix.as_ref().unwrap().description,
            "Adjust indentation from 1 to 0 spaces"
        );
        assert_eq!(
            violations[0].fix.as_ref().unwrap().replacement,
            Some("- Item 2 (1 space)\n".to_string())
        );

        assert_eq!(
            violations[1].fix.as_ref().unwrap().description,
            "Adjust indentation from 2 to 0 spaces"
        );
        assert_eq!(
            violations[1].fix.as_ref().unwrap().replacement,
            Some("- Item 3 (2 spaces)\n".to_string())
        );

        assert_eq!(
            violations[2].fix.as_ref().unwrap().description,
            "Adjust indentation from 3 to 0 spaces"
        );
        assert_eq!(
            violations[2].fix.as_ref().unwrap().replacement,
            Some("- Item 4 (3 spaces)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_preserves_content() {
        let content = r#"# List with Formatting

- Item with **bold** text
 - Item with *italic* text (wrong indent)
- Item with `code` text"#;

        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD005;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(
            fix.replacement,
            Some("- Item with *italic* text (wrong indent)\n".to_string())
        );
    }

    #[test]
    fn test_md005_fix_tabs_converted() {
        // Test MD005 can_fix method
        // Since MD005 uses AST parsing and tabs create separate list contexts,
        // we'll just verify the can_fix method works
        let rule = MD005;
        assert!(mdbook_lint_core::AstRule::can_fix(&rule));

        // Also test a simple case where space is inconsistent
        let content = "# List\n\n- Item 1\n - Item 2 (1 space - inconsistent)";
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].fix.is_some());

        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.description, "Adjust indentation from 1 to 0 spaces");
        assert_eq!(
            fix.replacement,
            Some("- Item 2 (1 space - inconsistent)\n".to_string())
        );
    }

    #[test]
    fn test_md005_can_fix() {
        let rule = MD005;
        assert!(mdbook_lint_core::AstRule::can_fix(&rule));
    }
}