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(
635 || self.modal.minibuffer().chars().count(),
636 escriba_search::Prompt::caret,
637 ),
638 count: self.match_count(),
639 message: self.messages.last().map(String::as_str),
640 }
641 }
642
643 #[must_use]
649 fn match_count(&self) -> MatchCount {
650 if self.search.is_prompting() {
651 let text = self.active_text();
652 return match self.search.preview(&text) {
657 escriba_search::Preview::Landed { step, total } => {
658 MatchCount::new(step.index, total)
659 }
660 escriba_search::Preview::NoMatch => MatchCount::None,
661 escriba_search::Preview::Incomplete | escriba_search::Preview::Idle => {
662 MatchCount::Idle
663 }
664 };
665 }
666 if self.search.pattern().is_none() {
667 return MatchCount::Idle;
668 }
669 let total = self.search.matches().len();
670 let rev = self.text_rev();
673 self.search_at.as_ref().and_then(|a| a.get(rev)).map_or(
674 if total == 0 {
675 MatchCount::None
676 } else {
677 MatchCount::Idle
678 },
679 |&i| MatchCount::new(i, total),
680 )
681 }
682
683 fn repeat_last_change(&mut self) {
689 let Some(change) = self.last_change.clone() else {
690 self.messages
691 .push("E32: No previous change to repeat".to_string());
692 return;
693 };
694
695 for _ in 0..change.count.max(1) {
696 self.apply_resolved(&change.action);
697 }
698 for c in change.inserted.chars() {
699 self.apply_resolved(&Action::InsertChar(c));
700 }
701 if self.modal.mode() == Mode::Insert {
702 self.apply_resolved(&Action::ChangeMode(Mode::Normal));
706 }
707 self.last_change = Some(change);
711 self.recording_insert = false;
712 }
713
714 fn resolve_object(&self, object: escriba_core::TextObject) -> Option<Range> {
721 use escriba_core::TextObject as O;
722 let at = self.cursor_char();
723 let matches = self.search.matches();
724
725 let idx = matches.iter().position(|m| m.contains(at)).or_else(|| {
737 let starts: Vec<usize> = matches.iter().map(|m| m.start).collect();
738 match object {
739 O::NextMatch => Bound::Inclusive.first_matching(&starts, at, true),
740 O::PrevMatch => Bound::Inclusive.first_matching(&starts, at, false),
741 }
742 })?;
743
744 let m = matches.get(idx)?;
745 let buf = self.buffers.get(self.active)?;
746 Some(Range {
747 start: buf.char_to_position(m.start),
748 end: buf.char_to_position(m.end),
749 })
750 }
751
752 fn land_on(&mut self, step: escriba_search::Step) {
753 if let Some(buf) = self.buffers.get(self.active) {
754 let pos = buf.char_to_position(step.target.start);
755 self.set_cursor(pos);
756 }
757 self.search_at = Some(Anchored::new(step.index, self.text_rev()));
761 }
762
763 fn report_wrap(&mut self, step: &escriba_search::Step) {
769 if let Some(msg) = step.wrapped.message() {
770 self.messages.push(msg.to_string());
771 }
772 }
773
774 fn jump_search(&mut self, reverse: bool) {
778 self.search.relight();
781 self.jumps.push(self.cursor());
783 let at = self.cursor_char();
784 match self.search.repeat(at, reverse) {
785 Some(step) => {
786 self.report_wrap(&step);
788 self.land_on(step);
789 }
790 None => {
791 let msg = self.search.pattern().map_or_else(
792 || "E35: No previous regular expression".to_string(),
793 |p| {
794 let mut m = String::from("E486: Pattern not found: ");
795 m.push_str(p.raw());
796 m
797 },
798 );
799 self.messages.push(msg);
800 }
801 }
802 }
803
804 fn preview_search(&mut self) {
811 let text = self.active_text();
812 let Some(origin) = self.search.prompt().map(|p| p.origin) else {
813 return;
814 };
815 let target = match self.search.preview(&text) {
816 escriba_search::Preview::Landed { step, .. } => step.target.start,
817 escriba_search::Preview::Idle
821 | escriba_search::Preview::Incomplete
822 | escriba_search::Preview::NoMatch => origin,
823 };
824 if let Some(buf) = self.buffers.get(self.active) {
833 let pos = buf.char_to_position(target);
834 self.set_cursor(pos);
835 }
836 }
837
838 fn commit_search_prompt(&mut self) -> CommitOutcome {
853 let text = self.active_text();
854 let Some((origin, skip)) = self.search.prompt().map(|p| (p.origin, p.preview_skip()))
855 else {
856 return CommitOutcome::NoPrompt;
857 };
858
859 match self.search.accept(&text) {
860 escriba_search::Accepted::Committed | escriba_search::Accepted::ReusedPrevious => {
861 self.modal.clear_minibuffer();
862 self.modal.enter(Mode::Normal);
863 match self.search.commit_step_skipping(origin, skip) {
864 Some(step) => {
865 self.report_wrap(&step);
871 CommitOutcome::Landed { origin, step }
872 }
873 None => {
874 self.report_pattern_not_found();
875 CommitOutcome::NotFound
876 }
877 }
878 }
879 escriba_search::Accepted::NothingToRepeat => {
880 self.modal.clear_minibuffer();
881 self.modal.enter(Mode::Normal);
882 self.messages
883 .push("E35: No previous regular expression".to_string());
884 CommitOutcome::NoPrevious
885 }
886 escriba_search::Accepted::Invalid(e) => {
891 let mut m = String::from("E383: Invalid search string: ");
892 m.push_str(&e.to_string());
893 self.messages.push(m);
894 CommitOutcome::NoPrompt
895 }
896 }
897 }
898
899 fn report_pattern_not_found(&mut self) {
902 let mut m = String::from("E486: Pattern not found");
903 if let Some(p) = self.search.pattern() {
904 m.push_str(": ");
905 m.push_str(p.raw());
906 }
907 self.messages.push(m);
908 }
909
910 fn submit_search(&mut self) {
915 match self.commit_search_prompt() {
916 CommitOutcome::Landed { origin, step } => {
917 if let Some(buf) = self.buffers.get(self.active) {
918 let from = buf.char_to_position(origin);
919 self.jumps.push(from);
920 }
921 self.land_on(step);
922 }
923 CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
924 }
925 }
926
927 fn submit_search_operated(&mut self, op: Operator) {
934 match self.commit_search_prompt() {
935 CommitOutcome::Landed { origin, step } => {
936 if let Some(buf) = self.buffers.get(self.active) {
937 let from = buf.char_to_position(origin);
938 let target = buf.char_to_position(step.target.start);
939 self.jumps.push(from);
941 self.set_cursor(from);
942 self.apply_operator_to(op, target);
943 }
944 }
945 CommitOutcome::NotFound | CommitOutcome::NoPrevious | CommitOutcome::NoPrompt => {}
946 }
947 }
948
949 fn apply_resolved(&mut self, action: &Action) {
950 let lines_before = self.active_line_count();
953 let rev_before = self.text_rev();
956 let cline_before = self.cursor().line;
957 match action {
958 Action::Move(m) => self.apply_motion(*m),
959 Action::SearchOpen(dir) => {
960 let origin = self.cursor_char();
964 self.search.open(*dir, origin);
965 self.modal.enter(Mode::Command);
966 }
967 Action::SearchRepeat { reverse } => self.jump_search(*reverse),
968 Action::SearchWord { reverse } => {
969 let dir = if *reverse {
970 SearchDirection::Backward
971 } else {
972 SearchDirection::Forward
973 };
974 let (text, at) = (self.active_text(), self.cursor_char());
975 self.jumps.push(self.cursor());
977 match self.search.search_word(&text, at, dir) {
978 Some(step) => self.land_on(step),
979 None => self
982 .messages
983 .push("E348: No string under cursor".to_string()),
984 }
985 }
986 Action::ClearSearchHighlight => self.search.clear_highlight(),
987 Action::SearchSubmitOperated { op } => self.submit_search_operated(*op),
988 Action::TextObject(object) => {
989 if let Some(range) = self.resolve_object(*object) {
995 self.jumps.push(self.cursor());
996 self.set_cursor(range.start);
997 } else {
998 self.report_pattern_not_found();
999 }
1000 }
1001 Action::ApplyOperatorObject { op, object } => match self.resolve_object(*object) {
1002 Some(range) => self.apply_operator_over(*op, range),
1003 None => self.report_pattern_not_found(),
1004 },
1005 Action::RepeatLastChange => self.repeat_last_change(),
1006 Action::JumpBack => {
1007 let here = self.cursor();
1008 if let Some(pos) = self.jumps.back(here) {
1009 self.set_cursor(pos);
1010 } else {
1011 self.messages
1012 .push("E662: At start of changelist".to_string());
1013 }
1014 }
1015 Action::JumpForward => {
1016 if let Some(pos) = self.jumps.forward() {
1017 self.set_cursor(pos);
1018 } else {
1019 self.messages.push("E663: At end of changelist".to_string());
1020 }
1021 }
1022 Action::ChangeMode(m) => {
1023 if *m == Mode::Normal && self.search.is_prompting() {
1027 if let Some(origin) = self.search.cancel() {
1028 if let Some(buf) = self.buffers.get(self.active) {
1029 let pos = buf.char_to_position(origin);
1030 self.set_cursor(pos);
1031 }
1032 }
1033 }
1034 self.modal.enter(*m);
1035 }
1036 Action::InsertChar(c) => self.insert_char(*c),
1037 Action::Edit(edit) => self.apply_edit(edit),
1038 Action::Undo => {
1039 if let Some(buf) = self.buffers.get_mut(self.active) {
1040 let _ = buf.undo();
1041 }
1042 self.set_cursor(self.cursor());
1045 }
1046 Action::Redo => {
1047 if let Some(buf) = self.buffers.get_mut(self.active) {
1048 let _ = buf.redo();
1049 }
1050 self.set_cursor(self.cursor());
1051 }
1052 Action::Save => {
1053 if let Some(buf) = self.buffers.get_mut(self.active) {
1054 let _ = buf.save();
1055 }
1056 self.set_cursor(self.cursor());
1057 }
1058 Action::Quit => self.quit_requested = true,
1059 Action::SubmitCommand => {
1060 if self.search.is_prompting() {
1061 self.submit_search();
1062 } else {
1063 self.submit_command();
1064 }
1065 }
1066 Action::Command { name, args } => self.run_command(name, args),
1067 Action::ApplyOperator { op, motion } => self.apply_operator(*op, *motion),
1068 Action::Operator(_) => {}
1071 Action::PromptCaret { to } => {
1072 if self.search.is_prompting() {
1073 self.search.move_caret(*to);
1074 }
1075 }
1076 Action::SearchPreviewStep { forward } => {
1077 if self.search.is_prompting() {
1078 self.search.preview_step(*forward);
1079 self.preview_search();
1080 }
1081 }
1082 Action::PromptDelete => {
1083 if self.search.is_prompting() {
1084 self.search.delete_at_caret();
1085 self.preview_search();
1086 }
1087 }
1088 Action::PromptDeleteWord => {
1089 if self.search.is_prompting() {
1090 self.search.delete_word_before_caret();
1091 self.preview_search();
1092 }
1093 }
1094 Action::PromptClearToStart => {
1095 if self.search.is_prompting() {
1096 self.search.clear_before_caret();
1097 self.preview_search();
1098 }
1099 }
1100 Action::PromptBackspace => {
1101 self.prompt_backspace();
1102 if self.search.is_prompting() {
1106 self.preview_search();
1107 }
1108 }
1109 Action::PromptHistory { back } => {
1110 if self.search.is_prompting() {
1111 self.search.history_step(*back);
1112 self.preview_search();
1116 }
1117 }
1118 Action::Pending => {}
1119 }
1120 let lines_after = self.active_line_count();
1125 let cline_after = self.cursor().line;
1126 let d = match action {
1127 Action::SearchOpen(_)
1131 | Action::PromptHistory { .. }
1132 | Action::PromptBackspace
1133 | Action::PromptCaret { .. }
1134 | Action::SearchPreviewStep { .. }
1135 | Action::PromptDelete
1136 | Action::PromptDeleteWord
1137 | Action::PromptClearToStart
1138 | Action::SearchRepeat { .. }
1139 | Action::SearchWord { .. }
1140 | Action::ClearSearchHighlight
1141 | Action::SearchSubmitOperated { .. }
1142 | Action::RepeatLastChange
1145 | Action::TextObject(_)
1146 | Action::ApplyOperatorObject { .. }
1147 | Action::JumpBack
1149 | Action::JumpForward => Damage::Full,
1150 Action::InsertChar(_)
1151 | Action::Edit(_)
1152 | Action::Undo
1153 | Action::Redo
1154 | Action::ApplyOperator { .. } => {
1155 if lines_after == lines_before {
1156 Damage::span(cline_before, cline_after)
1157 } else {
1158 Damage::Lines {
1159 from: cline_before.min(cline_after),
1160 to: u32::MAX,
1161 }
1162 }
1163 }
1164 Action::Move(_) | Action::ChangeMode(_) => Damage::span(cline_before, cline_after),
1165 Action::Save => Damage::Viewport,
1166 Action::Command { .. } | Action::SubmitCommand => Damage::Full,
1167 Action::Quit | Action::Operator(_) | Action::Pending => Damage::None,
1168 };
1169 self.damage = self.damage.join(d);
1170 if self.recording_insert {
1191 match action {
1192 Action::InsertChar(c) => {
1193 if let Some(lc) = self.last_change.as_mut() {
1194 lc.inserted.push(*c);
1195 }
1196 }
1197 Action::ChangeMode(m) if *m != Mode::Insert => self.recording_insert = false,
1199 _ => {}
1200 }
1201 } else if self.text_rev() != rev_before
1202 && !matches!(
1203 action,
1204 Action::RepeatLastChange | Action::Undo | Action::Redo
1205 )
1206 {
1207 self.last_change = Some(LastChange {
1208 action: action.clone(),
1209 count: 1,
1210 inserted: String::new(),
1211 });
1212 self.recording_insert = self.modal.mode() == Mode::Insert;
1213 }
1214
1215 if action.highlight_effect() == HighlightEffect::Clear {
1220 self.search.clear_highlight();
1221 }
1222 if action.text_effect() == TextEffect::Mutates && self.search.pattern().is_some() {
1231 let text = self.active_text();
1232 self.search.refresh(&text);
1233 }
1238 self.bump_gen();
1243 }
1244
1245 fn resolve_motion(&self, from: Position, motion: Motion) -> Option<Position> {
1255 let buf = self.buffers.get(self.active)?;
1256 let pos = from;
1257 Some(match motion {
1258 Motion::SearchNext | Motion::SearchPrev => {
1263 let at = buf.position_to_char(pos).ok()?;
1264 let step = self
1265 .search
1266 .repeat(at, matches!(motion, Motion::SearchPrev))?;
1267 buf.char_to_position(step.target.start)
1268 }
1269 Motion::Left => Position::new(pos.line, pos.column.saturating_sub(1)),
1270 Motion::Right => Position::new(pos.line, pos.column.saturating_add(1)),
1271 Motion::Up => Position::new(pos.line.saturating_sub(1), pos.column),
1272 Motion::Down => Position::new(pos.line.saturating_add(1), pos.column),
1273 Motion::LineStart => Position::new(pos.line, 0),
1274 Motion::LineEnd => Position::new(pos.line, buf.line_len_chars(pos.line)),
1275 Motion::LineFirstNonBlank => first_non_blank(buf, pos.line),
1276 Motion::DocStart => Position::ZERO,
1277 Motion::DocEnd => Position::new(
1278 buf.line_count().saturating_sub(1),
1279 buf.line_len_chars(buf.line_count().saturating_sub(1)),
1280 ),
1281 Motion::WordStartNext | Motion::WordEndNext => word_next(buf, pos),
1282 Motion::WordStartPrev => word_prev(buf, pos),
1283 Motion::PageDown | Motion::HalfPageDown => {
1284 Position::new(pos.line.saturating_add(10), pos.column)
1285 }
1286 Motion::PageUp | Motion::HalfPageUp => {
1287 Position::new(pos.line.saturating_sub(10), pos.column)
1288 }
1289 Motion::GotoLine(n) => Position::new(n.saturating_sub(1), 0),
1290 Motion::ForwardSexp
1293 | Motion::BackwardSexp
1294 | Motion::UpList
1295 | Motion::DownList
1296 | Motion::BeginningOfDefun
1297 | Motion::EndOfDefun
1298 | Motion::BeginningOfSexp
1299 | Motion::EndOfSexp => pos,
1300 })
1301 }
1302
1303 fn apply_motion(&mut self, motion: Motion) {
1304 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1312 self.jump_search(matches!(motion, Motion::SearchPrev));
1313 return;
1314 }
1315 let Some(pos) = self.resolve_motion(self.cursor(), motion) else {
1316 return;
1317 };
1318 self.set_cursor(pos);
1321 }
1322
1323 fn apply_operator(&mut self, op: Operator, motion: Motion) {
1330 let from = self.cursor();
1331 let Some(to) = self.resolve_motion(from, motion) else {
1332 if matches!(motion, Motion::SearchNext | Motion::SearchPrev) {
1337 if self.search.pattern().is_none() {
1338 self.messages
1339 .push("E35: No previous regular expression".to_string());
1340 } else {
1341 self.report_pattern_not_found();
1342 }
1343 }
1344 return;
1345 };
1346 self.apply_operator_to(op, to);
1347 }
1348
1349 fn apply_operator_to(&mut self, op: Operator, to: Position) {
1356 let from = self.cursor();
1357 self.apply_operator_over(
1358 op,
1359 Range {
1360 start: from,
1361 end: to,
1362 },
1363 );
1364 }
1365
1366 fn apply_operator_over(&mut self, op: Operator, range: Range) {
1373 let range = range.normalized();
1374 if range.is_empty() {
1375 return;
1376 }
1377 let text = self
1379 .buffers
1380 .get(self.active)
1381 .and_then(|buf| buf.slice(range).ok());
1382 if op.leaves_register() {
1383 if let Some(t) = &text {
1384 self.register = Some(t.clone());
1385 }
1386 }
1387 match op {
1388 Operator::Delete | Operator::Change => {
1391 if let Some(buf) = self.buffers.get_mut(self.active) {
1392 let _ = buf.apply(&Edit::delete(range));
1393 }
1394 self.set_cursor(range.start);
1395 if op == Operator::Change {
1396 self.modal.enter(Mode::Insert);
1397 }
1398 }
1399 Operator::Yank => {
1402 self.set_cursor(range.start);
1403 }
1404 _ => {
1408 self.messages
1409 .push("operator not yet implemented".to_owned());
1410 }
1411 }
1412 }
1413
1414 #[must_use]
1417 pub fn register(&self) -> Option<&str> {
1418 self.register.as_deref()
1419 }
1420
1421 fn insert_char(&mut self, c: char) {
1422 if self.modal.mode() == Mode::Command {
1423 if self.search.is_prompting() {
1427 self.search.push(c);
1441 self.preview_search();
1442 } else {
1443 self.modal.push_minibuffer(c);
1444 }
1445 return;
1446 }
1447 let cursor = self.cursor();
1448 let Some(buf) = self.buffers.get_mut(self.active) else {
1449 return;
1450 };
1451 let edit = Edit::insert(cursor, c.to_string());
1452 if buf.apply(&edit).is_ok() {
1453 let next = if c == '\n' {
1454 Position::new(cursor.line.saturating_add(1), 0)
1455 } else {
1456 cursor.shift_right(1)
1457 };
1458 self.set_cursor(next);
1461 }
1462 }
1463
1464 fn prompt_backspace(&mut self) -> bool {
1468 if self.modal.mode() != Mode::Command {
1469 return false;
1470 }
1471 if self.search.is_prompting() {
1472 if self.search.backspace() {
1477 self.modal.clear_minibuffer();
1478 self.modal.enter(Mode::Normal);
1479 }
1480 return true;
1483 }
1484 self.modal.pop_minibuffer();
1485 true
1486 }
1487
1488 fn apply_edit(&mut self, _edit: &Edit) {
1489 }
1493
1494 fn submit_command(&mut self) {
1495 let line = self.modal.minibuffer().to_string();
1499 self.modal.escape();
1500 let (name, args) = parse_command_line(&line);
1501 if name.is_empty() {
1502 return;
1503 }
1504 self.run_command(&name, &args);
1505 }
1506
1507 fn run_command(&mut self, name: &str, args: &[String]) {
1508 if matches!(name, "noh" | "nohl" | "nohlsearch") {
1514 self.search.clear_highlight();
1515 return;
1516 }
1517 if self.plugin_host.pending() > 0 {
1523 let pending = self.plugin_host.pending_for_command(name);
1524 for src in pending {
1525 self.apply_plugin_entry(&src);
1526 }
1527 }
1528 let active = Some(self.active);
1529 let mut quit = false;
1530 {
1531 let mut ctx = EditContext {
1532 buffers: &mut self.buffers,
1533 active,
1534 state: &mut self.modal,
1535 quit_requested: &mut quit,
1536 };
1537 let _ = self.commands.run(name, &mut ctx, args);
1538 }
1539 if quit {
1542 self.quit_requested = true;
1543 }
1544 }
1545
1546 #[must_use]
1551 pub fn snapshot(&self) -> EditorSnapshot {
1552 let current_line = self
1553 .buffers
1554 .get(self.active)
1555 .and_then(|b| b.line(self.cursor().line))
1556 .map(|s| s.trim_end_matches('\n').to_string())
1557 .unwrap_or_default();
1558 let buffer_name = self
1559 .buffers
1560 .get(self.active)
1561 .and_then(|b| b.path.as_ref())
1562 .map(|p| p.display().to_string())
1563 .unwrap_or_else(|| "[scratch]".to_string());
1564 EditorSnapshot {
1565 cursor_line: i64::from(self.cursor().line),
1566 cursor_column: i64::from(self.cursor().column),
1567 current_line,
1568 mode: self.modal.mode().as_str().to_string(),
1569 buffer_name,
1570 }
1571 }
1572
1573 pub fn run_lisp(&mut self, src: &str) -> Result<(), VmError> {
1589 let mut host = EscribaHost::with_snapshot(self.snapshot());
1590 let vm = self.lisp_vm.get_or_insert_with(EscribaVm::new);
1591 vm.eval(src, &mut host)?;
1592 let effects = host.take_effects();
1593 self.apply_host_effects(effects);
1594 Ok(())
1595 }
1596
1597 pub fn apply_host_effects(&mut self, effects: Vec<HostEffect>) {
1601 for eff in effects {
1602 match eff {
1603 HostEffect::Message(m) => self.messages.push(m),
1604 HostEffect::RunCommand { name, args } => self.run_command(&name, &args),
1605 HostEffect::SetOption { name, value } => {
1606 self.options.insert(name, value);
1607 }
1608 HostEffect::InsertText(text) => self.insert_text(&text),
1609 }
1610 }
1611 }
1612
1613 fn insert_text(&mut self, text: &str) {
1616 if text.is_empty() {
1617 return;
1618 }
1619 let cursor = self.cursor();
1620 let Some(buf) = self.buffers.get_mut(self.active) else {
1621 return;
1622 };
1623 let edit = Edit::insert(cursor, text.to_string());
1624 if buf.apply(&edit).is_ok() {
1625 let next = if let Some(nl) = text.rfind('\n') {
1626 let added_lines = u32::try_from(text.matches('\n').count()).unwrap_or(0);
1627 let last_line_len = u32::try_from(text[nl + 1..].chars().count()).unwrap_or(0);
1628 Position::new(cursor.line + added_lines, last_line_len)
1629 } else {
1630 let n = u32::try_from(text.chars().count()).unwrap_or(0);
1631 cursor.shift_right(n)
1632 };
1633 self.set_cursor(next);
1636 }
1637 }
1638}
1639
1640fn first_non_blank(buf: &escriba_buffer::Buffer, line: u32) -> Position {
1641 let Some(text) = buf.line(line) else {
1642 return Position::new(line, 0);
1643 };
1644 let col = text
1645 .chars()
1646 .take_while(|c| c.is_whitespace() && *c != '\n')
1647 .count();
1648 Position::new(line, u32::try_from(col).unwrap_or(0))
1649}
1650
1651fn word_next(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1652 let Some(text) = buf.line(pos.line) else {
1653 return pos;
1654 };
1655 let chars: Vec<char> = text.chars().collect();
1656 let start = pos.column as usize;
1657 let mut i = start;
1658 while i < chars.len() && !chars[i].is_whitespace() {
1659 i += 1;
1660 }
1661 while i < chars.len() && chars[i].is_whitespace() {
1662 i += 1;
1663 }
1664 if i >= chars.len() {
1665 if pos.line + 1 < buf.line_count() {
1667 return Position::new(pos.line + 1, 0);
1668 }
1669 }
1670 Position::new(pos.line, u32::try_from(i).unwrap_or(pos.column))
1671}
1672
1673fn word_prev(buf: &escriba_buffer::Buffer, pos: Position) -> Position {
1674 let Some(text) = buf.line(pos.line) else {
1675 return pos;
1676 };
1677 let chars: Vec<char> = text.chars().collect();
1678 let mut i = (pos.column as usize).min(chars.len());
1679 while i > 0 && chars[i - 1].is_whitespace() {
1680 i -= 1;
1681 }
1682 while i > 0 && !chars[i - 1].is_whitespace() {
1683 i -= 1;
1684 }
1685 Position::new(pos.line, u32::try_from(i).unwrap_or(0))
1686}
1687
1688fn parse_command_line(line: &str) -> (String, Vec<String>) {
1689 let mut parts = line.split_whitespace();
1690 let Some(first) = parts.next() else {
1691 return (String::new(), Vec::new());
1692 };
1693 let head = first.strip_prefix(':').unwrap_or(first);
1694 let name = match head {
1695 "w" => "save",
1696 "q" => "quit",
1697 "u" => "undo",
1698 other => other,
1699 };
1700 (name.to_string(), parts.map(str::to_string).collect())
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705 use super::*;
1706 use madori::event::{KeyCode, KeyEvent, Modifiers};
1707
1708 fn type_search(st: &mut EditorState, dir: SearchDirection, pat: &str) {
1716 st.apply(&Action::SearchOpen(dir));
1717 for c in pat.chars() {
1718 st.apply(&Action::InsertChar(c));
1719 }
1720 st.apply(&Action::SubmitCommand);
1721 }
1722
1723 #[test]
1724 fn slash_search_moves_the_cursor_to_the_match() {
1725 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1726 type_search(&mut st, SearchDirection::Forward, "charlie");
1727 assert_eq!(st.cursor().line, 2, "cursor lands on the matching line");
1728 assert_eq!(st.modal.mode(), Mode::Normal, "prompt closes on submit");
1729 assert_eq!(st.search.matches().len(), 1);
1730 }
1731
1732 #[test]
1733 fn n_and_N_walk_matches_in_both_directions() {
1734 let mut st = new_state_with("foo\nbar\nfoo\nbaz\nfoo\n");
1735 type_search(&mut st, SearchDirection::Forward, "foo");
1736 let first = st.cursor().line;
1737 st.apply(&Action::SearchRepeat { reverse: false });
1738 let second = st.cursor().line;
1739 assert!(second > first, "n advances ({first} -> {second})");
1740 st.apply(&Action::SearchRepeat { reverse: true });
1741 assert_eq!(st.cursor().line, first, "N comes back");
1742 }
1743
1744 #[test]
1745 fn star_searches_the_word_under_the_cursor() {
1746 let mut st = new_state_with("needle\nhaystack\nneedle\n");
1747 st.apply(&Action::SearchWord { reverse: false });
1748 assert_eq!(st.search.pattern().unwrap().raw(), r"\bneedle\b");
1749 assert_eq!(st.cursor().line, 2, "jumps to the other occurrence");
1750 }
1751
1752 #[test]
1753 fn escape_abandons_the_prompt_and_keeps_the_previous_search() {
1754 let mut st = new_state_with("foo\nbar\nfoo\n");
1755 type_search(&mut st, SearchDirection::Forward, "foo");
1756 let matches_before = st.search.matches().len();
1757
1758 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1759 st.apply(&Action::InsertChar('z'));
1760 st.apply(&Action::ChangeMode(Mode::Normal));
1761
1762 assert!(!st.search.is_prompting(), "prompt gone");
1763 assert_eq!(
1764 st.search.pattern().unwrap().raw(),
1765 "foo",
1766 "old pattern survives"
1767 );
1768 assert_eq!(
1769 st.search.matches().len(),
1770 matches_before,
1771 "old highlights survive"
1772 );
1773 }
1774
1775 #[test]
1776 fn a_search_prompt_and_an_ex_command_are_not_confused() {
1777 let mut st = new_state_with("foo\n");
1778 st.apply(&Action::ChangeMode(Mode::Command));
1780 assert!(!st.search.is_prompting(), "`:` must not open a search");
1781 st.apply(&Action::InsertChar('w'));
1782 assert!(
1783 st.search.prompt().is_none(),
1784 "typed char went to the ex line"
1785 );
1786 }
1787
1788 #[test]
1789 fn a_missing_pattern_reports_instead_of_failing_silently() {
1790 let mut st = new_state_with("alpha\nbravo\n");
1791 type_search(&mut st, SearchDirection::Forward, "zzz");
1792 assert!(
1793 st.messages.iter().any(|m| m.contains("E486")),
1794 "must report not-found, got {:?}",
1795 st.messages
1796 );
1797 }
1798
1799 #[test]
1800 fn n_without_any_search_reports_rather_than_moving() {
1801 let mut st = new_state_with("alpha\nbravo\n");
1802 let before = st.cursor();
1803 st.apply(&Action::SearchRepeat { reverse: false });
1804 assert_eq!(st.cursor(), before, "cursor must not move");
1805 assert!(
1806 st.messages.iter().any(|m| m.contains("E35")),
1807 "got {:?}",
1808 st.messages
1809 );
1810 }
1811
1812 #[test]
1813 fn search_as_a_motion_composes_with_an_operator() {
1814 let mut st = new_state_with("alpha bravo charlie\n");
1816 type_search(&mut st, SearchDirection::Forward, "charlie");
1817 st.set_cursor(Position::new(0, 0));
1818 let target = st.resolve_motion(Position::new(0, 0), Motion::SearchNext);
1819 assert!(target.is_some(), "search must resolve as a motion");
1820 assert_eq!(target.unwrap().column, 12, "at `charlie`");
1821 }
1822
1823 #[test]
1824 fn search_motion_without_a_pattern_fails_the_motion_instead_of_moving_to_zero() {
1825 let st = new_state_with("alpha bravo\n");
1828 assert!(
1829 st.resolve_motion(Position::new(0, 5), Motion::SearchNext)
1830 .is_none()
1831 );
1832 }
1833
1834 #[test]
1835 fn clear_highlight_keeps_the_pattern_usable() {
1836 let mut st = new_state_with("foo\nbar\nfoo\n");
1837 type_search(&mut st, SearchDirection::Forward, "foo");
1838 st.apply(&Action::ClearSearchHighlight);
1839 assert!(st.search.highlights().is_empty(), "nothing lit");
1840 st.apply(&Action::SearchRepeat { reverse: false });
1841 assert!(st.search.pattern().is_some(), "but n still works");
1842 }
1843
1844 #[test]
1845 fn typing_previews_incrementally_before_commit() {
1846 let mut st = new_state_with("alpha\nbravo\ncharlie\n");
1847 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1848 for c in "charlie".chars() {
1849 st.apply(&Action::InsertChar(c));
1850 }
1851 assert_eq!(st.cursor().line, 2, "preview moved the cursor");
1853 assert!(st.search.pattern().is_none(), "but nothing is committed");
1854 }
1855
1856 #[test]
1857 fn backspace_corrects_the_prompt_and_reruns_the_preview() {
1858 let mut st = new_state_with("alpha\nbravo\n");
1859 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1860 for c in "bravox".chars() {
1861 st.apply(&Action::InsertChar(c));
1862 }
1863 assert_eq!(st.search.prompt().unwrap().text, "bravox");
1864 st.apply(&Action::PromptBackspace);
1865 assert_eq!(st.search.prompt().unwrap().text, "bravo", "typo corrected");
1866 assert_eq!(
1867 st.status_model().prompt_text,
1868 "bravo",
1869 "the model reads the PROMPT — the minibuffer is the ex-line's store",
1870 );
1871 assert_eq!(st.cursor().line, 1, "preview re-ran and found it");
1872 }
1873
1874 #[test]
1875 fn backspacing_past_the_slash_closes_the_prompt() {
1876 let mut st = new_state_with("alpha\n");
1877 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1878 st.apply(&Action::InsertChar('a'));
1879 st.apply(&Action::PromptBackspace);
1880 st.apply(&Action::PromptBackspace);
1881 assert!(!st.search.is_prompting(), "prompt closed");
1882 assert_eq!(st.modal.mode(), Mode::Normal);
1883 }
1884
1885 #[test]
1886 fn noh_clears_highlights_and_keeps_the_pattern() {
1887 let mut st = new_state_with("foo\nbar\nfoo\n");
1888 type_search(&mut st, SearchDirection::Forward, "foo");
1889 assert!(!st.search.highlights().is_empty());
1890 st.run_command("noh", &[]);
1891 assert!(st.search.highlights().is_empty(), ":noh turns them off");
1892 assert!(st.search.pattern().is_some(), "but n still works");
1893 }
1894
1895 #[test]
1896 fn noh_accepts_the_vim_aliases() {
1897 for name in ["noh", "nohl", "nohlsearch"] {
1898 let mut st = new_state_with("foo\nfoo\n");
1899 type_search(&mut st, SearchDirection::Forward, "foo");
1900 st.run_command(name, &[]);
1901 assert!(st.search.highlights().is_empty(), "{name} must clear");
1902 }
1903 }
1904
1905 #[test]
1906 fn backspace_on_the_ex_line_does_not_touch_search_state() {
1907 let mut st = new_state_with("foo\n");
1908 st.apply(&Action::ChangeMode(Mode::Command));
1909 st.apply(&Action::InsertChar('w'));
1910 st.apply(&Action::InsertChar('q'));
1911 st.apply(&Action::PromptBackspace);
1912 assert_eq!(st.status_model().prompt_text, "w");
1913 assert!(st.search.prompt().is_none(), "no search was involved");
1914 }
1915
1916 #[test]
1917 fn up_arrow_recalls_the_previous_search() {
1918 let mut st = new_state_with("alpha\nbravo\n");
1919 type_search(&mut st, SearchDirection::Forward, "bravo");
1920 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1921 st.apply(&Action::PromptHistory { back: true });
1922 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1923 assert_eq!(
1924 st.status_model().prompt_text,
1925 "bravo",
1926 "display follows the prompt"
1927 );
1928 }
1929
1930 #[test]
1931 fn arrowing_back_down_restores_the_half_typed_pattern() {
1932 let mut st = new_state_with("alpha\nbravo\n");
1933 type_search(&mut st, SearchDirection::Forward, "bravo");
1934 st.apply(&Action::SearchOpen(SearchDirection::Forward));
1935 st.apply(&Action::InsertChar('a'));
1936 st.apply(&Action::PromptHistory { back: true });
1937 assert_eq!(st.search.prompt().unwrap().text, "bravo");
1938 st.apply(&Action::PromptHistory { back: false });
1939 assert_eq!(
1940 st.search.prompt().unwrap().text,
1941 "a",
1942 "the draft comes back"
1943 );
1944 assert_eq!(st.status_model().prompt_text, "a");
1945 }
1946
1947 #[test]
1948 fn history_arrows_do_nothing_on_the_ex_line() {
1949 let mut st = new_state_with("alpha\n");
1950 st.apply(&Action::ChangeMode(Mode::Command));
1951 st.apply(&Action::InsertChar('w'));
1952 st.apply(&Action::PromptHistory { back: true });
1953 assert_eq!(st.status_model().prompt_text, "w", "ex line untouched");
1954 }
1955
1956 fn new_state_with(text: &str) -> EditorState {
1957 let mut bufs = BufferSet::new();
1958 let id = bufs.scratch(text);
1959 EditorState::new_with_buffer(bufs, id)
1960 }
1961
1962 #[test]
1968 fn edit_gen_advances_on_applied_action_not_on_read() {
1969 let mut s = new_state_with("hello\nworld\n");
1970 let g0 = s.edit_gen();
1971 s.apply(&Action::InsertChar('X'));
1972 assert_ne!(
1973 s.edit_gen(),
1974 g0,
1975 "an applied action must advance the refresh generation",
1976 );
1977 let g1 = s.edit_gen();
1979 assert_eq!(s.edit_gen(), g1, "reading edit_gen must not advance it");
1980 }
1981
1982 #[test]
1987 fn damage_tracks_edit_scope_and_drains() {
1988 let mut s = new_state_with("hello\nworld\n");
1989 assert!(s.damage().is_none(), "a fresh state has no damage");
1990
1991 s.apply(&Action::InsertChar('X')); assert_eq!(
1993 s.damage(),
1994 Damage::Lines { from: 0, to: 0 },
1995 "a local edit damages just its line",
1996 );
1997
1998 let drained = s.take_damage();
1999 assert_eq!(drained, Damage::Lines { from: 0, to: 0 });
2000 assert!(s.damage().is_none(), "take_damage drains to None");
2001
2002 s.apply(&Action::InsertChar('\n')); assert_eq!(
2004 s.damage(),
2005 Damage::Lines {
2006 from: 0,
2007 to: u32::MAX,
2008 },
2009 "a line-count change damages to end-of-document",
2010 );
2011 }
2012
2013 fn new_state_small_viewport(text: &str, vis_lines: u32, vis_cols: u32) -> EditorState {
2017 let mut s = new_state_with(text);
2018 for w in &mut s.layout.windows {
2019 w.viewport.visible_lines = vis_lines;
2020 w.viewport.visible_columns = vis_cols;
2021 }
2022 s
2023 }
2024
2025 fn assert_cursor_in_viewport(s: &EditorState, ctx: &str) {
2030 let w = s.layout.active_window().expect("active window");
2031 let v = w.viewport;
2032 let c = s.cursor();
2033 assert!(
2034 v.top_line <= c.line && c.line < v.top_line + v.visible_lines,
2035 "[{ctx}] cursor line {} not in vertical window [{}, {}); viewport={v:?}",
2036 c.line,
2037 v.top_line,
2038 v.top_line + v.visible_lines,
2039 );
2040 assert!(
2041 v.left_column <= c.column && c.column < v.left_column + v.visible_columns,
2042 "[{ctx}] cursor column {} not in horizontal window [{}, {}); viewport={v:?}",
2043 c.column,
2044 v.left_column,
2045 v.left_column + v.visible_columns,
2046 );
2047 }
2048
2049 fn press(kc: KeyCode) -> AppEvent {
2050 AppEvent::Key(KeyEvent {
2051 key: kc,
2052 pressed: true,
2053 modifiers: Modifiers::default(),
2054 text: None,
2055 })
2056 }
2057
2058 fn line0_len(s: &EditorState) -> u32 {
2061 s.buffers.get(s.active).unwrap().line_len_chars(0)
2062 }
2063
2064 #[test]
2065 fn delete_to_line_end_clears_line_and_fills_register() {
2066 let mut s = new_state_with("hello world");
2067 s.apply(&Action::ApplyOperator {
2068 op: Operator::Delete,
2069 motion: Motion::LineEnd,
2070 });
2071 assert_eq!(line0_len(&s), 0, "d$ deletes to end of line");
2072 assert_eq!(
2073 s.register(),
2074 Some("hello world"),
2075 "delete fills the register"
2076 );
2077 assert_eq!(
2078 s.cursor(),
2079 Position::ZERO,
2080 "cursor lands at the range start"
2081 );
2082 }
2083
2084 #[test]
2085 fn delete_over_right_motion_removes_one_char() {
2086 let mut s = new_state_with("abc");
2087 s.apply(&Action::ApplyOperator {
2088 op: Operator::Delete,
2089 motion: Motion::Right,
2090 });
2091 assert_eq!(
2092 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2093 Some("bc")
2094 );
2095 assert_eq!(s.register(), Some("a"));
2096 }
2097
2098 #[test]
2099 fn change_to_line_end_deletes_and_enters_insert() {
2100 let mut s = new_state_with("hello world");
2101 assert_eq!(s.modal.mode(), Mode::Normal);
2102 s.apply(&Action::ApplyOperator {
2103 op: Operator::Change,
2104 motion: Motion::LineEnd,
2105 });
2106 assert_eq!(line0_len(&s), 0, "c$ deletes the range");
2107 assert_eq!(
2108 s.modal.mode(),
2109 Mode::Insert,
2110 "change enters Insert to type the replacement"
2111 );
2112 assert_eq!(
2113 s.register(),
2114 Some("hello world"),
2115 "change fills the register"
2116 );
2117 }
2118
2119 #[test]
2120 fn yank_to_line_end_fills_register_without_mutating() {
2121 let mut s = new_state_with("hello world");
2122 s.apply(&Action::ApplyOperator {
2123 op: Operator::Yank,
2124 motion: Motion::LineEnd,
2125 });
2126 assert_eq!(line0_len(&s), 11, "yank does not mutate the buffer");
2127 assert_eq!(s.register(), Some("hello world"), "yank fills the register");
2128 assert_eq!(s.modal.mode(), Mode::Normal, "yank stays in Normal");
2129 }
2130
2131 #[test]
2132 fn resolve_motion_is_the_shared_target_for_move_and_operator() {
2133 let mut s = new_state_with("hello world");
2137 let target = s.resolve_motion(Position::ZERO, Motion::LineEnd).unwrap();
2138 assert_eq!(target, Position::new(0, 11));
2139 s.apply_motion(Motion::LineEnd);
2140 assert_eq!(
2141 s.cursor(),
2142 target,
2143 "the move path resolves the same target the operator uses"
2144 );
2145 }
2146
2147 #[test]
2148 fn empty_motion_range_is_a_no_op() {
2149 let mut s = new_state_with("abc");
2152 s.apply(&Action::ApplyOperator {
2153 op: Operator::Delete,
2154 motion: Motion::LineStart,
2155 });
2156 assert_eq!(
2157 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2158 Some("abc")
2159 );
2160 assert_eq!(s.register(), None);
2161 }
2162
2163 #[test]
2164 fn operator_then_motion_composes_through_the_pending_fsm() {
2165 let mut s = new_state_with("hello world");
2169 s.apply(&Action::Operator(Operator::Delete));
2170 assert_eq!(line0_len(&s), 11, "the operator key alone mutates nothing");
2171 s.apply(&Action::Move(Motion::LineEnd));
2172 assert_eq!(
2173 line0_len(&s),
2174 0,
2175 "d then $ composes d$ and deletes the line"
2176 );
2177 assert_eq!(s.register(), Some("hello world"));
2178 }
2179
2180 #[test]
2181 fn change_operator_through_fsm_enters_insert() {
2182 let mut s = new_state_with("hello world");
2183 s.apply(&Action::Operator(Operator::Change));
2184 s.apply(&Action::Move(Motion::LineEnd));
2185 assert_eq!(s.modal.mode(), Mode::Insert, "c$ deletes and enters Insert");
2186 }
2187
2188 #[test]
2189 fn lone_motion_after_no_operator_just_moves() {
2190 let mut s = new_state_with("hello world");
2192 s.apply(&Action::Move(Motion::LineEnd));
2193 assert_eq!(s.cursor(), Position::new(0, 11));
2194 assert_eq!(line0_len(&s), 11, "a bare motion never mutates");
2195 }
2196
2197 #[test]
2198 fn counted_operator_deletes_count_times() {
2199 let mut s = new_state_with("abcdef");
2203 s.apply_counted(&Action::Operator(Operator::Delete), 3);
2204 assert_eq!(line0_len(&s), 6, "the operator key alone mutates nothing");
2205 s.apply(&Action::Move(Motion::Right));
2206 assert_eq!(
2207 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2208 Some("def")
2209 );
2210 }
2211
2212 #[test]
2213 fn operator_and_motion_counts_multiply_end_to_end() {
2214 let mut s = new_state_with("abcdefgh");
2216 s.apply_counted(&Action::Operator(Operator::Delete), 2);
2217 s.apply_counted(&Action::Move(Motion::Right), 3);
2218 assert_eq!(
2219 s.buffers.get(s.active).unwrap().line(0).as_deref(),
2220 Some("gh")
2221 );
2222 }
2223
2224 #[test]
2225 fn bare_counted_motion_still_repeats_no_regression() {
2226 let mut s = new_state_with("a\nb\nc\nd\ne");
2229 s.apply_counted(&Action::Move(Motion::Down), 3);
2230 assert_eq!(s.cursor().line, 3, "5j-style counted motion preserved");
2231 }
2232
2233 struct SpacedClock(std::time::Instant);
2239 impl SpacedClock {
2240 fn new() -> Self {
2241 Self(std::time::Instant::now())
2242 }
2243 fn next(&mut self) -> std::time::Instant {
2244 self.0 += std::time::Duration::from_secs(1);
2245 self.0
2246 }
2247 }
2248
2249 #[test]
2250 fn hjkl_moves_cursor() {
2251 let mut s = new_state_with("hello\nworld");
2252 s.tick(&press(KeyCode::Char('l')));
2253 assert_eq!(s.cursor().column, 1);
2254 s.tick(&press(KeyCode::Char('j')));
2255 assert_eq!(s.cursor().line, 1);
2256 s.tick(&press(KeyCode::Char('h')));
2257 assert_eq!(s.cursor().column, 0);
2258 }
2259
2260 #[test]
2261 fn insert_mode_inserts_chars() {
2262 let mut s = new_state_with("");
2263 s.tick(&press(KeyCode::Char('i')));
2264 assert_eq!(s.modal.mode(), Mode::Insert);
2265 s.tick(&press(KeyCode::Char('h')));
2266 s.tick(&press(KeyCode::Char('i')));
2267 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "hi");
2268 assert_eq!(s.cursor().column, 2);
2269 }
2270
2271 #[test]
2272 fn esc_returns_to_normal() {
2273 let mut s = new_state_with("");
2274 s.tick(&press(KeyCode::Char('i')));
2275 s.tick(&press(KeyCode::Escape));
2276 assert_eq!(s.modal.mode(), Mode::Normal);
2277 }
2278
2279 #[test]
2280 fn count_prefix_repeats_motion() {
2281 let mut s = new_state_with("abcdefghij");
2282 s.tick(&press(KeyCode::Char('5')));
2283 s.tick(&press(KeyCode::Char('l')));
2284 assert_eq!(s.cursor().column, 5);
2285 }
2286
2287 #[test]
2288 fn close_event_requests_quit() {
2289 let mut s = new_state_with("");
2290 s.tick(&AppEvent::CloseRequested);
2291 assert!(s.quit_requested);
2292 }
2293
2294 #[test]
2295 fn word_next_jumps_past_whitespace() {
2296 let mut s = new_state_with("foo bar baz");
2297 let mut clk = SpacedClock::new();
2300 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2301 assert_eq!(s.cursor().column, 4);
2302 s.tick_at(&press(KeyCode::Char('w')), clk.next());
2303 assert_eq!(s.cursor().column, 8);
2304 }
2305
2306 #[test]
2309 fn leader_sequence_holds_then_resolves() {
2310 let mut s = new_state_with("a\nbb\nccc");
2311 s.keymap.bind_sequence(
2312 Mode::Normal,
2313 vec![Key::Char(','), Key::Char('g')],
2314 Action::Move(Motion::DocEnd),
2315 "doc end",
2316 );
2317 s.on_key(&Key::Char(','));
2319 assert_eq!(s.pending_keys, vec![Key::Char(',')]);
2320 assert_eq!(s.cursor(), Position::ZERO);
2321 s.on_key(&Key::Char('g'));
2323 assert!(s.pending_keys.is_empty());
2324 assert_eq!(s.cursor().line, 2);
2325 }
2326
2327 #[test]
2328 fn two_key_gg_jumps_doc_start() {
2329 let mut s = new_state_with("a\nbb\nccc");
2330 s.keymap.bind_sequence(
2331 Mode::Normal,
2332 vec![Key::Char('g'), Key::Char('g')],
2333 Action::Move(Motion::DocStart),
2334 "doc start",
2335 );
2336 let mut clk = SpacedClock::new();
2337 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2338 s.tick_at(&press(KeyCode::Char('j')), clk.next());
2339 assert_eq!(s.cursor().line, 2);
2340 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2342 s.on_key(&Key::Char('g')); assert_eq!(s.cursor(), Position::ZERO);
2344 }
2345
2346 #[test]
2347 fn broken_sequence_aborts_and_clears_pending() {
2348 let mut s = new_state_with("hello");
2349 s.keymap.bind_sequence(
2350 Mode::Normal,
2351 vec![Key::Char('g'), Key::Char('g')],
2352 Action::Move(Motion::DocEnd),
2353 "doc end",
2354 );
2355 s.on_key(&Key::Char('g')); assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2357 s.on_key(&Key::Char('x')); assert!(s.pending_keys.is_empty());
2359 assert_eq!(s.cursor(), Position::ZERO);
2360 }
2361
2362 #[test]
2363 fn single_binding_wins_over_sequence_prefix() {
2364 let mut s = new_state_with("abcde");
2368 let mut clk = SpacedClock::new();
2369 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2370 s.tick_at(&press(KeyCode::Char('l')), clk.next());
2371 assert_eq!(s.cursor().column, 2);
2372 s.keymap.bind_sequence(
2373 Mode::Normal,
2374 vec![Key::Char('h'), Key::Char('z')],
2375 Action::Move(Motion::DocEnd),
2376 "shadowed",
2377 );
2378 s.on_key(&Key::Char('h'));
2379 assert!(s.pending_keys.is_empty(), "single binding should not pend");
2380 assert_eq!(s.cursor().column, 1, "h moved left immediately");
2381 }
2382
2383 #[test]
2386 fn lisp_set_option_writes_live_options() {
2387 let mut s = new_state_with("");
2388 s.run_lisp(r#"(set-option "number" "true")"#).unwrap();
2389 assert_eq!(s.options.get("number").map(String::as_str), Some("true"));
2390 }
2391
2392 #[test]
2393 fn lisp_insert_modifies_buffer_and_advances_cursor() {
2394 let mut s = new_state_with("");
2395 s.run_lisp(r#"(insert "abc")"#).unwrap();
2396 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2397 assert_eq!(s.cursor(), Position::new(0, 3));
2398 }
2399
2400 #[test]
2401 fn lisp_message_appends_to_messages() {
2402 let mut s = new_state_with("");
2403 s.run_lisp(r#"(message "hello from lisp")"#).unwrap();
2404 assert_eq!(s.messages, vec!["hello from lisp".to_string()]);
2405 }
2406
2407 #[test]
2408 fn lisp_reads_snapshot_and_branches_to_effect() {
2409 let mut s = new_state_with("one\ntwo\nthree");
2412 s.run_lisp(r#"(if (= (cursor-line) 0) (set-option "pos" "top") (set-option "pos" "mid"))"#)
2414 .unwrap();
2415 assert_eq!(s.options.get("pos").map(String::as_str), Some("top"));
2416 }
2417
2418 #[test]
2419 fn lisp_run_command_effect_drives_registry() {
2420 let mut s = new_state_with("");
2424 s.run_lisp(r#"(insert "abc")"#).unwrap();
2425 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "abc");
2426 s.run_lisp(r#"(run-command "undo")"#).unwrap();
2427 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "");
2428 }
2429
2430 #[test]
2431 fn lisp_run_command_quit_sets_quit_requested_via_typed_flag() {
2432 let mut s = new_state_with("");
2437 s.run_lisp(r#"(run-command "quit")"#).unwrap();
2438 assert!(s.quit_requested, "lisp-driven quit must set quit_requested");
2439 assert_eq!(
2440 s.modal.minibuffer(),
2441 "",
2442 "quit must not pollute any command line — Normal mode has no minibuffer",
2443 );
2444 }
2445
2446 #[test]
2449 fn lazy_plugin_activates_on_command_trigger() {
2450 let mut s = new_state_with("");
2454 s.register_lazy_plugin(
2455 "user-lazy",
2456 vec![LazyTrigger::Command("LazyGo".into())],
2457 r#"(defoption :name "lazy-loaded" :value "yes")
2458 (defcmd :name "LazyGo" :description "noop" :action "editor.noop")"#,
2459 );
2460 assert_eq!(s.plugin_host.pending(), 1);
2461 assert!(
2462 s.options.get("lazy-loaded").is_none(),
2463 "entry not applied yet"
2464 );
2465
2466 s.run_lisp(r#"(run-command "LazyGo")"#).unwrap();
2468
2469 assert_eq!(
2470 s.options.get("lazy-loaded").map(String::as_str),
2471 Some("yes"),
2472 "the command trigger applied the plugin's entry",
2473 );
2474 assert_eq!(s.plugin_host.pending(), 0, "plugin activated exactly once");
2475 }
2476
2477 #[test]
2478 fn lazy_plugin_activates_on_filetype() {
2479 let mut s = new_state_with("");
2480 s.register_lazy_plugin(
2481 "user-rust",
2482 vec![LazyTrigger::FileType("rust".into())],
2483 r#"(defoption :name "rust-plugin" :value "on")"#,
2484 );
2485 let n = s.activate_filetype_plugins("rust");
2486 assert_eq!(n, 1);
2487 assert_eq!(s.options.get("rust-plugin").map(String::as_str), Some("on"));
2488 assert_eq!(s.activate_filetype_plugins("rust"), 0);
2490 }
2491
2492 #[test]
2493 fn cached_vm_serves_multiple_run_lisp_calls() {
2494 let mut s = new_state_with("");
2495 s.run_lisp(r#"(message "one")"#).unwrap();
2496 assert!(
2497 s.lisp_vm.is_some(),
2498 "VM should be cached after first run_lisp"
2499 );
2500 s.run_lisp(r#"(message "two")"#).unwrap();
2501 assert_eq!(s.messages, vec!["one".to_string(), "two".to_string()]);
2502 }
2503
2504 #[test]
2505 fn lisp_define_persists_across_run_lisp_calls() {
2506 let mut s = new_state_with("");
2509 s.run_lisp(r#"(define greeting "hi")"#).unwrap();
2510 s.run_lisp(r#"(message greeting)"#).unwrap();
2511 assert_eq!(s.messages, vec!["hi".to_string()]);
2512 }
2513
2514 #[test]
2515 fn snapshot_is_isolated_within_one_run_lisp_call_and_refreshes_across() {
2516 let mut s = new_state_with("");
2520 s.run_lisp(
2521 r#"(insert "ab") (set-option "col" (if (= (cursor-column) 0) "stale-zero" "live"))"#,
2522 )
2523 .unwrap();
2524 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "ab");
2525 assert_eq!(
2526 s.options.get("col").map(String::as_str),
2527 Some("stale-zero"),
2528 "cursor-column within the same call reads the pre-eval snapshot",
2529 );
2530 s.run_lisp(r#"(set-option "col2" (if (= (cursor-column) 2) "live-two" "other"))"#)
2533 .unwrap();
2534 assert_eq!(
2535 s.options.get("col2").map(String::as_str),
2536 Some("live-two"),
2537 "a later call sees the refreshed snapshot",
2538 );
2539 }
2540
2541 #[test]
2542 fn insert_text_effect_multiline_lands_cursor_on_last_line() {
2543 let mut s = new_state_with("");
2544 s.apply_host_effects(vec![HostEffect::InsertText("foo\nbar".to_string())]);
2545 assert_eq!(s.buffers.get(s.active).unwrap().to_string(), "foo\nbar");
2546 assert_eq!(s.cursor(), Position::new(1, 3));
2547 }
2548
2549 #[test]
2550 fn visual_mode_sequence_resolves() {
2551 let mut s = new_state_with("abc");
2552 s.modal.enter(Mode::Visual);
2553 s.keymap.bind_sequence(
2554 Mode::Visual,
2555 vec![Key::Char('g'), Key::Char('e')],
2556 Action::Move(Motion::DocEnd),
2557 "ge",
2558 );
2559 s.on_key(&Key::Char('g'));
2560 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2561 s.on_key(&Key::Char('e'));
2562 assert!(s.pending_keys.is_empty());
2563 assert_eq!(
2564 s.cursor().column,
2565 3,
2566 "ge resolved to doc-end in visual mode"
2567 );
2568 }
2569
2570 #[test]
2571 fn sequence_abort_with_bound_breaking_key_redispatches() {
2572 let mut s = new_state_with("abcde");
2575 s.keymap.bind_sequence(
2576 Mode::Normal,
2577 vec![Key::Char('g'), Key::Char('g')],
2578 Action::Move(Motion::DocEnd),
2579 "gg",
2580 );
2581 s.on_key(&Key::Char('g'));
2582 assert_eq!(s.pending_keys, vec![Key::Char('g')]);
2583 s.on_key(&Key::Char('l'));
2584 assert!(s.pending_keys.is_empty());
2585 assert_eq!(
2586 s.cursor().column,
2587 1,
2588 "the breaking key l should re-dispatch as move-right",
2589 );
2590 }
2591
2592 #[test]
2595 fn viewport_contains_cursor_after_every_op() {
2596 let mut s = new_state_small_viewport("", 5, 10);
2600 assert_cursor_in_viewport(&s, "initial");
2601
2602 s.tick(&press(KeyCode::Char('i')));
2605 assert_eq!(s.modal.mode(), Mode::Insert);
2606 for line in 0..30u32 {
2607 for c in "line".chars() {
2608 s.tick(&press(KeyCode::Char(c)));
2609 assert_cursor_in_viewport(&s, "typing chars");
2610 }
2611 s.tick(&press(KeyCode::Enter));
2612 assert_cursor_in_viewport(&s, &format!("newline after line {line}"));
2613 }
2614
2615 for i in 0..200u32 {
2618 s.tick(&press(KeyCode::Char('x')));
2619 assert_cursor_in_viewport(&s, &format!("long-line char {i}"));
2620 }
2621
2622 s.insert_text("alpha\nbeta\ngamma delta epsilon zeta");
2624 assert_cursor_in_viewport(&s, "insert_text multiline");
2625
2626 s.tick(&press(KeyCode::Escape));
2628 assert_eq!(s.modal.mode(), Mode::Normal);
2629 for m in [
2630 Motion::DocStart,
2631 Motion::DocEnd,
2632 Motion::Down,
2633 Motion::Down,
2634 Motion::Up,
2635 Motion::Right,
2636 Motion::Right,
2637 Motion::Left,
2638 Motion::LineEnd,
2639 Motion::LineStart,
2640 Motion::GotoLine(1),
2641 Motion::GotoLine(40),
2642 Motion::PageDown,
2643 Motion::PageUp,
2644 ] {
2645 s.apply_motion(m);
2646 assert_cursor_in_viewport(&s, &format!("after motion {m:?}"));
2647 }
2648
2649 for i in 0..50u32 {
2652 s.apply(&Action::Undo);
2653 assert_cursor_in_viewport(&s, &format!("undo {i}"));
2654 }
2655 for i in 0..50u32 {
2657 s.apply(&Action::Redo);
2658 assert_cursor_in_viewport(&s, &format!("redo {i}"));
2659 }
2660 }
2661
2662 #[test]
2663 fn insert_at_eof_keeps_cursor_in_bounds() {
2664 let mut s = new_state_small_viewport("abc", 5, 10);
2667 s.apply_motion(Motion::DocEnd);
2668 s.tick(&press(KeyCode::Char('i')));
2669 s.tick(&press(KeyCode::Char('d')));
2670 let buf = s.buffers.get(s.active).unwrap();
2671 let clamped = buf.clamp(s.cursor());
2672 assert_eq!(
2673 s.cursor(),
2674 clamped,
2675 "cursor must be clamped in-bounds at EOF"
2676 );
2677 assert_cursor_in_viewport(&s, "insert at eof");
2678 }
2679
2680 #[test]
2681 fn count_prefix_then_sequence_repeats() {
2682 let mut s = new_state_with("a\nb\nc\nd\ne");
2684 s.keymap.bind_sequence(
2685 Mode::Normal,
2686 vec![Key::Char('g'), Key::Char('j')],
2687 Action::Move(Motion::Down),
2688 "gj",
2689 );
2690 s.on_key(&Key::Char('2'));
2691 s.on_key(&Key::Char('g'));
2692 s.on_key(&Key::Char('j'));
2693 assert_eq!(s.cursor().line, 2, "count 2 should repeat the gj motion");
2694 }
2695
2696 #[test]
2699 fn held_key_repeat_storm_is_debounced_in_normal_mode() {
2700 let mut s = new_state_with(&"x\n".repeat(40));
2706 let t0 = std::time::Instant::now();
2707 let mut delivered = 0u32;
2708 for i in 0..20u32 {
2709 let before = s.cursor().line;
2710 s.tick_at(
2711 &press(KeyCode::Char('j')),
2712 t0 + std::time::Duration::from_millis(u64::from(i) * 50),
2713 );
2714 if s.cursor().line != before {
2715 delivered += 1;
2716 }
2717 }
2718 assert!(
2721 (10..=14).contains(&delivered),
2722 "expected the storm debounced to ~13 moves, got {delivered}",
2723 );
2724 assert!(
2725 delivered < 20,
2726 "the gate must drop SOME storm ticks, not pass all 20",
2727 );
2728 }
2729
2730 #[test]
2731 fn spaced_intentional_taps_all_pass() {
2732 let mut s = new_state_with(&"x\n".repeat(10));
2735 let t0 = std::time::Instant::now();
2736 for i in 0..5u32 {
2737 s.tick_at(
2738 &press(KeyCode::Char('j')),
2739 t0 + std::time::Duration::from_millis(u64::from(i) * 100),
2741 );
2742 }
2743 assert_eq!(s.cursor().line, 5, "all 5 spaced `j` taps moved the cursor");
2744 }
2745
2746 #[test]
2747 fn distinct_keys_have_independent_clocks() {
2748 let mut s = new_state_with("abc\ndef\nghi");
2751 let t = std::time::Instant::now();
2752 s.tick_at(&press(KeyCode::Char('j')), t);
2753 s.tick_at(
2755 &press(KeyCode::Char('j')),
2756 t + std::time::Duration::from_millis(10),
2757 );
2758 assert_eq!(s.cursor().line, 1, "second `j` within window dropped");
2759 s.tick_at(
2761 &press(KeyCode::Char('l')),
2762 t + std::time::Duration::from_millis(10),
2763 );
2764 assert_eq!(s.cursor().column, 1, "`l` is not blocked by `j`'s clock");
2765 }
2766
2767 #[test]
2770 fn cursor_home_preserves_single_cursor_behavior() {
2771 let mut s = new_state_with("hello\nworld\nthere");
2776 assert_eq!(s.cursor(), Position::ZERO);
2777 assert_eq!(s.cursors.count(), 1, "phase-1 holds exactly one caret");
2778
2779 s.apply_motion(Motion::Down);
2780 s.apply_motion(Motion::Right);
2781 s.apply_motion(Motion::Right);
2782 assert_eq!(s.cursor(), Position::new(1, 2));
2783 assert_eq!(s.cursors.count(), 1);
2785
2786 let w = s.layout.active_window().unwrap();
2788 assert!(w.viewport.top_line <= s.cursor().line);
2789 }
2790
2791 #[test]
2792 fn insert_mode_is_ungated_so_repeat_typing_works() {
2793 let mut s = new_state_with("");
2797 s.tick(&press(KeyCode::Char('i')));
2798 assert_eq!(s.modal.mode(), Mode::Insert);
2799 let t = std::time::Instant::now();
2800 for _ in 0..10 {
2801 s.tick_at(&press(KeyCode::Char('x')), t);
2802 }
2803 assert_eq!(
2804 s.buffers.get(s.active).unwrap().to_string(),
2805 "xxxxxxxxxx",
2806 "insert-mode repeat typing is ungated",
2807 );
2808 }
2809}