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?
- Paste Markdown Document: Paste your raw Markdown or
README.mdtext into the input editor. - Configure Heading Depth: Set the minimum heading level (e.g.,
H2to omit the document H1 title) and maximum depth (e.g.,H4to omit deep sub-headings). - Select List Style & Anchor Flavor: Choose between Hyphen bullets (
-), Asterisks (*), or Numbered lists (1.), and select your target platform flavor (GitHub,GitLab,Bitbucket,CommonMark). - 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.mdand 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.mdPython (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 + ")");
}
}
}