2018-01-21 21:44:25 -08:00
|
|
|
// @ts-check
|
|
|
|
|
2024-11-28 20:36:44 -08:00
|
|
|
import { addError, addErrorContext } from "../helpers/helpers.cjs";
|
|
|
|
import { getDescendantsByType } from "../helpers/micromark-helpers.cjs";
|
|
|
|
import { filterByTypesCached } from "./cache.mjs";
|
2018-01-21 21:44:25 -08:00
|
|
|
|
2024-12-03 19:58:28 -08:00
|
|
|
/** @type {import("markdownlint").Rule} */
|
2024-11-28 20:36:44 -08:00
|
|
|
export default {
|
2018-01-21 21:44:25 -08:00
|
|
|
"names": [ "MD040", "fenced-code-language" ],
|
|
|
|
"description": "Fenced code blocks should have a language specified",
|
|
|
|
"tags": [ "code", "language" ],
|
2024-03-09 16:17:50 -08:00
|
|
|
"parser": "micromark",
|
2018-01-21 21:44:25 -08:00
|
|
|
"function": function MD040(params, onError) {
|
2022-10-18 03:29:29 +08:00
|
|
|
let allowed = params.config.allowed_languages;
|
2022-11-06 01:41:27 +01:00
|
|
|
allowed = Array.isArray(allowed) ? allowed : [];
|
2022-11-11 07:07:04 +01:00
|
|
|
const languageOnly = !!params.config.language_only;
|
2024-08-24 22:05:16 -07:00
|
|
|
const fencedCodes = filterByTypesCached([ "codeFenced" ]);
|
2024-02-18 17:22:32 -08:00
|
|
|
for (const fencedCode of fencedCodes) {
|
2024-09-16 20:50:54 -07:00
|
|
|
const openingFence = getDescendantsByType(fencedCode, [ "codeFencedFence" ])[0];
|
2024-09-24 22:48:14 -07:00
|
|
|
const { startLine, text } = openingFence;
|
|
|
|
const info = getDescendantsByType(openingFence, [ "codeFencedFenceInfo" ])[0]?.text;
|
2024-09-16 20:50:54 -07:00
|
|
|
if (!info) {
|
|
|
|
addErrorContext(onError, startLine, text);
|
|
|
|
} else if ((allowed.length > 0) && !allowed.includes(info)) {
|
|
|
|
addError(onError, startLine, `"${info}" is not allowed`);
|
|
|
|
}
|
2024-09-24 22:48:14 -07:00
|
|
|
if (languageOnly && getDescendantsByType(openingFence, [ "codeFencedFenceMeta" ]).length > 0) {
|
2024-09-16 20:50:54 -07:00
|
|
|
addError(onError, startLine, `Info string contains more than language: "${text}"`);
|
2022-11-11 07:07:04 +01:00
|
|
|
}
|
2024-02-18 17:22:32 -08:00
|
|
|
}
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
|
|
|
};
|