2018-01-21 21:44:25 -08:00
|
|
|
// @ts-check
|
|
|
|
|
2024-11-28 20:36:44 -08:00
|
|
|
import { addError, hasOverlap } from "../helpers/helpers.cjs";
|
|
|
|
import { addRangeToSet } from "../helpers/micromark-helpers.cjs";
|
|
|
|
import { filterByTypesCached } from "./cache.mjs";
|
2018-01-21 21:44:25 -08:00
|
|
|
|
2024-11-28 20:36:44 -08:00
|
|
|
const reversedLinkRe = /(^|[^\\])\(([^()]+)\)\[([^\]^][^\]]*)\](?!\()/g;
|
2018-01-21 21:44:25 -08:00
|
|
|
|
2024-11-28 20:36:44 -08:00
|
|
|
/** @type {import("./markdownlint.mjs").Rule} */
|
|
|
|
export default {
|
2018-01-21 21:44:25 -08:00
|
|
|
"names": [ "MD011", "no-reversed-links" ],
|
|
|
|
"description": "Reversed link syntax",
|
|
|
|
"tags": [ "links" ],
|
2024-08-15 21:34:27 -07:00
|
|
|
"parser": "micromark",
|
2018-01-21 21:44:25 -08:00
|
|
|
"function": function MD011(params, onError) {
|
2024-08-15 21:34:27 -07:00
|
|
|
const codeBlockLineNumbers = new Set();
|
2024-08-24 22:05:16 -07:00
|
|
|
for (const codeBlock of filterByTypesCached([ "codeFenced", "codeIndented" ])) {
|
2024-08-15 21:34:27 -07:00
|
|
|
addRangeToSet(codeBlockLineNumbers, codeBlock.startLine, codeBlock.endLine);
|
|
|
|
}
|
2024-09-27 23:58:40 -07:00
|
|
|
const codeTexts = filterByTypesCached([ "codeText" ]);
|
2024-08-15 21:34:27 -07:00
|
|
|
for (const [ lineIndex, line ] of params.lines.entries()) {
|
2024-09-27 23:58:40 -07:00
|
|
|
const lineNumber = lineIndex + 1;
|
|
|
|
if (!codeBlockLineNumbers.has(lineNumber)) {
|
2021-06-17 21:50:03 -07:00
|
|
|
let match = null;
|
|
|
|
while ((match = reversedLinkRe.exec(line)) !== null) {
|
2021-08-22 22:26:12 -07:00
|
|
|
const [ reversedLink, preChar, linkText, linkDestination ] = match;
|
|
|
|
if (
|
|
|
|
!linkText.endsWith("\\") &&
|
2024-09-27 23:58:40 -07:00
|
|
|
!linkDestination.endsWith("\\")
|
2021-08-22 22:26:12 -07:00
|
|
|
) {
|
2024-09-27 23:58:40 -07:00
|
|
|
const column = match.index + preChar.length + 1;
|
|
|
|
const length = match[0].length - preChar.length;
|
2024-11-28 20:36:44 -08:00
|
|
|
/** @type {import("../helpers/helpers.cjs").FileRange} */
|
2024-09-27 23:58:40 -07:00
|
|
|
const range = { "startLine": lineNumber, "startColumn": column, "endLine": lineNumber, "endColumn": column + length - 1 };
|
|
|
|
if (!codeTexts.some((codeText) => hasOverlap(codeText, range))) {
|
|
|
|
addError(
|
|
|
|
onError,
|
|
|
|
lineNumber,
|
|
|
|
reversedLink.slice(preChar.length),
|
|
|
|
undefined,
|
|
|
|
[ column, length ],
|
|
|
|
{
|
|
|
|
"editColumn": column,
|
|
|
|
"deleteCount": length,
|
|
|
|
"insertText": `[${linkText}](${linkDestination})`
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
2021-06-17 21:50:03 -07:00
|
|
|
}
|
|
|
|
}
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
2024-08-15 21:34:27 -07:00
|
|
|
}
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
|
|
|
};
|