mdbook-lint-rulesets 0.14.4

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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! MDBOOK006: Validate internal cross-reference links between chapters
//!
//! This rule validates anchor fragments in internal links, ensuring they point to valid headings
//! in target files. It complements MDBOOK002 by focusing on the anchor validation that MDBOOK002 skips.

use comrak::nodes::{AstNode, NodeValue};
use mdbook_lint_core::rule::{AstRule, RuleCategory, RuleMetadata};
use mdbook_lint_core::{
    Document,
    violation::{Severity, Violation},
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::{fs, io};

/// MDBOOK006: Validate internal cross-reference links between chapters
///
/// This rule validates that internal links with anchor fragments point to valid headings
/// in the target files. It focuses specifically on cross-reference validation between
/// chapters, ensuring that `[text](file.md#heading)` links work correctly.
///
/// The rule:
/// - Only processes internal links with anchor fragments (e.g., `file.md#section`)
/// - Resolves target files relative to the current document
/// - Parses target files to extract heading anchors
/// - Validates that the anchor fragment exists in the target file
/// - Supports configurable anchor ID generation strategies
/// - Caches parsed files to improve performance on large books
///
/// Anchor ID Generation:
/// - Converts heading text to lowercase
/// - Replaces spaces and non-alphanumeric characters with hyphens
/// - Removes leading/trailing hyphens and consecutive hyphens
/// - Handles Unicode characters appropriately
#[derive(Default)]
pub struct MDBOOK006 {
    /// Cache of parsed heading anchors by file path to avoid re-parsing
    anchor_cache: Arc<RwLock<HashMap<PathBuf, Vec<String>>>>,
}

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

    fn name(&self) -> &'static str {
        "internal-cross-references"
    }

    fn description(&self) -> &'static str {
        "Internal cross-reference links must point to valid headings in target files"
    }

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

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

        // Walk through all nodes in the AST
        for node in ast.descendants() {
            if let NodeValue::Link(link) = &node.data.borrow().value {
                let url = &link.url;

                // Skip external links
                if is_external_link(url) {
                    continue;
                }

                // Only process links with anchor fragments
                if !url.contains('#') {
                    continue;
                }

                // Skip same-document anchors (start with #)
                if url.starts_with('#') {
                    continue;
                }

                // Validate the cross-reference link
                if let Some(violation) = self.validate_cross_reference(document, node, url)? {
                    violations.push(violation);
                }
            }
        }

        Ok(violations)
    }
}

impl MDBOOK006 {
    /// Validate a cross-reference link with anchor fragment
    fn validate_cross_reference<'a>(
        &self,
        document: &Document,
        node: &'a AstNode<'a>,
        url: &str,
    ) -> mdbook_lint_core::error::Result<Option<Violation>> {
        // Split URL into file path and anchor
        let parts: Vec<&str> = url.splitn(2, '#').collect();
        if parts.len() != 2 {
            return Ok(None); // No anchor fragment
        }

        let file_path = parts[0];
        let anchor = parts[1];

        // Skip empty file paths or anchors
        if file_path.is_empty() || anchor.is_empty() {
            return Ok(None);
        }

        // Resolve the target file path relative to current document
        let target_path = self.resolve_target_path(&document.path, file_path);

        // Check if target file exists
        if !target_path.exists() {
            // File doesn't exist - this should be caught by MDBOOK002, so we skip it
            return Ok(None);
        }

        // Get anchors from the target file
        let anchors = match self.get_file_anchors(&target_path)? {
            Some(anchors) => anchors,
            None => return Ok(None), // Couldn't parse file
        };

        // Check if the anchor exists in the target file
        if !anchors.contains(&anchor.to_string()) {
            let (line, column) = document.node_position(node).unwrap_or((1, 1));

            // Create helpful suggestion
            let suggestion = self.suggest_similar_anchor(anchor, &anchors);
            let message = if let Some(suggestion) = suggestion {
                format!(
                    "Cross-reference anchor '{anchor}' not found in '{file_path}'. Did you mean '{suggestion}'?"
                )
            } else {
                format!(
                    "Cross-reference anchor '{}' not found in '{}'. Available anchors: {}",
                    anchor,
                    file_path,
                    if anchors.is_empty() {
                        "none".to_string()
                    } else {
                        anchors
                            .iter()
                            .take(5)
                            .map(|s| format!("'{s}'"))
                            .collect::<Vec<_>>()
                            .join(", ")
                    }
                )
            };

            return Ok(Some(self.create_violation(
                message,
                line,
                column,
                Severity::Error,
            )));
        }

        Ok(None)
    }

    /// Resolve target file path relative to current document
    fn resolve_target_path(&self, current_doc_path: &Path, link_path: &str) -> PathBuf {
        let current_dir = current_doc_path.parent().unwrap_or(Path::new("."));

        if let Some(stripped) = link_path.strip_prefix("./") {
            // Explicit relative path: ./file.md
            current_dir.join(stripped)
        } else if link_path.starts_with("../") {
            // Parent directory path: ../file.md
            current_dir.join(link_path)
        } else if let Some(stripped) = link_path.strip_prefix('/') {
            // Absolute path (relative to project root)
            PathBuf::from(stripped)
        } else {
            // Implicit relative path: file.md
            current_dir.join(link_path)
        }
    }

    /// Get all heading anchors from a markdown file (with caching)
    fn get_file_anchors(&self, file_path: &Path) -> io::Result<Option<Vec<String>>> {
        let canonical_path = match file_path.canonicalize() {
            Ok(path) => path,
            Err(_) => file_path.to_path_buf(),
        };

        // Check cache first
        {
            if let Ok(cache) = self.anchor_cache.read()
                && let Some(anchors) = cache.get(&canonical_path)
            {
                return Ok(Some(anchors.clone()));
            }
        }

        // Read and parse the file
        let content = match fs::read_to_string(file_path) {
            Ok(content) => content,
            Err(_) => return Ok(None), // File couldn't be read
        };

        let anchors = self.extract_heading_anchors(&content);

        // Cache the result
        {
            if let Ok(mut cache) = self.anchor_cache.write() {
                cache.insert(canonical_path, anchors.clone());
            }
        }

        Ok(Some(anchors))
    }

    /// Extract heading anchors from markdown content
    fn extract_heading_anchors(&self, content: &str) -> Vec<String> {
        let mut anchors = Vec::new();

        for line in content.lines() {
            let line = line.trim();

            // Match ATX headings (# ## ### etc)
            if let Some(heading_text) = self.extract_atx_heading(line) {
                let anchor = self.generate_anchor_id(&heading_text);
                if !anchor.is_empty() {
                    anchors.push(anchor);
                }
            }
        }

        // TODO: Handle Setext headings (underlined with = or -)
        // This is less common in mdBook but could be added for completeness

        anchors
    }

    /// Extract heading text from ATX heading line
    fn extract_atx_heading(&self, line: &str) -> Option<String> {
        if !line.starts_with('#') {
            return None;
        }

        // Count leading hashes
        let hash_count = line.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            return None; // Invalid heading level
        }

        // Extract text after hashes
        let rest = &line[hash_count..];
        let text = if let Some(stripped) = rest.strip_prefix(' ') {
            stripped
        } else {
            rest
        };

        // Remove trailing hashes if present (closed ATX style)
        let text = text.trim_end_matches(['#', ' ']);

        if text.is_empty() {
            return None;
        }

        Some(text.to_string())
    }

    /// Generate anchor ID from heading text (matching mdBook 0.5.x behavior)
    ///
    /// The algorithm:
    /// - Alphanumeric characters become lowercase
    /// - Hyphens and underscores are preserved as-is
    /// - Whitespace becomes hyphens
    /// - Other characters (punctuation) are removed
    /// - Leading/trailing hyphens are trimmed
    /// - Consecutive hyphens are NOT collapsed (mdBook preserves them)
    fn generate_anchor_id(&self, heading_text: &str) -> String {
        let mut fragment = String::new();

        for ch in heading_text.chars() {
            if ch.is_alphanumeric() {
                fragment.extend(ch.to_lowercase());
            } else if ch == '-' || ch == '_' {
                // Preserve hyphens and underscores as-is
                fragment.push(ch);
            } else if ch.is_whitespace() {
                // Replace whitespace (spaces, tabs) with hyphens
                fragment.push('-');
            }
            // Other characters (punctuation like +, &, etc.) are removed/ignored
        }

        // Remove leading/trailing hyphens only
        // Do NOT consolidate multiple consecutive hyphens - mdBook preserves them
        fragment.trim_matches('-').to_string()
    }

    /// Suggest similar anchor that might be what the user intended
    fn suggest_similar_anchor(&self, target: &str, available: &[String]) -> Option<String> {
        if available.is_empty() {
            return None;
        }

        // Simple similarity: find anchor that contains target or vice versa
        for anchor in available {
            if anchor.contains(target) || target.contains(anchor) {
                return Some(anchor.clone());
            }
        }

        // If no substring match, return the first available anchor as a suggestion
        Some(available[0].clone())
    }
}

/// Check if a URL is an external link
fn is_external_link(url: &str) -> bool {
    url.starts_with("http://")
        || url.starts_with("https://")
        || url.starts_with("mailto:")
        || url.starts_with("ftp://")
        || url.starts_with("tel:")
}

#[cfg(test)]
mod tests {
    use super::*;
    use mdbook_lint_core::rule::Rule;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_document(
        content: &str,
        file_path: &Path,
    ) -> mdbook_lint_core::error::Result<Document> {
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(file_path, content)?;
        Document::new(content.to_string(), file_path.to_path_buf())
    }

    #[test]
    fn test_mdbook006_valid_cross_references() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create target file with headings
        let target_content = r#"# Chapter 2

## Overview

Some content here.

### Implementation Details

More details.
"#;
        create_test_document(target_content, &root.join("chapter2.md"))?;

        // Create source file with links to target
        let source_content = r#"# Chapter 1

See [Chapter 2](chapter2.md#chapter-2) for more info.

Check out the [overview](chapter2.md#overview) section.

The [implementation](chapter2.md#implementation-details) is complex.
"#;
        let source_path = root.join("chapter1.md");
        let doc = create_test_document(source_content, &source_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        assert_eq!(
            violations.len(),
            0,
            "Valid cross-references should have no violations"
        );
        Ok(())
    }

    #[test]
    fn test_mdbook006_invalid_anchor() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create target file with headings
        let target_content = r#"# Chapter 2

## Overview

Some content.
"#;
        create_test_document(target_content, &root.join("chapter2.md"))?;

        // Create source file with invalid anchor
        let source_content = r#"# Chapter 1

See [nonexistent section](chapter2.md#nonexistent).
"#;
        let source_path = root.join("chapter1.md");
        let doc = create_test_document(source_content, &source_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rule_id, "MDBOOK006");
        assert!(
            violations[0]
                .message
                .contains("anchor 'nonexistent' not found")
        );
        assert!(violations[0].message.contains("chapter2.md"));
        Ok(())
    }

    #[test]
    fn test_mdbook006_missing_target_file() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create source file linking to nonexistent file
        let source_content = r#"# Chapter 1

See [missing](nonexistent.md#section).
"#;
        let source_path = root.join("chapter1.md");
        let doc = create_test_document(source_content, &source_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        // Should not report violations for missing files (MDBOOK002's job)
        assert_eq!(violations.len(), 0);
        Ok(())
    }

    #[test]
    fn test_mdbook006_same_document_anchors() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create file with internal anchor link
        let content = r#"# Chapter 1

## Section A

See [Section B](#section-b) below.

## Section B

Content here.
"#;
        let file_path = root.join("chapter1.md");
        let doc = create_test_document(content, &file_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        // Should not process same-document anchors
        assert_eq!(violations.len(), 0);
        Ok(())
    }

    #[test]
    fn test_mdbook006_external_links() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create file with external links
        let content = r#"# Chapter 1

See [external](https://example.com#section).
"#;
        let file_path = root.join("chapter1.md");
        let doc = create_test_document(content, &file_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        // Should ignore external links
        assert_eq!(violations.len(), 0);
        Ok(())
    }

    #[test]
    fn test_mdbook006_no_anchor_links() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create target file
        create_test_document("# Target", &root.join("target.md"))?;

        // Create file with links without anchors
        let content = r#"# Chapter 1

See [target](target.md) for more.
"#;
        let file_path = root.join("chapter1.md");
        let doc = create_test_document(content, &file_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        // Should ignore links without anchors
        assert_eq!(violations.len(), 0);
        Ok(())
    }

    #[test]
    fn test_extract_atx_heading() {
        let rule = MDBOOK006::default();

        assert_eq!(
            rule.extract_atx_heading("# Heading"),
            Some("Heading".to_string())
        );
        assert_eq!(
            rule.extract_atx_heading("## Sub Heading"),
            Some("Sub Heading".to_string())
        );
        assert_eq!(
            rule.extract_atx_heading("### Deep Heading ###"),
            Some("Deep Heading".to_string())
        );
        assert_eq!(
            rule.extract_atx_heading("#No Space"),
            Some("No Space".to_string())
        );

        // Invalid cases
        assert_eq!(rule.extract_atx_heading("Not a heading"), None);
        assert_eq!(rule.extract_atx_heading(""), None);
        assert_eq!(rule.extract_atx_heading("#"), None);
        assert_eq!(rule.extract_atx_heading("# "), None);
    }

    #[test]
    fn test_generate_anchor_id() {
        let rule = MDBOOK006::default();

        assert_eq!(rule.generate_anchor_id("Simple Heading"), "simple-heading");
        // Punctuation is removed, not converted to hyphens
        assert_eq!(
            rule.generate_anchor_id("Complex: Heading with! Punctuation?"),
            "complex-heading-with-punctuation"
        );
        // Multiple spaces become multiple hyphens (not collapsed)
        assert_eq!(
            rule.generate_anchor_id("Multiple   Spaces"),
            "multiple---spaces"
        );
        assert_eq!(rule.generate_anchor_id("UPPER case"), "upper-case");
        assert_eq!(rule.generate_anchor_id("123 Numbers"), "123-numbers");
        assert_eq!(rule.generate_anchor_id(""), "");
        // Underscores and hyphens are preserved
        assert_eq!(rule.generate_anchor_id("some_variable"), "some_variable");
        assert_eq!(rule.generate_anchor_id("dash-test"), "dash-test");
        // Example with brackets and punctuation
        // [2026-01-28] - V5.1.2:
        // - Brackets [] are removed
        // - Space-hyphen-space becomes ---
        // - Dots are removed (not alphanumeric/hyphen/underscore)
        assert_eq!(
            rule.generate_anchor_id("[2026-01-28] - V5.1.2"),
            "2026-01-28---v512"
        );
    }

    #[test]
    fn test_issue_399_unicode_anchor_ids() {
        let rule = MDBOOK006::default();

        // Unicode/umlaut headings must use Unicode-aware lowercasing
        assert_eq!(rule.generate_anchor_id("Übungen"), "übungen");
        assert_eq!(rule.generate_anchor_id("Ärger"), "ärger");
        assert_eq!(rule.generate_anchor_id("Überprüfung"), "überprüfung");
    }

    #[test]
    fn test_mdbook006_nested_directories() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create nested target file
        let target_content = r#"# Deep Chapter

## Nested Section

Content here.
"#;
        create_test_document(target_content, &root.join("guide/deep.md"))?;

        // Create source file with relative link
        let source_content = r#"# Main Chapter

See [nested section](guide/deep.md#nested-section).
"#;
        let source_path = root.join("chapter.md");
        let doc = create_test_document(source_content, &source_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        assert_eq!(
            violations.len(),
            0,
            "Nested directory cross-references should work"
        );
        Ok(())
    }

    #[test]
    fn test_mdbook006_helpful_suggestions() -> mdbook_lint_core::error::Result<()> {
        let temp_dir = TempDir::new()?;
        let root = temp_dir.path();

        // Create target file with similar heading
        let target_content = r#"# Target

## Implementation Details

Content here.
"#;
        create_test_document(target_content, &root.join("target.md"))?;

        // Create source file with similar but wrong anchor
        let source_content = r#"# Source

See [details](target.md#implementation).
"#;
        let source_path = root.join("source.md");
        let doc = create_test_document(source_content, &source_path)?;

        let rule = MDBOOK006::default();
        let violations = rule.check(&doc)?;

        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Did you mean"));
        assert!(violations[0].message.contains("implementation-details"));
        Ok(())
    }
}