mdbook-lint-rulesets 0.16.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
//! MD041: First line in file should be a top level heading
//!
//! This rule checks that the first line of the file is a top-level heading (H1).

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 that the first line is a top-level heading
pub struct MD041;

impl MD041 {
    /// Check if a line is a top-level heading (H1)
    fn is_top_level_heading(&self, line: &str) -> bool {
        let trimmed = line.trim();

        // ATX style: # Heading
        if trimmed.starts_with("# ") && !trimmed.starts_with("## ") {
            return true;
        }

        // Also accept just # without space if there's content after
        if trimmed.starts_with('#') && !trimmed.starts_with("##") && trimmed.len() > 1 {
            return true;
        }

        false
    }

    /// Check if a line is a setext-style H1 (underlined with =)
    fn is_setext_h1_underline(&self, line: &str) -> bool {
        let trimmed = line.trim();
        !trimmed.is_empty() && trimmed.chars().all(|c| c == '=')
    }

    /// Check if a line is content that could be a setext heading
    fn could_be_setext_heading(&self, line: &str) -> bool {
        let trimmed = line.trim();
        !trimmed.is_empty() && !trimmed.starts_with('#')
    }

    /// Check whether any frontmatter line declares a title field, e.g. `title: X`.
    ///
    /// Mirrors markdownlint's default `front_matter_title` pattern
    /// (`^\s*"?title"?\s*[:=]`), covering the common YAML (`title:`) and TOML
    /// (`title =`) spellings, with or without quotes around the key. A document
    /// whose frontmatter declares a title satisfies MD041's title requirement.
    fn frontmatter_declares_title(lines: &[String]) -> bool {
        lines.iter().any(|line| {
            let rest = line.trim_start();
            let rest = rest.strip_prefix('"').unwrap_or(rest);
            let Some(after_key) = rest.strip_prefix("title") else {
                return false;
            };
            let after_key = after_key.strip_prefix('"').unwrap_or(after_key);
            after_key.trim_start().starts_with([':', '='])
        })
    }
}

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

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

    fn description(&self) -> &'static str {
        "First line in file should be a top level heading"
    }

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

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

        if document.lines.is_empty() {
            return Ok(violations);
        }

        // YAML frontmatter is not Markdown content. If the document declares a
        // title there, the title requirement is already satisfied; otherwise skip
        // past the frontmatter block so its delimiters and keys are not linted as
        // the first heading.
        let mut scan_start = 0;
        if let Some((_, end)) = document.frontmatter_line_range() {
            if Self::frontmatter_declares_title(&document.lines[..end]) {
                return Ok(violations);
            }
            scan_start = end;
        }

        // Find the first non-empty, non-HTML-comment line
        let mut first_content_line_idx = None;
        let mut in_comment = false;
        for (idx, line) in document.lines.iter().enumerate().skip(scan_start) {
            let trimmed = line.trim();

            if trimmed.is_empty() {
                continue;
            }

            // Track multi-line HTML comments
            if in_comment {
                if trimmed.contains("-->") {
                    in_comment = false;
                }
                continue;
            }

            if trimmed.starts_with("<!--") {
                if !trimmed.contains("-->") {
                    // Multi-line comment opening
                    in_comment = true;
                }
                // Single-line comment (contains both <!-- and -->), skip it
                continue;
            }

            first_content_line_idx = Some(idx);
            break;
        }

        let Some(first_idx) = first_content_line_idx else {
            // File is empty or only whitespace
            return Ok(violations);
        };

        let first_line = &document.lines[first_idx];

        // Check if first line is an ATX H1
        if self.is_top_level_heading(first_line) {
            return Ok(violations);
        }

        // Check for setext-style H1 (current line + next line with =)
        if first_idx + 1 < document.lines.len() {
            let second_line = &document.lines[first_idx + 1];
            if self.could_be_setext_heading(first_line) && self.is_setext_h1_underline(second_line)
            {
                return Ok(violations);
            }
        }

        // If we get here, the first line is not a top-level heading
        violations.push(self.create_violation(
            "First line in file should be a top level heading".to_string(),
            first_idx + 1, // Convert to 1-based line number
            1,
            Severity::Warning,
        ));

        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_md041_atx_h1_valid() {
        let content = "# Top Level Heading\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_atx_h1_no_space_valid() {
        let content = "#Top Level Heading\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_setext_h1_valid() {
        let content = "Top Level Heading\n=================\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_h2_invalid() {
        let content = "## Second Level Heading\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rule_id, "MD041");
        assert_eq!(violations[0].line, 1);
        assert!(
            violations[0]
                .message
                .contains("First line in file should be a top level heading")
        );
    }

    #[test]
    fn test_md041_paragraph_first_invalid() {
        let content = "This is a paragraph.\n\n# Heading comes later";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_setext_h2_invalid() {
        let content = "Second Level Heading\n--------------------\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_empty_file_valid() {
        let content = "";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_whitespace_only_valid() {
        let content = "   \n\n\t\n   ";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_leading_whitespace_valid() {
        let content = "\n\n# Top Level Heading\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_leading_whitespace_invalid() {
        let content = "\n\nSome paragraph first.\n\n# Heading later";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 3); // Line with "Some paragraph first."
    }

    #[test]
    fn test_md041_bare_hash_invalid() {
        let content = "#\n\nSome content here.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_code_block_first_invalid() {
        let content = "```\ncode block\n```\n\n# Heading later";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_list_first_invalid() {
        let content = "- List item\n- Another item\n\n# Heading later";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_setext_incomplete_invalid() {
        let content = "Potential heading\n\nBut no underline.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 1);
    }

    #[test]
    fn test_md041_html_comment_before_heading_valid() {
        // Regression test for issue #392
        let content = "<!-- mdbook-lint-disable MD029 -->\n# Chapter 1\n\nSome content.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(
            violations.len(),
            0,
            "Should skip HTML comments when finding first content line"
        );
    }

    #[test]
    fn test_md041_multiline_comment_before_heading_valid() {
        let content = "<!--\nThis is a multi-line\ncomment\n-->\n# Chapter 1\n\nSome content.";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_frontmatter_then_heading_valid() {
        // Regression for issue #406: YAML frontmatter must not be linted as the
        // first heading; the body's H1 satisfies the rule.
        let content =
            "---\ntitle: My Document\nstatus: accepted\n---\n\n# My Document\n\nBody text.\n";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_frontmatter_title_satisfies_rule() {
        // Issue #406: a frontmatter `title:` field satisfies the title requirement
        // even when the body does not open with an H1.
        let content = "---\ntitle: My Document\nstatus: accepted\n---\n\nJust a paragraph.\n";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md041_frontmatter_without_title_still_checks_body() {
        // Without a title field, the body must still open with an H1; the
        // violation is reported at the real body line, not the frontmatter fence.
        let content = "---\nstatus: accepted\n---\n\nJust a paragraph, no heading.\n";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 5);
    }

    #[test]
    fn test_md041_comment_then_paragraph_invalid() {
        let content = "<!-- comment -->\nNot a heading.\n\n# Heading later";
        let document = create_test_document(content);
        let rule = MD041;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 2);
    }
}