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
9 changes: 8 additions & 1 deletion markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,10 @@ def _can_ignore(el):
parent_tags_for_children = set(parent_tags)
parent_tags_for_children.add(node.name)

if (node.name in {'h1', 'h2'} and '_inline' not in parent_tags
and self.options['heading_style'].lower() == UNDERLINED):
parent_tags_for_children.add('_setext')

# if this tag is a heading or table cell, add an '_inline' parent pseudo-tag
if (
re_html_heading.match(node.name) is not None # headings
Expand Down Expand Up @@ -433,7 +437,8 @@ def escape(self, text, parent_tags):

def underline(self, text, pad_char):
text = (text or '').rstrip()
return '\n\n%s\n%s\n\n' % (text, pad_char * len(text)) if text else ''
width = max((len(line) for line in text.splitlines()), default=0)
return '\n\n%s\n%s\n\n' % (text, pad_char * width) if text else ''

def convert_a(self, el, text, parent_tags):
if '_noformat' in parent_tags:
Expand Down Expand Up @@ -474,6 +479,8 @@ def _indent_for_blockquote(match):
return '\n' + text + '\n\n'

def convert_br(self, el, text, parent_tags):
if '_setext' in parent_tags:
return '\n' + text
if '_inline' in parent_tags:
return text + ' ' if text else ' '

Expand Down
11 changes: 11 additions & 0 deletions tests/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,17 @@ def test_hn_chained():
assert md('X<h1>First</h1>') == 'X\n\nFirst\n=====\n\n'


def test_multiline_heading_underline_width():
assert md('<h1>Long first line\nShort</h1>') == '\n\nLong first line\nShort\n===============\n\n'
assert md('<h2>Short\nLong second line</h2>') == '\n\nShort\nLong second line\n----------------\n\n'
assert md('<h1></h1>') == ''
assert md('<h1>First\nSecond</h1>', heading_style=ATX) == '\n\n# First Second\n\n'
assert md('<h1>Long first line<br>Short</h1>') == '\n\nLong first line\nShort\n===============\n\n'
assert md('<h2>Short<br />Long second line</h2>') == '\n\nShort\nLong second line\n----------------\n\n'
assert md('<h1>A<br>B<br />C</h1>') == '\n\nA\nB\nC\n=\n\n'
assert md('<td><h1>A<br>B</h1></td>') == ' A B |'


def test_hn_nested_tag_heading_style():
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX_CLOSED) == '\n\n# A P C #\n\n'
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX) == '\n\n# A P C\n\n'
Expand Down