Skip to content

Commit

Permalink
feat: Preserve HTML data attributes (from spans to anchors)
Browse files Browse the repository at this point in the history
Issue-#41: #41
  • Loading branch information
pawamoy committed Feb 23, 2024
1 parent 143d768 commit afff839
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/mkdocs_autorefs/references.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
from markdown import Markdown

AUTO_REF_RE = re.compile(
r"<span data-(?P<kind>autorefs-identifier|autorefs-optional|autorefs-optional-hover)="
r'("?)(?P<identifier>[^"<>]*)\2>(?P<title>.*?)</span>',
r"<span data-(?P<kind>autorefs-(?:identifier|optional|optional-hover))="
r'("?)(?P<identifier>[^"<>]+)\2(?P<attrs> [^<>]+)?>(?P<title>.*?)</span>',
flags=re.DOTALL,
)
"""A regular expression to match mkdocs-autorefs' special reference markers
Expand Down Expand Up @@ -157,6 +157,7 @@ def inner(match: Match) -> str:
identifier = match["identifier"]
title = match["title"]
kind = match["kind"]
attrs = match["attrs"] or ""

try:
url = url_mapper(unescape(identifier))
Expand All @@ -175,8 +176,8 @@ def inner(match: Match) -> str:
classes = ["autorefs", "autorefs-external" if external else "autorefs-internal"]
class_attr = " ".join(classes)
if kind == "autorefs-optional-hover":
return f'<a class="{class_attr}" title="{identifier}" href="{escape(url)}">{title}</a>'
return f'<a class="{class_attr}" href="{escape(url)}">{title}</a>'
return f'<a class="{class_attr}" title="{identifier}" href="{escape(url)}"{attrs}>{title}</a>'
return f'<a class="{class_attr}" href="{escape(url)}"{attrs}>{title}</a>'

return inner

Expand Down
8 changes: 8 additions & 0 deletions tests/test_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,11 @@ def test_external_references() -> None:
output, unmapped = fix_refs(source, url_map.__getitem__)
assert output == '<a class="autorefs autorefs-external" href="https://example.com">example</a>'
assert unmapped == []


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>'
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>'

0 comments on commit afff839

Please sign in to comment.