Commit e7f158ffcd

e7f158ffcd07032fcd7eb200eeb4fcfb56664d96

parent: ef868175cb

Unregistered key

Ulyssa <git@ulyssa.dev> · 2024-03-10 06:49 UTC
committer: <noreply@github.com>

Add support for custom key macros (#217)

Layout: unified · split

Cargo.lock +8 −5
@@ -1993,7 +1993,8 @@ dependencies = [
19931993[[package]]
19941994name = "keybindings"
19951995version = "0.0.1"
1996source = "git+https://github.com/ulyssa/modalkit?rev=cb8c8aeb9a499b9b16615ce144f9014d78036e01#cb8c8aeb9a499b9b16615ce144f9014d78036e01"
1996source = "registry+https://github.com/rust-lang/crates.io-index"
1997checksum = "680e4699c91c0622dd70da32c274881aadb1ac86252d738c3641266e90e4ca15"
19971998dependencies = [
19981999 "textwrap",
19992000 "unicode-segmentation",
@@ -2507,8 +2508,9 @@ dependencies = [
25072508
25082509[[package]]
25092510name = "modalkit"
2510version = "0.0.17"
2511source = "git+https://github.com/ulyssa/modalkit?rev=cb8c8aeb9a499b9b16615ce144f9014d78036e01#cb8c8aeb9a499b9b16615ce144f9014d78036e01"
2511version = "0.0.18"
2512source = "registry+https://github.com/rust-lang/crates.io-index"
2513checksum = "f7d68711785c96d06bede5bd38fee2e2ac856cfccce7ea0b3e302bc4c5688010"
25122514dependencies = [
25132515 "anymap2",
25142516 "arboard",
@@ -2528,8 +2530,9 @@ dependencies = [
25282530
25292531[[package]]
25302532name = "modalkit-ratatui"
2531version = "0.0.17"
2532source = "git+https://github.com/ulyssa/modalkit?rev=cb8c8aeb9a499b9b16615ce144f9014d78036e01#cb8c8aeb9a499b9b16615ce144f9014d78036e01"
2533version = "0.0.18"
2534source = "registry+https://github.com/rust-lang/crates.io-index"
2535checksum = "747e3dc36bfc4b62a152a37b6631f471797269afa094f6ba0d7aea768be31e2b"
25332536dependencies = [
25342537 "crossterm",
25352538 "intervaltree",
Cargo.toml +6 −6
@@ -59,14 +59,14 @@ url = {version = "^2.2.2", features = ["serde"]}
5959edit = "0.1.4"
6060
6161[dependencies.modalkit]
62version = "0.0.17"
63git = "https://github.com/ulyssa/modalkit"
64rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
62version = "0.0.18"
63#git = "https://github.com/ulyssa/modalkit"
64#rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
6565
6666[dependencies.modalkit-ratatui]
67version = "0.0.17"
68git = "https://github.com/ulyssa/modalkit"
69rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
67version = "0.0.18"
68#git = "https://github.com/ulyssa/modalkit"
69#rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
7070
7171[dependencies.matrix-sdk]
7272version = "0.7.1"
docs/example_config.json +9 −1
@@ -2,7 +2,7 @@
22 "default_profile": "default",
33 "profiles": {
44 "default": {
5 "user_id": "",
5 "user_id": "@user:matrix.org",
66 "url": "https://matrix.org",
77 "settings": {},
88 "dirs": {}
@@ -34,6 +34,14 @@
3434 }
3535 }
3636 },
37 "layout": {
38 "style": "restore"
39 },
40 "macros": {
41 "i": {
42 "jj": "<Esc>"
43 }
44 },
3745 "dirs": {
3846 "cache": "/home/user/.cache/iamb/",
3947 "logs": "/home/user/.local/share/iamb/logs/",
flake.nix −3
@@ -24,9 +24,6 @@
2424 src = ./.;
2525 cargoLock = {
2626 lockFile = ./Cargo.lock;
27 outputHashes = {
28 "keybindings-0.0.1" = "sha256-6gGviJF4/gzoPxgh0XJXXrhQoWxOTqyI9fwiOE+TY7s=";
29 };
3027 };
3128 nativeBuildInputs = [ pkg-config ];
3229 buildInputs = [ openssl ] ++ lib.optionals stdenv.isDarwin
src/config.rs +137 −8
@@ -19,6 +19,8 @@ use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer, Ser
1919use tracing::Level;
2020use url::Url;
2121
22use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
23
2224use super::base::{
2325 IambError,
2426 IambId,
@@ -29,6 +31,8 @@ use super::base::{
2931 SortOrder,
3032};
3133
34type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
35
3236macro_rules! usage {
3337 ( $($args: tt)* ) => {
3438 println!($($args)*);
@@ -136,6 +140,81 @@ pub enum ConfigError {
136140 Invalid(#[from] serde_json::Error),
137141}
138142
143#[derive(Clone, Debug, Eq, Hash, PartialEq)]
144pub struct Keys(pub Vec<TerminalKey>, pub String);
145pub struct KeysVisitor;
146
147impl<'de> Visitor<'de> for KeysVisitor {
148 type Value = Keys;
149
150 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
151 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
152 }
153
154 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
155 where
156 E: SerdeError,
157 {
158 match TerminalKey::from_macro_str(value) {
159 Ok(keys) => Ok(Keys(keys, value.to_string())),
160 Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
161 }
162 }
163}
164
165impl<'de> Deserialize<'de> for Keys {
166 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
167 where
168 D: Deserializer<'de>,
169 {
170 deserializer.deserialize_str(KeysVisitor)
171 }
172}
173
174#[derive(Clone, Debug, Eq, Hash, PartialEq)]
175pub struct VimModes(pub Vec<VimMode>);
176pub struct VimModesVisitor;
177
178impl<'de> Visitor<'de> for VimModesVisitor {
179 type Value = VimModes;
180
181 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
182 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
183 }
184
185 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
186 where
187 E: SerdeError,
188 {
189 let mut modes = vec![];
190
191 for mode in value.split('|') {
192 let mode = match mode.to_ascii_lowercase().as_str() {
193 "insert" | "i" => VimMode::Insert,
194 "normal" | "n" => VimMode::Normal,
195 "visual" | "v" => VimMode::Visual,
196 "command" | "c" => VimMode::Command,
197 "select" => VimMode::Select,
198 "operator-pending" => VimMode::OperationPending,
199 _ => return Err(E::custom("Could not parse into a Vim mode")),
200 };
201
202 modes.push(mode);
203 }
204
205 Ok(VimModes(modes))
206 }
207}
208
209impl<'de> Deserialize<'de> for VimModes {
210 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
211 where
212 D: Deserializer<'de>,
213 {
214 deserializer.deserialize_str(VimModesVisitor)
215 }
216}
217
139218#[derive(Clone, Debug, Eq, PartialEq)]
140219pub struct LogLevel(pub Level);
141220pub struct LogLevelVisitor;
@@ -276,7 +355,10 @@ fn merge_sorts(a: SortOverrides, b: SortOverrides) -> SortOverrides {
276355 }
277356}
278357
279fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
358fn merge_maps<K, V>(a: Option<HashMap<K, V>>, b: Option<HashMap<K, V>>) -> Option<HashMap<K, V>>
359where
360 K: Eq + Hash,
361{
280362 match (a, b) {
281363 (Some(a), None) => Some(a),
282364 (None, Some(b)) => Some(b),
@@ -431,7 +513,7 @@ impl Tunables {
431513 sort: merge_sorts(self.sort, other.sort),
432514 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
433515 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
434 users: merge_users(self.users, other.users),
516 users: merge_maps(self.users, other.users),
435517 username_display: self.username_display.or(other.username_display),
436518 message_user_color: self.message_user_color.or(other.message_user_color),
437519 default_room: self.default_room.or(other.default_room),
@@ -583,6 +665,7 @@ pub struct ProfileConfig {
583665 pub settings: Option<Tunables>,
584666 pub dirs: Option<Directories>,
585667 pub layout: Option<Layout>,
668 pub macros: Option<Macros>,
586669}
587670
588671#[derive(Clone, Deserialize)]
@@ -592,6 +675,7 @@ pub struct IambConfig {
592675 pub settings: Option<Tunables>,
593676 pub dirs: Option<Directories>,
594677 pub layout: Option<Layout>,
678 pub macros: Option<Macros>,
595679}
596680
597681impl IambConfig {
@@ -624,6 +708,7 @@ pub struct ApplicationSettings {
624708 pub tunables: TunableValues,
625709 pub dirs: DirectoryValues,
626710 pub layout: Layout,
711 pub macros: Macros,
627712}
628713
629714impl ApplicationSettings {
@@ -645,6 +730,7 @@ impl ApplicationSettings {
645730 dirs,
646731 settings: global,
647732 layout,
733 macros,
648734 } = IambConfig::load(config_json.as_path())?;
649735
650736 validate_profile_names(&profiles);
@@ -668,6 +754,7 @@ impl ApplicationSettings {
668754 );
669755 };
670756
757 let macros = merge_maps(macros, profile.macros.take()).unwrap_or_default();
671758 let layout = profile.layout.take().or(layout).unwrap_or_default();
672759
673760 let tunables = global.unwrap_or_default();
@@ -721,6 +808,7 @@ impl ApplicationSettings {
721808 tunables,
722809 dirs,
723810 layout,
811 macros,
724812 };
725813
726814 Ok(settings)
@@ -851,22 +939,22 @@ mod tests {
851939 .into_iter()
852940 .collect::<HashMap<_, _>>();
853941
854 let res = merge_users(a.clone(), a.clone());
942 let res = merge_maps(a.clone(), a.clone());
855943 assert_eq!(res, None);
856944
857 let res = merge_users(a.clone(), Some(b.clone()));
945 let res = merge_maps(a.clone(), Some(b.clone()));
858946 assert_eq!(res, Some(b.clone()));
859947
860 let res = merge_users(Some(b.clone()), a.clone());
948 let res = merge_maps(Some(b.clone()), a.clone());
861949 assert_eq!(res, Some(b.clone()));
862950
863 let res = merge_users(Some(b.clone()), Some(b.clone()));
951 let res = merge_maps(Some(b.clone()), Some(b.clone()));
864952 assert_eq!(res, Some(b.clone()));
865953
866 let res = merge_users(Some(b.clone()), Some(c.clone()));
954 let res = merge_maps(Some(b.clone()), Some(c.clone()));
867955 assert_eq!(res, Some(c.clone()));
868956
869 let res = merge_users(Some(c.clone()), Some(b.clone()));
957 let res = merge_maps(Some(c.clone()), Some(b.clone()));
870958 assert_eq!(res, Some(b.clone()));
871959 }
872960
@@ -1012,4 +1100,45 @@ mod tests {
10121100 let tabs = vec![split1, split3];
10131101 assert_eq!(res, Layout::Config { tabs });
10141102 }
1103
1104 #[test]
1105 fn test_parse_macros() {
1106 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1107 assert_eq!(res.len(), 1);
1108
1109 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1110 let mapped = res.get(&modes).unwrap();
1111 assert_eq!(mapped.len(), 1);
1112
1113 let j = "j".parse::<TerminalKey>().unwrap();
1114 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1115
1116 let jj = Keys(vec![j.clone(), j], "jj".into());
1117 let run = mapped.get(&jj).unwrap();
1118 let exp = Keys(vec![esc], "<Esc>".into());
1119 assert_eq!(run, &exp);
1120 }
1121
1122 #[test]
1123 fn test_load_example_config_json() {
1124 let path = PathBuf::from("docs/example_config.json");
1125 let config = IambConfig::load(&path).expect("can load example_config.json");
1126
1127 let IambConfig {
1128 profiles,
1129 default_profile,
1130 settings,
1131 dirs,
1132 layout,
1133 macros,
1134 } = config;
1135
1136 // There should be an example object for each top-level field.
1137 assert!(!profiles.is_empty());
1138 assert!(default_profile.is_some());
1139 assert!(settings.is_some());
1140 assert!(dirs.is_some());
1141 assert!(layout.is_some());
1142 assert!(macros.is_some());
1143 }
10151144}
src/keybindings.rs +34 −21
@@ -3,16 +3,23 @@
33//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim
44//! keys come from [modalkit::env::vim::keybindings].
55use modalkit::{
6 actions::WindowAction,
6 actions::{MacroAction, WindowAction},
77 env::vim::keybindings::{InputStep, VimBindings},
88 env::vim::VimMode,
9 env::CommonKeyClass,
910 key::TerminalKey,
1011 keybindings::{EdgeEvent, EdgeRepeat, InputBindings},
12 prelude::Count,
1113};
1214
1315use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
16use crate::config::{ApplicationSettings, Keys};
1417
15type IambStep = InputStep<IambInfo>;
18pub type IambStep = InputStep<IambInfo>;
19
20fn once(key: &TerminalKey) -> (EdgeRepeat, EdgeEvent<TerminalKey, CommonKeyClass>) {
21 (EdgeRepeat::Once, EdgeEvent::Key(*key))
22}
1623
1724/// Initialize the default keybinding state.
1825pub fn setup_keybindings() -> Keybindings {
@@ -24,20 +31,14 @@ pub fn setup_keybindings() -> Keybindings {
2431
2532 vim.setup(&mut ism);
2633
27 let ctrl_w = EdgeEvent::Key("<C-W>".parse::<TerminalKey>().unwrap());
28 let ctrl_m = EdgeEvent::Key("<C-M>".parse::<TerminalKey>().unwrap());
29 let ctrl_z = EdgeEvent::Key("<C-Z>".parse::<TerminalKey>().unwrap());
30 let key_m_lc = EdgeEvent::Key("m".parse::<TerminalKey>().unwrap());
31 let key_z_lc = EdgeEvent::Key("z".parse::<TerminalKey>().unwrap());
34 let ctrl_w = "<C-W>".parse::<TerminalKey>().unwrap();
35 let ctrl_m = "<C-M>".parse::<TerminalKey>().unwrap();
36 let ctrl_z = "<C-Z>".parse::<TerminalKey>().unwrap();
37 let key_m_lc = "m".parse::<TerminalKey>().unwrap();
38 let key_z_lc = "z".parse::<TerminalKey>().unwrap();
3239
33 let cwz = vec![
34 (EdgeRepeat::Once, ctrl_w.clone()),
35 (EdgeRepeat::Once, key_z_lc),
36 ];
37 let cwcz = vec![
38 (EdgeRepeat::Once, ctrl_w.clone()),
39 (EdgeRepeat::Once, ctrl_z),
40 ];
40 let cwz = vec![once(&ctrl_w), once(&key_z_lc)];
41 let cwcz = vec![once(&ctrl_w), once(&ctrl_z)];
4142 let zoom = IambStep::new()
4243 .actions(vec![WindowAction::ZoomToggle.into()])
4344 .goto(VimMode::Normal);
@@ -47,11 +48,8 @@ pub fn setup_keybindings() -> Keybindings {
4748 ism.add_mapping(VimMode::Normal, &cwcz, &zoom);
4849 ism.add_mapping(VimMode::Visual, &cwcz, &zoom);
4950
50 let cwm = vec![
51 (EdgeRepeat::Once, ctrl_w.clone()),
52 (EdgeRepeat::Once, key_m_lc),
53 ];
54 let cwcm = vec![(EdgeRepeat::Once, ctrl_w), (EdgeRepeat::Once, ctrl_m)];
51 let cwm = vec![once(&ctrl_w), once(&key_m_lc)];
52 let cwcm = vec![once(&ctrl_w), once(&ctrl_m)];
5553 let stoggle = IambStep::new()
5654 .actions(vec![IambAction::ToggleScrollbackFocus.into()])
5755 .goto(VimMode::Normal);
@@ -59,6 +57,21 @@ pub fn setup_keybindings() -> Keybindings {
5957 ism.add_mapping(VimMode::Visual, &cwm, &stoggle);
6058 ism.add_mapping(VimMode::Normal, &cwcm, &stoggle);
6159 ism.add_mapping(VimMode::Visual, &cwcm, &stoggle);
60 ism
61}
62
63impl InputBindings<TerminalKey, IambStep> for ApplicationSettings {
64 fn setup(&self, bindings: &mut Keybindings) {
65 for (modes, keys) in &self.macros {
66 for (Keys(input, _), Keys(_, run)) in keys {
67 let act = MacroAction::Run(run.clone(), Count::Contextual);
68 let step = IambStep::new().actions(vec![act.into()]);
69 let input = input.iter().map(once).collect::<Vec<_>>();
6270
63 return ism;
71 for mode in &modes.0 {
72 bindings.add_mapping(*mode, &input, &step);
73 }
74 }
75 }
76 }
6477}
src/main.rs +3 −1
@@ -29,6 +29,7 @@ use std::time::Duration;
2929use clap::Parser;
3030use matrix_sdk::crypto::encrypt_room_key_export;
3131use matrix_sdk::ruma::OwnedUserId;
32use modalkit::keybindings::InputBindings;
3233use rand::{distributions::Alphanumeric, Rng};
3334use temp_dir::TempDir;
3435use tokio::sync::Mutex as AsyncMutex;
@@ -257,7 +258,8 @@ impl Application {
257258 let backend = CrosstermBackend::new(stdout);
258259 let terminal = Terminal::new(backend)?;
259260
260 let bindings = crate::keybindings::setup_keybindings();
261 let mut bindings = crate::keybindings::setup_keybindings();
262 settings.setup(&mut bindings);
261263 let bindings = KeyManager::new(bindings);
262264
263265 let mut locked = store.lock().await;
src/tests.rs +2
@@ -217,10 +217,12 @@ pub fn mock_settings() -> ApplicationSettings {
217217 settings: None,
218218 dirs: None,
219219 layout: None,
220 macros: None,
220221 },
221222 tunables: mock_tunables(),
222223 dirs: mock_dirs(),
223224 layout: Default::default(),
225 macros: HashMap::default(),
224226 }
225227}
226228