fix(md012): do not flag blank lines adjacent to headings (fixes #990).

Blank lines immediately above or below a heading are now excluded from
MD012's consecutive-blank-line count. Those blank lines are governed by
MD022 (blanks-around-headings), so MD012 defers to it. This means users
can set MD022's lines_above/lines_below > 1 without triggering spurious
MD012 violations.
This commit is contained in:
Ruben J. Jongejan 2026-02-21 13:05:05 +01:00
parent 0213a0274d
commit ccd26cef7f
No known key found for this signature in database
7 changed files with 106 additions and 4 deletions

View file

@ -1,6 +1,6 @@
// @ts-check
import { addErrorDetailIf } from "../helpers/helpers.cjs";
import { addErrorDetailIf, isBlankLine } from "../helpers/helpers.cjs";
import { addRangeToSet } from "../helpers/micromark-helpers.cjs";
import { filterByTypesCached } from "./cache.mjs";
@ -17,14 +17,33 @@ export default {
for (const codeBlock of filterByTypesCached([ "codeFenced", "codeIndented" ])) {
addRangeToSet(codeBlockLineNumbers, codeBlock.startLine, codeBlock.endLine);
}
// Pre-compute blank lines adjacent to headings. Heading spacing is
// governed by MD022 (blanks-around-headings), so MD012 defers to it
// and does not flag blank lines immediately above or below a heading.
const headingAdjacentBlanks = new Set();
for (const heading of filterByTypesCached([ "atxHeading", "setextHeading" ])) {
let i = heading.startLine - 1;
while (i >= 1 && isBlankLine(lines[i - 1])) {
headingAdjacentBlanks.add(i);
i--;
}
i = heading.endLine + 1;
while (i <= lines.length && isBlankLine(lines[i - 1])) {
headingAdjacentBlanks.add(i);
i++;
}
}
let count = 0;
for (const [ lineIndex, line ] of lines.entries()) {
const inCode = codeBlockLineNumbers.has(lineIndex + 1);
const lineNumber = lineIndex + 1;
const inCode = codeBlockLineNumbers.has(lineNumber);
count = (inCode || (line.trim().length > 0)) ? 0 : count + 1;
if (maximum < count) {
if (maximum < count && !headingAdjacentBlanks.has(lineNumber)) {
addErrorDetailIf(
onError,
lineIndex + 1,
lineNumber,
maximum,
count,
undefined,