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..10e3a5940 --- /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, 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 c57b66e4f..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 @@ -44,6 +44,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*$") _TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"} @@ -114,22 +115,26 @@ 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) + used = _used_labels(filled, 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 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]): - found.append((bisect_right(starts, m.start()) + 1, m.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)]) @@ -150,17 +155,20 @@ 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 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 @@ -176,6 +184,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: @@ -198,13 +207,38 @@ def _blank_blocks(lines: list[str]) -> list[str]: if hidden and not pos: out.append(" " * len(line)) continue - above = cache(partial(_paragraph_above, out, start, i)) # joined only when a link check reads it, and once + filled.extend(out[len(filled):]) # a line blanked whole keeps its spaces: it starts a block of its own + above = cache(partial(_paragraph_above, filled, start, i)) # joined only when a link check reads it, and once line, comment, run = _blank_inline(line, close_ahead[i], pos, above) line, span = _open_span(lines, i, line, run) out.append(line) + filled.append(_fill_blanks(source, line)) + filled.extend(out[len(filled):]) + 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: + 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 @@ -323,13 +357,16 @@ def _paragraph_above(out: list[str], start: int, i: int) -> str: return "\n".join(out[start:i]) -def _unpaired_run(line: str, before: str | Callable[[], 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 | Callable[[], 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). + """ if not _BACKTICK_RUN.search(line): return None # the paragraph above is read only for a run before = before() if callable(before) else before 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) @@ -445,18 +482,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:] @@ -491,7 +528,7 @@ def _blank_inline( 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() @@ -192,13 +195,74 @@ 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]() "]), + ("~~~\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 + + +@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)]), + ("[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) + 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) + 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