Sections are split at level 1 and 2 headings outside code and comments, each with a content hash. Wikilinks are found outside code and comments. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
100 lines
3.4 KiB
Python
100 lines
3.4 KiB
Python
"""Find wiki links in a page body."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from chemenu.domain.markdown import line_content, mask_code, split_lines
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class WikiLink:
|
|
"""A link ``[[target#anchor|text]]``; ``embed`` for ``![[...]]``."""
|
|
|
|
target: str
|
|
anchor: str | None = None
|
|
text: str | None = None
|
|
embed: bool = False
|
|
|
|
|
|
def _parse(raw: str, masked: str, embed: bool) -> WikiLink | None:
|
|
"""Parse the inside of a link; ``masked`` locates the separators in ``raw``."""
|
|
bar = masked.find("|")
|
|
text: str | None
|
|
if bar >= 0:
|
|
head_end = bar - 1 if bar > 0 and masked[bar - 1] == "\\" else bar
|
|
text = raw[bar + 1 :].replace("\\|", "|")
|
|
else:
|
|
head_end = len(raw)
|
|
text = None
|
|
head = raw[:head_end]
|
|
hash_ = masked.find("#", 0, head_end)
|
|
target = (head[:hash_] if hash_ >= 0 else head).strip()
|
|
if not target:
|
|
return None
|
|
anchor = head[hash_ + 1 :].strip() if hash_ >= 0 else ""
|
|
return WikiLink(
|
|
target,
|
|
anchor or None,
|
|
(text.strip() or None) if text is not None else None,
|
|
embed,
|
|
)
|
|
|
|
|
|
def _escaped(line: str, index: int) -> bool:
|
|
start = index
|
|
while start > 0 and line[start - 1] == "\\":
|
|
start -= 1
|
|
return (index - start) % 2 == 1
|
|
|
|
|
|
def _links_in_line(raw: str, line: str) -> list[WikiLink]:
|
|
"""Links of one line; ``line`` is ``raw`` with code and comments masked."""
|
|
links: list[WikiLink] = []
|
|
pos = 0
|
|
close = -2
|
|
while True:
|
|
i = line.find("[[", pos)
|
|
if i < 0:
|
|
return links
|
|
# In "[[[x]]" the link opens at the last of the leading brackets.
|
|
while line.startswith("[", i + 2):
|
|
i += 1
|
|
if _escaped(line, i):
|
|
pos = i + 1
|
|
continue
|
|
if close < i + 2:
|
|
close = line.find("]]", i + 2)
|
|
if close < 0:
|
|
return links
|
|
nested = line.find("[[", i + 2, close)
|
|
if nested >= 0:
|
|
pos = nested
|
|
continue
|
|
link = _parse(raw[i + 2 : close], line[i + 2 : close], embed=i > 0 and line[i - 1] == "!")
|
|
if link is not None:
|
|
links.append(link)
|
|
pos = close + 2
|
|
|
|
|
|
def find_wikilinks(body: str) -> tuple[WikiLink, ...]:
|
|
"""All wiki links in order, duplicates kept.
|
|
|
|
Forms: ``[[T]]``, ``[[T|text]]``, ``[[T\\|text]]`` (escaped bar counts as
|
|
``|``), ``[[T#anchor]]``, ``![[T]]`` (embed). The anchor is everything after
|
|
the first ``#``; ``[[#X]]`` has no target and is no link. Target, anchor and
|
|
text are trimmed; an empty anchor or text is None. A link stays within one
|
|
line and contains no ``[[`` or ``]]``; it ends at the first ``]]``, so text
|
|
may hold single brackets (``[[T|a [b] c]]``) but not end in ``]``.
|
|
|
|
A backslash before the first bracket (``\\[[A]]``) makes it no link; two
|
|
backslashes cancel out. Code blocks (also in lists and quotes), inline code
|
|
and HTML comments are ignored as link markup; inside a link they are part of
|
|
target, anchor and text (``[[Use `x` now]]``). Indented code is not
|
|
recognised; lazy continuation lines are simplified (see ``block_lines``).
|
|
"""
|
|
links: list[WikiLink] = []
|
|
for raw, masked in zip(split_lines(body), split_lines(mask_code(body)), strict=True):
|
|
links.extend(_links_in_line(line_content(raw), line_content(masked)))
|
|
return tuple(links)
|