1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use crate::rule_config_serde::FlavorOverrideNotice;
6use crate::utils::range_utils::calculate_match_range;
7use crate::utils::regex_cache::{EMOJI_SHORTCODE_REGEX, HTML_ENTITY_REGEX};
8use regex::Regex;
9use std::collections::HashMap;
10use std::ops::Range;
11use std::sync::LazyLock;
12use std::sync::RwLock;
13
14mod md026_config;
15use md026_config::{DEFAULT_PUNCTUATION, MD026Config};
16
17static ATX_HEADING_UNIFIED: LazyLock<Regex> =
19 LazyLock::new(|| Regex::new(r"^( {0,3})(#{1,6})(\s+)(.+?)(\s+#{1,6})?$").unwrap());
20
21static QUICK_PUNCTUATION_CHECK: LazyLock<Regex> =
23 LazyLock::new(|| Regex::new(&format!(r"[{}]", regex::escape(DEFAULT_PUNCTUATION))).unwrap());
24
25static PUNCTUATION_REGEX_CACHE: LazyLock<RwLock<HashMap<String, Regex>>> =
27 LazyLock::new(|| RwLock::new(HashMap::new()));
28
29static MDG_PUNCTUATION_OVERRIDE: FlavorOverrideNotice = FlavorOverrideNotice::new();
31
32#[derive(Clone)]
34pub struct MD026NoTrailingPunctuation {
35 config: MD026Config,
36 mdg_punctuation: String,
40 colon_configured_explicitly: bool,
43}
44
45impl Default for MD026NoTrailingPunctuation {
46 fn default() -> Self {
47 Self::new(None)
48 }
49}
50
51impl MD026NoTrailingPunctuation {
52 pub fn new(punctuation: Option<String>) -> Self {
53 let explicit = punctuation.is_some();
54 Self::build(
55 MD026Config {
56 punctuation: punctuation.unwrap_or_else(|| DEFAULT_PUNCTUATION.to_string()),
57 },
58 explicit,
59 )
60 }
61
62 pub fn from_config_struct(config: MD026Config) -> Self {
63 Self::build(config, false)
64 }
65
66 fn build(config: MD026Config, punctuation_explicit: bool) -> Self {
67 let colon_configured_explicitly = punctuation_explicit && config.punctuation.contains(':');
68 let mdg_punctuation = config.punctuation.replace(':', "");
69
70 Self {
71 config,
72 mdg_punctuation,
73 colon_configured_explicitly,
74 }
75 }
76
77 #[inline]
79 fn effective_punctuation(&self, flavor: crate::config::MarkdownFlavor) -> &str {
80 if flavor == crate::config::MarkdownFlavor::MDG {
81 &self.mdg_punctuation
82 } else {
83 &self.config.punctuation
84 }
85 }
86
87 fn mdg_colon_override_applies(&self, flavor: crate::config::MarkdownFlavor) -> bool {
89 flavor == crate::config::MarkdownFlavor::MDG && self.colon_configured_explicitly
90 }
91
92 fn warn_once_about_mdg_colon_override(&self, flavor: crate::config::MarkdownFlavor) {
97 if self.mdg_colon_override_applies(flavor) {
98 MDG_PUNCTUATION_OVERRIDE.report(
99 "MD026",
100 "punctuation",
101 &self.config.punctuation,
102 &self.mdg_punctuation,
103 "the ASCII colon after a Gherkin keyword is structural",
104 );
105 }
106 }
107
108 #[inline]
109 fn get_punctuation_regex(&self, punctuation: &str) -> Result<Regex, regex::Error> {
110 {
112 let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
113 if let Some(cached_regex) = cache.get(punctuation) {
114 return Ok(cached_regex.clone());
115 }
116 }
117
118 let pattern = format!(r"([{}]+)$", regex::escape(punctuation));
120 let regex = Regex::new(&pattern)?;
121
122 {
123 let mut cache = PUNCTUATION_REGEX_CACHE.write().unwrap();
124 cache.insert(punctuation.to_string(), regex.clone());
125 }
126
127 Ok(regex)
128 }
129
130 fn trailing_punctuation_run(&self, text: &str, re: &Regex) -> Option<Range<usize>> {
141 let mut start = re.find(text)?.start();
142 let constructs = HTML_ENTITY_REGEX
143 .find_iter(text)
144 .chain(EMOJI_SHORTCODE_REGEX.find_iter(text));
145 for construct in constructs {
146 if Self::is_backslash_escaped(text, construct.start()) {
147 continue;
148 }
149 start = start.max(construct.end());
150 }
151 (start < text.len()).then_some(start..text.len())
152 }
153
154 fn is_backslash_escaped(text: &str, pos: usize) -> bool {
158 text[..pos].bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1
159 }
160
161 #[inline]
171 fn remove_trailing_punctuation(&self, text: &str, re: &Regex) -> String {
172 let mut result = text.trim().to_string();
173 loop {
174 let Some(run) = self.trailing_punctuation_run(&result, re) else {
175 return result;
177 };
178 result.truncate(run.start);
179 let trimmed_len = result.trim_end().len();
182 if trimmed_len != result.len() && self.trailing_punctuation_run(&result[..trimmed_len], re).is_some() {
183 result.truncate(trimmed_len);
184 } else {
185 return result;
186 }
187 }
188 }
189
190 #[inline]
192 fn fix_atx_heading(&self, line: &str, re: &Regex) -> String {
193 if let Some(captures) = ATX_HEADING_UNIFIED.captures(line) {
194 let indentation = captures.get(1).unwrap().as_str();
195 let hashes = captures.get(2).unwrap().as_str();
196 let space = captures.get(3).unwrap().as_str();
197 let content = captures.get(4).unwrap().as_str();
198
199 let fixed_content = if let Some(id_pos) = content.rfind(" {#") {
202 let before_id = &content[..id_pos];
204 let id_part = &content[id_pos..];
205 let fixed_before = self.remove_trailing_punctuation(before_id, re);
206 format!("{fixed_before}{id_part}")
207 } else {
208 self.remove_trailing_punctuation(content, re)
210 };
211
212 if let Some(trailing) = captures.get(5) {
214 return format!(
215 "{}{}{}{}{}",
216 indentation,
217 hashes,
218 space,
219 fixed_content,
220 trailing.as_str()
221 );
222 }
223
224 return format!("{indentation}{hashes}{space}{fixed_content}");
225 }
226
227 line.to_string()
229 }
230
231 #[inline]
233 fn fix_setext_heading(&self, content_line: &str, re: &Regex) -> String {
234 let trimmed = content_line.trim_end();
235 let mut whitespace = "";
236
237 if content_line.len() > trimmed.len() {
239 whitespace = &content_line[trimmed.len()..];
240 }
241
242 format!("{}{}", self.remove_trailing_punctuation(trimmed, re), whitespace)
244 }
245}
246
247impl Rule for MD026NoTrailingPunctuation {
248 fn name(&self) -> &'static str {
249 "MD026"
250 }
251
252 fn description(&self) -> &'static str {
253 "Trailing punctuation in heading"
254 }
255
256 fn category(&self) -> RuleCategory {
257 RuleCategory::Heading
258 }
259
260 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
261 self.warn_once_about_mdg_colon_override(ctx.flavor);
262
263 if !ctx.likely_has_headings() {
265 return true;
266 }
267 let punctuation = self.effective_punctuation(ctx.flavor);
269 !punctuation.chars().any(|p| ctx.content.contains(p))
270 }
271
272 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
273 let content = ctx.content;
274 let punctuation = self.effective_punctuation(ctx.flavor);
275
276 self.warn_once_about_mdg_colon_override(ctx.flavor);
277
278 if content.is_empty() {
280 return Ok(Vec::new());
281 }
282
283 if punctuation == DEFAULT_PUNCTUATION {
286 if !QUICK_PUNCTUATION_CHECK.is_match(content) {
287 return Ok(Vec::new());
288 }
289 } else {
290 let has_custom_punctuation = punctuation.chars().any(|c| content.contains(c));
292 if !has_custom_punctuation {
293 return Ok(Vec::new());
294 }
295 }
296
297 let has_headings = ctx.lines.iter().any(|line| line.heading.is_some());
299 if !has_headings {
300 return Ok(Vec::new());
301 }
302
303 let mut warnings = Vec::new();
304 let Ok(re) = self.get_punctuation_regex(punctuation) else {
305 return Ok(warnings);
306 };
307
308 for (line_num, line_info) in ctx.lines.iter().enumerate() {
310 if let Some(heading) = &line_info.heading {
311 if !heading.is_valid {
313 continue;
314 }
315
316 if line_info.visual_indent >= 4 && matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
318 continue;
319 }
320
321 let text_to_check = heading.text.as_str();
325
326 let Some(run) = self.trailing_punctuation_run(text_to_check, &re) else {
327 continue;
328 };
329 let line = line_info.content(ctx.content);
330
331 let text_pos_in_line = line.find(&heading.text).unwrap_or(heading.content_column);
333 let punctuation_start_in_line = text_pos_in_line + run.start;
334
335 let (start_line, start_col, end_line, end_col) = calculate_match_range(
336 line_num + 1, line,
338 punctuation_start_in_line,
339 run.len(),
340 );
341
342 let last_char = text_to_check.chars().last().unwrap_or(' ');
343 warnings.push(LintWarning {
344 rule_name: Some(self.name().to_string()),
345 line: start_line,
346 column: start_col,
347 end_line,
348 end_column: end_col,
349 message: format!("Heading '{text_to_check}' ends with punctuation '{last_char}'"),
350 severity: Severity::Warning,
351 fix: Some(Fix::new(
352 ctx.line_content_byte_range(line_num + 1),
353 if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
354 self.fix_atx_heading(line, &re)
355 } else {
356 self.fix_setext_heading(line, &re)
357 },
358 )),
359 });
360 }
361 }
362
363 Ok(warnings)
364 }
365
366 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
367 if self.should_skip(ctx) {
368 return Ok(ctx.content.to_string());
369 }
370 let warnings = self.check(ctx)?;
371 if warnings.is_empty() {
372 return Ok(ctx.content.to_string());
373 }
374 let warnings =
375 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
376 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
377 .map_err(crate::rule::LintError::InvalidInput)
378 }
379
380 fn as_any(&self) -> &dyn std::any::Any {
381 self
382 }
383
384 crate::impl_rule_config_sections!(MD026Config);
385
386 fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
387 where
388 Self: Sized,
389 {
390 let rule_config = crate::rule_config_serde::load_rule_config::<MD026Config>(config);
391
392 let punctuation_explicit = config
395 .rules
396 .get("MD026")
397 .is_some_and(|rule_cfg| rule_cfg.values.contains_key("punctuation"));
398
399 Box::new(Self::build(rule_config, punctuation_explicit))
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use crate::lint_context::LintContext;
407
408 #[test]
409 fn test_no_trailing_punctuation() {
410 let rule = MD026NoTrailingPunctuation::new(None);
411 let content = "# This is a heading\n\n## Another heading";
412 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
413 let result = rule.check(&ctx).unwrap();
414 assert!(result.is_empty(), "Headings without punctuation should not be flagged");
415 }
416
417 #[test]
418 fn test_trailing_period() {
419 let rule = MD026NoTrailingPunctuation::new(None);
420 let content = "# This is a heading.\n\n## Another one.";
421 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
422 let result = rule.check(&ctx).unwrap();
423 assert_eq!(result.len(), 2);
424 assert_eq!(result[0].line, 1);
425 assert_eq!(result[0].column, 20);
426 assert!(result[0].message.contains("ends with punctuation '.'"));
427 assert_eq!(result[1].line, 3);
428 assert_eq!(result[1].column, 15);
429 }
430
431 #[test]
432 fn test_trailing_comma() {
433 let rule = MD026NoTrailingPunctuation::new(None);
434 let content = "# Heading,\n## Sub-heading,";
435 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
436 let result = rule.check(&ctx).unwrap();
437 assert_eq!(result.len(), 2);
438 assert!(result[0].message.contains("ends with punctuation ','"));
439 }
440
441 #[test]
442 fn test_trailing_semicolon() {
443 let rule = MD026NoTrailingPunctuation::new(None);
444 let content = "# Title;\n## Subtitle;";
445 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
446 let result = rule.check(&ctx).unwrap();
447 assert_eq!(result.len(), 2);
448 assert!(result[0].message.contains("ends with punctuation ';'"));
449 }
450
451 #[test]
452 fn test_custom_punctuation() {
453 let rule = MD026NoTrailingPunctuation::new(Some("!".to_string()));
454 let content = "# Important!\n## Regular heading.";
455 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
456 let result = rule.check(&ctx).unwrap();
457 assert_eq!(result.len(), 1, "Only exclamation should be flagged with custom config");
458 assert_eq!(result[0].line, 1);
459 assert!(result[0].message.contains("ends with punctuation '!'"));
460 }
461
462 #[test]
463 fn test_legitimate_question_mark() {
464 let rule = MD026NoTrailingPunctuation::new(Some(".,;?".to_string()));
465 let content = "# What is this?\n# This is bad.";
466 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
467 let result = rule.check(&ctx).unwrap();
468 assert_eq!(result.len(), 2, "Both should be flagged with custom punctuation");
470 }
471
472 #[test]
473 fn test_question_marks_not_in_default() {
474 let rule = MD026NoTrailingPunctuation::new(None);
475 let content = "# What is Rust?\n# How does it work?\n# Is it fast?";
476 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
477 let result = rule.check(&ctx).unwrap();
478 assert!(result.is_empty(), "Question marks are not in default punctuation list");
479 }
480
481 #[test]
482 fn test_colons_in_default() {
483 let rule = MD026NoTrailingPunctuation::new(None);
484 let content = "# FAQ:\n# API Reference:\n# Step 1:\n# Version 2.0:";
485 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
486 let result = rule.check(&ctx).unwrap();
487 assert_eq!(
488 result.len(),
489 4,
490 "Colons are in default punctuation list and should be flagged"
491 );
492 }
493
494 #[test]
495 fn test_fix_atx_headings() {
496 let rule = MD026NoTrailingPunctuation::new(None);
497 let content = "# Title.\n## Subtitle,\n### Sub-subtitle;";
498 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
499 let fixed = rule.fix(&ctx).unwrap();
500 assert_eq!(fixed, "# Title\n## Subtitle\n### Sub-subtitle");
501 }
502
503 #[test]
504 fn test_fix_setext_headings() {
505 let rule = MD026NoTrailingPunctuation::new(None);
506 let content = "Title.\n======\n\nSubtitle,\n---------";
507 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
508 let fixed = rule.fix(&ctx).unwrap();
509 assert_eq!(fixed, "Title\n======\n\nSubtitle\n---------");
510 }
511
512 #[test]
513 fn test_fix_preserves_trailing_hashes() {
514 let rule = MD026NoTrailingPunctuation::new(None);
515 let content = "# Title. #\n## Subtitle, ##";
516 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
517 let fixed = rule.fix(&ctx).unwrap();
518 assert_eq!(fixed, "# Title #\n## Subtitle ##");
519 }
520
521 #[test]
522 fn test_indented_headings() {
523 let rule = MD026NoTrailingPunctuation::new(None);
524 let content = " # Title.\n ## Subtitle.";
525 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
526 let result = rule.check(&ctx).unwrap();
527 assert_eq!(result.len(), 2, "Indented headings (< 4 spaces) should be checked");
528 }
529
530 #[test]
531 fn test_deeply_indented_ignored() {
532 let rule = MD026NoTrailingPunctuation::new(None);
533 let content = " # This is code.";
534 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
535 let result = rule.check(&ctx).unwrap();
536 assert!(result.is_empty(), "Deeply indented lines (4+ spaces) should be ignored");
537 }
538
539 #[test]
540 fn test_multiple_punctuation() {
541 let rule = MD026NoTrailingPunctuation::new(None);
542 let content = "# Title...";
543 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
544 let result = rule.check(&ctx).unwrap();
545 assert_eq!(result.len(), 1);
546 assert_eq!(result[0].column, 8); }
548
549 #[test]
550 fn test_empty_content() {
551 let rule = MD026NoTrailingPunctuation::new(None);
552 let content = "";
553 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
554 let result = rule.check(&ctx).unwrap();
555 assert!(result.is_empty());
556 }
557
558 #[test]
559 fn test_no_headings() {
560 let rule = MD026NoTrailingPunctuation::new(None);
561 let content = "This is just text.\nMore text with punctuation.";
562 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
563 let result = rule.check(&ctx).unwrap();
564 assert!(result.is_empty(), "Non-heading lines should not be checked");
565 }
566
567 #[test]
568 fn test_get_punctuation_regex() {
569 let rule = MD026NoTrailingPunctuation::new(Some("!?".to_string()));
570 let regex = rule.get_punctuation_regex(&rule.config.punctuation).unwrap();
571 assert!(regex.is_match("text!"));
572 assert!(regex.is_match("text?"));
573 assert!(!regex.is_match("text."));
574 }
575
576 #[test]
577 fn test_regex_caching() {
578 let rule1 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
579 let rule2 = MD026NoTrailingPunctuation::new(Some("!".to_string()));
580
581 let _regex1 = rule1.get_punctuation_regex(&rule1.config.punctuation).unwrap();
583 let _regex2 = rule2.get_punctuation_regex(&rule2.config.punctuation).unwrap();
584
585 let cache = PUNCTUATION_REGEX_CACHE.read().unwrap();
587 assert!(cache.contains_key("!"));
588 }
589
590 #[test]
591 fn test_config_from_toml() {
592 let mut config = crate::config::Config::default();
593 let mut rule_config = crate::config::RuleConfig::default();
594 rule_config
595 .values
596 .insert("punctuation".to_string(), toml::Value::String("!?".to_string()));
597 config.rules.insert("MD026".to_string(), rule_config);
598
599 let rule = MD026NoTrailingPunctuation::from_config(&config);
600 let content = "# Title!\n# Another?";
601 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
602 let result = rule.check(&ctx).unwrap();
603 assert_eq!(result.len(), 2, "Custom punctuation from config should be used");
604 }
605
606 #[test]
607 fn test_fix_removes_punctuation() {
608 let rule = MD026NoTrailingPunctuation::new(None);
609 let content = "# Title. \n## Subtitle, ";
610 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
611 let fixed = rule.fix(&ctx).unwrap();
612 assert_eq!(fixed, "# Title\n## Subtitle");
614 }
615
616 #[test]
617 fn test_final_newline_preservation() {
618 let rule = MD026NoTrailingPunctuation::new(None);
619 let content = "# Title.\n";
620 let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
621 let fixed = rule.fix(&ctx).unwrap();
622 assert_eq!(fixed, "# Title\n");
623
624 let content_no_newline = "# Title.";
625 let ctx2 = LintContext::new(content_no_newline, crate::config::MarkdownFlavor::Standard, None);
626 let fixed2 = rule.fix(&ctx2).unwrap();
627 assert_eq!(fixed2, "# Title");
628 }
629
630 #[test]
636 fn test_mdg_punctuation_matrix() {
637 let rule = MD026NoTrailingPunctuation::new(None);
638 let cases = [
640 ("## Notes:\n", 1, "## Notes\n", 0, "## Notes:\n"),
641 ("## Scenario!:\n", 1, "## Scenario\n", 0, "## Scenario!:\n"),
642 ("# Scenario! :\n", 1, "# Scenario\n", 0, "# Scenario! :\n"),
643 ("## Scenario!\n", 1, "## Scenario\n", 1, "## Scenario\n"),
644 ("## Notes::\n", 1, "## Notes\n", 0, "## Notes::\n"),
645 (
646 "# Feature: Checkout:\n",
647 1,
648 "# Feature: Checkout\n",
649 0,
650 "# Feature: Checkout:\n",
651 ),
652 ("### Rule.:\n", 1, "### Rule\n", 0, "### Rule.:\n"),
653 ];
654
655 for (input, standard_count, standard_fixed, mdg_count, mdg_fixed) in cases {
656 for (flavor, count, expected) in [
657 (crate::config::MarkdownFlavor::Standard, standard_count, standard_fixed),
658 (crate::config::MarkdownFlavor::MDG, mdg_count, mdg_fixed),
659 ] {
660 let ctx = LintContext::new(input, flavor, None);
661 assert_eq!(
662 rule.check(&ctx).unwrap().len(),
663 count,
664 "{flavor:?} warning count for {input:?}"
665 );
666
667 let fixed = rule.fix(&ctx).unwrap();
668 assert_eq!(fixed, expected, "{flavor:?} fix for {input:?}");
669
670 let fixed_ctx = LintContext::new(&fixed, flavor, None);
671 assert!(
672 rule.check(&fixed_ctx).unwrap().is_empty(),
673 "{flavor:?} left a warning on the fixed {input:?}"
674 );
675 assert_eq!(
676 rule.fix(&fixed_ctx).unwrap(),
677 fixed,
678 "{flavor:?} fix for {input:?} should be idempotent"
679 );
680 }
681 }
682 }
683
684 #[test]
687 fn test_mdg_reports_an_explicitly_configured_colon_once() {
688 fn configured(punctuation: &str) -> MD026NoTrailingPunctuation {
689 let mut config = crate::config::Config::default();
690 let mut rule_config = crate::config::RuleConfig::default();
691 rule_config
692 .values
693 .insert("punctuation".to_string(), toml::Value::String(punctuation.to_string()));
694 config.rules.insert("MD026".to_string(), rule_config);
695
696 MD026NoTrailingPunctuation::from_config(&config)
697 .as_any()
698 .downcast_ref::<MD026NoTrailingPunctuation>()
699 .expect("MD026::from_config builds an MD026NoTrailingPunctuation")
700 .clone()
701 }
702
703 let explicit = configured(".,;:!");
704 assert_eq!(
705 explicit.effective_punctuation(crate::config::MarkdownFlavor::Standard),
706 ".,;:!"
707 );
708 assert_eq!(
709 explicit.effective_punctuation(crate::config::MarkdownFlavor::MDG),
710 ".,;!"
711 );
712 assert!(
713 !explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::Standard),
714 "a non-Gherkin file never reports the override"
715 );
716 assert!(explicit.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG));
717
718 let emitted_by_check = configured(".,;:!");
719 let ctx = LintContext::new("## Scenario!\n", crate::config::MarkdownFlavor::MDG, None);
720 assert_eq!(emitted_by_check.check(&ctx).unwrap().len(), 1);
721
722 let emitted_before_skip = configured(".,;:!");
723 let only_protected_punctuation = LintContext::new("#### Examples:\n", crate::config::MarkdownFlavor::MDG, None);
724 assert!(
725 emitted_before_skip.should_skip(&only_protected_punctuation),
726 "the post-override punctuation set has nothing to inspect"
727 );
728
729 let explicit_without_colon = configured(".,;!");
730 assert!(
731 !explicit_without_colon.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
732 "nothing is overridden when the configured set has no colon"
733 );
734
735 let default = MD026NoTrailingPunctuation::new(None);
736 assert_eq!(
737 default.effective_punctuation(crate::config::MarkdownFlavor::MDG),
738 ".,;!",
739 "the colon leaves the default set too"
740 );
741 assert!(
742 !default.mdg_colon_override_applies(crate::config::MarkdownFlavor::MDG),
743 "the default set is not an explicit configuration, so it is silent"
744 );
745 }
746
747 #[test]
748 fn test_mdg_exempts_a_lone_colon_behind_whitespace() {
749 let rule = MD026NoTrailingPunctuation::new(None);
753 let content = "# Scenario :\n## Notes:\n";
754
755 let standard_ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
756 let standard = rule.check(&standard_ctx).unwrap();
757 assert_eq!(standard.len(), 2);
758 assert_eq!((standard[0].line, standard[0].column), (1, 12));
759 assert_eq!((standard[1].line, standard[1].column), (2, 9));
760 let standard_fixed = rule.fix(&standard_ctx).unwrap();
761 assert_eq!(standard_fixed, "# Scenario \n## Notes\n");
762 let standard_fixed_ctx = LintContext::new(&standard_fixed, crate::config::MarkdownFlavor::Standard, None);
763 assert_eq!(
764 rule.fix(&standard_fixed_ctx).unwrap(),
765 standard_fixed,
766 "Standard fix should be idempotent"
767 );
768
769 let mdg_ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
770 assert!(rule.check(&mdg_ctx).unwrap().is_empty());
771 assert_eq!(
772 rule.fix(&mdg_ctx).unwrap(),
773 content,
774 "MDG leaves headings whose only trailing punctuation is the colon untouched"
775 );
776 }
777
778 #[test]
779 fn test_mdg_does_not_exempt_a_full_width_colon() {
780 let rule = MD026NoTrailingPunctuation::new(Some(".,;:!?:".to_string()));
783 assert_eq!(
784 rule.effective_punctuation(crate::config::MarkdownFlavor::MDG),
785 ".,;!?:",
786 "only the ASCII colon leaves the set"
787 );
788
789 let content = "## Scenario:\n";
790 for flavor in [
791 crate::config::MarkdownFlavor::MDG,
792 crate::config::MarkdownFlavor::Standard,
793 ] {
794 let ctx = LintContext::new(content, flavor, None);
795 assert_eq!(rule.check(&ctx).unwrap().len(), 1, "{flavor:?} must flag the `:`");
796 assert_eq!(rule.fix(&ctx).unwrap(), "## Scenario\n");
797 }
798 }
799}