Link Duplicate Markdown Headings Without Collisions
Repeated headings cannot share one HTML id. The first heading keeps the base anchor, while later matches receive occurrence suffixes such as -2 and -3; the tool inserts those exact ids before the headings and uses the same values in the generated links, so each entry reaches a different section.
Markdown with table of contents
The original document with one replaceable generated block and explicit HTML anchors before included headings.
Every linked heading
| 3 | 2 | Install | install |
| 5 | 3 | Linux | linux |
| 7 | 2 | Install! | install-2 |
| 9 | 3 | Windows | windows |
| 11 | 2 | Install | install-3 |
Two headings named Install become #install and #install-2 rather than two links to the same destination.
Duplicate detection happens after case, punctuation and spacing are normalised, so Install! and install can still collide.
The heading map table exposes the final anchor assigned to every source line before the document is downloaded.
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
Why not rely on the renderer to resolve duplicate headings?
Renderer suffix rules differ and are not part of core Markdown. Explicit ids make the link target part of the document rather than an undocumented host convention.
What happens when a heading contains only punctuation?
Its base becomes section, followed by the same numeric occurrence suffixes if more than one punctuation-only heading is included.
Sources
The full method, worked example and every assumption behind this figure are on Markdown Table of Contents Maker.