Skip to content

Commit 54a02a7

Browse files
committed
feat: Handle inline references with markup within them
Inline references with markup within them get their contents stashed. We unstash it to find the identifier, that we slugify to allow later resolution. Follow-up-of-issue-58: #58
1 parent 9e990d7 commit 54a02a7

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

Diff for: src/mkdocs_autorefs/references.py

+21-3
Original file line numberDiff line numberDiff line change
@@ -141,13 +141,25 @@ def handleMatch(self, m: Match[str], data: str) -> tuple[Element | None, int | N
141141
return None, None, None
142142

143143
if slug is None and re.search(r"[\x00-\x1f]", identifier):
144-
# Do nothing if the matched reference contains control characters (from 0 to 31 included).
145-
# Specifically `\x01` is used by Python-Markdown HTML stash when there's inline formatting,
146-
# but references with Markdown formatting are not possible anyway.
144+
# Do nothing if the matched reference still contains control characters (from 0 to 31 included)
145+
# that weren't unstashed when trying to compute a slug of the title.
147146
return None, m.start(0), end
148147

149148
return self._make_tag(identifier, text, slug=slug), m.start(0), end
150149

150+
def _unstash(self, identifier: str) -> str:
151+
stashed_nodes: dict[str, Element | str] = self.md.treeprocessors["inline"].stashed_nodes # type: ignore[attr-defined]
152+
153+
def _repl(match: Match) -> str:
154+
el = stashed_nodes.get(match[1])
155+
if isinstance(el, Element):
156+
return f"`{''.join(el.itertext())}`"
157+
if el == "\x0296\x03":
158+
return "`"
159+
return str(el)
160+
161+
return INLINE_PLACEHOLDER_RE.sub(_repl, identifier)
162+
151163
def _eval_id(self, data: str, index: int, text: str) -> tuple[str | None, str | None, int, bool]:
152164
"""Evaluate the id portion of `[ref][id]`.
153165
@@ -188,6 +200,12 @@ def _eval_id(self, data: str, index: int, text: str) -> tuple[str | None, str |
188200
identifier = Markup(html).striptags()
189201
self.md.htmlStash.rawHtmlBlocks[stash_index] = escape(identifier)
190202

203+
# In any other case, unstash the title and slugify it.
204+
# Examples: ``[`Foo` and `Bar`]``, `[The *Foo*][]`.
205+
else:
206+
identifier = self._unstash(identifier)
207+
slug = slugify(identifier, separator="-")
208+
191209
end = m.end(0)
192210
return identifier, slug, end, True
193211

0 commit comments

Comments
 (0)