From fff54eebd1f32ce21b84f8b853f4b24157bb5aaf Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Sun, 22 Nov 2026 20:51:05 +0800 Subject: [PATCH] Preserve plain newlines for breaks inside preformatted blocks --- markdownify/__init__.py | 3 +++ tests/test_pre_breaks.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tests/test_pre_breaks.py diff --git a/markdownify/__init__.py b/markdownify/__init__.py index d946d2c..98fd497 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -475,6 +475,9 @@ def _indent_for_blockquote(match): return '\n' + text + '\n\n' def convert_br(self, el, text, parent_tags): + if 'pre' in parent_tags and self.should_convert_tag('pre'): + return '\n' + text + if '_inline' in parent_tags: return text + ' ' if text else ' ' diff --git a/tests/test_pre_breaks.py b/tests/test_pre_breaks.py new file mode 100644 index 0000000..62bfe60 --- /dev/null +++ b/tests/test_pre_breaks.py @@ -0,0 +1,23 @@ +import pytest + +from markdownify import markdownify + + +@pytest.mark.parametrize('style', ['SPACES', 'BACKSLASH']) +@pytest.mark.parametrize('content', [ + 'print(1)
print(2)', + 'print(1)
print(2)
', + 'print(1)
print(2)
', +]) +def test_preformatted_breaks_are_plain_newlines(style, content): + assert markdownify('
' + content + '
', newline_style=style) == ( + '```\nprint(1)\nprint(2)\n```' + ) + + +def test_mixed_break_forms_keep_nested_text_in_pre(): + assert markdownify('
a
b
c
') == '```\na\nb\nc\n```' + + +def test_stripped_pre_keeps_normal_break_behavior(): + assert markdownify('
a
b
', strip=['pre']) == 'a \nb'