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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
/// Rule MD025: Document must have a single top-level heading
///
/// See [docs/md025.md](../../docs/md025.md) for full documentation, configuration, and examples.
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::types::HeadingLevel;
use crate::utils::range_utils::calculate_match_range;
use crate::utils::thematic_break;
use toml;

mod md025_config;
use md025_config::MD025Config;

#[derive(Clone, Default)]
pub struct MD025SingleTitle {
    config: MD025Config,
}

impl MD025SingleTitle {
    pub fn new(level: usize, front_matter_title: &str) -> Self {
        Self {
            config: MD025Config {
                level: HeadingLevel::new(level as u8).expect("Level must be 1-6"),
                front_matter_title: front_matter_title.to_string(),
                allow_document_sections: true,
                allow_with_separators: true,
            },
        }
    }

    pub fn strict() -> Self {
        Self {
            config: MD025Config {
                level: HeadingLevel::new(1).unwrap(),
                front_matter_title: "title".to_string(),
                allow_document_sections: false,
                allow_with_separators: false,
            },
        }
    }

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

    /// Check if the document's frontmatter contains a title field matching the configured key
    fn has_front_matter_title(&self, ctx: &crate::lint_context::LintContext) -> bool {
        if self.config.front_matter_title.is_empty() {
            return false;
        }

        let content_lines = ctx.raw_lines();
        if content_lines.first().map(|l| l.trim()) != Some("---") {
            return false;
        }

        for (idx, line) in content_lines.iter().enumerate().skip(1) {
            if line.trim() == "---" {
                let front_matter_content = content_lines[1..idx].join("\n");
                return front_matter_content
                    .lines()
                    .any(|l| l.trim().starts_with(&format!("{}:", self.config.front_matter_title)));
            }
        }

        false
    }

    /// Check if a heading text suggests it's a legitimate document section
    fn is_document_section_heading(&self, heading_text: &str) -> bool {
        if !self.config.allow_document_sections {
            return false;
        }

        let lower_text = heading_text.to_lowercase();

        // Common section names that are legitimate as separate H1s
        let section_indicators = [
            "appendix",
            "appendices",
            "reference",
            "references",
            "bibliography",
            "index",
            "indices",
            "glossary",
            "glossaries",
            "conclusion",
            "conclusions",
            "summary",
            "executive summary",
            "acknowledgment",
            "acknowledgments",
            "acknowledgement",
            "acknowledgements",
            "about",
            "contact",
            "license",
            "legal",
            "changelog",
            "change log",
            "history",
            "faq",
            "frequently asked questions",
            "troubleshooting",
            "support",
            "installation",
            "setup",
            "getting started",
            "api reference",
            "api documentation",
            "examples",
            "tutorials",
            "guides",
        ];

        // Check if the heading matches these patterns using whole-word matching
        let words: Vec<&str> = lower_text.split_whitespace().collect();
        section_indicators.iter().any(|&indicator| {
            // Multi-word indicators need contiguous word matching
            let indicator_words: Vec<&str> = indicator.split_whitespace().collect();
            let starts_with_indicator = if indicator_words.len() == 1 {
                words.first() == Some(&indicator)
            } else {
                words.len() >= indicator_words.len()
                    && words[..indicator_words.len()] == indicator_words[..]
            };

            starts_with_indicator ||
            lower_text.starts_with(&format!("{indicator}:")) ||
            // Whole-word match anywhere in the heading
            words.contains(&indicator) ||
            // Handle multi-word indicators appearing as a contiguous subsequence
            (indicator_words.len() > 1 && words.windows(indicator_words.len()).any(|w| w == indicator_words.as_slice())) ||
            // Handle appendix numbering like "Appendix A", "Appendix 1"
            (indicator == "appendix" && words.contains(&"appendix") && words.len() >= 2 && {
                let after_appendix = words.iter().skip_while(|&&w| w != "appendix").nth(1);
                matches!(after_appendix, Some(&"a" | &"b" | &"c" | &"d" | &"1" | &"2" | &"3" | &"i" | &"ii" | &"iii" | &"iv"))
            })
        })
    }

    fn is_horizontal_rule(line: &str) -> bool {
        thematic_break::is_thematic_break(line)
    }

    /// Build a demoted heading line. Returns the replacement line and whether
    /// the next line (Setext underline) should be skipped.
    fn build_demoted_heading(
        heading: &crate::lint_context::types::HeadingInfo,
        line_info: &crate::lint_context::types::LineInfo,
        content: &str,
        delta: usize,
    ) -> (String, bool) {
        let new_level = (heading.level as usize + delta).min(6);

        let style = match heading.style {
            crate::lint_context::HeadingStyle::ATX => {
                if heading.has_closing_sequence {
                    crate::rules::heading_utils::HeadingStyle::AtxClosed
                } else {
                    crate::rules::heading_utils::HeadingStyle::Atx
                }
            }
            crate::lint_context::HeadingStyle::Setext1 => {
                if new_level <= 2 {
                    if new_level == 1 {
                        crate::rules::heading_utils::HeadingStyle::Setext1
                    } else {
                        crate::rules::heading_utils::HeadingStyle::Setext2
                    }
                } else {
                    crate::rules::heading_utils::HeadingStyle::Atx
                }
            }
            crate::lint_context::HeadingStyle::Setext2 => {
                if new_level <= 2 {
                    crate::rules::heading_utils::HeadingStyle::Setext2
                } else {
                    crate::rules::heading_utils::HeadingStyle::Atx
                }
            }
        };

        let replacement = if heading.text.is_empty() {
            match style {
                crate::rules::heading_utils::HeadingStyle::Atx
                | crate::rules::heading_utils::HeadingStyle::SetextWithAtx => "#".repeat(new_level),
                crate::rules::heading_utils::HeadingStyle::AtxClosed
                | crate::rules::heading_utils::HeadingStyle::SetextWithAtxClosed => {
                    format!("{} {}", "#".repeat(new_level), "#".repeat(new_level))
                }
                crate::rules::heading_utils::HeadingStyle::Setext1
                | crate::rules::heading_utils::HeadingStyle::Setext2
                | crate::rules::heading_utils::HeadingStyle::Consistent => "#".repeat(new_level),
            }
        } else {
            crate::rules::heading_utils::HeadingUtils::convert_heading_style(&heading.raw_text, new_level as u32, style)
        };

        let line = line_info.content(content);
        let original_indent = &line[..line_info.indent];
        let result = format!("{original_indent}{replacement}");

        let should_skip_next = matches!(
            heading.style,
            crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
        );

        (result, should_skip_next)
    }

    /// Check if a line might be a Setext heading underline
    fn is_potential_setext_heading(ctx: &crate::lint_context::LintContext, line_num: usize) -> bool {
        if line_num == 0 || line_num >= ctx.lines.len() {
            return false;
        }

        let line = ctx.lines[line_num].content(ctx.content).trim();
        let prev_line = if line_num > 0 {
            ctx.lines[line_num - 1].content(ctx.content).trim()
        } else {
            ""
        };

        let is_dash_line = !line.is_empty() && line.chars().all(|c| c == '-');
        let is_equals_line = !line.is_empty() && line.chars().all(|c| c == '=');
        let prev_line_has_content = !prev_line.is_empty() && !Self::is_horizontal_rule(prev_line);
        (is_dash_line || is_equals_line) && prev_line_has_content
    }

    /// Check if headings are separated by horizontal rules
    fn has_separator_before_heading(&self, ctx: &crate::lint_context::LintContext, heading_line: usize) -> bool {
        if !self.config.allow_with_separators || heading_line == 0 {
            return false;
        }

        // Look for horizontal rules in the lines before this heading
        // Check up to 5 lines before the heading for a horizontal rule
        let search_start = heading_line.saturating_sub(5);

        for line_num in search_start..heading_line {
            if line_num >= ctx.lines.len() {
                continue;
            }

            let line = &ctx.lines[line_num].content(ctx.content);
            if Self::is_horizontal_rule(line) && !Self::is_potential_setext_heading(ctx, line_num) {
                // Found a horizontal rule before this heading
                // Check that there's no other heading between the HR and this heading
                let has_intermediate_heading =
                    ((line_num + 1)..heading_line).any(|idx| idx < ctx.lines.len() && ctx.lines[idx].heading.is_some());

                if !has_intermediate_heading {
                    return true;
                }
            }
        }

        false
    }
}

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

    fn description(&self) -> &'static str {
        "Multiple top-level headings in the same document"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        // Early return for empty content
        if ctx.lines.is_empty() {
            return Ok(Vec::new());
        }

        let mut warnings = Vec::new();

        let found_title_in_front_matter = self.has_front_matter_title(ctx);

        // Find all headings at the target level using cached information
        let mut target_level_headings = Vec::new();
        for (line_num, line_info) in ctx.lines.iter().enumerate() {
            if let Some(heading) = &line_info.heading
                && heading.level as usize == self.config.level.as_usize()
                && heading.is_valid
            // Skip malformed headings like `#NoSpace`
            {
                // Ignore if indented 4+ spaces (indented code block) or inside fenced code block
                if line_info.visual_indent >= 4 || line_info.in_code_block {
                    continue;
                }
                target_level_headings.push(line_num);
            }
        }

        // Determine which headings to flag as duplicates.
        // If frontmatter has a title, it counts as the first heading,
        // so ALL body headings at the target level are duplicates.
        // Otherwise, skip the first body heading and flag the rest.
        let headings_to_flag: &[usize] = if found_title_in_front_matter {
            &target_level_headings
        } else if target_level_headings.len() > 1 {
            &target_level_headings[1..]
        } else {
            &[]
        };

        if !headings_to_flag.is_empty() {
            for &line_num in headings_to_flag {
                if let Some(heading) = &ctx.lines[line_num].heading {
                    let heading_text = &heading.text;

                    // Check if this heading should be allowed
                    let should_allow = self.is_document_section_heading(heading_text)
                        || self.has_separator_before_heading(ctx, line_num);

                    if should_allow {
                        continue; // Skip flagging this heading
                    }

                    // Calculate precise character range for the heading text content
                    let line_content = &ctx.lines[line_num].content(ctx.content);
                    let text_start_in_line = if let Some(pos) = line_content.find(heading_text) {
                        pos
                    } else {
                        // Fallback: find after hash markers for ATX headings
                        if line_content.trim_start().starts_with('#') {
                            let trimmed = line_content.trim_start();
                            let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
                            let after_hashes = &trimmed[hash_count..];
                            let text_start_in_trimmed = after_hashes.find(heading_text).unwrap_or(0);
                            (line_content.len() - trimmed.len()) + hash_count + text_start_in_trimmed
                        } else {
                            0 // Setext headings start at beginning
                        }
                    };

                    let (start_line, start_col, end_line, end_col) = calculate_match_range(
                        line_num + 1, // Convert to 1-indexed
                        line_content,
                        text_start_in_line,
                        heading_text.len(),
                    );

                    // For Setext headings, the fix range must cover both
                    // the text line and the underline line
                    let is_setext = matches!(
                        heading.style,
                        crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                    );
                    let fix_range = if is_setext && line_num + 2 <= ctx.lines.len() {
                        // Cover text line + underline line
                        let text_range = ctx.line_index.line_content_range(line_num + 1);
                        let underline_range = ctx.line_index.line_content_range(line_num + 2);
                        text_range.start..underline_range.end
                    } else {
                        ctx.line_index.line_content_range(line_num + 1)
                    };

                    let replacement = {
                        let leading_spaces = line_content.len() - line_content.trim_start().len();
                        let indentation = " ".repeat(leading_spaces);
                        let raw = &heading.raw_text;
                        if raw.is_empty() {
                            format!("{}{}", indentation, "#".repeat(self.config.level.as_usize() + 1))
                        } else {
                            format!(
                                "{}{} {}",
                                indentation,
                                "#".repeat(self.config.level.as_usize() + 1),
                                raw
                            )
                        }
                    };

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: format!(
                            "Multiple top-level headings (level {}) in the same document",
                            self.config.level.as_usize()
                        ),
                        line: start_line,
                        column: start_col,
                        end_line,
                        end_column: end_col,
                        severity: Severity::Error,
                        fix: Some(Fix {
                            range: fix_range,
                            replacement,
                        }),
                    });
                }
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        let mut fixed_lines = Vec::new();
        // If frontmatter has a title, treat it as the first heading at the target level,
        // so all body headings at that level get demoted.
        let mut found_first = self.has_front_matter_title(ctx);
        let mut skip_next = false;
        // Track the demotion delta for cascading child headings.
        // When a duplicate target-level heading is demoted by +1, all headings
        // in its section (until the next target-level heading) also shift by +1.
        let mut current_delta: usize = 0;

        for (line_num, line_info) in ctx.lines.iter().enumerate() {
            if skip_next {
                skip_next = false;
                continue;
            }

            // Skip lines where this rule is disabled by inline config
            if ctx.inline_config().is_rule_disabled(self.name(), line_num + 1) {
                fixed_lines.push(line_info.content(ctx.content).to_string());
                if let Some(heading) = &line_info.heading {
                    // A target-level heading in a disabled region is preserved as-is,
                    // so it resets the cascade delta (it's not demoted)
                    if heading.level as usize == self.config.level.as_usize() {
                        current_delta = 0;
                    }
                    // For Setext headings, also preserve the underline
                    if matches!(
                        heading.style,
                        crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                    ) && line_num + 1 < ctx.lines.len()
                    {
                        fixed_lines.push(ctx.lines[line_num + 1].content(ctx.content).to_string());
                        skip_next = true;
                    }
                }
                continue;
            }

            if let Some(heading) = &line_info.heading {
                if heading.level as usize == self.config.level.as_usize() && !line_info.in_code_block {
                    if !found_first {
                        found_first = true;
                        current_delta = 0;
                        // Keep the first heading as-is
                        fixed_lines.push(line_info.content(ctx.content).to_string());

                        // For Setext headings, also add the underline
                        if matches!(
                            heading.style,
                            crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                        ) && line_num + 1 < ctx.lines.len()
                        {
                            fixed_lines.push(ctx.lines[line_num + 1].content(ctx.content).to_string());
                            skip_next = true;
                        }
                    } else {
                        // Check if this heading should be allowed
                        let should_allow = self.is_document_section_heading(&heading.text)
                            || self.has_separator_before_heading(ctx, line_num);

                        if should_allow {
                            current_delta = 0;
                            // Keep the heading as-is
                            fixed_lines.push(line_info.content(ctx.content).to_string());

                            // For Setext headings, also add the underline
                            if matches!(
                                heading.style,
                                crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                            ) && line_num + 1 < ctx.lines.len()
                            {
                                fixed_lines.push(ctx.lines[line_num + 1].content(ctx.content).to_string());
                                skip_next = true;
                            }
                        } else {
                            // Demote this heading and set delta for its children
                            current_delta = 1;
                            let (demoted, should_skip) =
                                Self::build_demoted_heading(heading, line_info, ctx.content, 1);
                            fixed_lines.push(demoted);
                            if should_skip && line_num + 1 < ctx.lines.len() {
                                skip_next = true;
                            }
                        }
                    }
                } else if current_delta > 0 && !line_info.in_code_block {
                    // Child heading in a demoted section — cascade the delta
                    let new_level = heading.level as usize + current_delta;
                    if new_level > 6 {
                        // Cannot demote beyond level 6, preserve as-is
                        fixed_lines.push(line_info.content(ctx.content).to_string());
                        if matches!(
                            heading.style,
                            crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                        ) && line_num + 1 < ctx.lines.len()
                        {
                            fixed_lines.push(ctx.lines[line_num + 1].content(ctx.content).to_string());
                            skip_next = true;
                        }
                    } else {
                        let (demoted, should_skip) =
                            Self::build_demoted_heading(heading, line_info, ctx.content, current_delta);
                        fixed_lines.push(demoted);
                        if should_skip && line_num + 1 < ctx.lines.len() {
                            skip_next = true;
                        }
                    }
                } else {
                    // Not in a demoted section or is a target level heading, keep as-is
                    fixed_lines.push(line_info.content(ctx.content).to_string());

                    // For Setext headings, also add the underline
                    if matches!(
                        heading.style,
                        crate::lint_context::HeadingStyle::Setext1 | crate::lint_context::HeadingStyle::Setext2
                    ) && line_num + 1 < ctx.lines.len()
                    {
                        fixed_lines.push(ctx.lines[line_num + 1].content(ctx.content).to_string());
                        skip_next = true;
                    }
                }
            } else {
                // Not a heading line, keep as-is
                fixed_lines.push(line_info.content(ctx.content).to_string());
            }
        }

        let result = fixed_lines.join("\n");
        if ctx.content.ends_with('\n') {
            Ok(result + "\n")
        } else {
            Ok(result)
        }
    }

    /// Get the category of this rule for selective processing
    fn category(&self) -> RuleCategory {
        RuleCategory::Heading
    }

    /// Check if this rule should be skipped for performance
    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Skip if content is empty
        if ctx.content.is_empty() {
            return true;
        }

        // Skip if no heading markers at all
        if !ctx.likely_has_headings() {
            return true;
        }

        let has_fm_title = self.has_front_matter_title(ctx);

        // Fast path: count target level headings efficiently
        let mut target_level_count = 0;
        for line_info in &ctx.lines {
            if let Some(heading) = &line_info.heading
                && heading.level as usize == self.config.level.as_usize()
            {
                // Ignore if indented 4+ spaces (indented code block), inside fenced code block, or PyMdown block
                if line_info.visual_indent >= 4 || line_info.in_code_block || line_info.in_pymdown_block {
                    continue;
                }
                target_level_count += 1;

                // If frontmatter has a title, even 1 body heading is a duplicate
                if has_fm_title {
                    return false;
                }

                // Otherwise, we need more than 1 to have duplicates
                if target_level_count > 1 {
                    return false;
                }
            }
        }

        // If we have 0 or 1 target level headings (without frontmatter title), skip
        target_level_count <= 1
    }

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

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let json_value = serde_json::to_value(&self.config).ok()?;
        Some((
            self.name().to_string(),
            crate::rule_config_serde::json_to_toml_value(&json_value)?,
        ))
    }

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_with_cached_headings() {
        let rule = MD025SingleTitle::default();

        // Test with only one level-1 heading
        let content = "# Title\n\n## Section 1\n\n## Section 2";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());

        // Test with multiple level-1 headings (non-section names) - should flag
        let content = "# Title 1\n\n## Section 1\n\n# Another Title\n\n## Section 2";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1); // Should flag the second level-1 heading
        assert_eq!(result[0].line, 5);

        // Test with front matter title and a level-1 heading - should flag the body H1
        let content = "---\ntitle: Document Title\n---\n\n# Main Heading\n\n## Section 1";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag body H1 when frontmatter has title");
        assert_eq!(result[0].line, 5);
    }

    #[test]
    fn test_allow_document_sections() {
        // Need to create rule with allow_document_sections = true
        let config = md025_config::MD025Config {
            allow_document_sections: true,
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // Test valid document sections that should NOT be flagged
        let valid_cases = vec![
            "# Main Title\n\n## Content\n\n# Appendix A\n\nAppendix content",
            "# Introduction\n\nContent here\n\n# References\n\nRef content",
            "# Guide\n\nMain content\n\n# Bibliography\n\nBib content",
            "# Manual\n\nContent\n\n# Index\n\nIndex content",
            "# Document\n\nContent\n\n# Conclusion\n\nFinal thoughts",
            "# Tutorial\n\nContent\n\n# FAQ\n\nQuestions and answers",
            "# Project\n\nContent\n\n# Acknowledgments\n\nThanks",
        ];

        for case in valid_cases {
            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();
            assert!(result.is_empty(), "Should not flag document sections in: {case}");
        }

        // Test invalid cases that should still be flagged
        let invalid_cases = vec![
            "# Main Title\n\n## Content\n\n# Random Other Title\n\nContent",
            "# First\n\nContent\n\n# Second Title\n\nMore content",
        ];

        for case in invalid_cases {
            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();
            assert!(!result.is_empty(), "Should flag non-section headings in: {case}");
        }
    }

    #[test]
    fn test_strict_mode() {
        let rule = MD025SingleTitle::strict(); // Has allow_document_sections = false

        // Even document sections should be flagged in strict mode
        let content = "# Main Title\n\n## Content\n\n# Appendix A\n\nAppendix content";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Strict mode should flag all multiple H1s");
    }

    #[test]
    fn test_bounds_checking_bug() {
        // Test case that could trigger bounds error in fix generation
        // When col + self.config.level.as_usize() exceeds line_content.len()
        let rule = MD025SingleTitle::default();

        // Create content with very short second heading
        let content = "# First\n#";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        // This should not panic
        let result = rule.check(&ctx);
        assert!(result.is_ok());

        // Test the fix as well
        let fix_result = rule.fix(&ctx);
        assert!(fix_result.is_ok());
    }

    #[test]
    fn test_bounds_checking_edge_case() {
        // Test case that specifically targets the bounds checking fix
        // Create a heading where col + self.config.level.as_usize() would exceed line length
        let rule = MD025SingleTitle::default();

        // Create content where the second heading is just "#" (length 1)
        // col will be 0, self.config.level.as_usize() is 1, so col + self.config.level.as_usize() = 1
        // This should not exceed bounds for "#" but tests the edge case
        let content = "# First Title\n#";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        // This should not panic and should handle the edge case gracefully
        let result = rule.check(&ctx);
        assert!(result.is_ok());

        if let Ok(warnings) = result
            && !warnings.is_empty()
        {
            // Check that the fix doesn't cause a panic
            let fix_result = rule.fix(&ctx);
            assert!(fix_result.is_ok());

            // The fix should produce valid content
            if let Ok(fixed_content) = fix_result {
                assert!(!fixed_content.is_empty());
                // Should convert the second "#" to "##" (or "## " if there's content)
                assert!(fixed_content.contains("##"));
            }
        }
    }

    #[test]
    fn test_horizontal_rule_separators() {
        // Need to create rule with allow_with_separators = true
        let config = md025_config::MD025Config {
            allow_with_separators: true,
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // Test that headings separated by horizontal rules are allowed
        let content = "# First Title\n\nContent here.\n\n---\n\n# Second Title\n\nMore content.\n\n***\n\n# Third Title\n\nFinal content.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Should not flag headings separated by horizontal rules"
        );

        // Test that headings without separators are still flagged
        let content = "# First Title\n\nContent here.\n\n---\n\n# Second Title\n\nMore content.\n\n# Third Title\n\nNo separator before this one.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag the heading without separator");
        assert_eq!(result[0].line, 11); // Third title on line 11

        // Test with allow_with_separators = false
        let strict_rule = MD025SingleTitle::strict();
        let content = "# First Title\n\nContent here.\n\n---\n\n# Second Title\n\nMore content.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = strict_rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "Strict mode should flag all multiple H1s regardless of separators"
        );
    }

    #[test]
    fn test_python_comments_in_code_blocks() {
        let rule = MD025SingleTitle::default();

        // Test that Python comments in code blocks are not treated as headers
        let content = "# Main Title\n\n```python\n# This is a Python comment, not a heading\nprint('Hello')\n```\n\n## Section\n\nMore content.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Should not flag Python comments in code blocks as headings"
        );

        // Test the fix method doesn't modify Python comments
        let content = "# Main Title\n\n```python\n# Python comment\nprint('test')\n```\n\n# Second Title";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("# Python comment"),
            "Fix should preserve Python comments in code blocks"
        );
        assert!(
            fixed.contains("## Second Title"),
            "Fix should demote the actual second heading"
        );
    }

    #[test]
    fn test_fix_preserves_attribute_lists() {
        let rule = MD025SingleTitle::strict();

        // Duplicate H1 with attribute list - fix should demote to H2 while preserving attrs
        let content = "# First Title\n\n# Second Title { #custom-id .special }";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        // Should flag the second H1
        let warnings = rule.check(&ctx).unwrap();
        assert_eq!(warnings.len(), 1);
        // Per-warning fix demotes the heading itself (cascade is handled by fix() method)
        assert!(warnings[0].fix.is_some());

        // Verify fix() preserves attribute list
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("## Second Title { #custom-id .special }"),
            "fix() should demote to H2 while preserving attribute list, got: {fixed}"
        );
    }

    #[test]
    fn test_frontmatter_title_counts_as_h1() {
        let rule = MD025SingleTitle::default();

        // Frontmatter with title + one body H1 → should warn on the body H1
        let content = "---\ntitle: Heading in frontmatter\n---\n\n# Heading in document\n\nSome introductory text.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should flag body H1 when frontmatter has title");
        assert_eq!(result[0].line, 5);
    }

    #[test]
    fn test_frontmatter_title_with_multiple_body_h1s() {
        let config = md025_config::MD025Config {
            front_matter_title: "title".to_string(),
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // Frontmatter with title + multiple body H1s → should warn on ALL body H1s
        let content = "---\ntitle: FM Title\n---\n\n# First Body H1\n\nContent\n\n# Second Body H1\n\nMore content";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2, "Should flag all body H1s when frontmatter has title");
        assert_eq!(result[0].line, 5);
        assert_eq!(result[1].line, 9);
    }

    #[test]
    fn test_frontmatter_without_title_no_warning() {
        let rule = MD025SingleTitle::default();

        // Frontmatter without title key + one body H1 → no warning
        let content = "---\nauthor: Someone\ndate: 2024-01-01\n---\n\n# Only Heading\n\nContent here.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Should not flag when frontmatter has no title");
    }

    #[test]
    fn test_no_frontmatter_single_h1_no_warning() {
        let rule = MD025SingleTitle::default();

        // No frontmatter + single body H1 → no warning
        let content = "# Only Heading\n\nSome content.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Should not flag single H1 without frontmatter");
    }

    #[test]
    fn test_frontmatter_custom_title_key() {
        // Custom front_matter_title key
        let config = md025_config::MD025Config {
            front_matter_title: "heading".to_string(),
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // Frontmatter with "heading:" key → should count as H1
        let content = "---\nheading: My Heading\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "Should flag body H1 when custom frontmatter key matches"
        );
        assert_eq!(result[0].line, 5);

        // Frontmatter with "title:" but configured for "heading:" → should not count
        let content = "---\ntitle: My Title\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Should not flag when frontmatter key doesn't match config"
        );
    }

    #[test]
    fn test_frontmatter_title_empty_config_disables() {
        // Empty front_matter_title disables frontmatter title detection
        let rule = MD025SingleTitle::new(1, "");

        let content = "---\ntitle: My Title\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Should not flag when front_matter_title is empty");
    }

    #[test]
    fn test_frontmatter_title_with_level_config() {
        // When level is set to 2, frontmatter title counts as the first heading at that level
        let config = md025_config::MD025Config {
            level: HeadingLevel::new(2).unwrap(),
            front_matter_title: "title".to_string(),
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // Frontmatter with title + body H2 → should flag body H2
        let content = "---\ntitle: FM Title\n---\n\n# Body H1\n\n## Body H2\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(
            result.len(),
            1,
            "Should flag body H2 when level=2 and frontmatter has title"
        );
        assert_eq!(result[0].line, 7);
    }

    #[test]
    fn test_frontmatter_title_fix_demotes_body_heading() {
        let config = md025_config::MD025Config {
            front_matter_title: "title".to_string(),
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        let content = "---\ntitle: FM Title\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("## Body Heading"),
            "Fix should demote body H1 to H2 when frontmatter has title, got: {fixed}"
        );
        // Frontmatter should be preserved
        assert!(fixed.contains("---\ntitle: FM Title\n---"));
    }

    #[test]
    fn test_frontmatter_title_should_skip_respects_frontmatter() {
        let rule = MD025SingleTitle::default();

        // With frontmatter title + 1 body H1, should_skip should return false
        let content = "---\ntitle: FM Title\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        assert!(
            !rule.should_skip(&ctx),
            "should_skip must return false when frontmatter has title and body has H1"
        );

        // Without frontmatter title + 1 body H1, should_skip should return true
        let content = "---\nauthor: Someone\n---\n\n# Body Heading\n\nContent.";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        assert!(
            rule.should_skip(&ctx),
            "should_skip should return true with no frontmatter title and single H1"
        );
    }

    #[test]
    fn test_section_indicator_whole_word_matching() {
        // Bug: substring matching causes false matches (e.g., "reindex" matches " index")
        let config = md025_config::MD025Config {
            allow_document_sections: true,
            ..Default::default()
        };
        let rule = MD025SingleTitle::from_config_struct(config);

        // These should NOT match section indicators (they contain indicators as substrings)
        let false_positive_cases = vec![
            "# Main Title\n\n# Understanding Reindex Operations",
            "# Main Title\n\n# The Summarization Pipeline",
            "# Main Title\n\n# Data Indexing Strategy",
            "# Main Title\n\n# Unsupported Browsers",
        ];

        for case in false_positive_cases {
            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();
            assert_eq!(
                result.len(),
                1,
                "Should flag duplicate H1 (not a section indicator): {case}"
            );
        }

        // These SHOULD still match as legitimate section indicators
        let true_positive_cases = vec![
            "# Main Title\n\n# Index",
            "# Main Title\n\n# Summary",
            "# Main Title\n\n# About",
            "# Main Title\n\n# References",
        ];

        for case in true_positive_cases {
            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();
            assert!(result.is_empty(), "Should allow section indicator heading: {case}");
        }
    }
}