Merge branch 'feat/clipboard-history'
Keep an in-memory history of copied text, browsable and searchable from keyboard shortcuts, without writing anything to disk.
This commit is contained in:
10 files changed
+385
-9
No files matched your search
@@ -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 ''
|
||||
|
||||
|
||||
+24
-4
@@ -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(...)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/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 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)
|
||||
@@ -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)
|
||||
|
||||
@@ -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',
|
||||
|
||||
Generated
+1
@@ -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);
|
||||
|
||||
Generated
+5
-1
@@ -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
|
||||
|
||||
Reference in new issue
Block a user