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_repeat_storm_candidate(key: &Key) -> bool {
163 matches!(
164 key,
165 Key::Char('h')
169 | Key::Char('j')
170 | Key::Char('k')
171 | Key::Char('l')
172 | Key::Left
173 | Key::Right
174 | Key::Up
175 | Key::Down
176 )
177}
178
179enum CommitOutcome {
193 Landed {
195 origin: usize,
196 step: escriba_search::Step,
197 },
198 NotFound,
200 NoPrevious,
202 NoPrompt,
204}
205
206#[derive(Debug, Clone)]
208struct LastChange {
209 action: Action,
211 count: u32,
213 inserted: String,
215}
216
217impl EditorState {
218 pub fn new_with_buffer(initial: BufferSet, active: BufferId) -> Self {
220 let window = Window {
221 id: WindowId(1),
222 buffer_id: active,
223 viewport: Viewport {
224 top_line: 0,
225 left_column: 0,
226 visible_lines: 40,
227 visible_columns: 160,
228 },
229 rect: Rect {
230 x: 0,
231 y: 0,
232 width: 1200,
233 height: 800,
234 },
235 };
236 Self {
237 buffers: initial,
238 modal: ModalState::new(),
239 search: SearchState::new(escriba_search::CaseMode::Smart),
240 search_at: None,
241 last_change: None,
242 recording_insert: false,
243 jumps: JumpList::new(),
244 keymap: Keymap::default_vim(),
245 commands: CommandRegistry::default_set(),
246 layout: Layout::single(window),
247 active,
248 cursors: Cursors::single(Position::ZERO),
249 quit_requested: false,
250 register: None,
251 op_pending: zenmai::Stateful::new(OpState::Resting),
252 messages: Vec::new(),
253 options: HashMap::new(),
254 lisp_vm: None,
255 pending_keys: Vec::new(),
256 repeat_gate: KeyRepeatGate::new(),
257 plugin_host: PluginHost::default(),
258 edit_gen: EditGen::default(),
259 damage: Damage::None,
260 }
261 }
262
263 #[must_use]
267 pub fn edit_gen(&self) -> EditGen {
268 self.edit_gen
269 }
270
271 fn bump_gen(&mut self) {
273 self.edit_gen = self.edit_gen.next();
274 }
275
276 #[must_use]
278 pub fn damage(&self) -> Damage {
279 self.damage
280 }
281
282 pub fn take_damage(&mut self) -> Damage {
286 std::mem::replace(&mut self.damage, Damage::None)
287 }
288
289 fn active_line_count(&self) -> u32 {
292 self.buffers
293 .get(self.active)
294 .map_or(0, escriba_buffer::Buffer::line_count)
295 }
296
297 pub fn register_lazy_plugin(
303 &mut self,
304 name: impl Into<String>,
305 triggers: Vec<LazyTrigger>,
306 entry_src: impl Into<String>,
307 ) {
308 self.plugin_host.register(name, triggers, entry_src);
309 }
310
311 fn apply_plugin_entry(&mut self, entry_src: &str) -> usize {
317 let Ok(plan) = escriba_lisp::apply_source(entry_src) else {
318 return 0;
319 };
320 let cmd = escriba_lisp::apply_plan_to_commands(&plan, &mut self.commands);
321 escriba_lisp::apply_plan_to_options(&plan, &mut self.options);
322 if let Some(value) = self.options.get("mapleader") {
323 if let Some(key) = escriba_lisp::parse_leader_key(value) {
324 self.keymap.set_leader(key);
325 }
326 }
327 let km = escriba_lisp::apply_plan_to_keymap(&plan, &mut self.keymap);
328 (cmd.registered + km.keybinds_applied) as usize
329 }
330
331 pub fn activate_filetype_plugins(&mut self, filetype: &str) -> usize {
335 let pending = self.plugin_host.pending_for_filetype(filetype);
336 let n = pending.len();
337 for src in pending {
338 self.apply_plugin_entry(&src);
339 }
340 n
341 }
342
343 pub fn activate_event_plugins(&mut self, event: &str) -> usize {
346 let pending = self.plugin_host.pending_for_event(event);
347 let n = pending.len();
348 for src in pending {
349 self.apply_plugin_entry(&src);
350 }
351 n
352 }
353
354 pub fn tick(&mut self, event: &AppEvent) {
359 self.tick_at(event, Instant::now());
360 }
361
362 pub fn tick_at(&mut self, event: &AppEvent, now: Instant) {
366 match translate_app_event(event) {
367 InputOutcome::Key(k) => {
368 if self.gate_key(&k, now) {
369 self.on_key(&k);
370 }
371 }
372 InputOutcome::Resized { width, height } => {
373 if let Some(w) = self
374 .layout
375 .windows
376 .iter_mut()
377 .find(|w| w.id == self.layout.active)
378 {
379 w.rect.width = width;
380 w.rect.height = height;
381 }
382 self.damage = self.damage.join(Damage::Viewport);
383 self.bump_gen();
384 }
385 InputOutcome::Quit => self.quit_requested = true,
386 InputOutcome::Focus(_) | InputOutcome::None => {}
387 }
388 }
389
390 fn gate_key(&mut self, key: &Key, now: Instant) -> bool {
400 match self.modal.mode() {
401 Mode::Normal | Mode::Visual | Mode::VisualLine => {
402 if is_repeat_storm_candidate(key) {
408 return self.repeat_gate.try_pass_at(*key, now);
409 }
410 true
411 }
412 Mode::Insert | Mode::Command => true,
413 }
414 }
415
416 pub fn on_key(&mut self, key: &Key) {
418 match self.step_sequence(key) {
422 SeqStep::Pending => return,
423 SeqStep::Resolved(action) => {
424 let count = self.modal.pending_count().unwrap_or(1);
425 self.modal.clear_count();
426 for _ in 0..count {
427 self.apply(&action);
428 if self.quit_requested {
429 return;
430 }
431 }
432 return;
433 }
434 SeqStep::Passthrough => {}
435 }
436 let counted = self.keymap.dispatch(&self.modal, key);
437 if matches!(counted.action, Action::Pending) {
439 if let Key::Char(c) = key {
440 if c.is_ascii_digit() {
441 let d = u32::from(*c as u8 - b'0');
442 self.modal.append_count(d);
443 }
444 }
445 return;
446 }
447 self.apply_counted(&counted.action, counted.count);
451 self.modal.clear_count();
453 }
454
455 fn step_sequence(&mut self, key: &Key) -> SeqStep {
467 let mode = self.modal.mode();
468 if !matches!(mode, Mode::Normal | Mode::Visual | Mode::VisualLine) {
469 return SeqStep::Passthrough;
470 }
471 if !self.pending_keys.is_empty() {
472 let mut seq = self.pending_keys.clone();
473 seq.push(key.clone());
474 if let Some(b) = self.keymap.lookup_sequence(mode, &seq) {
475 let action = b.action.clone();
476 self.pending_keys.clear();
477 return SeqStep::Resolved(action);
478 }
479 if self.keymap.is_sequence_prefix(mode, &seq) {
480 self.pending_keys = seq;
481 return SeqStep::Pending;
482 }
483 self.pending_keys.clear();
486 }
487 let start = [key.clone()];
488 if self.keymap.is_sequence_prefix(mode, &start) && self.keymap.lookup(mode, key).is_none() {
489 self.pending_keys = start.to_vec();
490 return SeqStep::Pending;
491 }
492 SeqStep::Passthrough
493 }
494
495 #[must_use]
500 pub fn cursor(&self) -> Position {
501 self.cursors.primary()
502 }
503
504 fn set_cursor(&mut self, pos: Position) {
513 let clamped = if let Some(buf) = self.buffers.get(self.active) {
514 buf.clamp(pos)
515 } else {
516 pos
517 };
518 self.cursors.set_primary(clamped);
519 if let Some(w) = self
520 .layout
521 .windows
522 .iter_mut()
523 .find(|w| w.id == self.layout.active)
524 {
525 w.viewport = w.viewport.scroll_to_contain(self.cursors.primary(), 2);
526 }
527 }
528
529 fn apply(&mut self, action: &Action) {
531 self.apply_counted(action, 1);
532 }
533
534 fn apply_counted(&mut self, action: &Action, count: u32) {
542 if matches!(action, Action::SubmitCommand) {
560 if let Some(e) = self.search.prompt_error() {
561 let mut m = String::from("E383: Invalid search string: ");
562 m.push_str(&e.to_string());
563 self.messages.push(m);
564 return;
565 }
566 }
567
568 for (resolved, times) in self.op_pending.dispatch((action.clone(), count)) {
569 for _ in 0..times {
570 self.apply_resolved(&resolved);
571 if self.quit_requested {
572 return;
573 }
574 }
575 }
576 }
577
578 #[must_use]
582 fn text_rev(&self) -> TextRev {
583 self.buffers
584 .get(self.active)
585 .map_or_else(TextRev::default, escriba_buffer::Buffer::text_rev)
586 }
587
588 fn active_text(&self) -> String {
589 self.buffers
590 .get(self.active)
591 .map(escriba_buffer::Buffer::to_string)
592 .unwrap_or_default()
593 }
594
595 fn cursor_char(&self) -> usize {
597 self.buffers
598 .get(self.active)
599 .and_then(|b| b.position_to_char(self.cursor()).ok())
600 .unwrap_or(0)
601 }
602
603 #[must_use]
611 pub fn status_model(&self) -> StatusModel<'_> {
612 let cursor = self.cursor();
613 let prompt = self.search.prompt();
614
615 let kind = match prompt.map(|p| p.direction) {
616 Some(escriba_search::Direction::Forward) => PromptKind::SearchForward,
617 Some(escriba_search::Direction::Backward) => PromptKind::SearchBackward,
618 None if self.modal.mode() == Mode::Command => PromptKind::Ex,
621 None => PromptKind::None,
622 };
623
624 StatusModel {
625 mode: self.modal.mode(),
626 line: cursor.line.saturating_add(1) as usize,
627 column: cursor.column.saturating_add(1) as usize,
628 prompt: kind,
629 prompt_text: prompt.map_or_else(|| self.modal.minibuffer(), |p| p.text.as_str()),
630 prompt_caret: prompt.map_or_else(
631 || self.modal.minibuffer_caret(),
632 escriba_search::Prompt::caret,
633 ),
634 count: self.match_count(),
635 message: self.messages.last().map(String::as_str),
636 }
637 }
638
639 #[must_use]
645 fn match_count(&self) -> MatchCount {
646 if self.search.is_prompting() {
647 let text = self.active_text();
648 return match self.search.preview(&text) {
653 escriba_search::Preview::Landed { step, total } => {
654 MatchCount::new(step.index, total)
655 }
656 escriba_search::Preview::NoMatch => MatchCount::None,
657 escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
658 MatchCount::Idle
659 }
660 };
661 }
662 if self.search.pattern().is_none() {
663 return MatchCount::Idle;
664 }
665 let total = self.search.matches().len();
666 let rev = self.text_rev();
669 self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
670 if total == 0 {
671 MatchCount::None
672 } else {
673 MatchCount::Idle
674 },
675 |&i| MatchCount::new(i, total),
676 )
677 }
678
679 fn repeat_last_change(&mut self) {
685 let Some(change) = self.last_change.clone() else {
686 self.messages
687 .push("E32: No previous change to repeat".to_string());
688 return;
689 };
690
691 for _ in 0..change.count.max(1) {
692 self.apply_resolved(&change.action);
693 }
694 for c in change.inserted.chars() {
695 self.apply_resolved(&Action::InsertChar(c));
696 }
697 if self.modal.mode() == Mode::Insert {
698 self.apply_resolved(&Action::ChangeMode(Mode::Normal));
702 }
703 self.last_change = Some(change);
707 self.recording_insert = false;
708 }
709
710 fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
717 use escriba_core::TextObject as O;
718 let at = self.cursor_char();
719 let matches = self.search.matches();
720
721 let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
733 let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
734 match object {
735 O::NextMatch => Bound::Inclusive.first_matching(&starts, at, true),
736 O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
737 }
738 })?;
739
740 let m = matches.get(idx)?;
741 let buf = self.buffers.get(self.active)?;
742 Some(Range {
743 start: buf.char_to_position(m.start),
744 end: buf.char_to_position(m.end),
745 })
746 }
747
748 fn land_on(&mut self, step: escriba_search::Step) {
749 if let Some(buf) = self.buffers.get(self.active) {
750 let pos = buf.char_to_position(step.target.start);
751 self.set_cursor(pos);
752 }
753 self.search_at = Some(Anchored::new(step.index, self.text_rev()));
757 }
758
759 fn report_wrap(&mut self, step: &escriba_search::Step) {
765 if let Some(msg) = step.wrapped.message() {
766 self.messages.push(msg.to_string());
767 }
768 }
769
770 fn jump_search(&mut self, reverse: bool) {
774 self.search.relight();
777 self.jumps.push(self.cursor());
779 let at = self.cursor_char();
780 match self.search.repeat(at, reverse) {
781 Some(step) => {
782 self.report_wrap(&step);
784 self.land_on(step);
785 }
786 None => {
787 let msg = self.search.pattern().map_or_else(
788 || "E35: No previous regular expression".to_string(),
789 |p| {
790 let mut m = String::from("E486: Pattern not found: ");
791 m.push_str(p.raw());
792 m
793 },
794 );
795 self.messages.push(msg);
796 }
797 }
798 }
799
800 fn preview_search(&mut self) {
807 let text = self.active_text();
808 let Some(origin) = self.search.prompt().map(|p| p.origin) else {
809 return;
810 };
811 let target = match self.search.preview(&text) {
812 escriba_search::Preview::Landed { step, .. } => step.target.start,
813 escriba_search::Preview::Idle
817 | escriba_search::Preview::Incomplete
818 | escriba_search::Preview::NoMatch => origin,
819 };
820 if let Some(buf) = self.buffers.get(self.active) {
829 let pos = buf.char_to_position(target);
830 self.set_cursor(pos);
831 }
832 }
833
834 fn commit_search_prompt(&mut self) -> CommitOutcome {
849 let text = self.active_text();
850 let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
851 else {
852 return CommitOutcome::NoPrompt;
853 };
854
855 match self.search.accept(&text) {
856 escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
857 self.modal.clear_minibuffer();
858 self.modal.enter(Mode::Normal);
859 match self.search.commit_step_skipping(origin, skip) {
860 Some(step) => {
861 self.report_wrap(&step);
867 CommitOutcome::Landed { origin, step }
868 }
869 None => {
870 self.report_pattern_not_found();
871 CommitOutcome::NotFound
872 }
873 }
874 }
875 escriba_search::Accepted::NothingToRepeat => {
876 self.modal.clear_minibuffer();
877 self.modal.enter(Mode::Normal);
878 self.messages
879 .push("E35: No previous regular expression".to_string());
880 CommitOutcome::NoPrevious
881 }
882 escriba_search::Accepted::Invalid(e) => {
887 let mut m = String::from("E383: Invalid search string: ");
888 m.push_str(&e.to_string());
889 self.messages.push(m);
890 CommitOutcome::NoPrompt
891 }
892 }
893 }
894
895 fn report_pattern_not_found(&mut self) {
898 let mut m = String::from("E486: Pattern not found");
899 if let Some(p) = self.search.pattern() {
900 m.push_str(": ");
901 m.push_str(p.raw());
902 }
903 self.messages.push(m);
904 }
905
906 fn submit_search(&mut self) {
911 match self.commit_search_prompt() {
912 CommitOutcome::Landed { origin, step } => {
913 if let Some(buf) = self.buffers.get(self.active) {
914 let from = buf.char_to_position(origin);
915 self.jumps.push(from);
916 }
917 self.land_on(step);
918 }
919 CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
920 }
921 }
922
923 fn submit_search_operated(&mut self, op: Operator) {
930 match self.commit_search_prompt() {
931 CommitOutcome::Landed { origin, step } => {
932 if let Some(buf) = self.buffers.get(self.active) {
933 let from = buf.char_to_position(origin);
934 let target = buf.char_to_position(step.target.start);
935 self.jumps.push(from);
937 self.set_cursor(from);
938 self.apply_operator_to(op, target);
939 }
940 }
941 CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
942 }
943 }
944
945 fn apply_resolved(&mut self, action: &Action) {
946 let lines_before = self.active_line_count();
949 let rev_before = self.text_rev();
952 let cline_before = self.cursor().line;
953 match action {
954 Action::Move(m) => self.apply_motion(*m),
955 Action::SearchOpen(dir) => {
956 let origin = self.cursor_char();
960 self.search.open(*dir, origin);
961 self.modal.enter(Mode::Command);
962 }
963 Action::SearchRepeat { reverse } => self.jump_search(*reverse),
964 Action::SearchWord { reverse } => {
965 let dir = if *reverse {
966 SearchDirection::Backward
967 } else {
968 SearchDirection::Forward
969 };
970 let (text, at) = (self.active_text(), self.cursor_char());
971 self.jumps.push(self.cursor());
973 match self.search.search_word(&text, at, dir) {
974 Some(step) => self.land_on(step),
975 None => self
978 .messages
979 .push("E348: No string under cursor".to_string()),
980 }
981 }
982 Action::ClearSearchHighlight => self.search.clear_highlight(),
983 Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
984 Action::TextObject(object) => {
985 if let Some(range) = self.resolve_object(*object) {
991 self.jumps.push(self.cursor());
992 self.set_cursor(range.start);
993 } else {
994 self.report_pattern_not_found();
995 }
996 }
997 Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
998 Some(range) => self.apply_operator_over(*op, range),
999 None => self.report_pattern_not_found(),
1000 },
1001 Action::RepeatLastChange => self.repeat_last_change(),
1002 Action::JumpBack => {
1003 let here = self.cursor();
1004 if let Some(pos) = self.jumps.back(here) {
1005 self.set_cursor(pos);
1006 } else {
1007 self.messages
1008 .push("E662: At start of changelist".to_string());
1009 }
1010 }
1011 Action::JumpForward => {
1012 if let Some(pos) = self.jumps.forward() {
1013 self.set_cursor(pos);
1014 } else {
1015 self.messages.push("E663: At end of changelist".to_string());
1016 }
1017 }
1018 Action::ChangeMode(m) => {
1019 if *m == Mode::Normal && self.search.is_prompting() {
1023 if let Some(origin) = self.search.cancel() {
1024 if let Some(buf) = self.buffers.get(self.active) {
1025 let pos = buf.char_to_position(origin);
1026 self.set_cursor(pos);
1027 }
1028 }
1029 }
1030 self.modal.enter(*m);
1031 }
1032 Action::InsertChar(c) => self.insert_char(*c),
1033 Action::Edit(edit) => self.apply_edit(edit),
1034 Action::Undo => {
1035 if let Some(buf) = self.buffers.get_mut(self.active) {
1036 let _ = buf.undo();
1037 }
1038 self.set_cursor(self.cursor());
1041 }
1042 Action::Redo => {
1043 if let Some(buf) = self.buffers.get_mut(self.active) {
1044 let _ = buf.redo();
1045 }
1046 self.set_cursor(self.cursor());
1047 }
1048 Action::Save => {
1049 if let Some(buf) = self.buffers.get_mut(self.active) {
1050 let _ = buf.save();
1051 }
1052 self.set_cursor(self.cursor());
1053 }
1054 Action::Quit => self.quit_requested = true,
1055 Action::SubmitCommand => {
1056 if self.search.is_prompting() {
1057 self.submit_search();
1058 } else {
1059 self.submit_command();
1060 }
1061 }
1062 Action::Command { name, args } => self.run_command(name, args),
1063 Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
1064 Action::Operator(_) => {}
1067 Action::PromptCaret { to } => {
1068 if self.search.is_prompting() {
1070 self.search.move_caret(*to);
1071 } else {
1072 self.modal.move_minibuffer_caret(*to);
1073 }
1074 }
1075 Action::SearchPreviewStep { forward } => {
1076 if self.search.is_prompting() {
1077 self.search.preview_step(*forward);
1078 self.preview_search();
1079 }
1080 }
1081 Action::PromptDelete => {
1082 if self.search.is_prompting() {
1083 self.search.delete_at_caret();
1084 self.preview_search();
1085 } else {
1086 self.modal.delete_minibuffer_at_caret();
1087 }
1088 }
1089 Action::PromptDeleteWord => {
1090 if self.search.is_prompting() {
1091 self.search.delete_word_before_caret();
1092 self.preview_search();
1093 }
1094 }
1095 Action::PromptClearToStart => {
1096 if self.search.is_prompting() {
1097 self.search.clear_before_caret();
1098 self.preview_search();
1099 }
1100 }
1101 Action::PromptBackspace => {
1102 self.prompt_backspace();
1103 if self.search.is_prompting() {
1107 self.preview_search();
1108 }
1109 }
1110 Action::PromptHistory { back } => {
1111 if self.search.is_prompting() {
1112 self.search.history_step(*back);
1113 self.preview_search();
1117 }
1118 }
1119 Action::Pending => {}
1120 }
1121 let lines_after = self.active_line_count();
1126 let cline_after = self.cursor().line;
1127 let d = match action {
1128 Action::SearchOpen(_)
1132 | Action::PromptHistory { .. }
1133 | Action::PromptBackspace
1134 | Action::PromptCaret { .. }
1135 | Action::SearchPreviewStep { .. }
1136 | Action::PromptDelete
1137 | Action::PromptDeleteWord
1138 | Action::PromptClearToStart
1139 | Action::SearchRepeat { .. }
1140 | Action::SearchWord { .. }
1141 | Action::ClearSearchHighlight
1142 | Action::SearchSubmitOperated { .. }
1143 | Action::RepeatLastChange
1146 | Action::TextObject(_)
1147 | Action::ApplyOperatorObject { .. }
1148 | Action::JumpBack
1150 | Action::JumpForward => Damage::Full,
1151 Action::InsertChar(_)
1152 | Action::Edit(_)
1153 | Action::Undo
1154 | Action::Redo
1155 | Action::ApplyOperator { .. } => {
1156 if lines_after == lines_before {
1157 Damage::span(cline_before, cline_after)
1158 } else {
1159 Damage::Lines {
1160 from: cline_before.min(cline_after),
1161 to: u32::MAX,
1162 }
1163 }
1164 }
1165 Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
1166 Action::Save => Damage::Viewport,
1167 Action::Command { .. } | Action::SubmitCommand => Damage::Full,
1168 Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
1169 };
1170 self.damage = self.damage.join(d);
1171 if self.recording_insert {
1192 match action {
1193 Action::InsertChar(c) => {
1194 if let Some(lc) = self.last_change.as_mut() {
1195 lc.inserted.push(*c);
1196 }
1197 }
1198 Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
1200 _ => {}
1201 }
1202 } else if self.text_rev() != rev_before
1203 && !matches!(
1204 action,
1205 Action::RepeatLastChange | Action::Undo | Action::Redo
1206 )
1207 {
1208 self.last_change = Some(LastChange {
1209 action: action.clone(),
1210 count: 1,
1211 inserted: String::new(),
1212 });
1213 self.recording_insert = self.modal.mode() == Mode::Insert;
1214 }
1215
1216 if action.highlight_effect() == HighlightEffect::Clear {
1221 self.search.clear_highlight();
1222 }
1223 if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
1232 let text = self.active_text();
1233 self.search.refresh(&text);
1234 }
1239 self.bump_gen();
1244 }
1245
1246 fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
1256 let buf = self.buffers.get(self.active)?;
1257 let pos = from;
1258 Some(match motion {
1259 Motion::SearchNext | Motion::SearchPrev => {
1264 let at = buf.position_to_char(pos).ok()?;
1265 let step = self
1266 .search
1267 .repeat(at, matches!(motion, Motion::SearchPrev))?;
1268 buf.char_to_position(step.target.start)
1269 }
1270 Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
1271 Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
1272 Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
1273 Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
1274 Motion::LineStart => Position::new(pos.line, 0),
1275 Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
1276 Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
1277 Motion::DocStart => Position::ZERO,
1278 Motion::DocEnd => Position::new(
1279 buf.line_count().saturating_sub(1),
1280 buf.line_len_chars(buf.line_count().saturating_sub(1)),
1281 ),
1282 Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
1283 Motion::WordStartPrev => word_prev(buf, pos),
1284 Motion::PageDown | Motion::HalfPageDown => {
1285 Position::new(pos.line.saturating_add(10), pos.column)
1286 }
1287 Motion::PageUp | Motion::HalfPageUp => {
1288 Position::new(pos.line.saturating_sub(10), pos.column)
1289 }
1290 Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
1291 Motion::ForwardSexp
1294 | Motion::BackwardSexp
1295 | Motion::UpList
1296 | Motion::DownList
1297 | Motion::BeginningOfDefun
1298 | Motion::EndOfDefun
1299 | Motion::BeginningOfSexp
1300 | Motion::EndOfSexp => pos,
1301 })
1302 }
1303
1304 fn apply_motion(&mut self, motion: Motion) {
1305 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1313 self.jump_search(matches!(motion, Motion::SearchPrev));
1314 return;
1315 }
1316 let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
1317 return;
1318 };
1319 self.set_cursor(pos);
1322 }
1323
1324 fn apply_operator(&mut self, op: Operator, motion: Motion) {
1331 let from = self.cursor();
1332 let Some(to) = self.resolve_motion(from, motion) else {
1333 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1338 if self.search.pattern().is_none() {
1339 self.messages
1340 .push("E35: No previous regular expression".to_string());
1341 } else {
1342 self.report_pattern_not_found();
1343 }
1344 }
1345 return;
1346 };
1347 self.apply_operator_to(op, to);
1348 }
1349
1350 fn apply_operator_to(&mut self, op: Operator, to: Position) {
1357 let from = self.cursor();
1358 self.apply_operator_over(
1359 op,
1360 Range {
1361 start: from,
1362 end: to,
1363 },
1364 );
1365 }
1366
1367 fn apply_operator_over(&mut self, op: Operator, range: Range) {
1374 let range = range.normalized();
1375 if range.is_empty() {
1376 return;
1377 }
1378 let text = self
1380 .buffers
1381 .get(self.active)
1382 .and_then(|buf| buf.slice(range).ok());
1383 if op.leaves_register() {
1384 if let Some(t) = &text {
1385 self.register = Some(t.clone());
1386 }
1387 }
1388 match op {
1389 Operator::Delete | Operator::Change => {
1392 if let Some(buf) = self.buffers.get_mut(self.active) {
1393 let _ = buf.apply(&Edit::delete(range));
1394 }
1395 self.set_cursor(range.start);
1396 if op == Operator::Change {
1397 self.modal.enter(Mode::Insert);
1398 }
1399 }
1400 Operator::Yank => {
1403 self.set_cursor(range.start);
1404 }
1405 _ => {
1409 self.messages
1410 .push("operator not yet implemented".to_owned());
1411 }
1412 }
1413 }
1414
1415 #[must_use]
1418 pub fn register(&self) -> Option<&str> {
1419 self.register.as_deref()
1420 }
1421
1422 fn insert_char(&mut self, c: char) {
1423 if self.modal.mode() == Mode::Command {
1424 if self.search.is_prompting() {
1428 self.search.push(c);
1442 self.preview_search();
1443 } else {
1444 self.modal.push_minibuffer(c);
1445 }
1446 return;
1447 }
1448 let cursor = self.cursor();
1449 let Some(buf) = self.buffers.get_mut(self.active) else {
1450 return;
1451 };
1452 let edit = Edit::insert(cursor, c.to_string());
1453 if buf.apply(&edit).is_ok() {
1454 let next = if c == '\n' {
1455 Position::new(cursor.line.saturating_add(1), 0)
1456 } else {
1457 cursor.shift_right(1)
1458 };
1459 self.set_cursor(next);
1462 }
1463 }
1464
1465 fn prompt_backspace(&mut self) -> bool {
1469 if self.modal.mode() != Mode::Command {
1470 return false;
1471 }
1472 if self.search.is_prompting() {
1473 if self.search.backspace() {
1478 self.modal.clear_minibuffer();
1479 self.modal.enter(Mode::Normal);
1480 }
1481 return true;
1484 }
1485 self.modal.pop_minibuffer();
1486 true
1487 }
1488
1489 fn apply_edit(&mut self, _edit: &Edit) {
1490 }
1494
1495 fn submit_command(&mut self) {
1496 let line = self.modal.minibuffer().to_string();
1500 self.modal.escape();
1501 let (name, args) = parse_command_line(&line);
1502 if name.is_empty() {
1503 return;
1504 }
1505 self.run_command(&name, &args);
1506 }
1507
1508 fn run_command(&mut self, name: &str, args: &[String]) {
1509 if matches!(name, "noh" | "nohl" | "nohlsearch") {
1515 self.search.clear_highlight();
1516 return;
1517 }
1518 if self.plugin_host.pending() > 0 {
1524 let pending = self.plugin_host.pending_for_command(name);
1525 for src in pending {
1526 self.apply_plugin_entry(&src);
1527 }
1528 }
1529 let active = Some(self.active);
1530 let mut quit = false;
1531 {
1532 let mut ctx = EditContext {
1533 buffers: &mut self.buffers,
1534 active,
1535 state: &mut self.modal,
1536 quit_requested: &mut quit,
1537 };
1538 let _ = self.commands.run(name, &mut ctx, args);
1539 }
1540 if quit {
1543 self.quit_requested = true;
1544 }
1545 }
1546
1547 #[must_use]
1552 pub fn snapshot(&self) -> EditorSnapshot {
1553 let current_line = self
1554 .buffers
1555 .get(self.active)
1556 .and_then(|b| b.line(self.cursor().line))
1557 .map(|s| s.trim_end_matches('\n').to_string())
1558 .unwrap_or_default();
1559 let buffer_name = self
1560 .buffers
1561 .get(self.active)
1562 .and_then(|b| b.path.as_ref())
1563 .map(|p| p.display().to_string())
1564 .unwrap_or_else(|| "[scratch]".to_string());
1565 EditorSnapshot {
1566 cursor_line: i64::from(self.cursor().line),
1567 cursor_column: i64::from(self.cursor().column),
1568 current_line,
1569 mode: self.modal.mode().as_str().to_string(),
1570 buffer_name,
1571 }
1572 }
1573
1574 pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
1590 let mut host = EscribaHost::with_snapshot(self.snapshot());
1591 let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
1592 vm.eval(src, &mut host)?;
1593 let effects = host.take_effects();
1594 self.apply_host_effects(effects);
1595 Ok(())
1596 }
1597
1598 pub fn apply_host_effects(&mut self, effects: Vec<HostEffect>) {
1602 for eff in effects {
1603 match eff {
1604 HostEffect::Message(m) => self.messages.push(m),
1605 HostEffect::RunCommand { name, args } => self.run_command(&name, &args),
1606 HostEffect::SetOption { name, value } => {
1607 self.options.insert(name, value);
1608 }
1609 HostEffect::InsertText(text) => self.insert_text(&text),
1610 }
1611 }
1612 }
1613
1614 fn insert_text(&mut self, text: &str) {
1617 if text.is_empty() {
1618 return;
1619 }
1620 let cursor = self.cursor();
1621 let Some(buf) = self.buffers.get_mut(self.active) else {
1622 return;
1623 };
1624 let edit = Edit::insert(cursor, text.to_string());
1625 if buf.apply(&edit).is_ok() {
1626 let next = if let Some(nl) = text.rfind('\n') {
1627 let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
1628 let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
1629 Position::new(cursor.line + added_lines, last_line_len)
1630 } else {
1631 let n = u32::try_from(text.chars().count()).unwrap_or(0);
1632 cursor.shift_right(n)
1633 };
1634 self.set_cursor(next);
1637 }
1638 }
1639}
1640
1641fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
1642 let Some(text) = buf.line(line) else {
1643 return Position::new(line, 0);
1644 };
1645 let col = text
1646 .chars()
1647 .take_while(|c| c.is_whitespace() && *c != '\n')
1648 .count();
1649 Position::new(line, u32::try_from(col).unwrap_or(0))
1650}
1651
1652fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1653 let Some(text) = buf.line(pos.line) else {
1654 return pos;
1655 };
1656 let chars: Vec<char> = text.chars().collect();
1657 let start = pos.column as usize;
1658 let mut i = start;
1659 while i < chars.len() && !chars[i].is_whitespace() {
1660 i += 1;
1661 }
1662 while i < chars.len() && chars[i].is_whitespace() {
1663 i += 1;
1664 }
1665 if i >= chars.len() {
1666 if pos.line + 1 < buf.line_count() {
1668 return Position::new(pos.line + 1, 0);
1669 }
1670 }
1671 Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
1672}
1673
1674fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1675 let Some(text) = buf.line(pos.line) else {
1676 return pos;
1677 };
1678 let chars: Vec<char> = text.chars().collect();
1679 let mut i = (pos.column as usize).min(chars.len());
1680 while i > 0 && chars[i - 1].is_whitespace() {
1681 i -= 1;
1682 }
1683 while i > 0 && !chars[i - 1].is_whitespace() {
1684 i -= 1;
1685 }
1686 Position::new(pos.line, u32::try_from(i).unwrap_or(0))
1687}
1688
1689fn parse_command_line(line: &str) -> (String, Vec<String>) {
1690 let mut parts = line.split_whitespace();
1691 let Some(first) = parts.next() else {
1692 return (String::new(), Vec::new());
1693 };
1694 let head = first.strip_prefix(':').unwrap_or(first);
1695 let name = match head {
1696 "w" => "save",
1697 "q" => "quit",
1698 "u" => "undo",
1699 other => other,
1700 };
1701 (name.to_string(), parts.map(str::to_string).collect())
1702}
1703
1704#[cfg(test)]
1705mod tests {
1706 use super::*;
1707 use madori::event::{KeyCode, KeyEvent, Modifiers};
1708
1709 fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
1717 st.apply(&Action::SearchOpen(dir));
1718 for c in pat.chars() {
1719 st.apply(&Action::InsertChar(c));
1720 }
1721 st.apply(&Action::SubmitCommand);
1722 }
1723
1724 #[test]
1725 fn slash_search_moves_the_cursor_to_the_match() {
1726 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1727 type_search(&mut st, SearchDirection::Forward, "charlie");
1728 assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
1729 assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
1730 assert_eq!(st.search.matches().len(), 1);
1731 }
1732
1733 #[test]
1734 fn n_and_N_walk_matches_in_both_directions() {
1735 let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
1736 type_search(&mut st, SearchDirection::Forward, "foo");
1737 let first = st.cursor().line;
1738 st.apply(&Action::SearchRepeat { reverse: false });
1739 let second = st.cursor().line;
1740 assert!(second > first, "n advances ({first} -> {second})");
1741 st.apply(&Action::SearchRepeat { reverse: true });
1742 assert_eq!(st.cursor().line, first, "N comes back");
1743 }
1744
1745 #[test]
1746 fn star_searches_the_word_under_the_cursor() {
1747 let mut st = new_state_with("needle\nhaystack\nneedle\n");
1748 st.apply(&Action::SearchWord { reverse: false });
1749 assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
1750 assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
1751 }
1752
1753 #[test]
1754 fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
1755 let mut st = new_state_with("foo\nbar\nfoo\n");
1756 type_search(&mut st, SearchDirection::Forward, "foo");
1757 let matches_before = st.search.matches().len();
1758
1759 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1760 st.apply(&Action::InsertChar('z'));
1761 st.apply(&Action::ChangeMode(Mode::Normal));
1762
1763 assert!(!st.search.is_prompting(), "prompt gone");
1764 assert_eq!(
1765 st.search.pattern().unwrap().raw(),
1766 "foo",
1767 "old pattern survives"
1768 );
1769 assert_eq!(
1770 st.search.matches().len(),
1771 matches_before,
1772 "old highlights survive"
1773 );
1774 }
1775
1776 #[test]
1777 fn a_search_prompt_and_an_ex_command_are_not_confused() {
1778 let mut st = new_state_with("foo\n");
1779 st.apply(&Action::ChangeMode(Mode::Command));
1781 assert!(!st.search.is_prompting(), "`:` must not open a search");
1782 st.apply(&Action::InsertChar('w'));
1783 assert!(
1784 st.search.prompt().is_none(),
1785 "typed char went to the ex line"
1786 );
1787 }
1788
1789 #[test]
1790 fn a_missing_pattern_reports_instead_of_failing_silently() {
1791 let mut st = new_state_with("alpha\nbravo\n");
1792 type_search(&mut st, SearchDirection::Forward, "zzz");
1793 assert!(
1794 st.messages.iter().any(|m| m.contains("E486")),
1795 "must report not-found, got {:?}",
1796 st.messages
1797 );
1798 }
1799
1800 #[test]
1801 fn n_without_any_search_reports_rather_than_moving() {
1802 let mut st = new_state_with("alpha\nbravo\n");
1803 let before = st.cursor();
1804 st.apply(&Action::SearchRepeat { reverse: false });
1805 assert_eq!(st.cursor(), before, "cursor must not move");
1806 assert!(
1807 st.messages.iter().any(|m| m.contains("E35")),
1808 "got {:?}",
1809 st.messages
1810 );
1811 }
1812
1813 #[test]
1814 fn search_as_a_motion_composes_with_an_operator() {
1815 let mut st = new_state_with("alpha bravo charlie\n");
1817 type_search(&mut st, SearchDirection::Forward, "charlie");
1818 st.set_cursor(Position::new(0, 0));
1819 let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
1820 assert!(target.is_some(), "search must resolve as a motion");
1821 assert_eq!(target.unwrap().column, 12, "at `charlie`");
1822 }
1823
1824 #[test]
1825 fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
1826 let st = new_state_with("alpha bravo\n");
1829 assert!(
1830 st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
1831 .is_none()
1832 );
1833 }
1834
1835 #[test]
1836 fn clear_highlight_keeps_the_pattern_usable() {
1837 let mut st = new_state_with("foo\nbar\nfoo\n");
1838 type_search(&mut st, SearchDirection::Forward, "foo");
1839 st.apply(&Action::ClearSearchHighlight);
1840 assert!(st.search.highlights().is_empty(), "nothing lit");
1841 st.apply(&Action::SearchRepeat { reverse: false });
1842 assert!(st.search.pattern().is_some(), "but n still works");
1843 }
1844
1845 #[test]
1846 fn typing_previews_incrementally_before_commit() {
1847 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1848 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1849 for c in "charlie".chars() {
1850 st.apply(&Action::InsertChar(c));
1851 }
1852 assert_eq!(st.cursor().line, 2, "preview moved the cursor");
1854 assert!(st.search.pattern().is_none(), "but nothing is committed");
1855 }
1856
1857 #[test]
1858 fn backspace_corrects_the_prompt_and_reruns_the_preview() {
1859 let mut st = new_state_with("alpha\nbravo\n");
1860 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1861 for c in "bravox".chars() {
1862 st.apply(&Action::InsertChar(c));
1863 }
1864 assert_eq!(st.search.prompt().unwrap().text, "bravox");
1865 st.apply(&Action::PromptBackspace);
1866 assert_eq!(st.search.prompt().unwrap().text, "bravo", "typo corrected");
1867 assert_eq!(
1868 st.status_model().prompt_text,
1869 "bravo",
1870 "the model reads the PROMPT — the minibuffer is the ex-line's store",
1871 );
1872 assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
1873 }
1874
1875 #[test]
1876 fn backspacing_past_the_slash_closes_the_prompt() {
1877 let mut st = new_state_with("alpha\n");
1878 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1879 st.apply(&Action::InsertChar('a'));
1880 st.apply(&Action::PromptBackspace);
1881 st.apply(&Action::PromptBackspace);
1882 assert!(!st.search.is_prompting(), "prompt closed");
1883 assert_eq!(st.modal.mode(), Mode::Normal);
1884 }
1885
1886 #[test]
1887 fn noh_clears_highlights_and_keeps_the_pattern() {
1888 let mut st = new_state_with("foo\nbar\nfoo\n");
1889 type_search(&mut st, SearchDirection::Forward, "foo");
1890 assert!(!st.search.highlights().is_empty());
1891 st.run_command("noh", &[]);
1892 assert!(st.search.highlights().is_empty(), ":noh turns them off");
1893 assert!(st.search.pattern().is_some(), "but n still works");
1894 }
1895
1896 #[test]
1897 fn noh_accepts_the_vim_aliases() {
1898 for name in ["noh", "nohl", "nohlsearch"] {
1899 let mut st = new_state_with("foo\nfoo\n");
1900 type_search(&mut st, SearchDirection::Forward, "foo");
1901 st.run_command(name, &[]);
1902 assert!(st.search.highlights().is_empty(), "{name} must clear");
1903 }
1904 }
1905
1906 #[test]
1907 fn backspace_on_the_ex_line_does_not_touch_search_state() {
1908 let mut st = new_state_with("foo\n");
1909 st.apply(&Action::ChangeMode(Mode::Command));
1910 st.apply(&Action::InsertChar('w'));
1911 st.apply(&Action::InsertChar('q'));
1912 st.apply(&Action::PromptBackspace);
1913 assert_eq!(st.status_model().prompt_text, "w");
1914 assert!(st.search.prompt().is_none(), "no search was involved");
1915 }
1916
1917 #[test]
1918 fn up_arrow_recalls_the_previous_search() {
1919 let mut st = new_state_with("alpha\nbravo\n");
1920 type_search(&mut st, SearchDirection::Forward, "bravo");
1921 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1922 st.apply(&Action::PromptHistory { back: true });
1923 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1924 assert_eq!(
1925 st.status_model().prompt_text,
1926 "bravo",
1927 "display follows the prompt"
1928 );
1929 }
1930
1931 #[test]
1932 fn arrowing_back_down_restores_the_half_typed_pattern() {
1933 let mut st = new_state_with("alpha\nbravo\n");
1934 type_search(&mut st, SearchDirection::Forward, "bravo");
1935 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1936 st.apply(&Action::InsertChar('a'));
1937 st.apply(&Action::PromptHistory { back: true });
1938 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1939 st.apply(&Action::PromptHistory { back: false });
1940 assert_eq!(
1941 st.search.prompt().unwrap().text,
1942 "a",
1943 "the draft comes back"
1944 );
1945 assert_eq!(st.status_model().prompt_text, "a");
1946 }
1947
1948 #[test]
1949 fn history_arrows_do_nothing_on_the_ex_line() {
1950 let mut st = new_state_with("alpha\n");
1951 st.apply(&Action::ChangeMode(Mode::Command));
1952 st.apply(&Action::InsertChar('w'));
1953 st.apply(&Action::PromptHistory { back: true });
1954 assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
1955 }
1956
1957 fn new_state_with(text: &str) -> EditorState {
1958 let mut bufs = BufferSet::new();
1959 let id = bufs.scratch(text);
1960 EditorState::new_with_buffer(bufs, id)
1961 }
1962
1963 #[test]
1969 fn edit_gen_advances_on_applied_action_not_on_read() {
1970 let mut s = new_state_with("hello\nworld\n");
1971 let g0 = s.edit_gen();
1972 s.apply(&Action::InsertChar('X'));
1973 assert_ne!(
1974 s.edit_gen(),
1975 g0,
1976 "an applied action must advance the refresh generation",
1977 );
1978 let g1 = s.edit_gen();
1980 assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
1981 }
1982
1983 #[test]
1988 fn damage_tracks_edit_scope_and_drains() {
1989 let mut s = new_state_with("hello\nworld\n");
1990 assert!(s.damage().is_none(), "a fresh state has no damage");
1991
1992 s.apply(&Action::InsertChar('X')); assert_eq!(
1994 s.damage(),
1995 Damage::Lines { from: 0, to: 0 },
1996 "a local edit damages just its line",
1997 );
1998
1999 let drained = s.take_damage();
2000 assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
2001 assert!(s.damage().is_none(), "take_damage drains to None");
2002
2003 s.apply(&Action::InsertChar('\n')); assert_eq!(
2005 s.damage(),
2006 Damage::Lines {
2007 from: 0,
2008 to: u32::MAX,
2009 },
2010 "a line-count change damages to end-of-document",
2011 );
2012 }
2013
2014 fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
2018 let mut s = new_state_with(text);
2019 for w in &mut s.layout.windows {
2020 w.viewport.visible_lines = vis_lines;
2021 w.viewport.visible_columns = vis_cols;
2022 }
2023 s
2024 }
2025
2026 fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
2031 let w = s.layout.active_window().expect("active window");
2032 let v = w.viewport;
2033 let c = s.cursor();
2034 assert!(
2035 v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
2036 "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
2037 c.line,
2038 v.top_line,
2039 v.top_line + v.visible_lines,
2040 );
2041 assert!(
2042 v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
2043 "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
2044 c.column,
2045 v.left_column,
2046 v.left_column + v.visible_columns,
2047 );
2048 }
2049
2050 fn press(kc: KeyCode) -> AppEvent {
2051 AppEvent::Key(KeyEvent {
2052 key: kc,
2053 pressed: true,
2054 modifiers: Modifiers::default(),
2055 text: None,
2056 })
2057 }
2058
2059 fn line0_len(s: &EditorState) -> u32 {
2062 s.buffers.get(s.active).unwrap().line_len_chars(0)
2063 }
2064
2065 #[test]
2066 fn delete_to_line_end_clears_line_and_fills_register() {
2067 let mut s = new_state_with("hello world");
2068 s.apply(&Action::ApplyOperator {
2069 op: Operator::Delete,
2070 motion: Motion::LineEnd,
2071 });
2072 assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
2073 assert_eq!(
2074 s.register(),
2075 Some("hello world"),
2076 "delete fills the register"
2077 );
2078 assert_eq!(
2079 s.cursor(),
2080 Position::ZERO,
2081 "cursor lands at the range start"
2082 );
2083 }
2084
2085 #[test]
2086 fn delete_over_right_motion_removes_one_char() {
2087 let mut s = new_state_with("abc");
2088 s.apply(&Action::ApplyOperator {
2089 op: Operator::Delete,
2090 motion: Motion::Right,
2091 });
2092 assert_eq!(
2093 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2094 Some("bc")
2095 );
2096 assert_eq!(s.register(), Some("a"));
2097 }
2098
2099 #[test]
2100 fn change_to_line_end_deletes_and_enters_insert() {
2101 let mut s = new_state_with("hello world");
2102 assert_eq!(s.modal.mode(), Mode::Normal);
2103 s.apply(&Action::ApplyOperator {
2104 op: Operator::Change,
2105 motion: Motion::LineEnd,
2106 });
2107 assert_eq!(line0_len(&s), 0, "c$ deletes the range");
2108 assert_eq!(
2109 s.modal.mode(),
2110 Mode::Insert,
2111 "change enters Insert to type the replacement"
2112 );
2113 assert_eq!(
2114 s.register(),
2115 Some("hello world"),
2116 "change fills the register"
2117 );
2118 }
2119
2120 #[test]
2121 fn yank_to_line_end_fills_register_without_mutating() {
2122 let mut s = new_state_with("hello world");
2123 s.apply(&Action::ApplyOperator {
2124 op: Operator::Yank,
2125 motion: Motion::LineEnd,
2126 });
2127 assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
2128 assert_eq!(s.register(), Some("hello world"), "yank fills the register");
2129 assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
2130 }
2131
2132 #[test]
2133 fn resolve_motion_is_the_shared_target_for_move_and_operator() {
2134 let mut s = new_state_with("hello world");
2138 let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
2139 assert_eq!(target, Position::new(0, 11));
2140 s.apply_motion(Motion::LineEnd);
2141 assert_eq!(
2142 s.cursor(),
2143 target,
2144 "the move path resolves the same target the operator uses"
2145 );
2146 }
2147
2148 #[test]
2149 fn empty_motion_range_is_a_no_op() {
2150 let mut s = new_state_with("abc");
2153 s.apply(&Action::ApplyOperator {
2154 op: Operator::Delete,
2155 motion: Motion::LineStart,
2156 });
2157 assert_eq!(
2158 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2159 Some("abc")
2160 );
2161 assert_eq!(s.register(), None);
2162 }
2163
2164 #[test]
2165 fn operator_then_motion_composes_through_the_pending_fsm() {
2166 let mut s = new_state_with("hello world");
2170 s.apply(&Action::Operator(Operator::Delete));
2171 assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
2172 s.apply(&Action::Move(Motion::LineEnd));
2173 assert_eq!(
2174 line0_len(&s),
2175 0,
2176 "d then $ composes d$ and deletes the line"
2177 );
2178 assert_eq!(s.register(), Some("hello world"));
2179 }
2180
2181 #[test]
2182 fn change_operator_through_fsm_enters_insert() {
2183 let mut s = new_state_with("hello world");
2184 s.apply(&Action::Operator(Operator::Change));
2185 s.apply(&Action::Move(Motion::LineEnd));
2186 assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
2187 }
2188
2189 #[test]
2190 fn lone_motion_after_no_operator_just_moves() {
2191 let mut s = new_state_with("hello world");
2193 s.apply(&Action::Move(Motion::LineEnd));
2194 assert_eq!(s.cursor(), Position::new(0, 11));
2195 assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
2196 }
2197
2198 #[test]
2199 fn counted_operator_deletes_count_times() {
2200 let mut s = new_state_with("abcdef");
2204 s.apply_counted(&Action::Operator(Operator::Delete), 3);
2205 assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
2206 s.apply(&Action::Move(Motion::Right));
2207 assert_eq!(
2208 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2209 Some("def")
2210 );
2211 }
2212
2213 #[test]
2214 fn operator_and_motion_counts_multiply_end_to_end() {
2215 let mut s = new_state_with("abcdefgh");
2217 s.apply_counted(&Action::Operator(Operator::Delete), 2);
2218 s.apply_counted(&Action::Move(Motion::Right), 3);
2219 assert_eq!(
2220 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2221 Some("gh")
2222 );
2223 }
2224
2225 #[test]
2226 fn bare_counted_motion_still_repeats_no_regression() {
2227 let mut s = new_state_with("a\nb\nc\nd\ne");
2230 s.apply_counted(&Action::Move(Motion::Down), 3);
2231 assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
2232 }
2233
2234 struct SpacedClock(std::time::Instant);
2240 impl SpacedClock {
2241 fn new() -> Self {
2242 Self(std::time::Instant::now())
2243 }
2244 fn next(&mut self) -> std::time::Instant {
2245 self.0 += std::time::Duration::from_secs(1);
2246 self.0
2247 }
2248 }
2249
2250 #[test]
2251 fn hjkl_moves_cursor() {
2252 let mut s = new_state_with("hello\nworld");
2253 s.tick(&press(KeyCode::Char('l')));
2254 assert_eq!(s.cursor().column, 1);
2255 s.tick(&press(KeyCode::Char('j')));
2256 assert_eq!(s.cursor().line, 1);
2257 s.tick(&press(KeyCode::Char('h')));
2258 assert_eq!(s.cursor().column, 0);
2259 }
2260
2261 #[test]
2262 fn insert_mode_inserts_chars() {
2263 let mut s = new_state_with("");
2264 s.tick(&press(KeyCode::Char('i')));
2265 assert_eq!(s.modal.mode(), Mode::Insert);
2266 s.tick(&press(KeyCode::Char('h')));
2267 s.tick(&press(KeyCode::Char('i')));
2268 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
2269 assert_eq!(s.cursor().column, 2);
2270 }
2271
2272 #[test]
2273 fn esc_returns_to_normal() {
2274 let mut s = new_state_with("");
2275 s.tick(&press(KeyCode::Char('i')));
2276 s.tick(&press(KeyCode::Escape));
2277 assert_eq!(s.modal.mode(), Mode::Normal);
2278 }
2279
2280 #[test]
2281 fn count_prefix_repeats_motion() {
2282 let mut s = new_state_with("abcdefghij");
2283 s.tick(&press(KeyCode::Char('5')));
2284 s.tick(&press(KeyCode::Char('l')));
2285 assert_eq!(s.cursor().column, 5);
2286 }
2287
2288 #[test]
2289 fn close_event_requests_quit() {
2290 let mut s = new_state_with("");
2291 s.tick(&AppEvent::CloseRequested);
2292 assert!(s.quit_requested);
2293 }
2294
2295 #[test]
2296 fn word_next_jumps_past_whitespace() {
2297 let mut s = new_state_with("foo bar baz");
2298 let mut clk = SpacedClock::new();
2301 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2302 assert_eq!(s.cursor().column, 4);
2303 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2304 assert_eq!(s.cursor().column, 8);
2305 }
2306
2307 #[test]
2310 fn leader_sequence_holds_then_resolves() {
2311 let mut s = new_state_with("a\nbb\nccc");
2312 s.keymap.bind_sequence(
2313 Mode::Normal,
2314 vec![Key::Char(','), Key::Char('g')],
2315 Action::Move(Motion::DocEnd),
2316 "doc end",
2317 );
2318 s.on_key(&Key::Char(','));
2320 assert_eq!(s.pending_keys, vec![Key::Char(',')]);
2321 assert_eq!(s.cursor(), Position::ZERO);
2322 s.on_key(&Key::Char('g'));
2324 assert!(s.pending_keys.is_empty());
2325 assert_eq!(s.cursor().line, 2);
2326 }
2327
2328 #[test]
2329 fn two_key_gg_jumps_doc_start() {
2330 let mut s = new_state_with("a\nbb\nccc");
2331 s.keymap.bind_sequence(
2332 Mode::Normal,
2333 vec![Key::Char('g'), Key::Char('g')],
2334 Action::Move(Motion::DocStart),
2335 "doc start",
2336 );
2337 let mut clk = SpacedClock::new();
2338 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2339 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2340 assert_eq!(s.cursor().line, 2);
2341 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2343 s.on_key(&Key::Char('g')); assert_eq!(s.cursor(), Position::ZERO);
2345 }
2346
2347 #[test]
2348 fn broken_sequence_aborts_and_clears_pending() {
2349 let mut s = new_state_with("hello");
2350 s.keymap.bind_sequence(
2351 Mode::Normal,
2352 vec![Key::Char('g'), Key::Char('g')],
2353 Action::Move(Motion::DocEnd),
2354 "doc end",
2355 );
2356 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2358 s.on_key(&Key::Char('x')); assert!(s.pending_keys.is_empty());
2360 assert_eq!(s.cursor(), Position::ZERO);
2361 }
2362
2363 #[test]
2364 fn single_binding_wins_over_sequence_prefix() {
2365 let mut s = new_state_with("abcde");
2369 let mut clk = SpacedClock::new();
2370 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2371 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2372 assert_eq!(s.cursor().column, 2);
2373 s.keymap.bind_sequence(
2374 Mode::Normal,
2375 vec![Key::Char('h'), Key::Char('z')],
2376 Action::Move(Motion::DocEnd),
2377 "shadowed",
2378 );
2379 s.on_key(&Key::Char('h'));
2380 assert!(s.pending_keys.is_empty(), "single binding should not pend");
2381 assert_eq!(s.cursor().column, 1, "h moved left immediately");
2382 }
2383
2384 #[test]
2387 fn lisp_set_option_writes_live_options() {
2388 let mut s = new_state_with("");
2389 s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
2390 assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
2391 }
2392
2393 #[test]
2394 fn lisp_insert_modifies_buffer_and_advances_cursor() {
2395 let mut s = new_state_with("");
2396 s.run_lisp(r#"(insert "abc")"#).unwrap();
2397 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2398 assert_eq!(s.cursor(), Position::new(0, 3));
2399 }
2400
2401 #[test]
2402 fn lisp_message_appends_to_messages() {
2403 let mut s = new_state_with("");
2404 s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
2405 assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
2406 }
2407
2408 #[test]
2409 fn lisp_reads_snapshot_and_branches_to_effect() {
2410 let mut s = new_state_with("one\ntwo\nthree");
2413 s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
2415 .unwrap();
2416 assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
2417 }
2418
2419 #[test]
2420 fn lisp_run_command_effect_drives_registry() {
2421 let mut s = new_state_with("");
2425 s.run_lisp(r#"(insert "abc")"#).unwrap();
2426 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2427 s.run_lisp(r#"(run-command "undo")"#).unwrap();
2428 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
2429 }
2430
2431 #[test]
2432 fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
2433 let mut s = new_state_with("");
2438 s.run_lisp(r#"(run-command "quit")"#).unwrap();
2439 assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
2440 assert_eq!(
2441 s.modal.minibuffer(),
2442 "",
2443 "quit must not pollute any command line — Normal mode has no minibuffer",
2444 );
2445 }
2446
2447 #[test]
2450 fn lazy_plugin_activates_on_command_trigger() {
2451 let mut s = new_state_with("");
2455 s.register_lazy_plugin(
2456 "user-lazy",
2457 vec![LazyTrigger::Command("LazyGo".into())],
2458 r#"(defoption :name "lazy-loaded" :value "yes")
2459 (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
2460 );
2461 assert_eq!(s.plugin_host.pending(), 1);
2462 assert!(
2463 s.options.get("lazy-loaded").is_none(),
2464 "entry not applied yet"
2465 );
2466
2467 s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
2469
2470 assert_eq!(
2471 s.options.get("lazy-loaded").map(String::as_str),
2472 Some("yes"),
2473 "the command trigger applied the plugin's entry",
2474 );
2475 assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
2476 }
2477
2478 #[test]
2479 fn lazy_plugin_activates_on_filetype() {
2480 let mut s = new_state_with("");
2481 s.register_lazy_plugin(
2482 "user-rust",
2483 vec![LazyTrigger::FileType("rust".into())],
2484 r#"(defoption :name "rust-plugin" :value "on")"#,
2485 );
2486 let n = s.activate_filetype_plugins("rust");
2487 assert_eq!(n, 1);
2488 assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
2489 assert_eq!(s.activate_filetype_plugins("rust"), 0);
2491 }
2492
2493 #[test]
2494 fn cached_vm_serves_multiple_run_lisp_calls() {
2495 let mut s = new_state_with("");
2496 s.run_lisp(r#"(message "one")"#).unwrap();
2497 assert!(
2498 s.lisp_vm.is_some(),
2499 "VM should be cached after first run_lisp"
2500 );
2501 s.run_lisp(r#"(message "two")"#).unwrap();
2502 assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
2503 }
2504
2505 #[test]
2506 fn lisp_define_persists_across_run_lisp_calls() {
2507 let mut s = new_state_with("");
2510 s.run_lisp(r#"(define greeting "hi")"#).unwrap();
2511 s.run_lisp(r#"(message greeting)"#).unwrap();
2512 assert_eq!(s.messages, vec!["hi".to_string()]);
2513 }
2514
2515 #[test]
2516 fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
2517 let mut s = new_state_with("");
2521 s.run_lisp(
2522 r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
2523 )
2524 .unwrap();
2525 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
2526 assert_eq!(
2527 s.options.get("col").map(String::as_str),
2528 Some("stale-zero"),
2529 "cursor-column within the same call reads the pre-eval snapshot",
2530 );
2531 s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
2534 .unwrap();
2535 assert_eq!(
2536 s.options.get("col2").map(String::as_str),
2537 Some("live-two"),
2538 "a later call sees the refreshed snapshot",
2539 );
2540 }
2541
2542 #[test]
2543 fn insert_text_effect_multiline_lands_cursor_on_last_line() {
2544 let mut s = new_state_with("");
2545 s.apply_host_effects(vec![HostEffect::InsertText("foo\nbar".to_string())]);
2546 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
2547 assert_eq!(s.cursor(), Position::new(1, 3));
2548 }
2549
2550 #[test]
2551 fn visual_mode_sequence_resolves() {
2552 let mut s = new_state_with("abc");
2553 s.modal.enter(Mode::Visual);
2554 s.keymap.bind_sequence(
2555 Mode::Visual,
2556 vec![Key::Char('g'), Key::Char('e')],
2557 Action::Move(Motion::DocEnd),
2558 "ge",
2559 );
2560 s.on_key(&Key::Char('g'));
2561 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2562 s.on_key(&Key::Char('e'));
2563 assert!(s.pending_keys.is_empty());
2564 assert_eq!(
2565 s.cursor().column,
2566 3,
2567 "ge resolved to doc-end in visual mode"
2568 );
2569 }
2570
2571 #[test]
2572 fn sequence_abort_with_bound_breaking_key_redispatches() {
2573 let mut s = new_state_with("abcde");
2576 s.keymap.bind_sequence(
2577 Mode::Normal,
2578 vec![Key::Char('g'), Key::Char('g')],
2579 Action::Move(Motion::DocEnd),
2580 "gg",
2581 );
2582 s.on_key(&Key::Char('g'));
2583 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2584 s.on_key(&Key::Char('l'));
2585 assert!(s.pending_keys.is_empty());
2586 assert_eq!(
2587 s.cursor().column,
2588 1,
2589 "the breaking key l should re-dispatch as move-right",
2590 );
2591 }
2592
2593 #[test]
2596 fn viewport_contains_cursor_after_every_op() {
2597 let mut s = new_state_small_viewport("", 5, 10);
2601 assert_cursor_in_viewport(&s, "initial");
2602
2603 s.tick(&press(KeyCode::Char('i')));
2606 assert_eq!(s.modal.mode(), Mode::Insert);
2607 for line in 0..30u32 {
2608 for c in "line".chars() {
2609 s.tick(&press(KeyCode::Char(c)));
2610 assert_cursor_in_viewport(&s, "typing chars");
2611 }
2612 s.tick(&press(KeyCode::Enter));
2613 assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
2614 }
2615
2616 for i in 0..200u32 {
2619 s.tick(&press(KeyCode::Char('x')));
2620 assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
2621 }
2622
2623 s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
2625 assert_cursor_in_viewport(&s, "insert_text multiline");
2626
2627 s.tick(&press(KeyCode::Escape));
2629 assert_eq!(s.modal.mode(), Mode::Normal);
2630 for m in [
2631 Motion::DocStart,
2632 Motion::DocEnd,
2633 Motion::Down,
2634 Motion::Down,
2635 Motion::Up,
2636 Motion::Right,
2637 Motion::Right,
2638 Motion::Left,
2639 Motion::LineEnd,
2640 Motion::LineStart,
2641 Motion::GotoLine(1),
2642 Motion::GotoLine(40),
2643 Motion::PageDown,
2644 Motion::PageUp,
2645 ] {
2646 s.apply_motion(m);
2647 assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
2648 }
2649
2650 for i in 0..50u32 {
2653 s.apply(&Action::Undo);
2654 assert_cursor_in_viewport(&s, &format!("undo {i}"));
2655 }
2656 for i in 0..50u32 {
2658 s.apply(&Action::Redo);
2659 assert_cursor_in_viewport(&s, &format!("redo {i}"));
2660 }
2661 }
2662
2663 #[test]
2664 fn insert_at_eof_keeps_cursor_in_bounds() {
2665 let mut s = new_state_small_viewport("abc", 5, 10);
2668 s.apply_motion(Motion::DocEnd);
2669 s.tick(&press(KeyCode::Char('i')));
2670 s.tick(&press(KeyCode::Char('d')));
2671 let buf = s.buffers.get(s.active).unwrap();
2672 let clamped = buf.clamp(s.cursor());
2673 assert_eq!(
2674 s.cursor(),
2675 clamped,
2676 "cursor must be clamped in-bounds at EOF"
2677 );
2678 assert_cursor_in_viewport(&s, "insert at eof");
2679 }
2680
2681 #[test]
2682 fn count_prefix_then_sequence_repeats() {
2683 let mut s = new_state_with("a\nb\nc\nd\ne");
2685 s.keymap.bind_sequence(
2686 Mode::Normal,
2687 vec![Key::Char('g'), Key::Char('j')],
2688 Action::Move(Motion::Down),
2689 "gj",
2690 );
2691 s.on_key(&Key::Char('2'));
2692 s.on_key(&Key::Char('g'));
2693 s.on_key(&Key::Char('j'));
2694 assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
2695 }
2696
2697 #[test]
2700 fn held_key_repeat_storm_is_debounced_in_normal_mode() {
2701 let mut s = new_state_with(&"x\n".repeat(40));
2707 let t0 = std::time::Instant::now();
2708 let mut delivered = 0u32;
2709 for i in 0..20u32 {
2710 let before = s.cursor().line;
2711 s.tick_at(
2712 &press(KeyCode::Char('j')),
2713 t0 + std::time::Duration::from_millis(u64::from(i) * 50),
2714 );
2715 if s.cursor().line != before {
2716 delivered += 1;
2717 }
2718 }
2719 assert!(
2722 (10..=14).contains(&delivered),
2723 "expected the storm debounced to ~13 moves, got {delivered}",
2724 );
2725 assert!(
2726 delivered < 20,
2727 "the gate must drop SOME storm ticks, not pass all 20",
2728 );
2729 }
2730
2731 #[test]
2732 fn spaced_intentional_taps_all_pass() {
2733 let mut s = new_state_with(&"x\n".repeat(10));
2736 let t0 = std::time::Instant::now();
2737 for i in 0..5u32 {
2738 s.tick_at(
2739 &press(KeyCode::Char('j')),
2740 t0 + std::time::Duration::from_millis(u64::from(i) * 100),
2742 );
2743 }
2744 assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
2745 }
2746
2747 #[test]
2748 fn distinct_keys_have_independent_clocks() {
2749 let mut s = new_state_with("abc\ndef\nghi");
2752 let t = std::time::Instant::now();
2753 s.tick_at(&press(KeyCode::Char('j')), t);
2754 s.tick_at(
2756 &press(KeyCode::Char('j')),
2757 t + std::time::Duration::from_millis(10),
2758 );
2759 assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
2760 s.tick_at(
2762 &press(KeyCode::Char('l')),
2763 t + std::time::Duration::from_millis(10),
2764 );
2765 assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
2766 }
2767
2768 #[test]
2771 fn cursor_home_preserves_single_cursor_behavior() {
2772 let mut s = new_state_with("hello\nworld\nthere");
2777 assert_eq!(s.cursor(), Position::ZERO);
2778 assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
2779
2780 s.apply_motion(Motion::Down);
2781 s.apply_motion(Motion::Right);
2782 s.apply_motion(Motion::Right);
2783 assert_eq!(s.cursor(), Position::new(1, 2));
2784 assert_eq!(s.cursors.count(), 1);
2786
2787 let w = s.layout.active_window().unwrap();
2789 assert!(w.viewport.top_line <= s.cursor().line);
2790 }
2791
2792 #[test]
2793 fn insert_mode_is_ungated_so_repeat_typing_works() {
2794 let mut s = new_state_with("");
2798 s.tick(&press(KeyCode::Char('i')));
2799 assert_eq!(s.modal.mode(), Mode::Insert);
2800 let t = std::time::Instant::now();
2801 for _ in 0..10 {
2802 s.tick_at(&press(KeyCode::Char('x')), t);
2803 }
2804 assert_eq!(
2805 s.buffers.get(s.active).unwrap().to_string(),
2806 "xxxxxxxxxx",
2807 "insert-mode repeat typing is ungated",
2808 );
2809 }
2810}