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