1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, Severity};
15use crate::utils::range_utils::LineIndex;
16use regex::Regex;
17use std::collections::HashSet;
18use std::ops::Range;
19use std::sync::LazyLock;
20
21mod md063_config;
22pub use md063_config::{HeadingCapStyle, MD063Config};
23
24static INLINE_CODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`+[^`]+`+").unwrap());
26
27static LINK_REGEX: LazyLock<Regex> =
29 LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\([^)]*\)|\[([^\]]*)\]\[[^\]]*\]").unwrap());
30
31static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
36 let tags = "kbd|abbr|code|span|sub|sup|mark|cite|dfn|var|samp|small|strong|em|b|i|u|s|q|br|wbr";
38 let pattern = format!(r"<({tags})(?:\s[^>]*)?>.*?</({tags})>|<({tags})(?:\s[^>]*)?\s*/?>");
39 Regex::new(&pattern).unwrap()
40});
41
42static CUSTOM_ID_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s*\{#[^}]+\}\s*$").unwrap());
44
45#[derive(Debug, Clone)]
47enum HeadingSegment {
48 Text(String),
50 Code(String),
52 Link {
54 full: String,
55 text_start: usize,
56 text_end: usize,
57 },
58 Html(String),
60}
61
62#[derive(Clone)]
64pub struct MD063HeadingCapitalization {
65 config: MD063Config,
66 lowercase_set: HashSet<String>,
67 proper_names: Vec<String>,
70}
71
72impl Default for MD063HeadingCapitalization {
73 fn default() -> Self {
74 Self::new()
75 }
76}
77
78impl MD063HeadingCapitalization {
79 pub fn new() -> Self {
80 let config = MD063Config::default();
81 let lowercase_set = config.lowercase_words.iter().cloned().collect();
82 Self {
83 config,
84 lowercase_set,
85 proper_names: Vec::new(),
86 }
87 }
88
89 pub fn from_config_struct(config: MD063Config) -> Self {
90 let lowercase_set = config.lowercase_words.iter().cloned().collect();
91 Self {
92 config,
93 lowercase_set,
94 proper_names: Vec::new(),
95 }
96 }
97
98 fn match_case_insensitive_at(text: &str, start: usize, pattern_lower: &str) -> Option<usize> {
105 if start > text.len() || !text.is_char_boundary(start) || pattern_lower.is_empty() {
106 return None;
107 }
108
109 let mut matched_bytes = 0;
110
111 for (offset, ch) in text[start..].char_indices() {
112 if matched_bytes >= pattern_lower.len() {
113 break;
114 }
115
116 let lowered: String = ch.to_lowercase().collect();
117 if !pattern_lower[matched_bytes..].starts_with(&lowered) {
118 return None;
119 }
120
121 matched_bytes += lowered.len();
122
123 if matched_bytes == pattern_lower.len() {
124 return Some(start + offset + ch.len_utf8());
125 }
126 }
127
128 None
129 }
130
131 fn find_case_insensitive_match(text: &str, pattern_lower: &str, search_start: usize) -> Option<(usize, usize)> {
134 if pattern_lower.is_empty() || search_start >= text.len() || !text.is_char_boundary(search_start) {
135 return None;
136 }
137
138 for (offset, _) in text[search_start..].char_indices() {
139 let start = search_start + offset;
140 if let Some(end) = Self::match_case_insensitive_at(text, start, pattern_lower) {
141 return Some((start, end));
142 }
143 }
144
145 None
146 }
147
148 fn proper_name_canonical_forms(&self, text: &str) -> std::collections::HashMap<usize, &str> {
154 let mut map = std::collections::HashMap::new();
155
156 for name in &self.proper_names {
157 if name.is_empty() {
158 continue;
159 }
160 let name_lower = name.to_lowercase();
161 let canonical_words: Vec<&str> = name.split_whitespace().collect();
162 if canonical_words.is_empty() {
163 continue;
164 }
165 let mut search_start = 0;
166
167 while search_start < text.len() {
168 let Some((abs_pos, end_pos)) = Self::find_case_insensitive_match(text, &name_lower, search_start)
169 else {
170 break;
171 };
172
173 let before_ok = abs_pos == 0 || !text[..abs_pos].chars().last().is_some_and(|c| c.is_alphanumeric());
175 let after_ok =
176 end_pos >= text.len() || !text[end_pos..].chars().next().is_some_and(|c| c.is_alphanumeric());
177
178 if before_ok && after_ok {
179 let text_slice = &text[abs_pos..end_pos];
183 let mut word_idx = 0;
184 let mut slice_offset = 0;
185
186 for text_word in text_slice.split_whitespace() {
187 if let Some(w_rel) = text_slice[slice_offset..].find(text_word) {
188 let word_abs = abs_pos + slice_offset + w_rel;
189 if let Some(&canonical_word) = canonical_words.get(word_idx) {
190 map.insert(word_abs, canonical_word);
191 }
192 slice_offset += w_rel + text_word.len();
193 word_idx += 1;
194 }
195 }
196 }
197
198 search_start = abs_pos + text[abs_pos..].chars().next().map_or(1, |c| c.len_utf8());
201 }
202 }
203
204 map
205 }
206
207 fn has_internal_capitals(&self, word: &str) -> bool {
209 let chars: Vec<char> = word.chars().collect();
210 if chars.len() < 2 {
211 return false;
212 }
213
214 let first = chars[0];
215 let rest = &chars[1..];
216 let has_upper_in_rest = rest.iter().any(|c| c.is_uppercase());
217 let has_lower_in_rest = rest.iter().any(|c| c.is_lowercase());
218
219 if has_upper_in_rest && has_lower_in_rest {
221 return true;
222 }
223
224 if first.is_lowercase() && has_upper_in_rest {
226 return true;
227 }
228
229 false
230 }
231
232 fn is_all_caps_acronym(&self, word: &str) -> bool {
236 if word.len() < 2 {
238 return false;
239 }
240
241 let mut consecutive_upper = 0;
242 let mut max_consecutive = 0;
243
244 for c in word.chars() {
245 if c.is_uppercase() {
246 consecutive_upper += 1;
247 max_consecutive = max_consecutive.max(consecutive_upper);
248 } else if c.is_lowercase() {
249 return false;
251 } else {
252 consecutive_upper = 0;
254 }
255 }
256
257 max_consecutive >= 2
259 }
260
261 fn should_preserve_word(&self, word: &str) -> bool {
263 if self.config.ignore_words.iter().any(|w| w == word) {
265 return true;
266 }
267
268 if self.config.preserve_cased_words && self.has_internal_capitals(word) {
270 return true;
271 }
272
273 if self.config.preserve_cased_words && self.is_all_caps_acronym(word) {
275 return true;
276 }
277
278 if self.is_caret_notation(word) {
280 return true;
281 }
282
283 false
284 }
285
286 fn is_caret_notation(&self, word: &str) -> bool {
288 let chars: Vec<char> = word.chars().collect();
289 if chars.len() >= 2 && chars[0] == '^' {
291 let second = chars[1];
292 if second.is_ascii_uppercase() || "@[\\]^_".contains(second) {
294 return true;
295 }
296 }
297 false
298 }
299
300 fn is_lowercase_word(&self, word: &str) -> bool {
302 self.lowercase_set.contains(&word.to_lowercase())
303 }
304
305 fn title_case_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
307 if word.is_empty() {
308 return word.to_string();
309 }
310
311 if self.should_preserve_word(word) {
313 return word.to_string();
314 }
315
316 if is_first || is_last {
318 return self.capitalize_first(word);
319 }
320
321 if self.is_lowercase_word(word) {
323 return Self::lowercase_preserving_composition(word);
324 }
325
326 self.capitalize_first(word)
328 }
329
330 fn apply_canonical_form_to_word(word: &str, canonical: &str) -> String {
333 let canonical_lower = canonical.to_lowercase();
334 if canonical_lower.is_empty() {
335 return canonical.to_string();
336 }
337
338 if let Some(end_pos) = Self::match_case_insensitive_at(word, 0, &canonical_lower) {
339 let mut out = String::with_capacity(canonical.len() + word.len().saturating_sub(end_pos));
340 out.push_str(canonical);
341 out.push_str(&word[end_pos..]);
342 out
343 } else {
344 canonical.to_string()
345 }
346 }
347
348 fn capitalize_first(&self, word: &str) -> String {
350 if word.is_empty() {
351 return String::new();
352 }
353
354 let first_alpha_pos = word.find(|c: char| c.is_alphabetic());
356 let Some(pos) = first_alpha_pos else {
357 return word.to_string();
358 };
359
360 let prefix = &word[..pos];
361 let mut chars = word[pos..].chars();
362 let first = chars.next().unwrap();
363 let first_upper = Self::uppercase_preserving_composition(&first.to_string());
366 let rest: String = chars.collect();
367 let rest_lower = Self::lowercase_preserving_composition(&rest);
368 format!("{prefix}{first_upper}{rest_lower}")
369 }
370
371 fn lowercase_preserving_composition(s: &str) -> String {
374 let mut result = String::with_capacity(s.len());
375 for c in s.chars() {
376 let lower: String = c.to_lowercase().collect();
377 if lower.chars().count() == 1 {
378 result.push_str(&lower);
379 } else {
380 result.push(c);
382 }
383 }
384 result
385 }
386
387 fn uppercase_preserving_composition(s: &str) -> String {
392 let mut result = String::with_capacity(s.len());
393 for c in s.chars() {
394 let upper: String = c.to_uppercase().collect();
395 if upper.chars().count() == 1 {
396 result.push_str(&upper);
397 } else {
398 result.push(c);
400 }
401 }
402 result
403 }
404
405 fn apply_title_case(&self, text: &str) -> String {
409 let canonical_forms = self.proper_name_canonical_forms(text);
410
411 let original_words: Vec<&str> = text.split_whitespace().collect();
412 let total_words = original_words.len();
413
414 let mut word_positions: Vec<usize> = Vec::with_capacity(original_words.len());
417 let mut pos = 0;
418 for word in &original_words {
419 if let Some(rel) = text[pos..].find(word) {
420 word_positions.push(pos + rel);
421 pos = pos + rel + word.len();
422 } else {
423 word_positions.push(usize::MAX);
424 }
425 }
426
427 let result_words: Vec<String> = original_words
428 .iter()
429 .enumerate()
430 .map(|(i, word)| {
431 let is_first = i == 0;
432 let is_last = i == total_words - 1;
433
434 if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
436 return Self::apply_canonical_form_to_word(word, canonical);
437 }
438
439 if self.should_preserve_word(word) {
441 return (*word).to_string();
442 }
443
444 if word.contains('-') {
446 return self.handle_hyphenated_word(word, is_first, is_last);
447 }
448
449 self.title_case_word(word, is_first, is_last)
450 })
451 .collect();
452
453 result_words.join(" ")
454 }
455
456 fn handle_hyphenated_word(&self, word: &str, is_first: bool, is_last: bool) -> String {
458 let parts: Vec<&str> = word.split('-').collect();
459 let total_parts = parts.len();
460
461 let result_parts: Vec<String> = parts
462 .iter()
463 .enumerate()
464 .map(|(i, part)| {
465 let part_is_first = is_first && i == 0;
467 let part_is_last = is_last && i == total_parts - 1;
468 self.title_case_word(part, part_is_first, part_is_last)
469 })
470 .collect();
471
472 result_parts.join("-")
473 }
474
475 fn apply_sentence_case(&self, text: &str) -> String {
477 if text.is_empty() {
478 return text.to_string();
479 }
480
481 let canonical_forms = self.proper_name_canonical_forms(text);
482 let mut result = String::new();
483 let mut current_pos = 0;
484 let mut is_first_word = true;
485
486 for word in text.split_whitespace() {
488 if let Some(pos) = text[current_pos..].find(word) {
489 let abs_pos = current_pos + pos;
490
491 result.push_str(&text[current_pos..abs_pos]);
493
494 if let Some(&canonical) = canonical_forms.get(&abs_pos) {
497 result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
498 is_first_word = false;
499 } else if is_first_word {
500 if self.should_preserve_word(word) {
502 result.push_str(word);
504 } else {
505 let mut chars = word.chars();
507 if let Some(first) = chars.next() {
508 result.push_str(&Self::uppercase_preserving_composition(&first.to_string()));
509 let rest: String = chars.collect();
510 result.push_str(&Self::lowercase_preserving_composition(&rest));
511 }
512 }
513 is_first_word = false;
514 } else {
515 if self.should_preserve_word(word) {
517 result.push_str(word);
518 } else {
519 result.push_str(&Self::lowercase_preserving_composition(word));
520 }
521 }
522
523 current_pos = abs_pos + word.len();
524 }
525 }
526
527 if current_pos < text.len() {
529 result.push_str(&text[current_pos..]);
530 }
531
532 result
533 }
534
535 fn apply_all_caps(&self, text: &str) -> String {
537 if text.is_empty() {
538 return text.to_string();
539 }
540
541 let canonical_forms = self.proper_name_canonical_forms(text);
542 let mut result = String::new();
543 let mut current_pos = 0;
544
545 for word in text.split_whitespace() {
547 if let Some(pos) = text[current_pos..].find(word) {
548 let abs_pos = current_pos + pos;
549
550 result.push_str(&text[current_pos..abs_pos]);
552
553 if let Some(&canonical) = canonical_forms.get(&abs_pos) {
556 result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
557 } else if self.should_preserve_word(word) {
558 result.push_str(word);
559 } else {
560 result.push_str(&Self::uppercase_preserving_composition(word));
561 }
562
563 current_pos = abs_pos + word.len();
564 }
565 }
566
567 if current_pos < text.len() {
569 result.push_str(&text[current_pos..]);
570 }
571
572 result
573 }
574
575 fn parse_segments(&self, text: &str) -> Vec<HeadingSegment> {
577 let mut segments = Vec::new();
578 let mut last_end = 0;
579
580 let mut special_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();
582
583 for mat in INLINE_CODE_REGEX.find_iter(text) {
585 special_regions.push((mat.start(), mat.end(), HeadingSegment::Code(mat.as_str().to_string())));
586 }
587
588 for caps in LINK_REGEX.captures_iter(text) {
590 let full_match = caps.get(0).unwrap();
591 let text_match = caps.get(1).or_else(|| caps.get(2));
592
593 if let Some(text_m) = text_match {
594 special_regions.push((
595 full_match.start(),
596 full_match.end(),
597 HeadingSegment::Link {
598 full: full_match.as_str().to_string(),
599 text_start: text_m.start() - full_match.start(),
600 text_end: text_m.end() - full_match.start(),
601 },
602 ));
603 }
604 }
605
606 for mat in HTML_TAG_REGEX.find_iter(text) {
608 special_regions.push((mat.start(), mat.end(), HeadingSegment::Html(mat.as_str().to_string())));
609 }
610
611 special_regions.sort_by_key(|(start, _, _)| *start);
613
614 let mut filtered_regions: Vec<(usize, usize, HeadingSegment)> = Vec::new();
616 for region in special_regions {
617 let overlaps = filtered_regions.iter().any(|(s, e, _)| region.0 < *e && region.1 > *s);
618 if !overlaps {
619 filtered_regions.push(region);
620 }
621 }
622
623 for (start, end, segment) in filtered_regions {
625 if start > last_end {
627 let text_segment = &text[last_end..start];
628 if !text_segment.is_empty() {
629 segments.push(HeadingSegment::Text(text_segment.to_string()));
630 }
631 }
632 segments.push(segment);
633 last_end = end;
634 }
635
636 if last_end < text.len() {
638 let remaining = &text[last_end..];
639 if !remaining.is_empty() {
640 segments.push(HeadingSegment::Text(remaining.to_string()));
641 }
642 }
643
644 if segments.is_empty() && !text.is_empty() {
646 segments.push(HeadingSegment::Text(text.to_string()));
647 }
648
649 segments
650 }
651
652 fn apply_capitalization(&self, text: &str) -> String {
654 let (main_text, custom_id) = if let Some(mat) = CUSTOM_ID_REGEX.find(text) {
656 (&text[..mat.start()], Some(mat.as_str()))
657 } else {
658 (text, None)
659 };
660
661 let segments = self.parse_segments(main_text);
663
664 let text_segments: Vec<usize> = segments
666 .iter()
667 .enumerate()
668 .filter_map(|(i, s)| matches!(s, HeadingSegment::Text(_)).then_some(i))
669 .collect();
670
671 let first_segment_is_text = segments
675 .first()
676 .map(|s| matches!(s, HeadingSegment::Text(_)))
677 .unwrap_or(false);
678
679 let last_segment_is_text = segments
683 .last()
684 .map(|s| matches!(s, HeadingSegment::Text(_)))
685 .unwrap_or(false);
686
687 let mut result_parts: Vec<String> = Vec::new();
689
690 for (i, segment) in segments.iter().enumerate() {
691 match segment {
692 HeadingSegment::Text(t) => {
693 let is_first_text = text_segments.first() == Some(&i);
694 let is_last_text = text_segments.last() == Some(&i) && last_segment_is_text;
698
699 let capitalized = match self.config.style {
700 HeadingCapStyle::TitleCase => self.apply_title_case_segment(t, is_first_text, is_last_text),
701 HeadingCapStyle::SentenceCase => {
702 if is_first_text && first_segment_is_text {
706 self.apply_sentence_case(t)
707 } else {
708 self.apply_sentence_case_non_first(t)
710 }
711 }
712 HeadingCapStyle::AllCaps => self.apply_all_caps(t),
713 };
714 result_parts.push(capitalized);
715 }
716 HeadingSegment::Code(c) => {
717 result_parts.push(c.clone());
718 }
719 HeadingSegment::Link {
720 full,
721 text_start,
722 text_end,
723 } => {
724 let link_text = &full[*text_start..*text_end];
726 let capitalized_text = match self.config.style {
727 HeadingCapStyle::TitleCase => self.apply_title_case(link_text),
728 HeadingCapStyle::SentenceCase => self.apply_sentence_case_non_first(link_text),
731 HeadingCapStyle::AllCaps => self.apply_all_caps(link_text),
732 };
733
734 let mut new_link = String::new();
735 new_link.push_str(&full[..*text_start]);
736 new_link.push_str(&capitalized_text);
737 new_link.push_str(&full[*text_end..]);
738 result_parts.push(new_link);
739 }
740 HeadingSegment::Html(h) => {
741 result_parts.push(h.clone());
743 }
744 }
745 }
746
747 let mut result = result_parts.join("");
748
749 if let Some(id) = custom_id {
751 result.push_str(id);
752 }
753
754 result
755 }
756
757 fn apply_title_case_segment(&self, text: &str, is_first_segment: bool, is_last_segment: bool) -> String {
759 let canonical_forms = self.proper_name_canonical_forms(text);
760 let words: Vec<&str> = text.split_whitespace().collect();
761 let total_words = words.len();
762
763 if total_words == 0 {
764 return text.to_string();
765 }
766
767 let mut word_positions: Vec<usize> = Vec::with_capacity(words.len());
770 let mut pos = 0;
771 for word in &words {
772 if let Some(rel) = text[pos..].find(word) {
773 word_positions.push(pos + rel);
774 pos = pos + rel + word.len();
775 } else {
776 word_positions.push(usize::MAX);
777 }
778 }
779
780 let result_words: Vec<String> = words
781 .iter()
782 .enumerate()
783 .map(|(i, word)| {
784 let is_first = is_first_segment && i == 0;
785 let is_last = is_last_segment && i == total_words - 1;
786
787 if let Some(&canonical) = word_positions.get(i).and_then(|&p| canonical_forms.get(&p)) {
789 return Self::apply_canonical_form_to_word(word, canonical);
790 }
791
792 if word.contains('-') {
794 return self.handle_hyphenated_word(word, is_first, is_last);
795 }
796
797 self.title_case_word(word, is_first, is_last)
798 })
799 .collect();
800
801 let mut result = String::new();
803 let mut word_iter = result_words.iter();
804 let mut in_word = false;
805
806 for c in text.chars() {
807 if c.is_whitespace() {
808 if in_word {
809 in_word = false;
810 }
811 result.push(c);
812 } else if !in_word {
813 if let Some(word) = word_iter.next() {
814 result.push_str(word);
815 }
816 in_word = true;
817 }
818 }
819
820 result
821 }
822
823 fn apply_sentence_case_non_first(&self, text: &str) -> String {
825 if text.is_empty() {
826 return text.to_string();
827 }
828
829 let canonical_forms = self.proper_name_canonical_forms(text);
830 let mut result = String::new();
831 let mut current_pos = 0;
832
833 for word in text.split_whitespace() {
836 if let Some(pos) = text[current_pos..].find(word) {
837 let abs_pos = current_pos + pos;
838
839 result.push_str(&text[current_pos..abs_pos]);
841
842 if let Some(&canonical) = canonical_forms.get(&abs_pos) {
844 result.push_str(&Self::apply_canonical_form_to_word(word, canonical));
845 } else if self.should_preserve_word(word) {
846 result.push_str(word);
847 } else {
848 result.push_str(&Self::lowercase_preserving_composition(word));
849 }
850
851 current_pos = abs_pos + word.len();
852 }
853 }
854
855 if current_pos < text.len() {
857 result.push_str(&text[current_pos..]);
858 }
859
860 result
861 }
862
863 fn get_line_byte_range(&self, content: &str, line_num: usize, line_index: &LineIndex) -> Range<usize> {
865 let start_pos = line_index.get_line_start_byte(line_num).unwrap_or(content.len());
866 let line = content.lines().nth(line_num - 1).unwrap_or("");
867 Range {
868 start: start_pos,
869 end: start_pos + line.len(),
870 }
871 }
872
873 fn fix_atx_heading(&self, _line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
875 let indent = " ".repeat(heading.marker_column);
877 let hashes = "#".repeat(heading.level as usize);
878
879 let fixed_text = self.apply_capitalization(&heading.raw_text);
881
882 let closing = &heading.closing_sequence;
884 if heading.has_closing_sequence {
885 format!("{indent}{hashes} {fixed_text} {closing}")
886 } else {
887 format!("{indent}{hashes} {fixed_text}")
888 }
889 }
890
891 fn fix_setext_heading(&self, line: &str, heading: &crate::lint_context::HeadingInfo) -> String {
893 let fixed_text = self.apply_capitalization(&heading.raw_text);
895
896 let leading_ws: String = line.chars().take_while(|c| c.is_whitespace()).collect();
898
899 format!("{leading_ws}{fixed_text}")
900 }
901}
902
903impl Rule for MD063HeadingCapitalization {
904 fn name(&self) -> &'static str {
905 "MD063"
906 }
907
908 fn description(&self) -> &'static str {
909 "Heading capitalization"
910 }
911
912 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
913 !ctx.likely_has_headings() || !ctx.lines.iter().any(|line| line.heading.is_some())
914 }
915
916 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
917 let content = ctx.content;
918
919 if content.is_empty() {
920 return Ok(Vec::new());
921 }
922
923 let mut warnings = Vec::new();
924 let line_index = &ctx.line_index;
925
926 for (line_num, line_info) in ctx.lines.iter().enumerate() {
927 if let Some(heading) = &line_info.heading {
928 if heading.level < self.config.min_level || heading.level > self.config.max_level {
930 continue;
931 }
932
933 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
935 continue;
936 }
937
938 let original_text = &heading.raw_text;
940 let fixed_text = self.apply_capitalization(original_text);
941
942 if original_text != &fixed_text {
943 let line = line_info.content(ctx.content);
944 let style_name = match self.config.style {
945 HeadingCapStyle::TitleCase => "title case",
946 HeadingCapStyle::SentenceCase => "sentence case",
947 HeadingCapStyle::AllCaps => "ALL CAPS",
948 };
949
950 warnings.push(LintWarning {
951 rule_name: Some(self.name().to_string()),
952 line: line_num + 1,
953 column: heading.content_column + 1,
954 end_line: line_num + 1,
955 end_column: heading.content_column + 1 + original_text.len(),
956 message: format!("Heading should use {style_name}: '{original_text}' -> '{fixed_text}'"),
957 severity: Severity::Warning,
958 fix: Some(Fix {
959 range: self.get_line_byte_range(content, line_num + 1, line_index),
960 replacement: match heading.style {
961 crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
962 _ => self.fix_setext_heading(line, heading),
963 },
964 }),
965 });
966 }
967 }
968 }
969
970 Ok(warnings)
971 }
972
973 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
974 let content = ctx.content;
975
976 if content.is_empty() {
977 return Ok(content.to_string());
978 }
979
980 let lines = ctx.raw_lines();
981 let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
982
983 for (line_num, line_info) in ctx.lines.iter().enumerate() {
984 if let Some(heading) = &line_info.heading {
985 if heading.level < self.config.min_level || heading.level > self.config.max_level {
987 continue;
988 }
989
990 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
992 continue;
993 }
994
995 let original_text = &heading.raw_text;
996 let fixed_text = self.apply_capitalization(original_text);
997
998 if original_text != &fixed_text {
999 let line = line_info.content(ctx.content);
1000 fixed_lines[line_num] = match heading.style {
1001 crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
1002 _ => self.fix_setext_heading(line, heading),
1003 };
1004 }
1005 }
1006 }
1007
1008 let mut result = String::with_capacity(content.len());
1010 for (i, line) in fixed_lines.iter().enumerate() {
1011 result.push_str(line);
1012 if i < fixed_lines.len() - 1 || content.ends_with('\n') {
1013 result.push('\n');
1014 }
1015 }
1016
1017 Ok(result)
1018 }
1019
1020 fn as_any(&self) -> &dyn std::any::Any {
1021 self
1022 }
1023
1024 fn default_config_section(&self) -> Option<(String, toml::Value)> {
1025 let json_value = serde_json::to_value(&self.config).ok()?;
1026 Some((
1027 self.name().to_string(),
1028 crate::rule_config_serde::json_to_toml_value(&json_value)?,
1029 ))
1030 }
1031
1032 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
1033 where
1034 Self: Sized,
1035 {
1036 let rule_config = crate::rule_config_serde::load_rule_config::<MD063Config>(config);
1037 let md044_config =
1038 crate::rule_config_serde::load_rule_config::<crate::rules::md044_proper_names::MD044Config>(config);
1039 let mut rule = Self::from_config_struct(rule_config);
1040 rule.proper_names = md044_config.names;
1041 Box::new(rule)
1042 }
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047 use super::*;
1048 use crate::lint_context::LintContext;
1049
1050 fn create_rule() -> MD063HeadingCapitalization {
1051 let config = MD063Config {
1052 enabled: true,
1053 ..Default::default()
1054 };
1055 MD063HeadingCapitalization::from_config_struct(config)
1056 }
1057
1058 fn create_rule_with_style(style: HeadingCapStyle) -> MD063HeadingCapitalization {
1059 let config = MD063Config {
1060 enabled: true,
1061 style,
1062 ..Default::default()
1063 };
1064 MD063HeadingCapitalization::from_config_struct(config)
1065 }
1066
1067 #[test]
1069 fn test_title_case_basic() {
1070 let rule = create_rule();
1071 let content = "# hello world\n";
1072 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1073 let result = rule.check(&ctx).unwrap();
1074 assert_eq!(result.len(), 1);
1075 assert!(result[0].message.contains("Hello World"));
1076 }
1077
1078 #[test]
1079 fn test_title_case_lowercase_words() {
1080 let rule = create_rule();
1081 let content = "# the quick brown fox\n";
1082 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1083 let result = rule.check(&ctx).unwrap();
1084 assert_eq!(result.len(), 1);
1085 assert!(result[0].message.contains("The Quick Brown Fox"));
1087 }
1088
1089 #[test]
1090 fn test_title_case_already_correct() {
1091 let rule = create_rule();
1092 let content = "# The Quick Brown Fox\n";
1093 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1094 let result = rule.check(&ctx).unwrap();
1095 assert!(result.is_empty(), "Already correct heading should not be flagged");
1096 }
1097
1098 #[test]
1099 fn test_title_case_hyphenated() {
1100 let rule = create_rule();
1101 let content = "# self-documenting code\n";
1102 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1103 let result = rule.check(&ctx).unwrap();
1104 assert_eq!(result.len(), 1);
1105 assert!(result[0].message.contains("Self-Documenting Code"));
1106 }
1107
1108 #[test]
1110 fn test_sentence_case_basic() {
1111 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1112 let content = "# The Quick Brown Fox\n";
1113 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1114 let result = rule.check(&ctx).unwrap();
1115 assert_eq!(result.len(), 1);
1116 assert!(result[0].message.contains("The quick brown fox"));
1117 }
1118
1119 #[test]
1120 fn test_sentence_case_already_correct() {
1121 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1122 let content = "# The quick brown fox\n";
1123 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1124 let result = rule.check(&ctx).unwrap();
1125 assert!(result.is_empty());
1126 }
1127
1128 #[test]
1130 fn test_all_caps_basic() {
1131 let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
1132 let content = "# hello world\n";
1133 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1134 let result = rule.check(&ctx).unwrap();
1135 assert_eq!(result.len(), 1);
1136 assert!(result[0].message.contains("HELLO WORLD"));
1137 }
1138
1139 #[test]
1141 fn test_preserve_ignore_words() {
1142 let config = MD063Config {
1143 enabled: true,
1144 ignore_words: vec!["iPhone".to_string(), "macOS".to_string()],
1145 ..Default::default()
1146 };
1147 let rule = MD063HeadingCapitalization::from_config_struct(config);
1148
1149 let content = "# using iPhone on macOS\n";
1150 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1151 let result = rule.check(&ctx).unwrap();
1152 assert_eq!(result.len(), 1);
1153 assert!(result[0].message.contains("iPhone"));
1155 assert!(result[0].message.contains("macOS"));
1156 }
1157
1158 #[test]
1159 fn test_preserve_cased_words() {
1160 let rule = create_rule();
1161 let content = "# using GitHub actions\n";
1162 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1163 let result = rule.check(&ctx).unwrap();
1164 assert_eq!(result.len(), 1);
1165 assert!(result[0].message.contains("GitHub"));
1167 }
1168
1169 #[test]
1171 fn test_inline_code_preserved() {
1172 let rule = create_rule();
1173 let content = "# using `const` in javascript\n";
1174 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1175 let result = rule.check(&ctx).unwrap();
1176 assert_eq!(result.len(), 1);
1177 assert!(result[0].message.contains("`const`"));
1179 assert!(result[0].message.contains("Javascript") || result[0].message.contains("JavaScript"));
1180 }
1181
1182 #[test]
1184 fn test_level_filter() {
1185 let config = MD063Config {
1186 enabled: true,
1187 min_level: 2,
1188 max_level: 4,
1189 ..Default::default()
1190 };
1191 let rule = MD063HeadingCapitalization::from_config_struct(config);
1192
1193 let content = "# h1 heading\n## h2 heading\n### h3 heading\n##### h5 heading\n";
1194 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1195 let result = rule.check(&ctx).unwrap();
1196
1197 assert_eq!(result.len(), 2);
1199 assert_eq!(result[0].line, 2); assert_eq!(result[1].line, 3); }
1202
1203 #[test]
1205 fn test_fix_atx_heading() {
1206 let rule = create_rule();
1207 let content = "# hello world\n";
1208 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1209 let fixed = rule.fix(&ctx).unwrap();
1210 assert_eq!(fixed, "# Hello World\n");
1211 }
1212
1213 #[test]
1214 fn test_fix_multiple_headings() {
1215 let rule = create_rule();
1216 let content = "# first heading\n\n## second heading\n";
1217 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1218 let fixed = rule.fix(&ctx).unwrap();
1219 assert_eq!(fixed, "# First Heading\n\n## Second Heading\n");
1220 }
1221
1222 #[test]
1224 fn test_setext_heading() {
1225 let rule = create_rule();
1226 let content = "hello world\n============\n";
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("Hello World"));
1231 }
1232
1233 #[test]
1235 fn test_custom_id_preserved() {
1236 let rule = create_rule();
1237 let content = "# getting started {#intro}\n";
1238 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1239 let result = rule.check(&ctx).unwrap();
1240 assert_eq!(result.len(), 1);
1241 assert!(result[0].message.contains("{#intro}"));
1243 }
1244
1245 #[test]
1247 fn test_preserve_all_caps_acronyms() {
1248 let rule = create_rule();
1249 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1250
1251 let fixed = rule.fix(&ctx("# using API in production\n")).unwrap();
1253 assert_eq!(fixed, "# Using API in Production\n");
1254
1255 let fixed = rule.fix(&ctx("# API and GPU integration\n")).unwrap();
1257 assert_eq!(fixed, "# API and GPU Integration\n");
1258
1259 let fixed = rule.fix(&ctx("# IO performance guide\n")).unwrap();
1261 assert_eq!(fixed, "# IO Performance Guide\n");
1262
1263 let fixed = rule.fix(&ctx("# HTTP2 and MD5 hashing\n")).unwrap();
1265 assert_eq!(fixed, "# HTTP2 and MD5 Hashing\n");
1266 }
1267
1268 #[test]
1269 fn test_preserve_acronyms_in_hyphenated_words() {
1270 let rule = create_rule();
1271 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1272
1273 let fixed = rule.fix(&ctx("# API-driven architecture\n")).unwrap();
1275 assert_eq!(fixed, "# API-Driven Architecture\n");
1276
1277 let fixed = rule.fix(&ctx("# GPU-accelerated CPU-intensive tasks\n")).unwrap();
1279 assert_eq!(fixed, "# GPU-Accelerated CPU-Intensive Tasks\n");
1280 }
1281
1282 #[test]
1283 fn test_single_letters_not_treated_as_acronyms() {
1284 let rule = create_rule();
1285 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1286
1287 let fixed = rule.fix(&ctx("# i am a heading\n")).unwrap();
1289 assert_eq!(fixed, "# I Am a Heading\n");
1290 }
1291
1292 #[test]
1293 fn test_lowercase_terms_need_ignore_words() {
1294 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1295
1296 let rule = create_rule();
1298 let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1299 assert_eq!(fixed, "# Using Npm Packages\n");
1300
1301 let config = MD063Config {
1303 enabled: true,
1304 ignore_words: vec!["npm".to_string()],
1305 ..Default::default()
1306 };
1307 let rule = MD063HeadingCapitalization::from_config_struct(config);
1308 let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1309 assert_eq!(fixed, "# Using npm Packages\n");
1310 }
1311
1312 #[test]
1313 fn test_acronyms_with_mixed_case_preserved() {
1314 let rule = create_rule();
1315 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1316
1317 let fixed = rule.fix(&ctx("# using API with GitHub\n")).unwrap();
1319 assert_eq!(fixed, "# Using API with GitHub\n");
1320 }
1321
1322 #[test]
1323 fn test_real_world_acronyms() {
1324 let rule = create_rule();
1325 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1326
1327 let content = "# FFI bindings for CPU optimization\n";
1329 let fixed = rule.fix(&ctx(content)).unwrap();
1330 assert_eq!(fixed, "# FFI Bindings for CPU Optimization\n");
1331
1332 let content = "# DOM manipulation and SSR rendering\n";
1333 let fixed = rule.fix(&ctx(content)).unwrap();
1334 assert_eq!(fixed, "# DOM Manipulation and SSR Rendering\n");
1335
1336 let content = "# CVE security and RNN models\n";
1337 let fixed = rule.fix(&ctx(content)).unwrap();
1338 assert_eq!(fixed, "# CVE Security and RNN Models\n");
1339 }
1340
1341 #[test]
1342 fn test_is_all_caps_acronym() {
1343 let rule = create_rule();
1344
1345 assert!(rule.is_all_caps_acronym("API"));
1347 assert!(rule.is_all_caps_acronym("IO"));
1348 assert!(rule.is_all_caps_acronym("GPU"));
1349 assert!(rule.is_all_caps_acronym("HTTP2")); assert!(!rule.is_all_caps_acronym("A"));
1353 assert!(!rule.is_all_caps_acronym("I"));
1354
1355 assert!(!rule.is_all_caps_acronym("Api"));
1357 assert!(!rule.is_all_caps_acronym("npm"));
1358 assert!(!rule.is_all_caps_acronym("iPhone"));
1359 }
1360
1361 #[test]
1362 fn test_sentence_case_ignore_words_first_word() {
1363 let config = MD063Config {
1364 enabled: true,
1365 style: HeadingCapStyle::SentenceCase,
1366 ignore_words: vec!["nvim".to_string()],
1367 ..Default::default()
1368 };
1369 let rule = MD063HeadingCapitalization::from_config_struct(config);
1370
1371 let content = "# nvim config\n";
1373 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1374 let result = rule.check(&ctx).unwrap();
1375 assert!(
1376 result.is_empty(),
1377 "nvim in ignore-words should not be flagged. Got: {result:?}"
1378 );
1379
1380 let fixed = rule.fix(&ctx).unwrap();
1382 assert_eq!(fixed, "# nvim config\n");
1383 }
1384
1385 #[test]
1386 fn test_sentence_case_ignore_words_not_first() {
1387 let config = MD063Config {
1388 enabled: true,
1389 style: HeadingCapStyle::SentenceCase,
1390 ignore_words: vec!["nvim".to_string()],
1391 ..Default::default()
1392 };
1393 let rule = MD063HeadingCapitalization::from_config_struct(config);
1394
1395 let content = "# Using nvim editor\n";
1397 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1398 let result = rule.check(&ctx).unwrap();
1399 assert!(
1400 result.is_empty(),
1401 "nvim in ignore-words should be preserved. Got: {result:?}"
1402 );
1403 }
1404
1405 #[test]
1406 fn test_preserve_cased_words_ios() {
1407 let config = MD063Config {
1408 enabled: true,
1409 style: HeadingCapStyle::SentenceCase,
1410 preserve_cased_words: true,
1411 ..Default::default()
1412 };
1413 let rule = MD063HeadingCapitalization::from_config_struct(config);
1414
1415 let content = "## This is iOS\n";
1417 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1418 let result = rule.check(&ctx).unwrap();
1419 assert!(
1420 result.is_empty(),
1421 "iOS should be preserved with preserve-cased-words. Got: {result:?}"
1422 );
1423
1424 let fixed = rule.fix(&ctx).unwrap();
1426 assert_eq!(fixed, "## This is iOS\n");
1427 }
1428
1429 #[test]
1430 fn test_preserve_cased_words_ios_title_case() {
1431 let config = MD063Config {
1432 enabled: true,
1433 style: HeadingCapStyle::TitleCase,
1434 preserve_cased_words: true,
1435 ..Default::default()
1436 };
1437 let rule = MD063HeadingCapitalization::from_config_struct(config);
1438
1439 let content = "# developing for iOS\n";
1441 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1442 let fixed = rule.fix(&ctx).unwrap();
1443 assert_eq!(fixed, "# Developing for iOS\n");
1444 }
1445
1446 #[test]
1447 fn test_has_internal_capitals_ios() {
1448 let rule = create_rule();
1449
1450 assert!(
1452 rule.has_internal_capitals("iOS"),
1453 "iOS has mixed case (lowercase i, uppercase OS)"
1454 );
1455
1456 assert!(rule.has_internal_capitals("iPhone"));
1458 assert!(rule.has_internal_capitals("macOS"));
1459 assert!(rule.has_internal_capitals("GitHub"));
1460 assert!(rule.has_internal_capitals("JavaScript"));
1461 assert!(rule.has_internal_capitals("eBay"));
1462
1463 assert!(!rule.has_internal_capitals("API"));
1465 assert!(!rule.has_internal_capitals("GPU"));
1466
1467 assert!(!rule.has_internal_capitals("npm"));
1469 assert!(!rule.has_internal_capitals("config"));
1470
1471 assert!(!rule.has_internal_capitals("The"));
1473 assert!(!rule.has_internal_capitals("Hello"));
1474 }
1475
1476 #[test]
1477 fn test_lowercase_words_before_trailing_code() {
1478 let config = MD063Config {
1479 enabled: true,
1480 style: HeadingCapStyle::TitleCase,
1481 lowercase_words: vec![
1482 "a".to_string(),
1483 "an".to_string(),
1484 "and".to_string(),
1485 "at".to_string(),
1486 "but".to_string(),
1487 "by".to_string(),
1488 "for".to_string(),
1489 "from".to_string(),
1490 "into".to_string(),
1491 "nor".to_string(),
1492 "on".to_string(),
1493 "onto".to_string(),
1494 "or".to_string(),
1495 "the".to_string(),
1496 "to".to_string(),
1497 "upon".to_string(),
1498 "via".to_string(),
1499 "vs".to_string(),
1500 "with".to_string(),
1501 "without".to_string(),
1502 ],
1503 preserve_cased_words: true,
1504 ..Default::default()
1505 };
1506 let rule = MD063HeadingCapitalization::from_config_struct(config);
1507
1508 let content = "## subtitle with a `app`\n";
1513 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1514 let result = rule.check(&ctx).unwrap();
1515
1516 assert!(!result.is_empty(), "Should flag incorrect capitalization");
1518 let fixed = rule.fix(&ctx).unwrap();
1519 assert!(
1521 fixed.contains("with a `app`"),
1522 "Expected 'with a `app`' but got: {fixed:?}"
1523 );
1524 assert!(
1525 !fixed.contains("with A `app`"),
1526 "Should not capitalize 'a' to 'A'. Got: {fixed:?}"
1527 );
1528 assert!(
1530 fixed.contains("Subtitle with a `app`"),
1531 "Expected 'Subtitle with a `app`' but got: {fixed:?}"
1532 );
1533 }
1534
1535 #[test]
1536 fn test_lowercase_words_preserved_before_trailing_code_variant() {
1537 let config = MD063Config {
1538 enabled: true,
1539 style: HeadingCapStyle::TitleCase,
1540 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1541 ..Default::default()
1542 };
1543 let rule = MD063HeadingCapitalization::from_config_struct(config);
1544
1545 let content = "## Title with the `code`\n";
1547 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1548 let fixed = rule.fix(&ctx).unwrap();
1549 assert!(
1551 fixed.contains("with the `code`"),
1552 "Expected 'with the `code`' but got: {fixed:?}"
1553 );
1554 assert!(
1555 !fixed.contains("with The `code`"),
1556 "Should not capitalize 'the' to 'The'. Got: {fixed:?}"
1557 );
1558 }
1559
1560 #[test]
1561 fn test_last_word_capitalized_when_no_trailing_code() {
1562 let config = MD063Config {
1565 enabled: true,
1566 style: HeadingCapStyle::TitleCase,
1567 lowercase_words: vec!["a".to_string(), "the".to_string()],
1568 ..Default::default()
1569 };
1570 let rule = MD063HeadingCapitalization::from_config_struct(config);
1571
1572 let content = "## title with a word\n";
1575 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1576 let fixed = rule.fix(&ctx).unwrap();
1577 assert!(
1579 fixed.contains("With a Word"),
1580 "Expected 'With a Word' but got: {fixed:?}"
1581 );
1582 }
1583
1584 #[test]
1585 fn test_multiple_lowercase_words_before_code() {
1586 let config = MD063Config {
1587 enabled: true,
1588 style: HeadingCapStyle::TitleCase,
1589 lowercase_words: vec![
1590 "a".to_string(),
1591 "the".to_string(),
1592 "with".to_string(),
1593 "for".to_string(),
1594 ],
1595 ..Default::default()
1596 };
1597 let rule = MD063HeadingCapitalization::from_config_struct(config);
1598
1599 let content = "## Guide for the `user`\n";
1601 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1602 let fixed = rule.fix(&ctx).unwrap();
1603 assert!(
1604 fixed.contains("for the `user`"),
1605 "Expected 'for the `user`' but got: {fixed:?}"
1606 );
1607 assert!(
1608 !fixed.contains("For The `user`"),
1609 "Should not capitalize lowercase words before code. Got: {fixed:?}"
1610 );
1611 }
1612
1613 #[test]
1614 fn test_code_in_middle_normal_rules_apply() {
1615 let config = MD063Config {
1616 enabled: true,
1617 style: HeadingCapStyle::TitleCase,
1618 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1619 ..Default::default()
1620 };
1621 let rule = MD063HeadingCapitalization::from_config_struct(config);
1622
1623 let content = "## Using `const` for the code\n";
1625 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1626 let fixed = rule.fix(&ctx).unwrap();
1627 assert!(
1629 fixed.contains("for the Code"),
1630 "Expected 'for the Code' but got: {fixed:?}"
1631 );
1632 }
1633
1634 #[test]
1635 fn test_link_at_end_same_as_code() {
1636 let config = MD063Config {
1637 enabled: true,
1638 style: HeadingCapStyle::TitleCase,
1639 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1640 ..Default::default()
1641 };
1642 let rule = MD063HeadingCapitalization::from_config_struct(config);
1643
1644 let content = "## Guide for the [link](./page.md)\n";
1646 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1647 let fixed = rule.fix(&ctx).unwrap();
1648 assert!(
1650 fixed.contains("for the [Link]"),
1651 "Expected 'for the [Link]' but got: {fixed:?}"
1652 );
1653 assert!(
1654 !fixed.contains("for The [Link]"),
1655 "Should not capitalize 'the' before link. Got: {fixed:?}"
1656 );
1657 }
1658
1659 #[test]
1660 fn test_multiple_code_segments() {
1661 let config = MD063Config {
1662 enabled: true,
1663 style: HeadingCapStyle::TitleCase,
1664 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1665 ..Default::default()
1666 };
1667 let rule = MD063HeadingCapitalization::from_config_struct(config);
1668
1669 let content = "## Using `const` with a `variable`\n";
1671 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1672 let fixed = rule.fix(&ctx).unwrap();
1673 assert!(
1675 fixed.contains("with a `variable`"),
1676 "Expected 'with a `variable`' but got: {fixed:?}"
1677 );
1678 assert!(
1679 !fixed.contains("with A `variable`"),
1680 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1681 );
1682 }
1683
1684 #[test]
1685 fn test_code_and_link_combination() {
1686 let config = MD063Config {
1687 enabled: true,
1688 style: HeadingCapStyle::TitleCase,
1689 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1690 ..Default::default()
1691 };
1692 let rule = MD063HeadingCapitalization::from_config_struct(config);
1693
1694 let content = "## Guide for the `code` [link](./page.md)\n";
1696 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1697 let fixed = rule.fix(&ctx).unwrap();
1698 assert!(
1700 fixed.contains("for the `code`"),
1701 "Expected 'for the `code`' but got: {fixed:?}"
1702 );
1703 }
1704
1705 #[test]
1706 fn test_text_after_code_capitalizes_last() {
1707 let config = MD063Config {
1708 enabled: true,
1709 style: HeadingCapStyle::TitleCase,
1710 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1711 ..Default::default()
1712 };
1713 let rule = MD063HeadingCapitalization::from_config_struct(config);
1714
1715 let content = "## Using `const` for the code\n";
1717 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1718 let fixed = rule.fix(&ctx).unwrap();
1719 assert!(
1721 fixed.contains("for the Code"),
1722 "Expected 'for the Code' but got: {fixed:?}"
1723 );
1724 }
1725
1726 #[test]
1727 fn test_preserve_cased_words_with_trailing_code() {
1728 let config = MD063Config {
1729 enabled: true,
1730 style: HeadingCapStyle::TitleCase,
1731 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1732 preserve_cased_words: true,
1733 ..Default::default()
1734 };
1735 let rule = MD063HeadingCapitalization::from_config_struct(config);
1736
1737 let content = "## Guide for iOS `app`\n";
1739 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1740 let fixed = rule.fix(&ctx).unwrap();
1741 assert!(
1743 fixed.contains("for iOS `app`"),
1744 "Expected 'for iOS `app`' but got: {fixed:?}"
1745 );
1746 assert!(
1747 !fixed.contains("For iOS `app`"),
1748 "Should not capitalize 'for' before trailing code. Got: {fixed:?}"
1749 );
1750 }
1751
1752 #[test]
1753 fn test_ignore_words_with_trailing_code() {
1754 let config = MD063Config {
1755 enabled: true,
1756 style: HeadingCapStyle::TitleCase,
1757 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1758 ignore_words: vec!["npm".to_string()],
1759 ..Default::default()
1760 };
1761 let rule = MD063HeadingCapitalization::from_config_struct(config);
1762
1763 let content = "## Using npm with a `script`\n";
1765 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1766 let fixed = rule.fix(&ctx).unwrap();
1767 assert!(
1769 fixed.contains("npm with a `script`"),
1770 "Expected 'npm with a `script`' but got: {fixed:?}"
1771 );
1772 assert!(
1773 !fixed.contains("with A `script`"),
1774 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1775 );
1776 }
1777
1778 #[test]
1779 fn test_empty_text_segment_edge_case() {
1780 let config = MD063Config {
1781 enabled: true,
1782 style: HeadingCapStyle::TitleCase,
1783 lowercase_words: vec!["a".to_string(), "with".to_string()],
1784 ..Default::default()
1785 };
1786 let rule = MD063HeadingCapitalization::from_config_struct(config);
1787
1788 let content = "## `start` with a `end`\n";
1790 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1791 let fixed = rule.fix(&ctx).unwrap();
1792 assert!(fixed.contains("a `end`"), "Expected 'a `end`' but got: {fixed:?}");
1795 assert!(
1796 !fixed.contains("A `end`"),
1797 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1798 );
1799 }
1800
1801 #[test]
1802 fn test_sentence_case_with_trailing_code() {
1803 let config = MD063Config {
1804 enabled: true,
1805 style: HeadingCapStyle::SentenceCase,
1806 lowercase_words: vec!["a".to_string(), "the".to_string()],
1807 ..Default::default()
1808 };
1809 let rule = MD063HeadingCapitalization::from_config_struct(config);
1810
1811 let content = "## guide for the `user`\n";
1813 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1814 let fixed = rule.fix(&ctx).unwrap();
1815 assert!(
1817 fixed.contains("Guide for the `user`"),
1818 "Expected 'Guide for the `user`' but got: {fixed:?}"
1819 );
1820 }
1821
1822 #[test]
1823 fn test_hyphenated_word_before_code() {
1824 let config = MD063Config {
1825 enabled: true,
1826 style: HeadingCapStyle::TitleCase,
1827 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1828 ..Default::default()
1829 };
1830 let rule = MD063HeadingCapitalization::from_config_struct(config);
1831
1832 let content = "## Self-contained with a `feature`\n";
1834 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1835 let fixed = rule.fix(&ctx).unwrap();
1836 assert!(
1838 fixed.contains("with a `feature`"),
1839 "Expected 'with a `feature`' but got: {fixed:?}"
1840 );
1841 }
1842
1843 #[test]
1848 fn test_sentence_case_code_at_start_basic() {
1849 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1851 let content = "# `rumdl` is a linter\n";
1852 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1853 let result = rule.check(&ctx).unwrap();
1854 assert!(
1856 result.is_empty(),
1857 "Heading with code at start should not flag 'is' for capitalization. Got: {:?}",
1858 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1859 );
1860 }
1861
1862 #[test]
1863 fn test_sentence_case_code_at_start_incorrect_capitalization() {
1864 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1866 let content = "# `rumdl` Is a Linter\n";
1867 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1868 let result = rule.check(&ctx).unwrap();
1869 assert_eq!(result.len(), 1, "Should detect incorrect capitalization");
1871 assert!(
1872 result[0].message.contains("`rumdl` is a linter"),
1873 "Should suggest lowercase after code. Got: {:?}",
1874 result[0].message
1875 );
1876 }
1877
1878 #[test]
1879 fn test_sentence_case_code_at_start_fix() {
1880 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1881 let content = "# `rumdl` Is A Linter\n";
1882 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1883 let fixed = rule.fix(&ctx).unwrap();
1884 assert!(
1885 fixed.contains("# `rumdl` is a linter"),
1886 "Should fix to lowercase after code. Got: {fixed:?}"
1887 );
1888 }
1889
1890 #[test]
1891 fn test_sentence_case_text_at_start_still_capitalizes() {
1892 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1894 let content = "# the quick brown fox\n";
1895 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1896 let result = rule.check(&ctx).unwrap();
1897 assert_eq!(result.len(), 1);
1898 assert!(
1899 result[0].message.contains("The quick brown fox"),
1900 "Text-first heading should capitalize first word. Got: {:?}",
1901 result[0].message
1902 );
1903 }
1904
1905 #[test]
1906 fn test_sentence_case_link_at_start() {
1907 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1909 let content = "# [api](api.md) reference guide\n";
1911 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1912 let result = rule.check(&ctx).unwrap();
1913 assert!(
1915 result.is_empty(),
1916 "Heading with link at start should not capitalize 'reference'. Got: {:?}",
1917 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1918 );
1919 }
1920
1921 #[test]
1922 fn test_sentence_case_link_preserves_acronyms() {
1923 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1925 let content = "# [API](api.md) Reference Guide\n";
1926 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1927 let result = rule.check(&ctx).unwrap();
1928 assert_eq!(result.len(), 1);
1929 assert!(
1931 result[0].message.contains("[API](api.md) reference guide"),
1932 "Should preserve acronym 'API' but lowercase following text. Got: {:?}",
1933 result[0].message
1934 );
1935 }
1936
1937 #[test]
1938 fn test_sentence_case_link_preserves_brand_names() {
1939 let config = MD063Config {
1941 enabled: true,
1942 style: HeadingCapStyle::SentenceCase,
1943 preserve_cased_words: true,
1944 ..Default::default()
1945 };
1946 let rule = MD063HeadingCapitalization::from_config_struct(config);
1947 let content = "# [iPhone](iphone.md) Features Guide\n";
1948 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1949 let result = rule.check(&ctx).unwrap();
1950 assert_eq!(result.len(), 1);
1951 assert!(
1953 result[0].message.contains("[iPhone](iphone.md) features guide"),
1954 "Should preserve 'iPhone' but lowercase following text. Got: {:?}",
1955 result[0].message
1956 );
1957 }
1958
1959 #[test]
1960 fn test_sentence_case_link_lowercases_regular_words() {
1961 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1963 let content = "# [Documentation](docs.md) Reference\n";
1964 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1965 let result = rule.check(&ctx).unwrap();
1966 assert_eq!(result.len(), 1);
1967 assert!(
1969 result[0].message.contains("[documentation](docs.md) reference"),
1970 "Should lowercase regular link text. Got: {:?}",
1971 result[0].message
1972 );
1973 }
1974
1975 #[test]
1976 fn test_sentence_case_link_at_start_correct_already() {
1977 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1979 let content = "# [API](api.md) reference guide\n";
1980 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1981 let result = rule.check(&ctx).unwrap();
1982 assert!(
1983 result.is_empty(),
1984 "Correctly cased heading with link should not be flagged. Got: {:?}",
1985 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1986 );
1987 }
1988
1989 #[test]
1990 fn test_sentence_case_link_github_preserved() {
1991 let config = MD063Config {
1993 enabled: true,
1994 style: HeadingCapStyle::SentenceCase,
1995 preserve_cased_words: true,
1996 ..Default::default()
1997 };
1998 let rule = MD063HeadingCapitalization::from_config_struct(config);
1999 let content = "# [GitHub](gh.md) Repository Setup\n";
2000 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2001 let result = rule.check(&ctx).unwrap();
2002 assert_eq!(result.len(), 1);
2003 assert!(
2004 result[0].message.contains("[GitHub](gh.md) repository setup"),
2005 "Should preserve 'GitHub'. Got: {:?}",
2006 result[0].message
2007 );
2008 }
2009
2010 #[test]
2011 fn test_sentence_case_multiple_code_spans() {
2012 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2013 let content = "# `foo` and `bar` are methods\n";
2014 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2015 let result = rule.check(&ctx).unwrap();
2016 assert!(
2018 result.is_empty(),
2019 "Should not capitalize words between/after code spans. Got: {:?}",
2020 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2021 );
2022 }
2023
2024 #[test]
2025 fn test_sentence_case_code_only_heading() {
2026 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2028 let content = "# `rumdl`\n";
2029 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2030 let result = rule.check(&ctx).unwrap();
2031 assert!(
2032 result.is_empty(),
2033 "Code-only heading should be fine. Got: {:?}",
2034 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2035 );
2036 }
2037
2038 #[test]
2039 fn test_sentence_case_code_at_end() {
2040 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2042 let content = "# install the `rumdl` tool\n";
2043 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2044 let result = rule.check(&ctx).unwrap();
2045 assert_eq!(result.len(), 1);
2047 assert!(
2048 result[0].message.contains("Install the `rumdl` tool"),
2049 "First word should still be capitalized when text comes first. Got: {:?}",
2050 result[0].message
2051 );
2052 }
2053
2054 #[test]
2055 fn test_sentence_case_code_in_middle() {
2056 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2058 let content = "# using the `rumdl` linter for markdown\n";
2059 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2060 let result = rule.check(&ctx).unwrap();
2061 assert_eq!(result.len(), 1);
2063 assert!(
2064 result[0].message.contains("Using the `rumdl` linter for markdown"),
2065 "First word should be capitalized. Got: {:?}",
2066 result[0].message
2067 );
2068 }
2069
2070 #[test]
2071 fn test_sentence_case_preserved_word_after_code() {
2072 let config = MD063Config {
2074 enabled: true,
2075 style: HeadingCapStyle::SentenceCase,
2076 preserve_cased_words: true,
2077 ..Default::default()
2078 };
2079 let rule = MD063HeadingCapitalization::from_config_struct(config);
2080 let content = "# `swift` iPhone development\n";
2081 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2082 let result = rule.check(&ctx).unwrap();
2083 assert!(
2085 result.is_empty(),
2086 "Preserved words after code should stay. Got: {:?}",
2087 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2088 );
2089 }
2090
2091 #[test]
2092 fn test_title_case_code_at_start_still_capitalizes() {
2093 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2095 let content = "# `api` quick start guide\n";
2096 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2097 let result = rule.check(&ctx).unwrap();
2098 assert_eq!(result.len(), 1);
2100 assert!(
2101 result[0].message.contains("Quick Start Guide") || result[0].message.contains("quick Start Guide"),
2102 "Title case should capitalize major words after code. Got: {:?}",
2103 result[0].message
2104 );
2105 }
2106
2107 #[test]
2110 fn test_sentence_case_html_tag_at_start() {
2111 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2113 let content = "# <kbd>Ctrl</kbd> is a Modifier Key\n";
2114 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2115 let result = rule.check(&ctx).unwrap();
2116 assert_eq!(result.len(), 1);
2118 let fixed = rule.fix(&ctx).unwrap();
2119 assert_eq!(
2120 fixed, "# <kbd>Ctrl</kbd> is a modifier key\n",
2121 "Text after HTML at start should be lowercase"
2122 );
2123 }
2124
2125 #[test]
2126 fn test_sentence_case_html_tag_preserves_content() {
2127 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2129 let content = "# The <abbr>API</abbr> documentation guide\n";
2130 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2131 let result = rule.check(&ctx).unwrap();
2132 assert!(
2134 result.is_empty(),
2135 "HTML tag content should be preserved. Got: {:?}",
2136 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2137 );
2138 }
2139
2140 #[test]
2141 fn test_sentence_case_html_tag_at_start_with_acronym() {
2142 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2144 let content = "# <abbr>API</abbr> Documentation Guide\n";
2145 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2146 let result = rule.check(&ctx).unwrap();
2147 assert_eq!(result.len(), 1);
2148 let fixed = rule.fix(&ctx).unwrap();
2149 assert_eq!(
2150 fixed, "# <abbr>API</abbr> documentation guide\n",
2151 "Text after HTML at start should be lowercase, HTML content preserved"
2152 );
2153 }
2154
2155 #[test]
2156 fn test_sentence_case_html_tag_in_middle() {
2157 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2159 let content = "# using the <code>config</code> File\n";
2160 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2161 let result = rule.check(&ctx).unwrap();
2162 assert_eq!(result.len(), 1);
2163 let fixed = rule.fix(&ctx).unwrap();
2164 assert_eq!(
2165 fixed, "# Using the <code>config</code> file\n",
2166 "First word capitalized, HTML preserved, rest lowercase"
2167 );
2168 }
2169
2170 #[test]
2171 fn test_html_tag_strong_emphasis() {
2172 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2174 let content = "# The <strong>Bold</strong> Way\n";
2175 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2176 let result = rule.check(&ctx).unwrap();
2177 assert_eq!(result.len(), 1);
2178 let fixed = rule.fix(&ctx).unwrap();
2179 assert_eq!(
2180 fixed, "# The <strong>Bold</strong> way\n",
2181 "<strong> tag content should be preserved"
2182 );
2183 }
2184
2185 #[test]
2186 fn test_html_tag_with_attributes() {
2187 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2189 let content = "# <span class=\"highlight\">Important</span> Notice Here\n";
2190 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2191 let result = rule.check(&ctx).unwrap();
2192 assert_eq!(result.len(), 1);
2193 let fixed = rule.fix(&ctx).unwrap();
2194 assert_eq!(
2195 fixed, "# <span class=\"highlight\">Important</span> notice here\n",
2196 "HTML tag with attributes should be preserved"
2197 );
2198 }
2199
2200 #[test]
2201 fn test_multiple_html_tags() {
2202 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2204 let content = "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to Copy Text\n";
2205 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2206 let result = rule.check(&ctx).unwrap();
2207 assert_eq!(result.len(), 1);
2208 let fixed = rule.fix(&ctx).unwrap();
2209 assert_eq!(
2210 fixed, "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy text\n",
2211 "Multiple HTML tags should all be preserved"
2212 );
2213 }
2214
2215 #[test]
2216 fn test_html_and_code_mixed() {
2217 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2219 let content = "# <kbd>Ctrl</kbd>+`v` Paste command\n";
2220 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2221 let result = rule.check(&ctx).unwrap();
2222 assert_eq!(result.len(), 1);
2223 let fixed = rule.fix(&ctx).unwrap();
2224 assert_eq!(
2225 fixed, "# <kbd>Ctrl</kbd>+`v` paste command\n",
2226 "HTML and code should both be preserved"
2227 );
2228 }
2229
2230 #[test]
2231 fn test_self_closing_html_tag() {
2232 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2234 let content = "# Line one<br/>Line Two Here\n";
2235 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2236 let result = rule.check(&ctx).unwrap();
2237 assert_eq!(result.len(), 1);
2238 let fixed = rule.fix(&ctx).unwrap();
2239 assert_eq!(
2240 fixed, "# Line one<br/>line two here\n",
2241 "Self-closing HTML tags should be preserved"
2242 );
2243 }
2244
2245 #[test]
2246 fn test_title_case_with_html_tags() {
2247 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2249 let content = "# the <kbd>ctrl</kbd> key is a modifier\n";
2250 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2251 let result = rule.check(&ctx).unwrap();
2252 assert_eq!(result.len(), 1);
2253 let fixed = rule.fix(&ctx).unwrap();
2254 assert!(
2256 fixed.contains("<kbd>ctrl</kbd>"),
2257 "HTML tag content should be preserved in title case. Got: {fixed}"
2258 );
2259 assert!(
2260 fixed.starts_with("# The ") || fixed.starts_with("# the "),
2261 "Title case should work with HTML. Got: {fixed}"
2262 );
2263 }
2264
2265 #[test]
2268 fn test_sentence_case_preserves_caret_notation() {
2269 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2271 let content = "## Ctrl+A, Ctrl+R output ^A, ^R on zsh\n";
2272 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2273 let result = rule.check(&ctx).unwrap();
2274 assert!(
2276 result.is_empty(),
2277 "Caret notation should be preserved. Got: {:?}",
2278 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2279 );
2280 }
2281
2282 #[test]
2283 fn test_sentence_case_caret_notation_various() {
2284 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2286
2287 let content = "## Press ^C to cancel\n";
2289 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2290 let result = rule.check(&ctx).unwrap();
2291 assert!(
2292 result.is_empty(),
2293 "^C should be preserved. Got: {:?}",
2294 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2295 );
2296
2297 let content = "## Use ^Z for background\n";
2299 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2300 let result = rule.check(&ctx).unwrap();
2301 assert!(
2302 result.is_empty(),
2303 "^Z should be preserved. Got: {:?}",
2304 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2305 );
2306
2307 let content = "## Press ^[ for escape\n";
2309 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2310 let result = rule.check(&ctx).unwrap();
2311 assert!(
2312 result.is_empty(),
2313 "^[ should be preserved. Got: {:?}",
2314 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2315 );
2316 }
2317
2318 #[test]
2319 fn test_caret_notation_detection() {
2320 let rule = create_rule();
2321
2322 assert!(rule.is_caret_notation("^A"));
2324 assert!(rule.is_caret_notation("^Z"));
2325 assert!(rule.is_caret_notation("^C"));
2326 assert!(rule.is_caret_notation("^@")); assert!(rule.is_caret_notation("^[")); assert!(rule.is_caret_notation("^]")); assert!(rule.is_caret_notation("^^")); assert!(rule.is_caret_notation("^_")); assert!(!rule.is_caret_notation("^a")); assert!(!rule.is_caret_notation("A")); assert!(!rule.is_caret_notation("^")); assert!(!rule.is_caret_notation("^1")); }
2338
2339 fn create_sentence_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2346 let config = MD063Config {
2347 enabled: true,
2348 style: HeadingCapStyle::SentenceCase,
2349 ..Default::default()
2350 };
2351 let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2352 rule.proper_names = names;
2353 rule
2354 }
2355
2356 #[test]
2357 fn test_sentence_case_preserves_single_word_proper_name() {
2358 let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2359 let content = "# installing javascript\n";
2361 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2362 let result = rule.check(&ctx).unwrap();
2363 assert_eq!(result.len(), 1, "Should flag the heading");
2364 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2365 assert!(
2366 fix_text.contains("JavaScript"),
2367 "Fix should preserve proper name 'JavaScript', got: {fix_text:?}"
2368 );
2369 assert!(
2370 !fix_text.contains("javascript"),
2371 "Fix should not have lowercase 'javascript', got: {fix_text:?}"
2372 );
2373 }
2374
2375 #[test]
2376 fn test_sentence_case_preserves_multi_word_proper_name() {
2377 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2378 let content = "# using good application features\n";
2380 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2381 let result = rule.check(&ctx).unwrap();
2382 assert_eq!(result.len(), 1, "Should flag the heading");
2383 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2384 assert!(
2385 fix_text.contains("Good Application"),
2386 "Fix should preserve 'Good Application' as a phrase, got: {fix_text:?}"
2387 );
2388 }
2389
2390 #[test]
2391 fn test_sentence_case_proper_name_at_start_of_heading() {
2392 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2393 let content = "# good application overview\n";
2395 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2396 let result = rule.check(&ctx).unwrap();
2397 assert_eq!(result.len(), 1, "Should flag the heading");
2398 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2399 assert!(
2400 fix_text.contains("Good Application"),
2401 "Fix should produce 'Good Application' at start of heading, got: {fix_text:?}"
2402 );
2403 assert!(
2404 fix_text.contains("overview"),
2405 "Non-proper-name word 'overview' should be lowercase, got: {fix_text:?}"
2406 );
2407 }
2408
2409 #[test]
2410 fn test_sentence_case_with_proper_names_no_oscillation() {
2411 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2414
2415 let content = "# installing good application on your system\n";
2417 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2418 let result = rule.check(&ctx).unwrap();
2419 assert_eq!(result.len(), 1);
2420 let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2421
2422 assert!(
2424 fixed_heading.contains("Good Application"),
2425 "After fix, proper name must be preserved: {fixed_heading:?}"
2426 );
2427
2428 let fixed_line = format!("{fixed_heading}\n");
2430 let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2431 let result2 = rule.check(&ctx2).unwrap();
2432 assert!(
2433 result2.is_empty(),
2434 "After one fix, heading must already satisfy both MD063 and MD044 - no oscillation. \
2435 Second pass warnings: {result2:?}"
2436 );
2437 }
2438
2439 #[test]
2440 fn test_sentence_case_proper_names_already_correct() {
2441 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2442 let content = "# Installing Good Application\n";
2444 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2445 let result = rule.check(&ctx).unwrap();
2446 assert!(
2447 result.is_empty(),
2448 "Correct sentence-case heading with proper name should not be flagged, got: {result:?}"
2449 );
2450 }
2451
2452 #[test]
2453 fn test_sentence_case_multiple_proper_names_in_heading() {
2454 let rule = create_sentence_case_rule_with_proper_names(vec!["TypeScript".to_string(), "React".to_string()]);
2455 let content = "# using typescript with react\n";
2456 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2457 let result = rule.check(&ctx).unwrap();
2458 assert_eq!(result.len(), 1);
2459 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2460 assert!(
2461 fix_text.contains("TypeScript"),
2462 "Fix should preserve 'TypeScript', got: {fix_text:?}"
2463 );
2464 assert!(
2465 fix_text.contains("React"),
2466 "Fix should preserve 'React', got: {fix_text:?}"
2467 );
2468 }
2469
2470 #[test]
2471 fn test_sentence_case_unicode_casefold_expansion_before_proper_name() {
2472 let rule = create_sentence_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2475 let content = "# İ österreich guide\n";
2476 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2477
2478 let result = rule.check(&ctx).unwrap();
2480 assert_eq!(result.len(), 1, "Should flag heading for canonical proper-name casing");
2481 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2482 assert!(
2483 fix_text.contains("Österreich"),
2484 "Fix should preserve canonical 'Österreich', got: {fix_text:?}"
2485 );
2486 }
2487
2488 #[test]
2489 fn test_sentence_case_preserves_trailing_punctuation_on_proper_name() {
2490 let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2491 let content = "# using javascript, today\n";
2492 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2493 let result = rule.check(&ctx).unwrap();
2494 assert_eq!(result.len(), 1, "Should flag heading");
2495 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2496 assert!(
2497 fix_text.contains("JavaScript,"),
2498 "Fix should preserve trailing punctuation, got: {fix_text:?}"
2499 );
2500 }
2501
2502 fn create_title_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2509 let config = MD063Config {
2510 enabled: true,
2511 style: HeadingCapStyle::TitleCase,
2512 ..Default::default()
2513 };
2514 let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2515 rule.proper_names = names;
2516 rule
2517 }
2518
2519 #[test]
2520 fn test_title_case_preserves_proper_name_with_lowercase_article() {
2521 let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2525 let content = "# listening to the rolling stones today\n";
2526 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2527 let result = rule.check(&ctx).unwrap();
2528 assert_eq!(result.len(), 1, "Should flag the heading");
2529 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2530 assert!(
2531 fix_text.contains("The Rolling Stones"),
2532 "Fix should preserve proper name 'The Rolling Stones', got: {fix_text:?}"
2533 );
2534 }
2535
2536 #[test]
2537 fn test_title_case_proper_name_no_oscillation() {
2538 let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2540 let content = "# listening to the rolling stones today\n";
2541 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2542 let result = rule.check(&ctx).unwrap();
2543 assert_eq!(result.len(), 1);
2544 let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2545
2546 let fixed_line = format!("{fixed_heading}\n");
2547 let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2548 let result2 = rule.check(&ctx2).unwrap();
2549 assert!(
2550 result2.is_empty(),
2551 "After one title-case fix, heading must already satisfy both rules. \
2552 Second pass warnings: {result2:?}"
2553 );
2554 }
2555
2556 #[test]
2557 fn test_title_case_unicode_casefold_expansion_before_proper_name() {
2558 let rule = create_title_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2559 let content = "# İ österreich guide\n";
2560 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2561 let result = rule.check(&ctx).unwrap();
2562 assert_eq!(result.len(), 1, "Should flag the heading");
2563 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2564 assert!(
2565 fix_text.contains("Österreich"),
2566 "Fix should preserve canonical proper-name casing, got: {fix_text:?}"
2567 );
2568 }
2569
2570 #[test]
2576 fn test_from_config_loads_md044_names_into_md063() {
2577 use crate::config::{Config, RuleConfig};
2578 use crate::rule::Rule;
2579 use std::collections::BTreeMap;
2580
2581 let mut config = Config::default();
2582
2583 let mut md063_values = BTreeMap::new();
2585 md063_values.insert("style".to_string(), toml::Value::String("sentence_case".to_string()));
2586 md063_values.insert("enabled".to_string(), toml::Value::Boolean(true));
2587 config.rules.insert(
2588 "MD063".to_string(),
2589 RuleConfig {
2590 values: md063_values,
2591 severity: None,
2592 },
2593 );
2594
2595 let mut md044_values = BTreeMap::new();
2597 md044_values.insert(
2598 "names".to_string(),
2599 toml::Value::Array(vec![toml::Value::String("Good Application".to_string())]),
2600 );
2601 config.rules.insert(
2602 "MD044".to_string(),
2603 RuleConfig {
2604 values: md044_values,
2605 severity: None,
2606 },
2607 );
2608
2609 let rule = MD063HeadingCapitalization::from_config(&config);
2611
2612 let content = "# using good application features\n";
2614 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2615 let result = rule.check(&ctx).unwrap();
2616 assert_eq!(result.len(), 1, "Should flag the heading");
2617 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2618 assert!(
2619 fix_text.contains("Good Application"),
2620 "from_config should wire MD044 names into MD063; fix should preserve \
2621 'Good Application', got: {fix_text:?}"
2622 );
2623 }
2624
2625 #[test]
2626 fn test_title_case_short_word_not_confused_with_substring() {
2627 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2631
2632 let content = "# in the insert\n";
2635 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2636 let result = rule.check(&ctx).unwrap();
2637 assert_eq!(result.len(), 1, "Should flag the heading");
2638 let fix = result[0].fix.as_ref().expect("Fix should be present");
2639 assert!(
2641 fix.replacement.contains("In the Insert"),
2642 "Expected 'In the Insert', got: {:?}",
2643 fix.replacement
2644 );
2645 }
2646
2647 #[test]
2648 fn test_title_case_or_not_confused_with_orchestra() {
2649 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2650
2651 let content = "# or the orchestra\n";
2654 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2655 let result = rule.check(&ctx).unwrap();
2656 assert_eq!(result.len(), 1, "Should flag the heading");
2657 let fix = result[0].fix.as_ref().expect("Fix should be present");
2658 assert!(
2660 fix.replacement.contains("Or the Orchestra"),
2661 "Expected 'Or the Orchestra', got: {:?}",
2662 fix.replacement
2663 );
2664 }
2665
2666 #[test]
2667 fn test_all_caps_preserves_all_words() {
2668 let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
2669
2670 let content = "# in the insert\n";
2671 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2672 let result = rule.check(&ctx).unwrap();
2673 assert_eq!(result.len(), 1, "Should flag the heading");
2674 let fix = result[0].fix.as_ref().expect("Fix should be present");
2675 assert!(
2676 fix.replacement.contains("IN THE INSERT"),
2677 "All caps should uppercase all words, got: {:?}",
2678 fix.replacement
2679 );
2680 }
2681}