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
use serde::Deserialize;
use std::rc::Rc;

use once_cell::sync::Lazy;
use regex::Regex;
use tree_sitter::Node;

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

use super::{Rule, RuleType};

// MD026-specific configuration types
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub struct MD026TrailingPunctuationTable {
    #[serde(default)]
    pub punctuation: String,
}

impl Default for MD026TrailingPunctuationTable {
    fn default() -> Self {
        Self {
            punctuation: ".,;:!。,;:!".to_string(),
        }
    }
}

impl MD026TrailingPunctuationTable {
    pub fn with_default_punctuation() -> Self {
        Self {
            punctuation: ".,;:!。,;:!".to_string(), // Default without '?' chars
        }
    }
}

pub(crate) struct MD026Linter {
    context: Rc<Context>,
    violations: Vec<RuleViolation>,
}

impl MD026Linter {
    pub fn new(context: Rc<Context>) -> Self {
        Self {
            context,
            violations: Vec::new(),
        }
    }

    fn extract_heading_text<'a>(&self, node: &Node, source: &'a str) -> &'a str {
        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(),
            "setext_heading" => {
                if let Some(line) = full_text.lines().next() {
                    line.trim()
                } else {
                    ""
                }
            }
            _ => "",
        }
    }

    fn check_trailing_punctuation(&mut self, node: &Node) {
        let source = self.context.get_document_content();
        let heading_text = self.extract_heading_text(node, &source);
        if heading_text.is_empty() {
            return;
        }

        let config = &self.context.config.linters.settings.trailing_punctuation;

        // Handle configuration: if punctuation is empty, the rule is effectively disabled
        let punctuation_chars = if config.punctuation.is_empty() {
            return; // Empty punctuation = rule disabled, allow all
        } else {
            &config.punctuation
        };

        // Check if the heading ends with any of the specified punctuation characters
        if let Some(trailing_char) = heading_text.chars().last() {
            if punctuation_chars.contains(trailing_char) {
                // Check if this is an HTML entity (ends with ;)
                if trailing_char == ';' && is_html_entity(heading_text) {
                    return; // Skip HTML entities
                }

                // Check if this is a gemoji code (ends with :)
                if trailing_char == ':' && is_gemoji_code(heading_text) {
                    return; // Skip gemoji codes
                }

                // Create a violation
                let range = tree_sitter::Range {
                    start_byte: 0, // Not used by range_from_tree_sitter
                    end_byte: 0,   // Not used by range_from_tree_sitter
                    start_point: tree_sitter::Point {
                        row: node.start_position().row,
                        column: 0,
                    },
                    end_point: tree_sitter::Point {
                        row: node.end_position().row,
                        column: node.end_position().column,
                    },
                };

                self.violations.push(RuleViolation::new(
                    &MD026,
                    format!("Punctuation: '{trailing_char}'"),
                    self.context.file_path.clone(),
                    range_from_tree_sitter(&range),
                ));
            }
        }
    }
}

impl RuleLinter for MD026Linter {
    fn feed(&mut self, node: &Node) {
        match node.kind() {
            "atx_heading" | "setext_heading" => self.check_trailing_punctuation(node),
            _ => {
                // Ignore other nodes
            }
        }
    }

    fn finalize(&mut self) -> Vec<RuleViolation> {
        std::mem::take(&mut self.violations)
    }
}

// Helper function to detect HTML entities
fn is_html_entity(text: &str) -> bool {
    static HTML_ENTITY_RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"&(?:[a-zA-Z\d]+|#\d+|#x[0-9a-fA-F]+);$").unwrap());
    HTML_ENTITY_RE.is_match(text.trim())
}

// Helper function to detect GitHub emoji codes (gemoji)
fn is_gemoji_code(text: &str) -> bool {
    static GEMOJI_RE: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r":(?:[abmovx]|[-+]1|100|1234|(?:1st|2nd|3rd)_place_medal|8ball|clock\d{1,4}|e-mail|non-potable_water|o2|t-rex|u5272|u5408|u55b6|u6307|u6708|u6709|u6e80|u7121|u7533|u7981|u7a7a|[a-z]{2,15}2?|[a-z]{1,14}(?:_[a-z\d]{1,16})+):$").unwrap()
    });
    GEMOJI_RE.is_match(text.trim())
}

pub const MD026: Rule = Rule {
    id: "MD026",
    alias: "no-trailing-punctuation",
    tags: &["headings"],
    description: "Trailing punctuation in heading",
    rule_type: RuleType::Token,
    required_nodes: &["atx_heading", "setext_heading"],
    new_linter: |context| Box::new(MD026Linter::new(context)),
};

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

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

    fn test_config(punctuation: &str) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("no-trailing-punctuation", RuleSeverity::Error)],
            LintersSettingsTable {
                trailing_punctuation: MD026TrailingPunctuationTable {
                    punctuation: punctuation.to_string(),
                },
                ..Default::default()
            },
        )
    }

    fn test_default_config() -> crate::config::QuickmarkConfig {
        test_config(".,;:!。,;:!")
    }

    #[test]
    fn test_atx_heading_with_period() {
        let config = test_default_config();
        let input = "# This is a heading.";

        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("Punctuation: '.'"));
    }

    #[test]
    fn test_atx_heading_with_exclamation() {
        let config = test_default_config();
        let input = "# This is a heading!";

        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("Punctuation: '!'"));
    }

    #[test]
    fn test_atx_heading_with_comma() {
        let config = test_default_config();
        let input = "## This is a heading,";

        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("Punctuation: ','"));
    }

    #[test]
    fn test_atx_heading_with_semicolon() {
        let config = test_default_config();
        let input = "### This is a heading;";

        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("Punctuation: ';'"));
    }

    #[test]
    fn test_atx_heading_with_colon() {
        let config = test_default_config();
        let input = "#### This is a heading:";

        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("Punctuation: ':'"));
    }

    #[test]
    fn test_atx_heading_with_question_mark_allowed() {
        let config = test_default_config();
        let input = "# This is a heading?";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0); // '?' is not in default punctuation
    }

    #[test]
    fn test_atx_heading_without_punctuation() {
        let config = test_default_config();
        let input = "# This is a heading";

        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_setext_heading_with_period() {
        let config = test_default_config();
        let input = "# Document\n\nThis is a heading.\n==================\n\nContent here";

        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("Punctuation: '.'"));
    }

    #[test]
    fn test_setext_heading_with_exclamation() {
        let config = test_default_config();
        let input = "# Document\n\nThis is a heading!\n------------------\n\nContent here";

        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("Punctuation: '!'"));
    }

    #[test]
    fn test_setext_heading_without_punctuation() {
        let config = test_default_config();
        let input = "# Document\n\nThis is a heading\n=================\n\nContent here";

        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_full_width_punctuation() {
        let config = test_default_config();
        let input = "# Heading with full-width period。";

        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("Punctuation: '。'"));
    }

    #[test]
    fn test_full_width_comma() {
        let config = test_default_config();
        let input = "# Heading with full-width comma,";

        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("Punctuation: ','"));
    }

    #[test]
    fn test_custom_punctuation() {
        let config = test_config(".,;:");
        let input = "# This heading has exclamation!";

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

    #[test]
    fn test_custom_punctuation_with_violation() {
        let config = test_config(".,;:");
        let input = "# This heading has period.";

        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("Punctuation: '.'"));
    }

    #[test]
    fn test_empty_punctuation_allows_all() {
        let config = test_config("");
        let input =
            "# This heading has period.\n## This heading has exclamation!\n### This has comma,";

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

    #[test]
    fn test_html_entity_ignored() {
        let config = test_default_config();
        let input = "# Copyright &copy;\n## Registered &reg;";

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

    #[test]
    fn test_numeric_html_entity_ignored() {
        let config = test_default_config();
        let input = "# Copyright &#169;\n## Registered &#174;";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0); // Numeric HTML entities should be ignored
    }

    #[test]
    fn test_hex_html_entity_ignored() {
        let config = test_default_config();
        let input = "# Copyright &#x000A9;\n## Registered &#xAE;";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(violations.len(), 0); // Hex HTML entities should be ignored
    }

    #[test]
    fn test_mixed_valid_and_invalid() {
        let config = test_default_config();
        let input =
            "# Good heading\n## Bad heading.\n### Another good heading\n#### Another bad heading!";

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

    #[test]
    fn test_atx_closed_style_heading() {
        let config = test_default_config();
        let input = "# This is a heading. #";

        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("Punctuation: '.'"));
    }

    #[test]
    fn test_multiple_trailing_punctuation() {
        let config = test_default_config();
        let input = "# This is a heading...";

        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("Punctuation: '.'"));
    }

    #[test]
    fn test_empty_heading() {
        let config = test_default_config();
        let input = "#\n==";

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