hjkl_engine/types.rs
1//! Core types for the engine trait surface.
2//!
3//! These are introduced alongside the legacy sqeel-vim public API. The
4//! trait extraction (phase 5) progressively rewires the existing FSM and
5//! Editor to operate on `Selection` / `SelectionSet` / `Edit` / `Pos`.
6//! Until that work lands, the legacy types in [`crate::editor`] and
7//! [`crate::vim`] remain authoritative.
8
9use std::ops::Range;
10
11/// Grapheme-indexed position. `line` is zero-based row; `col` is zero-based
12/// grapheme column within that line.
13///
14/// Note that `col` counts graphemes, not bytes or chars. Motions and
15/// rendering both honor grapheme boundaries.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
17pub struct Pos {
18 pub line: u32,
19 pub col: u32,
20}
21
22impl Pos {
23 pub const ORIGIN: Pos = Pos { line: 0, col: 0 };
24
25 pub const fn new(line: u32, col: u32) -> Self {
26 Pos { line, col }
27 }
28}
29
30/// What kind of region a [`Selection`] covers.
31///
32/// - `Char`: classic vim `v` selection — closed range on the inline character
33/// axis.
34/// - `Line`: linewise (`V`) — anchor/head columns ignored, full lines covered
35/// between `min(anchor.line, head.line)` and `max(...)`.
36/// - `Block`: blockwise (`Ctrl-V`) — rectangle from `min(col)` to `max(col)`,
37/// each line a sub-range. Falls out of multi-cursor model: implementations
38/// may expand a `Block` selection into N sub-selections during edit
39/// dispatch.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
41pub enum SelectionKind {
42 #[default]
43 Char,
44 Line,
45 Block,
46}
47
48/// A single anchored selection. Empty (caret-only) when `anchor == head`.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub struct Selection {
51 pub anchor: Pos,
52 pub head: Pos,
53 pub kind: SelectionKind,
54}
55
56impl Selection {
57 /// Caret at `pos` with no extent.
58 pub const fn caret(pos: Pos) -> Self {
59 Selection {
60 anchor: pos,
61 head: pos,
62 kind: SelectionKind::Char,
63 }
64 }
65
66 /// Inclusive range `[anchor, head]` (or reversed) as a `Char` selection.
67 pub const fn char_range(anchor: Pos, head: Pos) -> Self {
68 Selection {
69 anchor,
70 head,
71 kind: SelectionKind::Char,
72 }
73 }
74
75 /// True if `anchor == head`.
76 pub fn is_empty(&self) -> bool {
77 self.anchor == self.head
78 }
79}
80
81/// Ordered set of selections. Always non-empty in valid states; `primary`
82/// indexes the cursor visible to vim mode.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct SelectionSet {
85 pub items: Vec<Selection>,
86 pub primary: usize,
87}
88
89impl SelectionSet {
90 /// Single caret at `pos`.
91 pub fn caret(pos: Pos) -> Self {
92 SelectionSet {
93 items: vec![Selection::caret(pos)],
94 primary: 0,
95 }
96 }
97
98 /// Returns the primary selection, or the first if `primary` is out of
99 /// bounds.
100 pub fn primary(&self) -> &Selection {
101 self.items
102 .get(self.primary)
103 .or_else(|| self.items.first())
104 .expect("SelectionSet must contain at least one selection")
105 }
106}
107
108impl Default for SelectionSet {
109 fn default() -> Self {
110 SelectionSet::caret(Pos::ORIGIN)
111 }
112}
113
114/// A pending or applied edit. Multi-cursor edits fan out to `Vec<Edit>`
115/// ordered in **reverse byte offset** so each entry's positions remain valid
116/// after the prior entry applies.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct Edit {
119 pub range: Range<Pos>,
120 pub replacement: String,
121}
122
123/// Engine-native representation of a single buffer mutation in the
124/// shape tree-sitter's `InputEdit` consumes. Emitted by
125/// [`crate::Editor::mutate_edit`] and drained by hosts via
126/// [`crate::Editor::take_content_edits`] so the syntax layer can fan
127/// edits into a retained tree without the engine taking a tree-sitter
128/// dependency.
129///
130/// Positions are `(row, col_byte)` — byte offsets within the row, not
131/// char counts. Multi-row inserts/deletes set `new_end_position.0` /
132/// `old_end_position.0` to the relevant row delta. Conversion to
133/// `tree_sitter::InputEdit` is mechanical (see `apps/hjkl/src/syntax.rs`).
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct ContentEdit {
136 pub start_byte: usize,
137 pub old_end_byte: usize,
138 pub new_end_byte: usize,
139 pub start_position: (u32, u32),
140 pub old_end_position: (u32, u32),
141 pub new_end_position: (u32, u32),
142}
143
144impl Edit {
145 pub fn insert(at: Pos, text: impl Into<String>) -> Self {
146 Edit {
147 range: at..at,
148 replacement: text.into(),
149 }
150 }
151
152 pub fn delete(range: Range<Pos>) -> Self {
153 Edit {
154 range,
155 replacement: String::new(),
156 }
157 }
158
159 pub fn replace(range: Range<Pos>, text: impl Into<String>) -> Self {
160 Edit {
161 range,
162 replacement: text.into(),
163 }
164 }
165}
166
167/// Vim editor mode. Distinct from the legacy [`crate::VimMode`] — that one
168/// is the host-facing status-line summary; this is the engine's internal
169/// state machine.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
171pub enum Mode {
172 #[default]
173 Normal,
174 Insert,
175 Visual,
176 Replace,
177 Command,
178 OperatorPending,
179}
180
181/// Cursor shape intent emitted on mode transitions. Hosts honor it via
182/// `Host::emit_cursor_shape` once the trait extraction lands.
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
184pub enum CursorShape {
185 #[default]
186 Block,
187 Bar,
188 Underline,
189}
190
191/// Engine-native style. Replaces direct ratatui `Style` use in the public
192/// API once phase 5 trait extraction completes; until then both coexist.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
194pub struct Style {
195 pub fg: Option<Color>,
196 pub bg: Option<Color>,
197 pub attrs: Attrs,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
201pub struct Color(pub u8, pub u8, pub u8);
202
203bitflags::bitflags! {
204 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
205 pub struct Attrs: u8 {
206 const BOLD = 1 << 0;
207 const ITALIC = 1 << 1;
208 const UNDERLINE = 1 << 2;
209 const REVERSE = 1 << 3;
210 const DIM = 1 << 4;
211 const STRIKE = 1 << 5;
212 }
213}
214
215/// Highlight kind emitted by the engine's render pass. The host's style
216/// resolver picks colors for `Selection`/`SearchMatch`/etc.; `Syntax(id)`
217/// carries an opaque host-supplied id whose styling lives in the host.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum HighlightKind {
220 Selection,
221 SearchMatch,
222 IncSearch,
223 MatchParen,
224 Syntax(u32),
225}
226
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct Highlight {
229 pub range: Range<Pos>,
230 pub kind: HighlightKind,
231}
232
233/// Editor settings surfaced via `:set`. Per SPEC. Consumed once trait
234/// extraction lands; today's legacy `Settings` (in [`crate::editor`])
235/// continues to drive runtime behaviour.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct Options {
238 /// Display width of `\t` for column math + render. Default 8.
239 pub tabstop: u32,
240 /// Spaces per shift step (`>>`, `<<`, `Ctrl-T`, `Ctrl-D`).
241 pub shiftwidth: u32,
242 /// Insert spaces (`true`) or literal `\t` (`false`) for the Tab key.
243 pub expandtab: bool,
244 /// Soft tab stop in spaces. When `> 0`, the Tab key (with `expandtab`)
245 /// inserts spaces to the next softtabstop boundary, and Backspace at
246 /// the end of a softtabstop-aligned space run deletes the whole run.
247 /// `0` disables softtabstop semantics. Matches vim's `:set softtabstop`.
248 pub softtabstop: u32,
249 /// Characters considered part of a "word" for `w`/`b`/`*`/`#`.
250 /// Default `"@,48-57,_,192-255"` (ASCII letters, digits, `_`, plus
251 /// extended Latin); host may override per language.
252 pub iskeyword: String,
253 /// Default `false`: search is case-sensitive.
254 pub ignorecase: bool,
255 /// When `true` and `ignorecase` is `true`, an uppercase letter in the
256 /// pattern flips back to case-sensitive for that search.
257 pub smartcase: bool,
258 /// Highlight all matches of the last search.
259 pub hlsearch: bool,
260 /// Incrementally highlight matches while typing the search pattern.
261 pub incsearch: bool,
262 /// Wrap searches around the buffer ends.
263 pub wrapscan: bool,
264 /// Copy previous line's leading whitespace on Enter in insert mode.
265 pub autoindent: bool,
266 /// When `true`, bump indent by one `shiftwidth` after a line ending in
267 /// `{` / `(` / `[`, and strip one indent unit when the user types the
268 /// matching `}` / `)` / `]` on an otherwise-whitespace-only line.
269 /// Supersedes autoindent's plain copy when on. Future: a
270 /// tree-sitter `indents.scm` provider will replace the heuristic; see
271 /// `compute_enter_indent` in `vim.rs` for the plug-in point.
272 pub smartindent: bool,
273 /// Multi-key sequence timeout (e.g., `<C-w>v`). Vim's `timeoutlen`.
274 pub timeout_len: core::time::Duration,
275 /// Maximum undo-tree depth. Older entries pruned.
276 pub undo_levels: u32,
277 /// Break the current undo group on cursor motion in insert mode.
278 /// Matches vim default; turn off to merge multi-segment edits.
279 pub undo_break_on_motion: bool,
280 /// Reject every edit. `:set ro` sets this; `:w!` clears it.
281 pub readonly: bool,
282 /// Soft-wrap behavior for lines that exceed the viewport width.
283 /// Maps directly to `:set wrap` / `:set linebreak` / `:set nowrap`.
284 pub wrap: WrapMode,
285 /// Wrap column for `gq{motion}` text reflow. Vim's default is 79.
286 pub textwidth: u32,
287}
288
289/// Soft-wrap mode for the renderer + scroll math + `gj` / `gk`.
290/// Engine-native equivalent of [`hjkl_buffer::Wrap`]; the engine
291/// converts at the boundary to the buffer's runtime wrap setting.
292#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
293#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
294pub enum WrapMode {
295 /// Long lines extend past the right edge; `top_col` clips the
296 /// left side. Matches vim's `:set nowrap`.
297 #[default]
298 None,
299 /// Break at the cell boundary regardless of word edges. Matches
300 /// `:set wrap`.
301 Char,
302 /// Break at the last whitespace inside the visible width when
303 /// possible; falls back to a char break for runs longer than the
304 /// width. Matches `:set linebreak`.
305 Word,
306}
307
308/// Typed value for [`Options::set_by_name`] / [`Options::get_by_name`].
309///
310/// `:set tabstop=4` parses as `OptionValue::Int(4)`;
311/// `:set noexpandtab` parses as `OptionValue::Bool(false)`;
312/// `:set iskeyword=...` as `OptionValue::String(...)`.
313#[derive(Debug, Clone, PartialEq, Eq)]
314pub enum OptionValue {
315 Bool(bool),
316 Int(i64),
317 String(String),
318}
319
320impl Default for Options {
321 fn default() -> Self {
322 Options {
323 tabstop: 4,
324 shiftwidth: 4,
325 expandtab: true,
326 softtabstop: 4,
327 iskeyword: "@,48-57,_,192-255".to_string(),
328 ignorecase: false,
329 smartcase: false,
330 hlsearch: true,
331 incsearch: true,
332 wrapscan: true,
333 autoindent: true,
334 smartindent: true,
335 timeout_len: core::time::Duration::from_millis(1000),
336 undo_levels: 1000,
337 undo_break_on_motion: true,
338 readonly: false,
339 wrap: WrapMode::None,
340 textwidth: 79,
341 }
342 }
343}
344
345impl Options {
346 /// Set an option by name. Vim-flavored option naming. Returns
347 /// [`EngineError::Ex`] for unknown names or type-mismatched values.
348 ///
349 /// Booleans accept `OptionValue::Bool(_)` directly or
350 /// `OptionValue::Int(0)`/`Int(non_zero)`. Integers accept only
351 /// `Int(_)`. Strings accept only `String(_)`.
352 pub fn set_by_name(&mut self, name: &str, val: OptionValue) -> Result<(), EngineError> {
353 macro_rules! set_bool {
354 ($field:ident) => {{
355 self.$field = match val {
356 OptionValue::Bool(b) => b,
357 OptionValue::Int(n) => n != 0,
358 other => {
359 return Err(EngineError::Ex(format!(
360 "option `{name}` expects bool, got {other:?}"
361 )));
362 }
363 };
364 Ok(())
365 }};
366 }
367 macro_rules! set_u32 {
368 ($field:ident) => {{
369 self.$field = match val {
370 OptionValue::Int(n) if n >= 0 && n <= u32::MAX as i64 => n as u32,
371 OptionValue::Int(n) => {
372 return Err(EngineError::Ex(format!(
373 "option `{name}` out of u32 range: {n}"
374 )));
375 }
376 other => {
377 return Err(EngineError::Ex(format!(
378 "option `{name}` expects int, got {other:?}"
379 )));
380 }
381 };
382 Ok(())
383 }};
384 }
385 macro_rules! set_string {
386 ($field:ident) => {{
387 self.$field = match val {
388 OptionValue::String(s) => s,
389 other => {
390 return Err(EngineError::Ex(format!(
391 "option `{name}` expects string, got {other:?}"
392 )));
393 }
394 };
395 Ok(())
396 }};
397 }
398 match name {
399 "tabstop" | "ts" => set_u32!(tabstop),
400 "shiftwidth" | "sw" => set_u32!(shiftwidth),
401 "softtabstop" | "sts" => set_u32!(softtabstop),
402 "textwidth" | "tw" => set_u32!(textwidth),
403 "expandtab" | "et" => set_bool!(expandtab),
404 "iskeyword" | "isk" => set_string!(iskeyword),
405 "ignorecase" | "ic" => set_bool!(ignorecase),
406 "smartcase" | "scs" => set_bool!(smartcase),
407 "hlsearch" | "hls" => set_bool!(hlsearch),
408 "incsearch" | "is" => set_bool!(incsearch),
409 "wrapscan" | "ws" => set_bool!(wrapscan),
410 "autoindent" | "ai" => set_bool!(autoindent),
411 "smartindent" | "si" => set_bool!(smartindent),
412 "timeoutlen" | "tm" => {
413 self.timeout_len = match val {
414 OptionValue::Int(n) if n >= 0 => core::time::Duration::from_millis(n as u64),
415 other => {
416 return Err(EngineError::Ex(format!(
417 "option `{name}` expects non-negative int (millis), got {other:?}"
418 )));
419 }
420 };
421 Ok(())
422 }
423 "undolevels" | "ul" => set_u32!(undo_levels),
424 "undobreak" => set_bool!(undo_break_on_motion),
425 "readonly" | "ro" => set_bool!(readonly),
426 "wrap" => {
427 let on = match val {
428 OptionValue::Bool(b) => b,
429 OptionValue::Int(n) => n != 0,
430 other => {
431 return Err(EngineError::Ex(format!(
432 "option `{name}` expects bool, got {other:?}"
433 )));
434 }
435 };
436 self.wrap = match (on, self.wrap) {
437 (false, _) => WrapMode::None,
438 (true, WrapMode::Word) => WrapMode::Word,
439 (true, _) => WrapMode::Char,
440 };
441 Ok(())
442 }
443 "linebreak" | "lbr" => {
444 let on = match val {
445 OptionValue::Bool(b) => b,
446 OptionValue::Int(n) => n != 0,
447 other => {
448 return Err(EngineError::Ex(format!(
449 "option `{name}` expects bool, got {other:?}"
450 )));
451 }
452 };
453 self.wrap = match (on, self.wrap) {
454 (true, _) => WrapMode::Word,
455 (false, WrapMode::Word) => WrapMode::Char,
456 (false, other) => other,
457 };
458 Ok(())
459 }
460 other => Err(EngineError::Ex(format!("unknown option `{other}`"))),
461 }
462 }
463
464 /// Read an option by name. `None` for unknown names.
465 pub fn get_by_name(&self, name: &str) -> Option<OptionValue> {
466 Some(match name {
467 "tabstop" | "ts" => OptionValue::Int(self.tabstop as i64),
468 "shiftwidth" | "sw" => OptionValue::Int(self.shiftwidth as i64),
469 "softtabstop" | "sts" => OptionValue::Int(self.softtabstop as i64),
470 "textwidth" | "tw" => OptionValue::Int(self.textwidth as i64),
471 "expandtab" | "et" => OptionValue::Bool(self.expandtab),
472 "iskeyword" | "isk" => OptionValue::String(self.iskeyword.clone()),
473 "ignorecase" | "ic" => OptionValue::Bool(self.ignorecase),
474 "smartcase" | "scs" => OptionValue::Bool(self.smartcase),
475 "hlsearch" | "hls" => OptionValue::Bool(self.hlsearch),
476 "incsearch" | "is" => OptionValue::Bool(self.incsearch),
477 "wrapscan" | "ws" => OptionValue::Bool(self.wrapscan),
478 "autoindent" | "ai" => OptionValue::Bool(self.autoindent),
479 "smartindent" | "si" => OptionValue::Bool(self.smartindent),
480 "timeoutlen" | "tm" => OptionValue::Int(self.timeout_len.as_millis() as i64),
481 "undolevels" | "ul" => OptionValue::Int(self.undo_levels as i64),
482 "undobreak" => OptionValue::Bool(self.undo_break_on_motion),
483 "readonly" | "ro" => OptionValue::Bool(self.readonly),
484 "wrap" => OptionValue::Bool(!matches!(self.wrap, WrapMode::None)),
485 "linebreak" | "lbr" => OptionValue::Bool(matches!(self.wrap, WrapMode::Word)),
486 _ => return None,
487 })
488 }
489}
490
491/// Visible region of a buffer — the runtime viewport state the host
492/// owns and mutates per render frame.
493///
494/// 0.0.34 (Patch C-δ.1): semantic ownership moved from
495/// [`hjkl_buffer::Buffer`] to [`Host`]. The struct still lives in
496/// `hjkl-buffer` (alongside [`hjkl_buffer::Wrap`] and the rope-walking
497/// `wrap_segments` math it depends on) so the dependency graph stays
498/// `engine → buffer`; the engine re-exports it as
499/// [`crate::types::Viewport`] (this alias) for hosts that program to
500/// the SPEC surface.
501///
502/// The architectural decision is "viewport lives on Host, not Buffer":
503/// vim logic must work in GUI hosts (variable-width fonts, pixel
504/// canvases, soft-wrap by pixel) as well as TUI hosts, so the runtime
505/// viewport state is expressed in cells/rows/cols and is owned by the
506/// host. `top_row` and `top_col` are the first visible row / column
507/// (`top_col` is a char index).
508///
509/// `wrap` and `text_width` together drive soft-wrap-aware scrolling
510/// and motion. `text_width` is the cell width of the text area
511/// (i.e., `width` minus any gutter the host renders).
512pub use hjkl_buffer::Viewport;
513
514/// Opaque buffer identifier owned by the host. Engine echoes it back
515/// in [`Host::Intent`] variants for buffer-list operations
516/// (`SwitchBuffer`, etc.). Generation is the host's responsibility.
517#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
518pub struct BufferId(pub u64);
519
520/// Modifier bits accompanying every keystroke.
521#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
522pub struct Modifiers {
523 pub ctrl: bool,
524 pub shift: bool,
525 pub alt: bool,
526 pub super_: bool,
527}
528
529/// Special key codes — anything that isn't a printable character.
530#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
531#[non_exhaustive]
532pub enum SpecialKey {
533 Esc,
534 Enter,
535 Backspace,
536 Tab,
537 BackTab,
538 Up,
539 Down,
540 Left,
541 Right,
542 Home,
543 End,
544 PageUp,
545 PageDown,
546 Insert,
547 Delete,
548 F(u8),
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
552pub enum MouseKind {
553 Press,
554 Release,
555 Drag,
556 ScrollUp,
557 ScrollDown,
558}
559
560#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
561pub struct MouseEvent {
562 pub kind: MouseKind,
563 pub pos: Pos,
564 pub mods: Modifiers,
565}
566
567/// Single input event handed to the engine.
568///
569/// `Paste` content bypasses insert-mode mappings, abbreviations, and
570/// autoindent; the engine inserts the bracketed-paste payload as-is.
571#[derive(Debug, Clone, PartialEq, Eq)]
572#[non_exhaustive]
573pub enum Input {
574 Char(char, Modifiers),
575 Key(SpecialKey, Modifiers),
576 Mouse(MouseEvent),
577 Paste(String),
578 FocusGained,
579 FocusLost,
580 Resize(u16, u16),
581}
582
583/// Host adapter consumed by the engine. Lives behind the planned
584/// `Editor<B: Buffer, H: Host>` generic; today it's the contract that
585/// `buffr-modal::BuffrHost` and the (future) `sqeel-tui` Host impl
586/// align against.
587///
588/// Methods with default impls return safe no-ops so hosts that don't
589/// need a feature (cancellation, wrap-aware motion, syntax highlights)
590/// can ignore them.
591pub trait Host: Send {
592 /// Custom intent type. Hosts that don't fan out actions back to
593 /// themselves can use the unit type via the default impl approach
594 /// (set associated type explicitly).
595 type Intent;
596
597 // ── Clipboard (hybrid: write fire-and-forget, read cached) ──
598
599 /// Fire-and-forget clipboard write. Engine never blocks; the host
600 /// queues internally and flushes on its own task (OSC52, `wl-copy`,
601 /// `pbcopy`, …).
602 fn write_clipboard(&mut self, text: String);
603
604 /// Returns the last-known cached clipboard value. May be stale —
605 /// matches the OSC52/wl-paste model neovim and helix both ship.
606 fn read_clipboard(&mut self) -> Option<String>;
607
608 // ── Time + cancellation ──
609
610 /// Monotonic time. Multi-key timeout (`timeoutlen`) resolution
611 /// reads this; engine never reads `Instant::now()` directly so
612 /// macro replay stays deterministic.
613 fn now(&self) -> core::time::Duration;
614
615 /// Cooperative cancellation. Engine polls during long search /
616 /// regex / multi-cursor edit loops. Default returns `false`.
617 fn should_cancel(&self) -> bool {
618 false
619 }
620
621 // ── Search prompt ──
622
623 /// Synchronously prompt the user for a search pattern. Returning
624 /// `None` aborts the search.
625 fn prompt_search(&mut self) -> Option<String>;
626
627 // ── Wrap-aware motion (default: wrap is identity) ──
628
629 /// Map a logical position to its display line for `gj`/`gk`. Hosts
630 /// without wrapping may use the default identity impl.
631 fn display_line_for(&self, pos: Pos) -> u32 {
632 pos.line
633 }
634
635 /// Inverse of [`display_line_for`]. Default identity.
636 fn pos_for_display(&self, line: u32, col: u32) -> Pos {
637 Pos { line, col }
638 }
639
640 // ── Syntax highlights (default: none) ──
641
642 /// Host-supplied syntax highlights for `range`. Empty by default;
643 /// hosts wire tree-sitter or LSP semantic tokens here.
644 fn syntax_highlights(&self, range: Range<Pos>) -> Vec<Highlight> {
645 let _ = range;
646 Vec::new()
647 }
648
649 // ── Cursor shape ──
650
651 /// Engine emits this on every mode transition. Hosts repaint the
652 /// cursor in the requested shape.
653 fn emit_cursor_shape(&mut self, shape: CursorShape);
654
655 // ── Viewport (host owns runtime viewport state) ──
656
657 /// Borrow the host's viewport. The host writes `width`/`height`/
658 /// `text_width`/`wrap` per render frame; the engine reads/writes
659 /// `top_row` / `top_col` to scroll. 0.0.34 (Patch C-δ.1) moved
660 /// this off [`hjkl_buffer::Buffer`] onto `Host`.
661 fn viewport(&self) -> &Viewport;
662
663 /// Mutable viewport access. Engine motion + scroll code routes
664 /// here when scrolloff math advances `top_row`.
665 fn viewport_mut(&mut self) -> &mut Viewport;
666
667 // ── Custom intent fan-out ──
668
669 /// Host-defined event the engine raises (LSP request, fold op,
670 /// buffer switch, …).
671 fn emit_intent(&mut self, intent: Self::Intent);
672}
673
674/// Default no-op [`Host`] implementation. Suitable for tests, headless
675/// embedding, or any host that doesn't yet need clipboard / cursor-shape
676/// / cancellation plumbing.
677///
678/// Behaviour:
679/// - `write_clipboard` stores the most recent payload in an in-memory
680/// slot; `read_clipboard` returns it. Round-trip-only — no OS-level
681/// clipboard touched.
682/// - `now` returns wall-clock duration since construction.
683/// - `prompt_search` returns `None` (search is aborted).
684/// - `emit_cursor_shape` records the most recent shape; readable via
685/// [`DefaultHost::last_cursor_shape`].
686/// - `emit_intent` discards intents (intent type is `()`).
687#[derive(Debug)]
688pub struct DefaultHost {
689 clipboard: Option<String>,
690 last_cursor_shape: CursorShape,
691 started: std::time::Instant,
692 viewport: Viewport,
693}
694
695impl Default for DefaultHost {
696 fn default() -> Self {
697 Self::new()
698 }
699}
700
701impl DefaultHost {
702 /// Default viewport size for headless / test hosts: 80x24, no
703 /// soft-wrap. Matches the conventional terminal default.
704 pub const DEFAULT_VIEWPORT: Viewport = Viewport {
705 top_row: 0,
706 top_col: 0,
707 width: 80,
708 height: 24,
709 wrap: hjkl_buffer::Wrap::None,
710 text_width: 80,
711 tab_width: 0,
712 };
713
714 pub fn new() -> Self {
715 Self {
716 clipboard: None,
717 last_cursor_shape: CursorShape::Block,
718 started: std::time::Instant::now(),
719 viewport: Self::DEFAULT_VIEWPORT,
720 }
721 }
722
723 /// Construct a [`DefaultHost`] with a custom initial viewport.
724 /// Useful for tests that want to exercise scrolloff math at a
725 /// specific window size.
726 pub fn with_viewport(viewport: Viewport) -> Self {
727 Self {
728 clipboard: None,
729 last_cursor_shape: CursorShape::Block,
730 started: std::time::Instant::now(),
731 viewport,
732 }
733 }
734
735 /// Most recent cursor shape requested by the engine.
736 pub fn last_cursor_shape(&self) -> CursorShape {
737 self.last_cursor_shape
738 }
739}
740
741impl Host for DefaultHost {
742 type Intent = ();
743
744 fn write_clipboard(&mut self, text: String) {
745 self.clipboard = Some(text);
746 }
747
748 fn read_clipboard(&mut self) -> Option<String> {
749 self.clipboard.clone()
750 }
751
752 fn now(&self) -> core::time::Duration {
753 self.started.elapsed()
754 }
755
756 fn prompt_search(&mut self) -> Option<String> {
757 None
758 }
759
760 fn emit_cursor_shape(&mut self, shape: CursorShape) {
761 self.last_cursor_shape = shape;
762 }
763
764 fn viewport(&self) -> &Viewport {
765 &self.viewport
766 }
767
768 fn viewport_mut(&mut self) -> &mut Viewport {
769 &mut self.viewport
770 }
771
772 fn emit_intent(&mut self, _intent: Self::Intent) {}
773}
774
775/// Engine render frame consumed by the host once per redraw.
776///
777/// Borrow-style — the engine builds it on demand from its internal
778/// state without allocating clones of large fields. Hosts diff across
779/// frames to decide what to repaint.
780///
781/// Coarse today: covers mode, cursor, cursor shape, viewport top, and
782/// a snapshot of the current line count (to size the gutter). The
783/// SPEC-target fields (`selections`, `highlights`, `command_line`,
784/// `search_prompt`, `status_line`) land once trait extraction wires
785/// the FSM through `SelectionSet` and the highlight pipeline.
786#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
787pub struct RenderFrame {
788 pub mode: SnapshotMode,
789 pub cursor_row: u32,
790 pub cursor_col: u32,
791 pub cursor_shape: CursorShape,
792 pub viewport_top: u32,
793 pub line_count: u32,
794}
795
796/// Coarse editor snapshot suitable for serde round-tripping.
797///
798/// Today's shape is intentionally minimal — it carries only the bits
799/// the runtime [`crate::Editor`] knows how to round-trip without the
800/// trait extraction (mode, cursor, lines, viewport top, settings).
801/// Once `Editor<B: Buffer, H: Host>` ships under phase 5, this struct
802/// grows to cover full SPEC state: registers, marks, jump list, change
803/// list, undo tree, full options.
804///
805/// Hosts that persist editor state between sessions should:
806///
807/// - Treat the snapshot as opaque. Don't manually mutate fields.
808/// - Always check `version` after deserialization; reject on
809/// mismatch rather than attempt migration.
810///
811/// # Wire-format stability
812///
813/// - **0.0.x:** [`Self::VERSION`] bumps with every structural change to
814/// the snapshot. Hosts must reject mismatched persisted state — no
815/// migration path is offered.
816/// - **0.1.0:** [`Self::VERSION`] freezes. Hosts persisting editor state
817/// between sessions can rely on the wire format being stable for the
818/// entire 0.1.x line.
819/// - **0.2.0+:** any further structural change to this struct requires a
820/// `VERSION++` bump and is gated behind a major version bump of the
821/// crate.
822#[derive(Debug, Clone)]
823#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
824pub struct EditorSnapshot {
825 /// Format version. See [`Self::VERSION`] for the lock policy.
826 /// Hosts use this to detect mismatched persisted state.
827 pub version: u32,
828 /// Mode at snapshot time (status-line granularity).
829 pub mode: SnapshotMode,
830 /// Cursor `(row, col)` in byte indexing.
831 pub cursor: (u32, u32),
832 /// Buffer lines. Trailing `\n` not included.
833 pub lines: Vec<String>,
834 /// Viewport top line at snapshot time.
835 pub viewport_top: u32,
836 /// Register bank. Vim's `""`, `"0`–`"9`, `"a`–`"z`, `"+`/`"*`.
837 /// Skipped for `Eq`/`PartialEq` because [`crate::Registers`]
838 /// doesn't derive them today.
839 pub registers: crate::Registers,
840 /// Named marks — both lowercase (`'a`–`'z`, buffer-scope) and
841 /// uppercase (`'A`–`'Z`, file-scope). Round-trips across tab
842 /// swaps in the host.
843 ///
844 /// 0.0.36: consolidated from the prior `file_marks` field;
845 /// lowercase marks now persist as well since they live in the
846 /// same unified [`crate::Editor::marks`] map.
847 pub marks: std::collections::BTreeMap<char, (u32, u32)>,
848}
849
850/// Status-line mode summary. Bridges to the legacy
851/// [`crate::VimMode`] without leaking the full FSM type into the
852/// snapshot wire format.
853#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
854#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
855pub enum SnapshotMode {
856 #[default]
857 Normal,
858 Insert,
859 Visual,
860 VisualLine,
861 VisualBlock,
862}
863
864impl EditorSnapshot {
865 /// Current snapshot format version.
866 ///
867 /// Bumped to 2 in v0.0.8: registers added.
868 /// Bumped to 3 in v0.0.9: file_marks added.
869 /// Bumped to 4 in v0.0.36: file_marks → unified `marks` map
870 /// (lowercase + uppercase consolidated).
871 ///
872 /// # Lock policy
873 ///
874 /// - **0.0.x (today):** `VERSION` bumps freely with each structural
875 /// change to [`EditorSnapshot`]. Persisted state from an older
876 /// patch release will not round-trip; hosts must reject the
877 /// snapshot rather than attempt a field-by-field migration.
878 /// - **0.1.0:** `VERSION` freezes. Hosts persisting editor state
879 /// between sessions can rely on the wire format being stable for
880 /// the entire 0.1.x line.
881 /// - **0.2.0+:** any further structural change requires `VERSION++`
882 /// together with a major-version bump of `hjkl-engine`.
883 pub const VERSION: u32 = 4;
884}
885
886/// Errors surfaced from the engine to the host. Intentionally narrow —
887/// callsites that fail in user-facing ways return `Result<_,
888/// EngineError>`; internal invariant breaks use `debug_assert!`.
889#[derive(Debug, thiserror::Error)]
890pub enum EngineError {
891 /// `:s/pat/.../` couldn't compile the pattern. Host displays the
892 /// regex error in the status line.
893 #[error("regex compile error: {0}")]
894 Regex(#[from] regex::Error),
895
896 /// `:[range]` parse failed.
897 #[error("invalid range: {0}")]
898 InvalidRange(String),
899
900 /// Ex command parse failed (unknown command, malformed args).
901 #[error("ex parse: {0}")]
902 Ex(String),
903
904 /// Edit attempted on a read-only buffer.
905 #[error("buffer is read-only")]
906 ReadOnly,
907
908 /// Position passed by the caller pointed outside the buffer.
909 #[error("position out of bounds: {0:?}")]
910 OutOfBounds(Pos),
911
912 /// Snapshot version mismatch. Host should treat as "abandon
913 /// snapshot" rather than attempt migration.
914 #[error("snapshot version mismatch: file={0}, expected={1}")]
915 SnapshotVersion(u32, u32),
916}
917
918pub(crate) mod sealed {
919 /// Sealing trait for the planned 0.1.0 [`super::Buffer`] surface.
920 /// Pre-1.0 the engine reserves the right to add methods to the
921 /// `Buffer` super-trait without a major bump; downstream cannot
922 /// `impl Buffer` from outside this family.
923 ///
924 /// The in-tree [`hjkl_buffer::Buffer`] is the canonical impl; the
925 /// `Sealed` marker for it lives in `crate::buffer_impl`. The module
926 /// itself stays `pub(crate)` so the sibling impl module can name
927 /// the trait while keeping the seal closed to the outside world.
928 pub trait Sealed {}
929}
930
931/// Cursor sub-trait of [`Buffer`].
932///
933/// `Pos` here is the engine's grapheme-indexed [`Pos`] type. Buffer
934/// implementations convert at the boundary if their internal indexing
935/// differs (e.g., the rope's byte indexing).
936pub trait Cursor: Send {
937 /// Active primary cursor position.
938 fn cursor(&self) -> Pos;
939 /// Move the active primary cursor.
940 fn set_cursor(&mut self, pos: Pos);
941 /// Byte offset for `pos`. Used by regex search bridges.
942 fn byte_offset(&self, pos: Pos) -> usize;
943 /// Inverse of [`Self::byte_offset`].
944 fn pos_at_byte(&self, byte: usize) -> Pos;
945}
946
947/// Read-only query sub-trait of [`Buffer`].
948pub trait Query: Send {
949 /// Number of logical lines (excluding the implicit trailing line).
950 fn line_count(&self) -> u32;
951 /// Borrow line `idx` (0-based). Implementations should panic on
952 /// out-of-bounds rather than silently return empty.
953 fn line(&self, idx: u32) -> &str;
954 /// Total buffer length in bytes.
955 fn len_bytes(&self) -> usize;
956 /// Slice for the half-open `range`. May allocate (rope joins)
957 /// or borrow (contiguous storage). Returns
958 /// [`std::borrow::Cow<'_, str>`] so contiguous backends can
959 /// avoid the allocation.
960 fn slice(&self, range: core::ops::Range<Pos>) -> std::borrow::Cow<'_, str>;
961 /// Monotonic mutation generation counter. Increments on every
962 /// content-changing call (insert / delete / replace / fold-touch
963 /// edit / `set_content`). Read-only ops (cursor moves, queries,
964 /// view changes) leave it untouched.
965 ///
966 /// Engine consumers cache per-row data (search-match positions,
967 /// syntax spans, wrap layout) keyed off this counter — when it
968 /// advances, the cache is invalidated.
969 ///
970 /// Implementations may return any monotonically non-decreasing
971 /// value (zero is fine for non-canonical impls that don't have a
972 /// caching story); the contract is "if `dirty_gen` changed, the
973 /// content **may** have changed."
974 fn dirty_gen(&self) -> u64 {
975 0
976 }
977
978 /// Byte offset of the first byte of `row` within the buffer's
979 /// canonical `lines().join("\n")` rendering. Out-of-range rows
980 /// clamp to `len_bytes()`.
981 ///
982 /// Default implementation walks every prior row's byte length and
983 /// adds a separator byte per row gap. Backends with a faster path
984 /// (rope position-of-line) should override.
985 ///
986 /// Pre-0.1.0 default-impl addition — does not extend the sealed
987 /// surface for downstream impls.
988 fn byte_of_row(&self, row: usize) -> usize {
989 let n = self.line_count() as usize;
990 let row = row.min(n);
991 let mut acc = 0usize;
992 for r in 0..row {
993 acc += self.line(r as u32).len();
994 // Separator newline between rows. The canonical engine
995 // join uses `\n` between every pair of lines (no trailing
996 // newline), so add one separator per row strictly before
997 // the last buffer row.
998 if r + 1 < n {
999 acc += 1;
1000 }
1001 }
1002 acc
1003 }
1004}
1005
1006/// Mutating sub-trait of [`Buffer`]. Distinct trait name from the
1007/// crate-root [`Edit`] struct — this one carries methods, the other
1008/// is a value type.
1009pub trait BufferEdit: Send {
1010 /// Insert `text` at `pos`. Implementations clamp out-of-range
1011 /// positions to the document end.
1012 fn insert_at(&mut self, pos: Pos, text: &str);
1013 /// Delete the half-open `range`.
1014 fn delete_range(&mut self, range: core::ops::Range<Pos>);
1015 /// Replace the half-open `range` with `replacement`.
1016 fn replace_range(&mut self, range: core::ops::Range<Pos>, replacement: &str);
1017 /// Replace the entire buffer content with `text`. The cursor is
1018 /// clamped to the surviving content. Used by `:e!` / undo
1019 /// restore / snapshot replay where expressing "replace whole
1020 /// buffer" via [`replace_range`] would require knowing the end
1021 /// position. Default impl uses [`replace_range`] with a
1022 /// best-effort end (`u32::MAX` / `u32::MAX`); the canonical
1023 /// in-tree impl overrides it for a single-shot rebuild.
1024 fn replace_all(&mut self, text: &str) {
1025 self.replace_range(
1026 Pos::ORIGIN..Pos {
1027 line: u32::MAX,
1028 col: u32::MAX,
1029 },
1030 text,
1031 );
1032 }
1033}
1034
1035/// Search sub-trait of [`Buffer`]. The pattern is owned by the engine;
1036/// buffers do not cache compiled regexes.
1037pub trait Search: Send {
1038 /// First match at-or-after `from`. `None` when no match remains.
1039 fn find_next(&self, from: Pos, pat: ®ex::Regex) -> Option<core::ops::Range<Pos>>;
1040 /// Last match at-or-before `from`.
1041 fn find_prev(&self, from: Pos, pat: ®ex::Regex) -> Option<core::ops::Range<Pos>>;
1042}
1043
1044/// Buffer super-trait — the pre-1.0 contract every backend implements.
1045///
1046/// Sealed to the engine's own crate family (in-tree
1047/// `hjkl_buffer::Buffer` is the canonical impl). Pre-0.1.0 the engine
1048/// reserves the right to add methods on patch bumps; downstream
1049/// consumers depend on the full trait without naming
1050/// [`sealed::Sealed`].
1051pub trait Buffer: Cursor + Query + BufferEdit + Search + sealed::Sealed + Send {}
1052
1053/// Canonical fold-mutation op carried through [`FoldProvider::apply`].
1054///
1055/// Introduced in 0.0.38 (Patch C-δ.4). The engine raises one `FoldOp`
1056/// per `z…` keystroke / `:fold*` Ex command and dispatches it through
1057/// the [`FoldProvider::apply`] surface. Hosts that own the fold storage
1058/// (default in-tree wraps `&mut hjkl_buffer::Buffer`) decide how to
1059/// apply it — possibly batching, deduping, or vetoing. Hosts without
1060/// folds use [`NoopFoldProvider`] which silently discards every op.
1061///
1062/// `FoldOp` is engine-canonical (per the design doc's resolved
1063/// question 8.2): hosts don't invent their own fold-op enums. Each
1064/// host that exposes folds embeds a `FoldOp` variant in its `Intent`
1065/// enum (or simply observes the engine's pending-fold-op queue via
1066/// [`crate::Editor::take_fold_ops`]).
1067///
1068/// Row indices are zero-based and match the row coordinate space used
1069/// by [`hjkl_buffer::Buffer`]'s fold methods.
1070#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1071#[non_exhaustive]
1072pub enum FoldOp {
1073 /// `:fold {start,end}` / `zf{motion}` / visual-mode `zf` — register a
1074 /// new fold spanning `[start_row, end_row]` (inclusive). The `closed`
1075 /// flag matches the underlying [`hjkl_buffer::Fold::closed`].
1076 Add {
1077 start_row: usize,
1078 end_row: usize,
1079 closed: bool,
1080 },
1081 /// `zd` — drop the fold under `row` if any.
1082 RemoveAt(usize),
1083 /// `zo` — open the fold under `row` if any.
1084 OpenAt(usize),
1085 /// `zc` — close the fold under `row` if any.
1086 CloseAt(usize),
1087 /// `za` — flip the fold under `row` between open / closed.
1088 ToggleAt(usize),
1089 /// `zR` — open every fold in the buffer.
1090 OpenAll,
1091 /// `zM` — close every fold in the buffer.
1092 CloseAll,
1093 /// `zE` — eliminate every fold.
1094 ClearAll,
1095 /// Edit-driven fold invalidation. Drops every fold touching the
1096 /// row range `[start_row, end_row]`. Mirrors vim's "edits inside a
1097 /// fold open it" behaviour. Fired by the engine's edit pipeline,
1098 /// not bound to a `z…` keystroke.
1099 Invalidate { start_row: usize, end_row: usize },
1100}
1101
1102/// Fold-iteration + mutation trait. The engine asks "what's the next
1103/// visible row" / "is this row hidden" through this surface, and
1104/// dispatches fold mutations through [`FoldProvider::apply`], so fold
1105/// storage can live wherever the host pleases (on the buffer, in a
1106/// separate host-side fold tree, or absent entirely).
1107///
1108/// Introduced in 0.0.32 (Patch C-β) for read access; 0.0.38 (Patch
1109/// C-δ.4) added [`FoldProvider::apply`] + [`FoldProvider::invalidate_range`]
1110/// so engine call sites that used to call
1111/// `hjkl_buffer::Buffer::{open,close,toggle,…}_fold_at` directly route
1112/// through this trait now. The canonical read-only implementation
1113/// [`crate::buffer_impl::BufferFoldProvider`] wraps a
1114/// `&hjkl_buffer::Buffer`; the canonical mutable implementation
1115/// [`crate::buffer_impl::BufferFoldProviderMut`] wraps a
1116/// `&mut hjkl_buffer::Buffer`. Hosts that don't care about folds can
1117/// use [`NoopFoldProvider`].
1118///
1119/// The engine carries a `Box<dyn FoldProvider + 'a>` slot today and
1120/// looks up rows through it. Once `Editor<B, H>` flips generic
1121/// (Patch C, 0.1.0) the slot moves onto `Host` directly.
1122pub trait FoldProvider: Send {
1123 /// First visible row strictly after `row`, skipping hidden rows.
1124 /// `None` past the end of the buffer.
1125 fn next_visible_row(&self, row: usize, row_count: usize) -> Option<usize>;
1126 /// First visible row strictly before `row`. `None` past the top.
1127 fn prev_visible_row(&self, row: usize) -> Option<usize>;
1128 /// Is `row` currently hidden by a closed fold?
1129 fn is_row_hidden(&self, row: usize) -> bool;
1130 /// Range `(start_row, end_row, closed)` of the fold containing
1131 /// `row`, if any. Lets `za` / `zo` / `zc` find their target
1132 /// without iterating the full fold list.
1133 fn fold_at_row(&self, row: usize) -> Option<(usize, usize, bool)>;
1134
1135 /// Apply a [`FoldOp`] to the underlying fold storage. Read-only
1136 /// providers (e.g. [`crate::buffer_impl::BufferFoldProvider`] which
1137 /// holds a `&Buffer`) and providers that don't track folds (e.g.
1138 /// [`NoopFoldProvider`]) implement this as a no-op.
1139 ///
1140 /// Default impl is a no-op so that read-only / host-stub providers
1141 /// don't need to override it; mutable providers
1142 /// (e.g. [`crate::buffer_impl::BufferFoldProviderMut`]) override
1143 /// this to dispatch to the underlying buffer's fold methods.
1144 fn apply(&mut self, op: FoldOp) {
1145 let _ = op;
1146 }
1147
1148 /// Drop every fold whose range overlaps `[start_row, end_row]`.
1149 /// Edit pipelines call this after a user edit so vim's "edits
1150 /// inside a fold open it" behaviour fires. Default impl forwards
1151 /// to [`FoldProvider::apply`] with a [`FoldOp::Invalidate`].
1152 fn invalidate_range(&mut self, start_row: usize, end_row: usize) {
1153 self.apply(FoldOp::Invalidate { start_row, end_row });
1154 }
1155}
1156
1157/// No-op [`FoldProvider`] for hosts that don't expose folds. Every
1158/// row is visible; `is_row_hidden` always returns `false`.
1159#[derive(Debug, Default, Clone, Copy)]
1160pub struct NoopFoldProvider;
1161
1162impl FoldProvider for NoopFoldProvider {
1163 fn next_visible_row(&self, row: usize, row_count: usize) -> Option<usize> {
1164 let last = row_count.saturating_sub(1);
1165 if last == 0 && row == 0 {
1166 return None;
1167 }
1168 let r = row.checked_add(1)?;
1169 (r <= last).then_some(r)
1170 }
1171
1172 fn prev_visible_row(&self, row: usize) -> Option<usize> {
1173 row.checked_sub(1)
1174 }
1175
1176 fn is_row_hidden(&self, _row: usize) -> bool {
1177 false
1178 }
1179
1180 fn fold_at_row(&self, _row: usize) -> Option<(usize, usize, bool)> {
1181 None
1182 }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187 use super::*;
1188
1189 #[test]
1190 fn caret_is_empty() {
1191 let sel = Selection::caret(Pos::new(2, 4));
1192 assert!(sel.is_empty());
1193 assert_eq!(sel.anchor, sel.head);
1194 }
1195
1196 #[test]
1197 fn selection_set_default_has_one_caret() {
1198 let set = SelectionSet::default();
1199 assert_eq!(set.items.len(), 1);
1200 assert_eq!(set.primary, 0);
1201 assert_eq!(set.primary().anchor, Pos::ORIGIN);
1202 }
1203
1204 #[test]
1205 fn edit_constructors() {
1206 let p = Pos::new(0, 5);
1207 assert_eq!(Edit::insert(p, "x").range, p..p);
1208 assert!(Edit::insert(p, "x").replacement == "x");
1209 assert!(Edit::delete(p..p).replacement.is_empty());
1210 }
1211
1212 #[test]
1213 fn attrs_flags() {
1214 let a = Attrs::BOLD | Attrs::UNDERLINE;
1215 assert!(a.contains(Attrs::BOLD));
1216 assert!(!a.contains(Attrs::ITALIC));
1217 }
1218
1219 #[test]
1220 fn options_set_get_roundtrip() {
1221 let mut o = Options::default();
1222 o.set_by_name("tabstop", OptionValue::Int(4)).unwrap();
1223 assert!(matches!(o.get_by_name("ts"), Some(OptionValue::Int(4))));
1224 o.set_by_name("expandtab", OptionValue::Bool(true)).unwrap();
1225 assert!(matches!(o.get_by_name("et"), Some(OptionValue::Bool(true))));
1226 o.set_by_name("iskeyword", OptionValue::String("a-z".into()))
1227 .unwrap();
1228 match o.get_by_name("iskeyword") {
1229 Some(OptionValue::String(s)) => assert_eq!(s, "a-z"),
1230 other => panic!("expected String, got {other:?}"),
1231 }
1232 }
1233
1234 #[test]
1235 fn options_unknown_name_errors_on_set() {
1236 let mut o = Options::default();
1237 assert!(matches!(
1238 o.set_by_name("frobnicate", OptionValue::Int(1)),
1239 Err(EngineError::Ex(_))
1240 ));
1241 assert!(o.get_by_name("frobnicate").is_none());
1242 }
1243
1244 #[test]
1245 fn options_type_mismatch_errors() {
1246 let mut o = Options::default();
1247 assert!(matches!(
1248 o.set_by_name("tabstop", OptionValue::String("nope".into())),
1249 Err(EngineError::Ex(_))
1250 ));
1251 assert!(matches!(
1252 o.set_by_name("iskeyword", OptionValue::Int(7)),
1253 Err(EngineError::Ex(_))
1254 ));
1255 }
1256
1257 #[test]
1258 fn options_int_to_bool_coercion() {
1259 // `:set ic=0` reads as boolean false; `:set ic=1` as true.
1260 // Common vim spelling.
1261 let mut o = Options::default();
1262 o.set_by_name("ignorecase", OptionValue::Int(1)).unwrap();
1263 assert!(matches!(o.get_by_name("ic"), Some(OptionValue::Bool(true))));
1264 o.set_by_name("ignorecase", OptionValue::Int(0)).unwrap();
1265 assert!(matches!(
1266 o.get_by_name("ic"),
1267 Some(OptionValue::Bool(false))
1268 ));
1269 }
1270
1271 #[test]
1272 fn options_wrap_linebreak_roundtrip() {
1273 let mut o = Options::default();
1274 assert_eq!(o.wrap, WrapMode::None);
1275 o.set_by_name("wrap", OptionValue::Bool(true)).unwrap();
1276 assert_eq!(o.wrap, WrapMode::Char);
1277 o.set_by_name("linebreak", OptionValue::Bool(true)).unwrap();
1278 assert_eq!(o.wrap, WrapMode::Word);
1279 assert!(matches!(
1280 o.get_by_name("wrap"),
1281 Some(OptionValue::Bool(true))
1282 ));
1283 assert!(matches!(
1284 o.get_by_name("lbr"),
1285 Some(OptionValue::Bool(true))
1286 ));
1287 o.set_by_name("linebreak", OptionValue::Bool(false))
1288 .unwrap();
1289 assert_eq!(o.wrap, WrapMode::Char);
1290 o.set_by_name("wrap", OptionValue::Bool(false)).unwrap();
1291 assert_eq!(o.wrap, WrapMode::None);
1292 }
1293
1294 #[test]
1295 fn options_default_modern() {
1296 // 0.2.0: defaults flipped from vim's tabstop=8/expandtab=off to
1297 // modern editor defaults (4-space soft tabs).
1298 let o = Options::default();
1299 assert_eq!(o.tabstop, 4);
1300 assert_eq!(o.shiftwidth, 4);
1301 assert_eq!(o.softtabstop, 4);
1302 assert!(o.expandtab);
1303 assert!(o.hlsearch);
1304 assert!(o.wrapscan);
1305 assert!(o.smartindent);
1306 assert_eq!(o.timeout_len, core::time::Duration::from_millis(1000));
1307 }
1308
1309 #[test]
1310 fn editor_snapshot_version_const() {
1311 assert_eq!(EditorSnapshot::VERSION, 4);
1312 }
1313
1314 #[test]
1315 fn editor_snapshot_default_shape() {
1316 let s = EditorSnapshot {
1317 version: EditorSnapshot::VERSION,
1318 mode: SnapshotMode::Normal,
1319 cursor: (0, 0),
1320 lines: vec!["hello".to_string()],
1321 viewport_top: 0,
1322 registers: crate::Registers::default(),
1323 marks: Default::default(),
1324 };
1325 assert_eq!(s.cursor, (0, 0));
1326 assert_eq!(s.lines.len(), 1);
1327 }
1328
1329 #[cfg(feature = "serde")]
1330 #[test]
1331 fn editor_snapshot_roundtrip() {
1332 let mut marks = std::collections::BTreeMap::new();
1333 marks.insert('A', (5u32, 2u32));
1334 marks.insert('a', (1u32, 0u32));
1335 let s = EditorSnapshot {
1336 version: EditorSnapshot::VERSION,
1337 mode: SnapshotMode::Insert,
1338 cursor: (3, 7),
1339 lines: vec!["alpha".into(), "beta".into()],
1340 viewport_top: 2,
1341 registers: crate::Registers::default(),
1342 marks,
1343 };
1344 let json = serde_json::to_string(&s).unwrap();
1345 let back: EditorSnapshot = serde_json::from_str(&json).unwrap();
1346 assert_eq!(s.cursor, back.cursor);
1347 assert_eq!(s.lines, back.lines);
1348 assert_eq!(s.viewport_top, back.viewport_top);
1349 }
1350
1351 #[test]
1352 fn engine_error_display() {
1353 let e = EngineError::ReadOnly;
1354 assert_eq!(e.to_string(), "buffer is read-only");
1355 let e = EngineError::OutOfBounds(Pos::new(3, 7));
1356 assert!(e.to_string().contains("out of bounds"));
1357 }
1358}