1extern crate self as escriba_runtime;
9
10mod plugin_host;
11pub use plugin_host::{LazyTrigger, PluginHost};
12
13mod operator_pending;
14pub mod status;
15
16pub use operator_pending::{OpState, OperatorPending};
17pub use status::{PromptKind, StatusModel};
18
19use std::collections::HashMap;
20
21use awase::KeyRepeatGate;
22use escriba_buffer::BufferSet;
23use escriba_buffer::TextRev;
24use escriba_command::{CommandRegistry, EditContext};
25use escriba_core::{
26 Action, Anchored, Bound, BufferId, Cursors, Damage, Edit, EditGen, HighlightEffect, JumpList,
27 Mode, Motion, Operator, Position, Range, TextEffect, WindowId,
28};
29use escriba_input::{InputOutcome, translate_app_event};
30use escriba_keymap::{Key, Keymap};
31use escriba_mode::ModalState;
32use escriba_search::{Direction as SearchDirection, MatchCount, SearchState};
33use escriba_ui::{Layout, Rect, Viewport, Window};
34use escriba_vm::{EditorSnapshot, EscribaHost, EscribaVm, HostEffect, VmError};
35use madori::AppEvent;
36use std::time::Instant;
37
38pub struct EditorState {
41 pub buffers: BufferSet,
42 pub modal: ModalState,
43 pub search: SearchState,
47 pub keymap: Keymap,
48 pub commands: CommandRegistry,
49 pub layout: Layout,
50 pub active: BufferId,
51 cursors: Cursors,
56 pub quit_requested: bool,
57 pub messages: Vec<String>,
60 search_at: Option<Anchored<usize, TextRev>>,
69 last_change: Option<LastChange>,
76 recording_insert: bool,
79
80 pub jumps: JumpList,
84 pub options: HashMap<String, String>,
88 lisp_vm: Option<EscribaVm>,
94 pub pending_keys: Vec<Key>,
100 repeat_gate: KeyRepeatGate<Key>,
108 pub plugin_host: PluginHost,
113 register: Option<String>,
118 op_pending: zenmai::Stateful<OperatorPending>,
123 edit_gen: EditGen,
128 damage: Damage,
133}
134
135enum SeqStep {
137 Pending,
139 Resolved(Action),
141 Passthrough,
143}
144
145const fn is_discrete_jump(key: &Key) -> bool {
152 matches!(
153 key,
154 Key::Char('n')
155 | Key::Char('N')
156 | Key::Char('*')
157 | Key::Char('#')
158 | Key::Char('.')
164 | Key::Char('u')
167 | Key::Ctrl('r')
168 | Key::Ctrl('o')
169 | Key::Ctrl('i')
170 )
171}
172
173#[derive(Debug, Clone)]
175struct LastChange {
176 action: Action,
178 count: u32,
180 inserted: String,
182}
183
184impl EditorState {
185 pub fn new_with_buffer(initial: BufferSet, active: BufferId) -> Self {
187 let window = Window {
188 id: WindowId(1),
189 buffer_id: active,
190 viewport: Viewport {
191 top_line: 0,
192 left_column: 0,
193 visible_lines: 40,
194 visible_columns: 160,
195 },
196 rect: Rect {
197 x: 0,
198 y: 0,
199 width: 1200,
200 height: 800,
201 },
202 };
203 Self {
204 buffers: initial,
205 modal: ModalState::new(),
206 search: SearchState::new(escriba_search::CaseMode::Smart),
207 search_at: None,
208 last_change: None,
209 recording_insert: false,
210 jumps: JumpList::new(),
211 keymap: Keymap::default_vim(),
212 commands: CommandRegistry::default_set(),
213 layout: Layout::single(window),
214 active,
215 cursors: Cursors::single(Position::ZERO),
216 quit_requested: false,
217 register: None,
218 op_pending: zenmai::Stateful::new(OpState::Resting),
219 messages: Vec::new(),
220 options: HashMap::new(),
221 lisp_vm: None,
222 pending_keys: Vec::new(),
223 repeat_gate: KeyRepeatGate::new(),
224 plugin_host: PluginHost::default(),
225 edit_gen: EditGen::default(),
226 damage: Damage::None,
227 }
228 }
229
230 #[must_use]
234 pub fn edit_gen(&self) -> EditGen {
235 self.edit_gen
236 }
237
238 fn bump_gen(&mut self) {
240 self.edit_gen = self.edit_gen.next();
241 }
242
243 #[must_use]
245 pub fn damage(&self) -> Damage {
246 self.damage
247 }
248
249 pub fn take_damage(&mut self) -> Damage {
253 std::mem::replace(&mut self.damage, Damage::None)
254 }
255
256 fn active_line_count(&self) -> u32 {
259 self.buffers
260 .get(self.active)
261 .map_or(0, escriba_buffer::Buffer::line_count)
262 }
263
264 pub fn register_lazy_plugin(
270 &mut self,
271 name: impl Into<String>,
272 triggers: Vec<LazyTrigger>,
273 entry_src: impl Into<String>,
274 ) {
275 self.plugin_host.register(name, triggers, entry_src);
276 }
277
278 fn apply_plugin_entry(&mut self, entry_src: &str) -> usize {
284 let Ok(plan) = escriba_lisp::apply_source(entry_src) else {
285 return 0;
286 };
287 let cmd = escriba_lisp::apply_plan_to_commands(&plan, &mut self.commands);
288 escriba_lisp::apply_plan_to_options(&plan, &mut self.options);
289 if let Some(value) = self.options.get("mapleader") {
290 if let Some(key) = escriba_lisp::parse_leader_key(value) {
291 self.keymap.set_leader(key);
292 }
293 }
294 let km = escriba_lisp::apply_plan_to_keymap(&plan, &mut self.keymap);
295 (cmd.registered + km.keybinds_applied) as usize
296 }
297
298 pub fn activate_filetype_plugins(&mut self, filetype: &str) -> usize {
302 let pending = self.plugin_host.pending_for_filetype(filetype);
303 let n = pending.len();
304 for src in pending {
305 self.apply_plugin_entry(&src);
306 }
307 n
308 }
309
310 pub fn activate_event_plugins(&mut self, event: &str) -> usize {
313 let pending = self.plugin_host.pending_for_event(event);
314 let n = pending.len();
315 for src in pending {
316 self.apply_plugin_entry(&src);
317 }
318 n
319 }
320
321 pub fn tick(&mut self, event: &AppEvent) {
326 self.tick_at(event, Instant::now());
327 }
328
329 pub fn tick_at(&mut self, event: &AppEvent, now: Instant) {
333 match translate_app_event(event) {
334 InputOutcome::Key(k) => {
335 if self.gate_key(&k, now) {
336 self.on_key(&k);
337 }
338 }
339 InputOutcome::Resized { width, height } => {
340 if let Some(w) = self
341 .layout
342 .windows
343 .iter_mut()
344 .find(|w| w.id == self.layout.active)
345 {
346 w.rect.width = width;
347 w.rect.height = height;
348 }
349 self.damage = self.damage.join(Damage::Viewport);
350 self.bump_gen();
351 }
352 InputOutcome::Quit => self.quit_requested = true,
353 InputOutcome::Focus(_) | InputOutcome::None => {}
354 }
355 }
356
357 fn gate_key(&mut self, key: &Key, now: Instant) -> bool {
367 match self.modal.mode() {
368 Mode::Normal | Mode::Visual | Mode::VisualLine => {
369 if is_discrete_jump(key) {
375 return true;
376 }
377 self.repeat_gate.try_pass_at(*key, now)
378 }
379 Mode::Insert | Mode::Command => true,
380 }
381 }
382
383 pub fn on_key(&mut self, key: &Key) {
385 match self.step_sequence(key) {
389 SeqStep::Pending => return,
390 SeqStep::Resolved(action) => {
391 let count = self.modal.pending_count().unwrap_or(1);
392 self.modal.clear_count();
393 for _ in 0..count {
394 self.apply(&action);
395 if self.quit_requested {
396 return;
397 }
398 }
399 return;
400 }
401 SeqStep::Passthrough => {}
402 }
403 let counted = self.keymap.dispatch(&self.modal, key);
404 if matches!(counted.action, Action::Pending) {
406 if let Key::Char(c) = key {
407 if c.is_ascii_digit() {
408 let d = u32::from(*c as u8 - b'0');
409 self.modal.append_count(d);
410 }
411 }
412 return;
413 }
414 self.apply_counted(&counted.action, counted.count);
418 self.modal.clear_count();
420 }
421
422 fn step_sequence(&mut self, key: &Key) -> SeqStep {
434 let mode = self.modal.mode();
435 if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
436 return SeqStep::Passthrough;
437 }
438 if !self.pending_keys.is_empty() {
439 let mut seq = self.pending_keys.clone();
440 seq.push(key.clone());
441 if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
442 let action = b.action.clone();
443 self.pending_keys.clear();
444 return SeqStep::Resolved(action);
445 }
446 if self.keymap.is_sequence_prefix(mode, &seq) {
447 self.pending_keys = seq;
448 return SeqStep::Pending;
449 }
450 self.pending_keys.clear();
453 }
454 let start = [key.clone()];
455 if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
456 self.pending_keys = start.to_vec();
457 return SeqStep::Pending;
458 }
459 SeqStep::Passthrough
460 }
461
462 #[must_use]
467 pub fn cursor(&self) -> Position {
468 self.cursors.primary()
469 }
470
471 fn set_cursor(&mut self, pos: Position) {
480 let clamped = if let Some(buf) = self.buffers.get(self.active) {
481 buf.clamp(pos)
482 } else {
483 pos
484 };
485 self.cursors.set_primary(clamped);
486 if let Some(w) = self
487 .layout
488 .windows
489 .iter_mut()
490 .find(|w| w.id == self.layout.active)
491 {
492 w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
493 }
494 }
495
496 fn apply(&mut self, action: &Action) {
498 self.apply_counted(action, 1);
499 }
500
501 fn apply_counted(&mut self, action: &Action, count: u32) {
509 for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
510 for _ in 0..times {
511 self.apply_resolved(&resolved);
512 if self.quit_requested {
513 return;
514 }
515 }
516 }
517 }
518
519 #[must_use]
523 fn text_rev(&self) -> TextRev {
524 self.buffers
525 .get(self.active)
526 .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
527 }
528
529 fn active_text(&self) -> String {
530 self.buffers
531 .get(self.active)
532 .map(escriba_buffer::Buffer::to_string)
533 .unwrap_or_default()
534 }
535
536 fn cursor_char(&self) -> usize {
538 self.buffers
539 .get(self.active)
540 .and_then(|b| b.position_to_char(self.cursor()).ok())
541 .unwrap_or(0)
542 }
543
544 #[must_use]
552 pub fn status_model(&self) -> StatusModel<'_> {
553 let cursor = self.cursor();
554 let prompt = self.search.prompt();
555
556 let kind = match prompt.map(|p| p.direction) {
557 Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
558 Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
559 None if self.modal.mode() == Mode::Command => PromptKind::Ex,
562 None => PromptKind::None,
563 };
564
565 StatusModel {
566 mode: self.modal.mode(),
567 line: cursor.line.saturating_add(1) as usize,
568 column: cursor.column.saturating_add(1) as usize,
569 prompt: kind,
570 prompt_text: prompt.map_or_else(|| self.modal.minibuffer(), |p| p.text.as_str()),
571 prompt_caret: prompt.map_or_else(
576 || self.modal.minibuffer().chars().count(),
577 escriba_search::Prompt::caret,
578 ),
579 count: self.match_count(),
580 message: self.messages.last().map(String::as_str),
581 }
582 }
583
584 #[must_use]
590 fn match_count(&self) -> MatchCount {
591 if self.search.is_prompting() {
592 let text = self.active_text();
593 let total = self.search.preview_total(&text);
594 return match self.search.preview(&text) {
595 Some(step) => MatchCount::new(step.index, total),
596 None if total == 0 && !self.search.prompt_is_empty() => MatchCount::None,
600 None => MatchCount::Idle,
601 };
602 }
603 if self.search.pattern().is_none() {
604 return MatchCount::Idle;
605 }
606 let total = self.search.matches().len();
607 let rev = self.text_rev();
610 self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
611 if total == 0 {
612 MatchCount::None
613 } else {
614 MatchCount::Idle
615 },
616 |&i| MatchCount::new(i, total),
617 )
618 }
619
620 fn repeat_last_change(&mut self) {
626 let Some(change) = self.last_change.clone() else {
627 self.messages
628 .push("E32: No previous change to repeat".to_string());
629 return;
630 };
631
632 for _ in 0..change.count.max(1) {
633 self.apply_resolved(&change.action);
634 }
635 for c in change.inserted.chars() {
636 self.apply_resolved(&Action::InsertChar(c));
637 }
638 if self.modal.mode() == Mode::Insert {
639 self.apply_resolved(&Action::ChangeMode(Mode::Normal));
643 }
644 self.last_change = Some(change);
648 self.recording_insert = false;
649 }
650
651 fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
658 use escriba_core::TextObject as O;
659 let at = self.cursor_char();
660 let matches = self.search.matches();
661 let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
662
663 let idx = match object {
664 O::NextMatch => Bound::Inclusive.first_matching(&starts, at, true),
665 O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
666 }?;
667 let m = matches.get(idx)?;
668 let buf = self.buffers.get(self.active)?;
669 Some(Range {
670 start: buf.char_to_position(m.start),
671 end: buf.char_to_position(m.end),
672 })
673 }
674
675 fn land_on(&mut self, step: escriba_search::Step) {
676 if let Some(buf) = self.buffers.get(self.active) {
677 let pos = buf.char_to_position(step.target.start);
678 self.set_cursor(pos);
679 }
680 self.search_at = Some(Anchored::new(step.index, self.text_rev()));
684 if let Some(msg) = step.wrapped.message() {
685 self.messages.push(msg.to_string());
686 }
687 }
688
689 fn jump_search(&mut self, reverse: bool) {
693 self.search.relight();
696 self.jumps.push(self.cursor());
698 let at = self.cursor_char();
699 match self.search.repeat(at, reverse) {
700 Some(step) => self.land_on(step),
701 None => {
702 let msg = self.search.pattern().map_or_else(
703 || "E35: No previous regular expression".to_string(),
704 |p| {
705 let mut m = String::from("E486: Pattern not found: ");
706 m.push_str(p.raw());
707 m
708 },
709 );
710 self.messages.push(msg);
711 }
712 }
713 }
714
715 fn preview_search(&mut self) {
722 let text = self.active_text();
723 let Some(origin) = self.search.prompt().map(|p| p.origin) else {
724 return;
725 };
726 let target = self
727 .search
728 .preview(&text)
729 .map_or(origin, |s| s.target.start);
730 if let Some(buf) = self.buffers.get(self.active) {
739 let pos = buf.char_to_position(target);
740 self.set_cursor(pos);
741 }
742 }
743
744 fn submit_search_operated(&mut self, op: Operator) {
753 let text = self.active_text();
754 let Some(origin) = self.search.prompt().map(|p| p.origin) else {
755 return;
756 };
757
758 match self.search.accept(&text) {
759 escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
760 self.modal.clear_minibuffer();
761 self.modal.enter(Mode::Normal);
762 match self.search.commit_step(origin) {
763 Some(step) => {
764 if let Some(buf) = self.buffers.get(self.active) {
766 let from = buf.char_to_position(origin);
767 self.jumps.push(from);
768 let target = buf.char_to_position(step.target.start);
769 self.set_cursor(from);
770 self.search_at = Some(Anchored::new(step.index, self.text_rev()));
771 self.apply_operator_to(op, target);
772 }
773 }
774 None => self.report_pattern_not_found(),
775 }
776 }
777 escriba_search::Accepted::NothingToRepeat => {
778 self.modal.clear_minibuffer();
779 self.modal.enter(Mode::Normal);
780 self.messages
781 .push("E35: No previous regular expression".to_string());
782 }
783 escriba_search::Accepted::Invalid(e) => {
784 let mut m = String::from("E383: Invalid search string: ");
785 m.push_str(&e.to_string());
786 self.messages.push(m);
787 }
788 }
789 }
790
791 fn report_pattern_not_found(&mut self) {
794 let mut m = String::from("E486: Pattern not found");
795 if let Some(p) = self.search.pattern() {
796 m.push_str(": ");
797 m.push_str(p.raw());
798 }
799 self.messages.push(m);
800 }
801
802 fn submit_search(&mut self) {
804 let text = self.active_text();
805 let at = self
820 .search
821 .prompt()
822 .map_or_else(|| self.cursor_char(), |p| p.origin);
823 let skip = self
828 .search
829 .prompt()
830 .map_or(0, escriba_search::Prompt::preview_skip);
831 let outcome = self.search.accept(&text);
832 match outcome {
833 escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
834 self.modal.clear_minibuffer();
835 self.modal.enter(Mode::Normal);
836 if let Some(buf) = self.buffers.get(self.active) {
841 let origin = buf.char_to_position(at);
842 self.jumps.push(origin);
843 }
844 match self.search.commit_step_skipping(at, skip) {
845 Some(step) => self.land_on(step),
846 None => {
847 let mut m = String::from("E486: Pattern not found");
848 if let Some(p) = self.search.pattern() {
849 m.push_str(": ");
850 m.push_str(p.raw());
851 }
852 self.messages.push(m);
853 }
854 }
855 }
856 escriba_search::Accepted::NothingToRepeat => {
857 self.modal.clear_minibuffer();
858 self.modal.enter(Mode::Normal);
859 self.messages
860 .push("E35: No previous regular expression".to_string());
861 }
862 escriba_search::Accepted::Invalid(e) => {
865 let mut m = String::from("E383: Invalid search string: ");
866 m.push_str(&e.to_string());
867 self.messages.push(m);
868 }
869 }
870 }
871
872 fn apply_resolved(&mut self, action: &Action) {
873 let lines_before = self.active_line_count();
876 let cline_before = self.cursor().line;
877 match action {
878 Action::Move(m) => self.apply_motion(*m),
879 Action::SearchOpen(dir) => {
880 let origin = self.cursor_char();
884 self.search.open(*dir, origin);
885 self.modal.enter(Mode::Command);
886 }
887 Action::SearchRepeat { reverse } => self.jump_search(*reverse),
888 Action::SearchWord { reverse } => {
889 let dir = if *reverse {
890 SearchDirection::Backward
891 } else {
892 SearchDirection::Forward
893 };
894 let (text, at) = (self.active_text(), self.cursor_char());
895 self.jumps.push(self.cursor());
897 match self.search.search_word(&text, at, dir) {
898 Some(step) => self.land_on(step),
899 None => self
902 .messages
903 .push("E348: No string under cursor".to_string()),
904 }
905 }
906 Action::ClearSearchHighlight => self.search.clear_highlight(),
907 Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
908 Action::TextObject(object) => {
909 if let Some(range) = self.resolve_object(*object) {
915 self.jumps.push(self.cursor());
916 self.set_cursor(range.start);
917 } else {
918 self.report_pattern_not_found();
919 }
920 }
921 Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
922 Some(range) => self.apply_operator_over(*op, range),
923 None => self.report_pattern_not_found(),
924 },
925 Action::RepeatLastChange => self.repeat_last_change(),
926 Action::JumpBack => {
927 let here = self.cursor();
928 if let Some(pos) = self.jumps.back(here) {
929 self.set_cursor(pos);
930 } else {
931 self.messages
932 .push("E662: At start of changelist".to_string());
933 }
934 }
935 Action::JumpForward => {
936 if let Some(pos) = self.jumps.forward() {
937 self.set_cursor(pos);
938 } else {
939 self.messages.push("E663: At end of changelist".to_string());
940 }
941 }
942 Action::ChangeMode(m) => {
943 if *m == Mode::Normal && self.search.is_prompting() {
947 if let Some(origin) = self.search.cancel() {
948 if let Some(buf) = self.buffers.get(self.active) {
949 let pos = buf.char_to_position(origin);
950 self.set_cursor(pos);
951 }
952 }
953 }
954 self.modal.enter(*m);
955 }
956 Action::InsertChar(c) => self.insert_char(*c),
957 Action::Edit(edit) => self.apply_edit(edit),
958 Action::Undo => {
959 if let Some(buf) = self.buffers.get_mut(self.active) {
960 let _ = buf.undo();
961 }
962 self.set_cursor(self.cursor());
965 }
966 Action::Redo => {
967 if let Some(buf) = self.buffers.get_mut(self.active) {
968 let _ = buf.redo();
969 }
970 self.set_cursor(self.cursor());
971 }
972 Action::Save => {
973 if let Some(buf) = self.buffers.get_mut(self.active) {
974 let _ = buf.save();
975 }
976 self.set_cursor(self.cursor());
977 }
978 Action::Quit => self.quit_requested = true,
979 Action::SubmitCommand => {
980 if self.search.is_prompting() {
981 self.submit_search();
982 } else {
983 self.submit_command();
984 }
985 }
986 Action::Command { name, args } => self.run_command(name, args),
987 Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
988 Action::Operator(_) => {}
991 Action::PromptCaret { to } => {
992 if self.search.is_prompting() {
993 self.search.move_caret(*to);
994 }
995 }
996 Action::SearchPreviewStep { forward } => {
997 if self.search.is_prompting() {
998 self.search.preview_step(*forward);
999 self.preview_search();
1000 }
1001 }
1002 Action::PromptDelete => {
1003 if self.search.is_prompting() {
1004 self.search.delete_at_caret();
1005 self.preview_search();
1006 }
1007 }
1008 Action::PromptDeleteWord => {
1009 if self.search.is_prompting() {
1010 self.search.delete_word_before_caret();
1011 self.preview_search();
1012 }
1013 }
1014 Action::PromptClearToStart => {
1015 if self.search.is_prompting() {
1016 self.search.clear_before_caret();
1017 self.preview_search();
1018 }
1019 }
1020 Action::PromptBackspace => {
1021 self.prompt_backspace();
1022 if self.search.is_prompting() {
1026 self.preview_search();
1027 }
1028 }
1029 Action::PromptHistory { back } => {
1030 if self.search.is_prompting() {
1031 self.search.history_step(*back);
1032 self.modal.clear_minibuffer();
1036 if let Some(text) = self.search.prompt().map(|p| p.text.clone()) {
1037 self.modal.push_minibuffer_str(&text);
1038 }
1039 self.preview_search();
1040 }
1041 }
1042 Action::Pending => {}
1043 }
1044 let lines_after = self.active_line_count();
1049 let cline_after = self.cursor().line;
1050 let d = match action {
1051 Action::SearchOpen(_)
1055 | Action::PromptHistory { .. }
1056 | Action::PromptBackspace
1057 | Action::PromptCaret { .. }
1058 | Action::SearchPreviewStep { .. }
1059 | Action::PromptDelete
1060 | Action::PromptDeleteWord
1061 | Action::PromptClearToStart
1062 | Action::SearchRepeat { .. }
1063 | Action::SearchWord { .. }
1064 | Action::ClearSearchHighlight
1065 | Action::SearchSubmitOperated { .. }
1066 | Action::RepeatLastChange
1069 | Action::TextObject(_)
1070 | Action::ApplyOperatorObject { .. }
1071 | Action::JumpBack
1073 | Action::JumpForward => Damage::Full,
1074 Action::InsertChar(_)
1075 | Action::Edit(_)
1076 | Action::Undo
1077 | Action::Redo
1078 | Action::ApplyOperator { .. } => {
1079 if lines_after == lines_before {
1080 Damage::span(cline_before, cline_after)
1081 } else {
1082 Damage::Lines {
1083 from: cline_before.min(cline_after),
1084 to: u32::MAX,
1085 }
1086 }
1087 }
1088 Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
1089 Action::Save => Damage::Viewport,
1090 Action::Command { .. } | Action::SubmitCommand => Damage::Full,
1091 Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
1092 };
1093 self.damage = self.damage.join(d);
1094 if self.recording_insert {
1103 match action {
1104 Action::InsertChar(c) => {
1105 if let Some(lc) = self.last_change.as_mut() {
1106 lc.inserted.push(*c);
1107 }
1108 }
1109 Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
1111 _ => {}
1112 }
1113 } else if action.text_effect() == TextEffect::Mutates
1114 && !matches!(
1115 action,
1116 Action::RepeatLastChange | Action::Undo | Action::Redo
1117 )
1118 {
1119 self.last_change = Some(LastChange {
1123 action: action.clone(),
1124 count: 1,
1125 inserted: String::new(),
1126 });
1127 self.recording_insert = self.modal.mode() == Mode::Insert;
1128 }
1129
1130 if action.highlight_effect() == HighlightEffect::Clear {
1135 self.search.clear_highlight();
1136 }
1137 if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
1146 let text = self.active_text();
1147 self.search.refresh(&text);
1148 }
1153 self.bump_gen();
1158 }
1159
1160 fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
1170 let buf = self.buffers.get(self.active)?;
1171 let pos = from;
1172 Some(match motion {
1173 Motion::SearchNext | Motion::SearchPrev => {
1178 let at = buf.position_to_char(pos).ok()?;
1179 let step = self
1180 .search
1181 .repeat(at, matches!(motion, Motion::SearchPrev))?;
1182 buf.char_to_position(step.target.start)
1183 }
1184 Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
1185 Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
1186 Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
1187 Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
1188 Motion::LineStart => Position::new(pos.line, 0),
1189 Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
1190 Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
1191 Motion::DocStart => Position::ZERO,
1192 Motion::DocEnd => Position::new(
1193 buf.line_count().saturating_sub(1),
1194 buf.line_len_chars(buf.line_count().saturating_sub(1)),
1195 ),
1196 Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
1197 Motion::WordStartPrev => word_prev(buf, pos),
1198 Motion::PageDown | Motion::HalfPageDown => {
1199 Position::new(pos.line.saturating_add(10), pos.column)
1200 }
1201 Motion::PageUp | Motion::HalfPageUp => {
1202 Position::new(pos.line.saturating_sub(10), pos.column)
1203 }
1204 Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
1205 Motion::ForwardSexp
1208 | Motion::BackwardSexp
1209 | Motion::UpList
1210 | Motion::DownList
1211 | Motion::BeginningOfDefun
1212 | Motion::EndOfDefun
1213 | Motion::BeginningOfSexp
1214 | Motion::EndOfSexp => pos,
1215 })
1216 }
1217
1218 fn apply_motion(&mut self, motion: Motion) {
1219 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1227 self.jump_search(matches!(motion, Motion::SearchPrev));
1228 return;
1229 }
1230 let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
1231 return;
1232 };
1233 self.set_cursor(pos);
1236 }
1237
1238 fn apply_operator(&mut self, op: Operator, motion: Motion) {
1245 let from = self.cursor();
1246 let Some(to) = self.resolve_motion(from, motion) else {
1247 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1252 if self.search.pattern().is_none() {
1253 self.messages
1254 .push("E35: No previous regular expression".to_string());
1255 } else {
1256 self.report_pattern_not_found();
1257 }
1258 }
1259 return;
1260 };
1261 self.apply_operator_to(op, to);
1262 }
1263
1264 fn apply_operator_to(&mut self, op: Operator, to: Position) {
1271 let from = self.cursor();
1272 self.apply_operator_over(
1273 op,
1274 Range {
1275 start: from,
1276 end: to,
1277 },
1278 );
1279 }
1280
1281 fn apply_operator_over(&mut self, op: Operator, range: Range) {
1288 let range = range.normalized();
1289 if range.is_empty() {
1290 return;
1291 }
1292 let text = self
1294 .buffers
1295 .get(self.active)
1296 .and_then(|buf| buf.slice(range).ok());
1297 if op.leaves_register() {
1298 if let Some(t) = &text {
1299 self.register = Some(t.clone());
1300 }
1301 }
1302 match op {
1303 Operator::Delete | Operator::Change => {
1306 if let Some(buf) = self.buffers.get_mut(self.active) {
1307 let _ = buf.apply(&Edit::delete(range));
1308 }
1309 self.set_cursor(range.start);
1310 if op == Operator::Change {
1311 self.modal.enter(Mode::Insert);
1312 }
1313 }
1314 Operator::Yank => {
1317 self.set_cursor(range.start);
1318 }
1319 _ => {
1323 self.messages
1324 .push("operator not yet implemented".to_owned());
1325 }
1326 }
1327 }
1328
1329 #[must_use]
1332 pub fn register(&self) -> Option<&str> {
1333 self.register.as_deref()
1334 }
1335
1336 fn insert_char(&mut self, c: char) {
1337 if self.modal.mode() == Mode::Command {
1338 if self.search.is_prompting() {
1342 self.search.push(c);
1343 self.modal.push_minibuffer(c);
1344 self.preview_search();
1345 } else {
1346 self.modal.push_minibuffer(c);
1347 }
1348 return;
1349 }
1350 let cursor = self.cursor();
1351 let Some(buf) = self.buffers.get_mut(self.active) else {
1352 return;
1353 };
1354 let edit = Edit::insert(cursor, c.to_string());
1355 if buf.apply(&edit).is_ok() {
1356 let next = if c == '\n' {
1357 Position::new(cursor.line.saturating_add(1), 0)
1358 } else {
1359 cursor.shift_right(1)
1360 };
1361 self.set_cursor(next);
1364 }
1365 }
1366
1367 fn prompt_backspace(&mut self) -> bool {
1371 if self.modal.mode() != Mode::Command {
1372 return false;
1373 }
1374 if self.search.is_prompting() {
1375 if self.search.backspace() {
1377 self.modal.clear_minibuffer();
1378 self.modal.enter(Mode::Normal);
1379 return true;
1380 }
1381 }
1382 self.modal.pop_minibuffer();
1383 true
1384 }
1385
1386 fn apply_edit(&mut self, _edit: &Edit) {
1387 }
1391
1392 fn submit_command(&mut self) {
1393 let line = self.modal.minibuffer().to_string();
1397 self.modal.escape();
1398 let (name, args) = parse_command_line(&line);
1399 if name.is_empty() {
1400 return;
1401 }
1402 self.run_command(&name, &args);
1403 }
1404
1405 fn run_command(&mut self, name: &str, args: &[String]) {
1406 if matches!(name, "noh" | "nohl" | "nohlsearch") {
1412 self.search.clear_highlight();
1413 return;
1414 }
1415 if self.plugin_host.pending() > 0 {
1421 let pending = self.plugin_host.pending_for_command(name);
1422 for src in pending {
1423 self.apply_plugin_entry(&src);
1424 }
1425 }
1426 let active = Some(self.active);
1427 let mut quit = false;
1428 {
1429 let mut ctx = EditContext {
1430 buffers: &mut self.buffers,
1431 active,
1432 state: &mut self.modal,
1433 quit_requested: &mut quit,
1434 };
1435 let _ = self.commands.run(name, &mut ctx, args);
1436 }
1437 if quit {
1440 self.quit_requested = true;
1441 }
1442 }
1443
1444 #[must_use]
1449 pub fn snapshot(&self) -> EditorSnapshot {
1450 let current_line = self
1451 .buffers
1452 .get(self.active)
1453 .and_then(|b| b.line(self.cursor().line))
1454 .map(|s| s.trim_end_matches('\n').to_string())
1455 .unwrap_or_default();
1456 let buffer_name = self
1457 .buffers
1458 .get(self.active)
1459 .and_then(|b| b.path.as_ref())
1460 .map(|p| p.display().to_string())
1461 .unwrap_or_else(|| "[scratch]".to_string());
1462 EditorSnapshot {
1463 cursor_line: i64::from(self.cursor().line),
1464 cursor_column: i64::from(self.cursor().column),
1465 current_line,
1466 mode: self.modal.mode().as_str().to_string(),
1467 buffer_name,
1468 }
1469 }
1470
1471 pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
1487 let mut host = EscribaHost::with_snapshot(self.snapshot());
1488 let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
1489 vm.eval(src, &mut host)?;
1490 let effects = host.take_effects();
1491 self.apply_host_effects(effects);
1492 Ok(())
1493 }
1494
1495 pub fn apply_host_effects(&mut self, effects: Vec<HostEffect>) {
1499 for eff in effects {
1500 match eff {
1501 HostEffect::Message(m) => self.messages.push(m),
1502 HostEffect::RunCommand { name, args } => self.run_command(&name, &args),
1503 HostEffect::SetOption { name, value } => {
1504 self.options.insert(name, value);
1505 }
1506 HostEffect::InsertText(text) => self.insert_text(&text),
1507 }
1508 }
1509 }
1510
1511 fn insert_text(&mut self, text: &str) {
1514 if text.is_empty() {
1515 return;
1516 }
1517 let cursor = self.cursor();
1518 let Some(buf) = self.buffers.get_mut(self.active) else {
1519 return;
1520 };
1521 let edit = Edit::insert(cursor, text.to_string());
1522 if buf.apply(&edit).is_ok() {
1523 let next = if let Some(nl) = text.rfind('\n') {
1524 let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
1525 let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
1526 Position::new(cursor.line + added_lines, last_line_len)
1527 } else {
1528 let n = u32::try_from(text.chars().count()).unwrap_or(0);
1529 cursor.shift_right(n)
1530 };
1531 self.set_cursor(next);
1534 }
1535 }
1536}
1537
1538fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
1539 let Some(text) = buf.line(line) else {
1540 return Position::new(line, 0);
1541 };
1542 let col = text
1543 .chars()
1544 .take_while(|c| c.is_whitespace() && *c != '\n')
1545 .count();
1546 Position::new(line, u32::try_from(col).unwrap_or(0))
1547}
1548
1549fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1550 let Some(text) = buf.line(pos.line) else {
1551 return pos;
1552 };
1553 let chars: Vec<char> = text.chars().collect();
1554 let start = pos.column as usize;
1555 let mut i = start;
1556 while i < chars.len() && !chars[i].is_whitespace() {
1557 i += 1;
1558 }
1559 while i < chars.len() && chars[i].is_whitespace() {
1560 i += 1;
1561 }
1562 if i >= chars.len() {
1563 if pos.line + 1 < buf.line_count() {
1565 return Position::new(pos.line + 1, 0);
1566 }
1567 }
1568 Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
1569}
1570
1571fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1572 let Some(text) = buf.line(pos.line) else {
1573 return pos;
1574 };
1575 let chars: Vec<char> = text.chars().collect();
1576 let mut i = (pos.column as usize).min(chars.len());
1577 while i > 0 && chars[i - 1].is_whitespace() {
1578 i -= 1;
1579 }
1580 while i > 0 && !chars[i - 1].is_whitespace() {
1581 i -= 1;
1582 }
1583 Position::new(pos.line, u32::try_from(i).unwrap_or(0))
1584}
1585
1586fn parse_command_line(line: &str) -> (String, Vec<String>) {
1587 let mut parts = line.split_whitespace();
1588 let Some(first) = parts.next() else {
1589 return (String::new(), Vec::new());
1590 };
1591 let head = first.strip_prefix(':').unwrap_or(first);
1592 let name = match head {
1593 "w" => "save",
1594 "q" => "quit",
1595 "u" => "undo",
1596 other => other,
1597 };
1598 (name.to_string(), parts.map(str::to_string).collect())
1599}
1600
1601#[cfg(test)]
1602mod tests {
1603 use super::*;
1604 use madori::event::{KeyCode, KeyEvent, Modifiers};
1605
1606 fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
1614 st.apply(&Action::SearchOpen(dir));
1615 for c in pat.chars() {
1616 st.apply(&Action::InsertChar(c));
1617 }
1618 st.apply(&Action::SubmitCommand);
1619 }
1620
1621 #[test]
1622 fn slash_search_moves_the_cursor_to_the_match() {
1623 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1624 type_search(&mut st, SearchDirection::Forward, "charlie");
1625 assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
1626 assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
1627 assert_eq!(st.search.matches().len(), 1);
1628 }
1629
1630 #[test]
1631 fn n_and_N_walk_matches_in_both_directions() {
1632 let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
1633 type_search(&mut st, SearchDirection::Forward, "foo");
1634 let first = st.cursor().line;
1635 st.apply(&Action::SearchRepeat { reverse: false });
1636 let second = st.cursor().line;
1637 assert!(second > first, "n advances ({first} -> {second})");
1638 st.apply(&Action::SearchRepeat { reverse: true });
1639 assert_eq!(st.cursor().line, first, "N comes back");
1640 }
1641
1642 #[test]
1643 fn star_searches_the_word_under_the_cursor() {
1644 let mut st = new_state_with("needle\nhaystack\nneedle\n");
1645 st.apply(&Action::SearchWord { reverse: false });
1646 assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
1647 assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
1648 }
1649
1650 #[test]
1651 fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
1652 let mut st = new_state_with("foo\nbar\nfoo\n");
1653 type_search(&mut st, SearchDirection::Forward, "foo");
1654 let matches_before = st.search.matches().len();
1655
1656 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1657 st.apply(&Action::InsertChar('z'));
1658 st.apply(&Action::ChangeMode(Mode::Normal));
1659
1660 assert!(!st.search.is_prompting(), "prompt gone");
1661 assert_eq!(
1662 st.search.pattern().unwrap().raw(),
1663 "foo",
1664 "old pattern survives"
1665 );
1666 assert_eq!(
1667 st.search.matches().len(),
1668 matches_before,
1669 "old highlights survive"
1670 );
1671 }
1672
1673 #[test]
1674 fn a_search_prompt_and_an_ex_command_are_not_confused() {
1675 let mut st = new_state_with("foo\n");
1676 st.apply(&Action::ChangeMode(Mode::Command));
1678 assert!(!st.search.is_prompting(), "`:` must not open a search");
1679 st.apply(&Action::InsertChar('w'));
1680 assert!(
1681 st.search.prompt().is_none(),
1682 "typed char went to the ex line"
1683 );
1684 }
1685
1686 #[test]
1687 fn a_missing_pattern_reports_instead_of_failing_silently() {
1688 let mut st = new_state_with("alpha\nbravo\n");
1689 type_search(&mut st, SearchDirection::Forward, "zzz");
1690 assert!(
1691 st.messages.iter().any(|m| m.contains("E486")),
1692 "must report not-found, got {:?}",
1693 st.messages
1694 );
1695 }
1696
1697 #[test]
1698 fn n_without_any_search_reports_rather_than_moving() {
1699 let mut st = new_state_with("alpha\nbravo\n");
1700 let before = st.cursor();
1701 st.apply(&Action::SearchRepeat { reverse: false });
1702 assert_eq!(st.cursor(), before, "cursor must not move");
1703 assert!(
1704 st.messages.iter().any(|m| m.contains("E35")),
1705 "got {:?}",
1706 st.messages
1707 );
1708 }
1709
1710 #[test]
1711 fn search_as_a_motion_composes_with_an_operator() {
1712 let mut st = new_state_with("alpha bravo charlie\n");
1714 type_search(&mut st, SearchDirection::Forward, "charlie");
1715 st.set_cursor(Position::new(0, 0));
1716 let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
1717 assert!(target.is_some(), "search must resolve as a motion");
1718 assert_eq!(target.unwrap().column, 12, "at `charlie`");
1719 }
1720
1721 #[test]
1722 fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
1723 let st = new_state_with("alpha bravo\n");
1726 assert!(
1727 st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
1728 .is_none()
1729 );
1730 }
1731
1732 #[test]
1733 fn clear_highlight_keeps_the_pattern_usable() {
1734 let mut st = new_state_with("foo\nbar\nfoo\n");
1735 type_search(&mut st, SearchDirection::Forward, "foo");
1736 st.apply(&Action::ClearSearchHighlight);
1737 assert!(st.search.highlights().is_empty(), "nothing lit");
1738 st.apply(&Action::SearchRepeat { reverse: false });
1739 assert!(st.search.pattern().is_some(), "but n still works");
1740 }
1741
1742 #[test]
1743 fn typing_previews_incrementally_before_commit() {
1744 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1745 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1746 for c in "charlie".chars() {
1747 st.apply(&Action::InsertChar(c));
1748 }
1749 assert_eq!(st.cursor().line, 2, "preview moved the cursor");
1751 assert!(st.search.pattern().is_none(), "but nothing is committed");
1752 }
1753
1754 #[test]
1755 fn backspace_corrects_the_prompt_and_reruns_the_preview() {
1756 let mut st = new_state_with("alpha\nbravo\n");
1757 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1758 for c in "bravox".chars() {
1759 st.apply(&Action::InsertChar(c));
1760 }
1761 assert_eq!(st.search.prompt().unwrap().text, "bravox");
1762 st.apply(&Action::PromptBackspace);
1763 assert_eq!(st.search.prompt().unwrap().text, "bravo", "typo corrected");
1764 assert_eq!(st.modal.minibuffer(), "bravo", "display stays in lockstep");
1765 assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
1766 }
1767
1768 #[test]
1769 fn backspacing_past_the_slash_closes_the_prompt() {
1770 let mut st = new_state_with("alpha\n");
1771 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1772 st.apply(&Action::InsertChar('a'));
1773 st.apply(&Action::PromptBackspace);
1774 st.apply(&Action::PromptBackspace);
1775 assert!(!st.search.is_prompting(), "prompt closed");
1776 assert_eq!(st.modal.mode(), Mode::Normal);
1777 }
1778
1779 #[test]
1780 fn noh_clears_highlights_and_keeps_the_pattern() {
1781 let mut st = new_state_with("foo\nbar\nfoo\n");
1782 type_search(&mut st, SearchDirection::Forward, "foo");
1783 assert!(!st.search.highlights().is_empty());
1784 st.run_command("noh", &[]);
1785 assert!(st.search.highlights().is_empty(), ":noh turns them off");
1786 assert!(st.search.pattern().is_some(), "but n still works");
1787 }
1788
1789 #[test]
1790 fn noh_accepts_the_vim_aliases() {
1791 for name in ["noh", "nohl", "nohlsearch"] {
1792 let mut st = new_state_with("foo\nfoo\n");
1793 type_search(&mut st, SearchDirection::Forward, "foo");
1794 st.run_command(name, &[]);
1795 assert!(st.search.highlights().is_empty(), "{name} must clear");
1796 }
1797 }
1798
1799 #[test]
1800 fn backspace_on_the_ex_line_does_not_touch_search_state() {
1801 let mut st = new_state_with("foo\n");
1802 st.apply(&Action::ChangeMode(Mode::Command));
1803 st.apply(&Action::InsertChar('w'));
1804 st.apply(&Action::InsertChar('q'));
1805 st.apply(&Action::PromptBackspace);
1806 assert_eq!(st.modal.minibuffer(), "w");
1807 assert!(st.search.prompt().is_none(), "no search was involved");
1808 }
1809
1810 #[test]
1811 fn up_arrow_recalls_the_previous_search() {
1812 let mut st = new_state_with("alpha\nbravo\n");
1813 type_search(&mut st, SearchDirection::Forward, "bravo");
1814 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1815 st.apply(&Action::PromptHistory { back: true });
1816 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1817 assert_eq!(st.modal.minibuffer(), "bravo", "display follows the prompt");
1818 }
1819
1820 #[test]
1821 fn arrowing_back_down_restores_the_half_typed_pattern() {
1822 let mut st = new_state_with("alpha\nbravo\n");
1823 type_search(&mut st, SearchDirection::Forward, "bravo");
1824 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1825 st.apply(&Action::InsertChar('a'));
1826 st.apply(&Action::PromptHistory { back: true });
1827 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1828 st.apply(&Action::PromptHistory { back: false });
1829 assert_eq!(
1830 st.search.prompt().unwrap().text,
1831 "a",
1832 "the draft comes back"
1833 );
1834 assert_eq!(st.modal.minibuffer(), "a");
1835 }
1836
1837 #[test]
1838 fn history_arrows_do_nothing_on_the_ex_line() {
1839 let mut st = new_state_with("alpha\n");
1840 st.apply(&Action::ChangeMode(Mode::Command));
1841 st.apply(&Action::InsertChar('w'));
1842 st.apply(&Action::PromptHistory { back: true });
1843 assert_eq!(st.modal.minibuffer(), "w", "ex line untouched");
1844 }
1845
1846 fn new_state_with(text: &str) -> EditorState {
1847 let mut bufs = BufferSet::new();
1848 let id = bufs.scratch(text);
1849 EditorState::new_with_buffer(bufs, id)
1850 }
1851
1852 #[test]
1858 fn edit_gen_advances_on_applied_action_not_on_read() {
1859 let mut s = new_state_with("hello\nworld\n");
1860 let g0 = s.edit_gen();
1861 s.apply(&Action::InsertChar('X'));
1862 assert_ne!(
1863 s.edit_gen(),
1864 g0,
1865 "an applied action must advance the refresh generation",
1866 );
1867 let g1 = s.edit_gen();
1869 assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
1870 }
1871
1872 #[test]
1877 fn damage_tracks_edit_scope_and_drains() {
1878 let mut s = new_state_with("hello\nworld\n");
1879 assert!(s.damage().is_none(), "a fresh state has no damage");
1880
1881 s.apply(&Action::InsertChar('X')); assert_eq!(
1883 s.damage(),
1884 Damage::Lines { from: 0, to: 0 },
1885 "a local edit damages just its line",
1886 );
1887
1888 let drained = s.take_damage();
1889 assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
1890 assert!(s.damage().is_none(), "take_damage drains to None");
1891
1892 s.apply(&Action::InsertChar('\n')); assert_eq!(
1894 s.damage(),
1895 Damage::Lines {
1896 from: 0,
1897 to: u32::MAX,
1898 },
1899 "a line-count change damages to end-of-document",
1900 );
1901 }
1902
1903 fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
1907 let mut s = new_state_with(text);
1908 for w in &mut s.layout.windows {
1909 w.viewport.visible_lines = vis_lines;
1910 w.viewport.visible_columns = vis_cols;
1911 }
1912 s
1913 }
1914
1915 fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
1920 let w = s.layout.active_window().expect("active window");
1921 let v = w.viewport;
1922 let c = s.cursor();
1923 assert!(
1924 v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
1925 "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
1926 c.line,
1927 v.top_line,
1928 v.top_line + v.visible_lines,
1929 );
1930 assert!(
1931 v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
1932 "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
1933 c.column,
1934 v.left_column,
1935 v.left_column + v.visible_columns,
1936 );
1937 }
1938
1939 fn press(kc: KeyCode) -> AppEvent {
1940 AppEvent::Key(KeyEvent {
1941 key: kc,
1942 pressed: true,
1943 modifiers: Modifiers::default(),
1944 text: None,
1945 })
1946 }
1947
1948 fn line0_len(s: &EditorState) -> u32 {
1951 s.buffers.get(s.active).unwrap().line_len_chars(0)
1952 }
1953
1954 #[test]
1955 fn delete_to_line_end_clears_line_and_fills_register() {
1956 let mut s = new_state_with("hello world");
1957 s.apply(&Action::ApplyOperator {
1958 op: Operator::Delete,
1959 motion: Motion::LineEnd,
1960 });
1961 assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
1962 assert_eq!(
1963 s.register(),
1964 Some("hello world"),
1965 "delete fills the register"
1966 );
1967 assert_eq!(
1968 s.cursor(),
1969 Position::ZERO,
1970 "cursor lands at the range start"
1971 );
1972 }
1973
1974 #[test]
1975 fn delete_over_right_motion_removes_one_char() {
1976 let mut s = new_state_with("abc");
1977 s.apply(&Action::ApplyOperator {
1978 op: Operator::Delete,
1979 motion: Motion::Right,
1980 });
1981 assert_eq!(
1982 s.buffers.get(s.active).unwrap().line(0).as_deref(),
1983 Some("bc")
1984 );
1985 assert_eq!(s.register(), Some("a"));
1986 }
1987
1988 #[test]
1989 fn change_to_line_end_deletes_and_enters_insert() {
1990 let mut s = new_state_with("hello world");
1991 assert_eq!(s.modal.mode(), Mode::Normal);
1992 s.apply(&Action::ApplyOperator {
1993 op: Operator::Change,
1994 motion: Motion::LineEnd,
1995 });
1996 assert_eq!(line0_len(&s), 0, "c$ deletes the range");
1997 assert_eq!(
1998 s.modal.mode(),
1999 Mode::Insert,
2000 "change enters Insert to type the replacement"
2001 );
2002 assert_eq!(
2003 s.register(),
2004 Some("hello world"),
2005 "change fills the register"
2006 );
2007 }
2008
2009 #[test]
2010 fn yank_to_line_end_fills_register_without_mutating() {
2011 let mut s = new_state_with("hello world");
2012 s.apply(&Action::ApplyOperator {
2013 op: Operator::Yank,
2014 motion: Motion::LineEnd,
2015 });
2016 assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
2017 assert_eq!(s.register(), Some("hello world"), "yank fills the register");
2018 assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
2019 }
2020
2021 #[test]
2022 fn resolve_motion_is_the_shared_target_for_move_and_operator() {
2023 let mut s = new_state_with("hello world");
2027 let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
2028 assert_eq!(target, Position::new(0, 11));
2029 s.apply_motion(Motion::LineEnd);
2030 assert_eq!(
2031 s.cursor(),
2032 target,
2033 "the move path resolves the same target the operator uses"
2034 );
2035 }
2036
2037 #[test]
2038 fn empty_motion_range_is_a_no_op() {
2039 let mut s = new_state_with("abc");
2042 s.apply(&Action::ApplyOperator {
2043 op: Operator::Delete,
2044 motion: Motion::LineStart,
2045 });
2046 assert_eq!(
2047 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2048 Some("abc")
2049 );
2050 assert_eq!(s.register(), None);
2051 }
2052
2053 #[test]
2054 fn operator_then_motion_composes_through_the_pending_fsm() {
2055 let mut s = new_state_with("hello world");
2059 s.apply(&Action::Operator(Operator::Delete));
2060 assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
2061 s.apply(&Action::Move(Motion::LineEnd));
2062 assert_eq!(
2063 line0_len(&s),
2064 0,
2065 "d then $ composes d$ and deletes the line"
2066 );
2067 assert_eq!(s.register(), Some("hello world"));
2068 }
2069
2070 #[test]
2071 fn change_operator_through_fsm_enters_insert() {
2072 let mut s = new_state_with("hello world");
2073 s.apply(&Action::Operator(Operator::Change));
2074 s.apply(&Action::Move(Motion::LineEnd));
2075 assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
2076 }
2077
2078 #[test]
2079 fn lone_motion_after_no_operator_just_moves() {
2080 let mut s = new_state_with("hello world");
2082 s.apply(&Action::Move(Motion::LineEnd));
2083 assert_eq!(s.cursor(), Position::new(0, 11));
2084 assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
2085 }
2086
2087 #[test]
2088 fn counted_operator_deletes_count_times() {
2089 let mut s = new_state_with("abcdef");
2093 s.apply_counted(&Action::Operator(Operator::Delete), 3);
2094 assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
2095 s.apply(&Action::Move(Motion::Right));
2096 assert_eq!(
2097 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2098 Some("def")
2099 );
2100 }
2101
2102 #[test]
2103 fn operator_and_motion_counts_multiply_end_to_end() {
2104 let mut s = new_state_with("abcdefgh");
2106 s.apply_counted(&Action::Operator(Operator::Delete), 2);
2107 s.apply_counted(&Action::Move(Motion::Right), 3);
2108 assert_eq!(
2109 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2110 Some("gh")
2111 );
2112 }
2113
2114 #[test]
2115 fn bare_counted_motion_still_repeats_no_regression() {
2116 let mut s = new_state_with("a\nb\nc\nd\ne");
2119 s.apply_counted(&Action::Move(Motion::Down), 3);
2120 assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
2121 }
2122
2123 struct SpacedClock(std::time::Instant);
2129 impl SpacedClock {
2130 fn new() -> Self {
2131 Self(std::time::Instant::now())
2132 }
2133 fn next(&mut self) -> std::time::Instant {
2134 self.0 += std::time::Duration::from_secs(1);
2135 self.0
2136 }
2137 }
2138
2139 #[test]
2140 fn hjkl_moves_cursor() {
2141 let mut s = new_state_with("hello\nworld");
2142 s.tick(&press(KeyCode::Char('l')));
2143 assert_eq!(s.cursor().column, 1);
2144 s.tick(&press(KeyCode::Char('j')));
2145 assert_eq!(s.cursor().line, 1);
2146 s.tick(&press(KeyCode::Char('h')));
2147 assert_eq!(s.cursor().column, 0);
2148 }
2149
2150 #[test]
2151 fn insert_mode_inserts_chars() {
2152 let mut s = new_state_with("");
2153 s.tick(&press(KeyCode::Char('i')));
2154 assert_eq!(s.modal.mode(), Mode::Insert);
2155 s.tick(&press(KeyCode::Char('h')));
2156 s.tick(&press(KeyCode::Char('i')));
2157 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
2158 assert_eq!(s.cursor().column, 2);
2159 }
2160
2161 #[test]
2162 fn esc_returns_to_normal() {
2163 let mut s = new_state_with("");
2164 s.tick(&press(KeyCode::Char('i')));
2165 s.tick(&press(KeyCode::Escape));
2166 assert_eq!(s.modal.mode(), Mode::Normal);
2167 }
2168
2169 #[test]
2170 fn count_prefix_repeats_motion() {
2171 let mut s = new_state_with("abcdefghij");
2172 s.tick(&press(KeyCode::Char('5')));
2173 s.tick(&press(KeyCode::Char('l')));
2174 assert_eq!(s.cursor().column, 5);
2175 }
2176
2177 #[test]
2178 fn close_event_requests_quit() {
2179 let mut s = new_state_with("");
2180 s.tick(&AppEvent::CloseRequested);
2181 assert!(s.quit_requested);
2182 }
2183
2184 #[test]
2185 fn word_next_jumps_past_whitespace() {
2186 let mut s = new_state_with("foo bar baz");
2187 let mut clk = SpacedClock::new();
2190 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2191 assert_eq!(s.cursor().column, 4);
2192 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2193 assert_eq!(s.cursor().column, 8);
2194 }
2195
2196 #[test]
2199 fn leader_sequence_holds_then_resolves() {
2200 let mut s = new_state_with("a\nbb\nccc");
2201 s.keymap.bind_sequence(
2202 Mode::Normal,
2203 vec![Key::Char(','), Key::Char('g')],
2204 Action::Move(Motion::DocEnd),
2205 "doc end",
2206 );
2207 s.on_key(&Key::Char(','));
2209 assert_eq!(s.pending_keys, vec![Key::Char(',')]);
2210 assert_eq!(s.cursor(), Position::ZERO);
2211 s.on_key(&Key::Char('g'));
2213 assert!(s.pending_keys.is_empty());
2214 assert_eq!(s.cursor().line, 2);
2215 }
2216
2217 #[test]
2218 fn two_key_gg_jumps_doc_start() {
2219 let mut s = new_state_with("a\nbb\nccc");
2220 s.keymap.bind_sequence(
2221 Mode::Normal,
2222 vec![Key::Char('g'), Key::Char('g')],
2223 Action::Move(Motion::DocStart),
2224 "doc start",
2225 );
2226 let mut clk = SpacedClock::new();
2227 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2228 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2229 assert_eq!(s.cursor().line, 2);
2230 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2232 s.on_key(&Key::Char('g')); assert_eq!(s.cursor(), Position::ZERO);
2234 }
2235
2236 #[test]
2237 fn broken_sequence_aborts_and_clears_pending() {
2238 let mut s = new_state_with("hello");
2239 s.keymap.bind_sequence(
2240 Mode::Normal,
2241 vec![Key::Char('g'), Key::Char('g')],
2242 Action::Move(Motion::DocEnd),
2243 "doc end",
2244 );
2245 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2247 s.on_key(&Key::Char('x')); assert!(s.pending_keys.is_empty());
2249 assert_eq!(s.cursor(), Position::ZERO);
2250 }
2251
2252 #[test]
2253 fn single_binding_wins_over_sequence_prefix() {
2254 let mut s = new_state_with("abcde");
2258 let mut clk = SpacedClock::new();
2259 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2260 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2261 assert_eq!(s.cursor().column, 2);
2262 s.keymap.bind_sequence(
2263 Mode::Normal,
2264 vec![Key::Char('h'), Key::Char('z')],
2265 Action::Move(Motion::DocEnd),
2266 "shadowed",
2267 );
2268 s.on_key(&Key::Char('h'));
2269 assert!(s.pending_keys.is_empty(), "single binding should not pend");
2270 assert_eq!(s.cursor().column, 1, "h moved left immediately");
2271 }
2272
2273 #[test]
2276 fn lisp_set_option_writes_live_options() {
2277 let mut s = new_state_with("");
2278 s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
2279 assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
2280 }
2281
2282 #[test]
2283 fn lisp_insert_modifies_buffer_and_advances_cursor() {
2284 let mut s = new_state_with("");
2285 s.run_lisp(r#"(insert "abc")"#).unwrap();
2286 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2287 assert_eq!(s.cursor(), Position::new(0, 3));
2288 }
2289
2290 #[test]
2291 fn lisp_message_appends_to_messages() {
2292 let mut s = new_state_with("");
2293 s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
2294 assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
2295 }
2296
2297 #[test]
2298 fn lisp_reads_snapshot_and_branches_to_effect() {
2299 let mut s = new_state_with("one\ntwo\nthree");
2302 s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
2304 .unwrap();
2305 assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
2306 }
2307
2308 #[test]
2309 fn lisp_run_command_effect_drives_registry() {
2310 let mut s = new_state_with("");
2314 s.run_lisp(r#"(insert "abc")"#).unwrap();
2315 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2316 s.run_lisp(r#"(run-command "undo")"#).unwrap();
2317 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
2318 }
2319
2320 #[test]
2321 fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
2322 let mut s = new_state_with("");
2327 s.run_lisp(r#"(run-command "quit")"#).unwrap();
2328 assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
2329 assert_eq!(
2330 s.modal.minibuffer(),
2331 "",
2332 "quit must not pollute any command line — Normal mode has no minibuffer",
2333 );
2334 }
2335
2336 #[test]
2339 fn lazy_plugin_activates_on_command_trigger() {
2340 let mut s = new_state_with("");
2344 s.register_lazy_plugin(
2345 "user-lazy",
2346 vec![LazyTrigger::Command("LazyGo".into())],
2347 r#"(defoption :name "lazy-loaded" :value "yes")
2348 (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
2349 );
2350 assert_eq!(s.plugin_host.pending(), 1);
2351 assert!(
2352 s.options.get("lazy-loaded").is_none(),
2353 "entry not applied yet"
2354 );
2355
2356 s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
2358
2359 assert_eq!(
2360 s.options.get("lazy-loaded").map(String::as_str),
2361 Some("yes"),
2362 "the command trigger applied the plugin's entry",
2363 );
2364 assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
2365 }
2366
2367 #[test]
2368 fn lazy_plugin_activates_on_filetype() {
2369 let mut s = new_state_with("");
2370 s.register_lazy_plugin(
2371 "user-rust",
2372 vec![LazyTrigger::FileType("rust".into())],
2373 r#"(defoption :name "rust-plugin" :value "on")"#,
2374 );
2375 let n = s.activate_filetype_plugins("rust");
2376 assert_eq!(n, 1);
2377 assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
2378 assert_eq!(s.activate_filetype_plugins("rust"), 0);
2380 }
2381
2382 #[test]
2383 fn cached_vm_serves_multiple_run_lisp_calls() {
2384 let mut s = new_state_with("");
2385 s.run_lisp(r#"(message "one")"#).unwrap();
2386 assert!(
2387 s.lisp_vm.is_some(),
2388 "VM should be cached after first run_lisp"
2389 );
2390 s.run_lisp(r#"(message "two")"#).unwrap();
2391 assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
2392 }
2393
2394 #[test]
2395 fn lisp_define_persists_across_run_lisp_calls() {
2396 let mut s = new_state_with("");
2399 s.run_lisp(r#"(define greeting "hi")"#).unwrap();
2400 s.run_lisp(r#"(message greeting)"#).unwrap();
2401 assert_eq!(s.messages, vec!["hi".to_string()]);
2402 }
2403
2404 #[test]
2405 fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
2406 let mut s = new_state_with("");
2410 s.run_lisp(
2411 r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
2412 )
2413 .unwrap();
2414 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
2415 assert_eq!(
2416 s.options.get("col").map(String::as_str),
2417 Some("stale-zero"),
2418 "cursor-column within the same call reads the pre-eval snapshot",
2419 );
2420 s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
2423 .unwrap();
2424 assert_eq!(
2425 s.options.get("col2").map(String::as_str),
2426 Some("live-two"),
2427 "a later call sees the refreshed snapshot",
2428 );
2429 }
2430
2431 #[test]
2432 fn insert_text_effect_multiline_lands_cursor_on_last_line() {
2433 let mut s = new_state_with("");
2434 s.apply_host_effects(vec![HostEffect::InsertText("foo\nbar".to_string())]);
2435 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
2436 assert_eq!(s.cursor(), Position::new(1, 3));
2437 }
2438
2439 #[test]
2440 fn visual_mode_sequence_resolves() {
2441 let mut s = new_state_with("abc");
2442 s.modal.enter(Mode::Visual);
2443 s.keymap.bind_sequence(
2444 Mode::Visual,
2445 vec![Key::Char('g'), Key::Char('e')],
2446 Action::Move(Motion::DocEnd),
2447 "ge",
2448 );
2449 s.on_key(&Key::Char('g'));
2450 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2451 s.on_key(&Key::Char('e'));
2452 assert!(s.pending_keys.is_empty());
2453 assert_eq!(
2454 s.cursor().column,
2455 3,
2456 "ge resolved to doc-end in visual mode"
2457 );
2458 }
2459
2460 #[test]
2461 fn sequence_abort_with_bound_breaking_key_redispatches() {
2462 let mut s = new_state_with("abcde");
2465 s.keymap.bind_sequence(
2466 Mode::Normal,
2467 vec![Key::Char('g'), Key::Char('g')],
2468 Action::Move(Motion::DocEnd),
2469 "gg",
2470 );
2471 s.on_key(&Key::Char('g'));
2472 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2473 s.on_key(&Key::Char('l'));
2474 assert!(s.pending_keys.is_empty());
2475 assert_eq!(
2476 s.cursor().column,
2477 1,
2478 "the breaking key l should re-dispatch as move-right",
2479 );
2480 }
2481
2482 #[test]
2485 fn viewport_contains_cursor_after_every_op() {
2486 let mut s = new_state_small_viewport("", 5, 10);
2490 assert_cursor_in_viewport(&s, "initial");
2491
2492 s.tick(&press(KeyCode::Char('i')));
2495 assert_eq!(s.modal.mode(), Mode::Insert);
2496 for line in 0..30u32 {
2497 for c in "line".chars() {
2498 s.tick(&press(KeyCode::Char(c)));
2499 assert_cursor_in_viewport(&s, "typing chars");
2500 }
2501 s.tick(&press(KeyCode::Enter));
2502 assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
2503 }
2504
2505 for i in 0..200u32 {
2508 s.tick(&press(KeyCode::Char('x')));
2509 assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
2510 }
2511
2512 s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
2514 assert_cursor_in_viewport(&s, "insert_text multiline");
2515
2516 s.tick(&press(KeyCode::Escape));
2518 assert_eq!(s.modal.mode(), Mode::Normal);
2519 for m in [
2520 Motion::DocStart,
2521 Motion::DocEnd,
2522 Motion::Down,
2523 Motion::Down,
2524 Motion::Up,
2525 Motion::Right,
2526 Motion::Right,
2527 Motion::Left,
2528 Motion::LineEnd,
2529 Motion::LineStart,
2530 Motion::GotoLine(1),
2531 Motion::GotoLine(40),
2532 Motion::PageDown,
2533 Motion::PageUp,
2534 ] {
2535 s.apply_motion(m);
2536 assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
2537 }
2538
2539 for i in 0..50u32 {
2542 s.apply(&Action::Undo);
2543 assert_cursor_in_viewport(&s, &format!("undo {i}"));
2544 }
2545 for i in 0..50u32 {
2547 s.apply(&Action::Redo);
2548 assert_cursor_in_viewport(&s, &format!("redo {i}"));
2549 }
2550 }
2551
2552 #[test]
2553 fn insert_at_eof_keeps_cursor_in_bounds() {
2554 let mut s = new_state_small_viewport("abc", 5, 10);
2557 s.apply_motion(Motion::DocEnd);
2558 s.tick(&press(KeyCode::Char('i')));
2559 s.tick(&press(KeyCode::Char('d')));
2560 let buf = s.buffers.get(s.active).unwrap();
2561 let clamped = buf.clamp(s.cursor());
2562 assert_eq!(
2563 s.cursor(),
2564 clamped,
2565 "cursor must be clamped in-bounds at EOF"
2566 );
2567 assert_cursor_in_viewport(&s, "insert at eof");
2568 }
2569
2570 #[test]
2571 fn count_prefix_then_sequence_repeats() {
2572 let mut s = new_state_with("a\nb\nc\nd\ne");
2574 s.keymap.bind_sequence(
2575 Mode::Normal,
2576 vec![Key::Char('g'), Key::Char('j')],
2577 Action::Move(Motion::Down),
2578 "gj",
2579 );
2580 s.on_key(&Key::Char('2'));
2581 s.on_key(&Key::Char('g'));
2582 s.on_key(&Key::Char('j'));
2583 assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
2584 }
2585
2586 #[test]
2589 fn held_key_repeat_storm_is_debounced_in_normal_mode() {
2590 let mut s = new_state_with(&"x\n".repeat(40));
2596 let t0 = std::time::Instant::now();
2597 let mut delivered = 0u32;
2598 for i in 0..20u32 {
2599 let before = s.cursor().line;
2600 s.tick_at(
2601 &press(KeyCode::Char('j')),
2602 t0 + std::time::Duration::from_millis(u64::from(i) * 50),
2603 );
2604 if s.cursor().line != before {
2605 delivered += 1;
2606 }
2607 }
2608 assert!(
2611 (10..=14).contains(&delivered),
2612 "expected the storm debounced to ~13 moves, got {delivered}",
2613 );
2614 assert!(
2615 delivered < 20,
2616 "the gate must drop SOME storm ticks, not pass all 20",
2617 );
2618 }
2619
2620 #[test]
2621 fn spaced_intentional_taps_all_pass() {
2622 let mut s = new_state_with(&"x\n".repeat(10));
2625 let t0 = std::time::Instant::now();
2626 for i in 0..5u32 {
2627 s.tick_at(
2628 &press(KeyCode::Char('j')),
2629 t0 + std::time::Duration::from_millis(u64::from(i) * 100),
2631 );
2632 }
2633 assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
2634 }
2635
2636 #[test]
2637 fn distinct_keys_have_independent_clocks() {
2638 let mut s = new_state_with("abc\ndef\nghi");
2641 let t = std::time::Instant::now();
2642 s.tick_at(&press(KeyCode::Char('j')), t);
2643 s.tick_at(
2645 &press(KeyCode::Char('j')),
2646 t + std::time::Duration::from_millis(10),
2647 );
2648 assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
2649 s.tick_at(
2651 &press(KeyCode::Char('l')),
2652 t + std::time::Duration::from_millis(10),
2653 );
2654 assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
2655 }
2656
2657 #[test]
2660 fn cursor_home_preserves_single_cursor_behavior() {
2661 let mut s = new_state_with("hello\nworld\nthere");
2666 assert_eq!(s.cursor(), Position::ZERO);
2667 assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
2668
2669 s.apply_motion(Motion::Down);
2670 s.apply_motion(Motion::Right);
2671 s.apply_motion(Motion::Right);
2672 assert_eq!(s.cursor(), Position::new(1, 2));
2673 assert_eq!(s.cursors.count(), 1);
2675
2676 let w = s.layout.active_window().unwrap();
2678 assert!(w.viewport.top_line <= s.cursor().line);
2679 }
2680
2681 #[test]
2682 fn insert_mode_is_ungated_so_repeat_typing_works() {
2683 let mut s = new_state_with("");
2687 s.tick(&press(KeyCode::Char('i')));
2688 assert_eq!(s.modal.mode(), Mode::Insert);
2689 let t = std::time::Instant::now();
2690 for _ in 0..10 {
2691 s.tick_at(&press(KeyCode::Char('x')), t);
2692 }
2693 assert_eq!(
2694 s.buffers.get(s.active).unwrap().to_string(),
2695 "xxxxxxxxxx",
2696 "insert-mode repeat typing is ungated",
2697 );
2698 }
2699}