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.
This commit is contained in:
BlackAngelTV committed 2026-11-13 08:03:03 +01:00
1 parent dc13716431
commit bfc97997a1
10 files changed
+418 -13

No files matched your search

+9
View File
@@ -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',
"""
+40
View File
@@ -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:
+32 -1
View File
@@ -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):
+16
View File
@@ -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',
'',
+3
View File
@@ -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)
+2
View File
@@ -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'