on master help sign in
Revert "Refactor key into helix-view"

Did not use defaults when custom keymap was used This reverts commit ca806d4f852e934651132fc9570a6110e30f646d.

commit10f9f72232f5789323d689bf0f9cd359715770d6 authorBlaž Hrastnik <blaz@mxxn.io> dateSat 19 Jun 2021, 23:59 (5 years ago) parent11f20af
9 files changed+414−388
helix-term/src/application.rs+2−2 helix-term/src/commands.rs+27−44 helix-term/src/config.rs+31−45 helix-term/src/keymap.rs+316−20 helix-term/src/main.rs+8−6 helix-term/src/ui/editor.rs+2−4 helix-view/src/document.rs+25−36 helix-view/src/input.rs−226 helix-view/src/lib.rs+3−5
helix-term/src/application.rs+2−2
@@ -1,7 +1,7 @@
11use helix_lsp::{lsp, LspProgressMap};
22use helix_view::{document::Mode, Document, Editor, Theme, View};
33
4−use crate::{args::Args, compositor::Compositor, config::Config, ui};
4+use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui};
55
66use log::{error, info};
77
@@ -49,7 +49,7 @@ impl Application {
4949 let size = compositor.size();
5050 let mut editor = Editor::new(size);
5151
52− let mut editor_view = Box::new(ui::EditorView::new(config.keys));
52+ let mut editor_view = Box::new(ui::EditorView::new(config.keymaps));
5353 compositor.push(editor_view);
5454
5555 if !args.files.is_empty() {
helix-term/src/commands.rs+27−44
@@ -11,7 +11,6 @@ use helix_core::{
1111
1212use helix_view::{
1313 document::{IndentStyle, Mode},
14− input::{KeyCode, KeyEvent},
1514 view::{View, PADDING},
1615 Document, DocumentId, Editor, ViewId,
1716};
@@ -39,8 +38,8 @@ use std::{
3938 path::{Path, PathBuf},
4039};
4140
41+use crossterm::event::{KeyCode, KeyEvent};
4242use once_cell::sync::Lazy;
43−use serde::de::{self, Deserialize, Deserializer};
4443
4544pub struct Context<'a> {
4645 pub selected_register: helix_view::RegisterSelection,
@@ -253,48 +252,6 @@ impl Command {
253252 );
254253}
255254
256−impl fmt::Debug for Command {
257− fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258− let Command(name, _) = self;
259− f.debug_tuple("Command").field(name).finish()
260− }
261−}
262−
263−impl fmt::Display for Command {
264− fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265− let Command(name, _) = self;
266− f.write_str(name)
267− }
268−}
269−
270−impl std::str::FromStr for Command {
271− type Err = anyhow::Error;
272−
273− fn from_str(s: &str) -> Result<Self, Self::Err> {
274− Command::COMMAND_LIST
275− .iter()
276− .copied()
277− .find(|cmd| cmd.0 == s)
278− .ok_or_else(|| anyhow!("No command named '{}'", s))
279− }
280−}
281−
282−impl<'de> Deserialize<'de> for Command {
283− fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
284− where
285− D: Deserializer<'de>,
286− {
287− let s = String::deserialize(deserializer)?;
288− s.parse().map_err(de::Error::custom)
289− }
290−}
291−
292−impl PartialEq for Command {
293− fn eq(&self, other: &Self) -> bool {
294− self.name() == other.name()
295− }
296−}
297−
298255fn move_char_left(cx: &mut Context) {
299256 let count = cx.count();
300257 let (view, doc) = current!(cx.editor);
@@ -3085,3 +3042,29 @@ fn right_bracket_mode(cx: &mut Context) {
30853042 }
30863043 })
30873044}
3045+
3046+impl fmt::Display for Command {
3047+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3048+ let Command(name, _) = self;
3049+ f.write_str(name)
3050+ }
3051+}
3052+
3053+impl std::str::FromStr for Command {
3054+ type Err = anyhow::Error;
3055+
3056+ fn from_str(s: &str) -> Result<Self, Self::Err> {
3057+ Command::COMMAND_LIST
3058+ .iter()
3059+ .copied()
3060+ .find(|cmd| cmd.0 == s)
3061+ .ok_or_else(|| anyhow!("No command named '{}'", s))
3062+ }
3063+}
3064+
3065+impl fmt::Debug for Command {
3066+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3067+ let Command(name, _) = self;
3068+ f.debug_tuple("Command").field(name).finish()
3069+ }
3070+}
helix-term/src/config.rs+31−45
@@ -1,9 +1,10 @@
1−use serde::Deserialize;
1+use anyhow::{Error, Result};
2+use std::{collections::HashMap, str::FromStr};
23
3−use crate::commands::Command;
4−use crate::keymap::Keymaps;
4+use serde::{de::Error as SerdeError, Deserialize, Serialize};
5+
6+use crate::keymap::{parse_keymaps, Keymaps};
57
6−#[derive(Debug, PartialEq, Deserialize)]
78pub struct GlobalConfig {
89 pub lsp_progress: bool,
910}
@@ -14,50 +15,35 @@ impl Default for GlobalConfig {
1415 }
1516}
1617
17−#[derive(Debug, Default, PartialEq, Deserialize)]
18−#[serde(default)]
18+#[derive(Default)]
1919pub struct Config {
2020 pub global: GlobalConfig,
21− pub keys: Keymaps,
21+ pub keymaps: Keymaps,
2222}
2323
24−#[test]
25−fn parsing_keymaps_config_file() {
26− use helix_core::hashmap;
27− use helix_view::document::Mode;
28− use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
29−
30− let sample_keymaps = r#"
31− [keys.insert]
32− y = "move_line_down"
33− S-C-a = "delete_selection"
34−
35− [keys.normal]
36− A-F12 = "move_next_word_end"
37− "#;
24+#[derive(Serialize, Deserialize)]
25+#[serde(rename_all = "kebab-case")]
26+struct TomlConfig {
27+ lsp_progress: Option<bool>,
28+ keys: Option<HashMap<String, HashMap<String, String>>>,
29+}
3830
39− assert_eq!(
40− toml::from_str::<Config>(sample_keymaps).unwrap(),
41− Config {
42− global: Default::default(),
43− keys: Keymaps(hashmap! {
44− Mode::Insert => hashmap! {
45− KeyEvent {
46− code: KeyCode::Char('y'),
47− modifiers: KeyModifiers::NONE,
48− } => Command::move_line_down,
49− KeyEvent {
50− code: KeyCode::Char('a'),
51− modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL,
52− } => Command::delete_selection,
53− },
54− Mode::Normal => hashmap! {
55− KeyEvent {
56− code: KeyCode::F(12),
57− modifiers: KeyModifiers::ALT,
58− } => Command::move_next_word_end,
59− },
60− })
61− }
62− );
31+impl<'de> Deserialize<'de> for Config {
32+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
33+ where
34+ D: serde::Deserializer<'de>,
35+ {
36+ let config = TomlConfig::deserialize(deserializer)?;
37+ Ok(Self {
38+ global: GlobalConfig {
39+ lsp_progress: config.lsp_progress.unwrap_or(true),
40+ },
41+ keymaps: config
42+ .keys
43+ .map(|r| parse_keymaps(&r))
44+ .transpose()
45+ .map_err(|e| D::Error::custom(format!("Error deserializing keymap: {}", e)))?
46+ .unwrap_or_else(Keymaps::default),
47+ })
48+ }
6349}
helix-term/src/keymap.rs+316−20
@@ -3,8 +3,6 @@ pub use crate::commands::Command;
33use anyhow::{anyhow, Error, Result};
44use helix_core::hashmap;
55use helix_view::document::Mode;
6−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
7−use serde::Deserialize;
86use std::{
97 collections::HashMap,
108 fmt::Display,
@@ -101,6 +99,14 @@ use std::{
10199// D] = last diagnostic
102100// }
103101
102+// #[cfg(feature = "term")]
103+pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
104+
105+#[derive(Clone, Debug)]
106+pub struct Keymap(pub HashMap<KeyEvent, Command>);
107+#[derive(Clone, Debug)]
108+pub struct Keymaps(pub HashMap<Mode, Keymap>);
109+
104110#[macro_export]
105111macro_rules! key {
106112 ($key:ident) => {
@@ -135,21 +141,9 @@ macro_rules! alt {
135141 };
136142}
137143
138−#[derive(Debug, PartialEq, Deserialize)]
139−#[serde(transparent)]
140−pub struct Keymaps(pub HashMap<Mode, HashMap<KeyEvent, Command>>);
141−
142−impl Deref for Keymaps {
143− type Target = HashMap<Mode, HashMap<KeyEvent, Command>>;
144−
145− fn deref(&self) -> &Self::Target {
146− &self.0
147− }
148−}
149−
150144impl Default for Keymaps {
151− fn default() -> Keymaps {
152− let normal = hashmap!(
145+ fn default() -> Self {
146+ let normal = Keymap(hashmap!(
153147 key!('h') => Command::move_char_left,
154148 key!('j') => Command::move_line_down,
155149 key!('k') => Command::move_line_up,
@@ -283,12 +277,12 @@ impl Default for Keymaps {
283277 key!('z') => Command::view_mode,
284278
285279 key!('"') => Command::select_register,
286− );
280+ ));
287281 // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether
288282 // we keep this separate select mode. More keys can fit into normal mode then, but it's weird
289283 // because some selection operations can now be done from normal mode, some from select mode.
290284 let mut select = normal.clone();
291− select.extend(
285+ select.0.extend(
292286 hashmap!(
293287 key!('h') => Command::extend_char_left,
294288 key!('j') => Command::extend_line_down,
@@ -321,7 +315,7 @@ impl Default for Keymaps {
321315 // TODO: select could be normal mode with some bindings merged over
322316 Mode::Normal => normal,
323317 Mode::Select => select,
324− Mode::Insert => hashmap!(
318+ Mode::Insert => Keymap(hashmap!(
325319 key!(Esc) => Command::normal_mode as Command,
326320 key!(Backspace) => Command::delete_char_backward,
327321 key!(Delete) => Command::delete_char_forward,
@@ -337,7 +331,309 @@ impl Default for Keymaps {
337331 key!(End) => Command::move_line_end,
338332 ctrl!('x') => Command::completion,
339333 ctrl!('w') => Command::delete_word_backward,
340− ),
334+ )),
341335 ))
342336 }
343337}
338+
339+// Newtype wrapper over keys to allow toml serialization/parsing
340+#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Hash)]
341+pub struct RepresentableKeyEvent(pub KeyEvent);
342+impl Display for RepresentableKeyEvent {
343+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344+ let Self(key) = self;
345+ f.write_fmt(format_args!(
346+ "{}{}{}",
347+ if key.modifiers.contains(KeyModifiers::SHIFT) {
348+ "S-"
349+ } else {
350+ ""
351+ },
352+ if key.modifiers.contains(KeyModifiers::ALT) {
353+ "A-"
354+ } else {
355+ ""
356+ },
357+ if key.modifiers.contains(KeyModifiers::CONTROL) {
358+ "C-"
359+ } else {
360+ ""
361+ },
362+ ))?;
363+ match key.code {
364+ KeyCode::Backspace => f.write_str("backspace")?,
365+ KeyCode::Enter => f.write_str("ret")?,
366+ KeyCode::Left => f.write_str("left")?,
367+ KeyCode::Right => f.write_str("right")?,
368+ KeyCode::Up => f.write_str("up")?,
369+ KeyCode::Down => f.write_str("down")?,
370+ KeyCode::Home => f.write_str("home")?,
371+ KeyCode::End => f.write_str("end")?,
372+ KeyCode::PageUp => f.write_str("pageup")?,
373+ KeyCode::PageDown => f.write_str("pagedown")?,
374+ KeyCode::Tab => f.write_str("tab")?,
375+ KeyCode::BackTab => f.write_str("backtab")?,
376+ KeyCode::Delete => f.write_str("del")?,
377+ KeyCode::Insert => f.write_str("ins")?,
378+ KeyCode::Null => f.write_str("null")?,
379+ KeyCode::Esc => f.write_str("esc")?,
380+ KeyCode::Char('<') => f.write_str("lt")?,
381+ KeyCode::Char('>') => f.write_str("gt")?,
382+ KeyCode::Char('+') => f.write_str("plus")?,
383+ KeyCode::Char('-') => f.write_str("minus")?,
384+ KeyCode::Char(';') => f.write_str("semicolon")?,
385+ KeyCode::Char('%') => f.write_str("percent")?,
386+ KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?,
387+ KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?,
388+ };
389+ Ok(())
390+ }
391+}
392+
393+impl FromStr for RepresentableKeyEvent {
394+ type Err = Error;
395+
396+ fn from_str(s: &str) -> Result<Self, Self::Err> {
397+ let mut tokens: Vec<_> = s.split('-').collect();
398+ let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? {
399+ "backspace" => KeyCode::Backspace,
400+ "space" => KeyCode::Char(' '),
401+ "ret" => KeyCode::Enter,
402+ "lt" => KeyCode::Char('<'),
403+ "gt" => KeyCode::Char('>'),
404+ "plus" => KeyCode::Char('+'),
405+ "minus" => KeyCode::Char('-'),
406+ "semicolon" => KeyCode::Char(';'),
407+ "percent" => KeyCode::Char('%'),
408+ "left" => KeyCode::Left,
409+ "right" => KeyCode::Right,
410+ "up" => KeyCode::Down,
411+ "home" => KeyCode::Home,
412+ "end" => KeyCode::End,
413+ "pageup" => KeyCode::PageUp,
414+ "pagedown" => KeyCode::PageDown,
415+ "tab" => KeyCode::Tab,
416+ "backtab" => KeyCode::BackTab,
417+ "del" => KeyCode::Delete,
418+ "ins" => KeyCode::Insert,
419+ "null" => KeyCode::Null,
420+ "esc" => KeyCode::Esc,
421+ single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()),
422+ function if function.len() > 1 && function.starts_with('F') => {
423+ let function: String = function.chars().skip(1).collect();
424+ let function = str::parse::<u8>(&function)?;
425+ (function > 0 && function < 13)
426+ .then(|| KeyCode::F(function))
427+ .ok_or_else(|| anyhow!("Invalid function key '{}'", function))?
428+ }
429+ invalid => return Err(anyhow!("Invalid key code '{}'", invalid)),
430+ };
431+
432+ let mut modifiers = KeyModifiers::empty();
433+ for token in tokens {
434+ let flag = match token {
435+ "S" => KeyModifiers::SHIFT,
436+ "A" => KeyModifiers::ALT,
437+ "C" => KeyModifiers::CONTROL,
438+ _ => return Err(anyhow!("Invalid key modifier '{}-'", token)),
439+ };
440+
441+ if modifiers.contains(flag) {
442+ return Err(anyhow!("Repeated key modifier '{}-'", token));
443+ }
444+ modifiers.insert(flag);
445+ }
446+
447+ Ok(RepresentableKeyEvent(KeyEvent { code, modifiers }))
448+ }
449+}
450+
451+pub fn parse_keymaps(toml_keymaps: &HashMap<String, HashMap<String, String>>) -> Result<Keymaps> {
452+ let mut keymaps = Keymaps::default();
453+
454+ for (mode, map) in toml_keymaps {
455+ let mode = Mode::from_str(&mode)?;
456+ for (key, command) in map {
457+ let key = str::parse::<RepresentableKeyEvent>(&key)?;
458+ let command = str::parse::<Command>(&command)?;
459+ keymaps.0.get_mut(&mode).unwrap().0.insert(key.0, command);
460+ }
461+ }
462+ Ok(keymaps)
463+}
464+
465+impl Deref for Keymap {
466+ type Target = HashMap<KeyEvent, Command>;
467+ fn deref(&self) -> &Self::Target {
468+ &self.0
469+ }
470+}
471+
472+impl Deref for Keymaps {
473+ type Target = HashMap<Mode, Keymap>;
474+ fn deref(&self) -> &Self::Target {
475+ &self.0
476+ }
477+}
478+
479+impl DerefMut for Keymap {
480+ fn deref_mut(&mut self) -> &mut Self::Target {
481+ &mut self.0
482+ }
483+}
484+
485+impl DerefMut for Keymaps {
486+ fn deref_mut(&mut self) -> &mut Self::Target {
487+ &mut self.0
488+ }
489+}
490+
491+#[cfg(test)]
492+mod test {
493+ use crate::config::Config;
494+
495+ use super::*;
496+
497+ impl PartialEq for Command {
498+ fn eq(&self, other: &Self) -> bool {
499+ self.name() == other.name()
500+ }
501+ }
502+
503+ #[test]
504+ fn parsing_keymaps_config_file() {
505+ let sample_keymaps = r#"
506+ [keys.insert]
507+ y = "move_line_down"
508+ S-C-a = "delete_selection"
509+
510+ [keys.normal]
511+ A-F12 = "move_next_word_end"
512+ "#;
513+
514+ let config: Config = toml::from_str(sample_keymaps).unwrap();
515+ assert_eq!(
516+ *config
517+ .keymaps
518+ .0
519+ .get(&Mode::Insert)
520+ .unwrap()
521+ .0
522+ .get(&KeyEvent {
523+ code: KeyCode::Char('y'),
524+ modifiers: KeyModifiers::NONE
525+ })
526+ .unwrap(),
527+ Command::move_line_down
528+ );
529+ assert_eq!(
530+ *config
531+ .keymaps
532+ .0
533+ .get(&Mode::Insert)
534+ .unwrap()
535+ .0
536+ .get(&KeyEvent {
537+ code: KeyCode::Char('a'),
538+ modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
539+ })
540+ .unwrap(),
541+ Command::delete_selection
542+ );
543+ assert_eq!(
544+ *config
545+ .keymaps
546+ .0
547+ .get(&Mode::Normal)
548+ .unwrap()
549+ .0
550+ .get(&KeyEvent {
551+ code: KeyCode::F(12),
552+ modifiers: KeyModifiers::ALT
553+ })
554+ .unwrap(),
555+ Command::move_next_word_end
556+ );
557+ }
558+
559+ #[test]
560+ fn parsing_unmodified_keys() {
561+ assert_eq!(
562+ str::parse::<RepresentableKeyEvent>("backspace").unwrap(),
563+ RepresentableKeyEvent(KeyEvent {
564+ code: KeyCode::Backspace,
565+ modifiers: KeyModifiers::NONE
566+ })
567+ );
568+
569+ assert_eq!(
570+ str::parse::<RepresentableKeyEvent>("left").unwrap(),
571+ RepresentableKeyEvent(KeyEvent {
572+ code: KeyCode::Left,
573+ modifiers: KeyModifiers::NONE
574+ })
575+ );
576+
577+ assert_eq!(
578+ str::parse::<RepresentableKeyEvent>(",").unwrap(),
579+ RepresentableKeyEvent(KeyEvent {
580+ code: KeyCode::Char(','),
581+ modifiers: KeyModifiers::NONE
582+ })
583+ );
584+
585+ assert_eq!(
586+ str::parse::<RepresentableKeyEvent>("w").unwrap(),
587+ RepresentableKeyEvent(KeyEvent {
588+ code: KeyCode::Char('w'),
589+ modifiers: KeyModifiers::NONE
590+ })
591+ );
592+
593+ assert_eq!(
594+ str::parse::<RepresentableKeyEvent>("F12").unwrap(),
595+ RepresentableKeyEvent(KeyEvent {
596+ code: KeyCode::F(12),
597+ modifiers: KeyModifiers::NONE
598+ })
599+ );
600+ }
601+
602+ fn parsing_modified_keys() {
603+ assert_eq!(
604+ str::parse::<RepresentableKeyEvent>("S-minus").unwrap(),
605+ RepresentableKeyEvent(KeyEvent {
606+ code: KeyCode::Char('-'),
607+ modifiers: KeyModifiers::SHIFT
608+ })
609+ );
610+
611+ assert_eq!(
612+ str::parse::<RepresentableKeyEvent>("C-A-S-F12").unwrap(),
613+ RepresentableKeyEvent(KeyEvent {
614+ code: KeyCode::F(12),
615+ modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
616+ })
617+ );
618+
619+ assert_eq!(
620+ str::parse::<RepresentableKeyEvent>("S-C-2").unwrap(),
621+ RepresentableKeyEvent(KeyEvent {
622+ code: KeyCode::F(2),
623+ modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
624+ })
625+ );
626+ }
627+
628+ #[test]
629+ fn parsing_nonsensical_keys_fails() {
630+ assert!(str::parse::<RepresentableKeyEvent>("F13").is_err());
631+ assert!(str::parse::<RepresentableKeyEvent>("F0").is_err());
632+ assert!(str::parse::<RepresentableKeyEvent>("aaa").is_err());
633+ assert!(str::parse::<RepresentableKeyEvent>("S-S-a").is_err());
634+ assert!(str::parse::<RepresentableKeyEvent>("C-A-S-C-1").is_err());
635+ assert!(str::parse::<RepresentableKeyEvent>("FU").is_err());
636+ assert!(str::parse::<RepresentableKeyEvent>("123").is_err());
637+ assert!(str::parse::<RepresentableKeyEvent>("S--").is_err());
638+ }
639+}
helix-term/src/main.rs+8−6
@@ -1,9 +1,10 @@
1−use anyhow::{Context, Error, Result};
21use helix_term::application::Application;
32use helix_term::args::Args;
43use helix_term::config::Config;
54use std::path::PathBuf;
65
6+use anyhow::{Context, Result};
7+
78fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> {
89 let mut base_config = fern::Dispatch::new();
910
@@ -88,11 +89,12 @@ FLAGS:
8889 std::fs::create_dir_all(&conf_dir).ok();
8990 }
9091
91− let config = match std::fs::read_to_string(conf_dir.join("config.toml")) {
92− Ok(config) => toml::from_str(&config)?,
93− Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(),
94− Err(err) => return Err(Error::new(err)),
95− };
92+ let config = std::fs::read_to_string(conf_dir.join("config.toml"))
93+ .ok()
94+ .map(|s| toml::from_str(&s))
95+ .transpose()?
96+ .or_else(|| Some(Config::default()))
97+ .unwrap();
9698
9799 setup_logging(logpath, args.verbosity).context("failed to initialize logging")?;
98100
helix-term/src/ui/editor.rs+2−4
@@ -11,13 +11,12 @@ use helix_core::{
1111 syntax::{self, HighlightEvent},
1212 Position, Range,
1313};
14−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
1514use helix_view::{document::Mode, Document, Editor, Theme, View};
1615use std::borrow::Cow;
1716
1817use crossterm::{
1918 cursor,
20− event::{read, Event, EventStream},
19+ event::{read, Event, EventStream, KeyCode, KeyEvent, KeyModifiers},
2120};
2221use tui::{
2322 backend::CrosstermBackend,
@@ -608,8 +607,7 @@ impl Component for EditorView {
608607 cx.editor.resize(Rect::new(0, 0, width, height - 1));
609608 EventResult::Consumed(None)
610609 }
611− Event::Key(key) => {
612− let mut key = KeyEvent::from(key);
610+ Event::Key(mut key) => {
613611 canonicalize_key(&mut key);
614612 // clear status
615613 cx.editor.status_msg = None;
helix-view/src/document.rs+25−36
@@ -1,7 +1,5 @@
11use anyhow::{anyhow, Context, Error};
2−use serde::de::{self, Deserialize, Deserializer};
32use std::cell::Cell;
4−use std::collections::HashMap;
53use std::fmt::Display;
64use std::future::Future;
75use std::path::{Component, Path, PathBuf};
@@ -17,6 +15,8 @@ use helix_core::{
1715
1816use crate::{DocumentId, ViewId};
1917
18+use std::collections::HashMap;
19+
2020#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2121pub enum Mode {
2222 Normal,
@@ -24,40 +24,6 @@ pub enum Mode {
2424 Insert,
2525}
2626
27−impl Display for Mode {
28− fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29− match self {
30− Mode::Normal => f.write_str("normal"),
31− Mode::Select => f.write_str("select"),
32− Mode::Insert => f.write_str("insert"),
33− }
34− }
35−}
36−
37−impl FromStr for Mode {
38− type Err = Error;
39−
40− fn from_str(s: &str) -> Result<Self, Self::Err> {
41− match s {
42− "normal" => Ok(Mode::Normal),
43− "select" => Ok(Mode::Select),
44− "insert" => Ok(Mode::Insert),
45− _ => Err(anyhow!("Invalid mode '{}'", s)),
46− }
47− }
48−}
49−
50−// toml deserializer doesn't seem to recognize string as enum
51−impl<'de> Deserialize<'de> for Mode {
52− fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53− where
54− D: Deserializer<'de>,
55− {
56− let s = String::deserialize(deserializer)?;
57− s.parse().map_err(de::Error::custom)
58− }
59−}
60−
6127#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
6228pub enum IndentStyle {
6329 Tabs,
@@ -122,6 +88,29 @@ impl fmt::Debug for Document {
12288 }
12389}
12490
91+impl Display for Mode {
92+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93+ match self {
94+ Mode::Normal => f.write_str("normal"),
95+ Mode::Select => f.write_str("select"),
96+ Mode::Insert => f.write_str("insert"),
97+ }
98+ }
99+}
100+
101+impl FromStr for Mode {
102+ type Err = Error;
103+
104+ fn from_str(s: &str) -> Result<Self, Self::Err> {
105+ match s {
106+ "normal" => Ok(Mode::Normal),
107+ "select" => Ok(Mode::Select),
108+ "insert" => Ok(Mode::Insert),
109+ _ => Err(anyhow!("Invalid mode '{}'", s)),
110+ }
111+ }
112+}
113+
125114/// Like std::mem::replace() except it allows the replacement value to be mapped from the
126115/// original value.
127116fn take_with<T, F>(mut_ref: &mut T, closure: F)
helix-view/src/input.rsdeleted−226
@@ -1,226 +0,0 @@
1−//! Input event handling, currently backed by crossterm.
2−use anyhow::{anyhow, Error};
3−use crossterm::event;
4−use serde::de::{self, Deserialize, Deserializer};
5−use std::fmt;
6−
7−pub use crossterm::event::{KeyCode, KeyModifiers};
8−
9−/// Represents a key event.
10−// We use a newtype here because we want to customize Deserialize and Display.
11−#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)]
12−pub struct KeyEvent {
13− pub code: KeyCode,
14− pub modifiers: KeyModifiers,
15−}
16−
17−impl fmt::Display for KeyEvent {
18− fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
19− f.write_fmt(format_args!(
20− "{}{}{}",
21− if self.modifiers.contains(KeyModifiers::SHIFT) {
22− "S-"
23− } else {
24− ""
25− },
26− if self.modifiers.contains(KeyModifiers::ALT) {
27− "A-"
28− } else {
29− ""
30− },
31− if self.modifiers.contains(KeyModifiers::CONTROL) {
32− "C-"
33− } else {
34− ""
35− },
36− ))?;
37− match self.code {
38− KeyCode::Backspace => f.write_str("backspace")?,
39− KeyCode::Enter => f.write_str("ret")?,
40− KeyCode::Left => f.write_str("left")?,
41− KeyCode::Right => f.write_str("right")?,
42− KeyCode::Up => f.write_str("up")?,
43− KeyCode::Down => f.write_str("down")?,
44− KeyCode::Home => f.write_str("home")?,
45− KeyCode::End => f.write_str("end")?,
46− KeyCode::PageUp => f.write_str("pageup")?,
47− KeyCode::PageDown => f.write_str("pagedown")?,
48− KeyCode::Tab => f.write_str("tab")?,
49− KeyCode::BackTab => f.write_str("backtab")?,
50− KeyCode::Delete => f.write_str("del")?,
51− KeyCode::Insert => f.write_str("ins")?,
52− KeyCode::Null => f.write_str("null")?,
53− KeyCode::Esc => f.write_str("esc")?,
54− KeyCode::Char('<') => f.write_str("lt")?,
55− KeyCode::Char('>') => f.write_str("gt")?,
56− KeyCode::Char('+') => f.write_str("plus")?,
57− KeyCode::Char('-') => f.write_str("minus")?,
58− KeyCode::Char(';') => f.write_str("semicolon")?,
59− KeyCode::Char('%') => f.write_str("percent")?,
60− KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?,
61− KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?,
62− };
63− Ok(())
64− }
65−}
66−
67−impl std::str::FromStr for KeyEvent {
68− type Err = Error;
69−
70− fn from_str(s: &str) -> Result<Self, Self::Err> {
71− let mut tokens: Vec<_> = s.split('-').collect();
72− let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? {
73− "backspace" => KeyCode::Backspace,
74− "space" => KeyCode::Char(' '),
75− "ret" => KeyCode::Enter,
76− "lt" => KeyCode::Char('<'),
77− "gt" => KeyCode::Char('>'),
78− "plus" => KeyCode::Char('+'),
79− "minus" => KeyCode::Char('-'),
80− "semicolon" => KeyCode::Char(';'),
81− "percent" => KeyCode::Char('%'),
82− "left" => KeyCode::Left,
83− "right" => KeyCode::Right,
84− "up" => KeyCode::Down,
85− "home" => KeyCode::Home,
86− "end" => KeyCode::End,
87− "pageup" => KeyCode::PageUp,
88− "pagedown" => KeyCode::PageDown,
89− "tab" => KeyCode::Tab,
90− "backtab" => KeyCode::BackTab,
91− "del" => KeyCode::Delete,
92− "ins" => KeyCode::Insert,
93− "null" => KeyCode::Null,
94− "esc" => KeyCode::Esc,
95− single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()),
96− function if function.len() > 1 && function.starts_with('F') => {
97− let function: String = function.chars().skip(1).collect();
98− let function = str::parse::<u8>(&function)?;
99− (function > 0 && function < 13)
100− .then(|| KeyCode::F(function))
101− .ok_or_else(|| anyhow!("Invalid function key '{}'", function))?
102− }
103− invalid => return Err(anyhow!("Invalid key code '{}'", invalid)),
104− };
105−
106− let mut modifiers = KeyModifiers::empty();
107− for token in tokens {
108− let flag = match token {
109− "S" => KeyModifiers::SHIFT,
110− "A" => KeyModifiers::ALT,
111− "C" => KeyModifiers::CONTROL,
112− _ => return Err(anyhow!("Invalid key modifier '{}-'", token)),
113− };
114−
115− if modifiers.contains(flag) {
116− return Err(anyhow!("Repeated key modifier '{}-'", token));
117− }
118− modifiers.insert(flag);
119− }
120−
121− Ok(KeyEvent { code, modifiers })
122− }
123−}
124−
125−impl<'de> Deserialize<'de> for KeyEvent {
126− fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
127− where
128− D: Deserializer<'de>,
129− {
130− let s = String::deserialize(deserializer)?;
131− s.parse().map_err(de::Error::custom)
132− }
133−}
134−
135−impl From<event::KeyEvent> for KeyEvent {
136− fn from(event::KeyEvent { code, modifiers }: event::KeyEvent) -> KeyEvent {
137− KeyEvent { code, modifiers }
138− }
139−}
140−
141−#[cfg(test)]
142−mod test {
143− use super::*;
144−
145− #[test]
146− fn parsing_unmodified_keys() {
147− assert_eq!(
148− str::parse::<KeyEvent>("backspace").unwrap(),
149− KeyEvent {
150− code: KeyCode::Backspace,
151− modifiers: KeyModifiers::NONE
152− }
153− );
154−
155− assert_eq!(
156− str::parse::<KeyEvent>("left").unwrap(),
157− KeyEvent {
158− code: KeyCode::Left,
159− modifiers: KeyModifiers::NONE
160− }
161− );
162−
163− assert_eq!(
164− str::parse::<KeyEvent>(",").unwrap(),
165− KeyEvent {
166− code: KeyCode::Char(','),
167− modifiers: KeyModifiers::NONE
168− }
169− );
170−
171− assert_eq!(
172− str::parse::<KeyEvent>("w").unwrap(),
173− KeyEvent {
174− code: KeyCode::Char('w'),
175− modifiers: KeyModifiers::NONE
176− }
177− );
178−
179− assert_eq!(
180− str::parse::<KeyEvent>("F12").unwrap(),
181− KeyEvent {
182− code: KeyCode::F(12),
183− modifiers: KeyModifiers::NONE
184− }
185− );
186− }
187−
188− #[test]
189− fn parsing_modified_keys() {
190− assert_eq!(
191− str::parse::<KeyEvent>("S-minus").unwrap(),
192− KeyEvent {
193− code: KeyCode::Char('-'),
194− modifiers: KeyModifiers::SHIFT
195− }
196− );
197−
198− assert_eq!(
199− str::parse::<KeyEvent>("C-A-S-F12").unwrap(),
200− KeyEvent {
201− code: KeyCode::F(12),
202− modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
203− }
204− );
205−
206− assert_eq!(
207− str::parse::<KeyEvent>("S-C-2").unwrap(),
208− KeyEvent {
209− code: KeyCode::Char('2'),
210− modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
211− }
212− );
213− }
214−
215− #[test]
216− fn parsing_nonsensical_keys_fails() {
217− assert!(str::parse::<KeyEvent>("F13").is_err());
218− assert!(str::parse::<KeyEvent>("F0").is_err());
219− assert!(str::parse::<KeyEvent>("aaa").is_err());
220− assert!(str::parse::<KeyEvent>("S-S-a").is_err());
221− assert!(str::parse::<KeyEvent>("C-A-S-C-1").is_err());
222− assert!(str::parse::<KeyEvent>("FU").is_err());
223− assert!(str::parse::<KeyEvent>("123").is_err());
224− assert!(str::parse::<KeyEvent>("S--").is_err());
225− }
226−}
helix-view/src/lib.rs+3−5
@@ -3,16 +3,14 @@ pub mod macros;
33
44pub mod document;
55pub mod editor;
6−pub mod input;
76pub mod register_selection;
87pub mod theme;
98pub mod tree;
109pub mod view;
1110
12−slotmap::new_key_type! {
13− pub struct DocumentId;
14− pub struct ViewId;
15−}
11+use slotmap::new_key_type;
12+new_key_type! { pub struct DocumentId; }
13+new_key_type! { pub struct ViewId; }
1614
1715pub use document::Document;
1816pub use editor::Editor;