ratatui_code_editor/
editor_crossterm.rs1use crate::actions::*;
2use crate::editor::Editor;
3use crate::selection::SelectionSnap;
4use anyhow::Result;
5use crossterm::event::{
6 KeyEvent, KeyModifiers,
7 MouseButton, MouseEvent, MouseEventKind,
8};
9use ratatui_core::layout::Rect;
10
11impl Editor {
12 pub fn input(
13 &mut self, key: KeyEvent, area: &Rect,
14 ) -> Result<()> {
15 use crossterm::event::KeyCode;
16
17 let shift = key.modifiers.contains(KeyModifiers::SHIFT);
18 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
19 let _alt = key.modifiers.contains(KeyModifiers::ALT);
20
21 match key.code {
22 KeyCode::Char('รท') => self.apply(ToggleComment { }),
23 KeyCode::Char('z') if ctrl => self.apply(Undo { }),
24 KeyCode::Char('y') if ctrl => self.apply(Redo { }),
25 KeyCode::Char('c') if ctrl => self.apply(Copy { }),
26 KeyCode::Char('v') if ctrl => self.apply(Paste { }),
27 KeyCode::Char('x') if ctrl => self.apply(Cut { }),
28 KeyCode::Char('k') if ctrl => self.apply(DeleteLine { }),
29 KeyCode::Char('d') if ctrl => self.apply(Duplicate { }),
30 KeyCode::Char('a') if ctrl => self.apply(SelectAll { }),
31 KeyCode::Left => self.apply(MoveLeft { shift }),
32 KeyCode::Right => self.apply(MoveRight { shift }),
33 KeyCode::Up => self.apply(MoveUp { shift }),
34 KeyCode::Down => self.apply(MoveDown { shift }),
35 KeyCode::Backspace => self.apply(Delete { }),
36 KeyCode::Enter => self.apply(InsertNewline { }),
37 KeyCode::Char(c) => self.apply(InsertText { text: c.to_string() }),
38 KeyCode::Tab => self.apply(Indent { }),
39 KeyCode::BackTab => self.apply(UnIndent { }),
40 _ => {}
41 }
42 self.focus(&area);
43 Ok(())
44 }
45
46 pub fn mouse(
47 &mut self, mouse: MouseEvent, area: &Rect,
48 ) -> Result<()> {
49
50 match mouse.kind {
51 MouseEventKind::ScrollUp => self.scroll_up(),
52 MouseEventKind::ScrollDown => self.scroll_down(area.height as usize),
53 MouseEventKind::Down(MouseButton::Left) => {
54 let pos = self.cursor_from_mouse(mouse.column, mouse.row, area);
55 if let Some(cursor) = pos {
56 self.handle_mouse_down(cursor);
57 }
58 }
59 MouseEventKind::Drag(MouseButton::Left) => {
60 if mouse.row == area.top() {
62 self.scroll_up();
63 }
64 if mouse.row == area.bottom().saturating_sub(1) {
65 self.scroll_down(area.height as usize);
66 }
67 let pos = self.cursor_from_mouse(mouse.column, mouse.row, area);
68 if let Some(cursor) = pos {
69 self.handle_mouse_drag(cursor);
70 }
71 }
72 MouseEventKind::Up(MouseButton::Left) => {
73 self.selection_snap = SelectionSnap::None;
74 }
75 _ => {}
76 }
77 Ok(())
78 }
79}