Skip to main content

rumdl_lib/rules/
md088_quotes_dashes.rs

1//! Rule MD088: Replace look-alike quotes and dashes with ASCII equivalents.
2//!
3//! This rule flags all kinds of Unicode quotes and optionally dashes
4//! that are often introduced by smart-quote substitutions and rich text copy/paste,
5//! and replaces them with plain ASCII equivalents.
6
7mod md088_config;
8
9use crate::filtered_lines::FilteredLinesExt;
10use crate::lint_context::LintContext;
11use crate::rule::{Fix, FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
12use crate::utils::range_utils::byte_to_char_count;
13use crate::utils::skip_context::is_in_math_context;
14use crate::utils::unicode;
15use md088_config::MD088Config;
16
17/// Rule MD088: Look-alike punctuation.
18#[derive(Debug, Clone)]
19pub struct MD088QuotesDashes {
20    config: MD088Config,
21}
22
23impl Default for MD088QuotesDashes {
24    fn default() -> Self {
25        Self::from_config_struct(MD088Config::default())
26    }
27}
28
29impl MD088QuotesDashes {
30    fn from_config_struct(config: MD088Config) -> Self {
31        Self { config }
32    }
33
34    #[inline]
35    fn is_allowed(&self, c: char) -> bool {
36        self.config.allow.contains(&c)
37    }
38
39    #[inline]
40    fn replacement_for(&self, c: char) -> Option<&'static str> {
41        if self.is_allowed(c) {
42            return None;
43        }
44
45        // U+02BC MODIFIER LETTER APOSTROPHE is deliberately absent. It is a
46        // Modifier_Letter, not punctuation: Crimean Tatar, Nenets and Chechen spell
47        // words with it, so rewriting it to ASCII changes a word rather than its
48        // typography. U+02BB, the Hawaiian okina, is the same category and is absent
49        // for the same reason.
50        match c {
51            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2032}' if self.config.normalize_quotes => Some("'"),
52            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{2033}' if self.config.normalize_quotes => {
53                Some("\"")
54            }
55            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
56                if self.config.normalize_dashes =>
57            {
58                Some("-")
59            }
60            _ => None,
61        }
62    }
63
64    #[inline]
65    fn has_target_char(&self, ctx: &LintContext) -> bool {
66        ctx.content.chars().any(|c| self.replacement_for(c).is_some())
67    }
68}
69
70impl Rule for MD088QuotesDashes {
71    fn name(&self) -> &'static str {
72        "MD088"
73    }
74
75    fn description(&self) -> &'static str {
76        "Quotes and dashes should be replaced with ASCII equivalents"
77    }
78
79    fn category(&self) -> RuleCategory {
80        RuleCategory::Whitespace
81    }
82
83    fn fix_capability(&self) -> FixCapability {
84        FixCapability::FullyFixable
85    }
86
87    fn should_skip(&self, ctx: &LintContext) -> bool {
88        ctx.content.is_empty() || !self.has_target_char(ctx)
89    }
90
91    fn check(&self, ctx: &LintContext) -> LintResult {
92        let mut warnings = Vec::new();
93
94        for line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
95            for (byte_idx, c) in line.content.char_indices() {
96                let Some(replacement) = self.replacement_for(c) else {
97                    continue;
98                };
99
100                let absolute_byte = line.line_info.byte_offset + byte_idx;
101                if ctx.is_byte_offset_in_code_span(absolute_byte) {
102                    continue;
103                }
104
105                // Math is notation, not prose: `′` and `″` are the prime and double
106                // prime of a derivative or a unit, and their ASCII look-alikes do not
107                // typeset as primes.
108                if is_in_math_context(ctx, absolute_byte) {
109                    continue;
110                }
111
112                let column = byte_to_char_count(line.content, byte_idx);
113                let fix = if ctx.is_in_link(absolute_byte) || ctx.is_in_bare_url(absolute_byte) {
114                    None
115                } else {
116                    Some(Fix::new(
117                        ctx.line_column_byte_range_with_length(line.line_num, column, 1),
118                        replacement.to_string(),
119                    ))
120                };
121
122                warnings.push(LintWarning {
123                    rule_name: Some(self.name().to_string()),
124                    line: line.line_num,
125                    column,
126                    end_line: line.line_num,
127                    end_column: column + 1,
128                    severity: Severity::Warning,
129                    message: format!(
130                        "Unicode character {} ({}) should be replaced with {}",
131                        c,
132                        unicode::format_codepoint(c),
133                        replacement
134                    ),
135                    fix,
136                });
137            }
138        }
139
140        Ok(warnings)
141    }
142
143    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
144        if self.should_skip(ctx) {
145            return Ok(ctx.content.to_string());
146        }
147
148        let warnings = self.check(ctx)?;
149        if warnings.is_empty() {
150            return Ok(ctx.content.to_string());
151        }
152
153        let warnings =
154            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
155        crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
156            .map_err(crate::rule::LintError::InvalidInput)
157    }
158
159    fn as_any(&self) -> &dyn std::any::Any {
160        self
161    }
162
163    crate::impl_rule_config_methods!(MD088Config);
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::config::{Config, MarkdownFlavor};
170
171    #[test]
172    fn test_detects_and_fixes_single_and_double_quotes_look_alikes() {
173        let rule = MD088QuotesDashes::default();
174        let ctx = LintContext::new("It\u{2019}s \u{201C}fine\u{201D}.", MarkdownFlavor::Standard, None);
175
176        let warnings = rule.check(&ctx).unwrap();
177        assert_eq!(warnings.len(), 3);
178        assert!(warnings.iter().all(|w| w.fix.is_some()));
179
180        let fixed = rule.fix(&ctx).unwrap();
181        assert_eq!(fixed, "It's \"fine\".");
182    }
183
184    #[test]
185    fn test_detects_and_fixes_dash_look_alikes() {
186        let rule = MD088QuotesDashes::from_config_struct(MD088Config {
187            normalize_dashes: true,
188            ..Default::default()
189        });
190        let ctx = LintContext::new(
191            "Dash variants: \u{2010}\u{2011}\u{2012}\u{2013}\u{2014}\u{2015}",
192            MarkdownFlavor::Standard,
193            None,
194        );
195
196        let warnings = rule.check(&ctx).unwrap();
197        assert_eq!(warnings.len(), 6);
198        assert!(warnings.iter().all(|w| w.fix.is_some()));
199
200        let fixed = rule.fix(&ctx).unwrap();
201        assert_eq!(fixed, "Dash variants: ------");
202    }
203
204    #[test]
205    fn test_detects_and_fixes_prime_marks() {
206        let rule = MD088QuotesDashes::default();
207        let ctx = LintContext::new("Sizes: 6\u{2032} and 8\u{2033}", MarkdownFlavor::Standard, None);
208
209        let warnings = rule.check(&ctx).unwrap();
210        assert_eq!(warnings.len(), 2);
211        assert!(warnings.iter().all(|w| w.fix.is_some()));
212
213        let fixed = rule.fix(&ctx).unwrap();
214        assert_eq!(fixed, "Sizes: 6' and 8\"");
215    }
216
217    #[test]
218    fn test_modifier_letters_are_spelling_not_typography() {
219        // U+02BC and U+02BB are Modifier_Letter, so they spell words rather than quote
220        // them. Rewriting either to ASCII would change `Qaradenʼiz` into a different
221        // word, which no `allow` entry should be needed to prevent.
222        let rule = MD088QuotesDashes::default();
223        let content = "Qaraden\u{02BC}iz and Hawai\u{02BB}i.";
224        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
225
226        assert!(
227            rule.check(&ctx).unwrap().is_empty(),
228            "a modifier letter is part of a word's spelling"
229        );
230        assert_eq!(rule.fix(&ctx).unwrap(), content, "fix must not respell the words");
231
232        // Control: a real quotation mark in the same sentence is still normalized.
233        let ctx = LintContext::new("Qaraden\u{02BC}iz \u{2019}s.", MarkdownFlavor::Standard, None);
234        assert_eq!(rule.check(&ctx).unwrap().len(), 1);
235        assert_eq!(rule.fix(&ctx).unwrap(), "Qaraden\u{02BC}iz 's.");
236    }
237
238    #[test]
239    fn test_skips_math() {
240        // In math, `′` and `″` are prime and double prime. ASCII `'` renders as a prime
241        // but `"` does not, so normalizing changes the notation the reader sees.
242        let rule = MD088QuotesDashes::default();
243        let content = "Prose \u{2019}quote.\n\n$$\nx\u{2032} = y\u{2033}\n$$\n\nInline $a\u{2033}$ too.\n";
244        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
245
246        let warnings = rule.check(&ctx).unwrap();
247        assert_eq!(
248            warnings.len(),
249            1,
250            "only the prose quote is a finding, got {warnings:#?}"
251        );
252        assert_eq!(warnings[0].line, 1);
253        assert_eq!(
254            rule.fix(&ctx).unwrap(),
255            "Prose 'quote.\n\n$$\nx\u{2032} = y\u{2033}\n$$\n\nInline $a\u{2033}$ too.\n"
256        );
257
258        // Control: the same primes outside math are still normalized, so the guard is
259        // about math and not about primes.
260        let ctx = LintContext::new("Sizes: 6\u{2032} and 8\u{2033}.", MarkdownFlavor::Standard, None);
261        assert_eq!(rule.check(&ctx).unwrap().len(), 2);
262        assert_eq!(rule.fix(&ctx).unwrap(), "Sizes: 6' and 8\".");
263    }
264
265    #[test]
266    fn test_skips_inline_code_spans() {
267        let rule = MD088QuotesDashes::default();
268        let content = "Prose \u{2019}quote and `code \u{2019}quote`";
269        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
270
271        let warnings = rule.check(&ctx).unwrap();
272        assert_eq!(warnings.len(), 1);
273        assert_eq!(warnings[0].column, 7);
274        assert_eq!(rule.fix(&ctx).unwrap(), "Prose 'quote and `code \u{2019}quote`");
275    }
276
277    #[test]
278    fn test_skips_fenced_and_indented_code_blocks() {
279        let rule = MD088QuotesDashes::default();
280        let content = r#"
281This is a ‘quote in prose’.
282
283```
284This is a ‘quote in fenced code block’
285```
286
287    This is a ‘quote in indented code block’
288"#;
289        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
290
291        let warnings = rule.check(&ctx).unwrap();
292        assert_eq!(warnings.len(), 2);
293        assert_eq!(
294            rule.fix(&ctx).unwrap(),
295            r#"
296This is a 'quote in prose'.
297
298```
299This is a ‘quote in fenced code block’
300```
301
302    This is a ‘quote in indented code block’
303"#
304        );
305    }
306
307    #[test]
308    fn test_no_findings_for_plain_ascii_quotes() {
309        let rule = MD088QuotesDashes::default();
310        let content = "He said, \"it's fine\".";
311        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
312
313        let warnings = rule.check(&ctx).unwrap();
314        assert!(warnings.is_empty());
315        assert_eq!(rule.fix(&ctx).unwrap(), content);
316    }
317
318    #[test]
319    fn test_allow_list_keeps_configured_codepoints() {
320        let config: Config = toml::from_str(
321            r#"
322            [MD088]
323            allow = ["U+2019", "U+2014"]
324            "#,
325        )
326        .unwrap();
327
328        let rule = MD088QuotesDashes::from_config(&config);
329        let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
330
331        let content = "It\u{2019}s \u{2014} and \u{201C}quoted\u{201D}";
332        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
333        let fixed = rule.fix(&ctx).unwrap();
334
335        assert_eq!(fixed, "It\u{2019}s \u{2014} and \"quoted\"");
336    }
337
338    #[test]
339    fn test_reports_but_does_not_fix_bare_urls() {
340        let config: Config = toml::from_str(
341            r#"
342            [MD088]
343            normalize-quotes = true
344            normalize-dashes = true
345            "#,
346        )
347        .unwrap();
348
349        let rule = MD088QuotesDashes::from_config(&config);
350        let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
351
352        let content = "Visit https://this\u{2010}site.com and \u{201C}enjoy\u{201D}!.";
353        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
354
355        let warnings = rule.check(&ctx).unwrap();
356        assert_eq!(warnings.len(), 3, "Expected 3 warnings, got {warnings:#?}");
357
358        let url_warning = warnings.iter().find(|w| w.column > 10).unwrap();
359        assert!(url_warning.fix.is_none());
360
361        let fixed = rule.fix(&ctx).unwrap();
362        assert_eq!(fixed, "Visit https://this\u{2010}site.com and \"enjoy\"!.");
363    }
364
365    #[test]
366    fn test_reports_but_does_not_fix_findings_in_link_destinations() {
367        let rule = MD088QuotesDashes::from_config_struct(MD088Config {
368            normalize_quotes: true,
369            normalize_dashes: true,
370            ..Default::default()
371        });
372        let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
373
374        let content = "[link](https://example\u{2010}\u{2018}.com) and prose \u{2010}.";
375        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
376
377        let warnings = rule.check(&ctx).unwrap();
378        assert_eq!(warnings.len(), 3, "Expected 3 warnings, got {warnings:#?}");
379
380        let fixed = rule.fix(&ctx).unwrap();
381        assert_eq!(fixed, "[link](https://example\u{2010}\u{2018}.com) and prose -.");
382    }
383}