Skip to main content

rumdl_lib/rules/
md049_emphasis_style.rs

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/// Rule MD049: Emphasis style
11///
12/// See [docs/md049.md](../../docs/md049.md) for full documentation, configuration, and examples.
13///
14/// This rule is triggered when the style for emphasis is inconsistent:
15/// - Asterisks: `*text*`
16/// - Underscores: `_text_`
17///
18/// This rule is focused on regular emphasis, not strong emphasis.
19#[derive(Debug, Default, Clone)]
20pub struct MD049EmphasisStyle {
21    config: MD049Config,
22}
23
24impl MD049EmphasisStyle {
25    /// Create a new instance of MD049EmphasisStyle
26    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    /// Check if a byte position is within a link (inline links, reference links, or reference definitions).
37    /// Delegates to LintContext::is_in_link which uses O(log n) binary search.
38    fn is_in_link(ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
39        ctx.is_in_link(byte_pos)
40    }
41
42    // Collect emphasis from a single line
43    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)>, // (line, col, abs_pos, marker, content)
49    ) {
50        // Replace inline code to avoid false positives. `replace_inline_code`
51        // substitutes each inline-code span with an equal-length run of 'X', so
52        // every byte offset (and thus every emphasis marker position) is
53        // identical between `line` and `line_no_code`.
54        let line_no_code = replace_inline_code(line);
55
56        // Find all emphasis markers
57        let markers = find_emphasis_markers(&line_no_code);
58        if markers.is_empty() {
59            return;
60        }
61
62        // Find single emphasis spans (not strong emphasis)
63        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; // Convert to 1-based
68            let abs_pos = line_start_pos + span.opening.start_pos;
69
70            // Use the content from the *original* line, not the code-masked copy.
71            // The span content from `line_no_code` would contain the 'X'
72            // placeholders, which must never leak into the generated fix.
73            // Marker positions are byte offsets that are valid in `line` because
74            // masking preserves byte length and span boundaries.
75            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        // Early return if no emphasis markers
101        if !ctx.likely_has_emphasis() {
102            return Ok(warnings);
103        }
104
105        // Use LintContext to skip code blocks
106        // Create LineIndex for correct byte position calculations across all line ending types
107        let line_index = &ctx.line_index;
108
109        // Collect all emphasis from the document
110        let mut emphasis_info = vec![];
111
112        // Process content lines, automatically skipping front matter, code blocks, HTML comments,
113        // MDX constructs, math blocks, and Obsidian comments
114        // Math blocks contain LaTeX syntax where _ and * have special meaning
115        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            // Skip if the line doesn't contain any emphasis markers
127            if !line.content.contains('*') && !line.content.contains('_') {
128                continue;
129            }
130
131            // Get absolute position for this line
132            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        // Filter out emphasis markers that are inside links or MkDocs markup
137        let lines = ctx.raw_lines();
138        // Math byte ranges, computed once for the whole document. The
139        // line-level `skip_math_blocks` filter drops whole math-only lines,
140        // but a line that mixes a display span with lintable prose (e.g.
141        // `$$ _x_ $$ $$ _y_ $$`) stays lintable so trailing prose is checked;
142        // this byte-level guard then exempts only the underscores that fall
143        // inside the line-start `$$...$$` span, matching MD037/MD050.
144        // `math_byte_ranges` has no code-block awareness, so a `$$` inside a
145        // fenced code block would wrongly open a span that swallows real
146        // prose up to the next `$$`. Neutralize `$` bytes inside code-block
147        // ranges first (replacing only the ASCII `$` keeps every byte offset
148        // and UTF-8 validity intact) so the byte model agrees with the
149        // code-block-aware line-level math map.
150        // Sort and merge so membership is a binary search rather than a
151        // per-span linear scan: a math-heavy document (many `$x$` spans
152        // alternating with emphasis) would otherwise be O(spans x ranges).
153        // Ranges may overlap (e.g. a `$b$` inside a `$$...$$` block), so the
154        // merge collapses them into disjoint, ascending intervals.
155        let math_ranges: Vec<(usize, usize)> = {
156            // A `$` inside fenced code or an inline code span is never a math
157            // delimiter, but `math_byte_ranges` does not know that. Neutralize
158            // those `$` first so the byte model agrees with the code-block-
159            // aware line-level math map and inline code cannot synthesize a
160            // span around real emphasis.
161            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                // Only ASCII `$` was replaced with ASCII space, so the
181                // buffer is still valid UTF-8 and the same length.
182                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            // Skip emphasis inside math. `math_ranges` is disjoint and sorted
197            // by start, so the only interval that can contain `abs_pos` is
198            // the last one whose start is <= `abs_pos`.
199            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            // Skip emphasis inside Obsidian comments
204            if ctx.is_in_obsidian_comment(*abs_pos) {
205                return false;
206            }
207            // Skip if inside a link
208            if Self::is_in_link(ctx, *abs_pos) {
209                return false;
210            }
211            // Skip if inside MkDocs markup (Keys, Caret, Mark, icon shortcodes)
212            if let Some(line) = lines.get(*line_num - 1) {
213                let line_pos = col.saturating_sub(1); // Convert 1-indexed col to 0-indexed position
214                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 we have less than 2 emphasis nodes, no need to check consistency
224                if emphasis_info.len() < 2 {
225                    return Ok(warnings);
226                }
227
228                // Count how many times each marker appears (prevalence-based approach)
229                let asterisk_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '*').count();
230                let underscore_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '_').count();
231
232                // Use the most prevalent marker as the target style
233                // In case of a tie, prefer asterisk (matches CommonMark recommendation)
234                let target_marker = if asterisk_count >= underscore_count { '*' } else { '_' };
235
236                // Check all emphasis nodes for consistency with the prevalent style
237                for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
238                    if *marker != target_marker {
239                        // Calculate emphasis length (marker + content + marker).
240                        // The byte length drives the Fix range; the character length
241                        // drives the displayed end column.
242                        let emphasis_len = 1 + content.len() + 1;
243                        let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
244
245                        warnings.push(LintWarning {
246                            rule_name: Some(self.name().to_string()),
247                            line: *line_num,
248                            column: char_col,
249                            end_line: *line_num,
250                            end_column: char_col + content.chars().count() + 2,
251                            message: format!("Emphasis should use {target_marker} instead of {marker}"),
252                            fix: Some(Fix::new(
253                                *abs_pos..*abs_pos + emphasis_len,
254                                format!("{target_marker}{content}{target_marker}"),
255                            )),
256                            severity: Severity::Warning,
257                        });
258                    }
259                }
260            }
261            EmphasisStyle::Asterisk | EmphasisStyle::Underscore => {
262                let (wrong_marker, correct_marker) = match self.config.style {
263                    EmphasisStyle::Asterisk => ('_', '*'),
264                    EmphasisStyle::Underscore => ('*', '_'),
265                    EmphasisStyle::Consistent => {
266                        // This case is handled separately above
267                        // but fallback to asterisk style for safety
268                        ('_', '*')
269                    }
270                };
271
272                for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
273                    if *marker == wrong_marker {
274                        // Calculate emphasis length (marker + content + marker).
275                        // The byte length drives the Fix range; the character length
276                        // drives the displayed end column.
277                        let emphasis_len = 1 + content.len() + 1;
278                        let (_, char_col) = ctx.offset_to_line_col(*abs_pos);
279
280                        warnings.push(LintWarning {
281                            rule_name: Some(self.name().to_string()),
282                            line: *line_num,
283                            column: char_col,
284                            end_line: *line_num,
285                            end_column: char_col + content.chars().count() + 2,
286                            message: format!("Emphasis should use {correct_marker} instead of {wrong_marker}"),
287                            fix: Some(Fix::new(
288                                *abs_pos..*abs_pos + emphasis_len,
289                                format!("{correct_marker}{content}{correct_marker}"),
290                            )),
291                            severity: Severity::Warning,
292                        });
293                    }
294                }
295            }
296        }
297        Ok(warnings)
298    }
299
300    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
301        // Get all warnings with their fixes
302        let warnings = self.check(ctx)?;
303        let warnings =
304            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
305
306        // If no warnings, return original content
307        if warnings.is_empty() {
308            return Ok(ctx.content.to_string());
309        }
310
311        // Collect all fixes and sort by range start (descending) to apply from end to beginning
312        let mut fixes: Vec<_> = warnings
313            .iter()
314            .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
315            .collect();
316        fixes.sort_by_key(|f| std::cmp::Reverse(f.0));
317
318        // Apply fixes from end to beginning to preserve byte offsets
319        let mut result = ctx.content.to_string();
320        for (start, end, replacement) in fixes {
321            if start < result.len() && end <= result.len() && start <= end {
322                result.replace_range(start..end, replacement);
323            }
324        }
325
326        Ok(result)
327    }
328
329    /// Check if this rule should be skipped
330    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
331        ctx.content.is_empty() || !ctx.likely_has_emphasis()
332    }
333
334    fn as_any(&self) -> &dyn std::any::Any {
335        self
336    }
337
338    crate::impl_rule_config_methods!(MD049Config);
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    #[test]
346    fn test_name() {
347        let rule = MD049EmphasisStyle::default();
348        assert_eq!(rule.name(), "MD049");
349    }
350
351    #[test]
352    fn test_style_from_str() {
353        assert_eq!(EmphasisStyle::from("asterisk"), EmphasisStyle::Asterisk);
354        assert_eq!(EmphasisStyle::from("underscore"), EmphasisStyle::Underscore);
355        assert_eq!(EmphasisStyle::from("other"), EmphasisStyle::Consistent);
356    }
357
358    #[test]
359    fn test_emphasis_in_links_not_flagged() {
360        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
361        let content = r#"Check this [*asterisk*](https://example.com/*pattern*) link and [_underscore_](https://example.com/_private_).
362
363Also see the [`__init__`][__init__] reference.
364
365This should be _flagged_ since we're using asterisk style.
366
367[__init__]: https://example.com/__init__.py"#;
368        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
369        let result = rule.check(&ctx).unwrap();
370
371        // Only the real emphasis outside links should be flagged
372        assert_eq!(result.len(), 1);
373        assert!(result[0].message.contains("Emphasis should use * instead of _"));
374        // Should flag "_flagged_" but not emphasis patterns inside links
375        assert!(result[0].line == 5); // Line with "_flagged_"
376    }
377
378    #[test]
379    fn test_emphasis_in_links_vs_outside_links() {
380        let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
381        let content = r#"Check [*emphasis*](https://example.com/*test*) and inline *real emphasis* text.
382
383[*link*]: https://example.com/*path*"#;
384        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
385        let result = rule.check(&ctx).unwrap();
386
387        // Only the actual emphasis outside links should be flagged
388        assert_eq!(result.len(), 1);
389        assert!(result[0].message.contains("Emphasis should use _ instead of *"));
390        // Should be the "real emphasis" text on line 1
391        assert!(result[0].line == 1);
392    }
393
394    #[test]
395    fn test_mkdocs_keys_notation_not_flagged() {
396        // Keys notation uses ++ which shouldn't be confused with emphasis
397        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
398        let content = "Press ++ctrl+alt+del++ to restart.";
399        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
400        let result = rule.check(&ctx).unwrap();
401
402        // Keys notation should not be flagged as emphasis
403        assert!(
404            result.is_empty(),
405            "Keys notation should not be flagged as emphasis. Got: {result:?}"
406        );
407    }
408
409    #[test]
410    fn test_mkdocs_caret_notation_not_flagged() {
411        // Caret notation (^superscript^ and ^^insert^^) should not be flagged
412        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
413        let content = "This is ^superscript^ and ^^inserted^^ text.";
414        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
415        let result = rule.check(&ctx).unwrap();
416
417        assert!(
418            result.is_empty(),
419            "Caret notation should not be flagged as emphasis. Got: {result:?}"
420        );
421    }
422
423    #[test]
424    fn test_mkdocs_mark_notation_not_flagged() {
425        // Mark notation (==highlight==) should not be flagged
426        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
427        let content = "This is ==highlighted== text.";
428        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
429        let result = rule.check(&ctx).unwrap();
430
431        assert!(
432            result.is_empty(),
433            "Mark notation should not be flagged as emphasis. Got: {result:?}"
434        );
435    }
436
437    #[test]
438    fn test_mkdocs_mixed_content_with_real_emphasis() {
439        // Mixed content: MkDocs markup + real emphasis that should be flagged
440        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
441        let content = "Press ++ctrl++ and _underscore emphasis_ here.";
442        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
443        let result = rule.check(&ctx).unwrap();
444
445        // Only the real underscore emphasis should be flagged (not Keys notation)
446        assert_eq!(result.len(), 1, "Expected 1 warning, got: {result:?}");
447        assert!(result[0].message.contains("Emphasis should use * instead of _"));
448    }
449
450    #[test]
451    fn test_mkdocs_icon_shortcode_not_flagged() {
452        // Icon shortcodes like :material-star: should not affect emphasis detection
453        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
454        let content = "Click :material-check: and _this should be flagged_.";
455        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
456        let result = rule.check(&ctx).unwrap();
457
458        // The underscore emphasis should still be flagged
459        assert_eq!(result.len(), 1);
460        assert!(result[0].message.contains("Emphasis should use * instead of _"));
461    }
462
463    #[test]
464    fn test_mkdocstrings_block_not_flagged() {
465        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
466        let content = "# Example\n\n::: my_module.MyClass\n    options:\n      members:\n        - _private_method\n";
467        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
468        let result = rule.check(&ctx).unwrap();
469
470        assert!(
471            result.is_empty(),
472            "_private_method_ inside mkdocstrings block should not be flagged. Got: {result:?}"
473        );
474    }
475
476    #[test]
477    fn test_mkdocstrings_block_with_emphasis_outside() {
478        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
479        let content = "::: my_module.MyClass\n    options:\n      members:\n        - _init\n\nThis _should be flagged_ outside.\n";
480        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
481        let result = rule.check(&ctx).unwrap();
482
483        assert_eq!(
484            result.len(),
485            1,
486            "Only emphasis outside mkdocstrings should be flagged. Got: {result:?}"
487        );
488        assert_eq!(result[0].line, 6);
489    }
490
491    #[test]
492    fn test_inline_code_inside_emphasis_preserved_on_fix() {
493        // Regression test: inline code inside an emphasis span must survive the
494        // style conversion. Previously the 'X' masking placeholder leaked into
495        // the fix output, destroying the code span.
496        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
497        let content = "- _An item with `inline code` inside._ Trailing text.";
498        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
499
500        let fixed = rule.fix(&ctx).unwrap();
501        assert_eq!(fixed, "- *An item with `inline code` inside.* Trailing text.");
502        assert!(!fixed.contains('X'), "masking placeholder leaked into fix: {fixed}");
503
504        // Idempotent: fixing the already-fixed content changes nothing.
505        let ctx2 = crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, None);
506        assert_eq!(rule.fix(&ctx2).unwrap(), fixed);
507    }
508
509    #[test]
510    fn test_inline_code_inside_emphasis_underscore_style() {
511        // Same bug in the opposite direction (* -> _).
512        let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
513        let content = "See *the `id` field* below.";
514        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
515        let fixed = rule.fix(&ctx).unwrap();
516        assert_eq!(fixed, "See _the `id` field_ below.");
517    }
518
519    #[test]
520    fn test_obsidian_inline_comment_emphasis_ignored() {
521        // Emphasis inside Obsidian comments should be ignored
522        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
523        let content = "Visible %%_hidden_%% text.";
524        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
525        let result = rule.check(&ctx).unwrap();
526
527        assert!(
528            result.is_empty(),
529            "Should ignore emphasis inside Obsidian comments. Got: {result:?}"
530        );
531    }
532}