Skip to main content

rumdl_lib/lint_context/
types.rs

1use pulldown_cmark::LinkType;
2use std::borrow::Cow;
3
4/// Pre-computed information about a line
5#[derive(Debug, Clone)]
6pub struct LineInfo {
7    /// Byte offset where this line starts in the document
8    pub byte_offset: usize,
9    /// Length of the line in bytes (without newline)
10    pub byte_len: usize,
11    /// Number of bytes of leading whitespace (for substring extraction)
12    pub indent: usize,
13    /// Visual column width of leading whitespace (with proper tab expansion)
14    /// Per CommonMark, tabs expand to the next column that is a multiple of 4.
15    /// Use this for numeric comparisons like checking for indented code blocks (>= 4).
16    pub visual_indent: usize,
17    /// Whether the line is blank (empty or only whitespace)
18    pub is_blank: bool,
19    /// Whether this line is inside a code block
20    pub in_code_block: bool,
21    /// Whether this line is inside front matter
22    pub in_front_matter: bool,
23    /// Whether this line is inside an HTML block
24    pub in_html_block: bool,
25    /// Whether this line is part of a list block (precomputed for O(1) lookup)
26    pub in_list_block: bool,
27    /// Whether this line is part of a table block (precomputed for O(1) lookup)
28    pub in_table_block: bool,
29    /// Whether this line is inside an HTML comment
30    pub in_html_comment: bool,
31    /// List item information if this line starts a list item
32    /// Boxed to reduce LineInfo size: most lines are not list items
33    pub list_item: Option<Box<ListItemInfo>>,
34    /// Heading information if this line is a heading
35    /// Boxed to reduce LineInfo size: most lines are not headings
36    pub heading: Option<Box<HeadingInfo>>,
37    /// Blockquote information if this line is a blockquote
38    /// Boxed to reduce LineInfo size: most lines are not blockquotes
39    pub blockquote: Option<Box<BlockquoteInfo>>,
40    /// Whether this line is inside a mkdocstrings autodoc block
41    pub in_mkdocstrings: bool,
42    /// Whether this line is part of an ESM import/export block (MDX only)
43    pub in_esm_block: bool,
44    /// Whether this line is a continuation of a multi-line code span from a previous line
45    pub in_code_span_continuation: bool,
46    /// Whether this line is a horizontal rule (---, ***, ___, etc.)
47    /// Pre-computed for consistent detection across all rules
48    pub is_horizontal_rule: bool,
49    /// Whether this line is inside a math block ($$ ... $$)
50    pub in_math_block: bool,
51    /// Whether this line is inside a Pandoc/Quarto div block (::: ... :::)
52    pub in_pandoc_div: bool,
53    /// Whether this line is a Quarto/Pandoc div marker (opening ::: {.class} or closing :::)
54    /// Analogous to `is_horizontal_rule` — marks structural delimiters that are not paragraph text
55    pub is_div_marker: bool,
56    /// Whether this line contains or is inside a JSX expression (MDX only)
57    pub in_jsx_expression: bool,
58    /// Whether this line is inside an MDX comment {/* ... */} (MDX only)
59    pub in_mdx_comment: bool,
60    /// Whether this line is inside an MkDocs admonition block (!!! or ???)
61    pub in_admonition: bool,
62    /// Whether this line is inside an MkDocs content tab block (===)
63    pub in_content_tab: bool,
64    /// Whether this line is inside an HTML block with markdown attribute (MkDocs grid cards, etc.)
65    pub in_mkdocs_html_markdown: bool,
66    /// Whether this line is a definition list item (: definition)
67    pub in_definition_list: bool,
68    /// Whether this line is inside an Obsidian comment (%%...%% syntax, Obsidian flavor only)
69    pub in_obsidian_comment: bool,
70    /// Whether this line is inside a PyMdown Blocks region (/// ... ///, MkDocs flavor only)
71    pub in_pymdown_block: bool,
72    /// Whether this line is inside a kramdown extension block ({::comment}...{:/comment}, {::nomarkdown}...{:/nomarkdown})
73    pub in_kramdown_extension_block: bool,
74    /// Whether this line is a kramdown block IAL ({:.class #id}) or ALD ({:ref: .class})
75    pub is_kramdown_block_ial: bool,
76    /// Whether this line is inside a JSX component block (MDX only, e.g. `<Tabs>...</Tabs>`)
77    pub in_jsx_block: bool,
78    /// Whether this line is inside a footnote definition body (continuation lines)
79    pub in_footnote_definition: bool,
80    /// Whether this line is inside a MyST directive block (colon or backtick fence with `{name}`)
81    pub in_myst_directive: bool,
82    /// Whether this line is a MyST comment (`% comment`)
83    pub is_myst_comment: bool,
84}
85
86impl LineInfo {
87    /// Get the line content as a string slice from the source document
88    pub fn content<'a>(&self, source: &'a str) -> &'a str {
89        &source[self.byte_offset..self.byte_offset + self.byte_len]
90    }
91
92    /// Check if this line is inside MkDocs-specific indented content (admonitions, tabs, or markdown HTML).
93    /// This content uses 4-space indentation which pulldown-cmark would interpret as code blocks,
94    /// but in MkDocs flavor it's actually container content that should be preserved.
95    #[inline]
96    pub fn in_mkdocs_container(&self) -> bool {
97        self.in_admonition || self.in_content_tab || self.in_mkdocs_html_markdown
98    }
99
100    /// Whether this line could be part of a paragraph block (CommonMark `paragraph` token).
101    ///
102    /// Returns true for ordinary prose lines, including those inside blockquotes and list items.
103    /// Returns false for lines that belong to non-paragraph blocks: headings, code blocks,
104    /// HTML blocks, math blocks, horizontal rules, front matter, structural div markers, and
105    /// flavor-specific extension blocks. This is the per-line view; cross-line constructs like
106    /// setext underlines aren't visible here and need additional context to detect.
107    ///
108    /// Used by rules (e.g. MD009 strict mode) that need to distinguish "trailing whitespace
109    /// could produce a meaningful `<br>`" from "trailing whitespace is on a structural boundary."
110    #[inline]
111    pub fn is_paragraph_context(&self) -> bool {
112        !self.in_code_block
113            && !self.in_front_matter
114            && !self.in_html_block
115            && !self.in_html_comment
116            && !self.in_math_block
117            && !self.is_horizontal_rule
118            && !self.is_div_marker
119            && !self.in_pymdown_block
120            && !self.in_kramdown_extension_block
121            && !self.is_kramdown_block_ial
122            && !self.is_myst_comment
123            && self.heading.is_none()
124    }
125}
126
127/// Information about a list item
128#[derive(Debug, Clone)]
129pub struct ListItemInfo {
130    /// The marker used (*, -, +, or number with . or ))
131    pub marker: String,
132    /// Whether it's ordered (true) or unordered (false)
133    pub is_ordered: bool,
134    /// The number for ordered lists
135    pub number: Option<usize>,
136    /// Column where the marker starts (0-based)
137    pub marker_column: usize,
138    /// Column where content after marker starts
139    pub content_column: usize,
140}
141
142/// Heading style type
143#[derive(Debug, Clone, PartialEq)]
144pub enum HeadingStyle {
145    /// ATX style heading (# Heading)
146    ATX,
147    /// Setext style heading with = underline
148    Setext1,
149    /// Setext style heading with - underline
150    Setext2,
151}
152
153/// Parsed link information
154#[derive(Debug, Clone)]
155pub struct ParsedLink<'a> {
156    /// Line number (1-indexed)
157    pub line: usize,
158    /// Start column (0-indexed) in the line
159    pub start_col: usize,
160    /// End column (0-indexed) in the line
161    pub end_col: usize,
162    /// Byte offset in document
163    pub byte_offset: usize,
164    /// End byte offset in document
165    pub byte_end: usize,
166    /// Link text
167    pub text: Cow<'a, str>,
168    /// Link URL or reference
169    pub url: Cow<'a, str>,
170    /// Inline title (without surrounding delimiters), as produced by pulldown-cmark
171    /// after backslash-escape handling. `None` when the link has no title or is a
172    /// reference style without a matched definition.
173    pub title: Option<Cow<'a, str>>,
174    /// Whether this is a reference link `[text][ref]` vs inline `[text](url)`
175    pub is_reference: bool,
176    /// Reference ID for reference links
177    pub reference_id: Option<Cow<'a, str>>,
178    /// Link type from pulldown-cmark
179    pub link_type: LinkType,
180}
181
182/// Information about a broken link reported by pulldown-cmark
183#[derive(Debug, Clone)]
184pub struct BrokenLinkInfo {
185    /// The reference text that couldn't be resolved
186    pub reference: String,
187    /// Byte span in the source document
188    pub span: std::ops::Range<usize>,
189    /// The type of the broken link
190    pub link_type: LinkType,
191}
192
193/// Parsed footnote reference (e.g., `[^1]`, `[^note]`)
194#[derive(Debug, Clone)]
195pub struct FootnoteRef {
196    /// The footnote ID (without the ^ prefix)
197    pub id: String,
198    /// Line number (1-indexed)
199    pub line: usize,
200    /// Start byte offset in document
201    pub byte_offset: usize,
202}
203
204/// Parsed image information
205#[derive(Debug, Clone)]
206pub struct ParsedImage<'a> {
207    /// Line number (1-indexed)
208    pub line: usize,
209    /// Start column (0-indexed) in the line
210    pub start_col: usize,
211    /// End column (0-indexed) in the line
212    pub end_col: usize,
213    /// Byte offset in document
214    pub byte_offset: usize,
215    /// End byte offset in document
216    pub byte_end: usize,
217    /// Alt text
218    pub alt_text: Cow<'a, str>,
219    /// Image URL or reference
220    pub url: Cow<'a, str>,
221    /// Inline title (without surrounding delimiters), as produced by pulldown-cmark
222    /// after backslash-escape handling. `None` when the image has no title or is a
223    /// reference style without a matched definition.
224    pub title: Option<Cow<'a, str>>,
225    /// Whether this is a reference image ![alt][ref] vs inline ![alt](url)
226    pub is_reference: bool,
227    /// Reference ID for reference images
228    pub reference_id: Option<Cow<'a, str>>,
229    /// Link type from pulldown-cmark
230    pub link_type: LinkType,
231}
232
233/// Reference definition `[ref]: url "title"`
234#[derive(Debug, Clone)]
235pub struct ReferenceDef {
236    /// Line number (1-indexed)
237    pub line: usize,
238    /// Reference ID (normalized to lowercase)
239    pub id: String,
240    /// URL
241    pub url: String,
242    /// Optional title
243    pub title: Option<String>,
244    /// Byte offset where the reference definition starts
245    pub byte_offset: usize,
246    /// Byte offset where the reference definition ends
247    pub byte_end: usize,
248    /// Byte offset where the title starts (if present, includes quote)
249    pub title_byte_start: Option<usize>,
250    /// Byte offset where the title ends (if present, includes quote)
251    pub title_byte_end: Option<usize>,
252}
253
254/// Parsed code span information
255#[derive(Debug, Clone)]
256pub struct CodeSpan {
257    /// Line number where the code span starts (1-indexed)
258    pub line: usize,
259    /// Line number where the code span ends (1-indexed)
260    pub end_line: usize,
261    /// Start column (0-indexed) in the line
262    pub start_col: usize,
263    /// End column (0-indexed) in the line
264    pub end_col: usize,
265    /// Byte offset in document
266    pub byte_offset: usize,
267    /// End byte offset in document
268    pub byte_end: usize,
269    /// Number of backticks used (1, 2, 3, etc.)
270    pub backtick_count: usize,
271    /// Content inside the code span (without backticks)
272    pub content: String,
273}
274
275/// Parsed math span information (inline $...$ or display $$...$$)
276#[derive(Debug, Clone)]
277pub struct MathSpan {
278    /// Line number where the math span starts (1-indexed)
279    pub line: usize,
280    /// Line number where the math span ends (1-indexed)
281    pub end_line: usize,
282    /// Start column (0-indexed) in the line
283    pub start_col: usize,
284    /// End column (0-indexed) in the line
285    pub end_col: usize,
286    /// Byte offset in document
287    pub byte_offset: usize,
288    /// End byte offset in document
289    pub byte_end: usize,
290    /// Whether this is display math ($$...$$) vs inline ($...$)
291    pub is_display: bool,
292    /// Content inside the math delimiters
293    pub content: String,
294}
295
296/// Information about a heading
297#[derive(Debug, Clone)]
298pub struct HeadingInfo {
299    /// Heading level (1-6 for ATX, 1-2 for Setext)
300    pub level: u8,
301    /// Style of heading
302    pub style: HeadingStyle,
303    /// The heading marker (# characters or underline)
304    pub marker: String,
305    /// Column where the marker starts (0-based)
306    pub marker_column: usize,
307    /// Column where heading text starts
308    pub content_column: usize,
309    /// The heading text (without markers and without custom ID syntax)
310    pub text: String,
311    /// Custom header ID if present (e.g., from {#custom-id} syntax)
312    pub custom_id: Option<String>,
313    /// Original heading text including custom ID syntax
314    pub raw_text: String,
315    /// Whether it has a closing sequence (for ATX)
316    pub has_closing_sequence: bool,
317    /// The closing sequence if present
318    pub closing_sequence: String,
319    /// Whether this is a valid CommonMark heading (ATX headings require space after #)
320    /// False for malformed headings like `#NoSpace` that MD018 should flag
321    pub is_valid: bool,
322}
323
324/// A valid heading from a filtered iteration
325///
326/// Only includes headings that are CommonMark-compliant (have space after #).
327/// Hashtag-like patterns (`#tag`, `#123`) are excluded.
328#[derive(Debug, Clone)]
329pub struct ValidHeading<'a> {
330    /// The 1-indexed line number in the document
331    pub line_num: usize,
332    /// Reference to the heading information
333    pub heading: &'a HeadingInfo,
334    /// Reference to the full line info (for rules that need additional context)
335    pub line_info: &'a LineInfo,
336}
337
338/// Iterator over valid CommonMark headings in a document
339///
340/// Filters out malformed headings like `#NoSpace` that should be flagged by MD018
341/// but should not be processed by other heading rules.
342pub struct ValidHeadingsIter<'a> {
343    lines: &'a [LineInfo],
344    current_index: usize,
345}
346
347impl<'a> ValidHeadingsIter<'a> {
348    pub(super) fn new(lines: &'a [LineInfo]) -> Self {
349        Self {
350            lines,
351            current_index: 0,
352        }
353    }
354}
355
356impl<'a> Iterator for ValidHeadingsIter<'a> {
357    type Item = ValidHeading<'a>;
358
359    fn next(&mut self) -> Option<Self::Item> {
360        while self.current_index < self.lines.len() {
361            let idx = self.current_index;
362            self.current_index += 1;
363
364            let line_info = &self.lines[idx];
365            if let Some(heading) = line_info.heading.as_deref()
366                && heading.is_valid
367            {
368                return Some(ValidHeading {
369                    line_num: idx + 1, // Convert 0-indexed to 1-indexed
370                    heading,
371                    line_info,
372                });
373            }
374        }
375        None
376    }
377}
378
379/// Information about a blockquote line
380#[derive(Debug, Clone)]
381pub struct BlockquoteInfo {
382    /// Nesting level (1 for >, 2 for >>, etc.)
383    pub nesting_level: usize,
384    /// Column where the first > starts (0-based)
385    pub marker_column: usize,
386    /// The blockquote prefix (e.g., "> ", ">> ", etc.)
387    pub prefix: String,
388    /// Content after the blockquote marker(s)
389    pub content: String,
390    /// Whether the line has multiple spaces after the marker
391    pub has_multiple_spaces_after_marker: bool,
392}
393
394/// Information about a list block
395#[derive(Debug, Clone)]
396pub struct ListBlock {
397    /// Line number where the list starts (1-indexed)
398    pub start_line: usize,
399    /// Line number where the list ends (1-indexed)
400    pub end_line: usize,
401    /// Whether it's ordered or unordered
402    pub is_ordered: bool,
403    /// The consistent marker for unordered lists (if any)
404    pub marker: Option<String>,
405    /// Blockquote prefix for this list (empty if not in blockquote)
406    pub blockquote_prefix: String,
407    /// Lines that are list items within this block
408    pub item_lines: Vec<usize>,
409    /// Nesting level (0 for top-level lists)
410    pub nesting_level: usize,
411    /// Maximum marker width seen in this block (e.g., 3 for "1. ", 4 for "10. ")
412    pub max_marker_width: usize,
413}
414
415/// Character frequency data for fast content analysis
416#[derive(Debug, Clone, Default)]
417pub struct CharFrequency {
418    /// Count of # characters (headings)
419    pub hash_count: usize,
420    /// Count of * characters (emphasis, lists, horizontal rules)
421    pub asterisk_count: usize,
422    /// Count of _ characters (emphasis, horizontal rules)
423    pub underscore_count: usize,
424    /// Count of - characters (lists, horizontal rules, setext headings)
425    pub hyphen_count: usize,
426    /// Count of + characters (lists)
427    pub plus_count: usize,
428    /// Count of > characters (blockquotes)
429    pub gt_count: usize,
430    /// Count of | characters (tables)
431    pub pipe_count: usize,
432    /// Count of [ characters (links, images)
433    pub bracket_count: usize,
434    /// Count of ` characters (code spans, code blocks)
435    pub backtick_count: usize,
436    /// Count of < characters (HTML tags, autolinks)
437    pub lt_count: usize,
438    /// Count of ! characters (images)
439    pub exclamation_count: usize,
440    /// Count of newline characters
441    pub newline_count: usize,
442}
443
444/// Pre-parsed HTML tag information
445#[derive(Debug, Clone)]
446pub struct HtmlTag {
447    /// Line number (1-indexed)
448    pub line: usize,
449    /// Start column (0-indexed) in the line
450    pub start_col: usize,
451    /// End column (0-indexed) in the line
452    pub end_col: usize,
453    /// Byte offset in document
454    pub byte_offset: usize,
455    /// End byte offset in document
456    pub byte_end: usize,
457    /// Tag name (e.g., "div", "img", "br")
458    pub tag_name: String,
459    /// Whether it's a closing tag (`</tag>`)
460    pub is_closing: bool,
461    /// Whether it's self-closing (`<tag />`)
462    pub is_self_closing: bool,
463}
464
465/// Pre-parsed emphasis span information
466#[derive(Debug, Clone)]
467pub struct EmphasisSpan {
468    /// Line number (1-indexed)
469    pub line: usize,
470    /// Start column (0-indexed) in the line
471    pub start_col: usize,
472    /// End column (0-indexed) in the line
473    pub end_col: usize,
474    /// Byte offset in document
475    pub byte_offset: usize,
476    /// End byte offset in document
477    pub byte_end: usize,
478    /// Type of emphasis ('*' or '_')
479    pub marker: char,
480    /// Whether this span is strong emphasis (`**`/`__`) rather than ordinary emphasis (`*`/`_`)
481    pub is_strong: bool,
482    /// Content inside the emphasis
483    pub content: String,
484}
485
486/// Pre-parsed bare URL information (not in links)
487#[derive(Debug, Clone)]
488pub struct BareUrl {
489    /// Line number (1-indexed)
490    pub line: usize,
491    /// Start column (0-indexed) in the line
492    pub start_col: usize,
493    /// End column (0-indexed) in the line
494    pub end_col: usize,
495    /// Byte offset in document
496    pub byte_offset: usize,
497    /// End byte offset in document
498    pub byte_end: usize,
499    /// The URL string
500    pub url: String,
501}
502
503/// A lazy continuation line detected by pulldown-cmark.
504///
505/// Lazy continuation occurs when text continues a list item paragraph but with less
506/// indentation than expected.
507#[derive(Debug, Clone)]
508pub struct LazyContLine {
509    /// 1-indexed line number
510    pub line_num: usize,
511    /// Expected indentation
512    pub expected_indent: usize,
513    /// Current indentation
514    pub current_indent: usize,
515    /// Blockquote nesting level
516    pub blockquote_level: usize,
517}
518
519/// Check if a line is a horizontal rule (---, ***, ___) per CommonMark spec.
520/// CommonMark rules for thematic breaks (horizontal rules):
521/// - May have 0-3 spaces of leading indentation (but NOT tabs)
522/// - Must have 3+ of the same character (-, *, or _)
523/// - May have spaces between characters
524/// - No other characters allowed
525pub fn is_horizontal_rule_line(line: &str) -> bool {
526    // CommonMark: HRs can have 0-3 spaces of leading indentation, not tabs
527    let leading_spaces = line.len() - line.trim_start_matches(' ').len();
528    if leading_spaces > 3 || line.starts_with('\t') {
529        return false;
530    }
531
532    is_horizontal_rule_content(line.trim())
533}
534
535/// Check if trimmed content matches horizontal rule pattern.
536/// Use `is_horizontal_rule_line` for full CommonMark compliance including indentation check.
537pub fn is_horizontal_rule_content(trimmed: &str) -> bool {
538    if trimmed.len() < 3 {
539        return false;
540    }
541
542    let mut chars = trimmed.chars();
543    let Some(first_char @ ('-' | '*' | '_')) = chars.next() else {
544        return false;
545    };
546
547    // Count occurrences of the rule character, rejecting non-whitespace interlopers
548    let mut count = 1; // Already matched the first character
549    for ch in chars {
550        if ch == first_char {
551            count += 1;
552        } else if ch != ' ' && ch != '\t' {
553            return false;
554        }
555    }
556    count >= 3
557}