From 336623f288f6425e21c8c5b5a651883a0949eadc Mon Sep 17 00:00:00 2001 From: shubhook Date: Sat, 28 Nov 2026 21:07:56 +0530 Subject: [PATCH 1/3] editor: add T-112 task file for VS Code typing undo groups Refs: T-112, ED-2, ED-4 --- tasks/112-vscode-undo-groups.md | 171 ++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 tasks/112-vscode-undo-groups.md diff --git a/tasks/112-vscode-undo-groups.md b/tasks/112-vscode-undo-groups.md new file mode 100644 index 0000000..34a8963 --- /dev/null +++ b/tasks/112-vscode-undo-groups.md @@ -0,0 +1,171 @@ +# T-112: Group VS Code typing into undo steps + +After: T-109. This task waits until that one is merged. It is, as PR #42, and so are T-108 and T-110, which this task builds on, and T-114 (PR #45), which also changed `helm-editor`. This spec is written against main at `3566348`. + +**Questions 1 to 4 under "Open questions for Khakha" block the implementation.** The tests pin an answer to each that VS Code's documentation doesn't settle. Questions 5 to 7 have a default the implementation follows unless Khakha says otherwise. + +## Goal + +In VS Code mode, a run of typing undoes in one step, not one character at a time. `helm-editor` decides where each step starts and ends: at a pause, a cursor move or selection change, a switch between typing and deleting, a newline, a deleted line break, a paste, and an undo or redo. Vim mode's groups (T-108) don't change. With this, `cmd-z` after typing a word takes back the word, and a keymap switch never folds one keymap's edits into the other's step. + +PRD: ED-2 (undo and redo by transaction), ED-4 (VS Code's keymap works as a VS Code user expects). + +## Crates and public interface + +Crates: `helm-editor` (the implementation, in `src/**`, and new files in `tests/`) and `helm-bench` (a new benchmark file and its `[[bench]]` entry only). Nothing in `helm-text`. + +The interface is in `crates/helm-editor/src/` with doc comments. Each new function has a `todo!()` body. Fill them in. Don't change a signature, a type or a doc comment's contract. If one looks wrong, say so in the PR description. `UndoGrouping` and `Editor::TYPING_PAUSE` are plain data and already work. Delete each `#[expect(..., reason = "T-112 interface stub; ...")]` once its stub is filled, or clippy with `-D warnings` fails. The rules are in the "Typing groups (T-112)" section of `Editor`'s type docs. This file restates them below with where each comes from. + +Existing items change behaviour as their updated doc comments say, and the implementation must make them match: `Dispatcher::dispatch` and `dispatch_in` set the grouping before running a command, `vscode::keymap()` carries `UndoGrouping::Typing`, `Clone for Editor` copies the new state, and `end_undo_group` and `in_undo_group` cover typing groups. The editing, selection, undo and redo methods follow the "Typing groups" rules under `Typing` grouping and behave exactly as on main under `Explicit`. Every T-101 to T-114 test must still pass. + +- **`UndoGrouping`**, a new public enum exported from the crate root, with two values. `Explicit` is today's behaviour: a group opens and closes only through `begin_undo_group` and `end_undo_group`, and every edit outside one is its own undo step. `Typing` is VS Code's policy below: the editor opens and closes groups itself around runs of typing and deleting. `Explicit` is the default. +- **`Editor::set_undo_grouping` and `Editor::undo_grouping`.** Setting a different value ends any open group, explicit or typing. Setting the value the editor already has changes nothing. `Editor::new` starts at `Explicit`, so every T-105 to T-111 test that builds an editor sees no change. +- **`Editor::set_time`**, which takes a `std::time::Duration`: the time of the edits that follow, measured from any fixed origin. This is how `helm-editor` learns about time without a clock of its own. `helm-ui` calls it before dispatching each key, with the key event's timestamp if the platform gives one, or else the time it received the event from a monotonic clock. The editor stores the value and compares it with the time of the group's last edit. It never reads a clock. Until the first call every edit happens at time zero, so no pause ever ends a step. A time earlier than the last one counts as no pause. +- **`Editor::TYPING_PAUSE`**, a public associated `Duration` constant: how long a pause between two edits has to be to start a new step. One second (open question 1). +- **`Keymap::with_undo_grouping` and `Keymap::undo_grouping`.** A keymap carries the grouping its editors use. `Keymap::new` gives `Explicit`. `vscode::keymap()` returns a keymap with `Typing`. `vim::keymap()` keeps `Explicit`. +- **`Dispatcher::dispatch` and `Dispatcher::dispatch_in`** change behaviour, and their signatures stay. Before running a `Resolution::Run`, each sets the editor's grouping to the active keymap's with `set_undo_grouping`. A resolution that runs nothing leaves the grouping alone. `CommandRegistry::run` and `run_in` don't touch it. The grouping is set before `run_in` starts, because `run_in` ends Vim's `.` record when it finds the editor's group closed (T-109). So a switch to VS Code in the middle of a Vim insert ends that group and its record at the first VS Code key. +- **`Clone for Editor`**, which T-109 wrote by hand to give each copy its own identity, copies the new state too: the grouping, the time, the open group's kind, the time of its last edit and the move flag. A copy keeps an open typing group, as T-109's copy keeps an open explicit group. +- **`Editor::in_undo_group`** returns true while either kind of group is open. `end_undo_group` ends either kind and returns whether one was open. Their doc comments say so; their signatures stay. + +No command id, binding, mode or `KeyEvent` field changes. `vscode::keymap()` keeps its 39 bindings and `cursor_commands::ALL` its 26 ids, as T-107's tests pin. + +## The rules + +VS Code's public documentation doesn't describe when typing splits into undo steps. I read the "Basic editing" page, the "Key bindings" page and the default keybindings reference on code.visualstudio.com. They list `undo` (`cmd-z`), `redo` (`shift-cmd-z`), `cursorUndo` (`cmd-u`) and `editor.action.clipboardPasteAction` (`cmd-v`), and say nothing about grouping. So every rule below is a Helm proposal. Where VS Code's source supports a rule, the rule says so, and it is still a proposal: the source is an implementation detail, not documented behaviour. I read the MIT-licensed `microsoft/vscode` files `cursorCommon.ts`, `cursor/cursor.ts`, `cursor/cursorTypeOperations.ts`, `cursor/cursorDeleteOperations.ts` and part of `cursor/cursorTypeEditOperations.ts` to understand the behaviour. I copied no code from them, and the implementer must not either. + +### Edit kinds + +Under `Typing` grouping, the editor gives each editing command a kind: + +- **Typing:** `insert`, whatever its text, and `newline`. +- **Deleting backward:** `delete_backward`, and `delete_to` with `Left`, `Up`, `WordLeft`, `LineStart` or `TextStart`. VS Code's `cmd-backspace` and `alt-backspace` reach these. +- **Deleting forward:** `delete_forward`, and `delete_to` with `Right`, `Down`, `WordRight`, `LineEnd` or `TextEnd`. +- **Other:** every other edit this editor makes. That covers Vim's commands and T-109's puts if they run under `Typing` grouping, and any later command that edits through a private path. + +### When an edit joins the open step + +Under `Typing` grouping, with no explicit group open, a typing or deleting edit joins the open typing group only if all of these hold. Otherwise the editor ends that group, opens a new one and applies the edit as its first transaction. + +1. **A typing group is open.** `end_undo_group`, a successful `undo` or `redo`, `begin_undo_group`, a grouping change and an other edit each end it. +2. **There was no move since the group's last edit.** A move is a call to `set_selections`, `move_cursors`, `extend_selections`, `select_all`, `collapse_selections`, `add_cursor_above`, `add_cursor_below`, `add_next_match` or `select_all_matches` that changes the selections. A move that changes nothing, such as Left at offset 0 or `set_selections` with the same selections, doesn't count. A move and a move back still count, so Left then Right ends the step. Any other change to the selections, such as a Vim motion run under `Typing` grouping, counts when the selections differ from those just after the group's last edit. Clamping at the start of an edit isn't a move. Helm proposal. VS Code's cursor controller, in the files I read, doesn't reset its last edit type on a cursor move, so VS Code may join `ab`, Left, `c` into one step. I didn't check whether its text model adds a stop there. +3. **The kind is the same as the group's last edit's kind.** Typing after deleting, deleting after typing, and deleting forward after deleting backward each start a step. Helm proposal, which matches the source: VS Code puts a stop between edits of different types. +4. **It isn't a newline.** `newline` always starts a step, and typing after it joins that step. So `abc`, Enter, `def` undoes to `abc` first, then to the empty text. Two Enters make two steps. Helm proposal, which matches the source: VS Code's Enter pushes a stop before itself and none after. +5. **It deletes no line break.** A delete whose range, at any cursor, starts and ends on different lines as `TextBuffer::byte_to_line` counts them (so it covers a LF, a CR or a CRLF) starts a step, and later deletes of the same kind join it. So Backspace from the start of a line joins that line to the one above in a new step, and the Backspaces after it join that step. Helm proposal, which matches the source: VS Code's `deleteLeft` and `deleteRight` push a stop when a range spans lines. +6. **No pause.** The time from the group's last edit to this one is less than `TYPING_PAUSE`. A time of exactly `TYPING_PAUSE` starts a step. The pause is measured from the last edit, not the group's first, so a long run of quick keys stays one step. Helm proposal. The VS Code files I read have no timer for undo. I didn't read its text model, so I can't rule one out there. + +When an edit joins, it amends the group's transaction, with T-108's mechanics. If `amend` refuses because another transaction is now on top (an agent's edit, say), the edit applies a new transaction and the group goes on from it. That new transaction undoes as its own step, so an outside edit splits the run. VS Code's source resets its last edit type on an outside change, which also starts a new step. + +### Other rules + +- **An other edit is its own step.** It ends any open typing group, applies its own transaction, and leaves no group open after it. +- **Paste is its own step.** No VS Code paste command exists yet: clipboard commands belong to an ED-1 task. That task must make each paste one step. Calling `end_undo_group`, then `insert` with the pasted text, then `end_undo_group` does this with the methods above, and the tests show it works. A paste method of its own, of kind other, would work too. Helm proposal, which matches the source: VS Code's paste pushes a stop before and after itself. +- **An edit with nothing to do changes nothing.** Backspace at offset 0, or Delete at the end of the text, applies nothing, returns `Ok(None)`, and leaves the group, its last kind and its last time as they were. So `ab`, Delete at the end, `c` is one step. Helm proposal (open question 6). +- **Errors change nothing.** An `UnknownBuffer` error leaves the group, its kind and its time as they were, as T-108's rule for groups already says. +- **Several cursors are one step.** Every command already applies one transaction for all its cursors, so the rules above decide steps for the whole set. Cursors that merge during a run don't end the step, since the edit set those selections, not a move. This matches the source: VS Code pushes at most one stop per command for all cursors. +- **Undo and redo** put back the selections from just before the step's first edit, and from just after its last, as T-108 does for every group. + +### Explicit groups, Vim mode and keymap switches + +- **An explicit group overrides the typing rules.** `begin_undo_group` under either grouping ends an open typing group and opens an explicit one. While it is open, every edit folds into it whatever its kind, the pauses and the moves, as T-108 says. After `end_undo_group`, the next edit starts a new typing group. +- **Vim mode doesn't change.** `vim::keymap()` has `Explicit` grouping, so the dispatcher keeps Vim's editors at `Explicit`, and T-108's insert sessions stay one group each, whatever the pauses. Under `Explicit` grouping, `set_time` has no effect. +- **A keymap switch.** The dispatcher sets the editor's grouping from the new keymap before the first command it runs. A switch between VS Code and Vim changes the grouping, which ends any open group. So VS Code typing never folds into a Vim insert session, and a Vim insert session never folds into VS Code typing, even if `helm-ui` forgets T-108's rule. That rule stays: `helm-ui` still calls `end_undo_group` on every open editor right after `Dispatcher::set_keymap`. It is what ends the group when a switch keeps the grouping, such as reloading the same keymap. +- **ED-6.** The grouping follows the keymap, so the toggle applies to open editors from their next key with no restart. + +### What T-109 and T-114 left, checked on main at `3566348` + +The first draft of this file was written while T-109 was in progress, against main at `01f24e2`, and listed six assumptions about its code. I read the merged code at `7638344`, and again at `3566348` after T-114. T-114 changed bracket objects, the quote rule and comments on `EditorId` and puts. It didn't touch undo groups, `run_in`, the dispatcher or the change marks. All six hold: + +1. T-109 doesn't change what `begin_undo_group`, `end_undo_group`, `in_undo_group`, `undo` and `redo` do to a group. Its counted inserts run their repeats through `CommandRegistry::run_unrecorded` inside the open explicit group. +2. `run_in` ends a `.` record when it finds the editor's group closed: `Session::end_closed_record` before the command, and `finish_record` after it if no group is open. The 16 ids in `vim_commands::CHANGES` are all `vim.*` ids, so no command `vscode::keymap()` binds starts a record, and a typing group never holds one open. +3. Vim's edits, puts included (`apply_puts`), reach the buffer through `Editor`'s private `apply`. They call `begin_undo_group` where an insert session starts. So under `Typing` grouping they are other edits. +4. `dispatch_in` is filled in: `resolve`, then `run_in` for a `Run`. The grouping step goes before `run_in`, as the interface says. +5. `Keymap` still derives only `Clone` and `Debug`. T-109 added a private `lines` field the same way this task adds one. +6. `vscode::keymap()` is still used only by `tests/vscode_keymap.rs` and `tests/vim_keymap.rs`. T-109's edits to `vim_keymap.rs`, under Khakha's grant, touch only Vim's lists and keymap, not the switching tests. + +Two T-109 changes this file didn't foresee, now covered in "Crates and public interface": `Editor`'s `Clone` is written by hand, so the new fields must be copied there, and the order of the grouping step and `run_in`'s record check matters. `CommandArgs` gained `register`, and the `KeyEvent` struct literals that rule out a timestamp field are still in the same four test files and `benches/vim.rs`. + +### What the existing tests allow + +Checked by reading at `3566348`, and by running every `helm-editor` test with the throwaway implementation described under "Acceptance tests". None of the four files below changed since `01f24e2`, apart from Khakha's granted edit to `vim_keymap.rs`. + +- `tests/undo_groups.rs`'s `edits_outside_a_group_are_their_own_steps` pins one step per ungrouped edit on a plain `Editor`. That is why `Explicit` is the default and the typing rules need `set_undo_grouping`. +- `tests/dispatch.rs`'s `typing_at_every_cursor` and `bound_keys_edit_and_undo` undo one key at a time through a keymap the test builds with `Keymap::new`. That keymap has `Explicit` grouping, so both pass unchanged. +- `tests/vscode_keymap.rs` uses `vscode::keymap()`. `select_all_then_delete_and_undo` makes one edit before `cmd-z`. In `word_and_line_deletes`, `alt-backspace` and `cmd-backspace` join into one deleting-backward step, so the first `cmd-z` restores the text and the second finds nothing to undo. The text it asserts is the same either way. +- `tests/vim_keymap.rs`'s two switching tests type one VS Code char at a time between Vim edits. Both still give their asserted texts and the three undo steps. + +## Choices I made, and the ones I rejected + +- **Time comes through `Editor::set_time`.** I rejected a timestamp field on `KeyEvent`: four protected test files (`counts.rs`, `session.rs`, `vim_keymap.rs`, `vim_t109_keymap.rs`) and `benches/vim.rs` build `KeyEvent` with struct literals, so a new field needs a grant for each. I rejected a timer in `helm-ui` that calls `end_undo_group` after a pause: it wakes the UI thread for every pause, it would end Vim's insert sessions unless `helm-ui` tracked the group's kind, and the rule could only be tested with a window. I rejected an `Instant`, since tests can't build a chosen one, and a clock inside `helm-editor`, which would make the property tests depend on how fast they run. +- **The grouping is a setting on the editor that the keymap supplies.** I rejected always-on typing rules: they break `edits_outside_a_group_are_their_own_steps` and the two `tests/dispatch.rs` tests above. I rejected having `helm-ui` call `set_undo_grouping` on a switch: it is one more rule for `helm-ui` to remember, and the dispatcher already holds both the keymap and the editor for each key (open question 4). +- **The policy lives in `Editor`, not in the dispatcher.** A mouse click reaches the editor through `set_selections` without passing the dispatcher, and it has to end the step. Only the editor sees every move and every edit. +- **A move is a selection method that changes the selections.** I rejected only comparing the selections with those after the group's last edit: Up then Down back to the same offset would keep the step, which reads as a bug. A flag set by each of the nine methods costs nothing per move, since each already knows whether it changed anything. Vim's motions set the selections in many crate-private places, so for them the rule falls back to the comparison. They don't run under `Typing` grouping through a keymap, so a Vim round trip isn't tested. +- **No word-by-word steps.** The part of VS Code's source I couldn't read in full seems to put a stop before the first space typed after a word, so `hello world` would undo `" world"` first. I couldn't confirm it, and the brief didn't ask for it (open question 5). + +## Acceptance tests + +Three new files, committed before the implementation. 39 tests. Every test carries `#[ignore = "T-112: not implemented yet"]`. No existing test file changes. + +| File | What it proves | +| --- | --- | +| `crates/helm-editor/tests/typing_groups.rs` (25) | On `Editor` alone with `Typing` grouping. `Editor::new` is `Explicit`, and ungrouped edits stay one step each. A typed word undoes and redoes in one step, with the selections from before its first char and after its last, and every char returns the step's id. Three cursors in a CRLF text type as one step, and cursors that merge during a run of Backspaces keep it. Each of eleven moves ends the step: Left, TextEnd, Down, extending, `set_selections`, both add-cursor commands, both add-match commands, `select_all` and `collapse_selections`. A move that changes nothing keeps it, and a move and a move back, by motion or by `set_selections`, don't. Typing, Backspace, typing and Delete make four steps, and Backspace then Delete two. Backspace, `delete_to(WordLeft)` and `delete_to(LineStart)` join, so do Delete, `delete_to(WordRight)` and `delete_to(LineEnd)`, and a word delete in the other direction doesn't. Enter starts a step that typing after it joins, in LF and CRLF, and two Enters make two steps. Backspace and Delete over a LF, a CRLF and a lone CR start a step that later deletes join, and so does `delete_to(WordLeft)` across a line break. A pause of exactly `TYPING_PAUSE` starts a step, one nanosecond less doesn't, the pause counts from the last edit, a long run of quick keys stays one step, and a pause splits deletes too. With no `set_time`, and with time going backwards, nothing splits. Under `Explicit` grouping, `set_time` changes nothing, inside a group or out. Undo and redo end the step. `end_undo_group`, `insert` with two lines and `end_undo_group` make a paste its own step between two typing steps. An explicit group ends a typing group, and while it is open pauses, moves and kinds fold in. Changing the grouping ends either kind of group, and setting the same one doesn't. An edit with nothing to do keeps the step, and one before any typing opens nothing. `UnknownBuffer` from a delete or a newline changes nothing. An outside transaction splits the run. A Vim command run through the registry under `Typing` grouping is its own step and leaves no group open. A clone keeps the open step and its last edit's time. | +| `crates/helm-editor/tests/vscode_undo.rs` (10) | Through `Dispatcher::dispatch_in` with one `Session`, as `helm-ui` will run it. `vscode::keymap()` has `Typing` grouping and keeps its 39 bindings, and `vim::keymap()`, `Keymap::new` and `with_undo_grouping` give what they say. `dispatch` sets the editor's grouping on a run, and an unbound key and a pending chord leave it alone, and `dispatch_in` with Vim's keymap sets `Explicit`. A session of `hello world`, Enter, `x`, Left, `y` and Backspace undoes step by step with `cmd-z`, with the documented texts and cursors, and `shift-cmd-z` redoes it. Backspace, `alt-backspace` and `cmd-backspace` undo in one `cmd-z`. Typing after `cmd-z` starts a new step. `cmd-d`, `shift-cmd-l` and typing `total` at three cursors undoes in one `cmd-z` and gives back the three selections. `set_time` between keys splits a run at a pause. Switching to Vim without `end_undo_group` keeps VS Code's typing and Vim's `x` apart. Switching to VS Code in the middle of a Vim insert, also without it, keeps the two apart and finishes the insert's `.` record before VS Code's first key, so the record holds `i`, `x` and `y` and not `z`. T-108's three-step switching session, with two VS Code chars in place of one, still gives three steps. | +| `crates/helm-editor/tests/typing_group_properties.rs` (4) | proptest, 256 cases per property, over random texts of words, blanks, punctuation, `_`, é, 中, 😀, LF and CRLF, at up to three cursors, with up to 40 ops: typed chars, Enter, Backspace, Delete, word and line deletes, ten motions, waits of 0, 1 ms, 500 ms, just under `TYPING_PAUSE`, `TYPING_PAUSE` and three times it, times that go backwards, and `end_undo_group`. (1) With lone CRs and `begin_undo_group` added: every op leaves the same return value, text and selections under `Typing` as under `Explicit` grouping, so grouping changes only undo. (2) An oracle written from the rules marks the text before each edit that starts a step. Undoing returns each mark, newest first, then finds nothing, and redoing walks forward to the final text, then finds nothing. (3) Under `Explicit` grouping, with lone CRs, each edit that applies a transaction is one step whatever the time. (4) As (2), with `begin_undo_group` and `end_undo_group` mixed in, which the oracle treats as explicit groups. | + +The oracle runs the same ops on a second editor under `Explicit` grouping to learn three facts: whether each edit applied a transaction, whether each motion changed the selections, and whether a delete lowered the line count, which is when it took a line break. Properties (2) and (4) leave out lone CRs, since deleting the char between a lone CR and a LF would join them into a CRLF and lower the line count without deleting a break. `typing_groups.rs` covers lone CRs by hand. + +Against the stubs, `cargo test -p helm-editor --no-fail-fast -- --ignored` fails all 39. No test only reads plain data. + +I checked the tests against a throwaway implementation before committing them. All 39 pass on it, and all 443 tests in `helm-editor` pass with it, so no T-101 to T-114 test changes behaviour. The four properties also pass at 20,000 cases each. That implementation isn't in this PR. I also ran eleven wrong versions of it against the three files. Each of these failed at least one test, and most failed several: no move rule, moves found by comparison only (so a move and a move back keep the step), no pause rule, the pause counted from the step's first edit, Enter joining the typing before it, no line-break rule, kinds ignored, a grouping change that keeps an open group, `dispatch_in` not setting the grouping, and an other edit joining the typing step. The eleventh, an other edit that leaves a group open after itself, passed every test. It changes nothing, since an other edit already ends the typing group before it applies. + +**The rule for the implementer: the only allowed change to these three files is deleting the `#[ignore = "T-112: not implemented yet"]` lines.** Nothing else in them changes. That means no edited assertion, no new `#[ignore]` and no changed case count. Khakha checks the diff of these files before adding the `approved-protected` label. If a test looks wrong, say so in the PR description instead of changing it. + +## Performance budget + +NF-1 gives a keypress 5 ms from input to pixel. Deciding whether an edit joins the step is on that path, so it must stay small next to the edit itself. + +Cost rules: + +- **Under `Explicit` grouping** an edit costs what it costs on main, plus one check of the grouping. +- **Under `Typing` grouping** deciding costs a fixed amount per edit: comparing a kind, a time and the move flag. The line-break rule adds two `byte_to_line` lookups per deleted range, or nothing where the delete code already knows whether a range crosses a line. It never reads the deleted text. Comparing the selections with those after the step's last edit, for changes other than the nine moves, costs one pass over the selections. It may use the step's undo record instead of a copy. Joining costs what T-110's `amend` costs. +- **A move** sets a flag. `set_selections` compares the old and new selections, which costs no more than building the new ones. +- **No text is copied** and nothing is read from the buffer to decide a step, apart from the line-break check above. +- **No clock, timer or thread.** The editor never calls `Instant::now` or `SystemTime::now`. +- **The dispatcher** adds one comparison of the grouping per run. + +Add a new file, `crates/helm-bench/benches/typing.rs`, with a `[[bench]] name = "typing"`, `harness = false` entry in `crates/helm-bench/Cargo.toml`. It holds three criterion benchmarks in a group named `typing`, on the same 10 MiB text `benches/editor.rs` builds. Copy `LINES`, `floor_boundary` and `build_text` from `benches/cursor.rs` unchanged. + +| Benchmark id | What one iteration does | +| --- | --- | +| `typing/type_100_chars_undo_10mb` | With `Typing` grouping and one cursor at the start of the middle `fn main() {` line: `set_time` 10 ms later, then `insert` of one char, 100 times, cycling through the chars of `"helm 😀中é"`, then one `undo`. | +| `typing/type_10_chars_undo_1000_cursors_10mb` | The same with 10 chars at 1,000 cursors placed as `benches/cursor.rs` places them. | +| `typing/vscode_session_undo_10mb` | `Dispatcher::dispatch` with `vscode::keymap()` of `hello`, two Backspaces, `lo world`, Enter, `x`, Left and `y` at one cursor, with `set_time` 10 ms later before each key, then `cmd-z` five times, once per step. | + +Each iteration ends with the text and selections it started with, and the next edit drops the redo entries. Build the text, the set, the editor, the dispatcher and the events once, outside the timed code, and pass each result through `black_box`. + +Budget: the default 5% from `budgets.toml`, with no per-benchmark override and no target. The base commit has no `typing` benchmarks, so `bench-compare` reports them as head-only in this task's PR and gates them from the next PR on. This task also changes `Editor`'s edit path and `Dispatcher::dispatch`, so the `editor/`, `cursor/`, `amend/`, `vim/`, `vim_objects/` and `keymap/` benchmarks must not get more than 5% slower. + +As in T-101 to T-109, the implementation PR adds the benchmark file. The spec PR doesn't, since the benchmarks would call `todo!()` stubs. + +## Out of scope + +- Word-by-word steps for typed spaces: open question 5. +- `cursorUndo` (`cmd-u`) and undoing selection changes on their own, as T-105 left them: a later task. +- The paste, cut and copy commands and the clipboard (ED-1): a later task. It must follow the paste rule above. +- Auto-closing brackets, electric characters and auto-indent, which VS Code groups by their own rules: later, with SY-3. +- `helm-ui` calling `set_time` before each key, and any extra boundary `helm-ui` wants, such as on save or focus loss, through `end_undo_group`: `helm-ui`. +- A setting for `TYPING_PAUSE` or for turning the pause off (ST-1): later. +- Any change to Vim's grouping. +- Streaming an agent's edits into one transaction (AG-4): Phase 7. +- Removing the transaction clone in `Editor::apply` (T-111's finding 8): Stream K. + +## Open questions for Khakha + +Questions 1 to 4 block the implementation. Each rule is a Helm proposal that VS Code's documentation doesn't settle, and the tests pin it, so a different answer changes the tests before anyone implements them. Questions 5 to 7 don't block: the spec states a default for each, and the implementation follows it unless Khakha says otherwise. + +1. **Keep the pause rule, and at what length? (blocking)** VS Code's docs describe no pause, and its cursor code has no timer for undo. I propose one second as a Helm rule, long enough that ordinary typing never splits. A different length changes only `TYPING_PAUSE`, since the tests name the constant. Dropping the rule removes `set_time`, the pause tests in both test files, and the waits in the properties. +2. **Should every move end the step? (blocking)** VS Code's cursor controller doesn't reset on a move in the files I read, so VS Code may join `ab`, Left, `c`. I propose that every move ends the step, since the brief lists it and it gives the same result for a mouse click as for an arrow key. +3. **Enter starts a step, and typing after it joins. (blocking)** This matches VS Code's source. The other choices are Enter as its own step, or Enter joining the typing before it. +4. **The keymap carries the grouping, and the dispatcher applies it. (blocking)** The other choice is `helm-ui` calling `set_undo_grouping` after each switch. That keeps `Keymap` and `Dispatcher` as they are, but adds a second rule for `helm-ui` beside T-108's, and `vscode_undo.rs` would change. +5. **Word-by-word steps. (default: a later task)** Include VS Code's apparent space rule, where `hello world` undoes `" world"` first, in this task, in a later one, or not at all? I couldn't confirm it from the docs or from the parts of the source I read in full. +6. **An edit with nothing to do keeps the step. (default: as specified)** VS Code may record the type of a delete that deleted nothing. I couldn't tell from the source. I propose keeping the step, which follows Helm's rule that a command with nothing to do changes nothing. A different answer changes one test. +7. **`TYPING_PAUSE` as a public constant. (default: a constant)** Tests need to name it. If ST-1 will make it a setting, it could be a field on `Typing` grouping instead. That means `UndoGrouping::Typing { pause }` and a different `Keymap` API. From 1a54b47b559324122a635cf80f7c1c2db5200dbf Mon Sep 17 00:00:00 2001 From: shubhook Date: Sat, 28 Nov 2026 21:07:56 +0530 Subject: [PATCH 2/3] editor: add T-112 stubs and acceptance tests UndoGrouping, Editor::set_undo_grouping, undo_grouping, set_time and TYPING_PAUSE, and Keymap::with_undo_grouping and undo_grouping, with todo!() bodies and the rules in Editor's type docs. Three new test files, 39 tests, each ignored until the implementation lands. Refs: T-112, ED-2, ED-4 --- crates/helm-editor/src/dispatch.rs | 12 + crates/helm-editor/src/editor.rs | 135 +++- crates/helm-editor/src/keymap.rs | 20 +- crates/helm-editor/src/lib.rs | 8 +- crates/helm-editor/src/vscode.rs | 5 + .../tests/typing_group_properties.rs | 355 ++++++++++ crates/helm-editor/tests/typing_groups.rs | 613 ++++++++++++++++++ crates/helm-editor/tests/vscode_undo.rs | 327 ++++++++++ 8 files changed, 1468 insertions(+), 7 deletions(-) create mode 100644 crates/helm-editor/tests/typing_group_properties.rs create mode 100644 crates/helm-editor/tests/typing_groups.rs create mode 100644 crates/helm-editor/tests/vscode_undo.rs diff --git a/crates/helm-editor/src/dispatch.rs b/crates/helm-editor/src/dispatch.rs index a2f695f..1429eb0 100644 --- a/crates/helm-editor/src/dispatch.rs +++ b/crates/helm-editor/src/dispatch.rs @@ -475,6 +475,13 @@ impl Dispatcher { /// The command runs with a fresh [`Session`], so registers, `.` and /// the requests a command makes don't outlive the call (T-109). /// `helm-ui` uses [`dispatch_in`](Self::dispatch_in). + /// + /// Before running the command, it gives the editor the active keymap's + /// [`Keymap::undo_grouping`] with + /// [`Editor::set_undo_grouping`](crate::Editor::set_undo_grouping) + /// (T-112). So a switch between keymaps with different groupings ends + /// any open group at the first command the new keymap runs. A + /// resolution that runs nothing leaves the grouping alone. pub fn dispatch( &self, state: &mut KeyState, @@ -500,6 +507,11 @@ impl Dispatcher { /// This is the dispatch `helm-ui` uses. [`dispatch`](Self::dispatch) is /// this with a fresh [`Session`] that is dropped afterwards, along with /// the requests. + /// + /// It gives the editor the keymap's undo grouping before + /// [`CommandRegistry::run_in`] starts, as `dispatch` does (T-112), so + /// `run_in` sees a group the switch ended as closed and ends Vim's `.` + /// record with it. pub fn dispatch_in( &self, state: &mut KeyState, diff --git a/crates/helm-editor/src/editor.rs b/crates/helm-editor/src/editor.rs index 74661be..be999ac 100644 --- a/crates/helm-editor/src/editor.rs +++ b/crates/helm-editor/src/editor.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::ops::Range; use std::sync::{Arc, Weak}; +use std::time::Duration; use helm_text::{ Buffer, BufferId, BufferSet, Edit, FileFormat, TextBuffer, Transaction, TransactionId, @@ -133,8 +134,73 @@ pub(crate) use vim::{Entry, Operator, Target}; /// `helm-ui` must call `end_undo_group` on every open editor right after /// [`Dispatcher::set_keymap`](crate::Dispatcher::set_keymap), before any /// key reaches the new keymap. Otherwise typing in the new keymap folds -/// into the group the old one opened. Grouping VS Code's typing by pauses -/// and cursor moves is a later task. +/// into the group the old one opened. Under [`UndoGrouping::Typing`] the +/// dispatcher also ends the group itself when a switch changes the +/// grouping (T-112). +/// +/// # Typing groups (T-112) +/// +/// Under [`UndoGrouping::Typing`], VS Code's policy, the editor opens and +/// closes groups itself, so a run of typing undoes in one step. The +/// grouping is [`UndoGrouping::Explicit`] until +/// [`set_undo_grouping`](Self::set_undo_grouping) changes it, and then +/// nothing below applies. +/// +/// Each editing command has a kind: +/// +/// - typing: [`insert`](Self::insert), whatever its text, and +/// [`newline`](Self::newline); +/// - deleting backward: [`delete_backward`](Self::delete_backward), and +/// [`delete_to`](Self::delete_to) with [`Motion::Left`], [`Motion::Up`], +/// [`Motion::WordLeft`], [`Motion::LineStart`] or [`Motion::TextStart`]; +/// - deleting forward: [`delete_forward`](Self::delete_forward), and +/// `delete_to` with [`Motion::Right`], [`Motion::Down`], +/// [`Motion::WordRight`], [`Motion::LineEnd`] or [`Motion::TextEnd`]; +/// - other: every other edit this editor makes, such as Vim's commands. +/// +/// With no explicit group open, a typing or deleting edit that applies a +/// transaction joins the open typing group, amending its transaction as +/// above, only if all of these hold. Otherwise the open typing group ends, +/// a new one opens, and the edit is its first. +/// +/// 1. A typing group is open. [`end_undo_group`](Self::end_undo_group), +/// a successful `undo` or `redo`, +/// [`begin_undo_group`](Self::begin_undo_group), a grouping change and +/// an other edit each end it. +/// 2. There was no move since the group's last edit. A move is a call to +/// [`set_selections`](Self::set_selections), +/// [`move_cursors`](Self::move_cursors), +/// [`extend_selections`](Self::extend_selections), +/// [`select_all`](Self::select_all), +/// [`collapse_selections`](Self::collapse_selections), +/// [`add_cursor_above`](Self::add_cursor_above), +/// [`add_cursor_below`](Self::add_cursor_below), +/// [`add_next_match`](Self::add_next_match) or +/// [`select_all_matches`](Self::select_all_matches) that changes the +/// selections, so a move and a move back are still a move. Any other +/// change to the selections, such as a Vim motion, is a move when the +/// selections differ from those just after the group's last edit. +/// Clamping at the start of an edit isn't a move. +/// 3. The edit's kind is the group's last edit's kind. +/// 4. The edit isn't a [`newline`](Self::newline). A newline always starts +/// a group, and typing after it joins that group. +/// 5. The edit deletes no line break: no range it deletes, at any cursor, +/// starts and ends on different lines, as +/// [`TextBuffer::byte_to_line`](helm_text::TextBuffer::byte_to_line) +/// counts them, so a LF, a CR or a CRLF. A delete that does starts a +/// group, and later deletes of the same kind join it. +/// 6. The time [`set_time`](Self::set_time) last gave is less than +/// [`TYPING_PAUSE`](Self::TYPING_PAUSE) after the time of the group's +/// last edit. A time earlier than that one is no pause. +/// +/// An other edit ends any open typing group, applies its own transaction +/// and leaves no group open. A command with nothing to do, or one that +/// errors, changes nothing: not the group, its last kind or its last time. +/// An explicit group wins: while one is open, every edit folds into it +/// whatever its kind, the moves or the time. +/// +/// A paste is one step: call `end_undo_group`, then `insert` with the +/// pasted text, then `end_undo_group`. #[derive(Debug)] pub struct Editor { /// This editor's own identity (T-109), so a session can tell two views @@ -199,6 +265,10 @@ impl Clone for Editor { /// typing keeps the open undo group but not the record. Its Escape /// doesn't repeat a counted insert, and `.` still repeats the last /// change the session finished. + /// + /// The copy also keeps the grouping, the time, and an open typing + /// group with its last kind, its last time and whether a move followed + /// its last edit (T-112). fn clone(&self) -> Self { Self { id: EditorId::next(), @@ -213,6 +283,26 @@ impl Clone for Editor { } } +/// Who opens and closes an [`Editor`]'s undo groups (T-112). The type +/// docs of [`Editor`] hold the rules. +/// +/// A [`Keymap`](crate::Keymap) carries one, and +/// [`Dispatcher::dispatch`](crate::Dispatcher::dispatch) gives it to the +/// editor before each command it runs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum UndoGrouping { + /// Groups open and close only through + /// [`Editor::begin_undo_group`] and [`Editor::end_undo_group`], and + /// every edit outside one is its own undo step, as in T-108. Vim's + /// keymap uses this. + #[default] + Explicit, + /// VS Code's policy: the editor opens and closes groups itself around + /// runs of typing and deleting, as the "Typing groups" section of + /// [`Editor`] says. VS Code's keymap uses this. + Typing, +} + /// The selections just before and just after one transaction. #[derive(Clone, Debug)] struct Record { @@ -578,16 +668,51 @@ impl Editor { self.group = Some(None); } - /// Closes the open undo group (T-108). Returns whether one was open. - /// The next edit is a new undo step. + /// Closes the open undo group (T-108), explicit or typing (T-112). + /// Returns whether one was open. The next edit is a new undo step. pub fn end_undo_group(&mut self) -> bool { self.group.take().is_some() } - /// Whether an undo group is open (T-108). + /// Whether an undo group is open (T-108): an explicit one, or a typing + /// one under [`UndoGrouping::Typing`] (T-112). pub fn in_undo_group(&self) -> bool { self.group.is_some() } + + /// How long a pause between two edits must be to start a new typing + /// group (T-112): one second. See the type docs' "Typing groups". + pub const TYPING_PAUSE: Duration = Duration::from_secs(1); + + /// Sets who opens and closes this editor's undo groups (T-112). A + /// different value from the current one ends any open group, explicit + /// or typing. The same value changes nothing. A new editor has + /// [`UndoGrouping::Explicit`]. + #[expect( + unused_variables, + reason = "T-112 interface stub; the implementation deletes this" + )] + pub fn set_undo_grouping(&mut self, grouping: UndoGrouping) { + todo!() + } + + /// Who opens and closes this editor's undo groups (T-112). + pub fn undo_grouping(&self) -> UndoGrouping { + todo!() + } + + /// The time of the edits that follow (T-112), measured from any fixed + /// origin. `helm-ui` passes each key event's time before dispatching + /// it. The editor never reads a clock: it compares this with the time + /// of a typing group's last edit, under [`UndoGrouping::Typing`] only. + /// Until the first call, every edit happens at time zero. + #[expect( + unused_variables, + reason = "T-112 interface stub; the implementation deletes this" + )] + pub fn set_time(&mut self, now: Duration) { + todo!() + } } impl Editor { diff --git a/crates/helm-editor/src/keymap.rs b/crates/helm-editor/src/keymap.rs index 6518a21..b425b63 100644 --- a/crates/helm-editor/src/keymap.rs +++ b/crates/helm-editor/src/keymap.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::fmt; use std::sync::Arc; -use crate::{CommandId, KeyParseError, KeySequence, Keystroke}; +use crate::{CommandId, KeyParseError, KeySequence, Keystroke, UndoGrouping}; /// A mode's id, such as `"normal"` or `"insert"`. Unique within a keymap. /// @@ -304,6 +304,24 @@ impl Keymap { Ok(()) } + /// This keymap with `grouping` as its undo grouping (T-112): the + /// [`UndoGrouping`] [`Dispatcher::dispatch`](crate::Dispatcher::dispatch) + /// gives each editor before running a command. [`Keymap::new`] gives + /// [`UndoGrouping::Explicit`]. + #[expect( + unused_variables, + unused_mut, + reason = "T-112 interface stub; the implementation deletes this" + )] + pub fn with_undo_grouping(mut self, grouping: UndoGrouping) -> Self { + todo!() + } + + /// This keymap's undo grouping (T-112). + pub fn undo_grouping(&self) -> UndoGrouping { + todo!() + } + /// Whether any mode's typing is [`Typing::Count`]. pub(crate) fn counts(&self) -> bool { self.counts diff --git a/crates/helm-editor/src/lib.rs b/crates/helm-editor/src/lib.rs index 6441228..b993029 100644 --- a/crates/helm-editor/src/lib.rs +++ b/crates/helm-editor/src/lib.rs @@ -84,6 +84,12 @@ //! and [`CommandRegistry::with_vim_commands`] holds every command both //! keymaps bind. //! +//! VS Code's keymap groups typing differently (T-112): its +//! [`UndoGrouping::Typing`] lets the editor open and close groups itself, +//! at pauses, moves, newlines and switches between typing and deleting. +//! Each [`Keymap`] carries its grouping, and the dispatcher hands it to the +//! editor. [`Editor`]'s "Typing groups" section holds the rules. +//! //! # Registers, `.` and requests (T-109) //! //! A [`Session`] holds what every editor shares: Vim's registers and the @@ -113,7 +119,7 @@ pub use command::{ Invocation, RegisterError, }; pub use dispatch::{Dispatcher, KeyState, Resolution}; -pub use editor::Editor; +pub use editor::{Editor, UndoGrouping}; pub use error::EditorError; pub use key::{Key, KeyEvent, KeyParseError, KeySequence, Keystroke, Modifiers}; pub use keymap::{Action, Binding, Keymap, KeymapError, Mode, ModeId, Typing}; diff --git a/crates/helm-editor/src/vscode.rs b/crates/helm-editor/src/vscode.rs index 4147574..cb0efff 100644 --- a/crates/helm-editor/src/vscode.rs +++ b/crates/helm-editor/src/vscode.rs @@ -43,6 +43,11 @@ pub const MODE: &str = "default"; /// That is 39 bindings. None of them is a chord, and none uses a char /// that Shift makes, so the notation's folding of Shift into chars changes /// nothing here. +/// +/// The keymap's undo grouping is +/// [`UndoGrouping::Typing`](crate::UndoGrouping::Typing) (T-112), so typing +/// undoes in runs, as the "Typing groups" section of +/// [`Editor`](crate::Editor) says. pub fn keymap() -> Keymap { const BINDINGS: [(&str, &str); 39] = [ ("enter", editor::NEWLINE), diff --git a/crates/helm-editor/tests/typing_group_properties.rs b/crates/helm-editor/tests/typing_group_properties.rs new file mode 100644 index 0000000..64ee15d --- /dev/null +++ b/crates/helm-editor/tests/typing_group_properties.rs @@ -0,0 +1,355 @@ +//! T-112 acceptance tests: properties of typing groups. Grouping changes +//! only how edits undo, never the edits themselves, and the undo steps +//! start exactly where the "Typing groups" rules on `Editor` say. + +use std::time::Duration; + +use helm_editor::{Editor, Motion, Selection, Selections, UndoGrouping}; +use helm_text::{Buffer, BufferSet, FileFormat, LineEndings, TextBuffer}; +use proptest::prelude::*; + +const PAUSE: Duration = Editor::TYPING_PAUSE; + +/// One call on the editor. +#[derive(Clone, Debug)] +enum Op { + Type(char), + Enter, + Backspace, + Delete, + DeleteTo(Motion), + Move(Motion), + /// Moves time on by this much. + Wait(Duration), + /// Sets the time, which may go backwards. + SetTime(Duration), + Begin, + End, +} + +/// What an edit is, for the oracle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Typing, + Backward, + Forward, +} + +/// Text pieces. `lone_cr` adds a CR with no LF after it. +fn text_strategy(lone_cr: bool) -> impl Strategy { + let mut pieces = vec![ + "ab", "x", " ", " ", ".", "_", "é", "中", "😀", "\n", "\r\n", + ]; + if lone_cr { + pieces.push("\r"); + } + prop::collection::vec(prop::sample::select(pieces), 0..12).prop_map(|p| p.concat()) +} + +fn wait_strategy() -> impl Strategy { + prop_oneof![ + Just(Duration::ZERO), + Just(Duration::from_millis(1)), + Just(Duration::from_millis(500)), + Just(PAUSE - Duration::from_nanos(1)), + Just(PAUSE), + Just(3 * PAUSE), + ] +} + +fn op_strategy(groups: bool) -> BoxedStrategy { + let motion = prop::sample::select(vec![ + Motion::Left, + Motion::Right, + Motion::Up, + Motion::Down, + Motion::WordLeft, + Motion::WordRight, + Motion::LineStart, + Motion::LineEnd, + Motion::TextStart, + Motion::TextEnd, + ]); + let delete = prop::sample::select(vec![ + Motion::WordLeft, + Motion::WordRight, + Motion::LineStart, + Motion::LineEnd, + ]); + let typed = prop::sample::select(vec!['a', 'b', ' ', '.', 'é', '中', '😀']); + let ops = prop_oneof![ + 8 => typed.prop_map(Op::Type), + 2 => Just(Op::Enter), + 4 => Just(Op::Backspace), + 3 => Just(Op::Delete), + 2 => delete.prop_map(Op::DeleteTo), + 3 => motion.prop_map(Op::Move), + 3 => wait_strategy().prop_map(Op::Wait), + 1 => (0u64..5_000).prop_map(|ms| Op::SetTime(Duration::from_millis(ms))), + 1 => Just(Op::End), + ]; + if groups { + prop_oneof![27 => ops, 1 => Just(Op::Begin)].boxed() + } else { + ops.boxed() + } +} + +/// Char boundaries of `text` that aren't inside a CRLF. +fn positions(text: &str) -> Vec { + let bytes = text.as_bytes(); + (0..=text.len()) + .filter(|&i| text.is_char_boundary(i)) + .filter(|&i| !(i > 0 && i < bytes.len() && bytes[i - 1] == b'\r' && bytes[i] == b'\n')) + .collect() +} + +/// A text, up to three cursor positions in it (as indexes into its +/// `positions`), and a list of ops. +fn case( + lone_cr: bool, + groups: bool, +) -> impl Strategy, Vec)> { + ( + text_strategy(lone_cr), + prop::collection::vec(any::(), 1..=3), + prop::collection::vec(op_strategy(groups), 0..40), + ) +} + +fn editor( + text: &str, + cursors: &[prop::sample::Index], + grouping: UndoGrouping, +) -> (BufferSet, Editor) { + let mut set = BufferSet::new(); + let id = set.add(Buffer::from(text)); + let format = FileFormat { + bom: false, + line_endings: LineEndings::count(text), + }; + let mut editor = Editor::new(id, format); + let at = positions(text); + let selections = cursors + .iter() + .map(|index| Selection::cursor(at[index.index(at.len())])) + .collect(); + editor.set_selections(Selections::new(selections, 0).expect("non-empty")); + if grouping != UndoGrouping::Explicit { + editor.set_undo_grouping(grouping); + } + (set, editor) +} + +fn text(set: &BufferSet, editor: &Editor) -> String { + set.get(editor.buffer()).expect("in the set").to_string() +} + +fn lines(set: &BufferSet, editor: &Editor) -> usize { + set.get(editor.buffer()).expect("in the set").len_lines() +} + +/// Runs `op` on `editor`. Returns whether an edit applied a transaction +/// and, for a move, whether it changed the selections. +fn run(op: &Op, set: &mut BufferSet, editor: &mut Editor, now: &mut Duration) -> bool { + match op { + Op::Type(c) => editor.insert(set, &c.to_string()).unwrap().is_some(), + Op::Enter => editor.newline(set).unwrap().is_some(), + Op::Backspace => editor.delete_backward(set).unwrap().is_some(), + Op::Delete => editor.delete_forward(set).unwrap().is_some(), + Op::DeleteTo(motion) => editor.delete_to(set, *motion).unwrap().is_some(), + Op::Move(motion) => editor.move_cursors(set, *motion).unwrap(), + Op::Wait(d) => { + *now += *d; + editor.set_time(*now); + false + } + Op::SetTime(t) => { + *now = *t; + editor.set_time(*now); + false + } + Op::Begin => { + editor.begin_undo_group(); + false + } + Op::End => { + editor.end_undo_group(); + false + } + } +} + +fn kind(op: &Op) -> Option { + match op { + Op::Type(_) | Op::Enter => Some(Kind::Typing), + Op::Backspace => Some(Kind::Backward), + Op::Delete => Some(Kind::Forward), + Op::DeleteTo(Motion::WordLeft | Motion::LineStart) => Some(Kind::Backward), + Op::DeleteTo(_) => Some(Kind::Forward), + _ => None, + } +} + +/// The oracle: runs `ops` on an editor under `Explicit` grouping, with no +/// explicit groups of its own, and returns the text just before each edit +/// that starts an undo step under `Typing` grouping, oldest first, and the +/// final text. The twin shows whether each edit applied a transaction, +/// whether each move changed the selections, and, through its line count, +/// whether a delete took a line break. The texts have no lone CR, so a +/// delete can never join a CR and a LF into a new line break. +fn oracle(text0: &str, cursors: &[prop::sample::Index], ops: &[Op]) -> (Vec, String) { + let (mut set, mut twin) = editor(text0, cursors, UndoGrouping::Explicit); + let mut now = Duration::ZERO; + let mut marks = Vec::new(); + // The open typing group: its last kind and the time of its last edit. + let mut open: Option<(Kind, Duration)> = None; + let mut moved = false; + // An explicit group, and whether it has an edit yet. + let mut explicit: Option = None; + for op in ops { + let before = text(&set, &twin); + let lines_before = lines(&set, &twin); + match op { + Op::Begin => { + open = None; + explicit = Some(false); + continue; + } + Op::End => { + open = None; + explicit = None; + continue; + } + _ => {} + } + let changed = run(op, &mut set, &mut twin, &mut now); + let Some(kind) = kind(op) else { + if matches!(op, Op::Move(_)) && changed { + moved = true; + } + continue; + }; + if !changed { + continue; + } + if let Some(has_edit) = explicit.as_mut() { + if !*has_edit { + marks.push(before); + *has_edit = true; + } + continue; + } + let took_break = kind != Kind::Typing && lines(&set, &twin) < lines_before; + let joins = match open { + Some((last, at)) => { + last == kind + && !moved + && !matches!(op, Op::Enter) + && !took_break + && now.checked_sub(at).is_none_or(|gap| gap < PAUSE) + } + None => false, + }; + if !joins { + marks.push(before); + } + open = Some((kind, now)); + moved = false; + } + (marks, text(&set, &twin)) +} + +/// Checks that undoing `editor` goes back through `marks`, newest first, +/// then finds nothing, and that redoing comes forward to `last`. +fn check_steps( + set: &mut BufferSet, + editor: &mut Editor, + marks: &[String], + last: &str, +) -> Result<(), TestCaseError> { + prop_assert_eq!(text(set, editor), last); + for mark in marks.iter().rev() { + prop_assert!(editor.undo(set).unwrap().is_some()); + prop_assert_eq!(&text(set, editor), mark); + } + prop_assert_eq!(editor.undo(set).unwrap(), None); + // Redoing step `i` brings back the text from before step `i + 1`, or + // the final text after the last step. + let after: Vec<&str> = (1..=marks.len()) + .map(|i| marks.get(i).map_or(last, String::as_str)) + .collect(); + for expected in after { + prop_assert!(editor.redo(set).unwrap().is_some()); + prop_assert_eq!(text(set, editor), expected); + } + prop_assert_eq!(editor.redo(set).unwrap(), None); + Ok(()) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// Typing grouping changes only undo: the texts and selections after + /// every op are the same as under explicit grouping. + #[test] + #[ignore = "T-112: not implemented yet"] + fn grouping_never_changes_the_edits((text0, cursors, ops) in case(true, true)) { + let (mut set_a, mut typing) = editor(&text0, &cursors, UndoGrouping::Typing); + let (mut set_b, mut explicit) = editor(&text0, &cursors, UndoGrouping::Explicit); + let (mut now_a, mut now_b) = (Duration::ZERO, Duration::ZERO); + for op in &ops { + let a = run(op, &mut set_a, &mut typing, &mut now_a); + let b = run(op, &mut set_b, &mut explicit, &mut now_b); + prop_assert_eq!(a, b, "{:?}", op); + prop_assert_eq!(text(&set_a, &typing), text(&set_b, &explicit), "{:?}", op); + prop_assert_eq!(typing.selections(), explicit.selections(), "{:?}", op); + } + } + + /// Undo steps start where the rules say, and undo and redo walk them. + #[test] + #[ignore = "T-112: not implemented yet"] + fn steps_start_where_the_rules_say((text0, cursors, ops) in case(false, false)) { + let (marks, last) = oracle(&text0, &cursors, &ops); + let (mut set, mut e) = editor(&text0, &cursors, UndoGrouping::Typing); + let mut now = Duration::ZERO; + for op in &ops { + run(op, &mut set, &mut e, &mut now); + } + check_steps(&mut set, &mut e, &marks, &last)?; + } + + /// Under explicit grouping with no groups, every edit that applies a + /// transaction is one step, whatever the time says. + #[test] + #[ignore = "T-112: not implemented yet"] + fn explicit_grouping_makes_each_edit_a_step((text0, cursors, ops) in case(true, false)) { + let (mut set, mut e) = editor(&text0, &cursors, UndoGrouping::Explicit); + let mut now = Duration::ZERO; + let mut marks = Vec::new(); + for op in ops.iter().filter(|op| !matches!(op, Op::End)) { + let before = text(&set, &e); + if run(op, &mut set, &mut e, &mut now) && kind(op).is_some() { + marks.push(before); + } + } + let last = text(&set, &e); + check_steps(&mut set, &mut e, &marks, &last)?; + } + + /// The same as `steps_start_where_the_rules_say`, with explicit groups + /// opened and closed in between: each is one step, and typing groups + /// start again after it. + #[test] + #[ignore = "T-112: not implemented yet"] + fn explicit_groups_inside_typing_grouping((text0, cursors, ops) in case(false, true)) { + let (marks, last) = oracle(&text0, &cursors, &ops); + let (mut set, mut e) = editor(&text0, &cursors, UndoGrouping::Typing); + let mut now = Duration::ZERO; + for op in &ops { + run(op, &mut set, &mut e, &mut now); + } + check_steps(&mut set, &mut e, &marks, &last)?; + } +} diff --git a/crates/helm-editor/tests/typing_groups.rs b/crates/helm-editor/tests/typing_groups.rs new file mode 100644 index 0000000..1075526 --- /dev/null +++ b/crates/helm-editor/tests/typing_groups.rs @@ -0,0 +1,613 @@ +//! T-112 acceptance tests: typing groups on `Editor` alone. Under +//! `UndoGrouping::Typing`, the editor opens and closes undo groups itself, +//! so a run of typing undoes in one step. `Editor`'s "Typing groups" docs +//! hold the rules. + +use std::time::Duration; + +use helm_editor::{ + CommandRegistry, Editor, EditorError, Invocation, Motion, Selection, Selections, UndoGrouping, + vim_commands, +}; +use helm_text::{Buffer, BufferSet, Edit, FileFormat, LineEndings, Transaction}; + +const PAUSE: Duration = Editor::TYPING_PAUSE; + +/// An editor on `text` with `selections`, under `grouping`. +fn editor_with( + text: &str, + selections: &[Selection], + grouping: UndoGrouping, +) -> (BufferSet, Editor) { + let mut set = BufferSet::new(); + let id = set.add(Buffer::from(text)); + let format = FileFormat { + bom: false, + line_endings: LineEndings::count(text), + }; + let mut editor = Editor::new(id, format); + editor.set_selections(Selections::new(selections.to_vec(), 0).expect("non-empty")); + if grouping != UndoGrouping::Explicit { + editor.set_undo_grouping(grouping); + } + (set, editor) +} + +/// An editor under `UndoGrouping::Typing`. +fn typing(text: &str, selections: &[Selection]) -> (BufferSet, Editor) { + editor_with(text, selections, UndoGrouping::Typing) +} + +fn text(set: &BufferSet, editor: &Editor) -> String { + set.get(editor.buffer()).expect("in the set").to_string() +} + +fn cursors(editor: &Editor) -> Vec { + editor + .selections() + .as_slice() + .iter() + .map(|s| { + assert!(s.is_empty(), "{s:?}"); + s.head + }) + .collect() +} + +/// Types each char of `chars` as its own `insert`. +fn type_chars(set: &mut BufferSet, editor: &mut Editor, chars: &str) { + for c in chars.chars() { + editor + .insert(set, &c.to_string()) + .expect("the buffer is in the set") + .expect("typing applies a transaction"); + } +} + +/// Undoes until there is nothing left to undo, and returns the text after +/// each undo: one entry per undo step, newest first. +fn steps(set: &mut BufferSet, editor: &mut Editor) -> Vec { + let mut texts = Vec::new(); + while editor.undo(set).expect("not blocked").is_some() { + texts.push(text(set, editor)); + assert!(texts.len() < 1000, "undo never ran out"); + } + texts +} + +fn at(millis: u64) -> Duration { + Duration::from_millis(millis) +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn the_default_grouping_is_explicit_and_unchanged() { + assert_eq!(UndoGrouping::default(), UndoGrouping::Explicit); + let (mut set, mut e) = editor_with("", &[Selection::cursor(0)], UndoGrouping::Explicit); + assert_eq!(e.undo_grouping(), UndoGrouping::Explicit); + type_chars(&mut set, &mut e, "abc"); + assert!(!e.in_undo_group()); + assert_eq!(steps(&mut set, &mut e), ["ab", "a", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_typed_word_undoes_and_redoes_in_one_step() { + let (mut set, mut e) = typing("x", &[Selection::cursor(1)]); + assert_eq!(e.undo_grouping(), UndoGrouping::Typing); + assert!(!e.in_undo_group()); + let first = e.insert(&mut set, "h").unwrap().expect("applied"); + assert!(e.in_undo_group()); + for c in ["e", "l", "l", "o"] { + assert_eq!(e.insert(&mut set, c).unwrap(), Some(first)); + } + assert_eq!(text(&set, &e), "xhello"); + + assert_eq!(e.undo(&mut set).unwrap(), Some(first)); + assert_eq!(text(&set, &e), "x"); + assert_eq!(cursors(&e), [1]); + assert!(!e.in_undo_group()); + assert_eq!(e.undo(&mut set).unwrap(), None); + + assert_eq!(e.redo(&mut set).unwrap(), Some(first)); + assert_eq!(text(&set, &e), "xhello"); + assert_eq!(cursors(&e), [6]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn three_cursors_in_crlf_type_as_one_step() { + let (mut set, mut e) = typing( + "a\r\nb\r\nc", + &[ + Selection::cursor(1), + Selection::cursor(4), + Selection::cursor(7), + ], + ); + type_chars(&mut set, &mut e, "xy"); + assert_eq!(text(&set, &e), "axy\r\nbxy\r\ncxy"); + e.undo(&mut set).unwrap(); + assert_eq!(text(&set, &e), "a\r\nb\r\nc"); + assert_eq!(cursors(&e), [1, 4, 7]); + assert_eq!(e.undo(&mut set).unwrap(), None); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn cursors_that_merge_during_a_run_keep_the_step() { + let (mut set, mut e) = typing("xabcd", &[Selection::cursor(3), Selection::cursor(5)]); + e.delete_backward(&mut set).unwrap().expect("applied"); + assert_eq!(text(&set, &e), "xac"); + e.delete_backward(&mut set).unwrap().expect("applied"); + assert_eq!(text(&set, &e), "x"); + assert_eq!(cursors(&e), [1]); + e.delete_backward(&mut set).unwrap().expect("applied"); + assert_eq!(text(&set, &e), ""); + assert_eq!(steps(&mut set, &mut e), ["xabcd"]); +} + +/// A move, run between typing `x` and typing `y`. +type MoveFn = fn(&mut Editor, &BufferSet); + +#[test] +#[ignore = "T-112: not implemented yet"] +fn every_kind_of_move_ends_the_step() { + let start = "ab cd\nef"; + let cases: [(&str, Vec, MoveFn); 11] = [ + ("move left", vec![Selection::cursor(2)], |e, set| { + assert!(e.move_cursors(set, Motion::Left).unwrap()); + }), + ("move to the end", vec![Selection::cursor(2)], |e, set| { + assert!(e.move_cursors(set, Motion::TextEnd).unwrap()); + }), + ("move down", vec![Selection::cursor(2)], |e, set| { + assert!(e.move_cursors(set, Motion::Down).unwrap()); + }), + ("extend right", vec![Selection::cursor(2)], |e, set| { + assert!(e.extend_selections(set, Motion::Right).unwrap()); + }), + ("set selections", vec![Selection::cursor(2)], |e, _| { + e.set_selections(Selections::single(Selection::cursor(0))); + }), + ( + "add a cursor below", + vec![Selection::cursor(2)], + |e, set| { + assert!(e.add_cursor_below(set).unwrap()); + }, + ), + ( + "add a cursor above", + vec![Selection::cursor(8)], + |e, set| { + assert!(e.add_cursor_above(set).unwrap()); + }, + ), + ( + "add the next match", + vec![Selection::cursor(2)], + |e, set| { + assert!(e.add_next_match(set).unwrap()); + }, + ), + ( + "select all matches", + vec![Selection::cursor(2)], + |e, set| { + assert!(e.select_all_matches(set).unwrap()); + }, + ), + ("select all", vec![Selection::cursor(2)], |e, set| { + assert!(e.select_all(set).unwrap()); + }), + ( + "collapse", + vec![Selection::cursor(2), Selection::cursor(8)], + |e, set| { + assert!(e.collapse_selections(set).unwrap()); + }, + ), + ]; + for (name, selections, run) in cases { + let (mut set, mut e) = typing(start, &selections); + type_chars(&mut set, &mut e, "x"); + run(&mut e, &set); + type_chars(&mut set, &mut e, "y"); + let texts = steps(&mut set, &mut e); + assert_eq!(texts.len(), 2, "{name}: {texts:?}"); + assert_eq!(texts[1], start, "{name}"); + } +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_move_that_changes_nothing_keeps_the_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "a"); + assert!(!e.move_cursors(&set, Motion::Right).unwrap()); + assert!(!e.move_cursors(&set, Motion::Down).unwrap()); + assert!(!e.collapse_selections(&set).unwrap()); + e.set_selections(Selections::single(Selection::cursor(1))); + type_chars(&mut set, &mut e, "b"); + assert_eq!(text(&set, &e), "ab"); + assert_eq!(steps(&mut set, &mut e), [""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_move_and_a_move_back_end_the_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "a"); + e.move_cursors(&set, Motion::Left).unwrap(); + e.move_cursors(&set, Motion::Right).unwrap(); + type_chars(&mut set, &mut e, "b"); + e.set_selections(Selections::single(Selection::cursor(0))); + e.set_selections(Selections::single(Selection::cursor(2))); + type_chars(&mut set, &mut e, "c"); + assert_eq!(text(&set, &e), "abc"); + assert_eq!(steps(&mut set, &mut e), ["ab", "a", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn switching_between_typing_and_deleting_ends_the_step() { + let (mut set, mut e) = typing("Z", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "abc"); + e.delete_backward(&mut set).unwrap(); + e.delete_backward(&mut set).unwrap(); + type_chars(&mut set, &mut e, "xy"); + e.delete_forward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "axy"); + assert_eq!(steps(&mut set, &mut e), ["axyZ", "aZ", "abcZ", "Z"]); + + // Deleting backward then forward is two steps too. + let (mut set, mut e) = typing("abc", &[Selection::cursor(1)]); + e.delete_backward(&mut set).unwrap(); + e.delete_forward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "c"); + assert_eq!(steps(&mut set, &mut e), ["bc", "abc"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn word_and_line_deletes_join_the_delete_of_their_direction() { + let (mut set, mut e) = typing("let foo = bar;", &[Selection::cursor(13)]); + e.delete_backward(&mut set).unwrap(); + e.delete_to(&mut set, Motion::WordLeft).unwrap(); + assert_eq!(text(&set, &e), "let foo = ;"); + e.delete_to(&mut set, Motion::LineStart).unwrap(); + assert_eq!(text(&set, &e), ";"); + assert_eq!(steps(&mut set, &mut e), ["let foo = bar;"]); + + let (mut set, mut e) = typing("let foo = bar;", &[Selection::cursor(0)]); + e.delete_forward(&mut set).unwrap(); + e.delete_to(&mut set, Motion::WordRight).unwrap(); + assert_eq!(text(&set, &e), " foo = bar;"); + e.delete_to(&mut set, Motion::LineEnd).unwrap(); + assert_eq!(text(&set, &e), ""); + assert_eq!(steps(&mut set, &mut e), ["let foo = bar;"]); + + // A word delete in the other direction starts a step. + let (mut set, mut e) = typing("ab cd", &[Selection::cursor(2)]); + e.delete_backward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "a cd"); + e.delete_to(&mut set, Motion::WordRight).unwrap(); + assert_eq!(text(&set, &e), "a"); + assert_eq!(steps(&mut set, &mut e), ["a cd", "ab cd"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn enter_starts_a_step_that_typing_after_it_joins() { + let (mut set, mut e) = typing("\n", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "abc"); + e.newline(&mut set).unwrap(); + type_chars(&mut set, &mut e, "def"); + assert_eq!(text(&set, &e), "abc\ndef\n"); + assert_eq!(steps(&mut set, &mut e), ["abc\n", "\n"]); + + // Two Enters are two steps, and the second takes the typing after it. + let (mut set, mut e) = typing("\r\n", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "a"); + e.newline(&mut set).unwrap(); + e.newline(&mut set).unwrap(); + type_chars(&mut set, &mut e, "b"); + assert_eq!(text(&set, &e), "a\r\n\r\nb\r\n"); + assert_eq!(steps(&mut set, &mut e), ["a\r\n\r\n", "a\r\n", "\r\n"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn deleting_a_line_break_starts_a_step() { + for line_break in ["\n", "\r\n", "\r"] { + let start = format!("ab{line_break}cd"); + let (mut set, mut e) = typing(&start, &[Selection::cursor(start.len())]); + e.delete_backward(&mut set).unwrap(); + e.delete_backward(&mut set).unwrap(); + // This one takes the line break. + e.delete_backward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "ab", "{line_break:?}"); + e.delete_backward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "a", "{line_break:?}"); + assert_eq!( + steps(&mut set, &mut e), + [format!("ab{line_break}"), start.clone()], + "{line_break:?}" + ); + + let (mut set, mut e) = typing(&start, &[Selection::cursor(1)]); + e.delete_forward(&mut set).unwrap(); + e.delete_forward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "acd", "{line_break:?}"); + e.delete_forward(&mut set).unwrap(); + assert_eq!(text(&set, &e), "ad", "{line_break:?}"); + assert_eq!( + steps(&mut set, &mut e), + [format!("a{line_break}cd"), start.clone()], + "{line_break:?}" + ); + } +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_word_delete_across_a_line_break_starts_a_step() { + let (mut set, mut e) = typing("ab\ncd", &[Selection::cursor(5)]); + e.delete_backward(&mut set).unwrap(); + // From the start of the line, WordLeft crosses the line break. + e.delete_backward(&mut set).unwrap(); + e.delete_to(&mut set, Motion::WordLeft).unwrap(); + assert_eq!(text(&set, &e), "ab"); + assert_eq!(steps(&mut set, &mut e), ["ab\n", "ab\ncd"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_pause_of_typing_pause_starts_a_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + e.set_time(Duration::ZERO); + type_chars(&mut set, &mut e, "a"); + e.set_time(PAUSE - Duration::from_nanos(1)); + type_chars(&mut set, &mut e, "b"); + // Measured from the last edit, not the step's first. + e.set_time(2 * PAUSE - Duration::from_nanos(2)); + type_chars(&mut set, &mut e, "c"); + e.set_time(3 * PAUSE - Duration::from_nanos(2)); + type_chars(&mut set, &mut e, "d"); + assert_eq!(text(&set, &e), "abcd"); + assert_eq!(steps(&mut set, &mut e), ["abc", ""]); + + // A long run of quick keys stays one step. + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + for k in 0..50 { + e.set_time(at(1000 + 100 * k)); + type_chars(&mut set, &mut e, "x"); + } + assert_eq!(steps(&mut set, &mut e), [""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_pause_splits_deletes_too() { + let (mut set, mut e) = typing("abc", &[Selection::cursor(3)]); + e.set_time(at(0)); + e.delete_backward(&mut set).unwrap(); + e.set_time(at(0) + PAUSE); + e.delete_backward(&mut set).unwrap(); + assert_eq!(steps(&mut set, &mut e), ["ab", "abc"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn without_a_time_or_with_time_going_back_nothing_splits() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "abc"); + assert_eq!(steps(&mut set, &mut e), [""]); + + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + e.set_time(at(10_000)); + type_chars(&mut set, &mut e, "a"); + e.set_time(at(5_000)); + type_chars(&mut set, &mut e, "b"); + e.set_time(at(5_500)); + type_chars(&mut set, &mut e, "c"); + assert_eq!(steps(&mut set, &mut e), [""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn under_explicit_grouping_time_changes_nothing() { + let (mut set, mut e) = editor_with("", &[Selection::cursor(0)], UndoGrouping::Explicit); + e.set_time(at(0)); + type_chars(&mut set, &mut e, "a"); + e.set_time(at(1)); + type_chars(&mut set, &mut e, "b"); + assert_eq!(steps(&mut set, &mut e), ["a", ""]); + + let (mut set, mut e) = editor_with("", &[Selection::cursor(0)], UndoGrouping::Explicit); + e.begin_undo_group(); + e.set_time(at(0)); + type_chars(&mut set, &mut e, "a"); + e.set_time(at(0) + 10 * PAUSE); + type_chars(&mut set, &mut e, "b"); + e.end_undo_group(); + assert_eq!(steps(&mut set, &mut e), [""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn undo_and_redo_end_the_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "ab"); + e.undo(&mut set).unwrap(); + assert_eq!(text(&set, &e), ""); + assert!(!e.in_undo_group()); + type_chars(&mut set, &mut e, "cd"); + assert_eq!(text(&set, &e), "cd"); + e.undo(&mut set).unwrap(); + e.redo(&mut set).unwrap(); + assert!(!e.in_undo_group()); + type_chars(&mut set, &mut e, "e"); + assert_eq!(text(&set, &e), "cde"); + assert_eq!(steps(&mut set, &mut e), ["cd", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn end_undo_group_ends_a_typing_step_and_makes_a_paste_one_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "ab"); + // A paste, as the ED-1 task should make one. + assert!(e.end_undo_group()); + e.insert(&mut set, "x\ny").unwrap(); + assert!(e.end_undo_group()); + assert!(!e.end_undo_group()); + type_chars(&mut set, &mut e, "cd"); + assert_eq!(text(&set, &e), "abx\nycd"); + assert_eq!(steps(&mut set, &mut e), ["abx\ny", "ab", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn an_explicit_group_wins_over_the_typing_rules() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "a"); + e.begin_undo_group(); + assert!(e.in_undo_group()); + e.set_time(at(0)); + type_chars(&mut set, &mut e, "b"); + e.move_cursors(&set, Motion::Left).unwrap(); + e.delete_backward(&mut set).unwrap(); + e.newline(&mut set).unwrap(); + e.set_time(at(0) + 10 * PAUSE); + type_chars(&mut set, &mut e, "c"); + assert_eq!(text(&set, &e), "\ncb"); + assert!(e.end_undo_group()); + // The next edit starts a typing step of its own. + type_chars(&mut set, &mut e, "d"); + assert!(e.in_undo_group()); + assert_eq!(text(&set, &e), "\ncdb"); + assert_eq!(steps(&mut set, &mut e), ["\ncb", "a", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn changing_the_grouping_ends_any_group() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "a"); + // The same grouping keeps the typing group. + e.set_undo_grouping(UndoGrouping::Typing); + assert!(e.in_undo_group()); + type_chars(&mut set, &mut e, "b"); + e.set_undo_grouping(UndoGrouping::Explicit); + assert_eq!(e.undo_grouping(), UndoGrouping::Explicit); + assert!(!e.in_undo_group()); + type_chars(&mut set, &mut e, "c"); + + // The same for an explicit group. + e.begin_undo_group(); + e.set_undo_grouping(UndoGrouping::Explicit); + assert!(e.in_undo_group()); + type_chars(&mut set, &mut e, "d"); + e.set_undo_grouping(UndoGrouping::Typing); + assert!(!e.in_undo_group()); + type_chars(&mut set, &mut e, "e"); + assert_eq!(text(&set, &e), "abcde"); + assert_eq!(steps(&mut set, &mut e), ["abcd", "abc", "ab", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn an_edit_with_nothing_to_do_keeps_the_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "ab"); + // Delete at the end of the text deletes nothing. + assert_eq!(e.delete_forward(&mut set).unwrap(), None); + assert_eq!(e.delete_to(&mut set, Motion::TextEnd).unwrap(), None); + assert!(e.in_undo_group()); + type_chars(&mut set, &mut e, "c"); + assert_eq!(steps(&mut set, &mut e), [""]); + + // And backspace at the start, before any typing, opens nothing. + let (mut set, mut e) = typing("ab", &[Selection::cursor(0)]); + assert_eq!(e.delete_backward(&mut set).unwrap(), None); + assert!(!e.in_undo_group()); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn an_unknown_buffer_changes_nothing() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + let mut other = BufferSet::new(); + type_chars(&mut set, &mut e, "a"); + e.set_time(at(10)); + assert!(matches!( + e.delete_backward(&mut other), + Err(EditorError::UnknownBuffer { .. }) + )); + assert!(matches!( + e.newline(&mut other), + Err(EditorError::UnknownBuffer { .. }) + )); + assert!(e.in_undo_group()); + type_chars(&mut set, &mut e, "b"); + assert_eq!(steps(&mut set, &mut e), [""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn an_outside_transaction_splits_the_run() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "ab"); + // An agent appends to the buffer. + let mut outside = Transaction::new(); + outside.push(Edit::insert(e.buffer(), 2, "Z")); + set.apply(outside).unwrap(); + type_chars(&mut set, &mut e, "cd"); + assert_eq!(text(&set, &e), "abcdZ"); + // `cd`, then the agent's edit, then `ab`. + assert_eq!(steps(&mut set, &mut e), ["abZ", "ab", ""]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_vim_command_under_typing_grouping_is_its_own_step() { + let registry = CommandRegistry::with_vim_commands(); + let (mut set, mut e) = typing("abc", &[Selection::cursor(0)]); + type_chars(&mut set, &mut e, "x"); + registry + .run( + &Invocation::new(vim_commands::DELETE_CHAR), + &mut e, + &mut set, + ) + .unwrap(); + assert_eq!(text(&set, &e), "xbc"); + assert!(!e.in_undo_group()); + type_chars(&mut set, &mut e, "y"); + assert_eq!(text(&set, &e), "xybc"); + assert_eq!(steps(&mut set, &mut e), ["xbc", "xabc", "abc"]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_clone_keeps_the_open_typing_step() { + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + e.set_time(at(100)); + type_chars(&mut set, &mut e, "a"); + let mut copy = e.clone(); + assert_eq!(copy.undo_grouping(), UndoGrouping::Typing); + assert!(copy.in_undo_group()); + type_chars(&mut set, &mut copy, "b"); + assert_eq!(steps(&mut set, &mut copy), [""]); + + // The copy keeps the time of the step's last edit too. + let (mut set, mut e) = typing("", &[Selection::cursor(0)]); + e.set_time(at(100)); + type_chars(&mut set, &mut e, "a"); + let mut copy = e.clone(); + copy.set_time(at(100) + PAUSE); + type_chars(&mut set, &mut copy, "b"); + assert_eq!(steps(&mut set, &mut copy), ["a", ""]); +} diff --git a/crates/helm-editor/tests/vscode_undo.rs b/crates/helm-editor/tests/vscode_undo.rs new file mode 100644 index 0000000..1c4381c --- /dev/null +++ b/crates/helm-editor/tests/vscode_undo.rs @@ -0,0 +1,327 @@ +//! T-112 acceptance tests: VS Code's typing groups through the dispatcher. +//! `vscode::keymap()` carries `UndoGrouping::Typing`, and `dispatch` hands +//! the active keymap's grouping to the editor before each command. + +use std::time::Duration; + +use helm_editor::{ + Binding, CommandRegistry, Dispatcher, Editor, Key, KeyEvent, KeySequence, KeyState, Keymap, + Keystroke, Mode, Modifiers, Resolution, Selection, Selections, Session, Typing, UndoGrouping, + editor_commands, vim, vscode, +}; +use helm_text::{Buffer, BufferSet, FileFormat, LineEndings}; + +fn setup(text: &str, selections: &[Selection]) -> (BufferSet, Editor) { + let mut set = BufferSet::new(); + let id = set.add(Buffer::from(text)); + let format = FileFormat { + bom: false, + line_endings: LineEndings::count(text), + }; + let mut editor = Editor::new(id, format); + editor.set_selections(Selections::new(selections.to_vec(), 0).expect("non-empty")); + (set, editor) +} + +/// The key events of `keys`, in `KeySequence` notation. +fn events(keys: &str) -> Vec { + KeySequence::parse(keys) + .expect("valid keys") + .as_slice() + .iter() + .map(|&keystroke| KeyEvent::new(keystroke)) + .collect() +} + +/// One key event per char of `text`, each typing its char. +fn chars(text: &str) -> Vec { + text.chars() + .map(|c| KeyEvent::new(Keystroke::new(Key::Char(c), Modifiers::NONE))) + .collect() +} + +/// One editor on a dispatcher that holds every command, so it can switch +/// between VS Code's and Vim's keymaps. Keys go through `dispatch_in` with +/// one `Session`, as in `helm-ui`. +struct Window { + dispatcher: Dispatcher, + state: KeyState, + session: Session, + set: BufferSet, + editor: Editor, +} + +impl Window { + fn new(keymap: Keymap, text: &str, selections: &[Selection]) -> Self { + let dispatcher = Dispatcher::new(CommandRegistry::with_vim_commands(), keymap); + let state = dispatcher.key_state(); + let (set, editor) = setup(text, selections); + Self { + dispatcher, + state, + session: Session::new(), + set, + editor, + } + } + + fn send(&mut self, events: Vec) { + for event in events { + self.dispatcher + .dispatch_in( + &mut self.state, + &event, + &[], + &mut self.editor, + &mut self.set, + &mut self.session, + ) + .expect("the command runs"); + } + } + + fn keys(&mut self, keys: &str) { + self.send(events(keys)); + } + + fn type_text(&mut self, text: &str) { + self.send(chars(text)); + } + + /// Switches keymaps the way a settings toggle does, without the + /// `end_undo_group` call T-108 asks `helm-ui` to make. + fn switch(&mut self, keymap: Keymap) { + self.dispatcher.set_keymap(keymap); + self.dispatcher.sync(&mut self.state); + } + + fn text(&self) -> String { + self.set + .get(self.editor.buffer()) + .expect("in the set") + .to_string() + } + + fn selections(&self) -> &[Selection] { + self.editor.selections().as_slice() + } +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn each_keymap_carries_its_grouping() { + assert_eq!(vscode::keymap().undo_grouping(), UndoGrouping::Typing); + assert_eq!(vim::keymap().undo_grouping(), UndoGrouping::Explicit); + let plain = Keymap::new("plain", vec![Mode::new("m", Typing::Insert)]).unwrap(); + assert_eq!(plain.undo_grouping(), UndoGrouping::Explicit); + let typing = plain.with_undo_grouping(UndoGrouping::Typing); + assert_eq!(typing.undo_grouping(), UndoGrouping::Typing); + assert_eq!(typing.name(), "plain"); + // The VS Code keymap keeps its 39 bindings. + assert_eq!(vscode::keymap().bindings().len(), 39); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn dispatch_gives_the_editor_the_keymaps_grouping_on_a_run() { + let mut keymap = Keymap::new("chords", vec![Mode::new("m", Typing::Insert)]) + .unwrap() + .with_undo_grouping(UndoGrouping::Typing); + keymap + .bind(Binding::run("cmd-k cmd-z", editor_commands::UNDO).unwrap()) + .unwrap(); + let dispatcher = Dispatcher::new(CommandRegistry::with_all_commands(), keymap); + let mut state = dispatcher.key_state(); + let (mut set, mut editor) = setup("", &[Selection::cursor(0)]); + assert_eq!(editor.undo_grouping(), UndoGrouping::Explicit); + + let mut press = |editor: &mut Editor, set: &mut BufferSet, keys: &str| { + let event = &events(keys)[0]; + dispatcher + .dispatch(&mut state, event, &[], editor, set) + .unwrap() + }; + // An unbound key and a pending chord run nothing, so nothing changes. + assert_eq!(press(&mut editor, &mut set, "cmd-x"), Resolution::Unbound); + assert_eq!(press(&mut editor, &mut set, "cmd-k"), Resolution::Pending); + assert_eq!(editor.undo_grouping(), UndoGrouping::Explicit); + assert!(matches!( + press(&mut editor, &mut set, "cmd-z"), + Resolution::Run(_) + )); + assert_eq!(editor.undo_grouping(), UndoGrouping::Typing); + + // `dispatch_in` does the same, with Vim's keymap giving `Explicit`. + let vim = Dispatcher::new(CommandRegistry::with_vim_commands(), vim::keymap()); + let mut state = vim.key_state(); + let mut session = Session::new(); + vim.dispatch_in( + &mut state, + &chars("l")[0], + &[], + &mut editor, + &mut set, + &mut session, + ) + .unwrap(); + assert_eq!(editor.undo_grouping(), UndoGrouping::Explicit); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn a_vscode_session_undoes_step_by_step() { + let mut w = Window::new(vscode::keymap(), "", &[Selection::cursor(0)]); + w.type_text("hello world"); + w.keys("enter"); + w.type_text("x"); + w.keys("left"); + w.type_text("y"); + w.keys("backspace"); + assert_eq!(w.text(), "hello world\nx"); + + let undone = [ + ("hello world\nyx", 13), + ("hello world\nx", 12), + ("hello world", 11), + ("", 0), + ("", 0), + ]; + for (text, cursor) in undone { + w.keys("cmd-z"); + assert_eq!(w.text(), text); + assert_eq!(w.selections(), [Selection::cursor(cursor)], "{text:?}"); + } + let redone = [ + ("hello world", 11), + ("hello world\nx", 13), + ("hello world\nyx", 13), + ("hello world\nx", 12), + ]; + for (text, cursor) in redone { + w.keys("shift-cmd-z"); + assert_eq!(w.text(), text); + assert_eq!(w.selections(), [Selection::cursor(cursor)], "{text:?}"); + } +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn backspace_and_word_and_line_deletes_undo_together() { + let mut w = Window::new(vscode::keymap(), "let foo = bar;", &[Selection::cursor(13)]); + w.keys("backspace alt-backspace cmd-backspace"); + assert_eq!(w.text(), ";"); + w.keys("cmd-z"); + assert_eq!(w.text(), "let foo = bar;"); + assert_eq!(w.selections(), [Selection::cursor(13)]); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn typing_after_undo_starts_a_new_step() { + let mut w = Window::new(vscode::keymap(), "", &[Selection::cursor(0)]); + w.type_text("ab"); + w.keys("cmd-z"); + w.type_text("cd"); + w.keys("cmd-z"); + assert_eq!(w.text(), ""); + w.keys("shift-cmd-z"); + assert_eq!(w.text(), "cd"); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn typing_at_three_cursors_undoes_in_one_step() { + let mut w = Window::new(vscode::keymap(), "let a = a + a;", &[Selection::cursor(4)]); + w.keys("cmd-d shift-cmd-l"); + w.type_text("total"); + assert_eq!(w.text(), "let total = total + total;"); + w.keys("cmd-z"); + assert_eq!(w.text(), "let a = a + a;"); + assert_eq!( + w.selections(), + [ + Selection::new(4, 5), + Selection::new(8, 9), + Selection::new(12, 13) + ] + ); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn set_time_between_keys_splits_a_run_at_a_pause() { + let mut w = Window::new(vscode::keymap(), "", &[Selection::cursor(0)]); + let pause = Editor::TYPING_PAUSE; + let times = [ + Duration::ZERO, + Duration::from_millis(100), + Duration::from_millis(100) + pause, + ]; + for (c, time) in "abc".chars().zip(times) { + w.editor.set_time(time); + w.type_text(&c.to_string()); + } + w.keys("cmd-z"); + assert_eq!(w.text(), "ab"); + w.keys("cmd-z"); + assert_eq!(w.text(), ""); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn switching_to_vim_ends_the_typing_step() { + let mut w = Window::new(vscode::keymap(), "abc", &[Selection::cursor(0)]); + w.type_text("xy"); + assert!(w.editor.in_undo_group()); + w.switch(vim::keymap()); + // Vim's `x` deletes the char under the cursor, as its own step. + w.type_text("x"); + assert_eq!(w.text(), "xybc"); + assert_eq!(w.editor.undo_grouping(), UndoGrouping::Explicit); + w.type_text("u"); + assert_eq!(w.text(), "xyabc"); + w.type_text("u"); + assert_eq!(w.text(), "abc"); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn switching_to_vscode_mid_insert_ends_the_vim_group_and_its_record() { + let mut w = Window::new(vim::keymap(), "abc", &[Selection::cursor(0)]); + w.type_text("ixy"); + assert_eq!(w.state.mode().as_str(), vim::INSERT); + assert!(w.session.last_change().is_none()); + w.switch(vscode::keymap()); + w.type_text("z"); + // The switch ended the insert session before `z` ran, so `.` has the + // whole session and `z` isn't part of it. + let change = w.session.last_change().expect("the insert is recorded"); + assert_eq!(change.len(), 3); + assert_eq!(change[0].command.as_str(), "vim.insert"); + w.type_text("w"); + assert_eq!(w.text(), "xyzwabc"); + w.switch(vim::keymap()); + assert_eq!(w.state.mode().as_str(), vim::NORMAL); + w.type_text("u"); + assert_eq!(w.text(), "xyabc"); + w.type_text("u"); + assert_eq!(w.text(), "abc"); +} + +#[test] +#[ignore = "T-112: not implemented yet"] +fn with_helm_uis_close_on_each_switch_there_are_still_three_steps() { + let mut w = Window::new(vim::keymap(), "abc", &[Selection::cursor(0)]); + w.type_text("iy"); + w.switch(vscode::keymap()); + w.editor.end_undo_group(); + w.type_text("zw"); + w.switch(vim::keymap()); + w.editor.end_undo_group(); + w.type_text("x"); + assert_eq!(w.text(), "yzwbc"); + for expected in ["yzwabc", "yabc", "abc"] { + w.type_text("u"); + assert_eq!(w.text(), expected); + } +} From c53b211e6a61fde0c08088df8bcac3b9d57b0849 Mon Sep 17 00:00:00 2001 From: shubhook Date: Sat, 28 Nov 2026 21:58:20 +0530 Subject: [PATCH 3/3] editor: record Khakha's answers to T-112's open questions All seven keep the spec's choice, so the interface and tests stand. Refs: T-112, ED-2, ED-4 --- tasks/112-vscode-undo-groups.md | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/tasks/112-vscode-undo-groups.md b/tasks/112-vscode-undo-groups.md index 34a8963..f088f5b 100644 --- a/tasks/112-vscode-undo-groups.md +++ b/tasks/112-vscode-undo-groups.md @@ -2,7 +2,7 @@ After: T-109. This task waits until that one is merged. It is, as PR #42, and so are T-108 and T-110, which this task builds on, and T-114 (PR #45), which also changed `helm-editor`. This spec is written against main at `3566348`. -**Questions 1 to 4 under "Open questions for Khakha" block the implementation.** The tests pin an answer to each that VS Code's documentation doesn't settle. Questions 5 to 7 have a default the implementation follows unless Khakha says otherwise. +**The open questions are answered.** Khakha kept the spec's choice on all seven, so the interface and the tests stand as written and the implementation can start. See "Open questions for Khakha". ## Goal @@ -148,7 +148,7 @@ As in T-101 to T-109, the implementation PR adds the benchmark file. The spec PR ## Out of scope -- Word-by-word steps for typed spaces: open question 5. +- Word-by-word steps for typed spaces: a later task, per Khakha's answer 5. - `cursorUndo` (`cmd-u`) and undoing selection changes on their own, as T-105 left them: a later task. - The paste, cut and copy commands and the clipboard (ED-1): a later task. It must follow the paste rule above. - Auto-closing brackets, electric characters and auto-indent, which VS Code groups by their own rules: later, with SY-3. @@ -160,12 +160,24 @@ As in T-101 to T-109, the implementation PR adds the benchmark file. The spec PR ## Open questions for Khakha -Questions 1 to 4 block the implementation. Each rule is a Helm proposal that VS Code's documentation doesn't settle, and the tests pin it, so a different answer changes the tests before anyone implements them. Questions 5 to 7 don't block: the spec states a default for each, and the implementation follows it unless Khakha says otherwise. +Questions 1 to 4 blocked the implementation, and questions 5 to 7 had defaults. Khakha answered all seven on PR #46 and kept the spec's choice on each, so nothing in the interface or the tests changes. -1. **Keep the pause rule, and at what length? (blocking)** VS Code's docs describe no pause, and its cursor code has no timer for undo. I propose one second as a Helm rule, long enough that ordinary typing never splits. A different length changes only `TYPING_PAUSE`, since the tests name the constant. Dropping the rule removes `set_time`, the pause tests in both test files, and the waits in the properties. -2. **Should every move end the step? (blocking)** VS Code's cursor controller doesn't reset on a move in the files I read, so VS Code may join `ab`, Left, `c`. I propose that every move ends the step, since the brief lists it and it gives the same result for a mouse click as for an arrow key. -3. **Enter starts a step, and typing after it joins. (blocking)** This matches VS Code's source. The other choices are Enter as its own step, or Enter joining the typing before it. -4. **The keymap carries the grouping, and the dispatcher applies it. (blocking)** The other choice is `helm-ui` calling `set_undo_grouping` after each switch. That keeps `Keymap` and `Dispatcher` as they are, but adds a second rule for `helm-ui` beside T-108's, and `vscode_undo.rs` would change. -5. **Word-by-word steps. (default: a later task)** Include VS Code's apparent space rule, where `hello world` undoes `" world"` first, in this task, in a later one, or not at all? I couldn't confirm it from the docs or from the parts of the source I read in full. -6. **An edit with nothing to do keeps the step. (default: as specified)** VS Code may record the type of a delete that deleted nothing. I couldn't tell from the source. I propose keeping the step, which follows Helm's rule that a command with nothing to do changes nothing. A different answer changes one test. -7. **`TYPING_PAUSE` as a public constant. (default: a constant)** Tests need to name it. If ST-1 will make it a setting, it could be a field on `Typing` grouping instead. That means `UndoGrouping::Typing { pause }` and a different `Keymap` API. +Khakha's answers, as written: + +> 1. Keep the pause rule. TYPING_PAUSE is 1 s. +> 2. Yes, every cursor move ends the open undo step. +> 3. Yes, Enter starts a new step, and typing right after it joins that step. +> 4. Yes, the keymap carries the grouping, and the dispatcher applies it. helm-ui does not set it after each switch. +> 5. Word-by-word steps go to a later task. +> 6. An edit with nothing to do keeps the open step, as specified. +> 7. TYPING_PAUSE stays a constant. + +The questions as asked: + +1. **Keep the pause rule, and at what length? (answered: kept, 1 s)** VS Code's docs describe no pause, and its cursor code has no timer for undo. I propose one second as a Helm rule, long enough that ordinary typing never splits. A different length changes only `TYPING_PAUSE`, since the tests name the constant. Dropping the rule removes `set_time`, the pause tests in both test files, and the waits in the properties. +2. **Should every move end the step? (answered: yes)** VS Code's cursor controller doesn't reset on a move in the files I read, so VS Code may join `ab`, Left, `c`. I propose that every move ends the step, since the brief lists it and it gives the same result for a mouse click as for an arrow key. +3. **Enter starts a step, and typing after it joins. (answered: yes)** This matches VS Code's source. The other choices are Enter as its own step, or Enter joining the typing before it. +4. **The keymap carries the grouping, and the dispatcher applies it. (answered: yes)** The other choice is `helm-ui` calling `set_undo_grouping` after each switch. That keeps `Keymap` and `Dispatcher` as they are, but adds a second rule for `helm-ui` beside T-108's, and `vscode_undo.rs` would change. +5. **Word-by-word steps. (answered: a later task)** Include VS Code's apparent space rule, where `hello world` undoes `" world"` first, in this task, in a later one, or not at all? I couldn't confirm it from the docs or from the parts of the source I read in full. +6. **An edit with nothing to do keeps the step. (answered: as specified)** VS Code may record the type of a delete that deleted nothing. I couldn't tell from the source. I propose keeping the step, which follows Helm's rule that a command with nothing to do changes nothing. A different answer changes one test. +7. **`TYPING_PAUSE` as a public constant. (answered: a constant)** Tests need to name it. If ST-1 will make it a setting, it could be a field on `Typing` grouping instead. That means `UndoGrouping::Typing { pause }` and a different `Keymap` API.