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 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 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 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 FrontMatterUtils::has_front_matter_field(content, "title:")
124 }
125
126 fn is_non_content_line(line: &str) -> bool {
128 let trimmed = line.trim();
129
130 if trimmed.starts_with('[') && trimmed.contains("]: ") {
132 return true;
133 }
134
135 if trimmed.starts_with('*') && trimmed.contains("]: ") {
137 return true;
138 }
139
140 if Self::is_badge_image_line(trimmed) {
143 return true;
144 }
145
146 false
147 }
148
149 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 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 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 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 fn is_badge_image_line(line: &str) -> bool {
249 if line.is_empty() {
250 return false;
251 }
252
253 if !line.starts_with('!') && !line.starts_with('[') {
255 return false;
256 }
257
258 let mut remaining = line;
260 while !remaining.is_empty() {
261 remaining = remaining.trim_start();
262 if remaining.is_empty() {
263 break;
264 }
265
266 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 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 return false;
286 }
287
288 true
289 }
290
291 fn find_image_end(s: &str) -> Option<usize> {
293 if !s.starts_with("![") {
294 return None;
295 }
296 let alt_end = s[2..].find("](")?;
298 let paren_start = 2 + alt_end + 2; let paren_end = s[paren_start..].find(')')?;
301 Some(paren_start + paren_end + 1)
302 }
303
304 fn find_linked_image_end(s: &str) -> Option<usize> {
306 if !s.starts_with("[![") {
307 return None;
308 }
309 let inner_end = Self::find_image_end(&s[1..])?;
311 let after_inner = 1 + inner_end;
312 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 fn fix_heading_level(&self, line: &str, _current_level: usize, target_level: usize) -> String {
323 let trimmed = line.trim_start();
324
325 if trimmed.starts_with('#') {
327 let hashes = "#".repeat(target_level);
328 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 let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();
335 format!("{leading_ws}{hashes} {content}")
336 } else {
337 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 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 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 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 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 fn is_html_heading(ctx: &crate::lint_context::LintContext, first_line_idx: usize, level: usize) -> bool {
419 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 let html_tags = ctx.html_tags();
430 let target_tag = format!("h{level}");
431
432 let opening_index = html_tags.iter().position(|tag| {
434 tag.line == first_line_idx + 1 && 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 let mut depth = 1usize;
446 for tag in html_tags.iter().skip(open_idx + 1) {
447 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 fn analyze_for_fix(&self, ctx: &crate::lint_context::LintContext) -> Option<FixPlan> {
469 if ctx.lines.is_empty() {
470 return None;
471 }
472
473 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 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 let mut found_heading: Option<(usize, bool, usize)> = None;
503 let mut first_title_candidate: Option<(usize, String)> = None;
505 let mut found_non_title_content = false;
507 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 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 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 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 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 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; }
584
585 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 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 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 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 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 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 Self::is_html_heading(ctx, first_line_idx, self.level)
653 };
654
655 if !is_correct_heading {
656 let first_line = first_line_idx + 1; 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 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 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 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 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 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 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
870 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 (t.starts_with("{{#") && t.ends_with("}}"))
879 || (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 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 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 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 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 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 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); 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 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 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); }
1019
1020 #[test]
1021 fn test_front_matter_disabled() {
1022 let rule = MD041FirstLineHeading::new(1, false);
1023
1024 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); }
1031
1032 #[test]
1033 fn test_html_comments_before_heading() {
1034 let rule = MD041FirstLineHeading::default();
1035
1036 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 for level in 1..=6 {
1460 let rule = MD041FirstLineHeading::new(level, false);
1461
1462 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 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 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 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 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 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 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 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 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 for level in 1..=6 {
1579 let rule = MD041FirstLineHeading::new(level, false);
1580
1581 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 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 let content = "\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 let content = " \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 let content = "[](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 let content = "[](https://crates.io)\n[](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 let content = "\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 let content = " 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 assert!(MD041FirstLineHeading::is_badge_image_line(""));
1683 assert!(MD041FirstLineHeading::is_badge_image_line("[](link)"));
1684 assert!(MD041FirstLineHeading::is_badge_image_line(" "));
1685 assert!(MD041FirstLineHeading::is_badge_image_line("[](c) [](f)"));
1686
1687 assert!(!MD041FirstLineHeading::is_badge_image_line(""));
1689 assert!(!MD041FirstLineHeading::is_badge_image_line("Some text"));
1690 assert!(!MD041FirstLineHeading::is_badge_image_line(" text"));
1691 assert!(!MD041FirstLineHeading::is_badge_image_line("# Heading"));
1692 }
1693
1694 #[test]
1698 fn test_mkdocs_anchor_before_heading_in_mkdocs_flavor() {
1699 let rule = MD041FirstLineHeading::default();
1700
1701 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 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 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 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 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 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 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 #[test]
1800 fn test_fix_disabled_by_default() {
1801 use crate::rule::Rule;
1802 let rule = MD041FirstLineHeading::default();
1803
1804 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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 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 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 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 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 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 #[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 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 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 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 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 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 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 let rule = MD041FirstLineHeading::with_pattern(1, false, None, true);
2531 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 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 let rule = MD041FirstLineHeading::with_pattern(1, false, None, true);
2573 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 let mut patched = content.to_string();
2583 patched.replace_range(fix.range.clone(), &fix.replacement);
2584
2585 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 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 let rule = MD041FirstLineHeading::default();
2601 let warnings = rule.check(&ctx).unwrap();
2602 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 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 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 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 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 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}