diff --git a/docs/changelog.rst b/docs/changelog.rst index c2e20c7..890c22e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -232,6 +232,11 @@ Detailed list of changes that ends a command without reporting a status (:code:`OSC 133;D` with no argument) now shows :code:`0` instead of an empty status. +- 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 ` in a left dock by default, instead of requiring a manual mapping. This takes the key over from :ac:`open_url`; remap diff --git a/docs/clipboard.rst b/docs/clipboard.rst index 7f64957..08bf46b 100644 --- a/docs/clipboard.rst +++ b/docs/clipboard.rst @@ -264,3 +264,35 @@ 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 picker numbers the entries: type the number next to the entry you want to +paste, or press :kbd:`Escape` to cancel. + +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. + +Both actions have a default shortcut: :kbd:`kitty_mod+alt+v` opens the +history and :kbd:`kitty_mod+alt+f` asks for a fuzzy query before showing the +list. To use different keys, add for example to :file:`kitty.conf`: + +.. code-block:: conf + + map kitty_mod+alt+h paste_from_clipboard_history + map kitty_mod+alt+g 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. diff --git a/kitty/boss.py b/kitty/boss.py index 7702622..5a6a589 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -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,48 @@ 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] + # The picker is itself the active window while it is open, so keep the window the user was + # working in to paste into once it closes. The window can be gone by then. + target = self.window_for_dispatch or self.active_window + + def chosen(text: str | None) -> None: + if text and target is not None: + w = self.window_id_map.get(target.id) + if w is not None: + w.paste_with_actions(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 '' diff --git a/kitty/clipboard.py b/kitty/clipboard.py index e344af1..b807004 100644 --- a/kitty/clipboard.py +++ b/kitty/clipboard.py @@ -9,6 +9,7 @@ from gettext import gettext as _ from tempfile import TemporaryFile from typing import IO, NamedTuple, Union +from .clipboard_history import text_from_mime_data from .conf.utils import uniq from .constants import supports_primary_selection from .fast_data_types import ( @@ -96,15 +97,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 + if 'text/plain' not in self.data: + return + try: + # The payload can be a chunker rather than bytes, as writes are streamed from a temp file + text = text_from_mime_data(self.data['text/plain']) + history = getattr(get_boss(), 'clipboard_history', None) + except Exception: + return + if text and history is not None: + history.add(text, private=private) def get_text(self) -> str: parts: list[bytes] = [] @@ -309,7 +328,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(...) diff --git a/kitty/clipboard_history.py b/kitty/clipboard_history.py new file mode 100644 index 0000000..6e71029 --- /dev/null +++ b/kitty/clipboard_history.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +# 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 text_from_mime_data(data: object, max_chars: int = MAX_ENTRY_CHARS) -> str: + """Extract text from a clipboard MIME payload, or an empty string when it is not text. + + Clipboard payloads are either raw bytes or a factory returning a chunker, as the data can be + streamed from a temporary file. Only the start of the payload is materialized, since an entry + longer than max_chars is not kept anyway. + """ + limit = 4 * max_chars # a UTF-8 character takes at most four bytes + if isinstance(data, bytes | bytearray | memoryview): + raw = bytes(data[:limit]) + elif callable(data): + chunks: list[bytes] = [] + size = 0 + chunker = data() + while True: + q = chunker() + if not q: + break + chunks.append(q) + size += len(q) + if size >= limit: + break + raw = b''.join(chunks)[:limit] + else: + return '' + return raw.decode('utf-8', 'replace') + + +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) diff --git a/kitty/conf/generate.py b/kitty/conf/generate.py index 9b97aea..419c89c 100644 --- a/kitty/conf/generate.py +++ b/kitty/conf/generate.py @@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: if isinstance(option, MultiOption): mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}} func, typ = option_type_data(option) - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) for val in option: if val.add_to_default: gr = mval[val.only] @@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: func = str elif defn.has_color_table and option.is_color_table_color: func, typ = option_type_data(option) - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) t(f' ans[{option.name!r}] = {func.__name__}(val)') tc_imports.add((func.__module__, func.__name__)) cnum = int(option.name[5:]) @@ -130,7 +130,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: params = dict(inspect.signature(func).parameters) except Exception: params = {} - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) if 'dict_with_parse_results' in params: t(f' {func.__name__}(val, ans)') else: @@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: for aname, action in defn.actions.items(): option_names.add(aname) action_parsers[aname] = func = action.parser_func - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) th = get_type_hints(func) rettype = th['return'] typ = option_type_as_str(rettype) diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 56fdf1b..4be4d29 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -3959,6 +3959,15 @@ map( 'paste_from_selection shift+insert paste_from_selection', ) +map( + 'Paste from clipboard history', + 'paste_from_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+v paste_from_clipboard_history', +) +map( + 'Search the clipboard history', + 'search_clipboard_history --allow-fallback=shifted,ascii kitty_mod+alt+f search_clipboard_history', +) + map( 'Pass selection to program', 'pass_selection_to_program --allow-fallback=shifted,ascii kitty_mod+o pass_selection_to_program', diff --git a/kitty/options/to-c-generated.h b/kitty/options/to-c-generated.h index 7154bf1..5d09627 100644 --- a/kitty/options/to-c-generated.h +++ b/kitty/options/to-c-generated.h @@ -4,6 +4,7 @@ #include "to-c.h" + static void convert_from_python_font_size(PyObject *val, Options *opts) { opts->font_size = PyFloat_AsDouble(val); diff --git a/kitty/options/types.py b/kitty/options/types.py index 87ba0cd..8ba2c6e 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -902,6 +902,10 @@ defaults.map = [ KeyDefinition(trigger=SingleKey(mods=256, key=115), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_selection'), # paste_from_selection KeyDefinition(trigger=SingleKey(mods=1, key=57348), definition='paste_from_selection'), + # paste_from_clipboard_history + KeyDefinition(trigger=SingleKey(mods=258, key=118), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='paste_from_clipboard_history'), + # search_clipboard_history + KeyDefinition(trigger=SingleKey(mods=258, key=102), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='search_clipboard_history'), # pass_selection_to_program KeyDefinition(trigger=SingleKey(mods=256, key=111), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='pass_selection_to_program'), # scroll_line_up @@ -1029,7 +1033,7 @@ defaults.map = [ # command_palette KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'), # file_manager - KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=right --dock-size=60 kitten file-manager'), + KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'), # toggle_fullscreen KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'), # toggle_maximized diff --git a/kitty_tests/clipboard_history.py b/kitty_tests/clipboard_history.py new file mode 100644 index 0000000..0499011 --- /dev/null +++ b/kitty_tests/clipboard_history.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +from kitty.clipboard_history import ClipboardHistory, match_score, text_from_mime_data + +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_text_from_bytes(self) -> None: + self.ae(text_from_mime_data(b'hello'), 'hello') + self.ae(text_from_mime_data('not bytes'), '') + self.ae(text_from_mime_data(None), '') + self.ae(text_from_mime_data(b'a\xffb'), 'a\ufffdb') + + def test_text_from_chunker(self) -> None: + # OSC 52 writes are streamed, so the clipboard stores a chunker factory not bytes + chunks = [b'first ', b'second', b''] + + def factory(): + it = iter(chunks) + + def chunker(): + return next(it, b'') + + return chunker + + self.ae(text_from_mime_data(factory), 'first second') + + def test_text_from_chunker_is_bounded(self) -> None: + def factory(): + remaining = [b'x' * 1000] * 1000 + it = iter(remaining) + + def chunker(): + return next(it, b'') + + return chunker + + ans = text_from_mime_data(factory, max_chars=10) + self.assertLessEqual(len(ans), 40) + self.assertTrue(ans) + + 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'))