Skip to content

Commit

Permalink
fixup! feat: Add option to scan and register HTML anchors
Browse files Browse the repository at this point in the history
  • Loading branch information
oprypin committed Feb 23, 2024
1 parent bd1a636 commit cc7ab04
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 13 deletions.
11 changes: 1 addition & 10 deletions src/mkdocs_autorefs/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from typing import TYPE_CHECKING, Any, Callable, Sequence
from urllib.parse import urlsplit

from markdown.extensions.attr_list import AttrListExtension
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.plugins import BasePlugin
from mkdocs.structure.pages import Page
Expand Down Expand Up @@ -53,7 +52,6 @@ class AutorefsPlugin(BasePlugin):
"""

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

def __init__(self) -> None:
Expand Down Expand Up @@ -137,14 +135,7 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
The modified config.
"""
log.debug("Adding AutorefsExtension to the list")
for ext in config.markdown_extensions:
if ext == "attr_list" or isinstance(ext, AttrListExtension):
log.debug("Enabling Markdown anchors feature")
scan_anchors = True
break
else:
scan_anchors = False
config["markdown_extensions"].append(AutorefsExtension(plugin=self if scan_anchors else None))
config["markdown_extensions"].append(AutorefsExtension(self))
return config

def on_page_markdown(self, markdown: str, page: Page, **kwargs: Any) -> str: # noqa: ARG002
Expand Down
12 changes: 11 additions & 1 deletion src/mkdocs_autorefs/references.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import logging
import re
from html import escape, unescape
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Match, Tuple
Expand All @@ -19,6 +20,14 @@

from mkdocs_autorefs.plugin import AutorefsPlugin

try:
from mkdocs.plugins import get_plugin_logger

log = get_plugin_logger(__name__)
except ImportError:
# TODO: remove once support for MkDocs <1.5 is dropped
log = logging.getLogger(f"mkdocs.plugins.{__name__}") # type: ignore[assignment]

AUTO_REF_RE = re.compile(
r"<span data-(?P<kind>autorefs-identifier|autorefs-optional|autorefs-optional-hover)="
r'("?)(?P<identifier>[^"<>]*)\2>(?P<title>.*?)</span>',
Expand Down Expand Up @@ -300,7 +309,8 @@ def extendMarkdown(self, md: Markdown) -> None: # noqa: N802 (casing: parent me
"mkdocs-autorefs",
priority=168, # Right after markdown.inlinepatterns.ReferenceInlineProcessor
)
if self.plugin:
if self.plugin is not None and self.plugin.scan_toc and "attr_list" in md.treeprocessors:
log.debug("Enabling Markdown anchors feature")
md.treeprocessors.register(
AnchorScannerTreeProcessor(self.plugin, md),
"mkdocs-autorefs-anchors-scanner",
Expand Down
31 changes: 29 additions & 2 deletions tests/test_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def test_register_markdown_anchors() -> None:
[](){#alias7}
[decoy](){#alias8}
[](){#alias9}
## Heading more2
## Heading more2 {#heading-custom2}
[](){#alias10}
""",
Expand All @@ -279,6 +279,33 @@ def test_register_markdown_anchors() -> None:
"alias6": "page#alias6",
"alias7": "page#alias7",
"alias8": "page#alias8",
"alias9": "page#heading-more2",
"alias9": "page#heading-custom2",
"alias10": "page#alias10",
}


def test_register_markdown_anchors_with_admonition() -> None:
"""Check that Markdown anchors are registered inside a nested admonition element."""
plugin = AutorefsPlugin()
md = markdown.Markdown(extensions=["attr_list", "toc", "admonition", AutorefsExtension(plugin)])
plugin.current_page = "page"
md.convert(
dedent(
"""
[](){#alias1}
!!! note
## Heading foo
[](){#alias2}
## Heading bar
[](){#alias3}
## Heading baz
""",
),
)
assert plugin._url_map == {
"alias1": "page#alias1",
"alias2": "page#heading-bar",
"alias3": "page#alias3",
}

0 comments on commit cc7ab04

Please sign in to comment.