From 175ec8b7855a5ec35b73ca6750ed6d59e1f9cac3 Mon Sep 17 00:00:00 2001 From: Ferit Date: Tue, 20 Oct 2026 14:40:25 +0300 Subject: [PATCH] Use code delimiters longer than embedded backtick runs --- src/markdown.ts | 7 +++++-- test/test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/markdown.ts b/src/markdown.ts index 4644699..b212ba9 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -73,13 +73,16 @@ const filters: Filters = { }, CODE(el) { const text = el.textContent || '' + const longestRun = (text.match(/`+/g) || []).reduce((longest, run) => Math.max(longest, run.length), 0) if (el.parentNode && el.parentNode.nodeName === 'PRE') { - el.textContent = `\`\`\`\n${text.replace(/\n+$/, '')}\n\`\`\`\n\n` + const fence = '`'.repeat(Math.max(3, longestRun + 1)) + el.textContent = `${fence}\n${text.replace(/\n+$/, '')}\n${fence}\n\n` return el } if (text.indexOf('`') >= 0) { - return `\`\` ${text} \`\`` + const delimiter = '`'.repeat(longestRun + 1) + return `${delimiter} ${text} ${delimiter}` } return `\`${text}\`` }, diff --git a/test/test.js b/test/test.js index bba936d..124fa58 100644 --- a/test/test.js +++ b/test/test.js @@ -1,6 +1,7 @@ // eslint-disable-next-line import/named import {describe, it, beforeEach, afterEach, expect} from 'vitest' import {MarkdownQuote, Quote} from '../src/index' +import {insertMarkdownSyntax} from '../src/markdown' function createSelection(selection, el) { const range = document.createRange() @@ -144,6 +145,37 @@ describe('quote-selection', function () { document.body.innerHTML = '' }) + for (const block of [false, true]) { + it(`uses longer delimiters for backtick runs in ${block ? 'fenced' : 'inline'} code`, function () { + const cases = [ + ['plain', '`plain`', false], + ['a`b', '`` a`b ``', false], + ['`first``middle`last`', '``` `first``middle`last` ```', false], + ['plain', '```\nplain\n```\n\n', true], + ['a`b', '```\na`b\n```\n\n', true], + ['a``b', '``` a``b ```', false], + ['```', '```` ``` ````', false], + ['const code = ```', '````\nconst code = ```\n````\n\n', true], + ['````', '`````\n````\n`````\n\n', true] + ] + for (const [text, expected, fenced] of cases) { + if (fenced !== block) continue + const root = document.createDocumentFragment() + const code = document.createElement('code') + code.textContent = text + if (block) { + const pre = document.createElement('pre') + pre.append(code) + root.append(pre) + } else { + root.append(code) + } + insertMarkdownSyntax(root) + expect(root.textContent).toBe(expected) + } + }) + } + it('preserves formatting', function () { const quote = new MarkdownQuote('.comment-body') quote.select(document.querySelector('.comment-body'))