Right Ctrl: one table, and it reaches the session's own chords

The right-Ctrl rescue existed because some layouts claim that key and deliver
the chord as a bare letter, but it only covered what the *screens* answer: the
letter table listed ^R and ^P, while ^C and ^V were bound straight to their own
handlers above the dispatcher. So on the affected layouts right Ctrl-V typed a
`v` into the compose line and right Ctrl-C did nothing — the two chords a user
is most likely to reach for with the right hand.

Both now funnel through _dispatch like every other key, and the letter table is
the single source of truth for both halves of a chord's life: the Keys.Control*
bindings are generated from it, and the rescue reads it. Adding a chord is one
line, and a chord can no longer be bound without its rescue — or rescued into an
action nothing binds. `quit` and `paste_clipboard` are answered in the
dispatcher and never forwarded, so no screen sees them.

m/i/h stay out of the table on purpose: prompt_toolkit spells Enter, Tab and
Backspace as ControlM/ControlI/ControlH, so claiming them would rebind those.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-07-29 04:12:52 -04:00
1 parent 0756537bdf
commit 680fa294c6
2 files changed
+114 -36

No files matched your search

+58 -36
View File
@@ -44,6 +44,25 @@ from .prompt import (
from .screen import CANCEL, BusyScreen, Screen, ScrollScreen
from .select import Choice, ReorderScreen, SelectScreen, Separator
#: Every Ctrl-letter chord the app binds, keyed by the bare lowercase letter — the single
#: source of truth for both halves of a chord's life: the ``Keys.Control*`` bindings folded
#: into :data:`_KEY_ACTIONS` below, and the right-Ctrl rescue in :meth:`TuiSession._dispatch`
#: (see :func:`_right_ctrl_down`), which promotes the bare letter a layout-claimed right Ctrl
#: delivers as *text* back into the chord. Add a chord here and both Ctrl keys reach it — no
#: second edit, no chord that works on one side of the keyboard only. ``quit`` and
#: ``paste_clipboard`` are the session's own (answered in ``_dispatch``); the rest are actions
#: forwarded to the top screen. A bare letter only reaches text while the right Ctrl is held
#: when the layout has no third-level glyph for that key (i.e. it really is the chord) — a
#: genuine third-level character arrives as some *other* glyph and never matches this table.
#: ``m``/``i``/``h`` are not free: prompt_toolkit spells Enter, Tab and Backspace as
#: ``Keys.ControlM``/``ControlI``/``ControlH``, so claiming them here would rebind those keys.
_CTRL_LETTER_CHORDS: dict[str, str] = {
"c": "quit",
"p": "paths",
"r": "retry",
"v": "paste_clipboard",
}
#: Maps prompt_toolkit keys to the normalized action names screens understand.
_KEY_ACTIONS: dict[Any, str] = {
Keys.Up: "up",
@@ -72,8 +91,12 @@ _KEY_ACTIONS: dict[Any, str] = {
Keys.Delete: "delete",
Keys.Tab: "tab",
Keys.BackTab: "shift_tab",
Keys.ControlR: "retry",
Keys.ControlP: "paths",
# The Ctrl-letter chords, generated from the one table above so a chord can never be
# bound without its right-Ctrl rescue (or rescued into an action nothing binds).
**{
getattr(Keys, f"Control{letter.upper()}"): action
for letter, action in _CTRL_LETTER_CHORDS.items()
},
}
#: The plain navigation actions that have a Ctrl-chord sibling, for the right-Ctrl rescue
@@ -89,18 +112,6 @@ _CTRL_CHORDS: dict[str, str] = {
"pagedown": "ctrl_pagedown",
}
#: The letter Ctrl chords (the ``Keys.Control*`` letter entries in :data:`_KEY_ACTIONS`),
#: keyed by the bare lowercase letter a layout-claimed right Ctrl delivers as *text* instead.
#: Same right-Ctrl rescue as :data:`_CTRL_CHORDS`, but promoting a typed letter rather than a
#: navigation key — a bare ``r``/``p`` only reaches text while the right Ctrl is physically
#: held when the layout has no third-level glyph for that key (i.e. it really is the chord); a
#: genuine third-level character arrives as some *other* glyph and is never in this map. Keep
#: in step with the ``Keys.ControlR``/``Keys.ControlP`` entries above.
_CTRL_LETTER_CHORDS: dict[str, str] = {
"r": "retry",
"p": "paths",
}
def _right_ctrl_down() -> bool:
"""Whether the right Ctrl key is physically held right now (Windows; ``False`` elsewhere).
@@ -129,7 +140,7 @@ def _read_clipboard() -> str:
"""Best-effort read of the OS clipboard's Unicode text (Windows; ``""`` elsewhere).
The fallback behind Ctrl-V on a terminal that delivers the key literally rather than as a
bracketed paste (see :meth:`TuiSession._key_bindings`): it pulls the clipboard's text
bracketed paste (see :meth:`TuiSession._dispatch`): it pulls the clipboard's text
straight from the Win32 API. Every failure — a non-Windows platform, an empty or
non-text clipboard, a clipboard busy elsewhere we couldn't open — collapses to ``""``, so
the paste simply does nothing rather than raising into the key handler. Pointer-returning
@@ -1171,7 +1182,12 @@ class TuiSession:
# --- input ---------------------------------------------------------------
def _key_bindings(self) -> KeyBindings:
"""Build the global key bindings that dispatch normalized actions to the top."""
"""Build the global key bindings that dispatch normalized actions to the top.
Every key — navigation, Ctrl chord, typed character, pasted run — funnels through
:meth:`_dispatch`, which is what lets the right-Ctrl rescue there cover the whole app
rather than the screen actions only.
"""
kb = KeyBindings()
def bind(key: Any, action: str) -> None:
@@ -1182,21 +1198,6 @@ class TuiSession:
for key, action in _KEY_ACTIONS.items():
bind(key, action)
@kb.add(Keys.ControlC)
def _quit(event: Any) -> None: # noqa: ANN401
if self._app is not None:
self._app.exit()
@kb.add(Keys.ControlV)
def _paste_clipboard(event: Any) -> None: # noqa: ANN401
# Some terminals deliver Ctrl-V as the literal control key — no bracketed-paste
# sequence, so no text on the event. Read the OS clipboard ourselves and hand the
# run to the top screen as a paste. Terminals that instead translate Ctrl-V into a
# bracketed paste never reach here — that lands in _typed below as a multi-char run.
text = _read_clipboard()
if text:
self._dispatch("paste", text)
@kb.add(Keys.Any)
def _typed(event: Any) -> None: # noqa: ANN401
data = event.data
@@ -1215,20 +1216,41 @@ class TuiSession:
def _dispatch(self, action: str, data: str = "") -> None:
"""Forward an action to the top screen and repaint.
A plain navigation key — or a bare ``r``/``p`` typed as text — arriving while the right
Ctrl key is physically held is promoted to its Ctrl chord first (see
:func:`_right_ctrl_down`, :data:`_CTRL_CHORDS`, :data:`_CTRL_LETTER_CHORDS`) — a no-op
when the console already reported the chord, and the rescue when a layout-claimed right
Ctrl stripped it.
Right Ctrl is read as Ctrl first, app-wide: a plain navigation key, or *any* bare
letter arriving as text, is promoted to its Ctrl chord while the right Ctrl key is
physically held (see :func:`_right_ctrl_down`, :data:`_CTRL_CHORDS`,
:data:`_CTRL_LETTER_CHORDS`) — a no-op when the console already reported the chord, and
the rescue when a layout-claimed right Ctrl stripped it to a bare character. Because
every binding funnels through here, the rescue covers the session's own chords too, not
just the screen actions: right Ctrl-V pastes into a compose line instead of typing a
``v``, right Ctrl-C quits.
The two session-level actions are answered here rather than forwarded — no screen ever
sees ``quit`` or ``paste_clipboard``.
The repaint keeps prompt_toolkit's fast differential paint; a frame carrying a glyph
the terminal may draw narrower than pt reserves for it (an emoji) upgrades itself to a
full repaint at compose time — see :meth:`_emit`.
"""
# The key-state probe comes last in each test, so it only runs for a key that could
# be a chord at all — not on every keystroke.
if action in _CTRL_CHORDS and _right_ctrl_down():
action = _CTRL_CHORDS[action]
elif action == "text" and data.lower() in _CTRL_LETTER_CHORDS and _right_ctrl_down():
action, data = _CTRL_LETTER_CHORDS[data.lower()], ""
if action == "quit":
if self._app is not None:
self._app.exit()
return
if action == "paste_clipboard":
# Some terminals deliver Ctrl-V as the literal control key — no bracketed-paste
# sequence, so no text on the event. Read the OS clipboard ourselves and hand the
# run to the top screen as a paste. Terminals that instead translate Ctrl-V into a
# bracketed paste never reach here — that lands in _typed as a multi-char run.
text = _read_clipboard()
if text:
self._dispatch("paste", text)
return
top = self.top
if top is not None:
top.handle(action, data)
+56
View File
@@ -1653,6 +1653,62 @@ def test_dispatch_promotes_letter_chords_while_right_ctrl_is_held(monkeypatch) -
assert seen == [("retry", ""), ("paths", ""), ("text", "x"), ("text", "r")]
def test_right_ctrl_rescue_covers_the_sessions_own_chords(monkeypatch) -> None:
"""The rescue is app-wide, not screen-actions-only: ^V and ^C are answered by the session
itself, and a layout-claimed right Ctrl must reach them too — right Ctrl-V pastes the
clipboard into a compose line rather than typing a ``v``, right Ctrl-C quits. Neither
pseudo-action is ever forwarded to a screen."""
from meshterm.ui.tui import session as session_mod
session = TuiSession()
seen: list[tuple[str, str]] = []
class Probe(ScrollScreen):
def handle(self, action: str, data: str = "") -> None:
seen.append((action, data))
class FakeApp:
def __init__(self) -> None:
self.exited = False
def exit(self) -> None:
self.exited = True
def invalidate(self) -> None:
pass
session.push(Probe(Text("x")))
session._app = FakeApp()
monkeypatch.setattr(session_mod, "_read_clipboard", lambda: "pasted")
monkeypatch.setattr(session_mod, "_right_ctrl_down", lambda: True)
session._dispatch("text", "v") # ^V: clipboard reaches the screen as a paste
assert seen == [("paste", "pasted")]
session._dispatch("text", "c") # ^C: quits, and nothing lands on the screen
assert seen == [("paste", "pasted")]
assert session._app.exited is True
monkeypatch.setattr(session_mod, "_right_ctrl_down", lambda: False)
session._dispatch("text", "v") # released: a plain typed character again
assert seen[-1] == ("text", "v")
def test_every_ctrl_letter_chord_is_bound_on_both_ctrl_keys() -> None:
"""The chord table drives the prompt_toolkit bindings, so a chord can never be bound for
the left Ctrl without its right-Ctrl rescue (the drift the two used to be able to develop
when the letter map was maintained by hand)."""
from prompt_toolkit.keys import Keys
from meshterm.ui.tui.session import _CTRL_LETTER_CHORDS, _KEY_ACTIONS
for letter, action in _CTRL_LETTER_CHORDS.items():
key = getattr(Keys, f"Control{letter.upper()}")
assert _KEY_ACTIONS[key] == action
# Enter/Tab/Backspace are spelled c-m/c-i/c-h: claiming those letters would rebind them.
assert not {"m", "i", "h"} & set(_CTRL_LETTER_CHORDS)
assert _KEY_ACTIONS[Keys.Enter] == "enter"
def test_wide_glyph_detection_flags_emoji_not_marks() -> None:
"""The desync only ever comes from a width-2 glyph the terminal may draw narrower — an
emoji. Node-type marks, status marks and chart braille are width-1 everywhere, so they