From 802523dc81f8cd932b7f1c7ccb5690b81d531dae Mon Sep 17 00:00:00 2001 From: Chandan MK Date: Fri, 20 Nov 2026 15:05:01 +0530 Subject: [PATCH] fix: escape text inside stripped pre, code, kbd and samp tags process_tag marked every
, ,  and  with the
'_noformat' pseudo-tag, so process_text skipped escaping for their
contents even when the tag was stripped or left out of a convert list.
No fence or code span is emitted in that case, so the text came out
with no escaping at all and escape_misc=True was bypassed:
'<img src=x onerror=alert(1)>' with strip=['code']
became a raw  tag. Only add '_noformat' when the tag is converted.
---
 markdownify/__init__.py |  3 ++-
 tests/test_args.py      | 10 ++++++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index d946d2c..40091e2 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -281,7 +281,8 @@ def _can_ignore(el):
             parent_tags_for_children.add('_inline')
 
         # if this tag is a preformatted element, add a '_noformat' parent pseudo-tag
-        if node.name in {'pre', 'code', 'kbd', 'samp'}:
+        # (unless the tag is stripped, as its contents are then output as plain text)
+        if node.name in {'pre', 'code', 'kbd', 'samp'} and self.should_convert_tag(node.name):
             parent_tags_for_children.add('_noformat')
 
         # Convert the children elements into a list of result strings.
diff --git a/tests/test_args.py b/tests/test_args.py
index 25ffaae..7d3790e 100644
--- a/tests/test_args.py
+++ b/tests/test_args.py
@@ -27,6 +27,16 @@ def test_do_not_convert():
     assert text == 'Some Text'
 
 
+def test_strip_preformatted():
+    # stripped preformatted tags are output as plain text, so their contents are escaped
+    assert md('*foo* <b>', strip=['code'], escape_misc=True) == r'\*foo\* \'
+    assert md('*foo*', strip=['kbd']) == r'\*foo\*'
+    assert md('*foo*', convert=['b']) == r'\*foo\*'
+    assert md('
<script>
', convert=['p'], escape_misc=True) == r'\' + assert md('foo bar', strip=['code']) == 'foo **bar**' + assert md('
*foo*
', strip=['pre']) == '`*foo*`' + + def test_strip_document(): assert markdownify("

Hello

") == "Hello" # test default of STRIP assert markdownify("

Hello

", strip_document=LSTRIP) == "Hello\n\n"