Skip to main content

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    replace_inline_math,
9};
10use crate::utils::kramdown_utils::has_span_ial;
11use crate::utils::range_utils::byte_to_char_count;
12use crate::utils::regex_cache::UNORDERED_LIST_MARKER_REGEX;
13use crate::utils::skip_context::{
14    is_in_inline_html_code, is_in_jsx_expression, is_in_math_context, is_in_mdx_comment, is_in_mkdocs_markup,
15    is_in_table_cell,
16};
17
18/// Check if an emphasis span has spacing issues that should be flagged
19#[inline]
20fn has_spacing_issues(span: &EmphasisSpan) -> bool {
21    span.has_leading_space || span.has_trailing_space
22}
23
24/// Truncate long text for display in warning messages
25/// Shows first ~30 and last ~30 chars with ellipsis in middle for readability
26#[inline]
27fn truncate_for_display(text: &str, max_len: usize) -> String {
28    if text.len() <= max_len {
29        return text.to_string();
30    }
31
32    let prefix_len = max_len / 2 - 2; // -2 for "..."
33    let suffix_len = max_len / 2 - 2;
34
35    // Use floor_char_boundary to safely find UTF-8 character boundaries
36    let prefix_end = text.floor_char_boundary(prefix_len.min(text.len()));
37    let suffix_start = text.floor_char_boundary(text.len().saturating_sub(suffix_len));
38
39    format!("{}...{}", &text[..prefix_end], &text[suffix_start..])
40}
41
42/// Rule MD037: Spaces inside emphasis markers
43#[derive(Clone)]
44pub struct MD037NoSpaceInEmphasis;
45
46impl Default for MD037NoSpaceInEmphasis {
47    fn default() -> Self {
48        Self
49    }
50}
51
52impl MD037NoSpaceInEmphasis {
53    /// Check if a byte position is within a link (inline links, reference links, or reference definitions)
54    fn is_in_link(&self, ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
55        // Check inline and reference links
56        for link in &ctx.links {
57            if link.byte_offset <= byte_pos && byte_pos < link.byte_end {
58                return true;
59            }
60        }
61
62        // Check images (which use similar syntax)
63        for image in &ctx.images {
64            if image.byte_offset <= byte_pos && byte_pos < image.byte_end {
65                return true;
66            }
67        }
68
69        // Check reference definitions [ref]: url "title" using pre-computed data (O(1) vs O(n))
70        ctx.is_in_reference_def(byte_pos)
71    }
72}
73
74impl Rule for MD037NoSpaceInEmphasis {
75    fn name(&self) -> &'static str {
76        "MD037"
77    }
78
79    fn description(&self) -> &'static str {
80        "Spaces inside emphasis markers"
81    }
82
83    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
84        let content = ctx.content;
85        let _timer = crate::profiling::ScopedTimer::new("MD037_check");
86
87        // Early return: if no emphasis markers at all, skip processing
88        if !content.contains('*') && !content.contains('_') {
89            return Ok(vec![]);
90        }
91
92        // Create LineIndex for correct byte position calculations across all line ending types
93        let line_index = &ctx.line_index;
94
95        let mut warnings = Vec::new();
96
97        // Process content lines, automatically skipping front matter, code blocks, math blocks,
98        // and Obsidian comments (when in Obsidian flavor)
99        // Math blocks contain LaTeX syntax where _ and * have special meaning
100        for line in ctx
101            .filtered_lines()
102            .skip_front_matter()
103            .skip_code_blocks()
104            .skip_math_blocks()
105            .skip_html_blocks()
106            .skip_jsx_expressions()
107            .skip_mdx_comments()
108            .skip_obsidian_comments()
109            .skip_mkdocstrings()
110        {
111            // Skip if the line doesn't contain any emphasis markers
112            if !line.content.contains('*') && !line.content.contains('_') {
113                continue;
114            }
115
116            // Check for emphasis issues on the original line
117            self.check_line_for_emphasis_issues_fast(line.content, line.line_num, &mut warnings);
118        }
119
120        // Filter out warnings for emphasis markers that are inside links, HTML comments, math, or MkDocs markup
121        let mut filtered_warnings = Vec::new();
122        let lines = ctx.raw_lines();
123
124        for (line_idx, line) in lines.iter().enumerate() {
125            let line_num = line_idx + 1;
126            let line_start_pos = line_index.get_line_start_byte(line_num).unwrap_or(0);
127
128            // Find warnings for this line
129            for warning in &warnings {
130                if warning.line == line_num {
131                    // `warning.column` is a byte offset within the line at this stage.
132                    // Derive the byte position (for byte-based skip checks) and the
133                    // character column (for char-based checks and the emitted warning).
134                    let byte_pos = line_start_pos + (warning.column - 1);
135                    // Calculate byte position within the line (0-indexed)
136                    let line_pos = warning.column - 1;
137                    let char_col = byte_to_char_count(line, warning.column - 1);
138
139                    // Skip if inside links, HTML comments, math contexts, tables, code spans, MDX constructs, or MkDocs markup
140                    // Note: is_in_code_span uses pulldown-cmark and correctly handles multi-line spans
141                    // Pandoc bracketed spans `[text]{.class}` may contain spaced
142                    // emphasis markers as literal content; suppress MD037 there.
143                    // Subscripts/superscripts cannot contain whitespace per the
144                    // detector grammar, so MD037's spaced-emphasis warnings can
145                    // never land inside one.
146                    let in_pandoc_construct = ctx.flavor.is_pandoc_compatible() && ctx.is_in_bracketed_span(byte_pos);
147                    if !in_pandoc_construct
148                        && !self.is_in_link(ctx, byte_pos)
149                        && !ctx.is_in_html_comment(byte_pos)
150                        && !is_in_math_context(ctx, byte_pos)
151                        && !is_in_table_cell(ctx, line_num, char_col)
152                        && !ctx.is_in_code_span(line_num, char_col)
153                        && !is_in_inline_html_code(line, line_pos)
154                        && !is_in_jsx_expression(ctx, byte_pos)
155                        && !is_in_mdx_comment(ctx, byte_pos)
156                        && !is_in_mkdocs_markup(line, line_pos, ctx.flavor)
157                        && !ctx.is_position_in_obsidian_comment(line_num, char_col)
158                    {
159                        let mut adjusted_warning = warning.clone();
160                        // Emit character-based columns (byte-based skip checks done above).
161                        adjusted_warning.column = char_col;
162                        adjusted_warning.end_column = byte_to_char_count(line, warning.end_column - 1);
163                        if let Some(fix) = &mut adjusted_warning.fix {
164                            // Convert line-relative range to absolute range
165                            let abs_start = line_start_pos + fix.range.start;
166                            let abs_end = line_start_pos + fix.range.end;
167                            fix.range = abs_start..abs_end;
168                        }
169                        filtered_warnings.push(adjusted_warning);
170                    }
171                }
172            }
173        }
174
175        Ok(filtered_warnings)
176    }
177
178    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
179        let content = ctx.content;
180        let _timer = crate::profiling::ScopedTimer::new("MD037_fix");
181
182        // Fast path: if no emphasis markers, return unchanged
183        if !content.contains('*') && !content.contains('_') {
184            return Ok(content.to_string());
185        }
186
187        // First check for issues and get all warnings with fixes
188        let warnings = self.check(ctx)?;
189        let warnings =
190            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
191
192        // If no warnings, return original content
193        if warnings.is_empty() {
194            return Ok(content.to_string());
195        }
196
197        // Apply fixes
198        let mut result = content.to_string();
199        let mut offset: isize = 0;
200
201        // Sort warnings by position to apply fixes in the correct order
202        let mut sorted_warnings: Vec<_> = warnings.iter().filter(|w| w.fix.is_some()).collect();
203        sorted_warnings.sort_by_key(|w| (w.line, w.column));
204
205        for warning in sorted_warnings {
206            if let Some(fix) = &warning.fix {
207                // Apply fix with offset adjustment
208                let actual_start = (fix.range.start as isize + offset) as usize;
209                let actual_end = (fix.range.end as isize + offset) as usize;
210
211                // Make sure we're not out of bounds
212                if actual_start < result.len() && actual_end <= result.len() {
213                    // Replace the text
214                    result.replace_range(actual_start..actual_end, &fix.replacement);
215                    // Update offset for future replacements
216                    offset += fix.replacement.len() as isize - (fix.range.end - fix.range.start) as isize;
217                }
218            }
219        }
220
221        Ok(result)
222    }
223
224    /// Get the category of this rule for selective processing
225    fn category(&self) -> RuleCategory {
226        RuleCategory::Emphasis
227    }
228
229    /// Check if this rule should be skipped
230    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
231        ctx.content.is_empty() || !ctx.likely_has_emphasis()
232    }
233
234    fn as_any(&self) -> &dyn std::any::Any {
235        self
236    }
237
238    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
239    where
240        Self: Sized,
241    {
242        Box::new(MD037NoSpaceInEmphasis)
243    }
244}
245
246impl MD037NoSpaceInEmphasis {
247    /// Optimized line checking for emphasis spacing issues
248    #[inline]
249    fn check_line_for_emphasis_issues_fast(&self, line: &str, line_num: usize, warnings: &mut Vec<LintWarning>) {
250        // Quick documentation pattern checks
251        if has_doc_patterns(line) {
252            return;
253        }
254
255        // Optimized list detection with fast path
256        // When a list marker is detected, ALWAYS check only the content after the marker,
257        // never the full line. This prevents the list marker (* + -) from being mistaken
258        // for emphasis markers.
259        if (line.starts_with(' ') || line.starts_with('*') || line.starts_with('+') || line.starts_with('-'))
260            && UNORDERED_LIST_MARKER_REGEX.is_match(line)
261        {
262            if let Some(caps) = UNORDERED_LIST_MARKER_REGEX.captures(line)
263                && let Some(full_match) = caps.get(0)
264            {
265                let list_marker_end = full_match.end();
266                if list_marker_end < line.len() {
267                    let remaining_content = &line[list_marker_end..];
268
269                    // Always check just the remaining content (after the list marker).
270                    // The list marker itself is never emphasis.
271                    self.check_line_content_for_emphasis_fast(remaining_content, line_num, list_marker_end, warnings);
272                }
273            }
274            return;
275        }
276
277        // Check the entire line
278        self.check_line_content_for_emphasis_fast(line, line_num, 0, warnings);
279    }
280
281    /// Optimized line content checking for emphasis issues
282    fn check_line_content_for_emphasis_fast(
283        &self,
284        content: &str,
285        line_num: usize,
286        offset: usize,
287        warnings: &mut Vec<LintWarning>,
288    ) {
289        // Replace inline code and inline math to avoid false positives
290        // with emphasis markers inside backticks or dollar signs
291        let processed_content = replace_inline_code(content);
292        let processed_content = replace_inline_math(&processed_content);
293
294        // Find all emphasis markers using optimized parsing
295        let markers = find_emphasis_markers(&processed_content);
296        if markers.is_empty() {
297            return;
298        }
299
300        // Find valid emphasis spans
301        let spans = find_emphasis_spans(&processed_content, &markers);
302
303        // Check each span for spacing issues
304        for span in spans {
305            if has_spacing_issues(&span) {
306                // Calculate the full span including markers
307                let full_start = span.opening.start_pos;
308                let full_end = span.closing.end_pos();
309                let full_text = &content[full_start..full_end];
310
311                // Skip if this emphasis has a Kramdown span IAL immediately after it
312                // (no space between emphasis and IAL)
313                if full_end < content.len() {
314                    let remaining = &content[full_end..];
315                    // Check if IAL starts immediately after the emphasis (no whitespace)
316                    if remaining.starts_with('{') && has_span_ial(remaining.split_whitespace().next().unwrap_or("")) {
317                        continue;
318                    }
319                }
320
321                // Create the marker string efficiently
322                let marker_char = span.opening.as_char();
323                let marker_str = if span.opening.count == 1 {
324                    marker_char.to_string()
325                } else {
326                    format!("{marker_char}{marker_char}")
327                };
328
329                // Create the fixed version by trimming spaces from content.
330                // Slice the content from the *original* line, not from the
331                // code/math-masked copy: `span.content` would contain the 'X'/'M'
332                // placeholders, which must never leak into the generated fix.
333                // Masking is length-preserving, so the span byte offsets are
334                // valid in `content`.
335                let original_content = &content[span.opening.end_pos()..span.closing.start_pos];
336                let trimmed_content = original_content.trim();
337                let fixed_text = format!("{marker_str}{trimmed_content}{marker_str}");
338
339                // Truncate long emphasis spans for readable warning messages
340                let display_text = truncate_for_display(full_text, 60);
341
342                let warning = LintWarning {
343                    rule_name: Some(self.name().to_string()),
344                    message: format!("Spaces inside emphasis markers: {display_text:?}"),
345                    // Byte-based columns within the line. The filter pass below relies
346                    // on `column` being a byte offset for its skip checks, then converts
347                    // the emitted columns to character offsets.
348                    line: line_num,
349                    column: offset + full_start + 1,
350                    end_line: line_num,
351                    end_column: offset + full_end + 1,
352                    severity: Severity::Warning,
353                    fix: Some(Fix::new((offset + full_start)..(offset + full_end), fixed_text)),
354                };
355
356                warnings.push(warning);
357            }
358        }
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use crate::lint_context::LintContext;
366
367    #[test]
368    fn test_emphasis_marker_parsing() {
369        let markers = find_emphasis_markers("This has *single* and **double** emphasis");
370        assert_eq!(markers.len(), 4); // *, *, **, **
371
372        let markers = find_emphasis_markers("*start* and *end*");
373        assert_eq!(markers.len(), 4); // *, *, *, *
374    }
375
376    #[test]
377    fn test_emphasis_span_detection() {
378        let markers = find_emphasis_markers("This has *valid* emphasis");
379        let spans = find_emphasis_spans("This has *valid* emphasis", &markers);
380        assert_eq!(spans.len(), 1);
381        assert_eq!(spans[0].content, "valid");
382        assert!(!spans[0].has_leading_space);
383        assert!(!spans[0].has_trailing_space);
384
385        let markers = find_emphasis_markers("This has * invalid * emphasis");
386        let spans = find_emphasis_spans("This has * invalid * emphasis", &markers);
387        assert_eq!(spans.len(), 1);
388        assert_eq!(spans[0].content, " invalid ");
389        assert!(spans[0].has_leading_space);
390        assert!(spans[0].has_trailing_space);
391    }
392
393    #[test]
394    fn test_with_document_structure() {
395        let rule = MD037NoSpaceInEmphasis;
396
397        // Test with no spaces inside emphasis - should pass
398        let content = "This is *correct* emphasis and **strong emphasis**";
399        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
400        let result = rule.check(&ctx).unwrap();
401        assert!(result.is_empty(), "No warnings expected for correct emphasis");
402
403        // Test with actual spaces inside emphasis - use content that should warn
404        let content = "This is * text with spaces * and more content";
405        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
406        let result = rule.check(&ctx).unwrap();
407        assert!(!result.is_empty(), "Expected warnings for spaces in emphasis");
408
409        // Test with code blocks - emphasis in code should be ignored
410        let content = "This is *correct* emphasis\n```\n* incorrect * in code block\n```\nOutside block with * spaces in emphasis *";
411        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
412        let result = rule.check(&ctx).unwrap();
413        assert!(
414            !result.is_empty(),
415            "Expected warnings for spaces in emphasis outside code block"
416        );
417    }
418
419    #[test]
420    fn test_inline_code_inside_spaced_emphasis_preserved_on_fix() {
421        // Regression test: inline code inside a spaced emphasis span must survive the
422        // space-trimming fix. Previously the 'X' masking placeholder leaked into
423        // the fix output, destroying the code span.
424        let rule = MD037NoSpaceInEmphasis;
425        let content = "Set * the `id` field * below.";
426        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
427        let fixed = rule.fix(&ctx).unwrap();
428        assert_eq!(fixed, "Set *the `id` field* below.");
429        assert!(!fixed.contains('X'), "masking placeholder leaked into fix: {fixed}");
430    }
431
432    #[test]
433    fn test_emphasis_in_links_not_flagged() {
434        let rule = MD037NoSpaceInEmphasis;
435        let content = r#"Check this [* spaced asterisk *](https://example.com/*test*) link.
436
437This has * real spaced emphasis * that should be flagged."#;
438        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
439        let result = rule.check(&ctx).unwrap();
440
441        // Test passed - emphasis inside links are filtered out correctly
442
443        // Only the real emphasis outside links should be flagged
444        assert_eq!(
445            result.len(),
446            1,
447            "Expected exactly 1 warning, but got: {:?}",
448            result.len()
449        );
450        assert!(result[0].message.contains("Spaces inside emphasis markers"));
451        // Should flag "* real spaced emphasis *" but not emphasis patterns inside links
452        assert!(result[0].line == 3); // Line with "* real spaced emphasis *"
453    }
454
455    #[test]
456    fn test_emphasis_in_links_vs_outside_links() {
457        let rule = MD037NoSpaceInEmphasis;
458        let content = r#"Check [* spaced *](https://example.com/*test*) and inline * real spaced * text.
459
460[* link *]: https://example.com/*path*"#;
461        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
462        let result = rule.check(&ctx).unwrap();
463
464        // Only the actual emphasis outside links should be flagged
465        assert_eq!(result.len(), 1);
466        assert!(result[0].message.contains("Spaces inside emphasis markers"));
467        // Should be the "* real spaced *" text on line 1
468        assert!(result[0].line == 1);
469    }
470
471    #[test]
472    fn test_issue_49_asterisk_in_inline_code() {
473        // Test for issue #49 - Asterisk within backticks identified as for emphasis
474        let rule = MD037NoSpaceInEmphasis;
475
476        // Test case from issue #49
477        let content = "The `__mul__` method is needed for left-hand multiplication (`vector * 3`) and `__rmul__` is needed for right-hand multiplication (`3 * vector`).";
478        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
479        let result = rule.check(&ctx).unwrap();
480        assert!(
481            result.is_empty(),
482            "Should not flag asterisks inside inline code as emphasis (issue #49). Got: {result:?}"
483        );
484    }
485
486    #[test]
487    fn test_issue_28_inline_code_in_emphasis() {
488        // Test for issue #28 - MD037 should not flag inline code inside emphasis as spaces
489        let rule = MD037NoSpaceInEmphasis;
490
491        // Test case 1: inline code with single backticks inside bold emphasis
492        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.";
493        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
494        let result = rule.check(&ctx).unwrap();
495        assert!(
496            result.is_empty(),
497            "Should not flag inline code inside emphasis as spaces (issue #28). Got: {result:?}"
498        );
499
500        // Test case 2: multiple inline code snippets inside emphasis
501        let content2 = "The **`foo` and `bar`** methods are important.";
502        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
503        let result2 = rule.check(&ctx2).unwrap();
504        assert!(
505            result2.is_empty(),
506            "Should not flag multiple inline code snippets inside emphasis. Got: {result2:?}"
507        );
508
509        // Test case 3: inline code with underscores for emphasis
510        let content3 = "This is __inline `code`__ with underscores.";
511        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
512        let result3 = rule.check(&ctx3).unwrap();
513        assert!(
514            result3.is_empty(),
515            "Should not flag inline code with underscore emphasis. Got: {result3:?}"
516        );
517
518        // Test case 4: single asterisk emphasis with inline code
519        let content4 = "This is *inline `test`* with single asterisks.";
520        let ctx4 = LintContext::new(content4, crate::config::MarkdownFlavor::Standard, None);
521        let result4 = rule.check(&ctx4).unwrap();
522        assert!(
523            result4.is_empty(),
524            "Should not flag inline code with single asterisk emphasis. Got: {result4:?}"
525        );
526
527        // Test case 5: actual spaces that should be flagged
528        let content5 = "This has * real spaces * that should be flagged.";
529        let ctx5 = LintContext::new(content5, crate::config::MarkdownFlavor::Standard, None);
530        let result5 = rule.check(&ctx5).unwrap();
531        assert!(!result5.is_empty(), "Should still flag actual spaces in emphasis");
532        assert!(result5[0].message.contains("Spaces inside emphasis markers"));
533    }
534
535    #[test]
536    fn test_multibyte_utf8_no_panic() {
537        // Regression test: ensure multi-byte UTF-8 characters don't cause panics
538        // in the truncate_for_display function when handling long emphasis spans.
539        // These test cases include various scripts that could trigger boundary issues.
540        let rule = MD037NoSpaceInEmphasis;
541
542        // Greek text with emphasis
543        let greek = "Αυτό είναι ένα * τεστ με ελληνικά * και πολύ μεγάλο κείμενο που θα πρέπει να περικοπεί σωστά.";
544        let ctx = LintContext::new(greek, crate::config::MarkdownFlavor::Standard, None);
545        let result = rule.check(&ctx);
546        assert!(result.is_ok(), "Greek text should not panic");
547
548        // Chinese text with emphasis
549        let chinese = "这是一个 * 测试文本 * 包含中文字符,需要正确处理多字节边界。";
550        let ctx = LintContext::new(chinese, crate::config::MarkdownFlavor::Standard, None);
551        let result = rule.check(&ctx);
552        assert!(result.is_ok(), "Chinese text should not panic");
553
554        // Cyrillic/Russian text with emphasis
555        let cyrillic = "Это * тест с кириллицей * и очень длинным текстом для проверки обрезки.";
556        let ctx = LintContext::new(cyrillic, crate::config::MarkdownFlavor::Standard, None);
557        let result = rule.check(&ctx);
558        assert!(result.is_ok(), "Cyrillic text should not panic");
559
560        // Mixed multi-byte characters in a long emphasis span that triggers truncation
561        let mixed =
562            "日本語と * 中文と한국어が混在する非常に長いテキストでtruncate_for_displayの境界処理をテスト * します。";
563        let ctx = LintContext::new(mixed, crate::config::MarkdownFlavor::Standard, None);
564        let result = rule.check(&ctx);
565        assert!(result.is_ok(), "Mixed CJK text should not panic");
566
567        // Arabic text (right-to-left) with emphasis
568        let arabic = "هذا * اختبار بالعربية * مع نص طويل جداً لاختبار معالجة حدود الأحرف.";
569        let ctx = LintContext::new(arabic, crate::config::MarkdownFlavor::Standard, None);
570        let result = rule.check(&ctx);
571        assert!(result.is_ok(), "Arabic text should not panic");
572
573        // Emoji with emphasis
574        let emoji = "This has * 🎉 party 🎊 celebration 🥳 emojis * that use multi-byte sequences.";
575        let ctx = LintContext::new(emoji, crate::config::MarkdownFlavor::Standard, None);
576        let result = rule.check(&ctx);
577        assert!(result.is_ok(), "Emoji text should not panic");
578    }
579
580    #[test]
581    fn test_template_shortcode_syntax_not_flagged() {
582        // Test for FastAPI/MkDocs style template syntax {* ... *}
583        // These should NOT be flagged as emphasis with spaces
584        let rule = MD037NoSpaceInEmphasis;
585
586        // FastAPI style code inclusion
587        let content = "{* ../../docs_src/cookie_param_models/tutorial001.py hl[9:12,16] *}";
588        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
589        let result = rule.check(&ctx).unwrap();
590        assert!(
591            result.is_empty(),
592            "Template shortcode syntax should not be flagged. Got: {result:?}"
593        );
594
595        // Another FastAPI example
596        let content = "{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}";
597        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
598        let result = rule.check(&ctx).unwrap();
599        assert!(
600            result.is_empty(),
601            "Template shortcode syntax should not be flagged. Got: {result:?}"
602        );
603
604        // Multiple shortcodes on different lines
605        let content = "# Header\n\n{* file1.py *}\n\nSome text.\n\n{* file2.py hl[1-5] *}";
606        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
607        let result = rule.check(&ctx).unwrap();
608        assert!(
609            result.is_empty(),
610            "Multiple template shortcodes should not be flagged. Got: {result:?}"
611        );
612
613        // But actual emphasis with spaces should still be flagged
614        let content = "This has * real spaced emphasis * here.";
615        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
616        let result = rule.check(&ctx).unwrap();
617        assert!(!result.is_empty(), "Real spaced emphasis should still be flagged");
618    }
619
620    #[test]
621    fn test_multiline_code_span_not_flagged() {
622        // Test for multi-line code spans - asterisks inside should not be flagged
623        // This tests the case where a code span starts on one line and ends on another
624        let rule = MD037NoSpaceInEmphasis;
625
626        // Code span spanning multiple lines with asterisks inside
627        let content = "# Test\n\naffects the structure. `1 + 0 + 0` is parsed as `(1 + 0) +\n0` while `1 + 0 * 0` is parsed as `1 + (0 * 0)`. Since the pattern";
628        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
629        let result = rule.check(&ctx).unwrap();
630        assert!(
631            result.is_empty(),
632            "Should not flag asterisks inside multi-line code spans. Got: {result:?}"
633        );
634
635        // Another multi-line code span case
636        let content2 = "Text with `code that\nspans * multiple * lines` here.";
637        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
638        let result2 = rule.check(&ctx2).unwrap();
639        assert!(
640            result2.is_empty(),
641            "Should not flag asterisks inside multi-line code spans. Got: {result2:?}"
642        );
643    }
644
645    #[test]
646    fn test_html_block_asterisks_not_flagged() {
647        let rule = MD037NoSpaceInEmphasis;
648
649        // Asterisks used as multiplication inside HTML <code> tags within an HTML table
650        let content = r#"<table>
651<tr><td>Format</td><td>Size</td></tr>
652<tr><td>BC1</td><td><code>floor((width + 3) / 4) * floor((height + 3) / 4) * 8</code></td></tr>
653<tr><td>BC2</td><td><code>floor((width + 3) / 4) * floor((height + 3) / 4) * 16</code></td></tr>
654</table>"#;
655        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
656        let result = rule.check(&ctx).unwrap();
657        assert!(
658            result.is_empty(),
659            "Should not flag asterisks inside HTML blocks. Got: {result:?}"
660        );
661
662        // Standalone HTML block with emphasis-like patterns
663        let content2 = "<div>\n<p>Value is * something * here</p>\n</div>";
664        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
665        let result2 = rule.check(&ctx2).unwrap();
666        assert!(
667            result2.is_empty(),
668            "Should not flag emphasis-like patterns inside HTML div blocks. Got: {result2:?}"
669        );
670
671        // Regular markdown with spaced emphasis should still be flagged
672        let content3 = "Regular * spaced emphasis * text\n\n<div>* not emphasis *</div>";
673        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
674        let result3 = rule.check(&ctx3).unwrap();
675        assert_eq!(
676            result3.len(),
677            1,
678            "Should flag spaced emphasis in regular markdown but not inside HTML blocks. Got: {result3:?}"
679        );
680        assert_eq!(result3[0].line, 1, "Warning should be on line 1 (regular markdown)");
681    }
682
683    #[test]
684    fn test_mkdocs_icon_shortcode_not_flagged() {
685        // Test that MkDocs icon shortcodes with asterisks inside are not flagged
686        let rule = MD037NoSpaceInEmphasis;
687
688        // Icon shortcode syntax like :material-star: should not trigger MD037
689        // because it's valid MkDocs Material syntax
690        let content = "Click :material-check: to confirm and :fontawesome-solid-star: for favorites.";
691        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
692        let result = rule.check(&ctx).unwrap();
693        assert!(
694            result.is_empty(),
695            "Should not flag MkDocs icon shortcodes. Got: {result:?}"
696        );
697
698        // Actual emphasis with spaces should still be flagged even in MkDocs mode
699        let content2 = "This has * real spaced emphasis * but also :material-check: icon.";
700        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::MkDocs, None);
701        let result2 = rule.check(&ctx2).unwrap();
702        assert!(
703            !result2.is_empty(),
704            "Should still flag real spaced emphasis in MkDocs mode"
705        );
706    }
707
708    #[test]
709    fn test_mkdocs_pymdown_markup_not_flagged() {
710        // Test that PyMdown extension markup is not flagged as emphasis issues
711        let rule = MD037NoSpaceInEmphasis;
712
713        // Keys notation (++ctrl+alt+delete++)
714        let content = "Press ++ctrl+c++ to copy.";
715        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
716        let result = rule.check(&ctx).unwrap();
717        assert!(
718            result.is_empty(),
719            "Should not flag PyMdown Keys notation. Got: {result:?}"
720        );
721
722        // Mark notation (==highlighted==)
723        let content2 = "This is ==highlighted text== for emphasis.";
724        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::MkDocs, None);
725        let result2 = rule.check(&ctx2).unwrap();
726        assert!(
727            result2.is_empty(),
728            "Should not flag PyMdown Mark notation. Got: {result2:?}"
729        );
730
731        // Insert notation (^^inserted^^)
732        let content3 = "This is ^^inserted text^^ here.";
733        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::MkDocs, None);
734        let result3 = rule.check(&ctx3).unwrap();
735        assert!(
736            result3.is_empty(),
737            "Should not flag PyMdown Insert notation. Got: {result3:?}"
738        );
739
740        // Mixed content with real emphasis issue and PyMdown markup
741        let content4 = "Press ++ctrl++ then * spaced emphasis * here.";
742        let ctx4 = LintContext::new(content4, crate::config::MarkdownFlavor::MkDocs, None);
743        let result4 = rule.check(&ctx4).unwrap();
744        assert!(
745            !result4.is_empty(),
746            "Should still flag real spaced emphasis alongside PyMdown markup"
747        );
748    }
749
750    // ==================== Obsidian highlight tests ====================
751
752    #[test]
753    fn test_obsidian_highlight_not_flagged() {
754        // Test that Obsidian highlight syntax (==text==) is not flagged as emphasis
755        let rule = MD037NoSpaceInEmphasis;
756
757        // Simple highlight
758        let content = "This is ==highlighted text== here.";
759        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
760        let result = rule.check(&ctx).unwrap();
761        assert!(
762            result.is_empty(),
763            "Should not flag Obsidian highlight syntax. Got: {result:?}"
764        );
765    }
766
767    #[test]
768    fn test_obsidian_highlight_multiple_on_line() {
769        // Multiple highlights on one line
770        let rule = MD037NoSpaceInEmphasis;
771
772        let content = "Both ==one== and ==two== are highlighted.";
773        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
774        let result = rule.check(&ctx).unwrap();
775        assert!(
776            result.is_empty(),
777            "Should not flag multiple Obsidian highlights. Got: {result:?}"
778        );
779    }
780
781    #[test]
782    fn test_obsidian_highlight_entire_paragraph() {
783        // Entire paragraph highlighted
784        let rule = MD037NoSpaceInEmphasis;
785
786        let content = "==Entire paragraph highlighted==";
787        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
788        let result = rule.check(&ctx).unwrap();
789        assert!(
790            result.is_empty(),
791            "Should not flag entire highlighted paragraph. Got: {result:?}"
792        );
793    }
794
795    #[test]
796    fn test_obsidian_highlight_with_emphasis() {
797        // Highlights nested with other emphasis
798        let rule = MD037NoSpaceInEmphasis;
799
800        // Bold highlight
801        let content = "**==bold highlight==**";
802        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
803        let result = rule.check(&ctx).unwrap();
804        assert!(
805            result.is_empty(),
806            "Should not flag bold highlight combination. Got: {result:?}"
807        );
808
809        // Italic highlight
810        let content2 = "*==italic highlight==*";
811        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Obsidian, None);
812        let result2 = rule.check(&ctx2).unwrap();
813        assert!(
814            result2.is_empty(),
815            "Should not flag italic highlight combination. Got: {result2:?}"
816        );
817    }
818
819    #[test]
820    fn test_obsidian_highlight_in_lists() {
821        // Highlights in list items
822        let rule = MD037NoSpaceInEmphasis;
823
824        let content = "- Item with ==highlight== text\n- Another ==highlighted== item";
825        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
826        let result = rule.check(&ctx).unwrap();
827        assert!(
828            result.is_empty(),
829            "Should not flag highlights in list items. Got: {result:?}"
830        );
831    }
832
833    #[test]
834    fn test_obsidian_highlight_in_blockquote() {
835        // Highlights in blockquotes
836        let rule = MD037NoSpaceInEmphasis;
837
838        let content = "> This quote has ==highlighted== text.";
839        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
840        let result = rule.check(&ctx).unwrap();
841        assert!(
842            result.is_empty(),
843            "Should not flag highlights in blockquotes. Got: {result:?}"
844        );
845    }
846
847    #[test]
848    fn test_obsidian_highlight_in_tables() {
849        // Highlights in tables
850        let rule = MD037NoSpaceInEmphasis;
851
852        let content = "| Header | Column |\n|--------|--------|\n| ==highlighted== | text |";
853        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
854        let result = rule.check(&ctx).unwrap();
855        assert!(
856            result.is_empty(),
857            "Should not flag highlights in tables. Got: {result:?}"
858        );
859    }
860
861    #[test]
862    fn test_obsidian_highlight_in_code_blocks_ignored() {
863        // Highlights inside code blocks should be ignored (they're in code)
864        let rule = MD037NoSpaceInEmphasis;
865
866        let content = "```\n==not highlight in code==\n```";
867        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
868        let result = rule.check(&ctx).unwrap();
869        assert!(
870            result.is_empty(),
871            "Should ignore highlights in code blocks. Got: {result:?}"
872        );
873    }
874
875    #[test]
876    fn test_obsidian_highlight_edge_case_three_equals() {
877        // Three equals signs (===) should not be treated as highlight
878        let rule = MD037NoSpaceInEmphasis;
879
880        // This is not valid highlight syntax
881        let content = "Test === something === here";
882        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
883        let result = rule.check(&ctx).unwrap();
884        // This may or may not generate warnings depending on if it looks like emphasis
885        // The key is it shouldn't crash and should be handled gracefully
886        let _ = result;
887    }
888
889    #[test]
890    fn test_obsidian_highlight_edge_case_four_equals() {
891        // Four equals signs (====) - empty highlight
892        let rule = MD037NoSpaceInEmphasis;
893
894        let content = "Test ==== here";
895        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
896        let result = rule.check(&ctx).unwrap();
897        // Empty highlights should not match as valid highlights
898        let _ = result;
899    }
900
901    #[test]
902    fn test_obsidian_highlight_adjacent() {
903        // Adjacent highlights
904        let rule = MD037NoSpaceInEmphasis;
905
906        let content = "==one====two==";
907        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
908        let result = rule.check(&ctx).unwrap();
909        // Should handle adjacent highlights gracefully
910        let _ = result;
911    }
912
913    #[test]
914    fn test_obsidian_highlight_with_special_chars() {
915        // Highlights with special characters inside
916        let rule = MD037NoSpaceInEmphasis;
917
918        // Highlight with backtick inside
919        let content = "Test ==code: `test`== here";
920        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
921        let result = rule.check(&ctx).unwrap();
922        // Should handle gracefully
923        let _ = result;
924    }
925
926    #[test]
927    fn test_obsidian_highlight_unclosed() {
928        // Unclosed highlight should not cause issues
929        let rule = MD037NoSpaceInEmphasis;
930
931        let content = "This ==starts but never ends";
932        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
933        let result = rule.check(&ctx).unwrap();
934        // Unclosed highlight should not match anything special
935        let _ = result;
936    }
937
938    #[test]
939    fn test_obsidian_highlight_still_flags_real_emphasis_issues() {
940        // Real emphasis issues should still be flagged in Obsidian mode
941        let rule = MD037NoSpaceInEmphasis;
942
943        let content = "This has * spaced emphasis * and ==valid highlight==";
944        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
945        let result = rule.check(&ctx).unwrap();
946        assert!(
947            !result.is_empty(),
948            "Should still flag real spaced emphasis in Obsidian mode"
949        );
950        assert!(
951            result.len() == 1,
952            "Should flag exactly one issue (the spaced emphasis). Got: {result:?}"
953        );
954    }
955
956    #[test]
957    fn test_standard_flavor_does_not_recognize_highlight() {
958        // Standard flavor should NOT recognize ==highlight== as special
959        // It may or may not flag it as emphasis depending on context
960        let rule = MD037NoSpaceInEmphasis;
961
962        let content = "This is ==highlighted text== here.";
963        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
964        let result = rule.check(&ctx).unwrap();
965        // In standard flavor, == is not recognized as highlight syntax
966        // It won't be flagged as "spaces in emphasis" because == is not * or _
967        // The key is that standard flavor doesn't give special treatment to ==
968        let _ = result; // Just ensure it runs without error
969    }
970
971    #[test]
972    fn test_obsidian_highlight_mixed_with_regular_emphasis() {
973        // Mix of highlights and regular emphasis
974        let rule = MD037NoSpaceInEmphasis;
975
976        let content = "==highlighted== and *italic* and **bold** text";
977        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
978        let result = rule.check(&ctx).unwrap();
979        assert!(
980            result.is_empty(),
981            "Should not flag valid highlight and emphasis. Got: {result:?}"
982        );
983    }
984
985    #[test]
986    fn test_obsidian_highlight_unicode() {
987        // Highlights with Unicode content
988        let rule = MD037NoSpaceInEmphasis;
989
990        let content = "Text ==日本語 highlighted== here";
991        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
992        let result = rule.check(&ctx).unwrap();
993        assert!(
994            result.is_empty(),
995            "Should handle Unicode in highlights. Got: {result:?}"
996        );
997    }
998
999    #[test]
1000    fn test_obsidian_highlight_with_html() {
1001        // Highlights inside HTML should be handled
1002        let rule = MD037NoSpaceInEmphasis;
1003
1004        let content = "<!-- ==not highlight in comment== --> ==actual highlight==";
1005        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1006        let result = rule.check(&ctx).unwrap();
1007        // The highlight in HTML comment should be ignored, only the actual highlight is processed
1008        let _ = result;
1009    }
1010
1011    #[test]
1012    fn test_obsidian_inline_comment_emphasis_ignored() {
1013        // Emphasis inside Obsidian comments should be ignored
1014        let rule = MD037NoSpaceInEmphasis;
1015
1016        let content = "Visible %%* spaced emphasis *%% still visible.";
1017        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1018        let result = rule.check(&ctx).unwrap();
1019
1020        assert!(
1021            result.is_empty(),
1022            "Should ignore emphasis inside Obsidian comments. Got: {result:?}"
1023        );
1024    }
1025
1026    #[test]
1027    fn test_inline_html_code_not_flagged() {
1028        let rule = MD037NoSpaceInEmphasis;
1029
1030        // Asterisks used as multiplication inside inline <code> tags
1031        let content = "The formula is <code>a * b * c</code> in math.";
1032        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1033        let result = rule.check(&ctx).unwrap();
1034        assert!(
1035            result.is_empty(),
1036            "Should not flag asterisks inside inline <code> tags. Got: {result:?}"
1037        );
1038
1039        // Multiple inline code-like tags on the same line
1040        let content2 = "Use <kbd>Ctrl * A</kbd> and <samp>x * y</samp> here.";
1041        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1042        let result2 = rule.check(&ctx2).unwrap();
1043        assert!(
1044            result2.is_empty(),
1045            "Should not flag asterisks inside inline <kbd> and <samp> tags. Got: {result2:?}"
1046        );
1047
1048        // Code tag with attributes
1049        let content3 = r#"Result: <code class="math">a * b</code> done."#;
1050        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
1051        let result3 = rule.check(&ctx3).unwrap();
1052        assert!(
1053            result3.is_empty(),
1054            "Should not flag asterisks inside <code> with attributes. Got: {result3:?}"
1055        );
1056
1057        // Real emphasis on the same line as inline code should still be flagged
1058        let content4 = "Text * spaced * and <code>a * b</code>.";
1059        let ctx4 = LintContext::new(content4, crate::config::MarkdownFlavor::Standard, None);
1060        let result4 = rule.check(&ctx4).unwrap();
1061        assert_eq!(
1062            result4.len(),
1063            1,
1064            "Should flag real spaced emphasis but not code content. Got: {result4:?}"
1065        );
1066        assert_eq!(result4[0].column, 6);
1067    }
1068
1069    /// Emphasis with spaces inside Pandoc bracketed spans should be suppressed under Pandoc,
1070    /// but regular emphasis-with-spaces outside bracketed spans must still be flagged.
1071    #[test]
1072    fn test_pandoc_bracketed_span_guard() {
1073        use crate::config::MarkdownFlavor;
1074        let rule = MD037NoSpaceInEmphasis;
1075        // Emphasis-like pattern inside a bracketed span (Pandoc construct)
1076        let content = "See [* important *]{.highlight} for details.\n";
1077        let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
1078        let result = rule.check(&ctx).unwrap();
1079        assert!(
1080            result.is_empty(),
1081            "MD037 should not flag emphasis-like patterns inside Pandoc bracketed spans: {result:?}"
1082        );
1083
1084        // Outside Pandoc flavor, the same text should still be flagged
1085        let ctx_std = LintContext::new(content, MarkdownFlavor::Standard, None);
1086        let result_std = rule.check(&ctx_std).unwrap();
1087        assert!(
1088            !result_std.is_empty(),
1089            "MD037 should still flag spaces in emphasis under Standard flavor: {result_std:?}"
1090        );
1091    }
1092
1093    #[test]
1094    fn test_spaced_bold_metadata_pattern_detected() {
1095        let rule = MD037NoSpaceInEmphasis;
1096
1097        // Broken bold metadata — leading space after opening **
1098        let content = "# Test\n\n** Explicit Import**: Convert markdownlint configs to rumdl format:";
1099        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1100        let result = rule.check(&ctx).unwrap();
1101        assert_eq!(
1102            result.len(),
1103            1,
1104            "Should flag '** Explicit Import**' as spaced emphasis. Got: {result:?}"
1105        );
1106        assert_eq!(result[0].line, 3);
1107
1108        // Trailing space before closing **
1109        let content2 = "# Test\n\n**trailing only **: some text";
1110        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1111        let result2 = rule.check(&ctx2).unwrap();
1112        assert_eq!(
1113            result2.len(),
1114            1,
1115            "Should flag '**trailing only **' as spaced emphasis. Got: {result2:?}"
1116        );
1117
1118        // Both leading and trailing spaces with colon
1119        let content3 = "# Test\n\n** both spaces **: some text";
1120        let ctx3 = LintContext::new(content3, crate::config::MarkdownFlavor::Standard, None);
1121        let result3 = rule.check(&ctx3).unwrap();
1122        assert_eq!(
1123            result3.len(),
1124            1,
1125            "Should flag '** both spaces **' as spaced emphasis. Got: {result3:?}"
1126        );
1127
1128        // Valid bold metadata — should NOT be flagged
1129        let content4 = "# Test\n\n**Key**: value";
1130        let ctx4 = LintContext::new(content4, crate::config::MarkdownFlavor::Standard, None);
1131        let result4 = rule.check(&ctx4).unwrap();
1132        assert!(
1133            result4.is_empty(),
1134            "Should not flag valid bold metadata '**Key**: value'. Got: {result4:?}"
1135        );
1136    }
1137}