keymap-rs
keymap-rs is a lightweight and extensible key mapping library for Rust applications. It supports parsing key mappings from configuration files and mapping them to actions based on input events from backends like crossterm, termion, wasm (via web_sys), and others.
ð§ Features (v1.0.0)
- â Declarative key mappings via configuration (e.g., YAML, JSON, etc.)
- âĻïļ Supports single keys (e.g.
a,enter,ctrl-b, etc.) and key sequences (e.g.ctrl-b n) - ð§ Supports key groups:
@upperâ uppercase letters@lowerâ lowercase letters@alphaâ all alphabetic characters@alnumâ alphanumeric@anyâ match any key
- ð§Ž Derive-based config parser via
keymap_derive - ð Backend-agnostic (works with
crossterm,termion,web_sys, etc.) - ðŠķ Lightweight and extensible
ðĶ Installation
Run the following command:
[!NOTE] By default, this installs with
crosstermas the default backend. You can enable a different backend by specifying the feature flag:
ð Example
Using keymap_derive
Define your actions and key mappings:
/// Game actions
Use the config:
let config = keymap_config;
if let Key = read?
Using external configuration (e.g. toml, yaml, etc.)
Define a config:
= { = ["j", "up"], = "Jump with 'j'!" }
= { = ["@any"], = "Quit!" }
Deserialize with Config<T>
[!NOTE] The table below shows all keys that are deserialized only from the configuration file. Keys defined via
#[key("..")]are not included.
Key Action "j","up"Jump @anyQuit
let config: = from_str.unwrap;
Deserialize with DerivedConfig<T>
[!NOTE] The table below shows all keys when using both the configuration file and the keys defined via
#[key("..")]. The sets are merged.
Key Action "j","up"Jump "left"Left "right"Right @anyQuit
let config: = from_str.unwrap;
ð ïļ Bonus: Compile-time Validation
One powerful advantage of using the #[key(".."))] attribute macro from keymap_derive is that invalid key definitions are caught at compile time, ensuring early feedback and safety.
Example: Invalid Key
Compile Error
error: Invalid key "enter2": Parse error at position 5: expect end of input, found: 2
--> keymap_derive/tests/derive.rs:7:11
|
7 | #[key("enter2", "ctrl-b n")]
| ^^^^^^^^
This prevents runtime surprises and provides clear diagnostics during development.
ð License
This project is licensed under the MIT License.
ð Contributions
Contributions, issues, and feature requests are welcome. Have an idea for a new backend, pattern rule, or integration? Open a PR!