Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,17 +362,29 @@ def process_text(self, el, parent_tags=None):
# remove leading whitespace at the start or just after a
# block-level element; remove traliing whitespace at the end
# or just before a block-level element.
if (should_remove_whitespace_outside(el.previous_sibling)
if (self._removes_adjacent_whitespace(el.previous_sibling)
or (should_remove_whitespace_inside(el.parent)
and not el.previous_sibling)):
text = text.lstrip(' \t\r\n')
if (should_remove_whitespace_outside(el.next_sibling)
if (self._removes_adjacent_whitespace(el.next_sibling)
or (should_remove_whitespace_inside(el.parent)
and not el.next_sibling)):
text = text.rstrip()

return text

def _removes_adjacent_whitespace(self, el):
"""Return whether a sibling element absorbs the whitespace next to it.

Block-level elements normally do, but a block-level element that is
stripped (or otherwise not converted) is emitted inline, so the
whitespace that separates it from its neighbours must be preserved
instead of being collapsed away (see #249).
"""
if not should_remove_whitespace_outside(el):
return False
return self.should_convert_tag(el.name.lower())

def get_conv_fn_cached(self, tag_name):
"""Given a tag name, return the conversion function using the cache."""
# If conversion function is not in cache, add it
Expand Down
8 changes: 8 additions & 0 deletions tests/test_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ def test_do_not_strip():
assert text == '[Some Text](https://github.com/matthewwithanm)'


def test_strip_block_element_preserves_surrounding_whitespace():
# A stripped block-level element is rendered inline, so the whitespace
# separating it from its neighbours must be preserved (see #249).
html = '<span>Ignored <div>Still ignored</div> tag.</span>'
assert md(html, strip=['div']) == 'Ignored Still ignored tag.'
assert md(html, convert=['span']) == 'Ignored Still ignored tag.'


def test_convert():
text = md('<a href="https://github.com/matthewwithanm">Some Text</a>', convert=['a'])
assert text == '[Some Text](https://github.com/matthewwithanm)'
Expand Down