#!/usr/bin/env python3 """Генерация оглавления Markdown по заголовкам.""" from __future__ import annotations import argparse import re import shutil from pathlib import Path FENCE = re.compile(r"^\s*(```|~~~)") HEADING = re.compile(r"^(#{1,6})\s+(.*)$") START = "" END = "" def clean_title(title: str) -> str: title = re.sub(r"`([^`]*)`", r"\1", title) title = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", title) title = re.sub(r"[*_]{1,2}([^*_]+)[*_]{1,2}", r"\1", title) return title.strip() def slugify(title: str) -> str: text = clean_title(title).lower() text = re.sub(r"[^\w\s-]", "", text, flags=re.UNICODE) return re.sub(r"\s+", "-", text).strip("-") or "section" def headings(text: str) -> list[tuple[int, str]]: result = [] in_fence = False for line in text.splitlines(): if FENCE.match(line): in_fence = not in_fence continue if in_fence: continue match = HEADING.match(line) if match: result.append((len(match.group(1)), clean_title(match.group(2)))) return result def build_toc(items: list[tuple[int, str]], minimum: int, maximum: int) -> str: selected = [(level, title) for level, title in items if minimum <= level <= maximum] if not selected: return "" base = min(level for level, _ in selected) used: dict[str, int] = {} lines = [] for level, title in selected: slug = slugify(title) count = used.get(slug, 0) used[slug] = count + 1 anchor = slug if count == 0 else f"{slug}-{count}" label = title.replace("[", "\\[").replace("]", "\\]") lines.append(" " * (level - base) + f"- [{label}](#{anchor})") return "\n".join(lines) def main() -> int: parser = argparse.ArgumentParser(description="Собрать оглавление Markdown") parser.add_argument("--path", type=Path, required=True, help="Markdown-файл") parser.add_argument("--min-level", type=int, default=1, help="Минимальный уровень") parser.add_argument("--max-level", type=int, default=3, help="Максимальный уровень") parser.add_argument("--output", type=Path, help="Записать полный документ в новый файл") parser.add_argument("--in-place", action="store_true", help="Заменить блок между маркерами") args = parser.parse_args() source = args.path.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.in_place and args.output: parser.error("С --in-place не указывайте --output") if args.output and args.output.expanduser().resolve() == source.resolve(): parser.error("Выходной файл совпадает с входным, используйте --in-place") text = source.read_text(encoding="utf-8") items = headings(text) if not items: parser.error("Заголовки не найдены") toc = build_toc(items, args.min_level, args.max_level) if not toc: parser.error("В выбранном диапазоне уровней нет заголовков") if args.output: target = args.output.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(toc + "\n\n" + text, encoding="utf-8") print(f"Результат: {target}") elif args.in_place: if START not in text or END not in text: parser.error(f"В файле нужны маркеры {START} и {END}") backup = source.with_name(source.name + ".bak") shutil.copy2(source, backup) pattern = re.compile(re.escape(START) + r".*?" + re.escape(END), re.DOTALL) replacement = START + "\n" + toc + "\n" + END updated = pattern.sub(lambda _match: replacement, text) source.write_text(updated, encoding="utf-8") print(f"Оглавление обновлено, копия: {backup.name}") else: print(toc) return 0 if __name__ == "__main__": raise SystemExit(main())