From 7f65c2242b181db6c9fe1e05516d190cf15981ca Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Mon, 19 Sep 2022 22:12:35 -0700 Subject: [PATCH] copy-mode: vim style jump to character motion refs: https://github.com/wez/wezterm/issues/2528 --- config/src/keyassignment.rs | 4 + mux/src/pane.rs | 16 ++- wezterm-gui/src/overlay/copy.rs | 163 ++++++++++++++++++++++++- wezterm-gui/src/termwindow/keyevent.rs | 25 ++-- wezterm-gui/src/termwindow/mod.rs | 27 ++-- 5 files changed, 206 insertions(+), 29 deletions(-) diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs index 2ed60da3c..db82ca95a 100644 --- a/config/src/keyassignment.rs +++ b/config/src/keyassignment.rs @@ -599,6 +599,10 @@ pub enum CopyModeAssignment { MoveForwardSemanticZone, MoveBackwardZoneOfType(SemanticType), MoveForwardZoneOfType(SemanticType), + JumpForward { prev_char: bool }, + JumpBackward { prev_char: bool }, + JumpAgain, + JumpReverse, } pub type KeyTable = HashMap<(KeyCode, Modifiers), KeyTableEntry>; diff --git a/mux/src/pane.rs b/mux/src/pane.rs index 15dfafef5..242111969 100644 --- a/mux/src/pane.rs +++ b/mux/src/pane.rs @@ -28,6 +28,18 @@ pub fn alloc_pane_id() -> PaneId { PANE_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed) } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PerformAssignmentResult { + /// Continue search for handler + Unhandled, + /// Found handler and acted upon the action + Handled, + /// Do not perform assignment, but instead treat the key event + /// as though there was no assignment and run it as a key_down + /// event. + BlockAssignmentAndRouteToKeyDown, +} + #[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub struct SearchResult { pub start_y: StableRowIndex, @@ -251,8 +263,8 @@ pub trait Pane: Downcast { fn set_zoomed(&self, _zoomed: bool) {} fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()>; fn key_up(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()>; - fn perform_assignment(&self, _assignment: &KeyAssignment) -> bool { - false + fn perform_assignment(&self, _assignment: &KeyAssignment) -> PerformAssignmentResult { + PerformAssignmentResult::Unhandled } fn mouse_event(&self, event: MouseEvent) -> anyhow::Result<()>; fn perform_actions(&self, _actions: Vec) {} diff --git a/wezterm-gui/src/overlay/copy.rs b/wezterm-gui/src/overlay/copy.rs index c186f4aaa..321970f0a 100644 --- a/wezterm-gui/src/overlay/copy.rs +++ b/wezterm-gui/src/overlay/copy.rs @@ -6,7 +6,8 @@ use config::keyassignment::{ }; use mux::domain::DomainId; use mux::pane::{ - ForEachPaneLogicalLine, LogicalLine, Pane, PaneId, Pattern, SearchResult, WithPaneLines, + ForEachPaneLogicalLine, LogicalLine, Pane, PaneId, Pattern, PerformAssignmentResult, + SearchResult, WithPaneLines, }; use mux::renderable::*; use mux::tab::TabId; @@ -40,6 +41,19 @@ pub struct CopyOverlay { render: RefCell, } +#[derive(Copy, Clone, Debug)] +struct PendingJump { + forward: bool, + prev_char: bool, +} + +#[derive(Copy, Clone, Debug)] +struct Jump { + forward: bool, + prev_char: bool, + target: char, +} + struct CopyRenderable { cursor: StableCursorPosition, delegate: Rc, @@ -65,6 +79,8 @@ struct CopyRenderable { /// Used to debounce queries while the user is typing typing_cookie: usize, searching: Option, + pending_jump: Option, + last_jump: Option, } struct Searching { @@ -138,6 +154,8 @@ impl CopyOverlay { selection_mode: SelectionMode::Cell, typing_cookie: 0, searching: None, + pending_jump: None, + last_jump: None, }; let search_row = render.compute_search_row(); @@ -905,6 +923,70 @@ impl CopyRenderable { self.select_to_cursor_pos(); } + fn perform_jump(&mut self, jump: Jump) { + let y = self.cursor.y; + let (_top, lines) = self.delegate.get_lines(y..y + 1); + let target_str = jump.target.to_string(); + if let Some(line) = lines.get(0) { + // Find the indices of cells with a matching target + let mut candidates: Vec = line + .visible_cells() + .filter_map(|cell| { + if cell.str() == &target_str { + Some(cell.cell_index()) + } else { + None + } + }) + .collect(); + + if !jump.forward { + candidates.reverse(); + } + + // Find the target that matches the jump + let target = candidates + .iter() + .find(|&&idx| { + if jump.forward { + idx > self.cursor.x + } else { + idx < self.cursor.x + } + }) + .copied(); + + if let Some(target) = target { + // We'll select the target cell index, or the cell + // before/after depending on the prev_char and direction + let target = match (jump.prev_char, jump.forward) { + (false, true | false) => target, + (true, true) => target.saturating_sub(1), + (true, false) => target.saturating_add(1), + }; + + self.cursor.x = target; + self.select_to_cursor_pos(); + } + } + } + + fn jump(&mut self, forward: bool, prev_char: bool) { + self.pending_jump + .replace(PendingJump { forward, prev_char }); + // FIXME: replace copy_mode key table with something + // that won't intercept some chars + } + + fn jump_again(&mut self, reverse: bool) { + if let Some(mut jump) = self.last_jump { + if reverse { + jump.forward = !jump.forward; + } + self.perform_jump(jump); + } + } + fn set_selection_mode(&mut self, mode: &Option) { match mode { None => self.clear_selection_mode(), @@ -965,6 +1047,28 @@ impl Pane for CopyOverlay { fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> { let mut render = self.render.borrow_mut(); + if let Some(jump) = render.pending_jump.take() { + match (key, mods) { + (KeyCode::Char(c), KeyModifiers::NONE) + | (KeyCode::Char(c), KeyModifiers::SHIFT) => { + let jump = Jump { + forward: jump.forward, + prev_char: jump.prev_char, + target: c, + }; + render.last_jump.replace(jump); + render.perform_jump(jump); + } + _ => { + self.delegate + .perform_actions(vec![termwiz::escape::Action::Control( + termwiz::escape::ControlCode::Bell, + )]); + } + } + return Ok(()); + } + if render.editing_search { match (key, mods) { (KeyCode::Char(c), KeyModifiers::NONE) @@ -985,11 +1089,16 @@ impl Pane for CopyOverlay { Ok(()) } - fn perform_assignment(&self, assignment: &KeyAssignment) -> bool { + fn perform_assignment(&self, assignment: &KeyAssignment) -> PerformAssignmentResult { use CopyModeAssignment::*; + let mut render = self.render.borrow_mut(); + if render.pending_jump.is_some() { + // Block key assignments until key_down is called + // and resolves the next state + return PerformAssignmentResult::BlockAssignmentAndRouteToKeyDown; + } match assignment { KeyAssignment::CopyMode(assignment) => { - let mut render = self.render.borrow_mut(); match assignment { MoveToViewportBottom => render.move_to_viewport_bottom(), MoveToViewportTop => render.move_to_viewport_top(), @@ -1025,10 +1134,14 @@ impl Pane for CopyOverlay { MoveForwardSemanticZone => render.move_by_zone(1, None), MoveBackwardZoneOfType(zone_type) => render.move_by_zone(-1, Some(*zone_type)), MoveForwardZoneOfType(zone_type) => render.move_by_zone(1, Some(*zone_type)), + JumpForward { prev_char } => render.jump(true, *prev_char), + JumpBackward { prev_char } => render.jump(false, *prev_char), + JumpAgain => render.jump_again(false), + JumpReverse => render.jump_again(true), } - true + PerformAssignmentResult::Handled } - _ => false, + _ => PerformAssignmentResult::Unhandled, } } @@ -1653,6 +1766,46 @@ pub fn copy_key_table() -> KeyTable { KeyAssignment::CopyMode(CopyModeAssignment::Close), ]), ), + ( + WKeyCode::Char(';'), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpAgain), + ), + ( + WKeyCode::Char(','), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpReverse), + ), + ( + WKeyCode::Char('F'), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpBackward { prev_char: false }), + ), + ( + WKeyCode::Char('F'), + Modifiers::SHIFT, + KeyAssignment::CopyMode(CopyModeAssignment::JumpBackward { prev_char: false }), + ), + ( + WKeyCode::Char('T'), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpBackward { prev_char: true }), + ), + ( + WKeyCode::Char('T'), + Modifiers::SHIFT, + KeyAssignment::CopyMode(CopyModeAssignment::JumpBackward { prev_char: true }), + ), + ( + WKeyCode::Char('f'), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpForward { prev_char: false }), + ), + ( + WKeyCode::Char('t'), + Modifiers::NONE, + KeyAssignment::CopyMode(CopyModeAssignment::JumpForward { prev_char: true }), + ), ] { table.insert((key, mods), KeyTableEntry { action }); } diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs index 1e112f37f..e2a3c758e 100644 --- a/wezterm-gui/src/termwindow/keyevent.rs +++ b/wezterm-gui/src/termwindow/keyevent.rs @@ -2,7 +2,7 @@ use crate::termwindow::InputMap; use ::window::{DeadKeyStatus, KeyCode, KeyEvent, Modifiers, RawKeyEvent, WindowOps}; use anyhow::Context; use config::keyassignment::KeyTableEntry; -use mux::pane::Pane; +use mux::pane::{Pane, PerformAssignmentResult}; use smol::Timer; use std::rc::Rc; use std::time::{Duration, Instant}; @@ -280,16 +280,23 @@ impl super::TermWindow { } self.key_table_state.did_process_key(); - self.perform_key_assignment(&pane, &entry.action).ok(); - context.invalidate(); + let handled = match self.perform_key_assignment(&pane, &entry.action) { + Ok(PerformAssignmentResult::Handled) => true, + Err(_) => true, + Ok(_) => false, + }; - if leader_active { - // A successful leader key-lookup cancels the leader - // virtual modifier state - self.leader_done(); + if handled { + context.invalidate(); + + if leader_active { + // A successful leader key-lookup cancels the leader + // virtual modifier state + self.leader_done(); + } + + return true; } - - return true; } } diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 51068dabf..d0c260299 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -37,7 +37,7 @@ use config::{ WindowCloseConfirmation, }; use mlua::{FromLua, UserData, UserDataFields}; -use mux::pane::{CloseReason, Pane, PaneId, Pattern as MuxPattern}; +use mux::pane::{CloseReason, Pane, PaneId, Pattern as MuxPattern, PerformAssignmentResult}; use mux::renderable::RenderableDimensions; use mux::tab::{ PositionedPane, PositionedSplit, SplitDirection, SplitRequest, SplitSize as MuxSplitSize, Tab, @@ -2189,17 +2189,18 @@ impl TermWindow { &mut self, pane: &Rc, assignment: &KeyAssignment, - ) -> anyhow::Result<()> { + ) -> anyhow::Result { use KeyAssignment::*; if let Some(modal) = self.get_modal() { if modal.perform_assignment(assignment, self) { - return Ok(()); + return Ok(PerformAssignmentResult::Handled); } } - if pane.perform_assignment(assignment) { - return Ok(()); + match pane.perform_assignment(assignment) { + PerformAssignmentResult::Unhandled => {} + result => return Ok(result), } let window = self.window.as_ref().map(|w| w.clone()); @@ -2522,7 +2523,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; let tab_id = tab.tab_id(); @@ -2535,7 +2536,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; let tab_id = tab.tab_id(); @@ -2551,7 +2552,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; let tab_id = tab.tab_id(); @@ -2564,7 +2565,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; tab.toggle_zoom(); } @@ -2572,7 +2573,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; tab.set_zoomed(*zoomed); } @@ -2669,7 +2670,7 @@ impl TermWindow { let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return Ok(()), + None => return Ok(PerformAssignmentResult::Handled), }; match direction { RotationDirection::Clockwise => tab.rotate_clockwise(), @@ -2691,7 +2692,7 @@ impl TermWindow { "Invalid direction {:?} for SplitPane", split.direction ); - return Ok(()); + return Ok(PerformAssignmentResult::Handled); } }, target_is_second: match split.direction { @@ -2716,7 +2717,7 @@ impl TermWindow { self.modal.borrow_mut().replace(Rc::new(modal)); } }; - Ok(()) + Ok(PerformAssignmentResult::Handled) } fn do_open_link_at_mouse_cursor(&self, pane: &Rc) {