Reimplement MD019/no-multiple-space-atx using micromark tokens.

This commit is contained in:
David Anson 2024-06-11 21:37:09 -07:00
parent 3003d244f9
commit 4ff3a27fa2
6 changed files with 174 additions and 89 deletions

View file

@ -2,8 +2,8 @@
"use strict";
const { addErrorContext, filterTokens, headingStyleFor } =
require("../helpers");
const { addErrorContext } = require("../helpers");
const { filterByTypes, getHeadingStyle } = require("../helpers/micromark.cjs");
// eslint-disable-next-line jsdoc/valid-types
/** @type import("./markdownlint").Rule */
@ -11,32 +11,34 @@ module.exports = {
"names": [ "MD019", "no-multiple-space-atx" ],
"description": "Multiple spaces after hash on atx style heading",
"tags": [ "headings", "atx", "spaces" ],
"parser": "markdownit",
"parser": "micromark",
"function": function MD019(params, onError) {
filterTokens(params, "heading_open", (token) => {
if (headingStyleFor(token) === "atx") {
const { line, lineNumber } = token;
const match = /^(#+)([ \t]{2,})\S/.exec(line);
if (match) {
const [
,
{ "length": hashLength },
{ "length": spacesLength }
] = match;
addErrorContext(
onError,
lineNumber,
line.trim(),
undefined,
undefined,
[ 1, hashLength + spacesLength + 1 ],
{
"editColumn": hashLength + 1,
"deleteCount": spacesLength - 1
}
);
}
const atxHeadings = filterByTypes(
params.parsers.micromark.tokens,
[ "atxHeading" ]
).filter((heading) => getHeadingStyle(heading) === "atx");
for (const atxHeading of atxHeadings) {
const [ atxHeadingSequence, whitespace ] = atxHeading.children;
if (
(atxHeadingSequence?.type === "atxHeadingSequence") &&
(whitespace?.type === "whitespace") &&
(whitespace.text.length > 1)
) {
const column = whitespace.startColumn + 1;
const length = whitespace.endColumn - column;
addErrorContext(
onError,
atxHeading.startLine,
atxHeading.text.trim(),
undefined,
undefined,
[ column, length ],
{
"editColumn": column,
"deleteCount": length
}
);
}
});
}
}
};