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