Skip to content

Commit afff839

Browse files
committed
feat: Preserve HTML data attributes (from spans to anchors)
Issue-#41: #41
1 parent 143d768 commit afff839

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/mkdocs_autorefs/references.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
from markdown import Markdown
1717

1818
AUTO_REF_RE = re.compile(
19-
r"<span data-(?P<kind>autorefs-identifier|autorefs-optional|autorefs-optional-hover)="
20-
r'("?)(?P<identifier>[^"<>]*)\2>(?P<title>.*?)</span>',
19+
r"<span data-(?P<kind>autorefs-(?:identifier|optional|optional-hover))="
20+
r'("?)(?P<identifier>[^"<>]+)\2(?P<attrs> [^<>]+)?>(?P<title>.*?)</span>',
2121
flags=re.DOTALL,
2222
)
2323
"""A regular expression to match mkdocs-autorefs' special reference markers
@@ -157,6 +157,7 @@ def inner(match: Match) -> str:
157157
identifier = match["identifier"]
158158
title = match["title"]
159159
kind = match["kind"]
160+
attrs = match["attrs"] or ""
160161

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

181182
return inner
182183

tests/test_references.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,3 +224,11 @@ def test_external_references() -> None:
224224
output, unmapped = fix_refs(source, url_map.__getitem__)
225225
assert output == '<a class="autorefs autorefs-external" href="https://example.com">example</a>'
226226
assert unmapped == []
227+
228+
229+
def test_keep_data_attributes() -> None:
230+
"""Keep HTML data attributes from autorefs spans."""
231+
url_map = {"example": "https://e.com"}
232+
source = '<span data-autorefs-optional="example" data-foo data-bar="0">e</span>'
233+
output, _ = fix_refs(source, url_map.__getitem__)
234+
assert output == '<a class="autorefs autorefs-external" href="https://e.com" data-foo data-bar="0">e</a>'

0 commit comments

Comments
 (0)