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