alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# `vim` Module Notes

The `vim` module is intended to stay pure Rust editor semantics. It may expose
Bevy `Resource` derives for ECS storage, but Vim rules should not depend on
Bevy systems, ECS messages, rendering, filesystem state, or status UI policy.

## Public Shape

- input grammar: `KeyToken`, `NormalGrammar`, `VisualGrammar`
- actions and operations: `VimAction`, `ActionDispatcher`, `VimOperation`
- state: `VimCursor`, `VimMode`, `VimSelectionState`, `BlockSelection`,
  `VimSearchState`,
  `VimCommandState`, `LeaderState`, `NormalState`, `VisualState`,
  `RegisterBank`
- movement and text placement: `Motion`, `Count`, `Counted`, `Operator`,
  `PastePlacement`, motion subtypes
- status/errors: `VimError`, `VimStatusLine`, `VimStatusMessage`

The intended flow is:

```text
KeyToken -> grammar command -> VimAction/VimOperation -> pure state effects
```

The Bevy adapter may convert final outcomes into ECS messages, but the semantic
decision should already be represented in Vim-owned types.

## Modules

### `key`

`KeyToken` is the normalized input vocabulary consumed by grammar and keymaps.
It deliberately hides Bevy keyboard details.

Key methods:

- `count_digit() -> Option<usize>`
- `non_zero_count_digit() -> Option<NonZeroUsize>`

Invariant: count parsing only begins with a non-zero digit unless a count is
already pending. That policy is enforced by `NormalGrammar`, not by `KeyToken`.

### `grammar`

`NormalGrammar` parses normalized tokens into `NormalCommand`.

Key types:

- `Count`: non-zero Vim count.
- `Counted<T>`: parsed item plus count, defaulting to one.
- `NormalCommand`: motion, operator-with-motion, insert entry, paste, mode
  switch, prompt start, search repeat, dot-repeat, viewport placement.
- `Operator`: `Delete`, `Yank`, `Change`.
- `InsertEntry`: `i`, `a`, `I`, `A`, `o`, `O`.
- `PastePlacement`: `p` after or below, `P` before or above.
- `ModeSwitch`: normal-mode entry into visual modes.
- `ViewportPosition`: `zt`, `zz`, `zb`.

Key methods:

- `NormalGrammar::feed(token) -> NormalGrammarOutput`
- `NormalGrammar::reset()`
- `Counted::once(item)`

Invariants:

- Pending prefixes are explicit (`g`, `z`, char-search prefixes).
- Counts saturate on overflow.
- Char-search target characters are payload, not reinterpreted as following
  commands.
- Grammar emits typed commands only. It does not mutate cursor, mode, search,
  selection, status, buffers, or ECS.

Normal grammar now parses `d{motion}`, `y{motion}`, `c{motion}`, `p`, `P`, `.`,
visual `v`, `V`, `Ctrl-v`, motion counts, operator counts, paste counts, and
doubled operators such as `dd`, `yy`, and `cc`.

### `operation`

`operation.rs` is the pure semantic layer between grammar/actions and adapters.

Key types:

- `VimOperation`: semantic intent below key/action dispatch.
- `OperatorTargetSource`: unresolved operator target producer, currently normal
  motion, current line, text object, or visual selection.
- `ResolvedTarget`: alias for a resolved `OperatorTarget`.
- `OperationOutcome`: ordered operation effects before adapter emission.
- `OperationEffect`: pure effects such as cursor motion, prompt start, viewport
  placement, paste, or operator application.
- `OperationError`, `TargetResolutionError`: semantic failure shapes.

Key methods:

- `impl From<NormalCommand> for VimOperation`
- `VimOperation::resolve(stream, cursor_byte_index)`
- `VimOperation::resolve_without_target()`
- `OperationOutcome::effects()`
- `OperationOutcome::into_effects()`

Invariants:

- Operations do not know about ECS, Bevy entities, files, rendering, or backend
  synchronization.
- Unresolved operator targets fail as typed errors. They are not silently
  treated as no-ops.
- `VimOperation::resolve` produces stream-scoped target proofs, not buffer
  mutations.

Normal-mode and visual-mode operator operations resolve `OperatorTargetSource`
into `OperatorTarget` before producing `OperationEffect::ApplyOperator`. The
effect is still pure; registers and buffer mutation are later adapter/owner
work.

Paste operations remain pure intent. The adapter resolves them against the
view-local unnamed register through `vim::paste`, then emits a bounded
`BufferEditRequested` plus a cursor-cell request. Register text still does not
appear in diagnostics.

Dot-repeat stores repeatable semantic operations in `RepeatState`. It does not
store raw key events or prompt text. The current repeatable set is normal
delete/change operator commands and paste operations. Replay re-enters the same
target or paste planning path against current text and registers.

Text-object operator targets resolve through `vim::text_object` before they
become `OperatorTarget`s. `iw`, `aw`, `ip`, and `ap` are pure target producers;
the adapter still performs register writes and edit requests after resolution.

Successful visual delete and yank use the same resolved operator effect as
normal operators. The adapter performs the visual-mode cleanup after successful
register or edit effect emission: selection is cleared and mode returns to
normal.

### `operator`

`operator.rs` owns resolved operator targets. This is separate from
`operation.rs`: operations describe intent and target producers; operator
targets prove the byte range and target kind after resolution.

Key types:

- `TargetKind`: characterwise, linewise, blockwise-reserved.
- `OperatorTarget`: resolved target kind plus validated byte range.
- `ResolvedTarget`: alias for `OperatorTarget` at call sites where the
  distinction from target producers matters.
- `ValidatedOperatorRange`: stream-scoped `ValidatedTextRange` wrapper for
  ordered, in-bounds, UTF-8-aligned half-open ranges.
- `TargetResolutionError`: closed reasons for invalid or unsupported targets.

Key methods:

- `OperatorTarget::characterwise(stream, range)`
- `OperatorTarget::linewise(stream, range)`
- `OperatorTarget::from_visual_selection(stream, selection, cursor, mode)`
- `OperatorTarget::from_source(stream, cursor, source)`
- `OperatorTarget::from_normal_source(stream, cursor, source)`
- `OperatorTarget::current_line(stream, cursor)`
- `ValidatedOperatorRange::new(stream, range)`
- range accessors: `start()`, `end()`, `as_range()`,
  `validated_text_range()`, `len()`, `is_empty()`

Invariants:

- `OperatorTarget` is a stream and revision scoped range proof, not permission
  to mutate the buffer.
- The adapter may carry `validated_text_range()` into `BufferEdit`, but the
  buffer owner still revalidates stream identity and revision before mutation.
- Characterwise visual targets include the cursor cell.
- Linewise visual operator targets include the trailing newline when present.
- Blockwise visual mode exists for selection and rendering. Operator targets
  still reject it until block edit and register semantics have a dedicated
  representation.
- Invalid ranges are typed failures, not clamped destructive operations.
- Normal vertical motions and line-address motions resolve linewise.
- Normal word/column/character motions resolve characterwise, with `$`
  including the destination cell.
- Visual characterwise and linewise selections resolve through the same
  `OperatorTargetSource` and `VimOperation::resolve` path as normal operators.
- Text objects are resolved into characterwise targets and then validated by
  `ValidatedOperatorRange` against the current `TextByteStream`.

Current gap: characterwise Vim edge cases are intentionally conservative; later
operator work should add fixtures for `de`, more reverse normal motions, and
additional inclusive/exclusive Vim edge cases before broadening mutation
semantics.

### `text_object`

`text_object.rs` owns pure text-object target production.

Key types:

- `TextObject`: parsed object extent and family.
- `TextObjectScope`: inner or around.
- `TextObjectKind`: word or paragraph.

Key method:

- `resolve_text_object_range(text, cursor, object, count)`

Invariants:

- Text objects produce half-open byte ranges for one text snapshot.
- Word objects split keyword runs and punctuation runs; whitespace is a
  separator.
- Paragraph objects are nonblank line runs separated by blank lines.
- `Around` includes adjacent separators without storing or logging text.
- Missing objects fail closed as `TargetResolutionError::NoTextObject`.

### `register`

`register.rs` owns pure Vim register storage. Registers store arbitrary user
text, so debug output is redacted to register shape and byte lengths.

Key types:

- `RegisterBank`: current unnamed register and yank register `0`.
- `RegisterName`: supported register selectors.
- `RegisterText`: stored register text plus metadata.
- `RegisterKind`: characterwise or linewise metadata.
- `RegisterTextShape`, `RegisterBankShape`: redacted diagnostics.
- `RegisterWriteError`: closed write failure reasons.

Key methods:

- `RegisterBank::get(name)`
- `RegisterBank::unnamed()`
- `RegisterBank::yank0()`
- `RegisterBank::write_yank(stream, target)`
- `RegisterBank::write_delete(stream, target)`
- `RegisterText::from_target(stream, target)`
- `RegisterText::as_str()`
- `RegisterText::kind()`

Invariants:

- Register text fields are private.
- Registers are currently owned by `VimEditorState` inside `VimModalState`,
  which makes them `EditorView`-local state.
- `RegisterBank` enforces a per-entry byte limit before replacing existing
  register contents.
- Register ownership is deliberately not inside `NormalState`; registers are
  editor state, not grammar state.
- `Debug` for `RegisterText` and `RegisterBank` never includes stored text.
- Yank writes update both the unnamed register and register `0`.
- Delete writes update the unnamed register without replacing register `0`.
- Blockwise targets are rejected until blockwise visual mode is implemented.
- Register writes revalidate the target against the same stream snapshot before
  copying text.
- A target copied against a changed or different text stream fails closed as
  `RegisterWriteError::StaleTarget`.
- Property tests cover register copies and yank shape over arbitrary generated
  Unicode text and valid character-boundary ranges.

### `paste`

`paste.rs` owns pure Vim paste placement. It consumes a text snapshot, a cursor
cell, register text, a count, and `PastePlacement`, then returns a `PastePlan`.

Key types:

- `PastePlacement`: normal-mode `p` or `P`.
- `PastePlan`: insertion byte index, insertion text, and post-paste cursor cell.
- `PastePlanError`: empty register or count-expanded payload too large.

Key methods:

- `plan_paste(text, cursor, register, count, placement, max_byte_len)`

Invariants:

- Characterwise `p` inserts after the current cursor cell; `P` inserts before
  it.
- Linewise `p` inserts below the current physical line; `P` inserts above it.
- Linewise registers without a trailing newline are normalized to full lines at
  paste time.
- Count expansion is checked before allocation and fails closed under the
  caller-supplied byte budget.
- `PastePlan` is not authority to mutate text. It is converted into
  `BufferEditRequested`, and the buffer owner still validates UTF-8 boundaries.

### `repeat`

`repeat.rs` owns dot-repeat state. It stores the last repeatable change as a
semantic operation shape.

Key types:

- `RepeatState`: view-local last-change state.
- `RepeatableOperation`: accepted semantic operation for `.` replay.
- `RepeatStateShape`, `RepeatableOperationShape`: redacted diagnostics.

Key methods:

- `RepeatState::last_change()`
- `RepeatState::record(operation)`
- `RepeatableOperation::from_operation(operation)`
- `RepeatableOperation::operation()`

Invariants:

- Repeat state is editor state, not grammar state. In ECS it lives in
  `VimEditorState`, not `VimGrammarState`.
- Repeat state stores no buffer text, register text, prompt text, or raw input
  event history.
- Yank, motion, prompt, search, undo, and redo are not repeatable changes.
- Replay must still pass through target resolution, paste planning, ECS edit
  requests, and owner mutation.

### `action`

`VimAction` is the higher-level action vocabulary used by mappings and leader
bindings. `ActionDispatcher` applies actions to borrowed Vim state.

Key types:

- `VimAction`: normal command, search repeat, viewport page, viewport position,
  prefilled ex command, no-op.
- `ActionContext`: borrowed state needed for one dispatch.
- `ActionDispatcher`: stateless dispatcher.

Key method:

- `ActionDispatcher::dispatch(action, context)`

Invariants:

- Dispatch now routes through `VimOperation` before mutating Vim state.
- Viewport placement only clears Vim status here; ECS viewport messages are
  emitted by the adapter because viewport state is not owned by `vim`.
- Page motion uses viewport height from the caller; pure motion defaults are
  only for non-viewport-aware calls.

Current gap: unresolved operation errors are currently dropped by dispatch.
That is acceptable for unparsed operators today, but operator work should map
typed failures to status or adapter effects deliberately.

### `normal`

`NormalState` owns normal-mode parser state and last char-search state.

Key methods:

- `feed(token, NormalCommandContext) -> NormalGrammarOutput`
- `feed_command(token) -> NormalGrammarOutput`
- `apply_command(command, NormalCommandContext)`
- `apply_counted_motion(text, cursor, counted_motion)`

Invariants:

- Last char-search state belongs here because `;` and `,` depend on normal-mode
  command history.
- Relative motions repeat by count; line addresses resolve once.
- Vertical motion desired-column state is owned by `VimCursor`.
- Mode switches update `VimMode` and `VimSelectionState` together.

`NormalCommand::Operator` and newline-opening insert entries do not execute
authoritative mutation through `NormalState::apply_command`; operator and insert
entry execution moves through `VimOperation`/adapter boundaries and converts
resolved effects into typed ECS requests.

### `visual`

`VisualGrammar` reuses `NormalGrammar` for motion-shaped visual commands and
adds visual-specific controls.

Key types:

- `VisualCommand`: motion, mode switch, endpoint swap, operator, text object,
  exit.
- `VisualEndpoint`: `o` and `O`.
- `VisualState`: grammar holder.
- `VisualCommandContext`: borrowed state for one command.

Key methods:

- `VisualGrammar::feed(token)`
- `VisualState::feed(token, context)`
- `VisualState::apply_command(command, context)`
- `VisualCommand::operator_operation(selection_state, active_visual_mode)`

Invariants:

- Visual mode owns selection behavior, but reuses normal motion semantics.
- Toggling the active visual mode exits to normal and clears selection.
- Switching visual modes restarts the selection anchor at the current cursor.
- Endpoint swap exchanges cursor and anchor through `VimSelectionState`.
- `Ctrl-v` enters blockwise visual mode. Blockwise rendering derives
  per-physical-line byte ranges by character column.
- Visual `d`, `y`, and `c` parse into typed operators over the active
  selection.
- Visual operators use `OperatorTargetSource::VisualSelection`, so target
  validation is shared with normal operators and remains separate from mutation.

Visual operators are executed by the adapter through `VimOperation::resolve`
against the current `TextByteStream`. Delete writes the unnamed register and
emits a typed delete request; yank updates the unnamed and `0` registers
without mutating the buffer. Change uses the same validated target path as
delete, writes the unnamed register, emits the delete request, clears selection,
and enters insert mode.

Blockwise visual operators currently fail closed with
`TargetResolutionError::UnsupportedTarget`. This keeps block selection usable
for presentation without pretending the existing contiguous byte-range target is
adequate for rectangular mutation.

### `cursor`

`VimCursor` stores byte-index cursor state and desired column for vertical
movement.

Key methods:

- `byte_index()`
- `desired_column()`
- `set_byte_index(text, byte_index)`
- `set_desired_column(column)`
- `apply_motion(text, motion)`
- direction helpers: `move_left`, `move_right`, `move_up`, `move_down`
- word/paragraph helpers
- `clamp_to_text(text)`

Invariants:

- Cursor byte index is always clamped to a UTF-8 boundary.
- Cursor position prefers visible cursor cells. Newline bytes are not cursor
  cells except for empty-line starts and valid EOF cases.
- Horizontal and non-vertical movement clear desired column.
- Vertical movement preserves desired character column across short lines.
- ECS cursor requests distinguish normal cursor cells from insert caret
  boundaries through `CursorMoveDestination`. The cursor owner validates the
  requested coordinate kind.

### `motion`

`motion/mod.rs` is the public motion API. Helpers are split by movement family:

- `horizontal.rs`: single-line character, column, and char-search movement.
- `vertical.rs`: line movement and desired-column projection.
- `word.rs`: `word` and `WORD` movement.
- `paragraph.rs`: blank-line-delimited paragraph movement.

Key functions:

- `apply_motion(text, byte_index, motion) -> usize`
- `apply_page_motion(text, byte_index, direction, page_lines) -> usize`
- `apply_screen_column_motion(text, byte_index, column) -> usize`
- `apply_vertical_motion_to_column(text, byte_index, motion, column) -> usize`
- `clamp_to_boundary(text, index) -> usize`
- `clamp_to_cursor_position(text, index) -> usize`
- `is_cursor_position(text, index) -> bool`
- line address helpers: `first_line_start`, `last_line_start`,
  `numbered_line_start`

Invariants:

- All public motion functions return byte indices that are in-bounds and on
  UTF-8 boundaries.
- `apply_motion` additionally clamps to a valid normal-mode cursor cell.
- Lowercase word motions distinguish keyword and punctuation runs.
- Uppercase WORD motions use whitespace-delimited runs.
- Character searches stay on the current physical line.
- Page motion is pure and line-count based; viewport-aware dispatch provides
  the visible line count.

### `selection`

`VimSelectionState` stores the active visual anchor. `VimSelection` computes
ranges from the anchor and cursor. `BlockSelection` is the rectangular display
shape used by blockwise visual mode.

Key methods:

- `VimSelectionState::start(text, anchor)`
- `clear()`
- `selection()`
- `set_anchor(text, anchor)`
- `VimSelection::byte_range(text, cursor)`
- `characterwise_byte_range(text, cursor)`
- `linewise_byte_range(text, cursor)`
- `linewise_operator_byte_range(text, cursor)`
- `blockwise_byte_ranges(text, cursor)`
- `BlockSelection::new(text, anchor, cursor)`
- `BlockSelection::byte_ranges(text)`

Invariants:

- Selection anchors are clamped to UTF-8 boundaries at construction.
- Ranges are ordered and half-open.
- Characterwise visual ranges include the cursor cell.
- Linewise display ranges cover visible line content.
- Linewise operator ranges include the trailing newline when present.
- Blockwise display ranges are per-line, UTF-8-aligned, and skip physical lines
  shorter than the selected start column.

Visual operator ranges are wrapped into stream-scoped `ResolvedTarget` values
through `OperatorTargetSource::VisualSelection` and `VimOperation::resolve`.

### `search`

Search is literal-only today.

Key types:

- `SearchDirection`: forward/backward.
- `SearchRepeatDirection`: Vim `n`/`N` relative repeat.
- `SearchQuery`: bounded user query text.
- `SearchCaseSensitivity`: sensitive/insensitive.
- `SearchOutcome`: match byte index or `VimError`.
- `SearchState` / `VimSearchState`: active query and last submitted query.

Key methods:

- `SearchState::start(direction)`
- `cancel()`
- `push_text(text)`
- `backspace()`
- `submit(text, cursor, options)`
- `repeat(text, cursor, direction, options)`
- `repeat_relative(text, cursor, repeat_direction, options)`
- `find_literal(text, cursor, query, direction, options)`
- `literal_match_ranges_in_range(text, query, visible_range, options)`

Invariants:

- Query text is capped at 256 Unicode scalar values.
- Status rendering uses escaped query text.
- Empty search submit repeats the previous query or returns `E35`.
- `n`/`N` use the last submitted search direction.
- Matches are found at UTF-8 boundaries and final cursor targets are clamped to
  visible cursor cells.
- Highlight scanning is bounded by `DEFAULT_SEARCH_HIGHLIGHT_SCAN_BYTES`.

### `command`

Command-line state and parser for supported `:` commands.

Key types:

- `VimCommandState`
- `VimCommandText`
- `VimCommand`
- `CommandCatalog`
- `CommandSpec`
- `CommandName`
- `CommandArgSchema`
- `CommandAuthority`
- `QuitPolicy`
- `WriteQuitPolicy`

Key methods:

- `VimCommandState::start()`
- `start_with(text)`
- `cancel()`
- `push_text(text)`
- `backspace()`
- `submit() -> Result<VimCommand, VimError>`
- `VimCommandText::status_text()`
- `CommandCatalog::specs()`
- `CommandCatalog::parse(text)`

Supported commands:

- `:w`, `:write`
- `:q`, `:quit`
- `:q!`, `:quit!`
- `:wq`, `:wq!`
- `:x`, `:xit`, `:exit`
- `:set opaque`
- `:set transparent`

Invariants:

- Command text is capped at 256 Unicode scalar values.
- Command prompt rendering uses escaped text.
- Parsing returns typed commands, not strings.
- The catalog records command names, aliases, argument schemas, and authority
  classes before owner-boundary execution.
- Unsupported commands return `VimError::NotAnEditorCommand`.

### `error`

`VimError` contains user-facing Vim-compatible status errors.

Key types:

- `VimError`
- `VimStatusMessage`
- `VimStatusLine`

Key methods:

- `VimError::code()`
- `message()`
- `status_text()`
- `VimStatusLine::clear()`
- `set_error(error)`
- `set_info(text)`
- `message()`

Invariants:

- `VimError` is safe to render as status text.
- Filesystem/backend errors should map into stable Vim-facing variants before
  reaching this module.
- Arbitrary paths, buffer text, register text, or OS messages do not belong in
  `VimError`.

### `config`

`VimConfig` collects keymaps, options, motion config, and leader config.

Key types:

- `VimOptions`: `ignore_case`, `smart_case`, `wrap_scan`, `timeout_len_ms`.
- `KeymapSet`, `Keymap`, `ModeSet`, `KeySequence`, `KeyAction`.
- `BuiltinAction`.
- `MotionConfig`: currently empty.

Invariants:

- Key sequences are stored as normalized `KeyToken`s.
- Builtin actions are typed.
- Default keymaps cover `h`, `j`, `k`, `l`.
- Current keymap structures are mostly scaffolding; active dispatch still
  primarily uses grammar and leader bindings.

### `leader`

Leader state is normal-mode-only interaction state plus default bindings.

Key types:

- `LeaderState`
- `LeaderBinding`
- `LeaderConfig`

Key methods:

- `LeaderState::start()`
- `cancel()`
- `is_pending()`
- `is_menu_visible()`
- `tick(delta_ms, delay_ms)`
- `LeaderConfig::binding_for(sequence)`

Invariants:

- Leader delay uses saturating elapsed time.
- Leader UI state is separate from command grammar.
- Default bindings dispatch typed `VimAction`s.

### `mode`

`VimMode` is the high-level mode state. It currently supports:

- `Normal`
- `Insert(InsertState)`
- `Visual(VisualMode::Characterwise)`
- `Visual(VisualMode::Linewise)`

Insert mode carries an `InsertState` so future insert-like submodes can own
entry/exit policy without adding more top-level mode variants. `InsertCommand`
names text insertion, newline insertion, backward deletion, and exit intent, but
raw buffer mutation still belongs in a dedicated adapter path.

### `insert`

`insert.rs` owns pure insert-mode semantics. It resolves entry commands against
a text snapshot, plans insert-mode edits, enforces the insert payload byte
budget, and computes the caret used when returning to normal mode.

Key types:

- `InsertState`
- `InsertEntry`
- `InsertCommand`
- `InsertExitPolicy`
- `InsertEntryCaret`
- `InsertEditPlanner`
- `InsertPlanEdit`

Key methods:

- `InsertEntry::insert_state()`
- `InsertEntry::opens_line()`
- `resolve_insert_entry_caret(text, cursor_byte_index, entry)`
- `InsertEditPlanner::new(text, cursor_byte_index, max_payload_bytes)`
- `push_insert(text)`
- `delete_backward()`
- `exit_caret(policy)`
- `into_edits()`

Invariants:

- Insert planning uses byte indices over one text snapshot and preserves UTF-8
  caret boundaries.
- The planner returns pure `InsertPlanEdit` values, not `BufferEditRequested`
  ECS messages.
- `Debug` for insert commands, planned edits, and planners reports byte lengths
  and ranges, not inserted text or buffer text.
- `adapters::bevy::vim::insert` is the Bevy/ECS boundary. It decodes
  `EditorInputEvent`s into `InsertCommand`s, emits redacted input rejections,
  and converts `InsertPlanEdit` values into typed edit requests.
  Authoritative mutation remains in buffer owner systems.

## Cross-Module Invariants

- Byte indices are the coordinate system.
- Public motion, cursor, selection, and operation range constructors must
  preserve UTF-8 boundaries.
- Grammar parses; it does not mutate.
- Operations describe semantic intent; adapters collect effect batches before
  emitting ECS requests.
- ECS owner systems mutate authoritative buffers, files, viewports, and status.
- User text entering prompts is bounded and escaped before status rendering.
- User text stored in registers is bounded, view-local, and redacted in
  diagnostics and status output unless a later feature explicitly consumes it
  through a typed operation.
- Vim-facing errors are stable status contracts, not arbitrary diagnostic
  strings.
- Repeated behavior (`;`, `,`, `n`, `N`) depends on explicit state owners:
  `NormalState` for char search and `SearchState` for literal search.

## Current Work Queue

- Decide how operation errors become status or adapter effects.
- Add command catalog entries only with an argument schema, authority class, and
  owner-boundary handler.