Skip to main content

rumdl_lib/rules/
md038_no_space_in_code.rs

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