Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Provide hook interface, use it to expand identifiers and attach additional context to references #46

Merged
merged 5 commits into from
Sep 1, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/mkdocs_autorefs/references.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

import logging
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from html import escape, unescape
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Match
from urllib.parse import urlsplit
from xml.etree.ElementTree import Element
Expand Down Expand Up @@ -40,10 +43,53 @@
"""


class AutoRefHookInterface(ABC):
"""An interface for hooking into how AutoRef handles inline references."""

@dataclass
class Context:
domain: str
role: str
origin: str
filepath: str | Path
lineno: int

def as_dict(self) -> dict[str, str]:
return {
"data-autorefs-domain": self.domain,
"data-autorefs-role": self.role,
"data-autorefs-origin": self.origin,
"data-autorefs-filepath": str(self.filepath),
"data-autorefs-lineno": str(self.lineno),
}

@abstractmethod
def expand_identifier(self, identifier: str) -> str:
"""Expand an identifier in a given context.

Parameters:
identifier: The identifier to expand.

Returns:
The expanded identifier.
"""
raise NotImplementedError

@abstractmethod
def get_context(self) -> AutoRefHookInterface.Context:
"""Get the current context.

Returns:
The current context.
"""
raise NotImplementedError


class AutoRefInlineProcessor(ReferenceInlineProcessor):
"""A Markdown extension."""

name: str = "mkdocs-autorefs"
hook: AutoRefHookInterface | None = None

def __init__(self, *args: Any, **kwargs: Any) -> None: # noqa: D107
super().__init__(REFERENCE_RE, *args, **kwargs)
Expand Down Expand Up @@ -127,6 +173,9 @@ def _make_tag(self, identifier: str, text: str) -> Element:
A new element.
"""
el = Element("span")
if self.hook:
identifier = self.hook.expand_identifier(identifier)
el.attrib.update(self.hook.get_context().as_dict())
pawamoy marked this conversation as resolved.
Show resolved Hide resolved
el.set("data-autorefs-identifier", identifier)
el.text = text
return el
Expand Down
Loading