Add section splitting and wikilink detection to the domain
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>
This commit is contained in:
1 parent
b6a00ed972
commit
cc893be3d5
5 files changed
+722
No files matched your search
@@ -0,0 +1,328 @@
|
||||
"""Length-preserving masking of Markdown code and comments.
|
||||
|
||||
Lines end only at LF, CRLF and CR. ``str.splitlines`` is not used: U+2028,
|
||||
form feed and the like do not separate lines here.
|
||||
|
||||
Blocks (fenced code, HTML comments starting a line) hide everything inside
|
||||
them from heading detection. Whoever opens first wins: a fence inside a comment
|
||||
opens nothing and vice versa. Fences are tracked inside list items and block
|
||||
quotes. Indented code blocks are deliberately not recognised. Inline code spans
|
||||
and comments inside a line are matched within that line only, so that a missing
|
||||
backtick or ``-->`` cannot swallow the rest of the page.
|
||||
|
||||
Masked text has the same length and the same line endings as the input, so
|
||||
offsets stay valid.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_LINE_RE = re.compile(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+")
|
||||
_NOT_EOL_RE = re.compile(r"[^\r\n]")
|
||||
_BACKTICKS_RE = re.compile(r"`+")
|
||||
_OPENER_RE = re.compile(r"`+|<!--")
|
||||
_MAX_DEPTH = 32 # open containers; bounds the work per line
|
||||
_QUOTE = -1 # stack entry of a block quote; list entries hold their content column
|
||||
|
||||
|
||||
def split_lines(text: str) -> tuple[str, ...]:
|
||||
"""Split into lines, each keeping its ending (LF, CRLF or CR)."""
|
||||
return tuple(_LINE_RE.findall(text))
|
||||
|
||||
|
||||
def line_content(line: str) -> str:
|
||||
"""The line without its ending."""
|
||||
return line.rstrip("\r\n")
|
||||
|
||||
|
||||
def is_blank(line: str) -> bool:
|
||||
"""Whether the line holds only spaces and tabs (and its ending)."""
|
||||
return not line.strip(" \t\r\n")
|
||||
|
||||
|
||||
def _blank(text: str) -> str:
|
||||
return _NOT_EOL_RE.sub(" ", text)
|
||||
|
||||
|
||||
def _fence_opener(rest: str) -> tuple[str, int] | None:
|
||||
"""Fence character and length if ``rest`` (indent stripped) opens a fence."""
|
||||
if not rest or rest[0] not in "`~":
|
||||
return None
|
||||
char = rest[0]
|
||||
count = len(rest) - len(rest.lstrip(char))
|
||||
if count < 3:
|
||||
return None
|
||||
if char == "`" and "`" in rest[count:]:
|
||||
return None
|
||||
return char, count
|
||||
|
||||
|
||||
def _fence_closes(rest: str, char: str, count: int) -> bool:
|
||||
rest = rest.rstrip(" \t")
|
||||
return len(rest) >= count and rest == char * len(rest)
|
||||
|
||||
|
||||
def _skip_ws(content: str, pos: int, col: int, virt: int) -> tuple[int, int]:
|
||||
"""Skip spaces and tabs (4-column tab stops); return position and column.
|
||||
|
||||
``col`` is the column of the first unconsumed cell and ``virt`` the number
|
||||
of cells of a partly consumed tab that still precede ``content[pos]``.
|
||||
"""
|
||||
cell = col + virt
|
||||
while pos < len(content):
|
||||
char = content[pos]
|
||||
if char == " ":
|
||||
cell += 1
|
||||
elif char == "\t":
|
||||
cell += 4 - cell % 4
|
||||
else:
|
||||
break
|
||||
pos += 1
|
||||
return pos, cell
|
||||
|
||||
|
||||
def _advance(content: str, pos: int, col: int, virt: int, target: int) -> tuple[int, int, int]:
|
||||
"""Consume whitespace cells up to column ``target`` (at least that much exists)."""
|
||||
take = min(virt, target - col)
|
||||
col += take
|
||||
virt -= take
|
||||
while col < target:
|
||||
width = 1 if content[pos] == " " else 4 - col % 4
|
||||
pos += 1
|
||||
if col + width > target:
|
||||
return pos, target, col + width - target
|
||||
col += width
|
||||
return pos, col, virt
|
||||
|
||||
|
||||
def _after_marker(content: str, pos: int, col: int) -> tuple[int, int, int]:
|
||||
"""Cursor after the one optional space or tab that follows a marker."""
|
||||
if pos < len(content) and content[pos] == " ":
|
||||
return pos + 1, col + 1, 0
|
||||
if pos < len(content) and content[pos] == "\t":
|
||||
return pos + 1, col + 1, 3 - col % 4
|
||||
return pos, col, 0
|
||||
|
||||
|
||||
def _list_marker_end(content: str, pos: int) -> int:
|
||||
"""End index of a list marker at ``pos`` (followed by blank or end), else -1."""
|
||||
char = content[pos]
|
||||
end = pos + 1
|
||||
if char in "0123456789":
|
||||
while end < len(content) and content[end] in "0123456789":
|
||||
end += 1
|
||||
if end - pos > 9 or end >= len(content) or content[end] not in ".)":
|
||||
return -1
|
||||
end += 1
|
||||
elif char not in "-*+":
|
||||
return -1
|
||||
if end < len(content) and content[end] not in " \t":
|
||||
return -1
|
||||
return end
|
||||
|
||||
|
||||
def _thematic_tail(content: str) -> tuple[str, int] | None:
|
||||
"""Character and start of a trailing run of ``-`` or ``*`` and blanks."""
|
||||
stripped = content.rstrip(" \t")
|
||||
if not stripped or stripped[-1] not in "-*":
|
||||
return None
|
||||
char = stripped[-1]
|
||||
i = len(stripped)
|
||||
while i > 0 and stripped[i - 1] in (char, " ", "\t"):
|
||||
i -= 1
|
||||
return char, i
|
||||
|
||||
|
||||
class _Scanner:
|
||||
"""Line-by-line tracking of fences and comment blocks in their containers.
|
||||
|
||||
Containers are block quotes and list items (CommonMark, simplified: no
|
||||
lazy continuation, so an unindented line always ends open lists and
|
||||
quotes). A fence ends when its container ends.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.stack: list[int] = []
|
||||
self.fence: tuple[str, int, int] | None = None # char, length, container depth
|
||||
self.in_comment = False
|
||||
|
||||
def _match(self, content: str) -> tuple[int, int, int, int]:
|
||||
"""Number of open containers this line continues, and the cursor."""
|
||||
pos = col = virt = matched = 0
|
||||
for item in self.stack:
|
||||
start, cell = _skip_ws(content, pos, col, virt)
|
||||
if item == _QUOTE:
|
||||
if cell - col > 3 or start >= len(content) or content[start] != ">":
|
||||
break
|
||||
pos, col, virt = _after_marker(content, start + 1, cell + 1)
|
||||
elif start >= len(content):
|
||||
pass # a blank line continues a list item
|
||||
elif cell >= item:
|
||||
pos, col, virt = _advance(content, pos, col, virt, item)
|
||||
else:
|
||||
break
|
||||
matched += 1
|
||||
return matched, pos, col, virt
|
||||
|
||||
def _open(self, content: str, pos: int, col: int, virt: int) -> tuple[int, int, int]:
|
||||
"""Open new containers at the cursor; return the cursor behind them."""
|
||||
tail: tuple[str, int] | bool | None = False
|
||||
while True:
|
||||
start, cell = _skip_ws(content, pos, col, virt)
|
||||
if start >= len(content) or cell - col > 3 or len(self.stack) >= _MAX_DEPTH:
|
||||
return pos, col, virt
|
||||
if content[start] == ">":
|
||||
self.stack.append(_QUOTE)
|
||||
pos, col, virt = _after_marker(content, start + 1, cell + 1)
|
||||
continue
|
||||
end = _list_marker_end(content, start)
|
||||
if end < 0:
|
||||
return pos, col, virt
|
||||
if content[start] in "-*":
|
||||
if tail is False:
|
||||
tail = _thematic_tail(content)
|
||||
if (
|
||||
tail is not None
|
||||
and tail[0] == content[start]
|
||||
and start >= tail[1]
|
||||
and content.count(tail[0], start) >= 3
|
||||
):
|
||||
return pos, col, virt # thematic break
|
||||
mark = cell + end - start
|
||||
after, after_col = _skip_ws(content, end, mark, 0)
|
||||
if after >= len(content) or after_col - mark >= 5:
|
||||
self.stack.append(mark + 1)
|
||||
if end < len(content) and content[end] == "\t":
|
||||
pos, col, virt = end + 1, mark + 1, 3 - mark % 4
|
||||
else:
|
||||
pos, col, virt = min(end + 1, len(content)), mark + 1, 0
|
||||
else:
|
||||
self.stack.append(after_col)
|
||||
pos, col, virt = after, after_col, 0
|
||||
|
||||
def line(self, content: str) -> int | None:
|
||||
"""None for a normal line; else how many leading characters to mask."""
|
||||
size = len(content)
|
||||
if self.in_comment:
|
||||
end = content.find("-->")
|
||||
if end < 0:
|
||||
return size
|
||||
self.in_comment = False
|
||||
return end + 3
|
||||
matched, pos, col, virt = self._match(content)
|
||||
if self.fence is not None:
|
||||
char, count, depth = self.fence
|
||||
if matched >= depth:
|
||||
start, cell = _skip_ws(content, pos, col, virt)
|
||||
if cell - col <= 3 and _fence_closes(content[start:], char, count):
|
||||
self.fence = None
|
||||
return size
|
||||
self.fence = None # the container ended, so does the fence
|
||||
del self.stack[matched:]
|
||||
pos, col, virt = self._open(content, pos, col, virt)
|
||||
start, cell = _skip_ws(content, pos, col, virt)
|
||||
if start >= size or cell - col > 3:
|
||||
return None
|
||||
rest = content[start:]
|
||||
opener = _fence_opener(rest)
|
||||
if opener is not None:
|
||||
self.fence = (opener[0], opener[1], len(self.stack))
|
||||
return size
|
||||
if not self.stack and rest.startswith("<!--"):
|
||||
end = content.find("-->", start + 2)
|
||||
if end < 0:
|
||||
self.in_comment = True
|
||||
return size
|
||||
return end + 3
|
||||
return None
|
||||
|
||||
|
||||
def block_lines(lines: tuple[str, ...]) -> tuple[bool, ...]:
|
||||
"""Flag the lines inside fenced code blocks and line-initial HTML comments.
|
||||
|
||||
A fence block runs from its opener to its closer, both inclusive, to the
|
||||
end of its container (list item or block quote) or to the end of the text.
|
||||
A comment block starts on a top-level line with at most three spaces of
|
||||
indent before ``<!--`` and ends with the first line containing ``-->``.
|
||||
Lines with a comment end still count as comment lines as a whole.
|
||||
|
||||
Limits: indented code (four or more columns relative to the container) is
|
||||
not recognised and opens no fence; lazy continuation lines are simplified
|
||||
(a line with less indent than a list item or without ``>`` ends it); comment
|
||||
blocks are recognised only outside containers; containers count up to a
|
||||
depth of 32.
|
||||
"""
|
||||
scanner = _Scanner()
|
||||
return tuple(scanner.line(line_content(line)) is not None for line in lines)
|
||||
|
||||
|
||||
def _escaped(content: str, index: int, low: int) -> bool:
|
||||
"""Whether an odd number of backslashes precedes ``index``."""
|
||||
start = index
|
||||
while start > low and content[start - 1] == "\\":
|
||||
start -= 1
|
||||
return (index - start) % 2 == 1
|
||||
|
||||
|
||||
def _mask_line(content: str, begin: int = 0) -> str:
|
||||
"""Mask inline code spans and complete HTML comments from ``begin`` on.
|
||||
|
||||
A backslash escapes a backtick or ``<!--`` outside code spans only.
|
||||
"""
|
||||
runs: list[tuple[int, int, int]] = [] # opener start, run end, run start
|
||||
for m in _BACKTICKS_RE.finditer(content, begin):
|
||||
opener = m.start() + 1 if _escaped(content, m.start(), begin) else m.start()
|
||||
runs.append((opener, m.end(), m.start()))
|
||||
# For each run the end of the next run of the length it opens, -1 without one.
|
||||
closing = [-1] * len(runs)
|
||||
seen: dict[int, int] = {}
|
||||
for i in range(len(runs) - 1, -1, -1):
|
||||
opener, end, start = runs[i]
|
||||
closing[i] = seen.get(end - opener, -1) if end > opener else -1
|
||||
seen[end - start] = end
|
||||
spans = {
|
||||
opener: close for (opener, _, _), close in zip(runs, closing, strict=True) if close >= 0
|
||||
}
|
||||
out: list[str] = [" " * begin]
|
||||
pos = begin
|
||||
last_comment_end = content.rfind("-->")
|
||||
for match in _OPENER_RE.finditer(content, begin):
|
||||
start = match.start()
|
||||
if match[0] == "<!--":
|
||||
if _escaped(content, start, begin) or last_comment_end < start + 2:
|
||||
continue
|
||||
end = content.index("-->", start + 2) + 3
|
||||
else:
|
||||
if _escaped(content, start, begin):
|
||||
start += 1
|
||||
end = spans.get(start, -1)
|
||||
if end < 0:
|
||||
continue
|
||||
if start < pos:
|
||||
continue
|
||||
out.append(content[pos:start] + " " * (end - start))
|
||||
pos = end
|
||||
return "".join(out) + content[pos:]
|
||||
|
||||
|
||||
def mask_code(body: str) -> str:
|
||||
"""Replace code and comments by spaces, keeping length and line endings.
|
||||
|
||||
Masks fenced blocks, line-initial HTML comments (up to and including their
|
||||
``-->``; the rest of the line counts normally), inline code spans (per
|
||||
line, equal-length backtick runs) and HTML comments within a line.
|
||||
"""
|
||||
scanner = _Scanner()
|
||||
out: list[str] = []
|
||||
for line in split_lines(body):
|
||||
content = line_content(line)
|
||||
masked = scanner.line(content)
|
||||
if masked is None:
|
||||
out.append(_mask_line(content))
|
||||
elif masked >= len(content):
|
||||
out.append(_blank(content))
|
||||
else:
|
||||
out.append(_mask_line(content, masked))
|
||||
out.append(line[len(content) :])
|
||||
return "".join(out)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Split a page body into sections, each with a content hash."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
|
||||
from chemenu.domain.markdown import block_lines, is_blank, line_content, split_lines
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SectionKey:
|
||||
"""Identifies a section: heading text and its n-th occurrence on the page."""
|
||||
|
||||
heading: str | None # None: head of the page
|
||||
occurrence: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Section:
|
||||
"""A section: raw text (heading included) and a hash of its content."""
|
||||
|
||||
key: SectionKey
|
||||
text: str # raw, incl. heading; all texts joined == body
|
||||
version: str # SHA-256, hex
|
||||
|
||||
|
||||
def _heading(content: str) -> tuple[int, str] | None:
|
||||
"""Level and text of an ATX heading line, else None."""
|
||||
indent = len(content) - len(content.lstrip(" "))
|
||||
if indent > 3:
|
||||
return None
|
||||
rest = content[indent:]
|
||||
level = len(rest) - len(rest.lstrip("#"))
|
||||
if not 1 <= level <= 6:
|
||||
return None
|
||||
after = rest[level:]
|
||||
if after and after[0] not in " \t":
|
||||
return None
|
||||
text = after.strip(" \t")
|
||||
j = len(text)
|
||||
while j > 0 and text[j - 1] == "#":
|
||||
j -= 1
|
||||
if j == 0:
|
||||
text = ""
|
||||
elif text[j - 1] in " \t":
|
||||
text = text[:j].rstrip(" \t")
|
||||
return level, text
|
||||
|
||||
|
||||
def _version(lines: list[str]) -> str:
|
||||
"""Hash lines: LF endings, blank edge lines and the last ending dropped."""
|
||||
contents = [line_content(line) for line in lines]
|
||||
start, end = 0, len(contents)
|
||||
while start < end and is_blank(contents[start]):
|
||||
start += 1
|
||||
while start < end and is_blank(contents[end - 1]):
|
||||
end -= 1
|
||||
return hashlib.sha256("\n".join(contents[start:end]).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def split_sections(body: str) -> tuple[Section, ...]:
|
||||
"""Split into sections; the first one is always the head.
|
||||
|
||||
Separating are ATX headings of level 1 and 2 outside code blocks and HTML
|
||||
comments, except a level-1 line that is the first non-blank line (page
|
||||
title, part of the head). Deeper and setext headings do not separate.
|
||||
"""
|
||||
lines = split_lines(body)
|
||||
flags = block_lines(lines)
|
||||
first = next((i for i, line in enumerate(lines) if not is_blank(line)), None)
|
||||
# (start index, heading text, index of first hashed line)
|
||||
starts: list[tuple[int, str | None, int]] = [(0, None, 0)]
|
||||
for i, line in enumerate(lines):
|
||||
if flags[i]:
|
||||
continue
|
||||
found = _heading(line_content(line))
|
||||
if found is None or found[0] > 2:
|
||||
continue
|
||||
if i == first and found[0] == 1:
|
||||
starts[0] = (0, None, i + 1)
|
||||
continue
|
||||
starts.append((i, found[1], i + 1))
|
||||
counts: dict[str, int] = {}
|
||||
sections: list[Section] = []
|
||||
for n, (start, heading, hashed) in enumerate(starts):
|
||||
end = starts[n + 1][0] if n + 1 < len(starts) else len(lines)
|
||||
if heading is None:
|
||||
key = SectionKey(None)
|
||||
else:
|
||||
counts[heading] = counts.get(heading, 0) + 1
|
||||
key = SectionKey(heading, counts[heading])
|
||||
sections.append(Section(key, "".join(lines[start:end]), _version(list(lines[hashed:end]))))
|
||||
return tuple(sections)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""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)
|
||||
Reference in new issue
Block a user