rumdl_lib/rules/
md037_spaces_around_emphasis.rs

1/// Rule MD037: No spaces around emphasis markers
2///
3/// See [docs/md037.md](../../docs/md037.md) for full documentation, configuration, and examples.
4use crate::filtered_lines::FilteredLinesExt;
5use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
6use crate::utils::emphasis_utils::{
7    EmphasisSpan, find_emphasis_markers, find_emphasis_spans, has_doc_patterns, replace_inline_code,
8};
9use crate::utils::kramdown_utils::has_span_ial;
10use crate::utils::regex_cache::UNORDERED_LIST_MARKER_REGEX;
11use crate::utils::skip_context::{is_in_html_comment, is_in_math_context, is_in_table_cell};
12
13/// Check if an emphasis span has spacing issues that should be flagged
14#[inline]
15fn has_spacing_issues(span: &EmphasisSpan) -> bool {
16    span.has_leading_space || span.has_trailing_space
17}
18
19/// Truncate long text for display in warning messages
20/// Shows first ~30 and last ~30 chars with ellipsis in middle for readability
21#[inline]
22fn truncate_for_display(text: &str, max_len: usize) -> String {
23    if text.len() <= max_len {
24        return text.to_string();
25    }
26
27    let prefix_len = max_len / 2 - 2; // -2 for "..."
28    let suffix_len = max_len / 2 - 2;
29
30    // Use floor_char_boundary to safely find UTF-8 character boundaries
31    let prefix_end = text.floor_char_boundary(prefix_len.min(text.len()));
32    let suffix_start = text.floor_char_boundary(text.len().saturating_sub(suffix_len));
33
34    format!("{}...{}", &text[..prefix_end], &text[suffix_start..])
35}
36
37/// Rule MD037: Spaces inside emphasis markers
38#[derive(Clone)]
39pub struct MD037NoSpaceInEmphasis;
40
41impl Default for MD037NoSpaceInEmphasis {
42    fn default() -> Self {
43        Self
44    }
45}
46
47impl MD037NoSpaceInEmphasis {
48    /// Check if a byte position is within a link (inline links, reference links, or reference definitions)
49    fn is_in_link(&self, ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
50        // Check inline and reference links
51        for link in &ctx.links {
52            if link.byte_offset <= byte_pos && byte_pos < link.byte_end {
53                return true;
54            }
55        }
56
57        // Check images (which use similar syntax)
58        for image in &ctx.images {
59            if image.byte_offset <= byte_pos && byte_pos < image.byte_end {
60                return true;
61            }
62        }
63
64        // Check reference definitions [ref]: url "title" using pre-computed data (O(1) vs O(n))
65        ctx.is_in_reference_def(byte_pos)
66    }
67}
68
69impl Rule for MD037NoSpaceInEmphasis {
70    fn name(&self) -> &'static str {
71        "MD037"
72    }
73
74    fn description(&self) -> &'static str {
75        "Spaces inside emphasis markers"
76    }
77
78    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
79        let content = ctx.content;
80        let _timer = crate::profiling::ScopedTimer::new("MD037_check");
81
82        // Early return: if no emphasis markers at all, skip processing
83        if !content.contains('*') && !content.contains('_') {
84            return Ok(vec![]);
85        }
86
87        // Create LineIndex for correct byte position calculations across all line ending types
88        let line_index = &ctx.line_index;
89
90        let mut warnings = Vec::new();
91
92        // Process content lines, automatically skipping front matter and code blocks
93        for line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
94            // Skip if the line doesn't contain any emphasis markers
95            if !line.content.contains('*') && !line.content.contains('_') {
96                continue;
97            }
98
99            // Check for emphasis issues on the original line
100            self.check_line_for_emphasis_issues_fast(line.content, line.line_num, &mut warnings);
101        }
102
103        // Filter out warnings for emphasis markers that are inside links, HTML comments, or math
104        let mut filtered_warnings = Vec::new();
105
106        for (line_idx, _line) in content.lines().enumerate() {
107            let line_num = line_idx + 1;
108            let line_start_pos = line_index.get_line_start_byte(line_num).unwrap_or(0);
109
110            // Find warnings for this line
111            for warning in &warnings {
112                if warning.line == line_num {
113                    // Calculate byte position of the warning
114                    let byte_pos = line_start_pos + (warning.column - 1);
115
116                    // Skip if inside links, HTML comments, math contexts, or tables
117                    if !self.is_in_link(ctx, byte_pos)
118                        && !is_in_html_comment(content, byte_pos)
119                        && !is_in_math_context(ctx, byte_pos)
120                        && !is_in_table_cell(ctx, line_num, warning.column)
121                    {
122                        filtered_warnings.push(warning.clone());
123                    }
124                }
125            }
126        }
127
128        Ok(filtered_warnings)
129    }
130
131    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
132        let content = ctx.content;
133        let _timer = crate::profiling::ScopedTimer::new("MD037_fix");
134
135        // Fast path: if no emphasis markers, return unchanged
136        if !content.contains('*') && !content.contains('_') {
137            return Ok(content.to_string());
138        }
139
140        // First check for issues and get all warnings with fixes
141        let warnings = self.check(ctx)?;
142
143        // If no warnings, return original content
144        if warnings.is_empty() {
145            return Ok(content.to_string());
146        }
147
148        // Create LineIndex for correct byte position calculations across all line ending types
149        let line_index = &ctx.line_index;
150
151        // Apply fixes
152        let mut result = content.to_string();
153        let mut offset: isize = 0;
154
155        // Sort warnings by position to apply fixes in the correct order
156        let mut sorted_warnings: Vec<_> = warnings.iter().filter(|w| w.fix.is_some()).collect();
157        sorted_warnings.sort_by_key(|w| (w.line, w.column));
158
159        for warning in sorted_warnings {
160            if let Some(fix) = &warning.fix {
161                // Calculate the absolute position in the file
162                let line_start = line_index.get_line_start_byte(warning.line).unwrap_or(0);
163                let abs_start = line_start + warning.column - 1;
164                let abs_end = abs_start + (fix.range.end - fix.range.start);
165
166                // Apply fix with offset adjustment
167                let actual_start = (abs_start as isize + offset) as usize;
168                let actual_end = (abs_end as isize + offset) as usize;
169
170                // Make sure we're not out of bounds
171                if actual_start < result.len() && actual_end <= result.len() {
172                    // Replace the text
173                    result.replace_range(actual_start..actual_end, &fix.replacement);
174                    // Update offset for future replacements
175                    offset += fix.replacement.len() as isize - (fix.range.end - fix.range.start) as isize;
176                }
177            }
178        }
179
180        Ok(result)
181    }
182
183    /// Get the category of this rule for selective processing
184    fn category(&self) -> RuleCategory {
185        RuleCategory::Emphasis
186    }
187
188    /// Check if this rule should be skipped
189    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
190        ctx.content.is_empty() || !ctx.likely_has_emphasis()
191    }
192
193    fn as_any(&self) -> &dyn std::any::Any {
194        self
195    }
196
197    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
198    where
199        Self: Sized,
200    {
201        Box::new(MD037NoSpaceInEmphasis)
202    }
203}
204
205impl MD037NoSpaceInEmphasis {
206    /// Optimized line checking for emphasis spacing issues
207    #[inline]
208    fn check_line_for_emphasis_issues_fast(&self, line: &str, line_num: usize, warnings: &mut Vec<LintWarning>) {
209        // Quick documentation pattern checks
210        if has_doc_patterns(line) {
211            return;
212        }
213
214        // Optimized list detection with fast path
215        if (line.starts_with(' ') || line.starts_with('*') || line.starts_with('+') || line.starts_with('-'))
216            && UNORDERED_LIST_MARKER_REGEX.is_match(line)
217        {
218            if let Some(caps) = UNORDERED_LIST_MARKER_REGEX.captures(line)
219                && let Some(full_match) = caps.get(0)
220            {
221                let list_marker_end = full_match.end();
222                if list_marker_end < line.len() {
223                    let remaining_content = &line[list_marker_end..];
224
225                    if self.is_likely_list_item_fast(remaining_content) {
226                        self.check_line_content_for_emphasis_fast(
227                            remaining_content,
228                            line_num,
229                            list_marker_end,
230                            warnings,
231                        );
232                    } else {
233                        self.check_line_content_for_emphasis_fast(line, line_num, 0, warnings);
234                    }
235                }
236            }
237            return;
238        }
239
240        // Check the entire line
241        self.check_line_content_for_emphasis_fast(line, line_num, 0, warnings);
242    }
243
244    /// Fast list item detection with optimized logic
245    #[inline]
246    fn is_likely_list_item_fast(&self, content: &str) -> bool {
247        let trimmed = content.trim();
248
249        // Early returns for obvious cases
250        if trimmed.is_empty() || trimmed.len() < 3 {
251            return false;
252        }
253
254        // Quick word count using bytes
255        let word_count = trimmed.split_whitespace().count();
256
257        // Short content ending with * is likely emphasis
258        if word_count <= 2 && trimmed.ends_with('*') && !trimmed.ends_with("**") {
259            return false;
260        }
261
262        // Long content (4+ words) without emphasis is likely a list
263        if word_count >= 4 {
264            // Quick check: if no emphasis markers, it's a list
265            if !trimmed.contains('*') && !trimmed.contains('_') {
266                return true;
267            }
268        }
269
270        // For ambiguous cases, default to emphasis (more conservative)
271        false
272    }
273
274    /// Optimized line content checking for emphasis issues
275    fn check_line_content_for_emphasis_fast(
276        &self,
277        content: &str,
278        line_num: usize,
279        offset: usize,
280        warnings: &mut Vec<LintWarning>,
281    ) {
282        // Replace inline code to avoid false positives with emphasis markers inside backticks
283        let processed_content = replace_inline_code(content);
284
285        // Find all emphasis markers using optimized parsing
286        let markers = find_emphasis_markers(&processed_content);
287        if markers.is_empty() {
288            return;
289        }
290
291        // Find valid emphasis spans
292        let spans = find_emphasis_spans(&processed_content, markers);
293
294        // Check each span for spacing issues
295        for span in spans {
296            if has_spacing_issues(&span) {
297                // Calculate the full span including markers
298                let full_start = span.opening.start_pos;
299                let full_end = span.closing.end_pos();
300                let full_text = &content[full_start..full_end];
301
302                // Skip if this emphasis has a Kramdown span IAL immediately after it
303                // (no space between emphasis and IAL)
304                if full_end < content.len() {
305                    let remaining = &content[full_end..];
306                    // Check if IAL starts immediately after the emphasis (no whitespace)
307                    if remaining.starts_with('{') && has_span_ial(remaining.split_whitespace().next().unwrap_or("")) {
308                        continue;
309                    }
310                }
311
312                // Create the marker string efficiently
313                let marker_char = span.opening.as_char();
314                let marker_str = if span.opening.count == 1 {
315                    marker_char.to_string()
316                } else {
317                    format!("{marker_char}{marker_char}")
318                };
319
320                // Create the fixed version by trimming spaces from content
321                let trimmed_content = span.content.trim();
322                let fixed_text = format!("{marker_str}{trimmed_content}{marker_str}");
323
324                // Truncate long emphasis spans for readable warning messages
325                let display_text = truncate_for_display(full_text, 60);
326
327                let warning = LintWarning {
328                    rule_name: Some(self.name().to_string()),
329                    message: format!("Spaces inside emphasis markers: {display_text:?}"),
330                    line: line_num,
331                    column: offset + full_start + 1, // +1 because columns are 1-indexed
332                    end_line: line_num,
333                    end_column: offset + full_end + 1,
334                    severity: Severity::Warning,
335                    fix: Some(Fix {
336                        range: (offset + full_start)..(offset + full_end),
337                        replacement: fixed_text,
338                    }),
339                };
340
341                warnings.push(warning);
342            }
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use crate::lint_context::LintContext;
351
352    #[test]
353    fn test_emphasis_marker_parsing() {
354        let markers = find_emphasis_markers("This has *single* and **double** emphasis");
355        assert_eq!(markers.len(), 4); // *, *, **, **
356
357        let markers = find_emphasis_markers("*start* and *end*");
358        assert_eq!(markers.len(), 4); // *, *, *, *
359    }
360
361    #[test]
362    fn test_emphasis_span_detection() {
363        let markers = find_emphasis_markers("This has *valid* emphasis");
364        let spans = find_emphasis_spans("This has *valid* emphasis", markers);
365        assert_eq!(spans.len(), 1);
366        assert_eq!(spans[0].content, "valid");
367        assert!(!spans[0].has_leading_space);
368        assert!(!spans[0].has_trailing_space);
369
370        let markers = find_emphasis_markers("This has * invalid * emphasis");
371        let spans = find_emphasis_spans("This has * invalid * emphasis", markers);
372        assert_eq!(spans.len(), 1);
373        assert_eq!(spans[0].content, " invalid ");
374        assert!(spans[0].has_leading_space);
375        assert!(spans[0].has_trailing_space);
376    }
377
378    #[test]
379    fn test_with_document_structure() {
380        let rule = MD037NoSpaceInEmphasis;
381
382        // Test with no spaces inside emphasis - should pass
383        let content = "This is *correct* emphasis and **strong emphasis**";
384        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
385        let result = rule.check(&ctx).unwrap();
386        assert!(result.is_empty(), "No warnings expected for correct emphasis");
387
388        // Test with actual spaces inside emphasis - use content that should warn
389        let content = "This is * text with spaces * and more content";
390        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
391        let result = rule.check(&ctx).unwrap();
392        assert!(!result.is_empty(), "Expected warnings for spaces in emphasis");
393
394        // Test with code blocks - emphasis in code should be ignored
395        let content = "This is *correct* emphasis\n```\n* incorrect * in code block\n```\nOutside block with * spaces in emphasis *";
396        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
397        let result = rule.check(&ctx).unwrap();
398        assert!(
399            !result.is_empty(),
400            "Expected warnings for spaces in emphasis outside code block"
401        );
402    }
403
404    #[test]
405    fn test_emphasis_in_links_not_flagged() {
406        let rule = MD037NoSpaceInEmphasis;
407        let content = r#"Check this [* spaced asterisk *](https://example.com/*test*) link.
408
409This has * real spaced emphasis * that should be flagged."#;
410        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
411        let result = rule.check(&ctx).unwrap();
412
413        // Test passed - emphasis inside links are filtered out correctly
414
415        // Only the real emphasis outside links should be flagged
416        assert_eq!(
417            result.len(),
418            1,
419            "Expected exactly 1 warning, but got: {:?}",
420            result.len()
421        );
422        assert!(result[0].message.contains("Spaces inside emphasis markers"));
423        // Should flag "* real spaced emphasis *" but not emphasis patterns inside links
424        assert!(result[0].line == 3); // Line with "* real spaced emphasis *"
425    }
426
427    #[test]
428    fn test_emphasis_in_links_vs_outside_links() {
429        let rule = MD037NoSpaceInEmphasis;
430        let content = r#"Check [* spaced *](https://example.com/*test*) and inline * real spaced * text.
431
432[* link *]: https://example.com/*path*"#;
433        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
434        let result = rule.check(&ctx).unwrap();
435
436        // Only the actual emphasis outside links should be flagged
437        assert_eq!(result.len(), 1);
438        assert!(result[0].message.contains("Spaces inside emphasis markers"));
439        // Should be the "* real spaced *" text on line 1
440        assert!(result[0].line == 1);
441    }
442
443    #[test]
444    fn test_issue_49_asterisk_in_inline_code() {
445        // Test for issue #49 - Asterisk within backticks identified as for emphasis
446        let rule = MD037NoSpaceInEmphasis;
447
448        // Test case from issue #49
449        let content = "The `__mul__` method is needed for left-hand multiplication (`vector * 3`) and `__rmul__` is needed for right-hand multiplication (`3 * vector`).";
450        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
451        let result = rule.check(&ctx).unwrap();
452        assert!(
453            result.is_empty(),
454            "Should not flag asterisks inside inline code as emphasis (issue #49). Got: {result:?}"
455        );
456    }
457
458    #[test]
459    fn test_issue_28_inline_code_in_emphasis() {
460        // Test for issue #28 - MD037 should not flag inline code inside emphasis as spaces
461        let rule = MD037NoSpaceInEmphasis;
462
463        // Test case 1: inline code with single backticks inside bold emphasis
464        let content = "Though, we often call this an **inline `if`** because it looks sort of like an `if`-`else` statement all in *one line* of code.";
465        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard);
466        let result = rule.check(&ctx).unwrap();
467        assert!(
468            result.is_empty(),
469            "Should not flag inline code inside emphasis as spaces (issue #28). Got: {result:?}"
470        );
471
472        // Test case 2: multiple inline code snippets inside emphasis
473        let content2 = "The **`foo` and `bar`** methods are important.";
474        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard);
475        let result2 = rule.check(&ctx2).unwrap();
476        assert!(
477            result2.is_empty(),
478            "Should not flag multiple inline code snippets inside emphasis. Got: {result2:?}"
479        );
480
481        // Test case 3: inline code with underscores for emphasis
482        let content3 = "This is __inline `code`__ with underscores.";
483        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard);
484        let result3 = rule.check(&ctx3).unwrap();
485        assert!(
486            result3.is_empty(),
487            "Should not flag inline code with underscore emphasis. Got: {result3:?}"
488        );
489
490        // Test case 4: single asterisk emphasis with inline code
491        let content4 = "This is *inline `test`* with single asterisks.";
492        let ctx4 = LintContext::new(content4, crate::config::MarkdownFlavor::Standard);
493        let result4 = rule.check(&ctx4).unwrap();
494        assert!(
495            result4.is_empty(),
496            "Should not flag inline code with single asterisk emphasis. Got: {result4:?}"
497        );
498
499        // Test case 5: actual spaces that should be flagged
500        let content5 = "This has * real spaces * that should be flagged.";
501        let ctx5 = LintContext::new(content5, crate::config::MarkdownFlavor::Standard);
502        let result5 = rule.check(&ctx5).unwrap();
503        assert!(!result5.is_empty(), "Should still flag actual spaces in emphasis");
504        assert!(result5[0].message.contains("Spaces inside emphasis markers"));
505    }
506
507    #[test]
508    fn test_multibyte_utf8_no_panic() {
509        // Regression test: ensure multi-byte UTF-8 characters don't cause panics
510        // in the truncate_for_display function when handling long emphasis spans.
511        // These test cases include various scripts that could trigger boundary issues.
512        let rule = MD037NoSpaceInEmphasis;
513
514        // Greek text with emphasis
515        let greek = "Αυτό είναι ένα * τεστ με ελληνικά * και πολύ μεγάλο κείμενο που θα πρέπει να περικοπεί σωστά.";
516        let ctx = LintContext::new(greek, crate::config::MarkdownFlavor::Standard);
517        let result = rule.check(&ctx);
518        assert!(result.is_ok(), "Greek text should not panic");
519
520        // Chinese text with emphasis
521        let chinese = "这是一个 * 测试文本 * 包含中文字符,需要正确处理多字节边界。";
522        let ctx = LintContext::new(chinese, crate::config::MarkdownFlavor::Standard);
523        let result = rule.check(&ctx);
524        assert!(result.is_ok(), "Chinese text should not panic");
525
526        // Cyrillic/Russian text with emphasis
527        let cyrillic = "Это * тест с кириллицей * и очень длинным текстом для проверки обрезки.";
528        let ctx = LintContext::new(cyrillic, crate::config::MarkdownFlavor::Standard);
529        let result = rule.check(&ctx);
530        assert!(result.is_ok(), "Cyrillic text should not panic");
531
532        // Mixed multi-byte characters in a long emphasis span that triggers truncation
533        let mixed =
534            "日本語と * 中文と한국어が混在する非常に長いテキストでtruncate_for_displayの境界処理をテスト * します。";
535        let ctx = LintContext::new(mixed, crate::config::MarkdownFlavor::Standard);
536        let result = rule.check(&ctx);
537        assert!(result.is_ok(), "Mixed CJK text should not panic");
538
539        // Arabic text (right-to-left) with emphasis
540        let arabic = "هذا * اختبار بالعربية * مع نص طويل جداً لاختبار معالجة حدود الأحرف.";
541        let ctx = LintContext::new(arabic, crate::config::MarkdownFlavor::Standard);
542        let result = rule.check(&ctx);
543        assert!(result.is_ok(), "Arabic text should not panic");
544
545        // Emoji with emphasis
546        let emoji = "This has * 🎉 party 🎊 celebration 🥳 emojis * that use multi-byte sequences.";
547        let ctx = LintContext::new(emoji, crate::config::MarkdownFlavor::Standard);
548        let result = rule.check(&ctx);
549        assert!(result.is_ok(), "Emoji text should not panic");
550    }
551}