Add a Table of Contents to a Markdown README
Paste the README, include heading levels 2 through 4 and download the generated document. The tool places the table after an opening level-one title, inserts an explicit anchor before every included heading, and encloses its own block in markers so running the document through the tool again replaces rather than duplicates it.
Markdown with table of contents
The original document with one replaceable generated block and explicit HTML anchors before included headings.
Every linked heading
| 5 | 2 | Install | install |
| 7 | 3 | Requirements | requirements |
| 9 | 2 | Usage | usage |
| 11 | 3 | Command line | command-line |
Starting at level 2 leaves the README title above the generated navigation instead of linking the title to itself.
Fenced code samples that contain lines beginning with # do not become accidental entries.
The downloaded Markdown contains both the links and their anchors, so it does not depend on a hosting platform's private slug rules.
How it works
How it is done
- Normalise line endings and remove only a complete table-of-contents block and anchor lines previously generated by this tool.
- Scan lines in order, tracking backtick and tilde fences and ignoring four-space or tab-indented code before recognising ATX and Setext headings.
- Simplify each included heading to a lower-case Unicode slug, then append -2, -3 and later suffixes when normalised names collide.
- Insert the exact HTML anchor before each included heading and place one marked, nested list after an opening level-one title or at the document start.
What it assumes
- The selected shallowest level is not deeper than the selected maximum level.
- The scanner targets ordinary CommonMark ATX headings and single-line Setext headings; it is not a full extension-specific Markdown renderer.
- Raw HTML anchors are allowed by the destination renderer. A platform that strips authored HTML will also strip these explicit targets.
- Existing unmarked HTML ids and an incomplete generated marker block are treated as authored content and are never deleted.
Common questions
Where is the generated README table inserted?
When the first non-blank line is a level-one ATX heading, the generated block follows that title. Otherwise it is placed at the beginning of the document.
Can I regenerate the table after headings change?
Yes. The generated start and end comments identify the old block, which is removed before headings are scanned and replaced by one current table.
Sources
The full method, worked example and every assumption behind this figure are on Markdown Table of Contents Maker.