Reimplement MD001/heading-increment using micromark tokens.

This commit is contained in:
David Anson 2024-06-06 21:19:14 -07:00
parent 39afe0a775
commit f032849081
2 changed files with 36 additions and 18 deletions

View file

@ -2,7 +2,8 @@
"use strict";
const { addErrorDetailIf, filterTokens } = require("../helpers");
const { addErrorDetailIf } = require("../helpers");
const { filterByTypes, getHeadingLevel } = require("../helpers/micromark.cjs");
// eslint-disable-next-line jsdoc/valid-types
/** @type import("./markdownlint").Rule */
@ -10,16 +11,24 @@ module.exports = {
"names": [ "MD001", "heading-increment" ],
"description": "Heading levels should only increment by one level at a time",
"tags": [ "headings" ],
"parser": "markdownit",
"parser": "micromark",
"function": function MD001(params, onError) {
let prevLevel = 0;
filterTokens(params, "heading_open", function forToken(token) {
const level = Number.parseInt(token.tag.slice(1), 10);
if (prevLevel && (level > prevLevel)) {
addErrorDetailIf(onError, token.lineNumber,
"h" + (prevLevel + 1), "h" + level);
let prevLevel = Number.MAX_SAFE_INTEGER;
const headings = filterByTypes(
params.parsers.micromark.tokens,
[ "atxHeading", "setextHeading" ]
);
for (const heading of headings) {
const level = getHeadingLevel(heading);
if (level > prevLevel) {
addErrorDetailIf(
onError,
heading.startLine,
`h${prevLevel + 1}`,
`h${level}`
);
}
prevLevel = level;
});
}
}
};