# `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.