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