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
115 .filtered_lines()
116 .skip_front_matter()
117 .skip_code_blocks()
118 .skip_html_comments()
119 .skip_jsx_expressions()
120 .skip_mdx_comments()
121 .skip_math_blocks()
122 .skip_obsidian_comments()
123 .skip_mkdocstrings()
124 {
125 if !line.content.contains('*') && !line.content.contains('_') {
127 continue;
128 }
129
130 let line_start = ctx.line_start_byte(line.line_num).unwrap_or(0);
132 self.collect_emphasis_from_line(line.content, line.line_num, line_start, &mut emphasis_info);
133 }
134
135 let lines = ctx.raw_lines();
137 let math_ranges: Vec<(usize, usize)> = {
155 let code_spans = ctx.code_spans();
161 let math_source: std::borrow::Cow<'_, str> = if ctx.code_blocks.is_empty() && code_spans.is_empty() {
162 std::borrow::Cow::Borrowed(ctx.content)
163 } else {
164 let mut bytes = ctx.content.as_bytes().to_vec();
165 let len = bytes.len();
166 let mut mask = |start: usize, end: usize| {
167 for b in &mut bytes[start.min(len)..end.min(len)] {
168 if *b == b'$' {
169 *b = b' ';
170 }
171 }
172 };
173 for &(start, end) in &ctx.code_blocks {
174 mask(start, end);
175 }
176 for span in code_spans.iter() {
177 mask(span.byte_offset, span.byte_end);
178 }
179 std::borrow::Cow::Owned(String::from_utf8(bytes).expect("ASCII-only substitution"))
182 };
183 let mut r = crate::utils::skip_context::math_byte_ranges(&math_source);
184 r.sort_unstable_by_key(|&(start, _)| start);
185 let mut merged: Vec<(usize, usize)> = Vec::with_capacity(r.len());
186 for (start, end) in r {
187 match merged.last_mut() {
188 Some(last) if start <= last.1 => last.1 = last.1.max(end),
189 _ => merged.push((start, end)),
190 }
191 }
192 merged
193 };
194 emphasis_info.retain(|(line_num, col, abs_pos, _, _)| {
195 let idx = math_ranges.partition_point(|&(start, _)| start <= *abs_pos);
199 if idx > 0 && *abs_pos < math_ranges[idx - 1].1 {
200 return false;
201 }
202 if ctx.is_in_obsidian_comment(*abs_pos) {
204 return false;
205 }
206 if Self::is_in_link(ctx, *abs_pos) {
208 return false;
209 }
210 if let Some(line) = lines.get(*line_num - 1) {
212 let line_pos = col.saturating_sub(1); if is_in_mkdocs_markup(line, line_pos, ctx.flavor) {
214 return false;
215 }
216 }
217 true
218 });
219
220 match self.config.style {
221 EmphasisStyle::Consistent => {
222 if emphasis_info.len() < 2 {
224 return Ok(warnings);
225 }
226
227 let asterisk_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '*').count();
229 let underscore_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '_').count();
230
231 let target_marker = if asterisk_count >= underscore_count { '*' } else { '_' };
234
235 for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
237 if *marker != target_marker {
238 let emphasis_len = 1 + content.len() + 1;
242 let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
243
244 warnings.push(LintWarning {
245 rule_name: Some(self.name().to_string()),
246 line: *line_num,
247 column: char_col,
248 end_line: *line_num,
249 end_column: char_col + content.chars().count() + 2,
250 message: format!("Emphasis should use {target_marker} instead of {marker}"),
251 fix: Some(Fix::new(
252 *abs_pos..*abs_pos + emphasis_len,
253 format!("{target_marker}{content}{target_marker}"),
254 )),
255 severity: Severity::Warning,
256 });
257 }
258 }
259 }
260 EmphasisStyle::Asterisk | EmphasisStyle::Underscore => {
261 let (wrong_marker, correct_marker) = match self.config.style {
262 EmphasisStyle::Asterisk => ('_', '*'),
263 EmphasisStyle::Underscore => ('*', '_'),
264 EmphasisStyle::Consistent => {
265 ('_', '*')
268 }
269 };
270
271 for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
272 if *marker == wrong_marker {
273 let emphasis_len = 1 + content.len() + 1;
277 let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
278
279 warnings.push(LintWarning {
280 rule_name: Some(self.name().to_string()),
281 line: *line_num,
282 column: char_col,
283 end_line: *line_num,
284 end_column: char_col + content.chars().count() + 2,
285 message: format!("Emphasis should use {correct_marker} instead of {wrong_marker}"),
286 fix: Some(Fix::new(
287 *abs_pos..*abs_pos + emphasis_len,
288 format!("{correct_marker}{content}{correct_marker}"),
289 )),
290 severity: Severity::Warning,
291 });
292 }
293 }
294 }
295 }
296 Ok(warnings)
297 }
298
299 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
300 let warnings = self.check(ctx)?;
302 let warnings =
303 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
304
305 if warnings.is_empty() {
307 return Ok(ctx.content.to_string());
308 }
309
310 let mut fixes: Vec<_> = warnings
312 .iter()
313 .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
314 .collect();
315 fixes.sort_by_key(|f| std::cmp::Reverse(f.0));
316
317 let mut result = ctx.content.to_string();
319 for (start, end, replacement) in fixes {
320 if start < result.len() && end <= result.len() && start <= end {
321 result.replace_range(start..end, replacement);
322 }
323 }
324
325 Ok(result)
326 }
327
328 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
330 ctx.content.is_empty() || !ctx.likely_has_emphasis()
331 }
332
333 fn as_any(&self) -> &dyn std::any::Any {
334 self
335 }
336
337 crate::impl_rule_config_methods!(MD049Config);
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 #[test]
345 fn test_name() {
346 let rule = MD049EmphasisStyle::default();
347 assert_eq!(rule.name(), "MD049");
348 }
349
350 #[test]
351 fn test_style_from_str() {
352 assert_eq!(EmphasisStyle::from("asterisk"), EmphasisStyle::Asterisk);
353 assert_eq!(EmphasisStyle::from("underscore"), EmphasisStyle::Underscore);
354 assert_eq!(EmphasisStyle::from("other"), EmphasisStyle::Consistent);
355 }
356
357 #[test]
358 fn test_emphasis_in_links_not_flagged() {
359 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
360 let content = r#"Check this [*asterisk*](https://example.com/*pattern*) link and [_underscore_](https://example.com/_private_).
361
362Also see the [`__init__`][__init__] reference.
363
364This should be _flagged_ since we're using asterisk style.
365
366[__init__]: https://example.com/__init__.py"#;
367 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
368 let result = rule.check(&ctx).unwrap();
369
370 assert_eq!(result.len(), 1);
372 assert!(result[0].message.contains("Emphasis should use * instead of _"));
373 assert!(result[0].line == 5); }
376
377 #[test]
378 fn test_emphasis_in_links_vs_outside_links() {
379 let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
380 let content = r#"Check [*emphasis*](https://example.com/*test*) and inline *real emphasis* text.
381
382[*link*]: https://example.com/*path*"#;
383 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
384 let result = rule.check(&ctx).unwrap();
385
386 assert_eq!(result.len(), 1);
388 assert!(result[0].message.contains("Emphasis should use _ instead of *"));
389 assert!(result[0].line == 1);
391 }
392
393 #[test]
394 fn test_mkdocs_keys_notation_not_flagged() {
395 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
397 let content = "Press ++ctrl+alt+del++ to restart.";
398 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
399 let result = rule.check(&ctx).unwrap();
400
401 assert!(
403 result.is_empty(),
404 "Keys notation should not be flagged as emphasis. Got: {result:?}"
405 );
406 }
407
408 #[test]
409 fn test_mkdocs_caret_notation_not_flagged() {
410 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
412 let content = "This is ^superscript^ and ^^inserted^^ text.";
413 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
414 let result = rule.check(&ctx).unwrap();
415
416 assert!(
417 result.is_empty(),
418 "Caret notation should not be flagged as emphasis. Got: {result:?}"
419 );
420 }
421
422 #[test]
423 fn test_mkdocs_mark_notation_not_flagged() {
424 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
426 let content = "This is ==highlighted== text.";
427 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
428 let result = rule.check(&ctx).unwrap();
429
430 assert!(
431 result.is_empty(),
432 "Mark notation should not be flagged as emphasis. Got: {result:?}"
433 );
434 }
435
436 #[test]
437 fn test_mkdocs_mixed_content_with_real_emphasis() {
438 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
440 let content = "Press ++ctrl++ and _underscore emphasis_ here.";
441 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
442 let result = rule.check(&ctx).unwrap();
443
444 assert_eq!(result.len(), 1, "Expected 1 warning, got: {result:?}");
446 assert!(result[0].message.contains("Emphasis should use * instead of _"));
447 }
448
449 #[test]
450 fn test_mkdocs_icon_shortcode_not_flagged() {
451 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
453 let content = "Click :material-check: and _this should be flagged_.";
454 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
455 let result = rule.check(&ctx).unwrap();
456
457 assert_eq!(result.len(), 1);
459 assert!(result[0].message.contains("Emphasis should use * instead of _"));
460 }
461
462 #[test]
463 fn test_mkdocstrings_block_not_flagged() {
464 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
465 let content = "# Example\n\n::: my_module.MyClass\n options:\n members:\n - _private_method\n";
466 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
467 let result = rule.check(&ctx).unwrap();
468
469 assert!(
470 result.is_empty(),
471 "_private_method_ inside mkdocstrings block should not be flagged. Got: {result:?}"
472 );
473 }
474
475 #[test]
476 fn test_mkdocstrings_block_with_emphasis_outside() {
477 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
478 let content = "::: my_module.MyClass\n options:\n members:\n - _init\n\nThis _should be flagged_ outside.\n";
479 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
480 let result = rule.check(&ctx).unwrap();
481
482 assert_eq!(
483 result.len(),
484 1,
485 "Only emphasis outside mkdocstrings should be flagged. Got: {result:?}"
486 );
487 assert_eq!(result[0].line, 6);
488 }
489
490 #[test]
491 fn test_inline_code_inside_emphasis_preserved_on_fix() {
492 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
496 let content = "- _An item with `inline code` inside._ Trailing text.";
497 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
498
499 let fixed = rule.fix(&ctx).unwrap();
500 assert_eq!(fixed, "- *An item with `inline code` inside.* Trailing text.");
501 assert!(!fixed.contains('X'), "masking placeholder leaked into fix: {fixed}");
502
503 let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
505 assert_eq!(rule.fix(&ctx2).unwrap(), fixed);
506 }
507
508 #[test]
509 fn test_inline_code_inside_emphasis_underscore_style() {
510 let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
512 let content = "See *the `id` field* below.";
513 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
514 let fixed = rule.fix(&ctx).unwrap();
515 assert_eq!(fixed, "See _the `id` field_ below.");
516 }
517
518 #[test]
519 fn test_obsidian_inline_comment_emphasis_ignored() {
520 let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
522 let content = "Visible %%_hidden_%% text.";
523 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
524 let result = rule.check(&ctx).unwrap();
525
526 assert!(
527 result.is_empty(),
528 "Should ignore emphasis inside Obsidian comments. Got: {result:?}"
529 );
530 }
531}