quickmark-core 1.1.0

Lightning-fast Markdown/CommonMark linter core library with tree-sitter based parsing
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
use serde::Deserialize;
use std::rc::Rc;

use tree_sitter::Node;

use crate::{
    linter::{range_from_tree_sitter, Context, RuleLinter, RuleViolation},
    rules::{Rule, RuleType},
};

// MD025-specific configuration types
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub struct MD025SingleH1Table {
    #[serde(default)]
    pub level: u8,
    #[serde(default)]
    pub front_matter_title: String,
}

impl Default for MD025SingleH1Table {
    fn default() -> Self {
        Self {
            level: 1,
            front_matter_title: r"^\s*title\s*[:=]".to_string(),
        }
    }
}

#[derive(Debug)]
struct HeadingInfo {
    content: String,
    range: tree_sitter::Range,
    is_first_content_heading: bool,
}

pub(crate) struct MD025Linter {
    context: Rc<Context>,
    violations: Vec<RuleViolation>,
    matching_headings: Vec<HeadingInfo>,
    has_front_matter_title: Option<bool>,
}

impl MD025Linter {
    pub fn new(context: Rc<Context>) -> Self {
        Self {
            context,
            violations: Vec::new(),
            matching_headings: Vec::new(),
            has_front_matter_title: None,
        }
    }

    fn extract_heading_level(&self, node: &Node) -> u8 {
        match node.kind() {
            "atx_heading" => {
                for i in 0..node.child_count() {
                    let child = node.child(i).unwrap();
                    if child.kind().starts_with("atx_h") && child.kind().ends_with("_marker") {
                        return child.kind().chars().nth(5).unwrap().to_digit(10).unwrap() as u8;
                    }
                }
                1 // fallback
            }
            "setext_heading" => {
                for i in 0..node.child_count() {
                    let child = node.child(i).unwrap();
                    if child.kind() == "setext_h1_underline" {
                        return 1;
                    } else if child.kind() == "setext_h2_underline" {
                        return 2;
                    }
                }
                1 // fallback
            }
            _ => 1,
        }
    }

    fn extract_heading_content(&self, node: &Node) -> String {
        let source = self.context.get_document_content();
        let start_byte = node.start_byte();
        let end_byte = node.end_byte();
        let full_text = &source[start_byte..end_byte];

        match node.kind() {
            "atx_heading" => full_text
                .trim_start_matches('#')
                .trim()
                .trim_end_matches('#')
                .trim()
                .to_string(),
            "setext_heading" => {
                if let Some(line) = full_text.lines().next() {
                    line.trim().to_string()
                } else {
                    String::new()
                }
            }
            _ => String::new(),
        }
    }

    fn check_front_matter_has_title(&mut self) -> bool {
        if self.has_front_matter_title.is_some() {
            return self.has_front_matter_title.unwrap();
        }

        let config = &self.context.config.linters.settings.single_h1;
        if config.front_matter_title.is_empty() {
            self.has_front_matter_title = Some(false);
            return false; // Front matter checking disabled
        }

        let content = self.context.get_document_content();

        // Check if document starts with front matter (---)
        if !content.starts_with("---") {
            self.has_front_matter_title = Some(false);
            return false;
        }

        // Find the end of front matter
        let lines: Vec<&str> = content.lines().collect();
        if lines.len() < 3 {
            self.has_front_matter_title = Some(false);
            return false; // Too short to have valid front matter
        }

        let mut end_index = None;
        for (i, line) in lines.iter().enumerate().skip(1) {
            if line.trim() == "---" {
                end_index = Some(i);
                break;
            }
        }

        let end_index = match end_index {
            Some(idx) => idx,
            None => {
                self.has_front_matter_title = Some(false);
                return false; // No closing front matter delimiter
            }
        };

        // Check for title in front matter
        let front_matter_lines = &lines[1..end_index];
        let title_regex = regex::Regex::new(&config.front_matter_title).unwrap_or_else(|_| {
            // Fallback to default regex if invalid
            regex::Regex::new(r"^\s*title\s*[:=]").unwrap()
        });

        let has_title = front_matter_lines
            .iter()
            .any(|line| title_regex.is_match(line));
        self.has_front_matter_title = Some(has_title);
        has_title
    }

    fn is_first_content_heading(&self, node: &Node) -> bool {
        let content = self.context.get_document_content();
        let node_start_byte = node.start_byte();
        let target_level = self.context.config.linters.settings.single_h1.level;

        // Get text before this heading
        let text_before = &content[..node_start_byte];

        // Check if there's only whitespace, comments, front matter,
        // or headings above the target level before this heading
        let mut in_front_matter = false;

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

            if trimmed == "---" {
                if !in_front_matter {
                    in_front_matter = true;
                    continue;
                } else {
                    // End of front matter
                    in_front_matter = false;
                    continue;
                }
            }

            if in_front_matter {
                continue; // Skip front matter content
            }

            // Check if this line is a heading above target level
            if trimmed.starts_with('#') {
                let heading_level = trimmed.chars().take_while(|&c| c == '#').count() as u8;
                if heading_level < target_level {
                    continue; // Ignore headings above target level
                }
                if heading_level == target_level {
                    // Found another heading at target level before this one
                    return false;
                }
                // Headings below target level count as content
                return false;
            }

            // Check for setext headings
            if trimmed.chars().all(|c| c == '=' || c == '-') && !trimmed.is_empty() {
                // This might be a setext underline - need to check previous line for content
                // For simplicity, we'll consider all setext underlines as potential headings
                let setext_level = if trimmed.chars().all(|c| c == '=') {
                    1
                } else {
                    2
                };
                if setext_level < target_level {
                    continue; // Ignore headings above target level
                }
                return false; // Setext heading at or below target level
            }

            // After front matter is closed or if no front matter
            if !trimmed.is_empty() && !trimmed.starts_with("<!--") && !trimmed.starts_with("-->") {
                // Found non-whitespace, non-comment, non-heading content before heading
                return false;
            }
        }

        true
    }
}

impl RuleLinter for MD025Linter {
    fn feed(&mut self, node: &Node) {
        if node.kind() == "atx_heading" || node.kind() == "setext_heading" {
            let level = self.extract_heading_level(node);
            let config = &self.context.config.linters.settings.single_h1;

            if level != config.level {
                return; // Not the level we're checking
            }

            let content = self.extract_heading_content(node);
            let is_first_content = self.is_first_content_heading(node);

            // Store the heading info for processing in finalize
            self.matching_headings.push(HeadingInfo {
                content,
                range: node.range(),
                is_first_content_heading: is_first_content,
            });
        }
    }

    fn finalize(&mut self) -> Vec<RuleViolation> {
        if self.matching_headings.is_empty() {
            return Vec::new();
        }

        let has_front_matter_title = self.check_front_matter_has_title();

        // Determine if we have a "top-level heading" scenario
        let has_top_level_heading = has_front_matter_title
            || (!self.matching_headings.is_empty()
                && self.matching_headings[0].is_first_content_heading);

        if has_top_level_heading {
            // Determine which headings are violations
            let start_index = if has_front_matter_title { 0 } else { 1 };

            for heading in self.matching_headings.iter().skip(start_index) {
                self.violations.push(RuleViolation::new(
                    &MD025,
                    format!("{} [{}]", MD025.description, heading.content),
                    self.context.file_path.clone(),
                    range_from_tree_sitter(&heading.range),
                ));
            }
        }

        std::mem::take(&mut self.violations)
    }
}

pub const MD025: Rule = Rule {
    id: "MD025",
    alias: "single-h1",
    tags: &["headings"],
    description: "Multiple top-level headings in the same document",
    rule_type: RuleType::Document,
    required_nodes: &["atx_heading", "setext_heading"],
    new_linter: |context| Box::new(MD025Linter::new(context)),
};

#[cfg(test)]
mod test {
    use std::path::PathBuf;

    use crate::config::{LintersSettingsTable, MD025SingleH1Table, RuleSeverity};
    use crate::linter::MultiRuleLinter;
    use crate::test_utils::test_helpers::test_config_with_settings;

    fn test_config(level: u8, front_matter_title: &str) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("single-h1", RuleSeverity::Error)],
            LintersSettingsTable {
                single_h1: MD025SingleH1Table {
                    level,
                    front_matter_title: front_matter_title.to_string(),
                },
                ..Default::default()
            },
        )
    }

    #[test]
    fn test_single_h1_no_violations() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "# Title

Some content

## Section 1

Content

## Section 2

More content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_multiple_h1_violations() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "# First Title

Some content

# Second Title

More content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Second Title"));
    }

    #[test]
    fn test_front_matter_with_title_and_h1() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "---
layout: post
title: \"Welcome to Jekyll!\"
date: 2015-11-17 16:16:01 -0600
---
# Top level heading

Content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Top level heading"));
    }

    #[test]
    fn test_front_matter_without_title() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "---
layout: post
author: John Doe
date: 2015-11-17 16:16:01 -0600
---
# Title

Content

## Section";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_custom_level() {
        let config = test_config(2, r"^\s*title\s*[:=]");
        let input = "# Title (level 1, should be ignored)

## First H2

Content

## Second H2

More content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Second H2"));
    }

    #[test]
    fn test_setext_headings() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "First Title
===========

Content

Second Title
============

More content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Second Title"));
    }

    #[test]
    fn test_mixed_heading_styles() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "First Title
===========

Content

# Second Title

More content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Second Title"));
    }

    #[test]
    fn test_h1_not_first_content() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "Some intro paragraph

# Title

Content

# Another Title";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        // No violations because first H1 is not the first content
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_front_matter_title_disabled() {
        let config = test_config(1, ""); // Empty pattern disables front matter checking
        let input = "---
title: \"Welcome to Jekyll!\"
---
# Top level heading

Content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_custom_front_matter_title_regex() {
        let config = test_config(1, r"^\s*heading\s*:");
        let input = "---
layout: post
heading: \"My Custom Title\"
---
# Top level heading

Content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Top level heading"));
    }

    #[test]
    fn test_comments_before_heading() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "<!-- This is a comment -->

# Title

Content

# Another Title";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 1);
        assert!(violations[0].message().contains("Another Title"));
    }

    #[test]
    fn test_empty_document() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_only_lower_level_headings() {
        let config = test_config(1, r"^\s*title\s*[:=]");
        let input = "## Section 1

Content

### Subsection

More content

## Section 2

Final content";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0);
    }
}