Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: map non-latin layout ctrl chords to their base keys (#4961)

Can Celikabf0d07cf8b8
diff --git a/src/client/shell/input.rs b/src/client/shell/input.rs
index 98fe28947..e3a801cf8 100644
--- a/src/client/shell/input.rs
+++ b/src/client/shell/input.rs
@@ -419,12 +419,13 @@ impl ClientShellState {
};
// A native record is released as the recorded key. A VT release
// report already names its key and shifted character exactly,
- // except a non-Latin Ctrl chord pressed as its physical key: it
- // is released as that key, matching the press the pane saw.
- let physical_chord = key.base_layout_key().map(KeyCode::Char)
- == Some(lease.key.code)
- && key.code != lease.key.code;
- let release = if key.physical_key_id().is_some() || physical_chord {
+ // except around a non-Latin Ctrl chord: Ctrl alone resolves to
+ // the physical key, so a modifier let go before the key flips
+ // between the layout character and that key. It is released as
+ // the key the pane saw pressed.
+ let layout_chord =
+ key.code != lease.key.code && key.identity() == lease.key.identity();
+ let release = if key.physical_key_id().is_some() || layout_chord {
lease
.key
.with_modifiers(key.modifiers)
@@ -1127,7 +1128,7 @@ impl ClientShellState {
if let Some(lease) = self.input_leases.remove(lease_key) {
return Some(lease);
}
- let KeyCode::Char(c) = key.code else {
+ let KeyCode::Char(c) = key.layout_key().map_or(key.code, KeyCode::Char) else {
return None;
};
fn single(mut chars: impl Iterator<Item = char>) -> Option<char> {
@@ -1146,9 +1147,6 @@ impl ClientShellState {
.and_then(char::from_u32)
.into_iter()
.chain(other_case)
- // A Ctrl chord on a non-Latin layout was leased as its physical key;
- // its release names the layout character if Ctrl was let go first.
- .chain(key.base_layout_key())
.find_map(|candidate| {
self.input_leases.remove(&crate::input::InputLeaseKey::new(
LOCAL_INPUT_SOURCE,
diff --git a/src/client/shell/tests/input_conformance.rs b/src/client/shell/tests/input_conformance.rs
index 71b379e19..4854974c4 100644
--- a/src/client/shell/tests/input_conformance.rs
+++ b/src/client/shell/tests/input_conformance.rs
@@ -1314,6 +1314,383 @@ async fn reporter_text_key_release_reaches_kitty_event_pane() {
}
}
+/// A key on a non-US layout, as the Ghostty app reports it: the physical key
+/// and the layout's (unshifted, shifted) text.
+const fn layout_key(key: ffi::GhosttyKey, base: char, shifted: char) -> KeyDef {
+ text("layout", key, base, shifted)
+}
+
+fn layout_keystroke_through_herdr(
+ host: HostProfile,
+ pane_mode: &[u8],
+ def: KeyDef,
+ mods: u16,
+) -> (HostKeystroke, String, String) {
+ let keystroke = Oracle::new(host.setup(pane_mode)).keystroke(def, mods);
+ let (press, release) = Oracle::new(pane_mode).keystroke(def, mods);
+ let direct = if keystroke.1.is_empty() {
+ press
+ } else {
+ [press, release].concat()
+ };
+ let mut herdr = HerdrPath::new(host, pane_mode);
+ let pane_press = herdr.feed(&keystroke.0).expect("press reaches the pane");
+ let pane_release = herdr.feed(&keystroke.1).expect("release reaches the pane");
+ (
+ keystroke,
+ show(&direct),
+ show(&[pane_press, pane_release].concat()),
+ )
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn layout_ctrl_chords_match_ghostty_direct() {
+ // #1079. Keystrokes from a Kitty host on Russian, German, Turkish, French,
+ // Nordic and Polish layouts, built like Ghostty builds them. `ghostty` is
+ // what Ghostty sends the app directly (recorded from libghostty, and
+ // checked against it below); `herdr` is what the pane gets through Herdr.
+ use ffi::*;
+ const CTRL: u16 = ghostty::MOD_CTRL;
+ const ALT: u16 = ghostty::MOD_ALT;
+ const SHIFT: u16 = ghostty::MOD_SHIFT;
+ let ru_w = layout_key(GhosttyKey_GHOSTTY_KEY_W, '\u{446}', '\u{426}');
+ let ru_c = layout_key(GhosttyKey_GHOSTTY_KEY_C, '\u{441}', '\u{421}');
+ let ru_i = layout_key(GhosttyKey_GHOSTTY_KEY_I, '\u{448}', '\u{428}');
+ let ru_bracket = layout_key(GhosttyKey_GHOSTTY_KEY_BRACKET_LEFT, '\u{445}', '\u{425}');
+ let de = layout_key(GhosttyKey_GHOSTTY_KEY_SEMICOLON, '\u{f6}', '\u{d6}');
+ let tr = layout_key(GhosttyKey_GHOSTTY_KEY_I, '\u{131}', 'I');
+ let fr = layout_key(GhosttyKey_GHOSTTY_KEY_DIGIT_2, '\u{e9}', '2');
+ let no = layout_key(GhosttyKey_GHOSTTY_KEY_BRACKET_LEFT, '\u{e5}', '\u{c5}');
+ let pl = layout_key(GhosttyKey_GHOSTTY_KEY_E, '\u{119}', '\u{118}');
+ let keys = [
+ ("ru ctrl+w", ru_w, CTRL),
+ ("ru ctrl+c", ru_c, CTRL),
+ ("ru ctrl+i", ru_i, CTRL),
+ ("ru ctrl+[", ru_bracket, CTRL),
+ ("ru ctrl+shift+[", ru_bracket, CTRL | SHIFT),
+ ("ru alt+w", ru_w, ALT),
+ ("ru ctrl+alt+w", ru_w, CTRL | ALT),
+ ("ru w", ru_w, 0),
+ ("ru shift+w", ru_w, SHIFT),
+ ("de ctrl+\u{f6}", de, CTRL),
+ ("tr ctrl+\u{131}", tr, CTRL),
+ ("fr ctrl+\u{e9}", fr, CTRL),
+ ("no ctrl+\u{e5}", no, CTRL),
+ ("pl altgr \u{119}", pl, CTRL | ALT),
+ ];
+ // (pane, key, ghostty, herdr)
+ let table: &[(&str, &str, &str, &str)] = &[
+ // Plain shell. Ctrl alone maps to the physical key's control byte
+ // when Ghostty has one; Ctrl+I and Ctrl+[ keep the layout character.
+ ("legacy", "ru ctrl+w", "\\x17", "\\x17"),
+ ("legacy", "ru ctrl+c", "\\x03", "\\x03"),
+ ("legacy", "ru ctrl+i", "\\x1b[1096;5u", "\\x1b[1096;5u"),
+ ("legacy", "ru ctrl+[", "\\x1b[1093;5u", "\\x1b[1093;5u"),
+ (
+ "legacy",
+ "ru ctrl+shift+[",
+ "\\x1b[1061;5u",
+ "\\x1b[1061;5u",
+ ),
+ ("legacy", "ru alt+w", "\\x1b\\xd1\\x86", "\\x1b\\xd1\\x86"),
+ ("legacy", "ru w", "\\xd1\\x86", "\\xd1\\x86"),
+ ("legacy", "ru shift+w", "\\xd0\\xa6", "\\xd0\\xa6"),
+ ("legacy", "de ctrl+\u{f6}", "\\x1b[246;5u", "\\x1b[246;5u"),
+ ("legacy", "tr ctrl+\u{131}", "\\x1b[305;5u", "\\x1b[305;5u"),
+ ("legacy", "no ctrl+\u{e5}", "\\x1b[229;5u", "\\x1b[229;5u"),
+ // Ghostty maps these by physical key too, but Ctrl+Alt can be AltGr
+ // on Windows hosts and Latin keys are shortcuts of their own, so
+ // Herdr keeps the layout character.
+ ("legacy", "ru ctrl+alt+w", "\\x1b\\x17", "\\x1b[1094;7u"),
+ ("legacy", "fr ctrl+\u{e9}", "\\x00", "\\x1b[233;5u"),
+ ("legacy", "pl altgr \u{119}", "\\x1b\\x05", "\\x1b[281;7u"),
+ // Kitty apps. A rewritten chord reaches them as the physical key, the
+ // key the Kitty spec says to match shortcuts on.
+ ("kitty1", "ru ctrl+w", "\\x1b[1094;5u", "\\x1b[119;5u"),
+ ("kitty1", "ru ctrl+c", "\\x1b[1089;5u", "\\x1b[99;5u"),
+ ("kitty1", "ru ctrl+i", "\\x1b[1096;5u", "\\x1b[1096;5u"),
+ ("kitty1", "ru ctrl+[", "\\x1b[1093;5u", "\\x1b[1093;5u"),
+ (
+ "kitty1",
+ "ru ctrl+shift+[",
+ "\\x1b[1093;6u",
+ "\\x1b[1093;6u",
+ ),
+ ("kitty1", "ru alt+w", "\\x1b[1094;3u", "\\x1b[1094;3u"),
+ ("kitty1", "ru ctrl+alt+w", "\\x1b[1094;7u", "\\x1b[1094;7u"),
+ ("kitty1", "ru w", "\\xd1\\x86", "\\xd1\\x86"),
+ ("kitty1", "ru shift+w", "\\xd0\\xa6", "\\xd0\\xa6"),
+ ("kitty1", "de ctrl+\u{f6}", "\\x1b[246;5u", "\\x1b[246;5u"),
+ ("kitty1", "tr ctrl+\u{131}", "\\x1b[305;5u", "\\x1b[305;5u"),
+ ("kitty1", "fr ctrl+\u{e9}", "\\x1b[233;5u", "\\x1b[233;5u"),
+ ("kitty1", "no ctrl+\u{e5}", "\\x1b[229;5u", "\\x1b[229;5u"),
+ ("kitty1", "pl altgr \u{119}", "\\x1b[281;7u", "\\x1b[281;7u"),
+ (
+ "kitty3",
+ "ru ctrl+w",
+ "\\x1b[1094;5u\\x1b[1094;5:3u",
+ "\\x1b[119;5u\\x1b[119;5:3u",
+ ),
+ (
+ "kitty3",
+ "ru w",
+ "\\xd1\\x86\\x1b[1094;1:3u",
+ "\\xd1\\x86\\x1b[1094;1:3u",
+ ),
+ // Alternate keys: the pane input wire has no base-layout slot, so
+ // Herdr drops that field for every non-ASCII key (as on master).
+ ("kitty5", "ru ctrl+w", "\\x1b[1094::119;5u", "\\x1b[119;5u"),
+ ("kitty5", "ru ctrl+c", "\\x1b[1089::99;5u", "\\x1b[99;5u"),
+ (
+ "kitty5",
+ "ru ctrl+shift+[",
+ "\\x1b[1093:1061:91;6u",
+ "\\x1b[1093:1061;6u",
+ ),
+ ("kitty5", "ru alt+w", "\\x1b[1094::119;3u", "\\x1b[1094;3u"),
+ ("kitty5", "ru w", "\\xd1\\x86", "\\xd1\\x86"),
+ (
+ "kitty5",
+ "de ctrl+\u{f6}",
+ "\\x1b[246::59;5u",
+ "\\x1b[246;5u",
+ ),
+ ];
+ let panes: HashMap<&str, &[u8]> = [
+ ("legacy", &b""[..]),
+ ("kitty1", b"\x1b[>1u"),
+ ("kitty3", b"\x1b[>3u"),
+ ("kitty5", b"\x1b[>5u"),
+ ]
+ .into_iter()
+ .collect();
+ for &(pane, name, ghostty, want) in table {
+ let &(_, def, mods) = keys.iter().find(|(key, ..)| *key == name).unwrap();
+ let (host, direct, got) =
+ layout_keystroke_through_herdr(HostProfile::Kitty, panes[pane], def, mods);
+ assert_eq!(direct, ghostty, "{pane} {name}: Ghostty direct");
+ assert_eq!(got, want, "{pane} {name}: host sent {}", show(&host.0));
+ }
+ // Every key is covered in the plain shell and a Kitty app.
+ for (name, ..) in keys {
+ for pane in ["legacy", "kitty1"] {
+ assert!(
+ table.iter().any(|row| row.0 == pane && row.1 == name),
+ "{pane} {name}"
+ );
+ }
+ }
+
+ // Plain Cyrillic typing from a host without the Kitty protocol.
+ for (pane, pane_mode) in [("legacy", &b""[..]), ("kitty1", b"\x1b[>1u")] {
+ for mods in [0, SHIFT] {
+ let (_, direct, got) =
+ layout_keystroke_through_herdr(HostProfile::Legacy, pane_mode, ru_w, mods);
+ assert_eq!(got, direct, "legacy host {pane} {}", mods_name(mods));
+ }
+ }
+
+ // Hosts that name no base-layout key: nothing is known about the physical
+ // key, so the layout character goes through as reported.
+ for (pane_mode, host_bytes, want) in [
+ (&b""[..], &b"\x1b[1094;5u"[..], "\\x1b[1094;5u"),
+ (b"\x1b[>1u", b"\x1b[1094;5u", "\\x1b[1094;5u"),
+ (b"", b"\x1b[1094;3u", "\\x1b\\xd1\\x86"),
+ (b"\x1b[>1u", b"\x1b[1089:1057;6u", "\\x1b[1089;6u"),
+ ] {
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, pane_mode);
+ let got = herdr.feed(host_bytes).expect("reaches the pane");
+ assert_eq!(show(&got), want, "{}", show(host_bytes));
+ }
+
+ // Ctrl let go before the key: the release names the layout character
+ // without Ctrl, and is paired with the physical-key press.
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, b"\x1b[>3u");
+ let press = herdr.feed(b"\x1b[1094::119;5u").expect("press");
+ let release = herdr.feed(b"\x1b[1094::119;1:3u").expect("release");
+ assert_eq!(
+ show(&[press, release].concat()),
+ "\\x1b[119;5u\\x1b[119;1:3u"
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn layout_chord_releases_pair_when_modifiers_change_first() {
+ // A modifier let go before the key changes whether the chord is Ctrl
+ // alone, so the press and the release can name different keys (the layout
+ // character or the physical key). The release must still reach the pane
+ // as the key it saw pressed, and must not stay leased.
+ use ffi::*;
+ const CTRL: u16 = ghostty::MOD_CTRL;
+ const ALT: u16 = ghostty::MOD_ALT;
+ const SHIFT: u16 = ghostty::MOD_SHIFT;
+ const PRESS: ffi::GhosttyKeyAction = ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_PRESS;
+ const RELEASE: ffi::GhosttyKeyAction = ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_RELEASE;
+ let ru_w = layout_key(GhosttyKey_GHOSTTY_KEY_W, '\u{446}', '\u{426}');
+ // (case, press mods, release mods, Ghostty direct, Herdr)
+ let cases = [
+ (
+ "ctrl+shift, shift let go first",
+ CTRL | SHIFT,
+ CTRL,
+ "\\x1b[1094;6u\\x1b[1094;5:3u",
+ "\\x1b[1094;6u\\x1b[1094;5:3u",
+ ),
+ (
+ "ctrl+alt, alt let go first",
+ CTRL | ALT,
+ CTRL,
+ "\\x1b[1094;7u\\x1b[1094;5:3u",
+ "\\x1b[1094;7u\\x1b[1094;5:3u",
+ ),
+ (
+ "ctrl+shift, ctrl let go first",
+ CTRL | SHIFT,
+ SHIFT,
+ "\\x1b[1094;6u\\x1b[1094;2:3u",
+ "\\x1b[1094;6u\\x1b[1094;2:3u",
+ ),
+ // A Ctrl chord reaches Kitty apps as its physical key (see
+ // `layout_ctrl_chords_match_ghostty_direct`); its release follows.
+ (
+ "ctrl, ctrl let go first",
+ CTRL,
+ 0,
+ "\\x1b[1094;5u\\x1b[1094;1:3u",
+ "\\x1b[119;5u\\x1b[119;1:3u",
+ ),
+ (
+ "ctrl, shift added before release",
+ CTRL,
+ CTRL | SHIFT,
+ "\\x1b[1094;5u\\x1b[1094;6:3u",
+ "\\x1b[119;5u\\x1b[119;6:3u",
+ ),
+ ];
+ let pane_mode = b"\x1b[>3u";
+ for (name, press_mods, release_mods, ghostty, want) in cases {
+ let mut host = Oracle::new(HostProfile::Kitty.setup(pane_mode));
+ let host_press = host.encode(ru_w, press_mods, PRESS);
+ let host_release = host.encode(ru_w, release_mods, RELEASE);
+ let mut direct = Oracle::new(pane_mode);
+ let direct_bytes = [
+ direct.encode(ru_w, press_mods, PRESS),
+ direct.encode(ru_w, release_mods, RELEASE),
+ ]
+ .concat();
+ assert_eq!(show(&direct_bytes), ghostty, "{name}: Ghostty direct");
+
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, pane_mode);
+ let press = herdr.feed(&host_press).expect("press reaches the pane");
+ let release = herdr.feed(&host_release).expect("release reaches the pane");
+ assert_eq!(
+ show(&[press, release].concat()),
+ want,
+ "{name}: host sent {} {}",
+ show(&host_press),
+ show(&host_release)
+ );
+ // Nothing stays leased: losing focus releases no further key.
+ let after = herdr.feed(b"\x1b[O").unwrap_or_default();
+ assert!(
+ !show(&after).contains(":3u"),
+ "{name}: focus loss sent {}",
+ show(&after)
+ );
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn overlapping_layout_and_us_keys_release_exactly() {
+ // A US `w` held together with a Russian chord on the same physical key.
+ // Each release must end its own press, in either order, however the
+ // chord's modifiers changed in between.
+ use ffi::*;
+ const CTRL: u16 = ghostty::MOD_CTRL;
+ const SHIFT: u16 = ghostty::MOD_SHIFT;
+ const PRESS: ffi::GhosttyKeyAction = ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_PRESS;
+ const RELEASE: ffi::GhosttyKeyAction = ffi::GhosttyKeyAction_GHOSTTY_KEY_ACTION_RELEASE;
+ let us_w = *KEYS.iter().find(|def| def.name == "w").unwrap();
+ let ru_w = layout_key(GhosttyKey_GHOSTTY_KEY_W, '\u{446}', '\u{426}');
+ type Step = (KeyDef, u16, ffi::GhosttyKeyAction);
+ // (case, steps, Ghostty direct, Herdr)
+ let cases: [(&str, Vec<Step>, &str, &str); 4] = [
+ (
+ "ctrl+shift+\u{446}, shift let go, \u{446} then w released",
+ vec![
+ (us_w, 0, PRESS),
+ (ru_w, CTRL | SHIFT, PRESS),
+ (ru_w, CTRL, RELEASE),
+ (us_w, CTRL, RELEASE),
+ ],
+ "w\\x1b[1094;6u\\x1b[1094;5:3u\\x1b[119;5:3u",
+ "w\\x1b[1094;6u\\x1b[1094;5:3u\\x1b[119;5:3u",
+ ),
+ (
+ "ctrl+shift+\u{446}, shift let go, w then \u{446} released",
+ vec![
+ (us_w, 0, PRESS),
+ (ru_w, CTRL | SHIFT, PRESS),
+ (us_w, CTRL, RELEASE),
+ (ru_w, CTRL, RELEASE),
+ ],
+ "w\\x1b[1094;6u\\x1b[119;5:3u\\x1b[1094;5:3u",
+ "w\\x1b[1094;6u\\x1b[119;5:3u\\x1b[1094;5:3u",
+ ),
+ // A Ctrl chord reaches Kitty apps as its physical key (see
+ // `layout_ctrl_chords_match_ghostty_direct`); its release follows.
+ (
+ "ctrl+\u{446}, ctrl let go, \u{446} then w released",
+ vec![
+ (us_w, 0, PRESS),
+ (ru_w, CTRL, PRESS),
+ (ru_w, 0, RELEASE),
+ (us_w, 0, RELEASE),
+ ],
+ "w\\x1b[1094;5u\\x1b[1094;1:3u\\x1b[119;1:3u",
+ "w\\x1b[119;5u\\x1b[119;1:3u\\x1b[119;1:3u",
+ ),
+ (
+ "ctrl+\u{446}, ctrl let go, w then \u{446} released",
+ vec![
+ (us_w, 0, PRESS),
+ (ru_w, CTRL, PRESS),
+ (us_w, 0, RELEASE),
+ (ru_w, 0, RELEASE),
+ ],
+ "w\\x1b[1094;5u\\x1b[119;1:3u\\x1b[1094;1:3u",
+ "w\\x1b[119;5u\\x1b[119;1:3u\\x1b[119;1:3u",
+ ),
+ ];
+ let pane_mode = b"\x1b[>3u";
+ for (name, steps, ghostty, want) in cases {
+ let mut host = Oracle::new(HostProfile::Kitty.setup(pane_mode));
+ let mut direct = Oracle::new(pane_mode);
+ let mut herdr = HerdrPath::new(HostProfile::Kitty, pane_mode);
+ let mut direct_bytes = Vec::new();
+ let mut pane_bytes = Vec::new();
+ let mut host_bytes = Vec::new();
+ for (def, mods, action) in steps {
+ let report = host.encode(def, mods, action);
+ direct_bytes.extend(direct.encode(def, mods, action));
+ pane_bytes.extend(herdr.feed(&report).expect("reaches the pane"));
+ host_bytes.push(show(&report));
+ }
+ assert_eq!(show(&direct_bytes), ghostty, "{name}: Ghostty direct");
+ assert_eq!(show(&pane_bytes), want, "{name}: host sent {host_bytes:?}");
+ // Nothing stays leased: losing focus releases no further key.
+ let after = herdr.feed(b"\x1b[O").unwrap_or_default();
+ assert!(
+ !show(&after).contains(":3u"),
+ "{name}: focus loss sent {}",
+ show(&after)
+ );
+ }
+}
+
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn wezterm_escape_tap_reaches_the_pane_with_doubled_escape_preserved() {
diff --git a/src/config/keybinds.rs b/src/config/keybinds.rs
index 9d2792a08..276764a60 100644
--- a/src/config/keybinds.rs
+++ b/src/config/keybinds.rs
@@ -2048,6 +2048,43 @@ prefix = []
assert!(config.live_keybinds_with_diagnostics().is_err());
}
+ #[test]
+ fn ctrl_keybind_matches_non_latin_layout_chord_with_base_key() {
+ let config: Config = toml::from_str(
+ r#"
+[keys]
+navigate_pane_down = "ctrl+w"
+"#,
+ )
+ .unwrap();
+ let keybinds = config.keybinds();
+
+ // Russian layout: "\u{0446}" on the physical `w` key, Ctrl held.
+ let key = crate::input::parse_terminal_key_sequence("\x1b[1094::119;5u").unwrap();
+ assert!(keybinds.navigate.pane_down.matches_direct_key(&key));
+ let without_base = crate::input::parse_terminal_key_sequence("\x1b[1094;5u").unwrap();
+ assert!(!keybinds
+ .navigate
+ .pane_down
+ .matches_direct_key(&without_base));
+ }
+
+ #[test]
+ fn latin_layout_ctrl_keybind_keeps_matching_layout_key() {
+ let config: Config = toml::from_str(
+ r#"
+[keys]
+navigate_pane_down = "ctrl+\u00f6"
+"#,
+ )
+ .unwrap();
+ let keybinds = config.keybinds();
+
+ // German layout: "\u{f6}" on the physical `;` key.
+ let key = crate::input::parse_terminal_key_sequence("\x1b[246::59;5u").unwrap();
+ assert!(keybinds.navigate.pane_down.matches_direct_key(&key));
+ }
+
#[test]
fn navigate_bindings_allow_plain_keys_and_reject_local_conflicts() {
let config: Config = toml::from_str(
diff --git a/src/input/model.rs b/src/input/model.rs
index 8ad591fe4..7d3a480f3 100644
--- a/src/input/model.rs
+++ b/src/input/model.rs
@@ -79,10 +79,11 @@ pub struct TerminalKey {
pub generated_text: Option<String>,
physical_identity_hint: bool,
windows_dead_key: bool,
- /// The base-layout (physical) key a Kitty host named for this key. Client
- /// side only: it pairs releases whose layout character differs from the
- /// press (Ctrl let go first on a non-Latin layout).
- base_layout_key: Option<char>,
+ /// The layout character a non-Latin Ctrl chord was reported with before it
+ /// was resolved to its base-layout key. Client side only: the key's
+ /// identity, so a press and its release pair exactly even when a modifier
+ /// let go first changes which of the two the host report resolves to.
+ layout_key: Option<char>,
source: KeySource,
}
@@ -97,18 +98,18 @@ impl TerminalKey {
generated_text: None,
physical_identity_hint: false,
windows_dead_key: false,
- base_layout_key: None,
+ layout_key: None,
source: KeySource::Synthesized,
}
}
- pub(crate) fn with_base_layout_key(mut self, key: Option<char>) -> Self {
- self.base_layout_key = key;
+ pub(crate) fn with_layout_key(mut self, key: Option<char>) -> Self {
+ self.layout_key = key;
self
}
- pub(crate) fn base_layout_key(&self) -> Option<char> {
- self.base_layout_key
+ pub(crate) fn layout_key(&self) -> Option<char> {
+ self.layout_key
}
pub fn with_kind(mut self, kind: crossterm::event::KeyEventKind) -> Self {
@@ -219,7 +220,9 @@ impl TerminalKey {
KeySource::WindowsConsole {
physical_key: None, ..
} => KeyIdentity::Semantic(self.code),
- KeySource::Synthesized | KeySource::Vt { .. } => KeyIdentity::Semantic(self.code),
+ KeySource::Synthesized | KeySource::Vt { .. } => {
+ KeyIdentity::Semantic(self.layout_key.map_or(self.code, KeyCode::Char))
+ }
}
}
diff --git a/src/input/parse.rs b/src/input/parse.rs
index c75efa939..9e1243985 100644
--- a/src/input/parse.rs
+++ b/src/input/parse.rs
@@ -39,30 +39,42 @@ fn parse_kitty_key_sequence(data: &str) -> Option<TerminalKey> {
.and_then(|field| field.parse::<u32>().ok());
let mut code = kitty_codepoint_to_keycode(codepoint)?;
+ // Control-code text only ever matches Enter/Backspace/Tab/Esc, never a
+ // character key, so it is checked against the reported key.
+ let associated_text = match associated_text {
+ Some(value) => match parse_kitty_associated_text(value) {
+ Some(text) => Some(text),
+ None if matching_control_associated_text(value, code) => None,
+ None => return None,
+ },
+ None => None,
+ };
// Ctrl chords on a non-Latin layout (Ctrl+\u{441} on Russian) are shortcuts
// for the physical key the host names in the base-layout field: Ctrl+C.
- // Kitty sends ^C to a plain shell for them, and the Kitty spec tells apps
- // to match shortcuts on that key.
+ // Ghostty sends ^C to a plain shell for them, and the Kitty spec tells apps
+ // to match shortcuts on that key. Only what Ghostty maps is rewritten: Ctrl
+ // alone, on a key with a control byte. Shift, Alt and Super chords keep the
+ // layout character, Ctrl+Alt may be AltGr typing it, and Latin layouts
+ // (\u{f6}, \u{131}, \u{e5}) keep their own keys.
let mut shifted_codepoint = shifted_codepoint;
+ let mut layout_key = None;
if let (KeyCode::Char(ch), Some(base)) = (code, base_layout_codepoint.and_then(char::from_u32))
{
- if key_modifiers_from_u8(modifier).contains(KeyModifiers::CONTROL)
- && !ch.is_ascii()
- && base.is_ascii_graphic()
+ // A shifted alternate means Shift was held, even if the modifier
+ // field leaves it out (normalized below).
+ let shifted = shifted_codepoint.is_some_and(|shifted| shifted != codepoint);
+ if key_modifiers_from_u8(modifier) == KeyModifiers::CONTROL
+ && !shifted
+ && is_non_latin_script(ch)
+ && ghostty_maps_ctrl_to_physical_key(base)
+ && associated_text.is_none()
{
+ layout_key = Some(ch);
code = KeyCode::Char(base);
// The shifted alternate belongs to the layout character.
shifted_codepoint = None;
}
}
- let associated_text = match associated_text {
- Some(value) => match parse_kitty_associated_text(value) {
- Some(text) => Some(text),
- None if matching_control_associated_text(value, code) => None,
- None => return None,
- },
- None => None,
- };
let kind = parse_kitty_event_type(event_type)?;
let mut modifiers = key_modifiers_from_u8(modifier);
// Kitty permits the shifted alternate only while Shift is active. Normalize
@@ -74,18 +86,56 @@ fn parse_kitty_key_sequence(data: &str) -> Option<TerminalKey> {
modifiers |= KeyModifiers::SHIFT;
}
- let base_layout_key = base_layout_codepoint
- .and_then(char::from_u32)
- .filter(char::is_ascii_graphic);
let mut key = TerminalKey::new(code, modifiers)
.with_kind(kind)
- .with_base_layout_key(base_layout_key);
+ .with_layout_key(layout_key);
if let Some(shifted_codepoint) = shifted_codepoint {
key = key.with_shifted_codepoint(shifted_codepoint);
}
Some(key.with_generated_text(associated_text))
}
+/// Physical keys Ghostty sends a control byte for when Ctrl is held on a
+/// non-Latin layout. Ctrl+I, Ctrl+M and Ctrl+[ are left out on purpose
+/// (fixterms), so Ctrl+\u{448} is not Tab and Ctrl+\u{445} is not Esc.
+fn ghostty_maps_ctrl_to_physical_key(base: char) -> bool {
+ matches!(base, 'a'..='z' | '0'..='9' | '/' | '\\' | ']') && !matches!(base, 'i' | 'm')
+}
+
+/// Scripts whose layouts put their own letters on the US letter keys, so a
+/// Ctrl chord names the physical key. Latin scripts are excluded: their keys
+/// are shortcuts of their own (Ctrl+\u{f6} is not Ctrl+;).
+fn is_non_latin_script(ch: char) -> bool {
+ matches!(
+ u32::from(ch),
+ 0x0370..=0x03FF // Greek
+ | 0x0400..=0x052F // Cyrillic and supplement
+ | 0x0530..=0x058F // Armenian
+ | 0x0590..=0x05FF // Hebrew
+ | 0x0600..=0x06FF // Arabic
+ | 0x0700..=0x07FF // Syriac, Arabic supplement, Thaana, NKo
+ | 0x08A0..=0x08FF // Arabic extended-A
+ | 0x0900..=0x0DFF // Indic scripts through Sinhala
+ | 0x0E00..=0x0EFF // Thai, Lao
+ | 0x0F00..=0x0FFF // Tibetan
+ | 0x1000..=0x109F // Myanmar
+ | 0x10A0..=0x10FF // Georgian
+ | 0x1100..=0x11FF // Hangul Jamo
+ | 0x1200..=0x18FF // Ethiopic, Cherokee, Canadian Syllabics, Khmer, Mongolian
+ | 0x1C80..=0x1C8F // Cyrillic extended-C
+ | 0x1C90..=0x1CBF // Georgian extended
+ | 0x1F00..=0x1FFF // Greek extended
+ | 0x2DE0..=0x2DFF // Cyrillic extended-A
+ | 0x3040..=0x30FF // Hiragana, Katakana
+ | 0x3100..=0x318F // Bopomofo, Hangul compatibility Jamo
+ | 0x3400..=0x4DBF // CJK extension A
+ | 0x4E00..=0x9FFF // CJK unified ideographs
+ | 0xA640..=0xA69F // Cyrillic extended-B
+ | 0xAB70..=0xABBF // Cherokee supplement (lowercase)
+ | 0xAC00..=0xD7AF // Hangul syllables
+ )
+}
+
fn parse_kitty_associated_text(value: &str) -> Option<String> {
let mut text = String::new();
for codepoint in value.split(':') {
@@ -787,9 +837,16 @@ mod tests {
KeyCode::Char('c'),
KeyModifiers::CONTROL,
),
+ // Ctrl+Shift keeps the layout character, as Ghostty sends it.
(
"\x1b[1089:1057:99;6u",
- KeyCode::Char('c'),
+ KeyCode::Char('\u{441}'),
+ KeyModifiers::CONTROL | KeyModifiers::SHIFT,
+ ),
+ // Shift implied only by the shifted alternate.
+ (
+ "\x1b[1089:1057:99;5u",
+ KeyCode::Char('\u{441}'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
),
(
@@ -815,6 +872,100 @@ mod tests {
}
}
+ #[test]
+ fn parse_ctrl_chords_on_every_non_latin_script_as_their_base_layout_key() {
+ // Greek, Cyrillic, Hebrew, Arabic, Thai, Georgian, Hangul, Cherokee
+ // (and its lowercase supplement), Canadian Syllabics, Mongolian.
+ for codepoint in [
+ 945, 1092, 1513, 1588, 3615, 4304, 12609, 5024, 0xAB70, 5121, 6176,
+ ] {
+ for (event, kind) in [
+ ("", crossterm::event::KeyEventKind::Press),
+ (":2", crossterm::event::KeyEventKind::Repeat),
+ (":3", crossterm::event::KeyEventKind::Release),
+ ] {
+ let sequence = format!("\x1b[{codepoint}::97;5{event}u");
+ let key = parse_terminal_key_sequence(&sequence).unwrap();
+ assert_terminal_key_eq(key, KeyCode::Char('a'), KeyModifiers::CONTROL, kind, None);
+ }
+ }
+ }
+
+ /// Without a base-layout field nothing can be rewritten, so stripping it
+ /// gives the report as the layout key.
+ fn without_base_layout_field(sequence: &str) -> String {
+ let (key_part, rest) = sequence.split_once(';').unwrap_or((sequence, ""));
+ let mut fields = key_part.splitn(3, ':');
+ let codepoint = fields.next().unwrap_or_default();
+ let stripped = match fields.next() {
+ Some(shifted) if !shifted.is_empty() => format!("{codepoint}:{shifted}"),
+ _ => codepoint.to_string(),
+ };
+ if rest.is_empty() {
+ stripped
+ } else {
+ format!("{stripped};{rest}")
+ }
+ }
+
+ const LAYOUT_KEY_CHORDS: &[&str] = &[
+ // German \u{f6} on `;`, French \u{e9} on `2`, Turkish \u{131} on `i`,
+ // Nordic \u{e5} on `[`: Ctrl, Alt, Super, Ctrl+Shift, press and release.
+ "\x1b[246::59;5u",
+ "\x1b[246::59;5:3u",
+ "\x1b[246:214:59;6u",
+ "\x1b[233::50;5u",
+ "\x1b[233::50;3u",
+ "\x1b[305::105;5u",
+ "\x1b[305:73:105;6u",
+ "\x1b[229::91;5u",
+ "\x1b[229::91;9u",
+ "\x1b[229:197:91;6:3u",
+ // Textless AltGr (Ctrl+Alt), Latin and non-Latin.
+ "\x1b[281::101;7u",
+ "\x1b[281::101;7:3u",
+ "\x1b[1094::119;7u",
+ // Non-Latin chords other than Ctrl alone: plain, Shift, Ctrl+Shift,
+ // Alt, Super, Ctrl+Super. Ghostty sends the layout character for them.
+ "\x1b[1094::119;1u",
+ "\x1b[1094:1062:119;2u",
+ "\x1b[1093:1061:91;6u",
+ "\x1b[1094:1062:119;6:3u",
+ "\x1b[1094::119;3u",
+ "\x1b[1094::119;9u",
+ "\x1b[1094::119;13u",
+ // A chord that generated text is typing.
+ "\x1b[1094::119;5;1094u",
+ // Keys Ghostty sends no control byte for: Russian \u{448} on `i`,
+ // \u{44c} on `m`, \u{445} on `[`, \u{436} on `;`.
+ "\x1b[1096::105;5u",
+ "\x1b[1100::109;5u",
+ "\x1b[1093::91;5u",
+ "\x1b[1078::59;5u",
+ // macOS Option-generated characters reported with Alt.
+ "\x1b[248::111;3u",
+ "\x1b[8721::119;3u",
+ "\x1b[8721::119;3:3u",
+ ];
+
+ #[test]
+ fn parse_chords_other_than_non_latin_ctrl_keep_layout_key() {
+ for sequence in LAYOUT_KEY_CHORDS {
+ let stripped = without_base_layout_field(sequence);
+ assert_ne!(*sequence, stripped);
+ let key = parse_terminal_key_sequence(sequence).unwrap();
+ let layout_key = parse_terminal_key_sequence(&stripped).unwrap();
+ assert_eq!(key, layout_key, "{sequence:?}");
+ for pane_mode in [&b""[..], b"\x1b[>1u", b"\x1b[>5u", b"\x1b[>31u"] {
+ assert_eq!(
+ crate::pane::test_encode_key_for_app(pane_mode, key.clone()),
+ crate::pane::test_encode_key_for_app(pane_mode, layout_key.clone()),
+ "{sequence:?} {pane_mode:?}"
+ );
+ }
+ }
+ }
+
#[test]
fn parse_wezterm_control_associated_text_keeps_report_all_key_events() {
for (sequence, expected_code, expected_kind) in [