deduplicate.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import annotations
  2. from typing import Iterable
  3. from prompt_toolkit.document import Document
  4. from .base import CompleteEvent, Completer, Completion
  5. __all__ = ["DeduplicateCompleter"]
  6. class DeduplicateCompleter(Completer):
  7. """
  8. Wrapper around a completer that removes duplicates. Only the first unique
  9. completions are kept.
  10. Completions are considered to be a duplicate if they result in the same
  11. document text when they would be applied.
  12. """
  13. def __init__(self, completer: Completer) -> None:
  14. self.completer = completer
  15. def get_completions(
  16. self, document: Document, complete_event: CompleteEvent
  17. ) -> Iterable[Completion]:
  18. # Keep track of the document strings we'd get after applying any completion.
  19. found_so_far: set[str] = set()
  20. for completion in self.completer.get_completions(document, complete_event):
  21. text_if_applied = (
  22. document.text[: document.cursor_position + completion.start_position]
  23. + completion.text
  24. + document.text[document.cursor_position :]
  25. )
  26. if text_if_applied == document.text:
  27. # Don't include completions that don't have any effect at all.
  28. continue
  29. if text_if_applied in found_so_far:
  30. continue
  31. found_so_far.add(text_if_applied)
  32. yield completion