본문으로 건너뛰기
🛠️ToolsShed

마크다운 목차 생성기

마크다운 제목에서 앵커 링크가 있는 목차를 생성합니다.

이 도구 소개

마크다운 목차(TOC)는 문서 상단의 제목 목록으로, 독자가 특정 섹션으로 빠르게 이동하도록 도와줍니다. 이 생성기는 마크다운 소스에서 제목을 자동으로 추출하고 GitHub, GitLab 및 대부분의 마크다운 렌더러와 호환되는 링크된 앵커를 만듭니다. TOC 항목을 수동으로 작성하는 번거로운 작업을 제거하고 문서가 변경될 때 링크가 정확하게 유지되도록 보장합니다.

마크다운 텍스트를 붙여넣고 생성을 클릭하면 작동하는 앵커 링크가 있는 형식화된 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.