Skip to content

Commit

Permalink
fixup! feat: Preserve HTML data attributes (from spans to anchors)
Browse files Browse the repository at this point in the history
  • Loading branch information
oprypin authored and pawamoy committed Feb 27, 2024
1 parent afff839 commit ae897ee
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
10 changes: 6 additions & 4 deletions src/mkdocs_autorefs/references.py
Expand Up @@ -15,9 +15,10 @@
if TYPE_CHECKING:
from markdown import Markdown

_ATTR_VALUE = r'"[^"<>]+"|[^"<> ]+' # Possibly with double quotes around
AUTO_REF_RE = re.compile(
r"<span data-(?P<kind>autorefs-(?:identifier|optional|optional-hover))="
r'("?)(?P<identifier>[^"<>]+)\2(?P<attrs> [^<>]+)?>(?P<title>.*?)</span>',
rf"<span data-(?P<kind>autorefs-(?:identifier|optional|optional-hover))=(?P<identifier>{_ATTR_VALUE})"
rf"(?: class=(?P<class>{_ATTR_VALUE}))?(?P<attrs> [^<>]+)?>(?P<title>.*?)</span>",
flags=re.DOTALL,
)
"""A regular expression to match mkdocs-autorefs' special reference markers
Expand Down Expand Up @@ -154,10 +155,11 @@ def fix_ref(url_mapper: Callable[[str], str], unmapped: list[str]) -> Callable:
"""

def inner(match: Match) -> str:
identifier = match["identifier"]
identifier = match["identifier"].strip('"')
title = match["title"]
kind = match["kind"]
attrs = match["attrs"] or ""
classes = (match["class"] or "").strip('"').split()

try:
url = url_mapper(unescape(identifier))
Expand All @@ -173,7 +175,7 @@ def inner(match: Match) -> str:

parsed = urlsplit(url)
external = parsed.scheme or parsed.netloc
classes = ["autorefs", "autorefs-external" if external else "autorefs-internal"]
classes = ["autorefs", "autorefs-external" if external else "autorefs-internal", *classes]
class_attr = " ".join(classes)
if kind == "autorefs-optional-hover":
return f'<a class="{class_attr}" title="{identifier}" href="{escape(url)}"{attrs}>{title}</a>'
Expand Down
4 changes: 2 additions & 2 deletions tests/test_references.py
Expand Up @@ -229,6 +229,6 @@ def test_external_references() -> None:
def test_keep_data_attributes() -> None:
"""Keep HTML data attributes from autorefs spans."""
url_map = {"example": "https://e.com"}
source = '<span data-autorefs-optional="example" data-foo data-bar="0">e</span>'
source = '<span data-autorefs-optional="example" class="hi ho" data-foo data-bar="0">e</span>'
output, _ = fix_refs(source, url_map.__getitem__)
assert output == '<a class="autorefs autorefs-external" href="https://e.com" data-foo data-bar="0">e</a>'
assert output == '<a class="autorefs autorefs-external hi ho" href="https://e.com" data-foo data-bar="0">e</a>'

0 comments on commit ae897ee

Please sign in to comment.