mdbook-lint-rulesets 0.16.1

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
//! CONTENT004: Heading capitalization consistency
//!
//! Checks that headings use consistent capitalization style throughout
//! the document (e.g., Title Case vs sentence case).

use mdbook_lint_core::Document;
use mdbook_lint_core::rule::{Rule, RuleCategory, RuleMetadata};
use mdbook_lint_core::violation::{Severity, Violation};
use regex::Regex;
use std::sync::LazyLock;

/// Regex to extract heading text from ATX headings
static HEADING_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.+?)(?:\s*#*)?$").unwrap());

/// Common lowercase words in Title Case (articles, conjunctions, prepositions)
const TITLE_CASE_EXCEPTIONS: &[&str] = &[
    "a", "an", "the", "and", "but", "or", "nor", "for", "yet", "so", "at", "by", "in", "of", "on",
    "to", "up", "as", "if", "is", "it", "vs", "via", "with",
];

/// Capitalization style for headings
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CapitalizationStyle {
    /// Title Case: Most Words Are Capitalized
    TitleCase,
    /// Sentence case: Only first word and proper nouns capitalized
    SentenceCase,
    /// Consistent: Use whatever style the first heading uses
    #[default]
    Consistent,
}

/// CONTENT004: Checks heading capitalization consistency
///
/// This rule ensures headings use a consistent capitalization style.
/// By default, it detects the style from the first heading and expects
/// all subsequent headings to follow the same pattern.
#[derive(Clone, Default)]
pub struct CONTENT004 {
    /// Required capitalization style
    style: CapitalizationStyle,
}

impl CONTENT004 {
    /// Create with a specific capitalization style
    #[allow(dead_code)]
    pub fn with_style(style: CapitalizationStyle) -> Self {
        Self { style }
    }

    /// Create an instance from rule configuration.
    ///
    /// Recognized key:
    /// - `style`: `"title"`/`"title_case"`, `"sentence"`/`"sentence_case"`, or
    ///   `"consistent"` (default: use whatever style the first heading uses).
    ///   Unrecognized values fall back to the default.
    pub fn from_config(config: &toml::Value) -> Self {
        let mut rule = Self::default();
        if let Some(style) = config.get("style").and_then(|v| v.as_str()) {
            rule.style = match style.to_lowercase().replace(['-', ' '], "_").as_str() {
                "title" | "title_case" => CapitalizationStyle::TitleCase,
                "sentence" | "sentence_case" => CapitalizationStyle::SentenceCase,
                "consistent" => CapitalizationStyle::Consistent,
                _ => rule.style,
            };
        }
        rule
    }

    /// Extract heading text from a line
    fn extract_heading(&self, line: &str) -> Option<(usize, String)> {
        HEADING_REGEX.captures(line).map(|caps| {
            let level = caps.get(1).unwrap().as_str().len();
            let text = caps.get(2).unwrap().as_str().trim().to_string();
            (level, text)
        })
    }

    /// Check if a word is an acronym (all uppercase letters)
    fn is_acronym(&self, word: &str) -> bool {
        word.len() > 1
            && word.chars().all(|c| c.is_uppercase() || !c.is_alphabetic())
            && word.chars().any(|c| c.is_alphabetic())
    }

    /// Check if a word is a title case exception (article, preposition, etc.)
    fn is_exception(&self, word: &str) -> bool {
        TITLE_CASE_EXCEPTIONS.contains(&word.to_lowercase().as_str())
    }

    /// Get significant words (excluding acronyms and exceptions except first word)
    fn get_significant_words<'a>(&self, text: &'a str) -> Vec<(usize, &'a str)> {
        text.split_whitespace()
            .enumerate()
            .filter(|(i, word)| {
                // First word is always significant
                if *i == 0 {
                    return true;
                }
                // Skip acronyms
                if self.is_acronym(word) {
                    return false;
                }
                // Skip exception words
                if self.is_exception(word) {
                    return false;
                }
                // Skip non-alphabetic words
                if !word.chars().next().is_some_and(|c| c.is_alphabetic()) {
                    return false;
                }
                true
            })
            .collect()
    }

    /// Check if a heading appears to be Title Case
    fn is_title_case(&self, text: &str) -> bool {
        let words = self.get_significant_words(text);
        if words.is_empty() {
            return true;
        }

        let capitalized = words
            .iter()
            .filter(|(_, word)| word.chars().next().is_some_and(|c| c.is_uppercase()))
            .count();

        // Consider title case if >= 60% of significant words are capitalized
        capitalized as f64 / words.len() as f64 >= 0.6
    }

    /// Check if a heading appears to be sentence case
    fn is_sentence_case(&self, text: &str) -> bool {
        let words: Vec<&str> = text.split_whitespace().collect();
        if words.is_empty() {
            return true;
        }

        // First word should be capitalized
        if !words[0].chars().next().is_some_and(|c| c.is_uppercase()) {
            return false;
        }

        // Count non-first words that start with uppercase (excluding acronyms)
        let mut uppercase_non_first = 0;
        let mut checkable_non_first = 0;

        for word in words.iter().skip(1) {
            // Skip acronyms
            if self.is_acronym(word) {
                continue;
            }
            // Skip non-alphabetic
            if !word.chars().next().is_some_and(|c| c.is_alphabetic()) {
                continue;
            }

            checkable_non_first += 1;
            if word.chars().next().is_some_and(|c| c.is_uppercase()) {
                uppercase_non_first += 1;
            }
        }

        // Allow some capitalization for proper nouns (~30% of remaining words)
        checkable_non_first == 0 || uppercase_non_first as f64 / checkable_non_first as f64 <= 0.35
    }

    /// Detect the style a specific heading exhibits
    fn detect_style(&self, text: &str) -> HeadingStyle {
        let is_title = self.is_title_case(text);
        let is_sentence = self.is_sentence_case(text);

        match (is_title, is_sentence) {
            // Satisfies both conventions, so it says nothing about the document.
            (true, true) => HeadingStyle::Ambiguous,
            (true, false) => HeadingStyle::Title,
            // A heading matching neither convention is treated as sentence case,
            // preserving the previous handling of malformed headings.
            (false, _) => HeadingStyle::Sentence,
        }
    }
}

/// The capitalization style an individual heading exhibits.
///
/// Distinct from [`CapitalizationStyle`], which is the style the user requires.
/// A heading can satisfy both conventions at once, and such a heading must not
/// decide the document style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HeadingStyle {
    /// Title Case, and not also valid sentence case.
    Title,
    /// Sentence case, or matching neither convention.
    Sentence,
    /// Valid under both conventions.
    ///
    /// `# Agentic SDLC` is the canonical case: the only non-first word is an
    /// acronym, which both checks skip, leaving nothing to discriminate on.
    Ambiguous,
}

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

    fn name(&self) -> &'static str {
        "heading-capitalization"
    }

    fn description(&self) -> &'static str {
        "Headings should use consistent capitalization (Title Case or sentence case)"
    }

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

    fn check_with_ast<'a>(
        &self,
        document: &Document,
        _ast: Option<&'a comrak::nodes::AstNode<'a>>,
    ) -> mdbook_lint_core::error::Result<Vec<Violation>> {
        let mut violations = Vec::new();
        let mut detected_style: Option<HeadingStyle> = None;
        let mut in_code_block = false;

        for (line_idx, line) in document.lines.iter().enumerate() {
            let line_num = line_idx + 1;
            let trimmed = line.trim();

            // Track code blocks
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_code_block = !in_code_block;
                continue;
            }

            if in_code_block {
                continue;
            }

            // Extract heading
            if let Some((_level, text)) = self.extract_heading(trimmed) {
                // Skip very short headings (single word)
                if text.split_whitespace().count() < 2 {
                    continue;
                }

                match self.style {
                    CapitalizationStyle::Consistent => {
                        let heading_style = self.detect_style(&text);

                        // An ambiguous heading is valid under both conventions, so
                        // it neither establishes the document style nor conflicts
                        // with an established one.
                        if heading_style == HeadingStyle::Ambiguous {
                            continue;
                        }

                        if let Some(expected) = detected_style {
                            if heading_style != expected {
                                let expected_name = match expected {
                                    HeadingStyle::Title => "Title Case",
                                    HeadingStyle::Sentence => "sentence case",
                                    HeadingStyle::Ambiguous => {
                                        unreachable!("ambiguous headings never become the baseline")
                                    }
                                };
                                violations.push(self.create_violation(
                                    format!(
                                        "Heading '{}' uses inconsistent capitalization (expected {})",
                                        text, expected_name
                                    ),
                                    line_num,
                                    1,
                                    Severity::Warning,
                                ));
                            }
                        } else {
                            detected_style = Some(heading_style);
                        }
                    }
                    CapitalizationStyle::TitleCase => {
                        if !self.is_title_case(&text) {
                            violations.push(self.create_violation(
                                format!("Heading '{}' should use Title Case", text),
                                line_num,
                                1,
                                Severity::Warning,
                            ));
                        }
                    }
                    CapitalizationStyle::SentenceCase => {
                        if !self.is_sentence_case(&text) {
                            violations.push(self.create_violation(
                                format!("Heading '{}' should use sentence case", text),
                                line_num,
                                1,
                                Severity::Warning,
                            ));
                        }
                    }
                }
            }
        }

        Ok(violations)
    }
}

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

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

    #[test]
    fn test_from_config_style() {
        let mk = |s: &str| {
            let cfg: toml::Value = toml::from_str(&format!("style = \"{s}\"")).unwrap();
            CONTENT004::from_config(&cfg).style
        };
        assert_eq!(mk("title"), CapitalizationStyle::TitleCase);
        assert_eq!(mk("title_case"), CapitalizationStyle::TitleCase);
        assert_eq!(mk("sentence"), CapitalizationStyle::SentenceCase);
        assert_eq!(mk("consistent"), CapitalizationStyle::Consistent);
        // Unknown values fall back to the default (Consistent).
        assert_eq!(mk("bogus"), CapitalizationStyle::Consistent);
    }

    #[test]
    fn test_consistent_title_case() {
        let content = "# Getting Started Guide

## Installation Steps

### Configuration Options";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_ambiguous_first_heading_does_not_force_sentence_case() {
        // Issue #462: "Agentic SDLC" is valid title case and valid sentence case,
        // because the only non-first word is an acronym that both checks skip.
        // It must not become the document baseline and flag a Title Case document.
        let content = "# Agentic SDLC

## Installation Steps

## Configuration Options";
        let doc = create_test_document(content);
        let violations = CONTENT004::default().check(&doc).unwrap();
        assert_eq!(
            violations.len(),
            0,
            "ambiguous first heading should not override a Title Case document, got: {:?}",
            violations.iter().map(|v| &v.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_ambiguous_first_heading_allows_sentence_case_document() {
        let content = "# Agentic SDLC

## Installation steps

## Configuration options";
        let doc = create_test_document(content);
        let violations = CONTENT004::default().check(&doc).unwrap();
        assert_eq!(
            violations.len(),
            0,
            "ambiguous first heading should not conflict with a sentence case document, got: {:?}",
            violations.iter().map(|v| &v.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_ambiguous_heading_does_not_suppress_later_inconsistency() {
        // The baseline is established by the first discriminating heading, and
        // genuine inconsistency after that is still reported.
        let content = "# Agentic SDLC

## Installation Steps

## Configuration options";
        let doc = create_test_document(content);
        let violations = CONTENT004::default().check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Configuration options"));
        assert!(violations[0].message.contains("Title Case"));
    }

    #[test]
    fn test_ambiguous_heading_in_middle_is_not_flagged() {
        // An ambiguous heading is valid under an established baseline of either
        // style, so it is never itself a violation.
        for content in [
            "# Getting Started Guide\n\n## Agentic SDLC\n\n## Configuration Options",
            "# Getting started guide\n\n## Agentic SDLC\n\n## Configuration options",
        ] {
            let doc = create_test_document(content);
            let violations = CONTENT004::default().check(&doc).unwrap();
            assert_eq!(
                violations.len(),
                0,
                "ambiguous heading should not be flagged under either baseline, got: {:?}",
                violations.iter().map(|v| &v.message).collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn test_explicit_style_unaffected_by_ambiguity() {
        // Explicit style = "title" / "sentence" keeps its existing meaning:
        // an ambiguous heading satisfies both, so neither mode flags it.
        let content = "# Agentic SDLC";
        let doc = create_test_document(content);

        for style in [
            CapitalizationStyle::TitleCase,
            CapitalizationStyle::SentenceCase,
        ] {
            let violations = CONTENT004::with_style(style).check(&doc).unwrap();
            assert_eq!(violations.len(), 0, "unexpected violation for {style:?}");
        }
    }

    #[test]
    fn test_consistent_sentence_case() {
        let content = "# Getting started guide

## Installation steps

### Configuration options";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_inconsistent_capitalization() {
        let content = "# Getting Started Guide

## installation steps

### More Configuration Options";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("installation steps"));
    }

    #[test]
    fn test_enforced_title_case() {
        let content = "# Getting started guide

## Installation Steps";
        let doc = create_test_document(content);
        let rule = CONTENT004::with_style(CapitalizationStyle::TitleCase);
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Getting started guide"));
    }

    #[test]
    fn test_enforced_sentence_case() {
        let content = "# Getting Started Guide

## Installation steps";
        let doc = create_test_document(content);
        let rule = CONTENT004::with_style(CapitalizationStyle::SentenceCase);
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Getting Started Guide"));
    }

    #[test]
    fn test_single_word_headings_ignored() {
        let content = "# Introduction

## Overview

### Details";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_headings_in_code_blocks_ignored() {
        let content = "# Main Title Here

```markdown
# This Is Not a Real Heading
## neither is this
```

## Second Section Here";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_mixed_styles_detected() {
        let content = "# User Guide Introduction

## getting started quickly

### Advanced Configuration";
        let doc = create_test_document(content);
        let rule = CONTENT004::default();
        let violations = rule.check(&doc).unwrap();
        // Should detect that "getting started quickly" doesn't match Title Case
        assert!(!violations.is_empty());
    }

    #[test]
    fn test_is_title_case() {
        let rule = CONTENT004::default();
        assert!(rule.is_title_case("Getting Started Guide"));
        assert!(rule.is_title_case("The Quick Brown Fox"));
        assert!(!rule.is_title_case("getting started guide"));
    }

    #[test]
    fn test_is_sentence_case() {
        let rule = CONTENT004::default();
        assert!(rule.is_sentence_case("Getting started guide"));
        assert!(rule.is_sentence_case("The quick brown fox"));
        assert!(!rule.is_sentence_case("Getting Started Guide"));
    }

    #[test]
    fn test_is_acronym() {
        let rule = CONTENT004::default();
        assert!(rule.is_acronym("API"));
        assert!(rule.is_acronym("HTTP"));
        assert!(rule.is_acronym("REST"));
        assert!(!rule.is_acronym("Api"));
        assert!(!rule.is_acronym("A")); // Single letter not acronym
    }
}