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
//! MD018: No space after hash on atx style heading
//!
//! This rule checks for missing space after hash characters in ATX style headings.

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, Severity, Violation},
};

use super::atx::trailing_hash_sequence;

/// Rule to check for missing space after hash on ATX style headings
pub struct MD018;

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

    fn name(&self) -> &'static str {
        "no-missing-space-atx"
    }

    fn description(&self) -> &'static str {
        "No space after hash on atx style heading"
    }

    fn metadata(&self) -> RuleMetadata {
        RuleMetadata::stable(RuleCategory::Structure).introduced_in("markdownlint 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();
        let mut in_fenced_code_block = false;
        let mut paragraph_continuation_lines = vec![false; document.lines.len() + 1];
        let frontmatter_offset = document.frontmatter_ast_offset(ast);

        for node in ast.descendants() {
            let data = node.data.borrow();
            if matches!(data.value, NodeValue::Paragraph) {
                let start_line = data.sourcepos.start.line + frontmatter_offset;
                let end_line = data.sourcepos.end.line + frontmatter_offset;
                if document
                    .lines
                    .get(start_line.saturating_sub(1))
                    .is_some_and(|line| line.trim_start().starts_with('#'))
                {
                    continue;
                }
                let continuation_start = start_line + 1;
                let continuation_end = end_line.min(document.lines.len());
                if continuation_start <= continuation_end {
                    paragraph_continuation_lines[continuation_start..=continuation_end].fill(true);
                }
            }
        }

        for (line_number, line) in document.lines.iter().enumerate() {
            let line_num = line_number + 1; // Convert to 1-based line numbers
            let trimmed = line.trim_start();

            // Track fenced code blocks to skip content inside them
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_fenced_code_block = !in_fenced_code_block;
                continue;
            }

            // Skip content inside code blocks (e.g., Rust attributes like #[no_mangle])
            if in_fenced_code_block {
                continue;
            }

            // A line beginning with a bare issue reference can be a lazy
            // continuation of an existing paragraph, not a malformed heading.
            if paragraph_continuation_lines[line_num] {
                continue;
            }

            // Check if this is an ATX-style heading (starts with #)
            // Skip shebang lines (#!/...)
            if trimmed.starts_with('#') && !trimmed.starts_with("#!") {
                // Find where the heading content starts
                let hash_count = trimmed.chars().take_while(|&c| c == '#').count();

                // Check if there's content after the hashes
                if trimmed.len() > hash_count {
                    let after_hashes = &trimmed[hash_count..];

                    // If there's content but no space, it's a violation
                    if !after_hashes.is_empty() && !after_hashes.starts_with(' ') {
                        let column = line.len() - line.trim_start().len() + hash_count + 1;

                        // Create fixed line by adding a space after the hashes
                        let indent = &line[..line.len() - trimmed.len()];
                        let hashes = &trimmed[..hash_count];
                        let fixed_line = if let Some((closing_start, closing_end)) =
                            trailing_hash_sequence(trimmed)
                        {
                            let content =
                                trimmed[hash_count..closing_start].trim_matches([' ', '\t']);
                            let closing_hashes = &trimmed[closing_start..closing_end];
                            format!("{indent}{hashes} {content} {closing_hashes}")
                        } else {
                            format!("{indent}{hashes} {}", after_hashes.trim())
                        };

                        let fix = Fix::line_replacement(
                            "Add space after hash on atx style heading",
                            fixed_line,
                            line_num,
                            line,
                            document.line_ending(line_num),
                        );

                        violations.push(self.create_violation_with_fix(
                            "No space after hash on atx style heading".to_string(),
                            line_num,
                            column,
                            Severity::Warning,
                            fix,
                        ));
                    }
                }
            }
        }

        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_md018_valid_headings() {
        let content = "# Heading 1\n## Heading 2\n### Heading 3";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_no_space_after_hash() {
        let content = "#Heading without space";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rule_id, "MD018");
        assert_eq!(violations[0].line, 1);
        assert_eq!(violations[0].column, 2);
        assert!(violations[0].message.contains("No space after hash"));
    }

    #[test]
    fn test_md018_multiple_violations() {
        let content = "#Heading 1\n##Heading 2\n### Valid heading\n####Another violation";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_indented_heading() {
        let content = "  #Indented heading without space";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].column, 4); // After the hash
    }

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

        // Empty headings (just hashes) should not trigger violations
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md018_closed_atx_style() {
        let content = "#Heading#\n##Another#Heading##";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_setext_headings_ignored() {
        let content = "Setext Heading\n==============\n\nAnother Setext\n--------------";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        // Setext headings should not trigger this rule
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md018_mixed_valid_invalid() {
        let content = "# Valid heading\n#Invalid heading\n## Another valid\n###Invalid again";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_issue_reference_in_lazy_paragraph_continuation() {
        let content = "Upstream fixed this in PR\n#472 and shipped it in 0.15.2.";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_issue_reference_mid_line() {
        let content = "Upstream fixed this in PR #472.";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_malformed_heading_in_lazy_paragraph_continuation() {
        let content = "Paragraph text\n#Heading";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_standalone_malformed_heading_after_blank_line() {
        let content = "Paragraph text\n\n#Heading\n\nMore text";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

    #[test]
    fn test_md018_code_blocks_ignored() {
        // Issue #274: Rust attributes like #[no_mangle] inside code blocks should NOT be flagged
        let content = r#"# Valid Heading

```rust
#[no_mangle]
pub extern "C" fn call_from_c() {
    println!("Just called a Rust function from C!");
}

#[unsafe(no_mangle)]
fn another_function() {}
```

## Another Valid Heading

~~~python
# This is a comment in Python
def foo():
    pass
~~~

#This should be flagged
"#;
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        // Only the last line "#This should be flagged" should trigger a violation
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("No space after hash"));
        assert_eq!(violations[0].line, 21);
    }

    #[test]
    fn test_md018_shebang_lines_ignored() {
        let content = "#!/bin/bash\n#This should trigger\n#!/usr/bin/env python3\n# This is valid";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        // Only the actual malformed heading should trigger, not shebangs
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 2);
        assert!(violations[0].message.contains("No space after hash"));
    }

    #[test]
    fn test_md018_fix_single_hash() {
        let content = "#Heading";
        let document = create_test_document(content);
        let rule = MD018;
        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.as_ref().unwrap(), "# Heading");
        assert_eq!(fix.description, "Add space after hash on atx style heading");
    }

    #[test]
    fn test_md018_fix_multiple_hashes() {
        let content = "##Heading Two\n###Heading Three";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

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

        // First heading
        let fix1 = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix1.replacement.as_ref().unwrap(), "## Heading Two\n");

        // Second heading
        let fix2 = violations[1].fix.as_ref().unwrap();
        assert_eq!(fix2.replacement.as_ref().unwrap(), "### Heading Three");
    }

    #[test]
    fn test_md018_fix_preserves_indentation() {
        let content = "  ##Indented Heading";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.replacement.as_ref().unwrap(), "  ## Indented Heading");
    }

    #[test]
    fn test_md018_fix_closed_atx() {
        let content = "##Closed Heading##";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.replacement.as_ref().unwrap(), "## Closed Heading ##");
    }

    #[test]
    fn test_md018_fix_position_accuracy() {
        let content = "###No Space";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.start.line, 1);
        assert_eq!(fix.start.column, 1);
        assert_eq!(fix.end.line, 1);
        assert_eq!(fix.end.column, content.chars().count() + 1);
    }

    #[test]
    fn test_md018_fix_with_trailing_whitespace() {
        let content = "#Heading with spaces   ";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 1);
        let fix = violations[0].fix.as_ref().unwrap();
        assert_eq!(fix.replacement.as_ref().unwrap(), "# Heading with spaces");
    }

    #[test]
    fn test_md018_fix_all_heading_levels() {
        let content = "#H1\n##H2\n###H3\n####H4\n#####H5\n######H6";
        let document = create_test_document(content);
        let rule = MD018;
        let violations = rule.check(&document).unwrap();

        assert_eq!(violations.len(), 6);
        assert_eq!(
            violations[0]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "# H1\n"
        );
        assert_eq!(
            violations[1]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "## H2\n"
        );
        assert_eq!(
            violations[2]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "### H3\n"
        );
        assert_eq!(
            violations[3]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "#### H4\n"
        );
        assert_eq!(
            violations[4]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "##### H5\n"
        );
        assert_eq!(
            violations[5]
                .fix
                .as_ref()
                .unwrap()
                .replacement
                .as_ref()
                .unwrap(),
            "###### H6"
        );
    }
}