//! MD073: Table of Contents validation rule //! //! Validates that TOC sections match the actual document headings. use crate::lint_context::LintContext; use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity}; use crate::utils::anchor_styles::AnchorStyle; use crate::utils::header_id_utils::{extract_html_anchor_ids, is_backslash_escaped}; use percent_encoding::percent_decode_str; use regex::Regex; use std::borrow::Cow; use std::collections::HashMap; use std::sync::LazyLock; /// Regex for TOC start marker: `` with optional whitespace variations static TOC_START_MARKER: LazyLock = LazyLock::new(|| Regex::new(r"(?i)").unwrap()); /// Regex for TOC stop marker: `` or `` static TOC_STOP_MARKER: LazyLock = LazyLock::new(|| Regex::new(r"(?i)").unwrap()); /// Regex for extracting TOC entries: `- [text](#anchor)` or `* [text](#anchor)` /// with optional leading whitespace for nested items /// Handles nested brackets like `[`check [PATHS...]`](#check-paths)` static TOC_ENTRY_PATTERN: LazyLock = LazyLock::new(|| Regex::new(r"^(\s*)[-*]\s+\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\(#([^)]+)\)").unwrap()); /// Represents a detected TOC region in the document #[derive(Debug, Clone)] struct TocRegion { /// 1-indexed start line of the TOC content (after the marker) start_line: usize, /// 1-indexed end line of the TOC content (before the stop marker) end_line: usize, /// Byte offset where TOC content starts content_start: usize, /// Byte offset where TOC content ends content_end: usize, } /// A parsed TOC entry from the existing TOC #[derive(Debug, Clone)] struct TocEntry { /// Display text of the link text: String, /// Anchor/fragment (without #) anchor: String, /// Number of leading whitespace characters (for indentation checking) indent_spaces: usize, } /// An expected TOC entry generated from document headings #[derive(Debug, Clone)] struct ExpectedTocEntry { /// 1-indexed line number of the heading's first line heading_line: usize, /// Heading level (1-6) level: u8, /// Heading text (for display) text: String, /// The fragment a generated entry links to anchor: String, /// Other fragments that also reach the heading. A heading with its own `` /// keeps the slug generated from its text, so a TOC written against either is /// right. aliases: Vec, } impl ExpectedTocEntry { fn is_reached_by(&self, anchor: &str) -> bool { self.anchor == anchor || self.aliases.iter().any(|alias| alias == anchor) } } /// Types of mismatches between actual and expected TOC #[derive(Debug)] enum TocMismatch { /// Entry exists in TOC but heading doesn't exist StaleEntry { entry: TocEntry }, /// Heading exists but no TOC entry for it MissingEntry { expected: ExpectedTocEntry }, /// TOC entry text doesn't match heading text TextMismatch { entry: TocEntry, expected: ExpectedTocEntry, }, /// TOC entries are in wrong order OrderMismatch { entry: TocEntry, expected_position: usize }, /// TOC entry has wrong indentation level IndentationMismatch { entry: TocEntry, actual_indent: usize, expected_indent: usize, }, } /// Regex patterns used by `strip_links_and_images`. static MARKDOWN_LINK: LazyLock = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\([^)]+\)").unwrap()); static MARKDOWN_REF_LINK: LazyLock = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\[[^\]]*\]").unwrap()); static MARKDOWN_IMAGE: LazyLock = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\([^)]+\)").unwrap()); /// `anchor` written as the destination of a TOC link. /// /// A bare link destination cannot hold whitespace, control characters or an /// unbalanced parenthesis, and a `%` would read as the start of an escape, so /// those ASCII characters are percent-encoded. Everything else is written as it /// is, so a slug generated from heading text, non-ASCII letters included, is /// unchanged. fn encode_fragment(anchor: &str) -> Cow<'_, str> { fn needs_encoding(c: char) -> bool { c.is_ascii() && (c <= ' ' || c == '\x7f' || matches!(c, '(' | ')' | '%')) } if !anchor.contains(needs_encoding) { return Cow::Borrowed(anchor); } let mut encoded = String::with_capacity(anchor.len() + 6); for c in anchor.chars() { if needs_encoding(c) { encoded.push_str(&format!("%{:02X}", c as u32)); } else { encoded.push(c); } } Cow::Owned(encoded) } /// The fragment a written TOC entry reaches, its percent-encoding undone, as a /// browser decodes a fragment before matching it against ids. An escape sequence /// that does not decode to UTF-8 leaves the fragment as written. fn decode_fragment(anchor: &str) -> Cow<'_, str> { if !anchor.contains('%') { return Cow::Borrowed(anchor); } percent_decode_str(anchor) .decode_utf8() .unwrap_or(Cow::Borrowed(anchor)) } /// Extract code-span byte ranges from `text` using the CommonMark rule: /// a run of N backticks opens a span closed by exactly N backticks. /// Returns a sorted list of `(start, end)` byte offsets that are inside code spans /// (including the backtick delimiters themselves). fn code_span_ranges(text: &str) -> Vec<(usize, usize)> { let chars: Vec = text.chars().collect(); let len = chars.len(); let mut ranges = Vec::new(); let mut i = 0; while i < len { if chars[i] == '`' { let span_start = i; while i < len && chars[i] == '`' { i += 1; } let n = i - span_start; // Search for the matching closing sequence of exactly n backticks let mut j = i; let mut found = false; while j < len { if chars[j] == '`' { let close_start = j; while j < len && chars[j] == '`' { j += 1; } if j - close_start == n { // Convert char indices to byte offsets let byte_start: usize = text.char_indices().nth(span_start).map_or(0, |(b, _)| b); let byte_end: usize = text.char_indices().nth(j).map_or(text.len(), |(b, _)| b); ranges.push((byte_start, byte_end)); i = j; found = true; break; } } else { j += 1; } } if !found { // No matching close; skip past the opening backticks i = span_start + n; } } else { i += 1; } } ranges } /// Strip only links and images from `text`, preserving all other inline /// formatting (code spans, bold, italic, etc.). /// /// Links and images cannot appear inside a Markdown link label `[...]`, so they /// must be removed when building TOC display text. Code spans and emphasis are /// valid inside link labels and should be kept so the TOC entry faithfully /// reflects the heading's visual appearance. /// /// Code-span contents are protected: link-like syntax such as `[foo](bar)` that /// appears inside backticks is left untouched. /// /// Examples: /// - `` `my header` `` → `` `my header` `` (code ticks preserved) /// - `[terminal](url)` → `terminal` (link stripped) /// - `![alt](img.png)` → `alt` (image stripped) /// - `**bold**` → `**bold**` (emphasis preserved) /// - `` `[foo](bar)` `` → `` `[foo](bar)` `` (link inside code span preserved) /// - `Tool: [terminal](url)` → `Tool: terminal` fn strip_links_and_images(text: &str) -> String { // Collect code-span byte ranges so we can protect their contents from // the link/image regex substitutions. let protected = code_span_ranges(text); // If there are no code spans the fast path avoids all the extra work. if protected.is_empty() { let mut result = text.to_string(); result = MARKDOWN_IMAGE.replace_all(&result, "$1").to_string(); result = MARKDOWN_LINK.replace_all(&result, "$1").to_string(); result = MARKDOWN_REF_LINK.replace_all(&result, "$1").to_string(); return result; } // Replace each code span with a unique placeholder that cannot be matched // by the link/image regexes, apply the regexes, then restore the originals. let mut placeholders: Vec<(&str, String)> = Vec::with_capacity(protected.len()); let mut masked = text.to_string(); // Process spans in reverse order so byte offsets remain valid after each replacement. for (i, &(start, end)) in protected.iter().enumerate().rev() { // Placeholder: a string containing no `[`, `]`, `(`, `)`, `!` characters. let placeholder = format!("\x00CODESPAN{i}\x00"); let original = &text[start..end]; placeholders.push((original, placeholder.clone())); masked.replace_range(start..end, &placeholder); } // Apply link/image stripping to the masked string masked = MARKDOWN_IMAGE.replace_all(&masked, "$1").to_string(); masked = MARKDOWN_LINK.replace_all(&masked, "$1").to_string(); masked = MARKDOWN_REF_LINK.replace_all(&masked, "$1").to_string(); // Restore the original code-span text for (original, placeholder) in &placeholders { masked = masked.replace(placeholder.as_str(), original); } masked } /// MD073: Table of Contents Validation /// /// This rule validates that TOC sections match the actual document headings. /// It detects TOC regions via markers (`...`). /// /// To opt into TOC validation, add markers to your document: /// ```markdown /// /// - [Section](#section) /// /// ``` /// /// ## Configuration /// /// ```toml /// [MD073] /// # Enable the rule (opt-in, disabled by default) /// enabled = true /// # Minimum heading level to include (default: 2) /// min-level = 2 /// # Maximum heading level to include (default: 4) /// max-level = 4 /// # Whether TOC order must match document order (default: true) /// enforce-order = true /// # Indent size per nesting level (default: from MD007 config, or 2) /// indent = 2 /// ``` #[derive(Clone)] pub struct MD073TocValidation { /// Whether this rule is enabled (default: false - opt-in rule) enabled: bool, /// Minimum heading level to include min_level: u8, /// Maximum heading level to include max_level: u8, /// Whether to enforce order matching enforce_order: bool, /// Indent size per nesting level (reads from MD007 config by default) pub indent: usize, } impl Default for MD073TocValidation { fn default() -> Self { Self { enabled: false, // Disabled by default - opt-in rule min_level: 2, max_level: 4, enforce_order: true, indent: 2, // Default indent, can be overridden by MD007 config } } } impl std::fmt::Debug for MD073TocValidation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MD073TocValidation") .field("enabled", &self.enabled) .field("min_level", &self.min_level) .field("max_level", &self.max_level) .field("enforce_order", &self.enforce_order) .field("indent", &self.indent) .finish() } } impl MD073TocValidation { /// Create a new rule with default settings pub fn new() -> Self { Self::default() } /// Whether `content` contains a TOC marker that is Markdown syntax rather /// than literal text. A marker inside an inline code span is code, and one /// whose `<` is backslash-escaped renders as the characters themselves. fn has_active_marker(ctx: &LintContext, content: &str, line_byte_offset: usize, marker: &Regex) -> bool { marker.find_iter(content).any(|matched| { !ctx.is_in_code_span_byte(line_byte_offset + matched.start()) && !is_backslash_escaped(content, matched.start()) }) } /// Detect TOC region using markers fn detect_by_markers(&self, ctx: &LintContext) -> Option { let mut start_line = None; let mut start_byte = None; for (idx, line_info) in ctx.lines.iter().enumerate() { let line_num = idx + 1; let content = line_info.content(ctx.content); // Skip if in code block or front matter if line_info.in_code_block || line_info.in_front_matter { continue; } // Look for start marker or stop marker if let (Some(s_line), Some(s_byte)) = (start_line, start_byte) { // We have a start, now look for stop marker if Self::has_active_marker(ctx, content, line_info.byte_offset, &TOC_STOP_MARKER) { let end_line = line_num - 1; let content_end = line_info.byte_offset; // Handle case where there's no content between markers if end_line < s_line { return Some(TocRegion { start_line: s_line, end_line: s_line, content_start: s_byte, content_end: s_byte, }); } return Some(TocRegion { start_line: s_line, end_line, content_start: s_byte, content_end, }); } } else if Self::has_active_marker(ctx, content, line_info.byte_offset, &TOC_START_MARKER) { // TOC content starts on the next line if idx + 1 < ctx.lines.len() { start_line = Some(line_num + 1); start_byte = Some(ctx.lines[idx + 1].byte_offset); } } } None } /// Detect TOC region using markers fn detect_toc_region(&self, ctx: &LintContext) -> Option { self.detect_by_markers(ctx) } /// Remove `depth` blockquote markers, each with at most one following space, /// leaving any further indentation in place. fn strip_quote_markers(line: &str, depth: usize) -> &str { let mut rest = line; for _ in 0..depth { let Some(after) = rest.trim_start().strip_prefix('>') else { break; }; rest = after.strip_prefix(' ').unwrap_or(after); } rest } /// Extract TOC entries from the detected region fn extract_toc_entries(&self, ctx: &LintContext, region: &TocRegion) -> Vec { let mut entries = Vec::new(); for idx in (region.start_line - 1)..region.end_line.min(ctx.lines.len()) { let line_info = &ctx.lines[idx]; // A TOC inside a blockquote is matched on the text after the quote // markers, keeping the indentation of nested entries. let content = line_info.blockquote.as_ref().map_or_else( || line_info.content(ctx.content), |quote| Self::strip_quote_markers(line_info.content(ctx.content), quote.nesting_level), ); if let Some(caps) = TOC_ENTRY_PATTERN.captures(content) { let indent_spaces = caps.get(1).map_or(0, |m| m.as_str().len()); let text = caps.get(2).map_or("", |m| m.as_str()).to_string(); let anchor = caps.get(3).map_or("", |m| m.as_str()).to_string(); entries.push(TocEntry { text, anchor, indent_spaces, }); } } entries } /// Build expected TOC entries from document headings fn build_expected_toc(&self, ctx: &LintContext, toc_region: &TocRegion) -> Vec { let mut entries = Vec::new(); let mut fragment_counts: HashMap = HashMap::new(); // Every heading takes a number from the renderer, in document order, whether // or not it appears in the TOC, so the duplicate numbering runs over all of // them and only the entries are filtered. for parsed in ctx.headings() { let line_num = parsed.line_num; let line_info = parsed.line_info; let heading = parsed.heading; // Skip code blocks, front matter, HTML blocks if line_info.in_code_block || line_info.in_front_matter || line_info.in_html_block { continue; } // A custom ID ({#id}) replaces the generated slug. An HTML anchor // element beside the heading adds a target either way: the // renderer keeps the element's own id, and without a custom ID it // still generates the slug from the text, which still counts // towards the numbering of later duplicates. let (anchor, aliases) = match &heading.custom_id { Some(custom_id) => ( Self::deduplicate_fragment(&mut fragment_counts, custom_id), extract_html_anchor_ids(&heading.raw_text), ), None => { let slug = AnchorStyle::GitHub.generate_fragment(&heading.slug_text); let generated = Self::deduplicate_fragment(&mut fragment_counts, &slug); let mut explicit = extract_html_anchor_ids(&heading.raw_text); match explicit.first().cloned() { Some(preferred) => { explicit.remove(0); explicit.push(generated); (preferred, explicit) } // A heading whose text slugs to nothing (an image, an // emoji) gets no anchor from GitHub, only a number on a // repeat, so without an element of its own no TOC entry // can reach it. It still counts towards the numbering. None if slug.is_empty() => continue, None => (generated, Vec::new()), } } }; // Headings before/within the TOC region are not listed, and the // configured level range limits the rest. if line_num <= toc_region.end_line || heading.level < self.min_level || heading.level > self.max_level { continue; } entries.push(ExpectedTocEntry { // A Setext heading is recorded on the last line of its text, // and a reader looks for it where it starts. heading_line: parsed.first_line_num(), level: heading.level, text: heading.text.clone(), anchor, aliases, }); } entries } /// The fragment a renderer gives a heading whose base fragment has already /// been seen `n` times: `base`, then `base-1`, `base-2`, ... fn deduplicate_fragment(fragment_counts: &mut HashMap, base: &str) -> String { match fragment_counts.get_mut(base) { Some(count) => { let suffix = *count; *count += 1; format!("{base}-{suffix}") } None => { fragment_counts.insert(base.to_string(), 1); base.to_string() } } } /// Pair each actual TOC entry with the first still-unclaimed heading its /// anchor reaches. `None` marks an entry that reaches no heading. fn match_entries(actual: &[TocEntry], expected: &[ExpectedTocEntry]) -> Vec> { let mut claimed = vec![false; expected.len()]; actual .iter() .map(|entry| { let anchor = decode_fragment(&entry.anchor); let found = expected .iter() .enumerate() .position(|(idx, exp)| !claimed[idx] && exp.is_reached_by(&anchor)); if let Some(idx) = found { claimed[idx] = true; } found }) .collect() } /// Compare actual TOC entries against expected and find mismatches. /// /// `matching` pairs each actual entry with the heading it reaches, as /// computed by [`Self::match_entries`]. fn validate_toc( &self, actual: &[TocEntry], expected: &[ExpectedTocEntry], matching: &[Option], ) -> Vec { let mut mismatches = Vec::new(); let pairs = || { actual .iter() .zip(matching) .enumerate() .filter_map(|(actual_idx, (entry, matched))| matched.map(|exp_idx| (actual_idx, entry, exp_idx))) }; // Stale entries reach no heading. for (entry, matched) in actual.iter().zip(matching) { if matched.is_none() { mismatches.push(TocMismatch::StaleEntry { entry: entry.clone() }); } } // Missing entries are headings no TOC entry reaches. for (exp_idx, exp) in expected.iter().enumerate() { if !matching.contains(&Some(exp_idx)) { mismatches.push(TocMismatch::MissingEntry { expected: exp.clone() }); } } // Check for text mismatches. Compare with the same normalization used in // generate_toc: strip only links and images, preserve code spans and emphasis. // This ensures a correct user-written TOC entry like `` [`my header`](#anchor) `` // is not flagged against a heading `` `my header` ``. let mut text_mismatched = vec![false; actual.len()]; for (actual_idx, entry, exp_idx) in pairs() { let exp = &expected[exp_idx]; let actual_normalized = strip_links_and_images(entry.text.trim()); let expected_normalized = strip_links_and_images(exp.text.trim()); if actual_normalized != expected_normalized { text_mismatched[actual_idx] = true; mismatches.push(TocMismatch::TextMismatch { entry: entry.clone(), expected: exp.clone(), }); } } // Check for indentation mismatches // Expected indentation is indent spaces per level difference from base level if !expected.is_empty() { let base_level = expected.iter().map(|e| e.level).min().unwrap_or(2); for (actual_idx, entry, exp_idx) in pairs() { let level_diff = expected[exp_idx].level.saturating_sub(base_level) as usize; let expected_indent = level_diff * self.indent; // An entry already reported for its text is not reported again if entry.indent_spaces != expected_indent && !text_mismatched[actual_idx] { mismatches.push(TocMismatch::IndentationMismatch { entry: entry.clone(), actual_indent: entry.indent_spaces, expected_indent, }); } } } // Check order if enforce_order is enabled: walk the headings alongside the // matched entries, and an entry whose heading lies behind the walk is out // of order. if self.enforce_order && !actual.is_empty() && !expected.is_empty() { let mut expected_idx = 0; for (actual_idx, entry, exp_idx) in pairs() { if exp_idx >= expected_idx { expected_idx = exp_idx + 1; } else if !text_mismatched[actual_idx] { mismatches.push(TocMismatch::OrderMismatch { entry: entry.clone(), expected_position: exp_idx + 1, }); } } } mismatches } /// Expected entries as they should be regenerated: a TOC entry that already /// reaches its heading keeps the anchor it was written with. The anchor is /// stored decoded, as every expected anchor is, and encoded again on output. fn keep_reached_anchors( actual: &[TocEntry], expected: &[ExpectedTocEntry], matching: &[Option], ) -> Vec { let mut regenerated = expected.to_vec(); for (entry, exp_idx) in actual .iter() .zip(matching) .filter_map(|(entry, m)| m.map(|idx| (entry, idx))) { regenerated[exp_idx].anchor = decode_fragment(&entry.anchor).into_owned(); } regenerated } /// Generate a new TOC from expected entries (always uses nested indentation) fn generate_toc(&self, expected: &[ExpectedTocEntry]) -> String { if expected.is_empty() { return String::new(); } let mut result = String::new(); let base_level = expected.iter().map(|e| e.level).min().unwrap_or(2); let indent_str = " ".repeat(self.indent); for entry in expected { let level_diff = entry.level.saturating_sub(base_level) as usize; let indent = indent_str.repeat(level_diff); // Build display text: strip only links and images (which would create invalid // nested-link syntax inside `[...]`), but preserve code spans and emphasis so // the TOC entry reflects the heading's visual appearance. let display_text = strip_links_and_images(&entry.text); let fragment = encode_fragment(&entry.anchor); result.push_str(&format!("{indent}- [{display_text}](#{fragment})\n")); } result } } impl Rule for MD073TocValidation { fn name(&self) -> &'static str { "MD073" } fn description(&self) -> &'static str { "Table of Contents should match document headings" } fn should_skip(&self, ctx: &LintContext) -> bool { // Quick check: skip if no TOC markers. detect_toc_region() is // case-insensitive, so use a case-insensitive containment check here // to avoid skipping fix() on documents with uppercase markers like // ``. let lower = ctx.content.to_ascii_lowercase(); !(lower.contains(" - [Heading 1](#heading-1) ## Heading 1 Content here. "#; let ctx = create_ctx(content); let region = rule.detect_by_markers(&ctx); assert!(region.is_some()); let region = region.unwrap(); // Verify region boundaries are detected correctly assert_eq!(region.start_line, 4); assert_eq!(region.end_line, 6); } #[test] fn test_detect_markers_variations() { let rule = MD073TocValidation::new(); // Test (no spaces) let content1 = "\n- [A](#a)\n\n"; let ctx1 = create_ctx(content1); assert!(rule.detect_by_markers(&ctx1).is_some()); // Test (uppercase) let content2 = "\n- [A](#a)\n\n"; let ctx2 = create_ctx(content2); assert!(rule.detect_by_markers(&ctx2).is_some()); // Test (alternative stop marker) let content3 = "\n- [A](#a)\n\n"; let ctx3 = create_ctx(content3); assert!(rule.detect_by_markers(&ctx3).is_some()); } #[test] fn test_no_toc_region() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Heading 1 Content here. ## Heading 2 More content. "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx); assert!(region.is_none()); } // ========== Validation Tests ========== #[test] fn test_toc_matches_headings() { let rule = create_enabled_rule(); let content = r#"# Title - [Heading 1](#heading-1) - [Heading 2](#heading-2) ## Heading 1 Content. ## Heading 2 More content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Expected no warnings for matching TOC"); } #[test] fn test_missing_entry() { let rule = create_enabled_rule(); let content = r#"# Title - [Heading 1](#heading-1) ## Heading 1 Content. ## Heading 2 New heading not in TOC. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1); assert!(result[0].message.contains("Missing entry")); assert!(result[0].message.contains("Heading 2")); } #[test] fn test_stale_entry() { let rule = create_enabled_rule(); let content = r#"# Title - [Heading 1](#heading-1) - [Deleted Heading](#deleted-heading) ## Heading 1 Content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1); assert!(result[0].message.contains("Stale entry")); assert!(result[0].message.contains("Deleted Heading")); } #[test] fn test_text_mismatch() { let rule = create_enabled_rule(); let content = r#"# Title - [Old Name](#heading-1) ## Heading 1 Content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1); assert!(result[0].message.contains("Text mismatch")); } // ========== Level Filtering Tests ========== #[test] fn test_min_level_excludes_h1() { let mut rule = MD073TocValidation::new(); rule.min_level = 2; let content = r#" # Should Be Excluded ## Should Be Included Content. "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); assert_eq!(expected.len(), 1); assert_eq!(expected[0].text, "Should Be Included"); } #[test] fn test_max_level_excludes_h5_h6() { let mut rule = MD073TocValidation::new(); rule.max_level = 4; let content = r#" ## Level 2 ### Level 3 #### Level 4 ##### Level 5 Should Be Excluded ###### Level 6 Should Be Excluded "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); assert_eq!(expected.len(), 3); assert!(expected.iter().all(|e| e.level <= 4)); } // ========== Fix Tests ========== #[test] fn test_fix_adds_missing_entry() { let rule = MD073TocValidation::new(); let content = r#"# Title - [Heading 1](#heading-1) ## Heading 1 Content. ## Heading 2 New heading. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!(fixed.contains("- [Heading 2](#heading-2)")); } #[test] fn test_fix_removes_stale_entry() { let rule = MD073TocValidation::new(); let content = r#"# Title - [Heading 1](#heading-1) - [Deleted](#deleted) ## Heading 1 Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!(fixed.contains("- [Heading 1](#heading-1)")); assert!(!fixed.contains("Deleted")); } #[test] fn test_fix_idempotent() { let rule = MD073TocValidation::new(); let content = r#"# Title - [Heading 1](#heading-1) - [Heading 2](#heading-2) ## Heading 1 Content. ## Heading 2 More. "#; let ctx = create_ctx(content); let fixed1 = rule.fix(&ctx).unwrap(); let ctx2 = create_ctx(&fixed1); let fixed2 = rule.fix(&ctx2).unwrap(); // Second fix should produce same output assert_eq!(fixed1, fixed2); } #[test] fn test_fix_preserves_markers() { let rule = MD073TocValidation::new(); let content = r#"# Title Old TOC content. ## New Heading Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // Markers should still be present assert!(fixed.contains("")); assert!(fixed.contains("")); // New content should be generated assert!(fixed.contains("- [New Heading](#new-heading)")); } #[test] fn test_fix_requires_markers() { let rule = create_enabled_rule(); // Document without markers - no TOC detected, no changes let content_no_markers = r#"# Title ## Heading 1 Content. "#; let ctx = create_ctx(content_no_markers); let fixed = rule.fix(&ctx).unwrap(); assert_eq!(fixed, content_no_markers); // Document with markers - TOC detected and fixed let content_markers = r#"# Title - [Old Entry](#old-entry) ## Heading 1 Content. "#; let ctx = create_ctx(content_markers); let fixed = rule.fix(&ctx).unwrap(); assert!(fixed.contains("- [Heading 1](#heading-1)")); assert!(!fixed.contains("Old Entry")); } // ========== Anchor Tests ========== #[test] fn test_duplicate_heading_anchors() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Duplicate Content. ## Duplicate More content. ## Duplicate Even more. "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); assert_eq!(expected.len(), 3); assert_eq!(expected[0].anchor, "duplicate"); assert_eq!(expected[1].anchor, "duplicate-1"); assert_eq!(expected[2].anchor, "duplicate-2"); } // ========== Edge Cases ========== #[test] fn test_headings_in_code_blocks_ignored() { let rule = create_enabled_rule(); let content = r#"# Title - [Real Heading](#real-heading) ## Real Heading ```markdown ## Fake Heading In Code ``` Content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Should not report fake heading in code block"); } #[test] fn test_empty_toc_region() { let rule = create_enabled_rule(); let content = r#"# Title ## Heading 1 Content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1); assert!(result[0].message.contains("Missing entry")); } #[test] fn test_nested_indentation() { let rule = create_enabled_rule(); let content = r#" ## Level 2 ### Level 3 #### Level 4 ## Another Level 2 "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); let toc = rule.generate_toc(&expected); // Check indentation (always nested) assert!(toc.contains("- [Level 2](#level-2)")); assert!(toc.contains(" - [Level 3](#level-3)")); assert!(toc.contains(" - [Level 4](#level-4)")); assert!(toc.contains("- [Another Level 2](#another-level-2)")); } // ========== Indentation Mismatch Tests ========== #[test] fn test_indentation_mismatch_detected() { let rule = create_enabled_rule(); // TOC entries are all at same indentation level, but headings have different levels let content = r#" - [Hello](#hello) - [Another](#another) - [Heading](#heading) ## Hello ### Another ## Heading "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // Should detect indentation mismatch - "Another" is level 3 but has no indent assert_eq!(result.len(), 1, "Should report indentation mismatch: {result:?}"); assert!( result[0].message.contains("Indentation mismatch"), "Message should mention indentation: {}", result[0].message ); assert!( result[0].message.contains("Another"), "Message should mention the entry: {}", result[0].message ); } #[test] fn test_indentation_mismatch_fixed() { let rule = create_enabled_rule(); // TOC entries are all at same indentation level, but headings have different levels let content = r#" - [Hello](#hello) - [Another](#another) - [Heading](#heading) ## Hello ### Another ## Heading "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // After fix, "Another" should be indented assert!(fixed.contains("- [Hello](#hello)")); assert!(fixed.contains(" - [Another](#another)")); // Indented with 2 spaces assert!(fixed.contains("- [Heading](#heading)")); } #[test] fn test_no_indentation_mismatch_when_correct() { let rule = create_enabled_rule(); // TOC has correct indentation let content = r#" - [Hello](#hello) - [Another](#another) - [Heading](#heading) ## Hello ### Another ## Heading "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // Should not report any issues - indentation is correct assert!(result.is_empty(), "Should not report issues: {result:?}"); } // ========== Order Mismatch Tests ========== #[test] fn test_order_mismatch_detected() { let rule = create_enabled_rule(); let content = r#"# Title - [Section B](#section-b) - [Section A](#section-a) ## Section A Content A. ## Section B Content B. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // Should detect order mismatch - Section B appears before Section A in TOC // but Section A comes first in document assert!(!result.is_empty(), "Should detect order mismatch"); } #[test] fn test_order_mismatch_ignored_when_disabled() { let mut rule = create_enabled_rule(); rule.enforce_order = false; let content = r#"# Title - [Section B](#section-b) - [Section A](#section-a) ## Section A Content A. ## Section B Content B. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // With enforce_order=false, order mismatches should be ignored assert!(result.is_empty(), "Should not report order mismatch when disabled"); } // ========== Unicode and Special Characters Tests ========== #[test] fn test_unicode_headings() { let rule = create_enabled_rule(); let content = r#"# Title - [日本語の見出し](#日本語の見出し) - [Émojis 🎉](#émojis-) ## 日本語の見出し Japanese content. ## Émojis 🎉 Content with emojis. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // Should handle unicode correctly assert!(result.is_empty(), "Should handle unicode headings"); } #[test] fn test_special_characters_in_headings() { let rule = create_enabled_rule(); let content = r#"# Title - [What's New?](#whats-new) - [C++ Guide](#c-guide) ## What's New? News content. ## C++ Guide C++ content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Should handle special characters"); } #[test] fn test_code_spans_in_headings() { let rule = create_enabled_rule(); let content = r#"# Title - [`check [PATHS...]`](#check-paths) ## `check [PATHS...]` Command documentation. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Should handle code spans in headings with brackets"); } // ========== Config Tests ========== #[test] fn test_from_config_defaults() { let config = crate::config::Config::default(); let rule = MD073TocValidation::from_config(&config); let rule = rule.as_any().downcast_ref::().unwrap(); assert_eq!(rule.min_level, 2); assert_eq!(rule.max_level, 4); assert!(rule.enforce_order); assert_eq!(rule.indent, 2); } #[test] fn test_indent_from_md007_config() { use crate::config::{Config, RuleConfig}; use std::collections::BTreeMap; let mut config = Config::default(); // Set MD007 indent to 4 let mut md007_values = BTreeMap::new(); md007_values.insert("indent".to_string(), toml::Value::Integer(4)); config.rules.insert( "MD007".to_string(), RuleConfig { severity: None, values: md007_values, }, ); let rule = MD073TocValidation::from_config(&config); let rule = rule.as_any().downcast_ref::().unwrap(); assert_eq!(rule.indent, 4, "Should read indent from MD007 config"); } #[test] fn test_indent_md073_overrides_md007() { use crate::config::{Config, RuleConfig}; use std::collections::BTreeMap; let mut config = Config::default(); // Set MD007 indent to 4 let mut md007_values = BTreeMap::new(); md007_values.insert("indent".to_string(), toml::Value::Integer(4)); config.rules.insert( "MD007".to_string(), RuleConfig { severity: None, values: md007_values, }, ); // Set MD073 indent to 3 (should override MD007) let mut md073_values = BTreeMap::new(); md073_values.insert("enabled".to_string(), toml::Value::Boolean(true)); md073_values.insert("indent".to_string(), toml::Value::Integer(3)); config.rules.insert( "MD073".to_string(), RuleConfig { severity: None, values: md073_values, }, ); let rule = MD073TocValidation::from_config(&config); let rule = rule.as_any().downcast_ref::().unwrap(); assert_eq!(rule.indent, 3, "MD073 indent should override MD007"); } #[test] fn test_generate_toc_with_4_space_indent() { let mut rule = create_enabled_rule(); rule.indent = 4; let content = r#" ## Level 2 ### Level 3 #### Level 4 ## Another Level 2 "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); let toc = rule.generate_toc(&expected); // With 4-space indent: // Level 2 = 0 spaces (base level) // Level 3 = 4 spaces // Level 4 = 8 spaces assert!(toc.contains("- [Level 2](#level-2)"), "Level 2 should have no indent"); assert!( toc.contains(" - [Level 3](#level-3)"), "Level 3 should have 4-space indent" ); assert!( toc.contains(" - [Level 4](#level-4)"), "Level 4 should have 8-space indent" ); assert!(toc.contains("- [Another Level 2](#another-level-2)")); } #[test] fn test_validate_toc_with_4_space_indent() { let mut rule = create_enabled_rule(); rule.indent = 4; // TOC with correct 4-space indentation let content = r#" - [Hello](#hello) - [Another](#another) - [Heading](#heading) ## Hello ### Another ## Heading "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!( result.is_empty(), "Should accept 4-space indent when configured: {result:?}" ); } #[test] fn test_validate_toc_wrong_indent_with_4_space_config() { let mut rule = create_enabled_rule(); rule.indent = 4; // TOC with 2-space indentation (wrong when 4-space is configured) let content = r#" - [Hello](#hello) - [Another](#another) - [Heading](#heading) ## Hello ### Another ## Heading "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1, "Should detect wrong indent"); assert!( result[0].message.contains("Indentation mismatch"), "Should report indentation mismatch: {}", result[0].message ); assert!( result[0].message.contains("expected 4 spaces"), "Should mention expected 4 spaces: {}", result[0].message ); } // ========== Markdown Stripping Tests ========== #[test] fn test_strip_markdown_formatting_link() { let result = strip_markdown_formatting("Tool: [terminal](https://example.com)"); assert_eq!(result, "Tool: terminal"); } #[test] fn test_strip_markdown_formatting_bold() { let result = strip_markdown_formatting("This is **bold** text"); assert_eq!(result, "This is bold text"); let result = strip_markdown_formatting("This is __bold__ text"); assert_eq!(result, "This is bold text"); } #[test] fn test_strip_markdown_formatting_italic() { let result = strip_markdown_formatting("This is *italic* text"); assert_eq!(result, "This is italic text"); let result = strip_markdown_formatting("This is _italic_ text"); assert_eq!(result, "This is italic text"); } #[test] fn test_strip_markdown_formatting_code_span() { let result = strip_markdown_formatting("Use the `format` function"); assert_eq!(result, "Use the format function"); } #[test] fn test_strip_markdown_formatting_image() { let result = strip_markdown_formatting("See ![logo](image.png) for details"); assert_eq!(result, "See logo for details"); } #[test] fn test_strip_markdown_formatting_reference_link() { let result = strip_markdown_formatting("See [documentation][docs] for details"); assert_eq!(result, "See documentation for details"); } #[test] fn test_strip_markdown_formatting_combined() { // Link is stripped first, leaving bold, then bold is stripped let result = strip_markdown_formatting("Tool: [**terminal**](https://example.com)"); assert_eq!(result, "Tool: terminal"); } #[test] fn test_toc_with_link_in_heading_matches_stripped_text() { let rule = create_enabled_rule(); // TOC entry text matches the stripped heading text let content = r#"# Title - [Tool: terminal](#tool-terminal) ## Tool: [terminal](https://example.com) Content here. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!( result.is_empty(), "Stripped heading text should match TOC entry: {result:?}" ); } #[test] fn test_toc_with_simplified_text_still_mismatches() { let rule = create_enabled_rule(); // TOC entry "terminal" does NOT match stripped heading "Tool: terminal" let content = r#"# Title - [terminal](#tool-terminal) ## Tool: [terminal](https://example.com) Content here. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert_eq!(result.len(), 1, "Should report text mismatch"); assert!(result[0].message.contains("Text mismatch")); } #[test] fn test_fix_generates_stripped_toc_entries() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Tool: [busybox](https://www.busybox.net/) Content. ## Tool: [mount](https://en.wikipedia.org/wiki/Mount) More content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // Generated TOC should have stripped text (links removed) assert!( fixed.contains("- [Tool: busybox](#tool-busybox)"), "TOC entry should have stripped link text" ); assert!( fixed.contains("- [Tool: mount](#tool-mount)"), "TOC entry should have stripped link text" ); // TOC entries should NOT contain the URL (the actual headings in the document still will) // Check only within the TOC region (between toc markers) let toc_start = fixed.find("").unwrap(); let toc_end = fixed.find("").unwrap(); let toc_content = &fixed[toc_start..toc_end]; assert!( !toc_content.contains("busybox.net"), "TOC should not contain URLs: {toc_content}" ); assert!( !toc_content.contains("wikipedia.org"), "TOC should not contain URLs: {toc_content}" ); } #[test] fn test_fix_with_bold_in_heading() { let rule = MD073TocValidation::new(); let content = r#"# Title ## **Important** Section Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // Generated TOC preserves bold markers in display text; anchor strips them. assert!(fixed.contains("- [**Important** Section](#important-section)")); } #[test] fn test_fix_with_code_in_heading() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Using `async` Functions Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // Generated TOC preserves code ticks in display text; anchor strips them. assert!(fixed.contains("- [Using `async` Functions](#using-async-functions)")); } // ========== Custom Anchor Tests ========== #[test] fn test_custom_anchor_id_respected() { let rule = create_enabled_rule(); let content = r#"# Title - [My Section](#my-custom-anchor) ## My Section {#my-custom-anchor} Content here. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Should respect custom anchor IDs: {result:?}"); } #[test] fn test_custom_anchor_id_in_generated_toc() { let rule = create_enabled_rule(); let content = r#"# Title ## First Section {#custom-first} Content. ## Second Section {#another-custom} More content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!(fixed.contains("- [First Section](#custom-first)")); assert!(fixed.contains("- [Second Section](#another-custom)")); } #[test] fn test_mixed_custom_and_generated_anchors() { let rule = create_enabled_rule(); let content = r#"# Title - [Custom Section](#my-id) - [Normal Section](#normal-section) ## Custom Section {#my-id} Content. ## Normal Section More content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!(result.is_empty(), "Should handle mixed custom and generated anchors"); } // ========== Anchor Generation Tests ========== #[test] fn test_github_anchor_style() { let rule = create_enabled_rule(); let content = r#" ## Test_With_Underscores Content. "#; let ctx = create_ctx(content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); // GitHub-style anchors preserve underscores assert_eq!(expected[0].anchor, "test_with_underscores"); } // ========== Stress Tests ========== #[test] fn test_stress_many_headings() { let rule = create_enabled_rule(); // Generate a document with 150 headings let mut content = String::from("# Title\n\n\n\n\n\n"); for i in 1..=150 { content.push_str(&format!("## Heading Number {i}\n\nContent for section {i}.\n\n")); } let ctx = create_ctx(&content); // Should not panic or timeout let result = rule.check(&ctx).unwrap(); // Should report missing entries for all 150 headings assert_eq!(result.len(), 1, "Should report single warning for TOC"); assert!(result[0].message.contains("Missing entry")); // Fix should generate TOC with 150 entries let fixed = rule.fix(&ctx).unwrap(); assert!(fixed.contains("- [Heading Number 1](#heading-number-1)")); assert!(fixed.contains("- [Heading Number 100](#heading-number-100)")); assert!(fixed.contains("- [Heading Number 150](#heading-number-150)")); } #[test] fn test_stress_deeply_nested() { let rule = create_enabled_rule(); let content = r#"# Title ## Level 2 A ### Level 3 A #### Level 4 A ## Level 2 B ### Level 3 B #### Level 4 B ## Level 2 C ### Level 3 C #### Level 4 C ## Level 2 D ### Level 3 D #### Level 4 D "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // Check nested indentation is correct assert!(fixed.contains("- [Level 2 A](#level-2-a)")); assert!(fixed.contains(" - [Level 3 A](#level-3-a)")); assert!(fixed.contains(" - [Level 4 A](#level-4-a)")); assert!(fixed.contains("- [Level 2 D](#level-2-d)")); assert!(fixed.contains(" - [Level 3 D](#level-3-d)")); assert!(fixed.contains(" - [Level 4 D](#level-4-d)")); } // ==================== Duplicate TOC anchors ==================== #[test] fn test_duplicate_toc_anchors_produce_correct_diagnostics() { let rule = create_enabled_rule(); // Document has headings "Example", "Another", "Example" which produce anchors: // "example", "another", "example-1" // TOC incorrectly uses #example twice instead of #example and #example-1 let content = r#"# Document - [Example](#example) - [Another](#another) - [Example](#example) ## Example First. ## Another Middle. ## Example Second. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); // The TOC has #example twice but expected has #example and #example-1. // Should report that #example-1 is missing from the TOC. assert!(!result.is_empty(), "Should detect mismatch with duplicate TOC anchors"); assert!( result[0].message.contains("Missing entry") || result[0].message.contains("Stale entry"), "Should report missing or stale entries for duplicate anchors. Got: {}", result[0].message ); } // ==================== Multi-backtick code spans ==================== #[test] fn test_strip_double_backtick_code_span() { // Double-backtick code spans should be stripped let result = strip_markdown_formatting("Using ``code with ` backtick``"); assert_eq!( result, "Using code with ` backtick", "Should strip double-backtick code spans" ); } #[test] fn test_strip_triple_backtick_code_span() { // Triple-backtick code spans should be stripped let result = strip_markdown_formatting("Using ```code with `` backticks```"); assert_eq!( result, "Using code with `` backticks", "Should strip triple-backtick code spans" ); } #[test] fn test_toc_with_double_backtick_heading() { let rule = create_enabled_rule(); // Use fix() to generate the correct TOC (including anchor), then check() // should produce no warnings on the fixed output. let content = r#"# Title ## Using ``code with ` backtick`` Content here. "#; let ctx = create_ctx(content); // The heading uses double-backtick code span: ``code with ` backtick`` // TOC display text preserves the code span; anchor is derived from raw text. let fixed = rule.fix(&ctx).unwrap(); // Verify that the generated TOC entry preserves the double-backtick code span // in the display text. let toc_start = fixed.find("").unwrap(); let toc_end = fixed.find("").unwrap(); let toc_content = &fixed[toc_start..toc_end]; assert!( toc_content.contains("``code with ` backtick``"), "Fix should preserve double-backtick code span in TOC display text. Got: {toc_content}" ); // After fix, check() must produce no warnings (idempotency check) let ctx2 = create_ctx(&fixed); let result = rule.check(&ctx2).unwrap(); assert!( result.is_empty(), "check() should not warn on fixed output. Warnings: {result:?}" ); } #[test] fn test_stress_many_duplicates() { let rule = create_enabled_rule(); // Generate 50 headings with the same text let mut content = String::from("# Title\n\n\n\n\n\n"); for _ in 0..50 { content.push_str("## FAQ\n\nContent.\n\n"); } let ctx = create_ctx(&content); let region = rule.detect_toc_region(&ctx).unwrap(); let expected = rule.build_expected_toc(&ctx, ®ion); // Should generate unique anchors for all 50 assert_eq!(expected.len(), 50); assert_eq!(expected[0].anchor, "faq"); assert_eq!(expected[1].anchor, "faq-1"); assert_eq!(expected[49].anchor, "faq-49"); } /// Core invariant: for every warning with a Fix, fix() must produce /// output consistent with applying that fix directly. #[test] fn test_roundtrip_check_and_fix_alignment() { let rule = create_enabled_rule(); let inputs = [ // Stale entry "# Title\n\n\n- [Old Section](#old-section)\n\n\n## New Section\n", // Missing entry "# Title\n\n\n\n\n## One\n\n## Two\n", // Text mismatch "# Title\n\n\n- [Wrong Text](#real-section)\n\n\n## Real Section\n", // Already correct (no warnings, no change) "# Title\n\n\n- [One](#one)\n- [Two](#two)\n\n\n## One\n\n## Two\n", ]; for input in &inputs { let ctx = create_ctx(input); let fixed = rule.fix(&ctx).unwrap(); // Idempotency: fix(fix(x)) == fix(x) let ctx2 = create_ctx(&fixed); let fixed_twice = rule.fix(&ctx2).unwrap(); assert_eq!( fixed, fixed_twice, "fix() is not idempotent for input: {input:?}\nfirst: {fixed:?}\nsecond: {fixed_twice:?}" ); // After fix, check() should produce no warnings let warnings_after = rule.check(&ctx2).unwrap(); assert!( warnings_after.is_empty(), "check() should return no warnings after fix() for input: {input:?}\nfixed: {fixed:?}\nwarnings: {warnings_after:?}" ); } } /// If a TOC has no mismatches, check() emits no warnings and fix() /// returns content unchanged. #[test] fn test_no_mismatch_preserves_content() { let rule = create_enabled_rule(); let content = "# Title\n\n\n- [First Section](#first-section)\n- [Second Section](#second-section)\n\n\n## First Section\n\ntext\n\n## Second Section\n\ntext\n"; let ctx = create_ctx(content); let warnings = rule.check(&ctx).unwrap(); assert!(warnings.is_empty(), "No mismatches should emit no warnings"); let fixed = rule.fix(&ctx).unwrap(); assert_eq!(fixed, content, "Content should be unchanged when TOC matches headings"); } /// Inline-disabled TOC should not be modified by fix(). #[test] fn test_inline_disable_preserves_toc() { let rule = create_enabled_rule(); // TOC with a stale entry, but MD073 disabled for the TOC region let content = "# Title\n\n\n\n- [Stale](#stale)\n\n\n\n## Real\n"; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert_eq!(fixed, content, "TOC in a disabled region should be preserved exactly"); } /// The warning range is half-open and ends at the start of the stop marker /// line, so it covers every TOC entry line, the last one included. #[test] fn test_warning_range_ends_at_stop_marker_line() { let rule = create_enabled_rule(); let content = "# Title\n\n\n- [Alpha](#alpha)\n- [Stale](#stale)\n\n\n## Alpha\n"; let ctx = create_ctx(content); let warnings = rule.check(&ctx).unwrap(); assert_eq!(warnings.len(), 1); let w = &warnings[0]; assert_eq!((w.line, w.column, w.end_line, w.end_column), (4, 1, 6, 1)); assert_eq!(w.covered_lines(), 4..=5); } /// A `disable-line` comment on the last entry of a TOC suppresses MD073 in /// both check and fix, as it does on any other entry. #[test] fn test_disable_line_on_last_toc_entry_suppresses() { let content = "# Title\n\n\n- [Alpha](#alpha)\n- [Stale](#stale) \n\n\n## Alpha\n\n## Beta\n"; let rules: Vec> = vec![Box::new(create_enabled_rule())]; let warnings = crate::lint(content, &rules, false, MarkdownFlavor::Standard, None, None).unwrap(); assert!( warnings.is_empty(), "disable-line on the last entry must suppress: {warnings:?}" ); let fixed = create_enabled_rule().fix(&create_ctx(content)).unwrap(); assert_eq!(fixed, content, "a suppressed TOC must not be rewritten"); } // ========== Inline Formatting Preservation Tests (#634) ========== /// Backticks in a heading must be preserved in the TOC display text. /// The anchor is generated from the raw heading text (which includes backticks) /// and must still use the stripped form. #[test] fn test_fix_code_ticks_preserved_in_toc_display_text() { let rule = MD073TocValidation::new(); let content = r#"# Title ### `my header` Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!( fixed.contains("- [`my header`](#my-header)"), "Code ticks must be preserved in TOC display text. Got: {fixed}" ); } /// A correct user-written TOC entry with code ticks must not be re-flagged. #[test] fn test_validate_toc_with_code_ticks_is_valid() { let rule = create_enabled_rule(); let content = r#"# Title - [`my header`](#my-header) ## `my header` Content. "#; let ctx = create_ctx(content); let result = rule.check(&ctx).unwrap(); assert!( result.is_empty(), "A TOC entry with preserved code ticks should be accepted as valid: {result:?}" ); } /// A heading with bold/italic preserves emphasis markers in the TOC display text; /// the anchor is generated from the raw (formatted) heading text and still uses /// the stripped form. #[test] fn test_fix_emphasis_preserved_in_toc_display_text() { let rule = MD073TocValidation::new(); let content = r#"# Title ## **bold** and *italic* Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!( fixed.contains("- [**bold** and *italic*](#bold-and-italic)"), "Emphasis markers must be preserved in TOC display text. Got: {fixed}" ); } /// A heading containing a link must have the link stripped from the TOC display /// text (nested links are invalid in Markdown). #[test] fn test_fix_link_in_heading_is_stripped() { let rule = MD073TocValidation::new(); let content = r#"# Title ## See [docs](http://example.com) for details Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!( fixed.contains("- [See docs for details](#see-docs-for-details)"), "Link must be stripped from TOC display text. Got: {fixed}" ); // Ensure no URL leaks into TOC entry let toc_start = fixed.find("").unwrap(); let toc_end = fixed.find("").unwrap(); let toc_content = &fixed[toc_start..toc_end]; assert!( !toc_content.contains("http://example.com"), "TOC should not contain link URL: {toc_content}" ); } /// An image in a heading must still be stripped from the TOC display text. #[test] fn test_fix_image_in_heading_is_stripped() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Section ![icon](icon.png) Title Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); assert!( fixed.contains("- [Section icon Title](#section-icon-title)"), "Image must be stripped from TOC display text. Got: {fixed}" ); } /// Running fix() twice on a document with inline-formatted headings must /// produce stable output (idempotency). #[test] fn test_fix_idempotent_with_inline_formatting() { let rule = MD073TocValidation::new(); let content = r#"# Title ## `code` heading ### **bold** heading ## See [link](http://x.com) "#; let ctx = create_ctx(content); let fixed1 = rule.fix(&ctx).unwrap(); let ctx2 = create_ctx(&fixed1); let fixed2 = rule.fix(&ctx2).unwrap(); assert_eq!(fixed1, fixed2, "fix() must be idempotent for inline-formatted headings"); // After fix, check() must produce no warnings let warnings = rule.check(&ctx2).unwrap(); assert!( warnings.is_empty(), "check() must not warn after fix() for inline-formatted headings: {warnings:?}" ); } /// Link-like syntax inside a code span must not be stripped, because it is /// literal content of the code span and not a real Markdown link. #[test] fn test_link_inside_code_span_preserved_in_toc() { let rule = MD073TocValidation::new(); let content = r#"# Title ## Use `[foo](bar)` syntax Content. "#; let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); // The code span `[foo](bar)` must survive intact in the TOC display text. // The anchor is generated from the raw heading text by the GitHub algorithm, // which strips backtick, bracket, and paren characters. Verify only the // display-text preservation, not the exact anchor (which depends on the anchor // generation algorithm's treatment of non-alphanumeric chars in code spans). let toc_start = fixed.find("").unwrap(); let toc_end = fixed.find("").unwrap(); let toc_content = &fixed[toc_start..toc_end]; assert!( toc_content.contains("Use `[foo](bar)` syntax"), "Link-like text inside code span must be preserved in TOC display text. Got: {toc_content}" ); // Also ensure the real link stripping (outside code spans) still works assert!( !toc_content.contains("http://"), "Real links (outside code spans) should be stripped: {toc_content}" ); } // ========== HTML anchor targets ========== /// The TOC region after `fix`, without the markers and surrounding blank lines. fn generated_toc(content: &str) -> String { let rule = create_enabled_rule(); let ctx = create_ctx(content); let fixed = rule.fix(&ctx).unwrap(); let start = fixed.find("").unwrap() + "".len(); let end = fixed.find("").unwrap(); fixed[start..end].trim().to_string() } fn check_toc(content: &str) -> Vec { let rule = create_enabled_rule(); let ctx = create_ctx(content); rule.check(&ctx).unwrap() } #[test] fn test_toc_may_target_the_generated_slug_of_a_heading_with_an_html_anchor() { // GitHub gives the heading both `#cheat-sheets` (generated) and `#cheatsheets` // (the element's own id), so a TOC written against either reaches it. for anchor in ["cheat-sheets", "cheatsheets"] { let content = format!( "# Title\n\n\n\n- [Cheat Sheets](#{anchor})\n\n\n\n## Cheat Sheets\n\nContent.\n" ); let result = check_toc(&content); assert!(result.is_empty(), "#{anchor} reaches the heading, got {result:?}"); } } #[test] fn test_every_anchor_element_on_a_heading_is_a_valid_target() { for anchor in ["old", "older", "foo"] { let content = format!( "# Title\n\n\n\n- [Foo](#{anchor})\n\n\n\n## Foo\n" ); let result = check_toc(&content); assert!(result.is_empty(), "#{anchor} reaches the heading, got {result:?}"); } } #[test] fn test_generated_toc_prefers_the_explicit_html_anchor() { let toc = generated_toc("# Title\n\n\n\n\n## Cheat Sheets\n"); assert_eq!(toc, "- [Cheat Sheets](#cheatsheets)"); } #[test] fn test_regeneration_keeps_an_existing_anchor_that_reaches_its_heading() { // The unrelated missing entry forces a rewrite; the entry already reaching its // heading is not switched to the other valid spelling on the way. let content = "# Title\n\n\n\n- [Cheat Sheets](#cheat-sheets)\n\n\n\n## Cheat Sheets\n\n## Other\n"; assert_eq!( generated_toc(content), "- [Cheat Sheets](#cheat-sheets)\n- [Other](#other)" ); } #[test] fn test_an_attribute_merely_ending_in_id_or_name_is_not_an_anchor() { let toc = generated_toc( "# Title\n\n\n\n\n## Foo\n", ); assert_eq!(toc, "- [Foo](#foo)"); let result = check_toc( "# Title\n\n\n\n- [Foo](#tracking)\n\n\n\n## Foo\n", ); assert_eq!(result.len(), 1, "{result:?}"); assert!( result[0].message.contains("Stale entry: 'Foo'"), "{}", result[0].message ); assert!( result[0].message.contains("Missing entry: 'Foo'"), "{}", result[0].message ); } #[test] fn test_an_empty_id_is_not_an_anchor() { let toc = generated_toc("# Title\n\n\n\n\n## Foo\n"); assert_eq!(toc, "- [Foo](#foo)"); } #[test] fn test_an_explicit_anchor_still_consumes_the_generated_slug() { // GitHub numbers duplicate generated slugs whether or not the first heading also // carries its own id, so the second `Same` is `same-1`, never `same`. let toc = generated_toc("# Title\n\n\n\n\n## Same\n\n## Same\n"); assert_eq!(toc, "- [Same](#stable)\n- [Same](#same-1)"); } #[test] fn test_anchor_markup_inside_a_code_span_is_heading_text() { let heading = "Showing `` syntax"; let toc = generated_toc(&format!("# Title\n\n\n\n\n## {heading}\n")); let slug = AnchorStyle::GitHub.generate_fragment(heading); assert_ne!(slug, "literal"); assert_eq!(toc, format!("- [{heading}](#{slug})")); } #[test] fn test_anchor_markup_inside_an_html_comment_is_not_a_target() { let heading = "Foo "; let toc = generated_toc(&format!("# Title\n\n\n\n\n## {heading}\n")); let slug = AnchorStyle::GitHub.generate_fragment(heading); assert_ne!(slug, "hidden"); assert_eq!(toc, format!("- [{heading}](#{slug})")); } #[test] fn test_an_explicit_anchor_is_written_as_a_valid_link_destination() { // A bare link destination cannot hold `)` or a space, so the anchor is // percent-encoded on the way out, and the encoded entry reaches the heading // again on the next check, so the generated TOC is stable. let headings = "## Alpha\n\n## Beta\n"; let toc = generated_toc(&format!("# Title\n\n\n\n\n{headings}")); assert_eq!(toc, "- [Alpha](#foo%29bar)\n- [Beta](#has%20space)"); let result = check_toc(&format!( "# Title\n\n\n\n{toc}\n\n\n\n{headings}" )); assert!(result.is_empty(), "{result:?}"); } #[test] fn test_regeneration_does_not_encode_an_encoded_entry_twice() { // The entry reaching `foo)bar` is kept as written; the stale sibling forces // the rewrite. let content = "# Title\n\n\n\n- [Alpha](#foo%29bar)\n- [Gone](#gone)\n\n\n\n## Alpha\n"; assert_eq!(generated_toc(content), "- [Alpha](#foo%29bar)"); } #[test] fn test_a_backslash_escaped_anchor_element_defines_no_target() { // `\` renders as literal text, so `#example` reaches nothing. let heading = "Show \\ syntax"; let result = check_toc(&format!( "# Title\n\n\n\n- [{heading}](#example)\n\n\n\n## {heading}\n" )); assert_eq!(result.len(), 1, "{result:?}"); assert!(result[0].message.contains("Stale entry"), "{}", result[0].message); let toc = generated_toc(&format!("# Title\n\n\n\n\n## {heading}\n")); let slug = AnchorStyle::GitHub.generate_fragment(heading); assert_ne!(slug, "example"); assert_eq!(toc, format!("- [{heading}](#{slug})")); } #[test] fn test_a_backslash_escaped_marker_is_text() { // `\` renders as the literal text ``, so the pair // below delimits no TOC region and the prose between them is left alone. let content = "# Title\n\nWrite these lines:\n\n\\\n\nProse that must survive.\n\n\\\n\n## Alpha\n"; let result = check_toc(content); assert!(result.is_empty(), "{result:?}"); assert_eq!(create_enabled_rule().fix(&create_ctx(content)).unwrap(), content); // An even run of backslashes leaves the `<` itself unescaped, so the comment // is rendered and the marker is real. let toc = generated_toc("# Title\n\n\\\\\n\n\n## Alpha\n"); assert_eq!(toc, "- [Alpha](#alpha)"); } #[test] fn test_the_whitespace_beside_an_anchor_element_stays_in_the_heading_text() { // `Foo Bar` renders as "Foo Bar", so an entry written // that way is up to date and a regenerated entry reads the same. let content = "# Title\n\n\n- [Foo Bar](#foo-bar)\n\n\n## Foo Bar\n"; let warnings = check_toc(content); assert!(warnings.is_empty(), "{warnings:?}"); let toc = generated_toc("# Title\n\n\n\n\n## Foo Bar\n"); assert_eq!(toc, "- [Foo Bar](#alias)"); } #[test] fn test_the_whitespace_an_anchor_element_leaves_at_either_end_is_part_of_the_slug() { // `## Alpha ` renders as "Alpha", but GitHub slugs the text // content with the space the element leaves, so the heading answers to // `#alpha-` and `#x` and not to `#alpha`. A leading element likewise // leaves `#-beta`. let document = "# Title\n\n\n- [Alpha](#alpha-)\n- [Beta](#-beta)\n\n\n\ ## Alpha \n\n## Beta\n"; let warnings = check_toc(document); assert!(warnings.is_empty(), "{warnings:?}"); let trimmed = document.replace("#alpha-", "#alpha").replace("#-beta", "#beta"); assert_eq!( check_toc(&trimmed).len(), 1, "a TOC written against trimmed slugs is stale" ); let toc = generated_toc( "# Title\n\n\n\n\n## Alpha \n\n## Beta\n", ); assert_eq!(toc, "- [Alpha](#x)\n- [Beta](#y)"); } #[test] fn test_a_heading_whose_text_slugs_to_nothing_gets_no_toc_entry() { // An image's description becomes its alt text, in which markup is // escaped, so `` inside it is no element and no target, and // the heading's text content is empty: GitHub gives it no anchor at all. // A heading no fragment can reach gets no entry, so the TOC converges // instead of regenerating an `[](#)` entry on every run. let body = "## ![](img.png)\n\n## ![](img.png)\n\n## Plain\n"; let toc = generated_toc(&format!("# Title\n\n\n\n\n{body}")); assert_eq!(toc, "- [Plain](#plain)"); let warnings = check_toc(&format!( "# Title\n\n\n- [Plain](#plain)\n\n\n{body}" )); assert!(warnings.is_empty(), "{warnings:?}"); let warnings = check_toc(&format!( "# Title\n\n\n- [img](#img)\n- [Plain](#plain)\n\n\n{body}" )); assert_eq!( warnings.len(), 1, "an entry for the image's anchor is stale: {warnings:?}" ); } #[test] fn test_an_anchor_inside_another_tags_attribute_value_is_heading_text() { // The `` sits in the span's `title` value, so the browser makes no // element from it: the heading answers to `#foo` and keeps its bytes. let toc = generated_toc( "# Title\n\n\n\n\n## Foo\n", ); assert_eq!(toc, "- [Foo](#foo)"); } #[test] fn test_a_heading_with_a_custom_id_keeps_its_html_anchor_as_a_target() { // `{#new}` replaces the generated slug, but the element's own `name` is still // an anchor in the rendered page, so a TOC entry may use either of the two. let heading = "My Section {#new}"; let result = check_toc(&format!( "# Title\n\n\n\n- [My Section](#old)\n\n\n\n## {heading}\n" )); assert!(result.is_empty(), "{result:?}"); let toc = generated_toc(&format!("# Title\n\n\n\n\n## {heading}\n")); assert_eq!(toc, "- [My Section](#new)"); let result = check_toc(&format!( "# Title\n\n\n\n- [My Section](#my-section)\n\n\n\n## {heading}\n" )); assert_eq!(result.len(), 1, "the generated slug is replaced, got {result:?}"); } #[test] fn test_toc_entry_matches_a_multi_line_setext_heading() { // A setext underline makes a heading of the whole paragraph above it, so // the entry a TOC needs holds the joined text and the slug of that text. let content = "# Title\n\n\n\n- [First line second line](#first-line-second-line)\n\n\n\nFirst line\nsecond line\n---\n\nContent.\n"; assert!(check_toc(content).is_empty(), "{:?}", check_toc(content)); assert_eq!( generated_toc(content), "- [First line second line](#first-line-second-line)" ); } #[test] fn test_missing_entry_names_the_first_line_of_a_multi_line_setext_heading() { // The heading a missing entry points at starts on the first line of the // paragraph its underline ends, which is where a reader looks for it. let content = "# Title\n\n\n\n\n\nFirst line\nsecond line\n---\n\nContent.\n"; let result = check_toc(content); assert_eq!(result.len(), 1, "the TOC misses the heading, got {result:?}"); assert!( result[0] .message .contains("Missing entry: 'First line second line' (line 7)"), "the heading starts on line 7: {}", result[0].message ); } mod quoted_headings { use super::*; fn warnings(content: &str) -> usize { let rule = create_enabled_rule(); rule.check(&create_ctx(content)).unwrap().len() } #[test] fn quoted_heading_belongs_in_the_toc() { let toc = |entries: &str| format!("# T\n\n\n\n{entries}\n\n\n## A\n\n> ## Q\n"); assert_eq!(warnings(&toc("- [A](#a)\n- [Q](#q)\n")), 0); assert!( warnings(&toc("- [A](#a)\n")) > 0, "a quoted heading missing from the TOC is reported" ); } #[test] fn quoted_heading_in_every_container_shape_is_listed() { for body in ["> ## Q\n", "> > ## Q\n", "- x\n\n > ## Q\n", "> - x\n>\n> ## Q\n"] { let content = format!("# T\n\n\n\n\n\n{body}"); let rule = create_enabled_rule(); let fixed = rule.fix(&create_ctx(&content)).unwrap(); assert!(fixed.contains("[Q](#q)"), "{body:?}: {fixed:?}"); } } #[test] fn a_toc_inside_a_blockquote_is_reported_without_a_fix() { // Regenerated entries carry no quote prefix, so splicing them in // would end the quote. let content = "# T\n\n> \n>\n> \n\n## A\n"; let rule = create_enabled_rule(); let warnings = rule.check(&create_ctx(content)).unwrap(); assert_eq!(warnings.len(), 1); assert!(warnings[0].fix.is_none()); assert_eq!(rule.fix(&create_ctx(content)).unwrap(), content); } #[test] fn a_correct_toc_inside_a_blockquote_is_valid() { let content = "# T\n\n> \n>\n> - [A](#a)\n> - [Q](#q)\n>\n> \n\n## A\n\n> ## Q\n"; assert_eq!(warnings(content), 0); let stale = content.replace("> - [Q](#q)\n", ""); assert_eq!(warnings(&stale), 1); } #[test] fn a_quoted_toc_keeps_the_indentation_of_nested_entries() { for quote in [">", ">>"] { let mut toc = String::new(); for line in ["", "", "- [A](#a)", " - [B](#b)", "", ""] { toc.push_str(quote); if !line.is_empty() { toc.push(' '); toc.push_str(line); } toc.push('\n'); } let content = format!("# T\n\n{toc}\n## A\n\nx\n\n### B\n"); assert_eq!(warnings(&content), 0, "{content:?}"); let flat = content.replace(" - [B]", "- [B]"); assert_eq!(warnings(&flat), 1, "{flat:?}"); } } #[test] fn a_quote_next_to_an_unquoted_toc_does_not_withhold_its_fix() { let rule = create_enabled_rule(); for content in [ "# T\n\n\n\n> Intro\n\n## A\n", "> Intro\n\n\n\n## A\n", "> Intro\n\n\n\n\n\n> Outro\n\n## A\n", ] { let warnings = rule.check(&create_ctx(content)).unwrap(); assert_eq!(warnings.len(), 1, "{content:?}"); assert!(warnings[0].fix.is_some(), "{content:?}"); } } #[test] fn duplicates_are_numbered_across_quoted_and_unquoted_headings() { let content = "# T\n\n\n\n- [Q](#q)\n- [Q](#q-1)\n\n\n\n> ## Q\n\n## Q\n"; assert_eq!(warnings(content), 0); } #[test] fn headings_outside_the_level_range_still_take_a_number() { // The title is level 1, outside the default range, yet GitHub numbers the // later `## Repeat` as `repeat-1`. let content = "# Repeat\n\n\n\n- [Repeat](#repeat-1)\n\n\n\n## Repeat\n"; assert_eq!(warnings(content), 0); let quoted = "\n\n- [Repeat](#repeat-1)\n\n\n\n> # Repeat\n\n## Repeat\n"; assert_eq!(warnings(quoted), 0); } #[test] fn quoted_heading_in_a_quoted_code_block_is_not_listed() { let content = "# T\n\n\n\n\n\n> ```\n> ## Q\n> ```\n"; assert_eq!(warnings(content), 0); } } }