跳到内容
🛠️ToolsShed

Markdown 目录生成器

从Markdown标题生成带锚链接的目录。

关于此工具

Markdown 目录(TOC)是文档顶部的标题列表,帮助读者快速跳转到特定章节。该生成器自动从你的 Markdown 源代码中提取标题,并创建与 GitHub、GitLab 和大多数 Markdown 渲染器兼容的链接锚点。它消除了手动编写 TOC 条目的繁琐工作,并确保当文档更新时链接始终保持准确。

只需粘贴你的 Markdown 文本并点击生成,即可瞬间创建带有可工作锚点链接的格式化 TOC。该工具支持可定制的选项:控制要包含的最大标题深度(H1 到 H6),并选择你喜欢的项目符号样式(连字符、星号或加号)。重复的标题会自动检测并用后缀编号(如 #heading-1、#heading-2)来防止锚点冲突。

常见问题

代码实现

import re

def heading_to_anchor(text: str) -> str:
    """Convert heading text to a GitHub-Flavored Markdown anchor."""
    anchor = text.lower()
    anchor = re.sub(r"[^\w\s-]", "", anchor)   # remove punctuation (keep letters, digits, -, _)
    anchor = re.sub(r"\s+", "-", anchor.strip())  # spaces → hyphens
    return anchor

def generate_toc(markdown: str, max_depth: int = 3, bullet: str = "-") -> str:
    lines = []
    seen: dict[str, int] = {}

    for line in markdown.splitlines():
        m = re.match(r"^(#{1,6})\s+(.*)", line)
        if not m:
            continue
        level = len(m.group(1))
        if level > max_depth:
            continue

        title  = m.group(2).strip()
        anchor = heading_to_anchor(title)

        # Deduplicate: second occurrence → anchor-1, third → anchor-2, ...
        count  = seen.get(anchor, 0)
        seen[anchor] = count + 1
        if count > 0:
            anchor = f"{anchor}-{count}"

        indent = "  " * (level - 1)
        lines.append(f"{indent}{bullet} [{title}](#{anchor})")

    return "\n".join(lines)


md = """# Getting Started
## Installation
### Prerequisites
### Install
## Configuration
## Usage
# Advanced
## Performance
## Security
"""

print(generate_toc(md, max_depth=3, bullet="-"))
# - [Getting Started](#getting-started)
#   - [Installation](#installation)
#     - [Prerequisites](#prerequisites)
#     - [Install](#install)
#   - [Configuration](#configuration)
#   - [Usage](#usage)
# - [Advanced](#advanced)
#   - [Performance](#performance)
#   - [Security](#security)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.