Skip to main content

indigo_core/mode/
normal.rs

1#![cfg_attr(not(test), expect(clippy::enum_glob_use))]
2
3use crate::{
4    client::ClientMut,
5    mode::{Mode, command::enter_command_mode, insert, prompt, view},
6    selection::PasteMode,
7};
8use indigo_key::{Key, KeyCode, Keymap, KeymapResult, Mapping, keymap};
9use indigo_text::rope::{LINE_TYPE, RopeExt as _};
10use regex_cursor::engines::meta::Regex;
11use std::{cmp::min, num::NonZeroUsize, sync::Arc};
12
13#[derive(Debug)]
14pub enum Action {
15    AppendCountDigit(u8),
16    Commit,
17    EnterNormalMode,
18    EnterCommandMode,
19    EnterInsertMode,
20    EnterViewMode,
21    InsertAfterHead,
22    InsertAtLineNonBlankStart,
23    InsertAtLineEnd,
24    InsertLineAbove,
25    InsertLineBelow,
26    AddLineAbove,
27    AddLineBelow,
28    MoveLeft,
29    MoveRight,
30    MoveUp,
31    MoveDown,
32    ExtendLeft,
33    ExtendRight,
34    ExtendUp,
35    ExtendDown,
36    GotoMoveToLine,
37    GotoMoveToStart,
38    GotoExtendToStart,
39    GotoMoveToBottom,
40    GotoExtendToBottom,
41    GotoMoveToEnd,
42    GotoExtendToEnd,
43    GotoMoveToLineStart,
44    GotoExtendToLineStart,
45    GotoMoveToLineNonBlankStart,
46    GotoExtendToLineNonBlankStart,
47    GotoMoveUntilLineEnd,
48    GotoExtendUntilLineEnd,
49    Seek {
50        select: SeekSelect,
51        include: SeekInclude,
52        direction: SeekDirection,
53        byte: u8,
54    },
55    KeepPrimary,
56    RotateSelectionBackward,
57    RotateSelectionForward,
58    Collapse,
59    Flip,
60    FlipForward,
61    SelectAll,
62    ExpandToFullLines,
63    SplitIntoLines,
64    SelectRegex,
65    Delete,
66    Yank,
67    PasteAfter,
68    PasteBefore,
69    PasteReplace,
70    PasteAllAfter,
71    PasteAllBefore,
72    PasteAllReplace,
73    Replace(u8),
74    Undo,
75    Redo,
76    ScrollHalfPageUp,
77    ScrollHalfPageDown,
78    ScrollFullPageUp,
79    ScrollFullPageDown,
80    Suspend,
81    QuitHint,
82    Todo(&'static str),
83}
84
85#[derive(Clone, Copy, Debug)]
86pub enum SeekSelect {
87    Move,
88    Extend,
89}
90
91#[derive(Clone, Copy, Debug)]
92pub enum SeekInclude {
93    Until,
94    Onto,
95}
96
97#[derive(Clone, Copy, Debug)]
98pub enum SeekDirection {
99    Prev,
100    Next,
101}
102
103#[expect(clippy::too_many_lines)]
104#[must_use]
105pub fn keymap() -> Keymap<Vec<Action>> {
106    use Action::*;
107    use SeekDirection::{Next, Prev};
108    use SeekInclude::{Onto, Until};
109    use SeekSelect::{Extend, Move};
110    keymap! { Vec<Action>;
111        "<esc>" => vec![EnterNormalMode],
112
113        "0" => vec![AppendCountDigit(0)],
114        "1" => vec![AppendCountDigit(1)],
115        "2" => vec![AppendCountDigit(2)],
116        "3" => vec![AppendCountDigit(3)],
117        "4" => vec![AppendCountDigit(4)],
118        "5" => vec![AppendCountDigit(5)],
119        "6" => vec![AppendCountDigit(6)],
120        "7" => vec![AppendCountDigit(7)],
121        "8" => vec![AppendCountDigit(8)],
122        "9" => vec![AppendCountDigit(9)],
123
124        "h" => vec![MoveLeft], /// Move left
125        "l" => vec![MoveRight], /// Move right
126        "k" => vec![MoveUp], /// Move up
127        "j" => vec![MoveDown], /// Move down
128        "H" => vec![ExtendLeft], /// Extend left
129        "L" => vec![ExtendRight], /// Extend right
130        "K" => vec![ExtendUp], /// Extend up
131        "J" => vec![ExtendDown], /// Extend down
132
133        "q" => vec![Todo("q")], /// TODO: Move to previous word start
134        "w" => vec![Todo("w")], /// TODO: Move to next word start
135        "e" => vec![Todo("e")], /// TODO: Move to next word end
136        "<a-q>" => vec![Todo("<a-q>")], /// TODO: Move to previous WORD start
137        "<a-w>" => vec![Todo("<a-w>")], /// TODO: Move to next WORD start
138        "<a-e>" => vec![Todo("<a-e>")], /// TODO: Move to next WORD end
139        "Q" => vec![Todo("Q")], /// TODO: Extend to previous word start
140        "W" => vec![Todo("W")], /// TODO: Extend to next word start
141        "E" => vec![Todo("E")], /// TODO: Extend to next word end
142        "<a-Q>" => vec![Todo("<a-Q>")], /// TODO: Extend to previous WORD start
143        "<a-W>" => vec![Todo("<a-W>")], /// TODO: Extend to next WORD start
144        "<a-E>" => vec![Todo("<a-E>")], /// TODO: Extend to next WORD end
145
146        "m" => vec![Todo("m")], /// TODO: Move to next matching bracket
147        "<a-m>" => vec![Todo("<a-m>")], /// TODO: Move to previous matching bracket
148        "M" => vec![Todo("M")], /// TODO: Extend to next matching bracket
149        "<a-M>" => vec![Todo("<a-M>")], /// TODO: Extend to previous matching bracket
150
151        "i" => vec![EnterInsertMode], /// Enter insert mode at cursor
152        "a" => vec![InsertAfterHead], /// Enter insert mode after cursor
153        "I" => vec![InsertAtLineNonBlankStart], /// Enter insert mode at first non-blank
154        "A" => vec![InsertAtLineEnd], /// Enter insert mode at line end
155
156        "r<any>" => Mapping::Any(|key| Some(vec![Replace(key_char(key)?), Commit])), /// Replace characters
157        "y" => vec![Yank], /// Yank
158        "c" => vec![Yank, Delete, EnterInsertMode], /// Change
159        "d" => vec![Yank, Delete, Commit], /// Delete
160        "<a-c>" => vec![Delete, EnterInsertMode], /// Change without yanking
161        "<a-d>" => vec![Delete, Commit], /// Delete without yanking
162
163        "p" => vec![PasteAfter, Commit], /// Paste after
164        "P" => vec![PasteBefore, Commit], /// Paste before
165        "R" => vec![PasteReplace, Commit], /// Paste replacing selection
166        "<a-p>" => vec![PasteAllAfter, Commit], /// Paste all after
167        "<a-P>" => vec![PasteAllBefore, Commit], /// Paste all before
168        "<a-R>" => vec![PasteAllReplace, Commit], /// Paste all replacing selection
169
170        "<a-j>" => vec![Todo("<a-j>")], /// TODO: Join lines
171        "<a-J>" => vec![Todo("<a-J>")], /// TODO: Join lines and select spaces
172
173        "\\>" => vec![Todo("\\>")], /// TODO: Indent
174        "\\<" => vec![Todo("\\<")], /// TODO: Unindent
175        "<a-\\>>" => vec![Todo("<a-\\>>")], /// TODO: Indent including empty lines
176        "<a-\\<>" => vec![Todo("<a-\\<>")], /// TODO: Unindent and keep incomplete indent
177        "&" => vec![Todo("&")], /// TODO: Align selections
178        "<a-&>" => vec![Todo("<a-&>")], /// TODO: Copy indent from primary selection
179
180        "`" => vec![Todo("`")], /// TODO: Convert to lowercase
181        "~" => vec![Todo("~")], /// TODO: Convert to uppercase
182        "<a-`>" => vec![Todo("<a-`>")], /// TODO: Swap case
183        "@" => vec![Todo("@")], /// TODO: Convert tabs to spaces
184        "<a-@>" => vec![Todo("<a-@>")], /// TODO: Convert spaces to tabs
185
186        "<a-)>" => vec![Todo("<a-)>")], /// TODO: Rotate selection contents forward
187        "<a-(>" => vec![Todo("<a-(>")], /// TODO: Rotate selection contents backward
188
189        "." => vec![Todo(".")], /// TODO: Repeat last insert
190        "<a-.>" => vec![Todo("<a-.>")], /// TODO: Repeat last object or seek selection
191
192        "|" => vec![Todo("|")], /// TODO: Pipe through filter and replace
193        "<a-|>" => vec![Todo("<a-|>")], /// TODO: Pipe through filter and ignore output
194        "$" => vec![Todo("$")], /// TODO: Keep selections where filter exits successfully
195        "!" => vec![Todo("!")], /// TODO: Insert command output before
196        "<a-!>" => vec![Todo("<a-!>")], /// TODO: Append command output after
197
198        "u" => vec![Undo], /// Undo
199        "U" => vec![Redo], /// Redo
200
201        "<a-u>" => vec![Todo("<a-u>")], /// TODO: Undo selection change
202        "<a-U>" => vec![Todo("<a-U>")], /// TODO: Redo selection change
203        "<c-k>" => vec![Todo("<c-k>")], /// TODO: Move backward in change history
204        "<c-j>" => vec![Todo("<c-j>")], /// TODO: Move forward in change history
205
206        // TODO: With a count, `g` runs `GotoLine` instead of entering goto mode.
207        "gk" => vec![GotoMoveToStart], /// Move to buffer start
208        "gj" => vec![GotoMoveToBottom], /// Move to last line
209        "ge" => vec![GotoMoveToEnd], /// Move to buffer end
210        "gh" => vec![GotoMoveToLineStart], /// Move to line start
211        "gi" => vec![GotoMoveToLineNonBlankStart], /// Move to first non-blank
212        "gl" => vec![GotoMoveUntilLineEnd], /// Move to line end
213        "gK" => vec![GotoExtendToStart], /// Extend to buffer start
214        "gJ" => vec![GotoExtendToBottom], /// Extend to last line
215        "gE" => vec![GotoExtendToEnd], /// Extend to buffer end
216        "gH" => vec![GotoExtendToLineStart], /// Extend to line start
217        "gI" => vec![GotoExtendToLineNonBlankStart], /// Extend to first non-blank
218        "gL" => vec![GotoExtendUntilLineEnd], /// Extend to line end
219        "gt" => vec![Todo("gt")], /// TODO: Move to first displayed line
220        "gc" => vec![Todo("gc")], /// TODO: Move to middle displayed line
221        "gb" => vec![Todo("gb")], /// TODO: Move to last displayed line
222        "ga" => vec![Todo("ga")], /// TODO: Go to alternate buffer
223        "gf" => vec![Todo("gf")], /// TODO: Open file under selection
224        "g." => vec![Todo("g.")], /// TODO: Move to last modification
225
226        "f<any>" => Mapping::Any(|key| Some(vec![Seek { select: Move, include: Onto, direction: Next, byte: key_char(key)? }])), /// Move onto next character
227        "<a-f><any>" => Mapping::Any(|key| Some(vec![Seek { select: Move, include: Onto, direction: Prev, byte: key_char(key)? }])), /// Move onto previous character
228        "t<any>" => Mapping::Any(|key| Some(vec![Seek { select: Move, include: Until, direction: Next, byte: key_char(key)? }])), /// Move until next character
229        "<a-t><any>" => Mapping::Any(|key| Some(vec![Seek { select: Move, include: Until, direction: Prev, byte: key_char(key)? }])), /// Move until previous character
230        "F<any>" => Mapping::Any(|key| Some(vec![Seek { select: Extend, include: Onto, direction: Next, byte: key_char(key)? }])), /// Extend onto next character
231        "<a-F><any>" => Mapping::Any(|key| Some(vec![Seek { select: Extend, include: Onto, direction: Prev, byte: key_char(key)? }])), /// Extend onto previous character
232        "T<any>" => Mapping::Any(|key| Some(vec![Seek { select: Extend, include: Until, direction: Next, byte: key_char(key)? }])), /// Extend until next character
233        "<a-T><any>" => Mapping::Any(|key| Some(vec![Seek { select: Extend, include: Until, direction: Prev, byte: key_char(key)? }])), /// Extend until previous character
234
235        "<a-a>" => vec![Todo("<a-a>")], /// TODO: Select whole object
236        "<a-i>" => vec![Todo("<a-i>")], /// TODO: Select inner object
237        "[" => vec![Todo("[")], /// TODO: Move to object start
238        "]" => vec![Todo("]")], /// TODO: Move to object end
239        "{" => vec![Todo("{")], /// TODO: Extend to object start
240        "}" => vec![Todo("}")], /// TODO: Extend to object end
241        "<a-[>" => vec![Todo("<a-[>")], /// TODO: Move to inner object start
242        "<a-]>" => vec![Todo("<a-]>")], /// TODO: Move to inner object end
243        "<a-{>" => vec![Todo("<a-{>")], /// TODO: Extend to inner object start
244        "<a-}>" => vec![Todo("<a-}>")], /// TODO: Extend to inner object end
245
246        "/" => vec![Todo("/")], /// TODO: Search forward
247        "<a-/>" => vec![Todo("<a-/>")], /// TODO: Search backward
248        "?" => vec![Todo("?")], /// TODO: Extend to next match
249        "<a-?>" => vec![Todo("<a-?>")], /// TODO: Extend to previous match
250        "n" => vec![Todo("n")], /// TODO: Select next match
251        "<a-n>" => vec![Todo("<a-n>")], /// TODO: Select previous match
252        "N" => vec![Todo("N")], /// TODO: Add next match to selection
253        "<a-N>" => vec![Todo("<a-N>")], /// TODO: Add previous match to selection
254        "*" => vec![Todo("*")], /// TODO: Set search pattern from selection
255        "<a-*>" => vec![Todo("<a-*>")], /// TODO: Set search pattern from selection verbatim
256
257        "%" => vec![SelectAll], /// Select all
258        "s" => vec![SelectRegex], /// Select regex matches
259        "<a-s>" => vec![SplitIntoLines], /// Split into lines
260        "S" => vec![Todo("S")], /// TODO: Split on regex
261        "<a-S>" => vec![Todo("<a-S>")], /// TODO: Select first and last characters
262        "<a-k>" => vec![Todo("<a-k>")], /// TODO: Keep selection ranges matching regex
263        "<a-K>" => vec![Todo("<a-K>")], /// TODO: Remove selection ranges matching regex
264
265        "C" => vec![Todo("C")], /// TODO: Copy selection ranges down
266        "<a-C>" => vec![Todo("<a-C>")], /// TODO: Copy selection ranges up
267        "+" => vec![Todo("+")], /// TODO: Duplicate each selection range
268        "<a-+>" => vec![Todo("<a-+>")], /// TODO: Merge overlapping selection ranges
269        "<a-_>" => vec![Todo("<a-_>")], /// TODO: Merge contiguous selection ranges
270        "_" => vec![Todo("_")], /// TODO: Trim surrounding whitespace
271        "x" => vec![ExpandToFullLines], /// Expand to full lines
272        "X" => vec![Todo("X")], /// TODO: Extend to full lines
273        "<a-x>" => vec![Todo("<a-x>")], /// TODO: Trim to full lines
274
275        "<a-;>" => vec![Flip], /// Flip selection
276        "<a-:>" => vec![FlipForward], /// Flip selection forward
277        "(" => vec![RotateSelectionBackward], /// Rotate selection backward
278        ")" => vec![RotateSelectionForward], /// Rotate selection forward
279        "," => vec![KeepPrimary], /// Keep only primary selection range
280        "<a-,>" => vec![Todo("<a-,>")], /// TODO: Remove primary selection range
281        ";" => vec![Collapse], /// Collapse selection ranges
282
283        "Z" => vec![Todo("Z")], /// TODO: Save selection to register
284        "z" => vec![Todo("z")], /// TODO: Restore selection from register
285        "<a-Z>" => vec![Todo("<a-Z>")], /// TODO: Combine selection with register
286        "<a-z>" => vec![Todo("<a-z>")], /// TODO: Combine register with selection
287
288        "<c-o>" => vec![Todo("<c-o>")], /// TODO: Jump backward
289        "<c-i>" => vec![Todo("<c-i>")], /// TODO: Jump forward
290        "<c-s>" => vec![Todo("<c-s>")], /// TODO: Save selection to jump list
291
292        "o" => vec![InsertLineBelow], /// Enter insert mode on new line below
293        "O" => vec![InsertLineAbove], /// Enter insert mode on new line above
294        "<a-o>" => vec![AddLineBelow, Commit], /// Add line below
295        "<a-O>" => vec![AddLineAbove, Commit], /// Add line above
296
297        ":" => vec![EnterCommandMode], /// Enter command mode
298        "\\ " => vec![Todo("\\ ")], /// TODO: Enter user mode
299
300        "<c-u>" => vec![ScrollHalfPageUp], /// Scroll half page up
301        "<c-d>" => vec![ScrollHalfPageDown], /// Scroll half page down
302        "<c-b>" => vec![ScrollFullPageUp], /// Scroll page up
303        "<c-f>" => vec![ScrollFullPageDown], /// Scroll page down
304
305        "v" => vec![EnterViewMode], /// Enter view mode
306
307        "<c-z>" => vec![Suspend], /// Suspend
308        "<c-c>" => vec![QuitHint],
309    }
310}
311
312pub fn handle_actions(client: &mut ClientMut, actions: &[Action]) {
313    for action in actions {
314        handle_action(client, action);
315    }
316}
317
318pub fn handle_action(client: &mut ClientMut, action: &Action) {
319    match action {
320        Action::AppendCountDigit(digit) => append_count_digit(client, *digit),
321        Action::Commit => client.focused_buffer_mut().text.commit(),
322        Action::EnterNormalMode => enter(client),
323        Action::EnterCommandMode => enter_command_mode(client),
324        Action::EnterInsertMode => insert::enter(client),
325        Action::EnterViewMode => view::enter(client),
326        Action::InsertAfterHead => insert_after_head(client),
327        Action::InsertAtLineNonBlankStart => insert_at_line_non_blank_start(client),
328        Action::InsertAtLineEnd => insert_at_line_end(client),
329        Action::InsertLineAbove => insert_line_above(client),
330        Action::InsertLineBelow => insert_line_below(client),
331        Action::AddLineAbove => add_line_above(client),
332        Action::AddLineBelow => add_line_below(client),
333        Action::MoveLeft => move_left(client),
334        Action::MoveRight => move_right(client),
335        Action::MoveUp => move_up(client),
336        Action::MoveDown => move_down(client),
337        Action::ExtendLeft => extend_left(client),
338        Action::ExtendRight => extend_right(client),
339        Action::ExtendUp => extend_up(client),
340        Action::ExtendDown => extend_down(client),
341        Action::GotoMoveToLine => goto_move_to_line(client),
342        Action::GotoMoveToStart => goto_move_to_start(client),
343        Action::GotoExtendToStart => goto_extend_to_start(client),
344        Action::GotoMoveToBottom => goto_move_to_bottom(client),
345        Action::GotoExtendToBottom => goto_extend_to_bottom(client),
346        Action::GotoMoveToEnd => goto_move_to_end(client),
347        Action::GotoExtendToEnd => goto_extend_to_end(client),
348        Action::GotoMoveToLineStart => goto_move_to_line_start(client),
349        Action::GotoExtendToLineStart => goto_extend_to_line_start(client),
350        Action::GotoMoveToLineNonBlankStart => goto_move_to_line_non_blank_start(client),
351        Action::GotoExtendToLineNonBlankStart => goto_extend_to_line_non_blank_start(client),
352        Action::GotoMoveUntilLineEnd => goto_move_until_line_end(client),
353        Action::GotoExtendUntilLineEnd => goto_extend_until_line_end(client),
354        Action::Seek {
355            select,
356            include,
357            direction,
358            byte,
359        } => seek(client, *select, *include, *direction, *byte),
360        Action::KeepPrimary => keep_primary(client),
361        Action::RotateSelectionBackward => rotate_selection_backward(client),
362        Action::RotateSelectionForward => rotate_selection_forward(client),
363        Action::Collapse => collapse(client),
364        Action::Flip => flip(client),
365        Action::FlipForward => flip_forward(client),
366        Action::SelectAll => select_all(client),
367        Action::ExpandToFullLines => expand_to_full_lines(client),
368        Action::SplitIntoLines => split_into_lines(client),
369        Action::SelectRegex => select_regex(client),
370        Action::Delete => delete(client),
371        Action::Yank => yank(client),
372        Action::PasteAfter => paste(client, PasteMode::After),
373        Action::PasteBefore => paste(client, PasteMode::Before),
374        Action::PasteReplace => paste(client, PasteMode::Replace),
375        Action::PasteAllAfter => paste_all(client, PasteMode::After),
376        Action::PasteAllBefore => paste_all(client, PasteMode::Before),
377        Action::PasteAllReplace => paste_all(client, PasteMode::Replace),
378        Action::Replace(byte) => replace(client, *byte),
379        Action::Undo => undo(client),
380        Action::Redo => redo(client),
381        Action::ScrollHalfPageUp => scroll_half_page_up(client),
382        Action::ScrollHalfPageDown => scroll_half_page_down(client),
383        Action::ScrollFullPageUp => scroll_full_page_up(client),
384        Action::ScrollFullPageDown => scroll_full_page_down(client),
385        Action::Suspend => client.suspend = true,
386        Action::QuitHint => quit_hint(client),
387        Action::Todo(keys) => todo(client, keys),
388    }
389}
390
391pub fn handle_keys(client: &mut ClientMut) -> bool {
392    let keymap = Arc::clone(&client.keymaps.normal);
393    match keymap.get_keys(&client.pending_keys) {
394        KeymapResult::Mapped(actions) => {
395            client.pending_keys.clear();
396            handle_actions(client, actions);
397            true
398        }
399        KeymapResult::Computed(actions) => {
400            client.pending_keys.clear();
401            handle_actions(client, &actions);
402            true
403        }
404        KeymapResult::Unmapped => {
405            client.pending_keys.clear();
406            client.count = None;
407            false
408        }
409        KeymapResult::Pending => true,
410    }
411}
412
413// Generous cap that Indigo can still handle without hanging.
414const MAX_COUNT: usize = 100_000;
415
416pub fn append_count_digit(client: &mut ClientMut, digit: u8) {
417    let digit = usize::from(digit);
418    let old_count = client.count.map_or(0, |count| usize::from(count));
419    let uncapped_count = old_count.saturating_mul(10).saturating_add(digit);
420    if uncapped_count > MAX_COUNT {
421        client.set_error("Max count is 100,000");
422    }
423    let new_count = NonZeroUsize::new(min(uncapped_count, MAX_COUNT));
424    client.count = new_count;
425}
426
427fn key_char(key: Key) -> Option<u8> {
428    match key.code {
429        KeyCode::Return if key.modifiers.is_empty() => Some(b'\n'),
430        KeyCode::Tab if key.modifiers.is_empty() => Some(b'\t'),
431        _ => key.typed_char(),
432    }
433}
434
435fn seek(
436    client: &mut ClientMut,
437    select: SeekSelect,
438    include: SeekInclude,
439    direction: SeekDirection,
440    byte: u8,
441) {
442    use SeekDirection::{Next, Prev};
443    use SeekInclude::{Onto, Until};
444    use SeekSelect::{Extend, Move};
445
446    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
447
448    let mut window = client.focused_window_mut();
449
450    window
451        .selection_move()
452        .for_each_move(|mut range| match (select, include, direction) {
453            (Move, Until, Prev) => range.move_until_prev_byte(byte, count),
454            (Extend, Until, Prev) => range.extend_until_prev_byte(byte, count),
455            (Move, Until, Next) => range.move_until_next_byte(byte, count),
456            (Extend, Until, Next) => range.extend_until_next_byte(byte, count),
457            (Move, Onto, Prev) => range.move_onto_prev_byte(byte, count),
458            (Extend, Onto, Prev) => range.extend_onto_prev_byte(byte, count),
459            (Move, Onto, Next) => range.move_onto_next_byte(byte, count),
460            (Extend, Onto, Next) => range.extend_onto_next_byte(byte, count),
461        });
462    window.selection_move().merge_overlapping();
463
464    window.scroll_to_selection();
465}
466
467pub fn enter(client: &mut ClientMut) {
468    client.focused_buffer_mut().text.commit();
469    client.mode = Mode::Normal;
470    client.count = None;
471}
472
473fn extend_left(client: &mut ClientMut) {
474    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
475    let mut window = client.focused_window_mut();
476    window
477        .selection_move()
478        .for_each_move(|mut range| range.extend_left(count));
479    window.selection_move().merge_overlapping();
480    window.scroll_to_selection();
481}
482
483fn move_left(client: &mut ClientMut) {
484    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
485    let mut window = client.focused_window_mut();
486    window
487        .selection_move()
488        .for_each_move(|mut range| range.move_left(count));
489    window.selection_move().merge_overlapping();
490    window.scroll_to_selection();
491}
492
493fn extend_right(client: &mut ClientMut) {
494    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
495    let mut window = client.focused_window_mut();
496    window
497        .selection_move()
498        .for_each_move(|mut range| range.extend_right(count));
499    window.selection_move().merge_overlapping();
500    window.scroll_to_selection();
501}
502
503fn move_right(client: &mut ClientMut) {
504    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
505    let mut window = client.focused_window_mut();
506    window
507        .selection_move()
508        .for_each_move(|mut range| range.move_right(count));
509    window.selection_move().merge_overlapping();
510    window.scroll_to_selection();
511}
512
513fn extend_up(client: &mut ClientMut) {
514    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
515    let mut window = client.focused_window_mut();
516    window
517        .selection_move()
518        .for_each_move(|mut range| range.extend_up(count));
519    window.selection_move().merge_overlapping();
520    window.scroll_to_selection();
521}
522
523fn move_up(client: &mut ClientMut) {
524    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
525    let mut window = client.focused_window_mut();
526    window
527        .selection_move()
528        .for_each_move(|mut range| range.move_up(count));
529    window.selection_move().merge_overlapping();
530    window.scroll_to_selection();
531}
532
533fn extend_down(client: &mut ClientMut) {
534    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
535    let mut window = client.focused_window_mut();
536    window
537        .selection_move()
538        .for_each_move(|mut range| range.extend_down(count));
539    window.selection_move().merge_overlapping();
540    window.scroll_to_selection();
541}
542
543fn move_down(client: &mut ClientMut) {
544    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
545    let mut window = client.focused_window_mut();
546    window
547        .selection_move()
548        .for_each_move(|mut range| range.move_down(count));
549    window.selection_move().merge_overlapping();
550    window.scroll_to_selection();
551}
552
553fn quit_hint(client: &mut ClientMut) {
554    client.set_message("Type :q<ret> to quit");
555    client.count = None;
556}
557
558fn flip(client: &mut ClientMut) {
559    let mut window = client.focused_window_mut();
560    window
561        .selection_move()
562        .for_each_move(|mut range| range.flip());
563    window.scroll_to_selection();
564    client.count = None;
565}
566
567fn flip_forward(client: &mut ClientMut) {
568    let mut window = client.focused_window_mut();
569    window
570        .selection_move()
571        .for_each_move(|mut range| range.flip_forward());
572    window.scroll_to_selection();
573    client.count = None;
574}
575
576fn keep_primary(client: &mut ClientMut) {
577    let mut window = client.focused_window_mut();
578    window.selection_move().keep_primary();
579    window.scroll_to_selection();
580    client.count = None;
581}
582
583fn rotate_selection_backward(client: &mut ClientMut) {
584    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
585    let mut window = client.focused_window_mut();
586    window.selection_move().rotate_backward(count);
587    window.scroll_to_selection();
588}
589
590fn rotate_selection_forward(client: &mut ClientMut) {
591    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
592    let mut window = client.focused_window_mut();
593    window.selection_move().rotate_forward(count);
594    window.scroll_to_selection();
595}
596
597fn collapse(client: &mut ClientMut) {
598    let mut window = client.focused_window_mut();
599    window
600        .selection_move()
601        .for_each_move(|mut range| range.collapse());
602    window.scroll_to_selection();
603    client.count = None;
604}
605
606fn delete(client: &mut ClientMut) {
607    if client.focused_buffer().text.readonly {
608        client.set_error("Buffer is readonly");
609        client.count = None;
610        return;
611    }
612    let mut window = client.focused_window_mut();
613    window.selection_edit().delete();
614    window.scroll_to_selection();
615    client.count = None;
616}
617
618fn yank(client: &mut ClientMut) {
619    let values = client
620        .focused_window()
621        .selection()
622        .contents()
623        .map(String::from)
624        .collect();
625    client.session_mut().registers.insert('"', values);
626    client.count = None;
627}
628
629fn paste(client: &mut ClientMut, paste_mode: PasteMode) {
630    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
631    if client.focused_buffer().text.readonly {
632        client.set_error("Buffer is readonly");
633        return;
634    }
635    let count = if paste_mode == PasteMode::Replace {
636        1
637    } else {
638        count
639    };
640    let values = client
641        .session()
642        .registers
643        .get(&'"')
644        .cloned()
645        .unwrap_or_default();
646    let mut window = client.focused_window_mut();
647    for _ in 1..=count {
648        window.selection_edit().paste(&values, paste_mode);
649    }
650    window.scroll_to_selection();
651}
652
653fn paste_all(client: &mut ClientMut, paste_mode: PasteMode) {
654    client.count = None;
655    if client.focused_buffer().text.readonly {
656        client.set_error("Buffer is readonly");
657        return;
658    }
659    let values = client
660        .session()
661        .registers
662        .get(&'"')
663        .cloned()
664        .unwrap_or_default();
665    if values.is_empty() {
666        client.set_error("Nothing to paste");
667        return;
668    }
669    let mut window = client.focused_window_mut();
670    window.selection_edit().paste_all(&values, paste_mode);
671    window.scroll_to_selection();
672}
673
674fn replace(client: &mut ClientMut, byte: u8) {
675    if client.focused_buffer().text.readonly {
676        client.set_error("Buffer is readonly");
677        client.count = None;
678        return;
679    }
680    let mut window = client.focused_window_mut();
681    window.selection_edit().replace_each(byte);
682    window.scroll_to_selection();
683    client.count = None;
684}
685
686fn undo(client: &mut ClientMut) {
687    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
688    if client.focused_buffer().text.readonly {
689        client.set_error("Buffer is readonly");
690        return;
691    }
692    let mut window = client.focused_window_mut();
693    for _ in 1..=count {
694        if !window.undo().unwrap() {
695            break;
696        }
697    }
698    window.scroll_to_selection();
699}
700
701fn redo(client: &mut ClientMut) {
702    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
703    if client.focused_buffer().text.readonly {
704        client.set_error("Buffer is readonly");
705        return;
706    }
707    let mut window = client.focused_window_mut();
708    for _ in 1..=count {
709        if !window.redo().unwrap() {
710            break;
711        }
712    }
713    window.scroll_to_selection();
714}
715
716fn scroll_half_page_up(client: &mut ClientMut) {
717    client.focused_window_mut().scroll_half_page_up();
718    client.count = None;
719}
720
721fn scroll_half_page_down(client: &mut ClientMut) {
722    client.focused_window_mut().scroll_half_page_down();
723    client.count = None;
724}
725
726fn scroll_full_page_up(client: &mut ClientMut) {
727    client.focused_window_mut().scroll_full_page_up();
728    client.count = None;
729}
730
731fn scroll_full_page_down(client: &mut ClientMut) {
732    client.focused_window_mut().scroll_full_page_down();
733    client.count = None;
734}
735
736fn select_all(client: &mut ClientMut) {
737    let mut window = client.focused_window_mut();
738    window.selection_move().select_all();
739    window.scroll_to_selection();
740    client.count = None;
741}
742
743fn expand_to_full_lines(client: &mut ClientMut) {
744    let mut window = client.focused_window_mut();
745    window
746        .selection_move()
747        .for_each_move(|mut range| range.expand_to_full_lines());
748    window.selection_move().merge_overlapping();
749    window.scroll_to_selection();
750    client.count = None;
751}
752
753fn split_into_lines(client: &mut ClientMut) {
754    let mut window = client.focused_window_mut();
755    window.selection_move().split_into_lines();
756    window.scroll_to_selection();
757    client.count = None;
758}
759
760fn select_regex(client: &mut ClientMut) {
761    prompt::enter(client, "select", |client, regex_str| {
762        if regex_str.is_empty() {
763            client.set_error("Nothing selected");
764            client.count = None;
765            return;
766        }
767        let regex = Regex::builder()
768            .syntax(
769                regex_cursor::regex_automata::util::syntax::Config::new()
770                    .multi_line(true)
771                    .dot_matches_new_line(true),
772            )
773            .build(regex_str);
774        match regex {
775            Ok(regex) => {
776                let matched = client
777                    .focused_window_mut()
778                    .selection_move()
779                    .select_regex(&regex);
780                if !matched {
781                    client.set_error("Nothing selected");
782                }
783            }
784            Err(error) => {
785                // Syntax errors notate the pattern over several lines, ending in "error: <reason>".
786                let error = error
787                    .syntax_error()
788                    .map_or_else(|| error.to_string(), ToString::to_string);
789                let last_line = error.lines().last().unwrap_or_default();
790                let reason = last_line.trim_prefix("error: ");
791                client.set_error(format!("Invalid regex: {reason}"));
792            }
793        }
794        client.count = None;
795    });
796}
797
798fn insert_after_head(client: &mut ClientMut) {
799    if client.focused_buffer().text.readonly {
800        client.set_error("Buffer is readonly");
801        client.count = None;
802        return;
803    }
804    let mut window = client.focused_window_mut();
805    window.selection_edit().for_each_edit(|mut range| {
806        range.prepare_append();
807    });
808    window.scroll_to_selection();
809    client.mode = Mode::Insert;
810    client.count = None;
811}
812
813fn insert_at_line_non_blank_start(client: &mut ClientMut) {
814    if client.focused_buffer().text.readonly {
815        client.set_error("Buffer is readonly");
816        client.count = None;
817        return;
818    }
819    let mut window = client.focused_window_mut();
820    window.selection_move().for_each_move(|mut range| {
821        range.move_to_line_non_blank_start();
822    });
823    window.scroll_to_selection();
824    client.mode = Mode::Insert;
825    client.count = None;
826}
827
828fn insert_at_line_end(client: &mut ClientMut) {
829    if client.focused_buffer().text.readonly {
830        client.set_error("Buffer is readonly");
831        client.count = None;
832        return;
833    }
834    let mut window = client.focused_window_mut();
835    window.selection_move().for_each_move(|mut range| {
836        range.move_onto_line_end();
837    });
838    window.scroll_to_selection();
839    client.mode = Mode::Insert;
840    client.count = None;
841}
842
843fn insert_line_above(client: &mut ClientMut) {
844    // TODO: Insert multiple cursors (like Kakoune) when count > 1
845    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
846    if client.focused_buffer().text.readonly {
847        client.set_error("Buffer is readonly");
848        return;
849    }
850    let mut window = client.focused_window_mut();
851    // TODO: Switch to selection-level insert
852    window.selection_edit().for_each_edit(|mut range| {
853        range.move_to_line_start();
854        for _ in 0..count {
855            range.insert_char('\n');
856        }
857        range.move_left(1);
858    });
859    window.scroll_to_selection();
860    client.mode = Mode::Insert;
861}
862
863fn insert_line_below(client: &mut ClientMut) {
864    // TODO: Insert multiple cursors (like Kakoune) when count > 1
865    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
866    if client.focused_buffer().text.readonly {
867        client.set_error("Buffer is readonly");
868        return;
869    }
870    let mut window = client.focused_window_mut();
871    // TODO: Switch to selection-level insert
872    window.selection_edit().for_each_edit(|mut range| {
873        range.move_onto_line_end();
874        for _ in 0..count {
875            range.insert_char('\n');
876        }
877    });
878    window.scroll_to_selection();
879    client.mode = Mode::Insert;
880}
881
882fn add_line_above(client: &mut ClientMut) {
883    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
884    if client.focused_buffer().text.readonly {
885        client.set_error("Buffer is readonly");
886        return;
887    }
888    let mut window = client.focused_window_mut();
889    // TODO: Switch to selection-level insert
890    window.selection_edit().for_each_edit(|mut range| {
891        let snapshot = range.save();
892        range.move_to_line_start();
893        for _ in 0..count {
894            range.insert_char('\n');
895        }
896        assert!(range.restore(&snapshot));
897    });
898    window.selection_move().merge_overlapping();
899    window.scroll_to_selection();
900}
901
902fn add_line_below(client: &mut ClientMut) {
903    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
904    if client.focused_buffer().text.readonly {
905        client.set_error("Buffer is readonly");
906        return;
907    }
908    let mut window = client.focused_window_mut();
909    // TODO: Switch to selection-level insert
910    window.selection_edit().for_each_edit(|mut range| {
911        let snapshot = range.save();
912        range.move_onto_line_end();
913        for _ in 0..count {
914            range.insert_char('\n');
915        }
916        assert!(range.restore(&snapshot));
917    });
918    window.selection_move().merge_overlapping();
919    window.scroll_to_selection();
920}
921
922fn goto_move_to_line(client: &mut ClientMut) {
923    let count = client.count.take().unwrap_or(NonZeroUsize::MIN).get();
924    let mut window = client.focused_window_mut();
925    let rope = window.buffer().text.rope().clone();
926    let line_index = min(count - 1, rope.len_lines_unix() - 1);
927    let byte_index = rope.line_to_byte_idx(line_index, LINE_TYPE);
928    window
929        .selection_move()
930        .for_each_move(|mut range| range.move_to(byte_index));
931    window.selection_move().merge_overlapping();
932    window.scroll_to_selection();
933}
934
935fn goto_move_to_start(client: &mut ClientMut) {
936    let mut window = client.focused_window_mut();
937    window
938        .selection_move()
939        .for_each_move(|mut range| range.move_to_start());
940    window.selection_move().merge_overlapping();
941    window.scroll_to_selection();
942    client.count = None;
943}
944
945fn goto_extend_to_start(client: &mut ClientMut) {
946    let mut window = client.focused_window_mut();
947    window
948        .selection_move()
949        .for_each_move(|mut range| range.extend_to_start());
950    window.selection_move().merge_overlapping();
951    window.scroll_to_selection();
952    client.count = None;
953}
954
955fn goto_move_to_bottom(client: &mut ClientMut) {
956    let mut window = client.focused_window_mut();
957    window
958        .selection_move()
959        .for_each_move(|mut range| range.move_to_bottom());
960    window.selection_move().merge_overlapping();
961    window.scroll_to_selection();
962    client.count = None;
963}
964
965fn goto_extend_to_bottom(client: &mut ClientMut) {
966    let mut window = client.focused_window_mut();
967    window
968        .selection_move()
969        .for_each_move(|mut range| range.extend_to_bottom());
970    window.selection_move().merge_overlapping();
971    window.scroll_to_selection();
972    client.count = None;
973}
974
975fn goto_move_to_end(client: &mut ClientMut) {
976    let mut window = client.focused_window_mut();
977    window
978        .selection_move()
979        .for_each_move(|mut range| range.move_to_end());
980    window.selection_move().merge_overlapping();
981    window.scroll_to_selection();
982    client.count = None;
983}
984
985fn goto_extend_to_end(client: &mut ClientMut) {
986    let mut window = client.focused_window_mut();
987    window
988        .selection_move()
989        .for_each_move(|mut range| range.extend_to_end());
990    window.selection_move().merge_overlapping();
991    window.scroll_to_selection();
992    client.count = None;
993}
994
995fn goto_move_to_line_start(client: &mut ClientMut) {
996    let mut window = client.focused_window_mut();
997    window
998        .selection_move()
999        .for_each_move(|mut range| range.move_to_line_start());
1000    window.selection_move().merge_overlapping();
1001    client.count = None;
1002}
1003
1004fn goto_extend_to_line_start(client: &mut ClientMut) {
1005    let mut window = client.focused_window_mut();
1006    window
1007        .selection_move()
1008        .for_each_move(|mut range| range.extend_to_line_start());
1009    window.selection_move().merge_overlapping();
1010    client.count = None;
1011}
1012
1013fn goto_move_to_line_non_blank_start(client: &mut ClientMut) {
1014    let mut window = client.focused_window_mut();
1015    window
1016        .selection_move()
1017        .for_each_move(|mut range| range.move_to_line_non_blank_start());
1018    window.selection_move().merge_overlapping();
1019    client.count = None;
1020}
1021
1022fn goto_extend_to_line_non_blank_start(client: &mut ClientMut) {
1023    let mut window = client.focused_window_mut();
1024    window
1025        .selection_move()
1026        .for_each_move(|mut range| range.extend_to_line_non_blank_start());
1027    window.selection_move().merge_overlapping();
1028    client.count = None;
1029}
1030
1031fn goto_move_until_line_end(client: &mut ClientMut) {
1032    let mut window = client.focused_window_mut();
1033    window
1034        .selection_move()
1035        .for_each_move(|mut range| range.move_until_line_end());
1036    window.selection_move().merge_overlapping();
1037    client.count = None;
1038}
1039
1040fn goto_extend_until_line_end(client: &mut ClientMut) {
1041    let mut window = client.focused_window_mut();
1042    window
1043        .selection_move()
1044        .for_each_move(|mut range| range.extend_until_line_end());
1045    window.selection_move().merge_overlapping();
1046    client.count = None;
1047}
1048
1049fn todo(client: &mut ClientMut, keys: &str) {
1050    client.set_error(format!("{keys} is not implemented yet"));
1051    client.count = None;
1052}