Markdown Table of Contents & Anchor Generator

Generate clean, clickable Table of Contents (TOC) lists with deterministic GitHub / GitLab / Bitbucket heading anchor slugs for README.md files and documentation.

How to Use the Markdown Table of Contents & Anchor Generator

1

Paste Markdown / README Text

Paste your Markdown document, documentation files, or README.md text containing standard `#` headings.

2

Customize Depth & Anchor Flavor

Select your heading range (e.g. H2 to H4), list numbering style, and target anchor format (GitHub, GitLab, or Bitbucket).

3

Copy or Download TOC

Copy the clean TOC snippet or full document with automatically synchronized <!-- TOC --> markers.

Tool Options

Configurable Heading Depth

Filter headings between H1 and H6 to exclude top-level document titles or omit deep sub-sections.

Multi-Platform Anchor Slugs

Handles punctuation stripping, space replacement, and duplicate heading suffix resolution (#sec, #sec-1).

Automated Marker Injection

Detects existing <!-- TOC --> comment tags and replaces the block in-place with zero formatting loss.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the Markdown Table of Contents Generator do?

The Markdown Table of Contents & Anchor Generator parses standard Markdown documents, README.md files, and documentation repositories to automatically generate clean, clickable navigation indexes. It calculates deterministic anchor links according to GitHub Flavored Markdown (GFM), GitLab, and Bitbucket specifications, handles heading duplication collisions, and synchronizes <!-- TOC --> comment blocks.

Developers use this utility to maintain navigable documentation, index large README files, ensure anchor link integrity, and automate documentation builds across CI/CD workflows.

Core Concepts & Anchor Rules

Markdown renderers transform headings (# Title) into HTML anchors (<h1 id="title">Title</h1>). However, slugification algorithms vary across platforms:

  • GitHub & GitLab (GFM): Converts headings to lowercase, replaces spaces with hyphens (-), strips non-alphanumeric punctuation (except hyphens and underscores), and handles duplicate headings by appending numerical increments (#section, #section-1, #section-2).
  • Bitbucket: Prepend headings with the platform prefix markdown-header- (e.g. #markdown-header-installation).
  • Setext vs ATX Headings: Supports both inline # ATX headings (H1–H6) and underline-style === (H1) / --- (H2) Setext headings.

How to use the tool?

  1. Paste Markdown Document: Paste your raw Markdown or README.md text into the input editor.
  2. Configure Heading Depth: Set the minimum heading level (e.g., H2 to omit the document H1 title) and maximum depth (e.g., H4 to omit deep sub-headings).
  3. Select List Style & Anchor Flavor: Choose between Hyphen bullets (-), Asterisks (*), or Numbered lists (1.), and select your target platform flavor (GitHub, GitLab, Bitbucket, CommonMark).
  4. Generate Table of Contents: Click 📑 Generate Table of Contents to generate the TOC index, view the interactive visual tree, and copy the isolated TOC snippet or the complete Markdown document with synchronized TOC comment markers.

REST API Integration

Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/markdown/markdown-toc-generator) for programmatic integration.

API Request Parameters

Name Type Description Example
rawText String Raw Markdown document text. "# Project\n\n## Setup\n\n## Usage"
minLevel Number Minimum heading level to include (1-6). Default: 2. 2
maxLevel Number Maximum heading level to include (1-6). Default: 4. 4
listType String List formatting ("unordered", "asterisk", "ordered"). "unordered"
flavor String Target anchor standard ("github", "gitlab", "bitbucket", "plain"). "github"
insertMarker Boolean Whether to inject TOC into <!-- TOC --> block. true

API Request Payload Examples

cURL

curl -X POST https://blueutils.com/api/markdown/markdown-toc-generator \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "# My Project\n\n## Installation & Setup\n\n## API Reference\n### Authentication",
    "minLevel": 2,
    "maxLevel": 4,
    "listType": "unordered",
    "flavor": "github"
  }'

Python

import requests

url = "https://blueutils.com/api/markdown/markdown-toc-generator"
payload = {
    "rawText": "# My Project\n\n## Installation & Setup\n\n## API Reference\n### Authentication",
    "minLevel": 2,
    "maxLevel": 4,
    "listType": "unordered",
    "flavor": "github"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = "{\"rawText\":\"# Project\\n\\n## Setup\\n\\n## Usage\",\"minLevel\":2,\"maxLevel\":4}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/markdown/markdown-toc-generator"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether TOC generation succeeded. true
headingCount Number Total headings detected in document. 3
includedHeadingCount Number Total headings matching depth filter. 3
tocMarkdown String Formatted Table of Contents markdown block. "- [Setup](#setup)\n- [Usage](#usage)"
injectedDocument String Complete Markdown document with updated TOC. "# Project\n\n<!-- TOC -->..."
headings Array Structured list of heading objects and anchors. [...]

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "headingCount": 3,
  "includedHeadingCount": 3,
  "minLevel": 2,
  "maxLevel": 4,
  "listType": "unordered",
  "flavor": "github",
  "tocMarkdown": "- [Installation & Setup](#installation--setup)\n- [API Reference](#api-reference)\n  - [Authentication](#authentication)"
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "No Markdown headings (# H1, ## H2, etc.) were found in the provided text."
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to generate Table of Contents?

Integrating the Markdown TOC Generator API into CI/CD pipelines, DevOps scripts, or automated agent workflows provides several practical advantages:

  • Automated Documentation CI/CD: Keep README.md and repository wikis perfectly synchronized on every Git commit without manual link maintenance.
  • Optimized Token Efficiency for AI Agents: Offload Markdown AST parsing and slug computation to a deterministic API to reduce prompt and completion token overhead.
  • Deterministic Accuracy Without Broken Anchors: Language models frequently miscalculate duplicate slug suffixes or complex punctuation stripping. Delegating TOC generation to a deterministic parser ensures 100% valid clickable links.

Native Usage

How to generate Table of Contents lists locally using native command-line utilities and scripts:

Windows (PowerShell Regex Heading Extractor)

# Extract Markdown headings and generate TOC in PowerShell
Get-Content README.md | Where-Object { $_ -match '^(#{2,4})\s+(.+)$' } | ForEach-Object {
    $level = $Matches[1].Length
    $title = $Matches[2].Trim()
    $slug = $title.ToLower() -replace '[^\w\s-]', '' -replace '\s+', '-'
    $indent = ' ' * (($level - 2) * 2)
    "$indent- [$title](#$slug)"
}

Linux / Unix (Bash / AWK CLI Pipeline)

# Generate Markdown TOC using native AWK
awk '/^##+ / {
    level = length($1);
    title = substr($0, level + 2);
    slug = tolower(title);
    gsub(/[^a-z0-9 -]/, "", slug);
    gsub(/ /, "-", slug);
    indent = sprintf("%*s", (level - 2) * 2, "");
    printf "%s- [%s](#%s)\n", indent, title, slug;
}' README.md

Python (Standard Library re Markdown TOC)

import re

with open("README.md", "r", encoding="utf-8") as f:
    content = f.read()

for match in re.finditer(r'^(#{2,4})\s+(.+)$', content, re.MULTILINE):
    level = len(match.group(1))
    title = match.group(2).strip()
    slug = re.sub(r'[^\w\s-]', '', title.lower()).strip().replace(' ', '-')
    indent = ' ' * ((level - 2) * 2)
    print(f"{indent}- [{title}](#{slug})")

Java (Native Standard Library Heading Scanner)

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkdownToc {
    public static void main(String[] args) throws Exception {
        String content = Files.readString(Path.of("README.md"));
        Pattern pattern = Pattern.compile("^(#{2,4})\\s+(.+)$", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {
            int level = matcher.group(1).length();
            String title = matcher.group(2).trim();
            String slug = title.toLowerCase().replaceAll("[^\\w\\s-]", "").trim().replaceAll("\\s+", "-");
            String indent = " ".repeat((level - 2) * 2);
            System.out.println(indent + "- [" + title + "](#" + slug + ")");
        }
    }
}

Frequently Asked Questions (FAQ)

How do I generate a Table of Contents for Markdown or README files online?

Paste your Markdown document into the input editor, choose your desired heading depth range (e.g. H2 to H4), and click Generate Table of Contents to create clean, indented navigation links.

How does the tool calculate GitHub heading anchor link slugs?

The generator follows the GitHub Flavored Markdown (GFM) slugification specification by converting text to lowercase, replacing spaces with hyphens, stripping punctuation, and resolving duplicate headings with numerical suffixes.

Can the generator automatically inject the TOC into my README document?

Yes. The tool detects existing <!-- TOC --> comment tags in your document and replaces the block in-place, or prepends a synchronized TOC block directly to your markdown.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.