From 4d8c36fa9a5127ab74209dc6a89f972784240b40 Mon Sep 17 00:00:00 2001 From: Ricardo Amaral Date: Fri, 9 Aug 2024 17:27:14 +0100 Subject: [PATCH] fix(paste-markdown): Escape backslashes before punctuation --- src/extensions/rich-text/paste-markdown.ts | 11 ++++++++++- src/serializers/markdown/markdown.ts | 9 ++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/extensions/rich-text/paste-markdown.ts b/src/extensions/rich-text/paste-markdown.ts index 0eed9485..c544cfd3 100644 --- a/src/extensions/rich-text/paste-markdown.ts +++ b/src/extensions/rich-text/paste-markdown.ts @@ -5,6 +5,7 @@ import * as linkify from 'linkifyjs' import { ClipboardDataType } from '../../constants/common' import { PASTE_MARKDOWN_EXTENSION_PRIORITY } from '../../constants/extension-priorities' +import { REGEX_PUNCTUATION } from '../../constants/regular-expressions' /** * A partial type for the the clipboard metadata coming from VS Code. @@ -110,9 +111,17 @@ const PasteMarkdown = Extension.create({ return false } + // Escape all backslash characters that precede any punctuation marks, to + // prevent the backslash itself from being interpreted as an escape sequence + // for the subsequent character. + const escapedTextContent = textContent.replace( + new RegExp(`(\\\\${REGEX_PUNCTUATION.source})`, 'g'), + '\\$1', + ) + // Send the clipboard text through the HTML serializer to convert potential // Markdown into HTML, and then insert it into the editor - editor.commands.insertMarkdownContent(textContent) + editor.commands.insertMarkdownContent(escapedTextContent) // Suppress the default handling behaviour return true diff --git a/src/serializers/markdown/markdown.ts b/src/serializers/markdown/markdown.ts index 2c923ba7..354c8cc1 100644 --- a/src/serializers/markdown/markdown.ts +++ b/src/serializers/markdown/markdown.ts @@ -114,11 +114,10 @@ function createMarkdownSerializer(schema: Schema): MarkdownSerializerReturnType turndown.escape = (str) => { return ( str - // Escape all backslash characters that precedes any punctuation characters, - // otherwise the backslash character itself will be interpreted as escaping the - // character that comes after it (which is not the intent). It's important that - // this escape rule is executed before all other escape rules, otherwise we - // could be double escaping some backslash characters. + // Escape all backslash characters that precede any punctuation marks, to + // prevent the backslash itself from being interpreted as an escape sequence + // for the subsequent character. It's important to apply this rule first to + // avoid double escaping. .replace(new RegExp(`(\\\\${REGEX_PUNCTUATION.source})`, 'g'), '\\$1') // Although the CommonMark specification allows for bulleted or ordered lists