1use super::{ParsedKeybinding, ParsedMenu, helper::extract_value, prelude::*};
14use crate::Config;
15use strum_macros::EnumString;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumString)]
19#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
20pub enum KeyModifier {
21 Control,
22 Shift,
23 Alt,
24 Super,
25 Hyper,
26 Meta,
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum KeyCodeSpec {
32 Backspace,
33 Enter,
34 Down,
35 Up,
36 Left,
37 Right,
38 Home,
39 End,
40 PageUp,
41 PageDown,
42 Tab,
43 BackTab,
44 Delete,
45 Insert,
46 F(u8),
48 Char(char),
50 Null,
51 Esc,
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumString)]
59#[strum(ascii_case_insensitive)]
60pub enum EditModeName {
61 Emacs,
62 #[strum(serialize = "ViNormal", serialize = "vi_normal")]
63 ViNormal,
64 #[strum(serialize = "ViInsert", serialize = "vi_insert")]
65 ViInsert,
66 #[strum(serialize = "ViVisual", serialize = "vi_visual")]
67 ViVisual,
68 #[strum(serialize = "HelixNormal", serialize = "helix_normal")]
69 HelixNormal,
70 #[strum(serialize = "HelixInsert", serialize = "helix_insert")]
71 HelixInsert,
72 #[strum(serialize = "HelixSelect", serialize = "helix_select")]
73 HelixSelect,
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumString)]
78#[strum(serialize_all = "lowercase")]
79pub enum MenuLayout {
80 Columnar,
81 List,
82 Ide,
83 Description,
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumString)]
88#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
89pub enum MenuInputMode {
90 Diff,
91 CursorPrefix,
92 FullBuffer,
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumString)]
97#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
98pub enum MenuOutputMode {
99 SuggestedSpan,
100 FullBuffer,
101 ExtendToEnd,
102}
103
104const VALID_MODIFIERS: &str = "'control', 'shift', 'alt', 'super', 'hyper', 'meta', or 'none'";
105const VALID_KEYCODES: &str = "'backspace', 'enter', 'space', 'down', 'up', 'left', 'right', 'home', 'end', 'pageup', 'pagedown', 'tab', 'backtab', 'delete', 'insert', 'null', 'esc', 'f1' to 'f35', 'char_<char>', or 'char_u<hex code>'";
106pub const VALID_KEYBINDING_MODES: &str = "'emacs', 'vi_insert', 'vi_normal', 'vi_visual', 'helix_insert', 'helix_normal', or 'helix_select'";
108const VALID_LAYOUTS: &str = "'columnar', 'list', 'ide', or 'description'";
109const VALID_INPUT_MODES: &str = "'diff', 'cursor_prefix', or 'full_buffer'";
110const VALID_OUTPUT_MODES: &str = "'suggested_span', 'full_buffer', or 'extend_to_end'";
111
112impl ParsedKeybinding {
113 pub fn modifiers(&self) -> Result<Vec<KeyModifier>, ShellError> {
115 let Ok(modifier) = self.modifier.as_str() else {
116 return Err(ShellError::RuntimeTypeMismatch {
117 expected: Type::String,
118 actual: self.modifier.get_type(),
119 span: self.modifier.span(),
120 });
121 };
122
123 if modifier.eq_ignore_ascii_case("none") {
124 return Ok(Vec::new());
125 }
126 modifier
127 .split('_')
128 .map(|part| {
129 part.parse().map_err(|_| ShellError::InvalidValue {
130 valid: VALID_MODIFIERS.into(),
131 actual: format!("'{part}'"),
132 span: self.modifier.span(),
133 })
134 })
135 .collect()
136 }
137
138 pub fn key_code(&self) -> Result<KeyCodeSpec, ShellError> {
140 let Ok(keycode) = self.keycode.as_str() else {
141 return Err(ShellError::RuntimeTypeMismatch {
142 expected: Type::String,
143 actual: self.keycode.get_type(),
144 span: self.keycode.span(),
145 });
146 };
147 let span = self.keycode.span();
148 let keycode_lower = keycode.to_ascii_lowercase();
149
150 if let Some(rest) = keycode_lower.strip_prefix("char_") {
151 let error = |valid: &str, actual: &str| ShellError::InvalidValue {
152 valid: valid.into(),
153 actual: actual.into(),
154 span,
155 };
156
157 let mut chars = rest.chars();
158 let char = match (chars.next(), chars.next()) {
159 (Some(char), None) => char,
160 (Some('u'), Some(_)) => {
161 let Ok(code_point) = u32::from_str_radix(&rest[1..], 16) else {
163 return Err(error("a valid hex code", keycode));
164 };
165 char::from_u32(code_point)
166 .ok_or_else(|| error("a valid Unicode code point", keycode))?
167 }
168 _ => return Err(error("'char_<char>' or 'char_u<hex code>'", keycode)),
169 };
170 return Ok(KeyCodeSpec::Char(char));
171 }
172
173 Ok(match keycode_lower.as_str() {
174 "backspace" => KeyCodeSpec::Backspace,
175 "enter" => KeyCodeSpec::Enter,
176 "space" => KeyCodeSpec::Char(' '),
177 "down" => KeyCodeSpec::Down,
178 "up" => KeyCodeSpec::Up,
179 "left" => KeyCodeSpec::Left,
180 "right" => KeyCodeSpec::Right,
181 "home" => KeyCodeSpec::Home,
182 "end" => KeyCodeSpec::End,
183 "pageup" => KeyCodeSpec::PageUp,
184 "pagedown" => KeyCodeSpec::PageDown,
185 "tab" => KeyCodeSpec::Tab,
186 "backtab" => KeyCodeSpec::BackTab,
187 "delete" => KeyCodeSpec::Delete,
188 "insert" => KeyCodeSpec::Insert,
189 name if name.starts_with('f') => name[1..]
190 .parse()
191 .ok()
192 .filter(|num| (1..=35).contains(num))
193 .map(KeyCodeSpec::F)
194 .ok_or(ShellError::InvalidValue {
195 valid: VALID_KEYCODES.into(),
196 actual: format!("'{keycode}'"),
197 span,
198 })?,
199 "null" => KeyCodeSpec::Null,
200 "esc" | "escape" => KeyCodeSpec::Esc,
201 _ => {
202 return Err(ShellError::InvalidValue {
203 valid: VALID_KEYCODES.into(),
204 actual: format!("'{keycode}'"),
205 span,
206 });
207 }
208 })
209 }
210
211 pub fn modes(&self) -> Result<Vec<EditModeName>, ShellError> {
214 fn collect(mode: &Value, modes: &mut Vec<EditModeName>) -> Result<(), ShellError> {
215 match mode {
216 Value::String { val, .. } => {
217 modes.push(val.parse().map_err(|_| ShellError::InvalidValue {
218 valid: VALID_KEYBINDING_MODES.into(),
219 actual: format!("'{val}'"),
220 span: mode.span(),
221 })?);
222 }
223 Value::List { vals, .. } => {
224 for inner in vals {
225 collect(inner, modes)?;
226 }
227 }
228 v => {
229 return Err(ShellError::RuntimeTypeMismatch {
230 expected: Type::custom("string or list<string>"),
231 actual: v.get_type(),
232 span: v.span(),
233 });
234 }
235 }
236 Ok(())
237 }
238
239 let mut modes = Vec::new();
240 collect(&self.mode, &mut modes)?;
241 Ok(modes)
242 }
243
244 pub(crate) fn validate(&self) -> Result<(), ShellError> {
247 self.modes()?;
248 self.modifiers()?;
249 self.key_code()?;
250 Ok(())
251 }
252}
253
254impl ParsedMenu {
255 pub fn layout(&self, config: &Config) -> Result<MenuLayout, ShellError> {
258 let span = self.r#type.span();
259 let Value::Record { val, .. } = &self.r#type else {
260 return Err(ShellError::RuntimeTypeMismatch {
261 expected: Type::record(),
262 actual: self.r#type.get_type(),
263 span,
264 });
265 };
266
267 let layout = extract_value("layout", val, span)?.to_expanded_string("", config);
268 layout.parse().map_err(|_| ShellError::InvalidValue {
269 valid: VALID_LAYOUTS.into(),
270 actual: format!("'{layout}'"),
271 span,
272 })
273 }
274
275 pub fn input_mode(&self, config: &Config) -> Result<MenuInputMode, ShellError> {
279 match (&self.input_mode, &self.only_buffer_difference) {
280 (Some(input_mode), _) => {
281 let text = input_mode.to_expanded_string("", config);
282 text.parse().map_err(|_| ShellError::InvalidValue {
283 valid: VALID_INPUT_MODES.into(),
284 actual: format!("'{text}'"),
285 span: input_mode.span(),
286 })
287 }
288 (None, Some(only_buffer_difference)) => Ok(if only_buffer_difference.as_bool()? {
289 MenuInputMode::Diff
290 } else {
291 MenuInputMode::CursorPrefix
292 }),
293 (None, None) => Err(ShellError::MissingRequiredColumn {
294 column: "input_mode (or only_buffer_difference)",
295 span: self.name.span(),
296 }),
297 }
298 }
299
300 pub fn output_mode(&self, config: &Config) -> Result<Option<MenuOutputMode>, ShellError> {
303 self.output_mode
304 .as_ref()
305 .map(|output_mode| {
306 let text = output_mode.to_expanded_string("", config);
307 text.parse().map_err(|_| ShellError::InvalidValue {
308 valid: VALID_OUTPUT_MODES.into(),
309 actual: format!("'{text}'"),
310 span: output_mode.span(),
311 })
312 })
313 .transpose()
314 }
315
316 pub(crate) fn validate(&self, config: &Config) -> Result<(), ShellError> {
320 self.layout(config)?;
321 self.input_mode(config)?;
322 self.output_mode(config)?;
323 Ok(())
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330
331 fn entry(modifier: &str, keycode: &str, mode: Value) -> ParsedKeybinding {
332 ParsedKeybinding {
333 name: None,
334 modifier: Value::test_string(modifier),
335 keycode: Value::test_string(keycode),
336 event: Value::test_nothing(),
337 mode,
338 }
339 }
340
341 fn emacs() -> Value {
342 Value::test_string("emacs")
343 }
344
345 fn code(keycode: &str) -> Result<KeyCodeSpec, ShellError> {
346 entry("none", keycode, emacs()).key_code()
347 }
348
349 fn modifiers(modifier: &str) -> Result<Vec<KeyModifier>, ShellError> {
350 entry(modifier, "enter", emacs()).modifiers()
351 }
352
353 fn modes(mode: Value) -> Result<Vec<EditModeName>, ShellError> {
354 entry("none", "enter", mode).modes()
355 }
356
357 fn rejected(result: Result<impl std::fmt::Debug, ShellError>) -> String {
360 match result {
361 Err(ShellError::InvalidValue { actual, .. }) => actual,
362 other => format!("not an invalid value: {other:?}"),
363 }
364 }
365
366 #[test]
367 fn modifiers_are_an_unordered_set_in_any_case() -> Result<(), ShellError> {
368 assert_eq!(modifiers("none")?, vec![]);
369 assert_eq!(modifiers("None")?, vec![]);
370 assert_eq!(
371 modifiers("Control_shift")?,
372 vec![KeyModifier::Control, KeyModifier::Shift]
373 );
374 assert_eq!(
375 modifiers("super_hyper_meta_alt")?,
376 vec![
377 KeyModifier::Super,
378 KeyModifier::Hyper,
379 KeyModifier::Meta,
380 KeyModifier::Alt
381 ]
382 );
383 Ok(())
384 }
385
386 #[test]
387 fn a_modifier_that_is_not_one_is_named_in_the_error() {
388 assert_eq!(rejected(modifiers("control_bogus")), "'bogus'");
389 assert_eq!(rejected(modifiers("")), "''");
390 }
391
392 #[test]
393 fn a_value_that_is_not_text_is_a_type_mismatch() {
394 let mut keybinding = entry("none", "enter", emacs());
395 keybinding.modifier = Value::test_int(1);
396 keybinding.keycode = Value::test_list(vec![]);
397 keybinding.mode = Value::test_int(1);
398
399 let results = [
400 keybinding.modifiers().map(drop),
401 keybinding.key_code().map(drop),
402 keybinding.modes().map(drop),
403 ];
404 for result in results {
405 assert!(
406 matches!(result, Err(ShellError::RuntimeTypeMismatch { .. })),
407 "{result:?}"
408 );
409 }
410 }
411
412 #[test]
413 fn keycodes_name_characters_in_any_case() -> Result<(), ShellError> {
414 assert_eq!(code("char_a")?, KeyCodeSpec::Char('a'));
415 assert_eq!(code("Char_A")?, KeyCodeSpec::Char('a'));
417 assert_eq!(code("char_u1F600")?, KeyCodeSpec::Char('\u{1F600}'));
418 assert_eq!(code("char_u")?, KeyCodeSpec::Char('u'));
419 assert_eq!(code("space")?, KeyCodeSpec::Char(' '));
420 Ok(())
421 }
422
423 #[test]
424 fn a_character_keycode_that_is_not_one_is_named_in_the_error() {
425 assert_eq!(rejected(code("char_ab")), "char_ab");
426 assert_eq!(rejected(code("char_")), "char_");
427 assert_eq!(rejected(code("char_uzz")), "char_uzz");
428 assert_eq!(rejected(code("char_ud800")), "char_ud800");
430 }
431
432 #[test]
433 fn keycodes_name_the_keys_nushell_knows() -> Result<(), ShellError> {
434 let named = [
435 ("backspace", KeyCodeSpec::Backspace),
436 ("enter", KeyCodeSpec::Enter),
437 ("down", KeyCodeSpec::Down),
438 ("up", KeyCodeSpec::Up),
439 ("left", KeyCodeSpec::Left),
440 ("right", KeyCodeSpec::Right),
441 ("home", KeyCodeSpec::Home),
442 ("end", KeyCodeSpec::End),
443 ("pageup", KeyCodeSpec::PageUp),
444 ("pagedown", KeyCodeSpec::PageDown),
445 ("tab", KeyCodeSpec::Tab),
446 ("backtab", KeyCodeSpec::BackTab),
447 ("delete", KeyCodeSpec::Delete),
448 ("insert", KeyCodeSpec::Insert),
449 ("null", KeyCodeSpec::Null),
450 ("esc", KeyCodeSpec::Esc),
451 ("Escape", KeyCodeSpec::Esc),
452 ("PageUp", KeyCodeSpec::PageUp),
453 ("f1", KeyCodeSpec::F(1)),
454 ("F35", KeyCodeSpec::F(35)),
455 ];
456 for (name, expected) in named {
457 assert_eq!(code(name)?, expected, "{name}");
458 }
459 Ok(())
460 }
461
462 #[test]
463 fn a_keycode_that_is_not_one_is_named_in_the_error() {
464 for bad in ["f0", "f36", "f", "fx", "f-1", "foo", "nonsense", ""] {
466 assert_eq!(rejected(code(bad)), format!("'{bad}'"), "{bad}");
467 }
468 }
469
470 #[test]
471 fn a_mode_is_a_name_or_a_list_of_names_that_may_nest() -> Result<(), ShellError> {
472 assert_eq!(modes(emacs())?, vec![EditModeName::Emacs]);
473 assert_eq!(
474 modes(Value::test_list(vec![
475 Value::test_string("vi_normal"),
476 Value::test_list(vec![Value::test_string("helix_select")]),
477 ]))?,
478 vec![EditModeName::ViNormal, EditModeName::HelixSelect]
479 );
480 assert_eq!(modes(Value::test_list(vec![]))?, vec![]);
482 Ok(())
483 }
484
485 #[test]
486 fn a_mode_may_be_spelled_either_way_in_any_case() -> Result<(), ShellError> {
487 for (name, expected) in [
488 ("ViNormal", EditModeName::ViNormal),
489 ("vi_normal", EditModeName::ViNormal),
490 ("VI_INSERT", EditModeName::ViInsert),
491 ("ViVisual", EditModeName::ViVisual),
492 ("helix_normal", EditModeName::HelixNormal),
493 ("HelixInsert", EditModeName::HelixInsert),
494 ("helix_select", EditModeName::HelixSelect),
495 ("EMACS", EditModeName::Emacs),
496 ] {
497 assert_eq!(modes(Value::test_string(name))?, vec![expected], "{name}");
498 }
499 Ok(())
500 }
501
502 #[test]
503 fn a_mode_that_is_not_one_is_named_in_the_error() {
504 for bad in ["bogus", "default", "custom", "vi", ""] {
506 assert_eq!(
507 rejected(modes(Value::test_string(bad))),
508 format!("'{bad}'"),
509 "{bad}"
510 );
511 }
512 assert_eq!(
513 rejected(modes(Value::test_list(vec![
514 emacs(),
515 Value::test_string("nope")
516 ]))),
517 "'nope'"
518 );
519 }
520
521 fn menu(layout: Value) -> ParsedMenu {
522 ParsedMenu {
523 name: Value::test_string("m"),
524 marker: Value::test_string("| "),
525 only_buffer_difference: None,
526 input_mode: None,
527 output_mode: None,
528 style: Value::test_record(record! {}),
529 r#type: layout,
530 source: None,
531 }
532 }
533
534 fn layout_of(layout: &str) -> Result<MenuLayout, ShellError> {
535 let config = Config::default();
536 menu(Value::test_record(
537 record! { "layout" => Value::test_string(layout) },
538 ))
539 .layout(&config)
540 }
541
542 #[test]
543 fn a_menu_layout_is_one_of_four_lowercase_names() -> Result<(), ShellError> {
544 for (name, expected) in [
545 ("columnar", MenuLayout::Columnar),
546 ("list", MenuLayout::List),
547 ("ide", MenuLayout::Ide),
548 ("description", MenuLayout::Description),
549 ] {
550 assert_eq!(layout_of(name)?, expected, "{name}");
551 }
552 for bad in ["grid", "Columnar", ""] {
553 assert_eq!(rejected(layout_of(bad)), format!("'{bad}'"), "{bad}");
554 }
555 Ok(())
556 }
557
558 fn menu_with_modes(
559 input_mode: Option<Value>,
560 only_buffer_difference: Option<Value>,
561 ) -> ParsedMenu {
562 let mut menu = menu(Value::test_nothing());
563 menu.input_mode = input_mode;
564 menu.only_buffer_difference = only_buffer_difference;
565 menu
566 }
567
568 #[test]
569 fn a_menu_input_mode_is_a_name_or_the_legacy_flag() -> Result<(), ShellError> {
570 let config = Config::default();
571 let name = |name: &str| Some(Value::test_string(name));
572
573 assert_eq!(
574 menu_with_modes(name("Full_Buffer"), None).input_mode(&config)?,
575 MenuInputMode::FullBuffer
576 );
577 assert_eq!(
579 menu_with_modes(name("diff"), Some(Value::test_bool(false))).input_mode(&config)?,
580 MenuInputMode::Diff
581 );
582 assert_eq!(
583 menu_with_modes(None, Some(Value::test_bool(true))).input_mode(&config)?,
584 MenuInputMode::Diff
585 );
586 assert_eq!(
587 menu_with_modes(None, Some(Value::test_bool(false))).input_mode(&config)?,
588 MenuInputMode::CursorPrefix
589 );
590
591 assert_eq!(
592 rejected(menu_with_modes(name("nope"), None).input_mode(&config)),
593 "'nope'"
594 );
595 let not_a_bool = menu_with_modes(None, Some(Value::test_int(3)));
596 assert!(matches!(
597 not_a_bool.input_mode(&config),
598 Err(ShellError::CantConvert { .. })
599 ));
600 assert!(matches!(
601 menu_with_modes(None, None).input_mode(&config),
602 Err(ShellError::MissingRequiredColumn { .. })
603 ));
604 Ok(())
605 }
606
607 #[test]
608 fn a_menu_output_mode_is_optional_and_a_name() -> Result<(), ShellError> {
609 let config = Config::default();
610 let mut menu = menu(Value::test_nothing());
611 assert_eq!(menu.output_mode(&config)?, None);
612
613 menu.output_mode = Some(Value::test_string("Extend_To_End"));
614 assert_eq!(
615 menu.output_mode(&config)?,
616 Some(MenuOutputMode::ExtendToEnd)
617 );
618
619 menu.output_mode = Some(Value::test_string("nope"));
620 assert_eq!(rejected(menu.output_mode(&config)), "'nope'");
621 Ok(())
622 }
623
624 #[test]
625 fn a_menu_type_needs_a_layout_in_a_record() {
626 let config = Config::default();
627 assert!(matches!(
628 menu(Value::test_record(record! {})).layout(&config),
629 Err(ShellError::MissingRequiredColumn { .. })
630 ));
631 assert!(matches!(
632 menu(Value::test_string("columnar")).layout(&config),
633 Err(ShellError::RuntimeTypeMismatch { .. })
634 ));
635 }
636
637 #[test]
639 fn the_defaults_are_valid() {
640 let config = Config::default();
641 for keybinding in &config.keybindings {
642 assert!(keybinding.validate().is_ok(), "{:?}", keybinding.name);
643 }
644 for menu in &config.menus {
645 assert!(menu.validate(&config).is_ok(), "{:?}", menu.name);
646 }
647 }
648}