11"""History management classes."""
22
33import json
4- import operator
54import re
65from collections .abc import (
76 Callable ,
109from dataclasses import dataclass
1110from typing import (
1211 Any ,
13- Self ,
14- SupportsIndex ,
15- cast ,
1612 overload ,
1713)
1814
@@ -140,6 +136,25 @@ def from_dict(source_dict: dict[str, Any]) -> "HistoryItem":
140136 return HistoryItem (Statement .from_dict (statement_dict ))
141137
142138
139+ class _EntryRef :
140+ """Hashable reference to a history entry that compares by identity rather than by value.
141+
142+ Unlike id() keys, these are rehashed when a set of them is copied or unpickled, so they keep
143+ referring to the copied entries.
144+ """
145+
146+ __slots__ = ("entry" ,)
147+
148+ def __init__ (self , entry : HistoryItem ) -> None :
149+ self .entry = entry
150+
151+ def __hash__ (self ) -> int :
152+ return id (self .entry )
153+
154+ def __eq__ (self , other : object ) -> bool :
155+ return isinstance (other , _EntryRef ) and other .entry is self .entry
156+
157+
143158class HistoryIndexError (IndexError ):
144159 """Raised when a history index is invalid or a bounded range selects no items."""
145160
@@ -169,83 +184,42 @@ class to gain access to the historical record.
169184 def __init__ (self , seq : Iterable [HistoryItem ] = ()) -> None :
170185 """Initialize History instances."""
171186 super ().__init__ (seq )
172- self .session_start_index = 0
187+ # Entries that were in the list when the session started. Holding references keeps their
188+ # ids from being reused by new entries after they leave the list.
189+ self ._persisted : set [_EntryRef ] = set ()
173190
174- def __delitem__ (self , key : SupportsIndex | slice , / ) -> None :
175- """Delete entries and move the session boundary past any removed persisted entries."""
176- if isinstance (key , slice ):
177- removed_before = sum (index < self .session_start_index for index in range (* key .indices (len (self ))))
178- else :
179- key = operator .index (key )
180- position = key if key >= 0 else len (self ) + key
181- removed_before = int (position < self .session_start_index )
182- super ().__delitem__ (key )
183- self .session_start_index -= removed_before
191+ def is_persisted (self , item : HistoryItem ) -> bool :
192+ """Return whether an entry was in the history when the current session started.
184193
185- @overload
186- def __setitem__ (self , key : SupportsIndex , value : HistoryItem , / ) -> None : ... # pragma: no cover
194+ Membership belongs to the entry object rather than its position, so a persisted entry stays
195+ persisted when the list is reordered, filtered, or repeated, and new entries belong to the
196+ current session wherever they are placed. Equal commands from different sessions are separate
197+ entries. To record a persisted command again in the current session, append its statement.
187198
188- @overload
189- def __setitem__ (self , key : slice , value : Iterable [HistoryItem ], / ) -> None : ... # pragma: no cover
190-
191- def __setitem__ (self , key : SupportsIndex | slice , value : HistoryItem | Iterable [HistoryItem ], / ) -> None :
192- """Replace entries, retaining persisted item identities when a slice spans the session boundary."""
193- if not isinstance (key , slice ):
194- super ().__setitem__ (key , cast (HistoryItem , value ))
195- return
196- start , stop , step = key .indices (len (self ))
197- replacement = list (cast (Iterable [HistoryItem ], value ))
198- persisted_ids = (
199- {id (entry ) for entry in self [start : self .session_start_index ]}
200- if step == 1 and start < self .session_start_index < stop
201- else None
202- )
203- super ().__setitem__ (key , replacement )
204- if persisted_ids is not None :
205- boundary = start
206- for entry in replacement :
207- if id (entry ) not in persisted_ids :
208- break
209- boundary += 1
210- self .session_start_index = boundary
211- elif step == 1 and start < self .session_start_index :
212- stop = max (start , stop )
213- self .session_start_index += len (replacement ) - (stop - start )
214-
215- def insert (self , index : SupportsIndex , value : HistoryItem , / ) -> None :
216- """Insert an entry, shifting the session boundary if the insertion precedes it."""
217- index = operator .index (index )
218- position = min (len (self ), max (0 , index if index >= 0 else len (self ) + index ))
219- super ().insert (index , value )
220- if position < self .session_start_index :
221- self .session_start_index += 1
222-
223- def pop (self , index : SupportsIndex = - 1 , / ) -> HistoryItem :
224- """Remove and return an entry, retaining the session boundary."""
225- index = operator .index (index )
226- position = index if index >= 0 else len (self ) + index
227- result = super ().pop (index )
228- if position < self .session_start_index :
229- self .session_start_index -= 1
230- return result
199+ :param item: the history entry to check
200+ :return: True if the entry is from a previous session
201+ """
202+ return _EntryRef (item ) in self ._persisted
203+
204+ @property
205+ def session_start_index (self ) -> int :
206+ """Index just past the last persisted entry.
207+
208+ Every entry from this index on belongs to the current session. Unless the list has been
209+ reordered, every entry before it is persisted. Assigning ``n`` marks the first ``n`` entries
210+ as persisted and the rest as current.
211+ """
212+ for index in range (len (self ) - 1 , - 1 , - 1 ):
213+ if self .is_persisted (self [index ]):
214+ return index + 1
215+ return 0
231216
232- def remove (self , value : HistoryItem , / ) -> None :
233- """Remove the first matching entry, retaining the session boundary."""
234- position = super ().index (value )
235- super ().pop (position )
236- if position < self .session_start_index :
237- self .session_start_index -= 1
238-
239- def __imul__ (self , count : SupportsIndex , / ) -> Self :
240- """Repeat entries in place, resetting the boundary if repetition clears the list."""
241- count = operator .index (count )
242- super ().__imul__ (count )
243- if count <= 0 :
244- self .session_start_index = 0
245- return self
217+ @session_start_index .setter
218+ def session_start_index (self , index : int ) -> None :
219+ self ._persisted = {_EntryRef (entry ) for entry in self [:index ]}
246220
247221 def start_session (self ) -> None :
248- """Start a new session, thereby setting the next index as the first index in the new session ."""
222+ """Start a new session, marking every entry currently in the history as persisted ."""
249223 self .session_start_index = len (self )
250224
251225 def _zero_based_index (self , onebased : int | str ) -> int :
@@ -339,7 +313,7 @@ def span(self, span: str, include_persisted: bool = False) -> dict[int, "History
339313 if start < 0 :
340314 raise HistoryIndexError (NO_HISTORY_ITEMS )
341315 else :
342- start = 0 if include_persisted or end_token else self . session_start_index
316+ start = 0
343317
344318 if end_token :
345319 end = min (int (end_token ), len (self ))
@@ -348,10 +322,11 @@ def span(self, span: str, include_persisted: bool = False) -> dict[int, "History
348322 else :
349323 end = len (self )
350324
351- if (start_token or end_token ) and (start >= len (self ) or end <= start ):
325+ bounded = bool (start_token or end_token )
326+ if bounded and (start >= len (self ) or end <= start ):
352327 raise HistoryIndexError (NO_HISTORY_ITEMS )
353328
354- return self ._build_result_dictionary (start , end )
329+ return self ._build_result_dictionary (start , end , include_persisted = include_persisted or bounded )
355330
356331 def str_search (self , search : str , include_persisted : bool = False ) -> dict [int , "HistoryItem" ]:
357332 """Find history items which contain a given string.
@@ -369,8 +344,7 @@ def isin(history_item: HistoryItem) -> bool:
369344 inexpanded = sloppy in su .norm_fold (history_item .expanded )
370345 return inraw or inexpanded
371346
372- start = 0 if include_persisted else self .session_start_index
373- return self ._build_result_dictionary (start , len (self ), isin )
347+ return self ._build_result_dictionary (0 , len (self ), isin , include_persisted )
374348
375349 def regex_search (self , regex : str , include_persisted : bool = False ) -> dict [int , "HistoryItem" ]:
376350 """Find history items which match a given regular expression.
@@ -389,15 +363,13 @@ def isin(hi: HistoryItem) -> bool:
389363 """Filter function for doing a regular expression search of history."""
390364 return bool (finder .search (hi .raw ) or finder .search (hi .expanded ))
391365
392- start = 0 if include_persisted else self .session_start_index
393- return self ._build_result_dictionary (start , len (self ), isin )
366+ return self ._build_result_dictionary (0 , len (self ), isin , include_persisted )
394367
395368 def truncate (self , max_length : int ) -> None :
396369 """Truncate the length of the history, dropping the oldest items if necessary.
397370
398- The current session's start index is shifted so it still marks the first retained
399- current-session item. If any current-session items are dropped, all retained items
400- belong to the current session.
371+ Retained items keep their session membership, so retained current-session items still
372+ appear in unbounded ranges and searches.
401373
402374 :param max_length: the maximum length of the history, if zero or negative, all history
403375 items will be deleted
@@ -410,17 +382,24 @@ def truncate(self, max_length: int) -> None:
410382 del self [0 :last_element ]
411383
412384 def _build_result_dictionary (
413- self , start : int , end : int , filter_func : Callable [[HistoryItem ], bool ] | None = None
385+ self ,
386+ start : int ,
387+ end : int ,
388+ filter_func : Callable [[HistoryItem ], bool ] | None = None ,
389+ include_persisted : bool = True ,
414390 ) -> dict [int , "HistoryItem" ]:
415391 """Build history search results.
416392
417393 :param start: start index to search from
418394 :param end: end index to stop searching (exclusive).
395+ :param filter_func: optional function that returns True for entries to include
396+ :param include_persisted: if False, skip entries from previous sessions
419397 """
420398 results : dict [int , HistoryItem ] = {}
421399 for index in range (start , end ):
422- if filter_func is None or filter_func (self [index ]):
423- results [index + 1 ] = self [index ]
400+ entry = self [index ]
401+ if (include_persisted or not self .is_persisted (entry )) and (filter_func is None or filter_func (entry )):
402+ results [index + 1 ] = entry
424403 return results
425404
426405 def to_json (self ) -> str :
0 commit comments