Skip to content

Commit

Permalink
fixup! refactor: Duplicate anchors instead of modifying them in-place
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Feb 20, 2024
1 parent a198b36 commit e707340
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
24 changes: 12 additions & 12 deletions src/mkdocstrings/handlers/rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import copy
import re
import textwrap
from typing import TYPE_CHECKING, Any, Iterator
from typing import TYPE_CHECKING, Any

from markdown.extensions import Extension
from markdown.extensions.codehilite import CodeHiliteExtension
Expand Down Expand Up @@ -145,23 +145,23 @@ def __init__(self, md: Markdown, id_prefix: str):
super().__init__(md)
self.id_prefix = id_prefix

@staticmethod
def _iter(parent: Element) -> Iterator[tuple[Element, int, Element]]:
for index, element in enumerate(parent):
yield parent, index, element
yield from IdPrependingTreeprocessor._iter(element)

def run(self, root: Element) -> None: # noqa: D102 (ignore missing docstring)
if not self.id_prefix:
return
for parent, index, el in self._iter(root):
if self.id_prefix:
self._prefix_ids(root)

def _prefix_ids(self, root: Element) -> None:
index = -1
for el in reversed(root):
index += 1

self._prefix_ids(el)
href_attr = el.get("href")

if id_attr := el.get("id"):
if el.tag == "a" and not href_attr:
new_el = copy.copy(el)
new_el = copy.deepcopy(el)
new_el.set("id", self.id_prefix + id_attr)
parent.insert(index + 1, new_el)
root.insert(index + 1, new_el)
else:
el.set("id", self.id_prefix + id_attr)

Expand Down
10 changes: 10 additions & 0 deletions tests/test_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,13 @@ def test_removing_duplicated_headings(ext_markdown: Markdown) -> None:
assert output.count(">Heading two<") == 1
assert output.count(">Heading three<") == 1
assert output.count('class="mkdocstrings') == 0


@pytest.mark.parametrize("ext_markdown", [{"markdown_extensions": [{"attr_list": {}}]}], indirect=["ext_markdown"])
def test_backup_of_anchors(ext_markdown: Markdown) -> None:
"""Anchors with empty `href` are backed up."""
output = ext_markdown.convert("::: tests.fixtures.markdown_anchors")
assert 'id="anchor"' in output
assert 'id="tests.fixtures.markdown_anchors--anchor"' in output
assert 'id="heading-anchor"' in output
assert 'id="tests.fixtures.markdown_anchors--heading-anchor"' in output

0 comments on commit e707340

Please sign in to comment.