#!/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)