diff --git a/CHANGES b/CHANGES index ca1c339..f4ce34b 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,15 @@ _Notes on the upcoming release will go here._ +### Fixes + +#### Restrict 2D scrubber slack absorption to box-bordered cells (#144) + +{func}`~libvt.testing.serialize_vt_snapshot` and {func}`~libvt.testing.vt_screen` +leave leading indentation and interior prose spacing untouched on primary +autowrap streams and unbordered rows, absorbing scrubber width deltas only +within box-bordered cells on fixed-row 2D screens (`alt=True` or `!DECAWM`). + ## libvt 0.0.1a5 (2026-11-30) `libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and diff --git a/src/libvt/testing.py b/src/libvt/testing.py index e1bbf07..ba7691b 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -516,9 +516,9 @@ def vt_screen( >>> from libvt import Terminal >>> from libvt.testing import serialize_vt_snapshot, vt_screen >>> term = Terminal(rows=2, cols=16) - >>> term.feed(b"pid=4821 OK") + >>> term.feed("\x1b[?1049h\x1b[H│ pid=4821 OK │".encode()) >>> view = vt_screen(term, scrubbers=[(r"pid=\d+", "pid=")]) - >>> "│pid= OK │" in serialize_vt_snapshot(view) + >>> "││ pid= OK ││" in serialize_vt_snapshot(view) True """ return VtScreenView( @@ -660,6 +660,9 @@ def _scrub_cells( cells: list[_CellMeta], compiled: tuple[tuple[re.Pattern[str], str], ...], cursor_idx: int | None, + *, + mode_2027: bool = True, + profile: Profile = DEFAULT_PROFILE, ) -> tuple[list[_CellMeta], int | None, list[tuple[int, int, int]]]: cur = cursor_idx edits: list[tuple[int, int, int]] = [] @@ -672,8 +675,15 @@ def _scrub_cells( new_edits: list[tuple[int, int, int]] = [] new_cur = cur pos = 0 - for m in matches: + p_idx, n_prev = 0, len(edits) + for m_i, m in enumerate(matches): s, e = m.span() + next_s = matches[m_i + 1].start() if m_i + 1 < len(matches) else len(cells) + shift = len(out) - pos + while p_idx < n_prev and edits[p_idx][1] <= s: + ps, pe, pw = edits[p_idx] + new_edits.append((ps + shift, pe + shift, pw)) + p_idx += 1 out.extend(cells[pos:s]) rep_start = len(out) sl = cells[s:e] @@ -704,36 +714,50 @@ def _scrub_cells( else: out.append(_CellMeta(r_ch, f_st, f_lk)) rep_end = len(out) - new_edits.append((rep_start, rep_end, new_n - old_n)) + w_delta = _cells_width( + out[rep_start:rep_end], + mode_2027=mode_2027, + profile=profile, + ) - _cells_width(sl, mode_2027=mode_2027, profile=profile) + eff_start, eff_end = rep_start, rep_end + while p_idx < n_prev and edits[p_idx][0] < e: + ps, pe, pw = edits[p_idx] + w_delta += pw + eff_start = min(eff_start, rep_start - max(0, s - ps)) + eff_end = max(eff_end, rep_end + min(max(0, pe - e), next_s - e)) + p_idx += 1 + new_edits.append((eff_start, eff_end, w_delta)) if cur is not None: if pos <= cur <= s: new_cur = (rep_start - s) + cur elif s < cur <= e: new_cur = rep_end pos = e + tail_shift = len(out) - pos if cur is not None and cur > pos: new_cur = len(out) + (cur - pos) out.extend(cells[pos:]) + while p_idx < n_prev: + ps, pe, pw = edits[p_idx] + new_edits.append((ps + tail_shift, pe + tail_shift, pw)) + p_idx += 1 cells, cur, edits = out, new_cur, new_edits return cells, cur, edits +_BOX_DIVIDERS: t.Final[frozenset[str]] = frozenset("│┃║╎╏┆┇┊┋├┤╞╡╟╢╠╣┠┨┝┥") + + def _absorb_2d_slack( cells: list[_CellMeta], edits: list[tuple[int, int, int]], *, - target_cols: int, cursor_idx: int | None, - mode_2027: bool, - profile: Profile, ) -> tuple[list[_CellMeta], int | None]: - # Absorb token width deltas into >=2-space unstyled alignment gaps bounded by box - # dividers so 2D CSI H panels never wrap their right border onto the next row. + # Absorb net width deltas inside bordered 2D cells so right borders align. cur = cursor_idx - delta = _cells_width(cells, mode_2027=mode_2027, profile=profile) - target_cols - if delta == 0 or not edits: + if not edits: return cells, cur - dividers = frozenset("│┃║╎╏┆┇┊┋") def _is_space(i: int) -> bool: c = cells[i] @@ -741,7 +765,7 @@ def _is_space(i: int) -> bool: def _scan_gap(start: int, step: int) -> tuple[int, int] | None: i, n = start, len(cells) - while 0 <= i < n and cells[i].ch not in dividers: + while 0 <= i < n and cells[i].ch not in _BOX_DIVIDERS: if _is_space(i): j = i while 0 <= j < n and _is_space(j): @@ -754,25 +778,73 @@ def _scan_gap(start: int, step: int) -> tuple[int, int] | None: i += step return None - for rep_start, rep_end, _ in reversed(edits): - if delta == 0: - break - gap = _scan_gap(rep_end, 1) or _scan_gap(rep_start - 1, -1) - if gap is None: + def _shift_cells(at: int, delta_n: int) -> None: + nonlocal cur + if delta_n < 0: + lo = at + delta_n + del cells[lo:at] + if cur is not None and cur > lo: + cur = max(lo, cur + delta_n) + else: + cells[at:at] = [_CellMeta(" ", DEFAULT_STYLE, None)] * delta_n + if cur is not None and cur >= at: + cur += delta_n + + by_div: dict[int, list[tuple[int, int, int]]] = {} + for rep_start, rep_end, rem in edits: + div_idx = next( + (k for k in range(rep_end, len(cells)) if cells[k].ch in _BOX_DIVIDERS), + None, + ) + if div_idx is not None: + by_div.setdefault(div_idx, []).append((rep_start, rep_end, rem)) + + for div_idx in sorted(by_div, reverse=True): + cell_edits = by_div[div_idx] + rem = sum(d for _, _, d in cell_edits) + if rem == 0: continue - g_lo, g_hi = gap - if delta > 0: - eat = min(delta, (g_hi - g_lo) - 1) - del cells[g_hi - eat : g_hi] - if cur is not None and cur > g_hi - eat: - cur = max(g_hi - eat, cur - eat) - delta -= eat + first_start, first_end, _ = cell_edits[0] + last_end = cell_edits[-1][1] + has_left_div = any( + cells[k].ch in _BOX_DIVIDERS for k in range(first_start - 1, -1, -1) + ) + if rem > 0: + for anchor in ( + (last_end,) if first_end == last_end else (last_end, first_end) + ): + while rem > 0 and (gap := _scan_gap(anchor, 1)) is not None: + eat = min(rem, (gap[1] - gap[0]) - 1) + _shift_cells(gap[1], -eat) + if gap[1] <= last_end: + last_end -= eat + div_idx -= eat + rem -= eat + while ( + rem > 0 + and has_left_div + and (gap := _scan_gap(first_start - 1, -1)) is not None + ): + eat = min(rem, (gap[1] - gap[0]) - 1) + _shift_cells(gap[1], -eat) + first_start -= eat + last_end -= eat + div_idx -= eat + rem -= eat + if rem > 0 and div_idx > last_end and _is_space(div_idx - 1): + _shift_cells(div_idx, -1) else: - add = -delta - cells[g_hi:g_hi] = [_CellMeta(" ", DEFAULT_STYLE, None)] * add - if cur is not None and cur >= g_hi: - cur += add - delta = 0 + add = -rem + if (gap := _scan_gap(last_end, 1)) is not None: + _shift_cells(gap[1], add) + elif last_end < div_idx and _is_space(last_end): + _shift_cells(last_end + 1, add) + elif ( + first_end < last_end and (gap := _scan_gap(first_end, 1)) is not None + ) or (has_left_div and (gap := _scan_gap(first_start - 1, -1)) is not None): + _shift_cells(gap[1], add) + else: + _shift_cells(div_idx, add) return cells, cur @@ -871,15 +943,14 @@ def _render_fixed_rows( else None ) if compiled: - cells, c_in, edits = _scrub_cells(cells, compiled, c_in) - cells, c_in = _absorb_2d_slack( + cells, c_in, edits = _scrub_cells( cells, - edits, - target_cols=cols_n, - cursor_idx=c_in, + compiled, + c_in, mode_2027=mode_2027, profile=profile, ) + cells, c_in = _absorb_2d_slack(cells, edits, cursor_idx=c_in) packed, mapped = _wrap_or_pad_cells( cells, cols=cols_n, @@ -1178,21 +1249,13 @@ def _serialize_extracted( cur_idx = len(logical) + rel_idx logical.extend(seg) if compiled: - pre_w = _cells_width( + logical, cur_idx, _ = _scrub_cells( logical, + compiled, + cur_idx, mode_2027=mode_2027, profile=profile, ) - logical, cur_idx, edits = _scrub_cells(logical, compiled, cur_idx) - if c_end == c_start: - logical, cur_idx = _absorb_2d_slack( - logical, - edits, - target_cols=pre_w, - cursor_idx=cur_idx, - mode_2027=mode_2027, - profile=profile, - ) packed, mapped = _wrap_or_pad_cells( logical, cols=cols_n, diff --git a/tests/test_testing.py b/tests/test_testing.py index fa5c19a..469c9b5 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -245,6 +245,113 @@ def test_2d_alt_screen_tui_slack_absorption_preserves_borders() -> None: assert "│[API] PID= │" in s_unb_a +def test_2d_only_slack_preserves_primary_streams_and_bordered_2d_cells() -> None: + """Primary streams keep surrounding spaces; 2D slack applies only inside boxes.""" + t_indent = Terminal(rows=1, cols=80) + t_indent.feed(b" Full debug log: /tmp/pytest-of-runner/pytest-12/sync.log") + s_indent = serialize_vt_snapshot( + vt_screen(t_indent, scrubbers=[(r"/tmp/\S+", "")]) + ) + assert f"│ Full debug log: {' ' * 55}│" in s_indent + assert "cursor=(0,25,vis=True)" in s_indent + + retry_snaps: list[str] = [] + for dur in (b"0.1s", b"10.2s", b"100.2s"): + t_retry = Terminal(rows=1, cols=60) + t_retry.feed(b" - hung-repo (" + dur + b" elapsed) [retry]") + retry_snaps.append( + serialize_vt_snapshot( + vt_screen(t_retry, scrubbers=[(r"\d+\.\ds", "")]) + ) + ) + assert retry_snaps[0] == retry_snaps[1] == retry_snaps[2] + assert "│ - hung-repo ( elapsed) [retry]" in retry_snaps[0] + + path_scrub = [(r"/(?:private/var/folders|tmp)/\S+", "")] + t_short_log = Terminal(rows=2, cols=36) + t_short_log.feed(b"Saved /tmp/a -- see details") + t_wrapped_log = Terminal(rows=2, cols=36) + t_wrapped_log.feed( + b"Saved /private/var/folders/zz/abcdef1234567890/a -- see details" + ) + s_short_log = serialize_vt_snapshot(vt_screen(t_short_log, scrubbers=path_scrub)) + s_wrapped_log = serialize_vt_snapshot( + vt_screen(t_wrapped_log, scrubbers=path_scrub) + ) + assert s_short_log == s_wrapped_log + assert "│Saved -- see details │" in s_short_log + + # Symmetric unbordered primary rows preserve double-space gaps regardless of delta. + pid_scrub = [(r"pid=\d+", "pid=")] + t_sym_short = Terminal(rows=1, cols=20) + t_sym_short.feed(b"pid=42 OK") + t_sym_long = Terminal(rows=1, cols=20) + t_sym_long.feed(b"pid=123456 OK") + s_sym_short = serialize_vt_snapshot(vt_screen(t_sym_short, scrubbers=pid_scrub)) + s_sym_long = serialize_vt_snapshot(vt_screen(t_sym_long, scrubbers=pid_scrub)) + assert s_sym_short == s_sym_long + assert "│pid= OK │" in s_sym_short + + # Unbordered alt-screen full-width row preserves interior spacing. + t_alt_full = Terminal(rows=1, cols=18) + t_alt_full.feed(b"\x1b[?1049h\x1b[H[API] PID=2215012") + s_alt_full = serialize_vt_snapshot( + vt_screen(t_alt_full, scrubbers=[(r"PID=\d+", "PID=")]) + ) + assert "│[API] PID= │" in s_alt_full + assert "cursor=(0,16,vis=True)" in s_alt_full + + # Tight 1-space and 0-space bordered 2D cells and multi-scrubber 2D rows. + worker_snaps: list[str] = [] + for pid_b in (b"9 ", b"48291 ", b"482910"): + t_w = Terminal(rows=3, cols=25) + t_w.feed( + b"\x1b[?1049h\x1b[H" + + "┌───────────────────────┐\r\n".encode() + + b"\xe2\x94\x82 worker pid=" + + pid_b + + b" OK \xe2\x94\x82\r\n" + + "└───────────────────────┘".encode() + ) + worker_snaps.append(serialize_vt_snapshot(vt_screen(t_w, scrubbers=pid_scrub))) + assert worker_snaps[0] == worker_snaps[1] == worker_snaps[2] + + t_tight_1_a = Terminal(rows=1, cols=34) + t_tight_1_a.feed("\x1b[?1049h\x1b[H│ path=/tmp/very/long/dir │ ok │".encode()) + t_tight_1_b = Terminal(rows=1, cols=34) + t_tight_1_b.feed("\x1b[?1049h\x1b[H│ path=/tmp/a │ ok │".encode()) + assert serialize_vt_snapshot( + vt_screen(t_tight_1_a, scrubbers=path_scrub) + ) == serialize_vt_snapshot(vt_screen(t_tight_1_b, scrubbers=path_scrub)) + + zero_margin_scrub = [(r"/tmp/[a-z/]+", "")] + t_tight_0_a = Terminal(rows=1, cols=25) + t_tight_0_a.feed("\x1b[?1049h\x1b[H│path=/tmp/very/long/dir│".encode()) + t_tight_0_b = Terminal(rows=1, cols=25) + t_tight_0_b.feed("\x1b[?1049h\x1b[H│path=/tmp/a │".encode()) + assert serialize_vt_snapshot( + vt_screen(t_tight_0_a, scrubbers=zero_margin_scrub) + ) == serialize_vt_snapshot(vt_screen(t_tight_0_b, scrubbers=zero_margin_scrub)) + + multi_scrub = [(r"pid=\d+", "pid="), (r"\d+\.\ds", "")] + t_multi_a = Terminal(rows=1, cols=27) + t_multi_a.feed("\x1b[?1049h\x1b[H├ pid=9 │ 0.1s ┤".encode()) + t_multi_b = Terminal(rows=1, cols=27) + t_multi_b.feed("\x1b[?1049h\x1b[H├ pid=482910 │ 100.2s ┤".encode()) + assert serialize_vt_snapshot( + vt_screen(t_multi_a, scrubbers=multi_scrub) + ) == serialize_vt_snapshot(vt_screen(t_multi_b, scrubbers=multi_scrub)) + + composed_scrub = [(r"/tmp/[^/]+", ""), (r"run-\d+", "run-")] + t_comp_a = Terminal(rows=1, cols=32) + t_comp_a.feed("\x1b[?1049h\x1b[H│ /tmp/abcdef123/run-1 OK │".encode()) + t_comp_b = Terminal(rows=1, cols=32) + t_comp_b.feed("\x1b[?1049h\x1b[H│ /tmp/x/run-999999 OK │".encode()) + assert serialize_vt_snapshot( + vt_screen(t_comp_a, scrubbers=composed_scrub) + ) == serialize_vt_snapshot(vt_screen(t_comp_b, scrubbers=composed_scrub)) + + def test_vt_screen_styles_region_sync_hold_cjk_and_errors() -> None: """``vt_screen()``, ``Screen``, ``RegionView``, ``?2026`` hold, and errors.""" t1 = Terminal(rows=3, cols=16) @@ -336,14 +443,14 @@ def test_libvt_testing_serializer_runs_without_syrupy_or_pytest() -> None: "from libvt import Terminal; " "from libvt.testing import (" "format_vt_diff_lines, serialize_vt_snapshot, vt_screen); " - "t1, t2 = Terminal(rows=1, cols=16), Terminal(rows=1, cols=16); " - "t1.feed(b'pid=48210 \\x1b[1;32mPASS\\x1b[0m'); " - "t2.feed(b'pid=9 \\x1b[1;31mFAIL\\x1b[0m'); " + "t1, t2 = Terminal(rows=1, cols=18), Terminal(rows=1, cols=18); " + "t1.feed('\\x1b[?1049h\\x1b[H│ pid=48210 \\x1b[1;32mPASS\\x1b[0m │'.encode()); " + "t2.feed('\\x1b[?1049h\\x1b[H│ pid=9 \\x1b[1;31mFAIL\\x1b[0m │'.encode()); " "sc = [(r'pid=\\d+', 'pid=')]; " "s1 = serialize_vt_snapshot(vt_screen(t1, scrubbers=sc)); " "s2 = serialize_vt_snapshot(vt_screen(t2, scrubbers=sc)); " "diff = format_vt_diff_lines(s2, s1); " - "assert \"row 0 cols 10..14: 'PASS' -> 'FAIL'\" in diff[0], diff" + "assert \"row 0 cols 12..16: 'PASS' -> 'FAIL'\" in diff[0], diff" ) proc = subprocess.run( [sys.executable, "-c", script],