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, RuleCategory, 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 category(&self) -> RuleCategory {
913        RuleCategory::Heading
914    }
915
916    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
917        !ctx.likely_has_headings() || !ctx.lines.iter().any(|line| line.heading.is_some())
918    }
919
920    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
921        let content = ctx.content;
922
923        if content.is_empty() {
924            return Ok(Vec::new());
925        }
926
927        let mut warnings = Vec::new();
928        let line_index = &ctx.line_index;
929
930        for (line_num, line_info) in ctx.lines.iter().enumerate() {
931            if let Some(heading) = &line_info.heading {
932                // Check level filter
933                if heading.level < self.config.min_level || heading.level > self.config.max_level {
934                    continue;
935                }
936
937                // Skip headings in code blocks (indented headings)
938                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
939                    continue;
940                }
941
942                // Apply capitalization and compare
943                let original_text = &heading.raw_text;
944                let fixed_text = self.apply_capitalization(original_text);
945
946                if original_text != &fixed_text {
947                    let line = line_info.content(ctx.content);
948                    let style_name = match self.config.style {
949                        HeadingCapStyle::TitleCase => "title case",
950                        HeadingCapStyle::SentenceCase => "sentence case",
951                        HeadingCapStyle::AllCaps => "ALL CAPS",
952                    };
953
954                    warnings.push(LintWarning {
955                        rule_name: Some(self.name().to_string()),
956                        line: line_num + 1,
957                        column: heading.content_column + 1,
958                        end_line: line_num + 1,
959                        end_column: heading.content_column + 1 + original_text.len(),
960                        message: format!("Heading should use {style_name}: '{original_text}' -> '{fixed_text}'"),
961                        severity: Severity::Warning,
962                        fix: Some(Fix {
963                            range: self.get_line_byte_range(content, line_num + 1, line_index),
964                            replacement: match heading.style {
965                                crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
966                                _ => self.fix_setext_heading(line, heading),
967                            },
968                        }),
969                    });
970                }
971            }
972        }
973
974        Ok(warnings)
975    }
976
977    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
978        let content = ctx.content;
979
980        if content.is_empty() {
981            return Ok(content.to_string());
982        }
983
984        let lines = ctx.raw_lines();
985        let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
986
987        for (line_num, line_info) in ctx.lines.iter().enumerate() {
988            // Skip lines where the rule is disabled via inline config
989            if ctx.is_rule_disabled(self.name(), line_num + 1) {
990                continue;
991            }
992
993            if let Some(heading) = &line_info.heading {
994                // Check level filter
995                if heading.level < self.config.min_level || heading.level > self.config.max_level {
996                    continue;
997                }
998
999                // Skip headings in code blocks
1000                if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
1001                    continue;
1002                }
1003
1004                let original_text = &heading.raw_text;
1005                let fixed_text = self.apply_capitalization(original_text);
1006
1007                if original_text != &fixed_text {
1008                    let line = line_info.content(ctx.content);
1009                    fixed_lines[line_num] = match heading.style {
1010                        crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
1011                        _ => self.fix_setext_heading(line, heading),
1012                    };
1013                }
1014            }
1015        }
1016
1017        // Reconstruct content preserving line endings
1018        let mut result = String::with_capacity(content.len());
1019        for (i, line) in fixed_lines.iter().enumerate() {
1020            result.push_str(line);
1021            if i < fixed_lines.len() - 1 || content.ends_with('\n') {
1022                result.push('\n');
1023            }
1024        }
1025
1026        Ok(result)
1027    }
1028
1029    fn as_any(&self) -> &dyn std::any::Any {
1030        self
1031    }
1032
1033    fn default_config_section(&self) -> Option<(String, toml::Value)> {
1034        let json_value = serde_json::to_value(&self.config).ok()?;
1035        Some((
1036            self.name().to_string(),
1037            crate::rule_config_serde::json_to_toml_value(&json_value)?,
1038        ))
1039    }
1040
1041    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
1042    where
1043        Self: Sized,
1044    {
1045        let rule_config = crate::rule_config_serde::load_rule_config::<MD063Config>(config);
1046        let md044_config =
1047            crate::rule_config_serde::load_rule_config::<crate::rules::md044_proper_names::MD044Config>(config);
1048        let mut rule = Self::from_config_struct(rule_config);
1049        rule.proper_names = md044_config.names;
1050        Box::new(rule)
1051    }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056    use super::*;
1057    use crate::lint_context::LintContext;
1058
1059    fn create_rule() -> MD063HeadingCapitalization {
1060        let config = MD063Config {
1061            enabled: true,
1062            ..Default::default()
1063        };
1064        MD063HeadingCapitalization::from_config_struct(config)
1065    }
1066
1067    fn create_rule_with_style(style: HeadingCapStyle) -> MD063HeadingCapitalization {
1068        let config = MD063Config {
1069            enabled: true,
1070            style,
1071            ..Default::default()
1072        };
1073        MD063HeadingCapitalization::from_config_struct(config)
1074    }
1075
1076    // Title case tests
1077    #[test]
1078    fn test_title_case_basic() {
1079        let rule = create_rule();
1080        let content = "# hello world\n";
1081        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1082        let result = rule.check(&ctx).unwrap();
1083        assert_eq!(result.len(), 1);
1084        assert!(result[0].message.contains("Hello World"));
1085    }
1086
1087    #[test]
1088    fn test_title_case_lowercase_words() {
1089        let rule = create_rule();
1090        let content = "# the quick brown fox\n";
1091        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1092        let result = rule.check(&ctx).unwrap();
1093        assert_eq!(result.len(), 1);
1094        // "The" should be capitalized (first word), "quick", "brown", "fox" should be capitalized
1095        assert!(result[0].message.contains("The Quick Brown Fox"));
1096    }
1097
1098    #[test]
1099    fn test_title_case_already_correct() {
1100        let rule = create_rule();
1101        let content = "# The Quick Brown Fox\n";
1102        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1103        let result = rule.check(&ctx).unwrap();
1104        assert!(result.is_empty(), "Already correct heading should not be flagged");
1105    }
1106
1107    #[test]
1108    fn test_title_case_hyphenated() {
1109        let rule = create_rule();
1110        let content = "# self-documenting code\n";
1111        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1112        let result = rule.check(&ctx).unwrap();
1113        assert_eq!(result.len(), 1);
1114        assert!(result[0].message.contains("Self-Documenting Code"));
1115    }
1116
1117    // Sentence case tests
1118    #[test]
1119    fn test_sentence_case_basic() {
1120        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1121        let content = "# The Quick Brown Fox\n";
1122        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1123        let result = rule.check(&ctx).unwrap();
1124        assert_eq!(result.len(), 1);
1125        assert!(result[0].message.contains("The quick brown fox"));
1126    }
1127
1128    #[test]
1129    fn test_sentence_case_already_correct() {
1130        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1131        let content = "# The quick brown fox\n";
1132        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1133        let result = rule.check(&ctx).unwrap();
1134        assert!(result.is_empty());
1135    }
1136
1137    // All caps tests
1138    #[test]
1139    fn test_all_caps_basic() {
1140        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
1141        let content = "# hello world\n";
1142        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1143        let result = rule.check(&ctx).unwrap();
1144        assert_eq!(result.len(), 1);
1145        assert!(result[0].message.contains("HELLO WORLD"));
1146    }
1147
1148    // Preserve tests
1149    #[test]
1150    fn test_preserve_ignore_words() {
1151        let config = MD063Config {
1152            enabled: true,
1153            ignore_words: vec!["iPhone".to_string(), "macOS".to_string()],
1154            ..Default::default()
1155        };
1156        let rule = MD063HeadingCapitalization::from_config_struct(config);
1157
1158        let content = "# using iPhone on macOS\n";
1159        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1160        let result = rule.check(&ctx).unwrap();
1161        assert_eq!(result.len(), 1);
1162        // iPhone and macOS should be preserved
1163        assert!(result[0].message.contains("iPhone"));
1164        assert!(result[0].message.contains("macOS"));
1165    }
1166
1167    #[test]
1168    fn test_preserve_cased_words() {
1169        let rule = create_rule();
1170        let content = "# using GitHub actions\n";
1171        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1172        let result = rule.check(&ctx).unwrap();
1173        assert_eq!(result.len(), 1);
1174        // GitHub should be preserved (has internal capital)
1175        assert!(result[0].message.contains("GitHub"));
1176    }
1177
1178    // Inline code tests
1179    #[test]
1180    fn test_inline_code_preserved() {
1181        let rule = create_rule();
1182        let content = "# using `const` in javascript\n";
1183        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1184        let result = rule.check(&ctx).unwrap();
1185        assert_eq!(result.len(), 1);
1186        // `const` should be preserved, rest capitalized
1187        assert!(result[0].message.contains("`const`"));
1188        assert!(result[0].message.contains("Javascript") || result[0].message.contains("JavaScript"));
1189    }
1190
1191    // Level filter tests
1192    #[test]
1193    fn test_level_filter() {
1194        let config = MD063Config {
1195            enabled: true,
1196            min_level: 2,
1197            max_level: 4,
1198            ..Default::default()
1199        };
1200        let rule = MD063HeadingCapitalization::from_config_struct(config);
1201
1202        let content = "# h1 heading\n## h2 heading\n### h3 heading\n##### h5 heading\n";
1203        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1204        let result = rule.check(&ctx).unwrap();
1205
1206        // Only h2 and h3 should be flagged (h1 < min_level, h5 > max_level)
1207        assert_eq!(result.len(), 2);
1208        assert_eq!(result[0].line, 2); // h2
1209        assert_eq!(result[1].line, 3); // h3
1210    }
1211
1212    // Fix tests
1213    #[test]
1214    fn test_fix_atx_heading() {
1215        let rule = create_rule();
1216        let content = "# hello world\n";
1217        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1218        let fixed = rule.fix(&ctx).unwrap();
1219        assert_eq!(fixed, "# Hello World\n");
1220    }
1221
1222    #[test]
1223    fn test_fix_multiple_headings() {
1224        let rule = create_rule();
1225        let content = "# first heading\n\n## second heading\n";
1226        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1227        let fixed = rule.fix(&ctx).unwrap();
1228        assert_eq!(fixed, "# First Heading\n\n## Second Heading\n");
1229    }
1230
1231    // Setext heading tests
1232    #[test]
1233    fn test_setext_heading() {
1234        let rule = create_rule();
1235        let content = "hello world\n============\n";
1236        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1237        let result = rule.check(&ctx).unwrap();
1238        assert_eq!(result.len(), 1);
1239        assert!(result[0].message.contains("Hello World"));
1240    }
1241
1242    // Custom ID tests
1243    #[test]
1244    fn test_custom_id_preserved() {
1245        let rule = create_rule();
1246        let content = "# getting started {#intro}\n";
1247        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1248        let result = rule.check(&ctx).unwrap();
1249        assert_eq!(result.len(), 1);
1250        // Custom ID should be preserved
1251        assert!(result[0].message.contains("{#intro}"));
1252    }
1253
1254    // Acronym preservation tests
1255    #[test]
1256    fn test_preserve_all_caps_acronyms() {
1257        let rule = create_rule();
1258        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1259
1260        // Basic acronyms should be preserved
1261        let fixed = rule.fix(&ctx("# using API in production\n")).unwrap();
1262        assert_eq!(fixed, "# Using API in Production\n");
1263
1264        // Multiple acronyms
1265        let fixed = rule.fix(&ctx("# API and GPU integration\n")).unwrap();
1266        assert_eq!(fixed, "# API and GPU Integration\n");
1267
1268        // Two-letter acronyms
1269        let fixed = rule.fix(&ctx("# IO performance guide\n")).unwrap();
1270        assert_eq!(fixed, "# IO Performance Guide\n");
1271
1272        // Acronyms with numbers
1273        let fixed = rule.fix(&ctx("# HTTP2 and MD5 hashing\n")).unwrap();
1274        assert_eq!(fixed, "# HTTP2 and MD5 Hashing\n");
1275    }
1276
1277    #[test]
1278    fn test_preserve_acronyms_in_hyphenated_words() {
1279        let rule = create_rule();
1280        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1281
1282        // Acronyms at start of hyphenated word
1283        let fixed = rule.fix(&ctx("# API-driven architecture\n")).unwrap();
1284        assert_eq!(fixed, "# API-Driven Architecture\n");
1285
1286        // Multiple acronyms with hyphens
1287        let fixed = rule.fix(&ctx("# GPU-accelerated CPU-intensive tasks\n")).unwrap();
1288        assert_eq!(fixed, "# GPU-Accelerated CPU-Intensive Tasks\n");
1289    }
1290
1291    #[test]
1292    fn test_single_letters_not_treated_as_acronyms() {
1293        let rule = create_rule();
1294        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1295
1296        // Single uppercase letters should follow title case rules, not be preserved
1297        let fixed = rule.fix(&ctx("# i am a heading\n")).unwrap();
1298        assert_eq!(fixed, "# I Am a Heading\n");
1299    }
1300
1301    #[test]
1302    fn test_lowercase_terms_need_ignore_words() {
1303        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1304
1305        // Without ignore_words: npm gets capitalized
1306        let rule = create_rule();
1307        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1308        assert_eq!(fixed, "# Using Npm Packages\n");
1309
1310        // With ignore_words: npm preserved
1311        let config = MD063Config {
1312            enabled: true,
1313            ignore_words: vec!["npm".to_string()],
1314            ..Default::default()
1315        };
1316        let rule = MD063HeadingCapitalization::from_config_struct(config);
1317        let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1318        assert_eq!(fixed, "# Using npm Packages\n");
1319    }
1320
1321    #[test]
1322    fn test_acronyms_with_mixed_case_preserved() {
1323        let rule = create_rule();
1324        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1325
1326        // Both acronyms (API, GPU) and mixed-case (GitHub) should be preserved
1327        let fixed = rule.fix(&ctx("# using API with GitHub\n")).unwrap();
1328        assert_eq!(fixed, "# Using API with GitHub\n");
1329    }
1330
1331    #[test]
1332    fn test_real_world_acronyms() {
1333        let rule = create_rule();
1334        let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1335
1336        // Common technical acronyms from tested repositories
1337        let content = "# FFI bindings for CPU optimization\n";
1338        let fixed = rule.fix(&ctx(content)).unwrap();
1339        assert_eq!(fixed, "# FFI Bindings for CPU Optimization\n");
1340
1341        let content = "# DOM manipulation and SSR rendering\n";
1342        let fixed = rule.fix(&ctx(content)).unwrap();
1343        assert_eq!(fixed, "# DOM Manipulation and SSR Rendering\n");
1344
1345        let content = "# CVE security and RNN models\n";
1346        let fixed = rule.fix(&ctx(content)).unwrap();
1347        assert_eq!(fixed, "# CVE Security and RNN Models\n");
1348    }
1349
1350    #[test]
1351    fn test_is_all_caps_acronym() {
1352        let rule = create_rule();
1353
1354        // Should return true for all-caps with 2+ letters
1355        assert!(rule.is_all_caps_acronym("API"));
1356        assert!(rule.is_all_caps_acronym("IO"));
1357        assert!(rule.is_all_caps_acronym("GPU"));
1358        assert!(rule.is_all_caps_acronym("HTTP2")); // Numbers don't break it
1359
1360        // Should return false for single letters
1361        assert!(!rule.is_all_caps_acronym("A"));
1362        assert!(!rule.is_all_caps_acronym("I"));
1363
1364        // Should return false for words with lowercase
1365        assert!(!rule.is_all_caps_acronym("Api"));
1366        assert!(!rule.is_all_caps_acronym("npm"));
1367        assert!(!rule.is_all_caps_acronym("iPhone"));
1368    }
1369
1370    #[test]
1371    fn test_sentence_case_ignore_words_first_word() {
1372        let config = MD063Config {
1373            enabled: true,
1374            style: HeadingCapStyle::SentenceCase,
1375            ignore_words: vec!["nvim".to_string()],
1376            ..Default::default()
1377        };
1378        let rule = MD063HeadingCapitalization::from_config_struct(config);
1379
1380        // "nvim" as first word should be preserved exactly
1381        let content = "# nvim config\n";
1382        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1383        let result = rule.check(&ctx).unwrap();
1384        assert!(
1385            result.is_empty(),
1386            "nvim in ignore-words should not be flagged. Got: {result:?}"
1387        );
1388
1389        // Verify fix also preserves it
1390        let fixed = rule.fix(&ctx).unwrap();
1391        assert_eq!(fixed, "# nvim config\n");
1392    }
1393
1394    #[test]
1395    fn test_sentence_case_ignore_words_not_first() {
1396        let config = MD063Config {
1397            enabled: true,
1398            style: HeadingCapStyle::SentenceCase,
1399            ignore_words: vec!["nvim".to_string()],
1400            ..Default::default()
1401        };
1402        let rule = MD063HeadingCapitalization::from_config_struct(config);
1403
1404        // "nvim" in middle should also be preserved
1405        let content = "# Using nvim editor\n";
1406        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1407        let result = rule.check(&ctx).unwrap();
1408        assert!(
1409            result.is_empty(),
1410            "nvim in ignore-words should be preserved. Got: {result:?}"
1411        );
1412    }
1413
1414    #[test]
1415    fn test_preserve_cased_words_ios() {
1416        let config = MD063Config {
1417            enabled: true,
1418            style: HeadingCapStyle::SentenceCase,
1419            preserve_cased_words: true,
1420            ..Default::default()
1421        };
1422        let rule = MD063HeadingCapitalization::from_config_struct(config);
1423
1424        // "iOS" should be preserved (has mixed case: lowercase 'i' + uppercase 'OS')
1425        let content = "## This is iOS\n";
1426        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1427        let result = rule.check(&ctx).unwrap();
1428        assert!(
1429            result.is_empty(),
1430            "iOS should be preserved with preserve-cased-words. Got: {result:?}"
1431        );
1432
1433        // Verify fix also preserves it
1434        let fixed = rule.fix(&ctx).unwrap();
1435        assert_eq!(fixed, "## This is iOS\n");
1436    }
1437
1438    #[test]
1439    fn test_preserve_cased_words_ios_title_case() {
1440        let config = MD063Config {
1441            enabled: true,
1442            style: HeadingCapStyle::TitleCase,
1443            preserve_cased_words: true,
1444            ..Default::default()
1445        };
1446        let rule = MD063HeadingCapitalization::from_config_struct(config);
1447
1448        // "iOS" should be preserved in title case too
1449        let content = "# developing for iOS\n";
1450        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1451        let fixed = rule.fix(&ctx).unwrap();
1452        assert_eq!(fixed, "# Developing for iOS\n");
1453    }
1454
1455    #[test]
1456    fn test_has_internal_capitals_ios() {
1457        let rule = create_rule();
1458
1459        // iOS should be detected as having internal capitals
1460        assert!(
1461            rule.has_internal_capitals("iOS"),
1462            "iOS has mixed case (lowercase i, uppercase OS)"
1463        );
1464
1465        // Other mixed-case words
1466        assert!(rule.has_internal_capitals("iPhone"));
1467        assert!(rule.has_internal_capitals("macOS"));
1468        assert!(rule.has_internal_capitals("GitHub"));
1469        assert!(rule.has_internal_capitals("JavaScript"));
1470        assert!(rule.has_internal_capitals("eBay"));
1471
1472        // All-caps should NOT be detected (handled by is_all_caps_acronym)
1473        assert!(!rule.has_internal_capitals("API"));
1474        assert!(!rule.has_internal_capitals("GPU"));
1475
1476        // All-lowercase should NOT be detected
1477        assert!(!rule.has_internal_capitals("npm"));
1478        assert!(!rule.has_internal_capitals("config"));
1479
1480        // Regular capitalized words should NOT be detected
1481        assert!(!rule.has_internal_capitals("The"));
1482        assert!(!rule.has_internal_capitals("Hello"));
1483    }
1484
1485    #[test]
1486    fn test_lowercase_words_before_trailing_code() {
1487        let config = MD063Config {
1488            enabled: true,
1489            style: HeadingCapStyle::TitleCase,
1490            lowercase_words: vec![
1491                "a".to_string(),
1492                "an".to_string(),
1493                "and".to_string(),
1494                "at".to_string(),
1495                "but".to_string(),
1496                "by".to_string(),
1497                "for".to_string(),
1498                "from".to_string(),
1499                "into".to_string(),
1500                "nor".to_string(),
1501                "on".to_string(),
1502                "onto".to_string(),
1503                "or".to_string(),
1504                "the".to_string(),
1505                "to".to_string(),
1506                "upon".to_string(),
1507                "via".to_string(),
1508                "vs".to_string(),
1509                "with".to_string(),
1510                "without".to_string(),
1511            ],
1512            preserve_cased_words: true,
1513            ..Default::default()
1514        };
1515        let rule = MD063HeadingCapitalization::from_config_struct(config);
1516
1517        // Test: "subtitle with a `app`" (all lowercase input)
1518        // Expected fix: "Subtitle With a `app`" - capitalize "Subtitle" and "With",
1519        // but keep "a" lowercase (it's in lowercase-words and not the last word)
1520        // Incorrect: "Subtitle with A `app`" (would incorrectly capitalize "a")
1521        let content = "## subtitle with a `app`\n";
1522        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1523        let result = rule.check(&ctx).unwrap();
1524
1525        // Should flag it
1526        assert!(!result.is_empty(), "Should flag incorrect capitalization");
1527        let fixed = rule.fix(&ctx).unwrap();
1528        // "a" should remain lowercase (not "A") because inline code at end doesn't change lowercase-words behavior
1529        assert!(
1530            fixed.contains("with a `app`"),
1531            "Expected 'with a `app`' but got: {fixed:?}"
1532        );
1533        assert!(
1534            !fixed.contains("with A `app`"),
1535            "Should not capitalize 'a' to 'A'. Got: {fixed:?}"
1536        );
1537        // "Subtitle" should be capitalized, "with" and "a" should remain lowercase (they're in lowercase-words)
1538        assert!(
1539            fixed.contains("Subtitle with a `app`"),
1540            "Expected 'Subtitle with a `app`' but got: {fixed:?}"
1541        );
1542    }
1543
1544    #[test]
1545    fn test_lowercase_words_preserved_before_trailing_code_variant() {
1546        let config = MD063Config {
1547            enabled: true,
1548            style: HeadingCapStyle::TitleCase,
1549            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1550            ..Default::default()
1551        };
1552        let rule = MD063HeadingCapitalization::from_config_struct(config);
1553
1554        // Another variant: "Title with the `code`"
1555        let content = "## Title with the `code`\n";
1556        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1557        let fixed = rule.fix(&ctx).unwrap();
1558        // "the" should remain lowercase
1559        assert!(
1560            fixed.contains("with the `code`"),
1561            "Expected 'with the `code`' but got: {fixed:?}"
1562        );
1563        assert!(
1564            !fixed.contains("with The `code`"),
1565            "Should not capitalize 'the' to 'The'. Got: {fixed:?}"
1566        );
1567    }
1568
1569    #[test]
1570    fn test_last_word_capitalized_when_no_trailing_code() {
1571        // Verify that when there's NO trailing code, the last word IS capitalized
1572        // (even if it's in lowercase-words) - this is the normal title case behavior
1573        let config = MD063Config {
1574            enabled: true,
1575            style: HeadingCapStyle::TitleCase,
1576            lowercase_words: vec!["a".to_string(), "the".to_string()],
1577            ..Default::default()
1578        };
1579        let rule = MD063HeadingCapitalization::from_config_struct(config);
1580
1581        // "title with a word" - "word" is last, should be capitalized
1582        // "a" is in lowercase-words and not last, so should be lowercase
1583        let content = "## title with a word\n";
1584        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1585        let fixed = rule.fix(&ctx).unwrap();
1586        // "a" should be lowercase, "word" should be capitalized (it's last)
1587        assert!(
1588            fixed.contains("With a Word"),
1589            "Expected 'With a Word' but got: {fixed:?}"
1590        );
1591    }
1592
1593    #[test]
1594    fn test_multiple_lowercase_words_before_code() {
1595        let config = MD063Config {
1596            enabled: true,
1597            style: HeadingCapStyle::TitleCase,
1598            lowercase_words: vec![
1599                "a".to_string(),
1600                "the".to_string(),
1601                "with".to_string(),
1602                "for".to_string(),
1603            ],
1604            ..Default::default()
1605        };
1606        let rule = MD063HeadingCapitalization::from_config_struct(config);
1607
1608        // Multiple lowercase words before code - all should remain lowercase
1609        let content = "## Guide for the `user`\n";
1610        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1611        let fixed = rule.fix(&ctx).unwrap();
1612        assert!(
1613            fixed.contains("for the `user`"),
1614            "Expected 'for the `user`' but got: {fixed:?}"
1615        );
1616        assert!(
1617            !fixed.contains("For The `user`"),
1618            "Should not capitalize lowercase words before code. Got: {fixed:?}"
1619        );
1620    }
1621
1622    #[test]
1623    fn test_code_in_middle_normal_rules_apply() {
1624        let config = MD063Config {
1625            enabled: true,
1626            style: HeadingCapStyle::TitleCase,
1627            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1628            ..Default::default()
1629        };
1630        let rule = MD063HeadingCapitalization::from_config_struct(config);
1631
1632        // Code in the middle - normal title case rules apply (last word capitalized)
1633        let content = "## Using `const` for the code\n";
1634        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1635        let fixed = rule.fix(&ctx).unwrap();
1636        // "for" and "the" should be lowercase (middle), "code" should be capitalized (last)
1637        assert!(
1638            fixed.contains("for the Code"),
1639            "Expected 'for the Code' but got: {fixed:?}"
1640        );
1641    }
1642
1643    #[test]
1644    fn test_link_at_end_same_as_code() {
1645        let config = MD063Config {
1646            enabled: true,
1647            style: HeadingCapStyle::TitleCase,
1648            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1649            ..Default::default()
1650        };
1651        let rule = MD063HeadingCapitalization::from_config_struct(config);
1652
1653        // Link at the end - same behavior as code (lowercase words before should remain lowercase)
1654        let content = "## Guide for the [link](./page.md)\n";
1655        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1656        let fixed = rule.fix(&ctx).unwrap();
1657        // "for" and "the" should remain lowercase (not last word because link follows)
1658        assert!(
1659            fixed.contains("for the [Link]"),
1660            "Expected 'for the [Link]' but got: {fixed:?}"
1661        );
1662        assert!(
1663            !fixed.contains("for The [Link]"),
1664            "Should not capitalize 'the' before link. Got: {fixed:?}"
1665        );
1666    }
1667
1668    #[test]
1669    fn test_multiple_code_segments() {
1670        let config = MD063Config {
1671            enabled: true,
1672            style: HeadingCapStyle::TitleCase,
1673            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1674            ..Default::default()
1675        };
1676        let rule = MD063HeadingCapitalization::from_config_struct(config);
1677
1678        // Multiple code segments - last segment is code, so lowercase words before should remain lowercase
1679        let content = "## Using `const` with a `variable`\n";
1680        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1681        let fixed = rule.fix(&ctx).unwrap();
1682        // "a" should remain lowercase (not last word because code follows)
1683        assert!(
1684            fixed.contains("with a `variable`"),
1685            "Expected 'with a `variable`' but got: {fixed:?}"
1686        );
1687        assert!(
1688            !fixed.contains("with A `variable`"),
1689            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1690        );
1691    }
1692
1693    #[test]
1694    fn test_code_and_link_combination() {
1695        let config = MD063Config {
1696            enabled: true,
1697            style: HeadingCapStyle::TitleCase,
1698            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1699            ..Default::default()
1700        };
1701        let rule = MD063HeadingCapitalization::from_config_struct(config);
1702
1703        // Code then link - last segment is link, so lowercase words before code should remain lowercase
1704        let content = "## Guide for the `code` [link](./page.md)\n";
1705        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1706        let fixed = rule.fix(&ctx).unwrap();
1707        // "for" and "the" should remain lowercase (not last word because link follows)
1708        assert!(
1709            fixed.contains("for the `code`"),
1710            "Expected 'for the `code`' but got: {fixed:?}"
1711        );
1712    }
1713
1714    #[test]
1715    fn test_text_after_code_capitalizes_last() {
1716        let config = MD063Config {
1717            enabled: true,
1718            style: HeadingCapStyle::TitleCase,
1719            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1720            ..Default::default()
1721        };
1722        let rule = MD063HeadingCapitalization::from_config_struct(config);
1723
1724        // Code in middle, text after - last word should be capitalized
1725        let content = "## Using `const` for the code\n";
1726        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1727        let fixed = rule.fix(&ctx).unwrap();
1728        // "for" and "the" should be lowercase, "code" is last word, should be capitalized
1729        assert!(
1730            fixed.contains("for the Code"),
1731            "Expected 'for the Code' but got: {fixed:?}"
1732        );
1733    }
1734
1735    #[test]
1736    fn test_preserve_cased_words_with_trailing_code() {
1737        let config = MD063Config {
1738            enabled: true,
1739            style: HeadingCapStyle::TitleCase,
1740            lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1741            preserve_cased_words: true,
1742            ..Default::default()
1743        };
1744        let rule = MD063HeadingCapitalization::from_config_struct(config);
1745
1746        // Preserve-cased words should still work with trailing code
1747        let content = "## Guide for iOS `app`\n";
1748        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1749        let fixed = rule.fix(&ctx).unwrap();
1750        // "iOS" should be preserved, "for" should be lowercase
1751        assert!(
1752            fixed.contains("for iOS `app`"),
1753            "Expected 'for iOS `app`' but got: {fixed:?}"
1754        );
1755        assert!(
1756            !fixed.contains("For iOS `app`"),
1757            "Should not capitalize 'for' before trailing code. Got: {fixed:?}"
1758        );
1759    }
1760
1761    #[test]
1762    fn test_ignore_words_with_trailing_code() {
1763        let config = MD063Config {
1764            enabled: true,
1765            style: HeadingCapStyle::TitleCase,
1766            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1767            ignore_words: vec!["npm".to_string()],
1768            ..Default::default()
1769        };
1770        let rule = MD063HeadingCapitalization::from_config_struct(config);
1771
1772        // Ignore-words should still work with trailing code
1773        let content = "## Using npm with a `script`\n";
1774        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1775        let fixed = rule.fix(&ctx).unwrap();
1776        // "npm" should be preserved, "with" and "a" should be lowercase
1777        assert!(
1778            fixed.contains("npm with a `script`"),
1779            "Expected 'npm with a `script`' but got: {fixed:?}"
1780        );
1781        assert!(
1782            !fixed.contains("with A `script`"),
1783            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1784        );
1785    }
1786
1787    #[test]
1788    fn test_empty_text_segment_edge_case() {
1789        let config = MD063Config {
1790            enabled: true,
1791            style: HeadingCapStyle::TitleCase,
1792            lowercase_words: vec!["a".to_string(), "with".to_string()],
1793            ..Default::default()
1794        };
1795        let rule = MD063HeadingCapitalization::from_config_struct(config);
1796
1797        // Edge case: code at start, then text with lowercase word, then code at end
1798        let content = "## `start` with a `end`\n";
1799        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1800        let fixed = rule.fix(&ctx).unwrap();
1801        // "with" is first word in text segment, so capitalized (correct)
1802        // "a" should remain lowercase (not last word because code follows) - this is the key test
1803        assert!(fixed.contains("a `end`"), "Expected 'a `end`' but got: {fixed:?}");
1804        assert!(
1805            !fixed.contains("A `end`"),
1806            "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1807        );
1808    }
1809
1810    #[test]
1811    fn test_sentence_case_with_trailing_code() {
1812        let config = MD063Config {
1813            enabled: true,
1814            style: HeadingCapStyle::SentenceCase,
1815            lowercase_words: vec!["a".to_string(), "the".to_string()],
1816            ..Default::default()
1817        };
1818        let rule = MD063HeadingCapitalization::from_config_struct(config);
1819
1820        // Sentence case should also respect lowercase words before code
1821        let content = "## guide for the `user`\n";
1822        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1823        let fixed = rule.fix(&ctx).unwrap();
1824        // First word capitalized, rest lowercase including "the" before code
1825        assert!(
1826            fixed.contains("Guide for the `user`"),
1827            "Expected 'Guide for the `user`' but got: {fixed:?}"
1828        );
1829    }
1830
1831    #[test]
1832    fn test_hyphenated_word_before_code() {
1833        let config = MD063Config {
1834            enabled: true,
1835            style: HeadingCapStyle::TitleCase,
1836            lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1837            ..Default::default()
1838        };
1839        let rule = MD063HeadingCapitalization::from_config_struct(config);
1840
1841        // Hyphenated word before code - last part should respect lowercase-words
1842        let content = "## Self-contained with a `feature`\n";
1843        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1844        let fixed = rule.fix(&ctx).unwrap();
1845        // "with" and "a" should remain lowercase (not last word because code follows)
1846        assert!(
1847            fixed.contains("with a `feature`"),
1848            "Expected 'with a `feature`' but got: {fixed:?}"
1849        );
1850    }
1851
1852    // Issue #228: Sentence case with inline code at heading start
1853    // When a heading starts with inline code, the first word after the code
1854    // should NOT be capitalized because the heading already has a "first element"
1855
1856    #[test]
1857    fn test_sentence_case_code_at_start_basic() {
1858        // The exact case from issue #228
1859        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1860        let content = "# `rumdl` is a linter\n";
1861        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1862        let result = rule.check(&ctx).unwrap();
1863        // Should be correct as-is: code is first, "is" stays lowercase
1864        assert!(
1865            result.is_empty(),
1866            "Heading with code at start should not flag 'is' for capitalization. Got: {:?}",
1867            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1868        );
1869    }
1870
1871    #[test]
1872    fn test_sentence_case_code_at_start_incorrect_capitalization() {
1873        // Verify we detect incorrect capitalization after code at start
1874        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1875        let content = "# `rumdl` Is a Linter\n";
1876        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1877        let result = rule.check(&ctx).unwrap();
1878        // Should flag: "Is" and "Linter" should be lowercase
1879        assert_eq!(result.len(), 1, "Should detect incorrect capitalization");
1880        assert!(
1881            result[0].message.contains("`rumdl` is a linter"),
1882            "Should suggest lowercase after code. Got: {:?}",
1883            result[0].message
1884        );
1885    }
1886
1887    #[test]
1888    fn test_sentence_case_code_at_start_fix() {
1889        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1890        let content = "# `rumdl` Is A Linter\n";
1891        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1892        let fixed = rule.fix(&ctx).unwrap();
1893        assert!(
1894            fixed.contains("# `rumdl` is a linter"),
1895            "Should fix to lowercase after code. Got: {fixed:?}"
1896        );
1897    }
1898
1899    #[test]
1900    fn test_sentence_case_text_at_start_still_capitalizes() {
1901        // Ensure normal headings still capitalize first word
1902        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1903        let content = "# the quick brown fox\n";
1904        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1905        let result = rule.check(&ctx).unwrap();
1906        assert_eq!(result.len(), 1);
1907        assert!(
1908            result[0].message.contains("The quick brown fox"),
1909            "Text-first heading should capitalize first word. Got: {:?}",
1910            result[0].message
1911        );
1912    }
1913
1914    #[test]
1915    fn test_sentence_case_link_at_start() {
1916        // Links at start: link text is lowercased, following text also lowercase
1917        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1918        // Use lowercase link text to avoid link text case flagging
1919        let content = "# [api](api.md) reference guide\n";
1920        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1921        let result = rule.check(&ctx).unwrap();
1922        // "reference" should be lowercase (link is first)
1923        assert!(
1924            result.is_empty(),
1925            "Heading with link at start should not capitalize 'reference'. Got: {:?}",
1926            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1927        );
1928    }
1929
1930    #[test]
1931    fn test_sentence_case_link_preserves_acronyms() {
1932        // Acronyms in link text should be preserved (API, HTTP, etc.)
1933        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1934        let content = "# [API](api.md) Reference Guide\n";
1935        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1936        let result = rule.check(&ctx).unwrap();
1937        assert_eq!(result.len(), 1);
1938        // "API" should be preserved (acronym), "Reference Guide" should be lowercased
1939        assert!(
1940            result[0].message.contains("[API](api.md) reference guide"),
1941            "Should preserve acronym 'API' but lowercase following text. Got: {:?}",
1942            result[0].message
1943        );
1944    }
1945
1946    #[test]
1947    fn test_sentence_case_link_preserves_brand_names() {
1948        // Brand names with internal capitals should be preserved
1949        let config = MD063Config {
1950            enabled: true,
1951            style: HeadingCapStyle::SentenceCase,
1952            preserve_cased_words: true,
1953            ..Default::default()
1954        };
1955        let rule = MD063HeadingCapitalization::from_config_struct(config);
1956        let content = "# [iPhone](iphone.md) Features Guide\n";
1957        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1958        let result = rule.check(&ctx).unwrap();
1959        assert_eq!(result.len(), 1);
1960        // "iPhone" should be preserved, "Features Guide" should be lowercased
1961        assert!(
1962            result[0].message.contains("[iPhone](iphone.md) features guide"),
1963            "Should preserve 'iPhone' but lowercase following text. Got: {:?}",
1964            result[0].message
1965        );
1966    }
1967
1968    #[test]
1969    fn test_sentence_case_link_lowercases_regular_words() {
1970        // Regular words in link text should be lowercased
1971        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1972        let content = "# [Documentation](docs.md) Reference\n";
1973        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1974        let result = rule.check(&ctx).unwrap();
1975        assert_eq!(result.len(), 1);
1976        // "Documentation" should be lowercased (regular word)
1977        assert!(
1978            result[0].message.contains("[documentation](docs.md) reference"),
1979            "Should lowercase regular link text. Got: {:?}",
1980            result[0].message
1981        );
1982    }
1983
1984    #[test]
1985    fn test_sentence_case_link_at_start_correct_already() {
1986        // Link with correct casing should not be flagged
1987        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1988        let content = "# [API](api.md) reference guide\n";
1989        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1990        let result = rule.check(&ctx).unwrap();
1991        assert!(
1992            result.is_empty(),
1993            "Correctly cased heading with link should not be flagged. Got: {:?}",
1994            result.iter().map(|w| &w.message).collect::<Vec<_>>()
1995        );
1996    }
1997
1998    #[test]
1999    fn test_sentence_case_link_github_preserved() {
2000        // GitHub should be preserved (internal capitals)
2001        let config = MD063Config {
2002            enabled: true,
2003            style: HeadingCapStyle::SentenceCase,
2004            preserve_cased_words: true,
2005            ..Default::default()
2006        };
2007        let rule = MD063HeadingCapitalization::from_config_struct(config);
2008        let content = "# [GitHub](gh.md) Repository Setup\n";
2009        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2010        let result = rule.check(&ctx).unwrap();
2011        assert_eq!(result.len(), 1);
2012        assert!(
2013            result[0].message.contains("[GitHub](gh.md) repository setup"),
2014            "Should preserve 'GitHub'. Got: {:?}",
2015            result[0].message
2016        );
2017    }
2018
2019    #[test]
2020    fn test_sentence_case_multiple_code_spans() {
2021        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2022        let content = "# `foo` and `bar` are methods\n";
2023        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2024        let result = rule.check(&ctx).unwrap();
2025        // All text after first code should be lowercase
2026        assert!(
2027            result.is_empty(),
2028            "Should not capitalize words between/after code spans. Got: {:?}",
2029            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2030        );
2031    }
2032
2033    #[test]
2034    fn test_sentence_case_code_only_heading() {
2035        // Heading with only code, no text
2036        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2037        let content = "# `rumdl`\n";
2038        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2039        let result = rule.check(&ctx).unwrap();
2040        assert!(
2041            result.is_empty(),
2042            "Code-only heading should be fine. Got: {:?}",
2043            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2044        );
2045    }
2046
2047    #[test]
2048    fn test_sentence_case_code_at_end() {
2049        // Heading ending with code, text before should still capitalize first word
2050        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2051        let content = "# install the `rumdl` tool\n";
2052        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2053        let result = rule.check(&ctx).unwrap();
2054        // "install" should be capitalized (first word), rest lowercase
2055        assert_eq!(result.len(), 1);
2056        assert!(
2057            result[0].message.contains("Install the `rumdl` tool"),
2058            "First word should still be capitalized when text comes first. Got: {:?}",
2059            result[0].message
2060        );
2061    }
2062
2063    #[test]
2064    fn test_sentence_case_code_in_middle() {
2065        // Code in middle, text at start should capitalize first word
2066        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2067        let content = "# using the `rumdl` linter for markdown\n";
2068        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2069        let result = rule.check(&ctx).unwrap();
2070        // "using" should be capitalized, rest lowercase
2071        assert_eq!(result.len(), 1);
2072        assert!(
2073            result[0].message.contains("Using the `rumdl` linter for markdown"),
2074            "First word should be capitalized. Got: {:?}",
2075            result[0].message
2076        );
2077    }
2078
2079    #[test]
2080    fn test_sentence_case_preserved_word_after_code() {
2081        // Preserved words (like iPhone) should stay preserved even after code
2082        let config = MD063Config {
2083            enabled: true,
2084            style: HeadingCapStyle::SentenceCase,
2085            preserve_cased_words: true,
2086            ..Default::default()
2087        };
2088        let rule = MD063HeadingCapitalization::from_config_struct(config);
2089        let content = "# `swift` iPhone development\n";
2090        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2091        let result = rule.check(&ctx).unwrap();
2092        // "iPhone" should be preserved, "development" lowercase
2093        assert!(
2094            result.is_empty(),
2095            "Preserved words after code should stay. Got: {:?}",
2096            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2097        );
2098    }
2099
2100    #[test]
2101    fn test_title_case_code_at_start_still_capitalizes() {
2102        // Title case should still capitalize words even after code at start
2103        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2104        let content = "# `api` quick start guide\n";
2105        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2106        let result = rule.check(&ctx).unwrap();
2107        // Title case: all major words capitalized
2108        assert_eq!(result.len(), 1);
2109        assert!(
2110            result[0].message.contains("Quick Start Guide") || result[0].message.contains("quick Start Guide"),
2111            "Title case should capitalize major words after code. Got: {:?}",
2112            result[0].message
2113        );
2114    }
2115
2116    // ======== HTML TAG TESTS ========
2117
2118    #[test]
2119    fn test_sentence_case_html_tag_at_start() {
2120        // HTML tag at start: text after should NOT capitalize first word
2121        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2122        let content = "# <kbd>Ctrl</kbd> is a Modifier Key\n";
2123        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2124        let result = rule.check(&ctx).unwrap();
2125        // "is", "a", "Modifier", "Key" should all be lowercase (except preserved words)
2126        assert_eq!(result.len(), 1);
2127        let fixed = rule.fix(&ctx).unwrap();
2128        assert_eq!(
2129            fixed, "# <kbd>Ctrl</kbd> is a modifier key\n",
2130            "Text after HTML at start should be lowercase"
2131        );
2132    }
2133
2134    #[test]
2135    fn test_sentence_case_html_tag_preserves_content() {
2136        // Content inside HTML tags should be preserved as-is
2137        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2138        let content = "# The <abbr>API</abbr> documentation guide\n";
2139        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2140        let result = rule.check(&ctx).unwrap();
2141        // "The" is first, "API" inside tag preserved, rest lowercase
2142        assert!(
2143            result.is_empty(),
2144            "HTML tag content should be preserved. Got: {:?}",
2145            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2146        );
2147    }
2148
2149    #[test]
2150    fn test_sentence_case_html_tag_at_start_with_acronym() {
2151        // HTML tag at start with acronym content
2152        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2153        let content = "# <abbr>API</abbr> Documentation Guide\n";
2154        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2155        let result = rule.check(&ctx).unwrap();
2156        assert_eq!(result.len(), 1);
2157        let fixed = rule.fix(&ctx).unwrap();
2158        assert_eq!(
2159            fixed, "# <abbr>API</abbr> documentation guide\n",
2160            "Text after HTML at start should be lowercase, HTML content preserved"
2161        );
2162    }
2163
2164    #[test]
2165    fn test_sentence_case_html_tag_in_middle() {
2166        // HTML tag in middle: first word still capitalized
2167        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2168        let content = "# using the <code>config</code> File\n";
2169        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2170        let result = rule.check(&ctx).unwrap();
2171        assert_eq!(result.len(), 1);
2172        let fixed = rule.fix(&ctx).unwrap();
2173        assert_eq!(
2174            fixed, "# Using the <code>config</code> file\n",
2175            "First word capitalized, HTML preserved, rest lowercase"
2176        );
2177    }
2178
2179    #[test]
2180    fn test_html_tag_strong_emphasis() {
2181        // <strong> tag handling
2182        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2183        let content = "# The <strong>Bold</strong> Way\n";
2184        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2185        let result = rule.check(&ctx).unwrap();
2186        assert_eq!(result.len(), 1);
2187        let fixed = rule.fix(&ctx).unwrap();
2188        assert_eq!(
2189            fixed, "# The <strong>Bold</strong> way\n",
2190            "<strong> tag content should be preserved"
2191        );
2192    }
2193
2194    #[test]
2195    fn test_html_tag_with_attributes() {
2196        // HTML tags with attributes should still be detected
2197        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2198        let content = "# <span class=\"highlight\">Important</span> Notice Here\n";
2199        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2200        let result = rule.check(&ctx).unwrap();
2201        assert_eq!(result.len(), 1);
2202        let fixed = rule.fix(&ctx).unwrap();
2203        assert_eq!(
2204            fixed, "# <span class=\"highlight\">Important</span> notice here\n",
2205            "HTML tag with attributes should be preserved"
2206        );
2207    }
2208
2209    #[test]
2210    fn test_multiple_html_tags() {
2211        // Multiple HTML tags in heading
2212        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2213        let content = "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to Copy Text\n";
2214        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2215        let result = rule.check(&ctx).unwrap();
2216        assert_eq!(result.len(), 1);
2217        let fixed = rule.fix(&ctx).unwrap();
2218        assert_eq!(
2219            fixed, "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy text\n",
2220            "Multiple HTML tags should all be preserved"
2221        );
2222    }
2223
2224    #[test]
2225    fn test_html_and_code_mixed() {
2226        // Mix of HTML tags and inline code
2227        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2228        let content = "# <kbd>Ctrl</kbd>+`v` Paste command\n";
2229        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2230        let result = rule.check(&ctx).unwrap();
2231        assert_eq!(result.len(), 1);
2232        let fixed = rule.fix(&ctx).unwrap();
2233        assert_eq!(
2234            fixed, "# <kbd>Ctrl</kbd>+`v` paste command\n",
2235            "HTML and code should both be preserved"
2236        );
2237    }
2238
2239    #[test]
2240    fn test_self_closing_html_tag() {
2241        // Self-closing tags like <br/>
2242        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2243        let content = "# Line one<br/>Line Two Here\n";
2244        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2245        let result = rule.check(&ctx).unwrap();
2246        assert_eq!(result.len(), 1);
2247        let fixed = rule.fix(&ctx).unwrap();
2248        assert_eq!(
2249            fixed, "# Line one<br/>line two here\n",
2250            "Self-closing HTML tags should be preserved"
2251        );
2252    }
2253
2254    #[test]
2255    fn test_title_case_with_html_tags() {
2256        // Title case with HTML tags
2257        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2258        let content = "# the <kbd>ctrl</kbd> key is a modifier\n";
2259        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2260        let result = rule.check(&ctx).unwrap();
2261        assert_eq!(result.len(), 1);
2262        let fixed = rule.fix(&ctx).unwrap();
2263        // "the" as first word should be "The", content inside <kbd> preserved
2264        assert!(
2265            fixed.contains("<kbd>ctrl</kbd>"),
2266            "HTML tag content should be preserved in title case. Got: {fixed}"
2267        );
2268        assert!(
2269            fixed.starts_with("# The ") || fixed.starts_with("# the "),
2270            "Title case should work with HTML. Got: {fixed}"
2271        );
2272    }
2273
2274    // ======== CARET NOTATION TESTS ========
2275
2276    #[test]
2277    fn test_sentence_case_preserves_caret_notation() {
2278        // Caret notation for control characters should be preserved
2279        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2280        let content = "## Ctrl+A, Ctrl+R output ^A, ^R on zsh\n";
2281        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2282        let result = rule.check(&ctx).unwrap();
2283        // Should not flag - ^A and ^R are preserved
2284        assert!(
2285            result.is_empty(),
2286            "Caret notation should be preserved. Got: {:?}",
2287            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2288        );
2289    }
2290
2291    #[test]
2292    fn test_sentence_case_caret_notation_various() {
2293        // Various caret notation patterns
2294        let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2295
2296        // ^C for interrupt
2297        let content = "## Press ^C to cancel\n";
2298        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2299        let result = rule.check(&ctx).unwrap();
2300        assert!(
2301            result.is_empty(),
2302            "^C should be preserved. Got: {:?}",
2303            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2304        );
2305
2306        // ^Z for suspend
2307        let content = "## Use ^Z for background\n";
2308        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2309        let result = rule.check(&ctx).unwrap();
2310        assert!(
2311            result.is_empty(),
2312            "^Z should be preserved. Got: {:?}",
2313            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2314        );
2315
2316        // ^[ for escape
2317        let content = "## Press ^[ for escape\n";
2318        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2319        let result = rule.check(&ctx).unwrap();
2320        assert!(
2321            result.is_empty(),
2322            "^[ should be preserved. Got: {:?}",
2323            result.iter().map(|w| &w.message).collect::<Vec<_>>()
2324        );
2325    }
2326
2327    #[test]
2328    fn test_caret_notation_detection() {
2329        let rule = create_rule();
2330
2331        // Valid caret notation
2332        assert!(rule.is_caret_notation("^A"));
2333        assert!(rule.is_caret_notation("^Z"));
2334        assert!(rule.is_caret_notation("^C"));
2335        assert!(rule.is_caret_notation("^@")); // NUL
2336        assert!(rule.is_caret_notation("^[")); // ESC
2337        assert!(rule.is_caret_notation("^]")); // GS
2338        assert!(rule.is_caret_notation("^^")); // RS
2339        assert!(rule.is_caret_notation("^_")); // US
2340
2341        // Not caret notation
2342        assert!(!rule.is_caret_notation("^a")); // lowercase
2343        assert!(!rule.is_caret_notation("A")); // no caret
2344        assert!(!rule.is_caret_notation("^")); // caret alone
2345        assert!(!rule.is_caret_notation("^1")); // digit
2346    }
2347
2348    // MD044 proper names integration tests
2349    //
2350    // When MD063 (sentence case) and MD044 (proper names) are both active, MD063 must
2351    // preserve the exact capitalization of MD044 proper names rather than lowercasing them.
2352    // Without this, the two rules oscillate: MD044 re-capitalizes what MD063 lowercases.
2353
2354    fn create_sentence_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2355        let config = MD063Config {
2356            enabled: true,
2357            style: HeadingCapStyle::SentenceCase,
2358            ..Default::default()
2359        };
2360        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2361        rule.proper_names = names;
2362        rule
2363    }
2364
2365    #[test]
2366    fn test_sentence_case_preserves_single_word_proper_name() {
2367        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2368        // "javascript" in non-first position should become "JavaScript", not "javascript"
2369        let content = "# installing javascript\n";
2370        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2371        let result = rule.check(&ctx).unwrap();
2372        assert_eq!(result.len(), 1, "Should flag the heading");
2373        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2374        assert!(
2375            fix_text.contains("JavaScript"),
2376            "Fix should preserve proper name 'JavaScript', got: {fix_text:?}"
2377        );
2378        assert!(
2379            !fix_text.contains("javascript"),
2380            "Fix should not have lowercase 'javascript', got: {fix_text:?}"
2381        );
2382    }
2383
2384    #[test]
2385    fn test_sentence_case_preserves_multi_word_proper_name() {
2386        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2387        // "Good Application" is a proper name; sentence case must not lowercase "Application"
2388        let content = "# using good application features\n";
2389        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2390        let result = rule.check(&ctx).unwrap();
2391        assert_eq!(result.len(), 1, "Should flag the heading");
2392        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2393        assert!(
2394            fix_text.contains("Good Application"),
2395            "Fix should preserve 'Good Application' as a phrase, got: {fix_text:?}"
2396        );
2397    }
2398
2399    #[test]
2400    fn test_sentence_case_proper_name_at_start_of_heading() {
2401        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2402        // The proper name "Good Application" starts the heading; both words must be canonical
2403        let content = "# good application overview\n";
2404        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2405        let result = rule.check(&ctx).unwrap();
2406        assert_eq!(result.len(), 1, "Should flag the heading");
2407        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2408        assert!(
2409            fix_text.contains("Good Application"),
2410            "Fix should produce 'Good Application' at start of heading, got: {fix_text:?}"
2411        );
2412        assert!(
2413            fix_text.contains("overview"),
2414            "Non-proper-name word 'overview' should be lowercase, got: {fix_text:?}"
2415        );
2416    }
2417
2418    #[test]
2419    fn test_sentence_case_with_proper_names_no_oscillation() {
2420        // This is the core convergence test: applying the fix once must produce
2421        // output that is already correct (no further changes needed).
2422        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2423
2424        // First application of fix
2425        let content = "# installing good application on your system\n";
2426        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2427        let result = rule.check(&ctx).unwrap();
2428        assert_eq!(result.len(), 1);
2429        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2430
2431        // The fixed heading should contain the proper name preserved
2432        assert!(
2433            fixed_heading.contains("Good Application"),
2434            "After fix, proper name must be preserved: {fixed_heading:?}"
2435        );
2436
2437        // Second application: must produce no further warnings (convergence)
2438        let fixed_line = format!("{fixed_heading}\n");
2439        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2440        let result2 = rule.check(&ctx2).unwrap();
2441        assert!(
2442            result2.is_empty(),
2443            "After one fix, heading must already satisfy both MD063 and MD044 - no oscillation. \
2444             Second pass warnings: {result2:?}"
2445        );
2446    }
2447
2448    #[test]
2449    fn test_sentence_case_proper_names_already_correct() {
2450        let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2451        // Heading already has correct sentence case with proper name preserved
2452        let content = "# Installing Good Application\n";
2453        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2454        let result = rule.check(&ctx).unwrap();
2455        assert!(
2456            result.is_empty(),
2457            "Correct sentence-case heading with proper name should not be flagged, got: {result:?}"
2458        );
2459    }
2460
2461    #[test]
2462    fn test_sentence_case_multiple_proper_names_in_heading() {
2463        let rule = create_sentence_case_rule_with_proper_names(vec!["TypeScript".to_string(), "React".to_string()]);
2464        let content = "# using typescript with react\n";
2465        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2466        let result = rule.check(&ctx).unwrap();
2467        assert_eq!(result.len(), 1);
2468        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2469        assert!(
2470            fix_text.contains("TypeScript"),
2471            "Fix should preserve 'TypeScript', got: {fix_text:?}"
2472        );
2473        assert!(
2474            fix_text.contains("React"),
2475            "Fix should preserve 'React', got: {fix_text:?}"
2476        );
2477    }
2478
2479    #[test]
2480    fn test_sentence_case_unicode_casefold_expansion_before_proper_name() {
2481        // Regression for Unicode case-fold expansion: `İ` lowercases to `i̇` (2 code points),
2482        // so matching offsets must be computed from the original text, not from a lowercased copy.
2483        let rule = create_sentence_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2484        let content = "# İ österreich guide\n";
2485        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2486
2487        // Should not panic and should preserve canonical proper-name casing.
2488        let result = rule.check(&ctx).unwrap();
2489        assert_eq!(result.len(), 1, "Should flag heading for canonical proper-name casing");
2490        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2491        assert!(
2492            fix_text.contains("Österreich"),
2493            "Fix should preserve canonical 'Österreich', got: {fix_text:?}"
2494        );
2495    }
2496
2497    #[test]
2498    fn test_sentence_case_preserves_trailing_punctuation_on_proper_name() {
2499        let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2500        let content = "# using javascript, today\n";
2501        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2502        let result = rule.check(&ctx).unwrap();
2503        assert_eq!(result.len(), 1, "Should flag heading");
2504        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2505        assert!(
2506            fix_text.contains("JavaScript,"),
2507            "Fix should preserve trailing punctuation, got: {fix_text:?}"
2508        );
2509    }
2510
2511    // Title case + MD044 conflict tests
2512    //
2513    // In title case, short words like "the", "a", "of" are kept lowercase by MD063.
2514    // If those words are part of an MD044 proper name (e.g. "The Rolling Stones"),
2515    // the same oscillation problem occurs.  The fix must extend to title case too.
2516
2517    fn create_title_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2518        let config = MD063Config {
2519            enabled: true,
2520            style: HeadingCapStyle::TitleCase,
2521            ..Default::default()
2522        };
2523        let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2524        rule.proper_names = names;
2525        rule
2526    }
2527
2528    #[test]
2529    fn test_title_case_preserves_proper_name_with_lowercase_article() {
2530        // "The" is in the lowercase_words list for title case, so "the" in the middle
2531        // of a heading would normally stay lowercase.  But "The Rolling Stones" is a
2532        // proper name that must be capitalised exactly.
2533        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2534        let content = "# listening to the rolling stones today\n";
2535        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2536        let result = rule.check(&ctx).unwrap();
2537        assert_eq!(result.len(), 1, "Should flag the heading");
2538        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2539        assert!(
2540            fix_text.contains("The Rolling Stones"),
2541            "Fix should preserve proper name 'The Rolling Stones', got: {fix_text:?}"
2542        );
2543    }
2544
2545    #[test]
2546    fn test_title_case_proper_name_no_oscillation() {
2547        // One fix pass must produce output that title case already accepts.
2548        let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2549        let content = "# listening to the rolling stones today\n";
2550        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2551        let result = rule.check(&ctx).unwrap();
2552        assert_eq!(result.len(), 1);
2553        let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2554
2555        let fixed_line = format!("{fixed_heading}\n");
2556        let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2557        let result2 = rule.check(&ctx2).unwrap();
2558        assert!(
2559            result2.is_empty(),
2560            "After one title-case fix, heading must already satisfy both rules. \
2561             Second pass warnings: {result2:?}"
2562        );
2563    }
2564
2565    #[test]
2566    fn test_title_case_unicode_casefold_expansion_before_proper_name() {
2567        let rule = create_title_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2568        let content = "# İ österreich guide\n";
2569        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2570        let result = rule.check(&ctx).unwrap();
2571        assert_eq!(result.len(), 1, "Should flag the heading");
2572        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2573        assert!(
2574            fix_text.contains("Österreich"),
2575            "Fix should preserve canonical proper-name casing, got: {fix_text:?}"
2576        );
2577    }
2578
2579    // End-to-end integration test: from_config wires MD044 names into MD063
2580    //
2581    // This tests the actual code path used in production, where both rules are
2582    // configured in a rumdl.toml and the rule registry calls from_config.
2583
2584    #[test]
2585    fn test_from_config_loads_md044_names_into_md063() {
2586        use crate::config::{Config, RuleConfig};
2587        use crate::rule::Rule;
2588        use std::collections::BTreeMap;
2589
2590        let mut config = Config::default();
2591
2592        // Configure MD063 with sentence_case
2593        let mut md063_values = BTreeMap::new();
2594        md063_values.insert("style".to_string(), toml::Value::String("sentence_case".to_string()));
2595        md063_values.insert("enabled".to_string(), toml::Value::Boolean(true));
2596        config.rules.insert(
2597            "MD063".to_string(),
2598            RuleConfig {
2599                values: md063_values,
2600                severity: None,
2601            },
2602        );
2603
2604        // Configure MD044 with a proper name
2605        let mut md044_values = BTreeMap::new();
2606        md044_values.insert(
2607            "names".to_string(),
2608            toml::Value::Array(vec![toml::Value::String("Good Application".to_string())]),
2609        );
2610        config.rules.insert(
2611            "MD044".to_string(),
2612            RuleConfig {
2613                values: md044_values,
2614                severity: None,
2615            },
2616        );
2617
2618        // Build MD063 via the production code path
2619        let rule = MD063HeadingCapitalization::from_config(&config);
2620
2621        // Verify MD044 names were loaded: the fix must preserve "Good Application"
2622        let content = "# using good application features\n";
2623        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2624        let result = rule.check(&ctx).unwrap();
2625        assert_eq!(result.len(), 1, "Should flag the heading");
2626        let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2627        assert!(
2628            fix_text.contains("Good Application"),
2629            "from_config should wire MD044 names into MD063; fix should preserve \
2630             'Good Application', got: {fix_text:?}"
2631        );
2632    }
2633
2634    #[test]
2635    fn test_title_case_short_word_not_confused_with_substring() {
2636        // Verify that short preposition matching ("in") does not trigger on
2637        // substrings of longer words ("insert"). Title case must capitalize
2638        // "insert" while keeping "in" lowercase.
2639        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2640
2641        // "in" is a short preposition (should be lowercase in title case)
2642        // "insert" contains "in" as substring but is a regular word (should be capitalized)
2643        let content = "# in the insert\n";
2644        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2645        let result = rule.check(&ctx).unwrap();
2646        assert_eq!(result.len(), 1, "Should flag the heading");
2647        let fix = result[0].fix.as_ref().expect("Fix should be present");
2648        // "In" capitalized as first word, "the" lowercase as article, "Insert" capitalized
2649        assert!(
2650            fix.replacement.contains("In the Insert"),
2651            "Expected 'In the Insert', got: {:?}",
2652            fix.replacement
2653        );
2654    }
2655
2656    #[test]
2657    fn test_title_case_or_not_confused_with_orchestra() {
2658        let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2659
2660        // "or" is a conjunction (should be lowercase in title case)
2661        // "orchestra" contains "or" as substring but is a regular word
2662        let content = "# or the orchestra\n";
2663        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2664        let result = rule.check(&ctx).unwrap();
2665        assert_eq!(result.len(), 1, "Should flag the heading");
2666        let fix = result[0].fix.as_ref().expect("Fix should be present");
2667        // "Or" capitalized as first word, "the" lowercase, "Orchestra" capitalized
2668        assert!(
2669            fix.replacement.contains("Or the Orchestra"),
2670            "Expected 'Or the Orchestra', got: {:?}",
2671            fix.replacement
2672        );
2673    }
2674
2675    #[test]
2676    fn test_all_caps_preserves_all_words() {
2677        let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
2678
2679        let content = "# in the insert\n";
2680        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2681        let result = rule.check(&ctx).unwrap();
2682        assert_eq!(result.len(), 1, "Should flag the heading");
2683        let fix = result[0].fix.as_ref().expect("Fix should be present");
2684        assert!(
2685            fix.replacement.contains("IN THE INSERT"),
2686            "All caps should uppercase all words, got: {:?}",
2687            fix.replacement
2688        );
2689    }
2690}