pyperclip.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import absolute_import, unicode_literals
  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):
  14. self._data = None
  15. def set_data(self, data):
  16. assert isinstance(data, ClipboardData)
  17. self._data = data
  18. pyperclip.copy(data.text)
  19. def get_data(self):
  20. text = pyperclip.paste()
  21. # When the clipboard data is equal to what we copied last time, reuse
  22. # the `ClipboardData` instance. That way we're sure to keep the same
  23. # `SelectionType`.
  24. if self._data and self._data.text == text:
  25. return self._data
  26. # Pyperclip returned something else. Create a new `ClipboardData`
  27. # instance.
  28. else:
  29. return ClipboardData(
  30. text=text,
  31. type=SelectionType.LINES if '\n' in text else SelectionType.LINES)