From f7e00cf720f55ea82933ac6625b7511e9d38139e Mon Sep 17 00:00:00 2001 From: PabloMansanet Date: Thu, 17 Jun 2021 13:08:05 +0200 Subject: Configurable keys 2 (Mapping keys to commands) (#268) * Add convenience/clarity wrapper for Range initialization * Add keycode parse and display methods * Add remapping functions and tests * Implement key remapping * Add remapping book entry * Use raw string literal for toml * Add command constants * Make command functions private * Map directly to commands * Match key parsing/displaying to Kakoune * Formatting pass * Update documentation * Formatting * Fix example in the book * Refactor into single config file * Formatting * Refactor configuration and add keymap newtype wrappers * Address first batch of PR comments * Replace FromStr with custom deserialize--- helix-term/src/ui/editor.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) (limited to 'helix-term/src/ui') diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 63b3e277..07107c9e 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -11,10 +11,7 @@ use helix_core::{ syntax::{self, HighlightEvent}, Position, Range, }; -use helix_view::{ - document::{IndentStyle, Mode}, - Document, Editor, Theme, View, -}; +use helix_view::{document::Mode, Document, Editor, Theme, View}; use std::borrow::Cow; use crossterm::{ @@ -30,7 +27,7 @@ use tui::{ }; pub struct EditorView { - keymap: Keymaps, + keymaps: Keymaps, on_next_key: Option>, last_insert: (commands::Command, Vec), completion: Option, @@ -40,16 +37,16 @@ const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter impl Default for EditorView { fn default() -> Self { - Self::new() + Self::new(Keymaps::default()) } } impl EditorView { - pub fn new() -> Self { + pub fn new(keymaps: Keymaps) -> Self { Self { - keymap: keymap::default(), + keymaps, on_next_key: None, - last_insert: (commands::normal_mode, Vec::new()), + last_insert: (commands::Command::normal_mode, Vec::new()), completion: None, } } @@ -546,8 +543,8 @@ impl EditorView { } fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) { - if let Some(command) = self.keymap[&Mode::Insert].get(&event) { - command(cx); + if let Some(command) = self.keymaps[&Mode::Insert].get(&event) { + command.execute(cx); } else if let KeyEvent { code: KeyCode::Char(ch), .. @@ -568,7 +565,7 @@ impl EditorView { // special handling for repeat operator key!('.') => { // first execute whatever put us into insert mode - (self.last_insert.0)(cxt); + self.last_insert.0.execute(cxt); // then replay the inputs for key in &self.last_insert.1 { self.insert_mode(cxt, *key) @@ -584,8 +581,8 @@ impl EditorView { // set the register cxt.selected_register = cxt.editor.selected_register.take(); - if let Some(command) = self.keymap[&mode].get(&event) { - command(cxt); + if let Some(command) = self.keymaps[&mode].get(&event) { + command.execute(cxt); } } } @@ -699,7 +696,7 @@ impl Component for EditorView { // how we entered insert mode is important, and we should track that so // we can repeat the side effect. - self.last_insert.0 = self.keymap[&mode][&key]; + self.last_insert.0 = self.keymaps[&mode][&key]; self.last_insert.1.clear(); } (Mode::Insert, Mode::Normal) => { -- cgit v1.2.3-70-g09d2 From 8664d70e731c73fa34dda293b4f6b6dec80a3273 Mon Sep 17 00:00:00 2001 From: Benoît CORTIER Date: Thu, 17 Jun 2021 18:09:10 -0400 Subject: Replace `Editor::current` by a macro This is necessary to workaround ownership issues across function calls. The issue notably arised when implementing the registers into `Editor` and I was getting annoyed again when implementing copy/pasting into system clipboard. The problem is addressed by using macro calls instead of function calls. There is no notable side effect. --- helix-term/src/commands.rs | 256 +++++++++++++++++++--------------------- helix-term/src/lib.rs | 3 + helix-term/src/ui/completion.rs | 6 +- helix-term/src/ui/editor.rs | 4 +- helix-term/src/ui/mod.rs | 10 +- helix-view/src/editor.rs | 29 +---- helix-view/src/lib.rs | 3 + helix-view/src/macros.rs | 29 +++++ 8 files changed, 172 insertions(+), 168 deletions(-) create mode 100644 helix-view/src/macros.rs (limited to 'helix-term/src/ui') diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 3ec06aaa..dc4805a5 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -52,27 +52,6 @@ pub struct Context<'a> { } impl<'a> Context<'a> { - #[inline] - pub fn view(&mut self) -> &mut View { - self.editor.view_mut() - } - - #[inline] - pub fn doc(&mut self) -> &mut Document { - let id = self.editor.view().doc; - &mut self.editor.documents[id] - } - - #[inline] - pub fn current(&mut self) -> (&mut View, &mut Document) { - self.editor.current() - } - - #[inline] - pub fn current_with_registers(&mut self) -> (&mut View, &mut Document, &mut Registers) { - self.editor.current_with_registers() - } - /// Push a new component onto the compositor. pub fn push_layer(&mut self, mut component: Box) { self.callback = Some(Box::new(|compositor: &mut Compositor| { @@ -275,7 +254,7 @@ impl Command { fn move_char_left(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_horizontally(text, range, Direction::Backward, count, Movement::Move) @@ -285,7 +264,7 @@ fn move_char_left(cx: &mut Context) { fn move_char_right(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_horizontally(text, range, Direction::Forward, count, Movement::Move) @@ -295,7 +274,7 @@ fn move_char_right(cx: &mut Context) { fn move_line_up(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_vertically(text, range, Direction::Backward, count, Movement::Move) @@ -305,7 +284,7 @@ fn move_line_up(cx: &mut Context) { fn move_line_down(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_vertically(text, range, Direction::Forward, count, Movement::Move) @@ -314,7 +293,7 @@ fn move_line_down(cx: &mut Context) { } fn move_line_end(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -330,7 +309,7 @@ fn move_line_end(cx: &mut Context) { } fn move_line_start(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -345,7 +324,7 @@ fn move_line_start(cx: &mut Context) { } fn move_first_nonwhitespace(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -368,7 +347,7 @@ fn move_first_nonwhitespace(cx: &mut Context) { fn move_next_word_start(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc @@ -380,7 +359,7 @@ fn move_next_word_start(cx: &mut Context) { fn move_prev_word_start(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc @@ -392,7 +371,7 @@ fn move_prev_word_start(cx: &mut Context) { fn move_next_word_end(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc @@ -404,13 +383,13 @@ fn move_next_word_end(cx: &mut Context) { fn move_file_start(cx: &mut Context) { push_jump(cx.editor); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); doc.set_selection(view.id, Selection::point(0)); } fn move_file_end(cx: &mut Context) { push_jump(cx.editor); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text(); let last_line = text.line_to_char(text.len_lines().saturating_sub(2)); doc.set_selection(view.id, Selection::point(last_line)); @@ -418,7 +397,7 @@ fn move_file_end(cx: &mut Context) { fn extend_next_word_start(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|mut range| { @@ -432,7 +411,7 @@ fn extend_next_word_start(cx: &mut Context) { fn extend_prev_word_start(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|mut range| { @@ -445,7 +424,7 @@ fn extend_prev_word_start(cx: &mut Context) { fn extend_next_word_end(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|mut range| { @@ -482,7 +461,7 @@ where _ => return, }; - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|mut range| { @@ -574,7 +553,7 @@ fn extend_prev_char(cx: &mut Context) { } fn extend_first_nonwhitespace(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -607,7 +586,7 @@ fn replace(cx: &mut Context) { }; if let Some(ch) = ch { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let transaction = Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| { @@ -631,7 +610,7 @@ fn replace(cx: &mut Context) { fn scroll(cx: &mut Context, offset: usize, direction: Direction) { use Direction::*; - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let cursor = coords_at_pos(doc.text().slice(..), doc.selection(view.id).cursor()); let doc_last_line = doc.text().len_lines() - 1; @@ -672,32 +651,32 @@ fn scroll(cx: &mut Context, offset: usize, direction: Direction) { } fn page_up(cx: &mut Context) { - let view = cx.view(); + let view = view!(cx.editor); let offset = view.area.height as usize; scroll(cx, offset, Direction::Backward); } fn page_down(cx: &mut Context) { - let view = cx.view(); + let view = view!(cx.editor); let offset = view.area.height as usize; scroll(cx, offset, Direction::Forward); } fn half_page_up(cx: &mut Context) { - let view = cx.view(); + let view = view!(cx.editor); let offset = view.area.height as usize / 2; scroll(cx, offset, Direction::Backward); } fn half_page_down(cx: &mut Context) { - let view = cx.view(); + let view = view!(cx.editor); let offset = view.area.height as usize / 2; scroll(cx, offset, Direction::Forward); } fn extend_char_left(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_horizontally(text, range, Direction::Backward, count, Movement::Extend) @@ -707,7 +686,7 @@ fn extend_char_left(cx: &mut Context) { fn extend_char_right(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_horizontally(text, range, Direction::Forward, count, Movement::Extend) @@ -717,7 +696,7 @@ fn extend_char_right(cx: &mut Context) { fn extend_line_up(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_vertically(text, range, Direction::Backward, count, Movement::Extend) @@ -727,7 +706,7 @@ fn extend_line_up(cx: &mut Context) { fn extend_line_down(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc.selection(view.id).transform(|range| { movement::move_vertically(text, range, Direction::Forward, count, Movement::Extend) @@ -736,7 +715,7 @@ fn extend_line_down(cx: &mut Context) { } fn extend_line_end(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -752,7 +731,7 @@ fn extend_line_end(cx: &mut Context) { } fn extend_line_start(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id).transform(|range| { let text = doc.text(); @@ -767,7 +746,7 @@ fn extend_line_start(cx: &mut Context) { } fn select_all(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let end = doc.text().len_chars().saturating_sub(1); doc.set_selection(view.id, Selection::single(0, end)) @@ -796,7 +775,7 @@ fn split_selection(cx: &mut Context) { } fn split_selection_on_newline(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); // only compile the regex once #[allow(clippy::trivial_regex)] @@ -848,7 +827,7 @@ fn search_impl(doc: &mut Document, view: &mut View, contents: &str, regex: &Rege // TODO: use one function for search vs extend fn search(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); // TODO: could probably share with select_on_matches? @@ -871,7 +850,8 @@ fn search(cx: &mut Context) { } fn search_next_impl(cx: &mut Context, extend: bool) { - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; if let Some(query) = registers.read('\\') { let query = query.first().unwrap(); let contents = doc.text().slice(..).to_string(); @@ -889,7 +869,7 @@ fn extend_search_next(cx: &mut Context) { } fn search_selection(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let contents = doc.text().slice(..); let query = doc.selection(view.id).primary().fragment(contents); let regex = regex::escape(&query); @@ -905,7 +885,7 @@ fn search_selection(cx: &mut Context) { fn select_line(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let pos = doc.selection(view.id).primary(); let text = doc.text(); @@ -920,7 +900,7 @@ fn select_line(cx: &mut Context) { } fn extend_line(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let pos = doc.selection(view.id).primary(); let text = doc.text(); @@ -962,7 +942,8 @@ fn delete_selection_impl(reg: &mut Register, doc: &mut Document, view_id: ViewId fn delete_selection(cx: &mut Context) { let reg_name = cx.selected_register.name(); - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; let reg = registers.get_or_insert(reg_name); delete_selection_impl(reg, doc, view.id); @@ -974,14 +955,15 @@ fn delete_selection(cx: &mut Context) { fn change_selection(cx: &mut Context) { let reg_name = cx.selected_register.name(); - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; let reg = registers.get_or_insert(reg_name); delete_selection_impl(reg, doc, view.id); enter_insert_mode(doc); } fn collapse_selection(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc .selection(view.id) .transform(|range| Range::new(range.head, range.head)); @@ -990,7 +972,7 @@ fn collapse_selection(cx: &mut Context) { } fn flip_selections(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let selection = doc .selection(view.id) .transform(|range| Range::new(range.head, range.anchor)); @@ -1004,7 +986,7 @@ fn enter_insert_mode(doc: &mut Document) { // inserts at the start of each selection fn insert_mode(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); enter_insert_mode(doc); let selection = doc @@ -1015,7 +997,7 @@ fn insert_mode(cx: &mut Context) { // inserts at the end of each selection fn append_mode(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); enter_insert_mode(doc); doc.restore_cursor = true; @@ -1062,11 +1044,11 @@ mod cmd { if editor.tree.views().count() == 1 && buffers_remaining_impl(editor) { return; } - editor.close(editor.view().id, /* close_buffer */ false); + editor.close(view!(editor).id, /* close_buffer */ false); } fn force_quit(editor: &mut Editor, args: &[&str], event: PromptEvent) { - editor.close(editor.view().id, /* close_buffer */ false); + editor.close(view!(editor).id, /* close_buffer */ false); } fn open(editor: &mut Editor, args: &[&str], event: PromptEvent) { @@ -1108,7 +1090,7 @@ mod cmd { } fn write(editor: &mut Editor, args: &[&str], event: PromptEvent) { - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); if let Err(e) = write_impl(view, doc, args.first()) { editor.set_error(e.to_string()); }; @@ -1119,7 +1101,7 @@ mod cmd { } fn format(editor: &mut Editor, args: &[&str], event: PromptEvent) { - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); doc.format(view.id) } @@ -1129,7 +1111,7 @@ mod cmd { // If no argument, report current indent style. if args.is_empty() { - let style = editor.current().1.indent_style; + let style = current!(editor).1.indent_style; editor.set_status(match style { Tabs => "tabs".into(), Spaces(1) => "1 space".into(), @@ -1152,7 +1134,7 @@ mod cmd { }; if let Some(s) = style { - let (_, doc) = editor.current(); + let doc = doc_mut!(editor); doc.indent_style = s; } else { // Invalid argument. @@ -1168,7 +1150,7 @@ mod cmd { return; } }; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); doc.earlier(view.id, uk) } @@ -1180,12 +1162,12 @@ mod cmd { return; } }; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); doc.later(view.id, uk) } fn write_quit(editor: &mut Editor, args: &[&str], event: PromptEvent) { - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); if let Err(e) = write_impl(view, doc, args.first()) { editor.set_error(e.to_string()); return; @@ -1499,7 +1481,7 @@ fn file_picker(cx: &mut Context) { fn buffer_picker(cx: &mut Context) { use std::path::{Path, PathBuf}; - let current = cx.editor.view().doc; + let current = view!(cx.editor).doc; let picker = Picker::new( cx.editor @@ -1547,7 +1529,7 @@ fn symbol_picker(cx: &mut Context) { nested_to_flat(list, file, child); } } - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -1568,7 +1550,7 @@ fn symbol_picker(cx: &mut Context) { let symbols = match symbols { lsp::DocumentSymbolResponse::Flat(symbols) => symbols, lsp::DocumentSymbolResponse::Nested(symbols) => { - let (_view, doc) = editor.current(); + let (_view, doc) = current!(editor); let mut flat_symbols = Vec::new(); for symbol in symbols { nested_to_flat(&mut flat_symbols, &doc.identifier(), symbol) @@ -1582,7 +1564,7 @@ fn symbol_picker(cx: &mut Context) { |symbol| (&symbol.name).into(), move |editor: &mut Editor, symbol, _action| { push_jump(editor); - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); if let Some(range) = lsp_range_to_range(doc.text(), symbol.location.range, offset_encoding) @@ -1601,13 +1583,13 @@ fn symbol_picker(cx: &mut Context) { // I inserts at the first nonwhitespace character of each line with a selection fn prepend_to_line(cx: &mut Context) { move_first_nonwhitespace(cx); - let doc = cx.doc(); + let doc = doc_mut!(cx.editor); enter_insert_mode(doc); } // A inserts at the end of each line with a selection fn append_to_line(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); enter_insert_mode(doc); let selection = doc.selection(view.id).transform(|range| { @@ -1627,7 +1609,7 @@ enum Open { fn open(cx: &mut Context, open: Open) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); enter_insert_mode(doc); let text = doc.text().slice(..); @@ -1695,7 +1677,7 @@ fn open_above(cx: &mut Context) { } fn normal_mode(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); doc.mode = Mode::Normal; @@ -1718,13 +1700,13 @@ fn normal_mode(cx: &mut Context) { // Store a jump on the jumplist. fn push_jump(editor: &mut Editor) { - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let jump = (doc.id(), doc.selection(view.id).clone()); view.jumps.push(jump); } fn switch_to_last_accessed_file(cx: &mut Context) { - let alternate_file = cx.view().last_accessed_doc; + let alternate_file = view!(cx.editor).last_accessed_doc; if let Some(alt) = alternate_file { cx.editor.switch(alt, Action::Replace); } else { @@ -1736,7 +1718,7 @@ fn goto_mode(cx: &mut Context) { if let Some(count) = cx.count { push_jump(cx.editor); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let line_idx = std::cmp::min(count.get() - 1, doc.text().len_lines().saturating_sub(2)); let pos = doc.text().line_to_char(line_idx); doc.set_selection(view.id, Selection::point(pos)); @@ -1750,7 +1732,8 @@ fn goto_mode(cx: &mut Context) { } = event { // TODO: temporarily show GOTO in the mode list - match (cx.doc().mode, ch) { + let doc = doc_mut!(cx.editor); + match (doc.mode, ch) { (_, 'g') => move_file_start(cx), (_, 'e') => move_file_end(cx), (_, 'a') => switch_to_last_accessed_file(cx), @@ -1766,7 +1749,7 @@ fn goto_mode(cx: &mut Context) { (Mode::Select, 's') => extend_first_nonwhitespace(cx), (_, 't') | (_, 'm') | (_, 'b') => { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let pos = doc.selection(view.id).cursor(); let line = doc.text().char_to_line(pos); @@ -1794,11 +1777,11 @@ fn goto_mode(cx: &mut Context) { } fn select_mode(cx: &mut Context) { - cx.doc().mode = Mode::Select; + doc_mut!(cx.editor).mode = Mode::Select; } fn exit_select_mode(cx: &mut Context) { - cx.doc().mode = Mode::Normal; + doc_mut!(cx.editor).mode = Mode::Normal; } fn goto_impl( @@ -1820,7 +1803,7 @@ fn goto_impl( let id = editor .open(PathBuf::from(location.uri.path()), action) .expect("editor.open failed"); - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let definition_pos = location.range.start; // TODO: convert inside server let new_pos = @@ -1858,7 +1841,7 @@ fn goto_impl( } fn goto_definition(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -1895,7 +1878,7 @@ fn goto_definition(cx: &mut Context) { } fn goto_type_definition(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -1932,7 +1915,7 @@ fn goto_type_definition(cx: &mut Context) { } fn goto_implementation(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -1969,7 +1952,7 @@ fn goto_implementation(cx: &mut Context) { } fn goto_reference(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -2000,7 +1983,7 @@ fn goto_reference(cx: &mut Context) { fn goto_pos(editor: &mut Editor, pos: usize) { push_jump(editor); - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); doc.set_selection(view.id, Selection::point(pos)); align_view(doc, view, Align::Center); @@ -2008,7 +1991,7 @@ fn goto_pos(editor: &mut Editor, pos: usize) { fn goto_first_diag(cx: &mut Context) { let editor = &mut cx.editor; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let cursor_pos = doc.selection(view.id).cursor(); let diag = if let Some(diag) = doc.diagnostics().first() { @@ -2022,7 +2005,7 @@ fn goto_first_diag(cx: &mut Context) { fn goto_last_diag(cx: &mut Context) { let editor = &mut cx.editor; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let cursor_pos = doc.selection(view.id).cursor(); let diag = if let Some(diag) = doc.diagnostics().last() { @@ -2036,7 +2019,7 @@ fn goto_last_diag(cx: &mut Context) { fn goto_next_diag(cx: &mut Context) { let editor = &mut cx.editor; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let cursor_pos = doc.selection(view.id).cursor(); let diag = if let Some(diag) = doc @@ -2057,7 +2040,7 @@ fn goto_next_diag(cx: &mut Context) { fn goto_prev_diag(cx: &mut Context) { let editor = &mut cx.editor; - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); let cursor_pos = doc.selection(view.id).cursor(); let diag = if let Some(diag) = doc @@ -2078,7 +2061,7 @@ fn goto_prev_diag(cx: &mut Context) { } fn signature_help(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -2124,7 +2107,7 @@ pub mod insert { fn completion(cx: &mut Context, ch: char) { // if ch matches completion char, trigger completion - let doc = cx.doc(); + let doc = doc_mut!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -2152,7 +2135,7 @@ pub mod insert { fn signature_help(cx: &mut Context, ch: char) { // if ch matches signature_help char, trigger - let doc = cx.doc(); + let doc = doc_mut!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, None => return, @@ -2207,7 +2190,7 @@ pub mod insert { const POST_HOOKS: &[PostHook] = &[completion, signature_help]; pub fn insert_char(cx: &mut Context, c: char) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text(); let selection = doc.selection(view.id); @@ -2229,7 +2212,7 @@ pub mod insert { } pub fn insert_tab(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); // TODO: round out to nearest indentation level (for example a line with 3 spaces should // indent by one to reach 4 spaces). @@ -2239,7 +2222,7 @@ pub mod insert { } pub fn insert_newline(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let contents = doc.text(); @@ -2308,7 +2291,7 @@ pub mod insert { // TODO: handle indent-aware delete pub fn delete_char_backward(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let transaction = Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| { @@ -2323,7 +2306,7 @@ pub mod insert { pub fn delete_char_forward(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let transaction = Transaction::change_by_selection(doc.text(), doc.selection(view.id), |range| { @@ -2338,7 +2321,7 @@ pub mod insert { pub fn delete_word_backward(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text().slice(..); let selection = doc .selection(view.id) @@ -2354,20 +2337,22 @@ pub mod insert { // storing it? fn undo(cx: &mut Context) { - let view_id = cx.view().id; - cx.doc().undo(view_id); + let (view, doc) = current!(cx.editor); + let view_id = view.id; + doc.undo(view_id); } fn redo(cx: &mut Context) { - let view_id = cx.view().id; - cx.doc().redo(view_id); + let (view, doc) = current!(cx.editor); + let view_id = view.id; + doc.redo(view_id); } // Yank / Paste fn yank(cx: &mut Context) { // TODO: should selections be made end inclusive? - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let values: Vec = doc .selection(view.id) .fragments(doc.text().slice(..)) @@ -2432,7 +2417,8 @@ fn paste_impl( fn replace_with_yanked(cx: &mut Context) { let reg_name = cx.selected_register.name(); - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; if let Some(values) = registers.read(reg_name) { if let Some(yank) = values.first() { @@ -2461,7 +2447,8 @@ fn replace_with_yanked(cx: &mut Context) { fn paste_after(cx: &mut Context) { let reg_name = cx.selected_register.name(); - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; if let Some(transaction) = registers .read(reg_name) @@ -2474,7 +2461,8 @@ fn paste_after(cx: &mut Context) { fn paste_before(cx: &mut Context) { let reg_name = cx.selected_register.name(); - let (view, doc, registers) = cx.current_with_registers(); + let (view, doc) = current!(cx.editor); + let registers = &mut cx.editor.registers; if let Some(transaction) = registers .read(reg_name) @@ -2504,7 +2492,7 @@ fn get_lines(doc: &Document, view_id: ViewId) -> Vec { fn indent(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let lines = get_lines(doc, view.id); // Indent by one level @@ -2523,7 +2511,7 @@ fn indent(cx: &mut Context) { fn unindent(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let lines = get_lines(doc, view.id); let mut changes = Vec::with_capacity(lines.len()); let tab_width = doc.tab_width(); @@ -2562,7 +2550,7 @@ fn unindent(cx: &mut Context) { } fn format_selections(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); // via lsp if available // else via tree-sitter indentation calculations @@ -2609,7 +2597,7 @@ fn format_selections(cx: &mut Context) { fn join_selections(cx: &mut Context) { use movement::skip_while; - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let text = doc.text(); let slice = doc.text().slice(..); @@ -2665,7 +2653,7 @@ fn keep_selections(cx: &mut Context) { } fn keep_primary_selection(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let range = doc.selection(view.id).primary(); let selection = Selection::single(range.anchor, range.head); @@ -2678,7 +2666,7 @@ fn save(cx: &mut Context) { // Spawns an async task to actually do the saving. This way we prevent blocking. // TODO: handle save errors somehow? - tokio::spawn(cx.doc().save()); + tokio::spawn(doc_mut!(cx.editor).save()); } fn completion(cx: &mut Context) { @@ -2718,7 +2706,7 @@ fn completion(cx: &mut Context) { // The prefix still has to satisfy `company-minimum-prefix-length' before that // happens. The value of nil means no idle completion." - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -2772,7 +2760,7 @@ fn completion(cx: &mut Context) { } fn hover(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let language_server = match doc.language_server() { Some(language_server) => language_server, @@ -2822,7 +2810,7 @@ fn hover(cx: &mut Context) { // comments fn toggle_comments(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id)); doc.apply(&transaction, view.id); @@ -2832,7 +2820,7 @@ fn toggle_comments(cx: &mut Context) { // tree sitter node selection fn expand_selection(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); if let Some(syntax) = doc.syntax() { let text = doc.text().slice(..); @@ -2842,7 +2830,7 @@ fn expand_selection(cx: &mut Context) { } fn match_brackets(cx: &mut Context) { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); if let Some(syntax) = doc.syntax() { let pos = doc.selection(view.id).cursor(); @@ -2857,12 +2845,12 @@ fn match_brackets(cx: &mut Context) { fn jump_forward(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); if let Some((id, selection)) = view.jumps.forward(count) { view.doc = *id; let selection = selection.clone(); - let (view, doc) = cx.current(); // refetch doc + let (view, doc) = current!(cx.editor); // refetch doc doc.set_selection(view.id, selection); align_view(doc, view, Align::Center); @@ -2871,7 +2859,7 @@ fn jump_forward(cx: &mut Context) { fn jump_backward(cx: &mut Context) { let count = cx.count(); - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); if let Some((id, selection)) = view.jumps.backward(view.id, doc, count) { // manually set the alternate_file as we cannot use the Editor::switch function here. @@ -2880,7 +2868,7 @@ fn jump_backward(cx: &mut Context) { } view.doc = *id; let selection = selection.clone(); - let (view, doc) = cx.current(); // refetch doc + let (view, doc) = current!(cx.editor); // refetch doc doc.set_selection(view.id, selection); align_view(doc, view, Align::Center); @@ -2915,7 +2903,7 @@ use helix_view::editor::Action; use self::cmd::TypableCommand; fn split(cx: &mut Context, action: Action) { use helix_view::editor::Action; - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let id = doc.id(); let selection = doc.selection(view.id).clone(); let first_line = view.first_line; @@ -2923,7 +2911,7 @@ fn split(cx: &mut Context, action: Action) { cx.editor.switch(id, action); // match the selection in the previous view - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); view.first_line = first_line; doc.set_selection(view.id, selection); } @@ -2937,7 +2925,7 @@ fn vsplit(cx: &mut Context) { } fn wclose(cx: &mut Context) { - let view_id = cx.view().id; + let view_id = view!(cx.editor).id; // close current split cx.editor.close(view_id, /* close_buffer */ false); } @@ -2992,7 +2980,7 @@ fn view_mode(cx: &mut Context) { | 't' // bottom | 'b' => { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); align_view(doc, view, match ch { 'z' | 'c' => Align::Center, @@ -3002,7 +2990,7 @@ fn view_mode(cx: &mut Context) { }); } 'm' => { - let (view, doc) = cx.current(); + let (view, doc) = current!(cx.editor); let pos = doc.selection(view.id).cursor(); let pos = coords_at_pos(doc.text().slice(..), pos); diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs index 60190372..dc8ec38e 100644 --- a/helix-term/src/lib.rs +++ b/helix-term/src/lib.rs @@ -1,5 +1,8 @@ #![allow(unused)] +#[macro_use] +extern crate helix_view; + pub mod application; pub mod args; pub mod commands; diff --git a/helix-term/src/ui/completion.rs b/helix-term/src/ui/completion.rs index 00ecce03..06ed966d 100644 --- a/helix-term/src/ui/completion.rs +++ b/helix-term/src/ui/completion.rs @@ -89,7 +89,7 @@ impl Completion { // doc.state = snapshot.clone(); } PromptEvent::Validate => { - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); // revert state to what it was before the last update // doc.state = snapshot.clone(); @@ -169,7 +169,7 @@ impl Completion { pub fn update(&mut self, cx: &mut commands::Context) { // recompute menu based on matches let menu = self.popup.contents_mut(); - let (view, doc) = cx.editor.current(); + let (view, doc) = current!(cx.editor); // cx.hooks() // cx.add_hook(enum type, ||) @@ -233,7 +233,7 @@ impl Component for Completion { // --- // option.documentation - let (view, doc) = cx.editor.current(); + let (view, doc) = current!(cx.editor); let language = doc .language() .and_then(|scope| scope.strip_prefix("source.")) diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 07107c9e..ba5e7574 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -615,7 +615,7 @@ impl Component for EditorView { // clear status cx.editor.status_msg = None; - let (view, doc) = cx.editor.current(); + let (view, doc) = current!(cx.editor); let mode = doc.mode(); let mut cxt = commands::Context { @@ -684,7 +684,7 @@ impl Component for EditorView { return EventResult::Ignored; } - let (view, doc) = cx.editor.current(); + let (view, doc) = current!(cx.editor); view.ensure_cursor_in_view(doc); // mode transitions diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs index 77e53690..b2274d06 100644 --- a/helix-term/src/ui/mod.rs +++ b/helix-term/src/ui/mod.rs @@ -30,8 +30,9 @@ pub fn regex_prompt( prompt: String, fun: impl Fn(&mut View, &mut Document, &mut Registers, Regex) + 'static, ) -> Prompt { - let view_id = cx.view().id; - let snapshot = cx.doc().selection(view_id).clone(); + let (view, doc) = current!(cx.editor); + let view_id = view.id; + let snapshot = doc.selection(view_id).clone(); Prompt::new( prompt, @@ -40,7 +41,7 @@ pub fn regex_prompt( match event { PromptEvent::Abort => { // TODO: also revert text - let (view, doc) = editor.current(); + let (view, doc) = current!(editor); doc.set_selection(view.id, snapshot.clone()); } PromptEvent::Validate => { @@ -54,7 +55,8 @@ pub fn regex_prompt( match Regex::new(input) { Ok(regex) => { - let (view, doc, registers) = editor.current_with_registers(); + let (view, doc) = current!(editor); + let registers = &mut editor.registers; // revert state to what it was before the last update // TODO: also revert text diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 24f43c0e..a1c93f75 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -101,19 +101,19 @@ impl Editor { match action { Action::Replace => { - let view = self.view(); + let view = view!(self); let jump = ( view.doc, self.documents[view.doc].selection(view.id).clone(), ); - let view = self.view_mut(); + let view = view_mut!(self); view.jumps.push(jump); view.last_accessed_doc = Some(view.doc); view.doc = id; view.first_line = 0; - let (view, doc) = self.current(); + let (view, doc) = current!(self); // initialize selection for view let selection = doc @@ -238,27 +238,6 @@ impl Editor { self.tree.is_empty() } - pub fn current(&mut self) -> (&mut View, &mut Document) { - let view = self.tree.get_mut(self.tree.focus); - let doc = &mut self.documents[view.doc]; - (view, doc) - } - - pub fn current_with_registers(&mut self) -> (&mut View, &mut Document, &mut Registers) { - let view = self.tree.get_mut(self.tree.focus); - let doc = &mut self.documents[view.doc]; - let registers = &mut self.registers; - (view, doc, registers) - } - - pub fn view(&self) -> &View { - self.tree.get(self.tree.focus) - } - - pub fn view_mut(&mut self) -> &mut View { - self.tree.get_mut(self.tree.focus) - } - pub fn ensure_cursor_in_view(&mut self, id: ViewId) { let view = self.tree.get_mut(id); let doc = &self.documents[view.doc]; @@ -280,7 +259,7 @@ impl Editor { pub fn cursor(&self) -> (Option, CursorKind) { const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter - let view = self.view(); + let view = view!(self); let doc = &self.documents[view.doc]; let cursor = doc.selection(view.id).cursor(); if let Some(mut pos) = view.screen_coords_at_pos(doc, doc.text().slice(..), cursor) { diff --git a/helix-view/src/lib.rs b/helix-view/src/lib.rs index 7e253320..20613451 100644 --- a/helix-view/src/lib.rs +++ b/helix-view/src/lib.rs @@ -1,3 +1,6 @@ +#[macro_use] +pub mod macros; + pub mod document; pub mod editor; pub mod register_selection; diff --git a/helix-view/src/macros.rs b/helix-view/src/macros.rs new file mode 100644 index 00000000..a06d37e7 --- /dev/null +++ b/helix-view/src/macros.rs @@ -0,0 +1,29 @@ +#[macro_export] +macro_rules! current { + ( $( $editor:ident ).+ ) => {{ + let view = $crate::view_mut!( $( $editor ).+ ); + let doc = &mut $( $editor ).+ .documents[view.doc]; + (view, doc) + }}; +} + +#[macro_export] +macro_rules! doc_mut { + ( $( $editor:ident ).+ ) => {{ + $crate::current!( $( $editor ).+ ).1 + }}; +} + +#[macro_export] +macro_rules! view_mut { + ( $( $editor:ident ).+ ) => {{ + $( $editor ).+ .tree.get_mut($( $editor ).+ .tree.focus) + }}; +} + +#[macro_export] +macro_rules! view { + ( $( $editor:ident ).+ ) => {{ + $( $editor ).+ .tree.get($( $editor ).+ .tree.focus) + }}; +} -- cgit v1.2.3-70-g09d2 From 42142cf680197a2076b9fa8ec864b91e67068082 Mon Sep 17 00:00:00 2001 From: Benoît CORTIER Date: Thu, 17 Jun 2021 18:24:15 -0400 Subject: Fix panic when entering unicode in command prompt It was attempted to use `String::insert` and `String::remove` to insert without taking care of unicodes. Fixes https://github.com/helix-editor/helix/issues/282 --- helix-term/src/ui/prompt.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'helix-term/src/ui') diff --git a/helix-term/src/ui/prompt.rs b/helix-term/src/ui/prompt.rs index 7b8af820..991b328d 100644 --- a/helix-term/src/ui/prompt.rs +++ b/helix-term/src/ui/prompt.rs @@ -53,7 +53,16 @@ impl Prompt { } pub fn insert_char(&mut self, c: char) { - self.line.insert(self.cursor, c); + let pos = if self.line.is_empty() { + 0 + } else { + self.line + .char_indices() + .nth(self.cursor) + .map(|(pos, _)| pos) + .unwrap_or_else(|| self.line.len()) + }; + self.line.insert(pos, c); self.cursor += 1; self.completion = (self.completion_fn)(&self.line); self.exit_selection(); @@ -79,7 +88,13 @@ impl Prompt { pub fn delete_char_backwards(&mut self) { if self.cursor > 0 { - self.line.remove(self.cursor - 1); + let pos = self + .line + .char_indices() + .nth(self.cursor - 1) + .map(|(pos, _)| pos) + .expect("line is not empty"); + self.line.remove(pos); self.cursor -= 1; self.completion = (self.completion_fn)(&self.line); } -- cgit v1.2.3-70-g09d2 From 41b07486ad935ad820dd4ba210457a03c95e1145 Mon Sep 17 00:00:00 2001 From: Wojciech Kępka Date: Fri, 18 Jun 2021 08:19:34 +0200 Subject: Fix expansion of `~` (#284) * Fix expansion of `~`, dont use directory relative to cwd. * Add `expand_tilde` * Bring back `canonicalize_path`, use `expand_tilde` to `normalize` * Make `:open ~` completion work * Fix clippy * Fold home dir into tilde in Document `realitve_path`--- helix-core/src/lib.rs | 2 ++ helix-term/src/commands.rs | 6 ++--- helix-term/src/ui/mod.rs | 18 +++++++++++--- helix-view/src/document.rs | 61 +++++++++++++++++++++++++++++++++++++++------- 4 files changed, 71 insertions(+), 16 deletions(-) (limited to 'helix-term/src/ui') diff --git a/helix-core/src/lib.rs b/helix-core/src/lib.rs index b11faeab..03741719 100644 --- a/helix-core/src/lib.rs +++ b/helix-core/src/lib.rs @@ -89,6 +89,8 @@ pub fn cache_dir() -> std::path::PathBuf { path } +pub use etcetera::home_dir; + use etcetera::base_strategy::{choose_base_strategy, BaseStrategy}; pub use ropey::{Rope, RopeSlice}; diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index dc4805a5..b2dd0d11 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -1188,8 +1188,8 @@ mod cmd { .filter(|doc| doc.is_modified()) .map(|doc| { doc.relative_path() - .and_then(|path| path.to_str()) - .unwrap_or("[scratch]") + .map(|path| path.to_string_lossy().to_string()) + .unwrap_or_else(|| "[scratch]".into()) }) .collect(); if !modified.is_empty() { @@ -1487,7 +1487,7 @@ fn buffer_picker(cx: &mut Context) { cx.editor .documents .iter() - .map(|(id, doc)| (id, doc.relative_path().map(Path::to_path_buf))) + .map(|(id, doc)| (id, doc.relative_path())) .collect(), move |(id, path): &(DocumentId, Option)| { // format_fn diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs index b2274d06..39e11cd6 100644 --- a/helix-term/src/ui/mod.rs +++ b/helix-term/src/ui/mod.rs @@ -126,10 +126,11 @@ pub mod completers { use ignore::WalkBuilder; use std::path::{Path, PathBuf}; - let path = Path::new(input); + let is_tilde = input.starts_with('~') && input.len() == 1; + let path = helix_view::document::expand_tilde(Path::new(input)); let (dir, file_name) = if input.ends_with('/') { - (path.into(), None) + (path, None) } else { let file_name = path .file_name() @@ -154,7 +155,16 @@ pub mod completers { let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir()); let path = entry.path(); - let mut path = path.strip_prefix(&dir).unwrap_or(path).to_path_buf(); + let mut path = if is_tilde { + // if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on + // one of the directories the tilde will be replaced with a valid path not with a relative + // home directory name. + // ~ -> -> /home/user + // ~/ -> -> ~/first_entry + path.to_path_buf() + } else { + path.strip_prefix(&dir).unwrap_or(path).to_path_buf() + }; if is_dir { path.push(""); @@ -184,7 +194,7 @@ pub mod completers { }) .collect(); - let range = ((input.len() - file_name.len())..); + let range = ((input.len().saturating_sub(file_name.len()))..); matches.sort_unstable_by_key(|(_file, score)| Reverse(*score)); files = matches diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 254e01b0..fe9c87f7 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -127,6 +127,36 @@ where } } +/// Expands tilde `~` into users home directory if avilable, otherwise returns the path +/// unchanged. The tilde will only be expanded when present as the first component of the path +/// and only slash follows it. +pub fn expand_tilde(path: &Path) -> PathBuf { + let mut components = path.components().peekable(); + if let Some(Component::Normal(c)) = components.peek() { + if c == &"~" { + if let Ok(home) = helix_core::home_dir() { + // it's ok to unwrap, the path starts with `~` + return home.join(path.strip_prefix("~").unwrap()); + } + } + } + + path.to_path_buf() +} + +/// Replaces users home directory from `path` with tilde `~` if the directory +/// is available, otherwise returns the path unchanged. +pub fn fold_home_dir(path: &Path) -> PathBuf { + if let Ok(home) = helix_core::home_dir() { + if path.starts_with(&home) { + // it's ok to unwrap, the path starts with home dir + return PathBuf::from("~").join(path.strip_prefix(&home).unwrap()); + } + } + + path.to_path_buf() +} + /// Normalize a path, removing things like `.` and `..`. /// /// CAUTION: This does not resolve symlinks (unlike @@ -137,6 +167,7 @@ where /// needs to improve on. /// Copied from cargo: https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81 pub fn normalize_path(path: &Path) -> PathBuf { + let path = expand_tilde(path); let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { components.next(); @@ -163,12 +194,17 @@ pub fn normalize_path(path: &Path) -> PathBuf { ret } -// Returns the canonical, absolute form of a path with all intermediate components normalized. -// -// This function is used instead of `std::fs::canonicalize` because we don't want to verify -// here if the path exists, just normalize it's components. +/// Returns the canonical, absolute form of a path with all intermediate components normalized. +/// +/// This function is used instead of `std::fs::canonicalize` because we don't want to verify +/// here if the path exists, just normalize it's components. pub fn canonicalize_path(path: &Path) -> std::io::Result { - std::env::current_dir().map(|current_dir| normalize_path(¤t_dir.join(path))) + let normalized = normalize_path(path); + if normalized.is_absolute() { + Ok(normalized) + } else { + std::env::current_dir().map(|current_dir| current_dir.join(normalized)) + } } use helix_lsp::lsp; @@ -709,12 +745,19 @@ impl Document { &self.selections[&view_id] } - pub fn relative_path(&self) -> Option<&Path> { + pub fn relative_path(&self) -> Option { let cwdir = std::env::current_dir().expect("couldn't determine current directory"); - self.path - .as_ref() - .map(|path| path.strip_prefix(cwdir).unwrap_or(path)) + self.path.as_ref().map(|path| { + let path = fold_home_dir(path); + if path.is_relative() { + path + } else { + path.strip_prefix(cwdir) + .map(|p| p.to_path_buf()) + .unwrap_or(path) + } + }) } // pub fn slice(&self, range: R) -> RopeSlice where R: RangeBounds { -- cgit v1.2.3-70-g09d2 From 1c1474c3b8dbab8ca4b9a62220c079ddffb7ed9f Mon Sep 17 00:00:00 2001 From: wojciechkepka Date: Fri, 18 Jun 2021 20:22:15 +0200 Subject: Add `ui.statusline.inactive`, use `ui.statusline` for statusline text --- contrib/themes/bogster.toml | 5 +++-- contrib/themes/ingrid.toml | 3 ++- contrib/themes/onedark.toml | 1 + helix-term/src/ui/editor.rs | 17 +++++++---------- theme.toml | 3 ++- 5 files changed, 15 insertions(+), 14 deletions(-) (limited to 'helix-term/src/ui') diff --git a/contrib/themes/bogster.toml b/contrib/themes/bogster.toml index 205e464c..43b422f3 100644 --- a/contrib/themes/bogster.toml +++ b/contrib/themes/bogster.toml @@ -31,7 +31,8 @@ "ui.background" = { bg = "#161c23" } "ui.linenr" = { fg = "#415367" } "ui.linenr.selected" = { fg = "#e5ded6" } # TODO -"ui.statusline" = { bg = "#232d38" } +"ui.statusline" = { fg = "#e5ded6", bg = "#232d38" } +"ui.statusline.inactive" = { fg = "#c6b8ad", bg = "#232d38" } "ui.popup" = { bg = "#232d38" } "ui.window" = { bg = "#232d38" } "ui.help" = { bg = "#232d38", fg = "#e5ded6" } @@ -39,7 +40,7 @@ "ui.text" = { fg = "#e5ded6" } "ui.text.focus" = { fg = "#e5ded6", modifiers= ["bold"] } -"ui.selection" = { bg = "#540099" } +"ui.selection" = { bg = "#313f4e" } "ui.menu.selected" = { fg = "#e5ded6", bg = "#313f4e" } "warning" = "#dc7759" diff --git a/contrib/themes/ingrid.toml b/contrib/themes/ingrid.toml index da333fb8..d32a89d1 100644 --- a/contrib/themes/ingrid.toml +++ b/contrib/themes/ingrid.toml @@ -31,7 +31,8 @@ "ui.background" = { bg = "#FFFCFD" } "ui.linenr" = { fg = "#bbbbbb" } "ui.linenr.selected" = { fg = "#F3EAE9" } # TODO -"ui.statusline" = { bg = "#F3EAE9" } +"ui.statusline" = { fg = "#250E07", bg = "#F3EAE9" } +"ui.statusline.inactive" = { fg = "#7b91b3", bg = "#F3EAE9" } "ui.popup" = { bg = "#F3EAE9" } "ui.window" = { bg = "#D8B8B3" } "ui.help" = { bg = "#D8B8B3", fg = "#250E07" } diff --git a/contrib/themes/onedark.toml b/contrib/themes/onedark.toml index 4c13a217..65f26725 100644 --- a/contrib/themes/onedark.toml +++ b/contrib/themes/onedark.toml @@ -36,6 +36,7 @@ "ui.linenr.selected" = { fg = "#ABB2BF" } "ui.popup" = { bg = "#3E4452" } "ui.statusline" = { fg = "#ABB2BF", bg = "#2C323C" } +"ui.statusline.inactive" = { fg = "#ABB2Bf", bg = "#2C323C" } "ui.selection" = { bg = "#3E4452" } "ui.text" = { fg = "#ABB2BF", bg = "#282C34" } "ui.text.focus" = { fg = "#ABB2BF", bg = "#2C323C", modifiers = ['bold'] } diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index ba5e7574..3dc43d3f 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -476,18 +476,15 @@ impl EditorView { Mode::Select => "SEL", Mode::Normal => "NOR", }; - let text_color = if is_focused { - theme.get("ui.text.focus") + let style = if is_focused { + theme.get("ui.statusline") } else { - theme.get("ui.text") + theme.get("ui.statusline.inactive") }; // statusline - surface.set_style( - Rect::new(viewport.x, viewport.y, viewport.width, 1), - theme.get("ui.statusline"), - ); + surface.set_style(Rect::new(viewport.x, viewport.y, viewport.width, 1), style); if is_focused { - surface.set_string(viewport.x + 1, viewport.y, mode, text_color); + surface.set_string(viewport.x + 1, viewport.y, mode, style); } if let Some(path) = doc.relative_path() { @@ -499,7 +496,7 @@ impl EditorView { viewport.y, title, viewport.width.saturating_sub(6) as usize, - text_color, + style, ); } @@ -538,7 +535,7 @@ impl EditorView { viewport.x + viewport.width.saturating_sub(text_len), viewport.y, right_side_text, - text_color, + style, ); } diff --git a/theme.toml b/theme.toml index 903a5e26..a4f40267 100644 --- a/theme.toml +++ b/theme.toml @@ -41,7 +41,8 @@ "ui.background" = { bg = "#3b224c" } # midnight "ui.linenr" = { fg = "#5a5977" } # comet "ui.linenr.selected" = { fg = "#dbbfef" } # lilac -"ui.statusline" = { bg = "#281733" } # revolver +"ui.statusline" = { fg = "#dbbfef", bg = "#281733" } # revolver +"ui.statusline.inactive" = { fg = "#a4a0e8", bg = "#281733" } # revolver "ui.popup" = { bg = "#281733" } # revolver "ui.window" = { bg = "#452859" } # bossa nova "ui.window" = { bg = "#452859" } # bossa nova -- cgit v1.2.3-70-g09d2 From ca806d4f852e934651132fc9570a6110e30f646d Mon Sep 17 00:00:00 2001 From: Ivan Tham Date: Fri, 18 Jun 2021 00:52:41 +0800 Subject: Refactor key into helix-view Now also make use of Deserialize for Config. --- helix-term/src/application.rs | 4 +- helix-term/src/commands.rs | 71 +++++---- helix-term/src/config.rs | 76 ++++++---- helix-term/src/keymap.rs | 336 +++--------------------------------------- helix-term/src/main.rs | 14 +- helix-term/src/ui/editor.rs | 6 +- helix-view/src/document.rs | 61 ++++---- helix-view/src/input.rs | 226 ++++++++++++++++++++++++++++ helix-view/src/lib.rs | 8 +- 9 files changed, 388 insertions(+), 414 deletions(-) create mode 100644 helix-view/src/input.rs (limited to 'helix-term/src/ui') diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index 2fae467f..ce43808a 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -1,7 +1,7 @@ use helix_lsp::{lsp, LspProgressMap}; use helix_view::{document::Mode, Document, Editor, Theme, View}; -use crate::{args::Args, compositor::Compositor, config::Config, keymap::Keymaps, ui}; +use crate::{args::Args, compositor::Compositor, config::Config, ui}; use log::{error, info}; @@ -49,7 +49,7 @@ impl Application { let size = compositor.size(); let mut editor = Editor::new(size); - let mut editor_view = Box::new(ui::EditorView::new(config.keymaps)); + let mut editor_view = Box::new(ui::EditorView::new(config.keys)); compositor.push(editor_view); if !args.files.is_empty() { diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index a8610223..1243a86f 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -11,6 +11,7 @@ use helix_core::{ use helix_view::{ document::{IndentStyle, Mode}, + input::{KeyCode, KeyEvent}, view::{View, PADDING}, Document, DocumentId, Editor, ViewId, }; @@ -38,8 +39,8 @@ use std::{ path::{Path, PathBuf}, }; -use crossterm::event::{KeyCode, KeyEvent}; use once_cell::sync::Lazy; +use serde::de::{self, Deserialize, Deserializer}; pub struct Context<'a> { pub selected_register: helix_view::RegisterSelection, @@ -252,6 +253,48 @@ impl Command { ); } +impl fmt::Debug for Command { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Command(name, _) = self; + f.debug_tuple("Command").field(name).finish() + } +} + +impl fmt::Display for Command { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Command(name, _) = self; + f.write_str(name) + } +} + +impl std::str::FromStr for Command { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + Command::COMMAND_LIST + .iter() + .copied() + .find(|cmd| cmd.0 == s) + .ok_or_else(|| anyhow!("No command named '{}'", s)) + } +} + +impl<'de> Deserialize<'de> for Command { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + s.parse().map_err(de::Error::custom) + } +} + +impl PartialEq for Command { + fn eq(&self, other: &Self) -> bool { + self.name() == other.name() + } +} + fn move_char_left(cx: &mut Context) { let count = cx.count(); let (view, doc) = current!(cx.editor); @@ -3042,29 +3085,3 @@ fn right_bracket_mode(cx: &mut Context) { } }) } - -impl fmt::Display for Command { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let Command(name, _) = self; - f.write_str(name) - } -} - -impl std::str::FromStr for Command { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - Command::COMMAND_LIST - .iter() - .copied() - .find(|cmd| cmd.0 == s) - .ok_or_else(|| anyhow!("No command named '{}'", s)) - } -} - -impl fmt::Debug for Command { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let Command(name, _) = self; - f.debug_tuple("Command").field(name).finish() - } -} diff --git a/helix-term/src/config.rs b/helix-term/src/config.rs index e5e17753..9c962299 100644 --- a/helix-term/src/config.rs +++ b/helix-term/src/config.rs @@ -1,10 +1,9 @@ -use anyhow::{Error, Result}; -use std::{collections::HashMap, str::FromStr}; +use serde::Deserialize; -use serde::{de::Error as SerdeError, Deserialize, Serialize}; - -use crate::keymap::{parse_keymaps, Keymaps}; +use crate::commands::Command; +use crate::keymap::Keymaps; +#[derive(Debug, PartialEq, Deserialize)] pub struct GlobalConfig { pub lsp_progress: bool, } @@ -15,35 +14,50 @@ impl Default for GlobalConfig { } } -#[derive(Default)] +#[derive(Debug, Default, PartialEq, Deserialize)] +#[serde(default)] pub struct Config { pub global: GlobalConfig, - pub keymaps: Keymaps, + pub keys: Keymaps, } -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -struct TomlConfig { - lsp_progress: Option, - keys: Option>>, -} +#[test] +fn parsing_keymaps_config_file() { + use helix_core::hashmap; + use helix_view::document::Mode; + use helix_view::input::{KeyCode, KeyEvent, KeyModifiers}; -impl<'de> Deserialize<'de> for Config { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let config = TomlConfig::deserialize(deserializer)?; - Ok(Self { - global: GlobalConfig { - lsp_progress: config.lsp_progress.unwrap_or(true), - }, - keymaps: config - .keys - .map(|r| parse_keymaps(&r)) - .transpose() - .map_err(|e| D::Error::custom(format!("Error deserializing keymap: {}", e)))? - .unwrap_or_else(Keymaps::default), - }) - } + let sample_keymaps = r#" + [keys.insert] + y = "move_line_down" + S-C-a = "delete_selection" + + [keys.normal] + A-F12 = "move_next_word_end" + "#; + + assert_eq!( + toml::from_str::(sample_keymaps).unwrap(), + Config { + global: Default::default(), + keys: Keymaps(hashmap! { + Mode::Insert => hashmap! { + KeyEvent { + code: KeyCode::Char('y'), + modifiers: KeyModifiers::NONE, + } => Command::move_line_down, + KeyEvent { + code: KeyCode::Char('a'), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL, + } => Command::delete_selection, + }, + Mode::Normal => hashmap! { + KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::ALT, + } => Command::move_next_word_end, + }, + }) + } + ); } diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index f6bcbcc9..24924832 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -3,6 +3,8 @@ pub use crate::commands::Command; use anyhow::{anyhow, Error, Result}; use helix_core::hashmap; use helix_view::document::Mode; +use helix_view::input::{KeyCode, KeyEvent, KeyModifiers}; +use serde::Deserialize; use std::{ collections::HashMap, fmt::Display, @@ -99,14 +101,6 @@ use std::{ // D] = last diagnostic // } -// #[cfg(feature = "term")] -pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; - -#[derive(Clone, Debug)] -pub struct Keymap(pub HashMap); -#[derive(Clone, Debug)] -pub struct Keymaps(pub HashMap); - #[macro_export] macro_rules! key { ($key:ident) => { @@ -141,9 +135,21 @@ macro_rules! alt { }; } +#[derive(Debug, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct Keymaps(pub HashMap>); + +impl Deref for Keymaps { + type Target = HashMap>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + impl Default for Keymaps { - fn default() -> Self { - let normal = Keymap(hashmap!( + fn default() -> Keymaps { + let normal = hashmap!( key!('h') => Command::move_char_left, key!('j') => Command::move_line_down, key!('k') => Command::move_line_up, @@ -277,12 +283,12 @@ impl Default for Keymaps { key!('z') => Command::view_mode, key!('"') => Command::select_register, - )); + ); // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether // we keep this separate select mode. More keys can fit into normal mode then, but it's weird // because some selection operations can now be done from normal mode, some from select mode. let mut select = normal.clone(); - select.0.extend( + select.extend( hashmap!( key!('h') => Command::extend_char_left, key!('j') => Command::extend_line_down, @@ -315,7 +321,7 @@ impl Default for Keymaps { // TODO: select could be normal mode with some bindings merged over Mode::Normal => normal, Mode::Select => select, - Mode::Insert => Keymap(hashmap!( + Mode::Insert => hashmap!( key!(Esc) => Command::normal_mode as Command, key!(Backspace) => Command::delete_char_backward, key!(Delete) => Command::delete_char_forward, @@ -329,309 +335,7 @@ impl Default for Keymaps { key!(PageDown) => Command::page_down, ctrl!('x') => Command::completion, ctrl!('w') => Command::delete_word_backward, - )), + ), )) } } - -// Newtype wrapper over keys to allow toml serialization/parsing -#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Hash)] -pub struct RepresentableKeyEvent(pub KeyEvent); -impl Display for RepresentableKeyEvent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let Self(key) = self; - f.write_fmt(format_args!( - "{}{}{}", - if key.modifiers.contains(KeyModifiers::SHIFT) { - "S-" - } else { - "" - }, - if key.modifiers.contains(KeyModifiers::ALT) { - "A-" - } else { - "" - }, - if key.modifiers.contains(KeyModifiers::CONTROL) { - "C-" - } else { - "" - }, - ))?; - match key.code { - KeyCode::Backspace => f.write_str("backspace")?, - KeyCode::Enter => f.write_str("ret")?, - KeyCode::Left => f.write_str("left")?, - KeyCode::Right => f.write_str("right")?, - KeyCode::Up => f.write_str("up")?, - KeyCode::Down => f.write_str("down")?, - KeyCode::Home => f.write_str("home")?, - KeyCode::End => f.write_str("end")?, - KeyCode::PageUp => f.write_str("pageup")?, - KeyCode::PageDown => f.write_str("pagedown")?, - KeyCode::Tab => f.write_str("tab")?, - KeyCode::BackTab => f.write_str("backtab")?, - KeyCode::Delete => f.write_str("del")?, - KeyCode::Insert => f.write_str("ins")?, - KeyCode::Null => f.write_str("null")?, - KeyCode::Esc => f.write_str("esc")?, - KeyCode::Char('<') => f.write_str("lt")?, - KeyCode::Char('>') => f.write_str("gt")?, - KeyCode::Char('+') => f.write_str("plus")?, - KeyCode::Char('-') => f.write_str("minus")?, - KeyCode::Char(';') => f.write_str("semicolon")?, - KeyCode::Char('%') => f.write_str("percent")?, - KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?, - KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?, - }; - Ok(()) - } -} - -impl FromStr for RepresentableKeyEvent { - type Err = Error; - - fn from_str(s: &str) -> Result { - let mut tokens: Vec<_> = s.split('-').collect(); - let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? { - "backspace" => KeyCode::Backspace, - "space" => KeyCode::Char(' '), - "ret" => KeyCode::Enter, - "lt" => KeyCode::Char('<'), - "gt" => KeyCode::Char('>'), - "plus" => KeyCode::Char('+'), - "minus" => KeyCode::Char('-'), - "semicolon" => KeyCode::Char(';'), - "percent" => KeyCode::Char('%'), - "left" => KeyCode::Left, - "right" => KeyCode::Right, - "up" => KeyCode::Down, - "home" => KeyCode::Home, - "end" => KeyCode::End, - "pageup" => KeyCode::PageUp, - "pagedown" => KeyCode::PageDown, - "tab" => KeyCode::Tab, - "backtab" => KeyCode::BackTab, - "del" => KeyCode::Delete, - "ins" => KeyCode::Insert, - "null" => KeyCode::Null, - "esc" => KeyCode::Esc, - single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()), - function if function.len() > 1 && function.starts_with('F') => { - let function: String = function.chars().skip(1).collect(); - let function = str::parse::(&function)?; - (function > 0 && function < 13) - .then(|| KeyCode::F(function)) - .ok_or_else(|| anyhow!("Invalid function key '{}'", function))? - } - invalid => return Err(anyhow!("Invalid key code '{}'", invalid)), - }; - - let mut modifiers = KeyModifiers::empty(); - for token in tokens { - let flag = match token { - "S" => KeyModifiers::SHIFT, - "A" => KeyModifiers::ALT, - "C" => KeyModifiers::CONTROL, - _ => return Err(anyhow!("Invalid key modifier '{}-'", token)), - }; - - if modifiers.contains(flag) { - return Err(anyhow!("Repeated key modifier '{}-'", token)); - } - modifiers.insert(flag); - } - - Ok(RepresentableKeyEvent(KeyEvent { code, modifiers })) - } -} - -pub fn parse_keymaps(toml_keymaps: &HashMap>) -> Result { - let mut keymaps = Keymaps::default(); - - for (mode, map) in toml_keymaps { - let mode = Mode::from_str(&mode)?; - for (key, command) in map { - let key = str::parse::(&key)?; - let command = str::parse::(&command)?; - keymaps.0.get_mut(&mode).unwrap().0.insert(key.0, command); - } - } - Ok(keymaps) -} - -impl Deref for Keymap { - type Target = HashMap; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Deref for Keymaps { - type Target = HashMap; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for Keymap { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -impl DerefMut for Keymaps { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -#[cfg(test)] -mod test { - use crate::config::Config; - - use super::*; - - impl PartialEq for Command { - fn eq(&self, other: &Self) -> bool { - self.name() == other.name() - } - } - - #[test] - fn parsing_keymaps_config_file() { - let sample_keymaps = r#" - [keys.insert] - y = "move_line_down" - S-C-a = "delete_selection" - - [keys.normal] - A-F12 = "move_next_word_end" - "#; - - let config: Config = toml::from_str(sample_keymaps).unwrap(); - assert_eq!( - *config - .keymaps - .0 - .get(&Mode::Insert) - .unwrap() - .0 - .get(&KeyEvent { - code: KeyCode::Char('y'), - modifiers: KeyModifiers::NONE - }) - .unwrap(), - Command::move_line_down - ); - assert_eq!( - *config - .keymaps - .0 - .get(&Mode::Insert) - .unwrap() - .0 - .get(&KeyEvent { - code: KeyCode::Char('a'), - modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL - }) - .unwrap(), - Command::delete_selection - ); - assert_eq!( - *config - .keymaps - .0 - .get(&Mode::Normal) - .unwrap() - .0 - .get(&KeyEvent { - code: KeyCode::F(12), - modifiers: KeyModifiers::ALT - }) - .unwrap(), - Command::move_next_word_end - ); - } - - #[test] - fn parsing_unmodified_keys() { - assert_eq!( - str::parse::("backspace").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::Backspace, - modifiers: KeyModifiers::NONE - }) - ); - - assert_eq!( - str::parse::("left").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::Left, - modifiers: KeyModifiers::NONE - }) - ); - - assert_eq!( - str::parse::(",").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::Char(','), - modifiers: KeyModifiers::NONE - }) - ); - - assert_eq!( - str::parse::("w").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::Char('w'), - modifiers: KeyModifiers::NONE - }) - ); - - assert_eq!( - str::parse::("F12").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::F(12), - modifiers: KeyModifiers::NONE - }) - ); - } - - fn parsing_modified_keys() { - assert_eq!( - str::parse::("S-minus").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::Char('-'), - modifiers: KeyModifiers::SHIFT - }) - ); - - assert_eq!( - str::parse::("C-A-S-F12").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::F(12), - modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT - }) - ); - - assert_eq!( - str::parse::("S-C-2").unwrap(), - RepresentableKeyEvent(KeyEvent { - code: KeyCode::F(2), - modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL - }) - ); - } - - #[test] - fn parsing_nonsensical_keys_fails() { - assert!(str::parse::("F13").is_err()); - assert!(str::parse::("F0").is_err()); - assert!(str::parse::("aaa").is_err()); - assert!(str::parse::("S-S-a").is_err()); - assert!(str::parse::("C-A-S-C-1").is_err()); - assert!(str::parse::("FU").is_err()); - assert!(str::parse::("123").is_err()); - assert!(str::parse::("S--").is_err()); - } -} diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index ef912480..12176910 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -1,10 +1,9 @@ +use anyhow::{Context, Error, Result}; use helix_term::application::Application; use helix_term::args::Args; use helix_term::config::Config; use std::path::PathBuf; -use anyhow::{Context, Result}; - fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> { let mut base_config = fern::Dispatch::new(); @@ -89,12 +88,11 @@ FLAGS: std::fs::create_dir_all(&conf_dir).ok(); } - let config = std::fs::read_to_string(conf_dir.join("config.toml")) - .ok() - .map(|s| toml::from_str(&s)) - .transpose()? - .or_else(|| Some(Config::default())) - .unwrap(); + let config = match std::fs::read_to_string(conf_dir.join("config.toml")) { + Ok(config) => toml::from_str(&config)?, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(), + Err(err) => return Err(Error::new(err)), + }; setup_logging(logpath, args.verbosity).context("failed to initialize logging")?; diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 3dc43d3f..d0eedad6 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -11,12 +11,13 @@ use helix_core::{ syntax::{self, HighlightEvent}, Position, Range, }; +use helix_view::input::{KeyCode, KeyEvent, KeyModifiers}; use helix_view::{document::Mode, Document, Editor, Theme, View}; use std::borrow::Cow; use crossterm::{ cursor, - event::{read, Event, EventStream, KeyCode, KeyEvent, KeyModifiers}, + event::{read, Event, EventStream}, }; use tui::{ backend::CrosstermBackend, @@ -607,7 +608,8 @@ impl Component for EditorView { cx.editor.resize(Rect::new(0, 0, width, height - 1)); EventResult::Consumed(None) } - Event::Key(mut key) => { + Event::Key(key) => { + let mut key = KeyEvent::from(key); canonicalize_key(&mut key); // clear status cx.editor.status_msg = None; diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index e9a8097c..8875f70d 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -1,5 +1,7 @@ use anyhow::{anyhow, Context, Error}; +use serde::de::{self, Deserialize, Deserializer}; use std::cell::Cell; +use std::collections::HashMap; use std::fmt::Display; use std::future::Future; use std::path::{Component, Path, PathBuf}; @@ -15,8 +17,6 @@ use helix_core::{ use crate::{DocumentId, ViewId}; -use std::collections::HashMap; - #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Mode { Normal, @@ -24,6 +24,40 @@ pub enum Mode { Insert, } +impl Display for Mode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Mode::Normal => f.write_str("normal"), + Mode::Select => f.write_str("select"), + Mode::Insert => f.write_str("insert"), + } + } +} + +impl FromStr for Mode { + type Err = Error; + + fn from_str(s: &str) -> Result { + match s { + "normal" => Ok(Mode::Normal), + "select" => Ok(Mode::Select), + "insert" => Ok(Mode::Insert), + _ => Err(anyhow!("Invalid mode '{}'", s)), + } + } +} + +// toml deserializer doesn't seem to recognize string as enum +impl<'de> Deserialize<'de> for Mode { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + s.parse().map_err(de::Error::custom) + } +} + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum IndentStyle { Tabs, @@ -88,29 +122,6 @@ impl fmt::Debug for Document { } } -impl Display for Mode { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Mode::Normal => f.write_str("normal"), - Mode::Select => f.write_str("select"), - Mode::Insert => f.write_str("insert"), - } - } -} - -impl FromStr for Mode { - type Err = Error; - - fn from_str(s: &str) -> Result { - match s { - "normal" => Ok(Mode::Normal), - "select" => Ok(Mode::Select), - "insert" => Ok(Mode::Insert), - _ => Err(anyhow!("Invalid mode '{}'", s)), - } - } -} - /// Like std::mem::replace() except it allows the replacement value to be mapped from the /// original value. fn take_with(mut_ref: &mut T, closure: F) diff --git a/helix-view/src/input.rs b/helix-view/src/input.rs new file mode 100644 index 00000000..ab417819 --- /dev/null +++ b/helix-view/src/input.rs @@ -0,0 +1,226 @@ +//! Input event handling, currently backed by crossterm. +use anyhow::{anyhow, Error}; +use crossterm::event; +use serde::de::{self, Deserialize, Deserializer}; +use std::fmt; + +pub use crossterm::event::{KeyCode, KeyModifiers}; + +/// Represents a key event. +// We use a newtype here because we want to customize Deserialize and Display. +#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)] +pub struct KeyEvent { + pub code: KeyCode, + pub modifiers: KeyModifiers, +} + +impl fmt::Display for KeyEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!( + "{}{}{}", + if self.modifiers.contains(KeyModifiers::SHIFT) { + "S-" + } else { + "" + }, + if self.modifiers.contains(KeyModifiers::ALT) { + "A-" + } else { + "" + }, + if self.modifiers.contains(KeyModifiers::CONTROL) { + "C-" + } else { + "" + }, + ))?; + match self.code { + KeyCode::Backspace => f.write_str("backspace")?, + KeyCode::Enter => f.write_str("ret")?, + KeyCode::Left => f.write_str("left")?, + KeyCode::Right => f.write_str("right")?, + KeyCode::Up => f.write_str("up")?, + KeyCode::Down => f.write_str("down")?, + KeyCode::Home => f.write_str("home")?, + KeyCode::End => f.write_str("end")?, + KeyCode::PageUp => f.write_str("pageup")?, + KeyCode::PageDown => f.write_str("pagedown")?, + KeyCode::Tab => f.write_str("tab")?, + KeyCode::BackTab => f.write_str("backtab")?, + KeyCode::Delete => f.write_str("del")?, + KeyCode::Insert => f.write_str("ins")?, + KeyCode::Null => f.write_str("null")?, + KeyCode::Esc => f.write_str("esc")?, + KeyCode::Char('<') => f.write_str("lt")?, + KeyCode::Char('>') => f.write_str("gt")?, + KeyCode::Char('+') => f.write_str("plus")?, + KeyCode::Char('-') => f.write_str("minus")?, + KeyCode::Char(';') => f.write_str("semicolon")?, + KeyCode::Char('%') => f.write_str("percent")?, + KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?, + KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?, + }; + Ok(()) + } +} + +impl std::str::FromStr for KeyEvent { + type Err = Error; + + fn from_str(s: &str) -> Result { + let mut tokens: Vec<_> = s.split('-').collect(); + let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? { + "backspace" => KeyCode::Backspace, + "space" => KeyCode::Char(' '), + "ret" => KeyCode::Enter, + "lt" => KeyCode::Char('<'), + "gt" => KeyCode::Char('>'), + "plus" => KeyCode::Char('+'), + "minus" => KeyCode::Char('-'), + "semicolon" => KeyCode::Char(';'), + "percent" => KeyCode::Char('%'), + "left" => KeyCode::Left, + "right" => KeyCode::Right, + "up" => KeyCode::Down, + "home" => KeyCode::Home, + "end" => KeyCode::End, + "pageup" => KeyCode::PageUp, + "pagedown" => KeyCode::PageDown, + "tab" => KeyCode::Tab, + "backtab" => KeyCode::BackTab, + "del" => KeyCode::Delete, + "ins" => KeyCode::Insert, + "null" => KeyCode::Null, + "esc" => KeyCode::Esc, + single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()), + function if function.len() > 1 && function.starts_with('F') => { + let function: String = function.chars().skip(1).collect(); + let function = str::parse::(&function)?; + (function > 0 && function < 13) + .then(|| KeyCode::F(function)) + .ok_or_else(|| anyhow!("Invalid function key '{}'", function))? + } + invalid => return Err(anyhow!("Invalid key code '{}'", invalid)), + }; + + let mut modifiers = KeyModifiers::empty(); + for token in tokens { + let flag = match token { + "S" => KeyModifiers::SHIFT, + "A" => KeyModifiers::ALT, + "C" => KeyModifiers::CONTROL, + _ => return Err(anyhow!("Invalid key modifier '{}-'", token)), + }; + + if modifiers.contains(flag) { + return Err(anyhow!("Repeated key modifier '{}-'", token)); + } + modifiers.insert(flag); + } + + Ok(KeyEvent { code, modifiers }) + } +} + +impl<'de> Deserialize<'de> for KeyEvent { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + s.parse().map_err(de::Error::custom) + } +} + +impl From for KeyEvent { + fn from(event::KeyEvent { code, modifiers }: event::KeyEvent) -> KeyEvent { + KeyEvent { code, modifiers } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn parsing_unmodified_keys() { + assert_eq!( + str::parse::("backspace").unwrap(), + KeyEvent { + code: KeyCode::Backspace, + modifiers: KeyModifiers::NONE + } + ); + + assert_eq!( + str::parse::("left").unwrap(), + KeyEvent { + code: KeyCode::Left, + modifiers: KeyModifiers::NONE + } + ); + + assert_eq!( + str::parse::(",").unwrap(), + KeyEvent { + code: KeyCode::Char(','), + modifiers: KeyModifiers::NONE + } + ); + + assert_eq!( + str::parse::("w").unwrap(), + KeyEvent { + code: KeyCode::Char('w'), + modifiers: KeyModifiers::NONE + } + ); + + assert_eq!( + str::parse::("F12").unwrap(), + KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::NONE + } + ); + } + + #[test] + fn parsing_modified_keys() { + assert_eq!( + str::parse::("S-minus").unwrap(), + KeyEvent { + code: KeyCode::Char('-'), + modifiers: KeyModifiers::SHIFT + } + ); + + assert_eq!( + str::parse::("C-A-S-F12").unwrap(), + KeyEvent { + code: KeyCode::F(12), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT + } + ); + + assert_eq!( + str::parse::("S-C-2").unwrap(), + KeyEvent { + code: KeyCode::Char('2'), + modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL + } + ); + } + + #[test] + fn parsing_nonsensical_keys_fails() { + assert!(str::parse::("F13").is_err()); + assert!(str::parse::("F0").is_err()); + assert!(str::parse::("aaa").is_err()); + assert!(str::parse::("S-S-a").is_err()); + assert!(str::parse::("C-A-S-C-1").is_err()); + assert!(str::parse::("FU").is_err()); + assert!(str::parse::("123").is_err()); + assert!(str::parse::("S--").is_err()); + } +} diff --git a/helix-view/src/lib.rs b/helix-view/src/lib.rs index 20613451..8b635700 100644 --- a/helix-view/src/lib.rs +++ b/helix-view/src/lib.rs @@ -3,14 +3,16 @@ pub mod macros; pub mod document; pub mod editor; +pub mod input; pub mod register_selection; pub mod theme; pub mod tree; pub mod view; -use slotmap::new_key_type; -new_key_type! { pub struct DocumentId; } -new_key_type! { pub struct ViewId; } +slotmap::new_key_type! { + pub struct DocumentId; + pub struct ViewId; +} pub use document::Document; pub use editor::Editor; -- cgit v1.2.3-70-g09d2