You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Code span inside link text drops the backslash or ends the link early (\], \[, backtick) #4176
A code span inside link text loses its literal backslash, or ends the link early, when its content contains a backslash, a square bracket or a backtick. In CommonMark, code span content is literal (no backslash escapes), and code spans bind more tightly than link brackets.
To Reproduce
Unmodified new Marked().parse(input); the trailing newline is omitted from the output.
Matches the CommonMark reference implementation: the code span's content stays literal inside link text, and the second link in case 3 is parsed separately.
Found with a property test over generated Markdown. The class is narrow: a code span inside link text whose content has a backtick, backslash or square bracket. Happy to test a fix.
Took a look at this, there are two separate things going on:
Backslash dropped (cases 1 and 2):outputLink runs cap[1].replace(/\\([\[\]])/g, '$1') over the whole label before lexing it, so it also strips the \ inside the code span, where it should stay literal.
Link ends in the wrong place (case 3): the code alternative in the inline label regex (`+[^`]*?`+(?!`)) doesn't require the opening and closing backtick runs to be the same length. So in [ ``](…)[\](…)it pairs the with the single backtick in `[`` and the label runs on into the second link.
Fix I tried:
in outputLinkReplace, match code spans (same shape as inline.code) and lone backtick runs and leave them alone, only unescape \[ / \] outside them
in link(), if the label has a backtick, scan for the real closing ] (skip \x, skip whole code spans using inline.code, track bracket depth). If it's not where the regex put it, re-match the ](href "title") part from there with a small linkTail regex (same href/title pieces as link). Bail if there's no tail. Pedantic is left alone.
diff --git a/src/Tokenizer.ts b/src/Tokenizer.ts
index 26fcb34..47e23df 100644
--- a/src/Tokenizer.ts+++ b/src/Tokenizer.ts@@ -16,7 +16,7 @@ import type { MarkedOptions } from './MarkedOptions.ts';
function outputLink(cap: string[], link: Pick<Tokens.Link, 'href' | 'title'>, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image | undefined {
const href = link.href;
const title = link.title || null;
- const text = cap[1].replace(rules.other.outputLinkReplace, '$1');+ const text = cap[1].replace(rules.other.outputLinkReplace, (match, ticks, bracket) => bracket ?? match);
const isImage = cap[0].charAt(0) === '!';
const outerInLink = lexer.state.inLink;
@@ -78,6 +78,38 @@ function indentCodeCompensation(raw: string, text: string, rules: Rules) {
.join('\n');
}
+/**+ * Find the `]` that closes a link label starting at `labelStart`. Code spans+ * bind tighter than link brackets and their backslashes are literal, so they+ * are skipped whole, the way `codespan` would match them.+ */+function findLinkLabelEnd(src: string, labelStart: number, rules: Rules) {+ let level = 0;+ for (let i = labelStart; i < src.length; i++) {+ const char = src[i];+ if (char === '\\') {+ i++;+ } else if (char === '`') {+ const code = rules.inline.code.exec(src.slice(i));+ if (code) {+ i += code[0].length - 1;+ } else {+ while (src[i + 1] === '`') {+ i++;+ }+ }+ } else if (char === '[') {+ level++;+ } else if (char === ']') {+ if (level === 0) {+ return i;+ }+ level--;+ }+ }+ return -1;+}+
function isLabelEndInsideToken(src: string, label: string, labelStart: number, rules: Rules) {
if (!label.includes('<')) {
return false;
@@ -775,9 +807,21 @@ export class _Tokenizer<ParserOutput = string, RendererOutput = string> {
if (this.lexer.state.linkParenPossible === false) {
return undefined;
}
- const cap = this.rules.inline.link.exec(src);+ let cap: string[] | null = this.rules.inline.link.exec(src);
if (cap) {
const labelStart = cap[0].charAt(0) === '!' ? 2 : 1;
+ if (!this.options.pedantic && cap[1].includes('`')) {+ // the label regex can pair backtick runs of different lengths, so+ // let the code spans decide where the label ends+ const labelEnd = findLinkLabelEnd(src, labelStart, this.rules);+ if (labelEnd !== labelStart + cap[1].length) {+ const tail = labelEnd === -1 ? null : this.rules.inline.linkTail.exec(src.slice(labelEnd));+ if (!tail) {+ return;+ }+ cap = [src.slice(0, labelEnd) + tail[0], src.slice(labelStart, labelEnd), tail[1], tail[2]];+ }+ }
if (!this.options.pedantic && isLabelEndInsideToken(src, cap[1], labelStart, this.rules)) {
return;
}
diff --git a/src/rules.ts b/src/rules.ts
index d74f2e2..c7ed7c1 100644
--- a/src/rules.ts+++ b/src/rules.ts@@ -42,7 +42,9 @@ try {
export const other = {
codeRemoveIndent: /^(?: {0,3}\t| {1,4})/gm,
- outputLinkReplace: /\\([\[\]])/g,+ // a code span (matched like `inline.code`) or a lone backtick run is kept+ // as is: a backslash inside a code span is literal+ outputLinkReplace: /(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\([\[\]])/g,
indentCodeCompensation: /^(\s+)(?:```)/,
beginningSpace: /^\s+/,
endingHash: /#$/,
@@ -478,6 +480,13 @@ const link = edit(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \
.replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
.getRegex();
+// The part of `link` after the label, used when the label has to be found by+// scanning instead (see `findLinkLabelEnd`).+const linkTail = edit(/^\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/)+ .replace('href', /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/)+ .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)+ .getRegex();+
const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
.replace('label', _inlineLabel)
.replace('ref', _blockLabel)
@@ -541,6 +550,7 @@ const inlineNormal = {
emStrongRDelimUnd,
escape,
link,
+ linkTail,
nolink,
punctuation,
reflink,
Plus a spec test, test/specs/new/link_code_span_brackets.md/.html, with the three cases from the issue.
How I checked it:
all 3 cases now give exactly the CommonMark output you listed
the new spec fails on master (2 fails) and passes with the patch
npm run test:specs (1949 pass), test:unit (213 pass), test:lint and test:types are all clean
quick differential fuzz against commonmark.js 0.31.2 (200k random inputs built from `\[]](u) and some text, gfm off): about 7.5k inputs went from mismatch to match. 2 went from match to mismatch, and both are the existing escaped-backslash-plus-nested-link quirk: [[\\](u)``](u) already renders wrong on master, my change just shows it in a couple of extra spots. It's a separate thing, so I didn't touch it here.
Happy to open a PR if this approach works for you.
@UziTech looks like @hakarrr picked this up: #4205 (merged) covers the first two cases and #4209 covers the third, so I'll hold off on a duplicate PR. Happy to help test #4209 if that's useful.
Activity
hamarshehmhmd commentedon Nov 2, 2026
Took a look at this, there are two separate things going on:
outputLinkrunscap[1].replace(/\\([\[\]])/g, '$1')over the whole label before lexing it, so it also strips the\inside the code span, where it should stay literal.codealternative in the inline label regex (`+[^`]*?`+(?!`)) doesn't require the opening and closing backtick runs to be the same length. So in[``](…)[\](…)it pairs thewith the single backtick in `[`` and the label runs on into the second link.Fix I tried:
outputLinkReplace, match code spans (same shape asinline.code) and lone backtick runs and leave them alone, only unescape\[/\]outside themlink(), if the label has a backtick, scan for the real closing](skip\x, skip whole code spans usinginline.code, track bracket depth). If it's not where the regex put it, re-match the](href "title")part from there with a smalllinkTailregex (same href/title pieces aslink). Bail if there's no tail. Pedantic is left alone.Plus a spec test,
test/specs/new/link_code_span_brackets.md/.html, with the three cases from the issue.How I checked it:
npm run test:specs(1949 pass),test:unit(213 pass),test:lintandtest:typesare all clean`\[]](u)and some text, gfm off): about 7.5k inputs went from mismatch to match. 2 went from match to mismatch, and both are the existing escaped-backslash-plus-nested-link quirk:[[\\](u)``](u)already renders wrong on master, my change just shows it in a couple of extra spots. It's a separate thing, so I didn't touch it here.Happy to open a PR if this approach works for you.
UziTech commentedon Nov 6, 2026
@hamarshehmhmd could you create a PR?
Fix bracket escapes inside code spans in link text being stripped
Add spec tests for bracket escapes in link text code spans
Add expected HTML for bracket escapes in link text code spans
test: spec link text code spans whose content holds backticks
fix: Fix bracket escapes inside code spans in link text being stripped (
chore(release): 18.2.1 [skip ci]
hamarshehmhmd commentedon Nov 22, 2026
@UziTech looks like @hakarrr picked this up: #4205 (merged) covers the first two cases and #4209 covers the third, so I'll hold off on a duplicate PR. Happy to help test #4209 if that's useful.