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
5const NESTING_WORDS: [&str; 2] = ["code", "backtick"];
7
8#[derive(Default)]
10struct NestedBacktickState {
11 runs: Option<Vec<(usize, usize)>>,
13 line: Option<LineNesting>,
15}
16
17struct LineNesting {
24 line: usize,
26 char_offsets: Vec<usize>,
28 len: usize,
30 word_end_after_first: Option<usize>,
32 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 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 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 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 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 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#[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 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 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 if span_start >= 3 {
191 let before_span = &start_line_content[..span_start];
194
195 let char_at_span_start = start_line_content[span_start..].chars().next().unwrap_or(' ');
199
200 let is_hugo_start =
208 (before_span.ends_with("{{raw ") && char_at_span_start == '`')
210 || (before_span.starts_with("{{<") && before_span.ends_with(' ') && char_at_span_start == '`')
212 || (before_span.ends_with("{{% ") && char_at_span_start == '`')
214 || (before_span.ends_with("{{ ") && char_at_span_start == '`');
216
217 if is_hugo_start {
218 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 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 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 fn is_dataview_expression(content: &str) -> bool {
268 content.starts_with("= ") || content.starts_with("$= ")
271 }
272
273 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 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 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 if first == last {
310 return false;
311 }
312
313 let line_idx = current_span.line - 1; 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 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 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 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 let code_spans = ctx.code_spans();
393 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 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 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 if code_content.is_empty() {
422 continue;
423 }
424
425 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 if trimmed.is_empty() {
441 continue;
442 }
443
444 if code_content != trimmed {
446 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 if leading_spaces == 1 && trailing_spaces == 1 {
465 continue;
466 }
467 }
468 if trimmed.contains('`') {
471 continue;
472 }
473
474 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 if ctx.flavor == crate::config::MarkdownFlavor::MkDocs && is_inline_hilite_content(trimmed) {
489 continue;
490 }
491
492 if ctx.flavor == crate::config::MarkdownFlavor::Obsidian && Self::is_dataview_expression(code_content) {
496 continue;
497 }
498
499 if ctx.flavor.supports_myst_roles() && ctx.is_in_myst_role(code_span.byte_offset) {
502 continue;
503 }
504
505 if self.is_hugo_template_syntax(ctx, code_span) {
508 continue;
509 }
510
511 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, end_line: code_span.line,
526 end_column: code_span.end_col, 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 if !content.contains('`') {
553 return Ok(content.to_string());
554 }
555
556 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 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 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 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 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 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 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 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 let invalid_cases = vec![
686 "This is ` code` with leading space.",
688 "This is `code ` with trailing space.",
690 "This is ` code ` with double leading space.",
692 "This is ` code ` with double trailing space.",
694 "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 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 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 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 let test_cases = vec![
782 (
784 "This is ` code` with leading space.",
785 "This is `code` with leading space.",
786 ),
787 (
789 "This is `code ` with trailing space.",
790 "This is `code` with trailing space.",
791 ),
792 (
794 "This is ` code ` with both spaces.",
795 "This is ` code ` with both spaces.", ),
797 (
799 "This is ` code ` with double leading space.",
800 "This is `code` with double leading space.",
801 ),
802 (
804 "Multiple ` code ` and `spans ` to fix.",
805 "Multiple ` code ` and `spans` to fix.", ),
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 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 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 let rule = MD038NoSpaceInCode::new();
860
861 let content = r#"The result is `r nchar("test")` which equals 4."#;
864
865 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 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 #[test]
893 fn test_hugo_template_syntax_comprehensive() {
894 let rule = MD038NoSpaceInCode::new();
895
896 let valid_hugo_cases = vec![
900 (
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 ("{{< ` code ` >}}", "Partial shortcode with spaces"),
912 ("{{< `code` >}}", "Partial shortcode without spaces"),
913 ("{{% ` code ` %}}", "Percent shortcode with spaces"),
915 ("{{% `code` %}}", "Percent shortcode without spaces"),
916 ("{{ ` code ` }}", "Generic shortcode with spaces"),
918 ("{{ `code` }}", "Generic shortcode without spaces"),
919 ("{{< highlight go `code` >}}", "Shortcode with highlight parameter"),
921 ("{{< code `go list` >}}", "Shortcode with code parameter"),
922 ("{{raw `\n\tcommand here\n\tmore code\n`}}", "Multi-line raw template"),
924 ("{{< highlight `\ncode here\n` >}}", "Multi-line highlight template"),
925 (
927 "{{raw `\n\t{{.Variable}}\n\t{{range .Items}}\n`}}",
928 "Nested Go template syntax",
929 ),
930 ("{{raw `code`}}", "Hugo template at line start"),
932 ("Text {{raw `code`}}", "Hugo template at end of line"),
934 ("{{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 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 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 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 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 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 #[test]
1040 fn test_hugo_template_after_multibyte_text() {
1041 let rule = MD038NoSpaceInCode::new();
1042
1043 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 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]
1079 fn test_hugo_template_with_other_markdown() {
1080 let rule = MD038NoSpaceInCode::new();
1081
1082 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 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 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 #[test]
1108 fn test_hugo_template_performance() {
1109 let rule = MD038NoSpaceInCode::new();
1110
1111 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 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 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 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 let rule = MD038NoSpaceInCode::new();
1171
1172 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 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 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 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 #[test]
1204 fn test_obsidian_dataview_inline_dql_not_flagged() {
1205 let rule = MD038NoSpaceInCode::new();
1206
1207 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]
1237 fn test_obsidian_dataview_inline_dvjs_not_flagged() {
1238 let rule = MD038NoSpaceInCode::new();
1239
1240 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]
1265 fn test_obsidian_dataview_complex_expressions() {
1266 let rule = MD038NoSpaceInCode::new();
1267
1268 let complex_cases = vec![
1269 "`= sum(filter(pages, (p) => p.done))`",
1271 "`= length(filter(file.tags, (t) => startswith(t, \"project\")))`",
1272 "`= choice(x > 5, \"big\", \"small\")`",
1274 "`= choice(this.status = \"done\", \"✅\", \"⏳\")`",
1275 "`= date(today) - dur(7 days)`",
1277 "`= dateformat(this.file.mtime, \"yyyy-MM-dd\")`",
1278 "`= sum(rows.amount)`",
1280 "`= round(average(rows.score), 2)`",
1281 "`= min(rows.priority)`",
1282 "`= max(rows.priority)`",
1283 "`= join(this.file.tags, \", \")`",
1285 "`= replace(this.title, \"-\", \" \")`",
1286 "`= lower(this.file.name)`",
1287 "`= upper(this.file.name)`",
1288 "`= length(this.file.outlinks)`",
1290 "`= contains(this.file.tags, \"important\")`",
1291 "`= [[Page Name]].field`",
1293 "`= [[Folder/Subfolder/Page]].nested.field`",
1294 "`= 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]
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]
1344 fn test_standard_flavor_vs_obsidian_dataview() {
1345 let rule = MD038NoSpaceInCode::new();
1346
1347 let no_issue_cases = vec!["`= this.file.name`", "`$= dv.current()`"];
1350
1351 for case in no_issue_cases {
1352 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 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 let space_issues = vec![
1372 "` code`", "`code `", ];
1375
1376 for case in space_issues {
1377 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 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]
1397 fn test_obsidian_still_flags_regular_code_spans_with_space() {
1398 let rule = MD038NoSpaceInCode::new();
1399
1400 let invalid_cases = [
1403 "` regular code`", "`code `", "` code `", "` code`", ];
1408
1409 let expected_flags = [
1411 true, true, false, true, ];
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]
1436 fn test_obsidian_dataview_edge_cases() {
1437 let rule = MD038NoSpaceInCode::new();
1438
1439 let valid_cases = vec![
1441 ("`= x`", true), ("`$= x`", true), ("`= `", true), ("`$= `", true), ("`=x`", false), ("`$=x`", false), ("`= [[Link]]`", true), ("`= this`", true), ("`$= dv`", true), ("`= 1 + 2`", true), ("`$= 1 + 2`", true), ("`= \"string\"`", true), ("`$= 'string'`", true), ("`= this.field ?? \"default\"`", true), ("`$= dv?.pages()`", true), ];
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 let _ = result;
1470 }
1471 }
1472 }
1473
1474 #[test]
1476 fn test_obsidian_dataview_in_context() {
1477 let rule = MD038NoSpaceInCode::new();
1478
1479 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 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]
1505 fn test_obsidian_dataview_in_code_blocks() {
1506 let rule = MD038NoSpaceInCode::new();
1507
1508 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 assert!(
1525 result.is_empty(),
1526 "Dataview in code blocks should be ignored, inline Dataview should be valid"
1527 );
1528 }
1529
1530 #[test]
1532 fn test_obsidian_dataview_unicode() {
1533 let rule = MD038NoSpaceInCode::new();
1534
1535 let unicode_cases = vec![
1536 "`= this.日本語`", "`= this.中文字段`", "`= \"Привет мир\"`", "`$= dv.pages('#日本語タグ')`", "`= choice(true, \"✅\", \"❌\")`", "`= this.file.name + \" 📝\"`", ];
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]
1556 fn test_obsidian_regular_equals_still_works() {
1557 let rule = MD038NoSpaceInCode::new();
1558
1559 let valid_regular_cases = vec![
1561 "`x = 5`", "`a == b`", "`x >= 10`", "`let x = 10`", "`const y = 5`", ];
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]
1580 fn test_obsidian_dataview_fix_preserves_expressions() {
1581 let rule = MD038NoSpaceInCode::new();
1582
1583 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 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]
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 #[test]
1617 fn test_obsidian_dataview_performance() {
1618 let rule = MD038NoSpaceInCode::new();
1619
1620 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]
1640 fn test_is_dataview_expression_helper() {
1641 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 assert!(!MD038NoSpaceInCode::is_dataview_expression("=")); assert!(!MD038NoSpaceInCode::is_dataview_expression("$=")); assert!(!MD038NoSpaceInCode::is_dataview_expression("=x")); assert!(!MD038NoSpaceInCode::is_dataview_expression("$=x")); assert!(!MD038NoSpaceInCode::is_dataview_expression(" = x")); assert!(!MD038NoSpaceInCode::is_dataview_expression("x = 5")); assert!(!MD038NoSpaceInCode::is_dataview_expression("== x")); assert!(!MD038NoSpaceInCode::is_dataview_expression("")); assert!(!MD038NoSpaceInCode::is_dataview_expression("regular")); }
1660
1661 #[test]
1663 fn test_obsidian_dataview_with_tags() {
1664 let rule = MD038NoSpaceInCode::new();
1665
1666 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 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 let rule = MD038NoSpaceInCode::new();
1692
1693 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 assert!(result.is_ok(), "Should not panic with Unicode between code spans");
1699
1700 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 let rule = MD038NoSpaceInCode::new();
1715 let content = "See `r foo ` for details.\n";
1718
1719 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 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 #[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 #[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 #[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 #[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}