From 42c097c69af73d9ae6832629a279cf86d7f6c64b Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Thu, 3 Dec 2026 11:01:11 +0100 Subject: [PATCH 1/2] 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 --- docs/clipboard.rst | 6 +- kittens/hints/hints_generator.go | 18 +++++ kittens/hints/main.go | 134 +++++++++++++++++++++++++------ kittens/hints/main.py | 8 ++ kittens/hints/selection_test.go | 33 ++++++++ kitty/boss.py | 33 ++++++-- kitty/clipboard_history.py | 37 ++++++--- kitty_tests/clipboard_history.py | 13 +++ 8 files changed, 238 insertions(+), 44 deletions(-) create mode 100644 kittens/hints/selection_test.go diff --git a/docs/clipboard.rst b/docs/clipboard.rst index 08bf46b..3f65cff 100644 --- a/docs/clipboard.rst +++ b/docs/clipboard.rst @@ -276,8 +276,10 @@ 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 picker lists the entries with the time each one was copied and names the +window that will receive the paste. Move the highlighted entry with :kbd:`↑` and +:kbd:`↓` and press :kbd:`Enter` to paste it, or type the letters of the hint +shown next to it. 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 diff --git a/kittens/hints/hints_generator.go b/kittens/hints/hints_generator.go index d50f5d2..a579256 100644 --- a/kittens/hints/hints_generator.go +++ b/kittens/hints/hints_generator.go @@ -66,6 +66,24 @@ func rune_to_index_map(alphabet string) *map[rune]int { return &runeToIndexMap } +// next_selection moves pos by delta positions in a list of marks choices, +// wrapping around, as the arrow keys do in the list picker. A negative pos, +// meaning nothing is selected yet, selects the first choice when moving down +// and the last one when moving up, and a stale pos falls back to the first +// choice so that the arrow keys never stop working. +func next_selection(pos, marks, delta int) int { + if marks < 1 { + return -1 + } + if pos < 0 || pos >= marks { + if delta < 0 { + return marks - 1 + } + return 0 + } + return ((pos+delta)%marks + marks) % marks +} + // decode_hint converts a hint to its corresponding index as it would appear in // the breadth-first traversal of the prefix tree generated by the given // alphabet. diff --git a/kittens/hints/main.go b/kittens/hints/main.go index 57bd953..6d9c313 100644 --- a/kittens/hints/main.go +++ b/kittens/hints/main.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "os" + "sort" "strconv" "strings" "unicode" @@ -160,6 +161,10 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { } } chosen := []*Mark{} + // The list navigation is only offered when the input is an ordered list of + // choices, see the --pick-from-list option. + pick_from_list := o.PickFromList + selected_mark := -1 lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit if err != nil { return @@ -168,8 +173,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { faint := fctx.SprintFunc("dim") hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor)) text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor)) + selected_style := fctx.SprintFunc("reverse") - highlight_mark := func(m *Mark, mark_text string) string { + highlight_mark := func(m *Mark, mark_text string, selected bool) string { hint := encode_hint(m.Index, alphabet) if current_input != "" && !strings.HasPrefix(hint, current_input) { return faint(mark_text) @@ -207,6 +213,9 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { mark_text = string(runes[hint_runes:]) } ans := hint_style(hint) + text_style(mark_text) + if selected { + ans = selected_style(ans) + } return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans) } @@ -217,7 +226,7 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { if ignore_mark_indices.Has(mark.Index) { continue } - mtext := highlight_mark(mark, ans[mark.Start:mark.End]) + mtext := highlight_mark(mark, ans[mark.Start:mark.End], pick_from_list && mark.Index == selected_mark) ans = ans[:mark.Start] + mtext + ans[mark.End:] } ans = strings.ReplaceAll(ans, "\x00", "") @@ -238,6 +247,75 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { current_text = "" } + // The marks in the order they were given, which is the order of the list + // the user sees rather than the order of the hints + ordered_indices := make([]int, 0, len(index_map)) + for idx := range index_map { + ordered_indices = append(ordered_indices, idx) + } + sort.Ints(ordered_indices) + visible_marks := func() []*Mark { + ans := make([]*Mark, 0, len(ordered_indices)) + for _, idx := range ordered_indices { + m := index_map[idx] + if m == nil || ignore_mark_indices.Has(m.Index) { + continue + } + if current_input != "" && !strings.HasPrefix(encode_hint(idx, alphabet), current_input) { + continue + } + ans = append(ans, m) + } + return ans + } + select_first := func() { + selected_mark = -1 + if marks := visible_marks(); len(marks) > 0 { + selected_mark = marks[0].Index + } + } + choose_index := func(idx int) { + m := index_map[idx] + if m == nil { + current_input = "" + current_text = "" + draw_screen() + return + } + chosen = append(chosen, m) + ignore_mark_indices.Add(m.Index) + if o.Multiple { + reset() + select_first() + draw_screen() + } else { + lp.Quit(0) + } + } + select_by := func(delta int) { + marks := visible_marks() + if len(marks) == 0 { + return + } + pos := -1 + for i, m := range marks { + if m.Index == selected_mark { + pos = i + break + } + } + if pos < 0 { + pos = 0 + } + pos = next_selection(pos, len(marks), delta) + selected_mark = marks[pos].Index + current_text = "" + draw_screen() + } + if pick_from_list { + select_first() + } + lp.OnInitialize = func() (string, error) { lp.SetCursorVisible(false) lp.SetWindowTitle(window_title) @@ -295,13 +373,15 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { } if len(matches) == 1 { chosen = append(chosen, matches[0]) - if o.Multiple { - ignore_mark_indices.Add(matches[0].Index) - reset() - } else { + ignore_mark_indices.Add(matches[0].Index) + if !o.Multiple { lp.Quit(0) return nil } + reset() + } + if pick_from_list { + select_first() } current_text = "" draw_screen() @@ -310,7 +390,14 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { } lp.OnKeyEvent = func(ev *loop.KeyEvent) error { - if ev.MatchesPressOrRepeat("backspace") { + if pick_from_list && (ev.MatchesPressOrRepeat("up") || ev.MatchesPressOrRepeat("down")) { + ev.Handled = true + if ev.MatchesPressOrRepeat("up") { + select_by(-1) + } else { + select_by(1) + } + } else if ev.MatchesPressOrRepeat("backspace") { ev.Handled = true r := []rune(current_input) if len(r) > 0 { @@ -318,26 +405,25 @@ func main(_ *cli.Command, o *Options, args []string) (rc int, err error) { current_input = string(r) current_text = "" } + if pick_from_list { + select_first() + } draw_screen() - } else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") { + } else if ev.MatchesPressOrRepeat("enter") { ev.Handled = true - if current_input != "" { - char_to_index := rune_to_index_map(alphabet) - idx := decode_hint(current_input, char_to_index) - if m := index_map[idx]; m != nil { - chosen = append(chosen, m) - ignore_mark_indices.Add(idx) - if o.Multiple { - reset() - draw_screen() - } else { - lp.Quit(0) - } - } else { - current_input = "" - current_text = "" - draw_screen() + if pick_from_list { + if selected_mark > -1 { + choose_index(selected_mark) + } else if marks := visible_marks(); len(marks) > 0 { + choose_index(marks[0].Index) } + } else if current_input != "" { + choose_index(decode_hint(current_input, rune_to_index_map(alphabet))) + } + } else if ev.MatchesPressOrRepeat("space") { + ev.Handled = true + if !pick_from_list && current_input != "" { + choose_index(decode_hint(current_input, rune_to_index_map(alphabet))) } } else if ev.MatchesPressOrRepeat("esc") { if o.Multiple { diff --git a/kittens/hints/main.py b/kittens/hints/main.py index 8da6c16..bbb5989 100644 --- a/kittens/hints/main.py +++ b/kittens/hints/main.py @@ -271,6 +271,14 @@ elsewhere. See {hints_url} for details. --window-title The title for the hints window, default title is based on the type of text being hinted. + + +--pick-from-list +type=bool-set +The input is an ordered list of choices rather than text to search, as used by the +clipboard history picker. The first choice is selected and the arrow keys move the +selection, so a choice can be picked with :kbd:`Enter` instead of typing the +letters of its hint. """.format( default_regex=DEFAULT_REGEX, line='{{line}}', diff --git a/kittens/hints/selection_test.go b/kittens/hints/selection_test.go new file mode 100644 index 0000000..f67ddd6 --- /dev/null +++ b/kittens/hints/selection_test.go @@ -0,0 +1,33 @@ +// License: GPLv3 Copyright: 2026, Kovid Goyal, + +package hints + +import "testing" + +func TestNextSelection(t *testing.T) { + cases := []struct { + pos, marks, delta, expected int + }{ + // Nothing selected yet: down selects the first choice, up the last one + {-1, 3, 0, 0}, + {-1, 3, 1, 0}, + {-1, 3, -1, 2}, + // Moving past either end wraps around + {0, 3, 1, 1}, + {2, 3, 1, 0}, + {0, 3, -1, 2}, + {1, 1, 2, 0}, + {0, 3, 4, 1}, + {0, 3, -4, 2}, + // A stale position falls back to the first choice + {5, 3, 1, 0}, + // An empty list has nothing to select + {-1, 0, 1, -1}, + {0, 0, -1, -1}, + } + for _, c := range cases { + if got := next_selection(c.pos, c.marks, c.delta); got != c.expected { + t.Fatalf("next_selection(%d, %d, %d) = %d, expected %d", c.pos, c.marks, c.delta, got, c.expected) + } + } +} diff --git a/kitty/boss.py b/kitty/boss.py index 562ebea..8e508f8 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -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 diff --git a/kitty/clipboard_history.py b/kitty/clipboard_history.py index 6e71029..a48d9fd 100644 --- a/kitty/clipboard_history.py +++ b/kitty/clipboard_history.py @@ -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) diff --git a/kitty_tests/clipboard_history.py b/kitty_tests/clipboard_history.py index 0499011..fd269eb 100644 --- a/kitty_tests/clipboard_history.py +++ b/kitty_tests/clipboard_history.py @@ -78,6 +78,19 @@ class TestClipboardHistory(BaseTest): self.ae(h.search('mkb'), ('make build',)) self.ae(h.search('zzz'), ()) + def test_entries_carry_the_time_they_were_copied(self) -> None: + h = ClipboardHistory() + self.assertTrue(h.add('first', timestamp=100.0)) + self.assertTrue(h.add('second', timestamp=200.0)) + self.ae(h.entries(), ('second', 'first')) + self.ae(h.entries_with_times(), (('second', 200.0), ('first', 100.0))) + # A repeated copy moves the text and its new time to the top + self.assertTrue(h.add('first', timestamp=300.0)) + self.ae(h.entries(), ('first', 'second')) + self.ae(h.entries_with_times(), (('first', 300.0), ('second', 200.0))) + self.ae(h.search_with_times('sec'), (('second', 200.0),)) + self.ae(h.search('sec'), ('second',)) + def test_substring_matches_rank_before_subsequences(self) -> None: h = ClipboardHistory() h.add('xkcd') From 43d01ab87e008b7afee26beb82d069a1e9959087 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Thu, 3 Dec 2026 11:01:12 +0100 Subject: [PATCH 2/2] chore(release): bump the fork version to 0.1.16 --- README.md | 2 +- docs/changelog.rst | 5 ++++- kitty/launcher/main.c | 4 ++-- packaging/PKGBUILD | 2 +- tools/cli/help.go | 2 +- version | 2 +- 6 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3bc74d7..9a6826e 100644 --- a/README.md +++ b/README.md @@ -302,7 +302,7 @@ _branch=feat/file-manager-panel ### Publication automatique `version`, à la racine, est la source de vérité des releases. Il suit la version -du fork FWS (`0.1.15`), pas la version amont de kitty embarquée dans le paquet : +du fork FWS (`0.1.16`), pas la version amont de kitty embarquée dans le paquet : c'est elle qui nomme le tag, la release et le paquet `fws-kitty--`. Il doit rester égal à `pkgver` dans `packaging/PKGBUILD` et à la version affichée par `fws-kitty` diff --git a/docs/changelog.rst b/docs/changelog.rst index 6fb8c0c..619a991 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -235,7 +235,10 @@ Detailed list of changes - 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. + never recorded. See :ref:`clipboard_history` for details. The picker shows + when each entry was copied and the title of the window the text will be + pasted into, and :kbd:`↑`/:kbd:`↓` select an entry so that :kbd:`Enter` + pastes it without typing the letters of a hint. - kitty now remembers the state of the session that was in use when it exited, in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that diff --git a/kitty/launcher/main.c b/kitty/launcher/main.c index d7d8613..0eb2086 100644 --- a/kitty/launcher/main.c +++ b/kitty/launcher/main.c @@ -424,10 +424,10 @@ handle_fast_commandline(CLISpec *cli_spec, const char *instance_group_prefix) { if (get_bool_cli_val(cli_spec, "version")) { if (isatty(STDOUT_FILENO)) { printf("\x1b[3mkitty\x1b[23m \x1b[32m%s\x1b[39m created by \x1b[1;34mKovid Goyal\x1b[22;39m\n", KITTY_VERSION); - printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.15\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n"); + printf("\x1b[3mfws-kitty\x1b[23m \x1b[32m0.1.16\x1b[39m by \x1b[1;34mBlackAngelTV\x1b[22;39m\n"); } else { printf("kitty %s created by Kovid Goyal\n", KITTY_VERSION); - printf("fws-kitty 0.1.15 by BlackAngelTV\n"); + printf("fws-kitty 0.1.16 by BlackAngelTV\n"); } exit(0); } diff --git a/packaging/PKGBUILD b/packaging/PKGBUILD index e1e51f7..afddd8c 100644 --- a/packaging/PKGBUILD +++ b/packaging/PKGBUILD @@ -13,7 +13,7 @@ pkgname=fws-kitty # Fork version from the version file: it names the release and the package. # The upstream kitty release built inside is tracked by _kittyver below. -pkgver=0.1.15 +pkgver=0.1.16 pkgrel=1 pkgdesc='Fast, feature-rich, GPU based terminal (FWS fork with the file-manager kitten)' arch=('x86_64' 'aarch64') diff --git a/tools/cli/help.go b/tools/cli/help.go index f0f3ae4..754ff65 100644 --- a/tools/cli/help.go +++ b/tools/cli/help.go @@ -31,7 +31,7 @@ func ShowError(err error) { func (self *Command) version_string(formatter *markup.Context) string { return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal")) + - fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.15"), "by", formatter.Title("BlackAngelTV")) + fmt.Sprintln(formatter.Italic("fws-kitty"), formatter.Opt("0.1.16"), "by", formatter.Title("BlackAngelTV")) } func (self *Command) ShowVersion() { diff --git a/version b/version index c34958a..e8e277f 100644 --- a/version +++ b/version @@ -1 +1 @@ -0.1.15 +0.1.16