2525from contextlib import contextmanager
2626from dataclasses import dataclass , field , fields , replace
2727from functools import partial
28- from itertools import pairwise
29- from typing import Self
28+ from typing import NamedTuple , Self
3029
3130from . import commands , console , input
3231from .content import (
@@ -219,38 +218,26 @@ def with_full(self) -> Self:
219218 return replace (self , cursor_only = False , full = True )
220219
221220
222- @dataclass (frozen = True , slots = True )
223- class LineInput :
221+ class LineInput (NamedTuple ):
224222 text : str
225223 has_newline : bool
226224 prompt : str
227225 colors : tuple [ColorSpan , ...]
228226
229227
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- )
228+ def _prefix_colors (
229+ colors : tuple [ColorSpan , ...], stop : int ,
230+ ) -> tuple [tuple [int , int , str ], ...] | None :
231+ prefix = []
232+ previous_end = None
233+ for (start , end ), tag in colors :
234+ # The suffix can start inside a span only if spans are disjoint.
235+ if end < start or (previous_end is not None and start <= previous_end ):
236+ return None
237+ if start < stop :
238+ prefix .append ((start , min (end , stop - 1 ), tag ))
239+ previous_end = end
240+ return tuple (prefix )
254241
255242
256243@dataclass (frozen = True , slots = True )
@@ -259,37 +246,30 @@ class LineSnapshot:
259246 lines : tuple [RenderLine , ...]
260247 rows : tuple [LayoutRow , ...]
261248
262-
263249 def reusable_prefix (self , line : LineInput ) -> tuple [int , int ]:
264250 """Return the number of reusable rows and their extent in the buffer."""
265- if len ( self . rows ) < 2 or self .line .prompt != line .prompt :
251+ if self .line .prompt != line .prompt :
266252 return 0 , 0
267253
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 :
254+ count = start = 0
255+ for index , row in enumerate ( self . rows [: - 1 ], 1 ):
256+ end = start + row . buffer_advance
257+ # A wrap also depends on the first character of the next row.
258+ if not line . text . startswith ( self . line . text [ start : end + 1 ], start ) :
273259 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
260+ count , start = index , end
261+
262+ if start :
263+ colors = _prefix_colors (self .line .colors , start )
264+ if colors is not None and colors == _prefix_colors (line .colors , start ):
265+ return count , start
285266 return 0 , 0
286267
287268
288269@dataclass (frozen = True , slots = True )
289270class ScreenSnapshot :
290271 context : ScreenContext
291- text : str
292- default_colors : bool
272+ frame_key : tuple [str , tuple [str , ...]] | None
293273 logical_lines : tuple [LineSnapshot , ...]
294274 by_line : dict [LineInput , LineSnapshot ]
295275 lines : tuple [RenderLine , ...]
@@ -395,7 +375,6 @@ def __post_init__(self) -> None:
395375 self .rendered_screen = RenderedScreen .empty ()
396376 self .can_colorize = _colorize .can_colorize ()
397377 self .invalidation = RefreshInvalidation .empty ()
398-
399378 self ._screen_snapshot = None
400379
401380 @property
@@ -422,22 +401,14 @@ def calc_screen(self) -> RenderedScreen:
422401 if getattr (get_prompt , "__func__" , None ) is Reader .get_prompt :
423402 get_prompt = partial (self ._prompt_for_line , last_lineno = last_lineno )
424403 prompts = tuple (get_prompt (i , i == cursor_line ) for i in range (len (logical_lines )))
425-
426404 theme = THEME ()
427405 context = self .console .width , theme , self .can_colorize
428- default_colors = not self .can_colorize or self .gen_colors is gen_colors
406+ frame_key = None
407+ if not self .can_colorize or self .gen_colors is gen_colors :
408+ frame_key = text , prompts
429409 previous = self ._screen_snapshot
430410 if previous is not None and previous .context == context :
431- if (
432- previous .text == text
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- )
440- ):
411+ if frame_key is not None and previous .frame_key == frame_key :
441412 self .layout = previous .layout
442413 self .cxy = self .pos2xy ()
443414 return RenderedScreen (previous .lines , self .cxy )
@@ -463,16 +434,18 @@ def calc_screen(self) -> RenderedScreen:
463434 while end_color < len (colors ) and colors [end_color ].span .start < stop :
464435 end_color += 1
465436 # Relative offsets let a logical line retain its rows when it moves.
466- line_colors = tuple (
467- ColorSpan (Span (span .start - offset , span .end - offset ), tag )
468- for span , tag in colors [first_color :end_color ]
469- )
437+ line_colors = colors [first_color :end_color ]
438+ if offset :
439+ line_colors = tuple (
440+ ColorSpan (Span (start - offset , end - offset ), tag )
441+ for (start , end ), tag in line_colors
442+ )
470443 has_newline = lineno < last_lineno
471444 key = LineInput (line , has_newline , prompt , line_colors )
472445 snapshot = by_line .get (key ) or reusable .get (key )
473446 if snapshot is None :
474447 old_line = previous_lines [lineno ] if lineno < len (previous_lines ) else None
475- snapshot = self ._render_logical_line (key , lineno , offset , old_line , theme )
448+ snapshot = self ._render_logical_line (key , old_line , theme )
476449 snapshots .append (snapshot )
477450 by_line [snapshot .line ] = snapshot
478451 lines .extend (snapshot .lines )
@@ -483,15 +456,13 @@ def calc_screen(self) -> RenderedScreen:
483456 self .cxy = self .pos2xy ()
484457 rendered = tuple (lines )
485458 self ._screen_snapshot = ScreenSnapshot (
486- context , text , default_colors , tuple (snapshots ), by_line , rendered , self .layout ,
459+ context , frame_key , tuple (snapshots ), by_line , rendered , self .layout ,
487460 )
488461 return RenderedScreen (rendered , self .cxy )
489462
490463 def _render_logical_line (
491464 self ,
492465 line : LineInput ,
493- lineno : int ,
494- offset : int ,
495466 previous : LineSnapshot | None ,
496467 theme : _colorize .Syntax ,
497468 ) -> LineSnapshot :
@@ -500,13 +471,11 @@ def _render_logical_line(
500471 prefix_rows = previous .rows [:count ] if previous else ()
501472 suffix = line .text [start :]
502473 content = ContentLine (
503- source = SourceLine (lineno , suffix , offset + start , line .has_newline ),
474+ source = SourceLine (0 , suffix , start , line .has_newline ),
504475 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- ),
476+ body = build_body_fragments (suffix , list (line .colors ), start , theme ),
508477 )
509- layout = layout_content_lines ((content ,), self .console .width , offset + start )
478+ layout = layout_content_lines ((content ,), self .console .width , start )
510479 return LineSnapshot (
511480 line ,
512481 prefix_lines + tuple (self ._render_wrapped_rows (layout .wrapped_rows )),
@@ -725,7 +694,7 @@ def insert(self, text: str | list[str]) -> None:
725694 def invalidate_cursor (self ) -> None :
726695 self .invalidation = self .invalidation .with_cursor ()
727696
728- def invalidate_buffer (self , _from_pos : int ) -> None :
697+ def invalidate_buffer (self , from_pos : int ) -> None :
729698 self .invalidation = self .invalidation .with_buffer ()
730699
731700 def invalidate_prompt (self ) -> None :
0 commit comments