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