feat(clipboard): show the paste target and navigate the history picker

The clipboard history picker listed the entries without saying when they
were copied or which window would receive the paste, and the only way to
pick an entry was to read its hint label and type the letters, which the
picker never showed.

Each entry now carries the time it was copied and the window that will be
pasted into is named above the list, with a footer documenting the keys.
Pressing Up/Down moves the highlighted entry and Enter pastes it, through a
new --pick-from-list mode of the hints kitten that keeps the hint letters
working as before.

Fixes #49
This commit is contained in:
BlackAngelTV committed 2026-12-03 11:01:11 +01:00
1 parent 1b9e076139
commit 42c097c69a
8 files changed
+238 -44

No files matched your search

+28 -5
View File
@@ -3187,11 +3187,24 @@ class Boss:
q = ' '.join(text.split())
return q if len(q) <= 120 else q[:117] + '…'
def _choose_from_clipboard_history(self, entries: tuple[str, ...]) -> None:
def _clipboard_history_label(self, text: str, copied_at: float) -> str:
# The time an entry was copied tells apart entries that look alike
from datetime import datetime
when = datetime.fromtimestamp(copied_at).strftime('%H:%M')
return f'{when} {self._clipboard_history_preview(text) or _("(blank)")}'
def _clipboard_history_target_title(self, target: Window | None) -> str:
title = '' if target is None else ' '.join(target.title.split())
if not title:
return _('unknown window')
return title if len(title) <= 80 else title[:77] + '…'
def _choose_from_clipboard_history(self, entries: tuple[tuple[str, float], ...]) -> None:
if not entries:
self.ring_bell_if_allowed()
return
previews = [(text, self._clipboard_history_preview(text) or _('(blank)')) for text in entries]
previews = [(text, self._clipboard_history_label(text, when)) for text, when 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
@@ -3202,11 +3215,18 @@ class Boss:
if w is not None:
w.paste_with_actions(text)
self.choose_entry(_('Clipboard history'), previews, chosen)
self.choose_entry(
_('Clipboard history'),
previews,
chosen,
subtitle=_('Paste into: {}').format(self._clipboard_history_target_title(target)),
footer=_('↑/↓ move · Enter paste · Esc cancel'),
hints_args=('--pick-from-list',),
)
@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())
self._choose_from_clipboard_history(self.clipboard_history.entries_with_times())
@ac('cp', 'Search the clipboard history and paste the selected entry. See :ref:`clipboard_history`.')
def search_clipboard_history(self) -> None:
@@ -3215,7 +3235,7 @@ class Boss:
return
def query_entered(query: str) -> None:
self._choose_from_clipboard_history(self.clipboard_history.search(query))
self._choose_from_clipboard_history(self.clipboard_history.search_with_times(query))
self.get_line(
_('Search the clipboard history. Leave empty to list everything.'),
@@ -3979,6 +3999,7 @@ class Boss:
callback: Callable[[_T | str | None], None],
subtitle: str = '',
hints_args: tuple[str, ...] | None = None,
footer: str = '',
) -> Window | None:
lines = [title, subtitle, ' '] if subtitle else [title, ' ']
idx_map: list[_T | str | None] = []
@@ -3991,6 +4012,8 @@ class Boss:
lines.append(text)
else:
lines.append(fmt.format(len(idx_map), text))
if footer:
lines.append(f' {footer}')
def done(data: dict[str, Any], target_window_id: int, self: Boss) -> None:
nonlocal ans
+24 -13
View File
@@ -7,7 +7,7 @@
# help within one kitty instance, not to outlive it. Entries marked private are never recorded.
from collections import deque
from contextlib import suppress
from time import time
from typing import Iterator
DEFAULT_MAX_ENTRIES = 50
@@ -76,7 +76,7 @@ class ClipboardHistory:
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._entries: deque[tuple[str, float]] = deque()
self._total_chars = 0
def __len__(self) -> int:
@@ -86,43 +86,54 @@ class ClipboardHistory:
return bool(self._entries)
def __iter__(self) -> Iterator[str]:
return reversed(self._entries)
return iter(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(text for text, _ in reversed(self._entries))
def entries_with_times(self) -> tuple[tuple[str, float], ...]:
"""All entries with the time they were copied, most recent 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:
def add(self, text: str, private: bool = False, timestamp: float | None = None) -> 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)
for idx, (old_text, _) in enumerate(self._entries):
if old_text == text:
del self._entries[idx]
self._total_chars -= len(old_text)
break
self._entries.append((text, time() if timestamp is None else timestamp))
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())
self._total_chars -= len(self._entries.popleft()[0])
return True
def search(self, query: str) -> tuple[str, ...]:
"""Entries matching query, best match first, newest first among equal scores."""
return tuple(text for text, _ in self.search_with_times(query))
def search_with_times(self, query: str) -> tuple[tuple[str, float], ...]:
"""The entries search() returns, with the time each one was copied."""
entries = self.entries_with_times()
if not query.strip():
return self.entries()
return entries
scored = []
for idx, text in enumerate(self.entries()):
for idx, (text, when) in enumerate(entries):
score = match_score(query, text)
if score > -1:
scored.append((score, idx, text))
scored.append((score, idx, text, when))
scored.sort(key=lambda x: (x[0], x[1]))
return tuple(text for _, _, text in scored)
return tuple((text, when) for _, _, text, when in scored)