Keyboard input

Keyboard input arrives as key events. Event::KeyPress carries a Key for both presses and repeats. The repeat field identifies repeats reported by the terminal. Releases arrive as Event::KeyRelease.

The other Key fields you usually use are code (which key), modifiers (Ctrl, Alt, Shift, and friends), location, and the optional text it would produce.

Matching keys the easy way

For keybindings, check the shortcut text directly with matches or matches_any.

rust
use uncurses::event::Event;

let ev = program.read_event()?;

match ev {
    Event::KeyPress(ref k) if k.matches("ctrl+c") => return Ok(()),
    Event::KeyPress(ref k) if k.matches("f1") => show_help(),
    _ => {}
}

The grammar covers plain characters ("q"), named keys ("enter", "esc", "up", "f1"), and modifier chords ("ctrl+c", "alt+shift+left"). Do not compare k.to_string() to binding strings; display is structural. Under the kitty keyboard protocol, a shifted glyph like } may display as shift+], while k.matches("}") still matches the produced text.

rust
let ev = program.read_event()?;

match ev {
    Event::KeyPress(ref k) if k.matches_any(["q", "esc", "ctrl+c"]) => break,
    _ => {}
}

Matching keys structurally

When you want to branch on the key itself, match on KeyCode and inspect modifiers. modifiers is a bitset, so test it with contains and is_empty.

rust
use uncurses::event::{Event, Key, KeyCode, KeyModifiers};

let ev = program.read_event()?;

match ev {
    Event::KeyPress(Key { code: KeyCode::Char('q'), modifiers, .. })
        if modifiers.is_empty() => break,
    Event::KeyPress(Key { code: KeyCode::Char('c'), modifiers, .. })
        if modifiers.contains(KeyModifiers::CTRL) => break,
    Event::KeyPress(Key { code: KeyCode::Left, .. }) => move_left(),
    _ => {}
}

The modifier flags are SHIFT, ALT, CTRL, META, HYPER, SUPER, CAPS_LOCK, and NUM_LOCK.

A Key carries text only for printable input: a character or space with no modifiers other than Shift, Caps Lock, or Num Lock. Ctrl, Alt, Meta, Hyper, Super, and named keys (Enter, arrows, function keys) clear it. So a present text means the key would type something, already in the right layout ("!" for shift+1), which is what you want for text entry rather than the physical code.

rust
let ev = program.read_event()?;

if let Event::KeyPress(k) = ev {
    if let Some(text) = &k.text {
        buffer.push_str(text); // a printable key: insert what it typed
    }
}

Key locations

KeyCode identifies the logical key. The public location field identifies its position: Standard, Left, Right, or Keypad. For example, both Enter keys use KeyCode::Enter. The keypad Enter key uses KeyLocation::Keypad. Both Ctrl keys use KeyCode::Ctrl, with Left or Right.

The decoder records a location when the input protocol identifies it. Standard also covers input that leaves the location unspecified.

General bindings, such as "enter" and "ctrl+c", match at any location. Use "kpenter" or "rightctrl" to select a location. Location prefixes attach to the key name: "leftctrl", "rightalt", and "kp0". Modifier chords use "+", as in "ctrl+kp0". Explicit location bindings compare the key identity, even when associated text spells the binding. Check key.location == KeyLocation::Standard to select the standard location.

rust
use uncurses::event::{Key, KeyCode, KeyLocation, KeyModifiers};

let enter = Key::new(KeyCode::Enter, KeyModifiers::empty());
let mut keypad_enter = enter.clone();
keypad_enter.location = KeyLocation::Keypad;

assert!(keypad_enter.matches("enter"));
assert!(keypad_enter.matches("kpenter"));
assert!(!enter.matches("kpenter"));
assert_eq!(enter.location, KeyLocation::Standard);
assert_ne!(enter, keypad_enter);

Equality and hashing include the code, location, and modifiers, with lock bits excluded. Text, alternate key values, and repeat status are event metadata. Run cargo run --example key_locations for a terminal-independent example. Use keylog to inspect locations reported by your terminal.

Change legacy key decoding at runtime

ProgramOptions::legacy_keys selects the initial decoder flags. Use Program::decoder_flags() to read the active flags and Program::set_decoder_flags() to change them during a session.

rust
use uncurses::event::DecoderFlags;

let mut flags = program.decoder_flags();
flags.insert(DecoderFlags::LF_IS_ENTER);
program.set_decoder_flags(flags);

This makes subsequent legacy LF bytes read as Enter instead of Ctrl+J. The shared event source uses the new flags for subsequent decoding. Already-decoded events keep their values, including events returned through unread_event(). The setter leaves terminal modes and ProgramOptions::legacy_keys unchanged.

Run cargo run --example legacy_keys and press F2 to switch the LF mapping. Press Ctrl+J after each switch to see the decoded key.

Legacy Escape timing

Legacy terminals use the same bytes for some Alt keys and control sequence prefixes. For example, \x1b[ can mean Alt+[ or the start of CSI. An idle two-byte introducer resolves to one Alt-modified key. A new Escape sequence also resolves a bare two-byte introducer as an Alt key, then decodes normally. For example, \x1b[\x1ba yields Alt+[ followed by Alt+a. A lone Escape resolves when its own deadline expires, before another read.

EventSource::with_esc_timeout sets the wait, with a default of 50 milliseconds. New bytes reset the deadline while a key sequence remains incomplete. The source checks for ready continuation bytes before it expires that sequence.

Once bytes follow an OSC, DCS, APC, SOS, or PM introducer, the decoder treats them as a string body. The Escape timeout then stops applying. OSC 52 replies stream through clipboard events with a separate idle timeout. See clipboard replies for recovery controls. Known replies, such as drag and drop messages, wait for their terminator. An unknown string body of up to 4096 bytes arrives as one Event::Unknown { kind, bytes }. A longer unknown body streams through StringStart { kind }, StringChunk(bytes), and StringEnd { complete }. A streamed string ends with StringEnd { complete: false } after two seconds without input. Use EventSource::with_string_idle_timeout or set_string_idle_timeout to change that timeout, and call EventSource::end_string() for explicit recovery. The unknown_strings example prints both forms and an idle timeout.

The timeout passed to EventSource::poll limits the caller’s wait. An incomplete buffered string remains available for subsequent reads.

A new Escape sequence also interrupts an unfinished CSI or control string. For buffered sequences with a body, the source reports the interrupted bytes as Event::Unknown, then decodes the new sequence. Clipboard and string streams instead emit ClipboardEnd { complete: false } or StringEnd { complete: false }. A trailing Escape in a string waits for another byte, so a split ESC \ still terminates the string normally, including an empty string.

An unterminated string can absorb ordinary keystrokes until a terminator or another Escape sequence arrives. This reflects a limit of legacy input: Alt+] followed quickly by text can have the same bytes as an OSC string. The Kitty keyboard protocol provides distinct key encodings.

Run cargo run --example legacy_keys and press Alt+[ or Alt+]. The example displays the decoded key and its Alt modifier.

Presses, repeats, and releases

A held key can produce several KeyPress events. When the input protocol identifies an auto-repeat, key.repeat is true. A value of false means the input did not identify a repeat. Decoder-generated releases use false.

Key equality, hashing, shortcut matching, and display use the key identity. Inspect key.repeat separately for commands that must run once per press:

rust
use uncurses::event::Event;

match program.read_event()? {
    Event::KeyPress(key) if !key.repeat && key.matches("f1") => show_help(),
    _ => {}
}

The Kitty keyboard protocol can identify repeats and report releases. Select the flags with set_kitty_keyboard. Pass Some(flags) to enable the bits you want, or None to switch every enhancement back off.

rust
use uncurses::ansi::kitty::KittyKeyboardFlags;

program.set_kitty_keyboard(Some(
    KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES
        | KittyKeyboardFlags::REPORT_EVENT_TYPES,
))?;

// ... now your loop can also see, for keys sent as escape codes:
//   Event::KeyPress(k) with k.repeat == true
//   Event::KeyRelease(k)

The flags combine, and each one enables a specific behavior:

  • DISAMBIGUATE_ESCAPE_CODES makes keys that the legacy encoding blurs together distinct: Esc on its own, Ctrl+I versus Tab, and Ctrl+M versus Enter all become unambiguous escape codes.
  • REPORT_EVENT_TYPES identifies repeats and adds KeyRelease for keys sent as escape codes: arrows, function keys, and modified keys sent as sequences. Keys that produce text still arrive as plain UTF-8. A held letter produces KeyPress events with repeat set to false.
  • REPORT_ALL_KEYS_AS_ESCAPE reports every key as an escape code, including printable keys. Combine it with REPORT_EVENT_TYPES when you want repeats and releases for letters and digits too, for instance to track a held w in a game.
  • REPORT_ALTERNATE_KEYS adds shifted and base key values.
  • REPORT_ASSOCIATED_TEXT adds the produced text.

A terminal that does not speak the protocol ignores the request, so you keep getting plain presses and it is safe to ask unconditionally.

See the keylog example in examples/examples/ for a live readout of every key, modifier, repeat, and release.

Edit this page

Search documentation

Type to search the documentation.