Refactor to remove codeBlockAndSpanRanges helper.

This commit is contained in:
David Anson 2024-08-15 21:34:27 -07:00
parent c5f4a93cc7
commit 7efc2605b1
7 changed files with 96 additions and 128 deletions

View file

@ -2,8 +2,8 @@
"use strict";
const { addError, forEachLine, withinAnyRange } = require("../helpers");
const { codeBlockAndSpanRanges, lineMetadata } = require("./cache");
const { addError, withinAnyRange } = require("../helpers");
const { addRangeToSet, getExclusionsForToken, filterByTypes } = require("../helpers/micromark.cjs");
const reversedLinkRe =
/(^|[^\\])\(([^()]+)\)\[([^\]^][^\]]*)\](?!\()/g;
@ -14,11 +14,19 @@ module.exports = {
"names": [ "MD011", "no-reversed-links" ],
"description": "Reversed link syntax",
"tags": [ "links" ],
"parser": "none",
"parser": "micromark",
"function": function MD011(params, onError) {
const exclusions = codeBlockAndSpanRanges();
forEachLine(lineMetadata(), (line, lineIndex, inCode, onFence) => {
if (!inCode && !onFence) {
const { tokens } = params.parsers.micromark;
const codeBlockLineNumbers = new Set();
for (const codeBlock of filterByTypes(tokens, [ "codeFenced", "codeIndented" ])) {
addRangeToSet(codeBlockLineNumbers, codeBlock.startLine, codeBlock.endLine);
}
const exclusions = [];
for (const codeText of filterByTypes(tokens, [ "codeText" ])) {
exclusions.push(...getExclusionsForToken(params.lines, codeText));
}
for (const [ lineIndex, line ] of params.lines.entries()) {
if (!codeBlockLineNumbers.has(lineIndex + 1)) {
let match = null;
while ((match = reversedLinkRe.exec(line)) !== null) {
const [ reversedLink, preChar, linkText, linkDestination ] = match;
@ -27,7 +35,7 @@ module.exports = {
if (
!linkText.endsWith("\\") &&
!linkDestination.endsWith("\\") &&
!withinAnyRange(exclusions, lineIndex, index, length)
!withinAnyRange(exclusions, lineIndex + 1, index, length)
) {
addError(
onError,
@ -44,6 +52,6 @@ module.exports = {
}
}
}
});
}
}
};