1use crate::filtered_lines::FilteredLinesExt;
2use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
3use crate::rules::emphasis_style::EmphasisStyle;
4use crate::utils::emphasis_utils::{find_emphasis_markers, find_single_emphasis_spans, replace_inline_code};
5use crate::utils::skip_context::is_in_mkdocs_markup;
6
7mod md049_config;
8use md049_config::MD049Config;
9
10#[derive(Debug, Default, Clone)]
20pub struct MD049EmphasisStyle {
21 config: MD049Config,
22}
23
24impl MD049EmphasisStyle {
25 pub fn new(style: EmphasisStyle) -> Self {
27 MD049EmphasisStyle {
28 config: MD049Config { style },
29 }
30 }
31
32 pub fn from_config_struct(config: MD049Config) -> Self {
33 Self { config }
34 }
35
36 fn is_in_link(ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
39 ctx.is_in_link(byte_pos)
40 }
41
42 fn collect_emphasis_from_line(
44 &self,
45 line: &str,
46 line_num: usize,
47 line_start_pos: usize,
48 emphasis_info: &mut Vec<(usize, usize, usize, char, String)>, ) {
50 let line_no_code = replace_inline_code(line);
55
56 let markers = find_emphasis_markers(&line_no_code);
58 if markers.is_empty() {
59 return;
60 }
61
62 let spans = find_single_emphasis_spans(&line_no_code, &markers);
64
65 for span in spans {
66 let marker_char = span.opening.as_char();
67 let col = span.opening.start_pos + 1; let abs_pos = line_start_pos + span.opening.start_pos;
69
70 let content_start = span.opening.end_pos();
76 let content_end = span.closing.start_pos;
77 let original_content = line[content_start..content_end].to_string();
78
79 emphasis_info.push((line_num, col, abs_pos, marker_char, original_content));
80 }
81 }
82}
83
84impl Rule for MD049EmphasisStyle {
85 fn name(&self) -> &'static str {
86 "MD049"
87 }
88
89 fn description(&self) -> &'static str {
90 "Emphasis style should be consistent"
91 }
92
93 fn category(&self) -> RuleCategory {
94 RuleCategory::Emphasis
95 }
96
97 fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
98 let mut warnings = vec![];
99
100 if !ctx.likely_has_emphasis() {
102 return Ok(warnings);
103 }
104
105 let mut emphasis_info = vec![];
110
111 for line in ctx
116 .filtered_lines()
117 .skip_front_matter()
118 .skip_code_blocks()
119 .skip_html_blocks()
120 .skip_html_comments()
121 .skip_jsx_expressions()
122 .skip_mdx_comments()
123 .skip_math_blocks()
124 .skip_obsidian_comments()
125 .skip_mkdocstrings()
126 {
127 if !line.content.contains('*') && !line.content.contains('_') {
129 continue;
130 }
131
132 let line_start = ctx.line_start_byte(line.line_num).unwrap_or(0);
134 self.collect_emphasis_from_line(line.content, line.line_num, line_start, &mut emphasis_info);
135 }
136
137 let lines = ctx.raw_lines();
139 let math_ranges: Vec<(usize, usize)> = {
157 let code_spans = ctx.code_spans();
163 let math_source: std::borrow::Cow<'_, str> = if ctx.code_blocks.is_empty() && code_spans.is_empty() {
164 std::borrow::Cow::Borrowed(ctx.content)
165 } else {
166 let mut bytes = ctx.content.as_bytes().to_vec();
167 let len = bytes.len();
168 let mut mask = |start: usize, end: usize| {
169 for b in &mut bytes[start.min(len)..end.min(len)] {
170 if *b == b'$' {
171 *b = b' ';
172 }
173 }
174 };
175 for &(start, end) in &ctx.code_blocks {
176 mask(start, end);
177 }
178 for span in code_spans.iter() {
179 mask(span.byte_offset, span.byte_end);
180 }
181 std::borrow::Cow::Owned(String::from_utf8(bytes).expect("ASCII-only substitution"))
184 };
185 let mut r = crate::utils::skip_context::math_byte_ranges(&math_source);
186 r.sort_unstable_by_key(|&(start, _)| start);
187 let mut merged: Vec<(usize, usize)> = Vec::with_capacity(r.len());
188 for (start, end) in r {
189 match merged.last_mut() {
190 Some(last) if start <= last.1 => last.1 = last.1.max(end),
191 _ => merged.push((start, end)),
192 }
193 }
194 merged
195 };
196 emphasis_info.retain(|(line_num, col, abs_pos, _, _)| {
197 let idx = math_ranges.partition_point(|&(start, _)| start <= *abs_pos);
201 if idx > 0 && *abs_pos < math_ranges[idx - 1].1 {
202 return false;
203 }
204 if ctx.is_in_obsidian_comment(*abs_pos) {
206 return false;
207 }
208 if Self::is_in_link(ctx, *abs_pos) {
210 return false;
211 }
212 if let Some(line) = lines.get(*line_num - 1) {
214 let line_pos = col.saturating_sub(1); if is_in_mkdocs_markup(line, line_pos, ctx.flavor) {
216 return false;
217 }
218 }
219 true
220 });
221
222 match self.config.style {
223 EmphasisStyle::Consistent => {
224 if emphasis_info.len() < 2 {
226 return Ok(warnings);
227 }
228
229 let asterisk_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '*').count();
231 let underscore_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '_').count();
232
233 let target_marker = if asterisk_count >= underscore_count { '*' } else { '_' };
236
237 for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
239 if *marker != target_marker {
240 let emphasis_len = 1 + content.len() + 1;
244 let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
245
246 warnings.push(LintWarning {
247 rule_name: Some(self.name().to_string()),
248 line: *line_num,
249 column: char_col,
250 end_line: *line_num,
251 end_column: char_col + content.chars().count() + 2,
252 message: format!("Emphasis should use {target_marker} instead of {marker}"),
253 fix: Some(Fix::new(
254 *abs_pos..*abs_pos + emphasis_len,
255 format!("{target_marker}{content}{target_marker}"),
256 )),
257 severity: Severity::Warning,
258 });
259 }
260 }
261 }
262 EmphasisStyle::Asterisk | EmphasisStyle::Underscore => {
263 let (wrong_marker, correct_marker) = match self.config.style {
264 EmphasisStyle::Asterisk => ('_', '*'),
265 EmphasisStyle::Underscore => ('*', '_'),
266 EmphasisStyle::Consistent => {
267 ('_', '*')
270 }
271 };
272
273 for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
274 if *marker == wrong_marker {
275 let emphasis_len = 1 + content.len() + 1;
279 let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
280
281 warnings.push(LintWarning {
282 rule_name: Some(self.name().to_string()),
283 line: *line_num,
284 column: char_col,
285 end_line: *line_num,
286 end_column: char_col + content.chars().count() + 2,
287 message: format!("Emphasis should use {correct_marker} instead of {wrong_marker}"),
288 fix: Some(Fix::new(
289 *abs_pos..*abs_pos + emphasis_len,
290 format!("{correct_marker}{content}{correct_marker}"),
291 )),
292 severity: Severity::Warning,
293 });
294 }
295 }
296 }
297 }
298 Ok(warnings)
299 }
300
301 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
302 let warnings = self.check(ctx)?;
304 let warnings =
305 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
306
307 if warnings.is_empty() {
309 return Ok(ctx.content.to_string());
310 }
311
312 let mut fixes: Vec<_> = warnings
314 .iter()
315 .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
316 .collect();
317 fixes.sort_by_key(|f| std::cmp::Reverse(f.0));
318
319 let mut result = ctx.content.to_string();
321 for (start, end, replacement) in fixes {
322 if start < result.len() && end <= result.len() && start <= end {
323 result.replace_range(start..end, replacement);
324 }
325 }
326
327 Ok(result)
328 }
329
330 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
332 ctx.content.is_empty() || !ctx.likely_has_emphasis()
333 }
334
335 fn as_any(&self) -> &dyn std::any::Any {
336 self
337 }
338
339 crate::impl_rule_config_methods!(MD049Config);
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345
346 #[test]
347 fn test_name() {
348 let rule = MD049EmphasisStyle::default();
349 assert_eq!(rule.name(), "MD049");
350 }
351
352 #[test]
353 fn test_style_from_str() {
354 assert_eq!(EmphasisStyle::from("asterisk"), EmphasisStyle::Asterisk);
355 assert_eq!(EmphasisStyle::from("underscore"), EmphasisStyle::Underscore);
356 assert_eq!(EmphasisStyle::from("other"), EmphasisStyle::Consistent);
357 }
358
359 #[test]
360 fn test_emphasis_in_links_not_flagged() {
361 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
362 let content = r#"Check this [*asterisk*](https://example.com/*pattern*) link and [_underscore_](https://example.com/_private_).
363
364Also see the [`__init__`][__init__] reference.
365
366This should be _flagged_ since we're using asterisk style.
367
368[__init__]: https://example.com/__init__.py"#;
369 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
370 let result = rule.check(&ctx).unwrap();
371
372 assert_eq!(result.len(), 1);
374 assert!(result[0].message.contains("Emphasis should use * instead of _"));
375 assert!(result[0].line == 5); }
378
379 #[test]
380 fn test_emphasis_in_links_vs_outside_links() {
381 let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
382 let content = r#"Check [*emphasis*](https://example.com/*test*) and inline *real emphasis* text.
383
384[*link*]: https://example.com/*path*"#;
385 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
386 let result = rule.check(&ctx).unwrap();
387
388 assert_eq!(result.len(), 1);
390 assert!(result[0].message.contains("Emphasis should use _ instead of *"));
391 assert!(result[0].line == 1);
393 }
394
395 #[test]
396 fn test_mkdocs_keys_notation_not_flagged() {
397 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
399 let content = "Press ++ctrl+alt+del++ to restart.";
400 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
401 let result = rule.check(&ctx).unwrap();
402
403 assert!(
405 result.is_empty(),
406 "Keys notation should not be flagged as emphasis. Got: {result:?}"
407 );
408 }
409
410 #[test]
411 fn test_mkdocs_caret_notation_not_flagged() {
412 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
414 let content = "This is ^superscript^ and ^^inserted^^ text.";
415 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
416 let result = rule.check(&ctx).unwrap();
417
418 assert!(
419 result.is_empty(),
420 "Caret notation should not be flagged as emphasis. Got: {result:?}"
421 );
422 }
423
424 #[test]
425 fn test_mkdocs_mark_notation_not_flagged() {
426 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
428 let content = "This is ==highlighted== text.";
429 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
430 let result = rule.check(&ctx).unwrap();
431
432 assert!(
433 result.is_empty(),
434 "Mark notation should not be flagged as emphasis. Got: {result:?}"
435 );
436 }
437
438 #[test]
439 fn test_mkdocs_mixed_content_with_real_emphasis() {
440 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
442 let content = "Press ++ctrl++ and _underscore emphasis_ here.";
443 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
444 let result = rule.check(&ctx).unwrap();
445
446 assert_eq!(result.len(), 1, "Expected 1 warning, got: {result:?}");
448 assert!(result[0].message.contains("Emphasis should use * instead of _"));
449 }
450
451 #[test]
452 fn test_mkdocs_icon_shortcode_not_flagged() {
453 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
455 let content = "Click :material-check: and _this should be flagged_.";
456 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
457 let result = rule.check(&ctx).unwrap();
458
459 assert_eq!(result.len(), 1);
461 assert!(result[0].message.contains("Emphasis should use * instead of _"));
462 }
463
464 #[test]
465 fn test_mkdocstrings_block_not_flagged() {
466 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
467 let content = "# Example\n\n::: my_module.MyClass\n options:\n members:\n - _private_method\n";
468 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
469 let result = rule.check(&ctx).unwrap();
470
471 assert!(
472 result.is_empty(),
473 "_private_method_ inside mkdocstrings block should not be flagged. Got: {result:?}"
474 );
475 }
476
477 #[test]
478 fn test_mkdocstrings_block_with_emphasis_outside() {
479 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
480 let content = "::: my_module.MyClass\n options:\n members:\n - _init\n\nThis _should be flagged_ outside.\n";
481 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
482 let result = rule.check(&ctx).unwrap();
483
484 assert_eq!(
485 result.len(),
486 1,
487 "Only emphasis outside mkdocstrings should be flagged. Got: {result:?}"
488 );
489 assert_eq!(result[0].line, 6);
490 }
491
492 #[test]
493 fn test_inline_code_inside_emphasis_preserved_on_fix() {
494 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
498 let content = "- _An item with `inline code` inside._ Trailing text.";
499 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
500
501 let fixed = rule.fix(&ctx).unwrap();
502 assert_eq!(fixed, "- *An item with `inline code` inside.* Trailing text.");
503 assert!(!fixed.contains('X'), "masking placeholder leaked into fix: {fixed}");
504
505 let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
507 assert_eq!(rule.fix(&ctx2).unwrap(), fixed);
508 }
509
510 #[test]
511 fn test_inline_code_inside_emphasis_underscore_style() {
512 let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
514 let content = "See *the `id` field* below.";
515 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
516 let fixed = rule.fix(&ctx).unwrap();
517 assert_eq!(fixed, "See _the `id` field_ below.");
518 }
519
520 #[test]
521 fn test_obsidian_inline_comment_emphasis_ignored() {
522 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
524 let content = "Visible %%_hidden_%% text.";
525 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
526 let result = rule.check(&ctx).unwrap();
527
528 assert!(
529 result.is_empty(),
530 "Should ignore emphasis inside Obsidian comments. Got: {result:?}"
531 );
532 }
533
534 #[test]
535 fn test_asterisks_in_an_html_block_are_literal() {
536 let rule = MD049EmphasisStyle::new(EmphasisStyle::Consistent);
539 let content =
540 "Use _a_ and _b_.\n\n<table>\n <tr>\n <td><code>*://*.example.org/*</code></td>\n </tr>\n</table>\n";
541 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
542 assert!(rule.check(&ctx).unwrap().is_empty());
543 assert_eq!(rule.fix(&ctx).unwrap(), content);
544
545 let content = "Use _a_.\n\n<div>\n*b* and *c*\n</div>\n";
546 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
547 assert!(rule.check(&ctx).unwrap().is_empty());
548 }
549
550 #[test]
551 fn test_emphasis_after_an_html_block_is_still_checked() {
552 let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
554 let content = "<div>\n*a*\n</div>\n\nText *b* here.\n";
555 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
556 let result = rule.check(&ctx).unwrap();
557 assert_eq!(result.iter().map(|w| w.line).collect::<Vec<_>>(), vec![5]);
558 }
559}