Reimplement MD024/no-duplicate-heading using micromark tokens.

This commit is contained in:
David Anson 2024-06-19 21:05:31 -07:00
parent b1b16dabec
commit 96354678dc
6 changed files with 77 additions and 49 deletions

View file

@ -2,7 +2,8 @@
"use strict";
const { addErrorContext, forEachHeading } = require("../helpers");
const { addErrorContext } = require("../helpers");
const { filterByTypes, getHeadingLevel, getHeadingText } = require("../helpers/micromark.cjs");
// eslint-disable-next-line jsdoc/valid-types
/** @type import("./markdownlint").Rule */
@ -10,15 +11,20 @@ module.exports = {
"names": [ "MD024", "no-duplicate-heading" ],
"description": "Multiple headings with the same content",
"tags": [ "headings" ],
"parser": "markdownit",
"parser": "micromark",
"function": function MD024(params, onError) {
const siblingsOnly = !!params.config.siblings_only || false;
const knownContents = [ null, [] ];
let lastLevel = 1;
let knownContent = knownContents[lastLevel];
forEachHeading(params, (heading, content) => {
const headings = filterByTypes(
params.parsers.micromark.tokens,
[ "atxHeading", "setextHeading" ]
);
for (const heading of headings) {
const headingText = getHeadingText(heading);
if (siblingsOnly) {
const newLevel = heading.tag.slice(1);
const newLevel = getHeadingLevel(heading);
while (lastLevel < newLevel) {
lastLevel++;
knownContents[lastLevel] = [];
@ -30,16 +36,16 @@ module.exports = {
knownContent = knownContents[newLevel];
}
// @ts-ignore
if (knownContent.includes(content)) {
if (knownContent.includes(headingText)) {
addErrorContext(
onError,
heading.lineNumber,
heading.line.trim()
heading.startLine,
headingText.trim()
);
} else {
// @ts-ignore
knownContent.push(content);
knownContent.push(headingText);
}
});
}
}
};