pyperclip.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from __future__ import annotations
  2. import pyperclip
  3. from prompt_toolkit.selection import SelectionType
  4. from .base import Clipboard, ClipboardData
  5. __all__ = [
  6. "PyperclipClipboard",
  7. ]
  8. class PyperclipClipboard(Clipboard):
  9. """
  10. Clipboard that synchronizes with the Windows/Mac/Linux system clipboard,
  11. using the pyperclip module.
  12. """
  13. def __init__(self) -> None:
  14. self._data: ClipboardData | None = None
  15. def set_data(self, data: ClipboardData) -> None:
  16. self._data = data
  17. pyperclip.copy(data.text)
  18. def get_data(self) -> ClipboardData:
  19. text = pyperclip.paste()
  20. # When the clipboard data is equal to what we copied last time, reuse
  21. # the `ClipboardData` instance. That way we're sure to keep the same
  22. # `SelectionType`.
  23. if self._data and self._data.text == text:
  24. return self._data
  25. # Pyperclip returned something else. Create a new `ClipboardData`
  26. # instance.
  27. else:
  28. return ClipboardData(
  29. text=text,
  30. type=SelectionType.LINES if "\n" in text else SelectionType.CHARACTERS,
  31. )