1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, 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 category(&self) -> RuleCategory {
913 RuleCategory::Heading
914 }
915
916 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
917 !ctx.likely_has_headings() || !ctx.lines.iter().any(|line| line.heading.is_some())
918 }
919
920 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
921 let content = ctx.content;
922
923 if content.is_empty() {
924 return Ok(Vec::new());
925 }
926
927 let mut warnings = Vec::new();
928 let line_index = &ctx.line_index;
929
930 for (line_num, line_info) in ctx.lines.iter().enumerate() {
931 if let Some(heading) = &line_info.heading {
932 if heading.level < self.config.min_level || heading.level > self.config.max_level {
934 continue;
935 }
936
937 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
939 continue;
940 }
941
942 let original_text = &heading.raw_text;
944 let fixed_text = self.apply_capitalization(original_text);
945
946 if original_text != &fixed_text {
947 let line = line_info.content(ctx.content);
948 let style_name = match self.config.style {
949 HeadingCapStyle::TitleCase => "title case",
950 HeadingCapStyle::SentenceCase => "sentence case",
951 HeadingCapStyle::AllCaps => "ALL CAPS",
952 };
953
954 warnings.push(LintWarning {
955 rule_name: Some(self.name().to_string()),
956 line: line_num + 1,
957 column: heading.content_column + 1,
958 end_line: line_num + 1,
959 end_column: heading.content_column + 1 + original_text.len(),
960 message: format!("Heading should use {style_name}: '{original_text}' -> '{fixed_text}'"),
961 severity: Severity::Warning,
962 fix: Some(Fix {
963 range: self.get_line_byte_range(content, line_num + 1, line_index),
964 replacement: match heading.style {
965 crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
966 _ => self.fix_setext_heading(line, heading),
967 },
968 }),
969 });
970 }
971 }
972 }
973
974 Ok(warnings)
975 }
976
977 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
978 let content = ctx.content;
979
980 if content.is_empty() {
981 return Ok(content.to_string());
982 }
983
984 let lines = ctx.raw_lines();
985 let mut fixed_lines: Vec<String> = lines.iter().map(|&s| s.to_string()).collect();
986
987 for (line_num, line_info) in ctx.lines.iter().enumerate() {
988 if ctx.is_rule_disabled(self.name(), line_num + 1) {
990 continue;
991 }
992
993 if let Some(heading) = &line_info.heading {
994 if heading.level < self.config.min_level || heading.level > self.config.max_level {
996 continue;
997 }
998
999 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
1001 continue;
1002 }
1003
1004 let original_text = &heading.raw_text;
1005 let fixed_text = self.apply_capitalization(original_text);
1006
1007 if original_text != &fixed_text {
1008 let line = line_info.content(ctx.content);
1009 fixed_lines[line_num] = match heading.style {
1010 crate::lint_context::HeadingStyle::ATX => self.fix_atx_heading(line, heading),
1011 _ => self.fix_setext_heading(line, heading),
1012 };
1013 }
1014 }
1015 }
1016
1017 let mut result = String::with_capacity(content.len());
1019 for (i, line) in fixed_lines.iter().enumerate() {
1020 result.push_str(line);
1021 if i < fixed_lines.len() - 1 || content.ends_with('\n') {
1022 result.push('\n');
1023 }
1024 }
1025
1026 Ok(result)
1027 }
1028
1029 fn as_any(&self) -> &dyn std::any::Any {
1030 self
1031 }
1032
1033 fn default_config_section(&self) -> Option<(String, toml::Value)> {
1034 let json_value = serde_json::to_value(&self.config).ok()?;
1035 Some((
1036 self.name().to_string(),
1037 crate::rule_config_serde::json_to_toml_value(&json_value)?,
1038 ))
1039 }
1040
1041 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
1042 where
1043 Self: Sized,
1044 {
1045 let rule_config = crate::rule_config_serde::load_rule_config::<MD063Config>(config);
1046 let md044_config =
1047 crate::rule_config_serde::load_rule_config::<crate::rules::md044_proper_names::MD044Config>(config);
1048 let mut rule = Self::from_config_struct(rule_config);
1049 rule.proper_names = md044_config.names;
1050 Box::new(rule)
1051 }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056 use super::*;
1057 use crate::lint_context::LintContext;
1058
1059 fn create_rule() -> MD063HeadingCapitalization {
1060 let config = MD063Config {
1061 enabled: true,
1062 ..Default::default()
1063 };
1064 MD063HeadingCapitalization::from_config_struct(config)
1065 }
1066
1067 fn create_rule_with_style(style: HeadingCapStyle) -> MD063HeadingCapitalization {
1068 let config = MD063Config {
1069 enabled: true,
1070 style,
1071 ..Default::default()
1072 };
1073 MD063HeadingCapitalization::from_config_struct(config)
1074 }
1075
1076 #[test]
1078 fn test_title_case_basic() {
1079 let rule = create_rule();
1080 let content = "# hello world\n";
1081 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1082 let result = rule.check(&ctx).unwrap();
1083 assert_eq!(result.len(), 1);
1084 assert!(result[0].message.contains("Hello World"));
1085 }
1086
1087 #[test]
1088 fn test_title_case_lowercase_words() {
1089 let rule = create_rule();
1090 let content = "# the quick brown fox\n";
1091 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1092 let result = rule.check(&ctx).unwrap();
1093 assert_eq!(result.len(), 1);
1094 assert!(result[0].message.contains("The Quick Brown Fox"));
1096 }
1097
1098 #[test]
1099 fn test_title_case_already_correct() {
1100 let rule = create_rule();
1101 let content = "# The Quick Brown Fox\n";
1102 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1103 let result = rule.check(&ctx).unwrap();
1104 assert!(result.is_empty(), "Already correct heading should not be flagged");
1105 }
1106
1107 #[test]
1108 fn test_title_case_hyphenated() {
1109 let rule = create_rule();
1110 let content = "# self-documenting code\n";
1111 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1112 let result = rule.check(&ctx).unwrap();
1113 assert_eq!(result.len(), 1);
1114 assert!(result[0].message.contains("Self-Documenting Code"));
1115 }
1116
1117 #[test]
1119 fn test_sentence_case_basic() {
1120 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1121 let content = "# The Quick Brown Fox\n";
1122 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1123 let result = rule.check(&ctx).unwrap();
1124 assert_eq!(result.len(), 1);
1125 assert!(result[0].message.contains("The quick brown fox"));
1126 }
1127
1128 #[test]
1129 fn test_sentence_case_already_correct() {
1130 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1131 let content = "# The quick brown fox\n";
1132 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1133 let result = rule.check(&ctx).unwrap();
1134 assert!(result.is_empty());
1135 }
1136
1137 #[test]
1139 fn test_all_caps_basic() {
1140 let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
1141 let content = "# hello world\n";
1142 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1143 let result = rule.check(&ctx).unwrap();
1144 assert_eq!(result.len(), 1);
1145 assert!(result[0].message.contains("HELLO WORLD"));
1146 }
1147
1148 #[test]
1150 fn test_preserve_ignore_words() {
1151 let config = MD063Config {
1152 enabled: true,
1153 ignore_words: vec!["iPhone".to_string(), "macOS".to_string()],
1154 ..Default::default()
1155 };
1156 let rule = MD063HeadingCapitalization::from_config_struct(config);
1157
1158 let content = "# using iPhone on macOS\n";
1159 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1160 let result = rule.check(&ctx).unwrap();
1161 assert_eq!(result.len(), 1);
1162 assert!(result[0].message.contains("iPhone"));
1164 assert!(result[0].message.contains("macOS"));
1165 }
1166
1167 #[test]
1168 fn test_preserve_cased_words() {
1169 let rule = create_rule();
1170 let content = "# using GitHub actions\n";
1171 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1172 let result = rule.check(&ctx).unwrap();
1173 assert_eq!(result.len(), 1);
1174 assert!(result[0].message.contains("GitHub"));
1176 }
1177
1178 #[test]
1180 fn test_inline_code_preserved() {
1181 let rule = create_rule();
1182 let content = "# using `const` in javascript\n";
1183 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1184 let result = rule.check(&ctx).unwrap();
1185 assert_eq!(result.len(), 1);
1186 assert!(result[0].message.contains("`const`"));
1188 assert!(result[0].message.contains("Javascript") || result[0].message.contains("JavaScript"));
1189 }
1190
1191 #[test]
1193 fn test_level_filter() {
1194 let config = MD063Config {
1195 enabled: true,
1196 min_level: 2,
1197 max_level: 4,
1198 ..Default::default()
1199 };
1200 let rule = MD063HeadingCapitalization::from_config_struct(config);
1201
1202 let content = "# h1 heading\n## h2 heading\n### h3 heading\n##### h5 heading\n";
1203 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1204 let result = rule.check(&ctx).unwrap();
1205
1206 assert_eq!(result.len(), 2);
1208 assert_eq!(result[0].line, 2); assert_eq!(result[1].line, 3); }
1211
1212 #[test]
1214 fn test_fix_atx_heading() {
1215 let rule = create_rule();
1216 let content = "# hello world\n";
1217 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1218 let fixed = rule.fix(&ctx).unwrap();
1219 assert_eq!(fixed, "# Hello World\n");
1220 }
1221
1222 #[test]
1223 fn test_fix_multiple_headings() {
1224 let rule = create_rule();
1225 let content = "# first heading\n\n## second heading\n";
1226 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1227 let fixed = rule.fix(&ctx).unwrap();
1228 assert_eq!(fixed, "# First Heading\n\n## Second Heading\n");
1229 }
1230
1231 #[test]
1233 fn test_setext_heading() {
1234 let rule = create_rule();
1235 let content = "hello world\n============\n";
1236 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1237 let result = rule.check(&ctx).unwrap();
1238 assert_eq!(result.len(), 1);
1239 assert!(result[0].message.contains("Hello World"));
1240 }
1241
1242 #[test]
1244 fn test_custom_id_preserved() {
1245 let rule = create_rule();
1246 let content = "# getting started {#intro}\n";
1247 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1248 let result = rule.check(&ctx).unwrap();
1249 assert_eq!(result.len(), 1);
1250 assert!(result[0].message.contains("{#intro}"));
1252 }
1253
1254 #[test]
1256 fn test_preserve_all_caps_acronyms() {
1257 let rule = create_rule();
1258 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1259
1260 let fixed = rule.fix(&ctx("# using API in production\n")).unwrap();
1262 assert_eq!(fixed, "# Using API in Production\n");
1263
1264 let fixed = rule.fix(&ctx("# API and GPU integration\n")).unwrap();
1266 assert_eq!(fixed, "# API and GPU Integration\n");
1267
1268 let fixed = rule.fix(&ctx("# IO performance guide\n")).unwrap();
1270 assert_eq!(fixed, "# IO Performance Guide\n");
1271
1272 let fixed = rule.fix(&ctx("# HTTP2 and MD5 hashing\n")).unwrap();
1274 assert_eq!(fixed, "# HTTP2 and MD5 Hashing\n");
1275 }
1276
1277 #[test]
1278 fn test_preserve_acronyms_in_hyphenated_words() {
1279 let rule = create_rule();
1280 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1281
1282 let fixed = rule.fix(&ctx("# API-driven architecture\n")).unwrap();
1284 assert_eq!(fixed, "# API-Driven Architecture\n");
1285
1286 let fixed = rule.fix(&ctx("# GPU-accelerated CPU-intensive tasks\n")).unwrap();
1288 assert_eq!(fixed, "# GPU-Accelerated CPU-Intensive Tasks\n");
1289 }
1290
1291 #[test]
1292 fn test_single_letters_not_treated_as_acronyms() {
1293 let rule = create_rule();
1294 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1295
1296 let fixed = rule.fix(&ctx("# i am a heading\n")).unwrap();
1298 assert_eq!(fixed, "# I Am a Heading\n");
1299 }
1300
1301 #[test]
1302 fn test_lowercase_terms_need_ignore_words() {
1303 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1304
1305 let rule = create_rule();
1307 let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1308 assert_eq!(fixed, "# Using Npm Packages\n");
1309
1310 let config = MD063Config {
1312 enabled: true,
1313 ignore_words: vec!["npm".to_string()],
1314 ..Default::default()
1315 };
1316 let rule = MD063HeadingCapitalization::from_config_struct(config);
1317 let fixed = rule.fix(&ctx("# using npm packages\n")).unwrap();
1318 assert_eq!(fixed, "# Using npm Packages\n");
1319 }
1320
1321 #[test]
1322 fn test_acronyms_with_mixed_case_preserved() {
1323 let rule = create_rule();
1324 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1325
1326 let fixed = rule.fix(&ctx("# using API with GitHub\n")).unwrap();
1328 assert_eq!(fixed, "# Using API with GitHub\n");
1329 }
1330
1331 #[test]
1332 fn test_real_world_acronyms() {
1333 let rule = create_rule();
1334 let ctx = |c| LintContext::new(c, crate::config::MarkdownFlavor::Standard, None);
1335
1336 let content = "# FFI bindings for CPU optimization\n";
1338 let fixed = rule.fix(&ctx(content)).unwrap();
1339 assert_eq!(fixed, "# FFI Bindings for CPU Optimization\n");
1340
1341 let content = "# DOM manipulation and SSR rendering\n";
1342 let fixed = rule.fix(&ctx(content)).unwrap();
1343 assert_eq!(fixed, "# DOM Manipulation and SSR Rendering\n");
1344
1345 let content = "# CVE security and RNN models\n";
1346 let fixed = rule.fix(&ctx(content)).unwrap();
1347 assert_eq!(fixed, "# CVE Security and RNN Models\n");
1348 }
1349
1350 #[test]
1351 fn test_is_all_caps_acronym() {
1352 let rule = create_rule();
1353
1354 assert!(rule.is_all_caps_acronym("API"));
1356 assert!(rule.is_all_caps_acronym("IO"));
1357 assert!(rule.is_all_caps_acronym("GPU"));
1358 assert!(rule.is_all_caps_acronym("HTTP2")); assert!(!rule.is_all_caps_acronym("A"));
1362 assert!(!rule.is_all_caps_acronym("I"));
1363
1364 assert!(!rule.is_all_caps_acronym("Api"));
1366 assert!(!rule.is_all_caps_acronym("npm"));
1367 assert!(!rule.is_all_caps_acronym("iPhone"));
1368 }
1369
1370 #[test]
1371 fn test_sentence_case_ignore_words_first_word() {
1372 let config = MD063Config {
1373 enabled: true,
1374 style: HeadingCapStyle::SentenceCase,
1375 ignore_words: vec!["nvim".to_string()],
1376 ..Default::default()
1377 };
1378 let rule = MD063HeadingCapitalization::from_config_struct(config);
1379
1380 let content = "# nvim config\n";
1382 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1383 let result = rule.check(&ctx).unwrap();
1384 assert!(
1385 result.is_empty(),
1386 "nvim in ignore-words should not be flagged. Got: {result:?}"
1387 );
1388
1389 let fixed = rule.fix(&ctx).unwrap();
1391 assert_eq!(fixed, "# nvim config\n");
1392 }
1393
1394 #[test]
1395 fn test_sentence_case_ignore_words_not_first() {
1396 let config = MD063Config {
1397 enabled: true,
1398 style: HeadingCapStyle::SentenceCase,
1399 ignore_words: vec!["nvim".to_string()],
1400 ..Default::default()
1401 };
1402 let rule = MD063HeadingCapitalization::from_config_struct(config);
1403
1404 let content = "# Using nvim editor\n";
1406 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1407 let result = rule.check(&ctx).unwrap();
1408 assert!(
1409 result.is_empty(),
1410 "nvim in ignore-words should be preserved. Got: {result:?}"
1411 );
1412 }
1413
1414 #[test]
1415 fn test_preserve_cased_words_ios() {
1416 let config = MD063Config {
1417 enabled: true,
1418 style: HeadingCapStyle::SentenceCase,
1419 preserve_cased_words: true,
1420 ..Default::default()
1421 };
1422 let rule = MD063HeadingCapitalization::from_config_struct(config);
1423
1424 let content = "## This is iOS\n";
1426 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1427 let result = rule.check(&ctx).unwrap();
1428 assert!(
1429 result.is_empty(),
1430 "iOS should be preserved with preserve-cased-words. Got: {result:?}"
1431 );
1432
1433 let fixed = rule.fix(&ctx).unwrap();
1435 assert_eq!(fixed, "## This is iOS\n");
1436 }
1437
1438 #[test]
1439 fn test_preserve_cased_words_ios_title_case() {
1440 let config = MD063Config {
1441 enabled: true,
1442 style: HeadingCapStyle::TitleCase,
1443 preserve_cased_words: true,
1444 ..Default::default()
1445 };
1446 let rule = MD063HeadingCapitalization::from_config_struct(config);
1447
1448 let content = "# developing for iOS\n";
1450 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1451 let fixed = rule.fix(&ctx).unwrap();
1452 assert_eq!(fixed, "# Developing for iOS\n");
1453 }
1454
1455 #[test]
1456 fn test_has_internal_capitals_ios() {
1457 let rule = create_rule();
1458
1459 assert!(
1461 rule.has_internal_capitals("iOS"),
1462 "iOS has mixed case (lowercase i, uppercase OS)"
1463 );
1464
1465 assert!(rule.has_internal_capitals("iPhone"));
1467 assert!(rule.has_internal_capitals("macOS"));
1468 assert!(rule.has_internal_capitals("GitHub"));
1469 assert!(rule.has_internal_capitals("JavaScript"));
1470 assert!(rule.has_internal_capitals("eBay"));
1471
1472 assert!(!rule.has_internal_capitals("API"));
1474 assert!(!rule.has_internal_capitals("GPU"));
1475
1476 assert!(!rule.has_internal_capitals("npm"));
1478 assert!(!rule.has_internal_capitals("config"));
1479
1480 assert!(!rule.has_internal_capitals("The"));
1482 assert!(!rule.has_internal_capitals("Hello"));
1483 }
1484
1485 #[test]
1486 fn test_lowercase_words_before_trailing_code() {
1487 let config = MD063Config {
1488 enabled: true,
1489 style: HeadingCapStyle::TitleCase,
1490 lowercase_words: vec![
1491 "a".to_string(),
1492 "an".to_string(),
1493 "and".to_string(),
1494 "at".to_string(),
1495 "but".to_string(),
1496 "by".to_string(),
1497 "for".to_string(),
1498 "from".to_string(),
1499 "into".to_string(),
1500 "nor".to_string(),
1501 "on".to_string(),
1502 "onto".to_string(),
1503 "or".to_string(),
1504 "the".to_string(),
1505 "to".to_string(),
1506 "upon".to_string(),
1507 "via".to_string(),
1508 "vs".to_string(),
1509 "with".to_string(),
1510 "without".to_string(),
1511 ],
1512 preserve_cased_words: true,
1513 ..Default::default()
1514 };
1515 let rule = MD063HeadingCapitalization::from_config_struct(config);
1516
1517 let content = "## subtitle with a `app`\n";
1522 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1523 let result = rule.check(&ctx).unwrap();
1524
1525 assert!(!result.is_empty(), "Should flag incorrect capitalization");
1527 let fixed = rule.fix(&ctx).unwrap();
1528 assert!(
1530 fixed.contains("with a `app`"),
1531 "Expected 'with a `app`' but got: {fixed:?}"
1532 );
1533 assert!(
1534 !fixed.contains("with A `app`"),
1535 "Should not capitalize 'a' to 'A'. Got: {fixed:?}"
1536 );
1537 assert!(
1539 fixed.contains("Subtitle with a `app`"),
1540 "Expected 'Subtitle with a `app`' but got: {fixed:?}"
1541 );
1542 }
1543
1544 #[test]
1545 fn test_lowercase_words_preserved_before_trailing_code_variant() {
1546 let config = MD063Config {
1547 enabled: true,
1548 style: HeadingCapStyle::TitleCase,
1549 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1550 ..Default::default()
1551 };
1552 let rule = MD063HeadingCapitalization::from_config_struct(config);
1553
1554 let content = "## Title with the `code`\n";
1556 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1557 let fixed = rule.fix(&ctx).unwrap();
1558 assert!(
1560 fixed.contains("with the `code`"),
1561 "Expected 'with the `code`' but got: {fixed:?}"
1562 );
1563 assert!(
1564 !fixed.contains("with The `code`"),
1565 "Should not capitalize 'the' to 'The'. Got: {fixed:?}"
1566 );
1567 }
1568
1569 #[test]
1570 fn test_last_word_capitalized_when_no_trailing_code() {
1571 let config = MD063Config {
1574 enabled: true,
1575 style: HeadingCapStyle::TitleCase,
1576 lowercase_words: vec!["a".to_string(), "the".to_string()],
1577 ..Default::default()
1578 };
1579 let rule = MD063HeadingCapitalization::from_config_struct(config);
1580
1581 let content = "## title with a word\n";
1584 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1585 let fixed = rule.fix(&ctx).unwrap();
1586 assert!(
1588 fixed.contains("With a Word"),
1589 "Expected 'With a Word' but got: {fixed:?}"
1590 );
1591 }
1592
1593 #[test]
1594 fn test_multiple_lowercase_words_before_code() {
1595 let config = MD063Config {
1596 enabled: true,
1597 style: HeadingCapStyle::TitleCase,
1598 lowercase_words: vec![
1599 "a".to_string(),
1600 "the".to_string(),
1601 "with".to_string(),
1602 "for".to_string(),
1603 ],
1604 ..Default::default()
1605 };
1606 let rule = MD063HeadingCapitalization::from_config_struct(config);
1607
1608 let content = "## Guide for the `user`\n";
1610 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1611 let fixed = rule.fix(&ctx).unwrap();
1612 assert!(
1613 fixed.contains("for the `user`"),
1614 "Expected 'for the `user`' but got: {fixed:?}"
1615 );
1616 assert!(
1617 !fixed.contains("For The `user`"),
1618 "Should not capitalize lowercase words before code. Got: {fixed:?}"
1619 );
1620 }
1621
1622 #[test]
1623 fn test_code_in_middle_normal_rules_apply() {
1624 let config = MD063Config {
1625 enabled: true,
1626 style: HeadingCapStyle::TitleCase,
1627 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1628 ..Default::default()
1629 };
1630 let rule = MD063HeadingCapitalization::from_config_struct(config);
1631
1632 let content = "## Using `const` for the code\n";
1634 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1635 let fixed = rule.fix(&ctx).unwrap();
1636 assert!(
1638 fixed.contains("for the Code"),
1639 "Expected 'for the Code' but got: {fixed:?}"
1640 );
1641 }
1642
1643 #[test]
1644 fn test_link_at_end_same_as_code() {
1645 let config = MD063Config {
1646 enabled: true,
1647 style: HeadingCapStyle::TitleCase,
1648 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1649 ..Default::default()
1650 };
1651 let rule = MD063HeadingCapitalization::from_config_struct(config);
1652
1653 let content = "## Guide for the [link](./page.md)\n";
1655 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1656 let fixed = rule.fix(&ctx).unwrap();
1657 assert!(
1659 fixed.contains("for the [Link]"),
1660 "Expected 'for the [Link]' but got: {fixed:?}"
1661 );
1662 assert!(
1663 !fixed.contains("for The [Link]"),
1664 "Should not capitalize 'the' before link. Got: {fixed:?}"
1665 );
1666 }
1667
1668 #[test]
1669 fn test_multiple_code_segments() {
1670 let config = MD063Config {
1671 enabled: true,
1672 style: HeadingCapStyle::TitleCase,
1673 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1674 ..Default::default()
1675 };
1676 let rule = MD063HeadingCapitalization::from_config_struct(config);
1677
1678 let content = "## Using `const` with a `variable`\n";
1680 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1681 let fixed = rule.fix(&ctx).unwrap();
1682 assert!(
1684 fixed.contains("with a `variable`"),
1685 "Expected 'with a `variable`' but got: {fixed:?}"
1686 );
1687 assert!(
1688 !fixed.contains("with A `variable`"),
1689 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1690 );
1691 }
1692
1693 #[test]
1694 fn test_code_and_link_combination() {
1695 let config = MD063Config {
1696 enabled: true,
1697 style: HeadingCapStyle::TitleCase,
1698 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1699 ..Default::default()
1700 };
1701 let rule = MD063HeadingCapitalization::from_config_struct(config);
1702
1703 let content = "## Guide for the `code` [link](./page.md)\n";
1705 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1706 let fixed = rule.fix(&ctx).unwrap();
1707 assert!(
1709 fixed.contains("for the `code`"),
1710 "Expected 'for the `code`' but got: {fixed:?}"
1711 );
1712 }
1713
1714 #[test]
1715 fn test_text_after_code_capitalizes_last() {
1716 let config = MD063Config {
1717 enabled: true,
1718 style: HeadingCapStyle::TitleCase,
1719 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1720 ..Default::default()
1721 };
1722 let rule = MD063HeadingCapitalization::from_config_struct(config);
1723
1724 let content = "## Using `const` for the code\n";
1726 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1727 let fixed = rule.fix(&ctx).unwrap();
1728 assert!(
1730 fixed.contains("for the Code"),
1731 "Expected 'for the Code' but got: {fixed:?}"
1732 );
1733 }
1734
1735 #[test]
1736 fn test_preserve_cased_words_with_trailing_code() {
1737 let config = MD063Config {
1738 enabled: true,
1739 style: HeadingCapStyle::TitleCase,
1740 lowercase_words: vec!["a".to_string(), "the".to_string(), "for".to_string()],
1741 preserve_cased_words: true,
1742 ..Default::default()
1743 };
1744 let rule = MD063HeadingCapitalization::from_config_struct(config);
1745
1746 let content = "## Guide for iOS `app`\n";
1748 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1749 let fixed = rule.fix(&ctx).unwrap();
1750 assert!(
1752 fixed.contains("for iOS `app`"),
1753 "Expected 'for iOS `app`' but got: {fixed:?}"
1754 );
1755 assert!(
1756 !fixed.contains("For iOS `app`"),
1757 "Should not capitalize 'for' before trailing code. Got: {fixed:?}"
1758 );
1759 }
1760
1761 #[test]
1762 fn test_ignore_words_with_trailing_code() {
1763 let config = MD063Config {
1764 enabled: true,
1765 style: HeadingCapStyle::TitleCase,
1766 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1767 ignore_words: vec!["npm".to_string()],
1768 ..Default::default()
1769 };
1770 let rule = MD063HeadingCapitalization::from_config_struct(config);
1771
1772 let content = "## Using npm with a `script`\n";
1774 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1775 let fixed = rule.fix(&ctx).unwrap();
1776 assert!(
1778 fixed.contains("npm with a `script`"),
1779 "Expected 'npm with a `script`' but got: {fixed:?}"
1780 );
1781 assert!(
1782 !fixed.contains("with A `script`"),
1783 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1784 );
1785 }
1786
1787 #[test]
1788 fn test_empty_text_segment_edge_case() {
1789 let config = MD063Config {
1790 enabled: true,
1791 style: HeadingCapStyle::TitleCase,
1792 lowercase_words: vec!["a".to_string(), "with".to_string()],
1793 ..Default::default()
1794 };
1795 let rule = MD063HeadingCapitalization::from_config_struct(config);
1796
1797 let content = "## `start` with a `end`\n";
1799 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1800 let fixed = rule.fix(&ctx).unwrap();
1801 assert!(fixed.contains("a `end`"), "Expected 'a `end`' but got: {fixed:?}");
1804 assert!(
1805 !fixed.contains("A `end`"),
1806 "Should not capitalize 'a' before trailing code. Got: {fixed:?}"
1807 );
1808 }
1809
1810 #[test]
1811 fn test_sentence_case_with_trailing_code() {
1812 let config = MD063Config {
1813 enabled: true,
1814 style: HeadingCapStyle::SentenceCase,
1815 lowercase_words: vec!["a".to_string(), "the".to_string()],
1816 ..Default::default()
1817 };
1818 let rule = MD063HeadingCapitalization::from_config_struct(config);
1819
1820 let content = "## guide for the `user`\n";
1822 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1823 let fixed = rule.fix(&ctx).unwrap();
1824 assert!(
1826 fixed.contains("Guide for the `user`"),
1827 "Expected 'Guide for the `user`' but got: {fixed:?}"
1828 );
1829 }
1830
1831 #[test]
1832 fn test_hyphenated_word_before_code() {
1833 let config = MD063Config {
1834 enabled: true,
1835 style: HeadingCapStyle::TitleCase,
1836 lowercase_words: vec!["a".to_string(), "the".to_string(), "with".to_string()],
1837 ..Default::default()
1838 };
1839 let rule = MD063HeadingCapitalization::from_config_struct(config);
1840
1841 let content = "## Self-contained with a `feature`\n";
1843 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1844 let fixed = rule.fix(&ctx).unwrap();
1845 assert!(
1847 fixed.contains("with a `feature`"),
1848 "Expected 'with a `feature`' but got: {fixed:?}"
1849 );
1850 }
1851
1852 #[test]
1857 fn test_sentence_case_code_at_start_basic() {
1858 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1860 let content = "# `rumdl` is a linter\n";
1861 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1862 let result = rule.check(&ctx).unwrap();
1863 assert!(
1865 result.is_empty(),
1866 "Heading with code at start should not flag 'is' for capitalization. Got: {:?}",
1867 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1868 );
1869 }
1870
1871 #[test]
1872 fn test_sentence_case_code_at_start_incorrect_capitalization() {
1873 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1875 let content = "# `rumdl` Is a Linter\n";
1876 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1877 let result = rule.check(&ctx).unwrap();
1878 assert_eq!(result.len(), 1, "Should detect incorrect capitalization");
1880 assert!(
1881 result[0].message.contains("`rumdl` is a linter"),
1882 "Should suggest lowercase after code. Got: {:?}",
1883 result[0].message
1884 );
1885 }
1886
1887 #[test]
1888 fn test_sentence_case_code_at_start_fix() {
1889 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1890 let content = "# `rumdl` Is A Linter\n";
1891 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1892 let fixed = rule.fix(&ctx).unwrap();
1893 assert!(
1894 fixed.contains("# `rumdl` is a linter"),
1895 "Should fix to lowercase after code. Got: {fixed:?}"
1896 );
1897 }
1898
1899 #[test]
1900 fn test_sentence_case_text_at_start_still_capitalizes() {
1901 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1903 let content = "# the quick brown fox\n";
1904 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1905 let result = rule.check(&ctx).unwrap();
1906 assert_eq!(result.len(), 1);
1907 assert!(
1908 result[0].message.contains("The quick brown fox"),
1909 "Text-first heading should capitalize first word. Got: {:?}",
1910 result[0].message
1911 );
1912 }
1913
1914 #[test]
1915 fn test_sentence_case_link_at_start() {
1916 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1918 let content = "# [api](api.md) reference guide\n";
1920 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1921 let result = rule.check(&ctx).unwrap();
1922 assert!(
1924 result.is_empty(),
1925 "Heading with link at start should not capitalize 'reference'. Got: {:?}",
1926 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1927 );
1928 }
1929
1930 #[test]
1931 fn test_sentence_case_link_preserves_acronyms() {
1932 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1934 let content = "# [API](api.md) Reference Guide\n";
1935 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1936 let result = rule.check(&ctx).unwrap();
1937 assert_eq!(result.len(), 1);
1938 assert!(
1940 result[0].message.contains("[API](api.md) reference guide"),
1941 "Should preserve acronym 'API' but lowercase following text. Got: {:?}",
1942 result[0].message
1943 );
1944 }
1945
1946 #[test]
1947 fn test_sentence_case_link_preserves_brand_names() {
1948 let config = MD063Config {
1950 enabled: true,
1951 style: HeadingCapStyle::SentenceCase,
1952 preserve_cased_words: true,
1953 ..Default::default()
1954 };
1955 let rule = MD063HeadingCapitalization::from_config_struct(config);
1956 let content = "# [iPhone](iphone.md) Features Guide\n";
1957 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1958 let result = rule.check(&ctx).unwrap();
1959 assert_eq!(result.len(), 1);
1960 assert!(
1962 result[0].message.contains("[iPhone](iphone.md) features guide"),
1963 "Should preserve 'iPhone' but lowercase following text. Got: {:?}",
1964 result[0].message
1965 );
1966 }
1967
1968 #[test]
1969 fn test_sentence_case_link_lowercases_regular_words() {
1970 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1972 let content = "# [Documentation](docs.md) Reference\n";
1973 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1974 let result = rule.check(&ctx).unwrap();
1975 assert_eq!(result.len(), 1);
1976 assert!(
1978 result[0].message.contains("[documentation](docs.md) reference"),
1979 "Should lowercase regular link text. Got: {:?}",
1980 result[0].message
1981 );
1982 }
1983
1984 #[test]
1985 fn test_sentence_case_link_at_start_correct_already() {
1986 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
1988 let content = "# [API](api.md) reference guide\n";
1989 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1990 let result = rule.check(&ctx).unwrap();
1991 assert!(
1992 result.is_empty(),
1993 "Correctly cased heading with link should not be flagged. Got: {:?}",
1994 result.iter().map(|w| &w.message).collect::<Vec<_>>()
1995 );
1996 }
1997
1998 #[test]
1999 fn test_sentence_case_link_github_preserved() {
2000 let config = MD063Config {
2002 enabled: true,
2003 style: HeadingCapStyle::SentenceCase,
2004 preserve_cased_words: true,
2005 ..Default::default()
2006 };
2007 let rule = MD063HeadingCapitalization::from_config_struct(config);
2008 let content = "# [GitHub](gh.md) Repository Setup\n";
2009 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2010 let result = rule.check(&ctx).unwrap();
2011 assert_eq!(result.len(), 1);
2012 assert!(
2013 result[0].message.contains("[GitHub](gh.md) repository setup"),
2014 "Should preserve 'GitHub'. Got: {:?}",
2015 result[0].message
2016 );
2017 }
2018
2019 #[test]
2020 fn test_sentence_case_multiple_code_spans() {
2021 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2022 let content = "# `foo` and `bar` are methods\n";
2023 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2024 let result = rule.check(&ctx).unwrap();
2025 assert!(
2027 result.is_empty(),
2028 "Should not capitalize words between/after code spans. Got: {:?}",
2029 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2030 );
2031 }
2032
2033 #[test]
2034 fn test_sentence_case_code_only_heading() {
2035 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2037 let content = "# `rumdl`\n";
2038 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2039 let result = rule.check(&ctx).unwrap();
2040 assert!(
2041 result.is_empty(),
2042 "Code-only heading should be fine. Got: {:?}",
2043 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2044 );
2045 }
2046
2047 #[test]
2048 fn test_sentence_case_code_at_end() {
2049 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2051 let content = "# install the `rumdl` tool\n";
2052 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2053 let result = rule.check(&ctx).unwrap();
2054 assert_eq!(result.len(), 1);
2056 assert!(
2057 result[0].message.contains("Install the `rumdl` tool"),
2058 "First word should still be capitalized when text comes first. Got: {:?}",
2059 result[0].message
2060 );
2061 }
2062
2063 #[test]
2064 fn test_sentence_case_code_in_middle() {
2065 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2067 let content = "# using the `rumdl` linter for markdown\n";
2068 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2069 let result = rule.check(&ctx).unwrap();
2070 assert_eq!(result.len(), 1);
2072 assert!(
2073 result[0].message.contains("Using the `rumdl` linter for markdown"),
2074 "First word should be capitalized. Got: {:?}",
2075 result[0].message
2076 );
2077 }
2078
2079 #[test]
2080 fn test_sentence_case_preserved_word_after_code() {
2081 let config = MD063Config {
2083 enabled: true,
2084 style: HeadingCapStyle::SentenceCase,
2085 preserve_cased_words: true,
2086 ..Default::default()
2087 };
2088 let rule = MD063HeadingCapitalization::from_config_struct(config);
2089 let content = "# `swift` iPhone development\n";
2090 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2091 let result = rule.check(&ctx).unwrap();
2092 assert!(
2094 result.is_empty(),
2095 "Preserved words after code should stay. Got: {:?}",
2096 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2097 );
2098 }
2099
2100 #[test]
2101 fn test_title_case_code_at_start_still_capitalizes() {
2102 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2104 let content = "# `api` quick start guide\n";
2105 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2106 let result = rule.check(&ctx).unwrap();
2107 assert_eq!(result.len(), 1);
2109 assert!(
2110 result[0].message.contains("Quick Start Guide") || result[0].message.contains("quick Start Guide"),
2111 "Title case should capitalize major words after code. Got: {:?}",
2112 result[0].message
2113 );
2114 }
2115
2116 #[test]
2119 fn test_sentence_case_html_tag_at_start() {
2120 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2122 let content = "# <kbd>Ctrl</kbd> is a Modifier Key\n";
2123 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2124 let result = rule.check(&ctx).unwrap();
2125 assert_eq!(result.len(), 1);
2127 let fixed = rule.fix(&ctx).unwrap();
2128 assert_eq!(
2129 fixed, "# <kbd>Ctrl</kbd> is a modifier key\n",
2130 "Text after HTML at start should be lowercase"
2131 );
2132 }
2133
2134 #[test]
2135 fn test_sentence_case_html_tag_preserves_content() {
2136 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2138 let content = "# The <abbr>API</abbr> documentation guide\n";
2139 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2140 let result = rule.check(&ctx).unwrap();
2141 assert!(
2143 result.is_empty(),
2144 "HTML tag content should be preserved. Got: {:?}",
2145 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2146 );
2147 }
2148
2149 #[test]
2150 fn test_sentence_case_html_tag_at_start_with_acronym() {
2151 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2153 let content = "# <abbr>API</abbr> Documentation Guide\n";
2154 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2155 let result = rule.check(&ctx).unwrap();
2156 assert_eq!(result.len(), 1);
2157 let fixed = rule.fix(&ctx).unwrap();
2158 assert_eq!(
2159 fixed, "# <abbr>API</abbr> documentation guide\n",
2160 "Text after HTML at start should be lowercase, HTML content preserved"
2161 );
2162 }
2163
2164 #[test]
2165 fn test_sentence_case_html_tag_in_middle() {
2166 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2168 let content = "# using the <code>config</code> File\n";
2169 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2170 let result = rule.check(&ctx).unwrap();
2171 assert_eq!(result.len(), 1);
2172 let fixed = rule.fix(&ctx).unwrap();
2173 assert_eq!(
2174 fixed, "# Using the <code>config</code> file\n",
2175 "First word capitalized, HTML preserved, rest lowercase"
2176 );
2177 }
2178
2179 #[test]
2180 fn test_html_tag_strong_emphasis() {
2181 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2183 let content = "# The <strong>Bold</strong> Way\n";
2184 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2185 let result = rule.check(&ctx).unwrap();
2186 assert_eq!(result.len(), 1);
2187 let fixed = rule.fix(&ctx).unwrap();
2188 assert_eq!(
2189 fixed, "# The <strong>Bold</strong> way\n",
2190 "<strong> tag content should be preserved"
2191 );
2192 }
2193
2194 #[test]
2195 fn test_html_tag_with_attributes() {
2196 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2198 let content = "# <span class=\"highlight\">Important</span> Notice Here\n";
2199 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2200 let result = rule.check(&ctx).unwrap();
2201 assert_eq!(result.len(), 1);
2202 let fixed = rule.fix(&ctx).unwrap();
2203 assert_eq!(
2204 fixed, "# <span class=\"highlight\">Important</span> notice here\n",
2205 "HTML tag with attributes should be preserved"
2206 );
2207 }
2208
2209 #[test]
2210 fn test_multiple_html_tags() {
2211 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2213 let content = "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to Copy Text\n";
2214 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2215 let result = rule.check(&ctx).unwrap();
2216 assert_eq!(result.len(), 1);
2217 let fixed = rule.fix(&ctx).unwrap();
2218 assert_eq!(
2219 fixed, "# <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy text\n",
2220 "Multiple HTML tags should all be preserved"
2221 );
2222 }
2223
2224 #[test]
2225 fn test_html_and_code_mixed() {
2226 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2228 let content = "# <kbd>Ctrl</kbd>+`v` Paste command\n";
2229 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2230 let result = rule.check(&ctx).unwrap();
2231 assert_eq!(result.len(), 1);
2232 let fixed = rule.fix(&ctx).unwrap();
2233 assert_eq!(
2234 fixed, "# <kbd>Ctrl</kbd>+`v` paste command\n",
2235 "HTML and code should both be preserved"
2236 );
2237 }
2238
2239 #[test]
2240 fn test_self_closing_html_tag() {
2241 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2243 let content = "# Line one<br/>Line Two Here\n";
2244 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2245 let result = rule.check(&ctx).unwrap();
2246 assert_eq!(result.len(), 1);
2247 let fixed = rule.fix(&ctx).unwrap();
2248 assert_eq!(
2249 fixed, "# Line one<br/>line two here\n",
2250 "Self-closing HTML tags should be preserved"
2251 );
2252 }
2253
2254 #[test]
2255 fn test_title_case_with_html_tags() {
2256 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2258 let content = "# the <kbd>ctrl</kbd> key is a modifier\n";
2259 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2260 let result = rule.check(&ctx).unwrap();
2261 assert_eq!(result.len(), 1);
2262 let fixed = rule.fix(&ctx).unwrap();
2263 assert!(
2265 fixed.contains("<kbd>ctrl</kbd>"),
2266 "HTML tag content should be preserved in title case. Got: {fixed}"
2267 );
2268 assert!(
2269 fixed.starts_with("# The ") || fixed.starts_with("# the "),
2270 "Title case should work with HTML. Got: {fixed}"
2271 );
2272 }
2273
2274 #[test]
2277 fn test_sentence_case_preserves_caret_notation() {
2278 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2280 let content = "## Ctrl+A, Ctrl+R output ^A, ^R on zsh\n";
2281 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2282 let result = rule.check(&ctx).unwrap();
2283 assert!(
2285 result.is_empty(),
2286 "Caret notation should be preserved. Got: {:?}",
2287 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2288 );
2289 }
2290
2291 #[test]
2292 fn test_sentence_case_caret_notation_various() {
2293 let rule = create_rule_with_style(HeadingCapStyle::SentenceCase);
2295
2296 let content = "## Press ^C to cancel\n";
2298 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2299 let result = rule.check(&ctx).unwrap();
2300 assert!(
2301 result.is_empty(),
2302 "^C should be preserved. Got: {:?}",
2303 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2304 );
2305
2306 let content = "## Use ^Z for background\n";
2308 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2309 let result = rule.check(&ctx).unwrap();
2310 assert!(
2311 result.is_empty(),
2312 "^Z should be preserved. Got: {:?}",
2313 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2314 );
2315
2316 let content = "## Press ^[ for escape\n";
2318 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2319 let result = rule.check(&ctx).unwrap();
2320 assert!(
2321 result.is_empty(),
2322 "^[ should be preserved. Got: {:?}",
2323 result.iter().map(|w| &w.message).collect::<Vec<_>>()
2324 );
2325 }
2326
2327 #[test]
2328 fn test_caret_notation_detection() {
2329 let rule = create_rule();
2330
2331 assert!(rule.is_caret_notation("^A"));
2333 assert!(rule.is_caret_notation("^Z"));
2334 assert!(rule.is_caret_notation("^C"));
2335 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")); }
2347
2348 fn create_sentence_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2355 let config = MD063Config {
2356 enabled: true,
2357 style: HeadingCapStyle::SentenceCase,
2358 ..Default::default()
2359 };
2360 let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2361 rule.proper_names = names;
2362 rule
2363 }
2364
2365 #[test]
2366 fn test_sentence_case_preserves_single_word_proper_name() {
2367 let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2368 let content = "# installing javascript\n";
2370 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2371 let result = rule.check(&ctx).unwrap();
2372 assert_eq!(result.len(), 1, "Should flag the heading");
2373 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2374 assert!(
2375 fix_text.contains("JavaScript"),
2376 "Fix should preserve proper name 'JavaScript', got: {fix_text:?}"
2377 );
2378 assert!(
2379 !fix_text.contains("javascript"),
2380 "Fix should not have lowercase 'javascript', got: {fix_text:?}"
2381 );
2382 }
2383
2384 #[test]
2385 fn test_sentence_case_preserves_multi_word_proper_name() {
2386 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2387 let content = "# using good application features\n";
2389 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2390 let result = rule.check(&ctx).unwrap();
2391 assert_eq!(result.len(), 1, "Should flag the heading");
2392 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2393 assert!(
2394 fix_text.contains("Good Application"),
2395 "Fix should preserve 'Good Application' as a phrase, got: {fix_text:?}"
2396 );
2397 }
2398
2399 #[test]
2400 fn test_sentence_case_proper_name_at_start_of_heading() {
2401 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2402 let content = "# good application overview\n";
2404 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2405 let result = rule.check(&ctx).unwrap();
2406 assert_eq!(result.len(), 1, "Should flag the heading");
2407 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2408 assert!(
2409 fix_text.contains("Good Application"),
2410 "Fix should produce 'Good Application' at start of heading, got: {fix_text:?}"
2411 );
2412 assert!(
2413 fix_text.contains("overview"),
2414 "Non-proper-name word 'overview' should be lowercase, got: {fix_text:?}"
2415 );
2416 }
2417
2418 #[test]
2419 fn test_sentence_case_with_proper_names_no_oscillation() {
2420 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2423
2424 let content = "# installing good application on your system\n";
2426 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2427 let result = rule.check(&ctx).unwrap();
2428 assert_eq!(result.len(), 1);
2429 let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2430
2431 assert!(
2433 fixed_heading.contains("Good Application"),
2434 "After fix, proper name must be preserved: {fixed_heading:?}"
2435 );
2436
2437 let fixed_line = format!("{fixed_heading}\n");
2439 let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2440 let result2 = rule.check(&ctx2).unwrap();
2441 assert!(
2442 result2.is_empty(),
2443 "After one fix, heading must already satisfy both MD063 and MD044 - no oscillation. \
2444 Second pass warnings: {result2:?}"
2445 );
2446 }
2447
2448 #[test]
2449 fn test_sentence_case_proper_names_already_correct() {
2450 let rule = create_sentence_case_rule_with_proper_names(vec!["Good Application".to_string()]);
2451 let content = "# Installing Good Application\n";
2453 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2454 let result = rule.check(&ctx).unwrap();
2455 assert!(
2456 result.is_empty(),
2457 "Correct sentence-case heading with proper name should not be flagged, got: {result:?}"
2458 );
2459 }
2460
2461 #[test]
2462 fn test_sentence_case_multiple_proper_names_in_heading() {
2463 let rule = create_sentence_case_rule_with_proper_names(vec!["TypeScript".to_string(), "React".to_string()]);
2464 let content = "# using typescript with react\n";
2465 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2466 let result = rule.check(&ctx).unwrap();
2467 assert_eq!(result.len(), 1);
2468 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2469 assert!(
2470 fix_text.contains("TypeScript"),
2471 "Fix should preserve 'TypeScript', got: {fix_text:?}"
2472 );
2473 assert!(
2474 fix_text.contains("React"),
2475 "Fix should preserve 'React', got: {fix_text:?}"
2476 );
2477 }
2478
2479 #[test]
2480 fn test_sentence_case_unicode_casefold_expansion_before_proper_name() {
2481 let rule = create_sentence_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2484 let content = "# İ österreich guide\n";
2485 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2486
2487 let result = rule.check(&ctx).unwrap();
2489 assert_eq!(result.len(), 1, "Should flag heading for canonical proper-name casing");
2490 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2491 assert!(
2492 fix_text.contains("Österreich"),
2493 "Fix should preserve canonical 'Österreich', got: {fix_text:?}"
2494 );
2495 }
2496
2497 #[test]
2498 fn test_sentence_case_preserves_trailing_punctuation_on_proper_name() {
2499 let rule = create_sentence_case_rule_with_proper_names(vec!["JavaScript".to_string()]);
2500 let content = "# using javascript, today\n";
2501 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2502 let result = rule.check(&ctx).unwrap();
2503 assert_eq!(result.len(), 1, "Should flag heading");
2504 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2505 assert!(
2506 fix_text.contains("JavaScript,"),
2507 "Fix should preserve trailing punctuation, got: {fix_text:?}"
2508 );
2509 }
2510
2511 fn create_title_case_rule_with_proper_names(names: Vec<String>) -> MD063HeadingCapitalization {
2518 let config = MD063Config {
2519 enabled: true,
2520 style: HeadingCapStyle::TitleCase,
2521 ..Default::default()
2522 };
2523 let mut rule = MD063HeadingCapitalization::from_config_struct(config);
2524 rule.proper_names = names;
2525 rule
2526 }
2527
2528 #[test]
2529 fn test_title_case_preserves_proper_name_with_lowercase_article() {
2530 let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2534 let content = "# listening to the rolling stones today\n";
2535 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2536 let result = rule.check(&ctx).unwrap();
2537 assert_eq!(result.len(), 1, "Should flag the heading");
2538 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2539 assert!(
2540 fix_text.contains("The Rolling Stones"),
2541 "Fix should preserve proper name 'The Rolling Stones', got: {fix_text:?}"
2542 );
2543 }
2544
2545 #[test]
2546 fn test_title_case_proper_name_no_oscillation() {
2547 let rule = create_title_case_rule_with_proper_names(vec!["The Rolling Stones".to_string()]);
2549 let content = "# listening to the rolling stones today\n";
2550 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2551 let result = rule.check(&ctx).unwrap();
2552 assert_eq!(result.len(), 1);
2553 let fixed_heading = result[0].fix.as_ref().unwrap().replacement.as_str();
2554
2555 let fixed_line = format!("{fixed_heading}\n");
2556 let ctx2 = LintContext::new(&fixed_line, crate::config::MarkdownFlavor::Standard, None);
2557 let result2 = rule.check(&ctx2).unwrap();
2558 assert!(
2559 result2.is_empty(),
2560 "After one title-case fix, heading must already satisfy both rules. \
2561 Second pass warnings: {result2:?}"
2562 );
2563 }
2564
2565 #[test]
2566 fn test_title_case_unicode_casefold_expansion_before_proper_name() {
2567 let rule = create_title_case_rule_with_proper_names(vec!["Österreich".to_string()]);
2568 let content = "# İ österreich guide\n";
2569 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2570 let result = rule.check(&ctx).unwrap();
2571 assert_eq!(result.len(), 1, "Should flag the heading");
2572 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2573 assert!(
2574 fix_text.contains("Österreich"),
2575 "Fix should preserve canonical proper-name casing, got: {fix_text:?}"
2576 );
2577 }
2578
2579 #[test]
2585 fn test_from_config_loads_md044_names_into_md063() {
2586 use crate::config::{Config, RuleConfig};
2587 use crate::rule::Rule;
2588 use std::collections::BTreeMap;
2589
2590 let mut config = Config::default();
2591
2592 let mut md063_values = BTreeMap::new();
2594 md063_values.insert("style".to_string(), toml::Value::String("sentence_case".to_string()));
2595 md063_values.insert("enabled".to_string(), toml::Value::Boolean(true));
2596 config.rules.insert(
2597 "MD063".to_string(),
2598 RuleConfig {
2599 values: md063_values,
2600 severity: None,
2601 },
2602 );
2603
2604 let mut md044_values = BTreeMap::new();
2606 md044_values.insert(
2607 "names".to_string(),
2608 toml::Value::Array(vec![toml::Value::String("Good Application".to_string())]),
2609 );
2610 config.rules.insert(
2611 "MD044".to_string(),
2612 RuleConfig {
2613 values: md044_values,
2614 severity: None,
2615 },
2616 );
2617
2618 let rule = MD063HeadingCapitalization::from_config(&config);
2620
2621 let content = "# using good application features\n";
2623 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2624 let result = rule.check(&ctx).unwrap();
2625 assert_eq!(result.len(), 1, "Should flag the heading");
2626 let fix_text = result[0].fix.as_ref().unwrap().replacement.as_str();
2627 assert!(
2628 fix_text.contains("Good Application"),
2629 "from_config should wire MD044 names into MD063; fix should preserve \
2630 'Good Application', got: {fix_text:?}"
2631 );
2632 }
2633
2634 #[test]
2635 fn test_title_case_short_word_not_confused_with_substring() {
2636 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2640
2641 let content = "# in the insert\n";
2644 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2645 let result = rule.check(&ctx).unwrap();
2646 assert_eq!(result.len(), 1, "Should flag the heading");
2647 let fix = result[0].fix.as_ref().expect("Fix should be present");
2648 assert!(
2650 fix.replacement.contains("In the Insert"),
2651 "Expected 'In the Insert', got: {:?}",
2652 fix.replacement
2653 );
2654 }
2655
2656 #[test]
2657 fn test_title_case_or_not_confused_with_orchestra() {
2658 let rule = create_rule_with_style(HeadingCapStyle::TitleCase);
2659
2660 let content = "# or the orchestra\n";
2663 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2664 let result = rule.check(&ctx).unwrap();
2665 assert_eq!(result.len(), 1, "Should flag the heading");
2666 let fix = result[0].fix.as_ref().expect("Fix should be present");
2667 assert!(
2669 fix.replacement.contains("Or the Orchestra"),
2670 "Expected 'Or the Orchestra', got: {:?}",
2671 fix.replacement
2672 );
2673 }
2674
2675 #[test]
2676 fn test_all_caps_preserves_all_words() {
2677 let rule = create_rule_with_style(HeadingCapStyle::AllCaps);
2678
2679 let content = "# in the insert\n";
2680 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
2681 let result = rule.check(&ctx).unwrap();
2682 assert_eq!(result.len(), 1, "Should flag the heading");
2683 let fix = result[0].fix.as_ref().expect("Fix should be present");
2684 assert!(
2685 fix.replacement.contains("IN THE INSERT"),
2686 "All caps should uppercase all words, got: {:?}",
2687 fix.replacement
2688 );
2689 }
2690}