mirror of
https://github.com/DavidAnson/markdownlint.git
synced 2025-12-17 22:40:13 +01:00
Reimplement MD041/first-line-heading/first-line-h1 using micromark tokens.
This commit is contained in:
parent
0f5e65abd4
commit
a83e2d8a09
4 changed files with 94 additions and 80 deletions
46
lib/md041.js
46
lib/md041.js
|
|
@ -3,6 +3,8 @@
|
|||
"use strict";
|
||||
|
||||
const { addErrorContext, frontMatterHasTitle } = require("../helpers");
|
||||
const { filterByTypes, getHeadingLevel, getHtmlTagInfo, isHtmlFlowComment, nonContentTokens } =
|
||||
require("../helpers/micromark.cjs");
|
||||
|
||||
// eslint-disable-next-line jsdoc/valid-types
|
||||
/** @type import("./markdownlint").Rule */
|
||||
|
|
@ -10,36 +12,26 @@ module.exports = {
|
|||
"names": [ "MD041", "first-line-heading", "first-line-h1" ],
|
||||
"description": "First line in a file should be a top-level heading",
|
||||
"tags": [ "headings" ],
|
||||
"parser": "markdownit",
|
||||
"parser": "micromark",
|
||||
"function": function MD041(params, onError) {
|
||||
const level = Number(params.config.level || 1);
|
||||
const tag = "h" + level;
|
||||
const foundFrontMatterTitle =
|
||||
frontMatterHasTitle(
|
||||
params.frontMatterLines,
|
||||
params.config.front_matter_title
|
||||
);
|
||||
if (!foundFrontMatterTitle) {
|
||||
const htmlHeadingRe = new RegExp(`^<h${level}[ />]`, "i");
|
||||
params.parsers.markdownit.tokens.every((token) => {
|
||||
let isError = false;
|
||||
if (token.type === "html_block") {
|
||||
if (token.content.startsWith("<!--")) {
|
||||
// Ignore leading HTML comments
|
||||
return true;
|
||||
} else if (!htmlHeadingRe.test(token.content)) {
|
||||
// Something other than an HTML heading
|
||||
isError = true;
|
||||
if (!frontMatterHasTitle(params.frontMatterLines, params.config.front_matter_title)) {
|
||||
params.parsers.micromark.tokens.
|
||||
filter((token) => !nonContentTokens.has(token.type) && !isHtmlFlowComment(token)).
|
||||
every((token) => {
|
||||
let isError = true;
|
||||
if ((token.type === "atxHeading") || (token.type === "setextHeading")) {
|
||||
isError = (getHeadingLevel(token) !== level);
|
||||
} else if (token.type === "htmlFlow") {
|
||||
const htmlTexts = filterByTypes(token.children, [ "htmlText" ]);
|
||||
const tagInfo = (htmlTexts.length > 0) && getHtmlTagInfo(htmlTexts[0]);
|
||||
isError = !tagInfo || (tagInfo.name.toLowerCase() !== `h${level}`);
|
||||
}
|
||||
} else if ((token.type !== "heading_open") || (token.tag !== tag)) {
|
||||
// Something other than a Markdown heading
|
||||
isError = true;
|
||||
}
|
||||
if (isError) {
|
||||
addErrorContext(onError, token.lineNumber, token.line);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (isError) {
|
||||
addErrorContext(onError, token.startLine, params.lines[token.startLine - 1]);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue