Skip to main content

rumdl_lib/rules/md063_heading_capitalization/
mod.rs

1/// Rule MD063: Heading capitalization
2///
3/// See [docs/md063.md](../../docs/md063.md) for full documentation, configuration, and examples.
4///
5/// This rule enforces consistent capitalization styles for markdown headings.
6/// It supports title case, sentence case, and all caps styles.
7///
8/// **Note:** This rule is disabled by default. Enable it in your configuration:
9/// ```toml
10/// [MD063]
11/// enabled = true
12/// style = "title_case"
13/// ```
14use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, Severity};
15use crate::utils::range_utils::LineIndex;
16use regex::Regex;
17use std::collections::HashSet;
18use std::ops::Range;
19use std::sync::LazyLock;
20
21mod md063_config;
22pub use md063_config::{HeadingCapStyle, MD063Config};
23
24// Regex to match inline code spans (backticks)
25static INLINE_CODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`+[^`]+`+").unwrap());
26
27// Regex to match markdown links [text](url) or [text][ref]
28static LINK_REGEX: LazyLock<Regex> =
29    LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\([^)]*\)|\[([^\]]*)\]\[[^\]]*\]").unwrap());
30
31// Regex to match inline HTML tags commonly used in headings
32// Matches paired tags: <tag>content</tag>, <tag attr="val">content</tag>
33// Matches self-closing: <tag/>, <tag />
34// Uses explicit list of common inline tags to avoid backreference (not supported in Rust regex)
35static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
36    // Common inline HTML tags used in documentation headings
37    let tags = "kbd|abbr|code|span|sub|sup|mark|cite|dfn|var|samp|small|strong|em|b|i|u|s|q|br|wbr";
38    let pattern = format!(r"<({tags})(?:\s[^>]*)?>.*?</({tags})>|<({tags})(?:\s[^>]*)?\s*/?>");
39    Regex::new(&pattern).unwrap()
40});
41
42// Regex to match custom header IDs {#id}
43static CUSTOM_ID_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s*\{#[^}]+\}\s*$").unwrap());
44
45/// Represents a segment of heading text
46#[derive(Debug, Clone)]
47enum HeadingSegment {
48    /// Regular text that should be capitalized
49    Text(String),
50    /// Inline code that should be preserved as-is
51    Code(String),
52    /// Link with text that may be capitalized and URL that's preserved
53    Link {
54        full: String,
55        text_start: usize,
56        text_end: usize,
57    },
58    /// Inline HTML tag that should be preserved as-is
59    Html(String),
60}
61
62/// Rule MD063: Heading capitalization
63#[derive(Clone)]
64pub struct MD063HeadingCapitalization {
65    config: MD063Config,
66    lowercase_set: HashSet<String>,
67    /// Multi-word proper names from MD044 that must survive sentence-case transformation.
68    /// Populated via `from_config` when both rules are active.
69    proper_names: Vec<String>,
70}
71
72impl Default for MD063HeadingCapitalization {
73    fn default() -> Self {
74        Self::new()
75    }
76}
77
78impl MD063HeadingCapitalization {
79    pub fn new() -> Self {
80        let config = MD063Config::default();
81        let lowercase_set = config.lowercase_words.iter().cloned().collect();
82        Self {
83            config,
84            lowercase_set,
85            proper_names: Vec::new(),
86        }
87    }
88
89    pub fn from_config_struct(config: MD063Config) -> Self {
90        let lowercase_set = config.lowercase_words.iter().cloned().collect();
91        Self {
92            config,
93            lowercase_set,
94            proper_names: Vec::new(),
95        }
96    }
97
98    /// Match `pattern_lower` at `start` in `text` using Unicode-aware lowercasing.
99    /// Returns the end byte offset in `text` when the match succeeds.
100    ///
101    /// This avoids converting the full `text` to lowercase and then reusing those
102    /// offsets on the original string, which can panic for case-fold expansions
103    /// (e.g. `İ` -> `i̇`).
104    fn match_case_insensitive_at(text: &str, start: usize, pattern_lower: &str) -> Option<usize> {
105        if start > text.len() || !text.is_char_boundary(start) || pattern_lower.is_empty() {
106            return None;
107        }
108
109        let mut matched_bytes = 0;
110
111        for (offset, ch) in text[start..].char_indices() {
112            if matched_bytes >= pattern_lower.len() {
113                break;
114            }
115
116            let lowered: String = ch.to_lowercase().collect();
117            if !pattern_lower[matched_bytes..].starts_with(&lowered) {
118                return None;
119            }
120
121            matched_bytes += lowered.len();
122
123            if matched_bytes == pattern_lower.len() {
124                return Some(start + offset + ch.len_utf8());
125            }
126        }
127
128        None
129    }
130
131    /// Find the next case-insensitive match of `pattern_lower` in `text`,
132    /// returning byte offsets in the ORIGINAL string.
133    fn find_case_insensitive_match(text: &str, pattern_lower: &str, search_start: usize) -> Option<(usize, usize)> {
134        if pattern_lower.is_empty() || search_start >= text.len() || !text.is_char_boundary(search_start) {
135            return None;
136        }
137
138        for (offset, _) in text[search_start..].char_indices() {
139            let start = search_start + offset;
140            if let Some(end) = Self::match_case_insensitive_at(text, start, pattern_lower) {
141                return Some((start, end));
142            }
143        }
144
145        None
146    }
147
148    /// Build a map from word byte-position → canonical form for all proper names
149    /// that appear in the heading text (case-insensitive phrase match).
150    ///
151    /// This is used in `apply_sentence_case` so that words belonging to a proper
152    /// name phrase are never lowercased to begin with.
153    fn proper_name_canonical_forms(&self, text: &str) -> std::collections::HashMap<usize, &str> {
154        let mut map = std::collections::HashMap::new();
155
156        for name in &self.proper_names {
157            if name.is_empty() {
158                continue;
159            }
160            let name_lower = name.to_lowercase();
161            let canonical_words: Vec<&str> = name.split_whitespace().collect();
162            if canonical_words.is_empty() {
163                continue;
164            }
165            let mut search_start = 0;
166
167            while search_start < text.len() {
168                let Some((abs_pos, end_pos)) = Self::find_case_insensitive_match(text, &name_lower, search_start)
169                else {
170                    break;
171                };
172
173                // Require word boundaries
174                let before_ok = abs_pos == 0 || !text[..abs_pos].chars().last().is_some_and(|c| c.is_alphanumeric());
175                let after_ok =
176                    end_pos >= text.len() || !text[end_pos..].chars().next().is_some_and(|c| c.is_alphanumeric());
177
178                if before_ok && after_ok {
179                    // Map each word in the matched region to its canonical form.
180                    // We zip the words found in the text slice with the words of the
181                    // canonical name so that every word gets the right casing.
182                    let text_slice = &text[abs_pos..end_pos];
183                    let mut word_idx = 0;
184                    let mut slice_offset = 0;
185
186                    for text_word in text_slice.split_whitespace() {
187                        if let Some(w_rel) = text_slice[slice_offset..].find(text_word) {
188                            let word_abs = abs_pos + slice_offset + w_rel;
189                            if let Some(&canonical_word) = canonical_words.get(word_idx) {
190                                map.insert(word_abs, canonical_word);
191                            }
192                            slice_offset += w_rel + text_word.len();
193                            word_idx += 1;
194                        }
195                    }
196                }
197
198                // Advance by one Unicode scalar value to allow overlapping matches
199                // while staying on a UTF-8 char boundary.
200                search_start = abs_pos + text[abs_pos..].chars().next().map_or(1, |c| c.len_utf8());
201            }
202        }
203
204        map
205    }
206
207    /// Check if a word has internal capitals (like "iPhone", "macOS", "GitHub", "iOS")
208    fn has_internal_capitals(&self, word: &str) -> bool {
209        let chars: Vec<char> = word.chars().collect();
210        if chars.len() < 2 {
211            return false;
212        }
213
214        let first = chars[0];
215        let rest = &chars[1..];
216        let has_upper_in_rest = rest.iter().any(|c| c.is_uppercase());
217        let has_lower_in_rest = rest.iter().any(|c| c.is_lowercase());
218
219        // Case 1: Mixed case after first character (like "iPhone", "macOS", "GitHub", "JavaScript")
220        if has_upper_in_rest && has_lower_in_rest {
221            return true;
222        }
223
224        // Case 2: Lowercase first + uppercase in rest (like "iOS", "eBay")
225        if first.is_lowercase() && has_upper_in_rest {
226            return true;
227        }
228
229        false
230    }
231
232    /// Check if a word is an all-caps acronym (2+ consecutive uppercase letters)
233    /// Examples: "API", "GPU", "HTTP2", "IO" return true
234    /// Examples: "A", "iPhone", "npm" return false
235    fn is_all_caps_acronym(&self, word: &str) -> bool {
236        // Skip single-letter words (handled by title case rules)
237        if word.len() < 2 {
238            return false;
239        }
240
241        let mut consecutive_upper = 0;
242        let mut max_consecutive = 0;
243
244        for c in word.chars() {
245            if c.is_uppercase() {
246                consecutive_upper += 1;
247                max_consecutive = max_consecutive.max(consecutive_upper);
248            } else if c.is_lowercase() {
249                // Any lowercase letter means not all-caps
250                return false;
251            } else {
252                // Non-letter (number, punctuation) - reset counter but don't fail
253                consecutive_upper = 0;
254            }
255        }
256
257        // Must have at least 2 consecutive uppercase letters
258        max_consecutive >= 2
259    }
260
261    /// Check if a word should be preserved as-is
262    fn should_preserve_word(&self, word: &str) -> bool {
263        // Check ignore_words list (case-sensitive exact match)
264        if self.config.ignore_words.iter().any(|w| w == word) {
265            return true;
266        }
267
268        // Check if word has internal capitals and preserve_cased_words is enabled
269        if self.config.preserve_cased_words && self.has_internal_capitals(word) {
270            return true;
271        }
272
273        // Check if word is an all-caps acronym (2+ consecutive uppercase)
274        if self.config.preserve_cased_words && self.is_all_caps_acronym(word) {
275            return true;
276        }
277
278        // Preserve caret notation for control characters (^A, ^Z, ^@, etc.)
279        if self.is_caret_notation(word) {
280            return true;
281        }
282
283        false
284    }
285
286    /// Check if a word is caret notation for control characters (e.g., ^A, ^C, ^Z)
287    fn is_caret_notation(&self, word: &str) -> bool {
288        let chars: Vec<char> = word.chars().collect();
289        // Pattern: ^ followed by uppercase letter or @[\]^_
290        if chars.len() >= 2 && chars[0] == '^' {
291            let second = chars[1];
292            // Control characters: ^@ (NUL) through ^_ (US), which includes ^A-^Z
293            if second.is_ascii_uppercase() || "@[\\]^_".contains(second) {
294                return true;
295            }
296        }
297        false
298    }
299
300    /// Check if a word is a "lowercase word" (articles, prepositions, etc.)
301    fn is_lowercase_word(&self, word: &str) -> bool {
302        self.lowercase_set.contains(&word.to_lowercase())
303    }
304
305    /// Apply title case to a single word
306    fn title_case_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
307        if word.is_empty() {
308            return word.to_string();
309        }
310
311        // Preserve words in ignore list or with internal capitals
312        if self.should_preserve_word(word) {
313            return word.to_string();
314        }
315
316        // First and last words are always capitalized
317        if is_first || is_last {
318            return self.capitalize_first(word);
319        }
320
321        // Check if it's a lowercase word (articles, prepositions, etc.)
322        if self.is_lowercase_word(word) {
323            return Self::lowercase_preserving_composition(word);
324        }
325
326        // Regular word - capitalize first letter
327        self.capitalize_first(word)
328    }
329
330    /// Apply canonical proper-name casing while preserving any trailing punctuation
331    /// attached to the original whitespace token (e.g. `javascript,` -> `JavaScript,`).
332    fn apply_canonical_form_to_word(word: &str, canonical: &str) -> String {
333        let canonical_lower = canonical.to_lowercase();
334        if canonical_lower.is_empty() {
335            return canonical.to_string();
336        }
337
338        if let Some(end_pos) = Self::match_case_insensitive_at(word, 0, &canonical_lower) {
339            let mut out = String::with_capacity(canonical.len() + word.len().saturating_sub(end_pos));
340            out.push_str(canonical);
341            out.push_str(&word[end_pos..]);
342            out
343        } else {
344            canonical.to_string()
345        }
346    }
347
348    /// Capitalize the first letter of a word, handling Unicode properly
349    fn capitalize_first(&self, word: &str) -> String {
350        if word.is_empty() {
351            return String::new();
352        }
353
354        // Find the first alphabetic character to capitalize
355        let first_alpha_pos = word.find(|c: char| c.is_alphabetic());
356        let Some(pos) = first_alpha_pos else {
357            return word.to_string();
358        };
359
360        let prefix = &word[..pos];
361        let mut chars = word[pos..].chars();
362        let first = chars.next().unwrap();
363        // Use composition-preserving uppercase to avoid decomposing
364        // precomposed characters (e.g., ῷ → Ω + combining marks + Ι)
365        let first_upper = Self::uppercase_preserving_composition(&first.to_string());
366        let rest: String = chars.collect();
367        let rest_lower = Self::lowercase_preserving_composition(&rest);
368        format!("{prefix}{first_upper}{rest_lower}")
369    }
370
371    /// Lowercase a string character-by-character, preserving precomposed
372    /// characters that would decompose during case conversion.
373    fn lowercase_preserving_composition(s: &str) -> String {
374        let mut result = String::with_capacity(s.len());
375        for c in s.chars() {
376            let lower: String = c.to_lowercase().collect();
377            if lower.chars().count() == 1 {
378                result.push_str(&lower);
379            } else {
380                // Lowercasing would decompose this character; keep original
381                result.push(c);
382            }
383        }
384        result
385    }
386
387    /// Uppercase a string character-by-character, preserving precomposed
388    /// characters that would decompose during case conversion.
389    /// For example, ῷ (U+1FF7) would decompose into Ω + combining marks + Ι
390    /// via to_uppercase(); this function keeps ῷ unchanged instead.
391    fn uppercase_preserving_composition(s: &str) -> String {
392        let mut result = String::with_capacity(s.len());
393        for c in s.chars() {
394            let upper: String = c.to_uppercase().collect();
395            if upper.chars().count() == 1 {
396                result.push_str(&upper);
397            } else {
398                // Uppercasing would decompose this character; keep original
399                result.push(c);
400            }
401        }
402        result
403    }
404
405    /// Apply title case to text, using our own title-case logic.
406    /// We avoid the external titlecase crate because it decomposes
407    /// precomposed Unicode characters during case conversion.
408    fn apply_title_case(&self, text: &str) -> String {
409        let canonical_forms = self.proper_name_canonical_forms(text);
410
411        let original_words: Vec<&str> = text.split_whitespace().collect();
412        let total_words = original_words.len();
413
414        // Pre-compute byte position of each word for canonical form lookup.
415        // Use usize::MAX as sentinel for unfound words so canonical_forms.get() returns None.
416        let mut word_positions: Vec<usize> = Vec::with_capacity(original_words.len());
417        let mut pos = 0;
418        for word in &original_words {
419            if let Some(rel) = text[pos..].find(word) {
420                word_positions.push(pos + rel);
421                pos = pos + rel + word.len();
422            } else {
423                word_positions.push(usize::MAX);
424            }
425        }
426
427        let result_words: Vec<String> = original_words
428            .iter()
429            .enumerate()
430            .map(|(i, word)| {
431                let is_first = i == 0;
432                let is_last = i == total_words - 1;
433
434                // Words that are part of an MD044 proper name use the canonical form directly.
435                if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
436                    return Self::apply_canonical_form_to_word(word, canonical);
437                }
438
439                // Preserve words in ignore list or with internal capitals
440                if self.should_preserve_word(word) {
441                    return (*word).to_string();
442                }
443
444                // Handle hyphenated words
445                if word.contains('-') {
446                    return self.handle_hyphenated_word(word, is_first, is_last);
447                }
448
449                self.title_case_word(word, is_first, is_last)
450            })
451            .collect();
452
453        result_words.join(" ")
454    }
455
456    /// Handle hyphenated words like "self-documenting"
457    fn handle_hyphenated_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
458        let parts: Vec<&str> = word.split('-').collect();
459        let total_parts = parts.len();
460
461        let result_parts: Vec<String> = parts
462            .iter()
463            .enumerate()
464            .map(|(i, part)| {
465                // First part of first word and last part of last word get special treatment
466                let part_is_first = is_first && i == 0;
467                let part_is_last = is_last && i == total_parts - 1;
468                self.title_case_word(part, part_is_first, part_is_last)
469            })
470            .collect();
471
472        result_parts.join("-")
473    }
474
475    /// Apply sentence case to text
476    fn apply_sentence_case(&self, text: &str) -> String {
477        if text.is_empty() {
478            return text.to_string();
479        }
480
481        let canonical_forms = self.proper_name_canonical_forms(text);
482        let mut result = String::new();
483        let mut current_pos = 0;
484        let mut is_first_word = true;
485
486        // Use original text positions to preserve whitespace correctly
487        for word in text.split_whitespace() {
488            if let Some(pos) = text[current_pos..].find(word) {
489                let abs_pos = current_pos + pos;
490
491                // Preserve whitespace before this word
492                result.push_str(&text[current_pos..abs_pos]);
493
494                // Words that are part of an MD044 proper name use the canonical form
495                // directly, bypassing sentence-case lowercasing entirely.
496                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
497                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
498                    is_first_word = false;
499                } else if is_first_word {
500                    // Check if word should be preserved BEFORE any capitalization
501                    if self.should_preserve_word(word) {
502                        // Preserve ignore-words exactly as-is, even at start
503                        result.push_str(word);
504                    } else {
505                        // First word: capitalize first letter, lowercase rest
506                        let mut chars = word.chars();
507                        if let Some(first) = chars.next() {
508                            result.push_str(&Self::uppercase_preserving_composition(&first.to_string()));
509                            let rest: String = chars.collect();
510                            result.push_str(&Self::lowercase_preserving_composition(&rest));
511                        }
512                    }
513                    is_first_word = false;
514                } else {
515                    // Non-first words: preserve if needed, otherwise lowercase
516                    if self.should_preserve_word(word) {
517                        result.push_str(word);
518                    } else {
519                        result.push_str(&Self::lowercase_preserving_composition(word));
520                    }
521                }
522
523                current_pos = abs_pos + word.len();
524            }
525        }
526
527        // Preserve any trailing whitespace
528        if current_pos < text.len() {
529            result.push_str(&text[current_pos..]);
530        }
531
532        result
533    }
534
535    /// Apply all caps to text (preserve whitespace)
536    fn apply_all_caps(&self, text: &str) -> String {
537        if text.is_empty() {
538            return text.to_string();
539        }
540
541        let canonical_forms = self.proper_name_canonical_forms(text);
542        let mut result = String::new();
543        let mut current_pos = 0;
544
545        // Use original text positions to preserve whitespace correctly
546        for word in text.split_whitespace() {
547            if let Some(pos) = text[current_pos..].find(word) {
548                let abs_pos = current_pos + pos;
549
550                // Preserve whitespace before this word
551                result.push_str(&text[current_pos..abs_pos]);
552
553                // Words that are part of an MD044 proper name use the canonical form directly.
554                // This prevents oscillation with MD044 when all-caps style is active.
555                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
556                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
557                } else if self.should_preserve_word(word) {
558                    result.push_str(word);
559                } else {
560                    result.push_str(&Self::uppercase_preserving_composition(word));
561                }
562
563                current_pos = abs_pos + word.len();
564            }
565        }
566
567        // Preserve any trailing whitespace
568        if current_pos < text.len() {
569            result.push_str(&text[current_pos..]);
570        }
571
572        result
573    }
574
575    /// Parse heading text into segments
576    fn parse_segments(&self, text: &str) -> Vec<HeadingSegment> {
577        let mut segments = Vec::new();
578        let mut last_end = 0;
579
580        // Collect all special regions (code and links)
581        let mut special_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();
582
583        // Find inline code spans
584        for mat in INLINE_CODE_REGEX.find_iter(text) {
585            special_regions.push((mat.start(), mat.end(), HeadingSegment::Code(mat.as_str().to_string())));
586        }
587
588        // Find links
589        for caps in LINK_REGEX.captures_iter(text) {
590            let full_match = caps.get(0).unwrap();
591            let text_match = caps.get(1).or_else(|| caps.get(2));
592
593            if let Some(text_m) = text_match {
594                special_regions.push((
595                    full_match.start(),
596                    full_match.end(),
597                    HeadingSegment::Link {
598                        full: full_match.as_str().to_string(),
599                        text_start: text_m.start() - full_match.start(),
600                        text_end: text_m.end() - full_match.start(),
601                    },
602                ));
603            }
604        }
605
606        // Find inline HTML tags
607        for mat in HTML_TAG_REGEX.find_iter(text) {
608            special_regions.push((mat.start(), mat.end(), HeadingSegment::Html(mat.as_str().to_string())));
609        }
610
611        // Sort by start position
612        special_regions.sort_by_key(|(start, _, _)| *start);
613
614        // Remove overlapping regions (code takes precedence)
615        let mut filtered_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();
616        for region in special_regions {
617            let overlaps = filtered_regions.iter().any(|(s, e, _)| region.0 < *e && region.1 > *s);
618            if !overlaps {
619                filtered_regions.push(region);
620            }
621        }
622
623        // Build segments
624        for (start, end, segment) in filtered_regions {
625            // Add text before this special region
626            if start > last_end {
627                let text_segment = &text[last_end..start];
628                if !text_segment.is_empty() {
629                    segments.push(HeadingSegment::Text(text_segment.to_string()));
630                }
631            }
632            segments.push(segment);
633            last_end = end;
634        }
635
636        // Add remaining text
637        if last_end < text.len() {
638            let remaining = &text[last_end..];
639            if !remaining.is_empty() {
640                segments.push(HeadingSegment::Text(remaining.to_string()));
641            }
642        }
643
644        // If no segments were found, treat the whole thing as text
645        if segments.is_empty() && !text.is_empty() {
646            segments.push(HeadingSegment::Text(text.to_string()));
647        }
648
649        segments
650    }
651
652    /// Apply capitalization to heading text
653    fn apply_capitalization(&self, text: &str) -> String {
654        // Strip custom ID if present and re-add later
655        let (main_text, custom_id) = if let Some(mat) = CUSTOM_ID_REGEX.find(text) {
656            (&text[..mat.start()], Some(mat.as_str()))
657        } else {
658            (text, None)
659        };
660
661        // Parse into segments
662        let segments = self.parse_segments(main_text);
663
664        // Count text segments to determine first/last word context
665        let text_segments: Vec<usize> = segments
666            .iter()
667            .enumerate()
668            .filter_map(|(i, s)| matches!(s, HeadingSegment::Text(_)).then_some(i))
669            .collect();
670
671        // Determine if the first segment overall is a text segment
672        // For sentence case: if heading starts with code/link, the first text segment
673        // should NOT capitalize its first word (the heading already has a "first element")
674        let first_segment_is_text = segments
675            .first()
676            .map(|s| matches!(s, HeadingSegment::Text(_)))
677            .unwrap_or(false);
678
679        // Determine if the last segment overall is a text segment
680        // If the last segment is Code or Link, then the last text segment should NOT
681        // treat its last word as the heading's last word (for lowercase-words respect)
682        let last_segment_is_text = segments
683            .last()
684            .map(|s| matches!(s, HeadingSegment::Text(_)))
685            .unwrap_or(false);
686
687        // Apply capitalization to each segment
688        let mut result_parts: Vec<String> = Vec::new();
689
690        for (i, segment) in segments.iter().enumerate() {
691            match segment {
692                HeadingSegment::Text(t) => {
693                    let is_first_text = text_segments.first() == Some(&i);
694                    // A text segment is "last" only if it's the last text segment AND
695                    // the last segment overall is also text. If there's Code/Link after,
696                    // the last word should respect lowercase-words.
697                    let is_last_text = text_segments.last() == Some(&i) && last_segment_is_text;
698
699                    let capitalized = match self.config.style {
700                        HeadingCapStyle::TitleCase => self.apply_title_case_segment(t, is_first_text, is_last_text),
701                        HeadingCapStyle::SentenceCase => {
702                            // For sentence case, only capitalize first word if:
703                            // 1. This is the first text segment, AND
704                            // 2. The heading actually starts with text (not code/link)
705                            if is_first_text && first_segment_is_text {
706                                self.apply_sentence_case(t)
707                            } else {
708                                // Non-first segments OR heading starts with code/link
709                                self.apply_sentence_case_non_first(t)
710                            }
711                        }
712                        HeadingCapStyle::AllCaps => self.apply_all_caps(t),
713                    };
714                    result_parts.push(capitalized);
715                }
716                HeadingSegment::Code(c) => {
717                    result_parts.push(c.clone());
718                }
719                HeadingSegment::Link {
720                    full,
721                    text_start,
722                    text_end,
723                } => {
724                    // Apply capitalization to link text only
725                    let link_text = &full[*text_start..*text_end];
726                    let capitalized_text = match self.config.style {
727                        HeadingCapStyle::TitleCase => self.apply_title_case(link_text),
728                        // For sentence case, apply same preservation logic as non-first text
729                        // This preserves acronyms (API), brand names (iPhone), etc.
730                        HeadingCapStyle::SentenceCase => self.apply_sentence_case_non_first(link_text),
731                        HeadingCapStyle::AllCaps => self.apply_all_caps(link_text),
732                    };
733
734                    let mut new_link = String::new();
735                    new_link.push_str(&full[..*text_start]);
736                    new_link.push_str(&capitalized_text);
737                    new_link.push_str(&full[*text_end..]);
738                    result_parts.push(new_link);
739                }
740                HeadingSegment::Html(h) => {
741                    // Preserve HTML tags as-is (like code)
742                    result_parts.push(h.clone());
743                }
744            }
745        }
746
747        let mut result = result_parts.join("");
748
749        // Re-add custom ID if present
750        if let Some(id) = custom_id {
751            result.push_str(id);
752        }
753
754        result
755    }
756
757    /// Apply title case to a text segment with first/last awareness
758    fn apply_title_case_segment(&self, text: &str, is_first_segment: bool, is_last_segment: bool) -> String {
759        let canonical_forms = self.proper_name_canonical_forms(text);
760        let words: Vec<&str> = text.split_whitespace().collect();
761        let total_words = words.len();
762
763        if total_words == 0 {
764            return text.to_string();
765        }
766
767        // Pre-compute byte position of each word so we can look up canonical forms.
768        // Use usize::MAX as sentinel for unfound words so canonical_forms.get() returns None.
769        let mut word_positions: Vec<usize> = Vec::with_capacity(words.len());
770        let mut pos = 0;
771        for word in &words {
772            if let Some(rel) = text[pos..].find(word) {
773                word_positions.push(pos + rel);
774                pos = pos + rel + word.len();
775            } else {
776                word_positions.push(usize::MAX);
777            }
778        }
779
780        let result_words: Vec<String> = words
781            .iter()
782            .enumerate()
783            .map(|(i, word)| {
784                let is_first = is_first_segment && i == 0;
785                let is_last = is_last_segment && i == total_words - 1;
786
787                // Words that are part of an MD044 proper name use the canonical form directly.
788                if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
789                    return Self::apply_canonical_form_to_word(word, canonical);
790                }
791
792                // Handle hyphenated words
793                if word.contains('-') {
794                    return self.handle_hyphenated_word(word, is_first, is_last);
795                }
796
797                self.title_case_word(word, is_first, is_last)
798            })
799            .collect();
800
801        // Preserve original spacing
802        let mut result = String::new();
803        let mut word_iter = result_words.iter();
804        let mut in_word = false;
805
806        for c in text.chars() {
807            if c.is_whitespace() {
808                if in_word {
809                    in_word = false;
810                }
811                result.push(c);
812            } else if !in_word {
813                if let Some(word) = word_iter.next() {
814                    result.push_str(word);
815                }
816                in_word = true;
817            }
818        }
819
820        result
821    }
822
823    /// Apply sentence case to non-first segments (just lowercase, preserve whitespace)
824    fn apply_sentence_case_non_first(&self, text: &str) -> String {
825        if text.is_empty() {
826            return text.to_string();
827        }
828
829        let canonical_forms = self.proper_name_canonical_forms(text);
830        let mut result = String::new();
831        let mut current_pos = 0;
832
833        // Iterate over words in the original text so byte positions are consistent
834        // with the positions in canonical_forms (built from the same text).
835        for word in text.split_whitespace() {
836            if let Some(pos) = text[current_pos..].find(word) {
837                let abs_pos = current_pos + pos;
838
839                // Preserve whitespace before this word
840                result.push_str(&text[current_pos..abs_pos]);
841
842                // Words that are part of an MD044 proper name use the canonical form directly.
843                if let Some(&canonical) = canonical_forms.get(&abs_pos) {
844                    result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
845                } else if self.should_preserve_word(word) {
846                    result.push_str(word);
847                } else {
848                    result.push_str(&Self::lowercase_preserving_composition(word));
849                }
850
851                current_pos = abs_pos + word.len();
852            }
853        }
854
855        // Preserve any trailing whitespace
856        if current_pos < text.len() {
857            result.push_str(&text[current_pos..]);
858        }
859
860        result
861    }
862
863    /// Get byte range for a line
864    fn get_line_byte_range(&self, content: &str, line_num: usize, line_index: &LineIndex) -> Range<usize> {
865        let start_pos = line_index.get_line_start_byte(line_num).unwrap_or(content.len());
866        let line = content.lines().nth(line_num - 1).unwrap_or("");
867        Range {
868            start: start_pos,
869            end: start_pos + line.len(),
870        }
871    }
872
873    /// Fix an ATX heading line
874    fn fix_atx_heading(&self, _line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
875        // Parse the line to preserve structure
876        let indent = " ".repeat(heading.marker_column);
877        let hashes = "#".repeat(heading.level as usize);
878
879        // Apply capitalization to the text
880        let fixed_text = self.apply_capitalization(&heading.raw_text);
881
882        // Reconstruct with closing sequence if present
883        let closing = &heading.closing_sequence;
884        if heading.has_closing_sequence {
885            format!("{indent}{hashes} {fixed_text} {closing}")
886        } else {
887            format!("{indent}{hashes} {fixed_text}")
888        }
889    }
890
891    /// Fix a Setext heading line
892    fn fix_setext_heading(&self, line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
893        // Apply capitalization to the text
894        let fixed_text = self.apply_capitalization(&heading.raw_text);
895
896        // Preserve leading whitespace from original line
897        let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();
898
899        format!("{leading_ws}{fixed_text}")
900    }
901}
902
903impl Rule for MD063HeadingCapitalization {
904    fn name(&self) -> &'static str {
905        "MD063"
906    }
907
908    fn description(&self) -> &'static str {
909        "Heading capitalization"
910    }
911
912    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
913        !ctx.likely_has_headings() || !ctx.lines.iter().any(|line| line.heading.is_some())
914    }
915
916    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
917        let content = ctx.content;
918
919        if content.is_empty() {
920            return Ok(Vec::new());
921        }
922
923        let mut warnings = Vec::new();
924        let line_index = &ctx.line_index;
925
926        for (line_num, line_info) in ctx.lines.iter().enumerate() {
927            if let Some(heading) = &line_info.heading {
928                // Check level filter
929                if heading.level < self.config.min_level || heading.level > self.config.max_level {
930                    continue;
931                }
932
933                // Skip headings in code blocks (indented headings)
934                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
935                    continue;
936                }
937
938                // Apply capitalization and compare
939                let original_text = &heading.raw_text;
940                let fixed_text = self.apply_capitalization(original_text);
941
942                if original_text != &fixed_text {
943                    let line = line_info.content(ctx.content);
944                    let style_name = match self.config.style {
945                        HeadingCapStyle::TitleCase => "title case",
946                        HeadingCapStyle::SentenceCase => "sentence case",
947                        HeadingCapStyle::AllCaps => "ALL CAPS",
948                    };
949
950                    warnings.push(LintWarning {
951                        rule_name: Some(self.name().to_string()),
952                        line: line_num + 1,
953                        column: heading.content_column + 1,
954                        end_line: line_num + 1,
955                        end_column: heading.content_column + 1 + original_text.len(),
956                        message: format!("Heading should use {style_name}: '{original_text}' -> '{fixed_text}'"),
957                        severity: Severity::Warning,
958                        fix: Some(Fix {
959                            range: self.get_line_byte_range(content, line_num + 1, line_index),
960                            replacement: match heading.style {
961                                crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
962                                _ => self.fix_setext_heading(line, heading),
963                            },
964                        }),
965                    });
966                }
967            }
968        }
969
970        Ok(warnings)
971    }
972
973    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
974        let content = ctx.content;
975
976        if content.is_empty() {
977            return Ok(content.to_string());
978        }
979
980        let lines = ctx.raw_lines();
981        let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
982
983        for (line_num, line_info) in ctx.lines.iter().enumerate() {
984            // Skip lines where the rule is disabled via inline config
985            if ctx.is_rule_disabled(self.name(), line_num + 1) {
986                continue;
987            }
988
989            if let Some(heading) = &line_info.heading {
990                // Check level filter
991                if heading.level < self.config.min_level || heading.level > self.config.max_level {
992                    continue;
993                }
994
995                // Skip headings in code blocks
996                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
997                    continue;
998                }
999
1000                let original_text = &heading.raw_text;
1001                let fixed_text = self.apply_capitalization(original_text);
1002
1003                if original_text != &fixed_text {
1004                    let line = line_info.content(ctx.content);
1005                    fixed_lines[line_num] = match heading.style {
1006                        crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
1007                        _ => self.fix_setext_heading(line, heading),
1008                    };
1009                }
1010            }
1011        }
1012
1013        // Reconstruct content preserving line endings
1014        let mut result = String::with_capacity(content.len());
1015        for (i, line) in fixed_lines.iter().enumerate() {
1016            result.push_str(line);
1017            if i < fixed_lines.len() - 1 || content.ends_with('\n') {
1018                result.push('\n');
1019            }
1020        }
1021
1022        Ok(result)
1023    }
1024
1025    fn as_any(&self) -> &dyn std::any::Any {
1026        self
1027    }
1028
1029    fn default_config_section(&self) -> Option<(String, toml::Value)> {
1030        let json_value = serde_json::to_value(&self.config).ok()?;
1031        Some((
1032            self.name().to_string(),
1033            crate::rule_config_serde::json_to_toml_value(&json_value)?,
1034        ))
1035    }
1036
1037    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
1038    where
1039        Self: Sized,
1040    {
1041        let rule_config = crate::rule_config_serde::load_rule_config::<MD063Config>(config);
1042        let md044_config =
1043            crate::rule_config_serde::load_rule_config::<crate::rules::md044_proper_names::MD044Config>(config);
1044        let mut rule = Self::from_config_struct(rule_config);
1045        rule.proper_names = md044_config.names;
1046        Box::new(rule)
1047    }
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053    use crate::lint_context::LintContext;
1054
1055    fn create_rule() -> MD063HeadingCapitalization {
1056        let config = MD063Config {
1057            enabled: true,
1058            ..Default::default()
1059        };
1060        MD063HeadingCapitalization::from_config_struct(config)
1061    }
1062
1063    fn create_rule_with_style(style: HeadingCapStyle) -> MD063HeadingCapitalization {
1064        let config = MD063Config {
1065            enabled: true,
1066            style,
1067            ..Default::default()
1068        };
1069        MD063HeadingCapitalization::from_config_struct(config)
1070    }
1071
1072    // Title case tests
1073    #[test]
1074    fn test_title_case_basic() {
1075        let rule = create_rule();
1076        let content = "# hello world\n";
1077        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1078        let result = rule.check(&ctx).unwrap();
1079        assert_eq!(result.len(), 1);
1080        assert!(result[0].message.contains("Hello World"));
1081    }
1082
1083    #[test]
1084    fn test_title_case_lowercase_words() {
1085        let rule = create_rule();
1086        let content = "# the quick brown fox\n";
1087        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1088        let result = rule.check(&ctx).unwrap();
1089        assert_eq!(result.len(), 1);
1090        // "The" should be capitalized (first word), "quick", "brown", "fox" should be capitalized
1091        assert!(result[0].message.contains("The Quick Brown Fox"));
1092    }
1093
1094    #[test]
1095    fn test_title_case_already_correct() {
1096        let rule = create_rule();
1097        let content = "# The Quick Brown Fox\n";
1098        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1099        let result = rule.check(&ctx).unwrap();
1100        assert!(result.is_empty(), "Already correct heading should not be flagged");
1101    }
1102
1103    #[test]
1104    fn test_title_case_hyphenated() {
1105        let rule = create_rule();
1106        let content = "# self-documenting code\n";
1107        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1108        let result = rule.check(&ctx).unwrap();
1109        assert_eq!(result.len(), 1);
1110        assert!(result[0].message.contains("Self-Documenting Code"));
1111    }
1112
1113    // Sentence case tests
1114    #[test]
1115    fn test_sentence_case_basic() {
1116        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1117        let content = "# The Quick Brown Fox\n";
1118        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1119        let result = rule.check(&ctx).unwrap();
1120        assert_eq!(result.len(), 1);
1121        assert!(result[0].message.contains("The quick brown fox"));
1122    }
1123
1124    #[test]
1125    fn test_sentence_case_already_correct() {
1126        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1127        let content = "# The quick brown fox\n";
1128        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1129        let result = rule.check(&ctx).unwrap();
1130        assert!(result.is_empty());
1131    }
1132
1133    // All caps tests
1134    #[test]
1135    fn test_all_caps_basic() {
1136        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
1137        let content = "# hello world\n";
1138        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1139        let result = rule.check(&ctx).unwrap();
1140        assert_eq!(result.len(), 1);
1141        assert!(result[0].message.contains("HELLO WORLD"));
1142    }
1143
1144    // Preserve tests
1145    #[test]
1146    fn test_preserve_ignore_words() {
1147        let config = MD063Config {
1148            enabled: true,
1149            ignore_words: vec!["iPhone".to_string(), "macOS".to_string()],
1150            ..Default::default()
1151        };
1152        let rule = MD063HeadingCapitalization::from_config_struct(config);
1153
1154        let content = "# using iPhone on macOS\n";
1155        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1156        let result = rule.check(&ctx).unwrap();
1157        assert_eq!(result.len(), 1);
1158        // iPhone and macOS should be preserved
1159        assert!(result[0].message.contains("iPhone"));
1160        assert!(result[0].message.contains("macOS"));
1161    }
1162
1163    #[test]
1164    fn test_preserve_cased_words() {
1165        let rule = create_rule();
1166        let content = "# using GitHub actions\n";
1167        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1168        let result = rule.check(&ctx).unwrap();
1169        assert_eq!(result.len(), 1);
1170        // GitHub should be preserved (has internal capital)
1171        assert!(result[0].message.contains("GitHub"));
1172    }
1173
1174    // Inline code tests
1175    #[test]
1176    fn test_inline_code_preserved() {
1177        let rule = create_rule();
1178        let content = "# using `const` in javascript\n";
1179        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1180        let result = rule.check(&ctx).unwrap();
1181        assert_eq!(result.len(), 1);
1182        // `const` should be preserved, rest capitalized
1183        assert!(result[0].message.contains("`const`"));
1184        assert!(result[0].message.contains("Javascript") || result[0].message.contains("JavaScript"));
1185    }
1186
1187    // Level filter tests
1188    #[test]
1189    fn test_level_filter() {
1190        let config = MD063Config {
1191            enabled: true,
1192            min_level: 2,
1193            max_level: 4,
1194            ..Default::default()
1195        };
1196        let rule = MD063HeadingCapitalization::from_config_struct(config);
1197
1198        let content = "# h1 heading\n## h2 heading\n### h3 heading\n##### h5 heading\n";
1199        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1200        let result = rule.check(&ctx).unwrap();
1201
1202        // Only h2 and h3 should be flagged (h1 < min_level, h5 > max_level)
1203        assert_eq!(result.len(), 2);
1204        assert_eq!(result[0].line, 2); // h2
1205        assert_eq!(result[1].line, 3); // h3
1206    }
1207
1208    // Fix tests
1209    #[test]
1210    fn test_fix_atx_heading() {
1211        let rule = create_rule();
1212        let content = "# hello world\n";
1213        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1214        let fixed = rule.fix(&ctx).unwrap();
1215        assert_eq!(fixed, "# Hello World\n");
1216    }
1217
1218    #[test]
1219    fn test_fix_multiple_headings() {
1220        let rule = create_rule();
1221        let content = "# first heading\n\n## second heading\n";
1222        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1223        let fixed = rule.fix(&ctx).unwrap();
1224        assert_eq!(fixed, "# First Heading\n\n## Second Heading\n");
1225    }
1226
1227    // Setext heading tests
1228    #[test]
1229    fn test_setext_heading() {
1230        let rule = create_rule();
1231        let content = "hello world\n============\n";
1232        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1233        let result = rule.check(&ctx).unwrap();
1234        assert_eq!(result.len(), 1);
1235        assert!(result[0].message.contains("Hello World"));
1236    }
1237
1238    // Custom ID tests
1239    #[test]
1240    fn test_custom_id_preserved() {
1241        let rule = create_rule();
1242        let content = "# getting started {#intro}\n";
1243        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1244        let result = rule.check(&ctx).unwrap();
1245        assert_eq!(result.len(), 1);
1246        // Custom ID should be preserved
1247        assert!(result[0].message.contains("{#intro}"));
1248    }
1249
1250    // Acronym preservation tests
1251    #[test]
1252    fn test_preserve_all_caps_acronyms() {
1253        let rule = create_rule();
1254        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1255
1256        // Basic acronyms should be preserved
1257        let fixed = rule.fix(&ctx("# using API in production\n")).unwrap();
1258        assert_eq!(fixed, "# Using API in Production\n");
1259
1260        // Multiple acronyms
1261        let fixed = rule.fix(&ctx("# API and GPU integration\n")).unwrap();
1262        assert_eq!(fixed, "# API and GPU Integration\n");
1263
1264        // Two-letter acronyms
1265        let fixed = rule.fix(&ctx("# IO performance guide\n")).unwrap();
1266        assert_eq!(fixed, "# IO Performance Guide\n");
1267
1268        // Acronyms with numbers
1269        let fixed = rule.fix(&ctx("# HTTP2 and MD5 hashing\n")).unwrap();
1270        assert_eq!(fixed, "# HTTP2 and MD5 Hashing\n");
1271    }
1272
1273    #[test]
1274    fn test_preserve_acronyms_in_hyphenated_words() {
1275        let rule = create_rule();
1276        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1277
1278        // Acronyms at start of hyphenated word
1279        let fixed = rule.fix(&ctx("# API-driven architecture\n")).unwrap();
1280        assert_eq!(fixed, "# API-Driven Architecture\n");
1281
1282        // Multiple acronyms with hyphens
1283        let fixed = rule.fix(&ctx("# GPU-accelerated CPU-intensive tasks\n")).unwrap();
1284        assert_eq!(fixed, "# GPU-Accelerated CPU-Intensive Tasks\n");
1285    }
1286
1287    #[test]
1288    fn test_single_letters_not_treated_as_acronyms() {
1289        let rule = create_rule();
1290        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1291
1292        // Single uppercase letters should follow title case rules, not be preserved
1293        let fixed = rule.fix(&ctx("# i am a heading\n")).unwrap();
1294        assert_eq!(fixed, "# I Am a Heading\n");
1295    }
1296
1297    #[test]
1298    fn test_lowercase_terms_need_ignore_words() {
1299        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1300
1301        // Without ignore_words: npm gets capitalized
1302        let rule = create_rule();
1303        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1304        assert_eq!(fixed, "# Using Npm Packages\n");
1305
1306        // With ignore_words: npm preserved
1307        let config = MD063Config {
1308            enabled: true,
1309            ignore_words: vec!["npm".to_string()],
1310            ..Default::default()
1311        };
1312        let rule = MD063HeadingCapitalization::from_config_struct(config);
1313        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1314        assert_eq!(fixed, "# Using npm Packages\n");
1315    }
1316
1317    #[test]
1318    fn test_acronyms_with_mixed_case_preserved() {
1319        let rule = create_rule();
1320        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1321
1322        // Both acronyms (API, GPU) and mixed-case (GitHub) should be preserved
1323        let fixed = rule.fix(&ctx("# using API with GitHub\n")).unwrap();
1324        assert_eq!(fixed, "# Using API with GitHub\n");
1325    }
1326
1327    #[test]
1328    fn test_real_world_acronyms() {
1329        let rule = create_rule();
1330        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1331
1332        // Common technical acronyms from tested repositories
1333        let content = "# FFI bindings for CPU optimization\n";
1334        let fixed = rule.fix(&ctx(content)).unwrap();
1335        assert_eq!(fixed, "# FFI Bindings for CPU Optimization\n");
1336
1337        let content = "# DOM manipulation and SSR rendering\n";
1338        let fixed = rule.fix(&ctx(content)).unwrap();
1339        assert_eq!(fixed, "# DOM Manipulation and SSR Rendering\n");
1340
1341        let content = "# CVE security and RNN models\n";
1342        let fixed = rule.fix(&ctx(content)).unwrap();
1343        assert_eq!(fixed, "# CVE Security and RNN Models\n");
1344    }
1345
1346    #[test]
1347    fn test_is_all_caps_acronym() {
1348        let rule = create_rule();
1349
1350        // Should return true for all-caps with 2+ letters
1351        assert!(rule.is_all_caps_acronym("API"));
1352        assert!(rule.is_all_caps_acronym("IO"));
1353        assert!(rule.is_all_caps_acronym("GPU"));
1354        assert!(rule.is_all_caps_acronym("HTTP2")); // Numbers don't break it
1355
1356        // Should return false for single letters
1357        assert!(!rule.is_all_caps_acronym("A"));
1358        assert!(!rule.is_all_caps_acronym("I"));
1359
1360        // Should return false for words with lowercase
1361        assert!(!rule.is_all_caps_acronym("Api"));
1362        assert!(!rule.is_all_caps_acronym("npm"));
1363        assert!(!rule.is_all_caps_acronym("iPhone"));
1364    }
1365
1366    #[test]
1367    fn test_sentence_case_ignore_words_first_word() {
1368        let config = MD063Config {
1369            enabled: true,
1370            style: HeadingCapStyle::SentenceCase,
1371            ignore_words: vec!["nvim".to_string()],
1372            ..Default::default()
1373        };
1374        let rule = MD063HeadingCapitalization::from_config_struct(config);
1375
1376        // "nvim" as first word should be preserved exactly
1377        let content = "# nvim config\n";
1378        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1379        let result = rule.check(&ctx).unwrap();
1380        assert!(
1381            result.is_empty(),
1382            "nvim in ignore-words should not be flagged. Got: {result:?}"
1383        );
1384
1385        // Verify fix also preserves it
1386        let fixed = rule.fix(&ctx).unwrap();
1387        assert_eq!(fixed, "# nvim config\n");
1388    }
1389
1390    #[test]
1391    fn test_sentence_case_ignore_words_not_first() {
1392        let config = MD063Config {
1393            enabled: true,
1394            style: HeadingCapStyle::SentenceCase,
1395            ignore_words: vec!["nvim".to_string()],
1396            ..Default::default()
1397        };
1398        let rule = MD063HeadingCapitalization::from_config_struct(config);
1399
1400        // "nvim" in middle should also be preserved
1401        let content = "# Using nvim editor\n";
1402        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1403        let result = rule.check(&ctx).unwrap();
1404        assert!(
1405            result.is_empty(),
1406            "nvim in ignore-words should be preserved. Got: {result:?}"
1407        );
1408    }
1409
1410    #[test]
1411    fn test_preserve_cased_words_ios() {
1412        let config = MD063Config {
1413            enabled: true,
1414            style: HeadingCapStyle::SentenceCase,
1415            preserve_cased_words: true,
1416            ..Default::default()
1417        };
1418        let rule = MD063HeadingCapitalization::from_config_struct(config);
1419
1420        // "iOS" should be preserved (has mixed case: lowercase 'i' + uppercase 'OS')
1421        let content = "## This is iOS\n";
1422        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1423        let result = rule.check(&ctx).unwrap();
1424        assert!(
1425            result.is_empty(),
1426            "iOS should be preserved with preserve-cased-words. Got: {result:?}"
1427        );
1428
1429        // Verify fix also preserves it
1430        let fixed = rule.fix(&ctx).unwrap();
1431        assert_eq!(fixed, "## This is iOS\n");
1432    }
1433
1434    #[test]
1435    fn test_preserve_cased_words_ios_title_case() {
1436        let config = MD063Config {
1437            enabled: true,
1438            style: HeadingCapStyle::TitleCase,
1439            preserve_cased_words: true,
1440            ..Default::default()
1441        };
1442        let rule = MD063HeadingCapitalization::from_config_struct(config);
1443
1444        // "iOS" should be preserved in title case too
1445        let content = "# developing for iOS\n";
1446        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1447        let fixed = rule.fix(&ctx).unwrap();
1448        assert_eq!(fixed, "# Developing for iOS\n");
1449    }
1450
1451    #[test]
1452    fn test_has_internal_capitals_ios() {
1453        let rule = create_rule();
1454
1455        // iOS should be detected as having internal capitals
1456        assert!(
1457            rule.has_internal_capitals("iOS"),
1458            "iOS has mixed case (lowercase i, uppercase OS)"
1459        );
1460
1461        // Other mixed-case words
1462        assert!(rule.has_internal_capitals("iPhone"));
1463        assert!(rule.has_internal_capitals("macOS"));
1464        assert!(rule.has_internal_capitals("GitHub"));
1465        assert!(rule.has_internal_capitals("JavaScript"));
1466        assert!(rule.has_internal_capitals("eBay"));
1467
1468        // All-caps should NOT be detected (handled by is_all_caps_acronym)
1469        assert!(!rule.has_internal_capitals("API"));
1470        assert!(!rule.has_internal_capitals("GPU"));
1471
1472        // All-lowercase should NOT be detected
1473        assert!(!rule.has_internal_capitals("npm"));
1474        assert!(!rule.has_internal_capitals("config"));
1475
1476        // Regular capitalized words should NOT be detected
1477        assert!(!rule.has_internal_capitals("The"));
1478        assert!(!rule.has_internal_capitals("Hello"));
1479    }
1480
1481    #[test]
1482    fn test_lowercase_words_before_trailing_code() {
1483        let config = MD063Config {
1484            enabled: true,
1485            style: HeadingCapStyle::TitleCase,
1486            lowercase_words: vec![
1487                "a".to_string(),
1488                "an".to_string(),
1489                "and".to_string(),
1490                "at".to_string(),
1491                "but".to_string(),
1492                "by".to_string(),
1493                "for".to_string(),
1494                "from".to_string(),
1495                "into".to_string(),
1496                "nor".to_string(),
1497                "on".to_string(),
1498                "onto".to_string(),
1499                "or".to_string(),
1500                "the".to_string(),
1501                "to".to_string(),
1502                "upon".to_string(),
1503                "via".to_string(),
1504                "vs".to_string(),
1505                "with".to_string(),
1506                "without".to_string(),
1507            ],
1508            preserve_cased_words: true,
1509            ..Default::default()
1510        };
1511        let rule = MD063HeadingCapitalization::from_config_struct(config);
1512
1513        // Test: "subtitle with a `app`" (all lowercase input)
1514        // Expected fix: "Subtitle With a `app`" - capitalize "Subtitle" and "With",
1515        // but keep "a" lowercase (it's in lowercase-words and not the last word)
1516        // Incorrect: "Subtitle with A `app`" (would incorrectly capitalize "a")
1517        let content = "## subtitle with a `app`\n";
1518        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1519        let result = rule.check(&ctx).unwrap();
1520
1521        // Should flag it
1522        assert!(!result.is_empty(), "Should flag incorrect capitalization");
1523        let fixed = rule.fix(&ctx).unwrap();
1524        // "a" should remain lowercase (not "A") because inline code at end doesn't change lowercase-words behavior
1525        assert!(
1526            fixed.contains("with a `app`"),
1527            "Expected 'with a `app`' but got: {fixed:?}"
1528        );
1529        assert!(
1530            !fixed.contains("with A `app`"),
1531            "Should not capitalize 'a' to 'A'. Got: {fixed:?}"
1532        );
1533        // "Subtitle" should be capitalized, "with" and "a" should remain lowercase (they're in lowercase-words)
1534        assert!(
1535            fixed.contains("Subtitle with a `app`"),
1536            "Expected 'Subtitle with a `app`' but got: {fixed:?}"
1537        );
1538    }
1539
1540    #[test]
1541    fn test_lowercase_words_preserved_before_trailing_code_variant() {
1542        let config = MD063Config {
1543            enabled: true,
1544            style: HeadingCapStyle::TitleCase,
1545            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1546            ..Default::default()
1547        };
1548        let rule = MD063HeadingCapitalization::from_config_struct(config);
1549
1550        // Another variant: "Title with the `code`"
1551        let content = "## Title with the `code`\n";
1552        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1553        let fixed = rule.fix(&ctx).unwrap();
1554        // "the" should remain lowercase
1555        assert!(
1556            fixed.contains("with the `code`"),
1557            "Expected 'with the `code`' but got: {fixed:?}"
1558        );
1559        assert!(
1560            !fixed.contains("with The `code`"),
1561            "Should not capitalize 'the' to 'The'. Got: {fixed:?}"
1562        );
1563    }
1564
1565    #[test]
1566    fn test_last_word_capitalized_when_no_trailing_code() {
1567        // Verify that when there's NO trailing code, the last word IS capitalized
1568        // (even if it's in lowercase-words) - this is the normal title case behavior
1569        let config = MD063Config {
1570            enabled: true,
1571            style: HeadingCapStyle::TitleCase,
1572            lowercase_words: vec!["a".to_string(), "the".to_string()],
1573            ..Default::default()
1574        };
1575        let rule = MD063HeadingCapitalization::from_config_struct(config);
1576
1577        // "title with a word" - "word" is last, should be capitalized
1578        // "a" is in lowercase-words and not last, so should be lowercase
1579        let content = "## title with a word\n";
1580        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1581        let fixed = rule.fix(&ctx).unwrap();
1582        // "a" should be lowercase, "word" should be capitalized (it's last)
1583        assert!(
1584            fixed.contains("With a Word"),
1585            "Expected 'With a Word' but got: {fixed:?}"
1586        );
1587    }
1588
1589    #[test]
1590    fn test_multiple_lowercase_words_before_code() {
1591        let config = MD063Config {
1592            enabled: true,
1593            style: HeadingCapStyle::TitleCase,
1594            lowercase_words: vec![
1595                "a".to_string(),
1596                "the".to_string(),
1597                "with".to_string(),
1598                "for".to_string(),
1599            ],
1600            ..Default::default()
1601        };
1602        let rule = MD063HeadingCapitalization::from_config_struct(config);
1603
1604        // Multiple lowercase words before code - all should remain lowercase
1605        let content = "## Guide for the `user`\n";
1606        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1607        let fixed = rule.fix(&ctx).unwrap();
1608        assert!(
1609            fixed.contains("for the `user`"),
1610            "Expected 'for the `user`' but got: {fixed:?}"
1611        );
1612        assert!(
1613            !fixed.contains("For The `user`"),
1614            "Should not capitalize lowercase words before code. Got: {fixed:?}"
1615        );
1616    }
1617
1618    #[test]
1619    fn test_code_in_middle_normal_rules_apply() {
1620        let config = MD063Config {
1621            enabled: true,
1622            style: HeadingCapStyle::TitleCase,
1623            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1624            ..Default::default()
1625        };
1626        let rule = MD063HeadingCapitalization::from_config_struct(config);
1627
1628        // Code in the middle - normal title case rules apply (last word capitalized)
1629        let content = "## Using `const` for the code\n";
1630        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1631        let fixed = rule.fix(&ctx).unwrap();
1632        // "for" and "the" should be lowercase (middle), "code" should be capitalized (last)
1633        assert!(
1634            fixed.contains("for the Code"),
1635            "Expected 'for the Code' but got: {fixed:?}"
1636        );
1637    }
1638
1639    #[test]
1640    fn test_link_at_end_same_as_code() {
1641        let config = MD063Config {
1642            enabled: true,
1643            style: HeadingCapStyle::TitleCase,
1644            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1645            ..Default::default()
1646        };
1647        let rule = MD063HeadingCapitalization::from_config_struct(config);
1648
1649        // Link at the end - same behavior as code (lowercase words before should remain lowercase)
1650        let content = "## Guide for the [link](./page.md)\n";
1651        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1652        let fixed = rule.fix(&ctx).unwrap();
1653        // "for" and "the" should remain lowercase (not last word because link follows)
1654        assert!(
1655            fixed.contains("for the [Link]"),
1656            "Expected 'for the [Link]' but got: {fixed:?}"
1657        );
1658        assert!(
1659            !fixed.contains("for The [Link]"),
1660            "Should not capitalize 'the' before link. Got: {fixed:?}"
1661        );
1662    }
1663
1664    #[test]
1665    fn test_multiple_code_segments() {
1666        let config = MD063Config {
1667            enabled: true,
1668            style: HeadingCapStyle::TitleCase,
1669            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1670            ..Default::default()
1671        };
1672        let rule = MD063HeadingCapitalization::from_config_struct(config);
1673
1674        // Multiple code segments - last segment is code, so lowercase words before should remain lowercase
1675        let content = "## Using `const` with a `variable`\n";
1676        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1677        let fixed = rule.fix(&ctx).unwrap();
1678        // "a" should remain lowercase (not last word because code follows)
1679        assert!(
1680            fixed.contains("with a `variable`"),
1681            "Expected 'with a `variable`' but got: {fixed:?}"
1682        );
1683        assert!(
1684            !fixed.contains("with A `variable`"),
1685            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1686        );
1687    }
1688
1689    #[test]
1690    fn test_code_and_link_combination() {
1691        let config = MD063Config {
1692            enabled: true,
1693            style: HeadingCapStyle::TitleCase,
1694            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1695            ..Default::default()
1696        };
1697        let rule = MD063HeadingCapitalization::from_config_struct(config);
1698
1699        // Code then link - last segment is link, so lowercase words before code should remain lowercase
1700        let content = "## Guide for the `code` [link](./page.md)\n";
1701        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1702        let fixed = rule.fix(&ctx).unwrap();
1703        // "for" and "the" should remain lowercase (not last word because link follows)
1704        assert!(
1705            fixed.contains("for the `code`"),
1706            "Expected 'for the `code`' but got: {fixed:?}"
1707        );
1708    }
1709
1710    #[test]
1711    fn test_text_after_code_capitalizes_last() {
1712        let config = MD063Config {
1713            enabled: true,
1714            style: HeadingCapStyle::TitleCase,
1715            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1716            ..Default::default()
1717        };
1718        let rule = MD063HeadingCapitalization::from_config_struct(config);
1719
1720        // Code in middle, text after - last word should be capitalized
1721        let content = "## Using `const` for the code\n";
1722        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1723        let fixed = rule.fix(&ctx).unwrap();
1724        // "for" and "the" should be lowercase, "code" is last word, should be capitalized
1725        assert!(
1726            fixed.contains("for the Code"),
1727            "Expected 'for the Code' but got: {fixed:?}"
1728        );
1729    }
1730
1731    #[test]
1732    fn test_preserve_cased_words_with_trailing_code() {
1733        let config = MD063Config {
1734            enabled: true,
1735            style: HeadingCapStyle::TitleCase,
1736            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1737            preserve_cased_words: true,
1738            ..Default::default()
1739        };
1740        let rule = MD063HeadingCapitalization::from_config_struct(config);
1741
1742        // Preserve-cased words should still work with trailing code
1743        let content = "## Guide for iOS `app`\n";
1744        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1745        let fixed = rule.fix(&ctx).unwrap();
1746        // "iOS" should be preserved, "for" should be lowercase
1747        assert!(
1748            fixed.contains("for iOS `app`"),
1749            "Expected 'for iOS `app`' but got: {fixed:?}"
1750        );
1751        assert!(
1752            !fixed.contains("For iOS `app`"),
1753            "Should not capitalize 'for' before trailing code. Got: {fixed:?}"
1754        );
1755    }
1756
1757    #[test]
1758    fn test_ignore_words_with_trailing_code() {
1759        let config = MD063Config {
1760            enabled: true,
1761            style: HeadingCapStyle::TitleCase,
1762            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1763            ignore_words: vec!["npm".to_string()],
1764            ..Default::default()
1765        };
1766        let rule = MD063HeadingCapitalization::from_config_struct(config);
1767
1768        // Ignore-words should still work with trailing code
1769        let content = "## Using npm with a `script`\n";
1770        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1771        let fixed = rule.fix(&ctx).unwrap();
1772        // "npm" should be preserved, "with" and "a" should be lowercase
1773        assert!(
1774            fixed.contains("npm with a `script`"),
1775            "Expected 'npm with a `script`' but got: {fixed:?}"
1776        );
1777        assert!(
1778            !fixed.contains("with A `script`"),
1779            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1780        );
1781    }
1782
1783    #[test]
1784    fn test_empty_text_segment_edge_case() {
1785        let config = MD063Config {
1786            enabled: true,
1787            style: HeadingCapStyle::TitleCase,
1788            lowercase_words: vec!["a".to_string(), "with".to_string()],
1789            ..Default::default()
1790        };
1791        let rule = MD063HeadingCapitalization::from_config_struct(config);
1792
1793        // Edge case: code at start, then text with lowercase word, then code at end
1794        let content = "## `start` with a `end`\n";
1795        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1796        let fixed = rule.fix(&ctx).unwrap();
1797        // "with" is first word in text segment, so capitalized (correct)
1798        // "a" should remain lowercase (not last word because code follows) - this is the key test
1799        assert!(fixed.contains("a `end`"), "Expected 'a `end`' but got: {fixed:?}");
1800        assert!(
1801            !fixed.contains("A `end`"),
1802            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1803        );
1804    }
1805
1806    #[test]
1807    fn test_sentence_case_with_trailing_code() {
1808        let config = MD063Config {
1809            enabled: true,
1810            style: HeadingCapStyle::SentenceCase,
1811            lowercase_words: vec!["a".to_string(), "the".to_string()],
1812            ..Default::default()
1813        };
1814        let rule = MD063HeadingCapitalization::from_config_struct(config);
1815
1816        // Sentence case should also respect lowercase words before code
1817        let content = "## guide for the `user`\n";
1818        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1819        let fixed = rule.fix(&ctx).unwrap();
1820        // First word capitalized, rest lowercase including "the" before code
1821        assert!(
1822            fixed.contains("Guide for the `user`"),
1823            "Expected 'Guide for the `user`' but got: {fixed:?}"
1824        );
1825    }
1826
1827    #[test]
1828    fn test_hyphenated_word_before_code() {
1829        let config = MD063Config {
1830            enabled: true,
1831            style: HeadingCapStyle::TitleCase,
1832            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1833            ..Default::default()
1834        };
1835        let rule = MD063HeadingCapitalization::from_config_struct(config);
1836
1837        // Hyphenated word before code - last part should respect lowercase-words
1838        let content = "## Self-contained with a `feature`\n";
1839        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1840        let fixed = rule.fix(&ctx).unwrap();
1841        // "with" and "a" should remain lowercase (not last word because code follows)
1842        assert!(
1843            fixed.contains("with a `feature`"),
1844            "Expected 'with a `feature`' but got: {fixed:?}"
1845        );
1846    }
1847
1848    // Issue #228: Sentence case with inline code at heading start
1849    // When a heading starts with inline code, the first word after the code
1850    // should NOT be capitalized because the heading already has a "first element"
1851
1852    #[test]
1853    fn test_sentence_case_code_at_start_basic() {
1854        // The exact case from issue #228
1855        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1856        let content = "# `rumdl` is a linter\n";
1857        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1858        let result = rule.check(&ctx).unwrap();
1859        // Should be correct as-is: code is first, "is" stays lowercase
1860        assert!(
1861            result.is_empty(),
1862            "Heading with code at start should not flag 'is' for capitalization. Got: {:?}",
1863            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1864        );
1865    }
1866
1867    #[test]
1868    fn test_sentence_case_code_at_start_incorrect_capitalization() {
1869        // Verify we detect incorrect capitalization after code at start
1870        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1871        let content = "# `rumdl` Is a Linter\n";
1872        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1873        let result = rule.check(&ctx).unwrap();
1874        // Should flag: "Is" and "Linter" should be lowercase
1875        assert_eq!(result.len(), 1, "Should detect incorrect capitalization");
1876        assert!(
1877            result[0].message.contains("`rumdl` is a linter"),
1878            "Should suggest lowercase after code. Got: {:?}",
1879            result[0].message
1880        );
1881    }
1882
1883    #[test]
1884    fn test_sentence_case_code_at_start_fix() {
1885        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1886        let content = "# `rumdl` Is A Linter\n";
1887        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1888        let fixed = rule.fix(&ctx).unwrap();
1889        assert!(
1890            fixed.contains("# `rumdl` is a linter"),
1891            "Should fix to lowercase after code. Got: {fixed:?}"
1892        );
1893    }
1894
1895    #[test]
1896    fn test_sentence_case_text_at_start_still_capitalizes() {
1897        // Ensure normal headings still capitalize first word
1898        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1899        let content = "# the quick brown fox\n";
1900        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1901        let result = rule.check(&ctx).unwrap();
1902        assert_eq!(result.len(), 1);
1903        assert!(
1904            result[0].message.contains("The quick brown fox"),
1905            "Text-first heading should capitalize first word. Got: {:?}",
1906            result[0].message
1907        );
1908    }
1909
1910    #[test]
1911    fn test_sentence_case_link_at_start() {
1912        // Links at start: link text is lowercased, following text also lowercase
1913        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1914        // Use lowercase link text to avoid link text case flagging
1915        let content = "# [api](api.md) reference guide\n";
1916        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1917        let result = rule.check(&ctx).unwrap();
1918        // "reference" should be lowercase (link is first)
1919        assert!(
1920            result.is_empty(),
1921            "Heading with link at start should not capitalize 'reference'. Got: {:?}",
1922            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1923        );
1924    }
1925
1926    #[test]
1927    fn test_sentence_case_link_preserves_acronyms() {
1928        // Acronyms in link text should be preserved (API, HTTP, etc.)
1929        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1930        let content = "# [API](api.md) Reference Guide\n";
1931        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1932        let result = rule.check(&ctx).unwrap();
1933        assert_eq!(result.len(), 1);
1934        // "API" should be preserved (acronym), "Reference Guide" should be lowercased
1935        assert!(
1936            result[0].message.contains("[API](api.md) reference guide"),
1937            "Should preserve acronym 'API' but lowercase following text. Got: {:?}",
1938            result[0].message
1939        );
1940    }
1941
1942    #[test]
1943    fn test_sentence_case_link_preserves_brand_names() {
1944        // Brand names with internal capitals should be preserved
1945        let config = MD063Config {
1946            enabled: true,
1947            style: HeadingCapStyle::SentenceCase,
1948            preserve_cased_words: true,
1949            ..Default::default()
1950        };
1951        let rule = MD063HeadingCapitalization::from_config_struct(config);
1952        let content = "# [iPhone](iphone.md) Features Guide\n";
1953        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1954        let result = rule.check(&ctx).unwrap();
1955        assert_eq!(result.len(), 1);
1956        // "iPhone" should be preserved, "Features Guide" should be lowercased
1957        assert!(
1958            result[0].message.contains("[iPhone](iphone.md) features guide"),
1959            "Should preserve 'iPhone' but lowercase following text. Got: {:?}",
1960            result[0].message
1961        );
1962    }
1963
1964    #[test]
1965    fn test_sentence_case_link_lowercases_regular_words() {
1966        // Regular words in link text should be lowercased
1967        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1968        let content = "# [Documentation](docs.md) Reference\n";
1969        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1970        let result = rule.check(&ctx).unwrap();
1971        assert_eq!(result.len(), 1);
1972        // "Documentation" should be lowercased (regular word)
1973        assert!(
1974            result[0].message.contains("[documentation](docs.md) reference"),
1975            "Should lowercase regular link text. Got: {:?}",
1976            result[0].message
1977        );
1978    }
1979
1980    #[test]
1981    fn test_sentence_case_link_at_start_correct_already() {
1982        // Link with correct casing should not be flagged
1983        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1984        let content = "# [API](api.md) reference guide\n";
1985        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1986        let result = rule.check(&ctx).unwrap();
1987        assert!(
1988            result.is_empty(),
1989            "Correctly cased heading with link should not be flagged. Got: {:?}",
1990            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1991        );
1992    }
1993
1994    #[test]
1995    fn test_sentence_case_link_github_preserved() {
1996        // GitHub should be preserved (internal capitals)
1997        let config = MD063Config {
1998            enabled: true,
1999            style: HeadingCapStyle::SentenceCase,
2000            preserve_cased_words: true,
2001            ..Default::default()
2002        };
2003        let rule = MD063HeadingCapitalization::from_config_struct(config);
2004        let content = "# [GitHub](gh.md) Repository Setup\n";
2005        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2006        let result = rule.check(&ctx).unwrap();
2007        assert_eq!(result.len(), 1);
2008        assert!(
2009            result[0].message.contains("[GitHub](gh.md) repository setup"),
2010            "Should preserve 'GitHub'. Got: {:?}",
2011            result[0].message
2012        );
2013    }
2014
2015    #[test]
2016    fn test_sentence_case_multiple_code_spans() {
2017        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2018        let content = "# `foo` and `bar` are methods\n";
2019        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2020        let result = rule.check(&ctx).unwrap();
2021        // All text after first code should be lowercase
2022        assert!(
2023            result.is_empty(),
2024            "Should not capitalize words between/after code spans. Got: {:?}",
2025            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2026        );
2027    }
2028
2029    #[test]
2030    fn test_sentence_case_code_only_heading() {
2031        // Heading with only code, no text
2032        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2033        let content = "# `rumdl`\n";
2034        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2035        let result = rule.check(&ctx).unwrap();
2036        assert!(
2037            result.is_empty(),
2038            "Code-only heading should be fine. Got: {:?}",
2039            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2040        );
2041    }
2042
2043    #[test]
2044    fn test_sentence_case_code_at_end() {
2045        // Heading ending with code, text before should still capitalize first word
2046        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2047        let content = "# install the `rumdl` tool\n";
2048        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2049        let result = rule.check(&ctx).unwrap();
2050        // "install" should be capitalized (first word), rest lowercase
2051        assert_eq!(result.len(), 1);
2052        assert!(
2053            result[0].message.contains("Install the `rumdl` tool"),
2054            "First word should still be capitalized when text comes first. Got: {:?}",
2055            result[0].message
2056        );
2057    }
2058
2059    #[test]
2060    fn test_sentence_case_code_in_middle() {
2061        // Code in middle, text at start should capitalize first word
2062        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2063        let content = "# using the `rumdl` linter for markdown\n";
2064        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2065        let result = rule.check(&ctx).unwrap();
2066        // "using" should be capitalized, rest lowercase
2067        assert_eq!(result.len(), 1);
2068        assert!(
2069            result[0].message.contains("Using the `rumdl` linter for markdown"),
2070            "First word should be capitalized. Got: {:?}",
2071            result[0].message
2072        );
2073    }
2074
2075    #[test]
2076    fn test_sentence_case_preserved_word_after_code() {
2077        // Preserved words (like iPhone) should stay preserved even after code
2078        let config = MD063Config {
2079            enabled: true,
2080            style: HeadingCapStyle::SentenceCase,
2081            preserve_cased_words: true,
2082            ..Default::default()
2083        };
2084        let rule = MD063HeadingCapitalization::from_config_struct(config);
2085        let content = "# `swift` iPhone development\n";
2086        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2087        let result = rule.check(&ctx).unwrap();
2088        // "iPhone" should be preserved, "development" lowercase
2089        assert!(
2090            result.is_empty(),
2091            "Preserved words after code should stay. Got: {:?}",
2092            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2093        );
2094    }
2095
2096    #[test]
2097    fn test_title_case_code_at_start_still_capitalizes() {
2098        // Title case should still capitalize words even after code at start
2099        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2100        let content = "# `api` quick start guide\n";
2101        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2102        let result = rule.check(&ctx).unwrap();
2103        // Title case: all major words capitalized
2104        assert_eq!(result.len(), 1);
2105        assert!(
2106            result[0].message.contains("Quick Start Guide") || result[0].message.contains("quick Start Guide"),
2107            "Title case should capitalize major words after code. Got: {:?}",
2108            result[0].message
2109        );
2110    }
2111
2112    // ======== HTML TAG TESTS ========
2113
2114    #[test]
2115    fn test_sentence_case_html_tag_at_start() {
2116        // HTML tag at start: text after should NOT capitalize first word
2117        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2118        let content = "# <kbd>Ctrl</kbd> is a Modifier Key\n";
2119        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2120        let result = rule.check(&ctx).unwrap();
2121        // "is", "a", "Modifier", "Key" should all be lowercase (except preserved words)
2122        assert_eq!(result.len(), 1);
2123        let fixed = rule.fix(&ctx).unwrap();
2124        assert_eq!(
2125            fixed, "# <kbd>Ctrl</kbd> is a modifier key\n",
2126            "Text after HTML at start should be lowercase"
2127        );
2128    }
2129
2130    #[test]
2131    fn test_sentence_case_html_tag_preserves_content() {
2132        // Content inside HTML tags should be preserved as-is
2133        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2134        let content = "# The <abbr>API</abbr> documentation guide\n";
2135        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2136        let result = rule.check(&ctx).unwrap();
2137        // "The" is first, "API" inside tag preserved, rest lowercase
2138        assert!(
2139            result.is_empty(),
2140            "HTML tag content should be preserved. Got: {:?}",
2141            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2142        );
2143    }
2144
2145    #[test]
2146    fn test_sentence_case_html_tag_at_start_with_acronym() {
2147        // HTML tag at start with acronym content
2148        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2149        let content = "# <abbr>API</abbr> Documentation Guide\n";
2150        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2151        let result = rule.check(&ctx).unwrap();
2152        assert_eq!(result.len(), 1);
2153        let fixed = rule.fix(&ctx).unwrap();
2154        assert_eq!(
2155            fixed, "# <abbr>API</abbr> documentation guide\n",
2156            "Text after HTML at start should be lowercase, HTML content preserved"
2157        );
2158    }
2159
2160    #[test]
2161    fn test_sentence_case_html_tag_in_middle() {
2162        // HTML tag in middle: first word still capitalized
2163        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2164        let content = "# using the <code>config</code> File\n";
2165        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2166        let result = rule.check(&ctx).unwrap();
2167        assert_eq!(result.len(), 1);
2168        let fixed = rule.fix(&ctx).unwrap();
2169        assert_eq!(
2170            fixed, "# Using the <code>config</code> file\n",
2171            "First word capitalized, HTML preserved, rest lowercase"
2172        );
2173    }
2174
2175    #[test]
2176    fn test_html_tag_strong_emphasis() {
2177        // <strong> tag handling
2178        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2179        let content = "# The <strong>Bold</strong> Way\n";
2180        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2181        let result = rule.check(&ctx).unwrap();
2182        assert_eq!(result.len(), 1);
2183        let fixed = rule.fix(&ctx).unwrap();
2184        assert_eq!(
2185            fixed, "# The <strong>Bold</strong> way\n",
2186            "<strong> tag content should be preserved"
2187        );
2188    }
2189
2190    #[test]
2191    fn test_html_tag_with_attributes() {
2192        // HTML tags with attributes should still be detected
2193        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2194        let content = "# <span class=\"highlight\">Important</span> Notice Here\n";
2195        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2196        let result = rule.check(&ctx).unwrap();
2197        assert_eq!(result.len(), 1);
2198        let fixed = rule.fix(&ctx).unwrap();
2199        assert_eq!(
2200            fixed, "# <span class=\"highlight\">Important</span> notice here\n",
2201            "HTML tag with attributes should be preserved"
2202        );
2203    }
2204
2205    #[test]
2206    fn test_multiple_html_tags() {
2207        // Multiple HTML tags in heading
2208        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2209        let content = "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to Copy Text\n";
2210        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2211        let result = rule.check(&ctx).unwrap();
2212        assert_eq!(result.len(), 1);
2213        let fixed = rule.fix(&ctx).unwrap();
2214        assert_eq!(
2215            fixed, "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy text\n",
2216            "Multiple HTML tags should all be preserved"
2217        );
2218    }
2219
2220    #[test]
2221    fn test_html_and_code_mixed() {
2222        // Mix of HTML tags and inline code
2223        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2224        let content = "# <kbd>Ctrl</kbd>+`v` Paste command\n";
2225        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2226        let result = rule.check(&ctx).unwrap();
2227        assert_eq!(result.len(), 1);
2228        let fixed = rule.fix(&ctx).unwrap();
2229        assert_eq!(
2230            fixed, "# <kbd>Ctrl</kbd>+`v` paste command\n",
2231            "HTML and code should both be preserved"
2232        );
2233    }
2234
2235    #[test]
2236    fn test_self_closing_html_tag() {
2237        // Self-closing tags like <br/>
2238        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2239        let content = "# Line one<br/>Line Two Here\n";
2240        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2241        let result = rule.check(&ctx).unwrap();
2242        assert_eq!(result.len(), 1);
2243        let fixed = rule.fix(&ctx).unwrap();
2244        assert_eq!(
2245            fixed, "# Line one<br/>line two here\n",
2246            "Self-closing HTML tags should be preserved"
2247        );
2248    }
2249
2250    #[test]
2251    fn test_title_case_with_html_tags() {
2252        // Title case with HTML tags
2253        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2254        let content = "# the <kbd>ctrl</kbd> key is a modifier\n";
2255        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2256        let result = rule.check(&ctx).unwrap();
2257        assert_eq!(result.len(), 1);
2258        let fixed = rule.fix(&ctx).unwrap();
2259        // "the" as first word should be "The", content inside <kbd> preserved
2260        assert!(
2261            fixed.contains("<kbd>ctrl</kbd>"),
2262            "HTML tag content should be preserved in title case. Got: {fixed}"
2263        );
2264        assert!(
2265            fixed.starts_with("# The ") || fixed.starts_with("# the "),
2266            "Title case should work with HTML. Got: {fixed}"
2267        );
2268    }
2269
2270    // ======== CARET NOTATION TESTS ========
2271
2272    #[test]
2273    fn test_sentence_case_preserves_caret_notation() {
2274        // Caret notation for control characters should be preserved
2275        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2276        let content = "## Ctrl+A, Ctrl+R output ^A, ^R on zsh\n";
2277        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2278        let result = rule.check(&ctx).unwrap();
2279        // Should not flag - ^A and ^R are preserved
2280        assert!(
2281            result.is_empty(),
2282            "Caret notation should be preserved. Got: {:?}",
2283            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2284        );
2285    }
2286
2287    #[test]
2288    fn test_sentence_case_caret_notation_various() {
2289        // Various caret notation patterns
2290        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2291
2292        // ^C for interrupt
2293        let content = "## Press ^C to cancel\n";
2294        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2295        let result = rule.check(&ctx).unwrap();
2296        assert!(
2297            result.is_empty(),
2298            "^C should be preserved. Got: {:?}",
2299            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2300        );
2301
2302        // ^Z for suspend
2303        let content = "## Use ^Z for background\n";
2304        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2305        let result = rule.check(&ctx).unwrap();
2306        assert!(
2307            result.is_empty(),
2308            "^Z should be preserved. Got: {:?}",
2309            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2310        );
2311
2312        // ^[ for escape
2313        let content = "## Press ^[ for escape\n";
2314        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2315        let result = rule.check(&ctx).unwrap();
2316        assert!(
2317            result.is_empty(),
2318            "^[ should be preserved. Got: {:?}",
2319            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2320        );
2321    }
2322
2323    #[test]
2324    fn test_caret_notation_detection() {
2325        let rule = create_rule();
2326
2327        // Valid caret notation
2328        assert!(rule.is_caret_notation("^A"));
2329        assert!(rule.is_caret_notation("^Z"));
2330        assert!(rule.is_caret_notation("^C"));
2331        assert!(rule.is_caret_notation("^@")); // NUL
2332        assert!(rule.is_caret_notation("^[")); // ESC
2333        assert!(rule.is_caret_notation("^]")); // GS
2334        assert!(rule.is_caret_notation("^^")); // RS
2335        assert!(rule.is_caret_notation("^_")); // US
2336
2337        // Not caret notation
2338        assert!(!rule.is_caret_notation("^a")); // lowercase
2339        assert!(!rule.is_caret_notation("A")); // no caret
2340        assert!(!rule.is_caret_notation("^")); // caret alone
2341        assert!(!rule.is_caret_notation("^1")); // digit
2342    }
2343
2344    // MD044 proper names integration tests
2345    //
2346    // When MD063 (sentence case) and MD044 (proper names) are both active, MD063 must
2347    // preserve the exact capitalization of MD044 proper names rather than lowercasing them.
2348    // Without this, the two rules oscillate: MD044 re-capitalizes what MD063 lowercases.
2349
2350    fn create_sentence_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2351        let config = MD063Config {
2352            enabled: true,
2353            style: HeadingCapStyle::SentenceCase,
2354            ..Default::default()
2355        };
2356        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2357        rule.proper_names = names;
2358        rule
2359    }
2360
2361    #[test]
2362    fn test_sentence_case_preserves_single_word_proper_name() {
2363        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2364        // "javascript" in non-first position should become "JavaScript", not "javascript"
2365        let content = "# installing javascript\n";
2366        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2367        let result = rule.check(&ctx).unwrap();
2368        assert_eq!(result.len(), 1, "Should flag the heading");
2369        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2370        assert!(
2371            fix_text.contains("JavaScript"),
2372            "Fix should preserve proper name 'JavaScript', got: {fix_text:?}"
2373        );
2374        assert!(
2375            !fix_text.contains("javascript"),
2376            "Fix should not have lowercase 'javascript', got: {fix_text:?}"
2377        );
2378    }
2379
2380    #[test]
2381    fn test_sentence_case_preserves_multi_word_proper_name() {
2382        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2383        // "Good Application" is a proper name; sentence case must not lowercase "Application"
2384        let content = "# using good application features\n";
2385        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2386        let result = rule.check(&ctx).unwrap();
2387        assert_eq!(result.len(), 1, "Should flag the heading");
2388        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2389        assert!(
2390            fix_text.contains("Good Application"),
2391            "Fix should preserve 'Good Application' as a phrase, got: {fix_text:?}"
2392        );
2393    }
2394
2395    #[test]
2396    fn test_sentence_case_proper_name_at_start_of_heading() {
2397        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2398        // The proper name "Good Application" starts the heading; both words must be canonical
2399        let content = "# good application overview\n";
2400        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2401        let result = rule.check(&ctx).unwrap();
2402        assert_eq!(result.len(), 1, "Should flag the heading");
2403        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2404        assert!(
2405            fix_text.contains("Good Application"),
2406            "Fix should produce 'Good Application' at start of heading, got: {fix_text:?}"
2407        );
2408        assert!(
2409            fix_text.contains("overview"),
2410            "Non-proper-name word 'overview' should be lowercase, got: {fix_text:?}"
2411        );
2412    }
2413
2414    #[test]
2415    fn test_sentence_case_with_proper_names_no_oscillation() {
2416        // This is the core convergence test: applying the fix once must produce
2417        // output that is already correct (no further changes needed).
2418        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2419
2420        // First application of fix
2421        let content = "# installing good application on your system\n";
2422        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2423        let result = rule.check(&ctx).unwrap();
2424        assert_eq!(result.len(), 1);
2425        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2426
2427        // The fixed heading should contain the proper name preserved
2428        assert!(
2429            fixed_heading.contains("Good Application"),
2430            "After fix, proper name must be preserved: {fixed_heading:?}"
2431        );
2432
2433        // Second application: must produce no further warnings (convergence)
2434        let fixed_line = format!("{fixed_heading}\n");
2435        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2436        let result2 = rule.check(&ctx2).unwrap();
2437        assert!(
2438            result2.is_empty(),
2439            "After one fix, heading must already satisfy both MD063 and MD044 - no oscillation. \
2440             Second pass warnings: {result2:?}"
2441        );
2442    }
2443
2444    #[test]
2445    fn test_sentence_case_proper_names_already_correct() {
2446        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2447        // Heading already has correct sentence case with proper name preserved
2448        let content = "# Installing Good Application\n";
2449        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2450        let result = rule.check(&ctx).unwrap();
2451        assert!(
2452            result.is_empty(),
2453            "Correct sentence-case heading with proper name should not be flagged, got: {result:?}"
2454        );
2455    }
2456
2457    #[test]
2458    fn test_sentence_case_multiple_proper_names_in_heading() {
2459        let rule = create_sentence_case_rule_with_proper_names(vec!["TypeScript".to_string(), "React".to_string()]);
2460        let content = "# using typescript with react\n";
2461        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2462        let result = rule.check(&ctx).unwrap();
2463        assert_eq!(result.len(), 1);
2464        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2465        assert!(
2466            fix_text.contains("TypeScript"),
2467            "Fix should preserve 'TypeScript', got: {fix_text:?}"
2468        );
2469        assert!(
2470            fix_text.contains("React"),
2471            "Fix should preserve 'React', got: {fix_text:?}"
2472        );
2473    }
2474
2475    #[test]
2476    fn test_sentence_case_unicode_casefold_expansion_before_proper_name() {
2477        // Regression for Unicode case-fold expansion: `İ` lowercases to `i̇` (2 code points),
2478        // so matching offsets must be computed from the original text, not from a lowercased copy.
2479        let rule = create_sentence_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2480        let content = "# İ österreich guide\n";
2481        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2482
2483        // Should not panic and should preserve canonical proper-name casing.
2484        let result = rule.check(&ctx).unwrap();
2485        assert_eq!(result.len(), 1, "Should flag heading for canonical proper-name casing");
2486        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2487        assert!(
2488            fix_text.contains("Österreich"),
2489            "Fix should preserve canonical 'Österreich', got: {fix_text:?}"
2490        );
2491    }
2492
2493    #[test]
2494    fn test_sentence_case_preserves_trailing_punctuation_on_proper_name() {
2495        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2496        let content = "# using javascript, today\n";
2497        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2498        let result = rule.check(&ctx).unwrap();
2499        assert_eq!(result.len(), 1, "Should flag heading");
2500        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2501        assert!(
2502            fix_text.contains("JavaScript,"),
2503            "Fix should preserve trailing punctuation, got: {fix_text:?}"
2504        );
2505    }
2506
2507    // Title case + MD044 conflict tests
2508    //
2509    // In title case, short words like "the", "a", "of" are kept lowercase by MD063.
2510    // If those words are part of an MD044 proper name (e.g. "The Rolling Stones"),
2511    // the same oscillation problem occurs.  The fix must extend to title case too.
2512
2513    fn create_title_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2514        let config = MD063Config {
2515            enabled: true,
2516            style: HeadingCapStyle::TitleCase,
2517            ..Default::default()
2518        };
2519        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2520        rule.proper_names = names;
2521        rule
2522    }
2523
2524    #[test]
2525    fn test_title_case_preserves_proper_name_with_lowercase_article() {
2526        // "The" is in the lowercase_words list for title case, so "the" in the middle
2527        // of a heading would normally stay lowercase.  But "The Rolling Stones" is a
2528        // proper name that must be capitalised exactly.
2529        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2530        let content = "# listening to the rolling stones today\n";
2531        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2532        let result = rule.check(&ctx).unwrap();
2533        assert_eq!(result.len(), 1, "Should flag the heading");
2534        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2535        assert!(
2536            fix_text.contains("The Rolling Stones"),
2537            "Fix should preserve proper name 'The Rolling Stones', got: {fix_text:?}"
2538        );
2539    }
2540
2541    #[test]
2542    fn test_title_case_proper_name_no_oscillation() {
2543        // One fix pass must produce output that title case already accepts.
2544        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2545        let content = "# listening to the rolling stones today\n";
2546        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2547        let result = rule.check(&ctx).unwrap();
2548        assert_eq!(result.len(), 1);
2549        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2550
2551        let fixed_line = format!("{fixed_heading}\n");
2552        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2553        let result2 = rule.check(&ctx2).unwrap();
2554        assert!(
2555            result2.is_empty(),
2556            "After one title-case fix, heading must already satisfy both rules. \
2557             Second pass warnings: {result2:?}"
2558        );
2559    }
2560
2561    #[test]
2562    fn test_title_case_unicode_casefold_expansion_before_proper_name() {
2563        let rule = create_title_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2564        let content = "# İ österreich guide\n";
2565        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2566        let result = rule.check(&ctx).unwrap();
2567        assert_eq!(result.len(), 1, "Should flag the heading");
2568        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2569        assert!(
2570            fix_text.contains("Österreich"),
2571            "Fix should preserve canonical proper-name casing, got: {fix_text:?}"
2572        );
2573    }
2574
2575    // End-to-end integration test: from_config wires MD044 names into MD063
2576    //
2577    // This tests the actual code path used in production, where both rules are
2578    // configured in a rumdl.toml and the rule registry calls from_config.
2579
2580    #[test]
2581    fn test_from_config_loads_md044_names_into_md063() {
2582        use crate::config::{Config, RuleConfig};
2583        use crate::rule::Rule;
2584        use std::collections::BTreeMap;
2585
2586        let mut config = Config::default();
2587
2588        // Configure MD063 with sentence_case
2589        let mut md063_values = BTreeMap::new();
2590        md063_values.insert("style".to_string(), toml::Value::String("sentence_case".to_string()));
2591        md063_values.insert("enabled".to_string(), toml::Value::Boolean(true));
2592        config.rules.insert(
2593            "MD063".to_string(),
2594            RuleConfig {
2595                values: md063_values,
2596                severity: None,
2597            },
2598        );
2599
2600        // Configure MD044 with a proper name
2601        let mut md044_values = BTreeMap::new();
2602        md044_values.insert(
2603            "names".to_string(),
2604            toml::Value::Array(vec![toml::Value::String("Good Application".to_string())]),
2605        );
2606        config.rules.insert(
2607            "MD044".to_string(),
2608            RuleConfig {
2609                values: md044_values,
2610                severity: None,
2611            },
2612        );
2613
2614        // Build MD063 via the production code path
2615        let rule = MD063HeadingCapitalization::from_config(&config);
2616
2617        // Verify MD044 names were loaded: the fix must preserve "Good Application"
2618        let content = "# using good application features\n";
2619        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2620        let result = rule.check(&ctx).unwrap();
2621        assert_eq!(result.len(), 1, "Should flag the heading");
2622        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2623        assert!(
2624            fix_text.contains("Good Application"),
2625            "from_config should wire MD044 names into MD063; fix should preserve \
2626             'Good Application', got: {fix_text:?}"
2627        );
2628    }
2629
2630    #[test]
2631    fn test_title_case_short_word_not_confused_with_substring() {
2632        // Verify that short preposition matching ("in") does not trigger on
2633        // substrings of longer words ("insert"). Title case must capitalize
2634        // "insert" while keeping "in" lowercase.
2635        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2636
2637        // "in" is a short preposition (should be lowercase in title case)
2638        // "insert" contains "in" as substring but is a regular word (should be capitalized)
2639        let content = "# in the insert\n";
2640        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2641        let result = rule.check(&ctx).unwrap();
2642        assert_eq!(result.len(), 1, "Should flag the heading");
2643        let fix = result[0].fix.as_ref().expect("Fix should be present");
2644        // "In" capitalized as first word, "the" lowercase as article, "Insert" capitalized
2645        assert!(
2646            fix.replacement.contains("In the Insert"),
2647            "Expected 'In the Insert', got: {:?}",
2648            fix.replacement
2649        );
2650    }
2651
2652    #[test]
2653    fn test_title_case_or_not_confused_with_orchestra() {
2654        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2655
2656        // "or" is a conjunction (should be lowercase in title case)
2657        // "orchestra" contains "or" as substring but is a regular word
2658        let content = "# or the orchestra\n";
2659        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2660        let result = rule.check(&ctx).unwrap();
2661        assert_eq!(result.len(), 1, "Should flag the heading");
2662        let fix = result[0].fix.as_ref().expect("Fix should be present");
2663        // "Or" capitalized as first word, "the" lowercase, "Orchestra" capitalized
2664        assert!(
2665            fix.replacement.contains("Or the Orchestra"),
2666            "Expected 'Or the Orchestra', got: {:?}",
2667            fix.replacement
2668        );
2669    }
2670
2671    #[test]
2672    fn test_all_caps_preserves_all_words() {
2673        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
2674
2675        let content = "# in the insert\n";
2676        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2677        let result = rule.check(&ctx).unwrap();
2678        assert_eq!(result.len(), 1, "Should flag the heading");
2679        let fix = result[0].fix.as_ref().expect("Fix should be present");
2680        assert!(
2681            fix.replacement.contains("IN THE INSERT"),
2682            "All caps should uppercase all words, got: {:?}",
2683            fix.replacement
2684        );
2685    }
2686}