rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::rule_config_serde::RuleConfig;
use crate::utils::range_utils::calculate_trailing_range;
use crate::utils::regex_cache::{ORDERED_LIST_MARKER_REGEX, UNORDERED_LIST_MARKER_REGEX, get_cached_regex};

mod md009_config;
use md009_config::MD009Config;

// No need for lazy_static, we'll use get_cached_regex directly

#[derive(Debug, Clone, Default)]
pub struct MD009TrailingSpaces {
    config: MD009Config,
}

impl MD009TrailingSpaces {
    pub fn new(br_spaces: usize, strict: bool) -> Self {
        Self {
            config: MD009Config {
                br_spaces: crate::types::BrSpaces::from_const(br_spaces),
                strict,
                list_item_empty_lines: false,
            },
        }
    }

    pub const fn from_config_struct(config: MD009Config) -> Self {
        Self { config }
    }

    fn count_trailing_spaces(line: &str) -> usize {
        line.chars().rev().take_while(|&c| c == ' ').count()
    }

    fn count_trailing_spaces_ascii(line: &str) -> usize {
        line.as_bytes().iter().rev().take_while(|&&b| b == b' ').count()
    }

    /// Count all trailing whitespace characters (ASCII and Unicode).
    /// This includes U+2000..U+200A (various Unicode spaces), ASCII space, tab, etc.
    fn count_trailing_whitespace(line: &str) -> usize {
        line.chars().rev().take_while(|c| c.is_whitespace()).count()
    }

    /// Check if a line has any trailing whitespace (ASCII or Unicode)
    fn has_trailing_whitespace(line: &str) -> bool {
        line.chars().next_back().is_some_and(|c| c.is_whitespace())
    }

    fn trimmed_len_ascii_whitespace(line: &str) -> usize {
        line.as_bytes()
            .iter()
            .rposition(|b| !b.is_ascii_whitespace())
            .map(|idx| idx + 1)
            .unwrap_or(0)
    }

    fn calculate_trailing_range_ascii(
        line: usize,
        line_len: usize,
        content_end: usize,
    ) -> (usize, usize, usize, usize) {
        // Return 1-indexed columns to match calculate_trailing_range behavior
        (line, content_end + 1, line, line_len + 1)
    }

    fn is_empty_list_item_line(line: &str, prev_line: Option<&str>) -> bool {
        // A line is an empty list item line if:
        // 1. It's blank or only contains spaces
        // 2. The previous line is a list item
        if !line.trim().is_empty() {
            return false;
        }

        if let Some(prev) = prev_line {
            // Check for unordered list markers (*, -, +) with proper formatting
            UNORDERED_LIST_MARKER_REGEX.is_match(prev) || ORDERED_LIST_MARKER_REGEX.is_match(prev)
        } else {
            false
        }
    }
}

impl Rule for MD009TrailingSpaces {
    fn name(&self) -> &'static str {
        "MD009"
    }

    fn description(&self) -> &'static str {
        "Trailing spaces should be removed"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let content = ctx.content;
        let _line_index = &ctx.line_index;

        let mut warnings = Vec::new();

        // Use pre-computed lines (needed for looking back at prev_line)
        let lines = ctx.raw_lines();

        for (line_num, &line) in lines.iter().enumerate() {
            // Skip lines inside PyMdown blocks (MkDocs flavor)
            if ctx.line_info(line_num + 1).is_some_and(|info| info.in_pymdown_block) {
                continue;
            }

            let line_is_ascii = line.is_ascii();
            // Count ASCII trailing spaces for br_spaces comparison
            let trailing_ascii_spaces = if line_is_ascii {
                Self::count_trailing_spaces_ascii(line)
            } else {
                Self::count_trailing_spaces(line)
            };
            // For non-ASCII lines, also count all trailing whitespace (including Unicode)
            // to ensure the fix range covers everything that trim_end() removes
            let trailing_all_whitespace = if line_is_ascii {
                trailing_ascii_spaces
            } else {
                Self::count_trailing_whitespace(line)
            };

            // Skip if no trailing whitespace
            if trailing_all_whitespace == 0 {
                continue;
            }

            // Handle empty lines
            let trimmed_len = if line_is_ascii {
                Self::trimmed_len_ascii_whitespace(line)
            } else {
                line.trim_end().len()
            };
            if trimmed_len == 0 {
                if trailing_all_whitespace > 0 {
                    // Check if this is an empty list item line and config allows it
                    let prev_line = if line_num > 0 { Some(lines[line_num - 1]) } else { None };
                    if self.config.list_item_empty_lines && Self::is_empty_list_item_line(line, prev_line) {
                        continue;
                    }

                    // Calculate precise character range for all trailing whitespace on empty line
                    let (start_line, start_col, end_line, end_col) = if line_is_ascii {
                        Self::calculate_trailing_range_ascii(line_num + 1, line.len(), 0)
                    } else {
                        calculate_trailing_range(line_num + 1, line, 0)
                    };
                    let line_start = *ctx.line_offsets.get(line_num).unwrap_or(&0);
                    let fix_range = if line_is_ascii {
                        line_start..line_start + line.len()
                    } else {
                        _line_index.line_col_to_byte_range_with_length(line_num + 1, 1, line.chars().count())
                    };

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: start_line,
                        column: start_col,
                        end_line,
                        end_column: end_col,
                        message: "Empty line has trailing spaces".to_string(),
                        severity: Severity::Warning,
                        fix: Some(Fix {
                            range: fix_range,
                            replacement: String::new(),
                        }),
                    });
                }
                continue;
            }

            // Handle code blocks if not in strict mode
            if !self.config.strict {
                // Use pre-computed line info
                if let Some(line_info) = ctx.line_info(line_num + 1)
                    && line_info.in_code_block
                {
                    continue;
                }
            }

            // Check if it's a valid line break (only ASCII spaces count for br_spaces)
            let is_truly_last_line = line_num == lines.len() - 1 && !content.ends_with('\n');
            let has_only_ascii_trailing = trailing_ascii_spaces == trailing_all_whitespace;
            if !self.config.strict
                && !is_truly_last_line
                && has_only_ascii_trailing
                && trailing_ascii_spaces == self.config.br_spaces.get()
            {
                continue;
            }

            // Check if this is an empty blockquote line ("> " or ">> " etc)
            // These are allowed by MD028 to have a single trailing ASCII space
            let trimmed = if line_is_ascii {
                &line[..trimmed_len]
            } else {
                line.trim_end()
            };
            let is_empty_blockquote_with_space = trimmed.chars().all(|c| c == '>' || c == ' ' || c == '\t')
                && trimmed.contains('>')
                && has_only_ascii_trailing
                && trailing_ascii_spaces == 1;

            if is_empty_blockquote_with_space {
                continue; // Allow single trailing ASCII space for empty blockquote lines
            }
            // Calculate precise character range for all trailing whitespace
            let (start_line, start_col, end_line, end_col) = if line_is_ascii {
                Self::calculate_trailing_range_ascii(line_num + 1, line.len(), trimmed.len())
            } else {
                calculate_trailing_range(line_num + 1, line, trimmed.len())
            };
            let line_start = *ctx.line_offsets.get(line_num).unwrap_or(&0);
            let fix_range = if line_is_ascii {
                let start = line_start + trimmed.len();
                let end = start + trailing_all_whitespace;
                start..end
            } else {
                _line_index.line_col_to_byte_range_with_length(
                    line_num + 1,
                    trimmed.chars().count() + 1,
                    trailing_all_whitespace,
                )
            };

            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line: start_line,
                column: start_col,
                end_line,
                end_column: end_col,
                message: if trailing_all_whitespace == 1 {
                    "Trailing space found".to_string()
                } else {
                    format!("{trailing_all_whitespace} trailing spaces found")
                },
                severity: Severity::Warning,
                fix: Some(Fix {
                    range: fix_range,
                    replacement: String::new(),
                }),
            });
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        let content = ctx.content;

        // For simple cases (strict mode), use fast regex approach
        if self.config.strict {
            // In strict mode, remove ALL trailing whitespace everywhere
            // but respect inline config disable comments
            let lines = ctx.raw_lines();
            let mut result = String::with_capacity(content.len());
            for (i, line) in lines.iter().enumerate() {
                let line_num = i + 1;
                if ctx.inline_config().is_rule_disabled(self.name(), line_num) {
                    result.push_str(line);
                } else {
                    result.push_str(
                        &get_cached_regex(r"[\p{White_Space}&&[^\n\r]]+$")
                            .unwrap()
                            .replace_all(line, ""),
                    );
                }
                if i < lines.len() - 1 || content.ends_with('\n') {
                    result.push('\n');
                }
            }
            if !content.ends_with('\n') && result.ends_with('\n') {
                result.pop();
            }
            return Ok(result);
        }

        // For complex cases, we need line-by-line processing but with optimizations
        // Use pre-computed lines since we need to look at previous lines for list item checks
        let lines = ctx.raw_lines();
        let mut result = String::with_capacity(content.len()); // Pre-allocate capacity

        for (i, line) in lines.iter().enumerate() {
            let line_num = i + 1;
            // If rule is disabled for this line, keep original
            if ctx.inline_config().is_rule_disabled(self.name(), line_num) {
                result.push_str(line);
                result.push('\n');
                continue;
            }

            let line_is_ascii = line.is_ascii();
            // Fast path: check if line has any trailing spaces (ASCII) or
            // trailing whitespace (Unicode) that we need to handle
            let needs_processing = if line_is_ascii {
                line.ends_with(' ')
            } else {
                Self::has_trailing_whitespace(line)
            };
            if !needs_processing {
                result.push_str(line);
                result.push('\n');
                continue;
            }

            let trimmed = line.trim_end();
            // Count ASCII trailing spaces for br_spaces comparison
            let trailing_ascii_spaces = Self::count_trailing_spaces(line);
            // Count all trailing whitespace to detect Unicode whitespace presence
            let trailing_all_whitespace = if line_is_ascii {
                trailing_ascii_spaces
            } else {
                Self::count_trailing_whitespace(line)
            };
            // Only consider pure ASCII trailing spaces for br_spaces preservation
            let has_only_ascii_trailing = trailing_ascii_spaces == trailing_all_whitespace;

            // Handle empty lines - fast regex replacement
            if trimmed.is_empty() {
                // Check if this is an empty list item line and config allows it
                let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                if self.config.list_item_empty_lines && Self::is_empty_list_item_line(line, prev_line) {
                    result.push_str(line);
                } else {
                    // Remove all trailing spaces - line is empty so don't add anything
                }
                result.push('\n');
                continue;
            }

            // Handle code blocks if not in strict mode
            if let Some(line_info) = ctx.line_info(i + 1)
                && line_info.in_code_block
            {
                result.push_str(line);
                result.push('\n');
                continue;
            }

            // No special handling for empty blockquote lines - treat them like regular lines

            // Handle lines with trailing spaces
            let is_truly_last_line = i == lines.len() - 1 && !content.ends_with('\n');

            result.push_str(trimmed);

            // Check if this line is a heading - headings should never have trailing spaces
            let is_heading = if let Some(line_info) = ctx.line_info(i + 1) {
                line_info.heading.is_some()
            } else {
                // Fallback: check if line starts with #
                trimmed.starts_with('#')
            };

            // Check if this is an empty blockquote line (just ">")
            let is_empty_blockquote = if let Some(line_info) = ctx.line_info(i + 1) {
                line_info.blockquote.as_ref().is_some_and(|bq| bq.content.is_empty())
            } else {
                false
            };

            // In non-strict mode, preserve line breaks ONLY if they have exactly br_spaces
            // of pure ASCII trailing spaces (no Unicode whitespace mixed in).
            // Never preserve trailing spaces in headings or empty blockquotes.
            if !self.config.strict
                && !is_truly_last_line
                && has_only_ascii_trailing
                && trailing_ascii_spaces == self.config.br_spaces.get()
                && !is_heading
                && !is_empty_blockquote
            {
                // Preserve the exact number of spaces for hard line breaks
                match self.config.br_spaces.get() {
                    0 => {}
                    1 => result.push(' '),
                    2 => result.push_str("  "),
                    n => result.push_str(&" ".repeat(n)),
                }
            }
            result.push('\n');
        }

        // Preserve original ending (with or without final newline)
        if !content.ends_with('\n') && result.ends_with('\n') {
            result.pop();
        }

        Ok(result)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Skip if content is empty.
        // We cannot skip based on ASCII-space-only check because Unicode whitespace
        // characters (e.g., U+2000 EN QUAD) also count as trailing whitespace.
        // The per-line is_ascii fast path in check()/fix() handles performance.
        ctx.content.is_empty()
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Whitespace
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let default_config = MD009Config::default();
        let json_value = serde_json::to_value(&default_config).ok()?;
        let toml_value = crate::rule_config_serde::json_to_toml_value(&json_value)?;

        if let toml::Value::Table(table) = toml_value {
            if !table.is_empty() {
                Some((MD009Config::RULE_NAME.to_string(), toml::Value::Table(table)))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD009Config>(config);
        Box::new(Self::from_config_struct(rule_config))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lint_context::LintContext;
    use crate::rule::Rule;

    #[test]
    fn test_no_trailing_spaces() {
        let rule = MD009TrailingSpaces::default();
        let content = "This is a line\nAnother line\nNo trailing spaces";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_basic_trailing_spaces() {
        let rule = MD009TrailingSpaces::default();
        let content = "Line with spaces   \nAnother line  \nClean line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Default br_spaces=2, so line with 2 spaces is OK
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[0].message, "3 trailing spaces found");
    }

    #[test]
    fn test_fix_basic_trailing_spaces() {
        let rule = MD009TrailingSpaces::default();
        let content = "Line with spaces   \nAnother line  \nClean line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Line 1: 3 spaces -> removed (doesn't match br_spaces=2)
        // Line 2: 2 spaces -> kept (matches br_spaces=2)
        // Line 3: no spaces -> unchanged
        assert_eq!(fixed, "Line with spaces\nAnother line  \nClean line");
    }

    #[test]
    fn test_strict_mode() {
        let rule = MD009TrailingSpaces::new(2, true);
        let content = "Line with spaces  \nCode block:  \n```  \nCode with spaces  \n```  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // In strict mode, all trailing spaces are flagged
        assert_eq!(result.len(), 5);

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Line with spaces\nCode block:\n```\nCode with spaces\n```");
    }

    #[test]
    fn test_non_strict_mode_with_code_blocks() {
        let rule = MD009TrailingSpaces::new(2, false);
        let content = "Line with spaces  \n```\nCode with spaces  \n```\nOutside code  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // In non-strict mode, code blocks are not checked
        // Line 1 has 2 spaces (= br_spaces), so it's OK
        // Line 5 is last line without newline, so trailing spaces are flagged
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 5);
    }

    #[test]
    fn test_br_spaces_preservation() {
        let rule = MD009TrailingSpaces::new(2, false);
        let content = "Line with two spaces  \nLine with three spaces   \nLine with one space ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // br_spaces=2, so lines with exactly 2 spaces are OK
        // Line 2 has 3 spaces (should be removed, not normalized)
        // Line 3 has 1 space and is last line without newline (will be removed)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 2);
        assert_eq!(result[1].line, 3);

        let fixed = rule.fix(&ctx).unwrap();
        // Line 1: keeps 2 spaces (exact match with br_spaces)
        // Line 2: removes all 3 spaces (doesn't match br_spaces)
        // Line 3: last line without newline, spaces removed
        assert_eq!(
            fixed,
            "Line with two spaces  \nLine with three spaces\nLine with one space"
        );
    }

    #[test]
    fn test_empty_lines_with_spaces() {
        let rule = MD009TrailingSpaces::default();
        let content = "Normal line\n   \n  \nAnother line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].message, "Empty line has trailing spaces");
        assert_eq!(result[1].message, "Empty line has trailing spaces");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Normal line\n\n\nAnother line");
    }

    #[test]
    fn test_empty_blockquote_lines() {
        let rule = MD009TrailingSpaces::default();
        let content = "> Quote\n>   \n> More quote";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);
        assert_eq!(result[0].message, "3 trailing spaces found");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "> Quote\n>\n> More quote"); // All trailing spaces removed
    }

    #[test]
    fn test_last_line_handling() {
        let rule = MD009TrailingSpaces::new(2, false);

        // Content without final newline
        let content = "First line  \nLast line  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Last line without newline should have trailing spaces removed
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "First line  \nLast line");

        // Content with final newline
        let content_with_newline = "First line  \nLast line  \n";
        let ctx = LintContext::new(content_with_newline, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Both lines should preserve br_spaces
        assert!(result.is_empty());
    }

    #[test]
    fn test_single_trailing_space() {
        let rule = MD009TrailingSpaces::new(2, false);
        let content = "Line with one space ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].message, "Trailing space found");
    }

    #[test]
    fn test_tabs_not_spaces() {
        let rule = MD009TrailingSpaces::default();
        let content = "Line with tab\t\nLine with spaces  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only spaces are checked, not tabs
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);
    }

    #[test]
    fn test_mixed_content() {
        let rule = MD009TrailingSpaces::new(2, false);
        // Construct content with actual trailing spaces using string concatenation
        let mut content = String::new();
        content.push_str("# Heading");
        content.push_str("   "); // Add 3 trailing spaces (more than br_spaces=2)
        content.push('\n');
        content.push_str("Normal paragraph\n> Blockquote\n>\n```\nCode block\n```\n- List item\n");

        let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should flag the line with trailing spaces
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 1);
        assert!(result[0].message.contains("trailing spaces"));
    }

    #[test]
    fn test_column_positions() {
        let rule = MD009TrailingSpaces::default();
        let content = "Text   ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].column, 5); // After "Text"
        assert_eq!(result[0].end_column, 8); // After all spaces
    }

    #[test]
    fn test_default_config() {
        let rule = MD009TrailingSpaces::default();
        let config = rule.default_config_section();
        assert!(config.is_some());
        let (name, _value) = config.unwrap();
        assert_eq!(name, "MD009");
    }

    #[test]
    fn test_from_config() {
        let mut config = crate::config::Config::default();
        let mut rule_config = crate::config::RuleConfig::default();
        rule_config
            .values
            .insert("br_spaces".to_string(), toml::Value::Integer(3));
        rule_config
            .values
            .insert("strict".to_string(), toml::Value::Boolean(true));
        config.rules.insert("MD009".to_string(), rule_config);

        let rule = MD009TrailingSpaces::from_config(&config);
        let content = "Line   ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);

        // In strict mode, should remove all spaces
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Line");
    }

    #[test]
    fn test_list_item_empty_lines() {
        // Create rule with list_item_empty_lines enabled
        let config = MD009Config {
            list_item_empty_lines: true,
            ..Default::default()
        };
        let rule = MD009TrailingSpaces::from_config_struct(config);

        // Test unordered list with empty line
        let content = "- First item\n  \n- Second item";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should not flag the empty line with spaces after list item
        assert!(result.is_empty());

        // Test ordered list with empty line
        let content = "1. First item\n  \n2. Second item";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());

        // Test that non-list empty lines are still flagged
        let content = "Normal paragraph\n  \nAnother paragraph";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);
    }

    #[test]
    fn test_list_item_empty_lines_disabled() {
        // Default config has list_item_empty_lines disabled
        let rule = MD009TrailingSpaces::default();

        let content = "- First item\n  \n- Second item";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should flag the empty line with spaces
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);
    }

    #[test]
    fn test_performance_large_document() {
        let rule = MD009TrailingSpaces::default();
        let mut content = String::new();
        for i in 0..1000 {
            content.push_str(&format!("Line {i} with spaces  \n"));
        }
        let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Default br_spaces=2, so all lines with 2 spaces are OK
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_preserve_content_after_fix() {
        let rule = MD009TrailingSpaces::new(2, false);
        let content = "**Bold** text  \n*Italic* text  \n[Link](url)  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "**Bold** text  \n*Italic* text  \n[Link](url)");
    }

    #[test]
    fn test_nested_blockquotes() {
        let rule = MD009TrailingSpaces::default();
        let content = "> > Nested  \n> >   \n> Normal  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Line 2 has empty blockquote with 3 spaces, line 3 is last line without newline
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 2);
        assert_eq!(result[1].line, 3);

        let fixed = rule.fix(&ctx).unwrap();
        // Line 1: Keeps 2 spaces (exact match with br_spaces)
        // Line 2: Empty blockquote with 3 spaces -> removes all (doesn't match br_spaces)
        // Line 3: Last line without newline -> removes all spaces
        assert_eq!(fixed, "> > Nested  \n> >\n> Normal");
    }

    #[test]
    fn test_normalized_line_endings() {
        let rule = MD009TrailingSpaces::default();
        // In production, content is normalized to LF at I/O boundary
        let content = "Line with spaces  \nAnother line  ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Line 1 has 2 spaces (= br_spaces) so it's OK
        // Line 2 is last line without newline, so it's flagged
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 2);
    }

    #[test]
    fn test_issue_80_no_space_normalization() {
        // Test for GitHub issue #80 - MD009 should not add spaces when removing trailing spaces
        let rule = MD009TrailingSpaces::new(2, false); // br_spaces=2

        // Test that 1 trailing space is removed, not normalized to 2
        let content = "Line with one space \nNext line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[0].message, "Trailing space found");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Line with one space\nNext line");

        // Test that 3 trailing spaces are removed, not normalized to 2
        let content = "Line with three spaces   \nNext line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].line, 1);
        assert_eq!(result[0].message, "3 trailing spaces found");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Line with three spaces\nNext line");

        // Test that exactly 2 trailing spaces are preserved
        let content = "Line with two spaces  \nNext line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 0); // Should not flag lines with exact br_spaces

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Line with two spaces  \nNext line");
    }

    #[test]
    fn test_unicode_whitespace_idempotent_fix() {
        // Verify that mixed Unicode (U+2000 EN QUAD) and ASCII trailing whitespace
        // is stripped in a single idempotent pass.
        let rule = MD009TrailingSpaces::default(); // br_spaces=2

        // Case from proptest: blockquote with U+2000 and ASCII space
        let content = "> 0\u{2000} ";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should detect trailing Unicode+ASCII whitespace");

        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "> 0", "Should strip all trailing whitespace in one pass");

        // Verify idempotency: fixing again should produce same result
        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
        let fixed2 = rule.fix(&ctx2).unwrap();
        assert_eq!(fixed, fixed2, "Fix must be idempotent");
    }

    #[test]
    fn test_unicode_whitespace_variants() {
        let rule = MD009TrailingSpaces::default();

        // U+2000 EN QUAD
        let content = "text\u{2000}\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "text\n");

        // U+2001 EM QUAD
        let content = "text\u{2001}\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "text\n");

        // U+3000 IDEOGRAPHIC SPACE
        let content = "text\u{3000}\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "text\n");

        // Mixed: Unicode space + ASCII spaces
        // The trailing 2 ASCII spaces match br_spaces, so they are preserved.
        // The U+2000 between content and the spaces is removed.
        let content = "text\u{2000}  \n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Unicode+ASCII mix should be flagged");
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed, "text\n",
            "All trailing whitespace should be stripped when mix includes Unicode"
        );
        // Verify idempotency
        let ctx2 = LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
        let fixed2 = rule.fix(&ctx2).unwrap();
        assert_eq!(fixed, fixed2, "Fix must be idempotent");

        // Pure ASCII 2 spaces should still be preserved as br_spaces
        let content = "text  \nnext\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 0, "Pure ASCII br_spaces should still be preserved");
    }

    #[test]
    fn test_unicode_whitespace_strict_mode() {
        let rule = MD009TrailingSpaces::new(2, true);

        // Strict mode should remove all Unicode whitespace too
        let content = "text\u{2000}\nmore\u{3000}\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "text\nmore\n");
    }

    #[test]
    fn test_fix_replacement_always_removes_trailing_spaces() {
        // The fix replacement must always be an empty string, fully removing
        // trailing spaces that do not match the br_spaces allowance.
        let rule = MD009TrailingSpaces::new(2, false);

        // 3 trailing spaces (not matching br_spaces=2) should produce a warning
        // with an empty replacement that removes them entirely
        let content = "Hello   \nWorld\n";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1);

        let fix = result[0].fix.as_ref().expect("Should have a fix");
        assert_eq!(
            fix.replacement, "",
            "Fix replacement should always be empty string (remove trailing spaces)"
        );

        // Also verify via fix() method
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Hello\nWorld\n");
    }
}