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