from __future__ import annotations import re from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class Heading: level: int title: str slug: str def slugify_heading(text: str) -> str: slug = text.strip().casefold() slug = re.sub(r"[^\w\s\u4e00-\u9fff-]", "", slug) slug = re.sub(r"[\s_]+", "-", slug) slug = re.sub(r"-{2,}", "-", slug) return slug.strip("-") def extract_headings_from_text(markdown_text: str) -> list[Heading]: headings: list[Heading] = [] seen: dict[str, int] = {} in_fenced_block = False for line in markdown_text.splitlines(): stripped = line.strip() if stripped.startswith("```") or stripped.startswith("~~~"): in_fenced_block = not in_fenced_block continue if in_fenced_block: continue match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped) if not match: continue title = match.group(2).strip() slug = slugify_heading(title) if not slug: continue count = seen.get(slug, 0) seen[slug] = count + 1 if count: slug = f"{slug}-{count + 1}" headings.append(Heading(level=len(match.group(1)), title=title, slug=slug)) return headings def extract_headings(path: Path) -> list[Heading]: try: return extract_headings_from_text(path.read_text(encoding="utf-8")) except UnicodeDecodeError: return []