Skip to main content

rumdl_lib/utils/
emphasis_utils.rs

1use regex::Regex;
2use std::sync::LazyLock;
3
4// Better detection of inline code with support for multiple backticks
5static INLINE_CODE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(`+)([^`]|[^`].*?[^`])(`+)").unwrap());
6
7// Inline math pattern - matches both $...$ and $$...$$ syntax
8// The pattern allows zero or more characters between delimiters to handle empty math spans
9static INLINE_MATH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$\$[^$]*\$\$|\$[^$\n]*\$").unwrap());
10
11// Documentation style patterns
12static DOC_METADATA_PATTERN: LazyLock<Regex> =
13    LazyLock::new(|| Regex::new(r"^\s*\*?\s*\*\*(?:[^*\s][^*]*[^*\s]|[^*\s])\*\*\s*:").unwrap());
14
15// Bold text pattern (for preserving bold text in documentation) - only match valid bold without spaces
16static BOLD_TEXT_PATTERN: LazyLock<Regex> =
17    LazyLock::new(|| Regex::new(r"\*\*[^*\s][^*]*[^*\s]\*\*|\*\*[^*\s]\*\*").unwrap());
18
19// Pre-compiled patterns for quick checks
20static QUICK_DOC_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\*\s+\*").unwrap());
21static QUICK_BOLD_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*[^*\s]").unwrap());
22
23// Template/shortcode syntax pattern - {* ... *} used by documentation systems like FastAPI/MkDocs
24// These are not emphasis markers but template directives for code inclusion/highlighting
25static TEMPLATE_SHORTCODE_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\*.*\*\}").unwrap());
26
27/// Represents an emphasis marker found in text
28#[derive(Debug, Clone, PartialEq)]
29pub struct EmphasisMarker {
30    pub marker_type: u8,  // b'*' or b'_' for faster comparison
31    pub count: u8,        // 1 for single, 2 for double
32    pub start_pos: usize, // Position in the line
33}
34
35impl EmphasisMarker {
36    #[inline]
37    pub fn end_pos(&self) -> usize {
38        self.start_pos + self.count as usize
39    }
40
41    #[inline]
42    pub fn as_char(&self) -> char {
43        self.marker_type as char
44    }
45}
46
47/// Represents a complete emphasis span
48#[derive(Debug, Clone)]
49pub struct EmphasisSpan {
50    pub opening: EmphasisMarker,
51    pub closing: EmphasisMarker,
52    pub content: String,
53    pub has_leading_space: bool,
54    pub has_trailing_space: bool,
55}
56
57/// Delimiter and spacing facts used by built-in rules, without copied text.
58pub(crate) struct EmphasisEdges {
59    pub(crate) opening: EmphasisMarker,
60    pub(crate) closing: EmphasisMarker,
61    pub(crate) has_leading_space: bool,
62    pub(crate) has_trailing_space: bool,
63}
64
65fn owned_span(
66    opening: &EmphasisMarker,
67    closing: &EmphasisMarker,
68    content: &str,
69    has_leading_space: bool,
70    has_trailing_space: bool,
71) -> EmphasisSpan {
72    EmphasisSpan {
73        opening: opening.clone(),
74        closing: closing.clone(),
75        content: content.to_owned(),
76        has_leading_space,
77        has_trailing_space,
78    }
79}
80
81fn span_edges(
82    opening: &EmphasisMarker,
83    closing: &EmphasisMarker,
84    _content: &str,
85    has_leading_space: bool,
86    has_trailing_space: bool,
87) -> EmphasisEdges {
88    EmphasisEdges {
89        opening: opening.clone(),
90        closing: closing.clone(),
91        has_leading_space,
92        has_trailing_space,
93    }
94}
95
96/// Enhanced inline code replacement with optimized performance
97/// Replaces inline code with 'X' characters to prevent false positives in emphasis detection
98#[inline]
99pub fn replace_inline_code(line: &str) -> String {
100    replace_inline_code_cow(line).into_owned()
101}
102
103/// Borrow literal source until a code span actually needs masking. Replacement
104/// is byte-for-byte identical to `replace_inline_code`, including its existing
105/// delimiter grammar and equal-length ASCII placeholders.
106pub(crate) fn replace_inline_code_cow(line: &str) -> std::borrow::Cow<'_, str> {
107    mask_matches(line, '`', &INLINE_CODE, b'X')
108}
109
110/// Replace inline math ($...$ and $$...$$) with placeholder characters.
111pub fn replace_inline_math(line: &str) -> String {
112    replace_inline_math_cow(line).into_owned()
113}
114
115pub(crate) fn replace_inline_math_cow(line: &str) -> std::borrow::Cow<'_, str> {
116    mask_matches(line, '$', &INLINE_MATH, b'M')
117}
118
119fn mask_matches<'a>(line: &'a str, signal: char, regex: &Regex, placeholder: u8) -> std::borrow::Cow<'a, str> {
120    if !line.contains(signal) {
121        return std::borrow::Cow::Borrowed(line);
122    }
123    let mut bytes = None;
124    for matched in regex.find_iter(line) {
125        bytes.get_or_insert_with(|| line.as_bytes().to_vec())[matched.range()].fill(placeholder);
126    }
127    match bytes {
128        Some(bytes) => std::borrow::Cow::Owned(String::from_utf8(bytes).expect("ASCII-only span masking")),
129        None => std::borrow::Cow::Borrowed(line),
130    }
131}
132
133/// Optimized emphasis marker parsing using byte iteration
134#[inline]
135pub fn find_emphasis_markers(line: &str) -> Vec<EmphasisMarker> {
136    let mut markers = Vec::new();
137    find_emphasis_markers_into(line, &mut markers);
138    markers
139}
140
141/// Append line-relative delimiters to a reusable document arena.
142pub(crate) fn find_emphasis_markers_into(line: &str, markers: &mut Vec<EmphasisMarker>) {
143    // Early return for lines without emphasis markers
144    if !line.contains('*') && !line.contains('_') {
145        return;
146    }
147
148    let bytes = line.as_bytes();
149    let mut i = 0;
150
151    while i < bytes.len() {
152        let byte = bytes[i];
153        if byte == b'*' || byte == b'_' {
154            let start_pos = i;
155            let mut count = 1u8;
156
157            // Count consecutive markers (limit to avoid overflow)
158            while i + (count as usize) < bytes.len() && bytes[i + (count as usize)] == byte && count < 3 {
159                count += 1;
160            }
161
162            // Only consider single (*) and double (**) markers
163            if count == 1 || count == 2 {
164                markers.push(EmphasisMarker {
165                    marker_type: byte,
166                    count,
167                    start_pos,
168                });
169            }
170
171            i += count as usize;
172        } else {
173            i += 1;
174        }
175    }
176}
177
178/// Find all emphasis spans in a line, excluding only single emphasis (not strong)
179pub fn find_single_emphasis_spans(line: &str, markers: &[EmphasisMarker]) -> Vec<EmphasisSpan> {
180    find_single_emphasis_spans_with(line, markers, owned_span)
181}
182
183pub(crate) fn find_single_emphasis_edges(line: &str, markers: &[EmphasisMarker]) -> Vec<EmphasisEdges> {
184    find_single_emphasis_spans_with(line, markers, span_edges)
185}
186
187fn find_single_emphasis_spans_with<T>(
188    line: &str,
189    markers: &[EmphasisMarker],
190    mut emit: impl FnMut(&EmphasisMarker, &EmphasisMarker, &str, bool, bool) -> T,
191) -> Vec<T> {
192    // Early return for insufficient markers
193    if markers.len() < 2 {
194        return Vec::new();
195    }
196
197    // CommonMark left/right-flanking (whitespace clause): an emphasis opener
198    // must not be immediately followed by whitespace, and a closer must not be
199    // immediately preceded by it. A marker that can do neither is a literal
200    // `*`/`_` (e.g. a list-marker `*`, or a `*` flanked by spaces) and is
201    // transparent to delimiter matching. `find_emphasis_spans` (MD037)
202    // deliberately keeps such runs so MD037 can flag the spaces inside them;
203    // this single-emphasis finder, used only by MD049, must not.
204    let bytes = line.as_bytes();
205    let is_ws = |b: u8| b == b' ' || b == b'\t';
206    let can_open = |m: &EmphasisMarker| {
207        let after = m.end_pos();
208        after < bytes.len() && !is_ws(bytes[after])
209    };
210    let can_close = |m: &EmphasisMarker| m.start_pos > 0 && !is_ws(bytes[m.start_pos - 1]);
211
212    let mut spans = Vec::new();
213    let mut used_markers = vec![false; markers.len()];
214
215    for i in 0..markers.len() {
216        if used_markers[i] || markers[i].count != 1 || !can_open(&markers[i]) {
217            continue;
218        }
219        let opening = &markers[i];
220        // A viable single delimiter blocks every later candidate of this type,
221        // even when it is already used or can only open. Literal markers and
222        // strong delimiters remain transparent to this single-emphasis finder.
223        let Some(j) = (i + 1..markers.len()).find(|&j| {
224            let marker = &markers[j];
225            marker.marker_type == opening.marker_type && marker.count == 1 && (can_open(marker) || can_close(marker))
226        }) else {
227            continue;
228        };
229        let closing = &markers[j];
230        if used_markers[j] || !can_close(closing) {
231            continue;
232        }
233        let content_start = opening.end_pos();
234        let content_end = closing.start_pos;
235        if content_end > content_start {
236            let content = &line[content_start..content_end];
237            if is_valid_emphasis_content_fast(content) && is_valid_emphasis_span_fast(line, opening, closing) {
238                let has_leading_space = content.starts_with(' ') || content.starts_with('\t');
239                let has_trailing_space = content.ends_with(' ') || content.ends_with('\t');
240                spans.push(emit(opening, closing, content, has_leading_space, has_trailing_space));
241                used_markers[i] = true;
242                used_markers[j] = true;
243            }
244        }
245    }
246
247    spans
248}
249
250/// Optimized emphasis span finding with reduced complexity (includes both single and strong)
251pub fn find_emphasis_spans(line: &str, markers: &[EmphasisMarker]) -> Vec<EmphasisSpan> {
252    find_emphasis_spans_with(line, markers, owned_span)
253}
254
255pub(crate) fn find_emphasis_edges(line: &str, markers: &[EmphasisMarker]) -> Vec<EmphasisEdges> {
256    find_emphasis_spans_with(line, markers, span_edges)
257}
258
259fn find_emphasis_spans_with<T>(
260    line: &str,
261    markers: &[EmphasisMarker],
262    mut emit: impl FnMut(&EmphasisMarker, &EmphasisMarker, &str, bool, bool) -> T,
263) -> Vec<T> {
264    // Early return for insufficient markers
265    if markers.len() < 2 {
266        return Vec::new();
267    }
268
269    let mut spans = Vec::new();
270    let mut used_markers = vec![false; markers.len()];
271
272    for i in 0..markers.len() {
273        if used_markers[i] {
274            continue;
275        }
276        let opening = &markers[i];
277        // Every marker of this type blocks later candidates, regardless of
278        // strength or whether it has already been paired. Only the first can
279        // close this opener without crossing another marker of the same type.
280        let Some(j) = (i + 1..markers.len()).find(|&j| markers[j].marker_type == opening.marker_type) else {
281            continue;
282        };
283        let closing = &markers[j];
284        if used_markers[j] || closing.count != opening.count {
285            continue;
286        }
287        let content_start = opening.end_pos();
288        let content_end = closing.start_pos;
289        if content_end > content_start {
290            let content = &line[content_start..content_end];
291            if is_valid_emphasis_content_fast(content) && is_valid_emphasis_span_fast(line, opening, closing) {
292                let has_leading_space = content.starts_with(' ') || content.starts_with('\t');
293                let has_trailing_space = content.ends_with(' ') || content.ends_with('\t');
294                spans.push(emit(opening, closing, content, has_leading_space, has_trailing_space));
295                used_markers[i] = true;
296                used_markers[j] = true;
297            }
298        }
299    }
300
301    spans
302}
303
304/// Byte ranges `[start, end)` of *valid* CommonMark emphasis on a single line,
305/// covering both single (`*`/`_`) and double (`**`/`__`) emphasis.
306///
307/// Unlike [`find_emphasis_spans`] (which greedily pairs markers and keeps
308/// whitespace-padded runs so MD037 can flag them), this applies the CommonMark
309/// left/right-flanking whitespace rule: an opener must not be immediately
310/// followed by whitespace, a closer must not be immediately preceded by it, and
311/// a marker that can do neither is a transparent literal that does not block an
312/// outer pairing. MD037 uses these ranges to avoid flagging text that is in
313/// fact valid emphasis containing an interior literal marker, e.g.
314/// `*foo * bar*` -> `<em>foo * bar</em>`, where the inner `* ` is literal.
315pub fn find_valid_emphasis_ranges(line: &str, markers: &[EmphasisMarker]) -> Vec<(usize, usize)> {
316    if markers.len() < 2 {
317        return Vec::new();
318    }
319
320    let bytes = line.as_bytes();
321    let is_ws = |b: u8| b == b' ' || b == b'\t';
322    let can_open = |m: &EmphasisMarker| {
323        let after = m.end_pos();
324        after < bytes.len() && !is_ws(bytes[after])
325    };
326    let can_close = |m: &EmphasisMarker| m.start_pos > 0 && !is_ws(bytes[m.start_pos - 1]);
327
328    let mut ranges = Vec::new();
329    let mut used = vec![false; markers.len()];
330
331    for i in 0..markers.len() {
332        if used[i] || !can_open(&markers[i]) {
333            continue;
334        }
335        let opening = &markers[i];
336        // Unlike the single-emphasis finder, any viable strength blocks later
337        // candidates. Whitespace-flanked literal markers remain transparent.
338        let Some(j) = (i + 1..markers.len()).find(|&j| {
339            let marker = &markers[j];
340            marker.marker_type == opening.marker_type && (can_open(marker) || can_close(marker))
341        }) else {
342            continue;
343        };
344        let closing = &markers[j];
345        if used[j] || closing.count != opening.count || !can_close(closing) {
346            continue;
347        }
348        let content_start = opening.end_pos();
349        let content_end = closing.start_pos;
350        if content_end > content_start {
351            let content = &line[content_start..content_end];
352            if is_valid_emphasis_content_fast(content) && is_valid_emphasis_span_fast(line, opening, closing) {
353                ranges.push((opening.start_pos, closing.end_pos()));
354                used[i] = true;
355                used[j] = true;
356            }
357        }
358    }
359
360    ranges
361}
362
363/// Fast validation of emphasis span context
364#[inline]
365fn is_valid_emphasis_span_fast(line: &str, opening: &EmphasisMarker, closing: &EmphasisMarker) -> bool {
366    let content_start = opening.end_pos();
367    let content_end = closing.start_pos;
368
369    // Content must exist and not be just whitespace
370    if content_end <= content_start {
371        return false;
372    }
373
374    let content = &line[content_start..content_end];
375    if content.trim().is_empty() {
376        return false;
377    }
378
379    // Quick boundary checks using byte indexing
380    let bytes = line.as_bytes();
381
382    // Opening should be at start or after valid character
383    let valid_opening = opening.start_pos == 0
384        || matches!(
385            bytes.get(opening.start_pos.saturating_sub(1)),
386            Some(&b' ')
387                | Some(&b'\t')
388                | Some(&b'(')
389                | Some(&b'[')
390                | Some(&b'{')
391                | Some(&b'"')
392                | Some(&b'\'')
393                | Some(&b'>')
394        );
395
396    // Closing should be at end or before valid character
397    let valid_closing = closing.end_pos() >= bytes.len()
398        || matches!(
399            bytes.get(closing.end_pos()),
400            Some(&b' ')
401                | Some(&b'\t')
402                | Some(&b')')
403                | Some(&b']')
404                | Some(&b'}')
405                | Some(&b'"')
406                | Some(&b'\'')
407                | Some(&b'.')
408                | Some(&b',')
409                | Some(&b'!')
410                | Some(&b'?')
411                | Some(&b';')
412                | Some(&b':')
413                | Some(&b'<')
414        );
415
416    valid_opening && valid_closing && !content.contains('\n')
417}
418
419/// Fast validation of emphasis content
420#[inline]
421fn is_valid_emphasis_content_fast(content: &str) -> bool {
422    !content.trim().is_empty()
423}
424
425/// Check if line has documentation patterns that should be preserved
426pub fn has_doc_patterns(line: &str) -> bool {
427    // Check for template/shortcode syntax like {* ... *} used by FastAPI/MkDocs
428    // These contain asterisks that are not emphasis markers
429    if line.contains("{*") && TEMPLATE_SHORTCODE_PATTERN.is_match(line) {
430        return true;
431    }
432
433    (QUICK_DOC_CHECK.is_match(line) || QUICK_BOLD_CHECK.is_match(line))
434        && (DOC_METADATA_PATTERN.is_match(line) || BOLD_TEXT_PATTERN.is_match(line))
435}
436
437#[cfg(test)]
438mod masking_contract_tests {
439    use super::*;
440    use proptest::prelude::*;
441
442    // Independent oracle: the original replacement algorithm, before the
443    // shared source-backed view and borrowed no-op fast path.
444    fn original_mask(source: &str, regex: &Regex, placeholder: &str) -> String {
445        let mut result = source.to_owned();
446        for captures in regex.captures_iter(source) {
447            if placeholder == "X" && (1..=3).any(|group| captures.get(group).is_none()) {
448                continue;
449            }
450            let matched = captures.get(0).unwrap();
451            result.replace_range(matched.range(), &placeholder.repeat(matched.len()));
452        }
453        result
454    }
455
456    fn assert_contract(source: &str) {
457        assert_eq!(
458            replace_inline_code_cow(source),
459            original_mask(source, &INLINE_CODE, "X")
460        );
461        assert_eq!(
462            replace_inline_math_cow(source),
463            original_mask(source, &INLINE_MATH, "M")
464        );
465        assert_eq!(replace_inline_code_cow(source).len(), source.len());
466        assert_eq!(replace_inline_math_cow(source).len(), source.len());
467    }
468
469    proptest! {
470        #[test]
471        fn source_masks_match_original_replacements(source in prop_oneof!["(?s).{0,128}", "[`$*_aé \\r\\n]{0,1024}"]) {
472            assert_contract(&source);
473        }
474    }
475
476    #[test]
477    fn literal_and_mismatched_delimiters_preserve_source() {
478        for source in [
479            "plain text",
480            "`unclosed",
481            "$$",
482            "é🦀 `é🦀` _text_",
483            "`` a ` b `` $a$ _x_",
484            "`a`` and ```b`` $x$$y$",
485            "`$` _x_ $y$",
486            "`é`\r\n$$ z $$",
487            "`a` _x_ `b`",
488            "$$ a $$ $$ b $$",
489        ] {
490            assert_contract(source);
491        }
492        assert!(matches!(
493            replace_inline_code_cow("literal"),
494            std::borrow::Cow::Borrowed(_)
495        ));
496        assert!(matches!(
497            replace_inline_code_cow("`unclosed"),
498            std::borrow::Cow::Borrowed(_)
499        ));
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506
507    #[test]
508    fn test_emphasis_marker_parsing() {
509        let markers = find_emphasis_markers("This has *single* and **double** emphasis");
510        assert_eq!(markers.len(), 4); // *, *, **, **
511
512        let markers = find_emphasis_markers("*start* and *end*");
513        assert_eq!(markers.len(), 4); // *, *, *, *
514    }
515
516    #[test]
517    fn test_single_emphasis_span_detection() {
518        let markers = find_emphasis_markers("This has *valid* emphasis and **strong** too");
519        let spans = find_single_emphasis_spans("This has *valid* emphasis and **strong** too", &markers);
520        assert_eq!(spans.len(), 1); // Only the single emphasis
521        assert_eq!(spans[0].content, "valid");
522        assert!(!spans[0].has_leading_space);
523        assert!(!spans[0].has_trailing_space);
524    }
525
526    #[test]
527    fn test_emphasis_with_spaces() {
528        let markers = find_emphasis_markers("This has * invalid * emphasis");
529        let spans = find_emphasis_spans("This has * invalid * emphasis", &markers);
530        assert_eq!(spans.len(), 1);
531        assert_eq!(spans[0].content, " invalid ");
532        assert!(spans[0].has_leading_space);
533        assert!(spans[0].has_trailing_space);
534    }
535
536    #[test]
537    fn test_single_emphasis_rejects_whitespace_flanked_runs() {
538        // `find_single_emphasis_spans` powers MD049, which must only see real
539        // emphasis. A whitespace-flanked `* ... *` run is not emphasis per
540        // CommonMark, so no span is produced.
541        let line = "foo * bar * baz";
542        let markers = find_emphasis_markers(line);
543        let spans = find_single_emphasis_spans(line, &markers);
544        assert!(
545            spans.is_empty(),
546            "whitespace-flanked run must not be a single-emphasis span: {spans:?}"
547        );
548
549        // The sibling `find_emphasis_spans` (used by MD037) intentionally keeps
550        // the run so MD037 can flag the spaces. Locking this in prevents a
551        // future "fix" landing in the shared helper and breaking MD037.
552        let md037_spans = find_emphasis_spans(line, &markers);
553        assert_eq!(
554            md037_spans.len(),
555            1,
556            "MD037's span finder must still detect the spaced run: {md037_spans:?}"
557        );
558        assert_eq!(md037_spans[0].content, " bar ");
559    }
560
561    #[test]
562    fn test_valid_emphasis_ranges() {
563        let ranges = |line: &str| {
564            let markers = find_emphasis_markers(line);
565            find_valid_emphasis_ranges(line, &markers)
566        };
567
568        // Plain single and double emphasis yield their full marker-to-marker range.
569        assert_eq!(ranges("a *foo* b"), vec![(2, 7)]);
570        assert_eq!(ranges("a **foo** b"), vec![(2, 9)]);
571
572        // Valid emphasis spanning an interior whitespace-flanked literal marker.
573        assert_eq!(ranges("*foo * bar*"), vec![(0, 11)]);
574        assert_eq!(ranges("**foo ** bar**"), vec![(0, 14)]);
575
576        // Whitespace-flanked runs are not valid emphasis - no range.
577        assert!(ranges("foo * bar * baz").is_empty());
578        assert!(ranges("** spaced **").is_empty());
579        // A leading list marker `*` cannot open emphasis.
580        assert!(ranges("* item only").is_empty());
581    }
582
583    #[test]
584    fn test_single_emphasis_spans_literal_marker_inside_emphasis() {
585        // CommonMark parses `*foo * bar*` as <em>foo * bar</em>: the inner `*`
586        // is whitespace-flanked (a transparent literal), so the outer pair is
587        // still emphasis. A naive "skip on inner marker" would miss this.
588        let line = "*foo * bar*";
589        let markers = find_emphasis_markers(line);
590        let spans = find_single_emphasis_spans(line, &markers);
591        assert_eq!(spans.len(), 1, "outer emphasis must be detected: {spans:?}");
592        assert_eq!(spans[0].content, "foo * bar");
593
594        // `*a *b*` is `*a <em>b</em>`: the inner `*b*` is emphasis, the leading
595        // `*` stays literal. Only the inner span is a single-emphasis span.
596        let line = "*a *b*";
597        let markers = find_emphasis_markers(line);
598        let spans = find_single_emphasis_spans(line, &markers);
599        assert_eq!(spans.len(), 1, "only inner emphasis: {spans:?}");
600        assert_eq!(spans[0].content, "b");
601    }
602
603    #[test]
604    fn test_mixed_markers() {
605        let markers = find_emphasis_markers("This has *asterisk* and _underscore_ emphasis");
606        let spans = find_single_emphasis_spans("This has *asterisk* and _underscore_ emphasis", &markers);
607        assert_eq!(spans.len(), 2);
608        assert_eq!(spans[0].opening.as_char(), '*');
609        assert_eq!(spans[1].opening.as_char(), '_');
610    }
611
612    #[test]
613    fn test_template_shortcode_detection() {
614        // FastAPI/MkDocs style template syntax should be detected as doc pattern
615        assert!(has_doc_patterns(
616            "{* ../../docs_src/cookie_param_models/tutorial001.py hl[9:12,16] *}"
617        ));
618        assert!(has_doc_patterns(
619            "{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}"
620        ));
621        // Simple shortcode
622        assert!(has_doc_patterns("{* file.py *}"));
623        // With path and options
624        assert!(has_doc_patterns("{* ../path/to/file.py ln[1-10] *}"));
625
626        // Regular emphasis should NOT match
627        assert!(!has_doc_patterns("This has *emphasis* text"));
628        assert!(!has_doc_patterns("This has * spaces * in emphasis"));
629        // Only opening brace without closing should not match
630        assert!(!has_doc_patterns("{* incomplete"));
631    }
632
633    #[test]
634    fn test_doc_pattern_rejects_spaced_bold_metadata() {
635        // Valid bold metadata — should be treated as doc pattern (skip MD037)
636        assert!(has_doc_patterns("**Key**: value"));
637        assert!(has_doc_patterns("**Name**: another value"));
638        assert!(has_doc_patterns("**X**: single char"));
639        assert!(has_doc_patterns("* **Key**: list item with bold key"));
640
641        // Broken bold with internal spaces — should NOT be treated as doc pattern
642        // so MD037 can flag the spacing issue
643        assert!(!has_doc_patterns("** Key**: value"));
644        assert!(!has_doc_patterns("**Key **: value"));
645        assert!(!has_doc_patterns("** Key **: value"));
646        assert!(!has_doc_patterns(
647            "** Explicit Import**: Convert markdownlint configs to rumdl format:"
648        ));
649    }
650}
651
652#[cfg(test)]
653mod pairing_tests;