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        // Source-location queries preserve correct offsets across all line ending types.
107
108        // Collect all emphasis from the document
109        let mut emphasis_info = vec![];
110
111        // Process content lines, automatically skipping front matter, code blocks, HTML comments,
112        // MDX constructs, math blocks, and Obsidian comments
113        // Math blocks contain LaTeX syntax where _ and * have special meaning
114        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            // Skip if the line doesn't contain any emphasis markers
126            if !line.content.contains('*') && !line.content.contains('_') {
127                continue;
128            }
129
130            // Get absolute position for this line
131            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        // Filter out emphasis markers that are inside links or MkDocs markup
136        let lines = ctx.raw_lines();
137        // Math byte ranges, computed once for the whole document. The
138        // line-level `skip_math_blocks` filter drops whole math-only lines,
139        // but a line that mixes a display span with lintable prose (e.g.
140        // `$$ _x_ $$ $$ _y_ $$`) stays lintable so trailing prose is checked;
141        // this byte-level guard then exempts only the underscores that fall
142        // inside the line-start `$$...$$` span, matching MD037/MD050.
143        // `math_byte_ranges` has no code-block awareness, so a `$$` inside a
144        // fenced code block would wrongly open a span that swallows real
145        // prose up to the next `$$`. Neutralize `$` bytes inside code-block
146        // ranges first (replacing only the ASCII `$` keeps every byte offset
147        // and UTF-8 validity intact) so the byte model agrees with the
148        // code-block-aware line-level math map.
149        // Sort and merge so membership is a binary search rather than a
150        // per-span linear scan: a math-heavy document (many `$x$` spans
151        // alternating with emphasis) would otherwise be O(spans x ranges).
152        // Ranges may overlap (e.g. a `$b$` inside a `$$...$$` block), so the
153        // merge collapses them into disjoint, ascending intervals.
154        let math_ranges: Vec<(usize, usize)> = {
155            // A `$` inside fenced code or an inline code span is never a math
156            // delimiter, but `math_byte_ranges` does not know that. Neutralize
157            // those `$` first so the byte model agrees with the code-block-
158            // aware line-level math map and inline code cannot synthesize a
159            // span around real emphasis.
160            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                // Only ASCII `$` was replaced with ASCII space, so the
180                // buffer is still valid UTF-8 and the same length.
181                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            // Skip emphasis inside math. `math_ranges` is disjoint and sorted
196            // by start, so the only interval that can contain `abs_pos` is
197            // the last one whose start is <= `abs_pos`.
198            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            // Skip emphasis inside Obsidian comments
203            if ctx.is_in_obsidian_comment(*abs_pos) {
204                return false;
205            }
206            // Skip if inside a link
207            if Self::is_in_link(ctx, *abs_pos) {
208                return false;
209            }
210            // Skip if inside MkDocs markup (Keys, Caret, Mark, icon shortcodes)
211            if let Some(line) = lines.get(*line_num - 1) {
212                let line_pos = col.saturating_sub(1); // Convert 1-indexed col to 0-indexed position
213                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 we have less than 2 emphasis nodes, no need to check consistency
223                if emphasis_info.len() < 2 {
224                    return Ok(warnings);
225                }
226
227                // Count how many times each marker appears (prevalence-based approach)
228                let asterisk_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '*').count();
229                let underscore_count = emphasis_info.iter().filter(|(_, _, _, m, _)| *m == '_').count();
230
231                // Use the most prevalent marker as the target style
232                // In case of a tie, prefer asterisk (matches CommonMark recommendation)
233                let target_marker = if asterisk_count >= underscore_count { '*' } else { '_' };
234
235                // Check all emphasis nodes for consistency with the prevalent style
236                for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
237                    if *marker != target_marker {
238                        // Calculate emphasis length (marker + content + marker).
239                        // The byte length drives the Fix range; the character length
240                        // drives the displayed end column.
241                        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                        // This case is handled separately above
266                        // but fallback to asterisk style for safety
267                        ('_', '*')
268                    }
269                };
270
271                for (line_num, _col, abs_pos, marker, content) in &emphasis_info {
272                    if *marker == wrong_marker {
273                        // Calculate emphasis length (marker + content + marker).
274                        // The byte length drives the Fix range; the character length
275                        // drives the displayed end column.
276                        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        // Get all warnings with their fixes
301        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 no warnings, return original content
306        if warnings.is_empty() {
307            return Ok(ctx.content.to_string());
308        }
309
310        // Collect all fixes and sort by range start (descending) to apply from end to beginning
311        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        // Apply fixes from end to beginning to preserve byte offsets
318        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    /// Check if this rule should be skipped
329    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        // Only the real emphasis outside links should be flagged
371        assert_eq!(result.len(), 1);
372        assert!(result[0].message.contains("Emphasis should use * instead of _"));
373        // Should flag "_flagged_" but not emphasis patterns inside links
374        assert!(result[0].line == 5); // Line with "_flagged_"
375    }
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        // Only the actual emphasis outside links should be flagged
387        assert_eq!(result.len(), 1);
388        assert!(result[0].message.contains("Emphasis should use _ instead of *"));
389        // Should be the "real emphasis" text on line 1
390        assert!(result[0].line == 1);
391    }
392
393    #[test]
394    fn test_mkdocs_keys_notation_not_flagged() {
395        // Keys notation uses ++ which shouldn't be confused with emphasis
396        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        // Keys notation should not be flagged as emphasis
402        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        // Caret notation (^superscript^ and ^^insert^^) should not be flagged
411        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        // Mark notation (==highlight==) should not be flagged
425        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        // Mixed content: MkDocs markup + real emphasis that should be flagged
439        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        // Only the real underscore emphasis should be flagged (not Keys notation)
445        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        // Icon shortcodes like :material-star: should not affect emphasis detection
452        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        // The underscore emphasis should still be flagged
458        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        // Regression test: inline code inside an emphasis span must survive the
493        // style conversion. Previously the 'X' masking placeholder leaked into
494        // the fix output, destroying the code span.
495        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        // Idempotent: fixing the already-fixed content changes nothing.
504        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        // Same bug in the opposite direction (* -> _).
511        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        // Emphasis inside Obsidian comments should be ignored
521        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}