Skip to main content

rumdl_lib/lint_context/
mod.rs

1pub mod types;
2pub use types::*;
3
4mod element_parsers;
5mod flavor_detection;
6mod heading_detection;
7mod line_computation;
8mod link_parser;
9mod list_blocks;
10#[cfg(test)]
11mod tests;
12
13use crate::config::MarkdownFlavor;
14use crate::inline_config::InlineConfig;
15use crate::rules::front_matter_utils::FrontMatterUtils;
16use crate::utils::code_block_utils::{CodeBlockDetail, CodeBlockUtils};
17use std::collections::HashMap;
18use std::path::PathBuf;
19
20/// Macro for profiling sections - only active in non-WASM builds
21#[cfg(not(target_arch = "wasm32"))]
22macro_rules! profile_section {
23    ($name:expr, $profile:expr, $code:expr) => {{
24        let start = std::time::Instant::now();
25        let result = $code;
26        if $profile {
27            eprintln!("[PROFILE] {}: {:?}", $name, start.elapsed());
28        }
29        result
30    }};
31}
32
33#[cfg(target_arch = "wasm32")]
34macro_rules! profile_section {
35    ($name:expr, $profile:expr, $code:expr) => {{ $code }};
36}
37
38/// Grouped byte ranges for skip context detection
39/// Used to reduce parameter count in internal functions
40pub(super) struct SkipByteRanges<'a> {
41    pub(super) html_comment_ranges: &'a [crate::utils::skip_context::ByteRange],
42    pub(super) autodoc_ranges: &'a [crate::utils::skip_context::ByteRange],
43    pub(super) quarto_div_ranges: &'a [crate::utils::skip_context::ByteRange],
44    pub(super) pymdown_block_ranges: &'a [crate::utils::skip_context::ByteRange],
45}
46
47use std::sync::{Arc, OnceLock};
48
49/// Map from line byte offset to list item data: (is_ordered, marker, marker_column, content_column, number)
50pub(super) type ListItemMap = std::collections::HashMap<usize, (bool, String, usize, usize, Option<usize>)>;
51
52/// Type alias for byte ranges used in JSX expression and MDX comment detection
53pub(super) type ByteRanges = Vec<(usize, usize)>;
54
55pub struct LintContext<'a> {
56    pub content: &'a str,
57    content_lines: Vec<&'a str>, // Pre-split lines from content (avoids repeated allocations)
58    pub line_offsets: Vec<usize>,
59    pub code_blocks: Vec<(usize, usize)>, // Cached code block ranges (not including inline code spans)
60    pub code_block_details: Vec<CodeBlockDetail>, // Per-block metadata (fenced/indented, info string)
61    pub strong_spans: Vec<crate::utils::code_block_utils::StrongSpanDetail>, // Pre-computed strong emphasis spans
62    pub line_to_list: crate::utils::code_block_utils::LineToListMap, // Ordered list membership by line
63    pub list_start_values: crate::utils::code_block_utils::ListStartValues, // Start values per list ID
64    pub lines: Vec<LineInfo>,             // Pre-computed line information
65    pub links: Vec<ParsedLink<'a>>,       // Pre-parsed links
66    pub images: Vec<ParsedImage<'a>>,     // Pre-parsed images
67    pub broken_links: Vec<BrokenLinkInfo>, // Broken/undefined references
68    pub footnote_refs: Vec<FootnoteRef>,  // Pre-parsed footnote references
69    pub reference_defs: Vec<ReferenceDef>, // Reference definitions
70    reference_defs_map: HashMap<String, usize>, // O(1) lookup by lowercase ID -> index in reference_defs
71    code_spans_cache: OnceLock<Arc<Vec<CodeSpan>>>, // Lazy-loaded inline code spans
72    math_spans_cache: OnceLock<Arc<Vec<MathSpan>>>, // Lazy-loaded math spans ($...$ and $$...$$)
73    pub list_blocks: Vec<ListBlock>,      // Pre-parsed list blocks
74    pub char_frequency: CharFrequency,    // Character frequency analysis
75    html_tags_cache: OnceLock<Arc<Vec<HtmlTag>>>, // Lazy-loaded HTML tags
76    emphasis_spans_cache: OnceLock<Arc<Vec<EmphasisSpan>>>, // Lazy-loaded emphasis spans
77    table_rows_cache: OnceLock<Arc<Vec<TableRow>>>, // Lazy-loaded table rows
78    bare_urls_cache: OnceLock<Arc<Vec<BareUrl>>>, // Lazy-loaded bare URLs
79    has_mixed_list_nesting_cache: OnceLock<bool>, // Cached result for mixed ordered/unordered list nesting detection
80    html_comment_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed HTML comment ranges
81    pub table_blocks: Vec<crate::utils::table_utils::TableBlock>, // Pre-computed table blocks
82    pub line_index: crate::utils::range_utils::LineIndex<'a>, // Pre-computed line index for byte position calculations
83    jinja_ranges: Vec<(usize, usize)>,    // Pre-computed Jinja template ranges ({{ }}, {% %})
84    pub flavor: MarkdownFlavor,           // Markdown flavor being used
85    pub source_file: Option<PathBuf>,     // Source file path (for rules that need file context)
86    jsx_expression_ranges: Vec<(usize, usize)>, // Pre-computed JSX expression ranges (MDX: {expression})
87    mdx_comment_ranges: Vec<(usize, usize)>, // Pre-computed MDX comment ranges ({/* ... */})
88    citation_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc/Quarto citation ranges (Quarto: @key, [@key])
89    shortcode_ranges: Vec<(usize, usize)>, // Pre-computed Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
90    link_title_ranges: Vec<(usize, usize)>, // Pre-computed sorted link title byte ranges
91    code_span_byte_ranges: Vec<(usize, usize)>, // Pre-computed code span byte ranges from pulldown-cmark
92    inline_config: InlineConfig,           // Parsed inline configuration comments for rule disabling
93    obsidian_comment_ranges: Vec<(usize, usize)>, // Pre-computed Obsidian comment ranges (%%...%%)
94    lazy_cont_lines_cache: OnceLock<Arc<Vec<LazyContLine>>>, // Lazy-loaded lazy continuation lines
95}
96
97impl<'a> LintContext<'a> {
98    pub fn new(content: &'a str, flavor: MarkdownFlavor, source_file: Option<PathBuf>) -> Self {
99        #[cfg(not(target_arch = "wasm32"))]
100        let profile = std::env::var("RUMDL_PROFILE_QUADRATIC").is_ok();
101
102        let line_offsets = profile_section!("Line offsets", profile, {
103            let mut offsets = vec![0];
104            for (i, c) in content.char_indices() {
105                if c == '\n' {
106                    offsets.push(i + 1);
107                }
108            }
109            offsets
110        });
111
112        // Compute content_lines once for all functions that need it
113        let content_lines: Vec<&str> = content.lines().collect();
114
115        // Detect front matter boundaries once for all functions that need it
116        let front_matter_end = FrontMatterUtils::get_front_matter_end_line(content);
117
118        // Detect code blocks and code spans once and cache them
119        let parse_result = profile_section!(
120            "Code blocks",
121            profile,
122            CodeBlockUtils::detect_code_blocks_and_spans(content)
123        );
124        let mut code_blocks = parse_result.code_blocks;
125        let code_span_ranges = parse_result.code_spans;
126        let code_block_details = parse_result.code_block_details;
127        let strong_spans = parse_result.strong_spans;
128        let line_to_list = parse_result.line_to_list;
129        let list_start_values = parse_result.list_start_values;
130
131        // Pre-compute HTML comment ranges ONCE for all operations
132        let html_comment_ranges = profile_section!(
133            "HTML comment ranges",
134            profile,
135            crate::utils::skip_context::compute_html_comment_ranges(content)
136        );
137
138        // Pre-compute autodoc block ranges (avoids O(n^2) scaling)
139        // Detected for all flavors: `:::` blocks are structurally unique and should
140        // never be reflowed as prose, even without MkDocs flavor.
141        let autodoc_ranges = profile_section!(
142            "Autodoc block ranges",
143            profile,
144            crate::utils::mkdocstrings_refs::detect_autodoc_block_ranges(content)
145        );
146
147        // Pre-compute Quarto div block ranges for Quarto flavor
148        let quarto_div_ranges = profile_section!("Quarto div ranges", profile, {
149            if flavor == MarkdownFlavor::Quarto {
150                crate::utils::quarto_divs::detect_div_block_ranges(content)
151            } else {
152                Vec::new()
153            }
154        });
155
156        // Pre-compute PyMdown Blocks ranges for MkDocs flavor (/// ... ///)
157        let pymdown_block_ranges = profile_section!("PyMdown block ranges", profile, {
158            if flavor == MarkdownFlavor::MkDocs {
159                crate::utils::pymdown_blocks::detect_block_ranges(content)
160            } else {
161                Vec::new()
162            }
163        });
164
165        // Pre-compute line information AND emphasis spans (without headings/blockquotes yet)
166        // Emphasis spans are captured during the same pulldown-cmark parse as list detection
167        let skip_ranges = SkipByteRanges {
168            html_comment_ranges: &html_comment_ranges,
169            autodoc_ranges: &autodoc_ranges,
170            quarto_div_ranges: &quarto_div_ranges,
171            pymdown_block_ranges: &pymdown_block_ranges,
172        };
173        let (mut lines, emphasis_spans) = profile_section!(
174            "Basic line info",
175            profile,
176            line_computation::compute_basic_line_info(
177                content,
178                &content_lines,
179                &line_offsets,
180                &code_blocks,
181                flavor,
182                &skip_ranges,
183                front_matter_end,
184            )
185        );
186
187        // Detect HTML blocks BEFORE heading detection
188        profile_section!(
189            "HTML blocks",
190            profile,
191            heading_detection::detect_html_blocks(content, &mut lines)
192        );
193
194        // Detect ESM import/export blocks in MDX files BEFORE heading detection
195        profile_section!(
196            "ESM blocks",
197            profile,
198            flavor_detection::detect_esm_blocks(content, &mut lines, flavor)
199        );
200
201        // Detect JSX component blocks in MDX files (e.g. <Tabs>...</Tabs>)
202        profile_section!(
203            "JSX block detection",
204            profile,
205            flavor_detection::detect_jsx_blocks(content, &mut lines, flavor)
206        );
207
208        // Detect JSX expressions and MDX comments in MDX files
209        let (jsx_expression_ranges, mdx_comment_ranges) = profile_section!(
210            "JSX/MDX detection",
211            profile,
212            flavor_detection::detect_jsx_and_mdx_comments(content, &mut lines, flavor, &code_blocks)
213        );
214
215        // Detect MkDocs-specific constructs (admonitions, tabs, definition lists)
216        profile_section!(
217            "MkDocs constructs",
218            profile,
219            flavor_detection::detect_mkdocs_line_info(&content_lines, &mut lines, flavor)
220        );
221
222        // Detect footnote definitions and correct false code block detection.
223        // With ENABLE_FOOTNOTES, pulldown-cmark correctly parses multi-line
224        // footnotes, but the code block detector may still mark 4-space-indented
225        // footnote continuation lines as indented code blocks.
226        profile_section!(
227            "Footnote definitions",
228            profile,
229            detect_footnote_definitions(content, &mut lines, &line_offsets)
230        );
231
232        // Filter code_blocks to remove false positives from footnote continuation content.
233        // Same pattern as MkDocs/JSX corrections below.
234        {
235            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
236            for &(start, end) in &code_blocks {
237                let start_line = line_offsets
238                    .partition_point(|&offset| offset <= start)
239                    .saturating_sub(1);
240                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
241
242                let mut sub_start: Option<usize> = None;
243                for (i, &offset) in line_offsets[start_line..end_line]
244                    .iter()
245                    .enumerate()
246                    .map(|(j, o)| (j + start_line, o))
247                {
248                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
249                    if is_real_code && sub_start.is_none() {
250                        let byte_start = if i == start_line { start } else { offset };
251                        sub_start = Some(byte_start);
252                    } else if !is_real_code && sub_start.is_some() {
253                        new_code_blocks.push((sub_start.unwrap(), offset));
254                        sub_start = None;
255                    }
256                }
257                if let Some(s) = sub_start {
258                    new_code_blocks.push((s, end));
259                }
260            }
261            code_blocks = new_code_blocks;
262        }
263
264        // Filter code_blocks to remove false positives from MkDocs admonition/tab content.
265        // pulldown-cmark treats 4-space-indented content as indented code blocks, but inside
266        // MkDocs admonitions and content tabs this is regular markdown content.
267        // detect_mkdocs_line_info already corrected LineInfo.in_code_block for these lines,
268        // but the code_blocks byte ranges are still stale. We split ranges rather than using
269        // all-or-nothing removal, so fenced code blocks within admonitions are preserved.
270        if flavor == MarkdownFlavor::MkDocs {
271            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
272            for &(start, end) in &code_blocks {
273                let start_line = line_offsets
274                    .partition_point(|&offset| offset <= start)
275                    .saturating_sub(1);
276                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
277
278                // Walk lines in this range, collecting sub-ranges where in_code_block is true
279                let mut sub_start: Option<usize> = None;
280                for (i, &offset) in line_offsets[start_line..end_line]
281                    .iter()
282                    .enumerate()
283                    .map(|(j, o)| (j + start_line, o))
284                {
285                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
286                    if is_real_code && sub_start.is_none() {
287                        let byte_start = if i == start_line { start } else { offset };
288                        sub_start = Some(byte_start);
289                    } else if !is_real_code && sub_start.is_some() {
290                        new_code_blocks.push((sub_start.unwrap(), offset));
291                        sub_start = None;
292                    }
293                }
294                if let Some(s) = sub_start {
295                    new_code_blocks.push((s, end));
296                }
297            }
298            code_blocks = new_code_blocks;
299        }
300
301        // Filter code_blocks for MDX JSX blocks (same pattern as MkDocs above).
302        // detect_jsx_blocks already corrected LineInfo.in_code_block for indented content
303        // inside JSX component blocks, but code_blocks byte ranges need updating too.
304        if flavor.supports_jsx() {
305            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
306            for &(start, end) in &code_blocks {
307                let start_line = line_offsets
308                    .partition_point(|&offset| offset <= start)
309                    .saturating_sub(1);
310                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
311
312                let mut sub_start: Option<usize> = None;
313                for (i, &offset) in line_offsets[start_line..end_line]
314                    .iter()
315                    .enumerate()
316                    .map(|(j, o)| (j + start_line, o))
317                {
318                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
319                    if is_real_code && sub_start.is_none() {
320                        let byte_start = if i == start_line { start } else { offset };
321                        sub_start = Some(byte_start);
322                    } else if !is_real_code && sub_start.is_some() {
323                        new_code_blocks.push((sub_start.unwrap(), offset));
324                        sub_start = None;
325                    }
326                }
327                if let Some(s) = sub_start {
328                    new_code_blocks.push((s, end));
329                }
330            }
331            code_blocks = new_code_blocks;
332        }
333
334        // Detect kramdown constructs (extension blocks, IALs, ALDs) in kramdown flavor
335        profile_section!(
336            "Kramdown constructs",
337            profile,
338            flavor_detection::detect_kramdown_line_info(content, &mut lines, flavor)
339        );
340
341        // Layer 1: Sanitize content-derived fields inside kramdown extension blocks
342        // so downstream heading detection and collection builders never see them.
343        // This must run BEFORE detect_headings_and_blockquotes to prevent headings
344        // from being populated inside extension blocks.
345        for line in &mut lines {
346            if line.in_kramdown_extension_block {
347                line.list_item = None;
348                line.is_horizontal_rule = false;
349                line.blockquote = None;
350                line.is_kramdown_block_ial = false;
351            }
352        }
353
354        // Detect Obsidian comments (%%...%%) in Obsidian flavor
355        let obsidian_comment_ranges = profile_section!(
356            "Obsidian comments",
357            profile,
358            flavor_detection::detect_obsidian_comments(content, &mut lines, flavor, &code_span_ranges)
359        );
360
361        // Run pulldown-cmark parse for links, images, and link byte ranges in a single pass.
362        // Link byte ranges are needed for heading detection; links/images are finalized later
363        // after code_spans are available.
364        let pulldown_result = profile_section!(
365            "Links, images & link ranges",
366            profile,
367            link_parser::parse_links_images_pulldown(content, &lines, &code_blocks, flavor, &html_comment_ranges)
368        );
369
370        // Now detect headings and blockquotes
371        profile_section!(
372            "Headings & blockquotes",
373            profile,
374            heading_detection::detect_headings_and_blockquotes(
375                &content_lines,
376                &mut lines,
377                flavor,
378                &html_comment_ranges,
379                &pulldown_result.link_byte_ranges,
380                front_matter_end,
381            )
382        );
383
384        // Clear headings that were detected inside kramdown extension blocks
385        for line in &mut lines {
386            if line.in_kramdown_extension_block {
387                line.heading = None;
388            }
389        }
390
391        // Parse code spans early so we can exclude them from link/image parsing
392        let mut code_spans = profile_section!(
393            "Code spans",
394            profile,
395            element_parsers::build_code_spans_from_ranges(content, &lines, &code_span_ranges)
396        );
397
398        // Supplement code spans for MkDocs container content that pulldown-cmark missed.
399        // pulldown-cmark treats 4-space-indented MkDocs content as indented code blocks,
400        // so backtick code spans within admonitions/tabs/markdown HTML are invisible to it.
401        if flavor == MarkdownFlavor::MkDocs {
402            let extra = profile_section!(
403                "MkDocs code spans",
404                profile,
405                element_parsers::scan_mkdocs_container_code_spans(content, &lines, &code_span_ranges,)
406            );
407            if !extra.is_empty() {
408                code_spans.extend(extra);
409                code_spans.sort_by_key(|span| span.byte_offset);
410            }
411        }
412
413        // Supplement code spans for MDX JSX component body content that pulldown-cmark missed.
414        // pulldown-cmark treats JSX component opening tags (e.g. `<ParamField>`) as HTML block
415        // starters, so backtick code spans within component bodies are invisible to the initial
416        // parse.
417        if flavor == MarkdownFlavor::MDX {
418            let extra = profile_section!(
419                "MDX JSX code spans",
420                profile,
421                element_parsers::scan_jsx_block_code_spans(content, &lines, &code_span_ranges)
422            );
423            if !extra.is_empty() {
424                code_spans.extend(extra);
425                code_spans.sort_by_key(|span| span.byte_offset);
426            }
427        }
428
429        // Mark lines that are continuations of multi-line code spans
430        // This is needed for parse_list_blocks to correctly handle list items with multi-line code spans
431        for span in &code_spans {
432            if span.end_line > span.line {
433                // Mark lines after the first line as continuations
434                for line_num in (span.line + 1)..=span.end_line {
435                    if let Some(line_info) = lines.get_mut(line_num - 1) {
436                        line_info.in_code_span_continuation = true;
437                    }
438                }
439            }
440        }
441
442        // Finalize links and images: filter by code_spans and run regex fallbacks
443        let (links, images, broken_links, footnote_refs) = profile_section!(
444            "Links & images finalize",
445            profile,
446            link_parser::finalize_links_and_images(
447                content,
448                &lines,
449                &code_blocks,
450                &code_spans,
451                flavor,
452                &html_comment_ranges,
453                pulldown_result
454            )
455        );
456
457        let reference_defs = profile_section!(
458            "Reference defs",
459            profile,
460            link_parser::parse_reference_defs(content, &lines)
461        );
462
463        let list_blocks = profile_section!("List blocks", profile, list_blocks::parse_list_blocks(content, &lines));
464
465        // Compute character frequency for fast content analysis
466        let char_frequency = profile_section!(
467            "Char frequency",
468            profile,
469            line_computation::compute_char_frequency(content)
470        );
471
472        // Pre-compute table blocks for rules that need them (MD013, MD055, MD056, MD058, MD060)
473        let table_blocks = profile_section!(
474            "Table blocks",
475            profile,
476            crate::utils::table_utils::TableUtils::find_table_blocks_with_code_info(
477                content,
478                &code_blocks,
479                &code_spans,
480                &html_comment_ranges,
481            )
482        );
483
484        // Layer 2: Filter pre-computed collections to exclude items inside kramdown extension blocks.
485        // Rules that iterate these collections automatically skip kramdown content.
486        let links = links
487            .into_iter()
488            .filter(|link| !lines.get(link.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
489            .collect::<Vec<_>>();
490        let images = images
491            .into_iter()
492            .filter(|img| !lines.get(img.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
493            .collect::<Vec<_>>();
494        let broken_links = broken_links
495            .into_iter()
496            .filter(|bl| {
497                // BrokenLinkInfo has span but no line field; find line from byte offset
498                let line_idx = line_offsets
499                    .partition_point(|&offset| offset <= bl.span.start)
500                    .saturating_sub(1);
501                !lines.get(line_idx).is_some_and(|l| l.in_kramdown_extension_block)
502            })
503            .collect::<Vec<_>>();
504        let footnote_refs = footnote_refs
505            .into_iter()
506            .filter(|fr| !lines.get(fr.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
507            .collect::<Vec<_>>();
508        let reference_defs = reference_defs
509            .into_iter()
510            .filter(|def| !lines.get(def.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
511            .collect::<Vec<_>>();
512        let list_blocks = list_blocks
513            .into_iter()
514            .filter(|block| {
515                !lines
516                    .get(block.start_line - 1)
517                    .is_some_and(|l| l.in_kramdown_extension_block)
518            })
519            .collect::<Vec<_>>();
520        let table_blocks = table_blocks
521            .into_iter()
522            .filter(|block| {
523                // TableBlock.start_line is 0-indexed
524                !lines
525                    .get(block.start_line)
526                    .is_some_and(|l| l.in_kramdown_extension_block)
527            })
528            .collect::<Vec<_>>();
529        let emphasis_spans = emphasis_spans
530            .into_iter()
531            .filter(|span| !lines.get(span.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
532            .collect::<Vec<_>>();
533
534        // Rebuild reference_defs_map after filtering
535        let reference_defs_map: HashMap<String, usize> = reference_defs
536            .iter()
537            .enumerate()
538            .map(|(idx, def)| (def.id.to_lowercase(), idx))
539            .collect();
540
541        // Pre-compute sorted link title byte ranges for binary search
542        let link_title_ranges: Vec<(usize, usize)> = reference_defs
543            .iter()
544            .filter_map(|def| match (def.title_byte_start, def.title_byte_end) {
545                (Some(start), Some(end)) => Some((start, end)),
546                _ => None,
547            })
548            .collect();
549
550        // Reuse already-computed line_offsets and code_blocks instead of re-detecting
551        let line_index = profile_section!(
552            "Line index",
553            profile,
554            crate::utils::range_utils::LineIndex::with_line_starts_and_code_blocks(
555                content,
556                line_offsets.clone(),
557                &code_blocks,
558            )
559        );
560
561        // Pre-compute Jinja template ranges once for all rules (eliminates O(n*m) in MD011)
562        let jinja_ranges = profile_section!(
563            "Jinja ranges",
564            profile,
565            crate::utils::jinja_utils::find_jinja_ranges(content)
566        );
567
568        // Pre-compute Pandoc/Quarto citation ranges for Quarto flavor
569        let citation_ranges = profile_section!("Citation ranges", profile, {
570            if flavor == MarkdownFlavor::Quarto {
571                crate::utils::quarto_divs::find_citation_ranges(content)
572            } else {
573                Vec::new()
574            }
575        });
576
577        // Pre-compute Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
578        let shortcode_ranges = profile_section!("Shortcode ranges", profile, {
579            use crate::utils::regex_cache::HUGO_SHORTCODE_REGEX;
580            let mut ranges = Vec::new();
581            for mat in HUGO_SHORTCODE_REGEX.find_iter(content) {
582                ranges.push((mat.start(), mat.end()));
583            }
584            ranges
585        });
586
587        let inline_config = InlineConfig::from_content_with_code_blocks(content, &code_blocks);
588
589        Self {
590            content,
591            content_lines,
592            line_offsets,
593            code_blocks,
594            code_block_details,
595            strong_spans,
596            line_to_list,
597            list_start_values,
598            lines,
599            links,
600            images,
601            broken_links,
602            footnote_refs,
603            reference_defs,
604            reference_defs_map,
605            code_spans_cache: OnceLock::from(Arc::new(code_spans)),
606            math_spans_cache: OnceLock::new(), // Lazy-loaded on first access
607            list_blocks,
608            char_frequency,
609            html_tags_cache: OnceLock::new(),
610            emphasis_spans_cache: OnceLock::from(Arc::new(emphasis_spans)),
611            table_rows_cache: OnceLock::new(),
612            bare_urls_cache: OnceLock::new(),
613            has_mixed_list_nesting_cache: OnceLock::new(),
614            html_comment_ranges,
615            table_blocks,
616            line_index,
617            jinja_ranges,
618            flavor,
619            source_file,
620            jsx_expression_ranges,
621            mdx_comment_ranges,
622            citation_ranges,
623            shortcode_ranges,
624            link_title_ranges,
625            code_span_byte_ranges: code_span_ranges,
626            inline_config,
627            obsidian_comment_ranges,
628            lazy_cont_lines_cache: OnceLock::new(),
629        }
630    }
631
632    /// Binary search for whether `pos` falls inside any range in a sorted, non-overlapping
633    /// slice of `(start, end)` byte ranges. O(log n) instead of O(n).
634    #[inline]
635    fn binary_search_ranges(ranges: &[(usize, usize)], pos: usize) -> bool {
636        // Find the rightmost range whose start <= pos
637        let idx = ranges.partition_point(|&(start, _)| start <= pos);
638        // If idx == 0, no range starts at or before pos
639        idx > 0 && pos < ranges[idx - 1].1
640    }
641
642    /// Check if a byte position is within a code span. O(log n).
643    pub fn is_in_code_span_byte(&self, pos: usize) -> bool {
644        Self::binary_search_ranges(&self.code_span_byte_ranges, pos)
645    }
646
647    /// Check if `pos` is inside any link byte range. O(log n).
648    pub fn is_in_link(&self, pos: usize) -> bool {
649        let idx = self.links.partition_point(|link| link.byte_offset <= pos);
650        if idx > 0 && pos < self.links[idx - 1].byte_end {
651            return true;
652        }
653        let idx = self.images.partition_point(|img| img.byte_offset <= pos);
654        if idx > 0 && pos < self.images[idx - 1].byte_end {
655            return true;
656        }
657        self.is_in_reference_def(pos)
658    }
659
660    /// Get parsed inline configuration state.
661    pub fn inline_config(&self) -> &InlineConfig {
662        &self.inline_config
663    }
664
665    /// Get pre-split content lines, avoiding repeated `content.lines().collect()` allocations.
666    ///
667    /// Lines are 0-indexed (line 0 corresponds to line number 1 in the document).
668    pub fn raw_lines(&self) -> &[&'a str] {
669        &self.content_lines
670    }
671
672    /// Check if a rule is disabled at a specific line number (1-indexed)
673    ///
674    /// This method checks both persistent disable comments (<!-- rumdl-disable -->)
675    /// and line-specific comments (<!-- rumdl-disable-line -->, <!-- rumdl-disable-next-line -->).
676    pub fn is_rule_disabled(&self, rule_name: &str, line_number: usize) -> bool {
677        self.inline_config.is_rule_disabled(rule_name, line_number)
678    }
679
680    /// Get code spans - computed lazily on first access
681    pub fn code_spans(&self) -> Arc<Vec<CodeSpan>> {
682        Arc::clone(
683            self.code_spans_cache
684                .get_or_init(|| Arc::new(element_parsers::parse_code_spans(self.content, &self.lines))),
685        )
686    }
687
688    /// Get math spans - computed lazily on first access
689    pub fn math_spans(&self) -> Arc<Vec<MathSpan>> {
690        Arc::clone(
691            self.math_spans_cache
692                .get_or_init(|| Arc::new(element_parsers::parse_math_spans(self.content, &self.lines))),
693        )
694    }
695
696    /// Check if a byte position is within a math span (inline $...$ or display $$...$$)
697    pub fn is_in_math_span(&self, byte_pos: usize) -> bool {
698        let math_spans = self.math_spans();
699        // Binary search: find the last span whose byte_offset <= byte_pos
700        let idx = math_spans.partition_point(|span| span.byte_offset <= byte_pos);
701        idx > 0 && byte_pos < math_spans[idx - 1].byte_end
702    }
703
704    /// Get HTML comment ranges - pre-computed during LintContext construction
705    pub fn html_comment_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
706        &self.html_comment_ranges
707    }
708
709    /// Check if a byte position is inside an Obsidian comment
710    ///
711    /// Returns false for non-Obsidian flavors.
712    pub fn is_in_obsidian_comment(&self, byte_pos: usize) -> bool {
713        Self::binary_search_ranges(&self.obsidian_comment_ranges, byte_pos)
714    }
715
716    /// Check if a line/column position is inside an Obsidian comment
717    ///
718    /// Line number is 1-indexed, column is 1-indexed.
719    /// Returns false for non-Obsidian flavors.
720    pub fn is_position_in_obsidian_comment(&self, line_num: usize, col: usize) -> bool {
721        if self.obsidian_comment_ranges.is_empty() {
722            return false;
723        }
724
725        // Convert line/column (1-indexed, char-based) to byte position
726        let byte_pos = self.line_index.line_col_to_byte_range(line_num, col).start;
727        self.is_in_obsidian_comment(byte_pos)
728    }
729
730    /// Get HTML tags - computed lazily on first access
731    pub fn html_tags(&self) -> Arc<Vec<HtmlTag>> {
732        Arc::clone(self.html_tags_cache.get_or_init(|| {
733            let tags = element_parsers::parse_html_tags(self.content, &self.lines, &self.code_blocks, self.flavor);
734            // Filter out HTML tags inside kramdown extension blocks
735            Arc::new(
736                tags.into_iter()
737                    .filter(|tag| {
738                        !self
739                            .lines
740                            .get(tag.line - 1)
741                            .is_some_and(|l| l.in_kramdown_extension_block)
742                    })
743                    .collect(),
744            )
745        }))
746    }
747
748    /// Get emphasis spans - pre-computed during construction
749    pub fn emphasis_spans(&self) -> Arc<Vec<EmphasisSpan>> {
750        Arc::clone(
751            self.emphasis_spans_cache
752                .get()
753                .expect("emphasis_spans_cache initialized during construction"),
754        )
755    }
756
757    /// Get table rows - computed lazily on first access
758    pub fn table_rows(&self) -> Arc<Vec<TableRow>> {
759        Arc::clone(
760            self.table_rows_cache
761                .get_or_init(|| Arc::new(element_parsers::parse_table_rows(self.content, &self.lines))),
762        )
763    }
764
765    /// Get bare URLs - computed lazily on first access
766    pub fn bare_urls(&self) -> Arc<Vec<BareUrl>> {
767        Arc::clone(self.bare_urls_cache.get_or_init(|| {
768            Arc::new(element_parsers::parse_bare_urls(
769                self.content,
770                &self.lines,
771                &self.code_blocks,
772            ))
773        }))
774    }
775
776    /// Get lazy continuation lines - computed lazily on first access
777    pub fn lazy_continuation_lines(&self) -> Arc<Vec<LazyContLine>> {
778        Arc::clone(self.lazy_cont_lines_cache.get_or_init(|| {
779            Arc::new(element_parsers::detect_lazy_continuation_lines(
780                self.content,
781                &self.lines,
782                &self.line_offsets,
783            ))
784        }))
785    }
786
787    /// Check if document has mixed ordered/unordered list nesting.
788    /// Result is cached after first computation (document-level invariant).
789    /// This is used by MD007 for smart style auto-detection.
790    pub fn has_mixed_list_nesting(&self) -> bool {
791        *self
792            .has_mixed_list_nesting_cache
793            .get_or_init(|| self.compute_mixed_list_nesting())
794    }
795
796    /// Internal computation for mixed list nesting (only called once per LintContext).
797    fn compute_mixed_list_nesting(&self) -> bool {
798        // Track parent list items by their marker position and type
799        // Using marker_column instead of indent because it works correctly
800        // for blockquoted content where indent doesn't account for the prefix
801        // Stack stores: (marker_column, is_ordered)
802        let mut stack: Vec<(usize, bool)> = Vec::new();
803        let mut last_was_blank = false;
804
805        for line_info in &self.lines {
806            // Skip non-content lines (code blocks, frontmatter, HTML comments, etc.)
807            if line_info.in_code_block
808                || line_info.in_front_matter
809                || line_info.in_mkdocstrings
810                || line_info.in_html_comment
811                || line_info.in_mdx_comment
812                || line_info.in_esm_block
813            {
814                continue;
815            }
816
817            // OPTIMIZATION: Use pre-computed is_blank instead of content().trim()
818            if line_info.is_blank {
819                last_was_blank = true;
820                continue;
821            }
822
823            if let Some(list_item) = &line_info.list_item {
824                // Normalize column 1 to column 0 (consistent with MD007 check function)
825                let current_pos = if list_item.marker_column == 1 {
826                    0
827                } else {
828                    list_item.marker_column
829                };
830
831                // If there was a blank line and this item is at root level, reset stack
832                if last_was_blank && current_pos == 0 {
833                    stack.clear();
834                }
835                last_was_blank = false;
836
837                // Pop items at same or greater position (they're siblings or deeper, not parents)
838                while let Some(&(pos, _)) = stack.last() {
839                    if pos >= current_pos {
840                        stack.pop();
841                    } else {
842                        break;
843                    }
844                }
845
846                // Check if immediate parent has different type - this is mixed nesting
847                if let Some(&(_, parent_is_ordered)) = stack.last()
848                    && parent_is_ordered != list_item.is_ordered
849                {
850                    return true; // Found mixed nesting - early exit
851                }
852
853                stack.push((current_pos, list_item.is_ordered));
854            } else {
855                // Non-list line (but not blank) - could be paragraph or other content
856                last_was_blank = false;
857            }
858        }
859
860        false
861    }
862
863    /// Map a byte offset to (line, column)
864    pub fn offset_to_line_col(&self, offset: usize) -> (usize, usize) {
865        match self.line_offsets.binary_search(&offset) {
866            Ok(line) => (line + 1, 1),
867            Err(line) => {
868                let line_start = self.line_offsets.get(line.wrapping_sub(1)).copied().unwrap_or(0);
869                (line, offset - line_start + 1)
870            }
871        }
872    }
873
874    /// Check if a position is within a code block or code span. O(log n).
875    pub fn is_in_code_block_or_span(&self, pos: usize) -> bool {
876        // Check code blocks first (already uses binary search internally)
877        if CodeBlockUtils::is_in_code_block_or_span(&self.code_blocks, pos) {
878            return true;
879        }
880
881        // Check inline code spans via binary search
882        self.is_byte_offset_in_code_span(pos)
883    }
884
885    /// Get line information by line number (1-indexed)
886    pub fn line_info(&self, line_num: usize) -> Option<&LineInfo> {
887        if line_num > 0 {
888            self.lines.get(line_num - 1)
889        } else {
890            None
891        }
892    }
893
894    /// Get URL for a reference link/image by its ID (O(1) lookup via HashMap)
895    pub fn get_reference_url(&self, ref_id: &str) -> Option<&str> {
896        let normalized_id = ref_id.to_lowercase();
897        self.reference_defs_map
898            .get(&normalized_id)
899            .map(|&idx| self.reference_defs[idx].url.as_str())
900    }
901
902    /// Check if a line is part of a list block
903    pub fn is_in_list_block(&self, line_num: usize) -> bool {
904        self.list_blocks
905            .iter()
906            .any(|block| line_num >= block.start_line && line_num <= block.end_line)
907    }
908
909    /// Check if a line is within an HTML block
910    pub fn is_in_html_block(&self, line_num: usize) -> bool {
911        if line_num == 0 || line_num > self.lines.len() {
912            return false;
913        }
914        self.lines[line_num - 1].in_html_block
915    }
916
917    /// Check if a line and column is within a code span
918    pub fn is_in_code_span(&self, line_num: usize, col: usize) -> bool {
919        if line_num == 0 || line_num > self.lines.len() {
920            return false;
921        }
922
923        // Use the code spans cache to check
924        // Note: col is 1-indexed from caller, but span.start_col and span.end_col are 0-indexed
925        // Convert col to 0-indexed for comparison
926        let col_0indexed = if col > 0 { col - 1 } else { 0 };
927        let code_spans = self.code_spans();
928        code_spans.iter().any(|span| {
929            // Check if line is within the span's line range
930            if line_num < span.line || line_num > span.end_line {
931                return false;
932            }
933
934            if span.line == span.end_line {
935                // Single-line span: check column bounds
936                col_0indexed >= span.start_col && col_0indexed < span.end_col
937            } else if line_num == span.line {
938                // First line of multi-line span: anything after start_col is in span
939                col_0indexed >= span.start_col
940            } else if line_num == span.end_line {
941                // Last line of multi-line span: anything before end_col is in span
942                col_0indexed < span.end_col
943            } else {
944                // Middle line of multi-line span: entire line is in span
945                true
946            }
947        })
948    }
949
950    /// Check if a byte offset is within a code span. O(log n).
951    #[inline]
952    pub fn is_byte_offset_in_code_span(&self, byte_offset: usize) -> bool {
953        let code_spans = self.code_spans();
954        let idx = code_spans.partition_point(|span| span.byte_offset <= byte_offset);
955        idx > 0 && byte_offset < code_spans[idx - 1].byte_end
956    }
957
958    /// Check if a byte position is within a reference definition. O(log n).
959    #[inline]
960    pub fn is_in_reference_def(&self, byte_pos: usize) -> bool {
961        let idx = self.reference_defs.partition_point(|rd| rd.byte_offset <= byte_pos);
962        idx > 0 && byte_pos < self.reference_defs[idx - 1].byte_end
963    }
964
965    /// Check if a byte position is within an HTML comment. O(log n).
966    #[inline]
967    pub fn is_in_html_comment(&self, byte_pos: usize) -> bool {
968        let idx = self.html_comment_ranges.partition_point(|r| r.start <= byte_pos);
969        idx > 0 && byte_pos < self.html_comment_ranges[idx - 1].end
970    }
971
972    /// Check if a byte position is within an HTML tag (including multiline tags).
973    /// Uses the pre-parsed html_tags which correctly handles tags spanning multiple lines. O(log n).
974    #[inline]
975    pub fn is_in_html_tag(&self, byte_pos: usize) -> bool {
976        let tags = self.html_tags();
977        let idx = tags.partition_point(|tag| tag.byte_offset <= byte_pos);
978        idx > 0 && byte_pos < tags[idx - 1].byte_end
979    }
980
981    /// Check if a byte position is within a Jinja template ({{ }} or {% %}). O(log n).
982    pub fn is_in_jinja_range(&self, byte_pos: usize) -> bool {
983        Self::binary_search_ranges(&self.jinja_ranges, byte_pos)
984    }
985
986    /// Check if a byte position is within a JSX expression (MDX: {expression}). O(log n).
987    #[inline]
988    pub fn is_in_jsx_expression(&self, byte_pos: usize) -> bool {
989        Self::binary_search_ranges(&self.jsx_expression_ranges, byte_pos)
990    }
991
992    /// Check if a byte position is within an MDX comment ({/* ... */}). O(log n).
993    #[inline]
994    pub fn is_in_mdx_comment(&self, byte_pos: usize) -> bool {
995        Self::binary_search_ranges(&self.mdx_comment_ranges, byte_pos)
996    }
997
998    /// Check if a byte position is within a Pandoc/Quarto citation (`@key` or `[@key]`).
999    /// Only active in Quarto flavor. O(log n).
1000    #[inline]
1001    pub fn is_in_citation(&self, byte_pos: usize) -> bool {
1002        let idx = self.citation_ranges.partition_point(|r| r.start <= byte_pos);
1003        idx > 0 && byte_pos < self.citation_ranges[idx - 1].end
1004    }
1005
1006    /// Pre-computed Pandoc/Quarto citation ranges.
1007    #[inline]
1008    pub fn citation_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
1009        &self.citation_ranges
1010    }
1011
1012    /// Check if a byte position is within a Hugo/Quarto shortcode ({{< ... >}} or {{% ... %}}). O(log n).
1013    #[inline]
1014    pub fn is_in_shortcode(&self, byte_pos: usize) -> bool {
1015        Self::binary_search_ranges(&self.shortcode_ranges, byte_pos)
1016    }
1017
1018    /// Pre-computed Hugo/Quarto shortcode ranges.
1019    #[inline]
1020    pub fn shortcode_ranges(&self) -> &[(usize, usize)] {
1021        &self.shortcode_ranges
1022    }
1023
1024    /// Check if a byte position is within a link reference definition title. O(log n).
1025    pub fn is_in_link_title(&self, byte_pos: usize) -> bool {
1026        Self::binary_search_ranges(&self.link_title_ranges, byte_pos)
1027    }
1028
1029    /// Check if content has any instances of a specific character (fast)
1030    pub fn has_char(&self, ch: char) -> bool {
1031        match ch {
1032            '#' => self.char_frequency.hash_count > 0,
1033            '*' => self.char_frequency.asterisk_count > 0,
1034            '_' => self.char_frequency.underscore_count > 0,
1035            '-' => self.char_frequency.hyphen_count > 0,
1036            '+' => self.char_frequency.plus_count > 0,
1037            '>' => self.char_frequency.gt_count > 0,
1038            '|' => self.char_frequency.pipe_count > 0,
1039            '[' => self.char_frequency.bracket_count > 0,
1040            '`' => self.char_frequency.backtick_count > 0,
1041            '<' => self.char_frequency.lt_count > 0,
1042            '!' => self.char_frequency.exclamation_count > 0,
1043            '\n' => self.char_frequency.newline_count > 0,
1044            _ => self.content.contains(ch), // Fallback for other characters
1045        }
1046    }
1047
1048    /// Get count of a specific character (fast)
1049    pub fn char_count(&self, ch: char) -> usize {
1050        match ch {
1051            '#' => self.char_frequency.hash_count,
1052            '*' => self.char_frequency.asterisk_count,
1053            '_' => self.char_frequency.underscore_count,
1054            '-' => self.char_frequency.hyphen_count,
1055            '+' => self.char_frequency.plus_count,
1056            '>' => self.char_frequency.gt_count,
1057            '|' => self.char_frequency.pipe_count,
1058            '[' => self.char_frequency.bracket_count,
1059            '`' => self.char_frequency.backtick_count,
1060            '<' => self.char_frequency.lt_count,
1061            '!' => self.char_frequency.exclamation_count,
1062            '\n' => self.char_frequency.newline_count,
1063            _ => self.content.matches(ch).count(), // Fallback for other characters
1064        }
1065    }
1066
1067    /// Check if content likely contains headings (fast)
1068    pub fn likely_has_headings(&self) -> bool {
1069        self.char_frequency.hash_count > 0 || self.char_frequency.hyphen_count > 2 || self.content.contains('=') // Setext H1 underlines use '='
1070    }
1071
1072    /// Check if content likely contains lists (fast)
1073    pub fn likely_has_lists(&self) -> bool {
1074        self.char_frequency.asterisk_count > 0
1075            || self.char_frequency.hyphen_count > 0
1076            || self.char_frequency.plus_count > 0
1077    }
1078
1079    /// Check if content likely contains emphasis (fast)
1080    pub fn likely_has_emphasis(&self) -> bool {
1081        self.char_frequency.asterisk_count > 1 || self.char_frequency.underscore_count > 1
1082    }
1083
1084    /// Check if content likely contains tables (fast)
1085    pub fn likely_has_tables(&self) -> bool {
1086        self.char_frequency.pipe_count > 2
1087    }
1088
1089    /// Check if content likely contains blockquotes (fast)
1090    pub fn likely_has_blockquotes(&self) -> bool {
1091        self.char_frequency.gt_count > 0
1092    }
1093
1094    /// Check if content likely contains code (fast)
1095    pub fn likely_has_code(&self) -> bool {
1096        self.char_frequency.backtick_count > 0
1097    }
1098
1099    /// Check if content likely contains links or images (fast)
1100    pub fn likely_has_links_or_images(&self) -> bool {
1101        self.char_frequency.bracket_count > 0 || self.char_frequency.exclamation_count > 0
1102    }
1103
1104    /// Check if content likely contains HTML (fast)
1105    pub fn likely_has_html(&self) -> bool {
1106        self.char_frequency.lt_count > 0
1107    }
1108
1109    /// Get the blockquote prefix for inserting a blank line at the given line index.
1110    /// Returns the prefix without trailing content (e.g., ">" or ">>").
1111    /// This is needed because blank lines inside blockquotes must preserve the blockquote structure.
1112    /// Returns an empty string if the line is not inside a blockquote.
1113    pub fn blockquote_prefix_for_blank_line(&self, line_idx: usize) -> String {
1114        if let Some(line_info) = self.lines.get(line_idx)
1115            && let Some(ref bq) = line_info.blockquote
1116        {
1117            bq.prefix.trim_end().to_string()
1118        } else {
1119            String::new()
1120        }
1121    }
1122
1123    /// Find the line index for a given byte offset using binary search.
1124    /// Returns (line_index, line_number, column) where:
1125    /// - line_index is the 0-based index in the lines array
1126    /// - line_number is the 1-based line number
1127    /// - column is the byte offset within that line
1128    #[inline]
1129    fn find_line_for_offset(lines: &[LineInfo], byte_offset: usize) -> (usize, usize, usize) {
1130        // Binary search to find the line containing this byte offset
1131        let idx = match lines.binary_search_by(|line| {
1132            if byte_offset < line.byte_offset {
1133                std::cmp::Ordering::Greater
1134            } else if byte_offset > line.byte_offset + line.byte_len {
1135                std::cmp::Ordering::Less
1136            } else {
1137                std::cmp::Ordering::Equal
1138            }
1139        }) {
1140            Ok(idx) => idx,
1141            Err(idx) => idx.saturating_sub(1),
1142        };
1143
1144        let line = &lines[idx];
1145        let line_num = idx + 1;
1146        let col = byte_offset.saturating_sub(line.byte_offset);
1147
1148        (idx, line_num, col)
1149    }
1150
1151    /// Check if a byte offset is within a code span using binary search
1152    #[inline]
1153    fn is_offset_in_code_span(code_spans: &[CodeSpan], offset: usize) -> bool {
1154        // Since spans are sorted by byte_offset, use partition_point for binary search
1155        let idx = code_spans.partition_point(|span| span.byte_offset <= offset);
1156
1157        // Check the span that starts at or before our offset
1158        if idx > 0 {
1159            let span = &code_spans[idx - 1];
1160            if offset >= span.byte_offset && offset < span.byte_end {
1161                return true;
1162            }
1163        }
1164
1165        false
1166    }
1167
1168    /// Get an iterator over valid headings (skipping invalid ones like `#NoSpace`)
1169    ///
1170    /// Valid headings have proper spacing after the `#` markers (or are level > 1).
1171    /// This is the standard iterator for rules that need to process headings.
1172    ///
1173    /// # Examples
1174    ///
1175    /// ```
1176    /// use rumdl_lib::lint_context::LintContext;
1177    /// use rumdl_lib::config::MarkdownFlavor;
1178    ///
1179    /// let content = "# Valid Heading\n#NoSpace\n## Another Valid";
1180    /// let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1181    ///
1182    /// for heading in ctx.valid_headings() {
1183    ///     println!("Line {}: {} (level {})", heading.line_num, heading.heading.text, heading.heading.level);
1184    /// }
1185    /// // Only prints valid headings, skips `#NoSpace`
1186    /// ```
1187    #[must_use]
1188    pub fn valid_headings(&self) -> ValidHeadingsIter<'_> {
1189        ValidHeadingsIter::new(&self.lines)
1190    }
1191
1192    /// Check if the document contains any valid CommonMark headings
1193    ///
1194    /// Returns `true` if there is at least one heading with proper space after `#`.
1195    #[must_use]
1196    pub fn has_valid_headings(&self) -> bool {
1197        self.lines
1198            .iter()
1199            .any(|line| line.heading.as_ref().is_some_and(|h| h.is_valid))
1200    }
1201}
1202
1203/// Detect footnote definitions and mark their continuation lines.
1204///
1205/// Uses pulldown-cmark to find footnote definition ranges and fenced code
1206/// blocks within them, then:
1207/// 1. Sets `in_footnote_definition = true` on all lines within
1208/// 2. Clears `in_code_block = false` on continuation lines that were
1209///    misidentified as indented code blocks (but preserves real fenced
1210///    code blocks within footnotes)
1211fn detect_footnote_definitions(content: &str, lines: &mut [types::LineInfo], line_offsets: &[usize]) {
1212    use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag, TagEnd};
1213
1214    let options = crate::utils::rumdl_parser_options();
1215    let parser = Parser::new_ext(content, options).into_offset_iter();
1216
1217    // Collect footnote ranges and fenced code block ranges within them
1218    let mut footnote_ranges: Vec<(usize, usize)> = Vec::new();
1219    let mut fenced_code_ranges: Vec<(usize, usize)> = Vec::new();
1220    let mut in_footnote = false;
1221
1222    for (event, range) in parser {
1223        match event {
1224            Event::Start(Tag::FootnoteDefinition(_)) => {
1225                in_footnote = true;
1226                footnote_ranges.push((range.start, range.end));
1227            }
1228            Event::End(TagEnd::FootnoteDefinition) => {
1229                in_footnote = false;
1230            }
1231            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(_))) if in_footnote => {
1232                fenced_code_ranges.push((range.start, range.end));
1233            }
1234            _ => {}
1235        }
1236    }
1237
1238    let byte_to_line = |byte_offset: usize| -> usize {
1239        line_offsets
1240            .partition_point(|&offset| offset <= byte_offset)
1241            .saturating_sub(1)
1242    };
1243
1244    // Mark footnote definition lines
1245    for &(start, end) in &footnote_ranges {
1246        let start_line = byte_to_line(start);
1247        let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
1248
1249        for line in &mut lines[start_line..end_line] {
1250            line.in_footnote_definition = true;
1251            line.in_code_block = false;
1252        }
1253    }
1254
1255    // Restore in_code_block for fenced code blocks within footnotes
1256    for &(start, end) in &fenced_code_ranges {
1257        let start_line = byte_to_line(start);
1258        let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
1259
1260        for line in &mut lines[start_line..end_line] {
1261            line.in_code_block = true;
1262        }
1263    }
1264}