Skip to content

Commit

Permalink
actually add plugin option
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Feb 15, 2024
1 parent 3d1020d commit 831e614
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 8 deletions.
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ markdown_extensions:
permalink: "¤"

plugins:
- autorefs:
scan_anchors: true
- search
- markdown-exec
- gen-files:
Expand Down
21 changes: 13 additions & 8 deletions src/mkdocs_autorefs/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from urllib.parse import urlsplit

from mkdocs.plugins import BasePlugin
from mkdocs.config.base import Config
from mkdocs.config.config_options import Type

from mkdocs_autorefs.references import AutorefsExtension, fix_refs, relative_url

Expand All @@ -37,7 +39,11 @@
log = logging.getLogger(f"mkdocs.plugins.{__name__}") # type: ignore[assignment]


class AutorefsPlugin(BasePlugin):
class AutorefsConfig(Config):
scan_anchors = Type(bool, default=False)


class AutorefsPlugin(BasePlugin[AutorefsConfig]):
"""An `mkdocs` plugin.
This plugin defines the following event hooks:
Expand All @@ -50,7 +56,7 @@ class AutorefsPlugin(BasePlugin):
for more information about its plugin system.
"""

scan_html_tags: bool = False
scan_anchors: bool = False
scan_toc: bool = True
current_page: str | None = None

Expand All @@ -61,14 +67,14 @@ def __init__(self) -> None:
self._abs_url_map: dict[str, str] = {}
self.get_fallback_anchor: Callable[[str], str | None] | None = None

def register_anchor(self, page: str, identifier: str) -> None:
def register_anchor(self, page: str, identifier: str, anchor: str | None = None) -> None:
"""Register that an anchor corresponding to an identifier was encountered when rendering the page.
Arguments:
page: The relative URL of the current page. Examples: `'foo/bar/'`, `'foo/index.html'`
identifier: The HTML anchor (without '#') as a string.
"""
self._url_map[identifier] = f"{page}#{identifier}"
self._url_map[identifier] = f"{page}#{anchor or identifier}"

def register_url(self, identifier: str, url: str) -> None:
"""Register that the identifier should be turned into a link to this URL.
Expand Down Expand Up @@ -173,10 +179,9 @@ def on_page_content(self, html: str, page: Page, **kwargs: Any) -> str: # noqa:
for item in page.toc.items:
self.map_urls(page.url, item)

if self.scan_html_tags:
# Matches any html anchors with the id property (e.g. <a id="xx">)
for match in re.findall(r"""<a .*?id=["']([_\w-]*)["'].*?>""", html):
self.register_anchor(page.url, match)
if self.config.scan_anchors or self.scan_anchors:
for href, id in re.findall(r'<a(?:\s+href="([^"]*)")?\s+id="([^"]+)">', html):
self.register_anchor(page.url, identifier=id, anchor=href.lstrip("#"))

return html

Expand Down
22 changes: 22 additions & 0 deletions tests/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import pytest

from mkdocs_autorefs.plugin import AutorefsPlugin
from mkdocs.structure.pages import Page
from mkdocs.structure.files import File


def test_url_registration() -> None:
Expand Down Expand Up @@ -60,3 +62,23 @@ def test_dont_make_relative_urls_relative_again() -> None:
plugin.get_item_url("hello", from_url="baz/bar/foo.html", fallback=lambda _: ("foo.bar.baz",))
== "../../foo/bar/baz.html#foo.bar.baz"
)


def test_register_html_anchors() -> None:
"""Check that HT?ML anchors are registered when enabled."""
plugin = AutorefsPlugin()
plugin.scan_toc = False
plugin.config["scan_anchors"] = plugin.scan_anchors = True

class Page:
url = "/page/url"

plugin.on_page_content(
"""
<a id="foo.bar">
<a id="foo.baz" >
""",
page=Page(),
)
assert "foo.bar" in plugin._url_map
assert "foo.baz" in plugin._url_map

0 comments on commit 831e614

Please sign in to comment.