From 7d4adea7f4f754444c8d0e73a78cfc57d516aba5 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Tue, 8 Sep 2026 11:51:41 +0900 Subject: [PATCH] Preserve text spacing in anchors without destinations Return unlinked anchor content before trimming link-label whitespace so adjacent words remain separated. Confidence: high Scope-risk: narrow Tested: 84 tests; public API and CLI; nested spans Not-tested: Alternative BeautifulSoup parsers --- markdownify/__init__.py | 6 +++--- tests/test_conversions.py | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 28cdaf6..db09ba7 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -436,12 +436,12 @@ def underline(self, text, pad_char): return '\n\n%s\n%s\n\n' % (text, pad_char * len(text)) if text else '' def convert_a(self, el, text, parent_tags): - if '_noformat' in parent_tags: + href = el.get('href') + if '_noformat' in parent_tags or not href: return text prefix, suffix, text = chomp(text) if not text: return '' - href = el.get('href') title = el.get('title') # For the replacement see #29: text nodes underscores are escaped if (self.options['autolinks'] @@ -453,7 +453,7 @@ def convert_a(self, el, text, parent_tags): if self.options['default_title'] and not title: title = href title_part = ' "%s"' % title.replace('"', r'\"') if title else '' - return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) if href else text + return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol']) diff --git a/tests/test_conversions.py b/tests/test_conversions.py index c95483c..5efc644 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -31,6 +31,14 @@ def test_a_with_title(): assert md('https://google.com', default_title=True) == '[https://google.com](https://google.com "https://google.com")' +def test_a_without_destination_preserves_whitespace(): + assert md('left middle right') == 'left middle right' + assert md('left middle right') == 'left middle right' + assert md('left right') == 'left right' + assert md('left middle right') == 'left **middle** right' + assert md('leftright') == 'leftright' + + def test_a_shortcut(): text = md('http://google.com') assert text == ''