1use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
2use crate::utils::mkdocs_extensions::is_inline_hilite_content;
3
4#[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 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 let span_start_col = code_span.start_col;
67
68 if span_start_col >= 3 {
74 let before_span: String = start_line_content.chars().take(span_start_col).collect();
77
78 let char_at_span_start = start_line_content.chars().nth(span_start_col).unwrap_or(' ');
82
83 let is_hugo_start =
91 (before_span.ends_with("{{raw ") && char_at_span_start == '`')
93 || (before_span.starts_with("{{<") && before_span.ends_with(' ') && char_at_span_start == '`')
95 || (before_span.ends_with("{{% ") && char_at_span_start == '`')
97 || (before_span.ends_with("{{ ") && char_at_span_start == '`');
99
100 if is_hugo_start {
101 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 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 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 fn is_dataview_expression(content: &str) -> bool {
148 content.starts_with("= ") || content.starts_with("$= ")
151 }
152
153 fn is_likely_nested_backticks(&self, ctx: &crate::lint_context::LintContext, span_index: usize) -> bool {
155 let code_spans = ctx.code_spans();
158 let current_span = &code_spans[span_index];
159 let current_line = current_span.line;
160
161 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 let line_idx = current_line - 1; 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 (_, 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 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 between.contains("code") || between.contains("backtick") {
200 return true;
201 }
202 }
203 }
204 }
205
206 false
207 }
208
209 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 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 let code_spans = ctx.code_spans();
260 for (i, code_span) in code_spans.iter().enumerate() {
261 if let Some(line_info) = ctx.lines.get(code_span.line - 1) {
263 if line_info.in_code_block {
264 continue;
265 }
266 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 if code_content.is_empty() {
278 continue;
279 }
280
281 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 if code_content != trimmed {
293 if has_leading_space && has_trailing_space && !trimmed.is_empty() {
305 let leading_spaces = code_content.len() - code_content.trim_start().len();
306 let trailing_spaces = code_content.len() - code_content.trim_end().len();
307
308 if leading_spaces == 1 && trailing_spaces == 1 {
310 continue;
311 }
312 }
313 if trimmed.contains('`') {
316 continue;
317 }
318
319 if ctx.flavor == crate::config::MarkdownFlavor::Quarto
324 && trimmed.starts_with('r')
325 && trimmed.len() > 1
326 && trimmed.chars().nth(1).is_some_and(char::is_whitespace)
327 {
328 continue;
329 }
330
331 if ctx.flavor == crate::config::MarkdownFlavor::MkDocs && is_inline_hilite_content(trimmed) {
334 continue;
335 }
336
337 if ctx.flavor == crate::config::MarkdownFlavor::Obsidian && Self::is_dataview_expression(code_content) {
341 continue;
342 }
343
344 if self.is_hugo_template_syntax(ctx, code_span) {
347 continue;
348 }
349
350 if self.is_likely_nested_backticks(ctx, i) {
353 continue;
354 }
355
356 if self.has_attached_nested_backtick_boundary(ctx, code_span) {
357 continue;
358 }
359
360 warnings.push(LintWarning {
361 rule_name: Some(self.name().to_string()),
362 line: code_span.line,
363 column: code_span.start_col + 1, end_line: code_span.line,
365 end_column: code_span.end_col, message: "Spaces inside code span elements".to_string(),
367 severity: Severity::Warning,
368 fix: Some(Fix::new(
369 code_span.byte_offset..code_span.byte_end,
370 format!(
371 "{}{}{}",
372 "`".repeat(code_span.backtick_count),
373 trimmed,
374 "`".repeat(code_span.backtick_count)
375 ),
376 )),
377 });
378 }
379 }
380
381 Ok(warnings)
382 }
383
384 fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
385 let content = ctx.content;
386 if !self.enabled {
387 return Ok(content.to_string());
388 }
389
390 if !content.contains('`') {
392 return Ok(content.to_string());
393 }
394
395 let warnings = self.check(ctx)?;
397 let warnings =
398 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
399 if warnings.is_empty() {
400 return Ok(content.to_string());
401 }
402
403 let mut fixes: Vec<(std::ops::Range<usize>, String)> = warnings
405 .into_iter()
406 .filter_map(|w| w.fix.map(|f| (f.range, f.replacement)))
407 .collect();
408
409 fixes.sort_by_key(|(range, _)| std::cmp::Reverse(range.start));
410
411 let mut result = content.to_string();
413 for (range, replacement) in fixes {
414 result.replace_range(range, &replacement);
415 }
416
417 Ok(result)
418 }
419
420 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
422 !ctx.likely_has_code()
423 }
424
425 fn as_any(&self) -> &dyn std::any::Any {
426 self
427 }
428
429 fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
430 where
431 Self: Sized,
432 {
433 Box::new(MD038NoSpaceInCode { enabled: true })
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn test_md038_readme_false_positives() {
443 let rule = MD038NoSpaceInCode::new();
445 let valid_cases = vec![
446 "3. `pyproject.toml` (must contain `[tool.rumdl]` section)",
447 "#### Effective Configuration (`rumdl config`)",
448 "- Blue: `.rumdl.toml`",
449 "### Defaults Only (`rumdl config --defaults`)",
450 ];
451
452 for case in valid_cases {
453 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
454 let result = rule.check(&ctx).unwrap();
455 assert!(
456 result.is_empty(),
457 "Should not flag code spans without leading/trailing spaces: '{}'. Got {} warnings",
458 case,
459 result.len()
460 );
461 }
462 }
463
464 #[test]
465 fn test_md038_valid() {
466 let rule = MD038NoSpaceInCode::new();
467 let valid_cases = vec![
468 "This is `code` in a sentence.",
469 "This is a `longer code span` in a sentence.",
470 "This is `code with internal spaces` which is fine.",
471 "Code span at `end of line`",
472 "`Start of line` code span",
473 "Multiple `code spans` in `one line` are fine",
474 "Code span with `symbols: !@#$%^&*()`",
475 "Empty code span `` is technically valid",
476 ];
477 for case in valid_cases {
478 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
479 let result = rule.check(&ctx).unwrap();
480 assert!(result.is_empty(), "Valid case should not have warnings: {case}");
481 }
482 }
483
484 #[test]
485 fn test_md038_invalid() {
486 let rule = MD038NoSpaceInCode::new();
487 let invalid_cases = vec![
492 "This is ` code` with leading space.",
494 "This is `code ` with trailing space.",
496 "This is ` code ` with double leading space.",
498 "This is ` code ` with double trailing space.",
500 "This is ` code ` with double spaces both sides.",
502 ];
503 for case in invalid_cases {
504 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
505 let result = rule.check(&ctx).unwrap();
506 assert!(!result.is_empty(), "Invalid case should have warnings: {case}");
507 }
508 }
509
510 #[test]
511 fn test_md038_valid_commonmark_stripping() {
512 let rule = MD038NoSpaceInCode::new();
513 let valid_cases = vec![
517 "Type ` y ` to confirm.",
518 "Use ` git commit -m \"message\" ` to commit.",
519 "The variable ` $HOME ` contains home path.",
520 "The pattern ` *.txt ` matches text files.",
521 "This is ` random word ` with unnecessary spaces.",
522 "Text with ` plain text ` is valid.",
523 "Code with ` just code ` here.",
524 "Multiple ` word ` spans with ` text ` in one line.",
525 "This is ` code ` with both leading and trailing single space.",
526 "Use ` - ` as separator.",
527 ];
528 for case in valid_cases {
529 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
530 let result = rule.check(&ctx).unwrap();
531 assert!(
532 result.is_empty(),
533 "Single space on each side should not be flagged (CommonMark strips them): {case}"
534 );
535 }
536 }
537
538 #[test]
539 fn test_md038_fix() {
540 let rule = MD038NoSpaceInCode::new();
541 let test_cases = vec![
543 (
545 "This is ` code` with leading space.",
546 "This is `code` with leading space.",
547 ),
548 (
550 "This is `code ` with trailing space.",
551 "This is `code` with trailing space.",
552 ),
553 (
555 "This is ` code ` with both spaces.",
556 "This is ` code ` with both spaces.", ),
558 (
560 "This is ` code ` with double leading space.",
561 "This is `code` with double leading space.",
562 ),
563 (
565 "Multiple ` code ` and `spans ` to fix.",
566 "Multiple ` code ` and `spans` to fix.", ),
568 ];
569 for (input, expected) in test_cases {
570 let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
571 let result = rule.fix(&ctx).unwrap();
572 assert_eq!(result, expected, "Fix did not produce expected output for: {input}");
573 }
574 }
575
576 #[test]
577 fn test_check_invalid_leading_space() {
578 let rule = MD038NoSpaceInCode::new();
579 let input = "This has a ` leading space` in code";
580 let ctx = crate::lint_context::LintContext::new(input, crate::config::MarkdownFlavor::Standard, None);
581 let result = rule.check(&ctx).unwrap();
582 assert_eq!(result.len(), 1);
583 assert_eq!(result[0].line, 1);
584 assert!(result[0].fix.is_some());
585 }
586
587 #[test]
588 fn test_code_span_parsing_nested_backticks() {
589 let content = "Code with ` nested `code` example ` should preserve backticks";
590 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
591
592 println!("Content: {content}");
593 println!("Code spans found:");
594 let code_spans = ctx.code_spans();
595 for (i, span) in code_spans.iter().enumerate() {
596 println!(
597 " Span {}: line={}, col={}-{}, backticks={}, content='{}'",
598 i, span.line, span.start_col, span.end_col, span.backtick_count, span.content
599 );
600 }
601
602 assert_eq!(code_spans.len(), 2, "Should parse as 2 code spans");
604 }
605
606 #[test]
607 fn test_nested_backtick_detection() {
608 let rule = MD038NoSpaceInCode::new();
609
610 let content = "Code with `` `backticks` inside `` should not be flagged";
612 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
613 let result = rule.check(&ctx).unwrap();
614 assert!(result.is_empty(), "Code spans with backticks should be skipped");
615 }
616
617 #[test]
618 fn test_quarto_inline_r_code() {
619 let rule = MD038NoSpaceInCode::new();
621
622 let content = r#"The result is `r nchar("test")` which equals 4."#;
625
626 let ctx_quarto = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
628 let result_quarto = rule.check(&ctx_quarto).unwrap();
629 assert!(
630 result_quarto.is_empty(),
631 "Quarto inline R code should not trigger warnings. Got {} warnings",
632 result_quarto.len()
633 );
634
635 let content_other = "This has `plain text ` with trailing space.";
638 let ctx_other =
639 crate::lint_context::LintContext::new(content_other, crate::config::MarkdownFlavor::Quarto, None);
640 let result_other = rule.check(&ctx_other).unwrap();
641 assert_eq!(
642 result_other.len(),
643 1,
644 "Quarto should still flag non-R code spans with improper spaces"
645 );
646 }
647
648 #[test]
654 fn test_hugo_template_syntax_comprehensive() {
655 let rule = MD038NoSpaceInCode::new();
656
657 let valid_hugo_cases = vec![
661 (
663 "{{raw `\n\tgo list -f '{{.DefaultGODEBUG}}' my/main/package\n`}}",
664 "Multi-line raw shortcode",
665 ),
666 (
667 "Some text {{raw ` code `}} more text",
668 "Inline raw shortcode with spaces",
669 ),
670 ("{{raw `code`}}", "Raw shortcode without spaces"),
671 ("{{< ` code ` >}}", "Partial shortcode with spaces"),
673 ("{{< `code` >}}", "Partial shortcode without spaces"),
674 ("{{% ` code ` %}}", "Percent shortcode with spaces"),
676 ("{{% `code` %}}", "Percent shortcode without spaces"),
677 ("{{ ` code ` }}", "Generic shortcode with spaces"),
679 ("{{ `code` }}", "Generic shortcode without spaces"),
680 ("{{< highlight go `code` >}}", "Shortcode with highlight parameter"),
682 ("{{< code `go list` >}}", "Shortcode with code parameter"),
683 ("{{raw `\n\tcommand here\n\tmore code\n`}}", "Multi-line raw template"),
685 ("{{< highlight `\ncode here\n` >}}", "Multi-line highlight template"),
686 (
688 "{{raw `\n\t{{.Variable}}\n\t{{range .Items}}\n`}}",
689 "Nested Go template syntax",
690 ),
691 ("{{raw `code`}}", "Hugo template at line start"),
693 ("Text {{raw `code`}}", "Hugo template at end of line"),
695 ("{{raw `code1`}} and {{raw `code2`}}", "Multiple Hugo templates"),
697 ];
698
699 for (case, description) in valid_hugo_cases {
700 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
701 let result = rule.check(&ctx).unwrap();
702 assert!(
703 result.is_empty(),
704 "Hugo template syntax should not trigger MD038 warnings: {description} - {case}"
705 );
706 }
707
708 let should_be_flagged = vec![
713 ("This is ` code` with leading space.", "Leading space only"),
714 ("This is `code ` with trailing space.", "Trailing space only"),
715 ("Text ` code ` here", "Extra leading space (asymmetric)"),
716 ("Text ` code ` here", "Extra trailing space (asymmetric)"),
717 ("Text ` code` here", "Double leading, no trailing"),
718 ("Text `code ` here", "No leading, double trailing"),
719 ];
720
721 for (case, description) in should_be_flagged {
722 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
723 let result = rule.check(&ctx).unwrap();
724 assert!(
725 !result.is_empty(),
726 "Should flag asymmetric space code spans: {description} - {case}"
727 );
728 }
729
730 let symmetric_single_space = vec![
736 ("Text ` code ` here", "Symmetric single space - CommonMark strips"),
737 ("{raw ` code `}", "Looks like Hugo but missing opening {{"),
738 ("raw ` code `}}", "Missing opening {{ - but symmetric spaces"),
739 ];
740
741 for (case, description) in symmetric_single_space {
742 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
743 let result = rule.check(&ctx).unwrap();
744 assert!(
745 result.is_empty(),
746 "CommonMark symmetric spaces should NOT be flagged: {description} - {case}"
747 );
748 }
749
750 let unicode_cases = vec![
753 ("{{raw `\n\t你好世界\n`}}", "Unicode in Hugo template"),
754 ("{{raw `\n\t🎉 emoji\n`}}", "Emoji in Hugo template"),
755 ("{{raw `\n\tcode with \"quotes\"\n`}}", "Quotes in Hugo template"),
756 (
757 "{{raw `\n\tcode with 'single quotes'\n`}}",
758 "Single quotes in Hugo template",
759 ),
760 ];
761
762 for (case, description) in unicode_cases {
763 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
764 let result = rule.check(&ctx).unwrap();
765 assert!(
766 result.is_empty(),
767 "Hugo templates with special characters should not trigger warnings: {description} - {case}"
768 );
769 }
770
771 assert!(
775 rule.check(&crate::lint_context::LintContext::new(
776 "{{ ` ` }}",
777 crate::config::MarkdownFlavor::Standard,
778 None
779 ))
780 .unwrap()
781 .is_empty(),
782 "Minimum Hugo pattern should be valid"
783 );
784
785 assert!(
787 rule.check(&crate::lint_context::LintContext::new(
788 "{{raw `\n\t\n`}}",
789 crate::config::MarkdownFlavor::Standard,
790 None
791 ))
792 .unwrap()
793 .is_empty(),
794 "Hugo template with only whitespace should be valid"
795 );
796 }
797
798 #[test]
800 fn test_hugo_template_with_other_markdown() {
801 let rule = MD038NoSpaceInCode::new();
802
803 let content = r#"1. First item
8052. Second item with {{raw `code`}} template
8063. Third item"#;
807 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
808 let result = rule.check(&ctx).unwrap();
809 assert!(result.is_empty(), "Hugo template in list should not trigger warnings");
810
811 let content = r#"> Quote with {{raw `code`}} template"#;
813 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
814 let result = rule.check(&ctx).unwrap();
815 assert!(
816 result.is_empty(),
817 "Hugo template in blockquote should not trigger warnings"
818 );
819
820 let content = r#"{{raw `code`}} and ` bad code` here"#;
822 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
823 let result = rule.check(&ctx).unwrap();
824 assert_eq!(result.len(), 1, "Should flag regular code span but not Hugo template");
825 }
826
827 #[test]
829 fn test_hugo_template_performance() {
830 let rule = MD038NoSpaceInCode::new();
831
832 let mut content = String::new();
834 for i in 0..100 {
835 content.push_str(&format!("{{{{raw `code{i}\n`}}}}\n"));
836 }
837
838 let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
839 let start = std::time::Instant::now();
840 let result = rule.check(&ctx).unwrap();
841 let duration = start.elapsed();
842
843 assert!(result.is_empty(), "Many Hugo templates should not trigger warnings");
844 assert!(
845 duration.as_millis() < 1000,
846 "Performance test: Should process 100 Hugo templates in <1s, took {duration:?}"
847 );
848 }
849
850 #[test]
851 fn test_mkdocs_inline_hilite_not_flagged() {
852 let rule = MD038NoSpaceInCode::new();
855
856 let valid_cases = vec![
857 "`#!python print('hello')`",
858 "`#!js alert('hi')`",
859 "`#!c++ cout << x;`",
860 "Use `#!python import os` to import modules",
861 "`#!bash echo $HOME`",
862 ];
863
864 for case in valid_cases {
865 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::MkDocs, None);
866 let result = rule.check(&ctx).unwrap();
867 assert!(
868 result.is_empty(),
869 "InlineHilite syntax should not be flagged in MkDocs: {case}"
870 );
871 }
872
873 let content = "`#!python print('hello')`";
875 let ctx_standard =
876 crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
877 let result_standard = rule.check(&ctx_standard).unwrap();
878 assert!(
881 result_standard.is_empty(),
882 "InlineHilite with no extra spaces should not be flagged even in Standard flavor"
883 );
884 }
885
886 #[test]
887 fn test_multibyte_utf8_no_panic() {
888 let rule = MD038NoSpaceInCode::new();
892
893 let greek = "- Χρήσιμα εργαλεία της γραμμής εντολών είναι τα `ping`,` ipconfig`, `traceroute` και `netstat`.";
895 let ctx = crate::lint_context::LintContext::new(greek, crate::config::MarkdownFlavor::Standard, None);
896 let result = rule.check(&ctx);
897 assert!(result.is_ok(), "Greek text should not panic");
898
899 let chinese = "- 當你需要對文字檔案做集合交、並、差運算時,`sort`/`uniq` 很有幫助。";
901 let ctx = crate::lint_context::LintContext::new(chinese, crate::config::MarkdownFlavor::Standard, None);
902 let result = rule.check(&ctx);
903 assert!(result.is_ok(), "Chinese text should not panic");
904
905 let cyrillic = "- Основи роботи з файлами: `ls` і `ls -l`, `less`, `head`,` tail` і `tail -f`.";
907 let ctx = crate::lint_context::LintContext::new(cyrillic, crate::config::MarkdownFlavor::Standard, None);
908 let result = rule.check(&ctx);
909 assert!(result.is_ok(), "Cyrillic text should not panic");
910
911 let mixed = "使用 `git` 命令和 `npm` 工具来管理项目,可以用 `docker` 容器化。";
913 let ctx = crate::lint_context::LintContext::new(mixed, crate::config::MarkdownFlavor::Standard, None);
914 let result = rule.check(&ctx);
915 assert!(
916 result.is_ok(),
917 "Mixed Chinese text with multiple code spans should not panic"
918 );
919 }
920
921 #[test]
925 fn test_obsidian_dataview_inline_dql_not_flagged() {
926 let rule = MD038NoSpaceInCode::new();
927
928 let valid_dql_cases = vec![
930 "`= this.file.name`",
931 "`= date(today)`",
932 "`= [[Page]].field`",
933 "`= choice(condition, \"yes\", \"no\")`",
934 "`= this.file.mtime`",
935 "`= this.file.ctime`",
936 "`= this.file.path`",
937 "`= this.file.folder`",
938 "`= this.file.size`",
939 "`= this.file.ext`",
940 "`= this.file.link`",
941 "`= this.file.outlinks`",
942 "`= this.file.inlinks`",
943 "`= this.file.tags`",
944 ];
945
946 for case in valid_dql_cases {
947 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
948 let result = rule.check(&ctx).unwrap();
949 assert!(
950 result.is_empty(),
951 "Dataview DQL expression should not be flagged in Obsidian: {case}"
952 );
953 }
954 }
955
956 #[test]
958 fn test_obsidian_dataview_inline_dvjs_not_flagged() {
959 let rule = MD038NoSpaceInCode::new();
960
961 let valid_dvjs_cases = vec![
963 "`$= dv.current().file.mtime`",
964 "`$= dv.pages().length`",
965 "`$= dv.current()`",
966 "`$= dv.pages('#tag').length`",
967 "`$= dv.pages('\"folder\"').length`",
968 "`$= dv.current().file.name`",
969 "`$= dv.current().file.path`",
970 "`$= dv.current().file.folder`",
971 "`$= dv.current().file.link`",
972 ];
973
974 for case in valid_dvjs_cases {
975 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
976 let result = rule.check(&ctx).unwrap();
977 assert!(
978 result.is_empty(),
979 "Dataview JS expression should not be flagged in Obsidian: {case}"
980 );
981 }
982 }
983
984 #[test]
986 fn test_obsidian_dataview_complex_expressions() {
987 let rule = MD038NoSpaceInCode::new();
988
989 let complex_cases = vec![
990 "`= sum(filter(pages, (p) => p.done))`",
992 "`= length(filter(file.tags, (t) => startswith(t, \"project\")))`",
993 "`= choice(x > 5, \"big\", \"small\")`",
995 "`= choice(this.status = \"done\", \"✅\", \"⏳\")`",
996 "`= date(today) - dur(7 days)`",
998 "`= dateformat(this.file.mtime, \"yyyy-MM-dd\")`",
999 "`= sum(rows.amount)`",
1001 "`= round(average(rows.score), 2)`",
1002 "`= min(rows.priority)`",
1003 "`= max(rows.priority)`",
1004 "`= join(this.file.tags, \", \")`",
1006 "`= replace(this.title, \"-\", \" \")`",
1007 "`= lower(this.file.name)`",
1008 "`= upper(this.file.name)`",
1009 "`= length(this.file.outlinks)`",
1011 "`= contains(this.file.tags, \"important\")`",
1012 "`= [[Page Name]].field`",
1014 "`= [[Folder/Subfolder/Page]].nested.field`",
1015 "`= default(this.status, \"unknown\")`",
1017 "`= coalesce(this.priority, this.importance, 0)`",
1018 ];
1019
1020 for case in complex_cases {
1021 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1022 let result = rule.check(&ctx).unwrap();
1023 assert!(
1024 result.is_empty(),
1025 "Complex Dataview expression should not be flagged in Obsidian: {case}"
1026 );
1027 }
1028 }
1029
1030 #[test]
1032 fn test_obsidian_dataviewjs_method_chains() {
1033 let rule = MD038NoSpaceInCode::new();
1034
1035 let method_chain_cases = vec![
1036 "`$= dv.pages().where(p => p.status).length`",
1037 "`$= dv.pages('#project').where(p => !p.done).length`",
1038 "`$= dv.pages().filter(p => p.file.day).sort(p => p.file.mtime, 'desc').limit(5)`",
1039 "`$= dv.pages('\"folder\"').map(p => p.file.link).join(', ')`",
1040 "`$= dv.current().file.tasks.where(t => !t.completed).length`",
1041 "`$= dv.pages().flatMap(p => p.file.tags).distinct().sort()`",
1042 "`$= dv.page('Index').children.map(p => p.title)`",
1043 "`$= dv.pages().groupBy(p => p.status).map(g => [g.key, g.rows.length])`",
1044 ];
1045
1046 for case in method_chain_cases {
1047 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1048 let result = rule.check(&ctx).unwrap();
1049 assert!(
1050 result.is_empty(),
1051 "DataviewJS method chain should not be flagged in Obsidian: {case}"
1052 );
1053 }
1054 }
1055
1056 #[test]
1065 fn test_standard_flavor_vs_obsidian_dataview() {
1066 let rule = MD038NoSpaceInCode::new();
1067
1068 let no_issue_cases = vec!["`= this.file.name`", "`$= dv.current()`"];
1071
1072 for case in no_issue_cases {
1073 let ctx_std = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1075 let result_std = rule.check(&ctx_std).unwrap();
1076 assert!(
1077 result_std.is_empty(),
1078 "Dataview expression without leading space shouldn't be flagged in Standard: {case}"
1079 );
1080
1081 let ctx_obs = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1083 let result_obs = rule.check(&ctx_obs).unwrap();
1084 assert!(
1085 result_obs.is_empty(),
1086 "Dataview expression shouldn't be flagged in Obsidian: {case}"
1087 );
1088 }
1089
1090 let space_issues = vec![
1093 "` code`", "`code `", ];
1096
1097 for case in space_issues {
1098 let ctx_std = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Standard, None);
1100 let result_std = rule.check(&ctx_std).unwrap();
1101 assert!(
1102 !result_std.is_empty(),
1103 "Code with spacing issue should be flagged in Standard: {case}"
1104 );
1105
1106 let ctx_obs = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1108 let result_obs = rule.check(&ctx_obs).unwrap();
1109 assert!(
1110 !result_obs.is_empty(),
1111 "Code with spacing issue should be flagged in Obsidian (not Dataview): {case}"
1112 );
1113 }
1114 }
1115
1116 #[test]
1118 fn test_obsidian_still_flags_regular_code_spans_with_space() {
1119 let rule = MD038NoSpaceInCode::new();
1120
1121 let invalid_cases = [
1124 "` regular code`", "`code `", "` code `", "` code`", ];
1129
1130 let expected_flags = [
1132 true, true, false, true, ];
1137
1138 for (case, should_flag) in invalid_cases.iter().zip(expected_flags.iter()) {
1139 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1140 let result = rule.check(&ctx).unwrap();
1141 if *should_flag {
1142 assert!(
1143 !result.is_empty(),
1144 "Non-Dataview code span with spacing issue should be flagged in Obsidian: {case}"
1145 );
1146 } else {
1147 assert!(
1148 result.is_empty(),
1149 "CommonMark-valid symmetric spacing should not be flagged: {case}"
1150 );
1151 }
1152 }
1153 }
1154
1155 #[test]
1157 fn test_obsidian_dataview_edge_cases() {
1158 let rule = MD038NoSpaceInCode::new();
1159
1160 let valid_cases = vec![
1162 ("`= 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), ];
1178
1179 for (case, should_be_valid) in valid_cases {
1180 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1181 let result = rule.check(&ctx).unwrap();
1182 if should_be_valid {
1183 assert!(
1184 result.is_empty(),
1185 "Valid Dataview expression should not be flagged: {case}"
1186 );
1187 } else {
1188 let _ = result;
1191 }
1192 }
1193 }
1194
1195 #[test]
1197 fn test_obsidian_dataview_in_context() {
1198 let rule = MD038NoSpaceInCode::new();
1199
1200 let content = r#"# My Note
1202
1203The file name is `= this.file.name` and it was created on `= this.file.ctime`.
1204
1205Regular code: `println!("hello")` and `let x = 5;`
1206
1207DataviewJS count: `$= dv.pages('#project').length` projects found.
1208
1209More regular code with issue: ` bad code` should be flagged.
1210"#;
1211
1212 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1213 let result = rule.check(&ctx).unwrap();
1214
1215 assert_eq!(
1217 result.len(),
1218 1,
1219 "Should only flag the regular code span with leading space, not Dataview expressions"
1220 );
1221 assert_eq!(result[0].line, 9, "Warning should be on line 9");
1222 }
1223
1224 #[test]
1226 fn test_obsidian_dataview_in_code_blocks() {
1227 let rule = MD038NoSpaceInCode::new();
1228
1229 let content = r#"# Example
1232
1233```
1234`= this.file.name`
1235`$= dv.current()`
1236```
1237
1238Regular paragraph with `= this.file.name` Dataview.
1239"#;
1240
1241 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1242 let result = rule.check(&ctx).unwrap();
1243
1244 assert!(
1246 result.is_empty(),
1247 "Dataview in code blocks should be ignored, inline Dataview should be valid"
1248 );
1249 }
1250
1251 #[test]
1253 fn test_obsidian_dataview_unicode() {
1254 let rule = MD038NoSpaceInCode::new();
1255
1256 let unicode_cases = vec![
1257 "`= this.日本語`", "`= this.中文字段`", "`= \"Привет мир\"`", "`$= dv.pages('#日本語タグ')`", "`= choice(true, \"✅\", \"❌\")`", "`= this.file.name + \" 📝\"`", ];
1264
1265 for case in unicode_cases {
1266 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1267 let result = rule.check(&ctx).unwrap();
1268 assert!(
1269 result.is_empty(),
1270 "Unicode Dataview expression should not be flagged: {case}"
1271 );
1272 }
1273 }
1274
1275 #[test]
1277 fn test_obsidian_regular_equals_still_works() {
1278 let rule = MD038NoSpaceInCode::new();
1279
1280 let valid_regular_cases = vec![
1282 "`x = 5`", "`a == b`", "`x >= 10`", "`let x = 10`", "`const y = 5`", ];
1288
1289 for case in valid_regular_cases {
1290 let ctx = crate::lint_context::LintContext::new(case, crate::config::MarkdownFlavor::Obsidian, None);
1291 let result = rule.check(&ctx).unwrap();
1292 assert!(
1293 result.is_empty(),
1294 "Regular code with equals should not be flagged: {case}"
1295 );
1296 }
1297 }
1298
1299 #[test]
1301 fn test_obsidian_dataview_fix_preserves_expressions() {
1302 let rule = MD038NoSpaceInCode::new();
1303
1304 let content = "Dataview: `= this.file.name` and bad: ` fixme`";
1306 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1307 let fixed = rule.fix(&ctx).unwrap();
1308
1309 assert!(
1311 fixed.contains("`= this.file.name`"),
1312 "Dataview expression should be preserved after fix"
1313 );
1314 assert!(
1315 fixed.contains("`fixme`"),
1316 "Regular code span should be fixed (space removed)"
1317 );
1318 assert!(!fixed.contains("` fixme`"), "Bad code span should have been fixed");
1319 }
1320
1321 #[test]
1323 fn test_obsidian_multiple_dataview_same_line() {
1324 let rule = MD038NoSpaceInCode::new();
1325
1326 let content = "Created: `= this.file.ctime` | Modified: `= this.file.mtime` | Count: `$= dv.pages().length`";
1327 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1328 let result = rule.check(&ctx).unwrap();
1329
1330 assert!(
1331 result.is_empty(),
1332 "Multiple Dataview expressions on same line should all be valid"
1333 );
1334 }
1335
1336 #[test]
1338 fn test_obsidian_dataview_performance() {
1339 let rule = MD038NoSpaceInCode::new();
1340
1341 let mut content = String::new();
1343 for i in 0..100 {
1344 content.push_str(&format!("Field {i}: `= this.field{i}` | JS: `$= dv.current().f{i}`\n"));
1345 }
1346
1347 let ctx = crate::lint_context::LintContext::new(&content, crate::config::MarkdownFlavor::Obsidian, None);
1348 let start = std::time::Instant::now();
1349 let result = rule.check(&ctx).unwrap();
1350 let duration = start.elapsed();
1351
1352 assert!(result.is_empty(), "All Dataview expressions should be valid");
1353 assert!(
1354 duration.as_millis() < 1000,
1355 "Performance test: Should process 200 Dataview expressions in <1s, took {duration:?}"
1356 );
1357 }
1358
1359 #[test]
1361 fn test_is_dataview_expression_helper() {
1362 assert!(MD038NoSpaceInCode::is_dataview_expression("= this.file.name"));
1364 assert!(MD038NoSpaceInCode::is_dataview_expression("= "));
1365 assert!(MD038NoSpaceInCode::is_dataview_expression("$= dv.current()"));
1366 assert!(MD038NoSpaceInCode::is_dataview_expression("$= "));
1367 assert!(MD038NoSpaceInCode::is_dataview_expression("= x"));
1368 assert!(MD038NoSpaceInCode::is_dataview_expression("$= x"));
1369
1370 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")); }
1381
1382 #[test]
1384 fn test_obsidian_dataview_with_tags() {
1385 let rule = MD038NoSpaceInCode::new();
1386
1387 let content = r#"# Project Status
1389
1390Tags: #project #active
1391
1392Status: `= this.status`
1393Count: `$= dv.pages('#project').length`
1394
1395Regular code: `function test() {}`
1396"#;
1397
1398 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
1399 let result = rule.check(&ctx).unwrap();
1400
1401 assert!(
1403 result.is_empty(),
1404 "Dataview expressions and regular code should work together"
1405 );
1406 }
1407
1408 #[test]
1409 fn test_unicode_between_code_spans_no_panic() {
1410 let rule = MD038NoSpaceInCode::new();
1413
1414 let content = "Use `one` \u{00DC}nited `two` for backtick examples.";
1416 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1417 let result = rule.check(&ctx);
1418 assert!(result.is_ok(), "Should not panic with Unicode between code spans");
1420
1421 let content_cjk = "Use `one` \u{4E16}\u{754C} `two` for examples.";
1423 let ctx_cjk = crate::lint_context::LintContext::new(content_cjk, crate::config::MarkdownFlavor::Standard, None);
1424 let result_cjk = rule.check(&ctx_cjk);
1425 assert!(result_cjk.is_ok(), "Should not panic with CJK between code spans");
1426 }
1427
1428 #[test]
1429 fn test_pandoc_inline_r_code_not_exempt() {
1430 let rule = MD038NoSpaceInCode::new();
1436 let content = "See `r foo ` for details.\n";
1439
1440 let ctx_quarto = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Quarto, None);
1442 let result_quarto = rule.check(&ctx_quarto).unwrap();
1443 assert!(
1444 result_quarto.is_empty(),
1445 "MD038 should suppress trailing-space warning for `r expression` under Quarto: {result_quarto:?}"
1446 );
1447
1448 let ctx_pandoc = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1450 let result_pandoc = rule.check(&ctx_pandoc).unwrap();
1451 assert!(
1452 !result_pandoc.is_empty(),
1453 "MD038 should flag trailing space in `r expression` under Pandoc flavor (not Quarto/RMarkdown syntax): {result_pandoc:?}"
1454 );
1455 }
1456
1457 #[test]
1462 fn test_pandoc_inline_code_attr_does_not_suppress_leading_space() {
1463 let rule = MD038NoSpaceInCode::new();
1464 let content = "Use ` print()`{.python} for output.\n";
1465 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1466 let result = rule.check(&ctx).unwrap();
1467 assert!(
1468 !result.is_empty(),
1469 "MD038 must flag leading space inside `code`{{.lang}} under Pandoc — the attribute is outside the span: {result:?}"
1470 );
1471 }
1472
1473 #[test]
1477 fn test_pandoc_inline_code_attr_does_not_suppress_trailing_space() {
1478 let rule = MD038NoSpaceInCode::new();
1479 let content = "Use `print() `{.python} for output.\n";
1480 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1481 let result = rule.check(&ctx).unwrap();
1482 assert!(
1483 !result.is_empty(),
1484 "MD038 must flag trailing space inside `code`{{.lang}} under Pandoc — the attribute is outside the span: {result:?}"
1485 );
1486 }
1487
1488 #[test]
1490 fn test_standard_still_flags_leading_space_with_attr_syntax() {
1491 let rule = MD038NoSpaceInCode::new();
1492 let content = "Use ` print()`{.python} for output.\n";
1493 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1494 let result = rule.check(&ctx).unwrap();
1495 assert!(
1496 !result.is_empty(),
1497 "MD038 should flag leading space in code span under Standard flavor: {result:?}"
1498 );
1499 }
1500
1501 #[test]
1504 fn test_pandoc_inline_code_attr_clean_span_not_flagged() {
1505 let rule = MD038NoSpaceInCode::new();
1506 let content = "Use `print()`{.python} for output.\n";
1507 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Pandoc, None);
1508 let result = rule.check(&ctx).unwrap();
1509 assert!(
1510 result.is_empty(),
1511 "MD038 must not flag a clean attributed code span under Pandoc: {result:?}"
1512 );
1513 }
1514}