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 = [
1993[[package]] 1993[[package]]
1994name = "keybindings" 1994name = "keybindings"
1995version = "0.0.1" 1995version = "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"
1997dependencies = [ 1998dependencies = [
1998 "textwrap", 1999 "textwrap",
1999 "unicode-segmentation", 2000 "unicode-segmentation",
@@ -2507,8 +2508,9 @@ dependencies = [
2507 2508
2508[[package]] 2509[[package]]
2509name = "modalkit" 2510name = "modalkit"
2510version = "0.0.17" 2511version = "0.0.18"
2511source = "git+https://github.com/ulyssa/modalkit?rev=cb8c8aeb9a499b9b16615ce144f9014d78036e01#cb8c8aeb9a499b9b16615ce144f9014d78036e01" 2512source = "registry+https://github.com/rust-lang/crates.io-index"
2513checksum = "f7d68711785c96d06bede5bd38fee2e2ac856cfccce7ea0b3e302bc4c5688010"
2512dependencies = [ 2514dependencies = [
2513 "anymap2", 2515 "anymap2",
2514 "arboard", 2516 "arboard",
@@ -2528,8 +2530,9 @@ dependencies = [
2528 2530
2529[[package]] 2531[[package]]
2530name = "modalkit-ratatui" 2532name = "modalkit-ratatui"
2531version = "0.0.17" 2533version = "0.0.18"
2532source = "git+https://github.com/ulyssa/modalkit?rev=cb8c8aeb9a499b9b16615ce144f9014d78036e01#cb8c8aeb9a499b9b16615ce144f9014d78036e01" 2534source = "registry+https://github.com/rust-lang/crates.io-index"
2535checksum = "747e3dc36bfc4b62a152a37b6631f471797269afa094f6ba0d7aea768be31e2b"
2533dependencies = [ 2536dependencies = [
2534 "crossterm", 2537 "crossterm",
2535 "intervaltree", 2538 "intervaltree",
Cargo.toml +6 −6
@@ -59,14 +59,14 @@ url = {version = "^2.2.2", features = ["serde"]}
59edit = "0.1.4" 59edit = "0.1.4"
60 60
61[dependencies.modalkit] 61[dependencies.modalkit]
62version = "0.0.17" 62version = "0.0.18"
63git = "https://github.com/ulyssa/modalkit" 63#git = "https://github.com/ulyssa/modalkit"
64rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01" 64#rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
65 65
66[dependencies.modalkit-ratatui] 66[dependencies.modalkit-ratatui]
67version = "0.0.17" 67version = "0.0.18"
68git = "https://github.com/ulyssa/modalkit" 68#git = "https://github.com/ulyssa/modalkit"
69rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01" 69#rev = "cb8c8aeb9a499b9b16615ce144f9014d78036e01"
70 70
71[dependencies.matrix-sdk] 71[dependencies.matrix-sdk]
72version = "0.7.1" 72version = "0.7.1"
docs/example_config.json +9 −1
@@ -2,7 +2,7 @@
2 "default_profile": "default", 2 "default_profile": "default",
3 "profiles": { 3 "profiles": {
4 "default": { 4 "default": {
5 "user_id": "", 5 "user_id": "@user:matrix.org",
6 "url": "https://matrix.org", 6 "url": "https://matrix.org",
7 "settings": {}, 7 "settings": {},
8 "dirs": {} 8 "dirs": {}
@@ -34,6 +34,14 @@
34 } 34 }
35 } 35 }
36 }, 36 },
37 "layout": {
38 "style": "restore"
39 },
40 "macros": {
41 "i": {
42 "jj": "<Esc>"
43 }
44 },
37 "dirs": { 45 "dirs": {
38 "cache": "/home/user/.cache/iamb/", 46 "cache": "/home/user/.cache/iamb/",
39 "logs": "/home/user/.local/share/iamb/logs/", 47 "logs": "/home/user/.local/share/iamb/logs/",
flake.nix −3
@@ -24,9 +24,6 @@
24 src = ./.; 24 src = ./.;
25 cargoLock = { 25 cargoLock = {
26 lockFile = ./Cargo.lock; 26 lockFile = ./Cargo.lock;
27 outputHashes = {
28 "keybindings-0.0.1" = "sha256-6gGviJF4/gzoPxgh0XJXXrhQoWxOTqyI9fwiOE+TY7s=";
29 };
30 }; 27 };
31 nativeBuildInputs = [ pkg-config ]; 28 nativeBuildInputs = [ pkg-config ];
32 buildInputs = [ openssl ] ++ lib.optionals stdenv.isDarwin 29 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
19use tracing::Level; 19use tracing::Level;
20use url::Url; 20use url::Url;
21 21
22use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
23
22use super::base::{ 24use super::base::{
23 IambError, 25 IambError,
24 IambId, 26 IambId,
@@ -29,6 +31,8 @@ use super::base::{
29 SortOrder, 31 SortOrder,
30}; 32};
31 33
34type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
35
32macro_rules! usage { 36macro_rules! usage {
33 ( $($args: tt)* ) => { 37 ( $($args: tt)* ) => {
34 println!($($args)*); 38 println!($($args)*);
@@ -136,6 +140,81 @@ pub enum ConfigError {
136 Invalid(#[from] serde_json::Error), 140 Invalid(#[from] serde_json::Error),
137} 141}
138 142
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
139#[derive(Clone, Debug, Eq, PartialEq)] 218#[derive(Clone, Debug, Eq, PartialEq)]
140pub struct LogLevel(pub Level); 219pub struct LogLevel(pub Level);
141pub struct LogLevelVisitor; 220pub struct LogLevelVisitor;
@@ -276,7 +355,10 @@ fn merge_sorts(a: SortOverrides, b: SortOverrides) -> SortOverrides {
276 } 355 }
277} 356}
278 357
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{
280 match (a, b) { 362 match (a, b) {
281 (Some(a), None) => Some(a), 363 (Some(a), None) => Some(a),
282 (None, Some(b)) => Some(b), 364 (None, Some(b)) => Some(b),
@@ -431,7 +513,7 @@ impl Tunables {
431 sort: merge_sorts(self.sort, other.sort), 513 sort: merge_sorts(self.sort, other.sort),
432 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send), 514 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
433 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display), 515 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),
435 username_display: self.username_display.or(other.username_display), 517 username_display: self.username_display.or(other.username_display),
436 message_user_color: self.message_user_color.or(other.message_user_color), 518 message_user_color: self.message_user_color.or(other.message_user_color),
437 default_room: self.default_room.or(other.default_room), 519 default_room: self.default_room.or(other.default_room),
@@ -583,6 +665,7 @@ pub struct ProfileConfig {
583 pub settings: Option<Tunables>, 665 pub settings: Option<Tunables>,
584 pub dirs: Option<Directories>, 666 pub dirs: Option<Directories>,
585 pub layout: Option<Layout>, 667 pub layout: Option<Layout>,
668 pub macros: Option<Macros>,
586} 669}
587 670
588#[derive(Clone, Deserialize)] 671#[derive(Clone, Deserialize)]
@@ -592,6 +675,7 @@ pub struct IambConfig {
592 pub settings: Option<Tunables>, 675 pub settings: Option<Tunables>,
593 pub dirs: Option<Directories>, 676 pub dirs: Option<Directories>,
594 pub layout: Option<Layout>, 677 pub layout: Option<Layout>,
678 pub macros: Option<Macros>,
595} 679}
596 680
597impl IambConfig { 681impl IambConfig {
@@ -624,6 +708,7 @@ pub struct ApplicationSettings {
624 pub tunables: TunableValues, 708 pub tunables: TunableValues,
625 pub dirs: DirectoryValues, 709 pub dirs: DirectoryValues,
626 pub layout: Layout, 710 pub layout: Layout,
711 pub macros: Macros,
627} 712}
628 713
629impl ApplicationSettings { 714impl ApplicationSettings {
@@ -645,6 +730,7 @@ impl ApplicationSettings {
645 dirs, 730 dirs,
646 settings: global, 731 settings: global,
647 layout, 732 layout,
733 macros,
648 } = IambConfig::load(config_json.as_path())?; 734 } = IambConfig::load(config_json.as_path())?;
649 735
650 validate_profile_names(&profiles); 736 validate_profile_names(&profiles);
@@ -668,6 +754,7 @@ impl ApplicationSettings {
668 ); 754 );
669 }; 755 };
670 756
757 let macros = merge_maps(macros, profile.macros.take()).unwrap_or_default();
671 let layout = profile.layout.take().or(layout).unwrap_or_default(); 758 let layout = profile.layout.take().or(layout).unwrap_or_default();
672 759
673 let tunables = global.unwrap_or_default(); 760 let tunables = global.unwrap_or_default();
@@ -721,6 +808,7 @@ impl ApplicationSettings {
721 tunables, 808 tunables,
722 dirs, 809 dirs,
723 layout, 810 layout,
811 macros,
724 }; 812 };
725 813
726 Ok(settings) 814 Ok(settings)
@@ -851,22 +939,22 @@ mod tests {
851 .into_iter() 939 .into_iter()
852 .collect::<HashMap<_, _>>(); 940 .collect::<HashMap<_, _>>();
853 941
854 let res = merge_users(a.clone(), a.clone()); 942 let res = merge_maps(a.clone(), a.clone());
855 assert_eq!(res, None); 943 assert_eq!(res, None);
856 944
857 let res = merge_users(a.clone(), Some(b.clone())); 945 let res = merge_maps(a.clone(), Some(b.clone()));
858 assert_eq!(res, Some(b.clone())); 946 assert_eq!(res, Some(b.clone()));
859 947
860 let res = merge_users(Some(b.clone()), a.clone()); 948 let res = merge_maps(Some(b.clone()), a.clone());
861 assert_eq!(res, Some(b.clone())); 949 assert_eq!(res, Some(b.clone()));
862 950
863 let res = merge_users(Some(b.clone()), Some(b.clone())); 951 let res = merge_maps(Some(b.clone()), Some(b.clone()));
864 assert_eq!(res, Some(b.clone())); 952 assert_eq!(res, Some(b.clone()));
865 953
866 let res = merge_users(Some(b.clone()), Some(c.clone())); 954 let res = merge_maps(Some(b.clone()), Some(c.clone()));
867 assert_eq!(res, Some(c.clone())); 955 assert_eq!(res, Some(c.clone()));
868 956
869 let res = merge_users(Some(c.clone()), Some(b.clone())); 957 let res = merge_maps(Some(c.clone()), Some(b.clone()));
870 assert_eq!(res, Some(b.clone())); 958 assert_eq!(res, Some(b.clone()));
871 } 959 }
872 960
@@ -1012,4 +1100,45 @@ mod tests {
1012 let tabs = vec![split1, split3]; 1100 let tabs = vec![split1, split3];
1013 assert_eq!(res, Layout::Config { tabs }); 1101 assert_eq!(res, Layout::Config { tabs });
1014 } 1102 }
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 }
1015} 1144}
src/keybindings.rs +34 −21
@@ -3,16 +3,23 @@
3//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim 3//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim
4//! keys come from [modalkit::env::vim::keybindings]. 4//! keys come from [modalkit::env::vim::keybindings].
5use modalkit::{ 5use modalkit::{
6 actions::WindowAction, 6 actions::{MacroAction, WindowAction},
7 env::vim::keybindings::{InputStep, VimBindings}, 7 env::vim::keybindings::{InputStep, VimBindings},
8 env::vim::VimMode, 8 env::vim::VimMode,
9 env::CommonKeyClass,
9 key::TerminalKey, 10 key::TerminalKey,
10 keybindings::{EdgeEvent, EdgeRepeat, InputBindings}, 11 keybindings::{EdgeEvent, EdgeRepeat, InputBindings},
12 prelude::Count,
11}; 13};
12 14
13use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD}; 15use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
16use crate::config::{ApplicationSettings, Keys};
14 17
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}
16 23
17/// Initialize the default keybinding state. 24/// Initialize the default keybinding state.
18pub fn setup_keybindings() -> Keybindings { 25pub fn setup_keybindings() -> Keybindings {
@@ -24,20 +31,14 @@ pub fn setup_keybindings() -> Keybindings {
24 31
25 vim.setup(&mut ism); 32 vim.setup(&mut ism);
26 33
27 let ctrl_w = EdgeEvent::Key("<C-W>".parse::<TerminalKey>().unwrap()); 34 let ctrl_w = "<C-W>".parse::<TerminalKey>().unwrap();
28 let ctrl_m = EdgeEvent::Key("<C-M>".parse::<TerminalKey>().unwrap()); 35 let ctrl_m = "<C-M>".parse::<TerminalKey>().unwrap();
29 let ctrl_z = EdgeEvent::Key("<C-Z>".parse::<TerminalKey>().unwrap()); 36 let ctrl_z = "<C-Z>".parse::<TerminalKey>().unwrap();
30 let key_m_lc = EdgeEvent::Key("m".parse::<TerminalKey>().unwrap()); 37 let key_m_lc = "m".parse::<TerminalKey>().unwrap();
31 let key_z_lc = EdgeEvent::Key("z".parse::<TerminalKey>().unwrap()); 38 let key_z_lc = "z".parse::<TerminalKey>().unwrap();
32 39
33 let cwz = vec![ 40 let cwz = vec![once(&ctrl_w), once(&key_z_lc)];
34 (EdgeRepeat::Once, ctrl_w.clone()), 41 let cwcz = vec![once(&ctrl_w), once(&ctrl_z)];
35 (EdgeRepeat::Once, key_z_lc),
36 ];
37 let cwcz = vec![
38 (EdgeRepeat::Once, ctrl_w.clone()),
39 (EdgeRepeat::Once, ctrl_z),
40 ];
41 let zoom = IambStep::new() 42 let zoom = IambStep::new()
42 .actions(vec![WindowAction::ZoomToggle.into()]) 43 .actions(vec![WindowAction::ZoomToggle.into()])
43 .goto(VimMode::Normal); 44 .goto(VimMode::Normal);
@@ -47,11 +48,8 @@ pub fn setup_keybindings() -> Keybindings {
47 ism.add_mapping(VimMode::Normal, &cwcz, &zoom); 48 ism.add_mapping(VimMode::Normal, &cwcz, &zoom);
48 ism.add_mapping(VimMode::Visual, &cwcz, &zoom); 49 ism.add_mapping(VimMode::Visual, &cwcz, &zoom);
49 50
50 let cwm = vec![ 51 let cwm = vec![once(&ctrl_w), once(&key_m_lc)];
51 (EdgeRepeat::Once, ctrl_w.clone()), 52 let cwcm = vec![once(&ctrl_w), once(&ctrl_m)];
52 (EdgeRepeat::Once, key_m_lc),
53 ];
54 let cwcm = vec![(EdgeRepeat::Once, ctrl_w), (EdgeRepeat::Once, ctrl_m)];
55 let stoggle = IambStep::new() 53 let stoggle = IambStep::new()
56 .actions(vec![IambAction::ToggleScrollbackFocus.into()]) 54 .actions(vec![IambAction::ToggleScrollbackFocus.into()])
57 .goto(VimMode::Normal); 55 .goto(VimMode::Normal);
@@ -59,6 +57,21 @@ pub fn setup_keybindings() -> Keybindings {
59 ism.add_mapping(VimMode::Visual, &cwm, &stoggle); 57 ism.add_mapping(VimMode::Visual, &cwm, &stoggle);
60 ism.add_mapping(VimMode::Normal, &cwcm, &stoggle); 58 ism.add_mapping(VimMode::Normal, &cwcm, &stoggle);
61 ism.add_mapping(VimMode::Visual, &cwcm, &stoggle); 59 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<_>>();
62 70
63 return ism; 71 for mode in &modes.0 {
72 bindings.add_mapping(*mode, &input, &step);
73 }
74 }
75 }
76 }
64} 77}
src/main.rs +3 −1
@@ -29,6 +29,7 @@ use std::time::Duration;
29use clap::Parser; 29use clap::Parser;
30use matrix_sdk::crypto::encrypt_room_key_export; 30use matrix_sdk::crypto::encrypt_room_key_export;
31use matrix_sdk::ruma::OwnedUserId; 31use matrix_sdk::ruma::OwnedUserId;
32use modalkit::keybindings::InputBindings;
32use rand::{distributions::Alphanumeric, Rng}; 33use rand::{distributions::Alphanumeric, Rng};
33use temp_dir::TempDir; 34use temp_dir::TempDir;
34use tokio::sync::Mutex as AsyncMutex; 35use tokio::sync::Mutex as AsyncMutex;
@@ -257,7 +258,8 @@ impl Application {
257 let backend = CrosstermBackend::new(stdout); 258 let backend = CrosstermBackend::new(stdout);
258 let terminal = Terminal::new(backend)?; 259 let terminal = Terminal::new(backend)?;
259 260
260 let bindings = crate::keybindings::setup_keybindings(); 261 let mut bindings = crate::keybindings::setup_keybindings();
262 settings.setup(&mut bindings);
261 let bindings = KeyManager::new(bindings); 263 let bindings = KeyManager::new(bindings);
262 264
263 let mut locked = store.lock().await; 265 let mut locked = store.lock().await;
src/tests.rs +2
@@ -217,10 +217,12 @@ pub fn mock_settings() -> ApplicationSettings {
217 settings: None, 217 settings: None,
218 dirs: None, 218 dirs: None,
219 layout: None, 219 layout: None,
220 macros: None,
220 }, 221 },
221 tunables: mock_tunables(), 222 tunables: mock_tunables(),
222 dirs: mock_dirs(), 223 dirs: mock_dirs(),
223 layout: Default::default(), 224 layout: Default::default(),
225 macros: HashMap::default(),
224 } 226 }
225} 227}
226 228