1use crate::{
2 key::{Key, Keys},
3 trie::{GetError, InsertError, Match, Trie},
4};
5use arrayvec::ArrayVec;
6use std::mem;
7
8pub enum Mapping<V> {
9 Static(V),
10 Any(fn(Key) -> Option<V>),
11}
12
13impl<V> From<V> for Mapping<V> {
14 fn from(value: V) -> Self {
15 Self::Static(value)
16 }
17}
18
19struct Entry<V> {
20 value: Mapping<V>,
21 order: u16,
22 description: Option<&'static str>,
23}
24
25pub struct Keymap<V> {
26 mappings: Trie<Key, Entry<V>>,
27 next_order: u16,
28}
29
30impl<V> Keymap<V> {
31 #[must_use]
32 pub fn new() -> Self {
33 Self {
34 mappings: Trie::default(),
35 next_order: 0,
36 }
37 }
38
39 pub fn insert(
40 &mut self,
41 keys: &str,
42 value: impl Into<Mapping<V>>,
43 description: Option<&'static str>,
44 ) -> Result<Option<Mapping<V>>, InsertError> {
45 let value = value.into();
46 let keys: Keys = keys.parse().unwrap();
47 let anys = keys.0.iter().filter(|key| **key == Key::ANY).count();
48 match value {
49 Mapping::Static(_) => {
50 assert_eq!(anys, 0, "`Mapping::Static` forbids `<any>` keys");
51 }
52 Mapping::Any(_) => {
53 assert_eq!(anys, 1, "`Mapping::Any` requires exactly one `<any>` key");
54 }
55 }
56 if let Ok(entry) = self.mappings.get_mut(&keys.0) {
57 entry.description = description;
59 return Ok(Some(mem::replace(&mut entry.value, value)));
60 }
61 let order = self.next_order;
62 self.next_order = order.checked_add(1).expect("wow that's a lotta keys");
63 self.mappings.insert(
64 &keys.0,
65 Entry {
66 value,
67 order,
68 description,
69 },
70 )?;
71 Ok(None)
72 }
73
74 pub fn remove(&mut self, keys: &str) -> Option<Mapping<V>> {
75 let keys: Keys = keys.parse().unwrap();
76 self.mappings.remove(&keys.0).map(|entry| entry.value)
77 }
78
79 #[must_use]
80 pub fn get(&self, keys: &str) -> KeymapResult<'_, V> {
81 let keys: Keys = keys.parse().unwrap();
82 self.get_keys(&keys.0)
83 }
84
85 #[must_use]
86 pub fn get_keys(&self, keys: &[Key]) -> KeymapResult<'_, V> {
87 match self.mappings.get::<3>(keys, &Key::ANY) {
88 Err(GetError::Missing) => KeymapResult::Unmapped,
89 Err(GetError::Partial) => KeymapResult::Pending,
90 Ok(Match {
91 value: entry,
92 captures,
93 }) => match &entry.value {
94 Mapping::Static(value) => KeymapResult::Mapped(value),
95 Mapping::Any(f) => {
96 if let &[key] = captures.as_slice()
97 && let Some(value) = f(key)
98 {
99 KeymapResult::Computed(value)
100 } else {
101 KeymapResult::Unmapped
102 }
103 }
104 },
105 }
106 }
107
108 fn entries(&self) -> impl Iterator<Item = (ArrayVec<Key, 3>, &Entry<V>)> {
109 let mut pairs: Vec<_> = self.mappings.iter::<3>().collect();
110 pairs.sort_by_key(|(_, entry)| entry.order);
111 pairs.into_iter()
112 }
113
114 pub fn iter(&self) -> impl Iterator<Item = (ArrayVec<Key, 3>, &Mapping<V>)> + '_ {
115 self.entries().map(|(keys, entry)| (keys, &entry.value))
116 }
117
118 pub fn docs(
119 &self,
120 ) -> impl Iterator<Item = (Keys<ArrayVec<Key, 3>>, Option<&'static str>)> + '_ {
121 self.entries()
122 .map(|(keys, entry)| (Keys(keys), entry.description))
123 }
124}
125
126impl<'a, V> IntoIterator for &'a Keymap<V> {
127 type Item = (ArrayVec<Key, 3>, &'a Mapping<V>);
128 type IntoIter = std::vec::IntoIter<(ArrayVec<Key, 3>, &'a Mapping<V>)>;
129 fn into_iter(self) -> Self::IntoIter {
130 self.iter().collect::<Vec<_>>().into_iter()
131 }
132}
133
134impl<V> Default for Keymap<V> {
135 fn default() -> Self {
136 Self::new()
137 }
138}
139
140#[macro_export]
141macro_rules! keymap {
142 ($value_ty:ty; $($keys:literal => $value:expr, $(#[doc = $desc:literal])?)*) => {{
144 let mut keymap: $crate::Keymap<$value_ty> = $crate::Keymap::new();
145 $(keymap.insert($keys, $value, None $(.or(Some($desc.trim())))?).unwrap();)*
146 keymap
147 }};
148 ($($keys:literal => $value:expr, $(#[doc = $desc:literal])?)*) => {
150 $crate::keymap! { _;
151 $($keys => $value, $(#[doc = $desc])?)*
152 }
153 };
154}
155
156#[derive(Debug, PartialEq)]
157pub enum KeymapResult<'a, V> {
158 Unmapped,
159 Pending,
160 Mapped(&'a V),
161 Computed(V),
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 #[derive(Clone, Debug, PartialEq)]
169 struct Action(&'static str);
170
171 #[test]
172 fn keymap_get() {
173 let keymap = keymap! {
174 "gj" => vec![Action("move to bottom")],
175 };
176 assert_eq!(keymap.get("x"), KeymapResult::Unmapped);
177 assert_eq!(keymap.get("g"), KeymapResult::Pending);
178 assert_eq!(
179 keymap.get("gj"),
180 KeymapResult::Mapped(&vec![Action("move to bottom")])
181 );
182 }
183
184 #[test]
185 fn keymap_remove() {
186 let mut keymap = keymap! {
187 "gj" => vec![Action("move to bottom")],
188 "gk" => vec![Action("move to top")],
189 };
190 assert_eq!(
191 keymap.get("gj"),
192 KeymapResult::Mapped(&vec![Action("move to bottom")])
193 );
194 assert!(matches!(
195 keymap.remove("gj"),
196 Some(Mapping::Static(value)) if value == vec![Action("move to bottom")]
197 ));
198 assert_eq!(keymap.get("gj"), KeymapResult::Unmapped);
199 assert_eq!(
201 keymap.get("gk"),
202 KeymapResult::Mapped(&vec![Action("move to top")])
203 );
204 assert!(keymap.remove("x").is_none());
206 }
207
208 #[test]
209 fn keymap_any() {
210 let keymap = keymap! { Vec<Key>;
211 "f<any>" => Mapping::Any(|key| Some(vec![key])),
212 "g<any>" => Mapping::Any(|key| key.typed_char().map(|_| vec![key])),
213 };
214 let key = |key: &str| key.parse::<Key>().unwrap();
215 assert_eq!(keymap.get("f"), KeymapResult::Pending);
216 assert_eq!(keymap.get("fx"), KeymapResult::Computed(vec![key("x")]));
218 assert_eq!(
219 keymap.get("f<a-x>"),
220 KeymapResult::Computed(vec![key("<a-x>")])
221 );
222 assert_eq!(
223 keymap.get("f<esc>"),
224 KeymapResult::Computed(vec![key("<esc>")])
225 );
226 assert_eq!(keymap.get("fxy"), KeymapResult::Unmapped);
227 assert_eq!(keymap.get("gx"), KeymapResult::Computed(vec![key("x")]));
229 assert_eq!(keymap.get("g<a-x>"), KeymapResult::Unmapped);
230 }
231
232 #[test]
233 #[should_panic(expected = "requires exactly one `<any>`")]
234 fn keymap_any_requires_any_key() {
235 let _keymap = keymap! { Vec<Key>;
236 "f" => Mapping::Any(|key| Some(vec![key])),
237 };
238 }
239
240 #[test]
241 #[should_panic(expected = "forbids `<any>`")]
242 fn keymap_static_forbids_any_key() {
243 let _keymap = keymap! {
244 "f<any>" => vec![Action("seek")],
245 };
246 }
247
248 #[test]
249 #[should_panic]
250 fn keymap_forbids_overlap() {
251 let _keymap = keymap! {
252 "g" => vec![Action("enter goto mode")],
253 "gj" => vec![Action("move to bottom")],
254 };
255 }
256
257 #[test]
258 fn keymap_iter() {
259 let mut keymap = keymap! {
260 "gk" => vec![Action("move to top")],
261 "x" => vec![Action("select line")],
262 "gj" => vec![Action("move to bottom")],
263 };
264 let values = |keymap: &Keymap<Vec<Action>>| {
265 keymap
266 .iter()
267 .map(|(keys, value)| match value {
268 Mapping::Static(value) => (Keys(keys).to_string(), value[0].0),
269 Mapping::Any(_) => unreachable!(),
270 })
271 .collect::<Vec<_>>()
272 };
273 assert_eq!(
275 values(&keymap),
276 [
277 (String::from("gk"), "move to top"),
278 (String::from("x"), "select line"),
279 (String::from("gj"), "move to bottom"),
280 ]
281 );
282 keymap.insert("gk", vec![Action("goto top")], None).unwrap();
284 }
285
286 #[test]
287 fn keymap_descriptions() {
288 let keymap = keymap! {
289 "gk" => (), "x" => (), };
292 let descriptions: Vec<_> = keymap.docs().map(|(_, description)| description).collect();
293 assert_eq!(descriptions, [Some("Move to top"), None]);
294 }
295}