From cc893be3d5db0183df0e751ad0604d2f4b287d15 Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Thu, 3 Dec 2026 23:33:21 +0100 Subject: [PATCH] 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 --- src/chemenu/domain/markdown.py | 328 ++++++++++++++++++++++++++++++++ src/chemenu/domain/sections.py | 94 +++++++++ src/chemenu/domain/wikilinks.py | 99 ++++++++++ tests/domain/test_sections.py | 101 ++++++++++ tests/domain/test_wikilinks.py | 100 ++++++++++ 5 files changed, 722 insertions(+) create mode 100644 src/chemenu/domain/markdown.py create mode 100644 src/chemenu/domain/sections.py create mode 100644 src/chemenu/domain/wikilinks.py create mode 100644 tests/domain/test_sections.py create mode 100644 tests/domain/test_wikilinks.py diff --git a/src/chemenu/domain/markdown.py b/src/chemenu/domain/markdown.py new file mode 100644 index 0000000..1cfaf6f --- /dev/null +++ b/src/chemenu/domain/markdown.py @@ -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"`+|") + 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("", 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 ````. + 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 ``") + for match in _OPENER_RE.finditer(content, begin): + start = match.start() + if match[0] == "", 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) diff --git a/src/chemenu/domain/sections.py b/src/chemenu/domain/sections.py new file mode 100644 index 0000000..4d085d7 --- /dev/null +++ b/src/chemenu/domain/sections.py @@ -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) diff --git a/src/chemenu/domain/wikilinks.py b/src/chemenu/domain/wikilinks.py new file mode 100644 index 0000000..812d70a --- /dev/null +++ b/src/chemenu/domain/wikilinks.py @@ -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) diff --git a/tests/domain/test_sections.py b/tests/domain/test_sections.py new file mode 100644 index 0000000..f9b295e --- /dev/null +++ b/tests/domain/test_sections.py @@ -0,0 +1,101 @@ +from chemenu.domain.sections import SectionKey, split_sections + +BODY = "# Title\nintro\n\n## A\nalpha\n\n## B\nbeta\n" + + +def versions(body: str) -> dict[SectionKey, str]: + return {s.key: s.version for s in split_sections(body)} + + +def test_texts_join_to_body() -> None: + for body in ["", "x", BODY, "a\r\n## b\rc\n```\n## no", "\n\n## A", "## A\n## A\n"]: + assert "".join(s.text for s in split_sections(body)) == body + assert split_sections("")[0].key == SectionKey(None) + + +def test_change_affects_one_version() -> None: + before = versions(BODY) + after = versions(BODY.replace("alpha", "ALPHA")) + changed = [k for k in before if before[k] != after[k]] + assert changed == [SectionKey("A")] + + +def test_append_keeps_versions() -> None: + before = versions(BODY) + after = versions(BODY + "\n## C\ngamma\n") + assert all(after[k] == v for k, v in before.items()) + assert SectionKey("C") in after + + +def test_title_line_not_hashed() -> None: + a = split_sections("# One\n\ntext\n")[0] + b = split_sections("# Two\n\ntext\n")[0] + assert a.key == SectionKey(None) + assert a.version == b.version + assert len(split_sections("# One\ntext\n")) == 1 + # a second level-1 heading separates + assert [s.key.heading for s in split_sections("# One\n# Two\n")] == [None, "Two"] + + +def test_subheadings_belong_to_section() -> None: + body = "## A\n### sub\ntext\nSetext\n======\n ## indented\n#tag\n" + assert [s.key.heading for s in split_sections(body)] == [None, "A"] + + +def test_code_and_comments_do_not_split() -> None: + body = ( + "intro\n```\n## no\n```\n## yes\n~~~\n## no\n~~~\n" + "\n## also\n \n## last\n" + "```\n## open\n" + ) + assert [s.key.heading for s in split_sections(body)] == [None, "yes", "also", "last"] + # "" is a complete comment, a tab-indented fence does not close + tricky = "\n## A\n```\n\t```\n## no\n```\n## B\n" + assert [s.key.heading for s in split_sections(tricky)] == [None, "A", "B"] + inner = "## A\n\n## B\n" + assert [s.key.heading for s in split_sections(inner)] == [None, "A", "B"] + + +def test_duplicate_headings() -> None: + keys = [s.key for s in split_sections("## A\n# A\n## B\n## A\n")] + assert keys == [ + SectionKey(None), + SectionKey("A", 1), + SectionKey("A", 2), + SectionKey("B", 1), + SectionKey("A", 3), + ] + + +def test_crlf_same_version() -> None: + assert versions(BODY) == versions(BODY.replace("\n", "\r\n")) + assert versions(BODY) == versions(BODY.replace("\n", "\r")) + assert split_sections("## A ## \nx")[1].key == SectionKey("A") + + +def test_inner_whitespace_changes_version() -> None: + plain, blank_edges, indented, gap = ( + split_sections(f"## A\n{text}")[1].version + for text in ("a\nb\n", " \n\na\nb\n\t\n\n", " a\nb\n", "a\n\nb\n") + ) + assert plain == blank_edges + assert len({plain, indented, gap}) == 3 + + +def test_container_fences_do_not_hide_headings() -> None: + def headings(body: str) -> list[str | None]: + return [s.key.heading for s in split_sections(body)] + + assert headings("- ```bash\n ls\n ```\n## Next\n[[L]]\n") == [None, "Next"] + # unclosed fence in a list ends with the list + assert headings("- ```\n ## no\n## Next\n") == [None, "Next"] + assert headings("1. a\n ```\n ## no\n ```\n## B\n") == [None, "B"] + # unclosed fence in a quote ends with the quote + assert headings("> ```\n> ## no\n## Next\n") == [None, "Next"] + assert headings("> ```\n> ## no\n\n## Next\n") == [None, "Next"] + # at top level an unclosed fence runs to the end + assert headings("```\n## no\n- x\n## no\n") == [None] + # indented code is not recognised and opens no fence + assert headings(" ```\n## A\n") == [None, "A"] + # thematic breaks are not list items + assert headings("---\n```\n## no\n```\n## A\n* * *\n## B\n") == [None, "A", "B"] diff --git a/tests/domain/test_wikilinks.py b/tests/domain/test_wikilinks.py new file mode 100644 index 0000000..c9911a1 --- /dev/null +++ b/tests/domain/test_wikilinks.py @@ -0,0 +1,100 @@ +import time + +from chemenu.domain.wikilinks import WikiLink, find_wikilinks + + +def test_targets() -> None: + body = "[[Foo]] and [[Bar, Baz]] again [[Foo]]\n[[ ]] [[#X]] [[a\n b]]" + assert find_wikilinks(body) == ( + WikiLink("Foo"), + WikiLink("Bar, Baz"), + WikiLink("Foo"), + ) + + +def test_anchor_text_and_embed() -> None: + body = "[[T#A#b]] [[T#^blk|Txt]] ![[E]] [[ T # | ]] [[a [b] c|x [y]]]" + assert find_wikilinks(body) == ( + WikiLink("T", "A#b"), + WikiLink("T", "^blk", "Txt"), + WikiLink("E", embed=True), + WikiLink("T"), + WikiLink("a [b] c", None, "x [y"), + ) + + +def test_escaped_pipe() -> None: + assert find_wikilinks("| [[T\\|Text]] |") == (WikiLink("T", None, "Text"),) + + +def test_code_is_ignored() -> None: + body = ( + "```\n[[a]]\n```\n`[[b]]` ``[[c]]`` `x` [[d]]\n\nx [[g]]\n" + ) + assert [link.target for link in find_wikilinks(body)] == ["d", "g"] + + +def test_unclosed_code_or_comment_hides_nothing() -> None: + body = "x `\nx [[b]] `\n" + assert [link.target for link in find_wikilinks(body)] == ["a", "b"] + + +def targets(body: str) -> list[str]: + return [link.target for link in find_wikilinks(body)] + + +def test_anchor_with_escaped_pipe() -> None: + assert find_wikilinks("[[T#A\\|Text]]") == (WikiLink("T", "A", "Text"),) + + +def test_link_text_keeps_inline_code() -> None: + assert find_wikilinks("[[Use `x` now]]") == (WikiLink("Use `x` now"),) + assert find_wikilinks("[[T|`code`]]") == (WikiLink("T", None, "`code`"),) + assert find_wikilinks("[[T#A b|x]]") == (WikiLink("T", "A b", "x"),) + assert find_wikilinks("[[T#`a#b`|x]]") == (WikiLink("T", "`a#b`", "x"),) + assert find_wikilinks("[[T|`a|b`]]") == (WikiLink("T", None, "`a|b`"),) + + +def test_text_after_comment_counts() -> None: + assert targets(" [[B]]") == ["B"] + assert targets(" [[g]] `[[h]]` [[i]]\n") == ["g", "i"] + assert targets(" [[g]] [[i]]") == ["g", "i"] + + +def test_escapes() -> None: + assert targets("\\`[[A]]\\`") == ["A"] + assert targets("\\[[A]]") == [] + assert targets("\\\\[[A]]") == ["A"] + assert targets("\\\\\\[[A]]") == [] + assert targets("\\") == ["A"] + assert targets("`a\\` [[A]] `b`") == ["A"] + assert find_wikilinks("[[T\\|x]]") == (WikiLink("T", None, "x"),) + + +def test_fences_in_lists_and_quotes() -> None: + assert targets("- ```bash\n [[a]]\n ```\n[[b]]\n") == ["b"] + assert targets("- x\n ```\n [[a]]\n ```\n[[b]]\n") == ["b"] + assert targets("- a\n\t```\n\t[[a]]\n\t```\n[[b]]\n") == ["b"] + assert targets("> ```\n> [[a]]\n> ```\n[[b]]\n") == ["b"] + assert targets("> - ```\n> [[a]]\n") == [] + assert targets("1. ```\n [[a]]\n## H\n[[b]]\n") == ["b"] + assert targets("> ```\n> [[a]]\n\nparagraph [[b]]\n") == ["b"] + assert targets("```\n[[a]]\n- x\n[[b]]\n") == [] + assert targets(" ```\n[[a]]\n") == ["a"] + + +def test_large_input_is_fast() -> None: + units = ["[", "`", "