indigo_core/mode/
prompt.rs1#![cfg_attr(not(test), expect(clippy::enum_glob_use))]
2
3use crate::{
4 client::ClientMut,
5 cursor::{Cursor, CursorEdit, CursorMove, CursorState},
6 mode::{Mode, normal},
7 text::Text,
8};
9use indigo_key::{Keymap, KeymapResult, Mapping, keymap};
10use ropey::{Rope, RopeSlice};
11use std::sync::Arc;
12
13#[derive(Clone)]
14pub struct State {
15 pub prompt: &'static str,
16 text: Text,
17 cursor: CursorState,
18 handler: fn(&mut ClientMut, &str),
19}
20
21impl State {
22 #[must_use]
23 pub fn new(prompt: &'static str, handler: fn(&mut ClientMut, &str)) -> Self {
24 Self {
25 prompt,
26 text: Text::default(),
27 cursor: CursorState::default(),
28 handler,
29 }
30 }
31
32 #[must_use]
33 pub fn rope(&self) -> &Rope {
34 self.text.rope()
35 }
36
37 #[must_use]
39 pub fn content(&self) -> RopeSlice<'_> {
40 let rope = self.text.rope();
41 assert_eq!(
42 rope.byte(rope.len() - 1),
43 b'\n',
44 "Prompt text keeps its trailing newline"
45 );
46 rope.slice(..rope.len() - 1)
47 }
48
49 pub fn cursor(&self) -> Cursor<'_> {
50 let cursor = Cursor::new(&self.text, &self.cursor)
51 .expect("Command mode text and cursor state are always kept valid");
52 if cfg!(debug_assertions) {
53 cursor.assert_invariants().unwrap();
54 }
55 cursor
56 }
57
58 pub fn cursor_move(&mut self) -> CursorMove<'_> {
59 CursorMove::new(&self.text, &mut self.cursor)
60 .expect("Command mode text and cursor state are always kept valid")
61 .on_drop(|cursor| {
62 if cfg!(debug_assertions) {
63 cursor.assert_invariants().unwrap();
64 }
65 })
66 }
67
68 pub fn cursor_edit(&mut self) -> CursorEdit<'_> {
69 CursorEdit::new(&mut self.text, &mut self.cursor)
70 .expect("Command mode text and cursor state are always kept valid")
71 .on_drop(|cursor| {
72 if cfg!(debug_assertions) {
73 cursor.assert_invariants().unwrap();
74 }
75 })
76 }
77
78 pub fn assert_invariants(&self) -> anyhow::Result<()> {
79 let _ = Cursor::new(&self.text, &self.cursor)?;
80 Ok(())
81 }
82}
83
84#[derive(Debug)]
85pub enum Action {
86 EnterNormalMode,
87 MoveLeft,
88 MoveRight,
89 MoveToStart,
90 MoveToEnd,
91 DeleteToStart,
92 DeleteToEnd,
93 DeleteBefore,
94 InsertChar(char),
95 Exec,
96}
97
98#[must_use]
99pub fn keymap() -> Keymap<Vec<Action>> {
100 use Action::*;
101 keymap! { Vec<Action>;
102 "<esc>" => vec![EnterNormalMode], "<ret>" => vec![Exec], "<c-b>" => vec![MoveLeft], "<c-f>" => vec![MoveRight], "<c-a>" => vec![MoveToStart], "<c-e>" => vec![MoveToEnd], "<c-u>" => vec![DeleteToStart], "<c-k>" => vec![DeleteToEnd], "<bs>" => vec![DeleteBefore], "<any>" => Mapping::Any(|key| Some(vec![InsertChar(char::from(key.typed_char()?))])), }
113}
114
115pub fn handle_actions(client: &mut ClientMut, actions: &[Action]) {
116 for action in actions {
117 handle_action(client, action);
118 }
119}
120
121pub fn handle_action(client: &mut ClientMut, action: &Action) {
122 match action {
123 Action::EnterNormalMode => normal::enter(client),
124 Action::MoveLeft => move_left(client),
125 Action::MoveRight => move_right(client),
126 Action::MoveToStart => move_to_start(client),
127 Action::MoveToEnd => move_to_end(client),
128 Action::DeleteToStart => delete_to_start(client),
129 Action::DeleteToEnd => delete_to_end(client),
130 Action::DeleteBefore => delete_before(client),
131 Action::InsertChar(c) => insert_char(client, *c),
132 Action::Exec => exec(client),
133 }
134}
135
136pub fn handle_keys(client: &mut ClientMut) -> bool {
137 let keymap = Arc::clone(&client.keymaps.prompt);
138 match keymap.get_keys(&client.pending_keys) {
139 KeymapResult::Mapped(actions) => {
140 client.pending_keys.clear();
141 handle_actions(client, actions);
142 true
143 }
144 KeymapResult::Computed(actions) => {
145 client.pending_keys.clear();
146 handle_actions(client, &actions);
147 true
148 }
149 KeymapResult::Unmapped => {
150 client.pending_keys.clear();
151 false
152 }
153 KeymapResult::Pending => true,
154 }
155}
156
157pub fn enter(client: &mut ClientMut, prompt: &'static str, handler: fn(&mut ClientMut, &str)) {
158 client.mode = Mode::Prompt(State::new(prompt, handler));
159 client.count = None;
160}
161
162fn move_left(client: &mut ClientMut) {
163 let Mode::Prompt(prompt_mode) = &mut client.mode else {
164 panic!("Not in prompt mode")
165 };
166 prompt_mode.cursor_move().move_left(1);
167}
168
169fn move_right(client: &mut ClientMut) {
170 let Mode::Prompt(prompt_mode) = &mut client.mode else {
171 panic!("Not in prompt mode")
172 };
173 prompt_mode.cursor_move().move_right(1);
174}
175
176fn move_to_start(client: &mut ClientMut) {
177 let Mode::Prompt(prompt_mode) = &mut client.mode else {
178 panic!("Not in prompt mode")
179 };
180 prompt_mode.cursor_move().move_to_start();
181}
182
183fn move_to_end(client: &mut ClientMut) {
184 let Mode::Prompt(prompt_mode) = &mut client.mode else {
185 panic!("Not in prompt mode")
186 };
187 prompt_mode.cursor_move().move_to_end();
188}
189
190fn delete_to_start(client: &mut ClientMut) {
191 let Mode::Prompt(prompt_mode) = &mut client.mode else {
192 panic!("Not in prompt mode")
193 };
194 let mut cursor = prompt_mode.cursor_edit();
195 while cursor.delete_before().is_some() {}
196}
197
198fn delete_to_end(client: &mut ClientMut) {
199 let Mode::Prompt(prompt_mode) = &mut client.mode else {
200 panic!("Not in prompt mode")
201 };
202 let mut cursor = prompt_mode.cursor_edit();
203 while cursor.delete_after().is_some() {}
204}
205
206fn insert_char(client: &mut ClientMut, char: char) {
207 let Mode::Prompt(prompt_mode) = &mut client.mode else {
208 panic!("Not in prompt mode")
209 };
210 prompt_mode.cursor_edit().insert_char(char);
211}
212
213pub fn paste(client: &mut ClientMut, text: &str) {
214 let Mode::Prompt(prompt_mode) = &mut client.mode else {
215 panic!("Not in prompt mode")
216 };
217 prompt_mode.cursor_edit().insert(text);
218}
219
220fn delete_before(client: &mut ClientMut) {
221 let Mode::Prompt(prompt_mode) = &mut client.mode else {
222 panic!("Not in prompt mode")
223 };
224 if prompt_mode.cursor().is_at_start() {
225 normal::enter(client);
226 } else {
227 prompt_mode.cursor_edit().delete_before();
228 }
229}
230
231fn exec(client: &mut ClientMut) {
232 let Mode::Prompt(prompt_mode) = &mut client.mode else {
233 panic!("Not in prompt mode")
234 };
235 let text = prompt_mode.content().to_string();
236 (prompt_mode.handler)(client, &text);
237 normal::enter(client);
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn content_strips_trailing_newline() {
246 let mut state = State::new("test", |_, _| {});
247 assert_eq!(state.content().to_string(), "");
249 assert!(state.cursor().is_at_end());
250
251 state.cursor_edit().insert("abc");
252 assert_eq!(state.rope().to_string(), "abc\n");
253 assert_eq!(state.content().to_string(), "abc");
254
255 state.cursor_move().move_to_end();
257 assert!(state.cursor().is_at_end());
258 state.cursor_edit().insert_char('!');
259 assert_eq!(state.content().to_string(), "abc!");
260
261 state.cursor_move().move_to_start();
263 let mut cursor = state.cursor_edit();
264 while cursor.delete_after().is_some() {}
265 drop(cursor);
266 assert_eq!(state.content().to_string(), "");
267 }
268}