diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 28cdaf6..4ea60ec 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -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 @@ -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: @@ -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 ' ' diff --git a/tests/test_conversions.py b/tests/test_conversions.py index c95483c..eecdc8c 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -181,6 +181,17 @@ def test_hn_chained(): assert md('X

First

') == 'X\n\nFirst\n=====\n\n' +def test_multiline_heading_underline_width(): + assert md('

Long first line\nShort

') == '\n\nLong first line\nShort\n===============\n\n' + assert md('

Short\nLong second line

') == '\n\nShort\nLong second line\n----------------\n\n' + assert md('

') == '' + assert md('

First\nSecond

', heading_style=ATX) == '\n\n# First Second\n\n' + assert md('

Long first line
Short

') == '\n\nLong first line\nShort\n===============\n\n' + assert md('

Short
Long second line

') == '\n\nShort\nLong second line\n----------------\n\n' + assert md('

A
B
C

') == '\n\nA\nB\nC\n=\n\n' + assert md('

A
B

') == ' A B |' + + def test_hn_nested_tag_heading_style(): assert md('

A

P

C

', heading_style=ATX_CLOSED) == '\n\n# A P C #\n\n' assert md('

A

P

C

', heading_style=ATX) == '\n\n# A P C\n\n'