2018-01-21 21:44:25 -08:00
|
|
|
// @ts-check
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
2019-04-13 11:18:57 -07:00
|
|
|
const { addErrorContext, addErrorDetailIf, forEachHeading } =
|
|
|
|
require("../helpers");
|
2018-01-21 21:44:25 -08:00
|
|
|
|
|
|
|
module.exports = {
|
2018-03-19 23:39:42 +01:00
|
|
|
"names": [ "MD043", "required-headings", "required-headers" ],
|
|
|
|
"description": "Required heading structure",
|
|
|
|
"tags": [ "headings", "headers" ],
|
2018-01-21 21:44:25 -08:00
|
|
|
"function": function MD043(params, onError) {
|
2018-04-27 22:05:34 -07:00
|
|
|
const requiredHeadings = params.config.headings || params.config.headers;
|
2020-01-25 18:40:39 -08:00
|
|
|
if (Array.isArray(requiredHeadings)) {
|
2018-04-27 22:05:34 -07:00
|
|
|
const levels = {};
|
2020-11-23 20:47:28 -08:00
|
|
|
[ 1, 2, 3, 4, 5, 6 ].forEach((level) => {
|
2018-01-21 21:44:25 -08:00
|
|
|
levels["h" + level] = "######".substr(-level);
|
|
|
|
});
|
2018-04-27 22:05:34 -07:00
|
|
|
let i = 0;
|
2020-11-23 20:47:28 -08:00
|
|
|
let matchAny = false;
|
|
|
|
let hasError = false;
|
|
|
|
let anyHeadings = false;
|
|
|
|
// eslint-disable-next-line func-style
|
|
|
|
const getExpected = () => requiredHeadings[i++] || "[None]";
|
|
|
|
forEachHeading(params, (heading, content) => {
|
|
|
|
if (!hasError) {
|
|
|
|
anyHeadings = true;
|
2018-04-27 22:05:34 -07:00
|
|
|
const actual = levels[heading.tag] + " " + content;
|
2021-01-05 21:06:00 -08:00
|
|
|
const expected = getExpected();
|
2018-01-21 21:44:25 -08:00
|
|
|
if (expected === "*") {
|
2020-11-23 20:47:28 -08:00
|
|
|
matchAny = true;
|
2021-01-05 21:06:00 -08:00
|
|
|
getExpected();
|
2020-11-23 20:47:28 -08:00
|
|
|
} else if (expected === "+") {
|
|
|
|
matchAny = true;
|
2018-01-21 21:44:25 -08:00
|
|
|
} else if (expected.toLowerCase() === actual.toLowerCase()) {
|
2020-11-23 20:47:28 -08:00
|
|
|
matchAny = false;
|
|
|
|
} else if (matchAny) {
|
2018-01-21 21:44:25 -08:00
|
|
|
i--;
|
|
|
|
} else {
|
2019-04-13 11:18:57 -07:00
|
|
|
addErrorDetailIf(onError, heading.lineNumber,
|
2018-01-21 21:44:25 -08:00
|
|
|
expected, actual);
|
2020-11-23 20:47:28 -08:00
|
|
|
hasError = true;
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2020-11-23 20:47:28 -08:00
|
|
|
if (
|
|
|
|
!hasError &&
|
|
|
|
(i < requiredHeadings.length) &&
|
|
|
|
(anyHeadings || !requiredHeadings.every((heading) => heading === "*"))
|
|
|
|
) {
|
2019-04-13 11:18:57 -07:00
|
|
|
addErrorContext(onError, params.lines.length,
|
2018-03-19 23:39:42 +01:00
|
|
|
requiredHeadings[i]);
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|