mdbook-lint 0.2.0

A fast markdown linter for mdBook
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
//! MD050: Strong style consistency
//!
//! This rule checks that strong emphasis markers (bold text) are used consistently throughout the document.

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

/// Rule to check strong emphasis style consistency
pub struct MD050 {
    /// Preferred strong emphasis style
    style: StrongStyle,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StrongStyle {
    /// Use double asterisk (**text**)
    Asterisk,
    /// Use double underscore (__text__)
    Underscore,
    /// Detect from first usage in document
    Consistent,
}

impl MD050 {
    /// Create a new MD050 rule with consistent style detection
    pub fn new() -> Self {
        Self {
            style: StrongStyle::Consistent,
        }
    }

    /// Create a new MD050 rule with specific style preference
    #[allow(dead_code)]
    pub fn with_style(style: StrongStyle) -> Self {
        Self { style }
    }

    /// Find strong emphasis markers in a line and check for style violations
    fn check_line_strong(
        &self,
        line: &str,
        line_number: usize,
        expected_style: Option<StrongStyle>,
    ) -> (Vec<Violation>, Option<StrongStyle>) {
        let mut violations = Vec::new();
        let mut detected_style = expected_style;

        // Find strong emphasis markers - look for double ** or __
        let chars: Vec<char> = line.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            if (chars[i] == '*' || chars[i] == '_')
                && i + 1 < chars.len()
                && chars[i + 1] == chars[i]
            {
                let marker = chars[i];

                // Look for closing marker pair
                if let Some(end_pos) = self.find_closing_strong_marker(&chars, i + 2, marker) {
                    let current_style = if marker == '*' {
                        StrongStyle::Asterisk
                    } else {
                        StrongStyle::Underscore
                    };

                    // Establish or check style consistency
                    if let Some(ref expected) = detected_style {
                        if *expected != current_style {
                            let expected_marker = if *expected == StrongStyle::Asterisk {
                                "**"
                            } else {
                                "__"
                            };
                            let found_marker = if marker == '*' { "**" } else { "__" };
                            violations.push(self.create_violation(
                                format!(
                                    "Strong emphasis style inconsistent - expected '{expected_marker}' but found '{found_marker}'"
                                ),
                                line_number,
                                i + 1, // Convert to 1-based column
                                Severity::Warning,
                            ));
                        }
                    } else {
                        // First strong emphasis found - establish the style
                        detected_style = Some(current_style);
                    }

                    i = end_pos + 2;
                } else {
                    i += 2;
                }
            } else {
                i += 1;
            }
        }

        (violations, detected_style)
    }

    /// Find the closing strong emphasis marker pair
    fn find_closing_strong_marker(
        &self,
        chars: &[char],
        start: usize,
        marker: char,
    ) -> Option<usize> {
        let mut i = start;

        while i + 1 < chars.len() {
            if chars[i] == marker && chars[i + 1] == marker {
                return Some(i);
            }
            i += 1;
        }

        None
    }

    /// Get code block ranges to exclude from checking
    fn get_code_block_ranges(&self, lines: &[&str]) -> Vec<bool> {
        let mut in_code_block = vec![false; lines.len()];
        let mut in_fenced_block = false;

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Check for fenced code blocks
            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
                in_fenced_block = !in_fenced_block;
                in_code_block[i] = true;
                continue;
            }

            if in_fenced_block {
                in_code_block[i] = true;
                continue;
            }
        }

        in_code_block
    }
}

impl Default for MD050 {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn name(&self) -> &'static str {
        "strong-style"
    }

    fn description(&self) -> &'static str {
        "Strong emphasis style should be consistent"
    }

    fn metadata(&self) -> RuleMetadata {
        RuleMetadata::stable(RuleCategory::Formatting).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();
        let lines: Vec<&str> = document.content.lines().collect();
        let in_code_block = self.get_code_block_ranges(&lines);

        let mut expected_style = match self.style {
            StrongStyle::Asterisk => Some(StrongStyle::Asterisk),
            StrongStyle::Underscore => Some(StrongStyle::Underscore),
            StrongStyle::Consistent => None, // Detect from first usage
        };

        for (line_number, line) in lines.iter().enumerate() {
            let line_number = line_number + 1;

            // Skip lines inside code blocks
            if in_code_block[line_number - 1] {
                continue;
            }

            let (line_violations, detected_style) =
                self.check_line_strong(line, line_number, expected_style);
            violations.extend(line_violations);

            // Update expected style if we detected one
            if expected_style.is_none() && detected_style.is_some() {
                expected_style = detected_style;
            }
        }

        Ok(violations)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::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_md050_consistent_asterisk_style() {
        let content = r#"This has **strong** and more **bold text** here.

Another paragraph with **more strong** text.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md050_consistent_underscore_style() {
        let content = r#"This has __strong__ and more __bold text__ here.

Another paragraph with __more strong__ text.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md050_mixed_styles_violation() {
        let content = r#"This has **strong** and more __bold text__ here.

Another paragraph with **more strong** text.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rule_id, "MD050");
        assert_eq!(violations[0].line, 1);
        assert!(
            violations[0]
                .message
                .contains("expected '**' but found '__'")
        );
    }

    #[test]
    fn test_md050_preferred_asterisk_style() {
        let content = r#"This has __strong__ text.
"#;

        let document = create_test_document(content);
        let rule = MD050::with_style(StrongStyle::Asterisk);
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("expected '**' but found '__'")
        );
    }

    #[test]
    fn test_md050_preferred_underscore_style() {
        let content = r#"This has **strong** text.
"#;

        let document = create_test_document(content);
        let rule = MD050::with_style(StrongStyle::Underscore);
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("expected '__' but found '**'")
        );
    }

    #[test]
    fn test_md050_emphasis_ignored() {
        let content = r#"This has *italic text* and __strong text__.

More *italic* and __strong__ here.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0); // All strong uses __, should be consistent
    }

    #[test]
    fn test_md050_mixed_emphasis_and_strong() {
        let content = r#"This has *italic* and **strong** and __also strong__.

More text here.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("expected '**' but found '__'")
        );
    }

    #[test]
    fn test_md050_code_blocks_ignored() {
        let content = r#"This has **strong** text.

```
Code with **asterisks** and __underscores__ should be ignored.
```

This has __different style__ which should trigger violation.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 7);
    }

    #[test]
    fn test_md050_inline_code_spans() {
        let content = r#"This has **strong** and `code with **asterisks**` text.

More **strong** text here.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        // Code spans are not excluded by this rule (they're handled at line level)
        // but the strong emphasis should still be consistent
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md050_no_strong() {
        let content = r#"This document has no strong emphasis at all.

Just regular text with *italic* formatting.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_md050_multiple_violations() {
        let content = r#"Start with **strong** text.

Then switch to __different style__.

Back to **original style**.

And __different again__.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 2); // Line 3 and line 7 violations
        assert_eq!(violations[0].line, 3);
        assert_eq!(violations[1].line, 7);
    }

    #[test]
    fn test_md050_unclosed_strong() {
        let content = r#"This has **unclosed strong and __closed strong__.

More text here.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        // Only the properly closed strong should be checked
        assert_eq!(violations.len(), 0); // __closed strong__ is the only valid strong, so no violation
    }

    #[test]
    fn test_md050_nested_formatting() {
        let content = r#"This has **strong with *nested italic* text**.

More __strong__ text.
"#;

        let document = create_test_document(content);
        let rule = MD050::new();
        let violations = rule.check(&document).unwrap();
        assert_eq!(violations.len(), 1);
        assert!(
            violations[0]
                .message
                .contains("expected '**' but found '__'")
        );
    }
}