Content Linting with markdownlint

Markdown is forgiving, which is why writers like it and why documentation repositories drift. One writer uses * for bullets and another -; code fences appear with and without language tags, so half the code blocks lose syntax highlighting; a page jumps from ## to ####, breaking the table of contents and screen reader navigation; a list is indented by three spaces instead of two, and the nested code block inside it renders as a paragraph. None of these break the build, and reviewers stop noticing them after the first dozen pull requests.

This guide adds markdownlint-cli2 to a documentation repository with 1,300 Markdown files and 25 contributors: choosing rules that fit documentation, adding custom rules for the site's own conventions, autofixing on commit, reporting findings inline in pull requests, and introducing it without a wall of errors. It is part of Content Workflows for Documentation Teams, and complements prose linting with Editorial Checks with Vale in CI.

Prerequisites

  • Node 20+ and markdownlint-cli2.
  • The site's Markdown conventions written down, even briefly — heading rules, code fence style, how components and shortcodes appear.
  • A pre-commit framework (pre-commit, lefthook or husky) if writers commit locally.

Step 1: Measure the Starting Point

Running markdownlint with all default rules on the repository:

npx markdownlint-cli2 "content/**/*.md" 2>&1 | awk -F' ' '{print $2}' | sort | uniq -c | sort -rn | head
RuleFindings
MD013 line length18,420
MD033 inline HTML2,960
MD040 fenced code without language1,140
MD004 inconsistent list markers870
MD009 trailing spaces640
MD001 heading level skipped212
MD024 duplicate heading text188
MD034 bare URL96

Line length and inline HTML dominated and were mostly not problems for this site: writers use one line per paragraph, and Hugo shortcodes and a few HTML elements for components are intentional. The rest were real.

markdownlint findings by rule excluding line length and inline HTML Horizontal bars of findings from the first run, excluding the line length and inline HTML rules that did not fit the site. Code fences without a language 1,140. Inconsistent list markers 870. Trailing spaces 640. Skipped heading levels 212. Duplicate headings 188. Bare URLs 96. First run, findings that mattered MD040 fence without language 1,140 MD004 list markers 870 MD009 trailing spaces 640 MD001 skipped heading level 212 MD024 duplicate headings 188 MD034 bare URLs 96
1,300 Markdown files; line length (18,420) and inline HTML (2,960) findings were addressed by configuration, not content changes.

Step 2: Configure Rules for Documentation

.markdownlint-cli2.jsonc at the repository root sets rules and file globs:

{
  "config": {
    "default": true,
    "MD013": false,                                   // one paragraph per line
    "MD033": { "allowed_elements": ["details", "summary", "kbd", "br", "figure", "figcaption", "picture", "source", "img"] },
    "MD041": false,                                   // titles live in frontmatter
    "MD024": { "siblings_only": true },               // repeated "Example" under different parents is fine
    "MD004": { "style": "dash" },
    "MD046": { "style": "fenced" },
    "MD048": { "style": "backtick" },
    "MD049": { "style": "underscore" },
    "MD050": { "style": "asterisk" }
  },
  "globs": ["content/**/*.md"],
  "ignores": ["content/api/generated/**"],
  "customRules": ["./lint/rules/*.cjs"]
}

MD041 (first line must be a top-level heading) is off because titles come from frontmatter and the layout renders the h1. MD024 with siblings_only allows the same subheading under different sections. Generated API reference is ignored, since its Markdown comes from a tool that is fixed at the source.

Step 3: Custom Rules for Site Conventions

Generic rules cannot know a site's conventions. markdownlint custom rules are small JavaScript modules that inspect tokens. Three were added:

  • Internal links must be absolute paths with a trailing slash (/guide/install/), matching the site's URL policy and avoiding redirects.
  • Admonitions must use a known type (note, tip, warning, danger), catching typos like :::warnig that the generator would render as plain text.
  • Images need alt text in Markdown syntax (![](…) with empty brackets is flagged unless marked decorative).
// lint/rules/internal-links.cjs
module.exports = {
  names: ['DOCS001', 'internal-link-format'],
  description: 'Internal links must be absolute paths ending with a slash',
  tags: ['links'],
  function: (params, onError) => {
    for (const token of params.parsers.markdownit.tokens.filter((t) => t.type === 'inline')) {
      for (const child of token.children.filter((c) => c.type === 'link_open')) {
        const href = child.attrGet('href') ?? '';
        if (/^(https?:|mailto:|#)/.test(href)) continue;
        if (!href.startsWith('/') || (!href.endsWith('/') && !href.includes('#') && !/\.\w+$/.test(href))) {
          onError({ lineNumber: child.lineNumber, detail: `"${href}" should be an absolute path ending in /` });
        }
      }
    }
  }
};

The link rule found 1,106 relative or slash-less internal links; combined with the site's redirect policy, each had been an extra redirect hop for readers, as described in Canonical URLs and Duplicate Content on Static Sites.

Built-in markdownlint rules compared with custom site rules Two panels. Built-in rules check Markdown structure, such as heading order, list style, fence languages, trailing spaces and bare URLs, and many are autofixable. Custom rules check site conventions, such as internal links being absolute with a trailing slash, admonition types being known, and images having alt text, and report precise messages for writers. Built-in and custom rules Built-in rules heading order MD001 list style MD004 fence language MD040 trailing spaces MD009 many are autofixable Custom site rules links: absolute with slash admonitions: known types images: alt text about 90 lines of JS
Three custom rules, about 90 lines of JavaScript in total, caught the problems writers asked about most.

Step 4: Fix Automatically Where Possible

Many built-in rules can fix themselves. A one-time bulk fix handled the backlog of mechanical issues:

npx markdownlint-cli2 --fix "content/**/*.md"

That fixed trailing spaces, list markers, blank lines around fences and headings, and emphasis styles in 1,020 files in one commit, reviewed by sampling diffs. Code fence languages cannot be guessed safely by a fixer, so a small script inferred them from content ($ prompts → bash, { on the first line of a JSON-looking block → json) and a writer reviewed the 1,140 changes in batches over a week.

Going forward, a pre-commit hook runs markdownlint-cli2 --fix on staged files, so writers never see fixable findings at all — the fixes are simply part of their commit.

Step 5: Report in Pull Requests

In CI, the official action reports findings as annotations on the pull request's changed lines:

- uses: DavidAnson/markdownlint-cli2-action@v17
  with:
    globs: 'content/**/*.md'
    config: '.markdownlint-cli2.jsonc'

Annotations appear inline in the "Files changed" tab, next to the offending line, with the rule name and message. For writers who use GitHub's web editor and never run hooks, that is where they see findings. Custom rule messages were written for writers: "/guide/install should be an absolute path ending in /" is clearer than a rule code.

Stages at which Markdown lint findings are caught A writer edits Markdown in the editor with the markdownlint extension, which highlights issues as they type. On commit, a pre-commit hook autofixes mechanical issues. In the pull request, CI reports remaining issues as inline annotations. The check must pass before merge. Where each finding is caught Editor VS Code extension Pre-commit --fix on staged files CI annotations inline in the PR Required check before merge
By the time a pull request is opened, almost all findings are either fixed automatically or visible inline.

Rolling It Out Without a Wall of Errors

The rules were introduced in three stages over three weeks. First, configuration tuned to the site and the bulk autofix, so the only remaining findings were real content issues. Second, the CI check as a non-blocking report, with a writer assigned to clear the heading-level and fence-language backlog. Third, the check made required once the count was zero. Writers were told in advance, the contributing guide gained a short "Markdown style" section generated from the configuration, and the editor extension was recommended in the repository's .vscode/extensions.json.

Keeping the Configuration Healthy

A lint configuration is code and needs occasional care. When the site adopted a new component syntax for tabs, the inline HTML allowlist needed a new element; when writers started using definition lists through a Markdown extension, one built-in rule misread them as malformed lists and was disabled for those files with an override. Each such change is a small pull request with a one-line reason in a comment next to the rule. Twice a year, the team runs markdownlint with every rule enabled in report-only mode, to see whether a disabled rule has become useful again — the MD034 bare-URL rule was re-enabled that way after writers stopped pasting raw URLs into prose. Upgrading markdownlint-cli2 itself is handled by Renovate like any dependency, and new rules added upstream start as warnings until the backlog for them is cleared.

Measured Impact

MeasureBeforeAfter
Lint findings (configured rules)3,1460
Code blocks without syntax highlighting1,1400
Pages with skipped heading levels2120
Internal links causing redirects1,1060
Review comments about formatting (per month)~60~4
CI time for the lint step—6 s

Pitfalls & Rollback

  • Enabling every default rule. Line length and inline HTML rules clash with most documentation conventions.
  • Unreviewed bulk fixes. Sample the diff; fixers occasionally change meaning in edge cases like nested lists.
  • Rules without writer-friendly messages. Rule codes alone send writers searching.
  • Linting generated content. Fix the generator instead; ignore its output.
  • Rollback: the configuration and CI step can be removed or made non-blocking at any time; fixes already committed stay.

Conclusion

markdownlint keeps a docs repository's Markdown consistent without reviewers policing formatting. Tune the built-in rules to documentation conventions, add a few custom rules for the site's own link and component patterns, autofix on commit, and report the rest inline in pull requests. On this repository it cleared a backlog of 3,146 issues, gave every code block syntax highlighting, and cut formatting comments in review by more than 90%.

FAQ

What does markdownlint check?

Markdown structure and style, such as heading levels and order, list indentation and markers, code fence style and language tags, trailing spaces, line length, bare URLs and duplicate headings. It does not check spelling, grammar or tone, which tools such as Vale handle.

markdownlint-cli or markdownlint-cli2?

markdownlint-cli2 is the newer, faster command-line tool by the same author, with configuration files that support globs, custom rules and fixes. New projects generally start with cli2, and the official GitHub Action uses it.

Which rules are worth disabling for documentation?

Line length is usually disabled because writers use one sentence or paragraph per line and diffs are fine either way. Rules that conflict with the site's generator syntax, such as inline HTML for components or first-line heading rules when titles live in frontmatter, need adjusting rather than blanket enabling.

Can markdownlint fix problems automatically?

Many rules support automatic fixes with the --fix option, including trailing spaces, list markers, blank lines around headings and fences, and heading styles. Running fixes in a pre-commit hook means writers rarely see those findings at all.

Filed underHow-tos