Текст и документы

Собрать оглавление Markdown

Строит список разделов со ссылками-якорями и вставляет его между маркерами.

Python Windows macOS Linux Средний
Скачать table_of_contents.py
Описание

Что делает скрипт

Скрипт собирает заголовки вне блоков кода, создаёт уникальные якоря в стиле GitHub и формирует вложенное оглавление. По умолчанию список печатается на экран, а режим --in-place заменяет блок между комментариями toc. Уровни можно ограничить параметрами --min-level и --max-level.

Перед запуском
  • С --in-place меняется файл, но рядом остаётся копия .bak.
Запуск

Быстрый старт

python table_of_contents.py --path article.md

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python table_of_contents.py --path article.md
  • python table_of_contents.py --path article.md --min-level 2 --max-level 3
  • python table_of_contents.py --path article.md --in-place
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Исходник

table_of_contents.py

#!/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 = "<!-- toc -->"
END = "<!-- /toc -->"


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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get text-table-of-contents
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Текст и документы

Поиск, замена, кодировки, Markdown, CSV и работа с большими текстами.