Skip to main content

rumdl_lib/lint_context/
mod.rs

1pub mod types;
2pub(crate) use heading_detection::is_paragraph_text_line;
3pub(crate) use link_parser::{image_pattern, link_pattern};
4pub use types::*;
5
6mod element_parsers;
7mod flavor_detection;
8mod heading_detection;
9mod line_computation;
10mod link_parser;
11mod list_blocks;
12mod mdx;
13#[cfg(test)]
14mod tests;
15
16use crate::config::MarkdownFlavor;
17use crate::inline_config::InlineConfig;
18use crate::rules::front_matter_utils::FrontMatterUtils;
19use crate::utils::code_block_utils::{CodeBlockDetail, CodeBlockUtils};
20use crate::utils::range_utils::byte_to_char_count;
21use std::collections::HashMap;
22use std::ops::Range;
23use std::path::{Path, PathBuf};
24
25/// Run-scoped document paths that filesystem-aware link rules should treat as
26/// present even when their content did not come from disk.
27#[derive(Debug, Clone)]
28pub struct LinkTargetPolicy {
29    supplied_paths: Arc<std::collections::HashSet<PathBuf>>,
30    allow_disk_fallback: bool,
31}
32
33impl LinkTargetPolicy {
34    /// Supplied documents override disk, while targets outside the supplied set
35    /// continue to use normal filesystem resolution.
36    pub fn open_world<I, P>(paths: I) -> Self
37    where
38        I: IntoIterator<Item = P>,
39        P: AsRef<Path>,
40    {
41        Self::from_paths(paths, true)
42    }
43
44    /// Only supplied documents are valid relative link targets.
45    pub fn closed_world<I, P>(paths: I) -> Self
46    where
47        I: IntoIterator<Item = P>,
48        P: AsRef<Path>,
49    {
50        Self::from_paths(paths, false)
51    }
52
53    fn from_paths<I, P>(paths: I, allow_disk_fallback: bool) -> Self
54    where
55        I: IntoIterator<Item = P>,
56        P: AsRef<Path>,
57    {
58        let mut roots = Vec::new();
59        if let Ok(cwd) = std::env::current_dir() {
60            if let Ok(canonical_cwd) = cwd.canonicalize()
61                && canonical_cwd != cwd
62            {
63                roots.push(canonical_cwd);
64            }
65            roots.push(cwd);
66        }
67        Self::from_paths_with_roots(paths, allow_disk_fallback, roots)
68    }
69
70    fn from_paths_with_roots<I, P, R, Q>(paths: I, allow_disk_fallback: bool, roots: R) -> Self
71    where
72        I: IntoIterator<Item = P>,
73        P: AsRef<Path>,
74        R: IntoIterator<Item = Q>,
75        Q: AsRef<Path>,
76    {
77        let roots: Vec<PathBuf> = roots
78            .into_iter()
79            .map(|root| crate::workspace_index::normalize_relative_path(root.as_ref()))
80            .collect();
81        let mut supplied_paths = std::collections::HashSet::new();
82        for path in paths {
83            let path = path.as_ref();
84            supplied_paths.insert(crate::workspace_index::normalize_relative_path(path));
85
86            if path.is_relative() {
87                for root in &roots {
88                    supplied_paths.insert(crate::workspace_index::normalize_relative_path(&root.join(path)));
89                }
90            } else {
91                for source_root in &roots {
92                    if let Ok(relative) = path.strip_prefix(source_root) {
93                        for root in &roots {
94                            supplied_paths
95                                .insert(crate::workspace_index::normalize_relative_path(&root.join(relative)));
96                        }
97                    }
98                }
99            }
100        }
101        Self {
102            supplied_paths: Arc::new(supplied_paths),
103            allow_disk_fallback,
104        }
105    }
106
107    pub fn contains(&self, path: &Path) -> bool {
108        self.supplied_paths
109            .contains(&crate::workspace_index::normalize_relative_path(path))
110    }
111
112    pub(crate) fn resolve_supplied(&self, path: &Path) -> Option<PathBuf> {
113        let normalized = crate::workspace_index::normalize_relative_path(path);
114        if self.supplied_paths.contains(&normalized) {
115            return Some(normalized);
116        }
117
118        if path.extension().is_none() {
119            for extension in ["md", "markdown", "mdx", "mkd", "mkdn", "mdown", "mdwn", "qmd", "rmd"] {
120                let candidate = crate::workspace_index::normalize_relative_path(&path.with_extension(extension));
121                if self.supplied_paths.contains(&candidate) {
122                    return Some(candidate);
123                }
124            }
125        }
126
127        None
128    }
129
130    pub fn contains_with_markdown_extension(&self, path: &Path) -> bool {
131        self.resolve_supplied(path).is_some()
132    }
133
134    pub fn allow_disk_fallback(&self) -> bool {
135        self.allow_disk_fallback
136    }
137}
138
139/// Macro for profiling sections - only active in non-WASM builds
140#[cfg(not(target_arch = "wasm32"))]
141macro_rules! profile_section {
142    ($name:expr, $profile:expr, $code:expr) => {{
143        let start = std::time::Instant::now();
144        let result = $code;
145        if $profile {
146            eprintln!("[PROFILE] {}: {:?}", $name, start.elapsed());
147        }
148        result
149    }};
150}
151
152fn build_commonmark_ordered_lists(
153    lines: &[LineInfo],
154    line_to_list: &crate::utils::code_block_utils::LineToListMap,
155    list_start_values: &crate::utils::code_block_utils::ListStartValues,
156) -> Vec<CommonMarkOrderedListInfo> {
157    let mut grouped_lines: HashMap<usize, Vec<usize>> = HashMap::new();
158
159    for (&line_num, &list_id) in line_to_list {
160        let is_ordered_item = line_num
161            .checked_sub(1)
162            .and_then(|index| lines.get(index))
163            .and_then(|line| line.list_item.as_deref())
164            .is_some_and(|item| item.is_ordered);
165        if is_ordered_item {
166            grouped_lines.entry(list_id).or_default().push(line_num);
167        }
168    }
169
170    let mut lists: Vec<_> = grouped_lines
171        .into_iter()
172        .map(|(list_id, mut item_lines)| {
173            item_lines.sort_unstable();
174            CommonMarkOrderedListInfo {
175                start_value: list_start_values.get(&list_id).copied().unwrap_or(1),
176                item_lines,
177            }
178        })
179        .collect();
180    lists.sort_by_key(|list| list.item_lines.first().copied().unwrap_or(0));
181    lists
182}
183
184#[cfg(target_arch = "wasm32")]
185macro_rules! profile_section {
186    ($name:expr, $profile:expr, $code:expr) => {{ $code }};
187}
188
189/// Grouped byte ranges for skip context detection
190/// Used to reduce parameter count in internal functions
191pub(super) struct SkipByteRanges<'a> {
192    pub(super) html_comment_ranges: &'a [crate::utils::skip_context::ByteRange],
193    pub(super) autodoc_ranges: &'a [crate::utils::skip_context::ByteRange],
194    pub(super) pandoc_div_ranges: &'a [crate::utils::skip_context::ByteRange],
195    pub(super) pymdown_block_ranges: &'a [crate::utils::skip_context::ByteRange],
196}
197
198use std::sync::{Arc, OnceLock};
199
200/// Map from line byte offset to list item data: (is_ordered, marker, marker_column, content_column, number)
201pub(super) type ListItemMap = std::collections::HashMap<usize, (bool, String, usize, usize, Option<usize>)>;
202
203/// Type alias for byte ranges used in JSX expression and MDX comment detection
204pub(super) type ByteRanges = Vec<(usize, usize)>;
205
206pub struct LintContext<'a> {
207    pub content: &'a str,
208    content_lines: Vec<&'a str>, // Pre-split lines from content (avoids repeated allocations)
209    pub line_offsets: Vec<usize>,
210    pub code_blocks: Vec<(usize, usize)>, // Cached code block ranges (not including inline code spans)
211    pub code_block_details: Vec<CodeBlockDetail>, // Per-block metadata (fenced/indented, info string)
212    pub strong_spans: Vec<crate::utils::code_block_utils::StrongSpanDetail>, // Pre-computed strong emphasis spans
213    line_to_list: crate::utils::code_block_utils::LineToListMap, // Private CommonMark membership input
214    list_start_values: crate::utils::code_block_utils::ListStartValues, // Private CommonMark start-value input
215    commonmark_ordered_lists_cache: OnceLock<Vec<CommonMarkOrderedListInfo>>, // Lazy source-ordered view
216    pub lines: Vec<LineInfo>,             // Pre-computed line information
217    blockquote_headings: Vec<Option<Box<HeadingInfo>>>, // Container headings, parallel to `lines`
218    links: Vec<ParsedLink<'a>>,           // Pre-parsed links
219    images: Vec<ParsedImage<'a>>,         // Pre-parsed images
220    broken_links: Vec<BrokenLinkInfo>,    // Broken/undefined references
221    footnote_refs: Vec<FootnoteRef>,      // Pre-parsed footnote references
222    reference_defs: Vec<ReferenceDef>,    // Reference definitions
223    reference_defs_map: HashMap<String, usize>, // O(1) lookup by lowercase ID -> index in reference_defs
224    code_spans_cache: OnceLock<Arc<Vec<CodeSpan>>>, // Lazy-loaded inline code spans
225    math_spans_cache: OnceLock<Arc<Vec<MathSpan>>>, // Lazy-loaded math spans ($...$ and $$...$$)
226    math_byte_ranges_cache: OnceLock<Vec<(usize, usize)>>, // Lazy-loaded math byte ranges for is_in_math_context
227    pub list_blocks: Vec<ListBlock>,      // Pre-parsed list blocks
228    pub char_frequency: CharFrequency,    // Character frequency analysis
229    html_tags_cache: OnceLock<Arc<Vec<HtmlTag>>>, // Lazy-loaded HTML tags
230    jsx_component_tags_cache: OnceLock<Arc<Vec<HtmlTag>>>, // Lazy-loaded JSX component tags (shares the html_tags parse)
231    emphasis_spans_cache: OnceLock<Arc<Vec<EmphasisSpan>>>, // Lazy-loaded emphasis spans
232    bare_urls_cache: OnceLock<Arc<Vec<BareUrl>>>,          // Lazy-loaded bare URLs
233    has_mixed_list_nesting_cache: OnceLock<bool>, // Cached result for mixed ordered/unordered list nesting detection
234    html_comment_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed HTML comment ranges
235    pub table_blocks: Vec<crate::utils::table_utils::TableBlock>, // Pre-computed table blocks
236    line_index: crate::utils::range_utils::LineIndex<'a>, // Pre-computed source-location index
237    jinja_ranges: Vec<(usize, usize)>,            // Pre-computed Jinja template ranges ({{ }}, {% %})
238    pub flavor: MarkdownFlavor,                   // Markdown flavor being used
239    source_file: Option<PathBuf>,                 // Source file path (capability exposed through `source_file()`)
240    link_target_policy: Option<LinkTargetPolicy>, // Run-scoped virtual link targets
241    jsx_expression_ranges: Vec<(usize, usize)>,   // Pre-computed JSX expression ranges (MDX: {expression})
242    mdx_comment_ranges: Vec<(usize, usize)>,      // Pre-computed MDX comment ranges ({/* ... */})
243    citation_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc/Quarto citation ranges (@key, [@key])
244    pandoc_div_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc/Quarto div block ranges (::: ... :::)
245    colon_fence_details: Vec<CodeBlockDetail>, // Pre-computed Azure DevOps colon code fences (:::lang ... :::)
246    inline_footnote_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc inline footnote ranges (^[...])
247    pandoc_header_slugs: std::collections::HashSet<String>, // Pre-computed Pandoc implicit header reference slugs
248    example_list_marker_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc example-list marker ranges (@) / (@label)
249    example_reference_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc example reference ranges (@label) inline
250    sub_super_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc subscript (~x~) and superscript (^x^) ranges
251    inline_code_attr_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc inline code attribute ranges (`code`{.lang})
252    bracketed_span_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc bracketed span ranges ([text]{attrs})
253    line_block_ranges: Vec<crate::utils::skip_context::ByteRange>,     // Pre-computed Pandoc line block ranges (| text)
254    pipe_table_caption_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc pipe-table caption ranges (: caption)
255    pandoc_metadata_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc YAML metadata block ranges (--- ... --- or ...)
256    grid_table_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc grid-table ranges (+---+---+)
257    multi_line_table_ranges: Vec<crate::utils::skip_context::ByteRange>, // Pre-computed Pandoc multi-line table ranges
258    shortcode_ranges: Vec<(usize, usize)>, // Pre-computed Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
259    link_title_ranges: Vec<(usize, usize)>, // Pre-computed sorted link title byte ranges
260    code_span_byte_ranges: Vec<(usize, usize)>, // Pre-computed code span byte ranges from pulldown-cmark
261    inline_config: InlineConfig,           // Parsed inline configuration comments for rule disabling
262    obsidian_comment_ranges: Vec<(usize, usize)>, // Pre-computed Obsidian comment ranges (%%...%%)
263    unterminated_html_comment: Option<usize>, // Byte offset of a `<!--` with no `-->`
264    unterminated_obsidian_comment: Option<usize>, // Byte offset of a `%%` with no closing `%%`
265    lazy_cont_lines_cache: OnceLock<Arc<Vec<LazyContLine>>>, // Lazy-loaded lazy continuation lines
266    myst_directive_ranges: Vec<(usize, usize)>, // Pre-computed MyST colon directive byte ranges (:::{name} ... :::)
267    myst_comment_ranges: Vec<(usize, usize)>, // Pre-computed MyST comment byte ranges (% comment)
268    myst_role_ranges: Vec<(usize, usize)>, // Pre-computed MyST role byte ranges ({role}`content`)
269    front_matter_end: usize,               // 1-indexed line where front matter ends, 0 if none
270}
271
272/// The two kinds of byte range a document holds as code.
273pub struct CodeRanges {
274    /// Fenced and indented code block ranges
275    pub blocks: Vec<(usize, usize)>,
276    /// Inline code span ranges, backticks included
277    pub spans: Vec<(usize, usize)>,
278}
279
280/// The byte ranges this document's flavor really holds as code.
281///
282/// An inline directive written inside one of these configures nothing, so there
283/// is nothing to report about it. The answer is read off a full context rather
284/// than scanned out of the text, which is what keeps it identical to the one
285/// `InlineConfig` was built from: a MkDocs admonition body is indented but is
286/// structure, and a scan of the text alone reads it as an indented code block.
287///
288/// Building a context costs a parse, so callers filter with it only once they
289/// hold something to filter, and both kinds come back from the one parse.
290pub fn code_ranges(content: &str, flavor: MarkdownFlavor) -> CodeRanges {
291    let ctx = LintContext::new(content, flavor, None);
292    CodeRanges {
293        spans: code_span_byte_ranges(&ctx.code_spans()),
294        blocks: ctx.code_blocks,
295    }
296}
297
298/// The byte ranges of parsed code spans, as the plain pairs inline config works in.
299pub fn code_span_byte_ranges(code_spans: &[CodeSpan]) -> Vec<(usize, usize)> {
300    code_spans
301        .iter()
302        .map(|span| (span.byte_offset, span.byte_end))
303        .collect()
304}
305
306impl<'a> LintContext<'a> {
307    /// The native source path available to filesystem-aware rules.
308    ///
309    /// Virtual adapters intentionally leave this unset even when they provide a
310    /// logical path for configuration matching.
311    pub fn source_file(&self) -> Option<&Path> {
312        self.source_file.as_deref()
313    }
314
315    pub fn link_target_policy(&self) -> Option<&LinkTargetPolicy> {
316        self.link_target_policy.as_ref()
317    }
318
319    pub fn with_link_target_policy(mut self, policy: LinkTargetPolicy) -> Self {
320        self.link_target_policy = Some(policy);
321        self
322    }
323
324    pub fn new(content: &'a str, flavor: MarkdownFlavor, source_file: Option<PathBuf>) -> Self {
325        #[cfg(not(target_arch = "wasm32"))]
326        let profile = std::env::var("RUMDL_PROFILE_QUADRATIC").is_ok();
327
328        let line_offsets = profile_section!("Line offsets", profile, {
329            let mut offsets = vec![0];
330            for (i, c) in content.char_indices() {
331                if c == '\n' {
332                    offsets.push(i + 1);
333                }
334            }
335            offsets
336        });
337
338        // Compute content_lines once for all functions that need it
339        let content_lines: Vec<&str> = content.lines().collect();
340
341        // Detect front matter boundaries once for all functions that need it.
342        // This is the single allowed call site; rules read the cached value
343        // via front_matter_end_line().
344        #[allow(clippy::disallowed_methods)]
345        let front_matter_end = FrontMatterUtils::get_front_matter_end_line(content);
346
347        // Detect code blocks and code spans once and cache them
348        let parse_result = profile_section!(
349            "Code blocks",
350            profile,
351            CodeBlockUtils::detect_code_blocks_and_spans(content)
352        );
353        let mut code_blocks = parse_result.code_blocks;
354        let mut code_span_ranges = parse_result.code_spans;
355        let code_block_details = parse_result.code_block_details;
356        let strong_spans = parse_result.strong_spans;
357        let line_to_list = parse_result.line_to_list;
358        let list_start_values = parse_result.list_start_values;
359        let html_blocks = parse_result.html_blocks;
360
361        // Container structure the parser cannot see. Computed from the line text
362        // alone, so it is available here, before the line info it corrects.
363        let containers = profile_section!(
364            "Container lines",
365            profile,
366            flavor_detection::detect_container_lines(&content_lines, flavor)
367        );
368
369        // Pre-compute HTML comment ranges ONCE for all operations.
370        // Code-span and code-block ranges are passed so `<!--`/`-->` inside code
371        // are treated as literal text, not comment delimiters that could pair
372        // across code regions on different lines. An indented block over
373        // container content is the parser reading a MkDocs admonition or a
374        // `<div markdown>` body as code, and a comment written there is a real
375        // comment, so only the parts of such a block that a fence really does
376        // hold as code are kept.
377        let comment_code_block_ranges: Vec<(usize, usize)> = code_block_details
378            .iter()
379            .flat_map(|detail| {
380                if detail.is_fenced {
381                    return vec![(detail.start, detail.end)];
382                }
383                let start_line = line_offsets
384                    .partition_point(|&offset| offset <= detail.start)
385                    .saturating_sub(1);
386                let end_line = line_offsets.partition_point(|&offset| offset < detail.end);
387                containers
388                    .code_line_spans_in(start_line..end_line)
389                    .into_iter()
390                    .map(|span| {
391                        let start = line_offsets[span.start].max(detail.start);
392                        let end = line_offsets
393                            .get(span.end)
394                            .copied()
395                            .unwrap_or(content.len())
396                            .min(detail.end);
397                        (start, end)
398                    })
399                    .collect()
400            })
401            .collect();
402        // Front matter is data, not markdown: a `<!--` in a YAML value would
403        // otherwise pair with a `-->` in the body and hide everything between
404        // them from every rule. `front_matter_end` is the 1-indexed closing
405        // delimiter line, so the body starts at the line after it, and a
406        // document without front matter starts at byte 0.
407        let body_start = line_offsets.get(front_matter_end).copied().unwrap_or(content.len());
408        let html_comment_scan = profile_section!(
409            "HTML comment ranges",
410            profile,
411            crate::utils::skip_context::scan_html_comments(
412                content,
413                &code_span_ranges,
414                &comment_code_block_ranges,
415                body_start
416            )
417        );
418        let mut html_comment_ranges = html_comment_scan.ranges;
419        let unterminated_html_comment = html_comment_scan.unterminated;
420
421        // Pre-compute autodoc block ranges (avoids O(n^2) scaling)
422        // Detected for all flavors except AzureDevOps, where `:::` denotes code fences
423        // rather than autodoc directives.
424        let autodoc_ranges = profile_section!("Autodoc block ranges", profile, {
425            if flavor.supports_colon_code_fences() || flavor.supports_myst_directives() {
426                Vec::new()
427            } else {
428                crate::utils::mkdocstrings_refs::detect_autodoc_block_ranges(content)
429            }
430        });
431
432        // Pre-compute Pandoc/Quarto div block ranges for Pandoc-compatible flavors
433        let pandoc_div_ranges = profile_section!("Pandoc div ranges", profile, {
434            if flavor.is_pandoc_compatible() {
435                crate::utils::pandoc::detect_div_block_ranges(content)
436            } else {
437                Vec::new()
438            }
439        });
440
441        // Pre-compute PyMdown Blocks ranges for MkDocs flavor (/// ... ///)
442        let pymdown_block_ranges = profile_section!("PyMdown block ranges", profile, {
443            if flavor == MarkdownFlavor::MkDocs {
444                crate::utils::pymdown_blocks::detect_block_ranges(content)
445            } else {
446                Vec::new()
447            }
448        });
449
450        // Pre-compute line information AND emphasis spans (without headings/blockquotes yet)
451        // Emphasis spans are captured during the same pulldown-cmark parse as list detection
452        let skip_ranges = SkipByteRanges {
453            html_comment_ranges: &html_comment_ranges,
454            autodoc_ranges: &autodoc_ranges,
455            pandoc_div_ranges: &pandoc_div_ranges,
456            pymdown_block_ranges: &pymdown_block_ranges,
457        };
458        let (mut lines, emphasis_spans) = profile_section!(
459            "Basic line info",
460            profile,
461            line_computation::compute_basic_line_info(
462                content,
463                &content_lines,
464                &line_offsets,
465                &code_blocks,
466                flavor,
467                &skip_ranges,
468                front_matter_end,
469            )
470        );
471
472        // Detect HTML blocks BEFORE heading detection
473        profile_section!(
474            "HTML blocks",
475            profile,
476            heading_detection::detect_html_blocks(content, &mut lines)
477        );
478
479        // Detect ESM import/export blocks in MDX files BEFORE heading detection
480        profile_section!(
481            "ESM blocks",
482            profile,
483            flavor_detection::detect_esm_blocks(content, &mut lines, flavor)
484        );
485
486        // Detect JSX component blocks in MDX files (e.g. <Tabs>...</Tabs>)
487        profile_section!(
488            "JSX block detection",
489            profile,
490            flavor_detection::detect_jsx_blocks(content, &mut lines, flavor)
491        );
492
493        // Detect JSX expressions and MDX comments in MDX files
494        let (jsx_expression_ranges, mdx_comment_ranges) = profile_section!(
495            "JSX/MDX detection",
496            profile,
497            flavor_detection::detect_jsx_and_mdx_comments(content, &mut lines, flavor, &code_blocks)
498        );
499
500        // Detect `<div markdown>`-style HTML blocks (grid cards, etc.) regardless of flavor.
501        // The `markdown` attribute is an explicit, author-supplied signal; recognizing it
502        // in all flavors keeps `rumdl fmt` from mangling Material grid cards when the
503        // MkDocs flavor isn't active.
504        profile_section!(
505            "Markdown-in-HTML blocks",
506            profile,
507            flavor_detection::detect_markdown_html_blocks(&mut lines, &containers)
508        );
509
510        let mdx_context = if flavor == MarkdownFlavor::MDX {
511            mdx::MdxContext::parse(content, &lines)
512        } else {
513            None
514        };
515        let (jsx_expression_ranges, mdx_comment_ranges) = if let Some(mdx) = &mdx_context {
516            mdx.apply_lines(&mut lines);
517            code_blocks.clone_from(&mdx.code_blocks);
518            code_span_ranges.clone_from(&mdx.code_spans);
519            (mdx.expressions.clone(), mdx.comments.clone())
520        } else {
521            (jsx_expression_ranges, mdx_comment_ranges)
522        };
523
524        // Detect MkDocs-specific constructs (admonitions, tabs, definition lists)
525        profile_section!(
526            "MkDocs constructs",
527            profile,
528            flavor_detection::detect_mkdocs_line_info(&content_lines, &mut lines, flavor, &containers)
529        );
530
531        // Detect footnote definitions and correct false code block detection.
532        // With ENABLE_FOOTNOTES, pulldown-cmark correctly parses multi-line
533        // footnotes, but the code block detector may still mark 4-space-indented
534        // footnote continuation lines as indented code blocks.
535        profile_section!(
536            "Footnote definitions",
537            profile,
538            detect_footnote_definitions(content, &mut lines, &line_offsets)
539        );
540
541        // Filter code_blocks to remove false positives from footnote continuation content.
542        // Same pattern as MkDocs/JSX corrections below.
543        {
544            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
545            for &(start, end) in &code_blocks {
546                let start_line = line_offsets
547                    .partition_point(|&offset| offset <= start)
548                    .saturating_sub(1);
549                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
550
551                let mut sub_start: Option<usize> = None;
552                for (i, &offset) in line_offsets[start_line..end_line]
553                    .iter()
554                    .enumerate()
555                    .map(|(j, o)| (j + start_line, o))
556                {
557                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
558                    if is_real_code && sub_start.is_none() {
559                        let byte_start = if i == start_line { start } else { offset };
560                        sub_start = Some(byte_start);
561                    } else if !is_real_code && sub_start.is_some() {
562                        new_code_blocks.push((sub_start.unwrap(), offset));
563                        sub_start = None;
564                    }
565                }
566                if let Some(s) = sub_start {
567                    new_code_blocks.push((s, end));
568                }
569            }
570            code_blocks = new_code_blocks;
571        }
572
573        // Filter code_blocks to remove false positives from MkDocs admonition/tab content
574        // and `<div markdown>` HTML blocks (grid cards).
575        // pulldown-cmark treats 4-space-indented content as indented code blocks, but inside
576        // these containers this is regular markdown content. detect_mkdocs_line_info and
577        // detect_markdown_html_blocks already corrected LineInfo.in_code_block for these lines,
578        // but the code_blocks byte ranges are still stale. We split ranges rather than using
579        // all-or-nothing removal, so fenced code blocks within the containers are preserved.
580        let has_markdown_html = lines.iter().any(|l| l.in_mkdocs_html_markdown);
581        if flavor == MarkdownFlavor::MkDocs || has_markdown_html {
582            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
583            for &(start, end) in &code_blocks {
584                let start_line = line_offsets
585                    .partition_point(|&offset| offset <= start)
586                    .saturating_sub(1);
587                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
588
589                // Walk lines in this range, collecting sub-ranges where in_code_block is true
590                let mut sub_start: Option<usize> = None;
591                for (i, &offset) in line_offsets[start_line..end_line]
592                    .iter()
593                    .enumerate()
594                    .map(|(j, o)| (j + start_line, o))
595                {
596                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
597                    if is_real_code && sub_start.is_none() {
598                        let byte_start = if i == start_line { start } else { offset };
599                        sub_start = Some(byte_start);
600                    } else if !is_real_code && sub_start.is_some() {
601                        new_code_blocks.push((sub_start.unwrap(), offset));
602                        sub_start = None;
603                    }
604                }
605                if let Some(s) = sub_start {
606                    new_code_blocks.push((s, end));
607                }
608            }
609            code_blocks = new_code_blocks;
610        }
611
612        // Filter code_blocks for MDX JSX blocks (same pattern as MkDocs above).
613        // detect_jsx_blocks already corrected LineInfo.in_code_block for indented content
614        // inside JSX component blocks, but code_blocks byte ranges need updating too.
615        if flavor.supports_jsx() {
616            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
617            for &(start, end) in &code_blocks {
618                let start_line = line_offsets
619                    .partition_point(|&offset| offset <= start)
620                    .saturating_sub(1);
621                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
622
623                let mut sub_start: Option<usize> = None;
624                for (i, &offset) in line_offsets[start_line..end_line]
625                    .iter()
626                    .enumerate()
627                    .map(|(j, o)| (j + start_line, o))
628                {
629                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
630                    if is_real_code && sub_start.is_none() {
631                        let byte_start = if i == start_line { start } else { offset };
632                        sub_start = Some(byte_start);
633                    } else if !is_real_code && sub_start.is_some() {
634                        new_code_blocks.push((sub_start.unwrap(), offset));
635                        sub_start = None;
636                    }
637                }
638                if let Some(s) = sub_start {
639                    new_code_blocks.push((s, end));
640                }
641            }
642            code_blocks = new_code_blocks;
643
644            // Add byte ranges for fenced code blocks nested inside a JSX component.
645            // pulldown-cmark classifies the whole component as one HTML block and
646            // emits no code-block range for the fence, so the split loop above
647            // (which can only narrow existing ranges) never adds it. Derive the
648            // ranges from the per-line in_code_block flags detect_jsx_blocks set,
649            // so byte-range consumers (e.g. MD011, MD044) skip the fence content.
650            let mut jsx_fence_ranges: Vec<(usize, usize)> = Vec::new();
651            let mut run: Option<(usize, usize)> = None;
652            for line in &lines {
653                if line.in_jsx_block && line.in_code_block {
654                    let line_end = line.byte_offset + line.byte_len;
655                    match &mut run {
656                        Some((_, end)) => *end = line_end,
657                        None => run = Some((line.byte_offset, line_end)),
658                    }
659                } else if let Some(r) = run.take() {
660                    jsx_fence_ranges.push(r);
661                }
662            }
663            if let Some(r) = run.take() {
664                jsx_fence_ranges.push(r);
665            }
666            if !jsx_fence_ranges.is_empty() {
667                code_blocks.extend(jsx_fence_ranges);
668                code_blocks.sort_by_key(|&(start, _)| start);
669            }
670        }
671
672        // Detect Azure DevOps colon code fences and extend code_blocks so that
673        // all byte-range consumers correctly skip their content.
674        let colon_fence_details = profile_section!(
675            "Azure colon fence detection",
676            profile,
677            flavor_detection::detect_azure_colon_fences(content, &mut lines, flavor)
678        );
679        if !colon_fence_details.is_empty() {
680            code_blocks.extend(colon_fence_details.iter().map(|fence| (fence.start, fence.end)));
681            code_blocks.sort_by_key(|&(start, _)| start);
682        }
683
684        // Detect MyST colon directives (:::{name} ... :::) — these are structural
685        // containers, NOT code blocks. Content inside is linted as markdown.
686        let myst_directive_ranges = profile_section!(
687            "MyST colon directives",
688            profile,
689            flavor_detection::detect_myst_colon_directives(content, &mut lines, flavor)
690        );
691
692        // Detect MyST % comments
693        let myst_comment_ranges = profile_section!(
694            "MyST comments",
695            profile,
696            flavor_detection::detect_myst_comments(content, &mut lines, flavor)
697        );
698
699        // Detect MyST backtick directives (```{name}) and clear in_code_block for
700        // content-bearing directives so their body is linted as markdown.
701        profile_section!(
702            "MyST backtick directives",
703            profile,
704            flavor_detection::detect_myst_backtick_directives(
705                content,
706                &mut lines,
707                flavor,
708                &code_block_details,
709                &line_offsets
710            )
711        );
712
713        // Filter code_blocks to remove false positives from MyST content-bearing directives.
714        // Same pattern as MkDocs admonition filtering.
715        if flavor.supports_myst_directives() {
716            let mut new_code_blocks = Vec::with_capacity(code_blocks.len());
717            for &(start, end) in &code_blocks {
718                let start_line = line_offsets
719                    .partition_point(|&offset| offset <= start)
720                    .saturating_sub(1);
721                let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
722
723                let mut sub_start: Option<usize> = None;
724                for (i, &offset) in line_offsets[start_line..end_line]
725                    .iter()
726                    .enumerate()
727                    .map(|(j, o)| (j + start_line, o))
728                {
729                    let is_real_code = lines.get(i).is_some_and(|info| info.in_code_block);
730                    if is_real_code && sub_start.is_none() {
731                        let byte_start = if i == start_line { start } else { offset };
732                        sub_start = Some(byte_start);
733                    } else if !is_real_code && sub_start.is_some() {
734                        new_code_blocks.push((sub_start.unwrap(), offset));
735                        sub_start = None;
736                    }
737                }
738                if let Some(s) = sub_start {
739                    new_code_blocks.push((s, end));
740                }
741            }
742            code_blocks = new_code_blocks;
743        }
744
745        // Detect kramdown constructs (extension blocks, IALs, ALDs) in kramdown flavor
746        profile_section!(
747            "Kramdown constructs",
748            profile,
749            flavor_detection::detect_kramdown_line_info(content, &mut lines, flavor)
750        );
751
752        // Layer 1: Sanitize content-derived fields inside kramdown extension blocks
753        // so downstream heading detection and collection builders never see them.
754        // This must run BEFORE detect_headings_and_blockquotes to prevent headings
755        // from being populated inside extension blocks.
756        for line in &mut lines {
757            if line.in_kramdown_extension_block {
758                line.list_item = None;
759                line.is_horizontal_rule = false;
760                line.blockquote = None;
761                line.is_kramdown_block_ial = false;
762            }
763        }
764
765        // Detect Obsidian comments (%%...%%) in Obsidian flavor
766        let obsidian_comment_scan = profile_section!(
767            "Obsidian comments",
768            profile,
769            flavor_detection::detect_obsidian_comments(
770                content,
771                &mut lines,
772                flavor,
773                &code_span_ranges,
774                &html_comment_ranges,
775                body_start
776            )
777        );
778        let mut obsidian_comment_ranges = obsidian_comment_scan.ranges;
779        let mut unterminated_obsidian_comment = obsidian_comment_scan.unterminated;
780
781        // An Obsidian comment hides the text it wraps, so a `<!--` inside one is
782        // not a comment opener. The HTML scan cannot know that yet - detecting
783        // Obsidian comments needs its ranges - so the opener it reported is
784        // re-resolved here, now that the comments that hide it are known.
785        let unterminated_html_comment = crate::utils::skip_context::unterminated_html_comment_outside(
786            unterminated_html_comment,
787            &obsidian_comment_ranges,
788            content,
789            &code_span_ranges,
790            &comment_code_block_ranges,
791            body_start,
792        );
793
794        // An unclosed `<!--` that opens an HTML block comments out the rest of
795        // that block, so the text below it is not content any rule should judge.
796        // Without this the block-structure rules and the comment-aware rules
797        // disagree about the same lines: the parser reports no list inside the
798        // block, while a bare URL there is still flagged.
799        //
800        // The opener stays reported either way. This governs what the rest of
801        // the linter sees, not whether the missing closer is raised.
802        //
803        // It waits for the re-resolution above because an opener a `%%` pair
804        // hides is not an opener, and giving that one a range would hide the
805        // rest of the note from every rule.
806        if let Some(range) = unterminated_html_comment.and_then(|opener| {
807            crate::utils::skip_context::unterminated_comment_range(opener, &html_blocks)
808                .or_else(|| container_comment_range(opener, &containers, &lines, content))
809        }) {
810            // Every complete comment starts before the unclosed opener, so this
811            // keeps the ranges sorted for the binary searches over them.
812            html_comment_ranges.push(range);
813
814            // The line flags are computed before the Obsidian comments are
815            // known, so they predate this range. Recomputing them through the
816            // same helper keeps `is_in_html_comment` and the per-line flag
817            // answering alike, which is the agreement this range exists to
818            // create.
819            for line in &mut lines {
820                let text = line.content(content);
821                let content_start = line.byte_offset + line.indent;
822                let content_end = line.byte_offset + text.trim_end().len();
823                line.in_html_comment = crate::utils::skip_context::is_line_entirely_in_html_comment(
824                    &html_comment_ranges,
825                    content_start,
826                    content_end,
827                );
828                line.in_obsidian_comment = false;
829            }
830
831            // The `%%` delimiters the block covers are comment text, so a
832            // delimiter below the block opens a comment rather than closing the
833            // one those appeared to open. Only a rescan pairs them correctly;
834            // dropping the ranges that start inside the block would leave the
835            // delimiter below it paired with nothing and unreported.
836            //
837            // This is the mirror of the re-resolution above, and it needs no
838            // second round: the block starts at or after the opener, so the
839            // pairing before the opener is what it already was, and the opener
840            // resolved against it cannot change.
841            let obsidian_rescan = flavor_detection::detect_obsidian_comments(
842                content,
843                &mut lines,
844                flavor,
845                &code_span_ranges,
846                &html_comment_ranges,
847                body_start,
848            );
849            obsidian_comment_ranges = obsidian_rescan.ranges;
850            unterminated_obsidian_comment = obsidian_rescan.unterminated;
851        }
852
853        // Detect MyST role syntax ({role}`content`)
854        let myst_role_ranges = profile_section!(
855            "MyST roles",
856            profile,
857            flavor_detection::detect_myst_role_ranges(content, &lines, flavor, &code_blocks)
858        );
859
860        // Run pulldown-cmark parse for links, images, and link byte ranges in a single pass.
861        // Link byte ranges are needed for heading detection; links/images are finalized later
862        // after code_spans are available.
863        let mut pulldown_result = profile_section!(
864            "Links, images & link ranges",
865            profile,
866            link_parser::parse_links_images_pulldown(content, &lines, &code_blocks, flavor, &html_comment_ranges)
867        );
868
869        if let Some(mdx) = &mdx_context {
870            let (links, images) = mdx.links_and_images(content, &lines);
871            pulldown_result.link_byte_ranges = links.iter().map(|link| (link.byte_offset, link.byte_end)).collect();
872            pulldown_result.link_found_positions = links.iter().map(|link| link.byte_offset).collect();
873            pulldown_result.image_found_positions = images.iter().map(|image| image.byte_offset).collect();
874            pulldown_result.links = links;
875            pulldown_result.images = images;
876            pulldown_result.footnote_refs = mdx.footnote_refs();
877            pulldown_result
878                .broken_links
879                .retain(|link| mdx.contains_text(link.span.start, link.span.end));
880        }
881
882        // Now detect headings and blockquotes
883        let mut blockquote_headings = profile_section!(
884            "Headings & blockquotes",
885            profile,
886            heading_detection::detect_headings_and_blockquotes(
887                &content_lines,
888                &mut lines,
889                flavor,
890                &html_comment_ranges,
891                &pulldown_result.link_byte_ranges,
892                front_matter_end,
893            )
894        );
895
896        // Clear headings that were detected inside kramdown extension blocks
897        for line in &mut lines {
898            if line.in_kramdown_extension_block {
899                line.heading = None;
900            }
901        }
902        for (line, heading) in lines.iter().zip(&mut blockquote_headings) {
903            if line.in_kramdown_extension_block {
904                *heading = None;
905            }
906        }
907
908        // A run of `-`, `*` or `_` is a thematic break only because of the block it
909        // sits in, and that block is known only now: the passes above are what mark
910        // an HTML comment, an HTML block, a math block, an MDX or Obsidian comment,
911        // and the colon fences a flavor reads as code. The flag was computed from the
912        // line text before any of them ran, so it is settled here against the answers
913        // they produced, the way the kramdown sanitization above settles its own.
914        //
915        // Left alone deliberately: containers whose body IS markdown (Pandoc divs,
916        // MkDocs admonitions and tabs, PyMdown blocks, MyST directives) render a
917        // thematic break written in them.
918        for line in &mut lines {
919            if line.is_horizontal_rule
920                && (line.in_code_block
921                    || line.in_html_block
922                    || line.in_html_comment
923                    || line.in_math_block
924                    || line.in_mdx_comment
925                    || line.in_obsidian_comment)
926            {
927                line.is_horizontal_rule = false;
928            }
929        }
930
931        // Parse code spans early so we can exclude them from link/image parsing
932        let mut code_spans = profile_section!(
933            "Code spans",
934            profile,
935            element_parsers::build_code_spans_from_ranges(content, &lines, &code_span_ranges)
936        );
937
938        // Supplement code spans for MkDocs container content that pulldown-cmark missed.
939        // pulldown-cmark treats 4-space-indented MkDocs content as indented code blocks,
940        // so backtick code spans within admonitions/tabs/markdown HTML are invisible to it.
941        if flavor == MarkdownFlavor::MkDocs {
942            let extra = profile_section!(
943                "MkDocs code spans",
944                profile,
945                element_parsers::scan_mkdocs_container_code_spans(content, &lines, &code_span_ranges,)
946            );
947            if !extra.is_empty() {
948                code_spans.extend(extra);
949                code_spans.sort_by_key(|span| span.byte_offset);
950            }
951        }
952
953        // Supplement code spans for MDX JSX component body content that pulldown-cmark missed.
954        // pulldown-cmark treats JSX component opening tags (e.g. `<ParamField>`) as HTML block
955        // starters, so backtick code spans within component bodies are invisible to the initial
956        // parse.
957        if flavor == MarkdownFlavor::MDX && mdx_context.is_none() {
958            let extra = profile_section!(
959                "MDX JSX code spans",
960                profile,
961                element_parsers::scan_jsx_block_code_spans(content, &lines, &code_span_ranges)
962            );
963            if !extra.is_empty() {
964                code_spans.extend(extra);
965                code_spans.sort_by_key(|span| span.byte_offset);
966            }
967        }
968
969        // Mark lines that are continuations of multi-line code spans
970        // This is needed for parse_list_blocks to correctly handle list items with multi-line code spans
971        for span in &code_spans {
972            if span.end_line > span.line {
973                // Mark lines after the first line as continuations
974                for line_num in (span.line + 1)..=span.end_line {
975                    if let Some(line_info) = lines.get_mut(line_num - 1) {
976                        line_info.in_code_span_continuation = true;
977                    }
978                }
979            }
980        }
981
982        // Finalize links and images: filter by code_spans and run regex fallbacks
983        let (links, images, broken_links, footnote_refs) = profile_section!(
984            "Links & images finalize",
985            profile,
986            link_parser::finalize_links_and_images(
987                content,
988                &lines,
989                flavor,
990                &link_parser::LinkExclusions {
991                    code_blocks: &code_blocks,
992                    code_spans: &code_spans,
993                    html_comment_ranges: &html_comment_ranges,
994                    mdx: mdx_context.as_ref(),
995                },
996                pulldown_result,
997            )
998        );
999
1000        let reference_defs = profile_section!("Reference defs", profile, {
1001            if let Some(mdx) = &mdx_context {
1002                mdx.reference_defs(content)
1003            } else {
1004                link_parser::parse_reference_defs(content, &lines)
1005            }
1006        });
1007
1008        let list_blocks = profile_section!("List blocks", profile, list_blocks::parse_list_blocks(content, &lines));
1009
1010        // Compute character frequency for fast content analysis
1011        let char_frequency = profile_section!(
1012            "Char frequency",
1013            profile,
1014            line_computation::compute_char_frequency(content)
1015        );
1016
1017        // Pre-compute table blocks for rules that need them (MD013, MD055, MD056, MD058, MD060)
1018        let table_blocks = profile_section!(
1019            "Table blocks",
1020            profile,
1021            crate::utils::table_utils::TableUtils::find_table_blocks_with_code_info(
1022                content,
1023                &code_blocks,
1024                &code_spans,
1025                &html_comment_ranges,
1026                flavor,
1027            )
1028        );
1029
1030        // Layer 2: Filter pre-computed collections to exclude items inside kramdown extension blocks.
1031        // Rules that iterate these collections automatically skip kramdown content.
1032        let links = links
1033            .into_iter()
1034            .filter(|link| !lines.get(link.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
1035            .collect::<Vec<_>>();
1036        let images = images
1037            .into_iter()
1038            .filter(|img| !lines.get(img.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
1039            .collect::<Vec<_>>();
1040        let broken_links = broken_links
1041            .into_iter()
1042            .filter(|bl| {
1043                // BrokenLinkInfo has span but no line field; find line from byte offset
1044                let line_idx = line_offsets
1045                    .partition_point(|&offset| offset <= bl.span.start)
1046                    .saturating_sub(1);
1047                !lines.get(line_idx).is_some_and(|l| l.in_kramdown_extension_block)
1048            })
1049            .collect::<Vec<_>>();
1050        let footnote_refs = footnote_refs
1051            .into_iter()
1052            .filter(|fr| !lines.get(fr.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
1053            .collect::<Vec<_>>();
1054        let reference_defs = reference_defs
1055            .into_iter()
1056            .filter(|def| !lines.get(def.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
1057            .collect::<Vec<_>>();
1058        let list_blocks = list_blocks
1059            .into_iter()
1060            .filter(|block| {
1061                !lines
1062                    .get(block.start_line - 1)
1063                    .is_some_and(|l| l.in_kramdown_extension_block)
1064            })
1065            .collect::<Vec<_>>();
1066        let table_blocks = table_blocks
1067            .into_iter()
1068            .filter(|block| {
1069                // TableBlock.start_line is 0-indexed
1070                !lines
1071                    .get(block.start_line)
1072                    .is_some_and(|l| l.in_kramdown_extension_block)
1073            })
1074            .collect::<Vec<_>>();
1075        let emphasis_spans = emphasis_spans
1076            .into_iter()
1077            .filter(|span| !lines.get(span.line - 1).is_some_and(|l| l.in_kramdown_extension_block))
1078            .collect::<Vec<_>>();
1079
1080        // Mark lines covered by a list or table block so is_in_list_block /
1081        // is_in_table_block are O(1) reads (mirrors in_html_block) instead of
1082        // scanning the whole block vector on every call.
1083        for block in &list_blocks {
1084            // ListBlock line numbers are 1-indexed.
1085            for line_num in block.start_line..=block.end_line {
1086                if let Some(li) = lines.get_mut(line_num - 1) {
1087                    li.in_list_block = true;
1088                }
1089            }
1090        }
1091        for block in &table_blocks {
1092            // TableBlock line numbers are 0-indexed.
1093            for idx in block.start_line..=block.end_line {
1094                if let Some(li) = lines.get_mut(idx) {
1095                    li.in_table_block = true;
1096                }
1097            }
1098        }
1099
1100        // Rebuild reference_defs_map after filtering
1101        let reference_defs_map: HashMap<String, usize> = reference_defs
1102            .iter()
1103            .enumerate()
1104            .map(|(idx, def)| (def.id.to_lowercase(), idx))
1105            .collect();
1106
1107        // Pre-compute sorted link title byte ranges for binary search
1108        let link_title_ranges: Vec<(usize, usize)> = reference_defs
1109            .iter()
1110            .filter_map(|def| match (def.title_byte_start, def.title_byte_end) {
1111                (Some(start), Some(end)) => Some((start, end)),
1112                _ => None,
1113            })
1114            .collect();
1115
1116        // Reuse already-computed line_offsets and code_blocks instead of re-detecting
1117        let line_index = profile_section!(
1118            "Line index",
1119            profile,
1120            crate::utils::range_utils::LineIndex::with_line_starts_and_code_blocks(
1121                content,
1122                line_offsets.clone(),
1123                &code_blocks,
1124            )
1125        );
1126
1127        // Pre-compute Jinja template ranges once for all rules (eliminates O(n*m) in MD011)
1128        let jinja_ranges = profile_section!(
1129            "Jinja ranges",
1130            profile,
1131            crate::utils::jinja_utils::find_jinja_ranges(content)
1132        );
1133
1134        // Pre-compute Pandoc/Quarto citation ranges for Pandoc-compatible flavors
1135        let citation_ranges = profile_section!("Citation ranges", profile, {
1136            if flavor.is_pandoc_compatible() {
1137                crate::utils::pandoc::find_citation_ranges(content)
1138            } else {
1139                Vec::new()
1140            }
1141        });
1142
1143        // Pre-compute Pandoc inline footnote ranges for Pandoc-compatible flavors
1144        let inline_footnote_ranges = profile_section!("Inline footnote ranges", profile, {
1145            if flavor.is_pandoc_compatible() {
1146                crate::utils::pandoc::detect_inline_footnote_ranges(content)
1147            } else {
1148                Vec::new()
1149            }
1150        });
1151
1152        // Pre-compute Pandoc implicit header reference slugs for Pandoc-compatible flavors
1153        let pandoc_header_slugs = profile_section!("Pandoc header slugs", profile, {
1154            if flavor.is_pandoc_compatible() {
1155                crate::utils::pandoc::collect_pandoc_header_slugs(content)
1156            } else {
1157                std::collections::HashSet::new()
1158            }
1159        });
1160
1161        // Pre-compute Pandoc example-list marker ranges for Pandoc-compatible flavors
1162        let example_list_marker_ranges = profile_section!("Example list markers", profile, {
1163            if flavor.is_pandoc_compatible() {
1164                crate::utils::pandoc::detect_example_list_marker_ranges(content)
1165            } else {
1166                Vec::new()
1167            }
1168        });
1169
1170        // Pre-compute Pandoc example reference ranges for Pandoc-compatible flavors
1171        let example_reference_ranges = profile_section!("Example references", profile, {
1172            if flavor.is_pandoc_compatible() {
1173                crate::utils::pandoc::detect_example_reference_ranges(content, &example_list_marker_ranges)
1174            } else {
1175                Vec::new()
1176            }
1177        });
1178
1179        // Pre-compute Pandoc subscript (~x~) and superscript (^x^) ranges
1180        let sub_super_ranges = profile_section!("Subscript/superscript ranges", profile, {
1181            if flavor.is_pandoc_compatible() {
1182                crate::utils::pandoc::detect_subscript_superscript_ranges(content)
1183            } else {
1184                Vec::new()
1185            }
1186        });
1187
1188        // Pre-compute Pandoc inline code attribute ranges (`code`{.lang}) for Pandoc-compatible flavors
1189        let inline_code_attr_ranges = profile_section!("Inline code attribute ranges", profile, {
1190            if flavor.is_pandoc_compatible() {
1191                crate::utils::pandoc::detect_inline_code_attr_ranges(content)
1192            } else {
1193                Vec::new()
1194            }
1195        });
1196
1197        // Pre-compute Pandoc bracketed span ranges ([text]{attrs}) for Pandoc-compatible flavors
1198        let bracketed_span_ranges = profile_section!("Bracketed span ranges", profile, {
1199            if flavor.is_pandoc_compatible() {
1200                crate::utils::pandoc::detect_bracketed_span_ranges(content)
1201            } else {
1202                Vec::new()
1203            }
1204        });
1205
1206        // Pre-compute Pandoc line block ranges (| text) for Pandoc-compatible flavors
1207        let line_block_ranges = profile_section!("Line block ranges", profile, {
1208            if flavor.is_pandoc_compatible() {
1209                crate::utils::pandoc::detect_line_block_ranges(content)
1210            } else {
1211                Vec::new()
1212            }
1213        });
1214
1215        // Pre-compute Pandoc pipe-table caption ranges (: caption) for Pandoc-compatible flavors
1216        let pipe_table_caption_ranges = profile_section!("Pipe-table caption ranges", profile, {
1217            if flavor.is_pandoc_compatible() {
1218                crate::utils::pandoc::detect_pipe_table_caption_ranges(content)
1219            } else {
1220                Vec::new()
1221            }
1222        });
1223
1224        // Pre-compute Pandoc YAML metadata block ranges (--- ... --- or ...) for Pandoc-compatible flavors
1225        let pandoc_metadata_ranges = profile_section!("Pandoc metadata ranges", profile, {
1226            if flavor.is_pandoc_compatible() {
1227                crate::utils::pandoc::detect_yaml_metadata_block_ranges(content)
1228            } else {
1229                Vec::new()
1230            }
1231        });
1232
1233        // Pre-compute Pandoc grid-table ranges (+---+---+) for Pandoc-compatible flavors
1234        let grid_table_ranges = profile_section!("Grid table ranges", profile, {
1235            if flavor.is_pandoc_compatible() {
1236                crate::utils::pandoc::detect_grid_table_ranges(content)
1237            } else {
1238                Vec::new()
1239            }
1240        });
1241
1242        // Pre-compute Pandoc multi-line table ranges for Pandoc-compatible flavors
1243        let multi_line_table_ranges = profile_section!("Multi-line table ranges", profile, {
1244            if flavor.is_pandoc_compatible() {
1245                crate::utils::pandoc::detect_multi_line_table_ranges(content)
1246            } else {
1247                Vec::new()
1248            }
1249        });
1250
1251        // Pre-compute Hugo/Quarto shortcode ranges ({{< ... >}} and {{% ... %}})
1252        let shortcode_ranges = profile_section!("Shortcode ranges", profile, {
1253            use crate::utils::regex_cache::HUGO_SHORTCODE_REGEX;
1254            let mut ranges = Vec::new();
1255            for mat in HUGO_SHORTCODE_REGEX.find_iter(content) {
1256                ranges.push((mat.start(), mat.end()));
1257            }
1258            ranges
1259        });
1260
1261        let inline_config =
1262            InlineConfig::from_content_with_code_blocks(content, &code_blocks, &code_span_byte_ranges(&code_spans));
1263        Self {
1264            content,
1265            content_lines,
1266            line_offsets,
1267            code_blocks,
1268            code_block_details,
1269            strong_spans,
1270            line_to_list,
1271            list_start_values,
1272            commonmark_ordered_lists_cache: OnceLock::new(),
1273            lines,
1274            blockquote_headings,
1275            links,
1276            images,
1277            broken_links,
1278            footnote_refs,
1279            reference_defs,
1280            reference_defs_map,
1281            code_spans_cache: OnceLock::from(Arc::new(code_spans)),
1282            math_spans_cache: OnceLock::new(),       // Lazy-loaded on first access
1283            math_byte_ranges_cache: OnceLock::new(), // Lazy-loaded on first access
1284            list_blocks,
1285            char_frequency,
1286            html_tags_cache: OnceLock::new(),
1287            jsx_component_tags_cache: OnceLock::new(),
1288            emphasis_spans_cache: OnceLock::from(Arc::new(emphasis_spans)),
1289            bare_urls_cache: OnceLock::new(),
1290            has_mixed_list_nesting_cache: OnceLock::new(),
1291            html_comment_ranges,
1292            table_blocks,
1293            line_index,
1294            jinja_ranges,
1295            flavor,
1296            source_file,
1297            link_target_policy: None,
1298            jsx_expression_ranges,
1299            mdx_comment_ranges,
1300            citation_ranges,
1301            pandoc_div_ranges,
1302            colon_fence_details,
1303            inline_footnote_ranges,
1304            pandoc_header_slugs,
1305            example_list_marker_ranges,
1306            example_reference_ranges,
1307            sub_super_ranges,
1308            inline_code_attr_ranges,
1309            bracketed_span_ranges,
1310            line_block_ranges,
1311            pipe_table_caption_ranges,
1312            pandoc_metadata_ranges,
1313            grid_table_ranges,
1314            multi_line_table_ranges,
1315            shortcode_ranges,
1316            link_title_ranges,
1317            code_span_byte_ranges: code_span_ranges,
1318            inline_config,
1319            obsidian_comment_ranges,
1320            unterminated_html_comment,
1321            unterminated_obsidian_comment,
1322            lazy_cont_lines_cache: OnceLock::new(),
1323            myst_directive_ranges,
1324            myst_comment_ranges,
1325            myst_role_ranges,
1326            front_matter_end,
1327        }
1328    }
1329
1330    /// The 1-indexed line number where front matter ends (the closing
1331    /// delimiter line), or 0 when the document has no front matter.
1332    /// Computed once in `new()`; rules must use this instead of re-scanning
1333    /// the content with `FrontMatterUtils`.
1334    pub fn front_matter_end_line(&self) -> usize {
1335        self.front_matter_end
1336    }
1337
1338    /// Binary search for whether `pos` falls inside any range in a sorted, non-overlapping
1339    /// slice of `(start, end)` byte ranges. O(log n) instead of O(n).
1340    #[inline]
1341    fn binary_search_ranges(ranges: &[(usize, usize)], pos: usize) -> bool {
1342        // Find the rightmost range whose start <= pos
1343        let idx = ranges.partition_point(|&(start, _)| start <= pos);
1344        // If idx == 0, no range starts at or before pos
1345        idx > 0 && pos < ranges[idx - 1].1
1346    }
1347
1348    /// Check if a byte position is within a code span. O(log n).
1349    pub fn is_in_code_span_byte(&self, pos: usize) -> bool {
1350        Self::binary_search_ranges(&self.code_span_byte_ranges, pos)
1351    }
1352
1353    /// Check if `pos` is inside any link byte range. O(log n).
1354    pub fn is_in_link(&self, pos: usize) -> bool {
1355        self.link_containing(pos).is_some() || self.image_containing(pos).is_some() || self.is_in_reference_def(pos)
1356    }
1357
1358    /// Check if `pos`` is within a bare URL
1359    pub fn is_in_bare_url(&self, pos: usize) -> bool {
1360        let bare_urls = self.bare_urls();
1361        // Binary search (sorted by byte_offset) for the candidate containing byte_pos
1362        let idx = bare_urls.partition_point(|url| url.byte_offset <= pos);
1363        idx > 0 && pos < bare_urls[idx - 1].byte_end
1364    }
1365
1366    /// Get parsed inline configuration state.
1367    pub fn inline_config(&self) -> &InlineConfig {
1368        &self.inline_config
1369    }
1370
1371    /// Azure DevOps colon code fences (`:::lang … :::`), each with its byte range
1372    /// and the opener's info string. These are detected outside the CommonMark
1373    /// parse, so they never appear in `code_block_details`. Empty for all other
1374    /// flavors.
1375    pub fn colon_fence_details(&self) -> &[CodeBlockDetail] {
1376        &self.colon_fence_details
1377    }
1378
1379    /// Get pre-split content lines, avoiding repeated `content.lines().collect()` allocations.
1380    ///
1381    /// Lines are 0-indexed (line 0 corresponds to line number 1 in the document).
1382    pub fn raw_lines(&self) -> &[&'a str] {
1383        &self.content_lines
1384    }
1385
1386    /// Check if a rule is disabled at a specific line number (1-indexed)
1387    ///
1388    /// This method checks both persistent disable comments (<!-- rumdl-disable -->)
1389    /// and line-specific comments (<!-- rumdl-disable-line -->, <!-- rumdl-disable-next-line -->).
1390    pub fn is_rule_disabled(&self, rule_name: &str, line_number: usize) -> bool {
1391        self.inline_config.is_rule_disabled(rule_name, line_number)
1392    }
1393
1394    /// Get code spans - computed lazily on first access
1395    pub fn code_spans(&self) -> Arc<Vec<CodeSpan>> {
1396        Arc::clone(
1397            self.code_spans_cache
1398                .get_or_init(|| Arc::new(element_parsers::parse_code_spans(self.content, &self.lines))),
1399        )
1400    }
1401
1402    /// Math byte ranges (`$...$` inline and `$$...$$` display), computed once and
1403    /// cached. Used by `is_in_math_context`; without the cache that helper
1404    /// rescanned the whole document on every call.
1405    pub fn math_byte_ranges(&self) -> &[(usize, usize)] {
1406        self.math_byte_ranges_cache
1407            .get_or_init(|| crate::utils::skip_context::math_byte_ranges(self.content))
1408    }
1409
1410    /// Get math spans - computed lazily on first access
1411    pub fn math_spans(&self) -> Arc<Vec<MathSpan>> {
1412        Arc::clone(
1413            self.math_spans_cache
1414                .get_or_init(|| Arc::new(element_parsers::parse_math_spans(self.content, &self.lines))),
1415        )
1416    }
1417
1418    /// Check if a byte position is within a math span (inline $...$ or display $$...$$)
1419    pub fn is_in_math_span(&self, byte_pos: usize) -> bool {
1420        let math_spans = self.math_spans();
1421        // Binary search: find the last span whose byte_offset <= byte_pos
1422        let idx = math_spans.partition_point(|span| span.byte_offset <= byte_pos);
1423        idx > 0 && byte_pos < math_spans[idx - 1].byte_end
1424    }
1425
1426    /// Get HTML comment ranges - pre-computed during LintContext construction
1427    pub fn html_comment_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
1428        &self.html_comment_ranges
1429    }
1430
1431    /// Byte offset of a `<!--` that no `-->` closes, if the document has one.
1432    ///
1433    /// Everything after it is inside the comment as far as the parser is
1434    /// concerned, so no rule sees that text.
1435    pub fn unterminated_html_comment(&self) -> Option<usize> {
1436        self.unterminated_html_comment
1437    }
1438
1439    /// Byte offset of a `%%` that no second `%%` closes, if the document has
1440    /// one. Always `None` outside the Obsidian flavor, where `%%` is ordinary
1441    /// text rather than a comment delimiter.
1442    pub fn unterminated_obsidian_comment(&self) -> Option<usize> {
1443        self.unterminated_obsidian_comment
1444    }
1445
1446    /// Check if a byte position is inside an Obsidian comment
1447    ///
1448    /// Returns false for non-Obsidian flavors.
1449    pub fn is_in_obsidian_comment(&self, byte_pos: usize) -> bool {
1450        Self::binary_search_ranges(&self.obsidian_comment_ranges, byte_pos)
1451    }
1452
1453    /// Check if a line/column position is inside an Obsidian comment
1454    ///
1455    /// Line number is 1-indexed, column is 1-indexed.
1456    /// Returns false for non-Obsidian flavors.
1457    pub fn is_position_in_obsidian_comment(&self, line_num: usize, col: usize) -> bool {
1458        if self.obsidian_comment_ranges.is_empty() {
1459            return false;
1460        }
1461
1462        // Convert line/column (1-indexed, char-based) to byte position
1463        let byte_pos = self.line_index.line_col_to_byte_range(line_num, col).start;
1464        self.is_in_obsidian_comment(byte_pos)
1465    }
1466
1467    /// Get byte ranges of MyST colon directive blocks
1468    pub fn myst_directive_ranges(&self) -> &[(usize, usize)] {
1469        &self.myst_directive_ranges
1470    }
1471
1472    /// Check if a byte position is inside a MyST role (`{role}`content``)
1473    pub fn is_in_myst_role(&self, byte_pos: usize) -> bool {
1474        Self::binary_search_ranges(&self.myst_role_ranges, byte_pos)
1475    }
1476
1477    /// Check if a byte position is inside a MyST comment (`% comment`)
1478    pub fn is_in_myst_comment(&self, byte_pos: usize) -> bool {
1479        Self::binary_search_ranges(&self.myst_comment_ranges, byte_pos)
1480    }
1481
1482    /// Check if a line (1-indexed) is a MyST colon-fence directive opener (`:::{name} ...`).
1483    ///
1484    /// The text after `{name}` on an opener is the directive's argument (an opaque
1485    /// path, URL, or label), not markdown prose. Rules that reformat prose should
1486    /// skip these lines. Returns false for non-MyST flavors and for directive body
1487    /// or closer lines.
1488    pub fn is_myst_colon_directive_opener_line(&self, line_num: usize) -> bool {
1489        if !self.flavor.supports_myst_directives() {
1490            return false;
1491        }
1492        self.lines.get(line_num.wrapping_sub(1)).is_some_and(|info| {
1493            info.in_myst_directive
1494                && flavor_detection::myst_colon_directive_opener(info.content(self.content)).is_some()
1495        })
1496    }
1497
1498    /// Drop tags that live inside kramdown extension blocks, preserving order.
1499    fn filter_kramdown_tags(&self, tags: Vec<HtmlTag>) -> Vec<HtmlTag> {
1500        tags.into_iter()
1501            .filter(|tag| {
1502                !self
1503                    .lines
1504                    .get(tag.line - 1)
1505                    .is_some_and(|l| l.in_kramdown_extension_block)
1506            })
1507            .collect()
1508    }
1509
1510    /// Get HTML tags - computed lazily on first access.
1511    ///
1512    /// JSX component tags (e.g. `<Card .../>`) are excluded so HTML-specific rules
1513    /// keep ignoring them; use [`Self::jsx_component_tags`] to access those. The
1514    /// single underlying parse populates both caches at once.
1515    pub fn html_tags(&self) -> Arc<Vec<HtmlTag>> {
1516        Arc::clone(self.html_tags_cache.get_or_init(|| {
1517            let (html_tags, jsx_component_tags) =
1518                element_parsers::parse_html_tags(self.content, &self.lines, &self.code_blocks, self.flavor);
1519            // Populate the JSX-component cache from the same parse so it is built once.
1520            let _ = self
1521                .jsx_component_tags_cache
1522                .set(Arc::new(self.filter_kramdown_tags(jsx_component_tags)));
1523            Arc::new(self.filter_kramdown_tags(html_tags))
1524        }))
1525    }
1526
1527    /// Get JSX component tags (e.g. `<Card .../>`) - computed lazily, sharing the
1528    /// HTML-tag parse. Always empty for flavors without JSX support.
1529    pub fn jsx_component_tags(&self) -> Arc<Vec<HtmlTag>> {
1530        if let Some(cached) = self.jsx_component_tags_cache.get() {
1531            return Arc::clone(cached);
1532        }
1533        // Trigger the shared parse, which also fills jsx_component_tags_cache.
1534        let _ = self.html_tags();
1535        Arc::clone(
1536            self.jsx_component_tags_cache
1537                .get()
1538                .expect("html_tags() populates jsx_component_tags_cache"),
1539        )
1540    }
1541
1542    /// Get emphasis spans - pre-computed during construction
1543    pub fn emphasis_spans(&self) -> Arc<Vec<EmphasisSpan>> {
1544        Arc::clone(
1545            self.emphasis_spans_cache
1546                .get()
1547                .expect("emphasis_spans_cache initialized during construction"),
1548        )
1549    }
1550
1551    /// Get bare URLs - computed lazily on first access
1552    pub fn bare_urls(&self) -> Arc<Vec<BareUrl>> {
1553        Arc::clone(self.bare_urls_cache.get_or_init(|| {
1554            Arc::new(element_parsers::parse_bare_urls(
1555                self.content,
1556                &self.lines,
1557                &self.code_blocks,
1558            ))
1559        }))
1560    }
1561
1562    /// Get lazy continuation lines - computed lazily on first access
1563    pub fn lazy_continuation_lines(&self) -> Arc<Vec<LazyContLine>> {
1564        Arc::clone(self.lazy_cont_lines_cache.get_or_init(|| {
1565            Arc::new(element_parsers::detect_lazy_continuation_lines(
1566                self.content,
1567                &self.lines,
1568                &self.line_offsets,
1569            ))
1570        }))
1571    }
1572
1573    /// Check if document has mixed ordered/unordered list nesting.
1574    /// Result is cached after first computation (document-level invariant).
1575    /// This is used by MD007 for smart style auto-detection.
1576    pub fn has_mixed_list_nesting(&self) -> bool {
1577        *self
1578            .has_mixed_list_nesting_cache
1579            .get_or_init(|| self.compute_mixed_list_nesting())
1580    }
1581
1582    /// Internal computation for mixed list nesting (only called once per LintContext).
1583    fn compute_mixed_list_nesting(&self) -> bool {
1584        // Track parent list items by their marker position and type
1585        // Using marker_column instead of indent because it works correctly
1586        // for blockquoted content where indent doesn't account for the prefix
1587        // Stack stores: (marker_column, is_ordered)
1588        let mut stack: Vec<(usize, bool)> = Vec::new();
1589        let mut last_was_blank = false;
1590
1591        for line_info in &self.lines {
1592            // Skip non-content lines (code blocks, frontmatter, HTML comments, etc.)
1593            if line_info.in_code_block
1594                || line_info.in_front_matter
1595                || line_info.in_mkdocstrings
1596                || line_info.in_html_comment
1597                || line_info.in_mdx_comment
1598                || line_info.in_esm_block
1599            {
1600                continue;
1601            }
1602
1603            // OPTIMIZATION: Use pre-computed is_blank instead of content().trim()
1604            if line_info.is_blank {
1605                last_was_blank = true;
1606                continue;
1607            }
1608
1609            if let Some(list_item) = &line_info.list_item {
1610                // Normalize column 1 to column 0 (consistent with MD007 check function)
1611                let current_pos = if list_item.marker_column == 1 {
1612                    0
1613                } else {
1614                    list_item.marker_column
1615                };
1616
1617                // If there was a blank line and this item is at root level, reset stack
1618                if last_was_blank && current_pos == 0 {
1619                    stack.clear();
1620                }
1621                last_was_blank = false;
1622
1623                // Pop items at same or greater position (they're siblings or deeper, not parents)
1624                while let Some(&(pos, _)) = stack.last() {
1625                    if pos >= current_pos {
1626                        stack.pop();
1627                    } else {
1628                        break;
1629                    }
1630                }
1631
1632                // Check if immediate parent has different type - this is mixed nesting
1633                if let Some(&(_, parent_is_ordered)) = stack.last()
1634                    && parent_is_ordered != list_item.is_ordered
1635                {
1636                    return true; // Found mixed nesting - early exit
1637                }
1638
1639                stack.push((current_pos, list_item.is_ordered));
1640            } else {
1641                // Non-list line (but not blank) - could be paragraph or other content
1642                last_was_blank = false;
1643            }
1644        }
1645
1646        false
1647    }
1648
1649    /// Map a byte offset to (line, column).
1650    ///
1651    /// The column is a 1-indexed *character* offset within the line (rumdl's
1652    /// diagnostic convention), not a byte offset, so it is correct on lines
1653    /// containing multi-byte UTF-8 characters.
1654    pub fn offset_to_line_col(&self, offset: usize) -> (usize, usize) {
1655        match self.line_offsets.binary_search(&offset) {
1656            Ok(line) => (line + 1, 1),
1657            Err(line) => {
1658                let line_start = self.line_offsets.get(line.wrapping_sub(1)).copied().unwrap_or(0);
1659                // Convert the byte offset within the line to a character column.
1660                let col = byte_to_char_count(&self.content[line_start..], offset.saturating_sub(line_start));
1661                (line, col)
1662            }
1663        }
1664    }
1665
1666    /// Return the byte offset at which a 1-indexed source line starts.
1667    ///
1668    /// This is the inverse-facing half of [`Self::offset_to_line_col`]. Keeping
1669    /// both conversions on the document prevents rules from depending on the
1670    /// line-index representation or reconstructing it independently.
1671    pub fn line_start_byte(&self, line_number: usize) -> Option<usize> {
1672        self.line_index.get_line_start_byte(line_number)
1673    }
1674
1675    /// Return an empty byte range at a 1-indexed line and character column.
1676    ///
1677    /// Columns are character offsets, not UTF-8 byte offsets. Positions past
1678    /// the end of a line clamp to the end of its content; missing lines clamp to
1679    /// the end of the document.
1680    pub fn line_column_byte_range(&self, line_number: usize, column: usize) -> Range<usize> {
1681        self.line_index.line_col_to_byte_range(line_number, column)
1682    }
1683
1684    /// Return a byte range beginning at a 1-indexed line and character column.
1685    ///
1686    /// `length` is measured in characters. The result never crosses the line's
1687    /// content boundary and excludes its line ending.
1688    pub fn line_column_byte_range_with_length(&self, line_number: usize, column: usize, length: usize) -> Range<usize> {
1689        self.line_index
1690            .line_col_to_byte_range_with_length(line_number, column, length)
1691    }
1692
1693    /// Return the byte range of a complete 1-indexed line, including its line
1694    /// ending when one is present.
1695    pub fn whole_line_byte_range(&self, line_number: usize) -> Range<usize> {
1696        self.line_index.whole_line_range(line_number)
1697    }
1698
1699    /// Return the byte range between two 1-indexed character columns on a line.
1700    ///
1701    /// The range excludes the line ending and clamps both columns to valid
1702    /// character boundaries in the line content.
1703    pub fn line_text_byte_range(&self, line_number: usize, start_column: usize, end_column: usize) -> Range<usize> {
1704        self.line_index.line_text_range(line_number, start_column, end_column)
1705    }
1706
1707    /// Return the byte range of a 1-indexed line's content, excluding its line
1708    /// ending.
1709    pub fn line_content_byte_range(&self, line_number: usize) -> Range<usize> {
1710        self.line_index.line_content_range(line_number)
1711    }
1712
1713    /// Return the byte range spanning complete 1-indexed lines, inclusive.
1714    pub fn line_span_byte_range(&self, start_line: usize, end_line: usize) -> Range<usize> {
1715        self.line_index.multi_line_range(start_line, end_line)
1716    }
1717
1718    /// Check if a position is within a code block or code span. O(log n).
1719    pub fn is_in_code_block_or_span(&self, pos: usize) -> bool {
1720        // Check code blocks first (already uses binary search internally)
1721        if CodeBlockUtils::is_in_code_block_or_span(&self.code_blocks, pos) {
1722            return true;
1723        }
1724
1725        // Check inline code spans via binary search
1726        self.is_byte_offset_in_code_span(pos)
1727    }
1728
1729    /// Get line information by line number (1-indexed)
1730    pub fn line_info(&self, line_num: usize) -> Option<&LineInfo> {
1731        if line_num > 0 {
1732            self.lines.get(line_num - 1)
1733        } else {
1734            None
1735        }
1736    }
1737
1738    /// Parsed links in document order.
1739    pub fn links(&self) -> &[ParsedLink<'a>] {
1740        &self.links
1741    }
1742
1743    /// Parsed images in document order.
1744    pub fn images(&self) -> &[ParsedImage<'a>] {
1745        &self.images
1746    }
1747
1748    /// Broken or undefined reference links in document order.
1749    pub fn broken_links(&self) -> &[BrokenLinkInfo] {
1750        &self.broken_links
1751    }
1752
1753    /// Parsed footnote references in document order.
1754    pub fn footnote_references(&self) -> &[FootnoteRef] {
1755        &self.footnote_refs
1756    }
1757
1758    /// Parsed reference definitions in document order.
1759    pub fn reference_definitions(&self) -> &[ReferenceDef] {
1760        &self.reference_defs
1761    }
1762
1763    /// Links whose opening delimiter starts on `line_number` (1-indexed).
1764    pub fn links_on_line(&self, line_number: usize) -> &[ParsedLink<'a>] {
1765        let start = self.links.partition_point(|link| link.line < line_number);
1766        let end = self.links.partition_point(|link| link.line <= line_number);
1767        &self.links[start..end]
1768    }
1769
1770    /// Images whose opening delimiter starts on `line_number` (1-indexed).
1771    pub fn images_on_line(&self, line_number: usize) -> &[ParsedImage<'a>] {
1772        let start = self.images.partition_point(|image| image.line < line_number);
1773        let end = self.images.partition_point(|image| image.line <= line_number);
1774        &self.images[start..end]
1775    }
1776
1777    /// Find the link that starts at an exact byte offset. O(log n).
1778    pub fn link_starting_at(&self, byte_offset: usize) -> Option<&ParsedLink<'a>> {
1779        self.links
1780            .binary_search_by_key(&byte_offset, |link| link.byte_offset)
1781            .ok()
1782            .map(|index| &self.links[index])
1783    }
1784
1785    /// Find the image that starts at an exact byte offset. O(log n).
1786    pub fn image_starting_at(&self, byte_offset: usize) -> Option<&ParsedImage<'a>> {
1787        self.images
1788            .binary_search_by_key(&byte_offset, |image| image.byte_offset)
1789            .ok()
1790            .map(|index| &self.images[index])
1791    }
1792
1793    /// Find the parsed link containing `byte_offset`. O(log n).
1794    pub fn link_containing(&self, byte_offset: usize) -> Option<&ParsedLink<'a>> {
1795        let index = self.links.partition_point(|link| link.byte_offset <= byte_offset);
1796        self.links
1797            .get(index.checked_sub(1)?)
1798            .filter(|link| byte_offset < link.byte_end)
1799    }
1800
1801    /// Find the parsed image containing `byte_offset`. O(log n).
1802    pub fn image_containing(&self, byte_offset: usize) -> Option<&ParsedImage<'a>> {
1803        let index = self.images.partition_point(|image| image.byte_offset <= byte_offset);
1804        self.images
1805            .get(index.checked_sub(1)?)
1806            .filter(|image| byte_offset < image.byte_end)
1807    }
1808
1809    /// Links that start at or before `byte_offset`, in document order. O(log n).
1810    pub fn links_starting_before_or_at(&self, byte_offset: usize) -> &[ParsedLink<'a>] {
1811        let end = self.links.partition_point(|link| link.byte_offset <= byte_offset);
1812        &self.links[..end]
1813    }
1814
1815    /// Find a reference definition by its case-insensitive identifier.
1816    pub fn reference_definition(&self, ref_id: &str) -> Option<&ReferenceDef> {
1817        let normalized_id = ref_id.to_lowercase();
1818        self.reference_defs_map
1819            .get(&normalized_id)
1820            .map(|&index| &self.reference_defs[index])
1821    }
1822
1823    /// Get URL for a reference link/image by its ID (O(1) lookup via HashMap)
1824    pub fn get_reference_url(&self, ref_id: &str) -> Option<&str> {
1825        self.reference_definition(ref_id)
1826            .map(|definition| definition.url.as_str())
1827    }
1828
1829    /// Check if a line is part of a list block
1830    pub fn is_in_list_block(&self, line_num: usize) -> bool {
1831        if line_num == 0 || line_num > self.lines.len() {
1832            return false;
1833        }
1834        self.lines[line_num - 1].in_list_block
1835    }
1836
1837    /// Check if a line is within an HTML block
1838    pub fn is_in_html_block(&self, line_num: usize) -> bool {
1839        if line_num == 0 || line_num > self.lines.len() {
1840            return false;
1841        }
1842        self.lines[line_num - 1].in_html_block
1843    }
1844
1845    /// Check if a 1-indexed line number is inside a GFM table block.
1846    ///
1847    /// Returns `true` for the header line, delimiter line, and all body rows.
1848    /// `TableBlock` spans are stored 0-indexed; this helper accepts the
1849    /// 1-indexed line numbers used elsewhere in the rule API.
1850    pub fn is_in_table_block(&self, line_num: usize) -> bool {
1851        if line_num == 0 || line_num > self.lines.len() {
1852            return false;
1853        }
1854        self.lines[line_num - 1].in_table_block
1855    }
1856
1857    /// Check if a line and column is within a code span
1858    pub fn is_in_code_span(&self, line_num: usize, col: usize) -> bool {
1859        if line_num == 0 || line_num > self.lines.len() {
1860            return false;
1861        }
1862
1863        // Use the code spans cache to check
1864        // Note: col is 1-indexed from caller, but span.start_col and span.end_col are 0-indexed
1865        // Convert col to 0-indexed for comparison
1866        let col_0indexed = if col > 0 { col - 1 } else { 0 };
1867        let code_spans = self.code_spans();
1868        code_spans.iter().any(|span| {
1869            // Check if line is within the span's line range
1870            if line_num < span.line || line_num > span.end_line {
1871                return false;
1872            }
1873
1874            if span.line == span.end_line {
1875                // Single-line span: check column bounds
1876                col_0indexed >= span.start_col && col_0indexed < span.end_col
1877            } else if line_num == span.line {
1878                // First line of multi-line span: anything after start_col is in span
1879                col_0indexed >= span.start_col
1880            } else if line_num == span.end_line {
1881                // Last line of multi-line span: anything before end_col is in span
1882                col_0indexed < span.end_col
1883            } else {
1884                // Middle line of multi-line span: entire line is in span
1885                true
1886            }
1887        })
1888    }
1889
1890    /// Check if a byte offset is within a code span. O(log n).
1891    #[inline]
1892    pub fn is_byte_offset_in_code_span(&self, byte_offset: usize) -> bool {
1893        let code_spans = self.code_spans();
1894        let idx = code_spans.partition_point(|span| span.byte_offset <= byte_offset);
1895        idx > 0 && byte_offset < code_spans[idx - 1].byte_end
1896    }
1897
1898    /// Check if a byte position is within a reference definition. O(log n).
1899    #[inline]
1900    pub fn is_in_reference_def(&self, byte_pos: usize) -> bool {
1901        let idx = self.reference_defs.partition_point(|rd| rd.byte_offset <= byte_pos);
1902        idx > 0 && byte_pos < self.reference_defs[idx - 1].byte_end
1903    }
1904
1905    /// Check if a byte position is within an HTML comment. O(log n).
1906    #[inline]
1907    pub fn is_in_html_comment(&self, byte_pos: usize) -> bool {
1908        let idx = self.html_comment_ranges.partition_point(|r| r.start <= byte_pos);
1909        idx > 0 && byte_pos < self.html_comment_ranges[idx - 1].end
1910    }
1911
1912    /// Check if a byte position is within an HTML tag (including multiline tags).
1913    /// Uses the pre-parsed html_tags which correctly handles tags spanning multiple lines. O(log n).
1914    #[inline]
1915    pub fn is_in_html_tag(&self, byte_pos: usize) -> bool {
1916        let tags = self.html_tags();
1917        let idx = tags.partition_point(|tag| tag.byte_offset <= byte_pos);
1918        idx > 0 && byte_pos < tags[idx - 1].byte_end
1919    }
1920
1921    /// Check if a byte position is within a JSX component tag (e.g. `<Card .../>`),
1922    /// including its attribute values and multiline tags. Always false for flavors
1923    /// without JSX support. O(log n).
1924    #[inline]
1925    pub fn is_in_jsx_component_tag(&self, byte_pos: usize) -> bool {
1926        if !self.flavor.supports_jsx() {
1927            return false;
1928        }
1929        let tags = self.jsx_component_tags();
1930        let idx = tags.partition_point(|tag| tag.byte_offset <= byte_pos);
1931        idx > 0 && byte_pos < tags[idx - 1].byte_end
1932    }
1933
1934    /// Check if a byte position is within a Jinja template ({{ }} or {% %}). O(log n).
1935    pub fn is_in_jinja_range(&self, byte_pos: usize) -> bool {
1936        Self::binary_search_ranges(&self.jinja_ranges, byte_pos)
1937    }
1938
1939    /// Check if a byte position is within a JSX expression (MDX: {expression}). O(log n).
1940    #[inline]
1941    pub fn is_in_jsx_expression(&self, byte_pos: usize) -> bool {
1942        Self::binary_search_ranges(&self.jsx_expression_ranges, byte_pos)
1943    }
1944
1945    /// Check if a byte position is within an MDX comment ({/* ... */}). O(log n).
1946    #[inline]
1947    pub fn is_in_mdx_comment(&self, byte_pos: usize) -> bool {
1948        Self::binary_search_ranges(&self.mdx_comment_ranges, byte_pos)
1949    }
1950
1951    /// Check if a byte position is within a Pandoc/Quarto citation (`@key` or `[@key]`).
1952    /// Active for Pandoc-compatible flavors. O(log n).
1953    #[inline]
1954    pub fn is_in_citation(&self, byte_pos: usize) -> bool {
1955        let idx = self.citation_ranges.partition_point(|r| r.start <= byte_pos);
1956        idx > 0 && byte_pos < self.citation_ranges[idx - 1].end
1957    }
1958
1959    /// Pre-computed Pandoc/Quarto citation ranges.
1960    #[inline]
1961    pub fn citation_ranges(&self) -> &[crate::utils::skip_context::ByteRange] {
1962        &self.citation_ranges
1963    }
1964
1965    /// Check if a byte position is within a Pandoc/Quarto div block (`::: ... :::`).
1966    /// Active for Pandoc-compatible flavors. O(log n) via binary search over sorted ranges.
1967    #[inline]
1968    pub fn is_in_div_block(&self, byte_pos: usize) -> bool {
1969        let idx = self.pandoc_div_ranges.partition_point(|r| r.start <= byte_pos);
1970        idx > 0 && byte_pos < self.pandoc_div_ranges[idx - 1].end
1971    }
1972
1973    /// Check if a byte position is within a Pandoc inline footnote (`^[note text]`).
1974    /// Active for Pandoc-compatible flavors. O(log n).
1975    #[inline]
1976    pub fn is_in_inline_footnote(&self, byte_pos: usize) -> bool {
1977        let idx = self.inline_footnote_ranges.partition_point(|r| r.start <= byte_pos);
1978        idx > 0 && byte_pos < self.inline_footnote_ranges[idx - 1].end
1979    }
1980
1981    /// Check if a byte position is within a Pandoc example-list marker (`(@)` /
1982    /// `(@label)` at line start). Active for Pandoc-compatible flavors. O(log n).
1983    #[inline]
1984    pub fn is_in_example_list_marker(&self, byte_pos: usize) -> bool {
1985        let idx = self.example_list_marker_ranges.partition_point(|r| r.start <= byte_pos);
1986        idx > 0 && byte_pos < self.example_list_marker_ranges[idx - 1].end
1987    }
1988
1989    /// Check if a byte position is within a Pandoc example reference (`(@label)`
1990    /// inline). Active for Pandoc-compatible flavors. O(log n).
1991    #[inline]
1992    pub fn is_in_example_reference(&self, byte_pos: usize) -> bool {
1993        let idx = self.example_reference_ranges.partition_point(|r| r.start <= byte_pos);
1994        idx > 0 && byte_pos < self.example_reference_ranges[idx - 1].end
1995    }
1996
1997    /// Check if a byte position is within a Pandoc subscript (`~x~`) or
1998    /// superscript (`^x^`) span. Active for Pandoc-compatible flavors. O(log n).
1999    #[inline]
2000    pub fn is_in_subscript_or_superscript(&self, byte_pos: usize) -> bool {
2001        let idx = self.sub_super_ranges.partition_point(|r| r.start <= byte_pos);
2002        idx > 0 && byte_pos < self.sub_super_ranges[idx - 1].end
2003    }
2004
2005    /// Check if a byte position is within a Pandoc inline-code attribute block
2006    /// (`{.lang}` immediately following `` `code` ``). Active for Pandoc-compatible
2007    /// flavors. O(log n).
2008    #[inline]
2009    pub fn is_in_inline_code_attr(&self, byte_pos: usize) -> bool {
2010        let idx = self.inline_code_attr_ranges.partition_point(|r| r.start <= byte_pos);
2011        idx > 0 && byte_pos < self.inline_code_attr_ranges[idx - 1].end
2012    }
2013
2014    /// Check if a byte position is within a Pandoc bracketed span (`[text]{attrs}`).
2015    /// Active for Pandoc-compatible flavors. O(log n).
2016    #[inline]
2017    pub fn is_in_bracketed_span(&self, byte_pos: usize) -> bool {
2018        let idx = self.bracketed_span_ranges.partition_point(|r| r.start <= byte_pos);
2019        idx > 0 && byte_pos < self.bracketed_span_ranges[idx - 1].end
2020    }
2021
2022    /// Returns true if `byte_pos` falls inside a Pandoc line block (`| text`).
2023    /// Active for Pandoc-compatible flavors. O(log n).
2024    #[inline]
2025    pub fn is_in_line_block(&self, byte_pos: usize) -> bool {
2026        let idx = self.line_block_ranges.partition_point(|r| r.start <= byte_pos);
2027        idx > 0 && byte_pos < self.line_block_ranges[idx - 1].end
2028    }
2029
2030    /// Returns true if `byte_pos` falls inside a Pandoc pipe-table caption
2031    /// (`: caption` adjacent to a pipe table). Active for Pandoc-compatible
2032    /// flavors. O(log n).
2033    #[inline]
2034    pub fn is_in_pipe_table_caption(&self, byte_pos: usize) -> bool {
2035        let idx = self.pipe_table_caption_ranges.partition_point(|r| r.start <= byte_pos);
2036        idx > 0 && byte_pos < self.pipe_table_caption_ranges[idx - 1].end
2037    }
2038
2039    /// Returns true if `byte_pos` falls inside a Pandoc YAML metadata block.
2040    /// Active for Pandoc-compatible flavors. O(log n).
2041    #[inline]
2042    pub fn is_in_pandoc_metadata(&self, byte_pos: usize) -> bool {
2043        let idx = self.pandoc_metadata_ranges.partition_point(|r| r.start <= byte_pos);
2044        idx > 0 && byte_pos < self.pandoc_metadata_ranges[idx - 1].end
2045    }
2046
2047    /// Returns true if `byte_pos` falls inside a Pandoc grid table.
2048    /// Active for Pandoc-compatible flavors. O(log n).
2049    #[inline]
2050    pub fn is_in_grid_table(&self, byte_pos: usize) -> bool {
2051        let idx = self.grid_table_ranges.partition_point(|r| r.start <= byte_pos);
2052        idx > 0 && byte_pos < self.grid_table_ranges[idx - 1].end
2053    }
2054
2055    /// Returns true if `byte_pos` falls inside a Pandoc multi-line table.
2056    /// Active for Pandoc-compatible flavors. O(log n).
2057    #[inline]
2058    pub fn is_in_multi_line_table(&self, byte_pos: usize) -> bool {
2059        let idx = self.multi_line_table_ranges.partition_point(|r| r.start <= byte_pos);
2060        idx > 0 && byte_pos < self.multi_line_table_ranges[idx - 1].end
2061    }
2062
2063    /// Returns true if `link_text`, after Pandoc slugification, matches a heading
2064    /// in the document. Returns false for non-Pandoc-compatible flavors because
2065    /// the `pandoc_header_slugs` set is empty when the pre-pass detector is gated
2066    /// off. Use this when the caller has raw bracketed text (`[Section name]`).
2067    pub fn matches_implicit_header_reference(&self, link_text: &str) -> bool {
2068        let slug = crate::utils::pandoc::pandoc_header_slug(link_text);
2069        self.pandoc_header_slugs.contains(&slug)
2070    }
2071
2072    /// Returns true if `slug` (already in Pandoc-slug form) matches a heading
2073    /// in the document. Returns false for non-Pandoc-compatible flavors because
2074    /// the `pandoc_header_slugs` set is empty when the pre-pass detector is gated
2075    /// off. Use this when the caller already has a slug (e.g. the fragment of a
2076    /// URL after `#`). O(1).
2077    #[inline]
2078    pub fn has_pandoc_slug(&self, slug: &str) -> bool {
2079        self.pandoc_header_slugs.contains(slug)
2080    }
2081
2082    /// Check if a byte position is within a Hugo/Quarto shortcode ({{< ... >}} or {{% ... %}}). O(log n).
2083    #[inline]
2084    pub fn is_in_shortcode(&self, byte_pos: usize) -> bool {
2085        Self::binary_search_ranges(&self.shortcode_ranges, byte_pos)
2086    }
2087
2088    /// Pre-computed Hugo/Quarto shortcode ranges.
2089    #[inline]
2090    pub fn shortcode_ranges(&self) -> &[(usize, usize)] {
2091        &self.shortcode_ranges
2092    }
2093
2094    /// Check if a byte position is within a link reference definition title. O(log n).
2095    pub fn is_in_link_title(&self, byte_pos: usize) -> bool {
2096        Self::binary_search_ranges(&self.link_title_ranges, byte_pos)
2097    }
2098
2099    /// Check if content has any instances of a specific character (fast)
2100    pub fn has_char(&self, ch: char) -> bool {
2101        match ch {
2102            '#' => self.char_frequency.hash_count > 0,
2103            '*' => self.char_frequency.asterisk_count > 0,
2104            '_' => self.char_frequency.underscore_count > 0,
2105            '-' => self.char_frequency.hyphen_count > 0,
2106            '+' => self.char_frequency.plus_count > 0,
2107            '>' => self.char_frequency.gt_count > 0,
2108            '|' => self.char_frequency.pipe_count > 0,
2109            '[' => self.char_frequency.bracket_count > 0,
2110            '`' => self.char_frequency.backtick_count > 0,
2111            '<' => self.char_frequency.lt_count > 0,
2112            '!' => self.char_frequency.exclamation_count > 0,
2113            '\n' => self.char_frequency.newline_count > 0,
2114            _ => self.content.contains(ch), // Fallback for other characters
2115        }
2116    }
2117
2118    /// Get count of a specific character (fast)
2119    pub fn char_count(&self, ch: char) -> usize {
2120        match ch {
2121            '#' => self.char_frequency.hash_count,
2122            '*' => self.char_frequency.asterisk_count,
2123            '_' => self.char_frequency.underscore_count,
2124            '-' => self.char_frequency.hyphen_count,
2125            '+' => self.char_frequency.plus_count,
2126            '>' => self.char_frequency.gt_count,
2127            '|' => self.char_frequency.pipe_count,
2128            '[' => self.char_frequency.bracket_count,
2129            '`' => self.char_frequency.backtick_count,
2130            '<' => self.char_frequency.lt_count,
2131            '!' => self.char_frequency.exclamation_count,
2132            '\n' => self.char_frequency.newline_count,
2133            _ => self.content.matches(ch).count(), // Fallback for other characters
2134        }
2135    }
2136
2137    /// Check if content likely contains headings (fast)
2138    pub fn likely_has_headings(&self) -> bool {
2139        self.char_frequency.hash_count > 0 || self.char_frequency.hyphen_count > 2 || self.content.contains('=') // Setext H1 underlines use '='
2140    }
2141
2142    /// Check if content likely contains unordered lists (fast). Only bullet
2143    /// characters are counted, so an ordered-only document answers false;
2144    /// rules about ordered lists read `commonmark_ordered_lists` instead.
2145    pub fn likely_has_lists(&self) -> bool {
2146        self.char_frequency.asterisk_count > 0
2147            || self.char_frequency.hyphen_count > 0
2148            || self.char_frequency.plus_count > 0
2149    }
2150
2151    /// Check if content likely contains emphasis (fast)
2152    pub fn likely_has_emphasis(&self) -> bool {
2153        self.char_frequency.asterisk_count > 1 || self.char_frequency.underscore_count > 1
2154    }
2155
2156    /// Check if content likely contains tables (fast)
2157    pub fn likely_has_tables(&self) -> bool {
2158        self.char_frequency.pipe_count > 2
2159    }
2160
2161    /// Check if content likely contains blockquotes (fast)
2162    pub fn likely_has_blockquotes(&self) -> bool {
2163        self.char_frequency.gt_count > 0
2164    }
2165
2166    /// Check if content likely contains code (fast)
2167    pub fn likely_has_code(&self) -> bool {
2168        self.char_frequency.backtick_count > 0
2169    }
2170
2171    /// Check if content likely contains links or images (fast)
2172    pub fn likely_has_links_or_images(&self) -> bool {
2173        self.char_frequency.bracket_count > 0 || self.char_frequency.exclamation_count > 0
2174    }
2175
2176    /// Check if content likely contains HTML (fast)
2177    pub fn likely_has_html(&self) -> bool {
2178        self.char_frequency.lt_count > 0
2179    }
2180
2181    /// Get the blockquote prefix for inserting a blank line at the given line index.
2182    /// Returns the prefix without trailing content (e.g., ">" or ">>").
2183    /// This is needed because blank lines inside blockquotes must preserve the blockquote structure.
2184    /// Returns an empty string if the line is not inside a blockquote.
2185    pub fn blockquote_prefix_for_blank_line(&self, line_idx: usize) -> String {
2186        if let Some(line_info) = self.lines.get(line_idx)
2187            && let Some(ref bq) = line_info.blockquote
2188        {
2189            bq.prefix.trim_end().to_string()
2190        } else {
2191            String::new()
2192        }
2193    }
2194
2195    /// Find the line index for a given byte offset using binary search.
2196    /// Returns (line_index, line_number, column) where:
2197    /// - line_index is the 0-based index in the lines array
2198    /// - line_number is the 1-based line number
2199    /// - column is the 0-based *character* offset within that line
2200    ///
2201    /// The column is a character offset rather than a byte offset so that the
2202    /// `start_col`/`end_col` it feeds into match rumdl's diagnostic convention
2203    /// (columns are character positions). On lines with multi-byte UTF-8
2204    /// characters the two differ; reporting bytes would mis-position highlights.
2205    #[inline]
2206    fn find_line_for_offset(lines: &[LineInfo], content: &str, byte_offset: usize) -> (usize, usize, usize) {
2207        // Binary search to find the line containing this byte offset
2208        let idx = match lines.binary_search_by(|line| {
2209            if byte_offset < line.byte_offset {
2210                std::cmp::Ordering::Greater
2211            } else if byte_offset > line.byte_offset + line.byte_len {
2212                std::cmp::Ordering::Less
2213            } else {
2214                std::cmp::Ordering::Equal
2215            }
2216        }) {
2217            Ok(idx) => idx,
2218            Err(idx) => idx.saturating_sub(1),
2219        };
2220
2221        let line = &lines[idx];
2222        let line_num = idx + 1;
2223        let byte_col = byte_offset.saturating_sub(line.byte_offset);
2224        // Convert the byte offset within the line to a 0-based character column.
2225        // `byte_to_char_count` returns a 1-based value, so subtract 1.
2226        let col = byte_to_char_count(line.content(content), byte_col) - 1;
2227
2228        (idx, line_num, col)
2229    }
2230
2231    /// Check if a byte offset is within a code span using binary search
2232    #[inline]
2233    fn is_offset_in_code_span(code_spans: &[CodeSpan], offset: usize) -> bool {
2234        // Since spans are sorted by byte_offset, use partition_point for binary search
2235        let idx = code_spans.partition_point(|span| span.byte_offset <= offset);
2236
2237        // Check the span that starts at or before our offset
2238        if idx > 0 {
2239            let span = &code_spans[idx - 1];
2240            if offset >= span.byte_offset && offset < span.byte_end {
2241                return true;
2242            }
2243        }
2244
2245        false
2246    }
2247
2248    /// Get an iterator over valid headings (skipping invalid ones like `#NoSpace`)
2249    ///
2250    /// Valid headings have proper spacing after the `#` markers (or are level > 1).
2251    /// This is the standard iterator for rules that need to process headings.
2252    ///
2253    /// # Examples
2254    ///
2255    /// ```
2256    /// use rumdl_lib::lint_context::LintContext;
2257    /// use rumdl_lib::config::MarkdownFlavor;
2258    ///
2259    /// let content = "# Valid Heading\n#NoSpace\n## Another Valid";
2260    /// let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
2261    ///
2262    /// for heading in ctx.valid_headings() {
2263    ///     println!("Line {}: {} (level {})", heading.line_num, heading.heading.text, heading.heading.level);
2264    /// }
2265    /// // Only prints valid headings, skips `#NoSpace`
2266    /// ```
2267    #[must_use]
2268    pub fn valid_headings(&self) -> ValidHeadingsIter<'_> {
2269        ValidHeadingsIter::new(&self.lines)
2270    }
2271
2272    /// Check if the document contains any valid CommonMark headings
2273    ///
2274    /// Returns `true` if there is at least one heading with proper space after `#`.
2275    #[must_use]
2276    pub fn has_valid_headings(&self) -> bool {
2277        self.lines
2278            .iter()
2279            .any(|line| line.heading.as_ref().is_some_and(|h| h.is_valid))
2280    }
2281
2282    /// Iterate over every parsed list item in source order.
2283    #[must_use]
2284    pub fn list_items(&self) -> ParsedListItemsIter<'_> {
2285        ParsedListItemsIter::new(&self.lines)
2286    }
2287
2288    /// Return the parsed list item on a 1-indexed source line, if any.
2289    #[must_use]
2290    pub fn list_item_on_line(&self, line_num: usize) -> Option<ParsedListItem<'_>> {
2291        let line_info = self.lines.get(line_num.checked_sub(1)?)?;
2292        Some(ParsedListItem::new(
2293            line_num,
2294            line_info.list_item.as_deref()?,
2295            line_info,
2296        ))
2297    }
2298
2299    /// Borrow the document's parsed list blocks and their item iterators.
2300    #[must_use]
2301    pub fn parsed_list_blocks(&self) -> ParsedListBlocks<'_> {
2302        ParsedListBlocks::new(&self.list_blocks, &self.lines)
2303    }
2304
2305    /// The item lines of `block` grouped into the lists they form, one group
2306    /// per list as CommonMark nests them, in source order, so siblings can be
2307    /// compared without the nested items that sit between them.
2308    #[must_use]
2309    pub fn list_block_item_groups(&self, block: &ListBlock) -> Vec<Vec<usize>> {
2310        list_blocks::item_lines_by_list(self.content, &self.lines, block)
2311    }
2312
2313    /// Whether the document contains any parsed list items.
2314    #[must_use]
2315    pub fn has_list_items(&self) -> bool {
2316        self.lines.iter().any(|line| line.list_item.is_some())
2317    }
2318
2319    /// Whether the document contains any parsed unordered-list items.
2320    #[must_use]
2321    pub fn has_unordered_list_items(&self) -> bool {
2322        self.lines
2323            .iter()
2324            .any(|line| line.list_item.as_ref().is_some_and(|item| !item.is_ordered))
2325    }
2326
2327    /// Borrow ordered lists using the membership and start values determined by CommonMark.
2328    #[must_use]
2329    pub fn commonmark_ordered_lists(&self) -> CommonMarkOrderedLists<'_> {
2330        let lists = self
2331            .commonmark_ordered_lists_cache
2332            .get_or_init(|| build_commonmark_ordered_lists(&self.lines, &self.line_to_list, &self.list_start_values));
2333        CommonMarkOrderedLists::new(lists, &self.lines)
2334    }
2335
2336    /// Iterate over every heading recognized in the rendered document.
2337    ///
2338    /// This includes top-level ATX and Setext headings, ATX headings nested in
2339    /// blockquotes, and malformed top-level ATX headings retained for
2340    /// diagnostics. Code blocks, front matter, raw HTML blocks, and
2341    /// flavor-specific non-Markdown regions are excluded during parsing;
2342    /// explicitly Markdown-enabled HTML containers remain eligible.
2343    #[must_use]
2344    pub fn headings(&self) -> ParsedHeadingsIter<'_> {
2345        ParsedHeadingsIter::new(&self.lines, &self.blockquote_headings)
2346    }
2347
2348    /// Return the parsed heading on a 1-indexed source line, if any.
2349    #[must_use]
2350    pub fn heading_on_line(&self, line_num: usize) -> Option<ParsedHeading<'_>> {
2351        let idx = line_num.checked_sub(1)?;
2352        let line_info = self.lines.get(idx)?;
2353        let (heading, blockquote_depth) = match line_info.heading.as_deref() {
2354            Some(heading) => (heading, 0),
2355            None => (
2356                self.blockquote_headings.get(idx)?.as_deref()?,
2357                line_info.blockquote.as_ref().map_or(0, |bq| bq.nesting_level),
2358            ),
2359        };
2360        Some(ParsedHeading {
2361            line_num,
2362            heading,
2363            line_info,
2364            blockquote_depth,
2365        })
2366    }
2367}
2368
2369/// The range an unclosed `<!--` hides when it opens a block the parser missed.
2370///
2371/// A MkDocs admonition or a `<div markdown>` body is rendered as markdown in its
2372/// own right, so a `<!--` starting one of its lines opens an HTML block there
2373/// just as it would at the top level. The parser has no notion of either
2374/// container, reads the body as indented code or as a lazy paragraph
2375/// continuation, and so reports no block for the opener to run to the end of.
2376///
2377/// The block ends where the container's body ends, which is what CommonMark
2378/// gives an unclosed comment in any other container. An opener that is not the
2379/// first thing on its line is inline HTML and opens nothing, here as anywhere.
2380fn container_comment_range(
2381    opener: usize,
2382    containers: &flavor_detection::ContainerLines,
2383    lines: &[types::LineInfo],
2384    content: &str,
2385) -> Option<crate::utils::skip_context::ByteRange> {
2386    let line_index = lines
2387        .partition_point(|line| line.byte_offset <= opener)
2388        .checked_sub(1)?;
2389    let line = lines.get(line_index)?;
2390    if line.byte_offset + line.indent != opener {
2391        return None;
2392    }
2393    if !containers.is_container_body(line_index) {
2394        return None;
2395    }
2396    let end_line = lines.get(containers.body_end_line(line_index)?)?;
2397    Some(crate::utils::skip_context::ByteRange {
2398        start: opener,
2399        end: (end_line.byte_offset + end_line.byte_len).min(content.len()),
2400    })
2401}
2402
2403/// Detect footnote definitions and mark their continuation lines.
2404///
2405/// Uses pulldown-cmark to find footnote definition ranges and fenced code
2406/// blocks within them, then:
2407/// 1. Sets `in_footnote_definition = true` on all lines within
2408/// 2. Clears `in_code_block = false` on continuation lines that were
2409///    misidentified as indented code blocks (but preserves real fenced
2410///    code blocks within footnotes)
2411fn detect_footnote_definitions(content: &str, lines: &mut [types::LineInfo], line_offsets: &[usize]) {
2412    use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag, TagEnd};
2413
2414    let options = crate::utils::rumdl_parser_options();
2415    let parser = Parser::new_ext(content, options).into_offset_iter();
2416
2417    // Collect footnote ranges and fenced code block ranges within them
2418    let mut footnote_ranges: Vec<(usize, usize)> = Vec::new();
2419    let mut fenced_code_ranges: Vec<(usize, usize)> = Vec::new();
2420    let mut in_footnote = false;
2421
2422    for (event, range) in parser {
2423        match event {
2424            Event::Start(Tag::FootnoteDefinition(_)) => {
2425                in_footnote = true;
2426                footnote_ranges.push((range.start, range.end));
2427            }
2428            Event::End(TagEnd::FootnoteDefinition) => {
2429                in_footnote = false;
2430            }
2431            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(_))) if in_footnote => {
2432                fenced_code_ranges.push((range.start, range.end));
2433            }
2434            _ => {}
2435        }
2436    }
2437
2438    let byte_to_line = |byte_offset: usize| -> usize {
2439        line_offsets
2440            .partition_point(|&offset| offset <= byte_offset)
2441            .saturating_sub(1)
2442    };
2443
2444    // Mark footnote definition lines
2445    for &(start, end) in &footnote_ranges {
2446        let start_line = byte_to_line(start);
2447        let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
2448
2449        for line in &mut lines[start_line..end_line] {
2450            line.in_footnote_definition = true;
2451            line.in_code_block = false;
2452        }
2453    }
2454
2455    // Restore in_code_block for fenced code blocks within footnotes
2456    for &(start, end) in &fenced_code_ranges {
2457        let start_line = byte_to_line(start);
2458        let end_line = line_offsets.partition_point(|&offset| offset < end).min(lines.len());
2459
2460        for line in &mut lines[start_line..end_line] {
2461            line.in_code_block = true;
2462        }
2463    }
2464}