Compare commits
3
Commits
02f43b2ee9
...
e009b493c7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e009b493c7
|
||
|
|
242bffb671
|
||
|
|
10981dcf00
|
No files matched your search
@@ -222,6 +222,11 @@ Detailed list of changes
|
||||
0.50.1 [unreleased]
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
- kitty now keeps an in-memory history of the text copied to the clipboard,
|
||||
which :ac:`paste_from_clipboard_history` and :ac:`search_clipboard_history`
|
||||
can paste back. Nothing is written to disk and private clipboard writes are
|
||||
never recorded. See :ref:`clipboard_history` for details.
|
||||
|
||||
- :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten
|
||||
<kittens/file-manager>` in a left dock by default, instead of requiring a
|
||||
manual mapping. This takes the key over from :ac:`open_url`; remap
|
||||
|
||||
@@ -264,3 +264,30 @@ to access the clipboard.
|
||||
When the terminal sends an unsolicited paste event because the user triggered
|
||||
a paste and the 5522 mode is enabled, there will be no associated id. In this
|
||||
case, the multiplexer must forward the event to the currently active window.
|
||||
|
||||
|
||||
.. _clipboard_history:
|
||||
|
||||
Clipboard history
|
||||
---------------------
|
||||
|
||||
kitty keeps the last 50 pieces of plain text copied to the clipboard of each
|
||||
instance, newest first, and lets you paste one of them back with
|
||||
:ac:`paste_from_clipboard_history`. :ac:`search_clipboard_history` filters the
|
||||
history with a fuzzy query before showing the list.
|
||||
|
||||
The history lives in memory only: it is never written to disk, so it disappears
|
||||
when kitty exits and secrets copied during a session do not outlive it. Text
|
||||
written by a program that marks its request as private (by passing a ``pw``
|
||||
field in an *OSC 5522* write request) is never recorded, and neither is anything
|
||||
copied to the primary selection. Images and other non-text data are ignored.
|
||||
|
||||
To bind both actions, add something like this to :file:`kitty.conf`:
|
||||
|
||||
.. code-block:: conf
|
||||
|
||||
map kitty_mod+shift+v paste_from_clipboard_history
|
||||
map kitty_mod+shift+f search_clipboard_history
|
||||
|
||||
The size of the history is fixed at 50 entries, 64 KiB per entry and 1 MiB in
|
||||
total, so that a few large copies cannot use an unbounded amount of memory.
|
||||
@@ -40,6 +40,7 @@ from .clipboard import (
|
||||
set_clipboard_string,
|
||||
set_primary_selection,
|
||||
)
|
||||
from .clipboard_history import ClipboardHistory
|
||||
from .colors import ColorSchemes, theme_colors
|
||||
from .conf.utils import BadLine, KeyAction, to_cmdline
|
||||
from .config import common_opts_as_dict, prepare_config_file_for_editing, store_effective_config
|
||||
@@ -419,6 +420,7 @@ class Boss:
|
||||
self.atexit = Atexit()
|
||||
set_layout_options(opts)
|
||||
self.clipboard = Clipboard()
|
||||
self.clipboard_history = ClipboardHistory()
|
||||
self.window_for_dispatch: Window | None = None
|
||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||
self.update_check_started = False
|
||||
@@ -3159,6 +3161,43 @@ class Boss:
|
||||
if text:
|
||||
w.paste_with_actions(text)
|
||||
|
||||
def _clipboard_history_preview(self, text: str) -> str:
|
||||
# The picker shows one line per entry, so flatten newlines and keep the line short
|
||||
q = ' '.join(text.split())
|
||||
return q if len(q) <= 120 else q[:117] + '…'
|
||||
|
||||
def _choose_from_clipboard_history(self, entries: tuple[str, ...]) -> None:
|
||||
if not entries:
|
||||
self.ring_bell_if_allowed()
|
||||
return
|
||||
previews = [(text, self._clipboard_history_preview(text) or _('(blank)')) for text in entries]
|
||||
|
||||
def chosen(text: str | None) -> None:
|
||||
if text:
|
||||
self.paste_to_active_window(text)
|
||||
|
||||
self.choose_entry(_('Clipboard history'), previews, chosen)
|
||||
|
||||
@ac('cp', 'Paste an entry from the clipboard history. See :ref:`clipboard_history`.')
|
||||
def paste_from_clipboard_history(self) -> None:
|
||||
self._choose_from_clipboard_history(self.clipboard_history.entries())
|
||||
|
||||
@ac('cp', 'Search the clipboard history and paste the selected entry. See :ref:`clipboard_history`.')
|
||||
def search_clipboard_history(self) -> None:
|
||||
if not self.clipboard_history:
|
||||
self.ring_bell_if_allowed()
|
||||
return
|
||||
|
||||
def query_entered(query: str) -> None:
|
||||
self._choose_from_clipboard_history(self.clipboard_history.search(query))
|
||||
|
||||
self.get_line(
|
||||
_('Search the clipboard history. Leave empty to list everything.'),
|
||||
query_entered,
|
||||
prompt=_('Search: '),
|
||||
window_title=_('Search clipboard history'),
|
||||
)
|
||||
|
||||
def current_primary_selection(self) -> str:
|
||||
return get_primary_selection() if supports_primary_selection else ''
|
||||
|
||||
|
||||
+23
-4
@@ -96,15 +96,33 @@ class Clipboard:
|
||||
self.clipboard_type = clipboard_type
|
||||
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
|
||||
|
||||
def set_text(self, x: str | bytes) -> None:
|
||||
def set_text(self, x: str | bytes, private: bool = False) -> None:
|
||||
if isinstance(x, str):
|
||||
x = x.encode('utf-8')
|
||||
self.set_mime({'text/plain': x})
|
||||
self.set_mime({'text/plain': x}, private=private)
|
||||
|
||||
def set_mime(self, data: Mapping[str, DataType]) -> None:
|
||||
def set_mime(self, data: Mapping[str, DataType], private: bool = False) -> None:
|
||||
if self.enabled and isinstance(data, dict):
|
||||
self.data = dict(data)
|
||||
set_clipboard_data_types(self.clipboard_type, tuple(self.data))
|
||||
self._record_in_history(private=private)
|
||||
|
||||
def _record_in_history(self, private: bool) -> None:
|
||||
# Only plain text is useful in the history, and only for the clipboard: the primary selection
|
||||
# changes constantly and would evict everything else. Private writes are dropped by the
|
||||
# history itself, so that secrets never reach it.
|
||||
if self.clipboard_type is not ClipboardType.clipboard:
|
||||
return
|
||||
data = self.data.get('text/plain')
|
||||
if not isinstance(data, bytes):
|
||||
return
|
||||
try:
|
||||
text = data.decode('utf-8')
|
||||
history = getattr(get_boss(), 'clipboard_history', None)
|
||||
except Exception:
|
||||
return
|
||||
if history is not None:
|
||||
history.add(text, private=private)
|
||||
|
||||
def get_text(self) -> str:
|
||||
parts: list[bytes] = []
|
||||
@@ -309,7 +327,8 @@ class WriteRequest:
|
||||
if pos is not None:
|
||||
self.mime_map[alias] = pos
|
||||
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
|
||||
cp.set_mime(x)
|
||||
# A write request that carries a password is private: never keep its data in the history
|
||||
cp.set_mime(x, private=bool(self.password))
|
||||
|
||||
def abort(self, msg: str) -> ValueError:
|
||||
# returns the error to raise, so that callers read as: raise self.abort(...)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
# A bounded, in-memory history of what was copied to the clipboard.
|
||||
#
|
||||
# Nothing is ever written to disk: copied text often contains secrets and the history is meant to
|
||||
# help within one kitty instance, not to outlive it. Entries marked private are never recorded.
|
||||
|
||||
from collections import deque
|
||||
from contextlib import suppress
|
||||
from typing import Iterator
|
||||
|
||||
DEFAULT_MAX_ENTRIES = 50
|
||||
MAX_ENTRY_CHARS = 64 * 1024
|
||||
MAX_TOTAL_CHARS = 1024 * 1024
|
||||
|
||||
|
||||
def match_score(needle: str, haystack: str) -> int:
|
||||
"""Return a score, lower is better, or -1 when haystack does not contain needle as a subsequence.
|
||||
|
||||
A plain substring match always scores better than a subsequence so that what the user typed as
|
||||
a contiguous string is ranked first, which is what people expect from a fuzzy filter.
|
||||
"""
|
||||
if not needle:
|
||||
return 0
|
||||
needle, haystack = needle.lower(), haystack.lower()
|
||||
pos = haystack.find(needle)
|
||||
if pos > -1:
|
||||
return pos
|
||||
gaps = 0
|
||||
start = 0
|
||||
for ch in needle:
|
||||
idx = haystack.find(ch, start)
|
||||
if idx < 0:
|
||||
return -1
|
||||
gaps += idx - start
|
||||
start = idx + 1
|
||||
return MAX_TOTAL_CHARS + gaps
|
||||
|
||||
|
||||
class ClipboardHistory:
|
||||
def __init__(
|
||||
self,
|
||||
max_entries: int = DEFAULT_MAX_ENTRIES,
|
||||
max_entry_chars: int = MAX_ENTRY_CHARS,
|
||||
max_total_chars: int = MAX_TOTAL_CHARS,
|
||||
) -> None:
|
||||
self.max_entries = max(1, max_entries)
|
||||
self.max_entry_chars = max(1, max_entry_chars)
|
||||
self.max_total_chars = max(1, max_total_chars)
|
||||
self._entries: deque[str] = deque()
|
||||
self._total_chars = 0
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._entries)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self._entries)
|
||||
|
||||
def __iter__(self) -> Iterator[str]:
|
||||
return reversed(self._entries)
|
||||
|
||||
def __getitem__(self, idx: int) -> str:
|
||||
return self.entries()[idx]
|
||||
|
||||
def entries(self) -> tuple[str, ...]:
|
||||
"""All entries, most recently copied first."""
|
||||
return tuple(reversed(self._entries))
|
||||
|
||||
def clear(self) -> None:
|
||||
self._entries.clear()
|
||||
self._total_chars = 0
|
||||
|
||||
def add(self, text: str, private: bool = False) -> bool:
|
||||
"""Record text, returning False when it is deliberately not recorded."""
|
||||
if private or not text or not text.strip():
|
||||
return False
|
||||
if len(text) > self.max_entry_chars:
|
||||
return False
|
||||
# A repeated copy moves the entry to the top instead of duplicating it
|
||||
with suppress(ValueError):
|
||||
self._entries.remove(text)
|
||||
self._total_chars -= len(text)
|
||||
self._entries.append(text)
|
||||
self._total_chars += len(text)
|
||||
while self._entries and (len(self._entries) > self.max_entries or self._total_chars > self.max_total_chars):
|
||||
self._total_chars -= len(self._entries.popleft())
|
||||
return True
|
||||
|
||||
def search(self, query: str) -> tuple[str, ...]:
|
||||
"""Entries matching query, best match first, newest first among equal scores."""
|
||||
if not query.strip():
|
||||
return self.entries()
|
||||
scored = []
|
||||
for idx, text in enumerate(self.entries()):
|
||||
score = match_score(query, text)
|
||||
if score > -1:
|
||||
scored.append((score, idx, text))
|
||||
scored.sort(key=lambda x: (x[0], x[1]))
|
||||
return tuple(text for _, _, text in scored)
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from kitty.clipboard_history import ClipboardHistory, match_score
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestClipboardHistory(BaseTest):
|
||||
def test_newest_first(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
self.assertFalse(h)
|
||||
self.assertTrue(h.add('one'))
|
||||
self.assertTrue(h.add('two'))
|
||||
self.ae(h.entries(), ('two', 'one'))
|
||||
self.ae(list(h), ['two', 'one'])
|
||||
self.ae(len(h), 2)
|
||||
self.ae(h[0], 'two')
|
||||
|
||||
def test_empty_and_blank_text_is_ignored(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
self.assertFalse(h.add(''))
|
||||
self.assertFalse(h.add(' \n\t'))
|
||||
self.ae(len(h), 0)
|
||||
|
||||
def test_private_entries_are_never_recorded(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
self.assertFalse(h.add('hunter2', private=True))
|
||||
self.ae(len(h), 0)
|
||||
self.assertTrue(h.add('public'))
|
||||
self.assertFalse(h.add('hunter2', private=True))
|
||||
self.ae(h.entries(), ('public',))
|
||||
|
||||
def test_duplicates_move_to_the_top(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
for x in ('a', 'b', 'a'):
|
||||
h.add(x)
|
||||
self.ae(h.entries(), ('a', 'b'))
|
||||
|
||||
def test_entry_count_is_bounded(self) -> None:
|
||||
h = ClipboardHistory(max_entries=3)
|
||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
||||
h.add(x)
|
||||
self.ae(h.entries(), ('e', 'd', 'c'))
|
||||
|
||||
def test_total_size_is_bounded(self) -> None:
|
||||
h = ClipboardHistory(max_entries=100, max_total_chars=10)
|
||||
h.add('12345')
|
||||
h.add('67890')
|
||||
h.add('abcde')
|
||||
self.assertLessEqual(sum(len(x) for x in h.entries()), 10)
|
||||
self.ae(h.entries()[0], 'abcde')
|
||||
|
||||
def test_oversized_entries_are_ignored(self) -> None:
|
||||
h = ClipboardHistory(max_entry_chars=5)
|
||||
self.assertFalse(h.add('123456'))
|
||||
self.assertTrue(h.add('12345'))
|
||||
self.ae(h.entries(), ('12345',))
|
||||
|
||||
def test_clear(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
h.add('a')
|
||||
h.clear()
|
||||
self.ae(len(h), 0)
|
||||
self.assertFalse(h)
|
||||
# clearing resets the accounting, so new entries are kept even after large ones
|
||||
self.assertTrue(h.add('b'))
|
||||
self.ae(h.entries(), ('b',))
|
||||
|
||||
def test_search(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
for x in ('make test', 'make build', 'git status', 'echo make'):
|
||||
h.add(x)
|
||||
self.ae(h.search(''), h.entries())
|
||||
self.ae(h.search(' '), h.entries())
|
||||
# An earlier substring match ranks first, ties keep the newest entry first
|
||||
self.ae(h.search('make'), ('make build', 'make test', 'echo make'))
|
||||
self.ae(h.search('mkb'), ('make build',))
|
||||
self.ae(h.search('zzz'), ())
|
||||
|
||||
def test_substring_matches_rank_before_subsequences(self) -> None:
|
||||
h = ClipboardHistory()
|
||||
h.add('xkcd')
|
||||
h.add('kcd')
|
||||
self.ae(h.search('kcd'), ('kcd', 'xkcd'))
|
||||
|
||||
def test_match_score(self) -> None:
|
||||
self.ae(match_score('', 'anything'), 0)
|
||||
self.ae(match_score('abc', 'xxabc'), 2)
|
||||
self.assertGreater(match_score('abc', 'a-x-b-x-c'), 2)
|
||||
self.ae(match_score('abc', 'cba'), -1)
|
||||
self.ae(match_score('Abc', 'xxabc'), 2) # matching is case insensitive
|
||||
|
||||
def test_no_persistence_api(self) -> None:
|
||||
# The history is deliberately memory only: there is no save/load entry point to call
|
||||
h = ClipboardHistory()
|
||||
self.assertFalse(hasattr(h, 'save'))
|
||||
self.assertFalse(hasattr(h, 'load'))
|
||||
self.assertFalse(hasattr(h, 'path'))
|
||||
Reference in new issue
Block a user