rumdl 0.3.0

A fast Markdown linter and formatter written in Rust
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
use regex::Regex;
use std::collections::HashMap;
use std::sync::LazyLock;

// Front matter field pattern
static FRONT_MATTER_FIELD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^([^:]+):\s*(.*)$").unwrap());

// TOML field pattern
static TOML_FIELD_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"^([^=]+)\s*=\s*"?([^"]*)"?$"#).unwrap());

/// Represents the type of front matter found in a document
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum FrontMatterType {
    /// YAML front matter (---)
    Yaml,
    /// TOML front matter (+++)
    Toml,
    /// JSON front matter ({})
    Json,
    /// Malformed front matter
    Malformed,
    /// No front matter
    None,
}

/// Utility functions for detecting and handling front matter in Markdown documents
pub struct FrontMatterUtils;

impl FrontMatterUtils {
    /// Check if a content contains front matter with a specific field
    pub fn has_front_matter_field(content: &str, field_prefix: &str) -> bool {
        let field_name = field_prefix.trim_end_matches(':');
        Self::get_front_matter_field_value(content, field_name).is_some()
    }

    /// Get the value of a specific front matter field
    pub fn get_front_matter_field_value<'a>(content: &'a str, field_name: &str) -> Option<&'a str> {
        content.lines().nth(2)?;

        let front_matter_type = Self::detect_front_matter_type(content);
        if front_matter_type == FrontMatterType::None {
            return None;
        }

        let front_matter = Self::extract_front_matter(content);
        for line in front_matter {
            let line = line.trim();
            match front_matter_type {
                FrontMatterType::Toml => {
                    // Handle TOML-style fields (key = value)
                    if let Some(captures) = TOML_FIELD_PATTERN.captures(line) {
                        let key = captures.get(1).unwrap().as_str().trim();
                        if key == field_name {
                            let value = captures.get(2).unwrap().as_str();
                            return Some(value);
                        }
                    }
                }
                _ => {
                    // Handle YAML/JSON-style fields (key: value)
                    if let Some(captures) = FRONT_MATTER_FIELD.captures(line) {
                        let mut key = captures.get(1).unwrap().as_str().trim();

                        // Strip quotes from the key if present (for JSON-style fields in any format)
                        if key.starts_with('"') && key.ends_with('"') && key.len() >= 2 {
                            key = &key[1..key.len() - 1];
                        }

                        if key == field_name {
                            let value = captures.get(2).unwrap().as_str().trim();
                            // Strip quotes if present
                            if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
                                return Some(&value[1..value.len() - 1]);
                            }
                            return Some(value);
                        }
                    }
                }
            }
        }

        None
    }

    /// Extract all front matter fields as a HashMap
    pub fn extract_front_matter_fields(content: &str) -> HashMap<String, String> {
        let mut fields = HashMap::new();

        let front_matter_type = Self::detect_front_matter_type(content);
        if front_matter_type == FrontMatterType::None {
            return fields;
        }

        let front_matter = Self::extract_front_matter(content);
        let mut current_prefix = String::new();
        let mut indent_level = 0;

        for line in front_matter {
            let line_indent = line.chars().take_while(|c| c.is_whitespace()).count();
            let line = line.trim();

            // Handle indentation changes for nested fields
            match line_indent.cmp(&indent_level) {
                std::cmp::Ordering::Greater => {
                    // Going deeper
                    indent_level = line_indent;
                }
                std::cmp::Ordering::Less => {
                    // Going back up
                    indent_level = line_indent;
                    // Remove last nested level from prefix
                    if let Some(last_dot) = current_prefix.rfind('.') {
                        current_prefix.truncate(last_dot);
                    } else {
                        current_prefix.clear();
                    }
                }
                std::cmp::Ordering::Equal => {}
            }

            match front_matter_type {
                FrontMatterType::Toml => {
                    // Handle TOML-style fields
                    if let Some(captures) = TOML_FIELD_PATTERN.captures(line) {
                        let key = captures.get(1).unwrap().as_str().trim();
                        let value = captures.get(2).unwrap().as_str();
                        let full_key = if current_prefix.is_empty() {
                            key.to_string()
                        } else {
                            format!("{current_prefix}.{key}")
                        };
                        fields.insert(full_key, value.to_string());
                    }
                }
                _ => {
                    // Handle YAML/JSON-style fields
                    if let Some(captures) = FRONT_MATTER_FIELD.captures(line) {
                        let mut key = captures.get(1).unwrap().as_str().trim();
                        let value = captures.get(2).unwrap().as_str().trim();

                        // Strip quotes from the key if present (for JSON-style fields in any format)
                        if key.starts_with('"') && key.ends_with('"') && key.len() >= 2 {
                            key = &key[1..key.len() - 1];
                        }

                        if let Some(stripped) = key.strip_suffix(':') {
                            // This is a nested field marker
                            if current_prefix.is_empty() {
                                current_prefix = stripped.to_string();
                            } else {
                                current_prefix = format!("{current_prefix}.{stripped}");
                            }
                        } else {
                            // This is a field with a value
                            let full_key = if current_prefix.is_empty() {
                                key.to_string()
                            } else {
                                format!("{current_prefix}.{key}")
                            };
                            // Strip quotes if present
                            let value = value
                                .strip_prefix('"')
                                .and_then(|v| v.strip_suffix('"'))
                                .unwrap_or(value);
                            fields.insert(full_key, value.to_string());
                        }
                    }
                }
            }
        }

        fields
    }

    /// Extract the front matter content as a vector of lines.
    pub fn extract_front_matter(content: &str) -> Vec<&str> {
        if content.lines().nth(2).is_none() {
            return Vec::new();
        }
        Self::front_matter_boundary(content)
            .map_or_else(Vec::new, |(_, end)| content.lines().skip(1).take(end - 2).collect())
    }

    /// Detect the type of front matter in the content.
    pub fn detect_front_matter_type(content: &str) -> FrontMatterType {
        Self::front_matter_boundary(content).map_or(FrontMatterType::None, |(kind, _)| kind)
    }

    /// Get the line number where front matter ends (or 0 if no front matter).
    ///
    /// `LintContext::new` caches this result; downstream users must read
    /// `ctx.front_matter_end_line()` instead (enforced in clippy.toml).
    pub fn get_front_matter_end_line(content: &str) -> usize {
        if content.lines().nth(2).is_none() {
            return 0;
        }
        Self::front_matter_boundary(content).map_or(0, |(_, end)| end)
    }

    /// Only the first line can open front matter. Stop at its closing delimiter
    /// instead of splitting or scanning the Markdown body on every lookup.
    pub(crate) fn front_matter_boundary(content: &str) -> Option<(FrontMatterType, usize)> {
        let mut lines = content.lines();
        let first = lines.next()?;
        let kind = if Self::is_delimiter(first, "---") {
            FrontMatterType::Yaml
        } else if Self::is_delimiter(first, "+++") {
            FrontMatterType::Toml
        } else if Self::is_delimiter(first, "{") {
            FrontMatterType::Json
        } else if Self::is_delimiter(first, "- --") || Self::is_delimiter(first, "-- -") {
            FrontMatterType::Malformed
        } else {
            return None;
        };
        for (index, line) in lines.enumerate() {
            let closes = match kind {
                FrontMatterType::Yaml => Self::is_delimiter(line, "---"),
                FrontMatterType::Toml => Self::is_delimiter(line, "+++"),
                FrontMatterType::Json => Self::is_delimiter(line, "}"),
                FrontMatterType::Malformed => Self::is_delimiter(line, "- --") || Self::is_delimiter(line, "-- -"),
                FrontMatterType::None => unreachable!(),
            };
            if closes {
                return Some((kind, index + 2));
            }
        }
        None
    }

    fn is_delimiter(line: &str, marker: &str) -> bool {
        line.strip_prefix(marker)
            .is_some_and(|tail| tail.chars().all(char::is_whitespace))
    }

    /// Byte position of `separator` outside a leading quoted key: a quoted
    /// key (`"og:title":`, `"a=b" =`) may contain the separator character,
    /// so the search starts after the closing quote.
    pub fn separator_pos_outside_quoted_key(line: &str, separator: char) -> Option<usize> {
        let after_quote = if let Some(rest) = line.strip_prefix('"') {
            rest.find('"').map(|i| i + 2)
        } else if let Some(rest) = line.strip_prefix('\'') {
            rest.find('\'').map(|i| i + 2)
        } else {
            None
        };
        match after_quote {
            Some(start) => line[start..].find(separator).map(|i| start + i),
            None => line.find(separator),
        }
    }

    /// The top-level key a raw TOML key expression defines. A quoted key is
    /// atomic (`"a.b"` defines `a.b`); otherwise the root of a dotted path
    /// (`params.seo` defines `params`).
    pub fn toml_root_key(raw: &str) -> &str {
        if let Some(rest) = raw.strip_prefix('"') {
            if let Some(end) = rest.find('"') {
                return &rest[..end];
            }
        } else if let Some(rest) = raw.strip_prefix('\'')
            && let Some(end) = rest.find('\'')
        {
            return &rest[..end];
        }
        raw.split('.').next().unwrap_or(raw).trim()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn streaming_boundaries_match_legacy_unicode_delimiters() {
        let markers = [
            ("---", FrontMatterType::Yaml),
            ("+++", FrontMatterType::Toml),
            ("{", FrontMatterType::Json),
            ("- --", FrontMatterType::Malformed),
            ("-- -", FrontMatterType::Malformed),
        ];
        for (marker, kind) in markers {
            let legacy_open = Regex::new(&format!(r"^{}\s*$", regex::escape(marker))).unwrap();
            for suffix in [
                "", " ", "\t", "\r", "\u{0085}", "\u{00a0}", "\u{2028}", "\u{200b}", "\u{feff}", "x", " -",
            ] {
                let opening = format!("{marker}{suffix}");
                assert_eq!(
                    FrontMatterUtils::is_delimiter(&opening, marker),
                    legacy_open.is_match(&opening)
                );
                for closing in ["---", "+++", "}", "- --", "-- -", "none"] {
                    for tail in ["", "\n", "\nbody\n", "\r\nbody\r\n"] {
                        let source = format!("{opening}\nkey: value\n{closing}{tail}");
                        let expected = if legacy_open.is_match(&opening)
                            && match kind {
                                FrontMatterType::Yaml => closing == "---",
                                FrontMatterType::Toml => closing == "+++",
                                FrontMatterType::Json => closing == "}",
                                FrontMatterType::Malformed => matches!(closing, "- --" | "-- -"),
                                FrontMatterType::None => false,
                            } {
                            kind
                        } else {
                            FrontMatterType::None
                        };
                        assert_eq!(
                            FrontMatterUtils::detect_front_matter_type(&source),
                            expected,
                            "{source:?}"
                        );
                        let fields = FrontMatterUtils::extract_front_matter(&source);
                        assert_eq!(
                            fields,
                            if expected == FrontMatterType::None {
                                vec![]
                            } else {
                                vec!["key: value"]
                            },
                            "{source:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn test_front_matter_type_enum() {
        assert_eq!(FrontMatterType::Yaml, FrontMatterType::Yaml);
        assert_eq!(FrontMatterType::Toml, FrontMatterType::Toml);
        assert_eq!(FrontMatterType::Json, FrontMatterType::Json);
        assert_eq!(FrontMatterType::Malformed, FrontMatterType::Malformed);
        assert_eq!(FrontMatterType::None, FrontMatterType::None);
        assert_ne!(FrontMatterType::Yaml, FrontMatterType::Toml);
    }

    #[test]
    fn test_detect_front_matter_type() {
        // YAML front matter
        let yaml_content = "---\ntitle: Test\n---\nContent";
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(yaml_content),
            FrontMatterType::Yaml
        );

        // TOML front matter
        let toml_content = "+++\ntitle = \"Test\"\n+++\nContent";
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(toml_content),
            FrontMatterType::Toml
        );

        // JSON front matter
        let json_content = "{\n\"title\": \"Test\"\n}\nContent";
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(json_content),
            FrontMatterType::Json
        );

        // Malformed front matter
        let malformed1 = "- --\ntitle: Test\n- --\nContent";
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(malformed1),
            FrontMatterType::Malformed
        );

        let malformed2 = "-- -\ntitle: Test\n-- -\nContent";
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(malformed2),
            FrontMatterType::Malformed
        );

        // No front matter
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type("# Regular content"),
            FrontMatterType::None
        );
        assert_eq!(FrontMatterUtils::detect_front_matter_type(""), FrontMatterType::None);

        // Incomplete front matter (no closing marker)
        assert_eq!(
            FrontMatterUtils::detect_front_matter_type("---\ntitle: Test"),
            FrontMatterType::None
        );
    }

    #[test]
    fn test_extract_front_matter() {
        let content = "---\ntitle: Test\nauthor: Me\n---\nContent";
        let front_matter = FrontMatterUtils::extract_front_matter(content);

        assert_eq!(front_matter.len(), 2);
        assert_eq!(front_matter[0], "title: Test");
        assert_eq!(front_matter[1], "author: Me");

        // No front matter
        let no_fm = FrontMatterUtils::extract_front_matter("Regular content");
        assert!(no_fm.is_empty());

        // Too short content
        let short = FrontMatterUtils::extract_front_matter("---\n---");
        assert!(short.is_empty());
    }

    #[test]
    fn test_has_front_matter_field() {
        let content = "---\ntitle: Test\nauthor: Me\n---\nContent";

        assert!(FrontMatterUtils::has_front_matter_field(content, "title"));
        assert!(FrontMatterUtils::has_front_matter_field(content, "author"));
        assert!(!FrontMatterUtils::has_front_matter_field(content, "date"));

        // No front matter
        assert!(!FrontMatterUtils::has_front_matter_field("Regular content", "title"));

        // Too short content
        assert!(!FrontMatterUtils::has_front_matter_field("--", "title"));
    }

    #[test]
    fn test_get_front_matter_field_value() {
        // YAML front matter
        let yaml_content = "---\ntitle: Test Title\nauthor: \"John Doe\"\n---\nContent";
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(yaml_content, "title"),
            Some("Test Title")
        );
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(yaml_content, "author"),
            Some("John Doe")
        );
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(yaml_content, "nonexistent"),
            None
        );

        // TOML front matter
        let toml_content = "+++\ntitle = \"Test Title\"\nauthor = \"John Doe\"\n+++\nContent";
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(toml_content, "title"),
            Some("Test Title")
        );
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(toml_content, "author"),
            Some("John Doe")
        );

        // JSON-style fields in YAML front matter - keys should not include quotes
        let json_style_yaml = "---\n\"title\": \"Test Title\"\n---\nContent";
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(json_style_yaml, "title"),
            Some("Test Title")
        );

        // Actual JSON front matter
        let json_fm = "{\n\"title\": \"Test Title\"\n}\nContent";
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(json_fm, "title"),
            Some("Test Title")
        );

        // No front matter
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value("Regular content", "title"),
            None
        );

        // Too short content
        assert_eq!(FrontMatterUtils::get_front_matter_field_value("--", "title"), None);
    }

    #[test]
    fn test_extract_front_matter_fields() {
        // Simple YAML front matter
        let yaml_content = "---\ntitle: Test\nauthor: Me\n---\nContent";
        let fields = FrontMatterUtils::extract_front_matter_fields(yaml_content);

        assert_eq!(fields.get("title"), Some(&"Test".to_string()));
        assert_eq!(fields.get("author"), Some(&"Me".to_string()));

        // TOML front matter
        let toml_content = "+++\ntitle = \"Test\"\nauthor = \"Me\"\n+++\nContent";
        let toml_fields = FrontMatterUtils::extract_front_matter_fields(toml_content);

        assert_eq!(toml_fields.get("title"), Some(&"Test".to_string()));
        assert_eq!(toml_fields.get("author"), Some(&"Me".to_string()));

        // No front matter
        let no_fields = FrontMatterUtils::extract_front_matter_fields("Regular content");
        assert!(no_fields.is_empty());
    }

    #[test]
    #[allow(clippy::disallowed_methods)] // unit test of the scanner itself
    fn test_get_front_matter_end_line() {
        let content = "---\ntitle: Test\n---\nContent";
        assert_eq!(FrontMatterUtils::get_front_matter_end_line(content), 3);

        // TOML
        let toml_content = "+++\ntitle = \"Test\"\n+++\nContent";
        assert_eq!(FrontMatterUtils::get_front_matter_end_line(toml_content), 3);

        // No front matter
        assert_eq!(FrontMatterUtils::get_front_matter_end_line("Regular content"), 0);

        // Too short
        assert_eq!(FrontMatterUtils::get_front_matter_end_line("--"), 0);
    }

    #[test]
    fn test_nested_yaml_fields() {
        let content = "---
title: Test
author:
  name: John Doe
  email: john@example.com
---
Content";

        let fields = FrontMatterUtils::extract_front_matter_fields(content);

        // Note: The current implementation doesn't fully handle nested YAML
        // This test documents the current behavior
        assert!(fields.contains_key("title"));
        // Nested fields handling would need enhancement
    }

    #[test]
    #[allow(clippy::disallowed_methods)] // unit test of the scanner itself
    fn test_edge_cases() {
        // Empty content
        assert_eq!(FrontMatterUtils::detect_front_matter_type(""), FrontMatterType::None);
        assert!(FrontMatterUtils::extract_front_matter("").is_empty());
        assert_eq!(FrontMatterUtils::get_front_matter_end_line(""), 0);

        // Only delimiters
        let only_delim = "---\n---";
        assert!(FrontMatterUtils::extract_front_matter(only_delim).is_empty());

        // Multiple front matter sections (only first should be detected)
        let multiple = "---\ntitle: First\n---\n---\ntitle: Second\n---";
        let fm_type = FrontMatterUtils::detect_front_matter_type(multiple);
        assert_eq!(fm_type, FrontMatterType::Yaml);
        let fields = FrontMatterUtils::extract_front_matter_fields(multiple);
        assert_eq!(fields.get("title"), Some(&"First".to_string()));
    }

    #[test]
    fn test_unicode_content() {
        let content = "---\ntitle: 你好世界\nauthor: José\n---\nContent";

        assert_eq!(
            FrontMatterUtils::detect_front_matter_type(content),
            FrontMatterType::Yaml
        );
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(content, "title"),
            Some("你好世界")
        );
        assert_eq!(
            FrontMatterUtils::get_front_matter_field_value(content, "author"),
            Some("José")
        );
    }
}