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