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 = ' \nDocs
\n'
+ expected = '