rumdl_lib/utils/
regex_cache.rs

1//!
2//! Cached Regex Patterns and Fast Content Checks for Markdown Linting
3//!
4//! This module provides a centralized collection of pre-compiled, cached regex patterns
5//! for all major Markdown constructs (headings, lists, code blocks, links, images, etc.).
6//! It also includes fast-path utility functions for quickly checking if content
7//! potentially contains certain Markdown elements, allowing rules to skip expensive
8//! processing when unnecessary.
9//!
10//! # Performance
11//!
12//! All regexes are compiled once at startup using `lazy_static`, avoiding repeated
13//! compilation and improving performance across the linter. Use these shared patterns
14//! in rules instead of compiling new regexes.
15//!
16//! # Usage
17//!
18//! - Use the provided statics for common Markdown patterns.
19//! - Use the `regex_lazy!` macro for ad-hoc regexes that are not predefined.
20//! - Use the utility functions for fast content checks before running regexes.
21
22use fancy_regex::Regex as FancyRegex;
23use regex::Regex;
24use std::collections::HashMap;
25use std::sync::LazyLock;
26use std::sync::{Arc, Mutex};
27
28/// Global regex cache for dynamic patterns
29#[derive(Debug)]
30pub struct RegexCache {
31    cache: HashMap<String, Arc<Regex>>,
32    fancy_cache: HashMap<String, Arc<FancyRegex>>,
33    usage_stats: HashMap<String, u64>,
34}
35
36impl Default for RegexCache {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl RegexCache {
43    pub fn new() -> Self {
44        Self {
45            cache: HashMap::new(),
46            fancy_cache: HashMap::new(),
47            usage_stats: HashMap::new(),
48        }
49    }
50
51    /// Get or compile a regex pattern
52    pub fn get_regex(&mut self, pattern: &str) -> Result<Arc<Regex>, regex::Error> {
53        if let Some(regex) = self.cache.get(pattern) {
54            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
55            return Ok(regex.clone());
56        }
57
58        let regex = Arc::new(Regex::new(pattern)?);
59        self.cache.insert(pattern.to_string(), regex.clone());
60        *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
61        Ok(regex)
62    }
63
64    /// Get or compile a fancy regex pattern
65    pub fn get_fancy_regex(&mut self, pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
66        if let Some(regex) = self.fancy_cache.get(pattern) {
67            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
68            return Ok(regex.clone());
69        }
70
71        match FancyRegex::new(pattern) {
72            Ok(regex) => {
73                let arc_regex = Arc::new(regex);
74                self.fancy_cache.insert(pattern.to_string(), arc_regex.clone());
75                *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
76                Ok(arc_regex)
77            }
78            Err(e) => Err(Box::new(e)),
79        }
80    }
81
82    /// Get cache statistics
83    pub fn get_stats(&self) -> HashMap<String, u64> {
84        self.usage_stats.clone()
85    }
86
87    /// Clear cache (useful for testing)
88    pub fn clear(&mut self) {
89        self.cache.clear();
90        self.fancy_cache.clear();
91        self.usage_stats.clear();
92    }
93}
94
95/// Global regex cache instance
96static GLOBAL_REGEX_CACHE: LazyLock<Arc<Mutex<RegexCache>>> = LazyLock::new(|| Arc::new(Mutex::new(RegexCache::new())));
97
98/// Get a regex from the global cache
99///
100/// If the mutex is poisoned (another thread panicked while holding the lock),
101/// this function recovers by clearing the cache and continuing. This ensures
102/// the library never panics due to mutex poisoning.
103pub fn get_cached_regex(pattern: &str) -> Result<Arc<Regex>, regex::Error> {
104    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
105        // Recover from poisoned mutex by clearing the cache
106        let mut guard = poisoned.into_inner();
107        guard.clear();
108        guard
109    });
110    cache.get_regex(pattern)
111}
112
113/// Get a fancy regex from the global cache
114///
115/// If the mutex is poisoned (another thread panicked while holding the lock),
116/// this function recovers by clearing the cache and continuing. This ensures
117/// the library never panics due to mutex poisoning.
118pub fn get_cached_fancy_regex(pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
119    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
120        // Recover from poisoned mutex by clearing the cache
121        let mut guard = poisoned.into_inner();
122        guard.clear();
123        guard
124    });
125    cache.get_fancy_regex(pattern)
126}
127
128/// Get cache usage statistics
129///
130/// If the mutex is poisoned, returns an empty HashMap rather than panicking.
131pub fn get_cache_stats() -> HashMap<String, u64> {
132    match GLOBAL_REGEX_CACHE.lock() {
133        Ok(cache) => cache.get_stats(),
134        Err(_) => HashMap::new(),
135    }
136}
137
138/// Macro for defining a lazily-initialized, cached regex pattern.
139///
140/// Use this for ad-hoc regexes that are not already defined in this module.
141///
142/// # Panics
143///
144/// This macro will panic at initialization if the regex pattern is invalid.
145/// This is intentional for compile-time constant patterns - we want to catch
146/// invalid patterns during development, not at runtime.
147///
148/// # Example
149///
150/// ```
151/// use rumdl_lib::regex_lazy;
152/// let my_re = regex_lazy!(r"^foo.*bar$");
153/// assert!(my_re.is_match("foobar"));
154/// ```
155#[macro_export]
156macro_rules! regex_lazy {
157    ($pattern:expr) => {{
158        static REGEX: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new($pattern).unwrap());
159        &*REGEX
160    }};
161}
162
163/// Macro for getting regex from global cache.
164///
165/// # Panics
166///
167/// Panics if the regex pattern is invalid. This is acceptable for static patterns
168/// where we want to fail fast during development.
169#[macro_export]
170macro_rules! regex_cached {
171    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_regex($pattern).expect("Failed to compile regex") }};
172}
173
174/// Macro for getting fancy regex from global cache.
175///
176/// # Panics
177///
178/// Panics if the regex pattern is invalid. This is acceptable for static patterns
179/// where we want to fail fast during development.
180#[macro_export]
181macro_rules! fancy_regex_cached {
182    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_fancy_regex($pattern).expect("Failed to compile fancy regex") }};
183}
184
185// Also make the macro available directly from this module
186pub use crate::regex_lazy;
187
188// =============================================================================
189// URL REGEX PATTERNS - Centralized URL Detection
190// =============================================================================
191//
192// ## Pattern Hierarchy (use the most specific pattern for your needs):
193//
194// | Pattern              | Use Case                                    | Parens | Trailing Punct |
195// |----------------------|---------------------------------------------|--------|----------------|
196// | URL_STANDARD_REGEX   | MD034 bare URL detection with auto-fix      | Yes    | Captured*      |
197// | URL_WWW_REGEX        | www.domain URLs without protocol            | Yes    | Captured*      |
198// | URL_IPV6_REGEX       | IPv6 URLs like https://[::1]/path           | Yes    | Captured*      |
199// | URL_QUICK_CHECK_REGEX| Fast early-exit check (contains URL?)       | N/A    | N/A            |
200// | URL_SIMPLE_REGEX     | Content detection, line length exemption    | No     | Excluded       |
201//
202// *Trailing punctuation is captured by the regex; use trim_trailing_punctuation() to clean.
203//
204// ## Design Principles:
205// 1. Parentheses in paths are allowed for Wikipedia-style URLs (Issue #240)
206// 2. Host portion excludes / so path is captured separately
207// 3. Unbalanced trailing parens are handled by trim_trailing_punctuation()
208// 4. All patterns exclude angle brackets <> to avoid matching autolinks
209//
210// ## URL Structure: protocol://host[:port][/path][?query][#fragment]
211
212/// Pattern for standard HTTP(S)/FTP(S) URLs with full path support.
213///
214/// Use this for bare URL detection where you need the complete URL including
215/// Wikipedia-style parentheses in paths. Trailing punctuation like `,;.!?` may
216/// be captured and should be trimmed by the caller.
217///
218/// # Examples
219/// - `https://example.com/path_(with_parens)?query#fragment`
220/// - `https://en.wikipedia.org/wiki/Rust_(programming_language)`
221pub const URL_STANDARD_STR: &str = concat!(
222    r#"(?:https?|ftps?|ftp)://"#, // Protocol
223    r#"(?:"#,
224    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host OR
225    r#"|"#,
226    r#"[^\s<>\[\]()\\'\"`/]+"#, // Standard host (no parens, no /)
227    r#")"#,
228    r#"(?::\d+)?"#,                 // Optional port
229    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,  // Optional path (allows parens)
230    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#, // Optional query (allows parens)
231    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,  // Optional fragment (allows parens)
232);
233
234/// Pattern for www URLs without protocol.
235///
236/// Matches URLs starting with `www.` that lack a protocol prefix.
237/// These should be converted to proper URLs or flagged as bare URLs.
238/// Supports port, path, query string, and fragment like URL_STANDARD_STR.
239///
240/// # Examples
241/// - `www.example.com`
242/// - `www.example.com:8080`
243/// - `www.example.com/path`
244/// - `www.example.com?query=value`
245/// - `www.example.com#section`
246pub const URL_WWW_STR: &str = concat!(
247    r#"www\.(?:[a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}"#, // www.domain.tld
248    r#"(?::\d+)?"#,                                        // Optional port
249    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,                         // Optional path (allows parens)
250    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#,                        // Optional query (allows parens)
251    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,                         // Optional fragment (allows parens)
252);
253
254/// Pattern for IPv6 URLs specifically.
255///
256/// Matches URLs with IPv6 addresses in brackets, including zone identifiers.
257/// Examples: `https://[::1]/path`, `https://[fe80::1%eth0]:8080/`
258pub const URL_IPV6_STR: &str = concat!(
259    r#"(?:https?|ftps?|ftp)://"#,
260    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host in brackets
261    r#"(?::\d+)?"#,                   // Optional port
262    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,    // Optional path
263    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#,   // Optional query
264    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,    // Optional fragment
265);
266
267/// Pattern for XMPP URIs per GFM extended autolinks specification.
268///
269/// XMPP URIs use the format `xmpp:user@domain/resource` (without `://`).
270/// Reference: <https://github.github.com/gfm/#autolinks-extension->
271///
272/// # Examples
273/// - `xmpp:foo@bar.baz`
274/// - `xmpp:foo@bar.baz/txt`
275pub const XMPP_URI_STR: &str = r#"xmpp:[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:/[^\s<>\[\]\\'\"`]*)?"#;
276
277/// Quick check pattern for early exits.
278///
279/// Use this for fast pre-filtering before running more expensive patterns.
280/// Matches if the text likely contains a URL or email address.
281/// Includes `xmpp:` for GFM extended autolinks.
282pub const URL_QUICK_CHECK_STR: &str = r#"(?:https?|ftps?|ftp|xmpp)://|xmpp:|@|www\."#;
283
284/// Simple URL pattern for content detection.
285///
286/// Less strict pattern that excludes trailing sentence punctuation (.,).
287/// Use for line length exemption checks or content characteristic detection
288/// where you just need to know if a URL exists, not extract it precisely.
289pub const URL_SIMPLE_STR: &str = r#"(?:https?|ftps?|ftp)://[^\s<>]+[^\s<>.,]"#;
290
291// Pre-compiled static patterns for performance
292
293/// Standard URL regex - primary pattern for bare URL detection (MD034).
294/// See [`URL_STANDARD_STR`] for documentation.
295pub static URL_STANDARD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_STANDARD_STR).unwrap());
296
297/// WWW URL regex - for URLs starting with www. without protocol.
298/// See [`URL_WWW_STR`] for documentation.
299pub static URL_WWW_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_WWW_STR).unwrap());
300
301/// IPv6 URL regex - for URLs with IPv6 addresses.
302/// See [`URL_IPV6_STR`] for documentation.
303pub static URL_IPV6_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_IPV6_STR).unwrap());
304
305/// Quick check regex - fast early-exit test.
306/// See [`URL_QUICK_CHECK_STR`] for documentation.
307pub static URL_QUICK_CHECK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_QUICK_CHECK_STR).unwrap());
308
309/// Simple URL regex - for content detection and line length exemption.
310/// See [`URL_SIMPLE_STR`] for documentation.
311pub static URL_SIMPLE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_SIMPLE_STR).unwrap());
312
313/// Alias for `URL_SIMPLE_REGEX`. Used by MD013 for line length exemption.
314pub static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| URL_SIMPLE_REGEX.clone());
315
316/// XMPP URI regex - for GFM extended autolinks.
317/// See [`XMPP_URI_STR`] for documentation.
318pub static XMPP_URI_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(XMPP_URI_STR).unwrap());
319
320// Heading patterns
321pub static ATX_HEADING_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+|$)").unwrap());
322pub static CLOSED_ATX_HEADING_REGEX: LazyLock<Regex> =
323    LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+)(.*)(\s+)(#+)(\s*)$").unwrap());
324pub static SETEXT_HEADING_REGEX: LazyLock<Regex> =
325    LazyLock::new(|| Regex::new(r"^(\s*)[^\s]+.*\n(\s*)(=+|-+)\s*$").unwrap());
326pub static TRAILING_PUNCTUATION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.,:);!?]$").unwrap());
327
328// ATX heading patterns for MD051 and other rules
329pub static ATX_HEADING_WITH_CAPTURE: LazyLock<Regex> =
330    LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.+?)(?:\s+#*\s*)?$").unwrap());
331pub static SETEXT_HEADING_WITH_CAPTURE: LazyLock<FancyRegex> =
332    LazyLock::new(|| FancyRegex::new(r"^([^\n]+)\n([=\-])\2+\s*$").unwrap());
333
334// List patterns
335pub static UNORDERED_LIST_MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)([*+-])(\s+)").unwrap());
336pub static ORDERED_LIST_MARKER_REGEX: LazyLock<Regex> =
337    LazyLock::new(|| Regex::new(r"^(\s*)(\d+)([.)])(\s+)").unwrap());
338pub static LIST_MARKER_ANY_REGEX: LazyLock<Regex> =
339    LazyLock::new(|| Regex::new(r"^(\s*)(?:([*+-])|(\d+)[.)])(\s+)").unwrap());
340
341// Code block patterns
342pub static FENCED_CODE_BLOCK_START_REGEX: LazyLock<Regex> =
343    LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(.*)$").unwrap());
344pub static FENCED_CODE_BLOCK_END_REGEX: LazyLock<Regex> =
345    LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(\s*)$").unwrap());
346pub static INDENTED_CODE_BLOCK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})(.*)$").unwrap());
347pub static CODE_FENCE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(`{3,}|~{3,})").unwrap());
348
349// Emphasis patterns
350pub static EMPHASIS_REGEX: LazyLock<FancyRegex> =
351    LazyLock::new(|| FancyRegex::new(r"(\s|^)(\*{1,2}|_{1,2})(?=\S)(.+?)(?<=\S)(\2)(\s|$)").unwrap());
352pub static SPACE_IN_EMPHASIS_REGEX: LazyLock<FancyRegex> =
353    LazyLock::new(|| FancyRegex::new(r"(\*|_)(\s+)(.+?)(\s+)(\1)").unwrap());
354
355// MD037 specific emphasis patterns - improved to avoid false positives
356// Only match emphasis with spaces that are actually complete emphasis blocks
357// Use word boundaries and negative lookbehind/lookahead to avoid matching across emphasis boundaries
358pub static ASTERISK_EMPHASIS: LazyLock<Regex> =
359    LazyLock::new(|| Regex::new(r"(?:^|[^*])\*(\s+[^*]+\s*|\s*[^*]+\s+)\*(?:[^*]|$)").unwrap());
360pub static UNDERSCORE_EMPHASIS: LazyLock<Regex> =
361    LazyLock::new(|| Regex::new(r"(?:^|[^_])_(\s+[^_]+\s*|\s*[^_]+\s+)_(?:[^_]|$)").unwrap());
362pub static DOUBLE_UNDERSCORE_EMPHASIS: LazyLock<Regex> =
363    LazyLock::new(|| Regex::new(r"(?:^|[^_])__(\s+[^_]+\s*|\s*[^_]+\s+)__(?:[^_]|$)").unwrap());
364pub static DOUBLE_ASTERISK_EMPHASIS: LazyLock<FancyRegex> =
365    LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\s+\*\*").unwrap());
366pub static DOUBLE_ASTERISK_SPACE_START: LazyLock<FancyRegex> =
367    LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\*\*").unwrap());
368pub static DOUBLE_ASTERISK_SPACE_END: LazyLock<FancyRegex> =
369    LazyLock::new(|| FancyRegex::new(r"\*\*([^*]+?)\s+\*\*").unwrap());
370
371// Code block patterns
372pub static FENCED_CODE_BLOCK_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```(?:[^`\r\n]*)$").unwrap());
373pub static FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```\s*$").unwrap());
374pub static ALTERNATE_FENCED_CODE_BLOCK_START: LazyLock<Regex> =
375    LazyLock::new(|| Regex::new(r"^(\s*)~~~(?:[^~\r\n]*)$").unwrap());
376pub static ALTERNATE_FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)~~~\s*$").unwrap());
377pub static INDENTED_CODE_BLOCK_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})").unwrap());
378
379// HTML patterns
380pub static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*)>").unwrap());
381pub static HTML_SELF_CLOSING_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*/)>").unwrap());
382pub static HTML_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z][^>]*>").unwrap());
383pub static HTML_OPENING_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)<[a-zA-Z][^>]*>").unwrap());
384pub static HTML_TAG_QUICK_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z]").unwrap());
385
386// Link patterns for MD051 and other rules
387pub static LINK_REFERENCE_DEFINITION_REGEX: LazyLock<Regex> =
388    LazyLock::new(|| Regex::new(r"^\s*\[([^\]]+)\]:\s+(.+)$").unwrap());
389pub static INLINE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());
390pub static LINK_TEXT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]").unwrap());
391pub static LINK_REGEX: LazyLock<FancyRegex> =
392    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]*)\]\(([^)#]*)#([^)]+)\)").unwrap());
393pub static EXTERNAL_URL_REGEX: LazyLock<FancyRegex> =
394    LazyLock::new(|| FancyRegex::new(r"^(https?://|ftp://|www\.|[^/]+\.[a-z]{2,})").unwrap());
395
396// Image patterns
397pub static IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
398
399// Whitespace patterns
400pub static TRAILING_WHITESPACE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+$").unwrap());
401pub static MULTIPLE_BLANK_LINES_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
402
403// Front matter patterns
404pub static FRONT_MATTER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^---\n.*?\n---\n").unwrap());
405
406// MD051 specific patterns
407pub static INLINE_CODE_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"`[^`]+`").unwrap());
408pub static BOLD_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*(.+?)\*\*").unwrap());
409pub static BOLD_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"__(.+?)__").unwrap());
410pub static ITALIC_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*([^*]+?)\*").unwrap());
411pub static ITALIC_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"_([^_]+?)_").unwrap());
412pub static LINK_TEXT_FULL_REGEX: LazyLock<FancyRegex> =
413    LazyLock::new(|| FancyRegex::new(r"\[([^\]]*)\]\([^)]*\)").unwrap());
414pub static STRIKETHROUGH_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"~~(.+?)~~").unwrap());
415pub static MULTIPLE_HYPHENS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-{2,}").unwrap());
416pub static TOC_SECTION_START: LazyLock<Regex> =
417    LazyLock::new(|| Regex::new(r"^#+\s*(?:Table of Contents|Contents|TOC)\s*$").unwrap());
418
419// Blockquote patterns
420pub static BLOCKQUOTE_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*>+\s*)").unwrap());
421
422// MD013 specific patterns
423pub static IMAGE_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^!\[.*?\]\[.*?\]$").unwrap());
424pub static LINK_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[.*?\]:\s*https?://\S+$").unwrap());
425/// Greedy URL pattern for finding URLs in text for length calculation.
426///
427/// Pattern `https?://\S+` matches until whitespace, which may include trailing
428/// punctuation. This is intentional for MD013 line length calculation where
429/// we replace URLs with fixed-length placeholders.
430///
431/// For precise URL extraction, use `URL_STANDARD_REGEX` instead.
432pub static URL_IN_TEXT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://\S+").unwrap());
433pub static SENTENCE_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.!?]\s+[A-Z]").unwrap());
434pub static ABBREVIATION: LazyLock<Regex> = LazyLock::new(|| {
435    Regex::new(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|vs|etc|i\.e|e\.g|Inc|Corp|Ltd|Co|St|Ave|Blvd|Rd|Ph\.D|M\.D|B\.A|M\.A|Ph\.D|U\.S|U\.K|U\.N|N\.Y|L\.A|D\.C)\.\s+[A-Z]").unwrap()
436});
437pub static DECIMAL_NUMBER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d+\.\s*\d+").unwrap());
438pub static LIST_ITEM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\d+\.\s+").unwrap());
439pub static REFERENCE_LINK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\[([^\]]*)\]").unwrap());
440
441// Email pattern
442pub static EMAIL_PATTERN: LazyLock<Regex> =
443    LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap());
444
445// Third lazy_static block for link and image patterns used by MD052 and text_reflow
446// Reference link patterns (shared by MD052 and text_reflow)
447// Pattern to match reference links: [text][reference] or [text][]
448pub static REF_LINK_REGEX: LazyLock<FancyRegex> =
449    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
450
451// Pattern for shortcut reference links: [reference]
452// Must not be preceded by ] or ) (to avoid matching second part of [text][ref])
453// Must not be followed by [ or ( (to avoid matching first part of [text][ref] or [text](url))
454// The capturing group handles nested brackets to support cases like [`Union[T, None]`]
455pub static SHORTCUT_REF_REGEX: LazyLock<FancyRegex> =
456    LazyLock::new(|| FancyRegex::new(r"(?<![\\)\]])\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\](?!\s*[\[\(])").unwrap());
457
458// Inline link with fancy regex for better escaping handling (used by text_reflow)
459pub static INLINE_LINK_FANCY_REGEX: LazyLock<FancyRegex> =
460    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]+)\]\(([^)]+)\)").unwrap());
461
462// Inline image with fancy regex (used by MD052 and text_reflow)
463pub static INLINE_IMAGE_FANCY_REGEX: LazyLock<FancyRegex> =
464    LazyLock::new(|| FancyRegex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
465
466// Linked images (clickable badges) - all 4 variants
467// Must be detected before inline_image and inline_link to treat as atomic units
468//
469// Limitation: Alt text containing brackets like [![[v1.0]](img)](link) is not supported.
470// The [^\]]* pattern cannot match nested brackets. This is rare in practice.
471//
472// Pattern 1: Inline image in inline link - [![alt](img-url)](link-url)
473pub static LINKED_IMAGE_INLINE_INLINE: LazyLock<FancyRegex> =
474    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)").unwrap());
475
476// Pattern 2: Reference image in inline link - [![alt][img-ref]](link-url)
477pub static LINKED_IMAGE_REF_INLINE: LazyLock<FancyRegex> =
478    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\(([^)]+)\)").unwrap());
479
480// Pattern 3: Inline image in reference link - [![alt](img-url)][link-ref]
481pub static LINKED_IMAGE_INLINE_REF: LazyLock<FancyRegex> =
482    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\[([^\]]*)\]").unwrap());
483
484// Pattern 4: Reference image in reference link - [![alt][img-ref]][link-ref]
485pub static LINKED_IMAGE_REF_REF: LazyLock<FancyRegex> =
486    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\[([^\]]*)\]").unwrap());
487
488// Reference image: ![alt][ref] or ![alt][]
489pub static REF_IMAGE_REGEX: LazyLock<FancyRegex> =
490    LazyLock::new(|| FancyRegex::new(r"!\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
491
492// Footnote reference: [^note]
493pub static FOOTNOTE_REF_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\^([^\]]+)\]").unwrap());
494
495// Strikethrough with fancy regex: ~~text~~
496pub static STRIKETHROUGH_FANCY_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"~~([^~]+)~~").unwrap());
497
498// Wiki-style links: [[wiki]] or [[wiki|display text]]
499pub static WIKI_LINK_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\[([^\]]+)\]\]").unwrap());
500
501// Math formulas: $inline$ or $$display$$
502pub static INLINE_MATH_REGEX: LazyLock<FancyRegex> =
503    LazyLock::new(|| FancyRegex::new(r"(?<!\$)\$(?!\$)([^\$]+)\$(?!\$)").unwrap());
504pub static DISPLAY_MATH_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\$\$([^\$]+)\$\$").unwrap());
505
506// Emoji shortcodes: :emoji:
507pub static EMOJI_SHORTCODE_REGEX: LazyLock<FancyRegex> =
508    LazyLock::new(|| FancyRegex::new(r":([a-zA-Z0-9_+-]+):").unwrap());
509
510// HTML tags (opening, closing, self-closing)
511pub static HTML_TAG_PATTERN: LazyLock<FancyRegex> =
512    LazyLock::new(|| FancyRegex::new(r"</?[a-zA-Z][^>]*>|<[a-zA-Z][^>]*/\s*>").unwrap());
513
514// HTML entities: &nbsp; &mdash; etc
515pub static HTML_ENTITY_REGEX: LazyLock<FancyRegex> =
516    LazyLock::new(|| FancyRegex::new(r"&[a-zA-Z][a-zA-Z0-9]*;|&#\d+;|&#x[0-9a-fA-F]+;").unwrap());
517
518// Hugo/Go template shortcodes: {{< figure ... >}} and {{% shortcode %}}
519// Matches both delimiters: {{< ... >}} (shortcode) and {{% ... %}} (template)
520// Handles multi-line content with embedded quotes and newlines
521pub static HUGO_SHORTCODE_REGEX: LazyLock<FancyRegex> =
522    LazyLock::new(|| FancyRegex::new(r"\{\{[<%][\s\S]*?[%>]\}\}").unwrap());
523
524// Fourth lazy_static block for additional patterns
525// HTML comment patterns
526pub static HTML_COMMENT_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--").unwrap());
527pub static HTML_COMMENT_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-->").unwrap());
528pub static HTML_COMMENT_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--[\s\S]*?-->").unwrap());
529
530// HTML heading pattern (matches <h1> through <h6> tags)
531pub static HTML_HEADING_PATTERN: LazyLock<FancyRegex> =
532    LazyLock::new(|| FancyRegex::new(r"^\s*<h([1-6])(?:\s[^>]*)?>.*</h\1>\s*$").unwrap());
533
534// Heading quick check pattern
535pub static HEADING_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^(?:\s*)#").unwrap());
536
537// Horizontal rule patterns
538pub static HR_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\-{3,}\s*$").unwrap());
539pub static HR_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\*{3,}\s*$").unwrap());
540pub static HR_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^_{3,}\s*$").unwrap());
541pub static HR_SPACED_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\-\s+){2,}\-\s*$").unwrap());
542pub static HR_SPACED_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\*\s+){2,}\*\s*$").unwrap());
543pub static HR_SPACED_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(_\s+){2,}_\s*$").unwrap());
544
545/// Utility functions for quick content checks
546/// Check if content contains any headings (quick check before regex)
547pub fn has_heading_markers(content: &str) -> bool {
548    content.contains('#')
549}
550
551/// Check if content contains any lists (quick check before regex)
552pub fn has_list_markers(content: &str) -> bool {
553    content.contains('*')
554        || content.contains('-')
555        || content.contains('+')
556        || (content.contains('.') && content.contains(|c: char| c.is_ascii_digit()))
557}
558
559/// Check if content contains any code blocks (quick check before regex)
560pub fn has_code_block_markers(content: &str) -> bool {
561    content.contains("```") || content.contains("~~~") || content.contains("\n    ")
562    // Indented code block potential
563}
564
565/// Check if content contains any emphasis markers (quick check before regex)
566pub fn has_emphasis_markers(content: &str) -> bool {
567    content.contains('*') || content.contains('_')
568}
569
570/// Check if content contains any HTML tags (quick check before regex)
571pub fn has_html_tags(content: &str) -> bool {
572    content.contains('<') && (content.contains('>') || content.contains("/>"))
573}
574
575/// Check if content contains any links (quick check before regex)
576pub fn has_link_markers(content: &str) -> bool {
577    (content.contains('[') && content.contains(']'))
578        || content.contains("http://")
579        || content.contains("https://")
580        || content.contains("ftp://")
581}
582
583/// Check if content contains any images (quick check before regex)
584pub fn has_image_markers(content: &str) -> bool {
585    content.contains("![")
586}
587
588/// Optimize URL detection by implementing a character-by-character scanner
589/// that's much faster than regex for cases where we know there's no URL
590pub fn contains_url(content: &str) -> bool {
591    // Fast check - if these substrings aren't present, there's no URL
592    if !content.contains("://") {
593        return false;
594    }
595
596    let chars: Vec<char> = content.chars().collect();
597    let mut i = 0;
598
599    while i < chars.len() {
600        // Look for the start of a URL protocol
601        if i + 2 < chars.len()
602            && ((chars[i] == 'h' && chars[i + 1] == 't' && chars[i + 2] == 't')
603                || (chars[i] == 'f' && chars[i + 1] == 't' && chars[i + 2] == 'p'))
604        {
605            // Scan forward to find "://"
606            let mut j = i;
607            while j + 2 < chars.len() {
608                if chars[j] == ':' && chars[j + 1] == '/' && chars[j + 2] == '/' {
609                    return true;
610                }
611                j += 1;
612
613                // Don't scan too far ahead for the protocol
614                if j > i + 10 {
615                    break;
616                }
617            }
618        }
619        i += 1;
620    }
621
622    false
623}
624
625/// Escapes a string to be used in a regex pattern
626pub fn escape_regex(s: &str) -> String {
627    let mut result = String::with_capacity(s.len() * 2);
628
629    for c in s.chars() {
630        // Use matches! for O(1) lookup instead of array.contains() which is O(n)
631        if matches!(
632            c,
633            '.' | '+' | '*' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\'
634        ) {
635            result.push('\\');
636        }
637        result.push(c);
638    }
639
640    result
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn test_regex_cache_new() {
649        let cache = RegexCache::new();
650        assert!(cache.cache.is_empty());
651        assert!(cache.fancy_cache.is_empty());
652        assert!(cache.usage_stats.is_empty());
653    }
654
655    #[test]
656    fn test_regex_cache_default() {
657        let cache = RegexCache::default();
658        assert!(cache.cache.is_empty());
659        assert!(cache.fancy_cache.is_empty());
660        assert!(cache.usage_stats.is_empty());
661    }
662
663    #[test]
664    fn test_get_regex_compilation() {
665        let mut cache = RegexCache::new();
666
667        // First call compiles and caches
668        let regex1 = cache.get_regex(r"\d+").unwrap();
669        assert_eq!(cache.cache.len(), 1);
670        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&1));
671
672        // Second call returns cached version
673        let regex2 = cache.get_regex(r"\d+").unwrap();
674        assert_eq!(cache.cache.len(), 1);
675        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&2));
676
677        // Both should be the same Arc
678        assert!(Arc::ptr_eq(&regex1, &regex2));
679    }
680
681    #[test]
682    fn test_get_regex_invalid_pattern() {
683        let mut cache = RegexCache::new();
684        let result = cache.get_regex(r"[unterminated");
685        assert!(result.is_err());
686        assert!(cache.cache.is_empty());
687    }
688
689    #[test]
690    fn test_get_fancy_regex_compilation() {
691        let mut cache = RegexCache::new();
692
693        // First call compiles and caches
694        let regex1 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
695        assert_eq!(cache.fancy_cache.len(), 1);
696        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&1));
697
698        // Second call returns cached version
699        let regex2 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
700        assert_eq!(cache.fancy_cache.len(), 1);
701        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&2));
702
703        // Both should be the same Arc
704        assert!(Arc::ptr_eq(&regex1, &regex2));
705    }
706
707    #[test]
708    fn test_get_fancy_regex_invalid_pattern() {
709        let mut cache = RegexCache::new();
710        let result = cache.get_fancy_regex(r"(?<=invalid");
711        assert!(result.is_err());
712        assert!(cache.fancy_cache.is_empty());
713    }
714
715    #[test]
716    fn test_get_stats() {
717        let mut cache = RegexCache::new();
718
719        // Use some patterns
720        let _ = cache.get_regex(r"\d+").unwrap();
721        let _ = cache.get_regex(r"\d+").unwrap();
722        let _ = cache.get_regex(r"\w+").unwrap();
723        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
724
725        let stats = cache.get_stats();
726        assert_eq!(stats.get(r"\d+"), Some(&2));
727        assert_eq!(stats.get(r"\w+"), Some(&1));
728        assert_eq!(stats.get(r"(?<=foo)bar"), Some(&1));
729    }
730
731    #[test]
732    fn test_clear_cache() {
733        let mut cache = RegexCache::new();
734
735        // Add some patterns
736        let _ = cache.get_regex(r"\d+").unwrap();
737        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
738
739        assert!(!cache.cache.is_empty());
740        assert!(!cache.fancy_cache.is_empty());
741        assert!(!cache.usage_stats.is_empty());
742
743        // Clear cache
744        cache.clear();
745
746        assert!(cache.cache.is_empty());
747        assert!(cache.fancy_cache.is_empty());
748        assert!(cache.usage_stats.is_empty());
749    }
750
751    #[test]
752    fn test_global_cache_functions() {
753        // Test get_cached_regex
754        let regex1 = get_cached_regex(r"\d{3}").unwrap();
755        let regex2 = get_cached_regex(r"\d{3}").unwrap();
756        assert!(Arc::ptr_eq(&regex1, &regex2));
757
758        // Test get_cached_fancy_regex
759        let fancy1 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
760        let fancy2 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
761        assert!(Arc::ptr_eq(&fancy1, &fancy2));
762
763        // Test stats
764        let stats = get_cache_stats();
765        assert!(stats.contains_key(r"\d{3}"));
766        assert!(stats.contains_key(r"(?<=test)ing"));
767    }
768
769    #[test]
770    fn test_regex_lazy_macro() {
771        let re = regex_lazy!(r"^test.*end$");
772        assert!(re.is_match("test something end"));
773        assert!(!re.is_match("test something"));
774
775        // The macro creates a new static for each invocation location,
776        // so we can't test pointer equality across different invocations
777        // But we can test that the regex works correctly
778        let re2 = regex_lazy!(r"^start.*finish$");
779        assert!(re2.is_match("start and finish"));
780        assert!(!re2.is_match("start without end"));
781    }
782
783    #[test]
784    fn test_has_heading_markers() {
785        assert!(has_heading_markers("# Heading"));
786        assert!(has_heading_markers("Text with # symbol"));
787        assert!(!has_heading_markers("Text without heading marker"));
788    }
789
790    #[test]
791    fn test_has_list_markers() {
792        assert!(has_list_markers("* Item"));
793        assert!(has_list_markers("- Item"));
794        assert!(has_list_markers("+ Item"));
795        assert!(has_list_markers("1. Item"));
796        assert!(!has_list_markers("Text without list markers"));
797    }
798
799    #[test]
800    fn test_has_code_block_markers() {
801        assert!(has_code_block_markers("```code```"));
802        assert!(has_code_block_markers("~~~code~~~"));
803        assert!(has_code_block_markers("Text\n    indented code"));
804        assert!(!has_code_block_markers("Text without code blocks"));
805    }
806
807    #[test]
808    fn test_has_emphasis_markers() {
809        assert!(has_emphasis_markers("*emphasis*"));
810        assert!(has_emphasis_markers("_emphasis_"));
811        assert!(has_emphasis_markers("**bold**"));
812        assert!(has_emphasis_markers("__bold__"));
813        assert!(!has_emphasis_markers("no emphasis"));
814    }
815
816    #[test]
817    fn test_has_html_tags() {
818        assert!(has_html_tags("<div>content</div>"));
819        assert!(has_html_tags("<br/>"));
820        assert!(has_html_tags("<img src='test.jpg'>"));
821        assert!(!has_html_tags("no html tags"));
822        assert!(!has_html_tags("less than < but no tag"));
823    }
824
825    #[test]
826    fn test_has_link_markers() {
827        assert!(has_link_markers("[text](url)"));
828        assert!(has_link_markers("[reference][1]"));
829        assert!(has_link_markers("http://example.com"));
830        assert!(has_link_markers("https://example.com"));
831        assert!(has_link_markers("ftp://example.com"));
832        assert!(!has_link_markers("no links here"));
833    }
834
835    #[test]
836    fn test_has_image_markers() {
837        assert!(has_image_markers("![alt text](image.png)"));
838        assert!(has_image_markers("![](image.png)"));
839        assert!(!has_image_markers("[link](url)"));
840        assert!(!has_image_markers("no images"));
841    }
842
843    #[test]
844    fn test_contains_url() {
845        assert!(contains_url("http://example.com"));
846        assert!(contains_url("Text with https://example.com link"));
847        assert!(contains_url("ftp://example.com"));
848        assert!(!contains_url("Text without URL"));
849        assert!(!contains_url("http not followed by ://"));
850
851        // Edge cases
852        assert!(!contains_url("http"));
853        assert!(!contains_url("https"));
854        assert!(!contains_url("://"));
855        assert!(contains_url("Visit http://site.com now"));
856        assert!(contains_url("See https://secure.site.com/path"));
857    }
858
859    #[test]
860    fn test_contains_url_performance() {
861        // Test early exit for strings without "://"
862        let long_text = "a".repeat(10000);
863        assert!(!contains_url(&long_text));
864
865        // Test with URL at the end
866        let text_with_url = format!("{long_text}https://example.com");
867        assert!(contains_url(&text_with_url));
868    }
869
870    #[test]
871    fn test_escape_regex() {
872        assert_eq!(escape_regex("a.b"), "a\\.b");
873        assert_eq!(escape_regex("a+b*c"), "a\\+b\\*c");
874        assert_eq!(escape_regex("(test)"), "\\(test\\)");
875        assert_eq!(escape_regex("[a-z]"), "\\[a-z\\]");
876        assert_eq!(escape_regex("normal text"), "normal text");
877
878        // Test all special characters
879        assert_eq!(escape_regex(".$^{[(|)*+?\\"), "\\.\\$\\^\\{\\[\\(\\|\\)\\*\\+\\?\\\\");
880
881        // Test empty string
882        assert_eq!(escape_regex(""), "");
883
884        // Test mixed content
885        assert_eq!(escape_regex("test.com/path?query=1"), "test\\.com/path\\?query=1");
886    }
887
888    #[test]
889    fn test_static_regex_patterns() {
890        // Test URL patterns
891        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
892        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
893        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com"));
894        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
895
896        // Test heading patterns
897        assert!(ATX_HEADING_REGEX.is_match("# Heading"));
898        assert!(ATX_HEADING_REGEX.is_match("  ## Indented"));
899        assert!(ATX_HEADING_REGEX.is_match("### "));
900        assert!(!ATX_HEADING_REGEX.is_match("Not a heading"));
901
902        // Test list patterns
903        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("* Item"));
904        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("- Item"));
905        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("+ Item"));
906        assert!(ORDERED_LIST_MARKER_REGEX.is_match("1. Item"));
907        assert!(ORDERED_LIST_MARKER_REGEX.is_match("99. Item"));
908
909        // Test code block patterns
910        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```"));
911        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```rust"));
912        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("~~~"));
913        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("```"));
914        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("~~~"));
915
916        // Test emphasis patterns
917        assert!(BOLD_ASTERISK_REGEX.is_match("**bold**"));
918        assert!(BOLD_UNDERSCORE_REGEX.is_match("__bold__"));
919        assert!(ITALIC_ASTERISK_REGEX.is_match("*italic*"));
920        assert!(ITALIC_UNDERSCORE_REGEX.is_match("_italic_"));
921
922        // Test HTML patterns
923        assert!(HTML_TAG_REGEX.is_match("<div>"));
924        assert!(HTML_TAG_REGEX.is_match("<span class='test'>"));
925        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<br/>"));
926        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<img src='test'/>"));
927
928        // Test whitespace patterns
929        assert!(TRAILING_WHITESPACE_REGEX.is_match("line with spaces   "));
930        assert!(TRAILING_WHITESPACE_REGEX.is_match("tabs\t\t"));
931        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n"));
932        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n\n"));
933
934        // Test blockquote pattern
935        assert!(BLOCKQUOTE_PREFIX_RE.is_match("> Quote"));
936        assert!(BLOCKQUOTE_PREFIX_RE.is_match("  > Indented quote"));
937        assert!(BLOCKQUOTE_PREFIX_RE.is_match(">> Nested"));
938    }
939
940    #[test]
941    fn test_thread_safety() {
942        use std::thread;
943
944        let handles: Vec<_> = (0..10)
945            .map(|i| {
946                thread::spawn(move || {
947                    let pattern = format!(r"\d{{{i}}}");
948                    let regex = get_cached_regex(&pattern).unwrap();
949                    assert!(regex.is_match(&"1".repeat(i)));
950                })
951            })
952            .collect();
953
954        for handle in handles {
955            handle.join().unwrap();
956        }
957    }
958
959    // ==========================================================================
960    // Comprehensive URL Regex Tests
961    // ==========================================================================
962
963    #[test]
964    fn test_url_standard_basic() {
965        // Basic HTTP/HTTPS URLs
966        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
967        assert!(URL_STANDARD_REGEX.is_match("http://example.com"));
968        assert!(URL_STANDARD_REGEX.is_match("https://example.com/"));
969        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path"));
970        assert!(URL_STANDARD_REGEX.is_match("ftp://files.example.com"));
971        assert!(URL_STANDARD_REGEX.is_match("ftps://secure.example.com"));
972
973        // Should not match non-URLs
974        assert!(!URL_STANDARD_REGEX.is_match("not a url"));
975        assert!(!URL_STANDARD_REGEX.is_match("example.com"));
976        assert!(!URL_STANDARD_REGEX.is_match("www.example.com"));
977    }
978
979    #[test]
980    fn test_url_standard_with_path() {
981        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page"));
982        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page.html"));
983        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page/"));
984    }
985
986    #[test]
987    fn test_url_standard_with_query() {
988        assert!(URL_STANDARD_REGEX.is_match("https://example.com?query=value"));
989        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value"));
990        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?a=1&b=2"));
991    }
992
993    #[test]
994    fn test_url_standard_with_fragment() {
995        assert!(URL_STANDARD_REGEX.is_match("https://example.com#section"));
996        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path#section"));
997        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value#section"));
998    }
999
1000    #[test]
1001    fn test_url_standard_with_port() {
1002        assert!(URL_STANDARD_REGEX.is_match("https://example.com:8080"));
1003        assert!(URL_STANDARD_REGEX.is_match("https://example.com:443/path"));
1004        assert!(URL_STANDARD_REGEX.is_match("http://localhost:3000"));
1005        assert!(URL_STANDARD_REGEX.is_match("https://192.168.1.1:8080/path"));
1006    }
1007
1008    #[test]
1009    fn test_url_standard_wikipedia_style_parentheses() {
1010        // Wikipedia-style URLs with parentheses in path (Issue #240)
1011        let url = "https://en.wikipedia.org/wiki/Rust_(programming_language)";
1012        assert!(URL_STANDARD_REGEX.is_match(url));
1013
1014        // Verify the full URL is captured
1015        let cap = URL_STANDARD_REGEX.find(url).unwrap();
1016        assert_eq!(cap.as_str(), url);
1017
1018        // Multiple parentheses pairs
1019        let url2 = "https://example.com/path_(foo)_(bar)";
1020        let cap2 = URL_STANDARD_REGEX.find(url2).unwrap();
1021        assert_eq!(cap2.as_str(), url2);
1022    }
1023
1024    #[test]
1025    fn test_url_standard_ipv6() {
1026        // IPv6 addresses in URLs
1027        assert!(URL_STANDARD_REGEX.is_match("https://[::1]/path"));
1028        assert!(URL_STANDARD_REGEX.is_match("https://[2001:db8::1]:8080/path"));
1029        assert!(URL_STANDARD_REGEX.is_match("http://[fe80::1%eth0]/"));
1030    }
1031
1032    #[test]
1033    fn test_url_www_basic() {
1034        // www URLs without protocol
1035        assert!(URL_WWW_REGEX.is_match("www.example.com"));
1036        assert!(URL_WWW_REGEX.is_match("www.example.co.uk"));
1037        assert!(URL_WWW_REGEX.is_match("www.sub.example.com"));
1038
1039        // Should not match plain domains without www
1040        assert!(!URL_WWW_REGEX.is_match("example.com"));
1041
1042        // Note: https://www.example.com DOES match because it contains "www."
1043        // The URL_WWW_REGEX is designed to find www. URLs that lack a protocol
1044        // Use URL_STANDARD_REGEX for full URLs with protocols
1045        assert!(URL_WWW_REGEX.is_match("https://www.example.com"));
1046    }
1047
1048    #[test]
1049    fn test_url_www_with_path() {
1050        assert!(URL_WWW_REGEX.is_match("www.example.com/path"));
1051        assert!(URL_WWW_REGEX.is_match("www.example.com/path/to/page"));
1052        assert!(URL_WWW_REGEX.is_match("www.example.com/path_(with_parens)"));
1053    }
1054
1055    #[test]
1056    fn test_url_ipv6_basic() {
1057        // IPv6 specific patterns
1058        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1059        assert!(URL_IPV6_REGEX.is_match("http://[2001:db8::1]/path"));
1060        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1]:8080/path"));
1061        assert!(URL_IPV6_REGEX.is_match("ftp://[::ffff:192.168.1.1]/file"));
1062    }
1063
1064    #[test]
1065    fn test_url_ipv6_with_zone_id() {
1066        // IPv6 with zone identifiers
1067        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1%eth0]/path"));
1068        assert!(URL_IPV6_REGEX.is_match("http://[fe80::1%25eth0]:8080/"));
1069    }
1070
1071    #[test]
1072    fn test_url_simple_detection() {
1073        // Simple pattern for content characteristic detection
1074        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1075        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
1076        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com/file.zip"));
1077        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
1078    }
1079
1080    #[test]
1081    fn test_url_quick_check() {
1082        // Quick check pattern for early exits
1083        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1084        assert!(URL_QUICK_CHECK_REGEX.is_match("http://example.com"));
1085        assert!(URL_QUICK_CHECK_REGEX.is_match("ftp://files.com"));
1086        assert!(URL_QUICK_CHECK_REGEX.is_match("www.example.com"));
1087        assert!(URL_QUICK_CHECK_REGEX.is_match("user@example.com"));
1088        assert!(!URL_QUICK_CHECK_REGEX.is_match("just plain text"));
1089    }
1090
1091    #[test]
1092    fn test_url_edge_cases() {
1093        // URLs with special characters that should be excluded
1094        let url = "https://example.com/path";
1095        assert!(URL_STANDARD_REGEX.is_match(url));
1096
1097        // URL followed by punctuation - the regex captures trailing punctuation
1098        // because trimming is done by `trim_trailing_punctuation()` in the rule
1099        let text = "Check https://example.com, it's great!";
1100        let cap = URL_STANDARD_REGEX.find(text).unwrap();
1101        // The comma IS captured by the regex - rule-level trimming handles this
1102        assert!(cap.as_str().ends_with(','));
1103
1104        // URL in angle brackets should still be found
1105        let text2 = "See <https://example.com> for more";
1106        assert!(URL_STANDARD_REGEX.is_match(text2));
1107
1108        // URL ending at angle bracket should stop at >
1109        let cap2 = URL_STANDARD_REGEX.find(text2).unwrap();
1110        assert!(!cap2.as_str().contains('>'));
1111    }
1112
1113    #[test]
1114    fn test_url_with_complex_paths() {
1115        // Complex real-world URLs
1116        let urls = [
1117            "https://github.com/owner/repo/blob/main/src/file.rs#L123",
1118            "https://docs.example.com/api/v2/endpoint?format=json&page=1",
1119            "https://cdn.example.com/assets/images/logo.png?v=2023",
1120            "https://search.example.com/results?q=test+query&filter=all",
1121        ];
1122
1123        for url in urls {
1124            assert!(URL_STANDARD_REGEX.is_match(url), "Should match: {url}");
1125        }
1126    }
1127
1128    #[test]
1129    fn test_url_pattern_strings_are_valid() {
1130        // Verify patterns compile into valid regexes by accessing them
1131        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
1132        assert!(URL_WWW_REGEX.is_match("www.example.com"));
1133        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1134        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1135        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1136    }
1137}