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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! MDBOOK010: Missing or invalid preprocessor configuration
//!
//! This rule checks for invalid preprocessor directives in mdBook files.
//! Preprocessors like mermaid, katex, and others require specific syntax.

use mdbook_lint_core::error::Result;
use mdbook_lint_core::rule::{Rule, RuleCategory, RuleMetadata};
use mdbook_lint_core::{
    Document,
    violation::{Severity, Violation},
};
use regex::Regex;

/// Rule to check for invalid preprocessor configuration
pub struct MDBOOK010;

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

    fn name(&self) -> &'static str {
        "preprocessor-validation"
    }

    fn description(&self) -> &'static str {
        "Missing or invalid preprocessor configuration"
    }

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

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

        // Check for common preprocessor patterns
        self.check_mermaid_blocks(document, &mut violations);
        self.check_katex_blocks(document, &mut violations);
        self.check_admonish_blocks(document, &mut violations);

        Ok(violations)
    }
}

impl MDBOOK010 {
    /// Check for invalid mermaid blocks
    fn check_mermaid_blocks(&self, document: &Document, violations: &mut Vec<Violation>) {
        let _mermaid_re = Regex::new(r"```mermaid\s*\n([\s\S]*?)```").unwrap();

        for (line_num, line) in document.lines.iter().enumerate() {
            if line.trim() == "```mermaid" {
                // Check if the block is empty
                if line_num + 1 < document.lines.len() {
                    let next_line = &document.lines[line_num + 1];
                    if next_line.trim() == "```" {
                        violations.push(self.create_violation(
                            "Empty mermaid block detected".to_string(),
                            line_num + 1,
                            1,
                            Severity::Warning,
                        ));
                    }
                }
            }

            // Check for common mermaid syntax errors
            if line.contains("```mermaid") && !line.trim().eq("```mermaid") {
                violations.push(self.create_violation(
                    "Mermaid blocks should start with '```mermaid' on its own line".to_string(),
                    line_num + 1,
                    1,
                    Severity::Error,
                ));
            }
        }
    }

    /// Check for invalid KaTeX blocks
    fn check_katex_blocks(&self, document: &Document, violations: &mut Vec<Violation>) {
        // Check for inline math
        let _inline_math_re = Regex::new(r"\$([^$\n]+)\$").unwrap();
        // Check for display math
        let _display_math_re = Regex::new(r"\$\$([^$]+)\$\$").unwrap();

        let mut in_code_block = false;

        for (line_num, line) in document.lines.iter().enumerate() {
            // Track code block state - skip all processing inside code blocks
            if line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~") {
                in_code_block = !in_code_block;
                continue;
            }

            // Skip all processing if we're inside a code block
            if in_code_block {
                continue;
            }

            // Skip lines that look like shell prompts (start with $ followed by space or common commands)
            let trimmed = line.trim();
            if trimmed.starts_with("$ ") || trimmed == "$" {
                // This looks like a shell prompt, not a math block
                continue;
            }

            // Blank out dollars that cannot be delimiters (inline code spans,
            // literal table markers) before any delimiter analysis. Byte offsets
            // are preserved, so columns below still refer to the original line.
            let line = &Self::mask_literal_dollars(line);

            // Check for unclosed inline math - but exclude standalone $ at start of line
            // Only count unescaped $ signs (escaped \$ should not count as delimiters)
            let dollar_count = Self::count_unescaped_dollars(line);
            if dollar_count % 2 != 0 && !line.contains("$$") {
                // Additional check: only flag if there's actual math content
                // A single $ at the start followed by non-math content is likely a shell prompt
                // Also skip template variable syntax like ${var}
                if !Self::is_likely_shell_prompt(line) && !Self::is_template_variable_line(line) {
                    violations.push(self.create_violation(
                        "Unclosed inline math block (odd number of $ signs)".to_string(),
                        line_num + 1,
                        1,
                        Severity::Error,
                    ));
                }
            }

            // Check for empty math blocks (still only outside code blocks)
            if line.contains("$$$$") {
                violations.push(self.create_violation(
                    "Empty display math block detected".to_string(),
                    line_num + 1,
                    line.find("$$$$").unwrap() + 1,
                    Severity::Warning,
                ));
            }

            if line.contains("$ $") {
                violations.push(self.create_violation(
                    "Empty inline math block detected".to_string(),
                    line_num + 1,
                    line.find("$ $").unwrap() + 1,
                    Severity::Warning,
                ));
            }
        }
    }

    /// Helper function to detect if a line is likely a shell prompt or contains currency
    fn is_likely_shell_prompt(line: &str) -> bool {
        let trimmed = line.trim();

        // Common shell prompt patterns
        if trimmed.starts_with("$ ") || trimmed == "$" {
            return true;
        }

        // Check for PowerShell prompts
        if trimmed.starts_with("> ") || trimmed == ">" {
            return true;
        }

        // Check for numbered prompts like "1$" or similar
        if trimmed.starts_with(|c: char| c.is_ascii_digit()) && trimmed.contains("$") {
            return true;
        }

        // Check for currency amounts like $100, $50.00, $1,000, etc.
        // Only skip if ALL dollar signs on the line are currency (not mixed with math)
        if Self::is_currency_only_line(line) {
            return true;
        }

        // If line has a single $ and looks like a command (contains common shell keywords)
        if line.matches('$').count() == 1 {
            let after_dollar = line.split('$').nth(1).unwrap_or("");
            let first_word = after_dollar.split_whitespace().next().unwrap_or("");

            // Common shell commands/keywords
            let shell_keywords = [
                "cd", "ls", "pwd", "echo", "mkdir", "rm", "cp", "mv", "cat", "grep", "find",
                "curl", "wget", "git", "npm", "cargo", "rustc", "python", "ruby", "node", "java",
                "gcc", "make", "sudo", "apt", "yum", "brew", "docker", "kubectl", "rustup", "pip",
                "gem", "yarn", "pnpm", "deno", "./", "../", "~/", "/", "\\", ".", "..", "export",
                "source", "bash",
            ];

            if shell_keywords.iter().any(|&kw| first_word.starts_with(kw)) {
                return true;
            }
        }

        false
    }

    /// Check if a line contains only currency amounts with $ (no math)
    /// This is strict - ensures that ALL $ signs on the line are currency amounts
    /// like $100, $50.00, $1,000 (not mixed with math like $x$)
    fn is_currency_only_line(line: &str) -> bool {
        let chars: Vec<char> = line.chars().collect();
        let mut all_dollars_are_currency = true;
        let mut has_dollar = false;

        for i in 0..chars.len() {
            if chars[i] == '$' {
                has_dollar = true;
                // Check if this $ is followed immediately by a digit
                if i + 1 >= chars.len() || !chars[i + 1].is_ascii_digit() {
                    all_dollars_are_currency = false;
                    break;
                }
            }
        }

        has_dollar && all_dollars_are_currency
    }

    /// Check if a line contains template variable syntax like ${var}, ${{var}}, etc.
    /// These are not math blocks and should be skipped.
    fn is_template_variable_line(line: &str) -> bool {
        let chars: Vec<char> = line.chars().collect();

        for i in 0..chars.len() {
            if chars[i] == '$' {
                // Check if this $ is followed by { (template variable syntax)
                if i + 1 < chars.len() && chars[i + 1] == '{' {
                    return true;
                }
            }
        }
        false
    }

    /// Marker substituted for a `$` that cannot be a math delimiter.
    ///
    /// One byte wide, like `$` itself, so masking never shifts byte offsets and
    /// columns reported from a masked line still refer to the original. Chosen
    /// as a control character so masking cannot synthesize a `$ $` sequence.
    const MASKED_DOLLAR: char = '\u{1}';

    /// Blank out `$` characters that appear in contexts where a dollar sign is
    /// literal rather than a KaTeX delimiter.
    ///
    /// MDBOOK010 counts delimiters per source line. Fenced code blocks are
    /// already skipped by the caller, but inline code spans and literal table
    /// markers are not, so `` `$PATH` `` and a `$$$` price tier were read as
    /// math. Everything other than `$` is left untouched.
    fn mask_literal_dollars(line: &str) -> String {
        let mut chars: Vec<char> = line.chars().collect();
        Self::mask_code_spans(&mut chars);
        Self::mask_dollar_only_table_cells(&mut chars);
        chars.into_iter().collect()
    }

    /// Mask dollars inside inline code spans.
    ///
    /// Follows the CommonMark rule that a code span is delimited by backtick
    /// runs of equal length. An opening run with no matching closing run is
    /// literal text and is left alone.
    fn mask_code_spans(chars: &mut [char]) {
        let len = chars.len();
        let mut i = 0;

        while i < len {
            if chars[i] != '`' {
                i += 1;
                continue;
            }

            let open_start = i;
            while i < len && chars[i] == '`' {
                i += 1;
            }
            let run = i - open_start;

            // Look for a closing run of exactly the same length.
            let mut j = i;
            let mut close = None;
            while j < len {
                if chars[j] == '`' {
                    let start = j;
                    while j < len && chars[j] == '`' {
                        j += 1;
                    }
                    if j - start == run {
                        close = Some((start, j));
                        break;
                    }
                } else {
                    j += 1;
                }
            }

            // An unmatched opener is not a code span, so leave it alone and keep
            // scanning from just after it.
            if let Some((content_end, after_close)) = close {
                for c in chars.iter_mut().take(content_end).skip(i) {
                    if *c == '$' {
                        *c = Self::MASKED_DOLLAR;
                    }
                }
                i = after_close;
            }
        }
    }

    /// Mask table cells whose entire content is dollar signs.
    ///
    /// A price tier written as `$`, `$$`, or `$$$` is a literal marker, not a
    /// math span. Only applies to lines that look like table rows.
    fn mask_dollar_only_table_cells(chars: &mut [char]) {
        let first_visible = chars.iter().position(|c| !c.is_whitespace());
        if first_visible.is_none_or(|i| chars[i] != '|') {
            return;
        }

        let mut cell_start = 0;
        for i in 0..=chars.len() {
            if i != chars.len() && chars[i] != '|' {
                continue;
            }

            let cell: String = chars[cell_start..i].iter().collect();
            let trimmed = cell.trim();
            if !trimmed.is_empty() && trimmed.chars().all(|c| c == '$') {
                for c in chars.iter_mut().take(i).skip(cell_start) {
                    if *c == '$' {
                        *c = Self::MASKED_DOLLAR;
                    }
                }
            }
            cell_start = i + 1;
        }
    }

    /// Count only unescaped dollar signs in a line.
    /// A dollar sign is escaped if it's preceded by an odd number of backslashes.
    /// Examples:
    /// - `$` -> unescaped (count it)
    /// - `\$` -> escaped (don't count)
    /// - `\\$` -> unescaped (the backslash is escaped, so $ is a delimiter)
    /// - `\\\$` -> escaped (two escaped backslashes + escaped dollar)
    fn count_unescaped_dollars(line: &str) -> usize {
        let chars: Vec<char> = line.chars().collect();
        let mut count = 0;

        for i in 0..chars.len() {
            if chars[i] == '$' {
                // Count preceding backslashes
                let mut backslash_count = 0;
                let mut j = i as isize - 1;
                while j >= 0 && chars[j as usize] == '\\' {
                    backslash_count += 1;
                    j -= 1;
                }

                // Even number of backslashes (including 0) means $ is unescaped
                if backslash_count % 2 == 0 {
                    count += 1;
                }
            }
        }
        count
    }

    /// Check for invalid admonish blocks
    fn check_admonish_blocks(&self, document: &Document, violations: &mut Vec<Violation>) {
        let admonish_re = Regex::new(r"```admonish\s+(\w+)(.*)").unwrap();
        let valid_types = [
            "note",
            "tip",
            "info",
            "warning",
            "danger",
            "important",
            "caution",
            "bug",
            "example",
            "quote",
        ];

        for (line_num, line) in document.lines.iter().enumerate() {
            if line.starts_with("```admonish") {
                if let Some(captures) = admonish_re.captures(line) {
                    if let Some(admonish_type) = captures.get(1) {
                        let type_str = admonish_type.as_str();
                        if !valid_types.contains(&type_str) {
                            violations.push(self.create_violation(
                                format!(
                                    "Invalid admonish type '{}'. Valid types are: {}",
                                    type_str,
                                    valid_types.join(", ")
                                ),
                                line_num + 1,
                                admonish_type.start() + 1,
                                Severity::Error,
                            ));
                        }
                    }
                } else if line.trim() == "```admonish" {
                    violations.push(self.create_violation(
                        "Admonish block missing type. Use format: ```admonish <type>".to_string(),
                        line_num + 1,
                        1,
                        Severity::Error,
                    ));
                }
            }
        }
    }
}

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

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

Here's a mermaid diagram:

```mermaid
graph TD
    A --> B
```

Some math: $x = y^2$

Display math:
$$
E = mc^2
$$

```admonish note
This is a note.
```
"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

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

    #[test]
    fn test_empty_mermaid_block() {
        let content = r#"```mermaid
```"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Empty mermaid block"));
    }

    #[test]
    fn test_invalid_mermaid_syntax() {
        let content = "```mermaid with extra text";
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("should start with '```mermaid' on its own line")
        );
    }

    #[test]
    fn test_unclosed_inline_math() {
        let content = "This is $unclosed math";
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Unclosed inline math"));
    }

    #[test]
    fn test_empty_math_blocks() {
        let content = r#"Empty inline: $ $
Empty display: $$$$"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 2);
        assert!(violations[0].message.contains("Empty inline math"));
        assert!(violations[1].message.contains("Empty display math"));
    }

    #[test]
    fn test_invalid_admonish_type() {
        let content = "```admonish invalid";
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("Invalid admonish type 'invalid'")
        );
    }

    #[test]
    fn test_missing_admonish_type() {
        let content = "```admonish";
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("Admonish block missing type")
        );
    }

    #[test]
    fn test_shell_prompts_not_math() {
        let content = r#"# Shell Commands

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
$ cargo build --release
$ rustc main.rs
$ echo $PATH

Some actual math: $x = y^2$
But this is unclosed math: $x = y"#;

        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        // Should only flag the last line as unclosed math, not the shell commands
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Unclosed inline math"));
        assert_eq!(violations[0].line, 9); // The "But this is unclosed math" line
    }

    #[test]
    fn test_powershell_prompts() {
        let content = r#"> rustc main.rs
> echo %PATH%
> dir /B"#;

        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

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

    #[test]
    fn test_dollar_signs_in_code_blocks() {
        let content = r#"# Shell Examples

```bash
echo "Database status: $status"
if [ "$status" = "active" ]; then
    echo "System is $status"
    export PATH=$PATH:/usr/local/bin
fi

# Variables with dollar signs
name=$1
echo "Hello $name"
result=$(echo $value | grep pattern)
```

Regular text with math: $x = y^2$

~~~sh
# Another code block style
echo $HOME
echo $USER
~~~

More text after code block"#;

        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        // Should not flag any violations for dollar signs in code blocks
        assert_eq!(
            violations.len(),
            0,
            "Dollar signs in code blocks should be ignored"
        );
    }

    /// Lint `content` with MDBOOK010 and return the violation messages.
    fn violations_for(content: &str) -> Vec<String> {
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        MDBOOK010
            .check(&doc)
            .unwrap()
            .into_iter()
            .map(|v| v.message)
            .collect()
    }

    #[test]
    fn test_dollar_signs_in_inline_code_not_flagged() {
        // Issue #464: shell variables in code spans were counted as math
        // delimiters, producing error-severity false positives.
        for content in [
            "Use `$PATH` to find executables.",
            "Set `$BUZZ_ACP_AGENT_COMMAND` to the agent binary.",
            "Run `mdbook-lint lint $PWD/docs` from the repository root.",
            "Compare `$HOME` with `$PWD` before continuing.",
        ] {
            assert_eq!(
                violations_for(content),
                Vec::<String>::new(),
                "inline code should not be treated as math: {content}"
            );
        }
    }

    #[test]
    fn test_dollar_only_table_cells_not_flagged() {
        // A price tier written as $, $$, or $$$ is a literal marker.
        let content = r#"# Providers

| Provider | Price |
|----------|-------|
| Alpha    | $     |
| Beta     | $$    |
| Gamma    | $$$   |
"#;
        assert_eq!(violations_for(content), Vec::<String>::new());
    }

    #[test]
    fn test_real_math_still_validated() {
        // Balanced inline and display math remain clean.
        assert_eq!(
            violations_for("The value $x$ satisfies $$y = x^2$$ exactly."),
            Vec::<String>::new()
        );

        // Genuinely unclosed math in prose is still reported.
        let unclosed = violations_for("The value $x = y is never closed.");
        assert_eq!(unclosed.len(), 1, "got: {unclosed:?}");
        assert!(unclosed[0].contains("Unclosed inline math"));

        // A code span must not mask an unclosed delimiter outside it.
        let mixed = violations_for("Use `$PATH`, and then $x = y is unclosed.");
        assert_eq!(mixed.len(), 1, "got: {mixed:?}");
        assert!(mixed[0].contains("Unclosed inline math"));
    }

    #[test]
    fn test_mask_code_spans_handles_backtick_runs() {
        // Equal-length backtick runs delimit a code span, so the inner dollars
        // are literal.
        let masked = MDBOOK010::mask_literal_dollars("a ``$x$`` b");
        assert!(!masked.contains('$'), "got: {masked:?}");

        // A shorter run inside a longer span does not close it.
        let masked = MDBOOK010::mask_literal_dollars("``a ` $x$ `` b");
        assert!(!masked.contains('$'), "got: {masked:?}");

        // An unmatched backtick is literal text, so dollars after it still count.
        let masked = MDBOOK010::mask_literal_dollars("a ` b $x$ c");
        assert_eq!(masked.matches('$').count(), 2, "got: {masked:?}");
    }

    #[test]
    fn test_masking_preserves_byte_offsets() {
        // Columns are reported from the masked line, so masking must not shift
        // byte offsets even when the line contains multi-byte characters.
        for line in [
            "naïve `$PATH` and $x$",
            "| café | $$$ |",
            "emoji 🎉 with `$VAR` after",
        ] {
            assert_eq!(
                MDBOOK010::mask_literal_dollars(line).len(),
                line.len(),
                "byte length changed for: {line}"
            );
        }
    }

    #[test]
    fn test_unclosed_math_inside_code_span_not_flagged() {
        // An odd dollar count that lives entirely inside a code span is not math.
        assert_eq!(
            violations_for("Print the prompt with `echo \"$\"` and continue."),
            Vec::<String>::new()
        );
    }

    #[test]
    fn test_mixed_code_and_math() {
        let content = r#"# Mixed Content

Some inline math: $x = y^2$

```bash
# Shell code with dollars
echo $PATH
export VAR=$VALUE
```

Unclosed math: $x = y

```python
# Python code (no dollars but testing code block boundaries)
print("Hello")
```

Valid display math:
$$
E = mc^2
$$"#;

        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        // Should only flag the unclosed math outside code blocks
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message.contains("Unclosed inline math"));
        assert_eq!(violations[0].line, 11); // Line with "Unclosed math: $x = y"
    }

    #[test]
    fn test_escaped_dollar_in_katex() {
        // Issue #320: $(\$)$ should be valid (escaped $ inside math)
        let content = r#"KaTeX with escaped dollar: $(\$)$"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(
            violations.len(),
            0,
            "Escaped $ inside math block should not trigger unclosed math error"
        );
    }

    #[test]
    fn test_multiple_escaped_dollars() {
        let content = r#"Multiple escaped: $\$\$\$$"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(
            violations.len(),
            0,
            "Multiple escaped $ should not trigger error"
        );
    }

    #[test]
    fn test_escaped_and_unescaped_mix() {
        let content = r#"Mixed: $x\$y\$z$"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(violations.len(), 0, "Mixed escaped/unescaped should work");
    }

    #[test]
    fn test_double_backslash_before_dollar() {
        // \\$ means the backslash is escaped, so $ is a delimiter
        let content = r#"Double backslash: $\\$10$"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        // This has 3 unescaped $ signs (the \\ doesn't escape the $)
        // So it should trigger unclosed math
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn test_truly_unclosed_with_escaped_dollars() {
        // Truly unclosed: only one unescaped $
        let content = r#"Unclosed: $x\$y"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(
            violations.len(),
            1,
            "Truly unclosed math should still error"
        );
        assert!(violations[0].message.contains("Unclosed inline math"));
    }

    #[test]
    fn test_count_unescaped_dollars() {
        // Direct tests of the helper function
        assert_eq!(MDBOOK010::count_unescaped_dollars("$x$"), 2);
        assert_eq!(MDBOOK010::count_unescaped_dollars(r"$(\$)$"), 2);
        assert_eq!(MDBOOK010::count_unescaped_dollars(r"\$"), 0);
        assert_eq!(MDBOOK010::count_unescaped_dollars(r"\\$"), 1);
        assert_eq!(MDBOOK010::count_unescaped_dollars(r"\\\$"), 0);
        assert_eq!(MDBOOK010::count_unescaped_dollars(r"$\$\$$"), 2);
        assert_eq!(MDBOOK010::count_unescaped_dollars("no dollars here"), 0);
    }

    #[test]
    fn test_currency_amounts_not_flagged() {
        // Currency amounts like $100 should not be flagged as unclosed math
        let content = r#"# Pricing

The price is $100 for this item.
You can also pay $50.00 or even $1,000.
Prices range from $10 to $500.

Regular math still works: $x = y^2$
"#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

        assert_eq!(
            violations.len(),
            0,
            "Currency amounts should not be flagged as unclosed math"
        );
    }

    #[test]
    fn test_currency_in_sentences() {
        let content = r#"The item costs $100 and shipping is $20."#;
        let doc = Document::new(content.to_string(), PathBuf::from("chapter.md")).unwrap();
        let rule = MDBOOK010;
        let violations = rule.check(&doc).unwrap();

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

    #[test]
    fn test_is_currency_only_line() {
        // Lines with only currency amounts
        assert!(MDBOOK010::is_currency_only_line("The price is $100"));
        assert!(MDBOOK010::is_currency_only_line("$50.00"));
        assert!(MDBOOK010::is_currency_only_line("$1,000"));
        assert!(MDBOOK010::is_currency_only_line("Costs $10 to $500"));

        // Lines with math (not currency only)
        assert!(!MDBOOK010::is_currency_only_line("$x = y$")); // This is math, not currency
        assert!(!MDBOOK010::is_currency_only_line("$ command")); // Shell prompt
        assert!(!MDBOOK010::is_currency_only_line("no dollars")); // No dollar signs
        assert!(!MDBOOK010::is_currency_only_line("$100 and $x$")); // Mixed currency and math
    }
}