mdbook-lint-rulesets 0.14.3

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
//! MD026: Trailing punctuation in headings
//!
//! This rule checks that headings do not end with punctuation characters.

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 that headings do not end with punctuation
pub struct MD026 {
    /// Punctuation characters to check for (default: ".,;:!")
    /// Note: Question marks are excluded by default as question-style headings are common
    punctuation: String,
}

impl MD026 {
    /// Create a new MD026 rule with default settings
    pub fn new() -> Self {
        Self {
            // Exclude ? by default - question headings like "What Is Ownership?" are common
            punctuation: ".,;:!".to_string(),
        }
    }

    /// Create a new MD026 rule with custom punctuation characters
    #[allow(dead_code)]
    pub fn with_punctuation(punctuation: String) -> Self {
        Self { punctuation }
    }

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

        if let Some(punctuation) = config.get("punctuation").and_then(|v| v.as_str()) {
            rule.punctuation = punctuation.to_string();
        }

        rule
    }

    /// Check if a character is considered punctuation for this rule
    fn is_punctuation(&self, ch: char) -> bool {
        self.punctuation.contains(ch)
    }

    /// Check if heading ends with a Rust macro (identifier followed by !)
    /// Examples: panic!, assert!, format!, vec!
    /// We use a conservative approach: only recognize common Rust macros
    fn ends_with_rust_macro(&self, text: &str) -> bool {
        if !text.ends_with('!') {
            return false;
        }

        // Get the word before the !
        let without_bang = &text[..text.len() - 1];
        let last_word = without_bang.split_whitespace().next_back().unwrap_or("");

        if last_word.is_empty() {
            return false;
        }

        // Common Rust macros that are frequently used in documentation
        const KNOWN_MACROS: &[&str] = &[
            "panic",
            "assert",
            "assert_eq",
            "assert_ne",
            "debug_assert",
            "debug_assert_eq",
            "debug_assert_ne",
            "format",
            "print",
            "println",
            "eprint",
            "eprintln",
            "write",
            "writeln",
            "vec",
            "todo",
            "unimplemented",
            "unreachable",
            "matches",
            "cfg",
            "env",
            "include",
            "include_str",
            "include_bytes",
            "concat",
            "stringify",
            "macro_rules",
            "dbg",
            "column",
            "file",
            "line",
            "module_path",
            "option_env",
        ];

        // Check if it's a known macro
        KNOWN_MACROS.contains(&last_word)
    }

    /// Check if heading ends with Rust range operator (..)
    fn ends_with_range_operator(&self, text: &str) -> bool {
        text.ends_with("..")
    }
}

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

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

    fn name(&self) -> &'static str {
        "no-trailing-punctuation"
    }

    fn description(&self) -> &'static str {
        "Trailing punctuation in heading"
    }

    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 heading nodes
        for node in ast.descendants() {
            if let NodeValue::Heading(_heading) = &node.data.borrow().value
                && let Some((line, column)) = document.node_position(node)
            {
                let heading_text = document.node_text(node);
                let heading_text = heading_text.trim();

                // Skip empty headings
                if heading_text.is_empty() {
                    continue;
                }

                // Check if heading ends with punctuation
                if let Some(last_char) = heading_text.chars().last()
                    && self.is_punctuation(last_char)
                {
                    // Skip Rust macros (e.g., panic!, assert!, format!)
                    if last_char == '!' && self.ends_with_rust_macro(heading_text) {
                        continue;
                    }

                    // Skip Rust range operator (..)
                    if last_char == '.' && self.ends_with_range_operator(heading_text) {
                        continue;
                    }
                    // Create fix by removing trailing punctuation
                    let line_content = &document.lines[line - 1];
                    let heading_without_punct =
                        heading_text.trim_end_matches(|c| self.is_punctuation(c));

                    let fixed_line = if line_content.trim_start().starts_with('#') {
                        // ATX heading
                        let trimmed = line_content.trim_start();
                        let hashes_end = trimmed.find(|c: char| c != '#').unwrap_or(trimmed.len());
                        let hashes = &trimmed[..hashes_end];
                        // Check if it's a closed ATX heading (ends with hashes)
                        let content_after_hashes = &trimmed[hashes_end..];
                        if content_after_hashes.trim_end().ends_with('#') {
                            // Closed ATX - preserve closing hashes
                            let closing_hashes_start = content_after_hashes
                                .rfind(|c: char| c != '#' && !c.is_whitespace())
                                .map(|i| i + 1)
                                .unwrap_or(0);
                            format!(
                                "{} {} {}\n",
                                hashes,
                                heading_without_punct,
                                content_after_hashes[closing_hashes_start..].trim()
                            )
                        } else {
                            format!("{} {}\n", hashes, heading_without_punct)
                        }
                    } else {
                        // Setext heading - just replace the text
                        format!("{}\n", heading_without_punct)
                    };

                    let fix = Fix {
                        description: format!("Remove trailing punctuation '{}'", last_char),
                        replacement: Some(fixed_line),
                        start: Position { line, column: 1 },
                        end: Position {
                            line,
                            column: line_content.len() + 1,
                        },
                    };

                    violations.push(self.create_violation_with_fix(
                        format!(
                            "Heading should not end with punctuation '{last_char}': {heading_text}"
                        ),
                        line,
                        column,
                        Severity::Warning,
                        fix,
                    ));
                }
            }
        }

        Ok(violations)
    }
}

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

    #[test]
    fn test_md026_no_punctuation() {
        let content = r#"# Valid heading
## Another valid heading
### Third level heading
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md026_period_violation() {
        let content = r#"# Heading with period.
Some content here.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(violations[0].message.contains("Heading with period."));
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md026_multiple_punctuation_types() {
        let content = r#"# Heading with period.
## Heading with comma,
### Heading with semicolon;
#### Heading with colon:
##### Heading with exclamation!
###### Heading with question?
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Question marks are excluded by default, so only 5 violations
        assert_eq!(violations.len(), 5);

        // Check each punctuation type
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(
            violations[1]
                .message
                .contains("should not end with punctuation ','")
        );
        assert!(
            violations[2]
                .message
                .contains("should not end with punctuation ';'")
        );
        assert!(
            violations[3]
                .message
                .contains("should not end with punctuation ':'")
        );
        assert!(
            violations[4]
                .message
                .contains("should not end with punctuation '!'")
        );
        // Question mark is no longer flagged by default
    }

    #[test]
    fn test_md026_custom_punctuation() {
        let content = r#"# Heading with period.
## Heading with custom @
### Heading with allowed!
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::with_punctuation(".@".to_string());
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 2);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(
            violations[1]
                .message
                .contains("should not end with punctuation '@'")
        );
    }

    #[test]
    fn test_md026_setext_headings() {
        let content = r#"Setext heading with period.
===========================

Another setext with exclamation!
-----------------------------
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 2);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(
            violations[1]
                .message
                .contains("should not end with punctuation '!'")
        );
    }

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

##

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

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

    #[test]
    fn test_md026_punctuation_in_middle() {
        let content = r#"# Heading with punctuation, but not at end
## Question? No, this is fine at end!
### Period. In middle is ok
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '!'")
        );
        assert_eq!(violations[0].line, 2);
    }

    #[test]
    fn test_md026_whitespace_after_punctuation() {
        let content = r#"# Heading with period.
## Heading with spaces after punctuation.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Should detect punctuation even with trailing whitespace
        assert_eq!(violations.len(), 2);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(
            violations[1]
                .message
                .contains("should not end with punctuation '.'")
        );
    }

    #[test]
    fn test_md026_closed_atx_headings() {
        let content = r#"# Closed ATX heading. #
## Another closed heading! ##
### Valid closed heading ###
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 2);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert!(
            violations[1]
                .message
                .contains("should not end with punctuation '!'")
        );
    }

    #[test]
    fn test_md026_headings_in_code_blocks() {
        let content = r#"Some text here.

```markdown
# This heading has punctuation.
## This one too!
```

# But this real heading also has punctuation.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Should only detect the real heading, not the ones in code blocks
        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("should not end with punctuation '.'")
        );
        assert_eq!(violations[0].line, 8);
    }

    #[test]
    fn test_md026_fix_trailing_punctuation() {
        let content = "# Heading with exclamation!\n## Another with period.";
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

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

        // First heading - remove !
        assert!(violations[0].fix.is_some());
        let fix1 = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix1.description, "Remove trailing punctuation '!'");
        assert_eq!(
            fix1.replacement,
            Some("# Heading with exclamation\n".to_string())
        );

        // Second heading - remove .
        assert!(violations[1].fix.is_some());
        let fix2 = violations[1].fix.as_ref().unwrap();
        assert_eq!(fix2.description, "Remove trailing punctuation '.'");
        assert_eq!(
            fix2.replacement,
            Some("## Another with period\n".to_string())
        );
    }

    #[test]
    fn test_md026_fix_multiple_punctuation() {
        // Use colons instead of periods since .. is now recognized as range operator
        let content = "# Heading with multiple:::";
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        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();
        // Should remove all trailing punctuation
        assert_eq!(
            fix.replacement,
            Some("# Heading with multiple\n".to_string())
        );
    }

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

    #[test]
    fn test_md026_question_marks_allowed_by_default() {
        let content = r#"# What Is Ownership?
## Where's the -> Operator?
### Why Not An Enum?
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Question marks should not be flagged by default
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md026_question_marks_configurable() {
        let content = r#"# What Is Ownership?
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        // Explicitly include ? in punctuation
        let rule = MD026::with_punctuation(".,;:!?".to_string());
        let violations = rule.check(&document).unwrap();

        // Question mark should be flagged when explicitly configured
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("'?'"));
    }

    #[test]
    fn test_md026_rust_macros_not_flagged() {
        let content = r#"# Unrecoverable Errors with panic!
## Checking Results with assert!
### Testing Equality with assert_eq! and assert_ne!
#### Concatenating with + or format!
##### Using the vec! macro
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Rust macros should not be flagged
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md026_regular_exclamation_still_flagged() {
        let content = r#"# Hello, World!
## Hello, Cargo!
### This is exciting!
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Regular exclamation marks (not Rust macros) should still be flagged
        assert_eq!(violations.len(), 3);
        assert!(violations[0].message.contains("Hello, World!"));
        assert!(violations[1].message.contains("Hello, Cargo!"));
        assert!(violations[2].message.contains("This is exciting!"));
    }

    #[test]
    fn test_md026_range_operator_not_flagged() {
        let content = r#"# Remaining Parts of a Value with ..
## Using the range operator ..
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Range operator (..) should not be flagged
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md026_single_period_still_flagged() {
        let content = r#"# This heading ends with a period.
"#;
        let document = Document::new(content.to_string(), PathBuf::from("test.md")).unwrap();
        let rule = MD026::new();
        let violations = rule.check(&document).unwrap();

        // Single period should still be flagged
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("'.'"));
    }
}