From 7708d9386e1b43fcb2c7e26e86c3140d65ec981c Mon Sep 17 00:00:00 2001 From: Chandan MK Date: Tue, 17 Nov 2026 16:57:04 +0530 Subject: [PATCH] fix: keep line breaks out of inline code spans --- markdownify/__init__.py | 5 +++++ tests/test_advanced.py | 2 +- tests/test_conversions.py | 3 +++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 95eee9e..b31f984 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -489,6 +489,11 @@ def convert_code(self, el, text, parent_tags): if not text: return '' + # A line break would let the next line start a new block (heading, + # blockquote, HTML block) before the code span is closed. CommonMark + # renders line endings inside code spans as spaces anyway. + text = text.replace('\n', ' ') + # Find the maximum number of consecutive backticks in the text, then # delimit the code span with one more backtick than that max_backticks = max((len(match) for match in re.findall(re_backtick_runs, text)), default=0) diff --git a/tests/test_advanced.py b/tests/test_advanced.py index 6123d8c..1c0614c 100644 --- a/tests/test_advanced.py +++ b/tests/test_advanced.py @@ -31,7 +31,7 @@ def test_code_with_tricky_content(): assert md('>') == "`>`" assert md('/home/username') == "`/home/`**username**" assert md('First line blah blah
blah blah
second line') \ - == "First line `blah blah \nblah blah` second line" + == "First line `blah blah blah blah` second line" def test_special_tags(): diff --git a/tests/test_conversions.py b/tests/test_conversions.py index c95483c..64a3715 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -107,6 +107,9 @@ def test_code(): assert md('foo`bar`baz') == 'foo`` `bar` ``baz' assert md('foo``bar``baz') == 'foo``` ``bar`` ```baz' assert md('foo `bar` baz') == 'foo `` `bar` `` baz' + assert md('foo\n# bar') == '`foo # bar`' + assert md('foo\n<script>') == '`foo