diff --git a/markdownify/__init__.py b/markdownify/__init__.py index d946d2c..7fd9f03 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -1,4 +1,5 @@ from bs4 import BeautifulSoup, Comment, Doctype, NavigableString, Tag +from copy import copy from textwrap import fill import re @@ -268,6 +269,22 @@ def _can_ignore(el): children_to_convert = [el for el in node.children if not _can_ignore(el)] + # Markdown headings can contain links, but not the other way round. + if (node.name == 'a' and node.get('href') + and not parent_tags.intersection({'_inline', '_noformat'}) + and len(children_to_convert) == 1): + child = children_to_convert[0] + if (isinstance(child, Tag) and re.fullmatch(r'h[1-6]', child.name) + and self.should_convert_tag('a') + and self.should_convert_tag(child.name)): + # Adjust a detached copy so callers can reuse their soup. + link = copy(node) + heading = link.find(child.name, recursive=False).extract() + link.clear() + link.extend(list(heading.contents)) + heading.append(link) + return self.process_tag(heading, parent_tags=parent_tags) + # Create a copy of this tag's parent context, then update it to include this tag # to propagate down into the children. parent_tags_for_children = set(parent_tags) diff --git a/tests/test_conversions.py b/tests/test_conversions.py index c95483c..5b7f084 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -1,4 +1,6 @@ -from markdownify import ATX, ATX_CLOSED, BACKSLASH, SPACES, UNDERSCORE +from bs4 import BeautifulSoup + +from markdownify import ATX, ATX_CLOSED, BACKSLASH, MarkdownConverter, SPACES, UNDERSCORE from .utils import md @@ -18,6 +20,33 @@ def test_a(): assert md('https://community.kde.org/Get_Involved', autolinks=False) == '[https://community.kde.org/Get\\_Involved](https://community.kde.org/Get_Involved)' +def test_a_wrapping_a_heading(): + html = '

Search

' + assert md(html, heading_style=ATX) == '\n\n#### [Search](/search)\n\n' + + +def test_a_wrapping_a_heading_respects_heading_style_and_title(): + html = ' \n

Docs

\n
' + expected = '

Docs

' + assert md(html) == md(expected) + assert md(html, heading_style=ATX_CLOSED) == md(expected, heading_style=ATX_CLOSED) + + +def test_a_wrapping_a_heading_preserves_input_and_tag_options(): + html = '

Search

' + soup = BeautifulSoup(html, 'html.parser') + converter = MarkdownConverter(heading_style=ATX) + assert converter.convert_soup(soup) == '#### [Search](/search)' + assert str(soup) == html + assert md(html, strip=['h4']) == '[Search](/search)' + assert md(html, strip=['a']) == '\n\n#### Search\n\n' + + +def test_a_wrapping_a_heading_in_a_table_cell_stays_inline(): + html = '

Search

' + assert md(html, heading_style=ATX) == ' [Search](/search) |' + + def test_a_spaces(): assert md('foo Google bar') == 'foo [Google](http://google.com) bar' assert md('foo Google bar') == 'foo [Google](http://google.com) bar'