Skip to content

Commit

Permalink
feat: Provide hook interface, use it to expand identifiers and attach…
Browse files Browse the repository at this point in the history
… additional context to references
  • Loading branch information
pawamoy committed May 14, 2024
1 parent 036b825 commit fe3c22f
Showing 1 changed file with 49 additions and 0 deletions.
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())
el.set("data-autorefs-identifier", identifier)
el.text = text
return el
Expand Down

0 comments on commit fe3c22f

Please sign in to comment.