2525from contextlib import contextmanager
2626from dataclasses import dataclass , field , fields , replace
2727from functools import partial
28+ from itertools import pairwise
2829from typing import Self
2930
3031from . import commands , console , input
5960type CommandClass = type [Command ]
6061type CommandInput = tuple [CommandName | CommandClass , EventData ]
6162type PromptCellCacheKey = tuple [str , bool ]
62- type LineKey = tuple [str , bool , str , tuple [ColorSpan , ...]]
6363type 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 )
223257class 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 )
229289class 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 , ...],
0 commit comments