-
-
Notifications
You must be signed in to change notification settings - Fork 758
/
Copy pathmd043.mjs
70 lines (68 loc) · 2.23 KB
/
md043.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// @ts-check
import { addErrorContext, addErrorDetailIf } from "../helpers/helpers.cjs";
import { getHeadingLevel, getHeadingText } from "../helpers/micromark-helpers.cjs";
import { filterByTypesCached } from "./cache.mjs";
/** @type {import("markdownlint").Rule} */
export default {
"names": [ "MD043", "required-headings" ],
"description": "Required heading structure",
"tags": [ "headings" ],
"parser": "micromark",
"function": function MD043(params, onError) {
const requiredHeadings = params.config.headings;
if (!Array.isArray(requiredHeadings)) {
// Nothing to check; avoid doing any work
return;
}
const matchCase = params.config.match_case || false;
let i = 0;
let matchAny = false;
let hasError = false;
let anyHeadings = false;
const getExpected = () => requiredHeadings[i++] || "[None]";
const handleCase = (str) => (matchCase ? str : str.toLowerCase());
for (const heading of filterByTypesCached([ "atxHeading", "setextHeading" ])) {
if (!hasError) {
const headingText = getHeadingText(heading);
const headingLevel = getHeadingLevel(heading);
anyHeadings = true;
const actual = `${"".padEnd(headingLevel, "#")} ${headingText}`;
const expected = getExpected();
if (expected === "*") {
const nextExpected = getExpected();
if (handleCase(nextExpected) !== handleCase(actual)) {
matchAny = true;
i--;
}
} else if (expected === "+") {
matchAny = true;
} else if (handleCase(expected) === handleCase(actual)) {
matchAny = false;
} else if (matchAny) {
i--;
} else {
addErrorDetailIf(
onError,
heading.startLine,
expected,
actual
);
hasError = true;
}
}
}
const extraHeadings = requiredHeadings.length - i;
if (
!hasError &&
((extraHeadings > 1) ||
((extraHeadings === 1) && (requiredHeadings[i] !== "*"))) &&
(anyHeadings || !requiredHeadings.every((heading) => heading === "*"))
) {
addErrorContext(
onError,
params.lines.length,
requiredHeadings[i]
);
}
}
};