Skip to content

Commit

Permalink
fix(paste-markdown): Escape backslashes before punctuation
Browse files Browse the repository at this point in the history
  • Loading branch information
rfgamaral committed Aug 9, 2024
1 parent fea6cf8 commit 4d8c36f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
11 changes: 10 additions & 1 deletion src/extensions/rich-text/paste-markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions src/serializers/markdown/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4d8c36f

Please sign in to comment.