2018-01-21 21:44:25 -08:00
|
|
|
// @ts-check
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
2024-08-15 21:34:27 -07:00
|
|
|
const { addError, withinAnyRange } = require("../helpers");
|
2024-08-24 22:05:16 -07:00
|
|
|
const { addRangeToSet, getExclusionsForToken } = require("../helpers/micromark.cjs");
|
|
|
|
const { filterByTypesCached } = require("./cache");
|
2018-01-21 21:44:25 -08:00
|
|
|
|
2021-06-17 21:50:03 -07:00
|
|
|
const reversedLinkRe =
|
2022-12-19 21:36:24 -08:00
|
|
|
/(^|[^\\])\(([^()]+)\)\[([^\]^][^\]]*)\](?!\()/g;
|
2018-01-21 21:44:25 -08:00
|
|
|
|
2024-02-27 20:42:09 -08:00
|
|
|
// eslint-disable-next-line jsdoc/valid-types
|
|
|
|
/** @type import("./markdownlint").Rule */
|
2018-01-21 21:44:25 -08:00
|
|
|
module.exports = {
|
|
|
|
"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);
|
|
|
|
}
|
|
|
|
const exclusions = [];
|
2024-08-24 22:05:16 -07:00
|
|
|
for (const codeText of filterByTypesCached([ "codeText" ])) {
|
2024-08-15 21:34:27 -07:00
|
|
|
exclusions.push(...getExclusionsForToken(params.lines, codeText));
|
|
|
|
}
|
|
|
|
for (const [ lineIndex, line ] of params.lines.entries()) {
|
|
|
|
if (!codeBlockLineNumbers.has(lineIndex + 1)) {
|
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;
|
|
|
|
const index = match.index + preChar.length;
|
|
|
|
const length = match[0].length - preChar.length;
|
|
|
|
if (
|
|
|
|
!linkText.endsWith("\\") &&
|
|
|
|
!linkDestination.endsWith("\\") &&
|
2024-08-15 21:34:27 -07:00
|
|
|
!withinAnyRange(exclusions, lineIndex + 1, index, length)
|
2021-08-22 22:26:12 -07:00
|
|
|
) {
|
2021-06-17 21:50:03 -07:00
|
|
|
addError(
|
|
|
|
onError,
|
|
|
|
lineIndex + 1,
|
2021-08-22 22:26:12 -07:00
|
|
|
reversedLink.slice(preChar.length),
|
2022-10-16 22:16:51 -07:00
|
|
|
undefined,
|
2021-06-17 21:50:03 -07:00
|
|
|
[ index + 1, length ],
|
|
|
|
{
|
|
|
|
"editColumn": index + 1,
|
|
|
|
"deleteCount": length,
|
|
|
|
"insertText": `[${linkText}](${linkDestination})`
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
2024-08-15 21:34:27 -07:00
|
|
|
}
|
2018-01-21 21:44:25 -08:00
|
|
|
}
|
|
|
|
};
|