1mod 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#[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 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 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_index
118 .line_col_to_byte_range_with_length(line.line_num, column, 1),
119 replacement.to_string(),
120 ))
121 };
122
123 warnings.push(LintWarning {
124 rule_name: Some(self.name().to_string()),
125 line: line.line_num,
126 column,
127 end_line: line.line_num,
128 end_column: column + 1,
129 severity: Severity::Warning,
130 message: format!(
131 "Unicode character {} ({}) should be replaced with {}",
132 c,
133 unicode::format_codepoint(c),
134 replacement
135 ),
136 fix,
137 });
138 }
139 }
140
141 Ok(warnings)
142 }
143
144 fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
145 if self.should_skip(ctx) {
146 return Ok(ctx.content.to_string());
147 }
148
149 let warnings = self.check(ctx)?;
150 if warnings.is_empty() {
151 return Ok(ctx.content.to_string());
152 }
153
154 let warnings =
155 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
156 crate::utils::fix_utils::apply_warning_fixes(ctx.content, &warnings)
157 .map_err(crate::rule::LintError::InvalidInput)
158 }
159
160 fn as_any(&self) -> &dyn std::any::Any {
161 self
162 }
163
164 crate::impl_rule_config_methods!(MD088Config);
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use crate::config::{Config, MarkdownFlavor};
171
172 #[test]
173 fn test_detects_and_fixes_single_and_double_quotes_look_alikes() {
174 let rule = MD088QuotesDashes::default();
175 let ctx = LintContext::new("It\u{2019}s \u{201C}fine\u{201D}.", MarkdownFlavor::Standard, None);
176
177 let warnings = rule.check(&ctx).unwrap();
178 assert_eq!(warnings.len(), 3);
179 assert!(warnings.iter().all(|w| w.fix.is_some()));
180
181 let fixed = rule.fix(&ctx).unwrap();
182 assert_eq!(fixed, "It's \"fine\".");
183 }
184
185 #[test]
186 fn test_detects_and_fixes_dash_look_alikes() {
187 let rule = MD088QuotesDashes::from_config_struct(MD088Config {
188 normalize_dashes: true,
189 ..Default::default()
190 });
191 let ctx = LintContext::new(
192 "Dash variants: \u{2010}\u{2011}\u{2012}\u{2013}\u{2014}\u{2015}",
193 MarkdownFlavor::Standard,
194 None,
195 );
196
197 let warnings = rule.check(&ctx).unwrap();
198 assert_eq!(warnings.len(), 6);
199 assert!(warnings.iter().all(|w| w.fix.is_some()));
200
201 let fixed = rule.fix(&ctx).unwrap();
202 assert_eq!(fixed, "Dash variants: ------");
203 }
204
205 #[test]
206 fn test_detects_and_fixes_prime_marks() {
207 let rule = MD088QuotesDashes::default();
208 let ctx = LintContext::new("Sizes: 6\u{2032} and 8\u{2033}", MarkdownFlavor::Standard, None);
209
210 let warnings = rule.check(&ctx).unwrap();
211 assert_eq!(warnings.len(), 2);
212 assert!(warnings.iter().all(|w| w.fix.is_some()));
213
214 let fixed = rule.fix(&ctx).unwrap();
215 assert_eq!(fixed, "Sizes: 6' and 8\"");
216 }
217
218 #[test]
219 fn test_modifier_letters_are_spelling_not_typography() {
220 let rule = MD088QuotesDashes::default();
224 let content = "Qaraden\u{02BC}iz and Hawai\u{02BB}i.";
225 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
226
227 assert!(
228 rule.check(&ctx).unwrap().is_empty(),
229 "a modifier letter is part of a word's spelling"
230 );
231 assert_eq!(rule.fix(&ctx).unwrap(), content, "fix must not respell the words");
232
233 let ctx = LintContext::new("Qaraden\u{02BC}iz \u{2019}s.", MarkdownFlavor::Standard, None);
235 assert_eq!(rule.check(&ctx).unwrap().len(), 1);
236 assert_eq!(rule.fix(&ctx).unwrap(), "Qaraden\u{02BC}iz 's.");
237 }
238
239 #[test]
240 fn test_skips_math() {
241 let rule = MD088QuotesDashes::default();
244 let content = "Prose \u{2019}quote.\n\n$$\nx\u{2032} = y\u{2033}\n$$\n\nInline $a\u{2033}$ too.\n";
245 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
246
247 let warnings = rule.check(&ctx).unwrap();
248 assert_eq!(
249 warnings.len(),
250 1,
251 "only the prose quote is a finding, got {warnings:#?}"
252 );
253 assert_eq!(warnings[0].line, 1);
254 assert_eq!(
255 rule.fix(&ctx).unwrap(),
256 "Prose 'quote.\n\n$$\nx\u{2032} = y\u{2033}\n$$\n\nInline $a\u{2033}$ too.\n"
257 );
258
259 let ctx = LintContext::new("Sizes: 6\u{2032} and 8\u{2033}.", MarkdownFlavor::Standard, None);
262 assert_eq!(rule.check(&ctx).unwrap().len(), 2);
263 assert_eq!(rule.fix(&ctx).unwrap(), "Sizes: 6' and 8\".");
264 }
265
266 #[test]
267 fn test_skips_inline_code_spans() {
268 let rule = MD088QuotesDashes::default();
269 let content = "Prose \u{2019}quote and `code \u{2019}quote`";
270 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
271
272 let warnings = rule.check(&ctx).unwrap();
273 assert_eq!(warnings.len(), 1);
274 assert_eq!(warnings[0].column, 7);
275 assert_eq!(rule.fix(&ctx).unwrap(), "Prose 'quote and `code \u{2019}quote`");
276 }
277
278 #[test]
279 fn test_skips_fenced_and_indented_code_blocks() {
280 let rule = MD088QuotesDashes::default();
281 let content = r#"
282This is a ‘quote in prose’.
283
284```
285This is a ‘quote in fenced code block’
286```
287
288 This is a ‘quote in indented code block’
289"#;
290 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
291
292 let warnings = rule.check(&ctx).unwrap();
293 assert_eq!(warnings.len(), 2);
294 assert_eq!(
295 rule.fix(&ctx).unwrap(),
296 r#"
297This is a 'quote in prose'.
298
299```
300This is a ‘quote in fenced code block’
301```
302
303 This is a ‘quote in indented code block’
304"#
305 );
306 }
307
308 #[test]
309 fn test_no_findings_for_plain_ascii_quotes() {
310 let rule = MD088QuotesDashes::default();
311 let content = "He said, \"it's fine\".";
312 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
313
314 let warnings = rule.check(&ctx).unwrap();
315 assert!(warnings.is_empty());
316 assert_eq!(rule.fix(&ctx).unwrap(), content);
317 }
318
319 #[test]
320 fn test_allow_list_keeps_configured_codepoints() {
321 let config: Config = toml::from_str(
322 r#"
323 [MD088]
324 allow = ["U+2019", "U+2014"]
325 "#,
326 )
327 .unwrap();
328
329 let rule = MD088QuotesDashes::from_config(&config);
330 let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
331
332 let content = "It\u{2019}s \u{2014} and \u{201C}quoted\u{201D}";
333 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
334 let fixed = rule.fix(&ctx).unwrap();
335
336 assert_eq!(fixed, "It\u{2019}s \u{2014} and \"quoted\"");
337 }
338
339 #[test]
340 fn test_reports_but_does_not_fix_bare_urls() {
341 let config: Config = toml::from_str(
342 r#"
343 [MD088]
344 normalize-quotes = true
345 normalize-dashes = true
346 "#,
347 )
348 .unwrap();
349
350 let rule = MD088QuotesDashes::from_config(&config);
351 let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
352
353 let content = "Visit https://this\u{2010}site.com and \u{201C}enjoy\u{201D}!.";
354 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
355
356 let warnings = rule.check(&ctx).unwrap();
357 assert_eq!(warnings.len(), 3, "Expected 3 warnings, got {warnings:#?}");
358
359 let url_warning = warnings.iter().find(|w| w.column > 10).unwrap();
360 assert!(url_warning.fix.is_none());
361
362 let fixed = rule.fix(&ctx).unwrap();
363 assert_eq!(fixed, "Visit https://this\u{2010}site.com and \"enjoy\"!.");
364 }
365
366 #[test]
367 fn test_reports_but_does_not_fix_findings_in_link_destinations() {
368 let rule = MD088QuotesDashes::from_config_struct(MD088Config {
369 normalize_quotes: true,
370 normalize_dashes: true,
371 ..Default::default()
372 });
373 let rule = rule.as_any().downcast_ref::<MD088QuotesDashes>().unwrap();
374
375 let content = "[link](https://example\u{2010}\u{2018}.com) and prose \u{2010}.";
376 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
377
378 let warnings = rule.check(&ctx).unwrap();
379 assert_eq!(warnings.len(), 3, "Expected 3 warnings, got {warnings:#?}");
380
381 let fixed = rule.fix(&ctx).unwrap();
382 assert_eq!(fixed, "[link](https://example\u{2010}\u{2018}.com) and prose -.");
383 }
384}