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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use serde::Deserialize;
use std::rc::Rc;

use tree_sitter::Node;

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

// MD013-specific configuration types
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub struct MD013LineLengthTable {
    #[serde(default)]
    pub line_length: usize,
    #[serde(default)]
    pub code_block_line_length: usize,
    #[serde(default)]
    pub heading_line_length: usize,
    #[serde(default)]
    pub code_blocks: bool,
    #[serde(default)]
    pub headings: bool,
    #[serde(default)]
    pub tables: bool,
    #[serde(default)]
    pub strict: bool,
    #[serde(default)]
    pub stern: bool,
}

impl Default for MD013LineLengthTable {
    fn default() -> Self {
        Self {
            line_length: 80,
            code_block_line_length: 80,
            heading_line_length: 80,
            code_blocks: true,
            headings: true,
            tables: true,
            strict: false,
            stern: false,
        }
    }
}

/// MD013 Line Length Rule Linter
///
/// **SINGLE-USE CONTRACT**: This linter is designed for one-time use only.
/// After processing a document (via feed() calls and finalize()), the linter
/// should be discarded. The pending_violations state is not cleared between uses.
pub(crate) struct MD013Linter {
    context: Rc<Context>,
    violations: Vec<RuleViolation>,
}

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

    /// Analyze all lines and store all violations for reporting via finalize()
    /// Context cache is already initialized by MultiRuleLinter
    fn analyze_all_lines(&mut self) {
        let lines = self.context.lines.borrow();

        for (line_index, line) in lines.iter().enumerate() {
            let node_kind = self.context.get_node_type_for_line(line_index);
            let should_check = self.should_check_node_type(&node_kind);
            let should_violate = if should_check {
                self.should_violate_line(line, line_index, &node_kind)
            } else {
                false
            };

            if should_violate {
                let violation = self.create_violation_for_line(line, line_index, &node_kind);
                self.violations.push(violation);
            }
        }
    }

    fn is_link_reference_definition(&self, line: &str) -> bool {
        line.trim_start().starts_with('[') && line.contains("]:") && line.contains("http")
    }

    fn is_standalone_link_or_image(&self, line: &str) -> bool {
        let trimmed = line.trim();
        // Check for standalone link: [text](url)
        if trimmed.starts_with('[') && trimmed.contains("](") && trimmed.ends_with(')') {
            return true;
        }
        // Check for standalone image: ![alt](url)
        if trimmed.starts_with("![") && trimmed.contains("](") && trimmed.ends_with(')') {
            return true;
        }
        false
    }

    fn has_no_spaces_beyond_limit(&self, line: &str, limit: usize) -> bool {
        if line.len() <= limit {
            return false;
        }

        // Use character-aware slicing to avoid UTF-8 boundary panics
        // Find the character boundary at or after the limit position
        let mut char_boundary = limit;
        while char_boundary < line.len() && !line.is_char_boundary(char_boundary) {
            char_boundary += 1;
        }

        // If we've gone beyond the string length, there's nothing beyond the limit
        if char_boundary >= line.len() {
            return true; // No characters beyond limit, so no spaces
        }

        let beyond_limit = &line[char_boundary..];
        !beyond_limit.contains(' ')
    }

    fn should_check_node_type(&self, node_kind: &str) -> bool {
        let settings = &self.context.config.linters.settings.line_length;
        match node_kind {
            // Heading nodes
            s if s.starts_with("atx_h") && s.ends_with("_marker") => settings.headings,
            s if s.starts_with("setext_h") && s.ends_with("_underline") => settings.headings,
            "atx_heading" | "setext_heading" => settings.headings,
            // Code block nodes
            "fenced_code_block" | "indented_code_block" | "code_fence_content" => {
                settings.code_blocks
            }
            // Table nodes
            "table" | "table_row" => settings.tables,
            _ => true, // Check regular text content
        }
    }

    fn is_heading_line(&self, line: &str) -> bool {
        let trimmed = line.trim_start();
        // ATX headings start with #
        trimmed.starts_with('#') && (trimmed.len() > 1 && trimmed.chars().nth(1) == Some(' '))
    }

    fn get_line_limit(&self, node_kind: &str) -> usize {
        let settings = &self.context.config.linters.settings.line_length;
        match node_kind {
            // Heading nodes
            s if s.starts_with("atx_h") && s.ends_with("_marker") => settings.heading_line_length,
            s if s.starts_with("setext_h") && s.ends_with("_underline") => {
                settings.heading_line_length
            }
            "atx_heading" | "setext_heading" => settings.heading_line_length,
            // Code block nodes
            "fenced_code_block" | "indented_code_block" | "code_fence_content" => {
                settings.code_block_line_length
            }
            _ => settings.line_length,
        }
    }

    fn should_violate_line(&self, line: &str, _line_number: usize, node_kind: &str) -> bool {
        let settings = &self.context.config.linters.settings.line_length;

        // Check if this is a heading line and headings are disabled
        if self.is_heading_line(line) && !settings.headings {
            return false;
        }

        // Skip if this node type shouldn't be checked
        if !self.should_check_node_type(node_kind) {
            return false;
        }

        let limit = self.get_line_limit(node_kind);

        // Check if line exceeds limit
        if line.len() <= limit {
            return false;
        }

        // Apply exceptions
        if self.is_link_reference_definition(line) {
            return false;
        }

        if self.is_standalone_link_or_image(line) {
            return false;
        }

        // Strict mode: all lines beyond limit are violations
        if settings.strict {
            return true;
        }

        // Stern mode: more aggressive than default, but allows lines without spaces beyond limit
        if settings.stern {
            // In stern mode, allow lines without spaces beyond limit (like default)
            // but be more strict about other cases
            if self.has_no_spaces_beyond_limit(line, limit) {
                return false;
            }
            // If there are spaces beyond limit, it's a violation in stern mode
            return true;
        }

        // Default mode: allow lines without spaces beyond the limit
        if self.has_no_spaces_beyond_limit(line, limit) {
            return false;
        }

        true
    }

    fn create_violation_for_line(
        &self,
        line: &str,
        line_number: usize,
        node_kind: &str,
    ) -> RuleViolation {
        let limit = self.get_line_limit(node_kind);
        RuleViolation::new(
            &MD013,
            format!(
                "{} [Expected: <= {}; Actual: {}]",
                MD013.description,
                limit,
                line.len()
            ),
            self.context.file_path.clone(),
            range_from_tree_sitter(&tree_sitter::Range {
                start_byte: 0,
                end_byte: line.len(),
                start_point: tree_sitter::Point {
                    row: line_number,
                    column: 0,
                },
                end_point: tree_sitter::Point {
                    row: line_number,
                    column: line.len(),
                },
            }),
        )
    }
}

impl RuleLinter for MD013Linter {
    fn feed(&mut self, node: &Node) {
        // Analyze all lines when we see the document node
        // Context cache is already initialized by MultiRuleLinter
        if node.kind() == "document" {
            self.analyze_all_lines();
        }
    }

    fn finalize(&mut self) -> Vec<RuleViolation> {
        // Return all pending violations at once
        std::mem::take(&mut self.violations)
    }
}

pub const MD013: Rule = Rule {
    id: "MD013",
    alias: "line-length",
    tags: &["line_length"],
    description: "Line length should not exceed the configured limit",
    rule_type: RuleType::Line,
    required_nodes: &[], // Line-based rules don't require specific nodes
    new_linter: |context| Box::new(MD013Linter::new(context)),
};

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

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

    fn test_config() -> crate::config::QuickmarkConfig {
        test_config_with_rules(vec![
            ("line-length", RuleSeverity::Error),
            ("heading-style", RuleSeverity::Off),
            ("heading-increment", RuleSeverity::Off),
        ])
    }

    fn test_config_with_line_length(
        line_length_config: MD013LineLengthTable,
    ) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![
                ("line-length", RuleSeverity::Error),
                ("heading-style", RuleSeverity::Off),
                ("heading-increment", RuleSeverity::Off),
            ],
            LintersSettingsTable {
                line_length: line_length_config,
                ..Default::default()
            },
        )
    }

    #[test]
    fn test_line_length_violation() {
        let input = "This is a line that is definitely longer than eighty characters and should trigger a violation.";

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

        let violation = &violations[0];
        assert_eq!("MD013", violation.rule().id);
        assert!(violation.message().contains("Expected: <= 80"));
        assert!(violation
            .message()
            .contains(&format!("Actual: {}", input.len())));
    }

    #[test]
    fn test_line_length_no_violation() {
        let mut input =
            "This line should be exactly eighty characters long and not trigger".to_string();
        while input.len() < 80 {
            input.push('x');
        }
        assert_eq!(80, input.len());

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

    #[test]
    fn test_link_reference_definition_exception() {
        let input = "[very-long-link-reference-that-exceeds-eighty-characters]: https://example.com/very-long-url-that-should-be-exempted";

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

    #[test]
    fn test_standalone_link_exception() {
        let input = "[This is a very long link text that definitely exceeds eighty characters](https://example.com)";

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

    #[test]
    fn test_standalone_image_exception() {
        let input = "![This is a very long image alt text that definitely exceeds eighty characters](https://example.com/image.jpg)";

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

    #[test]
    fn test_no_spaces_beyond_limit_exception() {
        let input = "This line has exactly eighty characters and then continues without spaces: https://example.com/very-long-url-without-spaces";

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

    #[test]
    fn test_spaces_beyond_limit_violation() {
        // Create a string that exceeds 80 chars with a space beyond the limit
        let mut input =
            "This line has exactly eighty characters and should trigger violation".to_string();
        while input.len() < 80 {
            input.push('x');
        }
        input.push(' '); // Add space beyond limit

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

    #[test]
    fn test_strict_mode() {
        let line_length_config = MD013LineLengthTable {
            strict: true,
            ..MD013LineLengthTable::default()
        };

        let input = "This line has exactly eighty characters and then continues without spaces like: https://example.com/url";

        let config = test_config_with_line_length(line_length_config);
        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(1, violations.len()); // Should violate in strict mode
    }

    #[test]
    fn test_stern_mode_with_spaces_beyond_limit() {
        let config = MD013LineLengthTable {
            stern: true,
            ..MD013LineLengthTable::default()
        };

        // Line with spaces beyond limit - should violate in stern mode
        // Make sure the line has exactly 80 chars, then add text with spaces beyond that
        let mut input =
            "This line has exactly eighty characters and should trigger violations".to_string();
        while input.len() < 80 {
            input.push('x');
        }
        input.push_str(" with spaces"); // Add spaces beyond limit

        let full_config = test_config_with_line_length(config);
        let mut linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), full_config, &input);
        let violations = linter.analyze();
        assert_eq!(1, violations.len()); // Should violate in stern mode
    }

    #[test]
    fn test_stern_mode_without_spaces_beyond_limit() {
        let config = MD013LineLengthTable {
            stern: true,
            ..MD013LineLengthTable::default()
        };

        // Line without spaces beyond limit - should NOT violate in stern mode
        let input = "This line has exactly eighty characters and then continues without spaces: https://example.com/very-long-url-without-spaces";

        let full_config = test_config_with_line_length(config);
        let mut linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), full_config, input);
        let violations = linter.analyze();
        assert_eq!(0, violations.len()); // Should NOT violate in stern mode
    }

    #[test]
    fn test_stern_mode_vs_default_mode() {
        // Create line that exceeds limit with spaces beyond limit
        let mut input =
            "This line has exactly eighty characters and then continues with".to_string();
        while input.len() < 80 {
            input.push('x');
        }
        input.push_str(" spaces beyond"); // Add spaces beyond limit

        // Default mode - should violate because there are spaces beyond limit
        let default_config = MD013LineLengthTable::default();
        let default_full_config = test_config_with_line_length(default_config);
        let mut default_linter = MultiRuleLinter::new_for_document(
            PathBuf::from("test.md"),
            default_full_config,
            &input,
        );
        let default_violations = default_linter.analyze();

        // Stern mode - should violate because it's more aggressive about lines with spaces
        let stern_config = MD013LineLengthTable {
            stern: true,
            ..MD013LineLengthTable::default()
        };
        let stern_full_config = test_config_with_line_length(stern_config);
        let mut stern_linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), stern_full_config, &input);
        let stern_violations = stern_linter.analyze();

        // Both should catch this since it has spaces beyond limit
        assert_eq!(1, default_violations.len()); // Default should catch this since it has spaces
        assert_eq!(1, stern_violations.len()); // Stern should definitely catch this
    }

    #[test]
    fn test_stern_vs_strict_vs_default_comprehensive() {
        // Case 1: Line with spaces beyond limit - all modes should catch this
        let mut case1 =
            "This line has exactly eighty characters and then continues with".to_string();
        while case1.len() < 80 {
            case1.push('x');
        }
        case1.push_str(" spaces"); // Add spaces beyond limit

        // Case 2: Line without spaces beyond limit - only strict mode should catch this
        let case2 = "This line has exactly eighty characters and then continues without spaces: https://example.com/url".to_string();

        // Case 3: Line within limit - no mode should catch this
        let case3 = "This line is within the eighty character limit".to_string();

        let test_cases = vec![
            (&case1, true, true, true),    // Has spaces beyond limit
            (&case2, false, false, true),  // No spaces beyond limit
            (&case3, false, false, false), // Within limit
        ];

        for (input, expect_default, expect_stern, expect_strict) in test_cases {
            // Default mode
            let default_config = MD013LineLengthTable::default();
            let default_full_config = test_config_with_line_length(default_config);
            let mut default_linter = MultiRuleLinter::new_for_document(
                PathBuf::from("test.md"),
                default_full_config,
                input,
            );
            let default_violations = default_linter.analyze();
            assert_eq!(
                expect_default,
                !default_violations.is_empty(),
                "Default mode failed for: {input}"
            );

            // Stern mode
            let stern_config = MD013LineLengthTable {
                stern: true,
                ..MD013LineLengthTable::default()
            };
            let stern_full_config = test_config_with_line_length(stern_config);
            let mut stern_linter = MultiRuleLinter::new_for_document(
                PathBuf::from("test.md"),
                stern_full_config,
                input,
            );
            let stern_violations = stern_linter.analyze();
            assert_eq!(
                expect_stern,
                !stern_violations.is_empty(),
                "Stern mode failed for: {input}"
            );

            // Strict mode
            let strict_config = MD013LineLengthTable {
                strict: true,
                ..MD013LineLengthTable::default()
            };
            let strict_full_config = test_config_with_line_length(strict_config);
            let mut strict_linter = MultiRuleLinter::new_for_document(
                PathBuf::from("test.md"),
                strict_full_config,
                input,
            );
            let strict_violations = strict_linter.analyze();
            assert_eq!(
                expect_strict,
                !strict_violations.is_empty(),
                "Strict mode failed for: {input}"
            );
        }
    }

    #[test]
    fn test_custom_line_length() {
        let line_length_config = MD013LineLengthTable {
            line_length: 50,
            ..MD013LineLengthTable::default()
        };

        let input = "This line is longer than fifty characters and should violate";

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

    #[test]
    fn test_headings_disabled() {
        let line_length_config = MD013LineLengthTable {
            headings: false,
            ..MD013LineLengthTable::default()
        };

        let input = "# This is a very long heading that definitely exceeds the eighty character limit and should not trigger a violation";

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

    #[test]
    fn test_multiple_lines() {
        let input = "This is a short line.
This is a very long line that definitely exceeds the eighty character limit and should trigger a violation.
Another short line.";

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

    #[test]
    fn test_demonstrates_potential_bug_scenario() {
        // This test demonstrates that our concern was valid in theory, but doesn't occur in practice
        // because tree-sitter creates enough AST nodes for even simple documents

        let input = "A\nB\nC\n"; // Minimal document - just 3 short lines

        // Count AST nodes for this minimal document
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_md::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(input, None).unwrap();
        let mut node_count = 0;
        let walker = crate::tree_sitter_walker::TreeSitterWalker::new(&tree);
        walker.walk(|_node| {
            node_count += 1;
        });

        println!("Even a 3-line minimal document creates {node_count} AST nodes");
        println!("This explains why our MD013 implementation works correctly");

        // Even this tiny document creates multiple nodes (document, paragraph, text nodes, etc.)
        assert!(
            node_count >= 3,
            "Even minimal documents create multiple AST nodes"
        );
    }

    #[test]
    fn test_extreme_violations_vs_minimal_nodes() {
        // Create the most minimal AST possible: just plain text with no structure
        // This should create minimal AST nodes but many violations
        let mut input = String::new();

        // Add 100 long lines of plain text (no markdown structure at all)
        let long_line = "This line is definitely longer than 80 characters and should trigger a line length violation every single time.\n";
        assert!(
            long_line.len() > 80,
            "Test line should exceed 80 chars, got {}",
            long_line.len()
        );

        for i in 0..100 {
            input.push_str(&format!("Violation line {}: {}", i + 1, long_line));
        }

        println!("Total input length: {} chars", input.len());
        println!("Number of lines: {}", input.lines().count());

        // Count how many AST nodes are created by parsing this document
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_md::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(&input, None).unwrap();
        let mut node_count = 0;
        let walker = crate::tree_sitter_walker::TreeSitterWalker::new(&tree);
        walker.walk(|_node| {
            node_count += 1;
        });
        println!("Total AST nodes: {node_count}");

        let config = test_config();
        let mut linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, &input);
        let violations = linter.analyze();

        println!("Violations found: {}", violations.len());

        // This is the critical test: with the improved MD013, we should ALWAYS find all violations
        // regardless of the node count, because violations are tied to line numbers, not node traversal order
        println!(
            "Ratio: {} violations vs {} nodes",
            violations.len(),
            node_count
        );

        // We should find exactly 100 violations
        assert_eq!(100, violations.len(),
            "Expected 100 line length violations but found {}. The improved MD013 should never lose violations!",
            violations.len()
        );
    }

    #[test]
    fn test_violation_node_mismatch_scenario() {
        // This test creates a scenario where violations > nodes to ensure our fix works
        // Create a document with minimal structure but maximum line violations

        let mut input = "# Header\n\n".to_string(); // Creates multiple AST nodes

        // Add 50 long lines that should violate but may not have corresponding unique AST nodes
        for i in 0..50 {
            input.push_str(&format!("Line {} with text that is definitely over eighty characters and should trigger MD013 violation\n", i + 1));
        }

        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_md::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(&input, None).unwrap();
        let mut node_count = 0;
        let walker = crate::tree_sitter_walker::TreeSitterWalker::new(&tree);
        walker.walk(|_node| {
            node_count += 1;
        });

        let config = test_config();
        let mut linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, &input);
        let violations = linter.analyze();

        println!(
            "Stress test: {} violations vs {} nodes",
            violations.len(),
            node_count
        );

        // Should find exactly 50 violations (one per long line), regardless of node count
        assert_eq!(
            50,
            violations.len(),
            "Expected 50 violations but found {}. Improved MD013 must not lose violations!",
            violations.len()
        );

        // Verify each violation is on the correct line
        for (i, violation) in violations.iter().enumerate() {
            let expected_line = i + 2; // Lines 2, 3, 4, ..., 51 (line 0 is header, line 1 is empty)
            assert_eq!(
                expected_line,
                violation.location().range.start.line,
                "Violation {} should be on line {} but was on line {}",
                i + 1,
                expected_line,
                violation.location().range.start.line
            );
        }
    }

    #[test]
    fn test_many_violations_vs_few_nodes() {
        // Create a document with many line violations but few AST nodes
        // Structure: simple heading followed by many long lines of plain text
        let mut input = "# Short heading\n\n".to_string();

        // Add 20 long lines that should each trigger violations
        let long_line = "This line is definitely longer than 80 characters and should trigger a line length violation every time it appears.\n";
        assert!(
            long_line.len() > 80,
            "Test line should exceed 80 chars, got {}",
            long_line.len()
        );

        for i in 0..20 {
            input.push_str(&format!("Line {}: {}", i + 1, long_line));
        }

        println!("Total input length: {} chars", input.len());
        println!("Number of lines: {}", input.lines().count());

        let config = test_config();
        let mut linter =
            MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, &input);
        let violations = linter.analyze();

        // Debug: print actual violations found
        println!("Violations found: {}", violations.len());
        for (i, violation) in violations.iter().enumerate() {
            println!(
                "  Violation {}: line {}",
                i + 1,
                violation.location().range.start.line
            );
        }

        // We should find exactly 20 violations (one per long line)
        // If we find fewer, it means some violations were lost due to the bug
        assert_eq!(20, violations.len(),
            "Expected 20 line length violations but found {}. This suggests violations were lost due to insufficient AST nodes.",
            violations.len()
        );

        // Verify violations are on the correct lines (lines 2-21, since line 0 is heading, line 1 is empty)
        for (i, violation) in violations.iter().enumerate() {
            let expected_line = i + 2; // Lines 2, 3, 4, ..., 21
            assert_eq!(
                expected_line,
                violation.location().range.start.line,
                "Violation {} should be on line {} but was on line {}",
                i + 1,
                expected_line,
                violation.location().range.start.line
            );
        }
    }

    #[test]
    fn test_utf8_character_boundary_fix() {
        // Test that UTF-8 character boundary issues are properly handled
        // Create a line that has a multi-byte UTF-8 character at position 79-82 (checkmark ✓)
        // This previously caused a panic when slicing at position 80
        let input = "| View allowed and denied licenses **(ULTIMATE)** | ✓ (*1*) | ✓          | ✓           | ✓        | ✓      |";

        // Verify the test setup: checkmark should be at the boundary where slicing fails
        assert!(input.len() > 80, "Line should exceed 80 characters");
        let char_at_79 = input.as_bytes()[79];
        // UTF-8 checkmark starts at byte 79, so slicing at 80 would panic without the fix
        assert!(
            char_at_79 >= 0x80,
            "Should have multi-byte UTF-8 character near position 80"
        );

        let config = test_config();
        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        // This should NOT panic with the UTF-8 boundary fix
        let violations = linter.analyze();

        // Should find exactly 1 violation for the long line
        assert_eq!(1, violations.len(), "Should find one line length violation");
        assert_eq!("MD013", violations[0].rule().id);
        assert!(violations[0].message().contains("Expected: <= 80"));
    }
}