From ad3600d85efb8580b87d78eb81622ef6adb06452 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 12:14:25 +0000 Subject: [PATCH 1/5] fix(memory): a code span before an angle destination is not whitespace to the link check (#1343) The link check read the line with every blanked span turned into spaces, and the angle-link pattern allows spaces between `](` and `<`, so `[x]( `a` )` was taken for a link and `b` stayed text, although `a` is the destination and `)` and `[x](`a` <`a`>) `b`` now pin both spans blanked. Signed-off-by: Anton Volkov --- ...0_140000_memory-angle-link-blanked-span.md | 3 ++ dokimi/dokimi/memory/store.py | 33 +++++++++++++----- dokimi/tests/test_blank_inline.py | 34 ++++++++++++++++--- 3 files changed, 57 insertions(+), 13 deletions(-) create mode 100644 dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md diff --git a/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md new file mode 100644 index 000000000..2e20c2095 --- /dev/null +++ b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md @@ -0,0 +1,3 @@ +### Fixed + +- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` )`` for a link (#1343). diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 4766ab414..0fc1b8110 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -43,6 +43,7 @@ _BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") _BACKTICK_RUN = re.compile(r"(?\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK _TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$") @@ -150,6 +151,7 @@ def _blank_blocks(lines: list[str]) -> list[str]: needs a ``-->`` in its paragraph and ends at a blank line, a fence or the next block start. """ out: list[str] = [] + filled: list[str] = [] # the same lines with a blanked span as ``_FILL``, the paragraph above that a link is read on fence = "" comment = "" # "", or the kind of the comment the scan is inside: "block" or "inline" span = "" # the backtick run of a code span that runs on over the line break @@ -174,6 +176,7 @@ def _blank_blocks(lines: list[str]) -> list[str]: out.append(" " * len(line)) continue pos = 0 + source = line if span: pos = _span_end(line, span) if pos < 0: @@ -185,12 +188,21 @@ def _blank_blocks(lines: list[str]) -> list[str]: if hidden and not pos: out.append(" " * len(line)) continue - line, comment, run = _blank_inline(line, close_ahead[i], pos, _paragraph_above(lines, out, i)) + filled.extend(out[len(filled):]) # a line blanked whole keeps its spaces: it starts a block of its own + line, comment, run = _blank_inline(line, close_ahead[i], pos, _paragraph_above(lines, filled, i)) line, span = _open_span(lines, i, line, run) out.append(line) + filled.append(_fill_blanks(source, line)) return out +def _fill_blanks(source: str, blanked: str) -> str: + """``blanked`` with each space that replaced a non-space of ``source`` as ``_FILL``.""" + if blanked == source: + return blanked + return "".join(_FILL if b == " " and not s.isspace() else b for s, b in zip(source, blanked, strict=True)) + + def _resume_comment(line: str, comment: str, opener: str) -> tuple[str | None, str, str]: """``(line, comment, opener)`` for a line met inside a comment; ``line`` is None while the comment holds all of it.""" if comment == "inline" and _paragraph_break(line): # a blank line, a fence or a block start ends it @@ -289,10 +301,13 @@ def _paragraph_above(lines: list[str], out: list[str], i: int) -> str: return "\n".join(out[k:i]) -def _unpaired_run(line: str, before: str = "") -> re.Match | None: - """The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination.""" +def _unpaired_run(line: str, before: str = "", linked: str | None = None) -> re.Match | None: + """The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination. + + The links are read on ``linked``, the line with a blank as ``_FILL``, not as a space (``line`` when None). + """ head = before + "\n" if before else "" - text = head + line + text = head + (line if linked is None else linked) opens = [m.start() for m in re.finditer(r"\]\(", text)] links = _LinkCache(final=True) @@ -398,18 +413,18 @@ def blank(self, start: int, end: int) -> None: self._next += 1 # a ``](`` the blank touches is gone self.ranges.append((start, end)) - def text(self, upto: int | None = None) -> str: - """The blanked line, or its first ``upto`` characters, joined from the ranges in one pass.""" + def text(self, upto: int | None = None, fill: str = " ") -> str: + """The blanked line, or its first ``upto`` characters, joined from the ranges in one pass; a blank is ``fill`` per column.""" line = self.line if upto is None else self.line[:upto] chunks, prev = [], 0 for a, b in self.ranges: - chunks += [line[prev:a], " " * (b - a)] + chunks += [line[prev:a], fill * (b - a)] prev = b return "".join(chunks) + line[prev:] def _so_far(self) -> str: for a, b in self.ranges[self._seen:]: # the ranges blanked since the last call extend the prefix - self._prefix += self.line[self._ends:a] + " " * (b - a) + self._prefix += self.line[self._ends:a] + _FILL * (b - a) self._ends = b self._seen = len(self.ranges) return self._prefix + self.line[self._ends:] @@ -440,7 +455,7 @@ def _blank_inline(line: str, closes_ahead: bool, pos: int = 0, before: str = "") start = line.find("", start + 2) if end >= 0: line = line[:start] + " " * (end + 3 - start) + line[end + 3:] + filled = filled[:start] + store._FILL * (end + 3 - start) + filled[end + 3:] pos = end + 3 continue block = start <= 3 and not line[:start].strip() @@ -191,13 +194,36 @@ def test_a_link_opened_on_the_line_above_holds_the_spans_of_its_destination(befo _same("<`a`>) `b` `c`", False, 0, before) -@pytest.mark.parametrize("line, out", [("[x](`a`<`a`>)", "[x]( <`a`>)"), ("[x](`a` <`a`>) `b`", "[x]( <`a`>) "), +@pytest.mark.parametrize("line, out", [("[x](`a`<`a`>)", "[x]( < >)"), ("[x](`a` <`a`>) `b`", "[x]( < >) "), ("[x](<`<` `a`>)", "[x](< `a`>)")]) def test_a_link_that_matches_only_once_a_code_span_is_blanked_still_holds_its_spans(line: str, out: str) -> None: assert _blank_inline(line, False)[0] == out # a ``](`` that does not match yet stays live while a ``<`` may follow it _same(line, False) +@pytest.mark.parametrize("line, out", [ + ("[x]( `a` )", "[x]( )"), # `a` is the destination and ``)", "[x]( )"), + ("[x]( `a` )", "[x]( )"), + ("[x]()", "[x]()"), + ("[x]( \"t `c`\")", "[x]( \"t `c`\")"), + ("[`c`]()", "[ ]()"), +]) +def test_a_code_span_before_an_angle_destination_is_not_whitespace(line: str, out: str) -> None: + assert _blank_inline(line, False)[0] == out + _same(line, False) + + +@pytest.mark.parametrize("text, lines", [ + ("[x]( `a`\n)", ["[x]( ", ")"]), # a span on the line above is not whitespace either + ("[x]( `a` )\nfoo` bar", ["[x]( )", ["[x](", ")"]), + ("[x]() `c`", ["[x]() "]), +]) +def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(text: str, lines: list[str]) -> None: + assert prose_lines(text) == lines + + def test_scanning_past_many_comment_openers_with_no_close_grows_linearly() -> None: ratio, result = growth(lambda k: partial(_blank_inline, _unclosed(k), False), 2000) assert ratio < GROWTH_LIMIT From 927dd1cc5003a8b97da1e3b49d340da5fbe00465 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 17:28:24 +0000 Subject: [PATCH 2/5] fix(memory): index_targets reads a link on the text with a blanked span as text (#1343) Settles the review point that `MemoryStore.index_targets()` still matched the link on the space-filled lines: for ``[x]( `a` )`` it returned `[(1, 'y ', True)]` although `prose_lines` blanked the spans correctly. `_blank_blocks` now returns the filled lines beside the blanked ones, and `index_targets` matches `_MD_LINK` on the filled text, where a blanked span is not a space that ends a bare destination. The target is read from the raw line, so a span inside a destination is kept as written. The regression test calls `index_targets()` directly. Signed-off-by: Anton Volkov --- ...0_140000_memory-angle-link-blanked-span.md | 2 +- dokimi/dokimi/memory/store.py | 20 +++++++++------- dokimi/tests/test_blank_inline.py | 24 ++++++++++++++++++- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md index 2e20c2095..0aa22e7df 100644 --- a/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md +++ b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md @@ -1,3 +1,3 @@ ### Fixed -- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` )`` for a link (#1343). +- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` )`` for a link, in `prose_lines` and in the index targets `MemoryStore.index_targets()` returns (#1343). diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 9e695249e..b78e40dd3 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -115,18 +115,19 @@ def index_targets(self) -> list[tuple[int, str, bool]]: """ if self.index is None: return [] - lines = prose_lines(self.index.text) # blanked to the same columns, so a label is read from the raw text source = self.index.text.split("\n") + lines, filled = _blank_blocks(source) # blanked to the same columns, so a label is read from the raw text defs = _definitions(lines) used = _used_labels(lines, source, defs) found: list[tuple[int, str, bool]] = [] - text = "\n".join(lines) + text = "\n".join(filled) # a blanked span is text to a link, not a space that ends its destination + raw = "\n".join(source) starts = [m.start() for m in re.finditer("\n", text)] # a link may run over a line break: find its line by offset begin = [0, *(s + 1 for s in starts)] titles = _title_spans(lines, begin, defs) # a closed title holds no link for m in _MD_LINK.finditer(text): if _has_opener(text, m.start()) and not any(lo <= m.start() < hi for lo, hi in titles): - found.append((bisect_right(starts, m.start()) + 1, m.group(1), True)) + found.append((bisect_right(starts, m.start()) + 1, raw[m.start(1):m.end(1)], True)) defined: set[str] = set() for k, m in sorted(defs.items()): # the first definition of a label is the one Markdown uses label = _label(source[k][m.start(1):m.end(1)]) @@ -147,11 +148,13 @@ def index_links(self) -> list[tuple[int, str]]: def prose_lines(text: str) -> list[str]: """The lines of ``text`` with fenced blocks, HTML comments and code spans blanked: no link lives there.""" - return _blank_blocks(text.split("\n")) + return _blank_blocks(text.split("\n"))[0] -def _blank_blocks(lines: list[str]) -> list[str]: - """The lines with fenced and indented code, HTML comments and code spans blanked to spaces, so every column keeps its place. +def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: + """``(blanked, filled)``: the lines with fenced and indented code, HTML comments and code spans blanked to spaces, so every column keeps its place. + + ``filled`` is the same with each blank inside a line as ``_FILL``: the text a link is matched on, where a blanked span is text. One scan, so whichever opens first holds the lines after it. A comment that opens a line (up to three spaces in) runs to its ``-->``, blank lines included, or to the end of the text. One opened mid-line @@ -174,6 +177,7 @@ def _blank_blocks(lines: list[str]) -> list[str]: fence = "" out.append(" " * len(line)) continue + source = line if comment: rest, comment, opener = _resume_comment(line, comment, opener) if rest is None: @@ -185,7 +189,6 @@ def _blank_blocks(lines: list[str]) -> list[str]: out.append(" " * len(line)) continue pos = 0 - source = line if span: pos = _span_end(line, span) if pos < 0: @@ -203,7 +206,8 @@ def _blank_blocks(lines: list[str]) -> list[str]: line, span = _open_span(lines, i, line, run) out.append(line) filled.append(_fill_blanks(source, line)) - return out + filled.extend(out[len(filled):]) + return out, filled def _fill_blanks(source: str, blanked: str) -> str: diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 13d5245c7..ba12b22ff 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -9,12 +9,13 @@ import random import re from functools import partial +from pathlib import Path import pytest from dokimi.code_spans import LINE_BREAK, CodeSpanScanner from dokimi.memory import store -from dokimi.memory.store import _angle_link_end, _blank_inline, _code_span, _unpaired_run, prose_lines +from dokimi.memory.store import MemoryEntry, MemoryStore, _angle_link_end, _blank_inline, _code_span, _unpaired_run, prose_lines from tests.growth_timing import GROWTH_LIMIT, growth @@ -224,6 +225,27 @@ def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(te assert prose_lines(text) == lines +@pytest.mark.parametrize("text, targets", [ + ("[x]( `a` )", []), # the first example of #1343: a span is text before ``)", []), + ("[x]( `a` )", []), + ("[x](a`b`c)", [(1, "a`b`c", True)]), # a span inside a bare destination is part of it, read from the raw text + ("[x]( )", [(1, "y `b`", True)]), + ("[x]() `c`", [(1, "a `b`", True)]), +]) +def test_index_targets_reject_a_link_whose_destination_follows_a_code_span(text: str, targets: list[tuple[int, str, bool]]) -> None: + index = MemoryEntry("MEMORY.md", text, text, None) + assert MemoryStore(Path("/x"), index, []).index_targets() == targets + + +def test_the_filled_lines_keep_every_line_of_the_text_and_its_columns() -> None: + lines = ["[x]( `a` )", "```", "code", "```"] + blanked, filled = store._blank_blocks(lines) + assert len(filled) == len(lines) + assert filled == ["[x]( \x00\x00\x00 )", " ", " ", " "] + assert [len(f) for f in filled] == [len(b) for b in blanked] + + def test_scanning_past_many_comment_openers_with_no_close_grows_linearly() -> None: ratio, result = growth(lambda k: partial(_blank_inline, _unclosed(k), False), 2000) assert ratio < GROWTH_LIMIT From 3015ee57bfb63c4eb934a4259f30e455a7836a9a Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 20:04:27 +0000 Subject: [PATCH 3/5] fix(memory): index_targets reads a destination on the raw text, not the filled one Settles the review thread on store.py:123: the filled text reads a code span as text, so `[x](foo`(bar`)` matched with `foo` plus six fill characters and index_targets reported the raw slice `foo`(bar`` as a link target, though the destination's parenthesis is never closed. A match on the filled text is now kept only when the link grammar also matches the raw text at the same offset, and the target is the raw match's destination. `[x](foo`(bar`)` and `[x](`(`a)` report no target, and `[x](a`(b`)c)` reports the destination `a`(b`)c` whose parentheses balance in the raw text. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/store.py | 4 +++- dokimi/tests/test_blank_inline.py | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index fb1293d9e..7546026a2 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -131,7 +131,9 @@ def index_targets(self) -> list[tuple[int, str, bool]]: for m in matches: i = bisect_right(title_starts, m.start()) - 1 if m.start() in opened and not (i >= 0 and m.start() < title_ends[i]): - found.append((bisect_right(starts, m.start()) + 1, raw[m.start(1):m.end(1)], True)) + link = _MD_LINK.match(raw, m.start()) # a span is text to the match above, but its backticks are plain characters of a destination + if link is not None: + found.append((bisect_right(starts, m.start()) + 1, link.group(1), True)) defined: set[str] = set() for k, m in sorted(defs.items()): # the first definition of a label is the one Markdown uses label = _label(source[k][m.start(1):m.end(1)]) diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 195ffa103..02131d4e1 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -232,6 +232,9 @@ def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(te ("[x](a`b`c)", [(1, "a`b`c", True)]), # a span inside a bare destination is part of it, read from the raw text ("[x]( )", [(1, "y `b`", True)]), ("[x]() `c`", [(1, "a `b`", True)]), + ("[x](foo`(bar`)", []), # the parenthesis of the span is a parenthesis of the destination, which is never closed + ("[x](`(`a)", []), + ("[x](a`(b`)c)", [(1, "a`(b`)c", True)]), # balanced in the raw text: the destination runs past the span ]) def test_index_targets_reject_a_link_whose_destination_follows_a_code_span(text: str, targets: list[tuple[int, str, bool]]) -> None: index = MemoryEntry("MEMORY.md", text, text, None) From 6235e6d366f76b62227a06213e86d982efeb378c Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Mon, 30 Nov 2026 23:16:22 -0800 Subject: [PATCH 4/5] test(memory): an angle link after a fence or comment is still checked Dropping the catch-up of the filled lines in _blank_blocks lost the link on the line after a fenced block or an HTML comment, and no test failed. One prose_lines case and two index_targets cases now fail then. Signed-off-by: Alexander Rybkin --- dokimi/tests/test_blank_inline.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 02131d4e1..f916c7b1f 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -220,6 +220,7 @@ def test_a_code_span_before_an_angle_destination_is_not_whitespace(line: str, ou ("[x]( `a` )\nfoo` bar", ["[x]( )", ["[x](", ")"]), ("[x]() `c`", ["[x]() "]), + ("~~~\nx\n~~~\n[x](\n)", [" ", " ", " ", "[x](", ")"]), # a fence above: the paragraph above starts after it ]) def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(text: str, lines: list[str]) -> None: assert prose_lines(text) == lines @@ -235,6 +236,8 @@ def test_a_code_span_on_the_line_above_an_angle_destination_is_not_whitespace(te ("[x](foo`(bar`)", []), # the parenthesis of the span is a parenthesis of the destination, which is never closed ("[x](`(`a)", []), ("[x](a`(b`)c)", [(1, "a`(b`)c", True)]), # balanced in the raw text: the destination runs past the span + ("~~~\nx\n~~~\n[x](\n)", [(4, "y `b`", True)]), # a link after a block blanked whole is still checked + ("\n[x](\n)", [(4, "y `b`", True)]), ]) def test_index_targets_reject_a_link_whose_destination_follows_a_code_span(text: str, targets: list[tuple[int, str, bool]]) -> None: index = MemoryEntry("MEMORY.md", text, text, None) From 7c7b682db52c2957efc43d7358ba764f4c4e1051 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 01:27:53 -0800 Subject: [PATCH 5/5] fix(memory): a label use and a link inside a destination are read on the raw text too _used_labels read inline links on the space-blanked lines, so a span before an angle destination hid a used definition, and a span in a bare destination marked an unused one checked. A filled match inside an accepted raw destination is no second link. Signed-off-by: Alexander Rybkin --- ...0_140000_memory-angle-link-blanked-span.md | 2 +- dokimi/dokimi/memory/store.py | 53 +++++++++++++------ dokimi/tests/test_blank_inline.py | 11 ++++ 3 files changed, 50 insertions(+), 16 deletions(-) diff --git a/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md index 0aa22e7df..10e3a5940 100644 --- a/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md +++ b/dokimi/changelog.d/20261130_140000_memory-angle-link-blanked-span.md @@ -1,3 +1,3 @@ ### Fixed -- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` )`` for a link, in `prose_lines` and in the index targets `MemoryStore.index_targets()` returns (#1343). +- **`dokimi memory lint` no longer reads a code span before an angle destination as whitespace**, so the link check no longer takes ``[x]( `a` )`` for a link, in `prose_lines` and in the index targets `MemoryStore.index_targets()` returns (#1343). Whether a `[label]` uses a definition is read the same way, and a `](` inside a destination is not a second link. diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 7546026a2..80096e392 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -12,7 +12,7 @@ import re from bisect import bisect_right -from collections.abc import Callable +from collections.abc import Callable, Iterable from dataclasses import dataclass, field from functools import cache, partial from html import unescape @@ -118,7 +118,7 @@ def index_targets(self) -> list[tuple[int, str, bool]]: source = self.index.text.split("\n") lines, filled = _blank_blocks(source) # blanked to the same columns, so a label is read from the raw text defs = _definitions(lines) - used = _used_labels(lines, source, defs) + used = _used_labels(filled, source, defs) found: list[tuple[int, str, bool]] = [] text = "\n".join(filled) # a blanked span is text to a link, not a space that ends its destination raw = "\n".join(source) @@ -128,12 +128,13 @@ def index_targets(self) -> list[tuple[int, str, bool]]: matches = list(_MD_LINK.finditer(text)) opened = _closing_openers(text, {m.start() for m in matches}) title_starts, title_ends = _merged(titles) - for m in matches: - i = bisect_right(title_starts, m.start()) - 1 - if m.start() in opened and not (i >= 0 and m.start() < title_ends[i]): - link = _MD_LINK.match(raw, m.start()) # a span is text to the match above, but its backticks are plain characters of a destination - if link is not None: - found.append((bisect_right(starts, m.start()) + 1, link.group(1), True)) + + def live(at: int) -> bool: + i = bisect_right(title_starts, at) - 1 + return at in opened and not (i >= 0 and at < title_ends[i]) + + for link in _links(matches, raw, live): + found.append((bisect_right(starts, link.start()) + 1, link.group(1), True)) defined: set[str] = set() for k, m in sorted(defs.items()): # the first definition of a label is the one Markdown uses label = _label(source[k][m.start(1):m.end(1)]) @@ -216,6 +217,21 @@ def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: return out, filled +def _links(matches: Iterable[re.Match], raw: str, live: Callable[[int], bool] = lambda _: True) -> list[re.Match]: + """The links of ``matches`` (read on the filled text) that ``raw`` holds at the same offset, each matched on ``raw``. + + A span is text to the filled match, but its backticks are plain characters of a destination. A raw link may + run past its filled match: a later match inside it is part of that destination, not a link. + """ + out: list[re.Match] = [] + end = 0 + for m in matches: + if m.start() >= end and live(m.start()) and (link := _MD_LINK.match(raw, m.start())) is not None: + out.append(link) + end = link.end() + return out + + def _fill_blanks(source: str, blanked: str) -> str: """``blanked`` with each space that replaced a non-space of ``source`` as ``_FILL``.""" if blanked == source: @@ -533,11 +549,14 @@ def _blank_inline( def _used_labels(lines: list[str], source: list[str], defs: dict[int, re.Match]) -> set[str]: - """The labels some link uses: ``[label]``, ``[label][]``, ``[text][label]`` (only ``label``). A label is read from ``source``.""" + """The labels some link uses: ``[label]``, ``[label][]``, ``[text][label]`` (only ``label``). A label is read from ``source``. + + ``lines`` are the filled lines: an inline link is read on them and on ``source``, as ``index_targets`` reads it. + """ used: set[str] = set() # the label that opens a definition is not a use of itself for k, line in enumerate(lines): d = defs.get(k) - span_starts, span_ends = _merged([m.span() for m in _MD_LINK.finditer(line)]) # a label inside a destination or title is no use + span_starts, span_ends = _merged([m.span() for m in _links(_MD_LINK.finditer(line), source[k])]) # a label inside a destination or title is no use begin = d.end() if d else 0 if d and d.end() > len(line): # the destination is on the next line: the label line holds no use begin = len(line) @@ -549,15 +568,16 @@ def _used_labels(lines: list[str], source: list[str], defs: dict[int, re.Match]) inside = at >= 0 and m.start() < span_ends[at] text_of_explicit = j + 1 < len(labels) and labels[j + 1].start() == m.end() # [text][label]: text is no use two = line + "\n" + lines[k + 1] if k + 1 < len(lines) else line # a destination may start on the next line + raw = source[k] + "\n" + source[k + 1] if k + 1 < len(lines) else source[k] escaped = _escaped(line, m.start()) # \[label] opens no reference - if not inside and not escaped and not text_of_explicit and not _inline_link_at(two, m.end()): # [t](...) with no valid destination is [t] + if not inside and not escaped and not text_of_explicit and not _inline_link_at(two, raw, m.end()): # [t](...) with no valid destination is [t] used.add(_label(source[k][m.start(1):m.end(1)])) for k, (a, b) in enumerate(zip(lines, lines[1:], strict=False)): # a label may wrap onto the next line pair = f"{a}\n{b}" source_pair = f"{source[k]}\n{source[k + 1]}" for m in _LABEL_ACROSS_LINES.finditer(pair): explicit = pair.startswith("[", m.end()) and not pair.startswith("[]", m.end()) - if "\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, m.end()): + if "\n" in m.group(1) and not explicit and not _escaped(pair, m.start()) and not _inline_link_at(pair, source_pair, m.end()): used.add(_label(source_pair[m.start(1):m.end(1)])) return used @@ -658,9 +678,12 @@ def _label(text: str) -> str: return re.sub(r"\s+", " ", text).strip().casefold() -def _inline_link_at(line: str, end: int) -> bool: - """Whether the ``[label]`` ending at ``end`` is followed by a valid inline destination ``(...)``.""" - return line.startswith("(", end) and (_MD_LINK.match(line, end - 1) or _EMPTY_LINK.match(line, end - 1)) is not None +def _inline_link_at(line: str, raw: str, end: int) -> bool: + """Whether the ``[label]`` ending at ``end`` of the filled ``line`` is followed by a valid inline destination ``(...)``.""" + if not line.startswith("(", end): + return False + link = _MD_LINK.match(line, end - 1) + return bool(link and _links([link], raw)) or _EMPTY_LINK.match(line, end - 1) is not None def slug(name: str) -> str: diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index f916c7b1f..730f61ab5 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -244,6 +244,17 @@ def test_index_targets_reject_a_link_whose_destination_follows_a_code_span(text: assert MemoryStore(Path("/x"), index, []).index_targets() == targets +@pytest.mark.parametrize("text, targets", [ + ("[x]( `a` )\n\n[x]: missing.md", [(3, "missing.md", True)]), # no inline link, so [x] uses the definition + ("[x](a`b`c)\n\n[x]: missing.md", [(1, "a`b`c", True), (3, "missing.md", False)]), # an inline link: no use + ("[x](foo`(bar`)\n\n[x]: missing.md", [(3, "missing.md", True)]), # never closed in the raw text: a use + ("[x](a`(`b)[y](z))", [(1, "a`(`b)[y](z)", True)]), # [y](z) is inside the destination, no link of its own +]) +def test_a_label_and_a_link_are_read_as_index_targets_reads_a_destination(text: str, targets: list[tuple[int, str, bool]]) -> None: + index = MemoryEntry("MEMORY.md", text, text, None) + assert MemoryStore(Path("/x"), index, []).index_targets() == targets + + def test_the_filled_lines_keep_every_line_of_the_text_and_its_columns() -> None: lines = ["[x]( `a` )", "```", "code", "```"] blanked, filled = store._blank_blocks(lines)