Skip to content

Commit e2123a9

Browse files
authored
fix: Remove duplicated headings for docstrings nested in tabs/admonitions
Issue #609: #609 PR #610: #610
1 parent 2e9d352 commit e2123a9

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

src/mkdocstrings/extension.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,17 +231,26 @@ def _process_block(
231231

232232
class _PostProcessor(Treeprocessor):
233233
def run(self, root: Element) -> None:
234+
self._remove_duplicated_headings(root)
235+
236+
def _remove_duplicated_headings(self, parent: Element) -> bool:
234237
carry_text = ""
235-
for el in reversed(root): # Reversed mainly for the ability to mutate during iteration.
238+
found = False
239+
for el in reversed(parent): # Reversed mainly for the ability to mutate during iteration.
236240
if el.tag == "div" and el.get("class") == "mkdocstrings":
237241
# Delete the duplicated headings along with their container, but keep the text (i.e. the actual HTML).
238242
carry_text = (el.text or "") + carry_text
239-
root.remove(el)
243+
parent.remove(el)
244+
found = True
240245
elif carry_text:
241246
el.tail = (el.tail or "") + carry_text
242247
carry_text = ""
248+
elif self._remove_duplicated_headings(el):
249+
found = True
250+
break
243251
if carry_text:
244-
root.text = (root.text or "") + carry_text
252+
parent.text = (parent.text or "") + carry_text
253+
return found
245254

246255

247256
class MkdocstringsExtension(Extension):

tests/test_extension.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,21 @@ def test_use_options_yaml_key(ext_markdown: Markdown) -> None:
150150
"""Check that using the 'options' YAML key works as expected."""
151151
assert "h1" in ext_markdown.convert("::: tests.fixtures.headings\n options:\n heading_level: 1")
152152
assert "h1" not in ext_markdown.convert("::: tests.fixtures.headings\n options:\n heading_level: 2")
153+
154+
155+
@pytest.mark.parametrize("ext_markdown", [{"markdown_extensions": [{"pymdownx.tabbed": {"alternate_style": True}}]}], indirect=["ext_markdown"])
156+
def test_removing_duplicated_headings(ext_markdown: Markdown) -> None:
157+
"""Assert duplicated headings are removed from the output."""
158+
output = ext_markdown.convert(
159+
dedent(
160+
"""
161+
=== "Tab A"
162+
163+
::: tests.fixtures.headings
164+
165+
""",
166+
),
167+
)
168+
assert output.count("Foo") == 1
169+
assert output.count("Bar") == 1
170+
assert output.count("Baz") == 1

0 commit comments

Comments
 (0)