# MD051 - Link anchors should exist Aliases: `link-fragments` ## What this rule does Ensures that link anchors (the part after `#`) point to actual headings that exist. This includes both same-document anchors (like `#introduction`) and cross-file fragment links (like `file.md#heading`) when linting multiple files together. A cross-file fragment is checked in the file the link leads to, found the way [MD057](md057.md) finds it: the path is percent-decoded, a link without an extension tries the Markdown extensions, and MD057's `search-paths`, `absolute-links` and `roots` settings apply. A destination with a path always leads to another file, so its fragment is never checked against the linking document. A link whose file does not exist is reported by MD057. MD051 then checks its fragment only in the language server, when the file is a document the editor has open but not yet saved. Reference definitions are checked too, whether or not a link uses them. A definition such as `[setup]: #setup` or `[setup]: guide.md#setup` is reported once, at its destination, with the same messages and skips as an inline link. Definitions in front matter, code blocks, HTML comments and HTML blocks are not checked. ## Why this matters - **Navigation**: Broken internal links frustrate readers trying to jump to sections - **Maintenance**: Helps you catch links that break when headings are renamed - **User experience**: Ensures smooth document navigation ## Examples ### ✅ Correct ```markdown # Introduction ## Getting Started See the [Introduction](#introduction) for background. Jump to [Getting Started](#getting-started) to begin. ## Working with **bold** and *italic* Link to [formatted heading](#working-with-bold-and-italic) See [external documentation](README.md#setup) for setup instructions. ``` ### ❌ Incorrect ```markdown # Introduction ## Getting Started [Jump to Installation](#installation) [See Overview](#overview) ``` ### Suggestions When a link is a near miss, the warning names the anchor that does exist: ```text Link anchor '#purpose' does not exist in document headings (did you mean '#purpose-'?) ``` This happens when the fragment equals an existing anchor apart from case or leading and trailing hyphens, or is a small typo of exactly one anchor. For example, a heading `## Purpose ` has the anchor `#purpose-` on GitHub: the comment is dropped, but the space before it becomes a hyphen. A fragment that is close to several anchors, or to none, gets the plain message. ### 🔧 Fixed This rule cannot automatically fix missing anchors - you need to either: - Add the missing heading - Update the link to point to an existing heading - Remove the broken link ## Configuration This rule supports configuring the anchor generation style to match different Markdown processors: ```toml [MD051] # Anchor generation style (default: "github") # - "github": Preserves Unicode, underscores, and consecutive hyphens # - "kramdown": ASCII-only with normalization, removes underscores # - "kramdown-gfm" / "jekyll": Kramdown with GFM input (Jekyll/GitHub Pages) # - "python-markdown" / "mkdocs": Python-Markdown style (collapses separators, ASCII-only) anchor-style = "github" # Match link fragments against headings case-insensitively. # rumdl defaults to true (permissive). markdownlint defaults to false; set # this to false for strict markdownlint parity. ignore-case = true # Optional regex applied to the fragment text (without the leading '#'). # Fragments that match are skipped; useful for runtime-generated anchors # such as footnote IDs or build-time slugs. # ignored-pattern = "^fn:" ``` ### `ignore-case` Controls whether link fragments are matched against headings case-insensitively. - `true` (rumdl default): `[link](#MY-HEADING)` resolves to `# My Heading`. - `false` (markdownlint default): the fragment must exactly match the generated anchor (e.g., `#my-heading`). Useful when targeting strict markdownlint parity. ### `ignored-pattern` A regular expression matched against the fragment text (without the leading `#`). Any fragment that matches is skipped: neither validated nor reported. Use this for runtime-generated anchors that aren't visible in the source: ```toml [MD051] ignored-pattern = "^(fn|fnref):" # Skip footnote anchors ``` An invalid regex is treated as if `ignored-pattern` were unset (no fragment is silently ignored). When using `--flavor mkdocs`, the anchor style automatically defaults to `python-markdown` (unless explicitly overridden). This matches MkDocs's use of Python-Markdown's `toc` extension for anchor generation. ### `check-frontmatter` When enabled, path-shaped values in the document's frontmatter are checked the same way body links are. Disabled by default. | Value | Behavior | |-------|----------| | `false` (default) | Frontmatter values are not checked | | `true` | A fragment in a frontmatter value must name an existing anchor | ```toml # .rumdl.toml [MD051] check-frontmatter = true ``` It is off by default because frontmatter has no syntax marking a value as a link: a path-shaped value is only a guess at one. Static site generators also resolve frontmatter paths from the site root rather than the document's own directory, so checking them like body links reports working paths as broken. Enable it for projects whose frontmatter links really are relative to the document, and list the keys that are not under `ignore-frontmatter-fields`. A fragment-only value is resolved against this document's own headings. A value carrying a path resolves against the target file, exactly like a cross-file body link: ```yaml --- anchor: '#setup' # must match a heading in this document guide: ./install.md#setup # must match a heading in install.md canonical: https://example.com/a.md#setup # external, not checked title: Node.js # prose, not read as a link --- ``` `ignore-case` and `ignored-pattern` apply to frontmatter fragments exactly as they do to body links. ### `ignore-frontmatter-fields` Top-level frontmatter keys whose values are never checked. Matched case-insensitively, and a parent key excludes its whole subtree. Applies only when `check-frontmatter` is enabled. ```toml # .rumdl.toml [MD051] check-frontmatter = true ignore-frontmatter-fields = ["image", "cover"] ``` Use it for the keys a generator resolves from somewhere other than the document's directory, such as theme assets or site-root media paths. ### `html-comments` When enabled, the fragments of inline links written inside HTML comments are checked as well. Disabled by default. | Value | Behavior | |-------|----------| | `false` (default) | Links inside HTML comments are not checked | | `true` | A fragment in an inline link inside a comment must name an existing anchor | ```toml # .rumdl.toml [MD051] html-comments = true ``` It is off by default because a comment is not rendered, so a link in one is not a link the reader can follow. Enable it for projects that keep links in comments to bring back later, or to hand to another tool, and want them kept valid. A `#heading` link in a comment is resolved against this document's headings, and a `file.md#heading` link against the other file's, exactly like a link in the text. A heading written inside a comment is never an anchor. `ignore-case` and `ignored-pattern` apply as they do to body links. ```markdown ## Install ``` ```text a.md:4:13: [MD051] Link anchor '#setup' does not exist in document headings a.md:4:33: [MD051] Link fragment 'flags' not found in 'usage.md' ``` The report points at the link destination. Only inline links are read: images, autolinks, reference links, wikilinks and rumdl or markdownlint directive comments are not, and nothing inside a comment is ever rewritten. A fragment containing a template expression (`{{` or `{%`) is not checked. Pair it with [MD057's `html-comments`](md057.md#html-comments) to also check that the files the comments link to exist. A comment that opens a line of its own, or follows text in a paragraph, is read. A comment inside a larger HTML block (such as a `
`), and a second comment after the first `-->` of a comment that opens a line, are not, and neither is a comment that opens after text inside a blockquote or a list item and runs onto a further line, so a link there may go unchecked. Enabling the option from a `rumdl-configure-file` directive covers the fragments in the same document, not those in links to other files; enable it in the configuration for those. ### Anchor style differences | Heading | GitHub | Python-Markdown | kramdown | | ------------------- | -------------------- | -------------------- | ------------------- | | `Hello World` | `#hello-world` | `#hello-world` | `#hello-world` | | `respect_gitignore` | `#respect_gitignore` | `#respect_gitignore` | `#respectgitignore` | | `The End - yay` | `#the-end---yay` | `#the-end-yay` | `#the-end---yay` | | `CI/CD Migration` | `#cicd-migration` | `#cicd-migration` | `#cicd-migration` | | `Café au Lait` | `#café-au-lait` | `#cafe-au-lait` | `#cafe-au-lait` | | `你好世界` | `#你好世界` | (empty / `#_1`) | `#section` | **Key differences**: - **GitHub**: Preserves Unicode, underscores, and consecutive hyphens (e.g., `---`) - **Python-Markdown** (MkDocs): ASCII-only, collapses consecutive separators (e.g., `---` → `-`), preserves underscores - **kramdown**: ASCII-only, removes underscores, preserves consecutive hyphens ## Automatic fixes This rule does not provide automatic fixes since it cannot guess which heading you meant to link to. ## How heading anchors work When you create a heading like `## Getting Started`, Markdown automatically creates an anchor `#getting-started` that you can link to. The conversion follows these rules: 1. Convert to lowercase: `Getting Started` → `getting started` 2. Replace spaces with hyphens: `getting started` → `getting-started` 3. Remove special characters: `FAQ's & Tips!` → `faqs-tips` 4. Strip formatting: `**Bold** Text` → `bold-text` ## HTML anchors An HTML element in the document is a link target through its `id` attribute, whatever the element. An `` element is also a target through its legacy `name` attribute, the only element for which browsers honour `name` when navigating to a fragment: ```markdown
[both work](#legacy) and [so does this](#modern) and [this](#section-id) ``` Markup inside inline code or an HTML comment is not rendered, markup inside an image description is alt text, and a backslash-escaped `\<` is literal text, so none of these defines a target. Inside an HTML block no escapes are processed, so a backslash before a tag there is plain text and the element is still a target. Tag names there follow the browser, which accepts any character but whitespace, `/` and `>` after the first letter, where CommonMark's inline grammar accepts only letters, digits and hyphens. ## Learn more - [CommonMark anchors](https://spec.commonmark.org/) - How link anchors work - [GitHub heading IDs][github-ids] - GitHub's approach to heading anchors [github-ids]: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#section-links ## Related rules - [MD042](md042.md) - No empty links - [MD034](md034.md) - URLs should be formatted as links - [MD039](md039.md) - No spaces inside link text