feat(clipboard): keep an in-memory history of copied text

This commit is contained in:
BlackAngelTV committed 2026-11-11 21:05:30 +01:00
1 parent 02f43b2ee9
commit 10981dcf00
3 files changed
+162 -4

No files matched your search

+39
View File
@@ -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
View File
@@ -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(...)
+100
View File
@@ -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)