Skip to main content

rumdl_lib/rules/
md041_first_line_heading.rs

1mod md041_config;
2
3pub(super) use md041_config::MD041Config;
4
5use crate::filtered_lines::FilteredLinesExt;
6use crate::lint_context::HeadingStyle;
7use crate::rule::{Fix, FixCapability, LintError, LintResult, LintWarning, Rule, Severity};
8use crate::rules::front_matter_utils::FrontMatterUtils;
9use crate::utils::mkdocs_attr_list::is_mkdocs_anchor_line;
10use crate::utils::range_utils::calculate_line_range;
11use crate::utils::regex_cache::HTML_HEADING_PATTERN;
12use regex::Regex;
13
14/// Rule MD041: First line in file should be a top-level heading
15///
16/// See [docs/md041.md](../../docs/md041.md) for full documentation, configuration, and examples.
17
18#[derive(Clone)]
19pub struct MD041FirstLineHeading {
20    pub level: usize,
21    pub front_matter_title: bool,
22    pub front_matter_title_pattern: Option<Regex>,
23    pub allow_preamble: bool,
24    pub fix_enabled: bool,
25}
26
27impl Default for MD041FirstLineHeading {
28    fn default() -> Self {
29        Self {
30            level: 1,
31            front_matter_title: true,
32            front_matter_title_pattern: None,
33            allow_preamble: false,
34            fix_enabled: false,
35        }
36    }
37}
38
39/// How to make this document compliant with MD041 (internal helper)
40enum FixPlan {
41    /// Move an existing heading to the top (after front matter), optionally releveling it.
42    MoveOrRelevel {
43        front_matter_end_idx: usize,
44        heading_idx: usize,
45        is_setext: bool,
46        current_level: usize,
47        needs_level_fix: bool,
48    },
49    /// Promote the first plain-text title line to a level-N heading, moving it to the top.
50    PromotePlainText {
51        front_matter_end_idx: usize,
52        title_line_idx: usize,
53        title_text: String,
54    },
55    /// Insert a heading derived from the source filename at the top of the document.
56    /// Used when the document contains only directive blocks and no heading or title line.
57    InsertDerived {
58        front_matter_end_idx: usize,
59        derived_title: String,
60    },
61    /// Rewrite an existing heading to the required level, leaving it where it is.
62    /// Used when preamble is allowed: moving the heading to the top would delete the
63    /// preamble that the configuration exists to permit.
64    RelevelInPlace {
65        heading_idx: usize,
66        is_setext: bool,
67        current_level: usize,
68    },
69}
70
71impl MD041FirstLineHeading {
72    pub fn new(level: usize, front_matter_title: bool) -> Self {
73        Self {
74            level,
75            front_matter_title,
76            front_matter_title_pattern: None,
77            allow_preamble: false,
78            fix_enabled: false,
79        }
80    }
81
82    pub fn with_pattern(level: usize, front_matter_title: bool, pattern: Option<String>, fix_enabled: bool) -> Self {
83        let front_matter_title_pattern = pattern.and_then(|p| match Regex::new(&p) {
84            Ok(regex) => Some(regex),
85            Err(e) => {
86                log::warn!("Invalid front_matter_title_pattern regex: {e}");
87                None
88            }
89        });
90
91        Self {
92            level,
93            front_matter_title,
94            front_matter_title_pattern,
95            allow_preamble: false,
96            fix_enabled,
97        }
98    }
99
100    /// Allow content before the document's first heading.
101    pub fn with_allow_preamble(mut self, allow_preamble: bool) -> Self {
102        self.allow_preamble = allow_preamble;
103        self
104    }
105
106    fn has_front_matter_title(&self, content: &str) -> bool {
107        if !self.front_matter_title {
108            return false;
109        }
110
111        // If we have a custom pattern, use it to search front matter content
112        if let Some(ref pattern) = self.front_matter_title_pattern {
113            let front_matter_lines = FrontMatterUtils::extract_front_matter(content);
114            for line in front_matter_lines {
115                if pattern.is_match(line) {
116                    return true;
117                }
118            }
119            return false;
120        }
121
122        // Default behavior: check for "title:" field
123        FrontMatterUtils::has_front_matter_field(content, "title:")
124    }
125
126    /// Check if a line is a non-content token that should be skipped
127    fn is_non_content_line(line: &str) -> bool {
128        let trimmed = line.trim();
129
130        // Skip reference definitions
131        if trimmed.starts_with('[') && trimmed.contains("]: ") {
132            return true;
133        }
134
135        // Skip abbreviation definitions
136        if trimmed.starts_with('*') && trimmed.contains("]: ") {
137            return true;
138        }
139
140        // Skip badge/shield images - common pattern at top of READMEs
141        // Matches: ![badge](url) or [![badge](url)](url)
142        if Self::is_badge_image_line(trimmed) {
143            return true;
144        }
145
146        false
147    }
148
149    /// Find the first content line index (0-indexed) in the document.
150    ///
151    /// Skips front matter, blank lines, HTML/MDX comments, ESM blocks,
152    /// kramdown extensions, MkDocs anchors, reference definitions, and badges.
153    /// Used by both check() and fix() to ensure consistent behavior.
154    fn first_content_line_idx(ctx: &crate::lint_context::LintContext) -> Option<usize> {
155        let is_mkdocs = ctx.flavor == crate::config::MarkdownFlavor::MkDocs;
156
157        let filtered = ctx
158            .filtered_lines()
159            .skip_front_matter()
160            .skip_esm_blocks()
161            .skip_html_comments()
162            .skip_mdx_comments();
163
164        for filtered_line in filtered {
165            let idx = filtered_line.line_num - 1;
166            let line_info = &ctx.lines[idx];
167
168            if line_info.is_blank || line_info.is_kramdown_block_ial {
169                continue;
170            }
171
172            let line_content = filtered_line.content;
173            if is_mkdocs && is_mkdocs_anchor_line(line_content) {
174                continue;
175            }
176            if Self::is_non_content_line(line_content) {
177                continue;
178            }
179            return Some(idx);
180        }
181        None
182    }
183
184    /// Find the index (0-indexed) of the document's first top-level heading.
185    ///
186    /// Used when preamble is allowed, where the rule judges the level of the first
187    /// heading rather than requiring the document to open with one. Only top-level
188    /// headings count: one inside a list, blockquote, directive block or HTML element
189    /// is that container's content, so the scan passes over it and keeps looking.
190    /// Returns `None` for a document with no top-level heading, which the rule then
191    /// has nothing to judge.
192    fn first_top_level_heading_idx(ctx: &crate::lint_context::LintContext) -> Option<usize> {
193        for (idx, line_info) in ctx.lines.iter().enumerate() {
194            if line_info.is_blank
195                || line_info.in_front_matter
196                || line_info.in_code_block
197                || line_info.in_html_comment
198                || line_info.in_mdx_comment
199                || line_info.in_math_block
200            {
201                continue;
202            }
203
204            let in_container = line_info.in_list_block
205                || line_info.blockquote.is_some()
206                || line_info.in_admonition
207                || line_info.in_content_tab
208                || line_info.in_pandoc_div
209                || line_info.in_pymdown_block
210                || line_info.in_kramdown_extension_block;
211            if in_container {
212                continue;
213            }
214
215            if line_info.heading.is_some() {
216                return Some(idx);
217            }
218
219            // An HTML heading counts only where its block begins. An `<h1>` on a later
220            // line of the block is nested in whatever element opened it.
221            let continues_html_block = idx > 0 && line_info.in_html_block && ctx.lines[idx - 1].in_html_block;
222            if !continues_html_block && (1..=6).any(|level| Self::is_html_heading(ctx, idx, level)) {
223                return Some(idx);
224            }
225        }
226        None
227    }
228
229    /// The line this rule judges, which is also the line it reports on and the line
230    /// whose inline directives govern it.
231    ///
232    /// Allowing preamble moves the subject of the rule from the document's first
233    /// content line to its first heading, so a document with no heading has nothing
234    /// to judge.
235    fn checked_line_idx(&self, ctx: &crate::lint_context::LintContext) -> Option<usize> {
236        if self.allow_preamble {
237            Self::first_top_level_heading_idx(ctx)
238        } else {
239            Self::first_content_line_idx(ctx)
240        }
241    }
242
243    /// Check if a line consists only of badge/shield images
244    /// Common patterns:
245    /// - `![badge](url)`
246    /// - `[![badge](url)](url)` (linked badge)
247    /// - Multiple badges on one line
248    fn is_badge_image_line(line: &str) -> bool {
249        if line.is_empty() {
250            return false;
251        }
252
253        // Must start with image syntax
254        if !line.starts_with('!') && !line.starts_with('[') {
255            return false;
256        }
257
258        // Check if line contains only image/link patterns and whitespace
259        let mut remaining = line;
260        while !remaining.is_empty() {
261            remaining = remaining.trim_start();
262            if remaining.is_empty() {
263                break;
264            }
265
266            // Linked image: [![alt](img-url)](link-url)
267            if remaining.starts_with("[![") {
268                if let Some(end) = Self::find_linked_image_end(remaining) {
269                    remaining = &remaining[end..];
270                    continue;
271                }
272                return false;
273            }
274
275            // Simple image: ![alt](url)
276            if remaining.starts_with("![") {
277                if let Some(end) = Self::find_image_end(remaining) {
278                    remaining = &remaining[end..];
279                    continue;
280                }
281                return false;
282            }
283
284            // Not an image pattern
285            return false;
286        }
287
288        true
289    }
290
291    /// Find the end of an image pattern ![alt](url)
292    fn find_image_end(s: &str) -> Option<usize> {
293        if !s.starts_with("![") {
294            return None;
295        }
296        // Find ]( after ![
297        let alt_end = s[2..].find("](")?;
298        let paren_start = 2 + alt_end + 2; // Position after ](
299        // Find closing )
300        let paren_end = s[paren_start..].find(')')?;
301        Some(paren_start + paren_end + 1)
302    }
303
304    /// Find the end of a linked image pattern [![alt](img-url)](link-url)
305    fn find_linked_image_end(s: &str) -> Option<usize> {
306        if !s.starts_with("[![") {
307            return None;
308        }
309        // Find the inner image first
310        let inner_end = Self::find_image_end(&s[1..])?;
311        let after_inner = 1 + inner_end;
312        // Should be followed by ](url)
313        if !s[after_inner..].starts_with("](") {
314            return None;
315        }
316        let link_start = after_inner + 2;
317        let link_end = s[link_start..].find(')')?;
318        Some(link_start + link_end + 1)
319    }
320
321    /// Fix a heading line to use the specified level
322    fn fix_heading_level(&self, line: &str, _current_level: usize, target_level: usize) -> String {
323        let trimmed = line.trim_start();
324
325        // ATX-style heading (# Heading)
326        if trimmed.starts_with('#') {
327            let hashes = "#".repeat(target_level);
328            // Find where the content starts (after # and optional space)
329            let content_start = trimmed.chars().position(|c| c != '#').unwrap_or(trimmed.len());
330            let after_hashes = &trimmed[content_start..];
331            let content = after_hashes.trim_start();
332
333            // Preserve leading whitespace from original line
334            let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();
335            format!("{leading_ws}{hashes} {content}")
336        } else {
337            // Setext-style heading - convert to ATX
338            // The underline would be on the next line, so we just convert the text line
339            let hashes = "#".repeat(target_level);
340            let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();
341            format!("{leading_ws}{hashes} {trimmed}")
342        }
343    }
344
345    /// Returns true if `text` looks like a document title rather than a body paragraph.
346    ///
347    /// Criteria:
348    /// - Non-empty and ≤80 characters
349    /// - Does not end with sentence-ending punctuation (. ? ! : ;)
350    /// - Not a Markdown structural element (heading, list, blockquote)
351    /// - Followed by a blank line or EOF (visually separated from body text)
352    fn is_title_candidate(text: &str, next_is_blank_or_eof: bool) -> bool {
353        if text.is_empty() {
354            return false;
355        }
356
357        if !next_is_blank_or_eof {
358            return false;
359        }
360
361        if text.len() > 80 {
362            return false;
363        }
364
365        let last_char = text.chars().next_back().unwrap_or(' ');
366        if matches!(last_char, '.' | '?' | '!' | ':' | ';') {
367            return false;
368        }
369
370        // Already a heading or structural Markdown element
371        if text.starts_with('#')
372            || text.starts_with("- ")
373            || text.starts_with("* ")
374            || text.starts_with("+ ")
375            || text.starts_with("> ")
376        {
377            return false;
378        }
379
380        true
381    }
382
383    /// Derive a title string from the source file's stem.
384    /// Converts kebab-case and underscores to Title Case words.
385    /// Returns None when no source file is available.
386    fn derive_title(ctx: &crate::lint_context::LintContext) -> Option<String> {
387        let path = ctx.source_file.as_ref()?;
388        let stem = path.file_stem().and_then(|s| s.to_str())?;
389
390        // For index/readme files, use the parent directory name instead.
391        // If no parent directory exists, return None — "Index" or "README" are not useful titles.
392        let effective_stem = if stem.eq_ignore_ascii_case("index") || stem.eq_ignore_ascii_case("readme") {
393            path.parent().and_then(|p| p.file_name()).and_then(|s| s.to_str())?
394        } else {
395            stem
396        };
397
398        let title: String = effective_stem
399            .split(['-', '_'])
400            .filter(|w| !w.is_empty())
401            .map(|word| {
402                let mut chars = word.chars();
403                match chars.next() {
404                    None => String::new(),
405                    Some(first) => {
406                        let upper: String = first.to_uppercase().collect();
407                        upper + chars.as_str()
408                    }
409                }
410            })
411            .collect::<Vec<_>>()
412            .join(" ");
413
414        if title.is_empty() { None } else { Some(title) }
415    }
416
417    /// Check if a line is an HTML heading using the centralized HTML parser
418    fn is_html_heading(ctx: &crate::lint_context::LintContext, first_line_idx: usize, level: usize) -> bool {
419        // Check for single-line HTML heading using regex (fast path)
420        let first_line_content = ctx.lines[first_line_idx].content(ctx.content);
421        if let Ok(Some(captures)) = HTML_HEADING_PATTERN.captures(first_line_content.trim())
422            && let Some(h_level) = captures.get(1)
423            && h_level.as_str().parse::<usize>().unwrap_or(0) == level
424        {
425            return true;
426        }
427
428        // Use centralized HTML parser for multi-line headings
429        let html_tags = ctx.html_tags();
430        let target_tag = format!("h{level}");
431
432        // Find opening tag on first line
433        let opening_index = html_tags.iter().position(|tag| {
434            tag.line == first_line_idx + 1 // HtmlTag uses 1-indexed lines
435                && tag.tag_name == target_tag
436                && !tag.is_closing
437        });
438
439        let Some(open_idx) = opening_index else {
440            return false;
441        };
442
443        // Walk HTML tags to find the corresponding closing tag, allowing arbitrary nesting depth.
444        // This avoids brittle line-count heuristics and handles long headings with nested content.
445        let mut depth = 1usize;
446        for tag in html_tags.iter().skip(open_idx + 1) {
447            // Ignore tags that appear before the first heading line (possible when multiple tags share a line)
448            if tag.line <= first_line_idx + 1 {
449                continue;
450            }
451
452            if tag.tag_name == target_tag {
453                if tag.is_closing {
454                    depth -= 1;
455                    if depth == 0 {
456                        return true;
457                    }
458                } else if !tag.is_self_closing {
459                    depth += 1;
460                }
461            }
462        }
463
464        false
465    }
466
467    /// Analyze the document to determine how (if at all) it can be auto-fixed.
468    fn analyze_for_fix(&self, ctx: &crate::lint_context::LintContext) -> Option<FixPlan> {
469        if ctx.lines.is_empty() {
470            return None;
471        }
472
473        // Preamble is allowed, so the only safe repair is releveling the heading where
474        // it stands. Every other plan promotes something to the top of the document,
475        // which would remove the preamble this configuration permits.
476        if self.allow_preamble {
477            let heading_idx = Self::first_top_level_heading_idx(ctx)?;
478            let heading = ctx.lines[heading_idx].heading.as_ref()?;
479            if heading.level as usize == self.level {
480                return None;
481            }
482            return Some(FixPlan::RelevelInPlace {
483                heading_idx,
484                is_setext: matches!(heading.style, HeadingStyle::Setext1 | HeadingStyle::Setext2),
485                current_level: heading.level as usize,
486            });
487        }
488
489        // Find front matter end (handles YAML, TOML, JSON, malformed)
490        let mut front_matter_end_idx = 0;
491        for line_info in &ctx.lines {
492            if line_info.in_front_matter {
493                front_matter_end_idx += 1;
494            } else {
495                break;
496            }
497        }
498
499        let is_mkdocs = ctx.flavor == crate::config::MarkdownFlavor::MkDocs;
500
501        // (idx, is_setext, current_level) of the first ATX/Setext heading found
502        let mut found_heading: Option<(usize, bool, usize)> = None;
503        // First non-preamble, non-directive line that looks like a title
504        let mut first_title_candidate: Option<(usize, String)> = None;
505        // True once we see a non-preamble, non-directive line that is NOT a title candidate
506        let mut found_non_title_content = false;
507        // True when any non-directive, non-preamble line is encountered
508        let mut saw_non_directive_content = false;
509
510        'scan: for (idx, line_info) in ctx.lines.iter().enumerate().skip(front_matter_end_idx) {
511            let line_content = line_info.content(ctx.content);
512            let trimmed = line_content.trim();
513
514            // Preamble: invisible/structural tokens that don't count as content
515            let is_preamble = trimmed.is_empty()
516                || line_info.in_html_comment
517                || line_info.in_mdx_comment
518                || line_info.in_html_block
519                || Self::is_non_content_line(line_content)
520                || (is_mkdocs && is_mkdocs_anchor_line(line_content))
521                || line_info.in_kramdown_extension_block
522                || line_info.is_kramdown_block_ial;
523
524            if is_preamble {
525                continue;
526            }
527
528            // Directive blocks (admonitions, content tabs, Quarto/Pandoc divs, PyMdown Blocks)
529            // are structural containers, not narrative content.
530            let is_directive_block = line_info.in_admonition
531                || line_info.in_content_tab
532                || line_info.in_pandoc_div
533                || line_info.is_div_marker
534                || line_info.in_pymdown_block;
535
536            if !is_directive_block {
537                saw_non_directive_content = true;
538            }
539
540            // ATX or Setext heading (HTML headings cannot be moved/converted)
541            if let Some(heading) = &line_info.heading {
542                let is_setext = matches!(heading.style, HeadingStyle::Setext1 | HeadingStyle::Setext2);
543                found_heading = Some((idx, is_setext, heading.level as usize));
544                break 'scan;
545            }
546
547            // Track non-heading, non-directive content for PromotePlainText detection
548            if !is_directive_block && !found_non_title_content && first_title_candidate.is_none() {
549                let next_is_blank_or_eof = ctx
550                    .lines
551                    .get(idx + 1)
552                    .is_none_or(|l| l.content(ctx.content).trim().is_empty());
553
554                if Self::is_title_candidate(trimmed, next_is_blank_or_eof) {
555                    first_title_candidate = Some((idx, trimmed.to_string()));
556                } else {
557                    found_non_title_content = true;
558                }
559            }
560        }
561
562        if let Some((h_idx, is_setext, current_level)) = found_heading {
563            // Heading exists. Can we move/relevel it?
564            // If real content or a title candidate appeared before it, the heading is not the
565            // first significant element - reordering would change document meaning.
566            if found_non_title_content || first_title_candidate.is_some() {
567                return None;
568            }
569
570            let needs_level_fix = current_level != self.level;
571            let needs_move = h_idx > front_matter_end_idx;
572
573            if needs_level_fix || needs_move {
574                return Some(FixPlan::MoveOrRelevel {
575                    front_matter_end_idx,
576                    heading_idx: h_idx,
577                    is_setext,
578                    current_level,
579                    needs_level_fix,
580                });
581            }
582            return None; // Already at the correct position and level
583        }
584
585        // No heading found. Try to create one.
586
587        if let Some((title_idx, title_text)) = first_title_candidate {
588            return Some(FixPlan::PromotePlainText {
589                front_matter_end_idx,
590                title_line_idx: title_idx,
591                title_text,
592            });
593        }
594
595        // Document has no heading and no title candidate. If it contains only directive
596        // blocks (plus preamble), we can insert a heading derived from the filename.
597        if !saw_non_directive_content && let Some(derived_title) = Self::derive_title(ctx) {
598            return Some(FixPlan::InsertDerived {
599                front_matter_end_idx,
600                derived_title,
601            });
602        }
603
604        None
605    }
606
607    /// Determine if this document can be auto-fixed.
608    fn can_fix(&self, ctx: &crate::lint_context::LintContext) -> bool {
609        self.fix_enabled && self.analyze_for_fix(ctx).is_some()
610    }
611}
612
613impl Rule for MD041FirstLineHeading {
614    fn name(&self) -> &'static str {
615        "MD041"
616    }
617
618    fn description(&self) -> &'static str {
619        "First line in file should be a top level heading"
620    }
621
622    /// Fixing is opt-in: adding a document title is a content decision, so the rule
623    /// reports no fix capability until `fix = true` turns it on. Once on it is only
624    /// ever conditional, because a document with no heading to promote or move has
625    /// nothing the fixer can safely do.
626    fn fix_capability(&self) -> FixCapability {
627        if self.fix_enabled {
628            FixCapability::ConditionallyFixable
629        } else {
630            FixCapability::Unfixable
631        }
632    }
633
634    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
635        let mut warnings = Vec::new();
636
637        // Check if we should skip this file
638        if self.should_skip(ctx) {
639            return Ok(warnings);
640        }
641
642        let Some(first_line_idx) = self.checked_line_idx(ctx) else {
643            return Ok(warnings);
644        };
645
646        // Check if the first non-blank line is a heading of the required level
647        let first_line_info = &ctx.lines[first_line_idx];
648        let is_correct_heading = if let Some(heading) = &first_line_info.heading {
649            heading.level as usize == self.level
650        } else {
651            // Check for HTML heading (both single-line and multi-line)
652            Self::is_html_heading(ctx, first_line_idx, self.level)
653        };
654
655        if !is_correct_heading {
656            // Calculate precise character range for the entire first line
657            let first_line = first_line_idx + 1; // Convert to 1-indexed
658            let first_line_content = first_line_info.content(ctx.content);
659            let (start_line, start_col, end_line, end_col) = calculate_line_range(first_line, first_line_content);
660
661            // Compute the actual replacement so that LSP quick-fix can apply it
662            // directly without calling fix(). For simple cases (releveling,
663            // promote-plain-text at the first content line), we use a targeted
664            // range. For complex cases (moving headings, inserting derived
665            // titles), we replace the entire document via fix().
666            let fix = if self.can_fix(ctx) {
667                self.analyze_for_fix(ctx).and_then(|plan| {
668                    let range_start = first_line_info.byte_offset;
669                    let range_end = range_start + first_line_info.byte_len;
670                    match &plan {
671                        FixPlan::MoveOrRelevel {
672                            heading_idx,
673                            current_level,
674                            needs_level_fix,
675                            is_setext,
676                            ..
677                        } if *heading_idx == first_line_idx => {
678                            // Heading is already at the correct position, just needs releveling
679                            let heading_line = ctx.lines[*heading_idx].content(ctx.content);
680                            let replacement = if *needs_level_fix || *is_setext {
681                                self.fix_heading_level(heading_line, *current_level, self.level)
682                            } else {
683                                heading_line.to_string()
684                            };
685                            Some(Fix::new(range_start..range_end, replacement))
686                        }
687                        FixPlan::RelevelInPlace {
688                            heading_idx,
689                            current_level,
690                            is_setext,
691                        } if *heading_idx == first_line_idx && !*is_setext => {
692                            let replacement = self.fix_heading_level(
693                                ctx.lines[*heading_idx].content(ctx.content),
694                                *current_level,
695                                self.level,
696                            );
697                            Some(Fix::new(range_start..range_end, replacement))
698                        }
699                        FixPlan::PromotePlainText { title_line_idx, .. } if *title_line_idx == first_line_idx => {
700                            let replacement = format!(
701                                "{} {}",
702                                "#".repeat(self.level),
703                                ctx.lines[*title_line_idx].content(ctx.content).trim()
704                            );
705                            Some(Fix::new(range_start..range_end, replacement))
706                        }
707                        _ => {
708                            // Complex multi-line operations (moving headings, inserting
709                            // derived titles, promoting non-first-line text): replace
710                            // the entire document via fix().
711                            self.fix(ctx)
712                                .ok()
713                                .map(|fixed_content| Fix::new(0..ctx.content.len(), fixed_content))
714                        }
715                    }
716                })
717            } else {
718                None
719            };
720
721            warnings.push(LintWarning {
722                rule_name: Some(self.name().to_string()),
723                line: start_line,
724                column: start_col,
725                end_line,
726                end_column: end_col,
727                message: if self.allow_preamble {
728                    format!("First heading in file should be a level {} heading", self.level)
729                } else {
730                    format!("First line in file should be a level {} heading", self.level)
731                },
732                severity: Severity::Warning,
733                fix,
734            });
735        }
736        Ok(warnings)
737    }
738
739    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
740        if !self.fix_enabled {
741            return Ok(ctx.content.to_string());
742        }
743
744        if self.should_skip(ctx) {
745            return Ok(ctx.content.to_string());
746        }
747
748        // Respect inline disable comments, resolving the line the same way check()
749        // does so a directive suppresses exactly the warning it appears to suppress.
750        let checked_line = self.checked_line_idx(ctx).map_or(1, |i| i + 1);
751        if ctx.inline_config().is_rule_disabled(self.name(), checked_line) {
752            return Ok(ctx.content.to_string());
753        }
754
755        let Some(plan) = self.analyze_for_fix(ctx) else {
756            return Ok(ctx.content.to_string());
757        };
758
759        let lines = ctx.raw_lines();
760
761        let mut result = String::new();
762        let preserve_trailing_newline = ctx.content.ends_with('\n');
763
764        match plan {
765            FixPlan::MoveOrRelevel {
766                front_matter_end_idx,
767                heading_idx,
768                is_setext,
769                current_level,
770                needs_level_fix,
771            } => {
772                let heading_line = ctx.lines[heading_idx].content(ctx.content);
773                let fixed_heading = if needs_level_fix || is_setext {
774                    self.fix_heading_level(heading_line, current_level, self.level)
775                } else {
776                    heading_line.to_string()
777                };
778
779                for line in lines.iter().take(front_matter_end_idx) {
780                    result.push_str(line);
781                    result.push('\n');
782                }
783                result.push_str(&fixed_heading);
784                result.push('\n');
785                for (idx, line) in lines.iter().enumerate().skip(front_matter_end_idx) {
786                    if idx == heading_idx {
787                        continue;
788                    }
789                    if is_setext && idx == heading_idx + 1 {
790                        continue;
791                    }
792                    result.push_str(line);
793                    result.push('\n');
794                }
795            }
796
797            FixPlan::PromotePlainText {
798                front_matter_end_idx,
799                title_line_idx,
800                title_text,
801            } => {
802                let hashes = "#".repeat(self.level);
803                let new_heading = format!("{hashes} {title_text}");
804
805                for line in lines.iter().take(front_matter_end_idx) {
806                    result.push_str(line);
807                    result.push('\n');
808                }
809                result.push_str(&new_heading);
810                result.push('\n');
811                for (idx, line) in lines.iter().enumerate().skip(front_matter_end_idx) {
812                    if idx == title_line_idx {
813                        continue;
814                    }
815                    result.push_str(line);
816                    result.push('\n');
817                }
818            }
819
820            FixPlan::RelevelInPlace {
821                heading_idx,
822                is_setext,
823                current_level,
824            } => {
825                for (idx, line) in lines.iter().enumerate() {
826                    if idx == heading_idx {
827                        result.push_str(&self.fix_heading_level(line, current_level, self.level));
828                        result.push('\n');
829                        continue;
830                    }
831                    // The underline is gone: releveling rewrites a setext heading as ATX.
832                    if is_setext && idx == heading_idx + 1 {
833                        continue;
834                    }
835                    result.push_str(line);
836                    result.push('\n');
837                }
838            }
839
840            FixPlan::InsertDerived {
841                front_matter_end_idx,
842                derived_title,
843            } => {
844                let hashes = "#".repeat(self.level);
845                let new_heading = format!("{hashes} {derived_title}");
846
847                for line in lines.iter().take(front_matter_end_idx) {
848                    result.push_str(line);
849                    result.push('\n');
850                }
851                result.push_str(&new_heading);
852                result.push('\n');
853                result.push('\n');
854                for line in lines.iter().skip(front_matter_end_idx) {
855                    result.push_str(line);
856                    result.push('\n');
857                }
858            }
859        }
860
861        if !preserve_trailing_newline && result.ends_with('\n') {
862            result.pop();
863        }
864
865        Ok(result)
866    }
867
868    /// Check if this rule should be skipped
869    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
870        // Skip files that are purely preprocessor directives (e.g., mdBook includes).
871        // These files are composition/routing metadata, not standalone content.
872        // Example: A file containing only "{{#include ../../README.md}}" is a
873        // pointer to content, not content itself, and shouldn't need a heading.
874        let only_directives = !ctx.content.is_empty()
875            && ctx.content.lines().filter(|l| !l.trim().is_empty()).all(|l| {
876                let t = l.trim();
877                // mdBook directives: {{#include}}, {{#playground}}, {{#rustdoc_include}}, etc.
878                (t.starts_with("{{#") && t.ends_with("}}"))
879                        // HTML comments often accompany directives
880                        || (t.starts_with("<!--") && t.ends_with("-->"))
881            });
882
883        ctx.content.is_empty()
884            || (self.front_matter_title && self.has_front_matter_title(ctx.content))
885            || only_directives
886    }
887
888    fn as_any(&self) -> &dyn std::any::Any {
889        self
890    }
891
892    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
893    where
894        Self: Sized,
895    {
896        // Load config using serde with kebab-case support
897        let md041_config = crate::rule_config_serde::load_rule_config::<MD041Config>(config);
898
899        let use_front_matter = !md041_config.front_matter_title.is_empty();
900
901        Box::new(
902            MD041FirstLineHeading::with_pattern(
903                md041_config.level.as_usize(),
904                use_front_matter,
905                md041_config.front_matter_title_pattern,
906                md041_config.fix,
907            )
908            .with_allow_preamble(md041_config.allow_preamble),
909        )
910    }
911
912    fn default_config_section(&self) -> Option<(String, toml::Value)> {
913        Some((
914            "MD041".to_string(),
915            toml::toml! {
916                level = 1
917                front-matter-title = "title"
918                front-matter-title-pattern = ""
919                allow-preamble = false
920                fix = false
921            }
922            .into(),
923        ))
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930    use crate::lint_context::LintContext;
931
932    #[test]
933    fn test_first_line_is_heading_correct_level() {
934        let rule = MD041FirstLineHeading::default();
935
936        // First line is a level 1 heading (should pass)
937        let content = "# My Document\n\nSome content here.";
938        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
939        let result = rule.check(&ctx).unwrap();
940        assert!(
941            result.is_empty(),
942            "Expected no warnings when first line is a level 1 heading"
943        );
944    }
945
946    #[test]
947    fn test_first_line_is_heading_wrong_level() {
948        let rule = MD041FirstLineHeading::default();
949
950        // First line is a level 2 heading (should fail with level 1 requirement)
951        let content = "## My Document\n\nSome content here.";
952        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
953        let result = rule.check(&ctx).unwrap();
954        assert_eq!(result.len(), 1);
955        assert_eq!(result[0].line, 1);
956        assert!(result[0].message.contains("level 1 heading"));
957    }
958
959    #[test]
960    fn test_first_line_not_heading() {
961        let rule = MD041FirstLineHeading::default();
962
963        // First line is plain text (should fail)
964        let content = "This is not a heading\n\n# This is a heading";
965        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
966        let result = rule.check(&ctx).unwrap();
967        assert_eq!(result.len(), 1);
968        assert_eq!(result[0].line, 1);
969        assert!(result[0].message.contains("level 1 heading"));
970    }
971
972    #[test]
973    fn test_empty_lines_before_heading() {
974        let rule = MD041FirstLineHeading::default();
975
976        // Empty lines before first heading (should pass - rule skips empty lines)
977        let content = "\n\n# My Document\n\nSome content.";
978        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
979        let result = rule.check(&ctx).unwrap();
980        assert!(
981            result.is_empty(),
982            "Expected no warnings when empty lines precede a valid heading"
983        );
984
985        // Empty lines before non-heading content (should fail)
986        let content = "\n\nNot a heading\n\nSome content.";
987        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
988        let result = rule.check(&ctx).unwrap();
989        assert_eq!(result.len(), 1);
990        assert_eq!(result[0].line, 3); // First non-empty line
991        assert!(result[0].message.contains("level 1 heading"));
992    }
993
994    #[test]
995    fn test_front_matter_with_title() {
996        let rule = MD041FirstLineHeading::new(1, true);
997
998        // Front matter with title field (should pass)
999        let content = "---\ntitle: My Document\nauthor: John Doe\n---\n\nSome content here.";
1000        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1001        let result = rule.check(&ctx).unwrap();
1002        assert!(
1003            result.is_empty(),
1004            "Expected no warnings when front matter has title field"
1005        );
1006    }
1007
1008    #[test]
1009    fn test_front_matter_without_title() {
1010        let rule = MD041FirstLineHeading::new(1, true);
1011
1012        // Front matter without title field (should fail)
1013        let content = "---\nauthor: John Doe\ndate: 2024-01-01\n---\n\nSome content here.";
1014        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1015        let result = rule.check(&ctx).unwrap();
1016        assert_eq!(result.len(), 1);
1017        assert_eq!(result[0].line, 6); // First content line after front matter
1018    }
1019
1020    #[test]
1021    fn test_front_matter_disabled() {
1022        let rule = MD041FirstLineHeading::new(1, false);
1023
1024        // Front matter with title field but front_matter_title is false (should fail)
1025        let content = "---\ntitle: My Document\n---\n\nSome content here.";
1026        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1027        let result = rule.check(&ctx).unwrap();
1028        assert_eq!(result.len(), 1);
1029        assert_eq!(result[0].line, 5); // First content line after front matter
1030    }
1031
1032    #[test]
1033    fn test_html_comments_before_heading() {
1034        let rule = MD041FirstLineHeading::default();
1035
1036        // HTML comment before heading (should pass - comments are skipped, issue #155)
1037        let content = "<!-- This is a comment -->\n# My Document\n\nContent.";
1038        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1039        let result = rule.check(&ctx).unwrap();
1040        assert!(
1041            result.is_empty(),
1042            "HTML comments should be skipped when checking for first heading"
1043        );
1044    }
1045
1046    #[test]
1047    fn test_multiline_html_comment_before_heading() {
1048        let rule = MD041FirstLineHeading::default();
1049
1050        // Multi-line HTML comment before heading (should pass - issue #155)
1051        let content = "<!--\nThis is a multi-line\nHTML comment\n-->\n# My Document\n\nContent.";
1052        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1053        let result = rule.check(&ctx).unwrap();
1054        assert!(
1055            result.is_empty(),
1056            "Multi-line HTML comments should be skipped when checking for first heading"
1057        );
1058    }
1059
1060    #[test]
1061    fn test_html_comment_with_blank_lines_before_heading() {
1062        let rule = MD041FirstLineHeading::default();
1063
1064        // HTML comment with blank lines before heading (should pass - issue #155)
1065        let content = "<!-- This is a comment -->\n\n# My Document\n\nContent.";
1066        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1067        let result = rule.check(&ctx).unwrap();
1068        assert!(
1069            result.is_empty(),
1070            "HTML comments with blank lines should be skipped when checking for first heading"
1071        );
1072    }
1073
1074    #[test]
1075    fn test_html_comment_before_html_heading() {
1076        let rule = MD041FirstLineHeading::default();
1077
1078        // HTML comment before HTML heading (should pass - issue #155)
1079        let content = "<!-- This is a comment -->\n<h1>My Document</h1>\n\nContent.";
1080        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1081        let result = rule.check(&ctx).unwrap();
1082        assert!(
1083            result.is_empty(),
1084            "HTML comments should be skipped before HTML headings"
1085        );
1086    }
1087
1088    #[test]
1089    fn test_document_with_only_html_comments() {
1090        let rule = MD041FirstLineHeading::default();
1091
1092        // Document with only HTML comments (should pass - no warnings for comment-only files)
1093        let content = "<!-- This is a comment -->\n<!-- Another comment -->";
1094        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1095        let result = rule.check(&ctx).unwrap();
1096        assert!(
1097            result.is_empty(),
1098            "Documents with only HTML comments should not trigger MD041"
1099        );
1100    }
1101
1102    #[test]
1103    fn test_html_comment_followed_by_non_heading() {
1104        let rule = MD041FirstLineHeading::default();
1105
1106        // HTML comment followed by non-heading content (should still fail - issue #155)
1107        let content = "<!-- This is a comment -->\nThis is not a heading\n\nSome content.";
1108        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1109        let result = rule.check(&ctx).unwrap();
1110        assert_eq!(
1111            result.len(),
1112            1,
1113            "HTML comment followed by non-heading should still trigger MD041"
1114        );
1115        assert_eq!(
1116            result[0].line, 2,
1117            "Warning should be on the first non-comment, non-heading line"
1118        );
1119    }
1120
1121    #[test]
1122    fn test_multiple_html_comments_before_heading() {
1123        let rule = MD041FirstLineHeading::default();
1124
1125        // Multiple HTML comments before heading (should pass - issue #155)
1126        let content = "<!-- First comment -->\n<!-- Second comment -->\n# My Document\n\nContent.";
1127        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1128        let result = rule.check(&ctx).unwrap();
1129        assert!(
1130            result.is_empty(),
1131            "Multiple HTML comments should all be skipped before heading"
1132        );
1133    }
1134
1135    #[test]
1136    fn test_html_comment_with_wrong_level_heading() {
1137        let rule = MD041FirstLineHeading::default();
1138
1139        // HTML comment followed by wrong-level heading (should fail - issue #155)
1140        let content = "<!-- This is a comment -->\n## Wrong Level Heading\n\nContent.";
1141        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1142        let result = rule.check(&ctx).unwrap();
1143        assert_eq!(
1144            result.len(),
1145            1,
1146            "HTML comment followed by wrong-level heading should still trigger MD041"
1147        );
1148        assert!(
1149            result[0].message.contains("level 1 heading"),
1150            "Should require level 1 heading"
1151        );
1152    }
1153
1154    #[test]
1155    fn test_html_comment_mixed_with_reference_definitions() {
1156        let rule = MD041FirstLineHeading::default();
1157
1158        // HTML comment mixed with reference definitions before heading (should pass - issue #155)
1159        let content = "<!-- Comment -->\n[ref]: https://example.com\n# My Document\n\nContent.";
1160        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1161        let result = rule.check(&ctx).unwrap();
1162        assert!(
1163            result.is_empty(),
1164            "HTML comments and reference definitions should both be skipped before heading"
1165        );
1166    }
1167
1168    #[test]
1169    fn test_html_comment_after_front_matter() {
1170        let rule = MD041FirstLineHeading::default();
1171
1172        // HTML comment after front matter, before heading (should pass - issue #155)
1173        let content = "---\nauthor: John\n---\n<!-- Comment -->\n# My Document\n\nContent.";
1174        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1175        let result = rule.check(&ctx).unwrap();
1176        assert!(
1177            result.is_empty(),
1178            "HTML comments after front matter should be skipped before heading"
1179        );
1180    }
1181
1182    #[test]
1183    fn test_html_comment_not_at_start_should_not_affect_rule() {
1184        let rule = MD041FirstLineHeading::default();
1185
1186        // HTML comment in middle of document should not affect MD041 check
1187        let content = "# Valid Heading\n\nSome content.\n\n<!-- Comment in middle -->\n\nMore content.";
1188        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1189        let result = rule.check(&ctx).unwrap();
1190        assert!(
1191            result.is_empty(),
1192            "HTML comments in middle of document should not affect MD041 (only first content matters)"
1193        );
1194    }
1195
1196    #[test]
1197    fn test_multiline_html_comment_followed_by_non_heading() {
1198        let rule = MD041FirstLineHeading::default();
1199
1200        // Multi-line HTML comment followed by non-heading (should still fail - issue #155)
1201        let content = "<!--\nMulti-line\ncomment\n-->\nThis is not a heading\n\nContent.";
1202        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1203        let result = rule.check(&ctx).unwrap();
1204        assert_eq!(
1205            result.len(),
1206            1,
1207            "Multi-line HTML comment followed by non-heading should still trigger MD041"
1208        );
1209        assert_eq!(
1210            result[0].line, 5,
1211            "Warning should be on the first non-comment, non-heading line"
1212        );
1213    }
1214
1215    #[test]
1216    fn test_different_heading_levels() {
1217        // Test with level 2 requirement
1218        let rule = MD041FirstLineHeading::new(2, false);
1219
1220        let content = "## Second Level Heading\n\nContent.";
1221        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1222        let result = rule.check(&ctx).unwrap();
1223        assert!(result.is_empty(), "Expected no warnings for correct level 2 heading");
1224
1225        // Wrong level
1226        let content = "# First Level Heading\n\nContent.";
1227        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1228        let result = rule.check(&ctx).unwrap();
1229        assert_eq!(result.len(), 1);
1230        assert!(result[0].message.contains("level 2 heading"));
1231    }
1232
1233    #[test]
1234    fn test_setext_headings() {
1235        let rule = MD041FirstLineHeading::default();
1236
1237        // Setext style level 1 heading (should pass)
1238        let content = "My Document\n===========\n\nContent.";
1239        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1240        let result = rule.check(&ctx).unwrap();
1241        assert!(result.is_empty(), "Expected no warnings for setext level 1 heading");
1242
1243        // Setext style level 2 heading (should fail with level 1 requirement)
1244        let content = "My Document\n-----------\n\nContent.";
1245        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1246        let result = rule.check(&ctx).unwrap();
1247        assert_eq!(result.len(), 1);
1248        assert!(result[0].message.contains("level 1 heading"));
1249    }
1250
1251    #[test]
1252    fn test_empty_document() {
1253        let rule = MD041FirstLineHeading::default();
1254
1255        // Empty document (should pass - no warnings)
1256        let content = "";
1257        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1258        let result = rule.check(&ctx).unwrap();
1259        assert!(result.is_empty(), "Expected no warnings for empty document");
1260    }
1261
1262    #[test]
1263    fn test_whitespace_only_document() {
1264        let rule = MD041FirstLineHeading::default();
1265
1266        // Document with only whitespace (should pass - no warnings)
1267        let content = "   \n\n   \t\n";
1268        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1269        let result = rule.check(&ctx).unwrap();
1270        assert!(result.is_empty(), "Expected no warnings for whitespace-only document");
1271    }
1272
1273    #[test]
1274    fn test_front_matter_then_whitespace() {
1275        let rule = MD041FirstLineHeading::default();
1276
1277        // Front matter followed by only whitespace (should pass - no warnings)
1278        let content = "---\ntitle: Test\n---\n\n   \n\n";
1279        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1280        let result = rule.check(&ctx).unwrap();
1281        assert!(
1282            result.is_empty(),
1283            "Expected no warnings when no content after front matter"
1284        );
1285    }
1286
1287    #[test]
1288    fn test_multiple_front_matter_types() {
1289        let rule = MD041FirstLineHeading::new(1, true);
1290
1291        // TOML front matter with title (should pass - title satisfies heading requirement)
1292        let content = "+++\ntitle = \"My Document\"\n+++\n\nContent.";
1293        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1294        let result = rule.check(&ctx).unwrap();
1295        assert!(
1296            result.is_empty(),
1297            "Expected no warnings for TOML front matter with title"
1298        );
1299
1300        // JSON front matter with title (should pass)
1301        let content = "{\n\"title\": \"My Document\"\n}\n\nContent.";
1302        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1303        let result = rule.check(&ctx).unwrap();
1304        assert!(
1305            result.is_empty(),
1306            "Expected no warnings for JSON front matter with title"
1307        );
1308
1309        // YAML front matter with title field (standard case)
1310        let content = "---\ntitle: My Document\n---\n\nContent.";
1311        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1312        let result = rule.check(&ctx).unwrap();
1313        assert!(
1314            result.is_empty(),
1315            "Expected no warnings for YAML front matter with title"
1316        );
1317    }
1318
1319    #[test]
1320    fn test_toml_front_matter_with_heading() {
1321        let rule = MD041FirstLineHeading::default();
1322
1323        // TOML front matter followed by correct heading (should pass)
1324        let content = "+++\nauthor = \"John\"\n+++\n\n# My Document\n\nContent.";
1325        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1326        let result = rule.check(&ctx).unwrap();
1327        assert!(
1328            result.is_empty(),
1329            "Expected no warnings when heading follows TOML front matter"
1330        );
1331    }
1332
1333    #[test]
1334    fn test_toml_front_matter_without_title_no_heading() {
1335        let rule = MD041FirstLineHeading::new(1, true);
1336
1337        // TOML front matter without title, no heading (should warn)
1338        let content = "+++\nauthor = \"John\"\ndate = \"2024-01-01\"\n+++\n\nSome content here.";
1339        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1340        let result = rule.check(&ctx).unwrap();
1341        assert_eq!(result.len(), 1);
1342        assert_eq!(result[0].line, 6);
1343    }
1344
1345    #[test]
1346    fn test_toml_front_matter_level_2_heading() {
1347        // Reproduces the exact scenario from issue #427
1348        let rule = MD041FirstLineHeading::new(2, true);
1349
1350        let content = "+++\ntitle = \"Title\"\n+++\n\n## Documentation\n\nWrite stuff here...";
1351        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1352        let result = rule.check(&ctx).unwrap();
1353        assert!(
1354            result.is_empty(),
1355            "Issue #427: TOML front matter with title and correct heading level should not warn"
1356        );
1357    }
1358
1359    #[test]
1360    fn test_toml_front_matter_level_2_heading_with_yaml_style_pattern() {
1361        // Reproduces the exact config shape from issue #427
1362        let rule = MD041FirstLineHeading::with_pattern(2, true, Some("^(title|header):".to_string()), false);
1363
1364        let content = "+++\ntitle = \"Title\"\n+++\n\n## Documentation\n\nWrite stuff here...";
1365        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1366        let result = rule.check(&ctx).unwrap();
1367        assert!(
1368            result.is_empty(),
1369            "Issue #427 regression: TOML front matter must be skipped when locating first heading"
1370        );
1371    }
1372
1373    #[test]
1374    fn test_json_front_matter_with_heading() {
1375        let rule = MD041FirstLineHeading::default();
1376
1377        // JSON front matter followed by correct heading
1378        let content = "{\n\"author\": \"John\"\n}\n\n# My Document\n\nContent.";
1379        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1380        let result = rule.check(&ctx).unwrap();
1381        assert!(
1382            result.is_empty(),
1383            "Expected no warnings when heading follows JSON front matter"
1384        );
1385    }
1386
1387    #[test]
1388    fn test_malformed_front_matter() {
1389        let rule = MD041FirstLineHeading::new(1, true);
1390
1391        // Malformed front matter with title
1392        let content = "- --\ntitle: My Document\n- --\n\nContent.";
1393        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1394        let result = rule.check(&ctx).unwrap();
1395        assert!(
1396            result.is_empty(),
1397            "Expected no warnings for malformed front matter with title"
1398        );
1399    }
1400
1401    #[test]
1402    fn test_front_matter_with_heading() {
1403        let rule = MD041FirstLineHeading::default();
1404
1405        // Front matter without title field followed by correct heading
1406        let content = "---\nauthor: John Doe\n---\n\n# My Document\n\nContent.";
1407        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1408        let result = rule.check(&ctx).unwrap();
1409        assert!(
1410            result.is_empty(),
1411            "Expected no warnings when first line after front matter is correct heading"
1412        );
1413    }
1414
1415    #[test]
1416    fn test_no_fix_suggestion() {
1417        let rule = MD041FirstLineHeading::default();
1418
1419        // Check that NO fix suggestion is provided (MD041 is now detection-only)
1420        let content = "Not a heading\n\nContent.";
1421        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1422        let result = rule.check(&ctx).unwrap();
1423        assert_eq!(result.len(), 1);
1424        assert!(result[0].fix.is_none(), "MD041 should not provide fix suggestions");
1425    }
1426
1427    #[test]
1428    fn test_complex_document_structure() {
1429        let rule = MD041FirstLineHeading::default();
1430
1431        // Complex document with various elements - HTML comment should be skipped (issue #155)
1432        let content =
1433            "---\nauthor: John\n---\n\n<!-- Comment -->\n\n\n# Valid Heading\n\n## Subheading\n\nContent here.";
1434        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1435        let result = rule.check(&ctx).unwrap();
1436        assert!(
1437            result.is_empty(),
1438            "HTML comments should be skipped, so first heading after comment should be valid"
1439        );
1440    }
1441
1442    #[test]
1443    fn test_heading_with_special_characters() {
1444        let rule = MD041FirstLineHeading::default();
1445
1446        // Heading with special characters and formatting
1447        let content = "# Welcome to **My** _Document_ with `code`\n\nContent.";
1448        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1449        let result = rule.check(&ctx).unwrap();
1450        assert!(
1451            result.is_empty(),
1452            "Expected no warnings for heading with inline formatting"
1453        );
1454    }
1455
1456    #[test]
1457    fn test_level_configuration() {
1458        // Test various level configurations
1459        for level in 1..=6 {
1460            let rule = MD041FirstLineHeading::new(level, false);
1461
1462            // Correct level
1463            let content = format!("{} Heading at Level {}\n\nContent.", "#".repeat(level), level);
1464            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
1465            let result = rule.check(&ctx).unwrap();
1466            assert!(
1467                result.is_empty(),
1468                "Expected no warnings for correct level {level} heading"
1469            );
1470
1471            // Wrong level
1472            let wrong_level = if level == 1 { 2 } else { 1 };
1473            let content = format!("{} Wrong Level Heading\n\nContent.", "#".repeat(wrong_level));
1474            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
1475            let result = rule.check(&ctx).unwrap();
1476            assert_eq!(result.len(), 1);
1477            assert!(result[0].message.contains(&format!("level {level} heading")));
1478        }
1479    }
1480
1481    #[test]
1482    fn test_issue_152_multiline_html_heading() {
1483        let rule = MD041FirstLineHeading::default();
1484
1485        // Multi-line HTML h1 heading (should pass - issue #152)
1486        let content = "<h1>\nSome text\n</h1>";
1487        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1488        let result = rule.check(&ctx).unwrap();
1489        assert!(
1490            result.is_empty(),
1491            "Issue #152: Multi-line HTML h1 should be recognized as valid heading"
1492        );
1493    }
1494
1495    #[test]
1496    fn test_multiline_html_heading_with_attributes() {
1497        let rule = MD041FirstLineHeading::default();
1498
1499        // Multi-line HTML heading with attributes
1500        let content = "<h1 class=\"title\" id=\"main\">\nHeading Text\n</h1>\n\nContent.";
1501        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1502        let result = rule.check(&ctx).unwrap();
1503        assert!(
1504            result.is_empty(),
1505            "Multi-line HTML heading with attributes should be recognized"
1506        );
1507    }
1508
1509    #[test]
1510    fn test_multiline_html_heading_wrong_level() {
1511        let rule = MD041FirstLineHeading::default();
1512
1513        // Multi-line HTML h2 heading (should fail with level 1 requirement)
1514        let content = "<h2>\nSome text\n</h2>";
1515        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1516        let result = rule.check(&ctx).unwrap();
1517        assert_eq!(result.len(), 1);
1518        assert!(result[0].message.contains("level 1 heading"));
1519    }
1520
1521    #[test]
1522    fn test_multiline_html_heading_with_content_after() {
1523        let rule = MD041FirstLineHeading::default();
1524
1525        // Multi-line HTML heading followed by content
1526        let content = "<h1>\nMy Document\n</h1>\n\nThis is the document content.";
1527        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1528        let result = rule.check(&ctx).unwrap();
1529        assert!(
1530            result.is_empty(),
1531            "Multi-line HTML heading followed by content should be valid"
1532        );
1533    }
1534
1535    #[test]
1536    fn test_multiline_html_heading_incomplete() {
1537        let rule = MD041FirstLineHeading::default();
1538
1539        // Incomplete multi-line HTML heading (missing closing tag)
1540        let content = "<h1>\nSome text\n\nMore content without closing tag";
1541        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1542        let result = rule.check(&ctx).unwrap();
1543        assert_eq!(result.len(), 1);
1544        assert!(result[0].message.contains("level 1 heading"));
1545    }
1546
1547    #[test]
1548    fn test_singleline_html_heading_still_works() {
1549        let rule = MD041FirstLineHeading::default();
1550
1551        // Single-line HTML heading should still work
1552        let content = "<h1>My Document</h1>\n\nContent.";
1553        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1554        let result = rule.check(&ctx).unwrap();
1555        assert!(
1556            result.is_empty(),
1557            "Single-line HTML headings should still be recognized"
1558        );
1559    }
1560
1561    #[test]
1562    fn test_multiline_html_heading_with_nested_tags() {
1563        let rule = MD041FirstLineHeading::default();
1564
1565        // Multi-line HTML heading with nested tags
1566        let content = "<h1>\n<strong>Bold</strong> Heading\n</h1>";
1567        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1568        let result = rule.check(&ctx).unwrap();
1569        assert!(
1570            result.is_empty(),
1571            "Multi-line HTML heading with nested tags should be recognized"
1572        );
1573    }
1574
1575    #[test]
1576    fn test_multiline_html_heading_various_levels() {
1577        // Test multi-line headings at different levels
1578        for level in 1..=6 {
1579            let rule = MD041FirstLineHeading::new(level, false);
1580
1581            // Correct level multi-line
1582            let content = format!("<h{level}>\nHeading Text\n</h{level}>\n\nContent.");
1583            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
1584            let result = rule.check(&ctx).unwrap();
1585            assert!(
1586                result.is_empty(),
1587                "Multi-line HTML heading at level {level} should be recognized"
1588            );
1589
1590            // Wrong level multi-line
1591            let wrong_level = if level == 1 { 2 } else { 1 };
1592            let content = format!("<h{wrong_level}>\nHeading Text\n</h{wrong_level}>\n\nContent.");
1593            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
1594            let result = rule.check(&ctx).unwrap();
1595            assert_eq!(result.len(), 1);
1596            assert!(result[0].message.contains(&format!("level {level} heading")));
1597        }
1598    }
1599
1600    #[test]
1601    fn test_issue_152_nested_heading_spans_many_lines() {
1602        let rule = MD041FirstLineHeading::default();
1603
1604        let content = "<h1>\n  <div>\n    <img\n      href=\"https://example.com/image.png\"\n      alt=\"Example Image\"\n    />\n    <a\n      href=\"https://example.com\"\n    >Example Project</a>\n    <span>Documentation</span>\n  </div>\n</h1>";
1605        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1606        let result = rule.check(&ctx).unwrap();
1607        assert!(result.is_empty(), "Nested multi-line HTML heading should be recognized");
1608    }
1609
1610    #[test]
1611    fn test_issue_152_picture_tag_heading() {
1612        let rule = MD041FirstLineHeading::default();
1613
1614        let content = "<h1>\n  <picture>\n    <source\n      srcset=\"https://example.com/light.png\"\n      media=\"(prefers-color-scheme: light)\"\n    />\n    <source\n      srcset=\"https://example.com/dark.png\"\n      media=\"(prefers-color-scheme: dark)\"\n    />\n    <img src=\"https://example.com/default.png\" />\n  </picture>\n</h1>";
1615        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1616        let result = rule.check(&ctx).unwrap();
1617        assert!(
1618            result.is_empty(),
1619            "Picture tag inside multi-line HTML heading should be recognized"
1620        );
1621    }
1622
1623    #[test]
1624    fn test_badge_images_before_heading() {
1625        let rule = MD041FirstLineHeading::default();
1626
1627        // Single badge before heading
1628        let content = "![badge](https://img.shields.io/badge/test-passing-green)\n\n# My Project";
1629        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1630        let result = rule.check(&ctx).unwrap();
1631        assert!(result.is_empty(), "Badge image should be skipped");
1632
1633        // Multiple badges on one line
1634        let content = "![badge1](url1) ![badge2](url2)\n\n# My Project";
1635        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1636        let result = rule.check(&ctx).unwrap();
1637        assert!(result.is_empty(), "Multiple badges should be skipped");
1638
1639        // Linked badge (clickable)
1640        let content = "[![badge](https://img.shields.io/badge/test-pass-green)](https://example.com)\n\n# My Project";
1641        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1642        let result = rule.check(&ctx).unwrap();
1643        assert!(result.is_empty(), "Linked badge should be skipped");
1644    }
1645
1646    #[test]
1647    fn test_multiple_badge_lines_before_heading() {
1648        let rule = MD041FirstLineHeading::default();
1649
1650        // Multiple lines of badges
1651        let content = "[![Crates.io](https://img.shields.io/crates/v/example)](https://crates.io)\n[![docs.rs](https://img.shields.io/docsrs/example)](https://docs.rs)\n\n# My Project";
1652        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1653        let result = rule.check(&ctx).unwrap();
1654        assert!(result.is_empty(), "Multiple badge lines should be skipped");
1655    }
1656
1657    #[test]
1658    fn test_badges_without_heading_still_warns() {
1659        let rule = MD041FirstLineHeading::default();
1660
1661        // Badges followed by paragraph (not heading)
1662        let content = "![badge](url)\n\nThis is not a heading.";
1663        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1664        let result = rule.check(&ctx).unwrap();
1665        assert_eq!(result.len(), 1, "Should warn when badges followed by non-heading");
1666    }
1667
1668    #[test]
1669    fn test_mixed_content_not_badge_line() {
1670        let rule = MD041FirstLineHeading::default();
1671
1672        // Image with text is not a badge line
1673        let content = "![badge](url) Some text here\n\n# Heading";
1674        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1675        let result = rule.check(&ctx).unwrap();
1676        assert_eq!(result.len(), 1, "Mixed content line should not be skipped");
1677    }
1678
1679    #[test]
1680    fn test_is_badge_image_line_unit() {
1681        // Unit tests for is_badge_image_line
1682        assert!(MD041FirstLineHeading::is_badge_image_line("![badge](url)"));
1683        assert!(MD041FirstLineHeading::is_badge_image_line("[![badge](img)](link)"));
1684        assert!(MD041FirstLineHeading::is_badge_image_line("![a](b) ![c](d)"));
1685        assert!(MD041FirstLineHeading::is_badge_image_line("[![a](b)](c) [![d](e)](f)"));
1686
1687        // Not badge lines
1688        assert!(!MD041FirstLineHeading::is_badge_image_line(""));
1689        assert!(!MD041FirstLineHeading::is_badge_image_line("Some text"));
1690        assert!(!MD041FirstLineHeading::is_badge_image_line("![badge](url) text"));
1691        assert!(!MD041FirstLineHeading::is_badge_image_line("# Heading"));
1692    }
1693
1694    // Integration tests for MkDocs anchor line detection (issue #365)
1695    // Unit tests for is_mkdocs_anchor_line are in utils/mkdocs_attr_list.rs
1696
1697    #[test]
1698    fn test_mkdocs_anchor_before_heading_in_mkdocs_flavor() {
1699        let rule = MD041FirstLineHeading::default();
1700
1701        // MkDocs anchor line before heading in MkDocs flavor (should pass)
1702        let content = "[](){ #example }\n# Title";
1703        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1704        let result = rule.check(&ctx).unwrap();
1705        assert!(
1706            result.is_empty(),
1707            "MkDocs anchor line should be skipped in MkDocs flavor"
1708        );
1709    }
1710
1711    #[test]
1712    fn test_mkdocs_anchor_before_heading_in_standard_flavor() {
1713        let rule = MD041FirstLineHeading::default();
1714
1715        // MkDocs anchor line before heading in Standard flavor (should fail)
1716        let content = "[](){ #example }\n# Title";
1717        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1718        let result = rule.check(&ctx).unwrap();
1719        assert_eq!(
1720            result.len(),
1721            1,
1722            "MkDocs anchor line should NOT be skipped in Standard flavor"
1723        );
1724    }
1725
1726    #[test]
1727    fn test_multiple_mkdocs_anchors_before_heading() {
1728        let rule = MD041FirstLineHeading::default();
1729
1730        // Multiple MkDocs anchor lines before heading in MkDocs flavor
1731        let content = "[](){ #first }\n[](){ #second }\n# Title";
1732        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1733        let result = rule.check(&ctx).unwrap();
1734        assert!(
1735            result.is_empty(),
1736            "Multiple MkDocs anchor lines should all be skipped in MkDocs flavor"
1737        );
1738    }
1739
1740    #[test]
1741    fn test_mkdocs_anchor_with_front_matter() {
1742        let rule = MD041FirstLineHeading::default();
1743
1744        // MkDocs anchor after front matter
1745        let content = "---\nauthor: John\n---\n[](){ #anchor }\n# Title";
1746        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1747        let result = rule.check(&ctx).unwrap();
1748        assert!(
1749            result.is_empty(),
1750            "MkDocs anchor line after front matter should be skipped in MkDocs flavor"
1751        );
1752    }
1753
1754    #[test]
1755    fn test_mkdocs_anchor_kramdown_style() {
1756        let rule = MD041FirstLineHeading::default();
1757
1758        // Kramdown-style with colon
1759        let content = "[](){: #anchor }\n# Title";
1760        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1761        let result = rule.check(&ctx).unwrap();
1762        assert!(
1763            result.is_empty(),
1764            "Kramdown-style MkDocs anchor should be skipped in MkDocs flavor"
1765        );
1766    }
1767
1768    #[test]
1769    fn test_mkdocs_anchor_without_heading_still_warns() {
1770        let rule = MD041FirstLineHeading::default();
1771
1772        // MkDocs anchor followed by non-heading content
1773        let content = "[](){ #anchor }\nThis is not a heading.";
1774        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1775        let result = rule.check(&ctx).unwrap();
1776        assert_eq!(
1777            result.len(),
1778            1,
1779            "MkDocs anchor followed by non-heading should still trigger MD041"
1780        );
1781    }
1782
1783    #[test]
1784    fn test_mkdocs_anchor_with_html_comment() {
1785        let rule = MD041FirstLineHeading::default();
1786
1787        // MkDocs anchor combined with HTML comment before heading
1788        let content = "<!-- Comment -->\n[](){ #anchor }\n# Title";
1789        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
1790        let result = rule.check(&ctx).unwrap();
1791        assert!(
1792            result.is_empty(),
1793            "MkDocs anchor with HTML comment should both be skipped in MkDocs flavor"
1794        );
1795    }
1796
1797    // Tests for auto-fix functionality (issue #359)
1798
1799    #[test]
1800    fn test_fix_disabled_by_default() {
1801        use crate::rule::Rule;
1802        let rule = MD041FirstLineHeading::default();
1803
1804        // Fix should not change content when disabled
1805        let content = "## Wrong Level\n\nContent.";
1806        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1807        let fixed = rule.fix(&ctx).unwrap();
1808        assert_eq!(fixed, content, "Fix should not change content when disabled");
1809    }
1810
1811    #[test]
1812    fn test_fix_wrong_heading_level() {
1813        use crate::rule::Rule;
1814        let rule = MD041FirstLineHeading {
1815            level: 1,
1816            front_matter_title: false,
1817            front_matter_title_pattern: None,
1818            allow_preamble: false,
1819            fix_enabled: true,
1820        };
1821
1822        // ## should become #
1823        let content = "## Wrong Level\n\nContent.\n";
1824        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1825        let fixed = rule.fix(&ctx).unwrap();
1826        assert_eq!(fixed, "# Wrong Level\n\nContent.\n", "Should fix heading level");
1827    }
1828
1829    #[test]
1830    fn test_fix_heading_after_preamble() {
1831        use crate::rule::Rule;
1832        let rule = MD041FirstLineHeading {
1833            level: 1,
1834            front_matter_title: false,
1835            front_matter_title_pattern: None,
1836            allow_preamble: false,
1837            fix_enabled: true,
1838        };
1839
1840        // Heading after blank lines should be moved up
1841        let content = "\n\n# Title\n\nContent.\n";
1842        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1843        let fixed = rule.fix(&ctx).unwrap();
1844        assert!(
1845            fixed.starts_with("# Title\n"),
1846            "Heading should be moved to first line, got: {fixed}"
1847        );
1848    }
1849
1850    #[test]
1851    fn test_fix_heading_after_html_comment() {
1852        use crate::rule::Rule;
1853        let rule = MD041FirstLineHeading {
1854            level: 1,
1855            front_matter_title: false,
1856            front_matter_title_pattern: None,
1857            allow_preamble: false,
1858            fix_enabled: true,
1859        };
1860
1861        // Heading after HTML comment should be moved up
1862        let content = "<!-- Comment -->\n# Title\n\nContent.\n";
1863        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1864        let fixed = rule.fix(&ctx).unwrap();
1865        assert!(
1866            fixed.starts_with("# Title\n"),
1867            "Heading should be moved above comment, got: {fixed}"
1868        );
1869    }
1870
1871    #[test]
1872    fn test_fix_heading_level_and_move() {
1873        use crate::rule::Rule;
1874        let rule = MD041FirstLineHeading {
1875            level: 1,
1876            front_matter_title: false,
1877            front_matter_title_pattern: None,
1878            allow_preamble: false,
1879            fix_enabled: true,
1880        };
1881
1882        // Heading with wrong level after preamble should be fixed and moved
1883        let content = "<!-- Comment -->\n\n## Wrong Level\n\nContent.\n";
1884        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1885        let fixed = rule.fix(&ctx).unwrap();
1886        assert!(
1887            fixed.starts_with("# Wrong Level\n"),
1888            "Heading should be fixed and moved, got: {fixed}"
1889        );
1890    }
1891
1892    #[test]
1893    fn test_fix_with_front_matter() {
1894        use crate::rule::Rule;
1895        let rule = MD041FirstLineHeading {
1896            level: 1,
1897            front_matter_title: false,
1898            front_matter_title_pattern: None,
1899            allow_preamble: false,
1900            fix_enabled: true,
1901        };
1902
1903        // Heading after front matter and preamble
1904        let content = "---\nauthor: John\n---\n\n<!-- Comment -->\n## Title\n\nContent.\n";
1905        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1906        let fixed = rule.fix(&ctx).unwrap();
1907        assert!(
1908            fixed.starts_with("---\nauthor: John\n---\n# Title\n"),
1909            "Heading should be right after front matter, got: {fixed}"
1910        );
1911    }
1912
1913    #[test]
1914    fn test_fix_with_toml_front_matter() {
1915        use crate::rule::Rule;
1916        let rule = MD041FirstLineHeading {
1917            level: 1,
1918            front_matter_title: false,
1919            front_matter_title_pattern: None,
1920            allow_preamble: false,
1921            fix_enabled: true,
1922        };
1923
1924        // Heading after TOML front matter and preamble
1925        let content = "+++\nauthor = \"John\"\n+++\n\n<!-- Comment -->\n## Title\n\nContent.\n";
1926        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1927        let fixed = rule.fix(&ctx).unwrap();
1928        assert!(
1929            fixed.starts_with("+++\nauthor = \"John\"\n+++\n# Title\n"),
1930            "Heading should be right after TOML front matter, got: {fixed}"
1931        );
1932    }
1933
1934    #[test]
1935    fn test_fix_cannot_fix_no_heading() {
1936        use crate::rule::Rule;
1937        let rule = MD041FirstLineHeading {
1938            level: 1,
1939            front_matter_title: false,
1940            front_matter_title_pattern: None,
1941            allow_preamble: false,
1942            fix_enabled: true,
1943        };
1944
1945        // No heading in document - cannot fix
1946        let content = "Just some text.\n\nMore text.\n";
1947        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1948        let fixed = rule.fix(&ctx).unwrap();
1949        assert_eq!(fixed, content, "Should not change content when no heading exists");
1950    }
1951
1952    #[test]
1953    fn test_fix_cannot_fix_content_before_heading() {
1954        use crate::rule::Rule;
1955        let rule = MD041FirstLineHeading {
1956            level: 1,
1957            front_matter_title: false,
1958            front_matter_title_pattern: None,
1959            allow_preamble: false,
1960            fix_enabled: true,
1961        };
1962
1963        // Real content before heading - cannot safely fix
1964        let content = "Some intro text.\n\n# Title\n\nContent.\n";
1965        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1966        let fixed = rule.fix(&ctx).unwrap();
1967        assert_eq!(
1968            fixed, content,
1969            "Should not change content when real content exists before heading"
1970        );
1971    }
1972
1973    #[test]
1974    fn test_fix_already_correct() {
1975        use crate::rule::Rule;
1976        let rule = MD041FirstLineHeading {
1977            level: 1,
1978            front_matter_title: false,
1979            front_matter_title_pattern: None,
1980            allow_preamble: false,
1981            fix_enabled: true,
1982        };
1983
1984        // Already correct - no changes needed
1985        let content = "# Title\n\nContent.\n";
1986        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1987        let fixed = rule.fix(&ctx).unwrap();
1988        assert_eq!(fixed, content, "Should not change already correct content");
1989    }
1990
1991    #[test]
1992    fn test_fix_setext_heading_removes_underline() {
1993        use crate::rule::Rule;
1994        let rule = MD041FirstLineHeading {
1995            level: 1,
1996            front_matter_title: false,
1997            front_matter_title_pattern: None,
1998            allow_preamble: false,
1999            fix_enabled: true,
2000        };
2001
2002        // Setext heading (level 2 with --- underline)
2003        let content = "Wrong Level\n-----------\n\nContent.\n";
2004        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2005        let fixed = rule.fix(&ctx).unwrap();
2006        assert_eq!(
2007            fixed, "# Wrong Level\n\nContent.\n",
2008            "Setext heading should be converted to ATX and underline removed"
2009        );
2010    }
2011
2012    #[test]
2013    fn test_fix_setext_h1_heading() {
2014        use crate::rule::Rule;
2015        let rule = MD041FirstLineHeading {
2016            level: 1,
2017            front_matter_title: false,
2018            front_matter_title_pattern: None,
2019            allow_preamble: false,
2020            fix_enabled: true,
2021        };
2022
2023        // Setext h1 heading (=== underline) after preamble - needs move but not level fix
2024        let content = "<!-- comment -->\n\nTitle\n=====\n\nContent.\n";
2025        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2026        let fixed = rule.fix(&ctx).unwrap();
2027        assert_eq!(
2028            fixed, "# Title\n<!-- comment -->\n\n\nContent.\n",
2029            "Setext h1 should be moved and converted to ATX"
2030        );
2031    }
2032
2033    #[test]
2034    fn test_html_heading_not_claimed_fixable() {
2035        use crate::rule::Rule;
2036        let rule = MD041FirstLineHeading {
2037            level: 1,
2038            front_matter_title: false,
2039            front_matter_title_pattern: None,
2040            allow_preamble: false,
2041            fix_enabled: true,
2042        };
2043
2044        // HTML heading - should NOT be claimed as fixable (we can't convert HTML to ATX)
2045        let content = "<h2>Title</h2>\n\nContent.\n";
2046        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2047        let warnings = rule.check(&ctx).unwrap();
2048        assert_eq!(warnings.len(), 1);
2049        assert!(
2050            warnings[0].fix.is_none(),
2051            "HTML heading should not be claimed as fixable"
2052        );
2053    }
2054
2055    #[test]
2056    fn test_no_heading_not_claimed_fixable() {
2057        use crate::rule::Rule;
2058        let rule = MD041FirstLineHeading {
2059            level: 1,
2060            front_matter_title: false,
2061            front_matter_title_pattern: None,
2062            allow_preamble: false,
2063            fix_enabled: true,
2064        };
2065
2066        // No heading in document - should NOT be claimed as fixable
2067        let content = "Just some text.\n\nMore text.\n";
2068        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2069        let warnings = rule.check(&ctx).unwrap();
2070        assert_eq!(warnings.len(), 1);
2071        assert!(
2072            warnings[0].fix.is_none(),
2073            "Document without heading should not be claimed as fixable"
2074        );
2075    }
2076
2077    #[test]
2078    fn test_content_before_heading_not_claimed_fixable() {
2079        use crate::rule::Rule;
2080        let rule = MD041FirstLineHeading {
2081            level: 1,
2082            front_matter_title: false,
2083            front_matter_title_pattern: None,
2084            allow_preamble: false,
2085            fix_enabled: true,
2086        };
2087
2088        // Content before heading - should NOT be claimed as fixable
2089        let content = "Intro text.\n\n## Heading\n\nMore.\n";
2090        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2091        let warnings = rule.check(&ctx).unwrap();
2092        assert_eq!(warnings.len(), 1);
2093        assert!(
2094            warnings[0].fix.is_none(),
2095            "Document with content before heading should not be claimed as fixable"
2096        );
2097    }
2098
2099    // ── Phase 1 (Case C): HTML blocks treated as preamble ──────────────────────
2100
2101    #[test]
2102    fn test_fix_html_block_before_heading_is_now_fixable() {
2103        use crate::rule::Rule;
2104        let rule = MD041FirstLineHeading {
2105            level: 1,
2106            front_matter_title: false,
2107            front_matter_title_pattern: None,
2108            allow_preamble: false,
2109            fix_enabled: true,
2110        };
2111
2112        // HTML block (badges div) before the real heading – was unfixable before Phase 1
2113        let content = "<div>\n  Some HTML\n</div>\n\n# My Document\n\nContent.\n";
2114        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2115
2116        let warnings = rule.check(&ctx).unwrap();
2117        assert_eq!(warnings.len(), 1, "Warning should fire because first line is HTML");
2118        assert!(
2119            warnings[0].fix.is_some(),
2120            "Should be fixable: heading exists after HTML block preamble"
2121        );
2122
2123        let fixed = rule.fix(&ctx).unwrap();
2124        assert!(
2125            fixed.starts_with("# My Document\n"),
2126            "Heading should be moved to the top, got: {fixed}"
2127        );
2128    }
2129
2130    #[test]
2131    fn test_fix_html_block_wrong_level_before_heading() {
2132        use crate::rule::Rule;
2133        let rule = MD041FirstLineHeading {
2134            level: 1,
2135            front_matter_title: false,
2136            front_matter_title_pattern: None,
2137            allow_preamble: false,
2138            fix_enabled: true,
2139        };
2140
2141        let content = "<div>\n  badge\n</div>\n\n## Wrong Level\n\nContent.\n";
2142        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2143        let fixed = rule.fix(&ctx).unwrap();
2144        assert!(
2145            fixed.starts_with("# Wrong Level\n"),
2146            "Heading should be fixed to level 1 and moved to top, got: {fixed}"
2147        );
2148    }
2149
2150    // ── Phase 2 (Case A): PromotePlainText ──────────────────────────────────────
2151
2152    #[test]
2153    fn test_fix_promote_plain_text_title() {
2154        use crate::rule::Rule;
2155        let rule = MD041FirstLineHeading {
2156            level: 1,
2157            front_matter_title: false,
2158            front_matter_title_pattern: None,
2159            allow_preamble: false,
2160            fix_enabled: true,
2161        };
2162
2163        let content = "My Project\n\nSome content.\n";
2164        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2165
2166        let warnings = rule.check(&ctx).unwrap();
2167        assert_eq!(warnings.len(), 1, "Should warn: first line is not a heading");
2168        assert!(
2169            warnings[0].fix.is_some(),
2170            "Should be fixable: first line is a title candidate"
2171        );
2172
2173        let fixed = rule.fix(&ctx).unwrap();
2174        assert_eq!(
2175            fixed, "# My Project\n\nSome content.\n",
2176            "Title line should be promoted to heading"
2177        );
2178    }
2179
2180    #[test]
2181    fn test_fix_promote_plain_text_title_with_front_matter() {
2182        use crate::rule::Rule;
2183        let rule = MD041FirstLineHeading {
2184            level: 1,
2185            front_matter_title: false,
2186            front_matter_title_pattern: None,
2187            allow_preamble: false,
2188            fix_enabled: true,
2189        };
2190
2191        let content = "---\nauthor: John\n---\n\nMy Project\n\nContent.\n";
2192        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2193        let fixed = rule.fix(&ctx).unwrap();
2194        assert!(
2195            fixed.starts_with("---\nauthor: John\n---\n# My Project\n"),
2196            "Title should be promoted and placed right after front matter, got: {fixed}"
2197        );
2198    }
2199
2200    #[test]
2201    fn test_fix_no_promote_ends_with_period() {
2202        use crate::rule::Rule;
2203        let rule = MD041FirstLineHeading {
2204            level: 1,
2205            front_matter_title: false,
2206            front_matter_title_pattern: None,
2207            allow_preamble: false,
2208            fix_enabled: true,
2209        };
2210
2211        // Sentence-ending punctuation → NOT a title candidate
2212        let content = "This is a sentence.\n\nContent.\n";
2213        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2214        let fixed = rule.fix(&ctx).unwrap();
2215        assert_eq!(fixed, content, "Sentence-ending line should not be promoted");
2216
2217        let warnings = rule.check(&ctx).unwrap();
2218        assert!(warnings[0].fix.is_none(), "No fix should be offered");
2219    }
2220
2221    #[test]
2222    fn test_fix_no_promote_ends_with_colon() {
2223        use crate::rule::Rule;
2224        let rule = MD041FirstLineHeading {
2225            level: 1,
2226            front_matter_title: false,
2227            front_matter_title_pattern: None,
2228            allow_preamble: false,
2229            fix_enabled: true,
2230        };
2231
2232        let content = "Note:\n\nContent.\n";
2233        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2234        let fixed = rule.fix(&ctx).unwrap();
2235        assert_eq!(fixed, content, "Colon-ending line should not be promoted");
2236    }
2237
2238    #[test]
2239    fn test_fix_no_promote_if_too_long() {
2240        use crate::rule::Rule;
2241        let rule = MD041FirstLineHeading {
2242            level: 1,
2243            front_matter_title: false,
2244            front_matter_title_pattern: None,
2245            allow_preamble: false,
2246            fix_enabled: true,
2247        };
2248
2249        // >80 chars → not a title candidate
2250        let long_line = "A".repeat(81);
2251        let content = format!("{long_line}\n\nContent.\n");
2252        let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
2253        let fixed = rule.fix(&ctx).unwrap();
2254        assert_eq!(fixed, content, "Lines over 80 chars should not be promoted");
2255    }
2256
2257    #[test]
2258    fn test_fix_no_promote_if_no_blank_after() {
2259        use crate::rule::Rule;
2260        let rule = MD041FirstLineHeading {
2261            level: 1,
2262            front_matter_title: false,
2263            front_matter_title_pattern: None,
2264            allow_preamble: false,
2265            fix_enabled: true,
2266        };
2267
2268        // No blank line after potential title → NOT a title candidate
2269        let content = "My Project\nImmediately continues.\n\nContent.\n";
2270        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2271        let fixed = rule.fix(&ctx).unwrap();
2272        assert_eq!(fixed, content, "Line without following blank should not be promoted");
2273    }
2274
2275    #[test]
2276    fn test_fix_no_promote_when_heading_exists_after_title_candidate() {
2277        use crate::rule::Rule;
2278        let rule = MD041FirstLineHeading {
2279            level: 1,
2280            front_matter_title: false,
2281            front_matter_title_pattern: None,
2282            allow_preamble: false,
2283            fix_enabled: true,
2284        };
2285
2286        // Title candidate exists but so does a heading later → can't safely fix
2287        // (the title candidate is content before the heading)
2288        let content = "My Project\n\n# Actual Heading\n\nContent.\n";
2289        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2290        let fixed = rule.fix(&ctx).unwrap();
2291        assert_eq!(
2292            fixed, content,
2293            "Should not fix when title candidate exists before a heading"
2294        );
2295
2296        let warnings = rule.check(&ctx).unwrap();
2297        assert!(warnings[0].fix.is_none(), "No fix should be offered");
2298    }
2299
2300    #[test]
2301    fn test_fix_promote_title_at_eof_no_trailing_newline() {
2302        use crate::rule::Rule;
2303        let rule = MD041FirstLineHeading {
2304            level: 1,
2305            front_matter_title: false,
2306            front_matter_title_pattern: None,
2307            allow_preamble: false,
2308            fix_enabled: true,
2309        };
2310
2311        // Single title line at EOF with no trailing newline
2312        let content = "My Project";
2313        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2314        let fixed = rule.fix(&ctx).unwrap();
2315        assert_eq!(fixed, "# My Project", "Should promote title at EOF");
2316    }
2317
2318    // ── Phase 3 (Case B): InsertDerived ─────────────────────────────────────────
2319
2320    #[test]
2321    fn test_fix_insert_derived_directive_only_document() {
2322        use crate::rule::Rule;
2323        use std::path::PathBuf;
2324        let rule = MD041FirstLineHeading {
2325            level: 1,
2326            front_matter_title: false,
2327            front_matter_title_pattern: None,
2328            allow_preamble: false,
2329            fix_enabled: true,
2330        };
2331
2332        // Document with only a note admonition and no heading
2333        // (LintContext constructed with a source file path for title derivation)
2334        let content = "!!! note\n    This is a note.\n";
2335        let ctx = LintContext::new(
2336            content,
2337            crate::config::MarkdownFlavor::MkDocs,
2338            Some(PathBuf::from("setup-guide.md")),
2339        );
2340
2341        let can_fix = rule.can_fix(&ctx);
2342        assert!(can_fix, "Directive-only document with source file should be fixable");
2343
2344        let fixed = rule.fix(&ctx).unwrap();
2345        assert!(
2346            fixed.starts_with("# Setup Guide\n"),
2347            "Should insert derived heading, got: {fixed}"
2348        );
2349    }
2350
2351    #[test]
2352    fn test_fix_no_insert_derived_without_source_file() {
2353        use crate::rule::Rule;
2354        let rule = MD041FirstLineHeading {
2355            level: 1,
2356            front_matter_title: false,
2357            front_matter_title_pattern: None,
2358            allow_preamble: false,
2359            fix_enabled: true,
2360        };
2361
2362        // No source_file → derive_title returns None → InsertDerived unavailable
2363        let content = "!!! note\n    This is a note.\n";
2364        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
2365        let fixed = rule.fix(&ctx).unwrap();
2366        assert_eq!(fixed, content, "Without a source file, cannot derive a title");
2367    }
2368
2369    #[test]
2370    fn test_fix_no_insert_derived_when_has_real_content() {
2371        use crate::rule::Rule;
2372        use std::path::PathBuf;
2373        let rule = MD041FirstLineHeading {
2374            level: 1,
2375            front_matter_title: false,
2376            front_matter_title_pattern: None,
2377            allow_preamble: false,
2378            fix_enabled: true,
2379        };
2380
2381        // Document has real paragraph content in addition to directive blocks
2382        let content = "!!! note\n    A note.\n\nSome paragraph text.\n";
2383        let ctx = LintContext::new(
2384            content,
2385            crate::config::MarkdownFlavor::MkDocs,
2386            Some(PathBuf::from("guide.md")),
2387        );
2388        let fixed = rule.fix(&ctx).unwrap();
2389        assert_eq!(
2390            fixed, content,
2391            "Should not insert derived heading when real content is present"
2392        );
2393    }
2394
2395    #[test]
2396    fn test_derive_title_converts_kebab_case() {
2397        use std::path::PathBuf;
2398        let ctx = LintContext::new(
2399            "",
2400            crate::config::MarkdownFlavor::Standard,
2401            Some(PathBuf::from("my-setup-guide.md")),
2402        );
2403        let title = MD041FirstLineHeading::derive_title(&ctx);
2404        assert_eq!(title, Some("My Setup Guide".to_string()));
2405    }
2406
2407    #[test]
2408    fn test_derive_title_converts_underscores() {
2409        use std::path::PathBuf;
2410        let ctx = LintContext::new(
2411            "",
2412            crate::config::MarkdownFlavor::Standard,
2413            Some(PathBuf::from("api_reference.md")),
2414        );
2415        let title = MD041FirstLineHeading::derive_title(&ctx);
2416        assert_eq!(title, Some("Api Reference".to_string()));
2417    }
2418
2419    #[test]
2420    fn test_derive_title_none_without_source_file() {
2421        let ctx = LintContext::new("", crate::config::MarkdownFlavor::Standard, None);
2422        let title = MD041FirstLineHeading::derive_title(&ctx);
2423        assert_eq!(title, None);
2424    }
2425
2426    #[test]
2427    fn test_derive_title_index_file_uses_parent_dir() {
2428        use std::path::PathBuf;
2429        let ctx = LintContext::new(
2430            "",
2431            crate::config::MarkdownFlavor::Standard,
2432            Some(PathBuf::from("docs/getting-started/index.md")),
2433        );
2434        let title = MD041FirstLineHeading::derive_title(&ctx);
2435        assert_eq!(title, Some("Getting Started".to_string()));
2436    }
2437
2438    #[test]
2439    fn test_derive_title_readme_file_uses_parent_dir() {
2440        use std::path::PathBuf;
2441        let ctx = LintContext::new(
2442            "",
2443            crate::config::MarkdownFlavor::Standard,
2444            Some(PathBuf::from("my-project/README.md")),
2445        );
2446        let title = MD041FirstLineHeading::derive_title(&ctx);
2447        assert_eq!(title, Some("My Project".to_string()));
2448    }
2449
2450    #[test]
2451    fn test_derive_title_index_without_parent_returns_none() {
2452        use std::path::PathBuf;
2453        // Root-level index.md has no meaningful parent — "Index" is not a useful title
2454        let ctx = LintContext::new(
2455            "",
2456            crate::config::MarkdownFlavor::Standard,
2457            Some(PathBuf::from("index.md")),
2458        );
2459        let title = MD041FirstLineHeading::derive_title(&ctx);
2460        assert_eq!(title, None);
2461    }
2462
2463    #[test]
2464    fn test_derive_title_readme_without_parent_returns_none() {
2465        use std::path::PathBuf;
2466        let ctx = LintContext::new(
2467            "",
2468            crate::config::MarkdownFlavor::Standard,
2469            Some(PathBuf::from("README.md")),
2470        );
2471        let title = MD041FirstLineHeading::derive_title(&ctx);
2472        assert_eq!(title, None);
2473    }
2474
2475    #[test]
2476    fn test_derive_title_readme_case_insensitive() {
2477        use std::path::PathBuf;
2478        // Lowercase readme.md should also use parent dir
2479        let ctx = LintContext::new(
2480            "",
2481            crate::config::MarkdownFlavor::Standard,
2482            Some(PathBuf::from("docs/api/readme.md")),
2483        );
2484        let title = MD041FirstLineHeading::derive_title(&ctx);
2485        assert_eq!(title, Some("Api".to_string()));
2486    }
2487
2488    #[test]
2489    fn test_is_title_candidate_basic() {
2490        assert!(MD041FirstLineHeading::is_title_candidate("My Project", true));
2491        assert!(MD041FirstLineHeading::is_title_candidate("Getting Started", true));
2492        assert!(MD041FirstLineHeading::is_title_candidate("API Reference", true));
2493    }
2494
2495    #[test]
2496    fn test_is_title_candidate_rejects_sentence_punctuation() {
2497        assert!(!MD041FirstLineHeading::is_title_candidate("This is a sentence.", true));
2498        assert!(!MD041FirstLineHeading::is_title_candidate("Is this correct?", true));
2499        assert!(!MD041FirstLineHeading::is_title_candidate("Note:", true));
2500        assert!(!MD041FirstLineHeading::is_title_candidate("Stop!", true));
2501        assert!(!MD041FirstLineHeading::is_title_candidate("Step 1;", true));
2502    }
2503
2504    #[test]
2505    fn test_is_title_candidate_rejects_when_no_blank_after() {
2506        assert!(!MD041FirstLineHeading::is_title_candidate("My Project", false));
2507    }
2508
2509    #[test]
2510    fn test_is_title_candidate_rejects_long_lines() {
2511        let long = "A".repeat(81);
2512        assert!(!MD041FirstLineHeading::is_title_candidate(&long, true));
2513        // 80 chars is the boundary – exactly 80 is OK
2514        let ok = "A".repeat(80);
2515        assert!(MD041FirstLineHeading::is_title_candidate(&ok, true));
2516    }
2517
2518    #[test]
2519    fn test_is_title_candidate_rejects_structural_markdown() {
2520        assert!(!MD041FirstLineHeading::is_title_candidate("# Heading", true));
2521        assert!(!MD041FirstLineHeading::is_title_candidate("- list item", true));
2522        assert!(!MD041FirstLineHeading::is_title_candidate("* bullet", true));
2523        assert!(!MD041FirstLineHeading::is_title_candidate("> blockquote", true));
2524    }
2525
2526    #[test]
2527    fn test_fix_replacement_not_empty_for_plain_text_promotion() {
2528        // Verify that the fix replacement for plain-text-to-heading promotion is
2529        // non-empty, so applying the fix does not delete the line.
2530        let rule = MD041FirstLineHeading::with_pattern(1, false, None, true);
2531        // Title candidate: short text, no trailing punctuation, followed by blank line
2532        let content = "My Document Title\n\nMore content follows.";
2533        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2534        let warnings = rule.check(&ctx).unwrap();
2535        assert_eq!(warnings.len(), 1);
2536        let fix = warnings[0]
2537            .fix
2538            .as_ref()
2539            .expect("Fix should be present for promotable text");
2540        assert!(
2541            !fix.replacement.is_empty(),
2542            "Fix replacement must not be empty — applying it directly must produce valid output"
2543        );
2544        assert!(
2545            fix.replacement.starts_with("# "),
2546            "Fix replacement should be a level-1 heading, got: {:?}",
2547            fix.replacement
2548        );
2549        assert_eq!(fix.replacement, "# My Document Title");
2550    }
2551
2552    #[test]
2553    fn test_fix_replacement_not_empty_for_releveling() {
2554        // When the first line is a heading at the wrong level, the Fix should
2555        // contain the correctly-leveled heading, not an empty string.
2556        let rule = MD041FirstLineHeading::with_pattern(1, false, None, true);
2557        let content = "## Wrong Level\n\nContent.";
2558        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2559        let warnings = rule.check(&ctx).unwrap();
2560        assert_eq!(warnings.len(), 1);
2561        let fix = warnings[0].fix.as_ref().expect("Fix should be present for releveling");
2562        assert!(
2563            !fix.replacement.is_empty(),
2564            "Fix replacement must not be empty for releveling"
2565        );
2566        assert_eq!(fix.replacement, "# Wrong Level");
2567    }
2568
2569    #[test]
2570    fn test_fix_replacement_applied_produces_valid_output() {
2571        // Verify that applying the Fix from check() produces the same result as fix()
2572        let rule = MD041FirstLineHeading::with_pattern(1, false, None, true);
2573        // Title candidate: short, no trailing punctuation, followed by blank line
2574        let content = "My Document\n\nMore content.";
2575        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2576
2577        let warnings = rule.check(&ctx).unwrap();
2578        assert_eq!(warnings.len(), 1);
2579        let fix = warnings[0].fix.as_ref().expect("Fix should be present");
2580
2581        // Apply Fix directly (like LSP would)
2582        let mut patched = content.to_string();
2583        patched.replace_range(fix.range.clone(), &fix.replacement);
2584
2585        // Apply via fix() method
2586        let fixed = rule.fix(&ctx).unwrap();
2587
2588        assert_eq!(patched, fixed, "Applying Fix directly should match fix() output");
2589    }
2590
2591    #[test]
2592    fn test_mdx_disable_on_line_1_no_heading() {
2593        // The exact user scenario from issue #538:
2594        // MDX disable comment on line 1, NO heading anywhere.
2595        // The disable is the ONLY reason MD041 should not fire.
2596        let content = "{/* <!-- rumdl-disable MD041 MD034 --> */}\n<Note>\nThis documentation is linted with http://rumdl.dev/\n</Note>";
2597        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
2598
2599        // check() should produce a warning on line 2 (<Note> is the first content line)
2600        let rule = MD041FirstLineHeading::default();
2601        let warnings = rule.check(&ctx).unwrap();
2602        // The rule itself produces a warning, but the engine filters it via inline config.
2603        // MD041's check() doesn't filter inline config itself — the engine does.
2604        // What matters is that the warning is on line 2 (not line 1), so the engine
2605        // can see the disable is active at line 2 and suppress it.
2606        if !warnings.is_empty() {
2607            assert_eq!(
2608                warnings[0].line, 2,
2609                "Warning must be on line 2 (first content line after MDX comment), not line 1"
2610            );
2611        }
2612    }
2613
2614    #[test]
2615    fn test_mdx_disable_fix_returns_unchanged() {
2616        // fix() should return content unchanged when MDX disable is active
2617        let content = "{/* <!-- rumdl-disable MD041 --> */}\n<Note>\nContent\n</Note>";
2618        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
2619        let rule = MD041FirstLineHeading {
2620            fix_enabled: true,
2621            ..MD041FirstLineHeading::default()
2622        };
2623        let result = rule.fix(&ctx).unwrap();
2624        assert_eq!(
2625            result, content,
2626            "fix() should not modify content when MD041 is disabled via MDX comment"
2627        );
2628    }
2629
2630    #[test]
2631    fn test_mdx_comment_without_disable_heading_on_next_line() {
2632        let rule = MD041FirstLineHeading::default();
2633
2634        // MDX comment (not a disable directive) on line 1, heading on line 2
2635        let content = "{/* Some MDX comment */}\n# My Document\n\nContent.";
2636        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
2637        let result = rule.check(&ctx).unwrap();
2638        assert!(
2639            result.is_empty(),
2640            "MDX comment is preamble; heading on next line should satisfy MD041"
2641        );
2642    }
2643
2644    #[test]
2645    fn test_mdx_comment_without_heading_triggers_warning() {
2646        let rule = MD041FirstLineHeading::default();
2647
2648        // MDX comment on line 1, non-heading content on line 2
2649        let content = "{/* Some MDX comment */}\nThis is not a heading\n\nContent.";
2650        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
2651        let result = rule.check(&ctx).unwrap();
2652        assert_eq!(
2653            result.len(),
2654            1,
2655            "MDX comment followed by non-heading should trigger MD041"
2656        );
2657        assert_eq!(
2658            result[0].line, 2,
2659            "Warning should be on line 2 (the first content line after MDX comment)"
2660        );
2661    }
2662
2663    #[test]
2664    fn test_multiline_mdx_comment_followed_by_heading() {
2665        let rule = MD041FirstLineHeading::default();
2666
2667        // Multi-line MDX comment followed by heading
2668        let content = "{/*\nSome multi-line\nMDX comment\n*/}\n# My Document\n\nContent.";
2669        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
2670        let result = rule.check(&ctx).unwrap();
2671        assert!(
2672            result.is_empty(),
2673            "Multi-line MDX comment should be preamble; heading after it satisfies MD041"
2674        );
2675    }
2676
2677    #[test]
2678    fn test_html_comment_still_works_as_preamble_regression() {
2679        let rule = MD041FirstLineHeading::default();
2680
2681        // Plain HTML comment on line 1, heading on line 2
2682        let content = "<!-- Some comment -->\n# My Document\n\nContent.";
2683        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2684        let result = rule.check(&ctx).unwrap();
2685        assert!(
2686            result.is_empty(),
2687            "HTML comment should still be treated as preamble (regression test)"
2688        );
2689    }
2690}