on master help sign in
Revert "Refactor key into helix-view"
10f9f72Blaž Hrastnik
helix-term/src/application.rs+2−2
@@ -1,7 +1,7 @@
1use helix_lsp::{lsp, LspProgressMap};
1use helix_lsp::{lsp, LspProgressMap};
2use helix_view::{document::Mode, Document, Editor, Theme, View};
2use helix_view::{document::Mode, Document, Editor, Theme, View};
3
3
4−use crate::{args::Args, compositor::Compositor, config::Config, ui};
4+use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui};
5
5
6use log::{error, info};
6use log::{error, info};
7
7
@@ -49,7 +49,7 @@ impl Application {
49 let size = compositor.size();
49 let size = compositor.size();
50 let mut editor = Editor::new(size);
50 let mut editor = Editor::new(size);
51
51
52− let mut editor_view = Box::new(ui::EditorView::new(config.keys));
52+ let mut editor_view = Box::new(ui::EditorView::new(config.keymaps));
53 compositor.push(editor_view);
53 compositor.push(editor_view);
54
54
55 if !args.files.is_empty() {
55 if !args.files.is_empty() {
helix-term/src/commands.rs+27−44
@@ -11,7 +11,6 @@ use helix_core::{
11
11
12use helix_view::{
12use helix_view::{
13 document::{IndentStyle, Mode},
13 document::{IndentStyle, Mode},
14− input::{KeyCode, KeyEvent},
15 view::{View, PADDING},
14 view::{View, PADDING},
16 Document, DocumentId, Editor, ViewId,
15 Document, DocumentId, Editor, ViewId,
17};
16};
@@ -39,8 +38,8 @@ use std::{
39 path::{Path, PathBuf},
38 path::{Path, PathBuf},
40};
39};
41
40
41+use crossterm::event::{KeyCode, KeyEvent};
42use once_cell::sync::Lazy;
42use once_cell::sync::Lazy;
43−use serde::de::{self, Deserialize, Deserializer};
44
43
45pub struct Context<'a> {
44pub struct Context<'a> {
46 pub selected_register: helix_view::RegisterSelection,
45 pub selected_register: helix_view::RegisterSelection,
@@ -253,48 +252,6 @@ impl Command {
253 );
252 );
254}
253}
255
254
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−
298fn move_char_left(cx: &mut Context) {
255fn move_char_left(cx: &mut Context) {
299 let count = cx.count();
256 let count = cx.count();
300 let (view, doc) = current!(cx.editor);
257 let (view, doc) = current!(cx.editor);
@@ -3085,3 +3042,29 @@ fn right_bracket_mode(cx: &mut Context) {
3085 }
3042 }
3086 })
3043 })
3087}
3044}
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};
2
3
3−use crate::commands::Command;
4+use serde::{de::Error as SerdeError, Deserialize, Serialize};
5+
4−use crate::keymap::Keymaps;
6+use crate::keymap::{parse_keymaps, Keymaps};
5
7
6−#[derive(Debug, PartialEq, Deserialize)]
7pub struct GlobalConfig {
8pub struct GlobalConfig {
8 pub lsp_progress: bool,
9 pub lsp_progress: bool,
9}
10}
@@ -14,50 +15,35 @@ impl Default for GlobalConfig {
14 }
15 }
15}
16}
16
17
17−#[derive(Debug, Default, PartialEq, Deserialize)]
18+#[derive(Default)]
18−#[serde(default)]
19pub struct Config {
19pub struct Config {
20 pub global: GlobalConfig,
20 pub global: GlobalConfig,
21− pub keys: Keymaps,
21+ pub keymaps: Keymaps,
22}
22}
23
23
24−#[test]
24+#[derive(Serialize, Deserialize)]
25−fn parsing_keymaps_config_file() {
25+#[serde(rename_all = "kebab-case")]
26− use helix_core::hashmap;
26+struct TomlConfig {
27− use helix_view::document::Mode;
27+ lsp_progress: Option<bool>,
28− use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
28+ keys: Option<HashMap<String, HashMap<String, String>>>,
29−
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− "#;
38
30
39− assert_eq!(
31+impl<'de> Deserialize<'de> for Config {
40− toml::from_str::<Config>(sample_keymaps).unwrap(),
32+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
41− Config {
33+ where
42− global: Default::default(),
34+ D: serde::Deserializer<'de>,
43− keys: Keymaps(hashmap! {
35+ {
44− Mode::Insert => hashmap! {
36+ let config = TomlConfig::deserialize(deserializer)?;
45− KeyEvent {
37+ Ok(Self {
46− code: KeyCode::Char('y'),
38+ global: GlobalConfig {
47− modifiers: KeyModifiers::NONE,
39+ lsp_progress: config.lsp_progress.unwrap_or(true),
48− } => Command::move_line_down,
40+ },
49− KeyEvent {
41+ keymaps: config
50− code: KeyCode::Char('a'),
42+ .keys
51− modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL,
43+ .map(|r| parse_keymaps(&r))
52− } => Command::delete_selection,
44+ .transpose()
53− },
45+ .map_err(|e| D::Error::custom(format!("Error deserializing keymap: {}", e)))?
54− Mode::Normal => hashmap! {
46+ .unwrap_or_else(Keymaps::default),
55− KeyEvent {
56− code: KeyCode::F(12),
57− modifiers: KeyModifiers::ALT,
58− } => Command::move_next_word_end,
59− },
47+ })
60− })
61− }
48+ }
62− );
63}
49}
helix-term/src/keymap.rs+316−20
@@ -3,8 +3,6 @@ pub use crate::commands::Command;
3use anyhow::{anyhow, Error, Result};
3use anyhow::{anyhow, Error, Result};
4use helix_core::hashmap;
4use helix_core::hashmap;
5use helix_view::document::Mode;
5use helix_view::document::Mode;
6−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
7−use serde::Deserialize;
8use std::{
6use std::{
9 collections::HashMap,
7 collections::HashMap,
10 fmt::Display,
8 fmt::Display,
@@ -101,6 +99,14 @@ use std::{
101// D] = last diagnostic
99// D] = last diagnostic
102// }
100// }
103
101
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+
104#[macro_export]
110#[macro_export]
105macro_rules! key {
111macro_rules! key {
106 ($key:ident) => {
112 ($key:ident) => {
@@ -135,21 +141,9 @@ macro_rules! alt {
135 };
141 };
136}
142}
137
143
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−
150impl Default for Keymaps {
144impl Default for Keymaps {
151− fn default() -> Keymaps {
145+ fn default() -> Self {
152− let normal = hashmap!(
146+ let normal = Keymap(hashmap!(
153 key!('h') => Command::move_char_left,
147 key!('h') => Command::move_char_left,
154 key!('j') => Command::move_line_down,
148 key!('j') => Command::move_line_down,
155 key!('k') => Command::move_line_up,
149 key!('k') => Command::move_line_up,
@@ -283,12 +277,12 @@ impl Default for Keymaps {
283 key!('z') => Command::view_mode,
277 key!('z') => Command::view_mode,
284
278
285 key!('"') => Command::select_register,
279 key!('"') => Command::select_register,
286− );
280+ ));
287 // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether
281 // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether
288 // we keep this separate select mode. More keys can fit into normal mode then, but it's weird
282 // we keep this separate select mode. More keys can fit into normal mode then, but it's weird
289 // because some selection operations can now be done from normal mode, some from select mode.
283 // because some selection operations can now be done from normal mode, some from select mode.
290 let mut select = normal.clone();
284 let mut select = normal.clone();
291− select.extend(
285+ select.0.extend(
292 hashmap!(
286 hashmap!(
293 key!('h') => Command::extend_char_left,
287 key!('h') => Command::extend_char_left,
294 key!('j') => Command::extend_line_down,
288 key!('j') => Command::extend_line_down,
@@ -321,7 +315,7 @@ impl Default for Keymaps {
321 // TODO: select could be normal mode with some bindings merged over
315 // TODO: select could be normal mode with some bindings merged over
322 Mode::Normal => normal,
316 Mode::Normal => normal,
323 Mode::Select => select,
317 Mode::Select => select,
324− Mode::Insert => hashmap!(
318+ Mode::Insert => Keymap(hashmap!(
325 key!(Esc) => Command::normal_mode as Command,
319 key!(Esc) => Command::normal_mode as Command,
326 key!(Backspace) => Command::delete_char_backward,
320 key!(Backspace) => Command::delete_char_backward,
327 key!(Delete) => Command::delete_char_forward,
321 key!(Delete) => Command::delete_char_forward,
@@ -337,7 +331,309 @@ impl Default for Keymaps {
337 key!(End) => Command::move_line_end,
331 key!(End) => Command::move_line_end,
338 ctrl!('x') => Command::completion,
332 ctrl!('x') => Command::completion,
339 ctrl!('w') => Command::delete_word_backward,
333 ctrl!('w') => Command::delete_word_backward,
340− ),
334+ )),
341 ))
335 ))
342 }
336 }
343}
337}
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};
2use helix_term::application::Application;
1use helix_term::application::Application;
3use helix_term::args::Args;
2use helix_term::args::Args;
4use helix_term::config::Config;
3use helix_term::config::Config;
5use std::path::PathBuf;
4use std::path::PathBuf;
6
5
6+use anyhow::{Context, Result};
7+
7fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> {
8fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> {
8 let mut base_config = fern::Dispatch::new();
9 let mut base_config = fern::Dispatch::new();
9
10
@@ -88,11 +89,12 @@ FLAGS:
88 std::fs::create_dir_all(&conf_dir).ok();
89 std::fs::create_dir_all(&conf_dir).ok();
89 }
90 }
90
91
91− let config = match std::fs::read_to_string(conf_dir.join("config.toml")) {
92+ let config = std::fs::read_to_string(conf_dir.join("config.toml"))
93+ .ok()
92− Ok(config) => toml::from_str(&config)?,
94+ .map(|s| toml::from_str(&s))
93− Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(),
95+ .transpose()?
94− Err(err) => return Err(Error::new(err)),
96+ .or_else(|| Some(Config::default()))
95− };
97+ .unwrap();
96
98
97 setup_logging(logpath, args.verbosity).context("failed to initialize logging")?;
99 setup_logging(logpath, args.verbosity).context("failed to initialize logging")?;
98
100
helix-term/src/ui/editor.rs+2−4
@@ -11,13 +11,12 @@ use helix_core::{
11 syntax::{self, HighlightEvent},
11 syntax::{self, HighlightEvent},
12 Position, Range,
12 Position, Range,
13};
13};
14−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
15use helix_view::{document::Mode, Document, Editor, Theme, View};
14use helix_view::{document::Mode, Document, Editor, Theme, View};
16use std::borrow::Cow;
15use std::borrow::Cow;
17
16
18use crossterm::{
17use crossterm::{
19 cursor,
18 cursor,
20− event::{read, Event, EventStream},
19+ event::{read, Event, EventStream, KeyCode, KeyEvent, KeyModifiers},
21};
20};
22use tui::{
21use tui::{
23 backend::CrosstermBackend,
22 backend::CrosstermBackend,
@@ -608,8 +607,7 @@ impl Component for EditorView {
608 cx.editor.resize(Rect::new(0, 0, width, height - 1));
607 cx.editor.resize(Rect::new(0, 0, width, height - 1));
609 EventResult::Consumed(None)
608 EventResult::Consumed(None)
610 }
609 }
611− Event::Key(key) => {
610+ Event::Key(mut key) => {
612− let mut key = KeyEvent::from(key);
613 canonicalize_key(&mut key);
611 canonicalize_key(&mut key);
614 // clear status
612 // clear status
615 cx.editor.status_msg = None;
613 cx.editor.status_msg = None;
helix-view/src/document.rs+25−36
@@ -1,7 +1,5 @@
1use anyhow::{anyhow, Context, Error};
1use anyhow::{anyhow, Context, Error};
2−use serde::de::{self, Deserialize, Deserializer};
3use std::cell::Cell;
2use std::cell::Cell;
4−use std::collections::HashMap;
5use std::fmt::Display;
3use std::fmt::Display;
6use std::future::Future;
4use std::future::Future;
7use std::path::{Component, Path, PathBuf};
5use std::path::{Component, Path, PathBuf};
@@ -17,6 +15,8 @@ use helix_core::{
17
15
18use crate::{DocumentId, ViewId};
16use crate::{DocumentId, ViewId};
19
17
18+use std::collections::HashMap;
19+
20#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
20#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
21pub enum Mode {
21pub enum Mode {
22 Normal,
22 Normal,
@@ -24,40 +24,6 @@ pub enum Mode {
24 Insert,
24 Insert,
25}
25}
26
26
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−
61#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
27#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
62pub enum IndentStyle {
28pub enum IndentStyle {
63 Tabs,
29 Tabs,
@@ -122,6 +88,29 @@ impl fmt::Debug for Document {
122 }
88 }
123}
89}
124
90
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+
125/// Like std::mem::replace() except it allows the replacement value to be mapped from the
114/// Like std::mem::replace() except it allows the replacement value to be mapped from the
126/// original value.
115/// original value.
127fn take_with<T, F>(mut_ref: &mut T, closure: F)
116fn 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;
3
3
4pub mod document;
4pub mod document;
5pub mod editor;
5pub mod editor;
6−pub mod input;
7pub mod register_selection;
6pub mod register_selection;
8pub mod theme;
7pub mod theme;
9pub mod tree;
8pub mod tree;
10pub mod view;
9pub mod view;
11
10
12−slotmap::new_key_type! {
11+use slotmap::new_key_type;
13− pub struct DocumentId;
12+new_key_type! { pub struct DocumentId; }
14− pub struct ViewId;
13+new_key_type! { pub struct ViewId; }
15−}
16
14
17pub use document::Document;
15pub use document::Document;
18pub use editor::Editor;
16pub use editor::Editor;