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

use tree_sitter::Node;

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

// MD050-specific configuration types
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub enum StrongStyle {
    #[serde(rename = "consistent")]
    Consistent,
    #[serde(rename = "asterisk")]
    Asterisk,
    #[serde(rename = "underscore")]
    Underscore,
}

impl Default for StrongStyle {
    fn default() -> Self {
        Self::Consistent
    }
}

#[derive(Debug, PartialEq, Clone, Deserialize)]
pub struct MD050StrongStyleTable {
    #[serde(default)]
    pub style: StrongStyle,
}

impl Default for MD050StrongStyleTable {
    fn default() -> Self {
        Self {
            style: StrongStyle::Consistent,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
enum StrongMarkerType {
    Asterisk,
    Underscore,
}

pub(crate) struct MD050Linter {
    context: Rc<Context>,
    violations: Vec<RuleViolation>,
    first_strong_marker: Option<StrongMarkerType>,
    line_start_bytes: Vec<usize>,
}

impl MD050Linter {
    pub fn new(context: Rc<Context>) -> Self {
        let line_start_bytes = {
            let content = context.get_document_content();
            std::iter::once(0)
                .chain(content.match_indices('\n').map(|(i, _)| i + 1))
                .collect()
        };

        Self {
            context,
            violations: Vec::new(),
            first_strong_marker: None,
            line_start_bytes,
        }
    }

    fn is_in_code_context(&self, node: &Node) -> bool {
        // Check if this node is inside a code span or code block
        let mut current = Some(*node);
        while let Some(node_to_check) = current {
            if matches!(
                node_to_check.kind(),
                "code_span" | "fenced_code_block" | "indented_code_block"
            ) {
                return true;
            }
            current = node_to_check.parent();
        }
        false
    }

    fn find_strong_violations_in_text(&mut self, node: &Node) {
        if self.is_in_code_context(node) {
            return;
        }

        let node_start_byte = node.start_byte();
        let text = {
            let content = self.context.get_document_content();
            node.utf8_text(content.as_bytes()).unwrap_or("").to_string()
        };

        if !text.is_empty() {
            self.find_strong_patterns(&text, node_start_byte);
        }
    }

    fn find_strong_patterns(&mut self, text: &str, text_start_byte: usize) {
        let config = &self.context.config.linters.settings.strong_style;

        // Look for all strong emphasis markers - both opening and closing
        let mut i = 0;
        let chars: Vec<char> = text.chars().collect();

        while i < chars.len() {
            if i + 1 < chars.len() {
                let current_char = chars[i];
                let next_char = chars[i + 1];

                // Check for strong emphasis markers (both ** and __)
                if (current_char == '*' && next_char == '*')
                    || (current_char == '_' && next_char == '_')
                {
                    // Skip if this is part of a longer sequence that would make it invalid
                    // e.g., ____ should not be detected as __ + __
                    if i + 2 < chars.len() && chars[i + 2] == current_char {
                        // This is at least a triple marker, could be *** or ___
                        if i + 3 < chars.len() && chars[i + 3] == current_char {
                            // This is a quadruple marker like ____ or ****
                            // Skip the entire sequence
                            let mut skip_count = 4;
                            while i + skip_count < chars.len()
                                && chars[i + skip_count] == current_char
                            {
                                skip_count += 1;
                            }
                            i += skip_count;
                            continue;
                        }
                        // Triple marker (*** or ___) - handle as strong emphasis
                    }

                    let marker_type = if current_char == '*' {
                        StrongMarkerType::Asterisk
                    } else {
                        StrongMarkerType::Underscore
                    };

                    // Check if we should report a violation for this marker
                    let should_report_violation = match config.style {
                        StrongStyle::Consistent => {
                            if self.first_strong_marker.is_none() {
                                self.first_strong_marker = Some(marker_type.clone());
                                false
                            } else {
                                self.first_strong_marker.as_ref() != Some(&marker_type)
                            }
                        }
                        StrongStyle::Asterisk => marker_type != StrongMarkerType::Asterisk,
                        StrongStyle::Underscore => marker_type != StrongMarkerType::Underscore,
                    };

                    if should_report_violation {
                        let expected_style = match config.style {
                            StrongStyle::Asterisk => "asterisk",
                            StrongStyle::Underscore => "underscore",
                            StrongStyle::Consistent => {
                                match self.first_strong_marker.as_ref().unwrap() {
                                    StrongMarkerType::Asterisk => "asterisk",
                                    StrongMarkerType::Underscore => "underscore",
                                }
                            }
                        };

                        let actual_style = match marker_type {
                            StrongMarkerType::Asterisk => "asterisk",
                            StrongMarkerType::Underscore => "underscore",
                        };

                        // Calculate byte position - markdownlint reports position of the second character for double markers,
                        // and the third character for opening triple markers only
                        let is_opening_triple_marker = i + 2 < chars.len()
                            && chars[i + 2] == current_char
                            && (i == 0 || (i > 0 && chars[i - 1] != current_char));
                        let position_offset = if is_opening_triple_marker { 2 } else { 1 };
                        let char_start_byte = text_start_byte
                            + text
                                .chars()
                                .take(i + position_offset)
                                .map(|c| c.len_utf8())
                                .sum::<usize>()
                            - 1;
                        let char_end_byte = char_start_byte + current_char.len_utf8();

                        let range = tree_sitter::Range {
                            start_byte: char_start_byte,
                            end_byte: char_end_byte,
                            start_point: self.byte_to_point(char_start_byte),
                            end_point: self.byte_to_point(char_end_byte),
                        };

                        self.violations.push(RuleViolation::new(
                            &MD050,
                            format!("Expected: {expected_style}; Actual: {actual_style}"),
                            self.context.file_path.clone(),
                            range_from_tree_sitter(&range),
                        ));
                    }

                    // Move past this marker pair
                    i += 2;
                } else {
                    i += 1;
                }
            } else {
                i += 1;
            }
        }
    }

    fn byte_to_point(&self, byte_pos: usize) -> tree_sitter::Point {
        let line = self.line_start_bytes.partition_point(|&x| x <= byte_pos) - 1;
        let column = byte_pos - self.line_start_bytes[line];
        tree_sitter::Point { row: line, column }
    }
}

impl RuleLinter for MD050Linter {
    fn feed(&mut self, node: &Node) {
        if matches!(node.kind(), "text" | "inline") {
            self.find_strong_violations_in_text(node);
        }
    }

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

pub const MD050: Rule = Rule {
    id: "MD050",
    alias: "strong-style",
    tags: &["emphasis"],
    description: "Strong style should be consistent",
    rule_type: RuleType::Token,
    required_nodes: &["strong_emphasis"],
    new_linter: |context| Box::new(MD050Linter::new(context)),
};

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

    use crate::config::{RuleSeverity, StrongStyle};
    use crate::linter::MultiRuleLinter;
    use crate::test_utils::test_helpers::test_config_with_rules;

    fn test_config() -> crate::config::QuickmarkConfig {
        test_config_with_rules(vec![("strong-style", RuleSeverity::Error)])
    }

    fn test_config_with_style(style: StrongStyle) -> crate::config::QuickmarkConfig {
        let mut config = test_config();
        config.linters.settings.strong_style.style = style;
        config
    }

    #[test]
    fn test_no_violations_consistent_asterisk() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has **strong text** and **another strong**.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();
        assert_eq!(md050_violations.len(), 0);
    }

    #[test]
    fn test_no_violations_consistent_underscore() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has __strong text__ and __another strong__.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();
        assert_eq!(md050_violations.len(), 0);
    }

    #[test]
    fn test_violations_inconsistent_mixed() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has **strong text** and __inconsistent strong__.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find 2 violations for the inconsistent underscore strong (opening and closing)
        assert_eq!(md050_violations.len(), 2);
    }

    #[test]
    fn test_no_violations_asterisk_style() {
        let config = test_config_with_style(StrongStyle::Asterisk);
        let input = "This has **strong text** and **another strong**.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();
        assert_eq!(md050_violations.len(), 0);
    }

    #[test]
    fn test_violations_asterisk_style_with_underscore() {
        let config = test_config_with_style(StrongStyle::Asterisk);
        let input = "This has **strong text** and __invalid strong__.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find 2 violations for the underscore strong when asterisk is required (opening and closing)
        assert_eq!(md050_violations.len(), 2);
    }

    #[test]
    fn test_no_violations_underscore_style() {
        let config = test_config_with_style(StrongStyle::Underscore);
        let input = "This has __strong text__ and __another strong__.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();
        assert_eq!(md050_violations.len(), 0);
    }

    #[test]
    fn test_violations_underscore_style_with_asterisk() {
        let config = test_config_with_style(StrongStyle::Underscore);
        let input = "This has __strong text__ and **invalid strong**.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find 2 violations for the asterisk strong when underscore is required (opening and closing)
        assert_eq!(md050_violations.len(), 2);
    }

    #[test]
    fn test_mixed_emphasis_and_strong() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has *emphasis* and **strong** and __inconsistent strong__.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find 2 violations for the inconsistent strong (opening and closing, emphasis should not be considered)
        assert_eq!(md050_violations.len(), 2);
    }

    #[test]
    fn test_strong_emphasis_combination() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has ***strong emphasis*** and ***another***.";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find no violations as both use asterisk consistently
        assert_eq!(md050_violations.len(), 0);
    }

    #[test]
    fn test_strong_emphasis_inconsistent() {
        let config = test_config_with_style(StrongStyle::Consistent);
        let input = "This has ***strong emphasis*** and ___inconsistent___. ";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md050_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD050")
            .collect();

        // Should find 2 violations for the inconsistent strong emphasis (opening and closing)
        assert_eq!(md050_violations.len(), 2);
    }
}