From bfc97997a105abecb84a9ade030dc26df8538ced Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Fri, 13 Nov 2026 08:03:03 +0100 Subject: [PATCH] feat(shortcuts): add a leader key tree and palette remapping Expose the multi-key mappings starting at the configured leader key in a which-key panel, so that continuations are discoverable as soon as the prefix is pressed. Both the panel and the command palette read the same structured mapping data, and the palette can now write a new mapping for the selected action. --- kittens/command_palette/main.go | 173 +++++++++++++++++++++++++-- kittens/command_palette/main.py | 62 +++++++++- kittens/command_palette/main_test.go | 44 +++++++ kitty/boss.py | 9 ++ kitty/config.py | 40 +++++++ kitty/keys.py | 33 ++++- kitty/options/definition.py | 16 +++ kitty/options/parse.py | 3 + kitty/options/types.py | 2 + kitty_tests/command_palette.py | 49 ++++++++ 10 files changed, 418 insertions(+), 13 deletions(-) diff --git a/kittens/command_palette/main.go b/kittens/command_palette/main.go index 4348059..d90be82 100644 --- a/kittens/command_palette/main.go +++ b/kittens/command_palette/main.go @@ -38,6 +38,15 @@ type InputData struct { Mouse []Binding `json:"mouse"` ModeOrder []string `json:"mode_order"` CategoryOrder map[string][]string `json:"category_order"` + Leader *LeaderData `json:"leader"` +} + +// LeaderData is the which-key tree shown when the configured leader key is +// pressed. Key holds the key to press after the leader, not the full shortcut. +type LeaderData struct { + Prefix string `json:"prefix"` + Title string `json:"title"` + Bindings []Binding `json:"bindings"` } // wordToken represents a single word extracted from column text, with its @@ -277,6 +286,11 @@ type Handler struct { keyboard_shortcuts []*config.KeyAction read_only bool data_file string + leader *LeaderData + remap_mode bool + remap_binding *Binding + remap_key string + remap_action string } // initialize sets up the TUI: screen size, cursor, cached settings, and initial data load. @@ -293,11 +307,20 @@ func (h *Handler) initialize() (string, error) { if h.read_only { title = "Keyboard shortcuts" } + if h.input_data.Leader != nil { + title = h.input_data.Leader.Title + if title == "" { + title = "Leader keys" + } + } h.lp.SetWindowTitle(title) if h.read_only { // A reference panel is about bindings, not about actions without one. h.show_unmapped = false + } else if h.input_data.Leader != nil { + // The leader panel lists exactly the keys that are available. + h.show_unmapped = true } else { // Initialize with ShowUnmapped: true as the default; Load() returns this // default when no cache file exists yet. @@ -350,10 +373,26 @@ func (h *Handler) parseData(data []byte) error { return fmt.Errorf("failed to parse input data: %w", err) } + if h.input_data.Leader != nil { + h.leader = h.input_data.Leader + h.flattenLeaderBindings() + return nil + } h.flattenBindings() return nil } +// flattenLeaderBindings turns the leader tree produced by Python into display +// items. The key column already holds only the key to press after the leader. +func (h *Handler) flattenLeaderBindings() { + for _, b := range h.input_data.Leader.Bindings { + b.Category = "Leader" + b.Mode = "" + b.IsMouse = false + h.all_items = append(h.all_items, bindingToDisplayItem(b)) + } +} + // bindingToDisplayItem converts a Binding into a DisplayItem with pre-tokenized // words for word-level matching. func bindingToDisplayItem(b Binding) DisplayItem { @@ -595,7 +634,9 @@ func (h *Handler) draw_screen() { h.lp.QueueWriteString(h.query) // Draw results - if h.query == "" { + if h.leader != nil { + h.drawFlatResults(resultsStartY, resultsHeight, width) + } else if h.query == "" { h.drawGroupedResults(resultsStartY, resultsHeight, width) } else { h.drawFlatResults(resultsStartY, resultsHeight, width) @@ -615,12 +656,24 @@ func (h *Handler) draw_screen() { unmappedToggleLabel = "Hide" } footer := "" - if !h.read_only { - footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run " + if h.leader != nil { + footer = h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Close " + + h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " + + h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run or press the next key" + } else if h.remap_mode { + footer = h.lp.SprintStyled("fg=bright-yellow", "Press the new shortcut") + " " + + h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Cancel" + } else { + if !h.read_only { + footer = h.lp.SprintStyled("fg=bright-yellow", "[Enter]") + " Run " + } + footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " + + h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " + + h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped" + if !h.read_only { + footer += " " + h.lp.SprintStyled("fg=bright-yellow", "[Ctrl+R]") + " Remap" + } } - footer += h.lp.SprintStyled("fg=bright-yellow", "[Esc]") + " Quit " + - h.lp.SprintStyled("fg=bright-yellow", "\u2191\u2193") + " Navigate " + - h.lp.SprintStyled("fg=bright-yellow", "[F12]") + " " + unmappedToggleLabel + " unmapped" matchCount := "" if h.query != "" { matchCount = fmt.Sprintf(" %d/%d", len(h.filtered_idx), len(h.all_items)) @@ -695,7 +748,9 @@ func (h *Handler) drawFlatResults(startY, maxRows, width int) { b := &item.binding keyDisplay := keyDisplayText(b) catSuffix := "" - if b.Mode != "" { + if h.leader != nil { + // Leader rows have no category to disambiguate. + } else if b.Mode != "" { catSuffix = fmt.Sprintf(" [%s/%s]", b.Mode, b.Category) } else { catSuffix = fmt.Sprintf(" [%s]", b.Category) @@ -861,14 +916,14 @@ func (h *Handler) drawBindingLine(filteredIdx, width int, isSelected bool) { } // Render category suffix (only present in flat / search-results mode) - if h.query != "" { + if h.query != "" && h.leader == nil { h.drawCategorySuffix(b, mi, baseStyle, matchStyle) } // For selected rows, pad the rest of the line with reverse video if isSelected { rendered := 4 + wcswidth.Stringwidth(keyDisplay) + paddingLen + 1 + wcswidth.Stringwidth(actionDisplay) - if h.query != "" { + if h.query != "" && h.leader == nil { rendered += categorySuffixWidth(b) } if pad := width - rendered; pad > 0 { @@ -916,6 +971,25 @@ func (h *Handler) onMouseEvent(ev *loop.MouseEvent) error { // onKeyEvent handles keyboard input for navigation, selection, and query editing. func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error { + if h.remap_mode { + ev.Handled = true + if ev.MatchesPressOrRepeat("escape") || ev.MatchesPressOrRepeat("ctrl+c") { + h.remap_mode, h.remap_binding = false, nil + h.draw_screen() + return nil + } + if ev.Type&(loop.PRESS|loop.REPEAT) == 0 { + return nil + } + spec := keySpecForRemap(ev) + if spec == "" || h.remap_binding == nil { + h.lp.Beep() + return nil + } + h.remap_key, h.remap_action = spec, h.remap_binding.Definition + h.lp.Quit(0) + return nil + } if ev.MatchesPressOrRepeat("escape") { ev.Handled = true if h.query != "" { @@ -996,6 +1070,24 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error { } return nil } + if ev.MatchesPressOrRepeat("ctrl+r") && !h.read_only && h.leader == nil { + ev.Handled = true + if b := h.selectedBinding(); b != nil && !b.IsMouse { + h.remap_mode, h.remap_binding = true, b + h.draw_screen() + } else { + h.lp.Beep() + } + return nil + } + if h.leader != nil { + if b := h.matchLeaderBinding(ev); b != nil { + ev.Handled = true + h.leader_trigger(b) + return nil + } + return nil + } if ev.MatchesPressOrRepeat("f12") { ev.Handled = true h.show_unmapped = !h.show_unmapped @@ -1010,8 +1102,19 @@ func (h *Handler) onKeyEvent(ev *loop.KeyEvent) error { return nil } -// onText handles typed characters, appending them to the search query. +// onText handles typed characters, appending them to the search query, or +// running the binding whose key was typed in the leader panel. func (h *Handler) onText(text string, from_key_event bool, in_bracketed_paste bool) error { + if h.leader != nil { + for i := range h.all_items { + if b := &h.all_items[i].binding; b.Key != "" && strings.EqualFold(b.Key, text) { + h.leader_trigger(b) + return nil + } + } + h.lp.Beep() + return nil + } h.query += text h.updateFilter() h.draw_screen() @@ -1036,6 +1139,49 @@ func (h *Handler) moveSelection(delta int) { h.draw_screen() } +// matchLeaderBinding finds the leader entry whose key matches the event. +func (h *Handler) matchLeaderBinding(ev *loop.KeyEvent) *Binding { + for i := range h.all_items { + if b := &h.all_items[i].binding; b.Key != "" && ev.MatchesPressOrRepeat(b.Key) { + return b + } + } + return nil +} + +// leader_trigger runs a leader entry immediately, without waiting for the rest +// of a longer multi-key sequence. +func (h *Handler) leader_trigger(b *Binding) { + h.result = b.Definition + h.lp.Quit(0) +} + +// keySpecForRemap renders a key event in kitty.conf syntax so that the palette +// can write a map directive for it. +func keySpecForRemap(ev *loop.KeyEvent) string { + mods := ev.Mods.WithoutLocks() + parts := make([]string, 0, 4) + for _, m := range []struct { + mod loop.KeyModifiers + name string + }{{loop.CTRL, "ctrl"}, {loop.ALT, "alt"}, {loop.SHIFT, "shift"}, {loop.SUPER, "super"}, {loop.HYPER, "hyper"}, {loop.META, "meta"}} { + if mods&m.mod != 0 { + parts = append(parts, m.name) + } + } + key := ev.Key + if key == "" { + key = ev.Text + } + if key == "" { + return "" + } + if len(key) == 1 && key[0] >= 'A' && key[0] <= 'Z' { + key = strings.ToLower(key) + } + return strings.Join(append(parts, key), "+") +} + // triggerSelected sets the selected binding's definition as the result and exits. func (h *Handler) triggerSelected() { if h.read_only { @@ -1085,7 +1231,12 @@ func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) { return } rc = lp.ExitCode() - if handler.result != "" { + if handler.remap_key != "" { + s, serr := output(map[string]string{"remap_key": handler.remap_key, "remap_action": handler.remap_action}) + if serr == nil { + fmt.Println(s) + } + } else if handler.result != "" { s, serr := output(map[string]string{"action": handler.result}) if serr == nil { fmt.Println(s) diff --git a/kittens/command_palette/main.py b/kittens/command_palette/main.py index 7db3d36..3894ab1 100644 --- a/kittens/command_palette/main.py +++ b/kittens/command_palette/main.py @@ -318,6 +318,52 @@ def collect_keys_data(opts: Any) -> dict[str, Any]: } +def collect_leader_data(opts: Any, prefix: Any, definitions: Any = None) -> dict[str, Any]: + """Build the data for the leader/which-key panel from sequence mappings. + + Only the first key after the leader is listed: that is the key the user has + to press next, matching how which-key panels present prefix trees. When the + mapping needs more keys, the full definition is still shown in the action + column and selecting it runs the action directly. + """ + from kitty.types import Shortcut + + action_to_group, action_to_help, action_to_long_help = build_action_lookups() + if definitions is None: + definitions = [] + for defns in opts.keyboard_modes[''].keymap.values(): + for d in defns: + if d.is_sequence and d.trigger == prefix: + definitions.append(d) + + bindings: list[dict[str, str]] = [] + seen: set[str] = set() + for d in definitions: + if not d.is_sequence or not d.rest: + continue + key_repr = Shortcut((d.rest[0],)).human_repr(opts.kitty_mod) + if key_repr in seen: + continue + seen.add(key_repr) + action_name, category, alias = classify_action(d.definition, opts.alias_map, action_to_group) + entry: dict[str, str] = { + 'key': key_repr, + 'action': action_name, + 'action_display': d.human_repr(), + 'definition': d.definition, + 'help': action_to_help.get(action_name, ''), + 'long_help': action_to_long_help.get(action_name, ''), + 'category': category, + } + if alias: + entry['alias'] = alias + bindings.append(entry) + bindings.sort(key=lambda b: b['key']) + prefix_repr = Shortcut((prefix,)).human_repr(opts.kitty_mod) if prefix is not None else '' + title = f'Leader keys ({prefix_repr})' if prefix_repr else 'Leader keys' + return {'leader': {'prefix': prefix_repr, 'title': title, 'bindings': bindings}} + + def main(args: list[str]) -> None: raise SystemExit('This kitten must be used only from a kitty.conf mapping') @@ -330,7 +376,21 @@ def callback(target_window_id: int, action: str, timer_id: int | None) -> None: @result_handler(has_ready_notification=True) def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None: - if data and (action := data.get('action')): + if not data: + return + remap_key, remap_action = data.get('remap_key'), data.get('remap_action') + if remap_key and remap_action: + from kitty.config import append_map_to_config + + try: + path = append_map_to_config(remap_key, remap_action) + boss.load_config_file() + except Exception as err: + boss.show_error('Failed to remap shortcut', f'Could not update {remap_key} in the config file: {err}') + else: + print(f'Mapped {remap_key} to {remap_action} in {path}', flush=True) + return + if action := data.get('action'): # run action after event loop tick so command palette overlay is closed add_timer(partial(callback, target_window_id, action), 0, False) diff --git a/kittens/command_palette/main_test.go b/kittens/command_palette/main_test.go index f76ee01..2197d4d 100644 --- a/kittens/command_palette/main_test.go +++ b/kittens/command_palette/main_test.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" "testing" + + "github.com/kovidgoyal/kitty/tools/tui/loop" ) // testBinding creates a Binding where Action, ActionDisplay, and Definition all @@ -120,6 +122,48 @@ func newTestHandler() *Handler { build() } +func TestLeaderPanel(t *testing.T) { + h := &Handler{} + data := []byte(`{"leader":{"prefix":"ctrl+space","title":"Leader keys","bindings":[{"key":"n","action":"new_os_window","action_display":"new_os_window","definition":"new_os_window"},{"key":"shift+w","action":"new_window","action_display":"new_window","definition":"new_window"}]}}`) + if err := h.parseData(data); err != nil { + t.Fatal(err) + } + if h.leader == nil { + t.Fatal("expected leader mode to be active") + } + if len(h.all_items) != 2 { + t.Fatalf("expected 2 leader entries, got %d", len(h.all_items)) + } + if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "n"}); b == nil || b.Definition != "new_os_window" { + t.Fatalf("expected n to run new_os_window, got %+v", b) + } + if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "w", Mods: loop.SHIFT, ShiftedKey: "W"}); b == nil || b.Definition != "new_window" { + t.Fatalf("expected shift+w to run new_window, got %+v", b) + } + if b := h.matchLeaderBinding(&loop.KeyEvent{Type: loop.PRESS, Key: "x"}); b != nil { + t.Fatalf("expected x to match nothing, got %+v", b) + } +} + +func TestKeySpecForRemap(t *testing.T) { + cases := []struct { + ev loop.KeyEvent + expected string + }{ + {loop.KeyEvent{Type: loop.PRESS, Key: "a"}, "a"}, + {loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.SHIFT}, "shift+a"}, + {loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.SHIFT}, "ctrl+shift+a"}, + {loop.KeyEvent{Type: loop.PRESS, Key: "a", Mods: loop.CTRL | loop.CAPS_LOCK}, "ctrl+a"}, + {loop.KeyEvent{Type: loop.PRESS, Key: "", Text: "é"}, "é"}, + {loop.KeyEvent{Type: loop.PRESS, Key: "", Text: ""}, ""}, + } + for _, c := range cases { + if got := keySpecForRemap(&c.ev); got != c.expected { + t.Fatalf("keySpecForRemap(%+v) = %q, expected %q", c.ev, got, c.expected) + } + } +} + func TestFlattenAllBindings(t *testing.T) { h := newTestHandler() // 5 default mode + 2 mw mode + 2 mouse = 9 diff --git a/kitty/boss.py b/kitty/boss.py index 1231c61..562ebea 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -2856,6 +2856,15 @@ class Boss: data = collect_keys_data(get_options()) self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch) + def show_leader_keymap(self, prefix: Any, definitions: Any = None) -> None: + """Show the keys available under the leader prefix in the palette overlay.""" + from kittens.command_palette.main import collect_leader_data + + data = collect_leader_data(get_options(), prefix, definitions) + if not data['leader']['bindings']: + return + self.run_kitten_with_metadata('command-palette', input_data=json.dumps(data), window=self.window_for_dispatch) + @ac( 'tab', """ diff --git a/kitty/config.py b/kitty/config.py index 2c1a764..c444182 100644 --- a/kitty/config.py +++ b/kitty/config.py @@ -80,6 +80,45 @@ def prepare_config_file_for_editing() -> str: return defconf +def finalize_leader(opts: Options) -> None: + """Validate the leader shortcut once so that key handling can use it directly.""" + from .keys import leader_key_from_options + + try: + opts.leader_key = leader_key_from_options(opts) + except Exception as err: + opts.leader_key = None + log_error(f'Ignoring invalid leader shortcut: {opts.leader}. Error: {err}') + + +def append_map_to_config(key: str, definition: str, conf_path: str = '') -> str: + """Append a map directive to the user config, creating it when needed. + + The path is returned so that callers can report it. Only the mapping is + written, existing configuration is never rewritten. + """ + from .constants import config_dir + + path = conf_path or os.path.join(config_dir, 'kitty.conf') + parent = os.path.dirname(path) + if parent: + with suppress(FileExistsError): + os.makedirs(parent) + needs_newline = False + try: + if os.path.getsize(path) > 0: + with open(path, 'rb') as f: + f.seek(-1, os.SEEK_END) + needs_newline = f.read(1) != b'\n' + except FileNotFoundError: + pass + with open(path, 'ab') as f: + if needs_newline: + f.write(b'\n') + f.write(f'map {key} {definition}\n'.encode('utf-8')) + return path + + def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None: defns: list[KeyDefinition] = [] for d in opts.map: @@ -118,6 +157,7 @@ def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = No items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on] items.append(defn) opts.keyboard_modes = modes + finalize_leader(opts) def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None: diff --git a/kitty/keys.py b/kitty/keys.py index c8c7e65..9dc028a 100644 --- a/kitty/keys.py +++ b/kitty/keys.py @@ -23,7 +23,7 @@ from .fast_data_types import ( set_ignore_os_keyboard_processing, ) from .options.types import Options -from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions +from .options.utils import KeyboardMode, KeyDefinition, KeyFallbackType, KeyMap, KeyMapOptions, parse_shortcut from .typing_compat import ScreenType if TYPE_CHECKING: @@ -40,6 +40,14 @@ def keyboard_mode_name(screen: ScreenType) -> str: return 'application' if screen.cursor_key_mode else 'normal' +def leader_key_from_options(opts: Options) -> SingleKey | None: + """The shortcut that opens the leader tree, or None when disabled.""" + raw = (getattr(opts, 'leader', '') or '').strip() + if not raw or raw.lower() in ('none', 'no', 'off'): + return None + return parse_shortcut(raw) + + def get_shortcut(keymap: KeyMap, ev: KeyEvent) -> list[KeyDefinition] | None: mods = ev.mods & mod_mask ans = keymap.get(SingleKey(mods, False, ev.key)) @@ -111,6 +119,24 @@ class Mappings: self.keyboard_modes[''].keymap = km = km.copy() for sc in self.global_shortcuts.values(): km.pop(sc, None) + self.leader_key: SingleKey | None = getattr(self.get_options(), 'leader_key', None) + if self.leader_key is None: + try: + self.leader_key = leader_key_from_options(self.get_options()) + except Exception: + # An invalid leader is reported when the config is loaded. + self.leader_key = None + + def leader_continuations(self, mode: KeyboardMode) -> list[KeyDefinition]: + """Multi-key mappings whose first key is the leader key.""" + ans: list[KeyDefinition] = [] + if self.leader_key is None: + return ans + for defns in mode.keymap.values(): + for d in defns: + if d.is_sequence and d.trigger == self.leader_key: + ans.append(d) + return ans def clear_keyboard_modes(self) -> None: had_mode = bool(self.keyboard_mode_stack) @@ -212,6 +238,11 @@ class Mappings: # Handles shortcuts, return True if the key was consumed is_root_mode = not self.keyboard_mode_stack mode = self.keyboard_modes[''] if is_root_mode else self.keyboard_mode_stack[-1] + if is_root_mode and self.leader_key is not None and shortcut_matches(self.leader_key, ev): + continuations = self.matching_key_actions(self.leader_continuations(mode)) + if continuations: + get_boss().show_leader_keymap(self.leader_key, continuations) + return True key_action = get_shortcut(mode.keymap, ev) if key_action is None and self.global_shortcuts_map and (global_key_action := get_shortcut(self.global_shortcuts_map, ev)) is not None: if grab_keyboard(None): diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 8d73949..5ab39a4 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -3790,6 +3790,22 @@ this option to alter all default shortcuts that use :opt:`kitty_mod`. """, ) +opt( + 'leader', + 'ctrl+space', + long_text=""" +The key that opens the leader key tree. When you press it and there are +multi-key mappings starting with this key (for example +:code:`map ctrl+space>n new_os_window`), kitty displays every possible +continuation with its action and help text, without waiting for a timeout. See +:ref:`leader_keymap` for details. + +Set it to :code:`none` to disable the leader key. Only mappings whose first key +is the leader key are affected, a leader key with no multi-key mapping behind it +is passed through to the program running in kitty. +""", +) + opt( 'remap_modifiers', '', diff --git a/kitty/options/parse.py b/kitty/options/parse.py index 8815bc4..57c4092 100644 --- a/kitty/options/parse.py +++ b/kitty/options/parse.py @@ -1094,6 +1094,9 @@ class Parser: def kitty_mod(self, val: str, ans: dict[str, typing.Any]) -> None: ans['kitty_mod'] = to_modifiers(val) + def leader(self, val: str, ans: dict[str, typing.Any]) -> None: + ans['leader'] = str(val).strip() + def linux_bell_theme(self, val: str, ans: dict[str, typing.Any]) -> None: ans['linux_bell_theme'] = str(val) diff --git a/kitty/options/types.py b/kitty/options/types.py index ac16390..d893511 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -388,6 +388,7 @@ option_names = ( 'italic_font', 'kitten_alias', 'kitty_mod', + 'leader', 'linux_bell_theme', 'linux_display_server', 'listen_on', @@ -613,6 +614,7 @@ class Options: input_delay: int = 3 italic_font: FontSpec = FontSpec(family=None, style=None, postscript_name=None, full_name=None, system='auto', axes=(), variable_name=None, features=(), created_from_string='auto') kitty_mod: int = 5 + leader: str = 'ctrl+space' linux_bell_theme: str = '__custom' linux_display_server: choices_for_linux_display_server = 'auto' listen_on: str = 'none' diff --git a/kitty_tests/command_palette.py b/kitty_tests/command_palette.py index 805a457..0993962 100644 --- a/kitty_tests/command_palette.py +++ b/kitty_tests/command_palette.py @@ -279,3 +279,52 @@ class TestCommandPalette(BaseTest): def test_unmapped_actions_sorted_order(self): # Covered by test_collect_keys_bindings_sorted pass + + def test_leader_prefix_bindings(self): + from kittens.command_palette.main import collect_leader_data + from kitty.options.utils import parse_map, parse_shortcut + + opts = self.set_options({'leader': 'ctrl+space'}) + for spec in ('ctrl+space>n new_os_window', 'ctrl+space>w new_window', 'ctrl+space>n new_os_window'): + for kd in parse_map(spec): + kd = kd.resolve_and_copy(opts.kitty_mod) + opts.keyboard_modes[''].keymap.setdefault(kd.trigger, []).append(kd) + + data = collect_leader_data(opts, parse_shortcut('ctrl+space')) + leader = data['leader'] + self.ae(leader['prefix'], 'ctrl+space') + self.ae([b['key'] for b in leader['bindings']], ['n', 'w'], 'Duplicate continuations should collapse') + self.ae(leader['bindings'][0]['action'], 'new_os_window') + self.ae(leader['bindings'][1]['action'], 'new_window') + self.assertTrue(leader['bindings'][0]['help'], 'Bindings should carry their help text') + + def test_leader_option(self): + from kitty.keys import leader_key_from_options + + opts = self.set_options({'leader': 'none'}) + self.assertIsNone(leader_key_from_options(opts)) + self.assertIsNone(opts.leader_key) + + opts = self.set_options({'leader': 'ctrl+space'}) + self.assertIsNotNone(leader_key_from_options(opts)) + self.assertIsNotNone(opts.leader_key) + + def test_append_map_to_config(self): + import os + import tempfile + + from kitty.config import append_map_to_config + + with tempfile.TemporaryDirectory() as tdir: + path = os.path.join(tdir, 'kitty.conf') + self.ae(append_map_to_config('ctrl+u', 'new_os_window', path), path) + self.ae(append_map_to_config('ctrl+j', 'new_tab', path), path) + with open(path) as f: + self.ae(f.read().splitlines(), ['map ctrl+u new_os_window', 'map ctrl+j new_tab']) + + # A config file without a trailing newline must not get a mangled line + with open(path, 'w') as f: + f.write('font_size 12') + append_map_to_config('ctrl+k', 'new_window', path) + with open(path) as f: + self.ae(f.read().splitlines(), ['font_size 12', 'map ctrl+k new_window'])