From c7329ac1ef002d7ff35fa6395eefcf4c77e5e81f Mon Sep 17 00:00:00 2001 From: Joseph Myers Date: Wed, 19 Feb 2025 15:04:29 +0000 Subject: [PATCH] Escape right square brackets (#187) --- markdownify/__init__.py | 6 +++--- tests/test_escaping.py | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 32a3cf6..3ff0380 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -305,7 +305,7 @@ class MarkdownConverter(object): # escape special characters if we're not inside a preformatted or code element if '_noformat' not in parent_tags: - text = self.escape(text) + text = self.escape(text, parent_tags) # remove leading whitespace at the start or just after a # block-level element; remove traliing whitespace at the end @@ -347,11 +347,11 @@ class MarkdownConverter(object): else: return True - def escape(self, text): + def escape(self, text, parent_tags): if not text: return '' if self.options['escape_misc']: - text = re.sub(r'([\\&<`[>~=+|])', r'\\\1', text) + text = re.sub(r'([]\\&<`[>~=+|])', r'\\\1', text) # A sequence of one or more consecutive '-', preceded and # followed by whitespace or start/end of fragment, might # be confused with an underline of a header, or with a diff --git a/tests/test_escaping.py b/tests/test_escaping.py index d213675..bab4d11 100644 --- a/tests/test_escaping.py +++ b/tests/test_escaping.py @@ -51,7 +51,9 @@ def test_misc(): assert md('-y', escape_misc=True) == '-y' assert md('+ x\n+ y\n', escape_misc=True) == '\\+ x\n\\+ y\n' assert md('`x`', escape_misc=True) == r'\`x\`' - assert md('[text](link)', escape_misc=True) == r'\[text](link)' + assert md('[text](notalink)', escape_misc=True) == r'\[text\](notalink)' + assert md('text]', escape_misc=True) == r'[text\]](link)' + assert md('[text]', escape_misc=True) == r'[\[text\]](link)' assert md('1. x', escape_misc=True) == r'1\. x' # assert md('1. x', escape_misc=True) == r'1\. x' assert md('1. x', escape_misc=True) == r'1\. x'