Skip to main content

rumdl_lib/rules/
md038_no_space_in_code.rs

1use crate::lint_context::CodeSpan;
2use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
3use crate::utils::mkdocs_extensions::is_inline_hilite_content;
4
5/// Words that mark the text between two code spans as an illustration of nested backticks
6const NESTING_WORDS: [&str; 2] = ["code", "backtick"];
7
8/// State carried across the code spans of one document by the nested-backtick check
9#[derive(Default)]
10struct NestedBacktickState {
11    /// For each code span, the first and last index of the spans starting on its line
12    runs: Option<Vec<(usize, usize)>>,
13    /// The line most recently examined
14    line: Option<LineNesting>,
15}
16
17/// Where the nesting words sit on one line, relative to the spans that open and close it.
18///
19/// A span is compared against the farthest other span on each side, because the
20/// text examined between two spans grows with the distance between them and a
21/// shorter stretch is contained in a longer one. Both stretches therefore have
22/// one bound fixed for the whole line, which is what these two offsets record.
23struct LineNesting {
24    /// Line number (1-indexed) this data describes
25    line: usize,
26    /// Byte offset of each character, empty while every offset equals its index
27    char_offsets: Vec<usize>,
28    /// Length of the line in bytes
29    len: usize,
30    /// Smallest end offset among the nesting words that start after the span opening the line
31    word_end_after_first: Option<usize>,
32    /// Largest start offset among the nesting words that end before the span closing the line
33    word_start_before_last: Option<usize>,
34}
35
36impl LineNesting {
37    fn new(line_content: &str, line: usize, first: &CodeSpan, last: &CodeSpan) -> Self {
38        let char_offsets = if line_content.is_ascii() {
39            Vec::new()
40        } else {
41            line_content.char_indices().map(|(offset, _)| offset).collect()
42        };
43        let mut nesting = Self {
44            line,
45            char_offsets,
46            len: line_content.len(),
47            word_end_after_first: None,
48            word_start_before_last: None,
49        };
50
51        let after_first = nesting.char_offset(first.end_col);
52        let before_last = nesting.char_offset(last.start_col).unwrap_or(nesting.len);
53
54        for word in NESTING_WORDS {
55            for (start, matched) in line_content.match_indices(word) {
56                let end = start + matched.len();
57                if after_first.is_some_and(|bound| start >= bound) {
58                    nesting.word_end_after_first = Some(nesting.word_end_after_first.map_or(end, |e| e.min(end)));
59                }
60                if end <= before_last {
61                    nesting.word_start_before_last =
62                        Some(nesting.word_start_before_last.map_or(start, |s| s.max(start)));
63                }
64            }
65        }
66
67        nesting
68    }
69
70    /// Byte offset of the character at `char_index`, or `None` past the end of the line
71    fn char_offset(&self, char_index: usize) -> Option<usize> {
72        if self.char_offsets.is_empty() {
73            (char_index < self.len).then_some(char_index)
74        } else {
75            self.char_offsets.get(char_index).copied()
76        }
77    }
78
79    /// Whether a nesting word sits between the span opening the line and this span
80    fn names_backticks_before(&self, span: &CodeSpan) -> bool {
81        let Some(word_end) = self.word_end_after_first else {
82            return false;
83        };
84        word_end <= self.char_offset(span.start_col).unwrap_or(self.len)
85    }
86
87    /// Whether a nesting word sits between this span and the span closing the line
88    fn names_backticks_after(&self, span: &CodeSpan, last: &CodeSpan) -> bool {
89        let Some(word_start) = self.word_start_before_last else {
90            return false;
91        };
92        let Some(span_end) = self.char_offset(span.end_col.min(last.end_col)) else {
93            return false;
94        };
95        word_start >= span_end
96    }
97
98    /// Whether a nesting word sits in the text between two code spans
99    fn names_backticks_between(&self, line_content: &str, current_span: &CodeSpan, other_span: &CodeSpan) -> bool {
100        let start_char = current_span.end_col.min(other_span.end_col);
101        let end_char = current_span.start_col.max(other_span.start_col);
102        if start_char >= end_char {
103            return false;
104        }
105
106        // Convert character positions to byte offsets for string slicing
107        let Some(start_byte) = self.char_offset(start_char) else {
108            return false;
109        };
110        let end_byte = self.char_offset(end_char).unwrap_or(self.len);
111        if start_byte >= end_byte {
112            return false;
113        }
114
115        let between = &line_content[start_byte..end_byte];
116        NESTING_WORDS.iter().any(|word| between.contains(word))
117    }
118}
119
120/// Rule MD038: No space inside code span markers
121///
122/// See [docs/md038.md](../../docs/md038.md) for full documentation, configuration, and examples.
123///
124/// MD038: Spaces inside code span elements
125///
126/// This rule is triggered when there are spaces inside code span elements.
127///
128/// For example:
129///
130/// ``` markdown
131/// ` some text`
132/// `some text `
133/// ` some text `
134/// ```
135///
136/// To fix this issue, remove the leading and trailing spaces within the code span markers:
137///
138/// ``` markdown
139/// `some text`
140/// ```
141///
142/// Note: Code spans containing backticks (e.g., `` `backticks` inside ``) are not flagged
143/// to avoid breaking nested backtick structures used to display backticks in documentation.
144#[derive(Debug, Clone, Default)]
145pub struct MD038NoSpaceInCode {
146    pub enabled: bool,
147}
148
149impl MD038NoSpaceInCode {
150    pub fn new() -> Self {
151        Self { enabled: true }
152    }
153
154    /// Check if a code span is part of Hugo template syntax (e.g., {{raw `...`}})
155    ///
156    /// Hugo static site generator uses backticks as part of template delimiters,
157    /// not markdown code spans. This function detects common Hugo shortcode patterns:
158    /// - {{raw `...`}} - Raw HTML shortcode
159    /// - {{< `...` >}} - Partial shortcode
160    /// - {{% `...` %}} - Shortcode with percent delimiters
161    /// - {{ `...` }} - Generic shortcode
162    ///
163    /// The detection is conservative to avoid false positives:
164    /// - Requires opening {{ pattern before the backtick
165    /// - Requires closing }} after the code span
166    /// - Handles multi-line templates correctly
167    ///
168    /// Returns true if the code span is part of Hugo template syntax and should be skipped.
169    fn is_hugo_template_syntax(&self, ctx: &crate::lint_context::LintContext, code_span: &CodeSpan) -> bool {
170        let start_line_idx = code_span.line.saturating_sub(1);
171        let Some(start_line) = ctx.lines.get(start_line_idx) else {
172            return false;
173        };
174
175        let start_line_content = start_line.content(ctx.content);
176
177        // Byte position of the opening backtick within its own line
178        let Some(span_start) = code_span
179            .byte_offset
180            .checked_sub(start_line.byte_offset)
181            .filter(|offset| *offset <= start_line_content.len())
182        else {
183            return false;
184        };
185
186        // Check if there's Hugo template syntax before the code span on the same line
187        // Pattern: {{raw ` or {{< ` or similar Hugo template patterns
188        // The code span starts at the backtick, so we need to check what's before it
189        // Every pattern below is at least the 3 bytes of "{{ " wide
190        if span_start >= 3 {
191            // Look backwards for Hugo template patterns
192            // Get the content up to (but not including) the backtick
193            let before_span = &start_line_content[..span_start];
194
195            // Check for Hugo template patterns: {{raw `, {{< `, {{% `, etc.
196            // The backtick is at span_start, so we check if the content before it
197            // ends with the Hugo pattern (without the backtick), and verify the next char is a backtick
198            let char_at_span_start = start_line_content[span_start..].chars().next().unwrap_or(' ');
199
200            // Match Hugo shortcode patterns:
201            // - {{raw ` - Raw HTML shortcode
202            // - {{< ` - Partial shortcode (may have parameters before backtick)
203            // - {{% ` - Shortcode with percent delimiters
204            // - {{ ` - Generic shortcode
205            // Also handle cases with parameters: {{< highlight go ` or {{< code ` etc.
206            // We check if the pattern starts with {{ and contains the shortcode type before the backtick
207            let is_hugo_start =
208                // Exact match: {{raw `
209                (before_span.ends_with("{{raw ") && char_at_span_start == '`')
210                // Partial shortcode: {{< ` or {{< name ` or {{< name param ` etc.
211                || (before_span.starts_with("{{<") && before_span.ends_with(' ') && char_at_span_start == '`')
212                // Percent shortcode: {{% `
213                || (before_span.ends_with("{{% ") && char_at_span_start == '`')
214                // Generic shortcode: {{ `
215                || (before_span.ends_with("{{ ") && char_at_span_start == '`');
216
217            if is_hugo_start {
218                // Check if there's a closing }} after the code span
219                // First check the end line of the code span
220                let end_line_idx = code_span.end_line.saturating_sub(1);
221                if let Some(end_line) = ctx.lines.get(end_line_idx) {
222                    let end_line_content = end_line.content(ctx.content);
223                    let span_end = code_span
224                        .byte_end
225                        .checked_sub(end_line.byte_offset)
226                        .unwrap_or(end_line_content.len())
227                        .min(end_line_content.len());
228
229                    // Check for closing }} on the same line as the end of the code span
230                    if span_end < end_line_content.len() {
231                        let after_span = &end_line_content[span_end..];
232                        if after_span.trim_start().starts_with("}}") {
233                            return true;
234                        }
235                    }
236
237                    // Also check the next line for closing }}
238                    let next_line_idx = code_span.end_line;
239                    if next_line_idx < ctx.lines.len() {
240                        let next_line = ctx.lines[next_line_idx].content(ctx.content);
241                        if next_line.trim_start().starts_with("}}") {
242                            return true;
243                        }
244                    }
245                }
246            }
247        }
248
249        false
250    }
251
252    /// Check if content is an Obsidian Dataview inline query
253    ///
254    /// Dataview plugin uses two inline query syntaxes:
255    /// - Inline DQL: `= expression` - Starts with "= "
256    /// - Inline DataviewJS: `$= expression` - Starts with "$= "
257    ///
258    /// Examples:
259    /// - `= this.file.name` - Get current file name
260    /// - `= date(today)` - Get today's date
261    /// - `= [[Page]].field` - Access field from another page
262    /// - `$= dv.current().file.mtime` - DataviewJS expression
263    /// - `$= dv.pages().length` - Count pages
264    ///
265    /// These patterns legitimately start with a space after = or $=,
266    /// so they should not trigger MD038.
267    fn is_dataview_expression(content: &str) -> bool {
268        // Inline DQL: starts with "= " (equals followed by space)
269        // Inline DataviewJS: starts with "$= " (dollar-equals followed by space)
270        content.starts_with("= ") || content.starts_with("$= ")
271    }
272
273    /// Group code spans by the line they start on.
274    ///
275    /// Entry `i` holds the first and last index of the run of spans starting on
276    /// the same line as span `i`. Spans arrive sorted by byte offset, so the
277    /// spans of one line are contiguous.
278    fn same_line_runs(code_spans: &[CodeSpan]) -> Vec<(usize, usize)> {
279        let mut runs = vec![(0, 0); code_spans.len()];
280        let mut run_start = 0;
281
282        for index in 1..=code_spans.len() {
283            if index == code_spans.len() || code_spans[index].line != code_spans[run_start].line {
284                runs[run_start..index].fill((run_start, index - 1));
285                run_start = index;
286            }
287        }
288
289        runs
290    }
291
292    /// Check if a code span is likely part of a nested backtick structure
293    fn is_likely_nested_backticks(
294        &self,
295        ctx: &crate::lint_context::LintContext,
296        code_spans: &[CodeSpan],
297        span_index: usize,
298        state: &mut NestedBacktickState,
299    ) -> bool {
300        // If there are multiple code spans on the same line, and there's text
301        // between them that contains "code" or other indicators, it's likely nested
302        let current_span = &code_spans[span_index];
303        let (first, last) = {
304            let runs = state.runs.get_or_insert_with(|| Self::same_line_runs(code_spans));
305            runs[span_index]
306        };
307
308        // Look for other code spans on the same line
309        if first == last {
310            return false;
311        }
312
313        // Check if there's content between spans that might indicate nesting
314        // Get the line content
315        let line_idx = current_span.line - 1; // Convert to 0-based
316        if line_idx >= ctx.lines.len() {
317            return false;
318        }
319
320        let line_content = ctx.lines[line_idx].content(ctx.content);
321        let line = match &mut state.line {
322            Some(cached) if cached.line == current_span.line => cached,
323            slot => slot.insert(LineNesting::new(
324                line_content,
325                current_span.line,
326                &code_spans[first],
327                &code_spans[last],
328            )),
329        };
330
331        // A span continuing onto another line reports an end column belonging to
332        // that other line, which the bounds below assume stays on this one. Only
333        // the span closing a line can do that, so it is measured directly against
334        // the span opening the line, the farthest one from it.
335        if current_span.end_line != current_span.line {
336            return line.names_backticks_between(line_content, current_span, &code_spans[first]);
337        }
338
339        line.names_backticks_before(current_span) || line.names_backticks_after(current_span, &code_spans[last])
340    }
341
342    /// Check for a CommonMark parse shape produced by nested single backticks.
343    ///
344    /// In text like `` `{ outer `inner` outer }` ``, CommonMark sees two adjacent
345    /// code spans rather than one nested span. Removing the apparent leading or
346    /// trailing space from those parsed spans moves prose across the inner
347    /// backticks and changes the rendered text.
348    fn has_attached_nested_backtick_boundary(
349        &self,
350        ctx: &crate::lint_context::LintContext,
351        code_span: &crate::lint_context::CodeSpan,
352    ) -> bool {
353        let content = code_span.content.as_str();
354
355        let next_char = ctx.content[code_span.byte_end..].chars().next();
356        let prev_char = ctx.content[..code_span.byte_offset].chars().next_back();
357
358        // A Pandoc inline code attribute (`code`{.lang}) attached to the closing
359        // backtick is structural syntax, not a nested-backtick illustration.
360        // It must not silence inner-whitespace violations on the code span.
361        let trailing_neighbor_is_pandoc_attr =
362            ctx.flavor.is_pandoc_compatible() && ctx.is_in_inline_code_attr(code_span.byte_end);
363
364        (content.ends_with(char::is_whitespace)
365            && next_char.is_some_and(|c| !c.is_whitespace())
366            && !trailing_neighbor_is_pandoc_attr)
367            || (content.starts_with(char::is_whitespace) && prev_char.is_some_and(|c| !c.is_whitespace()))
368    }
369}
370
371impl Rule for MD038NoSpaceInCode {
372    fn name(&self) -> &'static str {
373        "MD038"
374    }
375
376    fn description(&self) -> &'static str {
377        "Spaces inside code span elements"
378    }
379
380    fn category(&self) -> RuleCategory {
381        RuleCategory::Other
382    }
383
384    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
385        if !self.enabled {
386            return Ok(vec![]);
387        }
388
389        let mut warnings = Vec::new();
390
391        // Use centralized code spans from LintContext
392        let code_spans = ctx.code_spans();
393        // Built on the first span that reaches the nested-backtick check, which most
394        // documents never do
395        let mut nesting = NestedBacktickState::default();
396        for (i, code_span) in code_spans.iter().enumerate() {
397            if let Some(line_info) = ctx.lines.get(code_span.line - 1) {
398                // Skip code spans that are inside fenced/indented code blocks, front-matter,
399                // math blocks, HTML blocks, HTML comments, mkdocstrings, or ESM blocks.
400                if line_info.in_code_block
401                    || line_info.in_front_matter
402                    || line_info.in_math_block
403                    || line_info.in_html_block
404                    || line_info.in_html_comment
405                    || line_info.in_mkdocstrings
406                    || line_info.in_esm_block
407                {
408                    continue;
409                }
410                // Skip multi-line code spans inside MkDocs containers where pulldown-cmark
411                // misinterprets indented fenced code block markers as code spans.
412                // Covers admonitions, tabs, HTML markdown blocks, and PyMdown blocks.
413                if (line_info.in_mkdocs_container() || line_info.in_pymdown_block) && code_span.content.contains('\n') {
414                    continue;
415                }
416            }
417
418            let code_content = &code_span.content;
419
420            // Skip empty code spans
421            if code_content.is_empty() {
422                continue;
423            }
424
425            // Early check: if no leading/trailing whitespace, skip
426            let has_leading_space = code_content.chars().next().is_some_and(char::is_whitespace);
427            let has_trailing_space = code_content.chars().last().is_some_and(char::is_whitespace);
428
429            if !has_leading_space && !has_trailing_space {
430                continue;
431            }
432
433            let trimmed = code_content.trim();
434
435            // CommonMark keeps a code span that consists entirely of whitespace
436            // verbatim: the single-space stripping rule only applies when the
437            // content is NOT all spaces. Flagging it would "fix" it to an empty
438            // code span (``), which reopens an unterminated span and changes the
439            // document's meaning. See https://spec.commonmark.org/0.31.2/#code-spans
440            if trimmed.is_empty() {
441                continue;
442            }
443
444            // Check if there are leading or trailing spaces
445            if code_content != trimmed {
446                // CommonMark behavior: if there is exactly ONE space at start AND ONE at end,
447                // and the content after trimming is non-empty, those spaces are stripped.
448                // We should NOT flag this case since the spaces are intentionally stripped.
449                // See: https://spec.commonmark.org/0.31.2/#code-spans
450                //
451                // Examples:
452                // ` text ` → "text" (spaces stripped, NOT flagged)
453                // `  text ` → " text" (extra leading space remains, FLAGGED)
454                // ` text  ` → "text " (extra trailing space remains, FLAGGED)
455                // ` text` → " text" (no trailing space to balance, FLAGGED)
456                // `text ` → "text " (no leading space to balance, FLAGGED)
457                // (trimmed is guaranteed non-empty here: all-whitespace spans
458                // were already skipped above.)
459                if has_leading_space && has_trailing_space {
460                    let leading_spaces = code_content.len() - code_content.trim_start().len();
461                    let trailing_spaces = code_content.len() - code_content.trim_end().len();
462
463                    // Exactly one space on each side - CommonMark strips them
464                    if leading_spaces == 1 && trailing_spaces == 1 {
465                        continue;
466                    }
467                }
468                // Check if the content itself contains backticks - if so, skip to avoid
469                // breaking nested backtick structures
470                if trimmed.contains('`') {
471                    continue;
472                }
473
474                // Skip inline R code in Quarto/RMarkdown: `r expression`
475                // This is RMarkdown/Quarto-specific syntax for inline R evaluation.
476                // Pandoc itself has no concept of executing inline R expressions,
477                // so the exemption is intentionally Quarto-only.
478                if ctx.flavor == crate::config::MarkdownFlavor::Quarto
479                    && trimmed.starts_with('r')
480                    && trimmed.len() > 1
481                    && trimmed.chars().nth(1).is_some_and(char::is_whitespace)
482                {
483                    continue;
484                }
485
486                // Skip InlineHilite syntax in MkDocs: `#!python code`
487                // The space after the language specifier is legitimate
488                if ctx.flavor == crate::config::MarkdownFlavor::MkDocs && is_inline_hilite_content(trimmed) {
489                    continue;
490                }
491
492                // Skip Dataview inline queries in Obsidian: `= expression` or `$= expression`
493                // Dataview plugin uses these patterns for inline DQL and DataviewJS queries.
494                // The space after = or $= is part of the syntax, not a spacing error.
495                if ctx.flavor == crate::config::MarkdownFlavor::Obsidian && Self::is_dataview_expression(code_content) {
496                    continue;
497                }
498
499                // Skip MyST role syntax: {role}`content` — the backtick content is part
500                // of the role's semantics, not a regular code span.
501                if ctx.flavor.supports_myst_roles() && ctx.is_in_myst_role(code_span.byte_offset) {
502                    continue;
503                }
504
505                // Check if this is part of Hugo template syntax (e.g., {{raw `...`}})
506                // Hugo uses backticks as part of template delimiters, not markdown code spans
507                if self.is_hugo_template_syntax(ctx, code_span) {
508                    continue;
509                }
510
511                // Check if this might be part of a nested backtick structure
512                // by looking for other code spans nearby that might indicate nesting
513                if self.is_likely_nested_backticks(ctx, &code_spans, i, &mut nesting) {
514                    continue;
515                }
516
517                if self.has_attached_nested_backtick_boundary(ctx, code_span) {
518                    continue;
519                }
520
521                warnings.push(LintWarning {
522                    rule_name: Some(self.name().to_string()),
523                    line: code_span.line,
524                    column: code_span.start_col + 1, // Convert to 1-indexed
525                    end_line: code_span.line,
526                    end_column: code_span.end_col, // Don't add 1 to match test expectation
527                    message: "Spaces inside code span elements".to_string(),
528                    severity: Severity::Warning,
529                    fix: Some(Fix::new(
530                        code_span.byte_offset..code_span.byte_end,
531                        format!(
532                            "{}{}{}",
533                            "`".repeat(code_span.backtick_count),
534                            trimmed,
535                            "`".repeat(code_span.backtick_count)
536                        ),
537                    )),
538                });
539            }
540        }
541
542        Ok(warnings)
543    }
544
545    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
546        let content = ctx.content;
547        if !self.enabled {
548            return Ok(content.to_string());
549        }
550
551        // Early return if no backticks in content
552        if !content.contains('`') {
553            return Ok(content.to_string());
554        }
555
556        // Get warnings to identify what needs to be fixed
557        let warnings = self.check(ctx)?;
558        let warnings =
559            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
560        if warnings.is_empty() {
561            return Ok(content.to_string());
562        }
563
564        // Collect all fixes and sort by position (reverse order to avoid position shifts)
565        let mut fixes: Vec<(std::ops::Range<usize>, String)> = warnings
566            .into_iter()
567            .filter_map(|w| w.fix.map(|f| (f.range, f.replacement)))
568            .collect();
569
570        fixes.sort_by_key(|(range, _)| std::cmp::Reverse(range.start));
571
572        // Apply fixes - only allocate string when we have fixes to apply
573        let mut result = content.to_string();
574        for (range, replacement) in fixes {
575            result.replace_range(range, &replacement);
576        }
577
578        Ok(result)
579    }
580
581    /// Check if content is likely to have code spans
582    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
583        !ctx.likely_has_code()
584    }
585
586    fn as_any(&self) -> &dyn std::any::Any {
587        self
588    }
589
590    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
591    where
592        Self: Sized,
593    {
594        Box::new(MD038NoSpaceInCode { enabled: true })
595    }
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    #[test]
603    fn test_md038_readme_false_positives() {
604        // These are the exact cases from README.md that are incorrectly flagged
605        let rule = MD038NoSpaceInCode::new();
606        let valid_cases = vec![
607            "3. `pyproject.toml` (must contain `[tool.rumdl]` section)",
608            "#### Effective Configuration (`rumdl config`)",
609            "- Blue: `.rumdl.toml`",
610            "### Defaults Only (`rumdl config --defaults`)",
611        ];
612
613        for case in valid_cases {
614            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
615            let result = rule.check(&ctx).unwrap();
616            assert!(
617                result.is_empty(),
618                "Should not flag code spans without leading/trailing spaces: '{}'. Got {} warnings",
619                case,
620                result.len()
621            );
622        }
623    }
624
625    #[test]
626    fn test_md038_front_matter() {
627        let rule = MD038NoSpaceInCode::new();
628        let content = "---\ntitle: \"`  code  `\"\n---\n`  code  `";
629        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
630        let result = rule.check(&ctx).unwrap();
631        // Should only flag the one in the body (line 4), not the one in front-matter (line 2)
632        assert_eq!(result.len(), 1);
633        assert_eq!(result[0].line, 4);
634    }
635
636    #[test]
637    fn test_md038_math_block() {
638        let rule = MD038NoSpaceInCode::new();
639        let content = "$$\n`  code  `\n$$\n`  code  `";
640        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
641        let result = rule.check(&ctx).unwrap();
642        // Should only flag the one in the body (line 4), not the one in math block (line 2)
643        assert_eq!(result.len(), 1);
644        assert_eq!(result[0].line, 4);
645    }
646
647    #[test]
648    fn test_md038_html_comment() {
649        let rule = MD038NoSpaceInCode::new();
650        let content = "<!--\n`  code  `\n-->\n`  code  `";
651        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
652        let result = rule.check(&ctx).unwrap();
653        // Should only flag the one in the body (line 4), not the one in HTML comment (line 2)
654        assert_eq!(result.len(), 1);
655        assert_eq!(result[0].line, 4);
656    }
657
658    #[test]
659    fn test_md038_valid() {
660        let rule = MD038NoSpaceInCode::new();
661        let valid_cases = vec![
662            "This is `code` in a sentence.",
663            "This is a `longer code span` in a sentence.",
664            "This is `code with internal spaces` which is fine.",
665            "Code span at `end of line`",
666            "`Start of line` code span",
667            "Multiple `code spans` in `one line` are fine",
668            "Code span with `symbols: !@#$%^&*()`",
669            "Empty code span `` is technically valid",
670        ];
671        for case in valid_cases {
672            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
673            let result = rule.check(&ctx).unwrap();
674            assert!(result.is_empty(), "Valid case should not have warnings: {case}");
675        }
676    }
677
678    #[test]
679    fn test_md038_invalid() {
680        let rule = MD038NoSpaceInCode::new();
681        // Flag cases that violate CommonMark:
682        // - Space only at start (no matching end space)
683        // - Space only at end (no matching start space)
684        // - Multiple spaces at start or end (extra space will remain after CommonMark stripping)
685        let invalid_cases = vec![
686            // Unbalanced: only leading space
687            "This is ` code` with leading space.",
688            // Unbalanced: only trailing space
689            "This is `code ` with trailing space.",
690            // Multiple leading spaces (one will remain after CommonMark strips one)
691            "This is `  code ` with double leading space.",
692            // Multiple trailing spaces (one will remain after CommonMark strips one)
693            "This is ` code  ` with double trailing space.",
694            // Multiple spaces both sides
695            "This is `  code  ` with double spaces both sides.",
696        ];
697        for case in invalid_cases {
698            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
699            let result = rule.check(&ctx).unwrap();
700            assert!(!result.is_empty(), "Invalid case should have warnings: {case}");
701        }
702    }
703
704    #[test]
705    fn test_md038_valid_commonmark_stripping() {
706        let rule = MD038NoSpaceInCode::new();
707        // These cases have exactly ONE space at start AND ONE at end.
708        // CommonMark strips both, so these should NOT be flagged.
709        // See: https://spec.commonmark.org/0.31.2/#code-spans
710        let valid_cases = vec![
711            "Type ` y ` to confirm.",
712            "Use ` git commit -m \"message\" ` to commit.",
713            "The variable ` $HOME ` contains home path.",
714            "The pattern ` *.txt ` matches text files.",
715            "This is ` random word ` with unnecessary spaces.",
716            "Text with ` plain text ` is valid.",
717            "Code with ` just code ` here.",
718            "Multiple ` word ` spans with ` text ` in one line.",
719            "This is ` code ` with both leading and trailing single space.",
720            "Use ` - ` as separator.",
721        ];
722        for case in valid_cases {
723            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
724            let result = rule.check(&ctx).unwrap();
725            assert!(
726                result.is_empty(),
727                "Single space on each side should not be flagged (CommonMark strips them): {case}"
728            );
729        }
730    }
731
732    #[test]
733    fn test_md038_whitespace_only_span_not_flagged() {
734        // CommonMark keeps a code span made up entirely of spaces verbatim: the
735        // single-space stripping rule only applies when the content is NOT all
736        // spaces (https://spec.commonmark.org/0.31.2/#code-spans). Flagging it
737        // would "fix" it to an empty code span (``), which reopens an
738        // unterminated span and changes the document's meaning.
739        let rule = MD038NoSpaceInCode::new();
740        let whitespace_only_cases = vec![
741            "A single-space span `\u{0020}` is intentional.",
742            "A two-space span `\u{0020}\u{0020}` is intentional.",
743            "A three-space span `\u{0020}\u{0020}\u{0020}` is intentional.",
744            "A tab span `\t` is intentional.",
745            "Just the span: ` `",
746        ];
747        for case in whitespace_only_cases {
748            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
749            let result = rule.check(&ctx).unwrap();
750            assert!(
751                result.is_empty(),
752                "Whitespace-only code span should not be flagged (kept verbatim per CommonMark): {case}"
753            );
754        }
755    }
756
757    #[test]
758    fn test_md038_whitespace_only_span_fix_preserves_verbatim() {
759        // The fix must never collapse a whitespace-only span to `` (which is
760        // invalid Markdown). Each input is left untouched.
761        let rule = MD038NoSpaceInCode::new();
762        let unchanged_cases = vec![
763            "A single-space span `\u{0020}` is intentional.",
764            "A two-space span `\u{0020}\u{0020}` is intentional.",
765            "Just the span: ` `",
766        ];
767        for case in unchanged_cases {
768            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
769            let result = rule.fix(&ctx).unwrap();
770            assert_eq!(
771                result, case,
772                "Whitespace-only code span must be left verbatim by fix, not collapsed to ``"
773            );
774        }
775    }
776
777    #[test]
778    fn test_md038_fix() {
779        let rule = MD038NoSpaceInCode::new();
780        // Only cases that violate CommonMark should be fixed
781        let test_cases = vec![
782            // Unbalanced: only leading space - should be fixed
783            (
784                "This is ` code` with leading space.",
785                "This is `code` with leading space.",
786            ),
787            // Unbalanced: only trailing space - should be fixed
788            (
789                "This is `code ` with trailing space.",
790                "This is `code` with trailing space.",
791            ),
792            // Single space on both sides - NOT fixed (valid per CommonMark)
793            (
794                "This is ` code ` with both spaces.",
795                "This is ` code ` with both spaces.", // unchanged
796            ),
797            // Double leading space - should be fixed
798            (
799                "This is `  code ` with double leading space.",
800                "This is `code` with double leading space.",
801            ),
802            // Mixed: one valid (single space both), one invalid (trailing only)
803            (
804                "Multiple ` code ` and `spans ` to fix.",
805                "Multiple ` code ` and `spans` to fix.", // only spans is fixed
806            ),
807        ];
808        for (input, expected) in test_cases {
809            let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
810            let result = rule.fix(&ctx).unwrap();
811            assert_eq!(result, expected, "Fix did not produce expected output for: {input}");
812        }
813    }
814
815    #[test]
816    fn test_check_invalid_leading_space() {
817        let rule = MD038NoSpaceInCode::new();
818        let input = "This has a ` leading space` in code";
819        let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
820        let result = rule.check(&ctx).unwrap();
821        assert_eq!(result.len(), 1);
822        assert_eq!(result[0].line, 1);
823        assert!(result[0].fix.is_some());
824    }
825
826    #[test]
827    fn test_code_span_parsing_nested_backticks() {
828        let content = "Code with ` nested `code` example ` should preserve backticks";
829        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
830
831        println!("Content: {content}");
832        println!("Code spans found:");
833        let code_spans = ctx.code_spans();
834        for (i, span) in code_spans.iter().enumerate() {
835            println!(
836                "  Span {}: line={}, col={}-{}, backticks={}, content='{}'",
837                i, span.line, span.start_col, span.end_col, span.backtick_count, span.content
838            );
839        }
840
841        // This test reveals the issue - we're getting multiple separate code spans instead of one
842        assert_eq!(code_spans.len(), 2, "Should parse as 2 code spans");
843    }
844
845    #[test]
846    fn test_nested_backtick_detection() {
847        let rule = MD038NoSpaceInCode::new();
848
849        // Test that code spans with backticks are skipped
850        let content = "Code with `` `backticks` inside `` should not be flagged";
851        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
852        let result = rule.check(&ctx).unwrap();
853        assert!(result.is_empty(), "Code spans with backticks should be skipped");
854    }
855
856    #[test]
857    fn test_quarto_inline_r_code() {
858        // Test that Quarto-specific R code exception works
859        let rule = MD038NoSpaceInCode::new();
860
861        // Test inline R code - should NOT trigger warning in Quarto flavor
862        // The key pattern is "r " followed by code
863        let content = r#"The result is `r nchar("test")` which equals 4."#;
864
865        // Quarto flavor should allow R code
866        let ctx_quarto = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
867        let result_quarto = rule.check(&ctx_quarto).unwrap();
868        assert!(
869            result_quarto.is_empty(),
870            "Quarto inline R code should not trigger warnings. Got {} warnings",
871            result_quarto.len()
872        );
873
874        // Test that invalid code spans (not matching CommonMark stripping) still get flagged in Quarto
875        // Use only trailing space - this violates CommonMark (no balanced stripping)
876        let content_other = "This has `plain text ` with trailing space.";
877        let ctx_other =
878            crate::lint_context::LintContext::new(content_other, crate::config::MarkdownFlavor::Quarto, None);
879        let result_other = rule.check(&ctx_other).unwrap();
880        assert_eq!(
881            result_other.len(),
882            1,
883            "Quarto should still flag non-R code spans with improper spaces"
884        );
885    }
886
887    /// Comprehensive tests for Hugo template syntax detection
888    ///
889    /// These tests ensure MD038 correctly handles Hugo template syntax patterns
890    /// without false positives, while maintaining correct detection of actual
891    /// code span spacing issues.
892    #[test]
893    fn test_hugo_template_syntax_comprehensive() {
894        let rule = MD038NoSpaceInCode::new();
895
896        // ===== VALID HUGO TEMPLATE SYNTAX (Should NOT trigger warnings) =====
897
898        // Basic Hugo shortcode patterns
899        let valid_hugo_cases = vec![
900            // Raw HTML shortcode
901            (
902                "{{raw `\n\tgo list -f '{{.DefaultGODEBUG}}' my/main/package\n`}}",
903                "Multi-line raw shortcode",
904            ),
905            (
906                "Some text {{raw ` code `}} more text",
907                "Inline raw shortcode with spaces",
908            ),
909            ("{{raw `code`}}", "Raw shortcode without spaces"),
910            // Partial shortcode
911            ("{{< ` code ` >}}", "Partial shortcode with spaces"),
912            ("{{< `code` >}}", "Partial shortcode without spaces"),
913            // Shortcode with percent
914            ("{{% ` code ` %}}", "Percent shortcode with spaces"),
915            ("{{% `code` %}}", "Percent shortcode without spaces"),
916            // Generic shortcode
917            ("{{ ` code ` }}", "Generic shortcode with spaces"),
918            ("{{ `code` }}", "Generic shortcode without spaces"),
919            // Shortcodes with parameters (common Hugo pattern)
920            ("{{< highlight go `code` >}}", "Shortcode with highlight parameter"),
921            ("{{< code `go list` >}}", "Shortcode with code parameter"),
922            // Multi-line Hugo templates
923            ("{{raw `\n\tcommand here\n\tmore code\n`}}", "Multi-line raw template"),
924            ("{{< highlight `\ncode here\n` >}}", "Multi-line highlight template"),
925            // Hugo templates with nested Go template syntax
926            (
927                "{{raw `\n\t{{.Variable}}\n\t{{range .Items}}\n`}}",
928                "Nested Go template syntax",
929            ),
930            // Edge case: Hugo template at start of line
931            ("{{raw `code`}}", "Hugo template at line start"),
932            // Edge case: Hugo template at end of line
933            ("Text {{raw `code`}}", "Hugo template at end of line"),
934            // Edge case: Multiple Hugo templates
935            ("{{raw `code1`}} and {{raw `code2`}}", "Multiple Hugo templates"),
936        ];
937
938        for (case, description) in valid_hugo_cases {
939            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
940            let result = rule.check(&ctx).unwrap();
941            assert!(
942                result.is_empty(),
943                "Hugo template syntax should not trigger MD038 warnings: {description} - {case}"
944            );
945        }
946
947        // ===== FALSE POSITIVE PREVENTION (Non-Hugo asymmetric spaces should be flagged) =====
948
949        // These have asymmetric spaces (leading-only or trailing-only) and should be flagged
950        // Per CommonMark spec: symmetric single-space pairs are stripped and NOT flagged
951        let should_be_flagged = vec![
952            ("This is ` code` with leading space.", "Leading space only"),
953            ("This is `code ` with trailing space.", "Trailing space only"),
954            ("Text `  code ` here", "Extra leading space (asymmetric)"),
955            ("Text ` code  ` here", "Extra trailing space (asymmetric)"),
956            ("Text `  code` here", "Double leading, no trailing"),
957            ("Text `code  ` here", "No leading, double trailing"),
958        ];
959
960        for (case, description) in should_be_flagged {
961            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
962            let result = rule.check(&ctx).unwrap();
963            assert!(
964                !result.is_empty(),
965                "Should flag asymmetric space code spans: {description} - {case}"
966            );
967        }
968
969        // ===== COMMONMARK SYMMETRIC SPACE BEHAVIOR (Should NOT be flagged) =====
970
971        // Per CommonMark 0.31.2: When a code span has exactly one space at start AND end,
972        // those spaces are stripped from the output. This is intentional, not an error.
973        // These cases should NOT trigger MD038.
974        let symmetric_single_space = vec![
975            ("Text ` code ` here", "Symmetric single space - CommonMark strips"),
976            ("{raw ` code `}", "Looks like Hugo but missing opening {{"),
977            ("raw ` code `}}", "Missing opening {{ - but symmetric spaces"),
978        ];
979
980        for (case, description) in symmetric_single_space {
981            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
982            let result = rule.check(&ctx).unwrap();
983            assert!(
984                result.is_empty(),
985                "CommonMark symmetric spaces should NOT be flagged: {description} - {case}"
986            );
987        }
988
989        // ===== EDGE CASES: Unicode and Special Characters =====
990
991        let unicode_cases = vec![
992            ("{{raw `\n\t你好世界\n`}}", "Unicode in Hugo template"),
993            ("{{raw `\n\t🎉 emoji\n`}}", "Emoji in Hugo template"),
994            ("{{raw `\n\tcode with \"quotes\"\n`}}", "Quotes in Hugo template"),
995            (
996                "{{raw `\n\tcode with 'single quotes'\n`}}",
997                "Single quotes in Hugo template",
998            ),
999        ];
1000
1001        for (case, description) in unicode_cases {
1002            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1003            let result = rule.check(&ctx).unwrap();
1004            assert!(
1005                result.is_empty(),
1006                "Hugo templates with special characters should not trigger warnings: {description} - {case}"
1007            );
1008        }
1009
1010        // ===== BOUNDARY CONDITIONS =====
1011
1012        // Minimum valid Hugo pattern
1013        assert!(
1014            rule.check(&crate::lint_context::LintContext::new(
1015                "{{ ` ` }}",
1016                crate::config::MarkdownFlavor::Standard,
1017                None
1018            ))
1019            .unwrap()
1020            .is_empty(),
1021            "Minimum Hugo pattern should be valid"
1022        );
1023
1024        // Hugo template with only whitespace
1025        assert!(
1026            rule.check(&crate::lint_context::LintContext::new(
1027                "{{raw `\n\t\n`}}",
1028                crate::config::MarkdownFlavor::Standard,
1029                None
1030            ))
1031            .unwrap()
1032            .is_empty(),
1033            "Hugo template with only whitespace should be valid"
1034        );
1035    }
1036
1037    /// Hugo templates are located by byte offset, so a line whose character
1038    /// positions differ from its byte positions must behave the same way
1039    #[test]
1040    fn test_hugo_template_after_multibyte_text() {
1041        let rule = MD038NoSpaceInCode::new();
1042
1043        // Spans that would be flagged for their trailing space if the template
1044        // around them were not recognized
1045        let exempt = [
1046            "日本語 {{raw `a ` }}",
1047            "café {{% `a ` }}",
1048            "{{< 日本語 `a ` }}",
1049            "日本語 {{ `a `\n}}",
1050            "日本語 {{raw `a\nb ` }}",
1051        ];
1052        for case in exempt {
1053            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1054            assert!(
1055                rule.check(&ctx).unwrap().is_empty(),
1056                "Hugo template behind multibyte text should not trigger MD038: {case}"
1057            );
1058        }
1059
1060        // Control: the same lines without a recognized opener stay reported
1061        let flagged = [
1062            "日本語 {{raw`a ` }}",
1063            "café {{ `a ` and",
1064            "{{< 日本語`a ` }}",
1065            "日本語 {{raw`a\nb ` }}",
1066        ];
1067        for case in flagged {
1068            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1069            assert_eq!(
1070                rule.check(&ctx).unwrap().len(),
1071                1,
1072                "Near miss behind multibyte text should still be reported: {case}"
1073            );
1074        }
1075    }
1076
1077    /// Test interaction with other markdown elements
1078    #[test]
1079    fn test_hugo_template_with_other_markdown() {
1080        let rule = MD038NoSpaceInCode::new();
1081
1082        // Hugo template inside a list
1083        let content = r#"1. First item
10842. Second item with {{raw `code`}} template
10853. Third item"#;
1086        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1087        let result = rule.check(&ctx).unwrap();
1088        assert!(result.is_empty(), "Hugo template in list should not trigger warnings");
1089
1090        // Hugo template in blockquote
1091        let content = r#"> Quote with {{raw `code`}} template"#;
1092        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1093        let result = rule.check(&ctx).unwrap();
1094        assert!(
1095            result.is_empty(),
1096            "Hugo template in blockquote should not trigger warnings"
1097        );
1098
1099        // Hugo template near regular code span (should flag the regular one)
1100        let content = r#"{{raw `code`}} and ` bad code` here"#;
1101        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1102        let result = rule.check(&ctx).unwrap();
1103        assert_eq!(result.len(), 1, "Should flag regular code span but not Hugo template");
1104    }
1105
1106    /// Performance test: Many Hugo templates
1107    #[test]
1108    fn test_hugo_template_performance() {
1109        let rule = MD038NoSpaceInCode::new();
1110
1111        // Create content with many Hugo templates
1112        let mut content = String::new();
1113        for i in 0..100 {
1114            content.push_str(&format!("{{{{raw `code{i}\n`}}}}\n"));
1115        }
1116
1117        let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
1118        let start = std::time::Instant::now();
1119        let result = rule.check(&ctx).unwrap();
1120        let duration = start.elapsed();
1121
1122        assert!(result.is_empty(), "Many Hugo templates should not trigger warnings");
1123        assert!(
1124            duration.as_millis() < 1000,
1125            "Performance test: Should process 100 Hugo templates in <1s, took {duration:?}"
1126        );
1127    }
1128
1129    #[test]
1130    fn test_mkdocs_inline_hilite_not_flagged() {
1131        // InlineHilite syntax: `#!language code` should NOT be flagged
1132        // The space after the language specifier is legitimate
1133        let rule = MD038NoSpaceInCode::new();
1134
1135        let valid_cases = vec![
1136            "`#!python print('hello')`",
1137            "`#!js alert('hi')`",
1138            "`#!c++ cout << x;`",
1139            "Use `#!python import os` to import modules",
1140            "`#!bash echo $HOME`",
1141        ];
1142
1143        for case in valid_cases {
1144            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::MkDocs, None);
1145            let result = rule.check(&ctx).unwrap();
1146            assert!(
1147                result.is_empty(),
1148                "InlineHilite syntax should not be flagged in MkDocs: {case}"
1149            );
1150        }
1151
1152        // Test that InlineHilite IS flagged in Standard flavor (not MkDocs-aware)
1153        let content = "`#!python print('hello')`";
1154        let ctx_standard =
1155            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1156        let result_standard = rule.check(&ctx_standard).unwrap();
1157        // In standard flavor, the content " print('hello')" has no special meaning
1158        // But since "#!python print('hello')" doesn't have leading/trailing spaces, it's valid!
1159        assert!(
1160            result_standard.is_empty(),
1161            "InlineHilite with no extra spaces should not be flagged even in Standard flavor"
1162        );
1163    }
1164
1165    #[test]
1166    fn test_multibyte_utf8_no_panic() {
1167        // Regression test: ensure multi-byte UTF-8 characters don't cause panics
1168        // when checking for nested backticks between code spans.
1169        // These are real examples from the-art-of-command-line translations.
1170        let rule = MD038NoSpaceInCode::new();
1171
1172        // Greek text with code spans
1173        let greek = "- Χρήσιμα εργαλεία της γραμμής εντολών είναι τα `ping`,` ipconfig`, `traceroute` και `netstat`.";
1174        let ctx = crate::lint_context::LintContext::new(greek, crate::config::MarkdownFlavor::Standard, None);
1175        let result = rule.check(&ctx);
1176        assert!(result.is_ok(), "Greek text should not panic");
1177
1178        // Chinese text with code spans
1179        let chinese = "- 當你需要對文字檔案做集合交、並、差運算時,`sort`/`uniq` 很有幫助。";
1180        let ctx = crate::lint_context::LintContext::new(chinese, crate::config::MarkdownFlavor::Standard, None);
1181        let result = rule.check(&ctx);
1182        assert!(result.is_ok(), "Chinese text should not panic");
1183
1184        // Cyrillic/Ukrainian text with code spans
1185        let cyrillic = "- Основи роботи з файлами: `ls` і `ls -l`, `less`, `head`,` tail` і `tail -f`.";
1186        let ctx = crate::lint_context::LintContext::new(cyrillic, crate::config::MarkdownFlavor::Standard, None);
1187        let result = rule.check(&ctx);
1188        assert!(result.is_ok(), "Cyrillic text should not panic");
1189
1190        // Mixed multi-byte with multiple code spans on same line
1191        let mixed = "使用 `git` 命令和 `npm` 工具来管理项目,可以用 `docker` 容器化。";
1192        let ctx = crate::lint_context::LintContext::new(mixed, crate::config::MarkdownFlavor::Standard, None);
1193        let result = rule.check(&ctx);
1194        assert!(
1195            result.is_ok(),
1196            "Mixed Chinese text with multiple code spans should not panic"
1197        );
1198    }
1199
1200    // ==================== Obsidian Dataview Plugin Tests ====================
1201
1202    /// Test that Dataview inline DQL expressions are not flagged in Obsidian flavor
1203    #[test]
1204    fn test_obsidian_dataview_inline_dql_not_flagged() {
1205        let rule = MD038NoSpaceInCode::new();
1206
1207        // Basic inline DQL expressions - should NOT be flagged in Obsidian
1208        let valid_dql_cases = vec![
1209            "`= this.file.name`",
1210            "`= date(today)`",
1211            "`= [[Page]].field`",
1212            "`= choice(condition, \"yes\", \"no\")`",
1213            "`= this.file.mtime`",
1214            "`= this.file.ctime`",
1215            "`= this.file.path`",
1216            "`= this.file.folder`",
1217            "`= this.file.size`",
1218            "`= this.file.ext`",
1219            "`= this.file.link`",
1220            "`= this.file.outlinks`",
1221            "`= this.file.inlinks`",
1222            "`= this.file.tags`",
1223        ];
1224
1225        for case in valid_dql_cases {
1226            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1227            let result = rule.check(&ctx).unwrap();
1228            assert!(
1229                result.is_empty(),
1230                "Dataview DQL expression should not be flagged in Obsidian: {case}"
1231            );
1232        }
1233    }
1234
1235    /// Test that Dataview inline DataviewJS expressions are not flagged in Obsidian flavor
1236    #[test]
1237    fn test_obsidian_dataview_inline_dvjs_not_flagged() {
1238        let rule = MD038NoSpaceInCode::new();
1239
1240        // Inline DataviewJS expressions - should NOT be flagged in Obsidian
1241        let valid_dvjs_cases = vec![
1242            "`$= dv.current().file.mtime`",
1243            "`$= dv.pages().length`",
1244            "`$= dv.current()`",
1245            "`$= dv.pages('#tag').length`",
1246            "`$= dv.pages('\"folder\"').length`",
1247            "`$= dv.current().file.name`",
1248            "`$= dv.current().file.path`",
1249            "`$= dv.current().file.folder`",
1250            "`$= dv.current().file.link`",
1251        ];
1252
1253        for case in valid_dvjs_cases {
1254            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1255            let result = rule.check(&ctx).unwrap();
1256            assert!(
1257                result.is_empty(),
1258                "Dataview JS expression should not be flagged in Obsidian: {case}"
1259            );
1260        }
1261    }
1262
1263    /// Test complex Dataview expressions with nested parentheses
1264    #[test]
1265    fn test_obsidian_dataview_complex_expressions() {
1266        let rule = MD038NoSpaceInCode::new();
1267
1268        let complex_cases = vec![
1269            // Nested function calls
1270            "`= sum(filter(pages, (p) => p.done))`",
1271            "`= length(filter(file.tags, (t) => startswith(t, \"project\")))`",
1272            // choice() function
1273            "`= choice(x > 5, \"big\", \"small\")`",
1274            "`= choice(this.status = \"done\", \"✅\", \"⏳\")`",
1275            // date functions
1276            "`= date(today) - dur(7 days)`",
1277            "`= dateformat(this.file.mtime, \"yyyy-MM-dd\")`",
1278            // Math expressions
1279            "`= sum(rows.amount)`",
1280            "`= round(average(rows.score), 2)`",
1281            "`= min(rows.priority)`",
1282            "`= max(rows.priority)`",
1283            // String operations
1284            "`= join(this.file.tags, \", \")`",
1285            "`= replace(this.title, \"-\", \" \")`",
1286            "`= lower(this.file.name)`",
1287            "`= upper(this.file.name)`",
1288            // List operations
1289            "`= length(this.file.outlinks)`",
1290            "`= contains(this.file.tags, \"important\")`",
1291            // Link references
1292            "`= [[Page Name]].field`",
1293            "`= [[Folder/Subfolder/Page]].nested.field`",
1294            // Conditional expressions
1295            "`= default(this.status, \"unknown\")`",
1296            "`= coalesce(this.priority, this.importance, 0)`",
1297        ];
1298
1299        for case in complex_cases {
1300            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1301            let result = rule.check(&ctx).unwrap();
1302            assert!(
1303                result.is_empty(),
1304                "Complex Dataview expression should not be flagged in Obsidian: {case}"
1305            );
1306        }
1307    }
1308
1309    /// Test that complex DataviewJS expressions with method chains are not flagged
1310    #[test]
1311    fn test_obsidian_dataviewjs_method_chains() {
1312        let rule = MD038NoSpaceInCode::new();
1313
1314        let method_chain_cases = vec![
1315            "`$= dv.pages().where(p => p.status).length`",
1316            "`$= dv.pages('#project').where(p => !p.done).length`",
1317            "`$= dv.pages().filter(p => p.file.day).sort(p => p.file.mtime, 'desc').limit(5)`",
1318            "`$= dv.pages('\"folder\"').map(p => p.file.link).join(', ')`",
1319            "`$= dv.current().file.tasks.where(t => !t.completed).length`",
1320            "`$= dv.pages().flatMap(p => p.file.tags).distinct().sort()`",
1321            "`$= dv.page('Index').children.map(p => p.title)`",
1322            "`$= dv.pages().groupBy(p => p.status).map(g => [g.key, g.rows.length])`",
1323        ];
1324
1325        for case in method_chain_cases {
1326            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1327            let result = rule.check(&ctx).unwrap();
1328            assert!(
1329                result.is_empty(),
1330                "DataviewJS method chain should not be flagged in Obsidian: {case}"
1331            );
1332        }
1333    }
1334
1335    /// Test Dataview-like patterns in Standard flavor
1336    ///
1337    /// Note: The actual content `= this.file.name` starts with `=`, not whitespace,
1338    /// so it doesn't have a leading space issue. Dataview expressions only become
1339    /// relevant when their content would otherwise be flagged.
1340    ///
1341    /// To properly test the difference, we need patterns that have leading whitespace
1342    /// issues that would be skipped in Obsidian but flagged in Standard.
1343    #[test]
1344    fn test_standard_flavor_vs_obsidian_dataview() {
1345        let rule = MD038NoSpaceInCode::new();
1346
1347        // These Dataview expressions don't have leading whitespace (they start with "=")
1348        // so they wouldn't be flagged in ANY flavor
1349        let no_issue_cases = vec!["`= this.file.name`", "`$= dv.current()`"];
1350
1351        for case in no_issue_cases {
1352            // Standard flavor - no issue because content doesn't start with whitespace
1353            let ctx_std = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1354            let result_std = rule.check(&ctx_std).unwrap();
1355            assert!(
1356                result_std.is_empty(),
1357                "Dataview expression without leading space shouldn't be flagged in Standard: {case}"
1358            );
1359
1360            // Obsidian flavor - also no issue
1361            let ctx_obs = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1362            let result_obs = rule.check(&ctx_obs).unwrap();
1363            assert!(
1364                result_obs.is_empty(),
1365                "Dataview expression shouldn't be flagged in Obsidian: {case}"
1366            );
1367        }
1368
1369        // Test that regular code with leading/trailing spaces is still flagged in both flavors
1370        // (when not matching Dataview pattern)
1371        let space_issues = vec![
1372            "` code`", // Leading space, no trailing
1373            "`code `", // Trailing space, no leading
1374        ];
1375
1376        for case in space_issues {
1377            // Standard flavor - should be flagged
1378            let ctx_std = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1379            let result_std = rule.check(&ctx_std).unwrap();
1380            assert!(
1381                !result_std.is_empty(),
1382                "Code with spacing issue should be flagged in Standard: {case}"
1383            );
1384
1385            // Obsidian flavor - should also be flagged (not a Dataview pattern)
1386            let ctx_obs = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1387            let result_obs = rule.check(&ctx_obs).unwrap();
1388            assert!(
1389                !result_obs.is_empty(),
1390                "Code with spacing issue should be flagged in Obsidian (not Dataview): {case}"
1391            );
1392        }
1393    }
1394
1395    /// Test that regular code spans with leading space are still flagged in Obsidian
1396    #[test]
1397    fn test_obsidian_still_flags_regular_code_spans_with_space() {
1398        let rule = MD038NoSpaceInCode::new();
1399
1400        // These are NOT Dataview expressions, just regular code spans with leading space
1401        // They should still be flagged even in Obsidian flavor
1402        let invalid_cases = [
1403            "` regular code`", // Space at start, not Dataview
1404            "`code `",         // Space at end
1405            "` code `",        // This is valid per CommonMark (symmetric single space)
1406            "`  code`",        // Double space at start (not Dataview pattern)
1407        ];
1408
1409        // Only the asymmetric cases should be flagged
1410        let expected_flags = [
1411            true,  // ` regular code` - leading space, no trailing
1412            true,  // `code ` - trailing space, no leading
1413            false, // ` code ` - symmetric single space (CommonMark valid)
1414            true,  // `  code` - double leading space
1415        ];
1416
1417        for (case, should_flag) in invalid_cases.iter().zip(expected_flags.iter()) {
1418            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1419            let result = rule.check(&ctx).unwrap();
1420            if *should_flag {
1421                assert!(
1422                    !result.is_empty(),
1423                    "Non-Dataview code span with spacing issue should be flagged in Obsidian: {case}"
1424                );
1425            } else {
1426                assert!(
1427                    result.is_empty(),
1428                    "CommonMark-valid symmetric spacing should not be flagged: {case}"
1429                );
1430            }
1431        }
1432    }
1433
1434    /// Test edge cases for Dataview pattern detection
1435    #[test]
1436    fn test_obsidian_dataview_edge_cases() {
1437        let rule = MD038NoSpaceInCode::new();
1438
1439        // Valid Dataview patterns
1440        let valid_cases = vec![
1441            ("`= x`", true),                         // Minimal DQL
1442            ("`$= x`", true),                        // Minimal DVJS
1443            ("`= `", true),                          // Just equals-space (empty expression)
1444            ("`$= `", true),                         // Just dollar-equals-space (empty expression)
1445            ("`=x`", false),                         // No space after = (not Dataview, and no leading whitespace issue)
1446            ("`$=x`", false),       // No space after $= (not Dataview, and no leading whitespace issue)
1447            ("`= [[Link]]`", true), // Link in expression
1448            ("`= this`", true),     // Simple this reference
1449            ("`$= dv`", true),      // Just dv object reference
1450            ("`= 1 + 2`", true),    // Math expression
1451            ("`$= 1 + 2`", true),   // Math in DVJS
1452            ("`= \"string\"`", true), // String literal
1453            ("`$= 'string'`", true), // Single-quoted string
1454            ("`= this.field ?? \"default\"`", true), // Null coalescing
1455            ("`$= dv?.pages()`", true), // Optional chaining
1456        ];
1457
1458        for (case, should_be_valid) in valid_cases {
1459            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1460            let result = rule.check(&ctx).unwrap();
1461            if should_be_valid {
1462                assert!(
1463                    result.is_empty(),
1464                    "Valid Dataview expression should not be flagged: {case}"
1465                );
1466            } else {
1467                // These might or might not be flagged depending on other MD038 rules
1468                // We just verify they don't crash
1469                let _ = result;
1470            }
1471        }
1472    }
1473
1474    /// Test Dataview expressions in context (mixed with regular markdown)
1475    #[test]
1476    fn test_obsidian_dataview_in_context() {
1477        let rule = MD038NoSpaceInCode::new();
1478
1479        // Document with mixed Dataview and regular code spans
1480        let content = r#"# My Note
1481
1482The file name is `= this.file.name` and it was created on `= this.file.ctime`.
1483
1484Regular code: `println!("hello")` and `let x = 5;`
1485
1486DataviewJS count: `$= dv.pages('#project').length` projects found.
1487
1488More regular code with issue: ` bad code` should be flagged.
1489"#;
1490
1491        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1492        let result = rule.check(&ctx).unwrap();
1493
1494        // Should only flag ` bad code` (line 9)
1495        assert_eq!(
1496            result.len(),
1497            1,
1498            "Should only flag the regular code span with leading space, not Dataview expressions"
1499        );
1500        assert_eq!(result[0].line, 9, "Warning should be on line 9");
1501    }
1502
1503    /// Test that Dataview expressions in code blocks are properly handled
1504    #[test]
1505    fn test_obsidian_dataview_in_code_blocks() {
1506        let rule = MD038NoSpaceInCode::new();
1507
1508        // Dataview expressions inside fenced code blocks should be ignored
1509        // (because they're inside code blocks, not because of Dataview logic)
1510        let content = r#"# Example
1511
1512```
1513`= this.file.name`
1514`$= dv.current()`
1515```
1516
1517Regular paragraph with `= this.file.name` Dataview.
1518"#;
1519
1520        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1521        let result = rule.check(&ctx).unwrap();
1522
1523        // Should not flag anything - code blocks are skipped, and inline Dataview is valid
1524        assert!(
1525            result.is_empty(),
1526            "Dataview in code blocks should be ignored, inline Dataview should be valid"
1527        );
1528    }
1529
1530    /// Test Dataview with Unicode content
1531    #[test]
1532    fn test_obsidian_dataview_unicode() {
1533        let rule = MD038NoSpaceInCode::new();
1534
1535        let unicode_cases = vec![
1536            "`= this.日本語`",                  // Japanese field name
1537            "`= this.中文字段`",                // Chinese field name
1538            "`= \"Привет мир\"`",               // Russian string
1539            "`$= dv.pages('#日本語タグ')`",     // Japanese tag
1540            "`= choice(true, \"✅\", \"❌\")`", // Emoji in strings
1541            "`= this.file.name + \" 📝\"`",     // Emoji concatenation
1542        ];
1543
1544        for case in unicode_cases {
1545            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1546            let result = rule.check(&ctx).unwrap();
1547            assert!(
1548                result.is_empty(),
1549                "Unicode Dataview expression should not be flagged: {case}"
1550            );
1551        }
1552    }
1553
1554    /// Test that Dataview detection doesn't break regular equals patterns
1555    #[test]
1556    fn test_obsidian_regular_equals_still_works() {
1557        let rule = MD038NoSpaceInCode::new();
1558
1559        // Regular code with equals signs should still work normally
1560        let valid_regular_cases = vec![
1561            "`x = 5`",       // Assignment (no leading space)
1562            "`a == b`",      // Equality check
1563            "`x >= 10`",     // Comparison
1564            "`let x = 10`",  // Variable declaration
1565            "`const y = 5`", // Const declaration
1566        ];
1567
1568        for case in valid_regular_cases {
1569            let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1570            let result = rule.check(&ctx).unwrap();
1571            assert!(
1572                result.is_empty(),
1573                "Regular code with equals should not be flagged: {case}"
1574            );
1575        }
1576    }
1577
1578    /// Test fix behavior doesn't break Dataview expressions
1579    #[test]
1580    fn test_obsidian_dataview_fix_preserves_expressions() {
1581        let rule = MD038NoSpaceInCode::new();
1582
1583        // Content with Dataview expressions and one fixable issue
1584        let content = "Dataview: `= this.file.name` and bad: ` fixme`";
1585        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1586        let fixed = rule.fix(&ctx).unwrap();
1587
1588        // Should fix ` fixme` but preserve `= this.file.name`
1589        assert!(
1590            fixed.contains("`= this.file.name`"),
1591            "Dataview expression should be preserved after fix"
1592        );
1593        assert!(
1594            fixed.contains("`fixme`"),
1595            "Regular code span should be fixed (space removed)"
1596        );
1597        assert!(!fixed.contains("` fixme`"), "Bad code span should have been fixed");
1598    }
1599
1600    /// Test multiple Dataview expressions on same line
1601    #[test]
1602    fn test_obsidian_multiple_dataview_same_line() {
1603        let rule = MD038NoSpaceInCode::new();
1604
1605        let content = "Created: `= this.file.ctime` | Modified: `= this.file.mtime` | Count: `$= dv.pages().length`";
1606        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1607        let result = rule.check(&ctx).unwrap();
1608
1609        assert!(
1610            result.is_empty(),
1611            "Multiple Dataview expressions on same line should all be valid"
1612        );
1613    }
1614
1615    /// Performance test: Many Dataview expressions
1616    #[test]
1617    fn test_obsidian_dataview_performance() {
1618        let rule = MD038NoSpaceInCode::new();
1619
1620        // Create content with many Dataview expressions
1621        let mut content = String::new();
1622        for i in 0..100 {
1623            content.push_str(&format!("Field {i}: `= this.field{i}` | JS: `$= dv.current().f{i}`\n"));
1624        }
1625
1626        let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Obsidian, None);
1627        let start = std::time::Instant::now();
1628        let result = rule.check(&ctx).unwrap();
1629        let duration = start.elapsed();
1630
1631        assert!(result.is_empty(), "All Dataview expressions should be valid");
1632        assert!(
1633            duration.as_millis() < 1000,
1634            "Performance test: Should process 200 Dataview expressions in <1s, took {duration:?}"
1635        );
1636    }
1637
1638    /// Test is_dataview_expression helper function directly
1639    #[test]
1640    fn test_is_dataview_expression_helper() {
1641        // Valid Dataview patterns
1642        assert!(MD038NoSpaceInCode::is_dataview_expression("= this.file.name"));
1643        assert!(MD038NoSpaceInCode::is_dataview_expression("= "));
1644        assert!(MD038NoSpaceInCode::is_dataview_expression("$= dv.current()"));
1645        assert!(MD038NoSpaceInCode::is_dataview_expression("$= "));
1646        assert!(MD038NoSpaceInCode::is_dataview_expression("= x"));
1647        assert!(MD038NoSpaceInCode::is_dataview_expression("$= x"));
1648
1649        // Invalid Dataview patterns
1650        assert!(!MD038NoSpaceInCode::is_dataview_expression("=")); // No space after =
1651        assert!(!MD038NoSpaceInCode::is_dataview_expression("$=")); // No space after $=
1652        assert!(!MD038NoSpaceInCode::is_dataview_expression("=x")); // No space
1653        assert!(!MD038NoSpaceInCode::is_dataview_expression("$=x")); // No space
1654        assert!(!MD038NoSpaceInCode::is_dataview_expression(" = x")); // Leading space before =
1655        assert!(!MD038NoSpaceInCode::is_dataview_expression("x = 5")); // Assignment, not Dataview
1656        assert!(!MD038NoSpaceInCode::is_dataview_expression("== x")); // Double equals
1657        assert!(!MD038NoSpaceInCode::is_dataview_expression("")); // Empty
1658        assert!(!MD038NoSpaceInCode::is_dataview_expression("regular")); // Regular text
1659    }
1660
1661    /// Test Dataview expressions work alongside other Obsidian features (tags)
1662    #[test]
1663    fn test_obsidian_dataview_with_tags() {
1664        let rule = MD038NoSpaceInCode::new();
1665
1666        // Document using both Dataview and Obsidian tags
1667        let content = r#"# Project Status
1668
1669Tags: #project #active
1670
1671Status: `= this.status`
1672Count: `$= dv.pages('#project').length`
1673
1674Regular code: `function test() {}`
1675"#;
1676
1677        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1678        let result = rule.check(&ctx).unwrap();
1679
1680        // Nothing should be flagged
1681        assert!(
1682            result.is_empty(),
1683            "Dataview expressions and regular code should work together"
1684        );
1685    }
1686
1687    #[test]
1688    fn test_unicode_between_code_spans_no_panic() {
1689        // Verify that multi-byte characters between code spans do not cause panics
1690        // or incorrect slicing in the nested-backtick detection logic.
1691        let rule = MD038NoSpaceInCode::new();
1692
1693        // Multi-byte character (U-umlaut = 2 bytes) between two code spans
1694        let content = "Use `one` \u{00DC}nited `two` for backtick examples.";
1695        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1696        let result = rule.check(&ctx);
1697        // Should not panic; any warnings or lack thereof are acceptable
1698        assert!(result.is_ok(), "Should not panic with Unicode between code spans");
1699
1700        // CJK characters (3 bytes each) between code spans
1701        let content_cjk = "Use `one` \u{4E16}\u{754C} `two` for examples.";
1702        let ctx_cjk = crate::lint_context::LintContext::new(content_cjk, crate::config::MarkdownFlavor::Standard, None);
1703        let result_cjk = rule.check(&ctx_cjk);
1704        assert!(result_cjk.is_ok(), "Should not panic with CJK between code spans");
1705    }
1706
1707    #[test]
1708    fn test_pandoc_inline_r_code_not_exempt() {
1709        // The `r expression` pattern is RMarkdown/Quarto-specific inline R evaluation syntax.
1710        // A code span like `r foo ` (trailing space, starts with `r `) triggers the Quarto
1711        // guard when in Quarto flavor — the trailing space violation is suppressed because the
1712        // content looks like inline R code.  Under Pandoc flavor the guard must NOT fire:
1713        // `r ` is not special Pandoc syntax, so the trailing space is a genuine MD038 violation.
1714        let rule = MD038NoSpaceInCode::new();
1715        // Trailing space only (no leading space) — CommonMark does not strip this, so it's a
1716        // real MD038 violation.  The `r ` prefix makes it match the Quarto `r expression` guard.
1717        let content = "See `r foo ` for details.\n";
1718
1719        // Under Quarto flavor, the `r expression` guard fires and suppresses the warning.
1720        let ctx_quarto = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
1721        let result_quarto = rule.check(&ctx_quarto).unwrap();
1722        assert!(
1723            result_quarto.is_empty(),
1724            "MD038 should suppress trailing-space warning for `r expression` under Quarto: {result_quarto:?}"
1725        );
1726
1727        // Under Pandoc flavor, the guard does NOT fire — trailing space is flagged.
1728        let ctx_pandoc = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1729        let result_pandoc = rule.check(&ctx_pandoc).unwrap();
1730        assert!(
1731            !result_pandoc.is_empty(),
1732            "MD038 should flag trailing space in `r expression` under Pandoc flavor (not Quarto/RMarkdown syntax): {result_pandoc:?}"
1733        );
1734    }
1735
1736    /// Pandoc inline code attribute syntax (`` `code`{.lang} ``) does not exempt
1737    /// the code span from MD038's inner-whitespace check: the attribute block lives
1738    /// outside the closing backtick, so a leading space inside the backticks is a
1739    /// real spacing violation regardless of any attached attribute.
1740    #[test]
1741    fn test_pandoc_inline_code_attr_does_not_suppress_leading_space() {
1742        let rule = MD038NoSpaceInCode::new();
1743        let content = "Use ` print()`{.python} for output.\n";
1744        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1745        let result = rule.check(&ctx).unwrap();
1746        assert!(
1747            !result.is_empty(),
1748            "MD038 must flag leading space inside `code`{{.lang}} under Pandoc — the attribute is outside the span: {result:?}"
1749        );
1750    }
1751
1752    /// Trailing space inside an attributed code span is also a real violation
1753    /// under Pandoc — the `{.lang}` attribute does not absorb whitespace from
1754    /// inside the backticks.
1755    #[test]
1756    fn test_pandoc_inline_code_attr_does_not_suppress_trailing_space() {
1757        let rule = MD038NoSpaceInCode::new();
1758        let content = "Use `print() `{.python} for output.\n";
1759        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1760        let result = rule.check(&ctx).unwrap();
1761        assert!(
1762            !result.is_empty(),
1763            "MD038 must flag trailing space inside `code`{{.lang}} under Pandoc — the attribute is outside the span: {result:?}"
1764        );
1765    }
1766
1767    /// Cross-flavor parity: Standard flavor still flags the same content.
1768    #[test]
1769    fn test_standard_still_flags_leading_space_with_attr_syntax() {
1770        let rule = MD038NoSpaceInCode::new();
1771        let content = "Use ` print()`{.python} for output.\n";
1772        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1773        let result = rule.check(&ctx).unwrap();
1774        assert!(
1775            !result.is_empty(),
1776            "MD038 should flag leading space in code span under Standard flavor: {result:?}"
1777        );
1778    }
1779
1780    /// Clean attributed code spans (no inner whitespace) must still pass under
1781    /// Pandoc — the no-whitespace fast path handles them, no special guard needed.
1782    #[test]
1783    fn test_pandoc_inline_code_attr_clean_span_not_flagged() {
1784        let rule = MD038NoSpaceInCode::new();
1785        let content = "Use `print()`{.python} for output.\n";
1786        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1787        let result = rule.check(&ctx).unwrap();
1788        assert!(
1789            result.is_empty(),
1790            "MD038 must not flag a clean attributed code span under Pandoc: {result:?}"
1791        );
1792    }
1793}