Skip to main content

rumdl_lib/rules/
md044_proper_names.rs

1use crate::utils::fast_hash;
2use crate::utils::regex_cache::{escape_regex, get_cached_regex};
3
4use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use std::collections::{HashMap, HashSet};
6use std::sync::{Arc, Mutex};
7
8mod md044_config;
9pub(super) use md044_config::MD044Config;
10
11type WarningPosition = (usize, usize, String); // (line, column, found_name)
12
13/// Rule MD044: Proper names should be capitalized
14///
15/// See [docs/md044.md](../../docs/md044.md) for full documentation, configuration, and examples.
16///
17/// This rule is triggered when proper names are not capitalized correctly in the document.
18/// For example, if you have defined "JavaScript" as a proper name, the rule will flag any
19/// occurrences of "javascript" or "Javascript" as violations.
20///
21/// ## Purpose
22///
23/// Ensuring consistent capitalization of proper names improves document quality and
24/// professionalism. This is especially important for technical documentation where
25/// product names, programming languages, and technologies often have specific
26/// capitalization conventions.
27///
28/// ## Configuration Options
29///
30/// The rule supports the following configuration options:
31///
32/// ```yaml
33/// MD044:
34///   names: []                # List of proper names to check for correct capitalization
35///   code-blocks: false       # Whether to check code blocks (default: false)
36/// ```
37///
38/// Example configuration:
39///
40/// ```yaml
41/// MD044:
42///   names: ["JavaScript", "Node.js", "TypeScript"]
43///   code-blocks: true
44/// ```
45///
46/// ## Performance Optimizations
47///
48/// This rule implements several performance optimizations:
49///
50/// 1. **Regex Caching**: Pre-compiles and caches regex patterns for each proper name
51/// 2. **Content Caching**: Caches results based on content hashing for repeated checks
52/// 3. **Efficient Text Processing**: Uses optimized algorithms to avoid redundant text processing
53/// 4. **Smart Code Block Detection**: Efficiently identifies and optionally excludes code blocks
54///
55/// ## Edge Cases Handled
56///
57/// - **Word Boundaries**: Only matches complete words, not substrings within other words
58/// - **Case Sensitivity**: Properly handles case-specific matching
59/// - **Code Blocks**: Optionally checks code blocks (controlled by code-blocks setting)
60/// - **Markdown Formatting**: Handles proper names within Markdown formatting elements
61///
62/// ## Fix Behavior
63///
64/// When fixing issues, this rule replaces incorrect capitalization with the correct form
65/// as defined in the configuration.
66///
67/// Check if a trimmed line is an inline config comment from a linting tool.
68/// Recognized tools: rumdl, markdownlint, Vale, and remark-lint.
69fn is_inline_config_comment(trimmed: &str) -> bool {
70    trimmed.starts_with("<!-- rumdl-")
71        || trimmed.starts_with("<!-- markdownlint-")
72        || trimmed.starts_with("<!-- vale off")
73        || trimmed.starts_with("<!-- vale on")
74        || (trimmed.starts_with("<!-- vale ") && trimmed.contains(" = "))
75        || trimmed.starts_with("<!-- vale style")
76        || trimmed.starts_with("<!-- lint disable ")
77        || trimmed.starts_with("<!-- lint enable ")
78        || trimmed.starts_with("<!-- lint ignore ")
79}
80
81#[derive(Clone)]
82pub struct MD044ProperNames {
83    config: MD044Config,
84    // Cache the combined regex pattern string
85    combined_pattern: Option<String>,
86    // Precomputed lowercase name variants for fast pre-checks
87    name_variants: Vec<String>,
88    // Cache for name violations by content hash
89    content_cache: Arc<Mutex<HashMap<u64, Vec<WarningPosition>>>>,
90}
91
92impl MD044ProperNames {
93    pub fn new(names: Vec<String>, code_blocks: bool) -> Self {
94        let config = MD044Config {
95            names,
96            code_blocks,
97            html_elements: true, // Default to checking HTML elements
98            html_comments: true, // Default to checking HTML comments
99        };
100        let combined_pattern = Self::create_combined_pattern(&config);
101        let name_variants = Self::build_name_variants(&config);
102        Self {
103            config,
104            combined_pattern,
105            name_variants,
106            content_cache: Arc::new(Mutex::new(HashMap::new())),
107        }
108    }
109
110    // Helper function for consistent ASCII normalization
111    fn ascii_normalize(s: &str) -> String {
112        s.replace(['é', 'è', 'ê', 'ë'], "e")
113            .replace(['à', 'á', 'â', 'ä', 'ã', 'å'], "a")
114            .replace(['ï', 'î', 'í', 'ì'], "i")
115            .replace(['ü', 'ú', 'ù', 'û'], "u")
116            .replace(['ö', 'ó', 'ò', 'ô', 'õ'], "o")
117            .replace('ñ', "n")
118            .replace('ç', "c")
119    }
120
121    pub fn from_config_struct(config: MD044Config) -> Self {
122        let combined_pattern = Self::create_combined_pattern(&config);
123        let name_variants = Self::build_name_variants(&config);
124        Self {
125            config,
126            combined_pattern,
127            name_variants,
128            content_cache: Arc::new(Mutex::new(HashMap::new())),
129        }
130    }
131
132    // Create a combined regex pattern for all proper names
133    fn create_combined_pattern(config: &MD044Config) -> Option<String> {
134        if config.names.is_empty() {
135            return None;
136        }
137
138        // Create patterns for all names and their variations
139        let mut patterns: Vec<String> = config
140            .names
141            .iter()
142            .flat_map(|name| {
143                let mut variations = vec![];
144                let lower_name = name.to_lowercase();
145
146                // Add the lowercase version
147                variations.push(escape_regex(&lower_name));
148
149                // Add version without dots
150                let lower_name_no_dots = lower_name.replace('.', "");
151                if lower_name != lower_name_no_dots {
152                    variations.push(escape_regex(&lower_name_no_dots));
153                }
154
155                // Add ASCII-normalized versions for common accented characters
156                let ascii_normalized = Self::ascii_normalize(&lower_name);
157
158                if ascii_normalized != lower_name {
159                    variations.push(escape_regex(&ascii_normalized));
160
161                    // Also add version without dots
162                    let ascii_no_dots = ascii_normalized.replace('.', "");
163                    if ascii_normalized != ascii_no_dots {
164                        variations.push(escape_regex(&ascii_no_dots));
165                    }
166                }
167
168                variations
169            })
170            .collect();
171
172        // Sort patterns by length (longest first) to avoid shorter patterns matching within longer ones
173        patterns.sort_by_key(|b| std::cmp::Reverse(b.len()));
174
175        // Combine all patterns into a single regex with capture groups
176        // Don't use \b as it doesn't work with Unicode - we'll check boundaries manually
177        Some(format!(r"(?i)({})", patterns.join("|")))
178    }
179
180    fn build_name_variants(config: &MD044Config) -> Vec<String> {
181        let mut variants = HashSet::new();
182        for name in &config.names {
183            let lower_name = name.to_lowercase();
184            variants.insert(lower_name.clone());
185
186            let lower_no_dots = lower_name.replace('.', "");
187            if lower_name != lower_no_dots {
188                variants.insert(lower_no_dots);
189            }
190
191            let ascii_normalized = Self::ascii_normalize(&lower_name);
192            if ascii_normalized != lower_name {
193                variants.insert(ascii_normalized.clone());
194
195                let ascii_no_dots = ascii_normalized.replace('.', "");
196                if ascii_normalized != ascii_no_dots {
197                    variants.insert(ascii_no_dots);
198                }
199            }
200        }
201
202        variants.into_iter().collect()
203    }
204
205    // Find all name violations in the content and return positions.
206    // `content_lower` is the pre-computed lowercase version of `content` to avoid redundant allocations.
207    fn find_name_violations(
208        &self,
209        content: &str,
210        ctx: &crate::lint_context::LintContext,
211        content_lower: &str,
212    ) -> Vec<WarningPosition> {
213        // Early return: if no names configured or content is empty
214        if self.config.names.is_empty() || content.is_empty() || self.combined_pattern.is_none() {
215            return Vec::new();
216        }
217
218        // Early return: quick check if any of the configured names might be in content
219        let has_potential_matches = self.name_variants.iter().any(|name| content_lower.contains(name));
220
221        if !has_potential_matches {
222            return Vec::new();
223        }
224
225        // Check if we have cached results
226        let hash = fast_hash(content);
227        {
228            // Use a separate scope for borrowing to minimize lock time
229            if let Ok(cache) = self.content_cache.lock()
230                && let Some(cached) = cache.get(&hash)
231            {
232                return cached.clone();
233            }
234        }
235
236        let mut violations = Vec::new();
237
238        // Get the regex from global cache
239        let combined_regex = match &self.combined_pattern {
240            Some(pattern) => match get_cached_regex(pattern) {
241                Ok(regex) => regex,
242                Err(_) => return Vec::new(),
243            },
244            None => return Vec::new(),
245        };
246
247        // Use ctx.lines for better performance
248        for (line_idx, line_info) in ctx.lines.iter().enumerate() {
249            let line_num = line_idx + 1;
250            let line = line_info.content(ctx.content);
251
252            // Skip code fence lines (```language or ~~~language)
253            let trimmed = line.trim_start();
254            if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
255                continue;
256            }
257
258            // Skip if in code block (when code_blocks = false)
259            if !self.config.code_blocks && line_info.in_code_block {
260                continue;
261            }
262
263            // Skip if in HTML block (when html_elements = false)
264            if !self.config.html_elements && line_info.in_html_block {
265                continue;
266            }
267
268            // Skip HTML comments using pre-computed line flag
269            if !self.config.html_comments && line_info.in_html_comment {
270                continue;
271            }
272
273            // Skip JSX expressions and MDX comments (MDX flavor)
274            if line_info.in_jsx_expression || line_info.in_mdx_comment {
275                continue;
276            }
277
278            // Skip Obsidian comments (Obsidian flavor)
279            if line_info.in_obsidian_comment {
280                continue;
281            }
282
283            // For frontmatter lines, determine offset where checkable value content starts.
284            // YAML keys should not be checked against proper names - only values.
285            let fm_value_offset = if line_info.in_front_matter {
286                Self::frontmatter_value_offset(line)
287            } else {
288                0
289            };
290            if fm_value_offset == usize::MAX {
291                continue;
292            }
293
294            // Skip inline config comments (rumdl, markdownlint, Vale, remark-lint directives)
295            if is_inline_config_comment(trimmed) {
296                continue;
297            }
298
299            // Early return: skip lines that don't contain any potential matches
300            let line_lower = line.to_lowercase();
301            let has_line_matches = self.name_variants.iter().any(|name| line_lower.contains(name));
302
303            if !has_line_matches {
304                continue;
305            }
306
307            // Use the combined regex to find all matches in one pass
308            for cap in combined_regex.find_iter(line) {
309                let found_name = &line[cap.start()..cap.end()];
310
311                // Check word boundaries manually for Unicode support
312                let start_pos = cap.start();
313                let end_pos = cap.end();
314
315                // Skip matches in the key portion of frontmatter lines
316                if start_pos < fm_value_offset {
317                    continue;
318                }
319
320                // Skip matches inside HTML tag attributes (handles multi-line tags)
321                let byte_pos = line_info.byte_offset + start_pos;
322                if ctx.is_in_html_tag(byte_pos) {
323                    continue;
324                }
325
326                if !Self::is_at_word_boundary(line, start_pos, true) || !Self::is_at_word_boundary(line, end_pos, false)
327                {
328                    continue; // Not at word boundary
329                }
330
331                // Skip if in inline code when code_blocks is false
332                if !self.config.code_blocks {
333                    if ctx.is_in_code_block_or_span(byte_pos) {
334                        continue;
335                    }
336                    // pulldown-cmark doesn't parse markdown syntax inside HTML
337                    // comments, HTML blocks, or frontmatter, so backtick-wrapped
338                    // text isn't detected by is_in_code_block_or_span. Check directly.
339                    if (line_info.in_html_comment || line_info.in_html_block || line_info.in_front_matter)
340                        && Self::is_in_backtick_code_in_line(line, start_pos)
341                    {
342                        continue;
343                    }
344                }
345
346                // Skip if in link URL or reference definition
347                if Self::is_in_link(ctx, byte_pos) {
348                    continue;
349                }
350
351                // Skip if inside an angle-bracket URL (e.g., <https://...>)
352                // The link parser skips autolinks inside HTML comments,
353                // so we detect them directly in the line text.
354                if Self::is_in_angle_bracket_url(line, start_pos) {
355                    continue;
356                }
357
358                // Skip if inside a Markdown inline link URL in contexts where
359                // pulldown-cmark doesn't parse Markdown syntax (HTML comments,
360                // HTML blocks, frontmatter).
361                if (line_info.in_html_comment || line_info.in_html_block || line_info.in_front_matter)
362                    && Self::is_in_markdown_link_url(line, start_pos)
363                {
364                    continue;
365                }
366
367                // Skip if inside the URL portion of a WikiLink followed by a
368                // parenthesised destination — [[text]](url). pulldown-cmark
369                // registers [[text]] as a WikiLink in ctx.links but leaves the
370                // (url) as plain text, so is_in_link() misses those bytes.
371                if Self::is_in_wikilink_url(ctx, byte_pos) {
372                    continue;
373                }
374
375                // Find which proper name this matches
376                if let Some(proper_name) = self.get_proper_name_for(found_name) {
377                    // Only flag if it's not already correct
378                    if found_name != proper_name {
379                        violations.push((line_num, cap.start() + 1, found_name.to_string()));
380                    }
381                }
382            }
383        }
384
385        // Store in cache (ignore if mutex is poisoned)
386        if let Ok(mut cache) = self.content_cache.lock() {
387            cache.insert(hash, violations.clone());
388        }
389        violations
390    }
391
392    /// Check if a byte position is within a link URL (not link text)
393    ///
394    /// Link text should be checked for proper names, but URLs should be skipped.
395    /// For `[text](url)` - check text, skip url
396    /// For `[text][ref]` - check text, skip reference portion
397    /// For `[[text]]` (WikiLinks) - check text, skip brackets
398    fn is_in_link(ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
399        use pulldown_cmark::LinkType;
400
401        // Binary search links (sorted by byte_offset) to find candidate containing byte_pos
402        let link_idx = ctx.links.partition_point(|link| link.byte_offset <= byte_pos);
403        if link_idx > 0 {
404            let link = &ctx.links[link_idx - 1];
405            if byte_pos < link.byte_end {
406                // WikiLinks [[text]] start with '[[', regular links [text] start with '['
407                let text_start = if matches!(link.link_type, LinkType::WikiLink { .. }) {
408                    link.byte_offset + 2
409                } else {
410                    link.byte_offset + 1
411                };
412                let text_end = text_start + link.text.len();
413
414                // If position is within the text portion, skip only if text is a URL.
415                // WikiLinks use the page name as both text and url; never treat them
416                // as bare-domain URLs regardless of whether the name contains dots.
417                if byte_pos >= text_start && byte_pos < text_end {
418                    let is_wikilink = matches!(link.link_type, LinkType::WikiLink { .. });
419                    return Self::link_text_is_url(&link.text)
420                        || (!is_wikilink && Self::link_text_matches_link_url(&link.text, &link.url));
421                }
422                // Position is in the URL/reference portion, skip it
423                return true;
424            }
425        }
426
427        // Binary search images (sorted by byte_offset) to find candidate containing byte_pos
428        let image_idx = ctx.images.partition_point(|img| img.byte_offset <= byte_pos);
429        if image_idx > 0 {
430            let image = &ctx.images[image_idx - 1];
431            if byte_pos < image.byte_end {
432                // Image starts with '![' so alt text starts at byte_offset + 2
433                let alt_start = image.byte_offset + 2;
434                let alt_end = alt_start + image.alt_text.len();
435
436                // If position is within the alt text portion, don't skip
437                if byte_pos >= alt_start && byte_pos < alt_end {
438                    return false;
439                }
440                // Position is in the URL/reference portion, skip it
441                return true;
442            }
443        }
444
445        // Check pre-computed reference definitions
446        ctx.is_in_reference_def(byte_pos)
447    }
448
449    /// Check if link text is a URL that should not have proper name corrections.
450    fn link_text_is_url(text: &str) -> bool {
451        let lower = text.trim().to_ascii_lowercase();
452        lower.starts_with("http://")
453            || lower.starts_with("https://")
454            || lower.starts_with("www.")
455            || lower.starts_with("//")
456    }
457
458    /// Check if link text is the bare hostname/path of its destination URL.
459    ///
460    /// When the display text is the URL with the scheme stripped (e.g.,
461    /// `[example.github.io](https://example.github.io)`), the text is a domain
462    /// label, not a prose reference to a product, and should not be corrected.
463    ///
464    /// Requires the text to contain a dot, which distinguishes domain-like display
465    /// text from single-word WikiLink targets (e.g. `[[javascript]]`) where
466    /// `url == text` but neither is a domain name. Dotted WikiLink targets are
467    /// excluded separately via the `!is_wikilink` guard in `is_in_link`. Comparison
468    /// is case-insensitive because URL schemes and hostnames are case-insensitive.
469    fn link_text_matches_link_url(text: &str, url: &str) -> bool {
470        let text = text.trim();
471        // Only domain-like text (containing a dot) can be a bare hostname.
472        if !text.contains('.') {
473            return false;
474        }
475        let url_lower = url.to_ascii_lowercase();
476        let url_without_scheme = url_lower
477            .strip_prefix("https://")
478            .or_else(|| url_lower.strip_prefix("http://"))
479            .or_else(|| url_lower.strip_prefix("//"))
480            .unwrap_or(&url_lower);
481        let text_lower = text.to_ascii_lowercase();
482        // Exact match: text equals the URL with the scheme removed.
483        if url_without_scheme == text_lower.as_str() {
484            return true;
485        }
486        // Prefix match: text is the hostname portion and the URL has a path/query/fragment.
487        url_without_scheme.len() > text_lower.len()
488            && url_without_scheme.starts_with(text_lower.as_str())
489            && matches!(
490                url_without_scheme.as_bytes().get(text_lower.len()),
491                Some(b'/') | Some(b'?') | Some(b'#')
492            )
493    }
494
495    /// Check if a position within a line falls inside an angle-bracket URL (`<scheme://...>`).
496    ///
497    /// The link parser skips autolinks inside HTML comments, so `ctx.links` won't
498    /// contain them. This function detects angle-bracket URLs directly in the line
499    /// text, covering both HTML comments and regular text as a safety net.
500    fn is_in_angle_bracket_url(line: &str, pos: usize) -> bool {
501        let bytes = line.as_bytes();
502        let len = bytes.len();
503        let mut i = 0;
504        while i < len {
505            if bytes[i] == b'<' {
506                let after_open = i + 1;
507                // Check for a valid URI scheme per CommonMark autolink spec:
508                // scheme = [a-zA-Z][a-zA-Z0-9+.-]{0,31}
509                // followed by ':'
510                if after_open < len && bytes[after_open].is_ascii_alphabetic() {
511                    let mut s = after_open + 1;
512                    let scheme_max = (after_open + 32).min(len);
513                    while s < scheme_max
514                        && (bytes[s].is_ascii_alphanumeric()
515                            || bytes[s] == b'+'
516                            || bytes[s] == b'-'
517                            || bytes[s] == b'.')
518                    {
519                        s += 1;
520                    }
521                    if s < len && bytes[s] == b':' {
522                        // Valid scheme found; scan for closing '>' with no spaces or '<'
523                        let mut j = s + 1;
524                        let mut found_close = false;
525                        while j < len {
526                            match bytes[j] {
527                                b'>' => {
528                                    found_close = true;
529                                    break;
530                                }
531                                b' ' | b'<' => break,
532                                _ => j += 1,
533                            }
534                        }
535                        if found_close && pos >= i && pos <= j {
536                            return true;
537                        }
538                        if found_close {
539                            i = j + 1;
540                            continue;
541                        }
542                    }
543                }
544            }
545            i += 1;
546        }
547        false
548    }
549
550    /// Check if `byte_pos` falls inside the URL of a `[[text]](url)` construct.
551    ///
552    /// pulldown-cmark with WikiLinks enabled parses `[[text]]` as a WikiLink and
553    /// records it in `ctx.links`, but the immediately following `(url)` is left as
554    /// plain text and is therefore absent from `ctx.links`. This function detects
555    /// that gap by looking for a WikiLink entry whose `byte_end` falls exactly on a
556    /// `(` in the raw content, then checking whether `byte_pos` lies inside the
557    /// matching parenthesised URL span.
558    ///
559    /// Unlike `is_in_markdown_link_url`, this function is anchored to real parser
560    /// output (`ctx.links`) and will not suppress violations in text that merely
561    /// looks like a link (e.g. `[foo](github x)` with a space in the URL).
562    fn is_in_wikilink_url(ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
563        use pulldown_cmark::LinkType;
564        let content = ctx.content.as_bytes();
565
566        // ctx.links is sorted by byte_offset; only links that start at or before
567        // byte_pos can have a URL that encloses it.
568        let end = ctx.links.partition_point(|l| l.byte_offset <= byte_pos);
569
570        for link in &ctx.links[..end] {
571            if !matches!(link.link_type, LinkType::WikiLink { .. }) {
572                continue;
573            }
574            let wiki_end = link.byte_end;
575            // The WikiLink must end before byte_pos and be immediately followed by '('.
576            if wiki_end >= byte_pos || wiki_end >= content.len() || content[wiki_end] != b'(' {
577                continue;
578            }
579            // Scan to the matching ')' tracking nested parens and backslash escapes.
580            // Per CommonMark, an unquoted inline link destination cannot contain
581            // spaces, tabs, or newlines. If we encounter one, this is parenthesised
582            // prose rather than a URL, and pulldown-cmark will not parse it as a link.
583            let mut depth: u32 = 1;
584            let mut k = wiki_end + 1;
585            let mut valid_destination = true;
586            while k < content.len() && depth > 0 {
587                match content[k] {
588                    b'\\' => {
589                        k += 1; // skip escaped character
590                    }
591                    b'(' => depth += 1,
592                    b')' => depth -= 1,
593                    b' ' | b'\t' | b'\n' | b'\r' => {
594                        valid_destination = false;
595                        break;
596                    }
597                    _ => {}
598                }
599                k += 1;
600            }
601            // byte_pos is inside the URL if it falls between '(' and the matching ')'
602            // and the destination is valid (no unescaped whitespace).
603            if valid_destination && depth == 0 && byte_pos > wiki_end && byte_pos < k {
604                return true;
605            }
606        }
607        false
608    }
609
610    /// Check if a position within a line falls inside a Markdown link's
611    /// non-text portion (URL or reference label).
612    ///
613    /// Used as a text-level fallback for HTML comments, HTML blocks, and
614    /// frontmatter where pulldown-cmark skips link parsing entirely. Operates on
615    /// raw line bytes and therefore cannot distinguish real links from text that
616    /// merely resembles link syntax; do not call on regular markdown lines.
617    /// - `[text](url)` — returns true if `pos` is within `(...)`
618    /// - `[text][ref]` — returns true if `pos` is within the second `[...]`
619    fn is_in_markdown_link_url(line: &str, pos: usize) -> bool {
620        let bytes = line.as_bytes();
621        let len = bytes.len();
622        let mut i = 0;
623
624        while i < len {
625            // Look for unescaped '[' (handle double-escaped \\[ as unescaped)
626            if bytes[i] == b'[' && (i == 0 || bytes[i - 1] != b'\\' || (i >= 2 && bytes[i - 2] == b'\\')) {
627                // Find matching ']' handling nested brackets
628                let mut depth: u32 = 1;
629                let mut j = i + 1;
630                while j < len && depth > 0 {
631                    match bytes[j] {
632                        b'\\' => {
633                            j += 1; // skip escaped char
634                        }
635                        b'[' => depth += 1,
636                        b']' => depth -= 1,
637                        _ => {}
638                    }
639                    j += 1;
640                }
641
642                // j is now one past the ']'
643                if depth == 0 && j < len {
644                    if bytes[j] == b'(' {
645                        // Inline link: [text](url)
646                        let url_start = j;
647                        let mut paren_depth: u32 = 1;
648                        let mut k = j + 1;
649                        while k < len && paren_depth > 0 {
650                            match bytes[k] {
651                                b'\\' => {
652                                    k += 1; // skip escaped char
653                                }
654                                b'(' => paren_depth += 1,
655                                b')' => paren_depth -= 1,
656                                _ => {}
657                            }
658                            k += 1;
659                        }
660
661                        if paren_depth == 0 {
662                            if pos > url_start && pos < k {
663                                return true;
664                            }
665                            i = k;
666                            continue;
667                        }
668                    } else if bytes[j] == b'[' {
669                        // Reference link: [text][ref]
670                        let ref_start = j;
671                        let mut ref_depth: u32 = 1;
672                        let mut k = j + 1;
673                        while k < len && ref_depth > 0 {
674                            match bytes[k] {
675                                b'\\' => {
676                                    k += 1;
677                                }
678                                b'[' => ref_depth += 1,
679                                b']' => ref_depth -= 1,
680                                _ => {}
681                            }
682                            k += 1;
683                        }
684
685                        if ref_depth == 0 {
686                            if pos > ref_start && pos < k {
687                                return true;
688                            }
689                            i = k;
690                            continue;
691                        }
692                    }
693                }
694            }
695            i += 1;
696        }
697        false
698    }
699
700    /// Check if a position within a line falls inside backtick-delimited code.
701    ///
702    /// pulldown-cmark does not parse markdown syntax inside HTML comments, so
703    /// `ctx.is_in_code_block_or_span` returns false for backtick-wrapped text
704    /// within comments. This function detects backtick code spans directly in
705    /// the line text following CommonMark rules: a code span starts with N
706    /// backticks and ends with exactly N backticks.
707    fn is_in_backtick_code_in_line(line: &str, pos: usize) -> bool {
708        let bytes = line.as_bytes();
709        let len = bytes.len();
710        let mut i = 0;
711        while i < len {
712            if bytes[i] == b'`' {
713                // Count the opening backtick sequence length
714                let open_start = i;
715                while i < len && bytes[i] == b'`' {
716                    i += 1;
717                }
718                let tick_len = i - open_start;
719
720                // Scan forward for a closing sequence of exactly tick_len backticks
721                while i < len {
722                    if bytes[i] == b'`' {
723                        let close_start = i;
724                        while i < len && bytes[i] == b'`' {
725                            i += 1;
726                        }
727                        if i - close_start == tick_len {
728                            // Matched pair found; the code span content is between
729                            // the end of the opening backticks and the start of the
730                            // closing backticks (exclusive of the backticks themselves).
731                            let content_start = open_start + tick_len;
732                            let content_end = close_start;
733                            if pos >= content_start && pos < content_end {
734                                return true;
735                            }
736                            // Continue scanning after this pair
737                            break;
738                        }
739                        // Not the right length; keep scanning
740                    } else {
741                        i += 1;
742                    }
743                }
744            } else {
745                i += 1;
746            }
747        }
748        false
749    }
750
751    // Check if a character is a word boundary (handles Unicode)
752    fn is_word_boundary_char(c: char) -> bool {
753        !c.is_alphanumeric()
754    }
755
756    // Check if position is at a word boundary using byte-level lookups.
757    fn is_at_word_boundary(content: &str, pos: usize, is_start: bool) -> bool {
758        if is_start {
759            if pos == 0 {
760                return true;
761            }
762            match content[..pos].chars().next_back() {
763                None => true,
764                Some(c) => Self::is_word_boundary_char(c),
765            }
766        } else {
767            if pos >= content.len() {
768                return true;
769            }
770            match content[pos..].chars().next() {
771                None => true,
772                Some(c) => Self::is_word_boundary_char(c),
773            }
774        }
775    }
776
777    /// For a frontmatter line, return the byte offset where the checkable
778    /// value portion starts. Returns `usize::MAX` if the entire line should be
779    /// skipped (frontmatter delimiters, key-only lines, YAML comments, flow constructs).
780    fn frontmatter_value_offset(line: &str) -> usize {
781        let trimmed = line.trim();
782
783        // Skip frontmatter delimiters and empty lines
784        if trimmed == "---" || trimmed == "+++" || trimmed.is_empty() {
785            return usize::MAX;
786        }
787
788        // Skip YAML comments
789        if trimmed.starts_with('#') {
790            return usize::MAX;
791        }
792
793        // YAML list item: "  - item" or "  - key: value"
794        let stripped = line.trim_start();
795        if let Some(after_dash) = stripped.strip_prefix("- ") {
796            let leading = line.len() - stripped.len();
797            // Check if the list item contains a mapping (e.g., "- key: value")
798            if let Some(result) = Self::kv_value_offset(line, after_dash, leading + 2) {
799                return result;
800            }
801            // Bare list item value (no colon) - check content after "- "
802            return leading + 2;
803        }
804        if stripped == "-" {
805            return usize::MAX;
806        }
807
808        // Key-value pair with colon separator (YAML): "key: value"
809        if let Some(result) = Self::kv_value_offset(line, stripped, line.len() - stripped.len()) {
810            return result;
811        }
812
813        // Key-value pair with equals separator (TOML): "key = value"
814        if let Some(eq_pos) = line.find('=') {
815            let after_eq = eq_pos + 1;
816            if after_eq < line.len() && line.as_bytes()[after_eq] == b' ' {
817                let value_start = after_eq + 1;
818                let value_slice = &line[value_start..];
819                let value_trimmed = value_slice.trim();
820                if value_trimmed.is_empty() {
821                    return usize::MAX;
822                }
823                // For quoted values, skip the opening quote character
824                if (value_trimmed.starts_with('"') && value_trimmed.ends_with('"'))
825                    || (value_trimmed.starts_with('\'') && value_trimmed.ends_with('\''))
826                {
827                    let quote_offset = value_slice.find(['"', '\'']).unwrap_or(0);
828                    return value_start + quote_offset + 1;
829                }
830                return value_start;
831            }
832            // Equals with no space after or at end of line -> no value to check
833            return usize::MAX;
834        }
835
836        // No separator found - continuation line or bare value, check the whole line
837        0
838    }
839
840    /// Parse a key-value pair using colon separator within `content` that starts
841    /// at `base_offset` in the original line. Returns `Some(offset)` if a colon
842    /// separator is found, `None` if no colon is present.
843    fn kv_value_offset(line: &str, content: &str, base_offset: usize) -> Option<usize> {
844        let colon_pos = content.find(':')?;
845        let abs_colon = base_offset + colon_pos;
846        let after_colon = abs_colon + 1;
847        if after_colon < line.len() && line.as_bytes()[after_colon] == b' ' {
848            let value_start = after_colon + 1;
849            let value_slice = &line[value_start..];
850            let value_trimmed = value_slice.trim();
851            if value_trimmed.is_empty() {
852                return Some(usize::MAX);
853            }
854            // Skip flow mappings and flow sequences - too complex for heuristic parsing
855            if value_trimmed.starts_with('{') || value_trimmed.starts_with('[') {
856                return Some(usize::MAX);
857            }
858            // For quoted values, skip the opening quote character
859            if (value_trimmed.starts_with('"') && value_trimmed.ends_with('"'))
860                || (value_trimmed.starts_with('\'') && value_trimmed.ends_with('\''))
861            {
862                let quote_offset = value_slice.find(['"', '\'']).unwrap_or(0);
863                return Some(value_start + quote_offset + 1);
864            }
865            return Some(value_start);
866        }
867        // Colon with no space after or at end of line -> no value to check
868        Some(usize::MAX)
869    }
870
871    // Get the proper name that should be used for a found name
872    fn get_proper_name_for(&self, found_name: &str) -> Option<String> {
873        let found_lower = found_name.to_lowercase();
874
875        // Iterate through the configured proper names
876        for name in &self.config.names {
877            let lower_name = name.to_lowercase();
878            let lower_name_no_dots = lower_name.replace('.', "");
879
880            // Direct match
881            if found_lower == lower_name || found_lower == lower_name_no_dots {
882                return Some(name.clone());
883            }
884
885            // Check ASCII-normalized version
886            let ascii_normalized = Self::ascii_normalize(&lower_name);
887
888            let ascii_no_dots = ascii_normalized.replace('.', "");
889
890            if found_lower == ascii_normalized || found_lower == ascii_no_dots {
891                return Some(name.clone());
892            }
893        }
894        None
895    }
896}
897
898impl Rule for MD044ProperNames {
899    fn name(&self) -> &'static str {
900        "MD044"
901    }
902
903    fn description(&self) -> &'static str {
904        "Proper names should have the correct capitalization"
905    }
906
907    fn category(&self) -> RuleCategory {
908        RuleCategory::Other
909    }
910
911    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
912        if self.config.names.is_empty() {
913            return true;
914        }
915        // Quick check if any configured name variants exist (case-insensitive)
916        let content_lower = if ctx.content.is_ascii() {
917            ctx.content.to_ascii_lowercase()
918        } else {
919            ctx.content.to_lowercase()
920        };
921        !self.name_variants.iter().any(|name| content_lower.contains(name))
922    }
923
924    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
925        let content = ctx.content;
926        if content.is_empty() || self.config.names.is_empty() || self.combined_pattern.is_none() {
927            return Ok(Vec::new());
928        }
929
930        // Compute lowercase content once and reuse across all checks
931        let content_lower = if content.is_ascii() {
932            content.to_ascii_lowercase()
933        } else {
934            content.to_lowercase()
935        };
936
937        // Early return: use pre-computed name_variants for the quick check
938        let has_potential_matches = self.name_variants.iter().any(|name| content_lower.contains(name));
939
940        if !has_potential_matches {
941            return Ok(Vec::new());
942        }
943
944        let line_index = &ctx.line_index;
945        let violations = self.find_name_violations(content, ctx, &content_lower);
946
947        let warnings = violations
948            .into_iter()
949            .filter_map(|(line, column, found_name)| {
950                self.get_proper_name_for(&found_name).map(|proper_name| {
951                    // `column` is a 1-indexed byte offset into the line (from regex .start() + 1).
952                    // Build the Fix range directly in bytes to avoid the character-based
953                    // line_col_to_byte_range_with_length function, which would misinterpret
954                    // the byte offset as a character count on lines with multi-byte content.
955                    let line_start = line_index.get_line_start_byte(line).unwrap_or(0);
956                    let byte_start = line_start + (column - 1);
957                    let byte_end = byte_start + found_name.len();
958                    LintWarning {
959                        rule_name: Some(self.name().to_string()),
960                        line,
961                        column,
962                        end_line: line,
963                        end_column: column + found_name.len(),
964                        message: format!("Proper name '{found_name}' should be '{proper_name}'"),
965                        severity: Severity::Warning,
966                        fix: Some(Fix::new(byte_start..byte_end, proper_name)),
967                    }
968                })
969            })
970            .collect();
971
972        Ok(warnings)
973    }
974
975    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
976        if self.should_skip(ctx) {
977            return Ok(ctx.content.to_string());
978        }
979        let warnings = self.check(ctx)?;
980        if warnings.is_empty() {
981            return Ok(ctx.content.to_string());
982        }
983        let warnings =
984            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
985        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
986            .map_err(crate::rule::LintError::InvalidInput)
987    }
988
989    fn as_any(&self) -> &dyn std::any::Any {
990        self
991    }
992
993    crate::impl_rule_config_methods!(MD044Config);
994}
995
996#[cfg(test)]
997mod tests {
998    use super::*;
999    use crate::lint_context::LintContext;
1000
1001    fn create_context(content: &str) -> LintContext<'_> {
1002        LintContext::new(content, crate::config::MarkdownFlavor::Standard, None)
1003    }
1004
1005    #[test]
1006    fn test_correctly_capitalized_names() {
1007        let rule = MD044ProperNames::new(
1008            vec![
1009                "JavaScript".to_string(),
1010                "TypeScript".to_string(),
1011                "Node.js".to_string(),
1012            ],
1013            true,
1014        );
1015
1016        let content = "This document uses JavaScript, TypeScript, and Node.js correctly.";
1017        let ctx = create_context(content);
1018        let result = rule.check(&ctx).unwrap();
1019        assert!(result.is_empty(), "Should not flag correctly capitalized names");
1020    }
1021
1022    #[test]
1023    fn test_incorrectly_capitalized_names() {
1024        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "TypeScript".to_string()], true);
1025
1026        let content = "This document uses javascript and typescript incorrectly.";
1027        let ctx = create_context(content);
1028        let result = rule.check(&ctx).unwrap();
1029
1030        assert_eq!(result.len(), 2, "Should flag two incorrect capitalizations");
1031        assert_eq!(result[0].message, "Proper name 'javascript' should be 'JavaScript'");
1032        assert_eq!(result[0].line, 1);
1033        assert_eq!(result[0].column, 20);
1034        assert_eq!(result[1].message, "Proper name 'typescript' should be 'TypeScript'");
1035        assert_eq!(result[1].line, 1);
1036        assert_eq!(result[1].column, 35);
1037    }
1038
1039    #[test]
1040    fn test_names_at_beginning_of_sentences() {
1041        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "Python".to_string()], true);
1042
1043        let content = "javascript is a great language. python is also popular.";
1044        let ctx = create_context(content);
1045        let result = rule.check(&ctx).unwrap();
1046
1047        assert_eq!(result.len(), 2, "Should flag names at beginning of sentences");
1048        assert_eq!(result[0].line, 1);
1049        assert_eq!(result[0].column, 1);
1050        assert_eq!(result[1].line, 1);
1051        assert_eq!(result[1].column, 33);
1052    }
1053
1054    #[test]
1055    fn test_names_in_code_blocks_checked_by_default() {
1056        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1057
1058        let content = r#"Here is some text with JavaScript.
1059
1060```javascript
1061// This javascript should be checked
1062const lang = "javascript";
1063```
1064
1065But this javascript should be flagged."#;
1066
1067        let ctx = create_context(content);
1068        let result = rule.check(&ctx).unwrap();
1069
1070        assert_eq!(result.len(), 3, "Should flag javascript inside and outside code blocks");
1071        assert_eq!(result[0].line, 4);
1072        assert_eq!(result[1].line, 5);
1073        assert_eq!(result[2].line, 8);
1074    }
1075
1076    #[test]
1077    fn test_names_in_code_blocks_ignored_when_disabled() {
1078        let rule = MD044ProperNames::new(
1079            vec!["JavaScript".to_string()],
1080            false, // code_blocks = false means skip code blocks
1081        );
1082
1083        let content = r#"```
1084javascript in code block
1085```"#;
1086
1087        let ctx = create_context(content);
1088        let result = rule.check(&ctx).unwrap();
1089
1090        assert_eq!(
1091            result.len(),
1092            0,
1093            "Should not flag javascript in code blocks when code_blocks is false"
1094        );
1095    }
1096
1097    #[test]
1098    fn test_names_in_inline_code_checked_by_default() {
1099        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1100
1101        let content = "This is `javascript` in inline code and javascript outside.";
1102        let ctx = create_context(content);
1103        let result = rule.check(&ctx).unwrap();
1104
1105        // When code_blocks=true, inline code should be checked
1106        assert_eq!(result.len(), 2, "Should flag javascript inside and outside inline code");
1107        assert_eq!(result[0].column, 10); // javascript in inline code
1108        assert_eq!(result[1].column, 41); // javascript outside
1109    }
1110
1111    #[test]
1112    fn test_multiple_names_in_same_line() {
1113        let rule = MD044ProperNames::new(
1114            vec!["JavaScript".to_string(), "TypeScript".to_string(), "React".to_string()],
1115            true,
1116        );
1117
1118        let content = "I use javascript, typescript, and react in my projects.";
1119        let ctx = create_context(content);
1120        let result = rule.check(&ctx).unwrap();
1121
1122        assert_eq!(result.len(), 3, "Should flag all three incorrect names");
1123        assert_eq!(result[0].message, "Proper name 'javascript' should be 'JavaScript'");
1124        assert_eq!(result[1].message, "Proper name 'typescript' should be 'TypeScript'");
1125        assert_eq!(result[2].message, "Proper name 'react' should be 'React'");
1126    }
1127
1128    #[test]
1129    fn test_case_sensitivity() {
1130        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1131
1132        let content = "JAVASCRIPT, Javascript, javascript, and JavaScript variations.";
1133        let ctx = create_context(content);
1134        let result = rule.check(&ctx).unwrap();
1135
1136        assert_eq!(result.len(), 3, "Should flag all incorrect case variations");
1137        // JavaScript (correct) should not be flagged
1138        assert!(result.iter().all(|w| w.message.contains("should be 'JavaScript'")));
1139    }
1140
1141    #[test]
1142    fn test_configuration_with_custom_name_list() {
1143        let config = MD044Config {
1144            names: vec!["GitHub".to_string(), "GitLab".to_string(), "DevOps".to_string()],
1145            code_blocks: true,
1146            html_elements: true,
1147            html_comments: true,
1148        };
1149        let rule = MD044ProperNames::from_config_struct(config);
1150
1151        let content = "We use github, gitlab, and devops for our workflow.";
1152        let ctx = create_context(content);
1153        let result = rule.check(&ctx).unwrap();
1154
1155        assert_eq!(result.len(), 3, "Should flag all custom names");
1156        assert_eq!(result[0].message, "Proper name 'github' should be 'GitHub'");
1157        assert_eq!(result[1].message, "Proper name 'gitlab' should be 'GitLab'");
1158        assert_eq!(result[2].message, "Proper name 'devops' should be 'DevOps'");
1159    }
1160
1161    #[test]
1162    fn test_empty_configuration() {
1163        let rule = MD044ProperNames::new(vec![], true);
1164
1165        let content = "This has javascript and typescript but no configured names.";
1166        let ctx = create_context(content);
1167        let result = rule.check(&ctx).unwrap();
1168
1169        assert!(result.is_empty(), "Should not flag anything with empty configuration");
1170    }
1171
1172    #[test]
1173    fn test_names_with_special_characters() {
1174        let rule = MD044ProperNames::new(
1175            vec!["Node.js".to_string(), "ASP.NET".to_string(), "C++".to_string()],
1176            true,
1177        );
1178
1179        let content = "We use nodejs, asp.net, ASP.NET, and c++ in our stack.";
1180        let ctx = create_context(content);
1181        let result = rule.check(&ctx).unwrap();
1182
1183        // nodejs should match Node.js (dotless variation)
1184        // asp.net should be flagged (wrong case)
1185        // ASP.NET should not be flagged (correct)
1186        // c++ should be flagged
1187        assert_eq!(result.len(), 3, "Should handle special characters correctly");
1188
1189        let messages: Vec<&str> = result.iter().map(|w| w.message.as_str()).collect();
1190        assert!(messages.contains(&"Proper name 'nodejs' should be 'Node.js'"));
1191        assert!(messages.contains(&"Proper name 'asp.net' should be 'ASP.NET'"));
1192        assert!(messages.contains(&"Proper name 'c++' should be 'C++'"));
1193    }
1194
1195    #[test]
1196    fn test_word_boundaries() {
1197        let rule = MD044ProperNames::new(vec!["Java".to_string(), "Script".to_string()], true);
1198
1199        let content = "JavaScript is not java or script, but Java and Script are separate.";
1200        let ctx = create_context(content);
1201        let result = rule.check(&ctx).unwrap();
1202
1203        // Should only flag lowercase "java" and "script" as separate words
1204        assert_eq!(result.len(), 2, "Should respect word boundaries");
1205        assert!(result.iter().any(|w| w.column == 19)); // "java" position
1206        assert!(result.iter().any(|w| w.column == 27)); // "script" position
1207    }
1208
1209    #[test]
1210    fn test_fix_method() {
1211        let rule = MD044ProperNames::new(
1212            vec![
1213                "JavaScript".to_string(),
1214                "TypeScript".to_string(),
1215                "Node.js".to_string(),
1216            ],
1217            true,
1218        );
1219
1220        let content = "I love javascript, typescript, and nodejs!";
1221        let ctx = create_context(content);
1222        let fixed = rule.fix(&ctx).unwrap();
1223
1224        assert_eq!(fixed, "I love JavaScript, TypeScript, and Node.js!");
1225    }
1226
1227    #[test]
1228    fn test_fix_multiple_occurrences() {
1229        let rule = MD044ProperNames::new(vec!["Python".to_string()], true);
1230
1231        let content = "python is great. I use python daily. PYTHON is powerful.";
1232        let ctx = create_context(content);
1233        let fixed = rule.fix(&ctx).unwrap();
1234
1235        assert_eq!(fixed, "Python is great. I use Python daily. Python is powerful.");
1236    }
1237
1238    #[test]
1239    fn test_fix_checks_code_blocks_by_default() {
1240        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1241
1242        let content = r#"I love javascript.
1243
1244```
1245const lang = "javascript";
1246```
1247
1248More javascript here."#;
1249
1250        let ctx = create_context(content);
1251        let fixed = rule.fix(&ctx).unwrap();
1252
1253        let expected = r#"I love JavaScript.
1254
1255```
1256const lang = "JavaScript";
1257```
1258
1259More JavaScript here."#;
1260
1261        assert_eq!(fixed, expected);
1262    }
1263
1264    #[test]
1265    fn test_multiline_content() {
1266        let rule = MD044ProperNames::new(vec!["Rust".to_string(), "Python".to_string()], true);
1267
1268        let content = r#"First line with rust.
1269Second line with python.
1270Third line with RUST and PYTHON."#;
1271
1272        let ctx = create_context(content);
1273        let result = rule.check(&ctx).unwrap();
1274
1275        assert_eq!(result.len(), 4, "Should flag all incorrect occurrences");
1276        assert_eq!(result[0].line, 1);
1277        assert_eq!(result[1].line, 2);
1278        assert_eq!(result[2].line, 3);
1279        assert_eq!(result[3].line, 3);
1280    }
1281
1282    #[test]
1283    fn test_default_config() {
1284        let config = MD044Config::default();
1285        assert!(config.names.is_empty());
1286        assert!(!config.code_blocks);
1287        assert!(config.html_elements);
1288        assert!(config.html_comments);
1289    }
1290
1291    #[test]
1292    fn test_default_config_checks_html_comments() {
1293        let config = MD044Config {
1294            names: vec!["JavaScript".to_string()],
1295            ..MD044Config::default()
1296        };
1297        let rule = MD044ProperNames::from_config_struct(config);
1298
1299        let content = "# Guide\n\n<!-- javascript mentioned here -->\n";
1300        let ctx = create_context(content);
1301        let result = rule.check(&ctx).unwrap();
1302
1303        assert_eq!(result.len(), 1, "Default config should check HTML comments");
1304        assert_eq!(result[0].line, 3);
1305    }
1306
1307    #[test]
1308    fn test_default_config_skips_code_blocks() {
1309        let config = MD044Config {
1310            names: vec!["JavaScript".to_string()],
1311            ..MD044Config::default()
1312        };
1313        let rule = MD044ProperNames::from_config_struct(config);
1314
1315        let content = "# Guide\n\n```\njavascript in code\n```\n";
1316        let ctx = create_context(content);
1317        let result = rule.check(&ctx).unwrap();
1318
1319        assert_eq!(result.len(), 0, "Default config should skip code blocks");
1320    }
1321
1322    #[test]
1323    fn test_standalone_html_comment_checked() {
1324        let config = MD044Config {
1325            names: vec!["Test".to_string()],
1326            ..MD044Config::default()
1327        };
1328        let rule = MD044ProperNames::from_config_struct(config);
1329
1330        let content = "# Heading\n\n<!-- this is a test example -->\n";
1331        let ctx = create_context(content);
1332        let result = rule.check(&ctx).unwrap();
1333
1334        assert_eq!(result.len(), 1, "Should flag proper name in standalone HTML comment");
1335        assert_eq!(result[0].line, 3);
1336    }
1337
1338    #[test]
1339    fn test_inline_config_comments_not_flagged() {
1340        let config = MD044Config {
1341            names: vec!["RUMDL".to_string()],
1342            ..MD044Config::default()
1343        };
1344        let rule = MD044ProperNames::from_config_struct(config);
1345
1346        // Lines 1, 3, 4, 6 are inline config comments — should not be flagged.
1347        // Lines 2, 5 contain "rumdl" in regular text — flagged by rule.check(),
1348        // but would be suppressed by the linting engine's inline config filtering.
1349        let content = "<!-- rumdl-disable MD044 -->\nSome rumdl text here.\n<!-- rumdl-enable MD044 -->\n<!-- markdownlint-disable -->\nMore rumdl text.\n<!-- markdownlint-enable -->\n";
1350        let ctx = create_context(content);
1351        let result = rule.check(&ctx).unwrap();
1352
1353        assert_eq!(result.len(), 2, "Should only flag body lines, not config comments");
1354        assert_eq!(result[0].line, 2);
1355        assert_eq!(result[1].line, 5);
1356    }
1357
1358    #[test]
1359    fn test_html_comment_skipped_when_disabled() {
1360        let config = MD044Config {
1361            names: vec!["Test".to_string()],
1362            code_blocks: true,
1363            html_elements: true,
1364            html_comments: false,
1365        };
1366        let rule = MD044ProperNames::from_config_struct(config);
1367
1368        let content = "# Heading\n\n<!-- this is a test example -->\n\nRegular test here.\n";
1369        let ctx = create_context(content);
1370        let result = rule.check(&ctx).unwrap();
1371
1372        assert_eq!(
1373            result.len(),
1374            1,
1375            "Should only flag 'test' outside HTML comment when html_comments=false"
1376        );
1377        assert_eq!(result[0].line, 5);
1378    }
1379
1380    #[test]
1381    fn test_fix_corrects_html_comment_content() {
1382        let config = MD044Config {
1383            names: vec!["JavaScript".to_string()],
1384            ..MD044Config::default()
1385        };
1386        let rule = MD044ProperNames::from_config_struct(config);
1387
1388        let content = "# Guide\n\n<!-- javascript mentioned here -->\n";
1389        let ctx = create_context(content);
1390        let fixed = rule.fix(&ctx).unwrap();
1391
1392        assert_eq!(fixed, "# Guide\n\n<!-- JavaScript mentioned here -->\n");
1393    }
1394
1395    #[test]
1396    fn test_fix_does_not_modify_inline_config_comments() {
1397        let config = MD044Config {
1398            names: vec!["RUMDL".to_string()],
1399            ..MD044Config::default()
1400        };
1401        let rule = MD044ProperNames::from_config_struct(config);
1402
1403        let content = "<!-- rumdl-disable -->\nSome rumdl text.\n<!-- rumdl-enable -->\n";
1404        let ctx = create_context(content);
1405        let fixed = rule.fix(&ctx).unwrap();
1406
1407        // Config comments should be untouched
1408        assert!(fixed.contains("<!-- rumdl-disable -->"));
1409        assert!(fixed.contains("<!-- rumdl-enable -->"));
1410        // Body text inside disable block should NOT be fixed (rule is disabled)
1411        assert!(
1412            fixed.contains("Some rumdl text."),
1413            "Line inside rumdl-disable block should not be modified by fix()"
1414        );
1415    }
1416
1417    #[test]
1418    fn test_fix_respects_inline_disable_partial() {
1419        let config = MD044Config {
1420            names: vec!["RUMDL".to_string()],
1421            ..MD044Config::default()
1422        };
1423        let rule = MD044ProperNames::from_config_struct(config);
1424
1425        let content =
1426            "<!-- rumdl-disable MD044 -->\nSome rumdl text.\n<!-- rumdl-enable MD044 -->\n\nSome rumdl text outside.\n";
1427        let ctx = create_context(content);
1428        let fixed = rule.fix(&ctx).unwrap();
1429
1430        // Line inside disable block should be preserved
1431        assert!(
1432            fixed.contains("Some rumdl text.\n<!-- rumdl-enable"),
1433            "Line inside disable block should not be modified"
1434        );
1435        // Line outside disable block should be fixed
1436        assert!(
1437            fixed.contains("Some RUMDL text outside."),
1438            "Line outside disable block should be fixed"
1439        );
1440    }
1441
1442    #[test]
1443    fn test_performance_with_many_names() {
1444        let mut names = vec![];
1445        for i in 0..50 {
1446            names.push(format!("ProperName{i}"));
1447        }
1448
1449        let rule = MD044ProperNames::new(names, true);
1450
1451        let content = "This has propername0, propername25, and propername49 incorrectly.";
1452        let ctx = create_context(content);
1453        let result = rule.check(&ctx).unwrap();
1454
1455        assert_eq!(result.len(), 3, "Should handle many configured names efficiently");
1456    }
1457
1458    #[test]
1459    fn test_large_name_count_performance() {
1460        // Verify MD044 can handle large numbers of names without regex limitations
1461        // This test confirms that fancy-regex handles large patterns well
1462        let names = (0..1000).map(|i| format!("ProperName{i}")).collect::<Vec<_>>();
1463
1464        let rule = MD044ProperNames::new(names, true);
1465
1466        // The combined pattern should be created successfully
1467        assert!(rule.combined_pattern.is_some());
1468
1469        // Should be able to check content without errors
1470        let content = "This has propername0 and propername999 in it.";
1471        let ctx = create_context(content);
1472        let result = rule.check(&ctx).unwrap();
1473
1474        // Should detect both incorrect names
1475        assert_eq!(result.len(), 2, "Should handle 1000 names without issues");
1476    }
1477
1478    #[test]
1479    fn test_cache_behavior() {
1480        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1481
1482        let content = "Using javascript here.";
1483        let ctx = create_context(content);
1484
1485        // First check
1486        let result1 = rule.check(&ctx).unwrap();
1487        assert_eq!(result1.len(), 1);
1488
1489        // Second check should use cache
1490        let result2 = rule.check(&ctx).unwrap();
1491        assert_eq!(result2.len(), 1);
1492
1493        // Results should be identical
1494        assert_eq!(result1[0].line, result2[0].line);
1495        assert_eq!(result1[0].column, result2[0].column);
1496    }
1497
1498    #[test]
1499    fn test_html_comments_not_checked_when_disabled() {
1500        let config = MD044Config {
1501            names: vec!["JavaScript".to_string()],
1502            code_blocks: true,    // Check code blocks
1503            html_elements: true,  // Check HTML elements
1504            html_comments: false, // Don't check HTML comments
1505        };
1506        let rule = MD044ProperNames::from_config_struct(config);
1507
1508        let content = r#"Regular javascript here.
1509<!-- This javascript in HTML comment should be ignored -->
1510More javascript outside."#;
1511
1512        let ctx = create_context(content);
1513        let result = rule.check(&ctx).unwrap();
1514
1515        assert_eq!(result.len(), 2, "Should only flag javascript outside HTML comments");
1516        assert_eq!(result[0].line, 1);
1517        assert_eq!(result[1].line, 3);
1518    }
1519
1520    #[test]
1521    fn test_html_comments_checked_when_enabled() {
1522        let config = MD044Config {
1523            names: vec!["JavaScript".to_string()],
1524            code_blocks: true,   // Check code blocks
1525            html_elements: true, // Check HTML elements
1526            html_comments: true, // Check HTML comments
1527        };
1528        let rule = MD044ProperNames::from_config_struct(config);
1529
1530        let content = r#"Regular javascript here.
1531<!-- This javascript in HTML comment should be checked -->
1532More javascript outside."#;
1533
1534        let ctx = create_context(content);
1535        let result = rule.check(&ctx).unwrap();
1536
1537        assert_eq!(
1538            result.len(),
1539            3,
1540            "Should flag all javascript occurrences including in HTML comments"
1541        );
1542    }
1543
1544    #[test]
1545    fn test_multiline_html_comments() {
1546        let config = MD044Config {
1547            names: vec!["Python".to_string(), "JavaScript".to_string()],
1548            code_blocks: true,    // Check code blocks
1549            html_elements: true,  // Check HTML elements
1550            html_comments: false, // Don't check HTML comments
1551        };
1552        let rule = MD044ProperNames::from_config_struct(config);
1553
1554        let content = r#"Regular python here.
1555<!--
1556This is a multiline comment
1557with javascript and python
1558that should be ignored
1559-->
1560More javascript outside."#;
1561
1562        let ctx = create_context(content);
1563        let result = rule.check(&ctx).unwrap();
1564
1565        assert_eq!(result.len(), 2, "Should only flag names outside HTML comments");
1566        assert_eq!(result[0].line, 1); // python
1567        assert_eq!(result[1].line, 7); // javascript
1568    }
1569
1570    #[test]
1571    fn test_fix_preserves_html_comments_when_disabled() {
1572        let config = MD044Config {
1573            names: vec!["JavaScript".to_string()],
1574            code_blocks: true,    // Check code blocks
1575            html_elements: true,  // Check HTML elements
1576            html_comments: false, // Don't check HTML comments
1577        };
1578        let rule = MD044ProperNames::from_config_struct(config);
1579
1580        let content = r#"javascript here.
1581<!-- javascript in comment -->
1582More javascript."#;
1583
1584        let ctx = create_context(content);
1585        let fixed = rule.fix(&ctx).unwrap();
1586
1587        let expected = r#"JavaScript here.
1588<!-- javascript in comment -->
1589More JavaScript."#;
1590
1591        assert_eq!(
1592            fixed, expected,
1593            "Should not fix names inside HTML comments when disabled"
1594        );
1595    }
1596
1597    #[test]
1598    fn test_proper_names_in_link_text_are_flagged() {
1599        let rule = MD044ProperNames::new(
1600            vec!["JavaScript".to_string(), "Node.js".to_string(), "Python".to_string()],
1601            true,
1602        );
1603
1604        let content = r#"Check this [javascript documentation](https://javascript.info) for info.
1605
1606Visit [node.js homepage](https://nodejs.org) and [python tutorial](https://python.org).
1607
1608Real javascript should be flagged.
1609
1610Also see the [typescript guide][ts-ref] for more.
1611
1612Real python should be flagged too.
1613
1614[ts-ref]: https://typescript.org/handbook"#;
1615
1616        let ctx = create_context(content);
1617        let result = rule.check(&ctx).unwrap();
1618
1619        // Link text should be checked, URLs should not be checked
1620        // Line 1: [javascript documentation] - "javascript" should be flagged
1621        // Line 3: [node.js homepage] - "node.js" should be flagged (matches "Node.js")
1622        // Line 3: [python tutorial] - "python" should be flagged
1623        // Line 5: standalone javascript
1624        // Line 9: standalone python
1625        assert_eq!(result.len(), 5, "Expected 5 warnings: 3 in link text + 2 standalone");
1626
1627        // Verify line numbers for link text warnings
1628        let line_1_warnings: Vec<_> = result.iter().filter(|w| w.line == 1).collect();
1629        assert_eq!(line_1_warnings.len(), 1);
1630        assert!(
1631            line_1_warnings[0]
1632                .message
1633                .contains("'javascript' should be 'JavaScript'")
1634        );
1635
1636        let line_3_warnings: Vec<_> = result.iter().filter(|w| w.line == 3).collect();
1637        assert_eq!(line_3_warnings.len(), 2); // node.js and python
1638
1639        // Standalone warnings
1640        assert!(result.iter().any(|w| w.line == 5 && w.message.contains("'javascript'")));
1641        assert!(result.iter().any(|w| w.line == 9 && w.message.contains("'python'")));
1642    }
1643
1644    #[test]
1645    fn test_link_urls_not_flagged() {
1646        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1647
1648        // URL contains "javascript" but should NOT be flagged
1649        let content = r#"[Link Text](https://javascript.info/guide)"#;
1650
1651        let ctx = create_context(content);
1652        let result = rule.check(&ctx).unwrap();
1653
1654        // URL should not be checked
1655        assert!(result.is_empty(), "URLs should not be checked for proper names");
1656    }
1657
1658    #[test]
1659    fn test_proper_names_in_image_alt_text_are_flagged() {
1660        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1661
1662        let content = r#"Here is a ![javascript logo](javascript.png "javascript icon") image.
1663
1664Real javascript should be flagged."#;
1665
1666        let ctx = create_context(content);
1667        let result = rule.check(&ctx).unwrap();
1668
1669        // Image alt text should be checked, URL and title should not be checked
1670        // Line 1: ![javascript logo] - "javascript" should be flagged
1671        // Line 3: standalone javascript
1672        assert_eq!(result.len(), 2, "Expected 2 warnings: 1 in alt text + 1 standalone");
1673        assert!(result[0].message.contains("'javascript' should be 'JavaScript'"));
1674        assert!(result[0].line == 1); // "![javascript logo]"
1675        assert!(result[1].message.contains("'javascript' should be 'JavaScript'"));
1676        assert!(result[1].line == 3); // "Real javascript should be flagged."
1677    }
1678
1679    #[test]
1680    fn test_image_urls_not_flagged() {
1681        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1682
1683        // URL contains "javascript" but should NOT be flagged
1684        let content = r#"![Logo](https://javascript.info/logo.png)"#;
1685
1686        let ctx = create_context(content);
1687        let result = rule.check(&ctx).unwrap();
1688
1689        // Image URL should not be checked
1690        assert!(result.is_empty(), "Image URLs should not be checked for proper names");
1691    }
1692
1693    #[test]
1694    fn test_reference_link_text_flagged_but_definition_not() {
1695        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "TypeScript".to_string()], true);
1696
1697        let content = r#"Check the [javascript guide][js-ref] for details.
1698
1699Real javascript should be flagged.
1700
1701[js-ref]: https://javascript.info/typescript/guide"#;
1702
1703        let ctx = create_context(content);
1704        let result = rule.check(&ctx).unwrap();
1705
1706        // Link text should be checked, reference definitions should not
1707        // Line 1: [javascript guide] - should be flagged
1708        // Line 3: standalone javascript - should be flagged
1709        // Line 5: reference definition - should NOT be flagged
1710        assert_eq!(result.len(), 2, "Expected 2 warnings: 1 in link text + 1 standalone");
1711        assert!(result.iter().any(|w| w.line == 1 && w.message.contains("'javascript'")));
1712        assert!(result.iter().any(|w| w.line == 3 && w.message.contains("'javascript'")));
1713    }
1714
1715    #[test]
1716    fn test_reference_definitions_not_flagged() {
1717        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1718
1719        // Reference definition should NOT be flagged
1720        let content = r#"[js-ref]: https://javascript.info/guide"#;
1721
1722        let ctx = create_context(content);
1723        let result = rule.check(&ctx).unwrap();
1724
1725        // Reference definition URLs should not be checked
1726        assert!(result.is_empty(), "Reference definitions should not be checked");
1727    }
1728
1729    #[test]
1730    fn test_wikilinks_text_is_flagged() {
1731        let rule = MD044ProperNames::new(vec!["JavaScript".to_string()], true);
1732
1733        // WikiLinks [[destination]] should have their text checked
1734        let content = r#"[[javascript]]
1735
1736Regular javascript here.
1737
1738[[JavaScript|display text]]"#;
1739
1740        let ctx = create_context(content);
1741        let result = rule.check(&ctx).unwrap();
1742
1743        // Line 1: [[javascript]] - should be flagged (WikiLink text)
1744        // Line 3: standalone javascript - should be flagged
1745        // Line 5: [[JavaScript|display text]] - correct capitalization, no flag
1746        assert_eq!(result.len(), 2, "Expected 2 warnings: 1 in WikiLink + 1 standalone");
1747        assert!(
1748            result
1749                .iter()
1750                .any(|w| w.line == 1 && w.column == 3 && w.message.contains("'javascript'"))
1751        );
1752        assert!(result.iter().any(|w| w.line == 3 && w.message.contains("'javascript'")));
1753    }
1754
1755    #[test]
1756    fn test_url_link_text_not_flagged() {
1757        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1758
1759        // Link text that is itself a URL should not be flagged
1760        let content = r#"[https://github.com/org/repo](https://github.com/org/repo)
1761
1762[http://github.com/org/repo](http://github.com/org/repo)
1763
1764[www.github.com/org/repo](https://www.github.com/org/repo)"#;
1765
1766        let ctx = create_context(content);
1767        let result = rule.check(&ctx).unwrap();
1768
1769        assert!(
1770            result.is_empty(),
1771            "URL-like link text should not be flagged, got: {result:?}"
1772        );
1773    }
1774
1775    #[test]
1776    fn test_url_link_text_with_leading_space_not_flagged() {
1777        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1778
1779        // Leading/trailing whitespace in link text should be trimmed before URL check
1780        let content = r#"[ https://github.com/org/repo](https://github.com/org/repo)"#;
1781
1782        let ctx = create_context(content);
1783        let result = rule.check(&ctx).unwrap();
1784
1785        assert!(
1786            result.is_empty(),
1787            "URL-like link text with leading space should not be flagged, got: {result:?}"
1788        );
1789    }
1790
1791    #[test]
1792    fn test_url_link_text_uppercase_scheme_not_flagged() {
1793        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1794
1795        let content = r#"[HTTPS://GITHUB.COM/org/repo](https://github.com/org/repo)"#;
1796
1797        let ctx = create_context(content);
1798        let result = rule.check(&ctx).unwrap();
1799
1800        assert!(
1801            result.is_empty(),
1802            "URL-like link text with uppercase scheme should not be flagged, got: {result:?}"
1803        );
1804    }
1805
1806    #[test]
1807    fn test_non_url_link_text_still_flagged() {
1808        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1809
1810        // Only prose descriptions in link text should be flagged.
1811        // Bare-domain, protocol-relative, and scheme-prefixed link texts that
1812        // match the destination URL are all URLs and must not be corrected.
1813        let content = r#"[github.com/org/repo](https://github.com/org/repo)
1814
1815[Visit github](https://github.com/org/repo)
1816
1817[//github.com/org/repo](//github.com/org/repo)
1818
1819[ftp://github.com/org/repo](ftp://github.com/org/repo)"#;
1820
1821        let ctx = create_context(content);
1822        let result = rule.check(&ctx).unwrap();
1823
1824        // Line 1: bare-domain text matches destination — not flagged
1825        // Line 3: prose description — flagged
1826        // Line 5: protocol-relative URL text — not flagged
1827        // Line 7: ftp:// URL text matches destination — not flagged
1828        assert_eq!(
1829            result.len(),
1830            1,
1831            "Only prose link text should be flagged, got: {result:?}"
1832        );
1833        assert!(
1834            result.iter().any(|w| w.line == 3),
1835            "Expected 'Visit github' on line 3 to be flagged"
1836        );
1837    }
1838
1839    #[test]
1840    fn test_url_link_text_fix_not_applied() {
1841        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1842
1843        let content = "[https://github.com/org/repo](https://github.com/org/repo)\n";
1844
1845        let ctx = create_context(content);
1846        let result = rule.fix(&ctx).unwrap();
1847
1848        assert_eq!(result, content, "Fix should not modify URL-like link text");
1849    }
1850
1851    #[test]
1852    fn test_mixed_url_and_regular_link_text() {
1853        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
1854
1855        // Mix of URL link text (should skip) and regular text (should flag)
1856        let content = r#"[https://github.com/org/repo](https://github.com/org/repo)
1857
1858Visit [github documentation](https://github.com/docs) for details.
1859
1860[www.github.com/pricing](https://www.github.com/pricing)"#;
1861
1862        let ctx = create_context(content);
1863        let result = rule.check(&ctx).unwrap();
1864
1865        // Only line 3 should be flagged ("github documentation" is not a URL)
1866        assert_eq!(
1867            result.len(),
1868            1,
1869            "Only non-URL link text should be flagged, got: {result:?}"
1870        );
1871        assert_eq!(result[0].line, 3);
1872    }
1873
1874    #[test]
1875    fn test_html_attribute_values_not_flagged() {
1876        // Matches inside HTML tag attributes (between `<` and `>`) are not flagged.
1877        // Attribute values are not prose — they hold URLs, class names, data values, etc.
1878        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1879        let content = "# Heading\n\ntest\n\n<img src=\"www.example.test/test_image.png\">\n";
1880        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1881        let result = rule.check(&ctx).unwrap();
1882
1883        // Nothing on line 5 should be flagged — everything is inside the `<img ...>` tag
1884        let line5_violations: Vec<_> = result.iter().filter(|w| w.line == 5).collect();
1885        assert!(
1886            line5_violations.is_empty(),
1887            "Should not flag anything inside HTML tag attributes: {line5_violations:?}"
1888        );
1889
1890        // Plain text on line 3 is still flagged
1891        let line3_violations: Vec<_> = result.iter().filter(|w| w.line == 3).collect();
1892        assert_eq!(line3_violations.len(), 1, "Plain 'test' on line 3 should be flagged");
1893    }
1894
1895    #[test]
1896    fn test_html_text_content_still_flagged() {
1897        // Text between HTML tags (not inside `<...>`) is still checked.
1898        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1899        let content = "# Heading\n\n<a href=\"https://example.test/page\">test link</a>\n";
1900        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1901        let result = rule.check(&ctx).unwrap();
1902
1903        // "example.test" in the href attribute → not flagged (inside `<...>`)
1904        // "test link" in the anchor text → flagged (between `>` and `<`)
1905        assert_eq!(
1906            result.len(),
1907            1,
1908            "Should flag only 'test' in anchor text, not in href: {result:?}"
1909        );
1910        assert_eq!(result[0].column, 37, "Should flag col 37 ('test link' in anchor text)");
1911    }
1912
1913    #[test]
1914    fn test_html_attribute_various_not_flagged() {
1915        // All attribute types are ignored: src, href, alt, class, data-*, title, etc.
1916        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1917        let content = concat!(
1918            "# Heading\n\n",
1919            "<img src=\"test.png\" alt=\"test image\">\n",
1920            "<span class=\"test-class\" data-test=\"value\">test content</span>\n",
1921        );
1922        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1923        let result = rule.check(&ctx).unwrap();
1924
1925        // Only "test content" (between tags on line 4) should be flagged
1926        assert_eq!(
1927            result.len(),
1928            1,
1929            "Should flag only 'test content' between tags: {result:?}"
1930        );
1931        assert_eq!(result[0].line, 4);
1932    }
1933
1934    #[test]
1935    fn test_plain_text_underscore_boundary_unchanged() {
1936        // Plain text (outside HTML tags) still uses original word boundary semantics where
1937        // underscore is a boundary character, matching markdownlint's behavior via AST splitting.
1938        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1939        let content = "# Heading\n\ntest_image is here and just_test ends here\n";
1940        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1941        let result = rule.check(&ctx).unwrap();
1942
1943        // Both "test_image" (test at start) and "just_test" (test at end) are flagged
1944        // because in plain text, "_" is a word boundary
1945        assert_eq!(
1946            result.len(),
1947            2,
1948            "Should flag 'test' in both 'test_image' and 'just_test': {result:?}"
1949        );
1950        let cols: Vec<usize> = result.iter().map(|w| w.column).collect();
1951        assert!(cols.contains(&1), "Should flag col 1 (test_image): {cols:?}");
1952        assert!(cols.contains(&29), "Should flag col 29 (just_test): {cols:?}");
1953    }
1954
1955    #[test]
1956    fn test_frontmatter_yaml_keys_not_flagged() {
1957        // YAML keys in frontmatter should NOT be checked for proper name violations.
1958        // Only values should be checked.
1959        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1960
1961        let content = "---\ntitle: Heading\ntest: Some Test value\n---\n\nTest\n";
1962        let ctx = create_context(content);
1963        let result = rule.check(&ctx).unwrap();
1964
1965        // "test" in the YAML key (line 3) should NOT be flagged
1966        // "Test" in the YAML value (line 3) is correct capitalization, no flag
1967        // "Test" in body (line 6) is correct capitalization, no flag
1968        assert!(
1969            result.is_empty(),
1970            "Should not flag YAML keys or correctly capitalized values: {result:?}"
1971        );
1972    }
1973
1974    #[test]
1975    fn test_frontmatter_yaml_values_flagged() {
1976        // Incorrectly capitalized names in YAML values should be flagged.
1977        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1978
1979        let content = "---\ntitle: Heading\nkey: a test value\n---\n\nTest\n";
1980        let ctx = create_context(content);
1981        let result = rule.check(&ctx).unwrap();
1982
1983        // "test" in the YAML value (line 3) SHOULD be flagged
1984        assert_eq!(result.len(), 1, "Should flag 'test' in YAML value: {result:?}");
1985        assert_eq!(result[0].line, 3);
1986        assert_eq!(result[0].column, 8); // "key: a " = 7 chars, then "test" at column 8
1987    }
1988
1989    #[test]
1990    fn test_frontmatter_key_matches_name_not_flagged() {
1991        // A YAML key that happens to match a configured name should NOT be flagged.
1992        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
1993
1994        let content = "---\ntest: other value\n---\n\nBody text\n";
1995        let ctx = create_context(content);
1996        let result = rule.check(&ctx).unwrap();
1997
1998        assert!(
1999            result.is_empty(),
2000            "Should not flag YAML key that matches configured name: {result:?}"
2001        );
2002    }
2003
2004    #[test]
2005    fn test_frontmatter_empty_value_not_flagged() {
2006        // YAML key with no value should be skipped entirely.
2007        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2008
2009        let content = "---\ntest:\ntest: \n---\n\nBody text\n";
2010        let ctx = create_context(content);
2011        let result = rule.check(&ctx).unwrap();
2012
2013        assert!(
2014            result.is_empty(),
2015            "Should not flag YAML keys with empty values: {result:?}"
2016        );
2017    }
2018
2019    #[test]
2020    fn test_frontmatter_nested_yaml_key_not_flagged() {
2021        // Nested/indented YAML keys should also be skipped.
2022        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2023
2024        let content = "---\nparent:\n  test: nested value\n---\n\nBody text\n";
2025        let ctx = create_context(content);
2026        let result = rule.check(&ctx).unwrap();
2027
2028        // "test" as a nested key should NOT be flagged
2029        assert!(result.is_empty(), "Should not flag nested YAML keys: {result:?}");
2030    }
2031
2032    #[test]
2033    fn test_frontmatter_list_items_checked() {
2034        // YAML list items are values and should be checked for proper names.
2035        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2036
2037        let content = "---\ntags:\n  - test\n  - other\n---\n\nBody text\n";
2038        let ctx = create_context(content);
2039        let result = rule.check(&ctx).unwrap();
2040
2041        // "test" as a list item value SHOULD be flagged
2042        assert_eq!(result.len(), 1, "Should flag 'test' in YAML list item: {result:?}");
2043        assert_eq!(result[0].line, 3);
2044    }
2045
2046    #[test]
2047    fn test_frontmatter_value_with_multiple_colons() {
2048        // For "key: value: more", key is before first colon.
2049        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2050
2051        let content = "---\ntest: description: a test thing\n---\n\nBody text\n";
2052        let ctx = create_context(content);
2053        let result = rule.check(&ctx).unwrap();
2054
2055        // "test" as key should NOT be flagged
2056        // "test" in value portion ("description: a test thing") SHOULD be flagged
2057        assert_eq!(
2058            result.len(),
2059            1,
2060            "Should flag 'test' in value after first colon: {result:?}"
2061        );
2062        assert_eq!(result[0].line, 2);
2063        assert!(result[0].column > 6, "Violation column should be in value portion");
2064    }
2065
2066    #[test]
2067    fn test_frontmatter_does_not_affect_body() {
2068        // Body text after frontmatter should still be fully checked.
2069        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2070
2071        let content = "---\ntitle: Heading\n---\n\ntest should be flagged here\n";
2072        let ctx = create_context(content);
2073        let result = rule.check(&ctx).unwrap();
2074
2075        assert_eq!(result.len(), 1, "Should flag 'test' in body text: {result:?}");
2076        assert_eq!(result[0].line, 5);
2077    }
2078
2079    #[test]
2080    fn test_frontmatter_fix_corrects_values_preserves_keys() {
2081        // Fix should correct YAML values but preserve keys.
2082        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2083
2084        let content = "---\ntest: a test value\n---\n\ntest here\n";
2085        let ctx = create_context(content);
2086        let fixed = rule.fix(&ctx).unwrap();
2087
2088        // Key "test" should remain lowercase; value "test" should become "Test"
2089        assert_eq!(fixed, "---\ntest: a Test value\n---\n\nTest here\n");
2090    }
2091
2092    #[test]
2093    fn test_frontmatter_multiword_value_flagged() {
2094        // Multiple proper names in a single YAML value should all be flagged.
2095        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "TypeScript".to_string()], true);
2096
2097        let content = "---\ndescription: Learn javascript and typescript\n---\n\nBody\n";
2098        let ctx = create_context(content);
2099        let result = rule.check(&ctx).unwrap();
2100
2101        assert_eq!(result.len(), 2, "Should flag both names in YAML value: {result:?}");
2102        assert!(result.iter().all(|w| w.line == 2));
2103    }
2104
2105    #[test]
2106    fn test_frontmatter_yaml_comments_not_checked() {
2107        // YAML comments inside frontmatter should be skipped entirely.
2108        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2109
2110        let content = "---\n# test comment\ntitle: Heading\n---\n\nBody text\n";
2111        let ctx = create_context(content);
2112        let result = rule.check(&ctx).unwrap();
2113
2114        assert!(result.is_empty(), "Should not flag names in YAML comments: {result:?}");
2115    }
2116
2117    #[test]
2118    fn test_frontmatter_delimiters_not_checked() {
2119        // Frontmatter delimiter lines (--- or +++) should never be checked.
2120        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2121
2122        let content = "---\ntitle: Heading\n---\n\ntest here\n";
2123        let ctx = create_context(content);
2124        let result = rule.check(&ctx).unwrap();
2125
2126        // Only the body "test" on line 5 should be flagged
2127        assert_eq!(result.len(), 1, "Should only flag body text: {result:?}");
2128        assert_eq!(result[0].line, 5);
2129    }
2130
2131    #[test]
2132    fn test_frontmatter_continuation_lines_checked() {
2133        // Continuation lines (indented, no colon) are value content and should be checked.
2134        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2135
2136        let content = "---\ndescription: >\n  a test value\n  continued here\n---\n\nBody\n";
2137        let ctx = create_context(content);
2138        let result = rule.check(&ctx).unwrap();
2139
2140        // "test" on the continuation line should be flagged
2141        assert_eq!(result.len(), 1, "Should flag 'test' in continuation line: {result:?}");
2142        assert_eq!(result[0].line, 3);
2143    }
2144
2145    #[test]
2146    fn test_frontmatter_quoted_values_checked() {
2147        // Quoted YAML values should have their content checked (inside the quotes).
2148        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2149
2150        let content = "---\ntitle: \"a test title\"\n---\n\nBody\n";
2151        let ctx = create_context(content);
2152        let result = rule.check(&ctx).unwrap();
2153
2154        assert_eq!(result.len(), 1, "Should flag 'test' in quoted YAML value: {result:?}");
2155        assert_eq!(result[0].line, 2);
2156    }
2157
2158    #[test]
2159    fn test_frontmatter_single_quoted_values_checked() {
2160        // Single-quoted YAML values should have their content checked.
2161        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2162
2163        let content = "---\ntitle: 'a test title'\n---\n\nBody\n";
2164        let ctx = create_context(content);
2165        let result = rule.check(&ctx).unwrap();
2166
2167        assert_eq!(
2168            result.len(),
2169            1,
2170            "Should flag 'test' in single-quoted YAML value: {result:?}"
2171        );
2172        assert_eq!(result[0].line, 2);
2173    }
2174
2175    #[test]
2176    fn test_frontmatter_fix_multiword_values() {
2177        // Fix should correct all proper names in frontmatter values.
2178        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "TypeScript".to_string()], true);
2179
2180        let content = "---\ndescription: Learn javascript and typescript\n---\n\nBody\n";
2181        let ctx = create_context(content);
2182        let fixed = rule.fix(&ctx).unwrap();
2183
2184        assert_eq!(
2185            fixed,
2186            "---\ndescription: Learn JavaScript and TypeScript\n---\n\nBody\n"
2187        );
2188    }
2189
2190    #[test]
2191    fn test_frontmatter_fix_preserves_yaml_structure() {
2192        // Fix should preserve YAML structure while correcting values.
2193        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2194
2195        let content = "---\ntags:\n  - test\n  - other\ntitle: a test doc\n---\n\ntest body\n";
2196        let ctx = create_context(content);
2197        let fixed = rule.fix(&ctx).unwrap();
2198
2199        assert_eq!(
2200            fixed,
2201            "---\ntags:\n  - Test\n  - other\ntitle: a Test doc\n---\n\nTest body\n"
2202        );
2203    }
2204
2205    #[test]
2206    fn test_frontmatter_toml_delimiters_not_checked() {
2207        // TOML frontmatter with +++ delimiters should also be handled.
2208        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2209
2210        let content = "+++\ntitle = \"a test title\"\n+++\n\ntest body\n";
2211        let ctx = create_context(content);
2212        let result = rule.check(&ctx).unwrap();
2213
2214        // "title" as TOML key should NOT be flagged
2215        // "test" in TOML quoted value SHOULD be flagged (line 2)
2216        // "test" in body SHOULD be flagged (line 5)
2217        assert_eq!(result.len(), 2, "Should flag TOML value and body: {result:?}");
2218        let fm_violations: Vec<_> = result.iter().filter(|w| w.line == 2).collect();
2219        assert_eq!(fm_violations.len(), 1, "Should flag 'test' in TOML value: {result:?}");
2220        let body_violations: Vec<_> = result.iter().filter(|w| w.line == 5).collect();
2221        assert_eq!(body_violations.len(), 1, "Should flag body 'test': {result:?}");
2222    }
2223
2224    #[test]
2225    fn test_frontmatter_toml_key_not_flagged() {
2226        // TOML keys should NOT be flagged, only values.
2227        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2228
2229        let content = "+++\ntest = \"other value\"\n+++\n\nBody text\n";
2230        let ctx = create_context(content);
2231        let result = rule.check(&ctx).unwrap();
2232
2233        assert!(
2234            result.is_empty(),
2235            "Should not flag TOML key that matches configured name: {result:?}"
2236        );
2237    }
2238
2239    #[test]
2240    fn test_frontmatter_toml_fix_preserves_keys() {
2241        // Fix should correct TOML values but preserve keys.
2242        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2243
2244        let content = "+++\ntest = \"a test value\"\n+++\n\ntest here\n";
2245        let ctx = create_context(content);
2246        let fixed = rule.fix(&ctx).unwrap();
2247
2248        // Key "test" should remain lowercase; value "test" should become "Test"
2249        assert_eq!(fixed, "+++\ntest = \"a Test value\"\n+++\n\nTest here\n");
2250    }
2251
2252    #[test]
2253    fn test_frontmatter_list_item_mapping_key_not_flagged() {
2254        // In "- test: nested value", "test" is a YAML key within a list-item mapping.
2255        // The key should NOT be flagged; only the value should be checked.
2256        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2257
2258        let content = "---\nitems:\n  - test: nested value\n---\n\nBody text\n";
2259        let ctx = create_context(content);
2260        let result = rule.check(&ctx).unwrap();
2261
2262        assert!(
2263            result.is_empty(),
2264            "Should not flag YAML key in list-item mapping: {result:?}"
2265        );
2266    }
2267
2268    #[test]
2269    fn test_frontmatter_list_item_mapping_value_flagged() {
2270        // In "- key: test value", the value portion should be checked.
2271        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2272
2273        let content = "---\nitems:\n  - key: a test value\n---\n\nBody text\n";
2274        let ctx = create_context(content);
2275        let result = rule.check(&ctx).unwrap();
2276
2277        assert_eq!(
2278            result.len(),
2279            1,
2280            "Should flag 'test' in list-item mapping value: {result:?}"
2281        );
2282        assert_eq!(result[0].line, 3);
2283    }
2284
2285    #[test]
2286    fn test_frontmatter_bare_list_item_still_flagged() {
2287        // Bare list items without a colon (e.g., "- test") are values and should be flagged.
2288        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2289
2290        let content = "---\ntags:\n  - test\n  - other\n---\n\nBody text\n";
2291        let ctx = create_context(content);
2292        let result = rule.check(&ctx).unwrap();
2293
2294        assert_eq!(result.len(), 1, "Should flag 'test' in bare list item: {result:?}");
2295        assert_eq!(result[0].line, 3);
2296    }
2297
2298    #[test]
2299    fn test_frontmatter_flow_mapping_not_flagged() {
2300        // Flow mappings like {test: value} contain YAML keys that should not be flagged.
2301        // The entire flow construct should be skipped.
2302        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2303
2304        let content = "---\nflow_map: {test: value, other: test}\n---\n\nBody text\n";
2305        let ctx = create_context(content);
2306        let result = rule.check(&ctx).unwrap();
2307
2308        assert!(
2309            result.is_empty(),
2310            "Should not flag names inside flow mappings: {result:?}"
2311        );
2312    }
2313
2314    #[test]
2315    fn test_frontmatter_flow_sequence_not_flagged() {
2316        // Flow sequences like [test, other] should also be skipped.
2317        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2318
2319        let content = "---\nitems: [test, other, test]\n---\n\nBody text\n";
2320        let ctx = create_context(content);
2321        let result = rule.check(&ctx).unwrap();
2322
2323        assert!(
2324            result.is_empty(),
2325            "Should not flag names inside flow sequences: {result:?}"
2326        );
2327    }
2328
2329    #[test]
2330    fn test_frontmatter_list_item_mapping_fix_preserves_key() {
2331        // Fix should correct values in list-item mappings but preserve keys.
2332        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2333
2334        let content = "---\nitems:\n  - test: a test value\n---\n\ntest here\n";
2335        let ctx = create_context(content);
2336        let fixed = rule.fix(&ctx).unwrap();
2337
2338        // "test" as list-item key should remain lowercase;
2339        // "test" in value portion should become "Test"
2340        assert_eq!(fixed, "---\nitems:\n  - test: a Test value\n---\n\nTest here\n");
2341    }
2342
2343    #[test]
2344    fn test_frontmatter_backtick_code_not_flagged() {
2345        // Names inside backticks in frontmatter should NOT be flagged when code_blocks=false.
2346        let config = MD044Config {
2347            names: vec!["GoodApplication".to_string()],
2348            code_blocks: false,
2349            ..MD044Config::default()
2350        };
2351        let rule = MD044ProperNames::from_config_struct(config);
2352
2353        let content = "---\ntitle: \"`goodapplication` CLI\"\n---\n\nIntroductory `goodapplication` CLI text.\n";
2354        let ctx = create_context(content);
2355        let result = rule.check(&ctx).unwrap();
2356
2357        // Neither the frontmatter nor the body backtick-wrapped name should be flagged
2358        assert!(
2359            result.is_empty(),
2360            "Should not flag names inside backticks in frontmatter or body: {result:?}"
2361        );
2362    }
2363
2364    #[test]
2365    fn test_frontmatter_unquoted_backtick_code_not_flagged() {
2366        // Exact case from issue #513: unquoted YAML frontmatter with backticks
2367        let config = MD044Config {
2368            names: vec!["GoodApplication".to_string()],
2369            code_blocks: false,
2370            ..MD044Config::default()
2371        };
2372        let rule = MD044ProperNames::from_config_struct(config);
2373
2374        let content = "---\ntitle: `goodapplication` CLI\n---\n\nIntroductory `goodapplication` CLI text.\n";
2375        let ctx = create_context(content);
2376        let result = rule.check(&ctx).unwrap();
2377
2378        assert!(
2379            result.is_empty(),
2380            "Should not flag names inside backticks in unquoted YAML frontmatter: {result:?}"
2381        );
2382    }
2383
2384    #[test]
2385    fn test_frontmatter_bare_name_still_flagged_with_backtick_nearby() {
2386        // Names outside backticks in frontmatter should still be flagged.
2387        let config = MD044Config {
2388            names: vec!["GoodApplication".to_string()],
2389            code_blocks: false,
2390            ..MD044Config::default()
2391        };
2392        let rule = MD044ProperNames::from_config_struct(config);
2393
2394        let content = "---\ntitle: goodapplication `goodapplication` CLI\n---\n\nBody\n";
2395        let ctx = create_context(content);
2396        let result = rule.check(&ctx).unwrap();
2397
2398        // Only the bare "goodapplication" (before backticks) should be flagged
2399        assert_eq!(
2400            result.len(),
2401            1,
2402            "Should flag bare name but not backtick-wrapped name: {result:?}"
2403        );
2404        assert_eq!(result[0].line, 2);
2405        assert_eq!(result[0].column, 8); // "title: " = 7 chars, name at column 8
2406    }
2407
2408    #[test]
2409    fn test_frontmatter_backtick_code_with_code_blocks_true() {
2410        // When code_blocks=true, names inside backticks ARE checked.
2411        let config = MD044Config {
2412            names: vec!["GoodApplication".to_string()],
2413            code_blocks: true,
2414            ..MD044Config::default()
2415        };
2416        let rule = MD044ProperNames::from_config_struct(config);
2417
2418        let content = "---\ntitle: \"`goodapplication` CLI\"\n---\n\nBody\n";
2419        let ctx = create_context(content);
2420        let result = rule.check(&ctx).unwrap();
2421
2422        // With code_blocks=true, backtick-wrapped name SHOULD be flagged
2423        assert_eq!(
2424            result.len(),
2425            1,
2426            "Should flag backtick-wrapped name when code_blocks=true: {result:?}"
2427        );
2428        assert_eq!(result[0].line, 2);
2429    }
2430
2431    #[test]
2432    fn test_frontmatter_fix_preserves_backtick_code() {
2433        // Fix should NOT change names inside backticks in frontmatter.
2434        let config = MD044Config {
2435            names: vec!["GoodApplication".to_string()],
2436            code_blocks: false,
2437            ..MD044Config::default()
2438        };
2439        let rule = MD044ProperNames::from_config_struct(config);
2440
2441        let content = "---\ntitle: \"`goodapplication` CLI\"\n---\n\nIntroductory `goodapplication` CLI text.\n";
2442        let ctx = create_context(content);
2443        let fixed = rule.fix(&ctx).unwrap();
2444
2445        // Neither backtick-wrapped occurrence should be changed
2446        assert_eq!(
2447            fixed, content,
2448            "Fix should not modify names inside backticks in frontmatter"
2449        );
2450    }
2451
2452    // --- Angle-bracket URL tests (issue #457) ---
2453
2454    #[test]
2455    fn test_angle_bracket_url_in_html_comment_not_flagged() {
2456        // Angle-bracket URLs inside HTML comments should be skipped
2457        let config = MD044Config {
2458            names: vec!["Test".to_string()],
2459            ..MD044Config::default()
2460        };
2461        let rule = MD044ProperNames::from_config_struct(config);
2462
2463        let content = "---\ntitle: Level 1 heading\n---\n\n<https://www.example.test>\n\n<!-- This is a Test https://www.example.test -->\n<!-- This is a Test <https://www.example.test> -->\n";
2464        let ctx = create_context(content);
2465        let result = rule.check(&ctx).unwrap();
2466
2467        // Line 7: "Test" in comment prose before bare URL -- already correct capitalization
2468        // Line 7: "test" in bare URL (not in angle brackets) -- but "test" is in URL domain, not prose.
2469        //   However, .example.test has "test" at a word boundary (after '.'), so it IS flagged.
2470        // Line 8: "Test" in comment prose -- correct capitalization, not flagged
2471        // Line 8: "test" in <https://www.example.test> -- inside angle-bracket URL, NOT flagged
2472
2473        // The key assertion: line 8's angle-bracket URL should NOT produce a warning
2474        let line8_warnings: Vec<_> = result.iter().filter(|w| w.line == 8).collect();
2475        assert!(
2476            line8_warnings.is_empty(),
2477            "Should not flag names inside angle-bracket URLs in HTML comments: {line8_warnings:?}"
2478        );
2479    }
2480
2481    #[test]
2482    fn test_bare_url_in_html_comment_still_flagged() {
2483        // Bare URLs (not in angle brackets) inside HTML comments should still be checked
2484        let config = MD044Config {
2485            names: vec!["Test".to_string()],
2486            ..MD044Config::default()
2487        };
2488        let rule = MD044ProperNames::from_config_struct(config);
2489
2490        let content = "<!-- This is a test https://www.example.test -->\n";
2491        let ctx = create_context(content);
2492        let result = rule.check(&ctx).unwrap();
2493
2494        // "test" appears as prose text before URL and also in the bare URL domain
2495        // At minimum, the prose "test" should be flagged
2496        assert!(
2497            !result.is_empty(),
2498            "Should flag 'test' in prose text of HTML comment with bare URL"
2499        );
2500    }
2501
2502    #[test]
2503    fn test_angle_bracket_url_in_regular_markdown_not_flagged() {
2504        // Angle-bracket URLs in regular markdown are already handled by the link parser,
2505        // but the angle-bracket check provides a safety net
2506        let rule = MD044ProperNames::new(vec!["Test".to_string()], true);
2507
2508        let content = "<https://www.example.test>\n";
2509        let ctx = create_context(content);
2510        let result = rule.check(&ctx).unwrap();
2511
2512        assert!(
2513            result.is_empty(),
2514            "Should not flag names inside angle-bracket URLs in regular markdown: {result:?}"
2515        );
2516    }
2517
2518    #[test]
2519    fn test_multiple_angle_bracket_urls_in_one_comment() {
2520        let config = MD044Config {
2521            names: vec!["Test".to_string()],
2522            ..MD044Config::default()
2523        };
2524        let rule = MD044ProperNames::from_config_struct(config);
2525
2526        let content = "<!-- See <https://test.example.com> and <https://www.example.test> for details -->\n";
2527        let ctx = create_context(content);
2528        let result = rule.check(&ctx).unwrap();
2529
2530        // Both URLs are inside angle brackets, so "test" inside them should NOT be flagged
2531        assert!(
2532            result.is_empty(),
2533            "Should not flag names inside multiple angle-bracket URLs: {result:?}"
2534        );
2535    }
2536
2537    #[test]
2538    fn test_angle_bracket_non_url_still_flagged() {
2539        // <Test> is NOT a URL (no scheme), so is_in_angle_bracket_url does NOT protect it.
2540        // Whether it gets flagged depends on HTML tag detection, not on our URL check.
2541        assert!(
2542            !MD044ProperNames::is_in_angle_bracket_url("<test> which is not a URL.", 1),
2543            "is_in_angle_bracket_url should return false for non-URL angle brackets"
2544        );
2545    }
2546
2547    #[test]
2548    fn test_angle_bracket_mailto_url_not_flagged() {
2549        let config = MD044Config {
2550            names: vec!["Test".to_string()],
2551            ..MD044Config::default()
2552        };
2553        let rule = MD044ProperNames::from_config_struct(config);
2554
2555        let content = "<!-- Contact <mailto:test@example.com> for help -->\n";
2556        let ctx = create_context(content);
2557        let result = rule.check(&ctx).unwrap();
2558
2559        assert!(
2560            result.is_empty(),
2561            "Should not flag names inside angle-bracket mailto URLs: {result:?}"
2562        );
2563    }
2564
2565    #[test]
2566    fn test_angle_bracket_ftp_url_not_flagged() {
2567        let config = MD044Config {
2568            names: vec!["Test".to_string()],
2569            ..MD044Config::default()
2570        };
2571        let rule = MD044ProperNames::from_config_struct(config);
2572
2573        let content = "<!-- Download from <ftp://test.example.com/file> -->\n";
2574        let ctx = create_context(content);
2575        let result = rule.check(&ctx).unwrap();
2576
2577        assert!(
2578            result.is_empty(),
2579            "Should not flag names inside angle-bracket FTP URLs: {result:?}"
2580        );
2581    }
2582
2583    #[test]
2584    fn test_angle_bracket_url_fix_preserves_url() {
2585        // Fix should not modify text inside angle-bracket URLs
2586        let config = MD044Config {
2587            names: vec!["Test".to_string()],
2588            ..MD044Config::default()
2589        };
2590        let rule = MD044ProperNames::from_config_struct(config);
2591
2592        let content = "<!-- test text <https://www.example.test> -->\n";
2593        let ctx = create_context(content);
2594        let fixed = rule.fix(&ctx).unwrap();
2595
2596        // "test" in prose should be fixed, URL should be preserved
2597        assert!(
2598            fixed.contains("<https://www.example.test>"),
2599            "Fix should preserve angle-bracket URLs: {fixed}"
2600        );
2601        assert!(
2602            fixed.contains("Test text"),
2603            "Fix should correct prose 'test' to 'Test': {fixed}"
2604        );
2605    }
2606
2607    #[test]
2608    fn test_is_in_angle_bracket_url_helper() {
2609        // Direct tests of the helper function
2610        let line = "text <https://example.test> more text";
2611
2612        // Inside the URL
2613        assert!(MD044ProperNames::is_in_angle_bracket_url(line, 5)); // '<'
2614        assert!(MD044ProperNames::is_in_angle_bracket_url(line, 6)); // 'h'
2615        assert!(MD044ProperNames::is_in_angle_bracket_url(line, 15)); // middle of URL
2616        assert!(MD044ProperNames::is_in_angle_bracket_url(line, 26)); // '>'
2617
2618        // Outside the URL
2619        assert!(!MD044ProperNames::is_in_angle_bracket_url(line, 0)); // 't' at start
2620        assert!(!MD044ProperNames::is_in_angle_bracket_url(line, 4)); // space before '<'
2621        assert!(!MD044ProperNames::is_in_angle_bracket_url(line, 27)); // space after '>'
2622
2623        // Non-URL angle brackets
2624        assert!(!MD044ProperNames::is_in_angle_bracket_url("<notaurl>", 1));
2625
2626        // mailto scheme
2627        assert!(MD044ProperNames::is_in_angle_bracket_url(
2628            "<mailto:test@example.com>",
2629            10
2630        ));
2631
2632        // ftp scheme
2633        assert!(MD044ProperNames::is_in_angle_bracket_url(
2634            "<ftp://test.example.com>",
2635            10
2636        ));
2637    }
2638
2639    #[test]
2640    fn test_is_in_angle_bracket_url_uppercase_scheme() {
2641        // RFC 3986: URI schemes are case-insensitive
2642        assert!(MD044ProperNames::is_in_angle_bracket_url(
2643            "<HTTPS://test.example.com>",
2644            10
2645        ));
2646        assert!(MD044ProperNames::is_in_angle_bracket_url(
2647            "<Http://test.example.com>",
2648            10
2649        ));
2650    }
2651
2652    #[test]
2653    fn test_is_in_angle_bracket_url_uncommon_schemes() {
2654        // ssh scheme
2655        assert!(MD044ProperNames::is_in_angle_bracket_url(
2656            "<ssh://test@example.com>",
2657            10
2658        ));
2659        // file scheme
2660        assert!(MD044ProperNames::is_in_angle_bracket_url("<file:///test/path>", 10));
2661        // data scheme (no authority, just colon)
2662        assert!(MD044ProperNames::is_in_angle_bracket_url("<data:text/plain;test>", 10));
2663    }
2664
2665    #[test]
2666    fn test_is_in_angle_bracket_url_unclosed() {
2667        // Unclosed angle bracket should NOT match
2668        assert!(!MD044ProperNames::is_in_angle_bracket_url(
2669            "<https://test.example.com",
2670            10
2671        ));
2672    }
2673
2674    #[test]
2675    fn test_vale_inline_config_comments_not_flagged() {
2676        let config = MD044Config {
2677            names: vec!["Vale".to_string(), "JavaScript".to_string()],
2678            ..MD044Config::default()
2679        };
2680        let rule = MD044ProperNames::from_config_struct(config);
2681
2682        let content = "\
2683<!-- vale off -->
2684Some javascript text here.
2685<!-- vale on -->
2686<!-- vale Style.Rule = NO -->
2687More javascript text.
2688<!-- vale Style.Rule = YES -->
2689<!-- vale JavaScript.Grammar = NO -->
2690";
2691        let ctx = create_context(content);
2692        let result = rule.check(&ctx).unwrap();
2693
2694        // Only the body text lines (2, 5) should be flagged for "javascript"
2695        assert_eq!(result.len(), 2, "Should only flag body lines, not Vale config comments");
2696        assert_eq!(result[0].line, 2);
2697        assert_eq!(result[1].line, 5);
2698    }
2699
2700    #[test]
2701    fn test_remark_lint_inline_config_comments_not_flagged() {
2702        let config = MD044Config {
2703            names: vec!["JavaScript".to_string()],
2704            ..MD044Config::default()
2705        };
2706        let rule = MD044ProperNames::from_config_struct(config);
2707
2708        let content = "\
2709<!-- lint disable remark-lint-some-rule -->
2710Some javascript text here.
2711<!-- lint enable remark-lint-some-rule -->
2712<!-- lint ignore remark-lint-some-rule -->
2713More javascript text.
2714";
2715        let ctx = create_context(content);
2716        let result = rule.check(&ctx).unwrap();
2717
2718        assert_eq!(
2719            result.len(),
2720            2,
2721            "Should only flag body lines, not remark-lint config comments"
2722        );
2723        assert_eq!(result[0].line, 2);
2724        assert_eq!(result[1].line, 5);
2725    }
2726
2727    #[test]
2728    fn test_fix_does_not_modify_vale_remark_lint_comments() {
2729        let config = MD044Config {
2730            names: vec!["JavaScript".to_string(), "Vale".to_string()],
2731            ..MD044Config::default()
2732        };
2733        let rule = MD044ProperNames::from_config_struct(config);
2734
2735        let content = "\
2736<!-- vale off -->
2737Some javascript text.
2738<!-- vale on -->
2739<!-- lint disable remark-lint-some-rule -->
2740More javascript text.
2741<!-- lint enable remark-lint-some-rule -->
2742";
2743        let ctx = create_context(content);
2744        let fixed = rule.fix(&ctx).unwrap();
2745
2746        // Config directive lines must be preserved unchanged
2747        assert!(fixed.contains("<!-- vale off -->"));
2748        assert!(fixed.contains("<!-- vale on -->"));
2749        assert!(fixed.contains("<!-- lint disable remark-lint-some-rule -->"));
2750        assert!(fixed.contains("<!-- lint enable remark-lint-some-rule -->"));
2751        // Body text should be fixed
2752        assert!(fixed.contains("Some JavaScript text."));
2753        assert!(fixed.contains("More JavaScript text."));
2754    }
2755
2756    #[test]
2757    fn test_mixed_tool_directives_all_skipped() {
2758        let config = MD044Config {
2759            names: vec!["JavaScript".to_string(), "Vale".to_string()],
2760            ..MD044Config::default()
2761        };
2762        let rule = MD044ProperNames::from_config_struct(config);
2763
2764        let content = "\
2765<!-- rumdl-disable MD044 -->
2766Some javascript text.
2767<!-- markdownlint-disable -->
2768More javascript text.
2769<!-- vale off -->
2770Even more javascript text.
2771<!-- lint disable some-rule -->
2772Final javascript text.
2773<!-- rumdl-enable MD044 -->
2774<!-- markdownlint-enable -->
2775<!-- vale on -->
2776<!-- lint enable some-rule -->
2777";
2778        let ctx = create_context(content);
2779        let result = rule.check(&ctx).unwrap();
2780
2781        // Only body text lines should be flagged (lines 2, 4, 6, 8)
2782        assert_eq!(
2783            result.len(),
2784            4,
2785            "Should only flag body lines, not any tool directive comments"
2786        );
2787        assert_eq!(result[0].line, 2);
2788        assert_eq!(result[1].line, 4);
2789        assert_eq!(result[2].line, 6);
2790        assert_eq!(result[3].line, 8);
2791    }
2792
2793    #[test]
2794    fn test_vale_remark_lint_edge_cases_not_matched() {
2795        let config = MD044Config {
2796            names: vec!["JavaScript".to_string(), "Vale".to_string()],
2797            ..MD044Config::default()
2798        };
2799        let rule = MD044ProperNames::from_config_struct(config);
2800
2801        // These are regular HTML comments, NOT tool directives:
2802        // - "<!-- vale -->" is not a valid Vale directive (no action keyword)
2803        // - "<!-- vale is a tool -->" starts with "vale" but is prose, not a directive
2804        // - "<!-- valedictorian javascript -->" does not start with "<!-- vale "
2805        // - "<!-- linting javascript tips -->" does not start with "<!-- lint "
2806        // - "<!-- vale javascript -->" starts with "vale" but has no action keyword
2807        // - "<!-- lint your javascript code -->" starts with "lint" but has no action keyword
2808        let content = "\
2809<!-- vale -->
2810<!-- vale is a tool for writing -->
2811<!-- valedictorian javascript -->
2812<!-- linting javascript tips -->
2813<!-- vale javascript -->
2814<!-- lint your javascript code -->
2815";
2816        let ctx = create_context(content);
2817        let result = rule.check(&ctx).unwrap();
2818
2819        // Line 1: "<!-- vale -->" contains "vale" (wrong case for "Vale") -> flagged
2820        // Line 2: "<!-- vale is a tool for writing -->" contains "vale" -> flagged
2821        // Line 3: "<!-- valedictorian javascript -->" contains "javascript" -> flagged
2822        // Line 4: "<!-- linting javascript tips -->" contains "javascript" -> flagged
2823        // Line 5: "<!-- vale javascript -->" contains "vale" and "javascript" -> flagged for both
2824        // Line 6: "<!-- lint your javascript code -->" contains "javascript" -> flagged
2825        assert_eq!(
2826            result.len(),
2827            7,
2828            "Should flag proper names in non-directive HTML comments: got {result:?}"
2829        );
2830        assert_eq!(result[0].line, 1); // "vale" in <!-- vale -->
2831        assert_eq!(result[1].line, 2); // "vale" in <!-- vale is a tool -->
2832        assert_eq!(result[2].line, 3); // "javascript" in <!-- valedictorian javascript -->
2833        assert_eq!(result[3].line, 4); // "javascript" in <!-- linting javascript tips -->
2834        assert_eq!(result[4].line, 5); // "vale" in <!-- vale javascript -->
2835        assert_eq!(result[5].line, 5); // "javascript" in <!-- vale javascript -->
2836        assert_eq!(result[6].line, 6); // "javascript" in <!-- lint your javascript code -->
2837    }
2838
2839    #[test]
2840    fn test_vale_style_directives_skipped() {
2841        let config = MD044Config {
2842            names: vec!["JavaScript".to_string(), "Vale".to_string()],
2843            ..MD044Config::default()
2844        };
2845        let rule = MD044ProperNames::from_config_struct(config);
2846
2847        // These ARE valid Vale directives and should be skipped:
2848        let content = "\
2849<!-- vale style = MyStyle -->
2850<!-- vale styles = Style1, Style2 -->
2851<!-- vale MyRule.Name = YES -->
2852<!-- vale MyRule.Name = NO -->
2853Some javascript text.
2854";
2855        let ctx = create_context(content);
2856        let result = rule.check(&ctx).unwrap();
2857
2858        // Only line 5 (body text) should be flagged
2859        assert_eq!(
2860            result.len(),
2861            1,
2862            "Should only flag body lines, not Vale style/rule directives: got {result:?}"
2863        );
2864        assert_eq!(result[0].line, 5);
2865    }
2866
2867    // --- is_in_backtick_code_in_line unit tests ---
2868
2869    #[test]
2870    fn test_backtick_code_single_backticks() {
2871        let line = "hello `world` bye";
2872        // 'w' is at index 7, inside the backtick span (content between backticks at 6 and 12)
2873        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 7));
2874        // 'h' at index 0 is outside
2875        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 0));
2876        // 'b' at index 14 is outside
2877        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 14));
2878    }
2879
2880    #[test]
2881    fn test_backtick_code_double_backticks() {
2882        let line = "a ``code`` b";
2883        // 'c' is at index 4, inside ``...``
2884        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 4));
2885        // 'a' at index 0 is outside
2886        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 0));
2887        // 'b' at index 11 is outside
2888        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 11));
2889    }
2890
2891    #[test]
2892    fn test_backtick_code_unclosed() {
2893        let line = "a `code b";
2894        // No closing backtick, so nothing is a code span
2895        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 3));
2896    }
2897
2898    #[test]
2899    fn test_backtick_code_mismatched_count() {
2900        // Single backtick opening, double backtick is not a match
2901        let line = "a `code`` b";
2902        // The single ` at index 2 doesn't match `` at index 7-8
2903        // So 'c' at index 3 is NOT in a code span
2904        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 3));
2905    }
2906
2907    #[test]
2908    fn test_backtick_code_multiple_spans() {
2909        let line = "`first` and `second`";
2910        // 'f' at index 1 (inside first span)
2911        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 1));
2912        // 'a' at index 8 (between spans)
2913        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 8));
2914        // 's' at index 13 (inside second span)
2915        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 13));
2916    }
2917
2918    #[test]
2919    fn test_backtick_code_on_backtick_boundary() {
2920        let line = "`code`";
2921        // Position 0 is the opening backtick itself, not inside the span
2922        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 0));
2923        // Position 5 is the closing backtick, not inside the span
2924        assert!(!MD044ProperNames::is_in_backtick_code_in_line(line, 5));
2925        // Position 1-4 are inside the span
2926        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 1));
2927        assert!(MD044ProperNames::is_in_backtick_code_in_line(line, 4));
2928    }
2929
2930    // Double-bracket WikiLink + URL: [[text]](url)
2931    // pulldown-cmark parses [[text]] as a WikiLink but leaves the (url)
2932    // as plain text, so ctx.links does not cover the URL portion.
2933    // MD044 must fall back to is_in_markdown_link_url for all lines.
2934
2935    #[test]
2936    fn test_double_bracket_link_url_not_flagged() {
2937        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
2938        // Exact reproduction from issue #564
2939        let content = "[[rumdl]](https://github.com/rvben/rumdl)";
2940        let ctx = create_context(content);
2941        let result = rule.check(&ctx).unwrap();
2942        assert!(
2943            result.is_empty(),
2944            "URL inside [[text]](url) must not be flagged, got: {result:?}"
2945        );
2946    }
2947
2948    #[test]
2949    fn test_double_bracket_link_url_not_fixed() {
2950        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
2951        let content = "[[rumdl]](https://github.com/rvben/rumdl)\n";
2952        let ctx = create_context(content);
2953        let fixed = rule.fix(&ctx).unwrap();
2954        assert_eq!(
2955            fixed, content,
2956            "fix() must leave the URL inside [[text]](url) unchanged"
2957        );
2958    }
2959
2960    #[test]
2961    fn test_double_bracket_link_text_still_flagged() {
2962        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
2963        // The link text portion [[github]](url) should still be checked.
2964        let content = "[[github]](https://example.com)";
2965        let ctx = create_context(content);
2966        let result = rule.check(&ctx).unwrap();
2967        assert_eq!(
2968            result.len(),
2969            1,
2970            "Incorrect name in [[text]] link text should still be flagged, got: {result:?}"
2971        );
2972        assert_eq!(result[0].message, "Proper name 'github' should be 'GitHub'");
2973    }
2974
2975    #[test]
2976    fn test_double_bracket_link_mixed_line() {
2977        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
2978        // URL must be skipped, standalone text must be flagged.
2979        let content = "See [[rumdl]](https://github.com/rvben/rumdl) and github for more.";
2980        let ctx = create_context(content);
2981        let result = rule.check(&ctx).unwrap();
2982        assert_eq!(
2983            result.len(),
2984            1,
2985            "Only the standalone 'github' after the link should be flagged, got: {result:?}"
2986        );
2987        assert!(result[0].message.contains("'github'"));
2988        // "See " (4) + "[[rumdl]](https://github.com/rvben/rumdl)" (42) + " and " (4) = column 51
2989        assert_eq!(
2990            result[0].column, 51,
2991            "Flagged column should be the trailing 'github', not the one in the URL"
2992        );
2993    }
2994
2995    #[test]
2996    fn test_regular_link_url_still_not_flagged() {
2997        // Confirm existing [text](url) behavior is unaffected by the fix.
2998        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
2999        let content = "[rumdl](https://github.com/rvben/rumdl)";
3000        let ctx = create_context(content);
3001        let result = rule.check(&ctx).unwrap();
3002        assert!(
3003            result.is_empty(),
3004            "URL inside regular [text](url) must still not be flagged, got: {result:?}"
3005        );
3006    }
3007
3008    #[test]
3009    fn test_link_like_text_in_code_span_still_flagged_when_code_blocks_enabled() {
3010        // When code-blocks = true the user explicitly opts into checking code spans.
3011        // A code span containing link-like text (`[foo](https://github.com)`) must
3012        // NOT be silently suppressed by is_in_markdown_link_url: the content is
3013        // literal characters, not a real Markdown link.
3014        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], true);
3015        let content = "`[foo](https://github.com/org/repo)`";
3016        let ctx = create_context(content);
3017        let result = rule.check(&ctx).unwrap();
3018        assert_eq!(
3019            result.len(),
3020            1,
3021            "Proper name inside a code span must be flagged when code-blocks=true, got: {result:?}"
3022        );
3023        assert!(result[0].message.contains("'github'"));
3024    }
3025
3026    #[test]
3027    fn test_malformed_link_not_treated_as_url() {
3028        // [text](url with spaces) is NOT a valid Markdown link; pulldown-cmark
3029        // does not parse it, so the name inside must still be flagged.
3030        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3031        let content = "See [rumdl](github repo) for details.";
3032        let ctx = create_context(content);
3033        let result = rule.check(&ctx).unwrap();
3034        assert_eq!(
3035            result.len(),
3036            1,
3037            "Name inside malformed [text](url with spaces) must still be flagged, got: {result:?}"
3038        );
3039        assert!(result[0].message.contains("'github'"));
3040    }
3041
3042    #[test]
3043    fn test_wikilink_followed_by_prose_parens_still_flagged() {
3044        // [[note]](github repo) — WikiLink followed by parenthesised prose, NOT
3045        // a valid link URL (space in destination). pulldown-cmark does not parse
3046        // it as a link, so the name inside must still be flagged.
3047        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3048        let content = "[[note]](github repo)";
3049        let ctx = create_context(content);
3050        let result = rule.check(&ctx).unwrap();
3051        assert_eq!(
3052            result.len(),
3053            1,
3054            "Name inside [[wikilink]](prose with spaces) must still be flagged, got: {result:?}"
3055        );
3056        assert!(result[0].message.contains("'github'"));
3057    }
3058
3059    /// Roundtrip safety: fix() output must produce zero warnings on re-check.
3060    #[test]
3061    fn test_roundtrip_fix_then_check_basic() {
3062        let rule = MD044ProperNames::new(
3063            vec![
3064                "JavaScript".to_string(),
3065                "TypeScript".to_string(),
3066                "Node.js".to_string(),
3067            ],
3068            true,
3069        );
3070        let content = "I love javascript, typescript, and nodejs!";
3071        let ctx = create_context(content);
3072        let fixed = rule.fix(&ctx).unwrap();
3073        let ctx2 = create_context(&fixed);
3074        let warnings = rule.check(&ctx2).unwrap();
3075        assert!(
3076            warnings.is_empty(),
3077            "Re-check after fix should produce zero warnings, got: {warnings:?}"
3078        );
3079    }
3080
3081    /// Roundtrip safety: fix() output must produce zero warnings for multiline content.
3082    #[test]
3083    fn test_roundtrip_fix_then_check_multiline() {
3084        let rule = MD044ProperNames::new(vec!["Rust".to_string(), "Python".to_string()], true);
3085        let content = "First line with rust.\nSecond line with python.\nThird line with RUST and PYTHON.\n";
3086        let ctx = create_context(content);
3087        let fixed = rule.fix(&ctx).unwrap();
3088        let ctx2 = create_context(&fixed);
3089        let warnings = rule.check(&ctx2).unwrap();
3090        assert!(
3091            warnings.is_empty(),
3092            "Re-check after fix should produce zero warnings, got: {warnings:?}"
3093        );
3094    }
3095
3096    /// Roundtrip safety: fix() with inline config disable blocks.
3097    #[test]
3098    fn test_roundtrip_fix_then_check_inline_config() {
3099        let config = MD044Config {
3100            names: vec!["RUMDL".to_string()],
3101            ..MD044Config::default()
3102        };
3103        let rule = MD044ProperNames::from_config_struct(config);
3104        let content =
3105            "<!-- rumdl-disable MD044 -->\nSome rumdl text.\n<!-- rumdl-enable MD044 -->\n\nSome rumdl text outside.\n";
3106        let ctx = create_context(content);
3107        let fixed = rule.fix(&ctx).unwrap();
3108        // The disabled block should be preserved, the outside text fixed
3109        assert!(
3110            fixed.contains("Some rumdl text.\n"),
3111            "Disabled block text should be preserved"
3112        );
3113        assert!(
3114            fixed.contains("Some RUMDL text outside."),
3115            "Outside text should be fixed"
3116        );
3117    }
3118
3119    /// Roundtrip safety: fix() with HTML comment content.
3120    #[test]
3121    fn test_roundtrip_fix_then_check_html_comments() {
3122        let config = MD044Config {
3123            names: vec!["JavaScript".to_string()],
3124            ..MD044Config::default()
3125        };
3126        let rule = MD044ProperNames::from_config_struct(config);
3127        let content = "# Guide\n\n<!-- javascript mentioned here -->\n\njavascript outside\n";
3128        let ctx = create_context(content);
3129        let fixed = rule.fix(&ctx).unwrap();
3130        let ctx2 = create_context(&fixed);
3131        let warnings = rule.check(&ctx2).unwrap();
3132        assert!(
3133            warnings.is_empty(),
3134            "Re-check after fix should produce zero warnings, got: {warnings:?}"
3135        );
3136    }
3137
3138    /// Roundtrip safety: fix() preserves content when no violations exist.
3139    #[test]
3140    fn test_roundtrip_no_op_when_correct() {
3141        let rule = MD044ProperNames::new(vec!["JavaScript".to_string(), "TypeScript".to_string()], true);
3142        let content = "This uses JavaScript and TypeScript correctly.\n";
3143        let ctx = create_context(content);
3144        let fixed = rule.fix(&ctx).unwrap();
3145        assert_eq!(fixed, content, "Fix should be a no-op when content is already correct");
3146    }
3147
3148    // --- Bare-domain link text: display text is the destination URL with scheme stripped ---
3149
3150    #[test]
3151    fn test_bare_domain_link_text_not_flagged() {
3152        // `[ravencentric.github.io](https://ravencentric.github.io)` — the display text
3153        // is the URL with the scheme stripped; "github" here is a domain label, not a
3154        // reference to "GitHub" the product, and must not be corrected.
3155        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3156        let content = "My site is [ravencentric.github.io](https://ravencentric.github.io).\n";
3157        let ctx = create_context(content);
3158        let result = rule.check(&ctx).unwrap();
3159        assert!(
3160            result.is_empty(),
3161            "Should not flag 'github' in a bare-domain link text that matches the link URL: {result:?}"
3162        );
3163    }
3164
3165    #[test]
3166    fn test_bare_domain_link_text_not_fixed() {
3167        // fix() must not rewrite the link text when it is the bare URL hostname.
3168        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3169        let content = "My site is [ravencentric.github.io](https://ravencentric.github.io).\n";
3170        let ctx = create_context(content);
3171        let fixed = rule.fix(&ctx).unwrap();
3172        assert_eq!(
3173            fixed, content,
3174            "fix() must not alter bare-domain link text that matches the destination URL"
3175        );
3176    }
3177
3178    #[test]
3179    fn test_bare_domain_link_text_with_path_not_flagged() {
3180        // Display text is the hostname only; destination has a path.
3181        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3182        let content = "Visit [ravencentric.github.io](https://ravencentric.github.io/projects).\n";
3183        let ctx = create_context(content);
3184        let result = rule.check(&ctx).unwrap();
3185        assert!(
3186            result.is_empty(),
3187            "Should not flag 'github' when bare-domain text is the hostname of its destination URL: {result:?}"
3188        );
3189    }
3190
3191    #[test]
3192    fn test_bare_domain_link_text_full_path_not_flagged() {
3193        // Display text is the full URL-without-scheme including a path.
3194        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3195        let content = "See [ravencentric.github.io/blog](https://ravencentric.github.io/blog).\n";
3196        let ctx = create_context(content);
3197        let result = rule.check(&ctx).unwrap();
3198        assert!(
3199            result.is_empty(),
3200            "Should not flag 'github' when link text is the full URL path without scheme: {result:?}"
3201        );
3202    }
3203
3204    #[test]
3205    fn test_github_product_name_in_link_text_still_flagged() {
3206        // `[github pages](https://pages.github.com)` — the display text is a human
3207        // description, not a bare domain; "github" should still be corrected to "GitHub".
3208        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3209        let content = "Hosted on [github pages](https://pages.github.com).\n";
3210        let ctx = create_context(content);
3211        let result = rule.check(&ctx).unwrap();
3212        assert!(
3213            !result.is_empty(),
3214            "Should still flag 'github' in descriptive link text that does not match the destination URL"
3215        );
3216    }
3217
3218    #[test]
3219    fn test_protocol_relative_bare_domain_link_text_not_flagged() {
3220        // Protocol-relative URL `[github.io](//github.io)`.
3221        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3222        let content = "See [github.io](//github.io).\n";
3223        let ctx = create_context(content);
3224        let result = rule.check(&ctx).unwrap();
3225        assert!(
3226            result.is_empty(),
3227            "Should not flag 'github' in bare-domain text matching a protocol-relative destination: {result:?}"
3228        );
3229    }
3230
3231    #[test]
3232    fn test_dotted_wikilink_target_still_flagged() {
3233        // `[[node.js]]` is a WikiLink whose page name contains a dot.
3234        // The dot guard alone does not protect it because text == url == "node.js".
3235        // The is_in_link WikiLink guard must prevent bare-domain suppression,
3236        // so the improper capitalization is still caught.
3237        let rule = MD044ProperNames::new(vec!["Node.js".to_string()], false);
3238        let content = "See [[node.js]] for details.\n";
3239        let ctx = create_context(content);
3240        let result = rule.check(&ctx).unwrap();
3241        assert!(
3242            !result.is_empty(),
3243            "Should flag 'node.js' in a dotted WikiLink target: {result:?}"
3244        );
3245    }
3246
3247    #[test]
3248    fn test_bare_domain_link_text_case_insensitive_url() {
3249        // URL with uppercase scheme `[github.io](HTTPS://github.io)` — the scheme is
3250        // case-insensitive, so the display text should still be recognised as a bare domain.
3251        let rule = MD044ProperNames::new(vec!["GitHub".to_string()], false);
3252        let content = "See [github.io](HTTPS://github.io).\n";
3253        let ctx = create_context(content);
3254        let result = rule.check(&ctx).unwrap();
3255        assert!(
3256            result.is_empty(),
3257            "Should not flag bare-domain text when destination URL has an uppercase scheme: {result:?}"
3258        );
3259    }
3260}