Skip to content

Commit cf1b116

Browse files
committed
Reuse unchanged wrapped rows in PyREPL
1 parent ee19d95 commit cf1b116

3 files changed

Lines changed: 162 additions & 45 deletions

File tree

‎Lib/_pyrepl/content.py‎

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from dataclasses import dataclass
22

3-
from .utils import ColorSpan, StyleRef, THEME, iter_display_chars, unbracket, wlen
3+
from _colorize import Syntax
4+
5+
from .utils import ColorSpan, StyleRef, iter_display_chars, unbracket, wlen
46

57

68
@dataclass(frozen=True, slots=True)
@@ -108,27 +110,14 @@ def build_body_fragments(
108110
buffer: str,
109111
colors: list[ColorSpan] | None,
110112
start_index: int,
113+
theme: Syntax,
111114
) -> tuple[ContentFragment, ...]:
112115
"""Convert a line's text into styled content fragments."""
113-
# Two separate loops to avoid the THEME() call in the common uncolored path.
114-
if colors is None:
115-
return tuple(
116-
ContentFragment(
117-
styled_char.text,
118-
styled_char.width,
119-
StyleRef(),
120-
)
121-
for styled_char in iter_display_chars(buffer, colors, start_index)
122-
)
123-
124-
theme = THEME()
125-
return tuple(
126-
ContentFragment(
127-
styled_char.text,
128-
styled_char.width,
129-
StyleRef.from_tag(styled_char.tag, theme[styled_char.tag])
130-
if styled_char.tag
131-
else StyleRef(),
132-
)
133-
for styled_char in iter_display_chars(buffer, colors, start_index)
134-
)
116+
plain = StyleRef()
117+
style = plain
118+
fragments = []
119+
for text, width, tag in iter_display_chars(buffer, colors, start_index):
120+
if tag != style.tag:
121+
style = StyleRef.from_tag(tag, theme[tag]) if tag else plain
122+
fragments.append(ContentFragment(text, width, style))
123+
return tuple(fragments)

‎Lib/_pyrepl/reader.py‎

Lines changed: 108 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from contextlib import contextmanager
2626
from dataclasses import dataclass, field, fields, replace
2727
from functools import partial
28+
from itertools import pairwise
2829
from typing import Self
2930

3031
from . import commands, console, input
@@ -59,7 +60,6 @@
5960
type CommandClass = type[Command]
6061
type CommandInput = tuple[CommandName | CommandClass, EventData]
6162
type PromptCellCacheKey = tuple[str, bool]
62-
type LineKey = tuple[str, bool, str, tuple[ColorSpan, ...]]
6363
type ScreenContext = tuple[int, _colorize.Syntax, bool]
6464

6565

@@ -219,19 +219,79 @@ def with_full(self) -> Self:
219219
return replace(self, cursor_only=False, full=True)
220220

221221

222+
@dataclass(frozen=True, slots=True)
223+
class LineInput:
224+
text: str
225+
has_newline: bool
226+
prompt: str
227+
colors: tuple[ColorSpan, ...]
228+
229+
230+
def _common_text_prefix(before: str, after: str) -> int:
231+
shared = min(len(before), len(after))
232+
if before.startswith(after) or after.startswith(before):
233+
return shared
234+
for index in range(shared):
235+
if before[index] != after[index]:
236+
return index
237+
return shared
238+
239+
240+
def _colors_before(colors: tuple[ColorSpan, ...], end: int) -> tuple[ColorSpan, ...]:
241+
return tuple(
242+
ColorSpan(Span(span.start, min(span.end, end - 1)), tag)
243+
for span, tag in colors
244+
if span.start < end
245+
)
246+
247+
248+
def _colors_can_restart(colors: tuple[ColorSpan, ...]) -> bool:
249+
# Starting inside a span is safe only when spans are ordered and disjoint.
250+
return (
251+
all(span.start <= span.end for span, _ in colors)
252+
and all(left.span.end < right.span.start for left, right in pairwise(colors))
253+
)
254+
255+
222256
@dataclass(frozen=True, slots=True)
223257
class LineSnapshot:
258+
line: LineInput
224259
lines: tuple[RenderLine, ...]
225260
rows: tuple[LayoutRow, ...]
226261

227262

263+
def reusable_prefix(self, line: LineInput) -> tuple[int, int]:
264+
"""Return the number of reusable rows and their extent in the buffer."""
265+
if len(self.rows) < 2 or self.line.prompt != line.prompt:
266+
return 0, 0
267+
268+
shared = _common_text_prefix(self.line.text, line.text)
269+
end = offset = count = 0
270+
for index, row in enumerate(self.rows):
271+
end += row.buffer_advance
272+
if end >= shared:
273+
break
274+
if row.suffix_width:
275+
offset, count = end, index + 1
276+
277+
# Each retained wrap depends on the first character on the next row.
278+
# Leave the last row to the layout code so it can handle the newline.
279+
if offset and (
280+
_colors_can_restart(self.line.colors)
281+
and _colors_can_restart(line.colors)
282+
and _colors_before(self.line.colors, offset) == _colors_before(line.colors, offset)
283+
):
284+
return count, offset
285+
return 0, 0
286+
287+
228288
@dataclass(frozen=True, slots=True)
229289
class ScreenSnapshot:
230290
context: ScreenContext
231291
text: str
232-
prompts: tuple[str, ...]
233292
default_colors: bool
234-
by_line: dict[LineKey, LineSnapshot]
293+
logical_lines: tuple[LineSnapshot, ...]
294+
by_line: dict[LineInput, LineSnapshot]
235295
lines: tuple[RenderLine, ...]
236296
layout: LayoutMap
237297

@@ -363,27 +423,36 @@ def calc_screen(self) -> RenderedScreen:
363423
get_prompt = partial(self._prompt_for_line, last_lineno=last_lineno)
364424
prompts = tuple(get_prompt(i, i == cursor_line) for i in range(len(logical_lines)))
365425

366-
context = self.console.width, THEME(), self.can_colorize
426+
theme = THEME()
427+
context = self.console.width, theme, self.can_colorize
367428
default_colors = not self.can_colorize or self.gen_colors is gen_colors
368429
previous = self._screen_snapshot
369430
if previous is not None and previous.context == context:
370431
if (
371432
previous.text == text
372-
and previous.prompts == prompts
373-
and previous.default_colors and default_colors
433+
and previous.default_colors
434+
and default_colors
435+
and len(previous.logical_lines) == len(prompts)
436+
and all(
437+
snapshot.line.prompt == prompt
438+
for snapshot, prompt in zip(previous.logical_lines, prompts)
439+
)
374440
):
375441
self.layout = previous.layout
376442
self.cxy = self.pos2xy()
377443
return RenderedScreen(previous.lines, self.cxy)
378444
reusable = previous.by_line
445+
previous_lines = previous.logical_lines
379446
else:
380447
self._prompt_cell_cache.clear()
381448
reusable = {}
449+
previous_lines = ()
382450

383451
colors = tuple(self.gen_colors(text)) if self.can_colorize else ()
384452
first_color = 0
385453
offset = 0
386-
by_line: dict[LineKey, LineSnapshot] = {}
454+
snapshots: list[LineSnapshot] = []
455+
by_line: dict[LineInput, LineSnapshot] = {}
387456
lines: list[RenderLine] = []
388457
rows: list[LayoutRow] = []
389458
for lineno, (line, prompt) in enumerate(zip(logical_lines, prompts)):
@@ -399,22 +468,13 @@ def calc_screen(self) -> RenderedScreen:
399468
for span, tag in colors[first_color:end_color]
400469
)
401470
has_newline = lineno < last_lineno
402-
key = line, has_newline, prompt, line_colors
471+
key = LineInput(line, has_newline, prompt, line_colors)
403472
snapshot = by_line.get(key) or reusable.get(key)
404473
if snapshot is None:
405-
content = ContentLine(
406-
source=SourceLine(lineno, line, offset, has_newline),
407-
prompt=build_prompt_content(prompt),
408-
body=build_body_fragments(
409-
line, list(line_colors) if self.can_colorize else None, 0,
410-
),
411-
)
412-
layout = layout_content_lines((content,), self.console.width, offset)
413-
snapshot = LineSnapshot(
414-
tuple(self._render_wrapped_rows(layout.wrapped_rows)),
415-
layout.layout_map.rows,
416-
)
417-
by_line[key] = snapshot
474+
old_line = previous_lines[lineno] if lineno < len(previous_lines) else None
475+
snapshot = self._render_logical_line(key, lineno, offset, old_line, theme)
476+
snapshots.append(snapshot)
477+
by_line[snapshot.line] = snapshot
418478
lines.extend(snapshot.lines)
419479
rows.extend(snapshot.rows)
420480
offset = stop + has_newline
@@ -423,10 +483,36 @@ def calc_screen(self) -> RenderedScreen:
423483
self.cxy = self.pos2xy()
424484
rendered = tuple(lines)
425485
self._screen_snapshot = ScreenSnapshot(
426-
context, text, prompts, default_colors, by_line, rendered, self.layout,
486+
context, text, default_colors, tuple(snapshots), by_line, rendered, self.layout,
427487
)
428488
return RenderedScreen(rendered, self.cxy)
429489

490+
def _render_logical_line(
491+
self,
492+
line: LineInput,
493+
lineno: int,
494+
offset: int,
495+
previous: LineSnapshot | None,
496+
theme: _colorize.Syntax,
497+
) -> LineSnapshot:
498+
count, start = previous.reusable_prefix(line) if previous else (0, 0)
499+
prefix_lines = previous.lines[:count] if previous else ()
500+
prefix_rows = previous.rows[:count] if previous else ()
501+
suffix = line.text[start:]
502+
content = ContentLine(
503+
source=SourceLine(lineno, suffix, offset + start, line.has_newline),
504+
prompt=build_prompt_content("" if count else line.prompt),
505+
body=build_body_fragments(
506+
suffix, list(line.colors) if self.can_colorize else None, start, theme,
507+
),
508+
)
509+
layout = layout_content_lines((content,), self.console.width, offset + start)
510+
return LineSnapshot(
511+
line,
512+
prefix_lines + tuple(self._render_wrapped_rows(layout.wrapped_rows)),
513+
prefix_rows + layout.layout_map.rows,
514+
)
515+
430516
def _render_wrapped_rows(
431517
self,
432518
wrapped_rows: tuple[WrappedRow, ...],

‎Lib/test/test_pyrepl/test_reader.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from _pyrepl.layout import LayoutMap
1515
from _pyrepl.readline import ReadlineAlikeReader, ReadlineConfig
1616
from _pyrepl.reader import Reader
17+
from _pyrepl.utils import ColorSpan, Span
1718
from _colorize import default_theme
1819

1920

@@ -74,6 +75,47 @@ def test_edit_after_wrapped_line_preserves_last_prompt(self):
7475
reader.insert("!")
7576
self.assertEqual(reader.calc_screen().screen_lines[-1], "end value!")
7677

78+
def test_edit_in_wrapped_string_reuses_prefix_rows(self):
79+
reader = prepare_reader_multiline_prompt(prepare_console((), width=14))
80+
reader.can_colorize = True
81+
reader.insert("'" + "a" * 30)
82+
before = reader.calc_screen()
83+
rows = reader.layout.rows
84+
85+
reader.insert("b")
86+
after = reader.calc_screen()
87+
for old, new in zip(before.lines[:-1], after.lines[:-1], strict=True):
88+
self.assertIs(new, old)
89+
for old, new in zip(rows[:-1], reader.layout.rows[:-1], strict=True):
90+
self.assertIs(new, old)
91+
self.assertEqual(after.lines[-1].cells[-1].text, "b")
92+
93+
def test_edit_at_wrap_boundary_can_remove_the_wrap(self):
94+
reader = prepare_reader(prepare_console((), width=10))
95+
reader.insert("a" * 8 + "界")
96+
self.assertEqual(reader.calc_screen().screen_lines, ("aaaaaaaa\\", "界"))
97+
98+
reader.buffer[-1] = "b"
99+
reader.invalidate_buffer(len(reader.buffer) - 1)
100+
self.assertEqual(reader.calc_screen().screen_lines, ("aaaaaaaab",))
101+
102+
def test_recolored_wrapped_prefix_renders_again(self):
103+
reader = prepare_reader(prepare_console((), width=10))
104+
reader.can_colorize = True
105+
106+
def colorize(text):
107+
tag = "comment" if text.endswith("!") else "string"
108+
yield ColorSpan(Span(0, len(text) - 1), tag)
109+
110+
reader.gen_colors = colorize
111+
reader.insert("a" * 20)
112+
before = reader.calc_screen()
113+
114+
reader.insert("!")
115+
after = reader.calc_screen()
116+
self.assertEqual(before.lines[0].cells[0].style.tag, "string")
117+
self.assertEqual(after.lines[0].cells[0].style.tag, "comment")
118+
77119
def test_calc_screen_wrap_simple(self):
78120
events = code_to_events(10 * "a")
79121
reader, _ = handle_events_narrow_console(events)

0 commit comments

Comments
 (0)