robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
81.0 KiB2183 linesraw
1-- Tests for atom capture: the CmdAtom event, and dot-repeat of whole insert sessions.
2
3local t = require('test.testutil')
4local n = require('test.functional.testnvim')()
5local Screen = require('test.functional.ui.screen')
6local t_atom = require('test.functional.editor.atom_testutil')
7
8local describe, it, before_each = t.describe, t.it, t.before_each
9local retry = t.retry
10local clear = n.clear
11local command = n.command
12local exec = n.exec
13local feed = n.feed
14local fn = n.fn
15local eq = t.eq
16local api = n.api
17local get_lines = t_atom.get_lines
18local k = t_atom.k
19local atoms_start = t_atom.atoms_start
20local atoms = t_atom.atoms
21local atoms_tail = t_atom.atoms_tail
22local atom_last = t_atom.atom_last
23local pick = t.pick
24local subatoms = t_atom.subatoms
25
26describe('dot-repeat', function()
27  before_each(clear)
28
29  it('replays insert-mode cursor-moves (the whole session)', function()
30    fn.setline(1, { 'one', 'two' })
31    feed('iab<Left>c<Esc>')
32    eq({ 'acbone', 'two' }, get_lines())
33    -- The ". register and undo still restart at the cursor-move, like Vim.
34    eq('c', fn.getreg('.'))
35    feed('u')
36    eq({ 'abone', 'two' }, get_lines())
37    feed('<C-r>')
38    -- "." re-executes the whole session, cursor-move included.
39    feed('j0.')
40    eq({ 'acbone', 'acbtwo' }, get_lines())
41    -- An absolute jump (<C-Home>) still restarts the capture: "." replays
42    -- only the post-jump insert.
43    feed('ggAxy<C-Home>z<Esc>')
44    eq({ 'zacbonexy', 'acbtwo' }, get_lines())
45    eq('z', fn.getreg('.'))
46    feed('j0.')
47    eq({ 'zacbonexy', 'zacbtwo' }, get_lines())
48    -- Vim's repeat-only-the-tail behavior is a mapping away (documented in
49    -- vim_diff.txt): i_CTRL-O re-entry restarts the capture.
50    command('inoremap <Left> <C-o><Left>')
51    feed('ggiab<Left>c<Esc>')
52    eq({ 'acbzacbonexy', 'zacbtwo' }, get_lines())
53    feed('j0.')
54    eq({ 'acbzacbonexy', 'czacbtwo' }, get_lines())
55  end)
56
57  it('failing mid-selection ends Visual-mode #41896', function()
58    fn.setline(1, { '1', '2', '3' })
59    feed('<C-V>jI1<Esc>j.j.') -- The 2nd "." fails: "j" on the last line.
60    eq({ '11', '112', '13' }, get_lines())
61    eq('n', fn.mode(1))
62    feed('k0.') -- The failed "." did not replace the last change.
63    eq({ '11', '1112', '113' }, get_lines())
64    -- Error (E20) instead of beep. ModeChanged fires after the error, not inside emsg().
65    command('autocmd ModeChanged V:n echomsg "ModeChanged"')
66    for _, eb in ipairs({ 'noerrorbells', 'errorbells' }) do
67      api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two' })
68      feed('ggmajV`a~')
69      command(('set %s | delmarks a | messages clear'):format(eb))
70      feed('.')
71      eq({ 'ONE', 'TWO' }, get_lines(), eb)
72      eq('n', fn.mode(1))
73      eq('\nE20: Mark not set\nModeChanged', fn.execute('messages'))
74    end
75    -- A macro or mapping still stops at the failed motion, in Visual mode (map-error).
76    api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two', 'three' })
77    fn.setreg('q', 'Vjd')
78    command('nnoremap Q Vjd')
79    for _, keys in ipairs({ 'gg2@q', 'Q' }) do
80      feed(keys)
81      eq({ 'three' }, get_lines(), keys)
82      eq('V', fn.mode(1))
83      feed('<Esc>')
84    end
85  end)
86
87  it('of a visual op does not churn showcmd', function()
88    local screen = Screen.new(40, 8, { ext_messages = true })
89    command('set showcmd')
90    fn.setline(1, { 'foo bar', 'longword two' })
91    feed('gg0viWgU')
92    feed('2gg0')
93    screen:expect({ any = '%^longword' })
94    local updates = {}
95    function screen:_handle_msg_showcmd(msg)
96      local text = table.concat(vim.tbl_map(function(chunk)
97        return chunk[2]
98      end, msg))
99      if text ~= '' then
100        updates[#updates + 1] = text
101      end
102      self.showcmd = msg
103    end
104    feed('.')
105    retry(nil, nil, function()
106      eq({ 'FOO bar', 'LONGWORD two' }, get_lines())
107    end)
108    screen:sleep(50)
109    -- Stuffed (replayed) keys must not display in 'showcmd': ext_messages UIs redraw per showcmd
110    -- change, which would paint the replay's transient states (its in-progress Visual selection).
111    eq(
112      {},
113      vim.tbl_filter(function(s)
114        return s:find('[UW]') ~= nil
115      end, updates)
116    )
117  end)
118end)
119
120describe('CmdAtom', function()
121  before_each(clear)
122
123  describe('composite', function()
124    it('motion mapping', function()
125      command('nnoremap j gj')
126      fn.setline(1, { 'a1', 'b2', 'c3', 'd4', 'e5' })
127      feed('gg')
128      atoms_start()
129      feed('3j')
130      eq(4, fn.line('.'))
131      local ev = atom_last()
132      eq(
133        { type = 'motion', lhs = 'j', keys = '3gj', count = 3 },
134        pick(ev, 'type', 'lhs', 'keys', 'count')
135      )
136      -- The "," repeat recipe: replaying the KEYS verbatim repeats the count.
137      feed('gg')
138      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
139      eq(4, fn.line('.'))
140      -- Multi-command mapping: the pre-typed count lands in the FIRST folded
141      -- command; the folded atom itself has no single count.
142      command('nnoremap <F6> xw')
143      fn.setline(1, { 'abcdef ghi', 'jkl' })
144      feed('gg0')
145      feed('3<F6>')
146      ev = atom_last()
147      eq({ type = 'mapping', lhs = k('<F6>') }, pick(ev, 'type', 'count', 'lhs'))
148      -- Only the composite carries the mapping's LHS: a subatom is its own input.
149      eq({ keys = '3dl', count = 3, lhs = '3dl' }, pick(ev.atoms[1], 'keys', 'count', 'lhs'))
150      -- "." repeats the mapping's EDIT as ONE atom, labeled "." (not "<F6>").
151      local before = #atoms()
152      feed('.')
153      eq(before + 1, #atoms())
154      eq({ type = 'operator', keys = '3dl', lhs = '.' }, pick(atom_last(), 'type', 'keys', 'lhs'))
155    end)
156
157    it('Lua mapping (e.g. "]q" default)', function()
158      -- Default "]q" mapping: a Lua callback with unknown keys. Still a user action, emits an atom.
159      n.exec_lua([[
160        vim.keymap.set('n', ']q', function()
161          vim.cmd({ cmd = 'cnext', count = vim.v.count1 })
162        end, { desc = ':cnext' })
163      ]])
164      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
165      local bufnr = api.nvim_get_current_buf()
166      fn.setqflist({ { bufnr = bufnr, lnum = 1 }, { bufnr = bufnr, lnum = 3 } })
167      command('cfirst')
168      atoms_start()
169      feed(']q')
170      eq(3, fn.line('.')) -- The mapping did run (:cnext).
171      eq(
172        { type = 'mapping', lhs = ']q', changed = false },
173        pick(atom_last(), 'type', 'lhs', 'keys', 'changed')
174      )
175      -- Empty `keys` mapping that edits via API: `changed=true`.
176      n.exec_lua([[
177        vim.keymap.set('n', ',e', function()
178          vim.api.nvim_buf_set_lines(0, 0, 0, false, { 'NEW' })
179        end)
180      ]])
181      feed(',e')
182      eq({ lhs = ',e', changed = true }, pick(atom_last(), 'keys', 'lhs', 'changed'))
183
184      -- "<Cmd>" is opaque too, but unlike a Lua callback its command is text (like a ":" mapping).
185      command('nnoremap ,c <Cmd>call setline(1, "N" . v:count)<CR>')
186      feed('3,c')
187      local cmdev = atom_last()
188      eq({
189        type = 'excmd',
190        lhs = ',c',
191        keys = k('3<Cmd>call setline(1, "N" . v:count)<NL>'),
192        text = 'call setline(1, "N" . v:count)',
193        count = 3,
194        changed = true,
195      }, pick(cmdev, 'type', 'lhs', 'keys', 'text', 'count', 'changed'))
196      -- Those keys replay: the count must survive, since "<Cmd>" reads v:count.
197      eq('N3', fn.getline(1))
198      fn.setline(1, 'reset')
199      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(cmdev.keys))
200      eq('N3', fn.getline(1))
201      -- "<Cmd>" text is raw, a trailing "0" is not CTRL-V escaped (as for a ":" cmdline).
202      command([[nnoremap ,z <Cmd>call setline(1, 'Z') <Bar> let g:z = 10<CR>]])
203      feed(',z')
204      eq(k([[<Cmd>call setline(1, 'Z') | let g:z = 10<NL>]]), atom_last().keys)
205
206      -- <expr> mapping that returns a "<Cmd>lua …<CR>" (dot-repeat idiom #41387) captures the same
207      -- way: the constructed command is the atom.
208      n.exec_lua([[
209        vim.keymap.set('n', ',x', function()
210          return '<Cmd>call setline(1, "E" . v:count1)<CR>'
211        end, { expr = true })
212      ]])
213      feed('2,x')
214      cmdev = atom_last()
215      eq({
216        type = 'excmd',
217        lhs = ',x',
218        keys = k('2<Cmd>call setline(1, "E" . v:count1)<NL>'),
219        count = 2,
220      }, pick(cmdev, 'type', 'lhs', 'keys', 'count'))
221      fn.setline(1, 'reset')
222      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(cmdev.keys))
223      eq('E2', fn.getline(1))
224
225      -- Opaque key that changes nothing is invisible: mid-selection it must not void the pending
226      -- visual atom, which would void its per-cursor extents.
227      command('vnoremap ,n <Cmd>call execute("")<CR>')
228      fn.setline(1, { 'aaa bbb' })
229      feed('gg0viw,nd')
230      eq(' bbb', fn.getline(1))
231      eq({ type = 'visual', keys = 'viwd' }, pick(atom_last(), 'type', 'keys'))
232    end)
233
234    it('<expr> mapping: EXPRESSION input vs EXECUTION input #41665', function()
235      atoms_start()
236      for _, reader in ipairs({ 'getcharstr', 'input' }) do
237        n.exec_lua(function(reader_)
238          _G._log = {}
239          vim.keymap.set('o', 's', function()
240            local input = reader_ == 'input' and vim.fn.input('') or vim.fn.getcharstr()
241            local data = { input, vim.v.count1 }
242            return ('<Cmd>lua table.insert(_G._log, %s)<CR>'):format(vim.inspect(data))
243          end, { expr = true })
244        end, reader)
245
246        local input = reader == 'input' and 'e<CR>' or 'e'
247        -- Placement of [count] should not change the behavior. #41665
248        for _, prefix in ipairs({ '2d', 'd2' }) do
249          feed(('%ss%s'):format(prefix, input))
250          eq({
251            type = 'operator',
252            operator = 'd',
253            count = 2,
254            lhs = k(('ds%s'):format(input)),
255            keys = k('2d<Cmd>lua table.insert(_G._log, { "e", 2 })<NL>'),
256          }, pick(atom_last(), 'type', 'operator', 'count', 'lhs', 'keys'))
257        end
258        eq({ { 'e', 2 }, { 'e', 2 } }, n.exec_lua('return _G._log'))
259      end
260
261      -- expr EVALUATION gets "e" from getcharstr(), which the expr-mapping RETURNS, thus hardcoding
262      -- it into `keys` (not APPENDED by the capture engine).
263      -- Mapping EXECUTION getcharstr() consumes "q" _when executed_, thus "q" is APPENDED to `keys`.
264      n.exec_lua([[
265        vim.keymap.set('o', 's', function()
266          return ('<Cmd>let g:read_input = %q . getcharstr()<CR>'):format(vim.fn.getcharstr())
267        end, { expr = true })
268      ]])
269      for _, keys in ipairs({ '2dseq', 'd2seq' }) do
270        feed(keys)
271        local ev = atom_last()
272        eq(
273          { lhs = 'dseq', keys = k('2d<Cmd>let g:read_input = "e" . getcharstr()<NL>q') },
274          pick(ev, 'lhs', 'keys')
275        )
276        eq('eq', api.nvim_get_var('read_input'))
277        api.nvim_set_var('read_input', '')
278        api.nvim_feedkeys(ev.keys, 'nx', false)
279        eq('eq', api.nvim_get_var('read_input'))
280      end
281    end)
282
283    it('mapping that enters :terminal mode', function()
284      -- Fake picker/fuzzy-finder: a mapping that opens a :terminal UI (like fzf-lua).
285      -- Its composite ends when :terminal is entered.
286      n.exec_lua(function(prg)
287        vim.keymap.set('n', ',f', function()
288          vim.cmd('enew')
289          vim.fn.jobstart({ prg, 'INTERACT' }, { term = true })
290          vim.cmd.startinsert()
291        end)
292      end, n.testprg('shell-test'))
293      atoms_start()
294      feed(',f')
295      n.poke_eventloop()
296      eq(
297        { buftype = 'terminal', mode = 't' },
298        n.exec_lua('return { buftype = vim.bo.buftype, mode = vim.fn.mode(1) }')
299      )
300      feed('exit<CR>') -- Terminal-mode input: no atoms.
301      n.poke_eventloop()
302      feed([[<C-\><C-N>]])
303      feed('gg')
304      eq({
305        { type = 'mapping', lhs = ',f' },
306        { type = 'jump', lhs = 'gg', keys = 'gg' },
307      }, atoms_tail(2, 'type', 'lhs', 'keys'))
308    end)
309
310    it('simple mapping (single command) "unwraps" to the underlying type', function()
311      command('nnoremap ,d dw')
312      fn.setline(1, { 'one two aa bb cc dd' })
313      feed('gg0')
314      atoms_start()
315      feed(',d')
316      eq({ 'two aa bb cc dd' }, get_lines())
317      local evs = atoms()
318      eq(1, #evs)
319      -- Inapplicable fields (count/reg/arg/motionforce/text/atoms) are omitted.
320      eq({
321        type = 'operator', -- Unwrapped.
322        keys = 'dw',
323        operator = 'd',
324        cmd = 'w',
325        changed = true,
326        lhs = ',d',
327        moved = false, -- "dw" deletes at the cursor; does not move!
328        pos = { 1, 0 }, -- Original cursor position.
329        undoseq = 2, -- Undo state after the change; decreases on undo (see |restore-undo-cursor|).
330      }, evs[#evs])
331      -- Count/register are captured; one event per occurrence.
332      feed('"z2dw')
333      feed('"z2dw')
334      evs = atoms()
335      eq({ keys = '"z2dw', count = 2, reg = 'z' }, pick(evs[#evs], 'keys', 'count', 'reg'))
336      -- Identical occurrences, except `undoseq`: each edit is a new undo state.
337      evs[#evs].undoseq, evs[#evs - 1].undoseq = nil, nil
338      eq(evs[#evs - 1], evs[#evs])
339    end)
340
341    it('complex mapping with edits/motions emits one type=mapping atom', function()
342      -- Split the line at the cursor, ending at the EOL of the first half.
343      command('nnoremap gj i<c-j><esc>k$')
344      fn.setline(1, { 'aaa bbb' })
345      feed('gg04l')
346      atoms_start()
347      feed('gj')
348      eq({ 'aaa ', 'bbb' }, get_lines())
349      -- The mapping commands (insert-session, k, $) accumulate and fold into one CmdAtom, labeled
350      -- with the user-typed LHS; the resolved keys remain the (replayable) payload.
351      local evs = atoms()
352      eq(1, #evs)
353      eq(
354        { type = 'mapping', lhs = 'gj', keys = k('1i<NL><Esc>k$'), changed = true },
355        pick(evs[1], 'type', 'lhs', 'keys', 'changed')
356      )
357      -- The sub-commands are exposed as subatoms.
358      eq({
359        { type = 'insert', keys = k('1i<NL><Esc>') },
360        { type = 'motion', keys = 'k' },
361        { type = 'motion', keys = '$' },
362      }, subatoms(evs[1], 'type', 'keys'))
363      eq({ 'k', false }, { evs[1].atoms[2].cmd, evs[1].atoms[2].changed })
364      -- A scroll inside a mapping is not a subatom: the composite's keys must stay replayable, so
365      -- the scroll is elided.
366      fn.setline(1, { 'l1', 'l2', 'l3', 'l4', 'l5', 'l6' })
367      feed('3G')
368      command('nnoremap gk <C-e>j$')
369      feed('gk')
370      eq(4, fn.line('.'))
371      eq({ type = 'mapping', lhs = 'gk', keys = 'j$' }, pick(atom_last(), 'type', 'lhs', 'keys'))
372      -- A recursive mapping (:nmap gJ gj) does not nest: the inner mapping's commands flatten
373      -- into ONE composite labeled with the typed LHS, with the same resolved keys.
374      command('nmap gJ gj')
375      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa bbb' })
376      feed('gg04l')
377      local before = #atoms()
378      feed('gJ')
379      eq({ 'aaa ', 'bbb' }, get_lines())
380      evs = atoms()
381      eq(before + 1, #evs)
382      eq(
383        { type = 'mapping', lhs = 'gJ', keys = k('1i<NL><Esc>k$') },
384        pick(evs[#evs], 'type', 'lhs', 'keys')
385      )
386    end)
387
388    it('Visual-mode mapping spanning Visual/Normal/Insert is one atom', function()
389      -- Unlike Insert mode, Visual is a MODE_NORMAL mode, so atom_map_start() opens the composite
390      -- up front and it spans every mode the RHS passes through.
391      command('xnoremap q <esc>0lix<esc>l')
392      fn.setline(1, { 'ABCD' })
393      feed('gg0')
394      atoms_start()
395      feed('vl')
396      feed('q')
397      local evs = atoms()
398      eq(1, #evs)
399      eq(
400        { type = 'mapping', lhs = 'q', keys = k('vl<Esc>0l1ix<Esc>l') },
401        pick(evs[1], 'type', 'lhs', 'keys')
402      )
403      eq({
404        { type = 'visual', keys = k('vl<Esc>') },
405        { type = 'motion', keys = '0' },
406        { type = 'motion', keys = 'l' },
407        { type = 'insert', keys = k('1ix<Esc>') },
408        { type = 'motion', keys = 'l' },
409      }, subatoms(evs[1], 'type', 'keys'))
410      eq({ 'AxBCD' }, get_lines())
411    end)
412
413    it('mapping that returns to the mode it started in', function()
414      -- The composite closes where the returned-to mode resolves (insert-session end, selection use),
415      -- so the keys typed after the mapping fold into its atom.
416      command('inoremap <F2> <Esc>lli')
417      fn.setline(1, { 'abcdefg' })
418      feed('gg0')
419      atoms_start()
420      feed('iAB<F2>CD<Esc>')
421      local evs = atoms()
422      eq(2, #evs)
423      eq({ type = 'insert', keys = k('1iAB<Esc>') }, pick(evs[1], 'type', 'keys'))
424      -- `lhs` is the trigger plus the keys typed while the composite ran.
425      eq(
426        { type = 'mapping', lhs = k('<F2>CD<Esc>'), keys = k('ll1iCD<Esc>') },
427        pick(evs[2], 'type', 'lhs', 'keys')
428      )
429      eq({ 'ABaCDbcdefg' }, get_lines())
430
431      -- A Normal-mode mapping ending in Insert has the same shape: returning to the starting mode is
432      -- not special, the composite simply spans the session.
433      command('nnoremap <F3> lli')
434      api.nvim_buf_set_lines(0, 0, -1, true, { 'abcdefg' })
435      feed('gg0')
436      local before = #atoms()
437      feed('<F3>CD<Esc>')
438      evs = atoms()
439      eq(before + 1, #evs)
440      eq(
441        { type = 'mapping', lhs = k('<F3>CD<Esc>'), keys = k('ll1iCD<Esc>') },
442        pick(evs[#evs], 'type', 'lhs', 'keys')
443      )
444      eq({ 'abCDcdefg' }, get_lines())
445
446      -- Visual round-trip: selection is pending at mapping end, keeps the composite open.
447      command('xnoremap <F4> <Esc>jvl')
448      api.nvim_buf_set_lines(0, 0, -1, true, { 'abcd', 'efgh' })
449      feed('gg0')
450      before = #atoms()
451      feed('vl<F4>')
452      eq(before, #atoms())
453      feed('d')
454      evs = atoms()
455      eq(before + 1, #evs)
456      eq(
457        { type = 'mapping', lhs = k('<F4>d'), keys = k('vl<Esc>jvld') },
458        pick(evs[#evs], 'type', 'lhs', 'keys')
459      )
460      eq({
461        { type = 'visual', keys = k('vl<Esc>') },
462        { type = 'motion', keys = 'j' },
463        { type = 'visual', keys = 'vld' },
464      }, subatoms(evs[#evs], 'type', 'keys'))
465      eq({ 'abcd', 'eh' }, get_lines())
466    end)
467
468    it('Cmdline mapping captures Normal-mode tail', function()
469      -- Cmdline-mode is non-MODE_NORMAL, so atom_map_start() defers the composite.
470      command('cnoremap <F2> <C-c>x')
471      fn.setline(1, { 'ABCD' })
472      feed('gg0')
473      atoms_start()
474      feed(':')
475      feed('<F2>')
476      -- "x" resolves to its builtin translation "dl"; `lhs` is still the user input.
477      eq(
478        { { type = 'operator', lhs = k('<F2>'), keys = 'dl' } },
479        atoms_tail(1, 'type', 'lhs', 'keys')
480      )
481      eq({ 'BCD' }, get_lines())
482
483      -- A mapping that stays in the cmdline opens no composite: the accepted cmdline is the atom,
484      -- labeled with the cmdline rather than the LHS.
485      command('cnoremap <F3> echo 1')
486      local before = #atoms()
487      feed(':<F3><CR>')
488      eq(before + 1, #atoms())
489      eq(
490        { { type = 'excmd', lhs = ':echo 1\n', keys = ':echo 1\n' } },
491        atoms_tail(1, 'type', 'lhs', 'keys')
492      )
493    end)
494
495    it('Terminal-mode mapping captures Normal-mode tail', function()
496      -- Terminal-mode is non-MODE_NORMAL, so atom_map_start() defers the composite.
497      command('terminal')
498      command('tnoremap <F2> <C-\\><C-n>gg')
499      atoms_start()
500      feed('i') -- Enter Terminal-mode.
501      feed('<F2>')
502      eq({
503        { type = 'normal', lhs = 'i', keys = 'i' },
504        { type = 'jump', lhs = k('<F2>'), keys = 'gg' }, -- Labeled with the mapping.
505      }, atoms_tail(2, 'type', 'lhs', 'keys'))
506      eq('nt', api.nvim_get_mode().mode)
507
508      -- RHS returning to Terminal mode. The trailing "i" is not captured, unlike the typed "i".
509      command([[tnoremap <F3> <C-\><C-n>ggi]])
510      local before = #atoms()
511      feed('i')
512      feed('<F3>')
513      -- Only the typed "i" and the motion: the RHS's trailing "i" is captured as nothing.
514      eq(before + 2, #atoms())
515      eq({
516        { type = 'normal', lhs = 'i', keys = 'i' },
517        { type = 'jump', lhs = k('<F3>'), keys = 'gg' },
518      }, atoms_tail(2, 'type', 'lhs', 'keys'))
519      eq('t', api.nvim_get_mode().mode)
520    end)
521
522    it('":call" payload mapping appends payload to `keys`', function()
523      n.exec(t_atom.delsurround_vim)
524      fn.setline(1, { 'a (one)', 'b (two)' })
525      feed('gg0f(')
526      atoms_start()
527      feed('ds)') -- ")" is the getchar()'d payload
528      eq({ 'a one', 'b (two)' }, get_lines())
529      local ev = atom_last()
530      -- getchar() payload is appended to `keys`, replayable.
531      eq({ lhs = 'ds)', keys = ':call DelSurround()\n)' }, pick(ev, 'lhs', 'keys'))
532      feed('2G0f(')
533      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
534      eq({ 'a one', 'b two' }, get_lines())
535
536      -- input() payload is appended to `keys`, replayable.
537      n.exec([[
538        function! Suffix() abort
539          call setline('.', getline('.') .. input('suffix: '))
540        endfunction
541        nnoremap ,s :<C-U>call Suffix()<CR>
542      ]])
543      feed('gg')
544      feed(',sX<CR>')
545      n.poke_eventloop()
546      eq('a oneX', fn.getline(1))
547      ev = atom_last()
548      eq({ lhs = k(',sX<CR>'), keys = ':call Suffix()\nX\r' }, pick(ev, 'lhs', 'keys'))
549      feed('j')
550      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
551      eq('b twoX', fn.getline(2))
552
553      -- Operator-pending mapping (:omap custom motion, like vim-sneak "z") fully captured.
554      n.exec(t_atom.minisneak_vim)
555      api.nvim_buf_set_lines(0, 0, -1, true, { 'aa (x) here', 'bb (y) here' })
556      feed('gg0')
557      n.poke_eventloop()
558      feed('dzhe')
559      n.poke_eventloop()
560      eq('here', fn.getline(1))
561      ev = atom_last()
562      eq(
563        { type = 'operator', operator = 'd', lhs = 'dzhe', keys = 'd:call MiniSneak()\nhe' },
564        pick(ev, 'type', 'operator', 'lhs', 'keys')
565      )
566      feed('j0')
567      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
568      eq('here', fn.getline(2))
569
570      -- An :omap that abandons the operator is still one replayable atom.
571      command('onoremap <F2> <Esc>x')
572      api.nvim_buf_set_lines(0, 0, -1, true, { 'abcd' })
573      feed('gg0')
574      local before = #atoms()
575      feed('d<F2>')
576      -- The typed "d" is part of the composite atom.
577      eq(before + 1, #atoms())
578      eq(
579        { { type = 'mapping', lhs = k('d<F2>'), keys = k('<Esc>dl') } },
580        atoms_tail(1, 'type', 'lhs', 'keys')
581      )
582      eq({ 'bcd' }, get_lines())
583
584      -- Burst input ("f(" and the mapping arrive together): "f" peeks for a composing char with
585      -- mappings enabled, so "ds" resolves while "f(" is still executing. The motion is still its
586      -- own atom, and the K_IGNORE left by the peek stays out of `lhs`.
587      api.nvim_buf_set_lines(0, 0, -1, true, { 'a (one)' })
588      feed('gg0')
589      n.poke_eventloop()
590      feed('f(ds)')
591      eq({ 'a one' }, get_lines())
592      eq({
593        { type = 'motion', keys = 'f(', lhs = 'f(' },
594        { type = 'excmd', keys = ':call DelSurround()\n)', lhs = 'ds)' },
595      }, atoms_tail(2, 'type', 'keys', 'lhs'))
596
597      -- Same, mid-op ("t(" + "ds" in one batch): the next mapping is not the pending op's operand.
598      command('nnoremap ,D d')
599      api.nvim_buf_set_lines(0, 0, -1, true, { 'a x(one)' })
600      feed('gg0')
601      n.poke_eventloop()
602      feed(',Dt(ds)')
603      eq({ 'one' }, get_lines())
604      eq({
605        { type = 'operator', keys = 'dt(', lhs = ',Dt(' },
606        { type = 'excmd', keys = ':call DelSurround()\n)', lhs = 'ds)' },
607      }, atoms_tail(2, 'type', 'keys', 'lhs'))
608    end)
609
610    it('replay of deleted/redefined Lua mapping fails (E5117)', function()
611      n.exec_lua([[
612        vim.keymap.set('o', 'gt', function()
613          vim.cmd('normal! viw')
614        end)
615      ]])
616      fn.setline(1, { 'k1 k2', 'k3 k4' })
617      atoms_start()
618      feed('gg0dgt')
619      eq(' k2', fn.getline(1))
620      local ev = atom_last()
621      n.exec_lua([[
622        vim.keymap.del('o', 'gt')
623        vim.keymap.set('o', 'gt', function()
624          vim.cmd('normal! viw')
625        end)
626      ]])
627      feed('j0')
628      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
629      eq('k3 k4', fn.getline(2))
630      t.matches('E5117', fn.execute('messages'))
631      -- Running the (re-defined) mapping emits CmdAtom.keys with the updated id.
632      feed('dgt')
633      eq(' k4', fn.getline(2))
634      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(atom_last().keys))
635      eq('k4', fn.getline(2))
636    end)
637
638    it('temporary mapping ("submode"), expired by the next unrelated atom', function()
639      n.exec_lua([==[
640        local active = false
641        vim.api.nvim_create_autocmd('CmdAtom', {
642          callback = function(ev)
643            -- `cmd` is a key-notation name (unlike `keys`, which is raw bytes).
644            local resize = ev.data.cmd == '<C-W>+' or ev.data.cmd == '<C-W>-'
645            if resize then
646              -- Activate. Use of "+"/"-" resolves to the same cmd => re-activates.
647              vim.keymap.set('n', '+', '<C-w>+')
648              vim.keymap.set('n', '-', '<C-w>-')
649              active = true
650            elseif active then
651              vim.keymap.del('n', '+')
652              vim.keymap.del('n', '-')
653              active = false
654            end
655          end,
656        })
657        -- Also works if <c-w>+ was mapped to something else:
658        vim.cmd[[nnoremap <leader>+ <c-w>+]]
659      ]==])
660      --- Waits for the deferred CmdAtom to (de)activate the temporary mappings.
661      local function wait_active(active)
662        eq(
663          true,
664          n.exec_lua(
665            [[
666              local active = ...
667              return vim.wait(1000, function()
668                return (vim.fn.maparg('+', 'n') ~= '') == active
669              end)
670            ]],
671            active
672          )
673        )
674      end
675      fn.setline(1, { 'one', 'two' })
676      command('split')
677      local height = fn.winheight(0)
678      feed('<C-w>+')
679      wait_active(true) -- the deferred CmdAtom activated the mappings
680      eq(height + 1, fn.winheight(0))
681      feed('+') -- temporary mapping: resizes without the CTRL-W prefix
682      n.poke_eventloop()
683      eq(height + 2, fn.winheight(0))
684      feed('-') -- its own use emits the same resolved keys: stays active
685      n.poke_eventloop()
686      eq(height + 1, fn.winheight(0))
687      feed('j') -- any unrelated atom expires the mappings
688      wait_active(false)
689      feed('-') -- back to the builtin: a motion (up one line), not a resize
690      n.poke_eventloop()
691      eq(height + 1, fn.winheight(0))
692      eq(1, fn.line('.'))
693      -- A mapping whose atom RESOLVES to a resize also activates the submode.
694      feed('\\+')
695      n.poke_eventloop()
696      eq(height + 2, fn.winheight(0))
697      wait_active(true)
698    end)
699  end)
700
701  describe('insert-mode', function()
702    it('session captures its text', function()
703      fn.setline(1, { 'aaa' })
704      feed('gg0')
705      atoms_start()
706      -- No event for the "i" entry, and none per keystroke: one whole-session event at <Esc>.
707      feed('i')
708      eq(0, #atoms())
709      feed('X')
710      eq(0, #atoms())
711      feed('Y')
712      eq(0, #atoms())
713      feed('<Esc>')
714      local evs = atoms()
715      eq(1, #evs)
716      -- Insert keys always embed count ("1i…"). "dw" omits its count.
717      eq(
718        { type = 'insert', count = 1, text = 'XY', keys = k('1iXY<Esc>') },
719        pick(evs[1], 'type', 'count', 'text', 'keys')
720      )
721      -- Counted insert: entry cmd + text + <Esc> keys.
722      feed('3iZ<Esc>')
723      eq({ type = 'insert', count = 3, text = 'Z' }, pick(atom_last(), 'type', 'count', 'text'))
724    end)
725
726    it('mapping captures Normal-mode tail #41864', function()
727      -- Insert-mode is non-MODE_NORMAL, so atom_map_start() defers the composite.
728
729      -- "inoremap <Esc> <Esc>l": <Esc> ends the session; the trailing "l" runs in Normal mode.
730      command('inoremap <Esc> <Esc>l')
731      fn.setline(1, { 'echo hi' })
732      feed('W') -- column 5
733      atoms_start()
734      feed('i<Esc>')
735      -- Two atoms: (empty) insert session, then the mapping tail ("l").
736      local evs = atoms()
737      eq(2, #evs)
738      eq({ type = 'insert', keys = k('1i<Esc>') }, pick(evs[1], 'type', 'keys'))
739      eq({ type = 'motion', lhs = k('<Esc>'), keys = 'l' }, pick(evs[2], 'type', 'lhs', 'keys'))
740      -- The tail moved the cursor right (column 5), overriding the default leftward "<Esc>".
741      eq({ 1, 5 }, api.nvim_win_get_cursor(0))
742
743      -- Same shape when the session is not empty: the tail is independent of the session's text.
744      fn.setline(1, { 'echo hi' })
745      feed('gg0W') -- column 5 again
746      local before = #atoms() -- a second atoms_start() would double-register the collector
747      feed('iZZ<Esc>')
748      evs = atoms()
749      eq(before + 2, #evs)
750      eq(
751        { type = 'insert', keys = k('1iZZ<Esc>'), text = 'ZZ' },
752        pick(evs[#evs - 1], 'type', 'keys', 'text')
753      )
754      eq({ type = 'motion', lhs = k('<Esc>'), keys = 'l' }, pick(evs[#evs], 'type', 'lhs', 'keys'))
755      eq({ 'echo ZZhi' }, get_lines())
756      eq({ 1, 7 }, api.nvim_win_get_cursor(0))
757    end)
758
759    it('crazy mapping captured as type=insert + type=mapping', function()
760      -- The RHS leaves Insert mode, then runs motions and further insert sessions.
761      command('inoremap x ....<esc>0laa..<esc>ab<space><space><esc>hic<esc>')
762      fn.setline(1, { 'AB' })
763      feed('gg0')
764      atoms_start()
765      feed('ix')
766      local evs = atoms()
767      eq(2, #evs)
768      -- The insert-session (interrupted by the mapping) is a `type=insert` atom.
769      eq(
770        { type = 'insert', keys = k('1i....<Esc>'), text = ('.'):rep(4) },
771        pick(evs[1], 'type', 'keys', 'text')
772      )
773      -- The tail of the mapping (which started in insert-mode...) is a `type=mapping` atom.
774      eq({
775        type = 'mapping',
776        lhs = 'x',
777        keys = k('0l1aa..<Esc>1ab  <Esc>h1ic<Esc>'),
778      }, pick(evs[2], 'type', 'lhs', 'keys'))
779      -- Composite subatoms:
780      eq({
781        { type = 'motion', keys = '0' },
782        { type = 'motion', keys = 'l' },
783        { type = 'insert', keys = k('1aa..<Esc>') },
784        { type = 'insert', keys = k('1ab  <Esc>') },
785        { type = 'motion', keys = 'h' },
786        { type = 'insert', keys = k('1ic<Esc>') },
787      }, subatoms(evs[2], 'type', 'keys'))
788      eq({ ('..a..bc  %sAB'):format(('.'):rep(2)) }, get_lines())
789    end)
790
791    it('insert-session entered programmatically, still captures *user* input #41516', function()
792      atoms_start()
793      n.exec_lua([[
794        vim.keymap.set('i', '<C-j>', function()
795          vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes('<Esc>', true, false, true), 'n', false)
796          vim.schedule(function()
797            vim.api.nvim_feedkeys('i', 'n', false)
798          end)
799        end)
800      ]])
801      local before = #atoms()
802      feed('i')
803      n.exec_lua('vim.wait(50)')
804      feed('<C-j>')
805      n.exec_lua('vim.wait(50)')
806      feed('<Esc>')
807      local evs = atoms()
808      eq(before + 2, #evs)
809      eq({ k('1i<Esc>'), k('1i<Esc>') }, { evs[#evs - 1].keys, evs[#evs].keys })
810      -- Typed text within such a session lands in its atom...
811      n.exec_lua([[vim.schedule(function() vim.api.nvim_feedkeys('i', 'n', false) end)]])
812      n.exec_lua('vim.wait(50)')
813      feed('hi<Esc>')
814      eq({ text = 'hi', keys = k('1ihi<Esc>') }, pick(atom_last(), 'text', 'keys'))
815      -- ...but with NO typed input within it, the session emits nothing.
816      before = #atoms()
817      n.exec_lua([[vim.schedule(function() vim.api.nvim_feedkeys('i', 'n', false) end)]])
818      n.exec_lua('vim.wait(50)')
819      n.exec_lua([[vim.api.nvim_feedkeys('\27', 'n', false)]])
820      eq(before, #atoms())
821    end)
822  end)
823
824  describe('visual', function()
825    it('replay; fallback to equal-size if unreplayable', function()
826      -- The core use-case for a plugin: observe CmdAtom, capture a Visual-mode
827      -- operation's resolved `keys`, and replay them verbatim to re-execute it.
828      fn.setline(1, { 'foo bar', 'longword bar' })
829      feed('gg0')
830      atoms_start()
831      feed('viwd') -- select the inner word and delete it
832      eq({ ' bar', 'longword bar' }, get_lines())
833      local ev = atom_last()
834      eq('visual', ev.type)
835
836      -- Replay the captured keys at line 2. The keysequence re-executes (not equal-size reselect):
837      -- "iw" selects cursor-relative word, so the delete adapts to the new context.
838      feed('j0')
839      n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
840      eq({ ' bar', ' bar' }, get_lines())
841
842      -- A viewport scroll that drags the cursor along (edge/'scrolloff') grows the selection by
843      -- a viewport-dependent amount: void, no atom.
844      local lines = vim.tbl_map(function(i)
845        return 'l' .. i
846      end, fn.range(1, 30))
847      fn.setline(1, lines)
848      feed('gg')
849      local before = #atoms()
850      feed('V<C-e>')
851      eq(2, fn.line('.')) -- Scroll dragged the cursor: selection is lines 1-2.
852      feed('d')
853      -- Publishes with empty `CmdAtom.keys`; the keys that produced it are in `lhs`.
854      eq(before + 1, #atoms())
855      eq(
856        { type = 'visual', keys = '', lhs = k('V<C-E>d'), changed = true },
857        pick(atom_last(), 'type', 'keys', 'lhs', 'changed')
858      )
859      eq('l3', fn.getline(1)) -- The edit itself deleted both selected lines.
860
861      -- "." on the unreplayable operation falls back to equal-size reselect ("1v" + op).
862      feed('.')
863      eq('l5', fn.getline(1))
864
865      -- But a viewport key that preserves cursor ("zz") does not move the selection: still
866      -- replayable, and collected like any other subatom.
867      fn.setline(1, lines)
868      feed('gg')
869      before = #atoms()
870      feed('Vzzd')
871      eq('l2', fn.getline(1))
872      eq(before + 1, #atoms())
873      -- Nothing was translated, so lhs=keys.
874      eq({ type = 'visual', keys = 'Vzzd', lhs = 'Vzzd' }, pick(atom_last(), 'type', 'keys', 'lhs'))
875      feed('.')
876      eq('l3', fn.getline(1))
877
878      --
879      -- Visual selection moved by a Lua mapping (via API): captured as the mapping cmd. #41956
880      --
881      n.exec_lua(function()
882        vim.keymap.set('x', 'gh', function()
883          local cursor = vim.api.nvim_win_get_cursor(0)
884          vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 1 })
885          vim.cmd('normal! o')
886          vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 3 })
887        end)
888      end)
889      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaaaaa', 'bbb' })
890      feed('gg0vghd')
891      eq('aaaa', fn.getline(1))
892      eq('visual', atom_last().type)
893      feed('j0.')
894      eq('b', fn.getline(2)) -- The API move clamps on the short line; "1v" would have emptied it.
895      -- Also when only the fed key follows the API move: "o" alone would replay a 1-char selection.
896      -- Defined >=10 times: at least 1 mapping-id ends in "0" (exercises redobuf encoding...).
897      for _ = 1, 10 do
898        n.exec_lua(function()
899          vim.keymap.set('x', 'gH', function()
900            local cursor = vim.api.nvim_win_get_cursor(0)
901            vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 1 })
902            vim.cmd('normal! o')
903          end)
904        end)
905        api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaaaaa', 'bbbbbbb' })
906        feed('gg0vgHd')
907        eq('aaaaa', fn.getline(1))
908        feed('j0.')
909        eq('bbbbb', fn.getline(2))
910      end
911      -- A fed "gv" reselects marks the mapping set.
912      n.exec_lua(function()
913        vim.keymap.set('x', 'gs', function()
914          local row, col = unpack(vim.api.nvim_win_get_cursor(0))
915          vim.fn.setpos("'<", { 0, row, col + 1, 0 })
916          vim.fn.setpos("'>", { 0, row, vim.fn.col('$') - 1, 0 })
917          vim.cmd.normal({ 'gv', bang = true })
918        end)
919      end)
920      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaaaaa', 'bbbbbbbbbb' })
921      feed('gg0vgsd')
922      eq('', fn.getline(1))
923      feed('j0.')
924      eq('', fn.getline(2)) -- To end of line again; "1v" would have left 3 chars.
925
926      -- Textobject mapping that ends selection and reselects by "norm! <linenr>GV…". #41754
927      n.exec_lua(function()
928        vim.keymap.set('x', '<M-m>', function()
929          local cur_line = vim.fn.line('.')
930          vim.cmd('normal! \27')
931          vim.cmd(('normal! %dGV%dG'):format(cur_line, 2 * cur_line))
932        end)
933      end)
934      api.nvim_buf_set_lines(0, 0, -1, true, { '1', '2', '3', '4', '5', '6', '7', '8' })
935      feed('ggv<M-m>d')
936      eq({ '3', '4', '5', '6', '7', '8' }, get_lines())
937      feed('j.')
938      eq({ '3', '7', '8' }, get_lines())
939
940      -- "gv" is replayable, but "." redoes a fixed-size region ("1v"), like Vim.
941      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa bbb ccc' })
942      feed('gg0viw<Esc>')
943      before = #atoms()
944      feed('gvd')
945      eq(' bbb ccc', fn.getline(1))
946      eq(before + 1, #atoms())
947      eq({ type = 'visual', keys = 'gvd', lhs = 'gvd' }, pick(atom_last(), 'type', 'keys', 'lhs'))
948      feed('w.') -- "." containing "gv" replays "1v" fallback at the cursor ("bbb").
949      eq('  ccc', fn.getline(1))
950      -- Visual-entered Insert. The atom has "gv" (as typed), not redo's "1v" fallback.
951      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa bbb ccc' })
952      feed('gg0viw<Esc>')
953      before = #atoms()
954      feed('gvcX<Esc>')
955      eq('X bbb ccc', fn.getline(1))
956      eq(before + 1, #atoms())
957      eq({ type = 'visual', keys = k('gvcX<Esc>') }, pick(atom_last(), 'type', 'keys'))
958      feed('w.')
959      eq('X X ccc', fn.getline(1))
960
961      -- A fed (":normal!") Visual-put preps the selection keysequence, like any fed visual
962      -- operator (":normal! vjd"): "." re-executes "Vjp", not a bare "p".
963      api.nvim_buf_set_lines(0, 0, -1, true, { 'aa', 'bb', 'cc', 'dd', 'ee' })
964      feed('ggyy')
965      command('normal! Vjp')
966      eq({ 'aa', 'cc', 'dd', 'ee' }, get_lines())
967      feed('j.')
968      eq({ 'aa', 'aa', 'bb', 'ee' }, get_lines())
969
970      -- {Visual}r<C-V><CR> replaces with a literal <CR> (REPLACE_CR_NCHAR): inexpressible as
971      -- spec chars, so the literal keys compose the redo tail, which "." replays.
972      api.nvim_buf_set_lines(0, 0, -1, true, { 'abcd', 'efgh' })
973      feed('gg0vlr<C-V><CR>')
974      eq({ '\r\rcd', 'efgh' }, get_lines())
975      feed('j0.')
976      eq({ '\r\rcd', '\r\rgh' }, get_lines())
977
978      -- <Cmd> ":norm" mapping that extends the selection: "." replays it. #41323
979      command('xmap <M-m> <Cmd>normal! $<CR>')
980      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa', 'bbb' })
981      feed('gg0v<M-m>d') -- "$" in Visual is one past EOL, so "d" swallows the newline (= plain v$d)
982      eq({ 'bbb' }, get_lines())
983      command('let v:errmsg = ""')
984      feed('.')
985      eq('', api.nvim_get_vvar('errmsg'))
986      eq('n', fn.mode()) -- Not in Visual.
987      eq({ '' }, get_lines())
988
989      -- <Cmd> ":norm" captured as itself (not its subatoms).
990      command('xmap <M-w> <Cmd>normal! e<CR>')
991      api.nvim_buf_set_lines(0, 0, -1, true, { 'one two three', 'four five six' })
992      feed('gg0v<M-w>d')
993      eq({ ' two three', 'four five six' }, get_lines())
994      eq({ type = 'visual', keys = k('v<Cmd>normal! e<NL>d') }, pick(atom_last(), 'type', 'keys'))
995      feed('j0.')
996      eq({ ' two three', ' five six' }, get_lines())
997
998      -- Nested command can replace the pending selection, not just extend it. #41705
999      n.exec_lua(function()
1000        vim.keymap.set('x', 'Z', function()
1001          -- Mapping ends with the selection "open".
1002          vim.cmd.normal({ vim.keycode('<Esc>viW'), bang = true })
1003        end)
1004      end)
1005      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo.bar tail' })
1006      feed('gg0')
1007      command('normal viwZ')
1008      feed('d')
1009      eq({ ' tail' }, get_lines())
1010      eq({ type = 'visual', keys = 'viWd' }, pick(atom_last(), 'type', 'keys'))
1011
1012      -- Buffer-editing <Cmd> is captured as itself.
1013      command('xmap <M-a> <Cmd>call append(1, "X")<CR>')
1014      api.nvim_buf_set_lines(0, 0, -1, true, { 'ab', 'cd' })
1015      feed('gg0vl<M-a>d')
1016      eq({ '', 'X', 'cd' }, get_lines())
1017      eq(
1018        { type = 'visual', keys = k('vl<Cmd>call append(1, "X")<NL>d') },
1019        pick(atom_last(), 'type', 'keys')
1020      )
1021      feed('3gg0.')
1022      eq({ '', 'X', '' }, get_lines())
1023
1024      -- Search-extended selection: the payload travels in the collected keys.
1025      api.nvim_buf_set_lines(0, 0, -1, true, { 'ab META x', 'cdef META y' })
1026      feed('gg0v/META<CR>d')
1027      eq({ 'ETA x', 'cdef META y' }, get_lines())
1028      eq({ type = 'visual', keys = k('v/META<NL>d') }, pick(atom_last(), 'type', 'keys'))
1029      feed('j0.')
1030      eq({ 'ETA x', 'ETA y' }, get_lines())
1031
1032      -- Excmd that visually-selects. Replaying ":" prefills "'<,'>"; keys place <C-U> internally.
1033      exec([[
1034        func SelectWord()
1035          normal! viw
1036        endfunc
1037      ]])
1038      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo bar', 'longword bar' })
1039      feed('gg0v:<C-U>call SelectWord()<CR>d')
1040      eq({ ' bar', 'longword bar' }, get_lines())
1041      eq(
1042        { type = 'visual', keys = k('v:<C-U>call SelectWord()<NL>d') },
1043        pick(atom_last(), 'type', 'keys')
1044      )
1045      feed('j0.')
1046      eq({ ' bar', ' bar' }, get_lines())
1047
1048      -- Nothing typed a <C-U> here: this ":" keeps the prefilled range.
1049      api.nvim_buf_set_lines(0, 0, -1, true, { 'a xx', 'b xx', 'c xx' })
1050      feed('gg0Vj:s/xx/YY/<CR>')
1051      eq({ 'a YY', 'b YY', 'c xx' }, get_lines())
1052      eq(k("Vj:<C-U>'<,'>s/xx/YY/<NL>"), atom_last().keys)
1053    end)
1054
1055    it('|visual-fixed-size| example in visual.txt', function()
1056      n.exec_lua([[
1057        local vop ---@type string?
1058        vim.api.nvim_create_autocmd('CmdAtom', {
1059          callback = function(ev)
1060            if ev.data.type == 'visual' then
1061              local children = ev.data.atoms
1062              vop = children and children[#children].keys or nil
1063            elseif ev.data.changed then
1064              vop = nil  -- the last change is no longer the Visual one
1065            end
1066          end,
1067        })
1068        vim.keymap.set('n', '.', function()
1069          vim.schedule(function()
1070            vim.api.nvim_feedkeys(vop and ('1v' .. vop) or '.', 'n', false)
1071          end)
1072        end)
1073      ]])
1074      fn.setline(1, { 'foo bar', 'longword bar' })
1075      feed('gg0viwd')
1076      eq({ ' bar', 'longword bar' }, get_lines())
1077      -- Equal-size repeat: a 3-char region at the cursor, NOT that line's word.
1078      feed('j0.')
1079      retry(nil, 1000, function()
1080        eq({ ' bar', 'gword bar' }, get_lines())
1081      end)
1082      -- A non-visual change falls back to the builtin |.|.
1083      feed('gg0x')
1084      eq({ 'bar', 'gword bar' }, get_lines())
1085      feed('j0.')
1086      retry(nil, 1000, function()
1087        eq({ 'bar', 'word bar' }, get_lines())
1088      end)
1089    end)
1090  end)
1091
1092  describe('repeat.txt examples', function()
1093    it('|action-repeat|', function()
1094      n.exec_lua([[
1095        _G.saved = nil
1096        vim.api.nvim_create_autocmd('CmdAtom', { callback = function(ev) _G.last = ev.data end })
1097        _G.save = function() _G.saved = _G.last end
1098        _G.replay = function()
1099          local d = _G.saved
1100          vim.api.nvim_feedkeys(d.keys or d.lhs, d.keys and 'n' or 'm', false)
1101        end
1102      ]])
1103      n.exec(t_atom.delsurround_vim)
1104      command('nnoremap ,d x')
1105      command('nnoremap <F6> xw')
1106      command('let @q = "x"')
1107      n.exec_lua([[
1108        vim.keymap.set('n', ']e', function()
1109          vim.api.nvim_set_current_line(vim.api.nvim_get_current_line() .. '!')
1110        end)
1111      ]])
1112
1113      --- Runs `keys` on line 1, then replays that atom on line 2 (both prefixed by `pre`). Reports
1114      --- the atom's input/resolution pair, whether the resolution decomposes into subatoms, and
1115      --- whether the replay reproduced line 1.
1116      local function both(line, pre, keys)
1117        api.nvim_buf_set_lines(0, 0, -1, true, { line, line })
1118        feed('gg0' .. pre)
1119        n.poke_eventloop()
1120        feed(keys)
1121        n.poke_eventloop()
1122        n.exec_lua('_G.save()')
1123        feed('2G0' .. pre)
1124        n.poke_eventloop()
1125        n.exec_lua('_G.replay()')
1126        n.poke_eventloop()
1127        local l = get_lines()
1128        local d = n.exec_lua('return _G.saved')
1129        local subs = d.atoms
1130          and table.concat(vim.tbl_map(function(c)
1131            return c.keys
1132          end, d.atoms))
1133        return { lhs = d.lhs, keys = d.keys, subs = subs, replayed = l[1] == l[2] }
1134      end
1135
1136      -- Note the symmetry: "x", a mapping to "x", and a macro of "x" all resolve to "dl".
1137      eq({
1138        { lhs = 'dw', keys = 'dw', replayed = true },
1139        { lhs = 'x', keys = 'dl', replayed = true },
1140        { lhs = ',d', keys = 'dl', replayed = true },
1141        { lhs = '@q', keys = 'dl', replayed = true },
1142        { lhs = k('<F6>'), keys = 'dlw', subs = 'dlw', replayed = true },
1143        -- No `keys` (Lua callback): the recipe feeds `lhs` with remapping.
1144        { lhs = ']e', replayed = true },
1145        -- getchar() ")" is appended to `keys`, replayable.
1146        { lhs = 'ds)', keys = ':call DelSurround()\n)', replayed = true },
1147      }, {
1148        both('a one two', '', 'dw'),
1149        both('aaa bbb', '', 'x'),
1150        both('aaa bbb', '', ',d'),
1151        both('aaa bbb', '', '@q'),
1152        both('aaa bbb ccc', '', '<F6>'),
1153        both('a b', '', ']e'),
1154        both('a (one)', 'f(', 'ds)'),
1155      })
1156
1157      -- Repeat fold command ("zf"). #9821
1158      api.nvim_buf_set_lines(0, 0, -1, true, { 'a {', '  x', '}', 'b {', '  y', '}' })
1159      feed('gg0zfa{')
1160      n.poke_eventloop()
1161      n.exec_lua('_G.save()')
1162      eq(
1163        { lhs = 'zfa{', keys = 'zfa{', changed = false, operator = 'zf' },
1164        pick(n.exec_lua('return _G.saved'), 'lhs', 'keys', 'changed', 'operator')
1165      )
1166      feed('zR4gg0') -- open the new fold, move past it
1167      eq(0, fn.foldlevel(4))
1168      n.exec_lua('_G.replay()')
1169      n.poke_eventloop()
1170      eq({ 4, 6 }, { fn.foldclosed(4), fn.foldclosedend(4) }) -- "zf" closes what it creates
1171
1172      -- Unreplayable: a void Visual op has empty keys, so the recipe feeds nothing
1173      -- rather than replaying a viewport-dependent selection.
1174      api.nvim_buf_set_lines(
1175        0,
1176        0,
1177        -1,
1178        true,
1179        vim.tbl_map(function(i)
1180          return 'l' .. i
1181        end, fn.range(1, 30))
1182      )
1183      feed('gg')
1184      feed(k('V<C-e>d'))
1185      n.poke_eventloop()
1186      n.exec_lua('_G.save()')
1187      eq({ keys = '' }, pick(n.exec_lua('return _G.saved'), 'keys'))
1188      local before = get_lines()
1189      n.exec_lua('_G.replay()')
1190      n.poke_eventloop()
1191      eq(before, get_lines())
1192
1193      -- A repeat mapping is an atom too, and absent `keys` sends the recipe back to
1194      -- its own `lhs`: a recorder must skip it, or the repeat replays itself.
1195      n.exec_lua([[vim.keymap.set('n', '<F7>', function() end)]])
1196      feed('<F7>')
1197      n.poke_eventloop()
1198      eq(
1199        { type = 'mapping', lhs = k('<F7>') },
1200        pick(n.exec_lua('return _G.last'), 'type', 'keys', 'lhs')
1201      )
1202    end)
1203
1204    it('|edit-repeat|', function()
1205      n.exec_lua([[
1206        local last ---@type vim.event.cmdatom.data?
1207        vim.api.nvim_create_autocmd('CmdAtom', {
1208          callback = function(ev)
1209            local is_redo_or_undo = ev.data.changed
1210              and (ev.data.undoseq or 0) <= (vim.b[ev.buf].maxseq or 0)
1211            vim.b[ev.buf].maxseq = math.max(vim.b[ev.buf].maxseq or 0, ev.data.undoseq or 0)
1212            if ev.data.changed and not is_redo_or_undo and ev.data.lhs ~= '.' then
1213              last = ev.data
1214            end
1215          end,
1216        })
1217        vim.keymap.set('n', '.', function()
1218          -- Multicursors: degrade to builtin ".", which repeats at each cursor.
1219          local mc = vim.api.nvim_create_namespace('nvim.multicursor')
1220          if #vim.api.nvim_buf_get_extmarks(0, mc, 0, -1, { limit = 1 }) > 0 then
1221            vim.api.nvim_feedkeys('.', 'n', false)
1222            return
1223          end
1224          vim.schedule(function()
1225            if last then
1226              vim.api.nvim_feedkeys(last.keys or last.lhs, last.keys and 'n' or 'm', false)
1227            end
1228          end)
1229        end)
1230      ]])
1231      n.exec(t_atom.delsurround_vim)
1232      fn.setline(1, { 'aa bb', 'a (one)', 'b (two)' })
1233      -- "Builtin" edit.
1234      feed('gg0dw')
1235      n.poke_eventloop()
1236      feed('.')
1237      retry(nil, 1000, function()
1238        eq('', fn.getline(1))
1239      end)
1240      -- Payload mapping: builtin "." could not repeat this (without e.g. vim-repeat).
1241      feed('2G0f(ds)')
1242      n.poke_eventloop()
1243      eq('a one', fn.getline(2))
1244      feed('3G0f(.')
1245      retry(nil, 1000, function()
1246        eq('b two', fn.getline(3))
1247      end)
1248
1249      -- Edit fed by nvim_feedkeys(…, "mt") #41485.
1250      n.exec_lua([[
1251        vim.keymap.set('n', '<M-m>', function()
1252          vim.api.nvim_feedkeys('dl', 'mt', false)
1253        end)
1254      ]])
1255      api.nvim_buf_set_lines(0, 0, -1, true, { 'abcd' })
1256      feed('gg0<M-m>')
1257      n.poke_eventloop()
1258      eq('bcd', fn.getline(1))
1259      feed('.')
1260      retry(nil, 1000, function()
1261        eq('cd', fn.getline(1))
1262      end)
1263
1264      -- Undo is not captured: "." still repeats the edit.
1265      feed('u')
1266      n.poke_eventloop()
1267      eq('bcd', fn.getline(1))
1268      feed('.')
1269      retry(nil, 1000, function()
1270        eq('cd', fn.getline(1))
1271      end)
1272
1273      -- Visual edit: replays the resolved keys, so "iw" selects the cursor-relative word.
1274      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo bar', 'longword bar' })
1275      feed('gg0viwd')
1276      n.poke_eventloop()
1277      feed('j0.')
1278      retry(nil, 1000, function()
1279        eq({ ' bar', ' bar' }, get_lines())
1280      end)
1281      -- Visual change (insert session): selection, operator, text and <Esc> all replay.
1282      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo bar', 'longword bar' })
1283      feed('gg0viwcX<Esc>')
1284      n.poke_eventloop()
1285      feed('j0.')
1286      retry(nil, 1000, function()
1287        eq({ 'X bar', 'X bar' }, get_lines())
1288      end)
1289
1290      -- While multicursor is active, the "." mapping degrades to builtin "." so it cascades.
1291      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa', 'bbb', 'ccc' })
1292      feed('gg0QjQj')
1293      feed('x')
1294      n.poke_eventloop()
1295      eq({ 'aa', 'bb', 'cc' }, api.nvim_buf_get_lines(0, 0, -1, true))
1296      feed('.')
1297      retry(nil, 1000, function()
1298        eq({ 'a', 'b', 'c' }, api.nvim_buf_get_lines(0, 0, -1, true))
1299      end)
1300    end)
1301
1302    it('|motion-repeat|', function()
1303      n.exec_lua([[
1304        local last ---@type string?
1305        vim.api.nvim_create_autocmd('CmdAtom', {
1306          pattern = 'motion',
1307          callback = function(ev)
1308            last = ev.data.keys
1309          end,
1310        })
1311        vim.keymap.set('n', ',', function()
1312          -- CmdAtom delivery is deferred: schedule the replay AFTER any pending
1313          -- event, so `last` is fresh even when "," immediately follows a
1314          -- motion. A scheduled replay is programmatic input: it emits no
1315          -- CmdAtom itself (no feedback loop).
1316          vim.schedule(function()
1317            if last then
1318              vim.api.nvim_feedkeys(last, 'n', false)  -- "n": already resolved
1319            end
1320          end)
1321        end)
1322      ]])
1323      local screen = Screen.new(30, 3)
1324      fn.setline(1, { 'aa bb cc dd ee' })
1325      feed('gg0')
1326      feed('2w') -- last motion: "2w" (count included)
1327      n.poke_eventloop() -- deliver the deferred CmdAtom before ","
1328      screen:expect([[
1329        aa bb ^cc dd ee                |
1330        {1:~                             }|
1331                                      |
1332      ]])
1333      feed(',') -- repeated: "2w" again
1334      screen:expect([[
1335        aa bb cc dd ^ee                |
1336        {1:~                             }|
1337                                      |
1338      ]])
1339      feed('0fb') -- last motion: "fb" (payload char included)
1340      n.poke_eventloop()
1341      screen:expect([[
1342        aa ^bb cc dd ee                |
1343        {1:~                             }|
1344                                      |
1345      ]])
1346      feed(',') -- repeated "fb": the second "b"
1347      screen:expect([[
1348        aa b^b cc dd ee                |
1349        {1:~                             }|
1350                                      |
1351      ]])
1352    end)
1353
1354    it('|restore-undo-cursor|: `pos`, `undoseq` restore across undo', function()
1355      n.exec_lua([[
1356        local seen = {} -- buf -> { prev = <seq>, [seq] = <cursor before that edit> }
1357        vim.api.nvim_create_autocmd('CmdAtom', {
1358          callback = function(ev)
1359            local seq = ev.data.undoseq
1360            if not seq then
1361              return
1362            end
1363            local s = seen[ev.buf] or {}
1364            seen[ev.buf] = s
1365            if s.prev and seq < s.prev and s[seq + 1] then
1366              vim.api.nvim_win_set_cursor(0, s[seq + 1]) -- undid: first state left behind
1367            elseif s.prev and seq > s.prev and s[seq] then
1368              vim.api.nvim_win_set_cursor(0, s[seq]) -- redid: a seq we already have
1369            elseif ev.data.changed and not s[seq] then
1370              s[seq] = ev.data.pos -- new edit
1371            end
1372            s.prev = seq
1373          end,
1374        })
1375      ]])
1376      command('nnoremap <F8> u')
1377      --- Puts the cursor at `pre`, edits, then undoes via `undo`. Reports the
1378      --- column before the edit and after the undo: they must match.
1379      local function undone(pre, edit, undo)
1380        api.nvim_buf_set_lines(0, 0, -1, true, { 'this is a test' })
1381        n.poke_eventloop()
1382        feed('gg0' .. pre)
1383        n.poke_eventloop()
1384        local before = fn.col('.')
1385        feed(edit)
1386        n.poke_eventloop()
1387        -- Drained between steps: batched atoms would deliver the undo's restore
1388        -- only after the redo already ran.
1389        for _, step in ipairs(type(undo) == 'table' and undo or { undo }) do
1390          if step:sub(1, 1) == ':' then
1391            command(step:sub(2))
1392          else
1393            feed(step)
1394          end
1395          n.poke_eventloop()
1396        end
1397        return { before, fn.col('.') }
1398      end
1399      -- "a"/"o" enter Insert AFTER moving the cursor, so the session's `pos` must
1400      -- come from the command frame, not from where the entry command landed.
1401      -- The last five need `undoseq`: they are not recognizable from the keys.
1402      eq(
1403        { { 4, 4 }, { 4, 4 }, { 4, 4 }, { 7, 7 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 } },
1404        {
1405          undone('lll', 'diw', 'u'),
1406          undone('lll', 'aXY<Esc>', 'u'),
1407          undone('lll', 'oXY<Esc>', 'u'),
1408          undone('llllll', 'd^', 'u'),
1409          undone('lll', 'diw', '<F8>'), -- mapping to undo
1410          undone('lll', 'diwwdawdaw', '3u'), -- count
1411          undone('lll', 'diwwdaw', ':undo 1'),
1412          undone('lll', 'diw', 'g-'),
1413          undone('lll', 'diw', { 'u', '0', '<C-r>' }), -- redo, after moving away
1414        }
1415      )
1416    end)
1417  end)
1418
1419  it('motions, search, excmd emit without an edit', function()
1420    -- Emission is not tied to editing: every user action emits, so
1421    -- plugins can observe all activity.
1422    fn.setline(1, { 'alpha beta', 'gamma delta' })
1423    feed('gg0')
1424    atoms_start()
1425    feed('w')
1426    feed('3l')
1427    feed('/gamma<CR>')
1428    feed(':nohlsearch<CR>')
1429    eq({
1430      { type = 'motion', keys = 'w' },
1431      { type = 'motion', keys = '3l' },
1432      { type = 'motion', keys = k('/gamma<NL>') },
1433      { type = 'excmd', keys = k(':nohlsearch<NL>') },
1434    }, atoms_tail(4, 'type', 'keys'))
1435
1436    -- Cursor-relative marks ('< '. '{ …) are classified as type=motion. Other marks are type=jump.
1437    feed('ma')
1438    feed('`.')
1439    feed("'[")
1440    feed('`{')
1441    feed('g`.')
1442    feed('`a')
1443    feed("g'a")
1444    feed('G')
1445    eq({
1446      { type = 'motion', keys = '`.' },
1447      { type = 'motion', keys = "'[" },
1448      { type = 'motion', keys = '`{' },
1449      { type = 'motion', keys = 'g`.' },
1450      { type = 'jump', keys = '`a' },
1451      { type = 'jump', keys = "g'a" },
1452      { type = 'jump', keys = 'G' },
1453    }, atoms_tail(7, 'type', 'keys'))
1454
1455    -- ":" embeds its count as the range prefill, never as composed digits;
1456    -- the count field carries it.
1457    feed('gg')
1458    feed('2:<CR>')
1459    eq(2, fn.line('.'))
1460    eq(
1461      { type = 'excmd', keys = k(':.,.+1<NL>'), count = 2, cmd = ':' },
1462      pick(atom_last(), 'type', 'keys', 'count', 'cmd')
1463    )
1464    eq({ 'alpha beta', 'gamma delta' }, get_lines()) -- nothing was edited
1465    -- Scrolls and mouse presses also emit (type "scroll"/"mouse"): emit-only,
1466    -- never cascaded.
1467    feed('<C-e>')
1468    feed('3<C-y>')
1469    api.nvim_input_mouse('wheel', 'up', '', 0, 0, 0)
1470    api.nvim_input_mouse('left', 'press', '', 0, 1, 2)
1471    eq({
1472      { type = 'scroll', keys = k('<C-E>') },
1473      { type = 'scroll', keys = k('3<C-Y>') },
1474      { type = 'scroll', keys = k('<ScrollWheelUp>') },
1475      { type = 'mouse', keys = k('<LeftMouse>') },
1476    }, atoms_tail(4, 'type', 'keys'))
1477    eq(2, fn.line('.')) -- the click moved the cursor
1478    -- <amatch>/match is the atom type, never path-expanded.
1479    n.exec_lua([[
1480      vim.api.nvim_create_autocmd('CmdAtom', {
1481        callback = function(ev)
1482          _G.last_match = ev.match
1483        end,
1484      })
1485    ]])
1486    feed('0w')
1487    n.poke_eventloop()
1488    eq('motion', n.exec_lua('return _G.last_match'))
1489  end)
1490
1491  it('captures counts, payload', function()
1492    fn.setline(1, { 'abcd,ef' })
1493    feed('gg0')
1494    atoms_start()
1495    feed('yw')
1496
1497    -- A yank emits but does not edit.
1498    eq({ operator = 'y', changed = false }, pick(atom_last(), 'operator', 'changed'))
1499    feed('3x')
1500    eq({ 'd,ef' }, get_lines())
1501    feed('vf,d')
1502    eq({ 'ef' }, get_lines())
1503    eq({ '3dl', 'vf,d' }, atoms_tail(2))
1504
1505    -- Structured decomposition: operator/motion/operand as fields, no byte-parsing.
1506    local op = atoms()[#atoms() - 1] -- "3dl"
1507    eq(
1508      { operator = 'd', cmd = 'l', count = 3, changed = true },
1509      pick(op, 'operator', 'cmd', 'cmdarg', 'count', 'motionforce', 'changed')
1510    )
1511
1512    -- A visual atom carries the completing operator's fields, and decomposes
1513    -- into its commands ("v", "f," and the operator).
1514    local vis = atom_last() -- "vf,d"
1515    eq({ type = 'visual', operator = 'd' }, pick(vis, 'type', 'operator'))
1516    eq({
1517      { keys = 'v', cmd = 'v', changed = false },
1518      { keys = 'f,', cmd = 'f', cmdarg = ',', changed = false },
1519      { keys = 'd', changed = true }, -- the completing operator did the edit
1520    }, subatoms(vis, 'keys', 'cmd', 'cmdarg', 'changed'))
1521    eq('d', vis.atoms[3].operator)
1522
1523    -- Operators with an interactively-typed search payload: the atom is the
1524    -- redobuff, which includes the payload.
1525    fn.setline(1, { 'aa END bb' })
1526    feed('gg0')
1527    feed('d/END<CR>')
1528    eq({ 'END bb' }, get_lines())
1529    eq({ k('d/END<NL>') }, atoms_tail(1))
1530    eq(
1531      { operator = 'd', cmd = '/', changed = true },
1532      pick(atom_last(), 'operator', 'cmd', 'changed')
1533    )
1534
1535    -- An operand (mark or register name, target char) is its own field; the second char of a
1536    -- two-char command NAME ("gJ") composes into `cmd`.
1537    fn.setline(1, { 'one', 'two' })
1538    feed('gg0magJ')
1539    eq({ 'onetwo' }, get_lines()) -- "gJ": join without inserting a space
1540    eq({ cmd = 'm', cmdarg = 'a' }, pick(atoms()[#atoms() - 1], 'cmd', 'cmdarg'))
1541    eq({ cmd = 'gJ' }, pick(atom_last(), 'cmd', 'cmdarg'))
1542    local nrec = #atoms()
1543    feed('qax') -- the recording register is an operand, not part of the name
1544    feed('q')
1545    eq({ cmd = 'q', cmdarg = 'a' }, pick(atoms()[nrec + 1], 'cmd', 'cmdarg'))
1546
1547    -- Forced motion type ("dvj") is a field.
1548    fn.setline(1, { 'one', 'two' })
1549    feed('gg0dvj')
1550    eq(
1551      { operator = 'd', motionforce = 'v', cmd = 'j' },
1552      pick(atom_last(), 'operator', 'motionforce', 'cmd')
1553    )
1554  end)
1555
1556  it('"!" operator captures its stuffed cmdline', function()
1557    -- ":.,.+1!" + typed "{prg}<CR>" completes the operator atom, like "d/END<CR>". #41447
1558    local prg = n.testprg('shell-test') .. ' REP 2 X'
1559    fn.setline(1, { 'b', 'a', '', 'e', 'c', 'd' })
1560    atoms_start()
1561    feed('gg')
1562    feed(('!ip%s<CR>'):format(prg))
1563    eq({ '0: X', '1: X', '', 'e', 'c', 'd' }, get_lines())
1564    local bang = atom_last()
1565    local keys = ('!ip%s\n'):format(prg)
1566    eq(
1567      { type = 'operator', operator = '!', lhs = keys, keys = keys },
1568      pick(bang, 'type', 'operator', 'lhs', 'keys')
1569    )
1570    -- Replay recomputes the range from the motion: the whole 3-line paragraph is replaced.
1571    feed('4G')
1572    n.exec_lua(function(keys)
1573      vim.api.nvim_feedkeys(keys, 'nx', false)
1574    end, bang.keys)
1575    eq({ '0: X', '1: X', '', '0: X', '1: X' }, get_lines())
1576    -- Same for "=" with 'equalprg', "gq" with 'formatprg'.
1577    api.nvim_set_option_value('equalprg', prg, {})
1578    api.nvim_set_option_value('formatprg', prg, {})
1579    api.nvim_buf_set_lines(0, 0, -1, true, { 'b', 'a', '', 'd', 'c' })
1580    feed('gg=ip')
1581    eq({ '0: X', '1: X', '', 'd', 'c' }, get_lines())
1582    eq(
1583      { type = 'operator', operator = '=', keys = '=ip' },
1584      pick(atom_last(), 'type', 'operator', 'keys')
1585    )
1586    feed('4Ggqip')
1587    eq({ '0: X', '1: X', '', '0: X', '1: X' }, get_lines())
1588    eq(
1589      { type = 'operator', operator = 'gq', keys = 'gqip' },
1590      pick(atom_last(), 'type', 'operator', 'keys')
1591    )
1592  end)
1593
1594  it('stuffed translations execute within their command (exec_stuffed)', function()
1595    -- A register prefix crosses into the "." replay; an explicit register must not touch the
1596    -- small-delete register.
1597    atoms_start()
1598    fn.setline(1, { 'aaa bbb', 'ccc ddd' })
1599    feed('gg0dw')
1600    eq('aaa ', fn.getreg('-'))
1601    feed('j0"z.')
1602    eq('ccc ', fn.getreg('z'))
1603    eq('aaa ', fn.getreg('-'))
1604    eq({ 'bbb', 'ddd' }, get_lines())
1605    -- One atom: the stuffed replay collects into the "."-labeled composite.
1606    eq(
1607      { type = 'operator', lhs = k('"z.'), keys = '"zdw', reg = 'z' },
1608      pick(atom_last(), 'type', 'lhs', 'keys', 'reg')
1609    )
1610    -- i_CTRL-O inside a stuffed translation's insert session ("S" == "cc"): the session resumes
1611    -- after ONE normal command.
1612    api.nvim_buf_set_lines(0, 0, -1, true, { 'xxxx', 'yyyy' })
1613    feed('ggSabc<C-o>0def<Esc>')
1614    eq({ 'defabc', 'yyyy' }, get_lines())
1615    -- i_CTRL-O resolution is lossy: keys=nil, replay the "S"-labeled `lhs` instead.
1616    eq(
1617      { type = 'mapping', lhs = k('Sabc<C-o>0def<Esc>') },
1618      pick(atom_last(), 'type', 'lhs', 'keys')
1619    )
1620    -- r<Tab> under 'expandtab'/'smarttab' ("{count}R<Tab><Esc>": edit() does the tab).
1621    command('set expandtab shiftwidth=4 tabstop=4')
1622    api.nvim_buf_set_lines(0, 0, -1, true, { 'abcdefgh', 'ABCDEFGH' })
1623    feed('gg03r<Tab>')
1624    eq('            defgh', fn.getline(1))
1625    eq(
1626      { type = 'insert', lhs = k('3r<Tab>'), keys = k('3R<Tab><Esc>') },
1627      pick(atom_last(), 'type', 'lhs', 'keys')
1628    )
1629    feed('j0.')
1630    eq('            DEFGH', fn.getline(2))
1631    api.nvim_buf_set_lines(0, 0, -1, true, { 'abcdefgh' })
1632    feed('gg0r<C-v><Tab>')
1633    eq('\tbcdefgh', fn.getline(1))
1634    command('set noexpandtab smarttab shiftwidth=4 tabstop=8')
1635    api.nvim_buf_set_lines(0, 0, -1, true, { 'abcdefgh' })
1636    feed('gg02r<Tab>')
1637    eq('\tcdefgh', fn.getline(1))
1638    command('set expandtab& smarttab& shiftwidth& tabstop&')
1639    -- "&" and "count&" (":.,.+Ns").
1640    api.nvim_buf_set_lines(0, 0, -1, true, { 'blue a', 'blue b', 'blue c', 'blue d' })
1641    command('1s/blue/red/')
1642    feed('2G&3G2&')
1643    eq({ 'red a', 'red b', 'red c', 'red d' }, get_lines())
1644    eq({ type = 'excmd', lhs = '2&', keys = ':.,.+1s\n' }, pick(atom_last(), 'type', 'lhs', 'keys'))
1645
1646    -- Reg "." put re-inserts through edit(), and a mapping's composite labels it.
1647    api.nvim_buf_set_lines(0, 0, -1, true, { 'one' })
1648    feed('ggifoo<Esc>')
1649    feed('$".p')
1650    eq('fooonefoo', fn.getline(1))
1651    eq(
1652      { type = 'insert', lhs = k('1afoo<Esc>'), keys = k('1afoo<Esc>') },
1653      pick(atom_last(), 'type', 'lhs', 'keys')
1654    )
1655    command('nnoremap ,p ".p')
1656    feed(',p')
1657    eq(
1658      { type = 'insert', lhs = ',p', keys = k('1afoo<Esc>') },
1659      pick(atom_last(), 'type', 'lhs', 'keys')
1660    )
1661    -- Typed ":put ." emits typed cmdline payload, not the internal ":put _" translation.
1662    feed(':put .<CR>')
1663    eq('foo', fn.getline(2))
1664    eq(
1665      { type = 'excmd', lhs = ':put .\n', keys = ':put .\n', text = 'put .' },
1666      pick(atom_last(), 'type', 'lhs', 'keys', 'text')
1667    )
1668  end)
1669
1670  it('fires for user input, not programmatic sources', function()
1671    atoms_start()
1672    -- Drain deferred CmdAtom events, then return + clear the collected list.
1673    local function take()
1674      n.poke_eventloop()
1675      return n.exec_lua([[local a = _G.atoms; _G.atoms = {}; return a]])
1676    end
1677    -- Fresh buffer + cursor via the API (no keys, so no motion atoms).
1678    local function fresh()
1679      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaaaaaa', 'bbbbbbbb' })
1680      api.nvim_win_set_cursor(0, { 1, 0 })
1681      take()
1682    end
1683
1684    -- Typed input emits: real keys (nvim_input, via feed())...
1685    fresh()
1686    feed('x')
1687    eq(1, #take())
1688    -- ...and nvim_feedkeys() with the "t" (typed) flag.
1689    n.exec_lua([[vim.api.nvim_feedkeys('x', 't', false)]])
1690    eq(1, #take())
1691
1692    -- A typed macro folds into exactly ONE atom, labeled "@q".
1693    fresh()
1694    feed('qqxq') -- recording is typed input
1695    take()
1696    feed('@q')
1697    local evs = take()
1698    eq(1, #evs)
1699    eq('@q', evs[1].lhs)
1700
1701    -- Programmatic / replayed input must NOT leak any atom.
1702    fresh()
1703    api.nvim_buf_set_lines(0, 0, 1, true, { 'ZZZZ' }) -- API buffer edit
1704    eq(0, #take())
1705    api.nvim_buf_set_text(0, 0, 0, 0, 1, { 'Q' })
1706    eq(0, #take())
1707    command('normal! x') -- :normal!
1708    eq(0, #take())
1709    command('normal x') -- :normal (with mappings)
1710    eq(0, #take())
1711    n.exec_lua([[vim.cmd('normal! x')]])
1712    eq(0, #take())
1713    n.exec_lua([[vim.api.nvim_feedkeys('x', '', false)]]) -- feedkeys without "t"
1714    eq(0, #take())
1715    command('nnoremap gj i<c-j><esc>k$')
1716    n.exec_lua([[vim.api.nvim_feedkeys('gj', 'm', false)]]) -- remapped feedkeys without "t"
1717    eq({}, take())
1718    n.exec_lua([[vim.api.nvim_feedkeys('ihello\27', '', false)]]) -- insert session without "t"
1719    eq({}, take())
1720    command('normal! @q') -- macro played programmatically, not typed
1721    eq(0, #take())
1722    n.exec_lua([[vim.api.nvim_feedkeys('@q', '', false)]])
1723    eq(0, #take())
1724    command('normal! yy') -- prep-exempt operator (a yank builds no redo)
1725    eq(0, #take())
1726    n.exec_lua([[vim.api.nvim_feedkeys('viwd', '', false)]]) -- Visual sequence
1727    eq(0, #take())
1728
1729    -- A timer/scheduled API edit must NOT leak.
1730    n.exec_lua([[
1731      _G.done = false
1732      vim.defer_fn(function()
1733        vim.api.nvim_buf_set_lines(0, 0, 1, true, { 'TTTT' })
1734        _G.done = true
1735      end, 5)
1736    ]])
1737    n.exec_lua('vim.wait(200, function() return _G.done end)')
1738    eq(0, #take())
1739
1740    -- Sanity: typed input still emits after all the programmatic noise.
1741    fresh()
1742    feed('x')
1743    eq(1, #take())
1744  end)
1745
1746  it('one event per user action', function()
1747    n.clear({ args = { '--clean' }, args_rm = { '--cmd' } })
1748    --- Feeds `keys`, asserts exactly ONE new event, with the given keys.
1749    local function atom(keys, expected, lhs, type_)
1750      local before = #atoms()
1751      feed(keys)
1752      local evs = atoms()
1753      eq(
1754        { before + 1, k(expected), k(lhs or expected), type_ or evs[#evs].type },
1755        { #evs, evs[#evs].keys, evs[#evs].lhs, evs[#evs].type }
1756      )
1757    end
1758    fn.setline(1, fn['repeat']({ 'alpha beta gamma delta epsilon zeta' }, 20))
1759    feed('gg0')
1760    atoms_start()
1761    -- "." with nothing to repeat stuffs nothing.
1762    feed('.')
1763    eq({ { type = 'normal', keys = '.', lhs = '.' } }, atoms_tail(1, 'type', 'keys', 'lhs'))
1764    -- Operators: the atom is the redobuff (count/register included).
1765    -- "x" is normalized ("translated") to the elemental command "dl".
1766    atom('x', 'dl', 'x')
1767    -- A stuffed translation UNWRAPS: keeps the resolved "type" and has no subatoms.
1768    -- Only `lhs` marks it as translated; it is not a composite.
1769    eq({ type = 'operator' }, pick(atom_last(), 'type', 'atoms'))
1770    atom('3x', '3dl', '3x')
1771    atom('D', 'd$', 'D')
1772    atom('dw', 'dw')
1773    atom('"z2dw', '"z2dw')
1774    atom('yy', 'yy')
1775    atom('p', 'p')
1776    atom('J', '2J')
1777    atom('3J', '3J')
1778    atom('r?', '1r?')
1779    atom('~', '~')
1780    atom('guiw', 'guiw')
1781    atom('gUiw', 'gUiw')
1782    atom('>>', '>>')
1783    atom('dfa', 'dfa')
1784    feed('ddk')
1785    atom('P', 'P')
1786    -- Insert sessions: one whole-session atom (entry + text + <Esc>).
1787    atom('iXY<Esc>', '1iXY<Esc>')
1788    atom('A!<Esc>', '1A!<Esc>')
1789    atom('oNEW<Esc>', '1oNEW<Esc>')
1790    atom('3iZ<Esc>', '3iZ<Esc>')
1791    atom('cwWORD<Esc>', 'cwWORD<Esc>')
1792    -- Visual: the full typed keysequence.
1793    atom('viwd', 'viwd')
1794    atom('Vd', 'Vd')
1795    atom('<C-v>jd', '<C-V>jd')
1796    -- Motions: the target is relative to the cursor.
1797    atom('w', 'w')
1798    atom('3w', '3w')
1799    atom('fb', 'fb')
1800    atom('$', '$')
1801    feed('gg0')
1802    atom(']]', ']]')
1803    -- "%" is cursor-relative.
1804    command('silent! nunmap %') -- the bundled matchit plugin maps it
1805    fn.setline(1, 'alpha (beta) gamma')
1806    feed('gg0f(')
1807    atom('%', '%', nil, 'motion')
1808    fn.setline(1, 'alpha beta gamma delta epsilon zeta')
1809    -- "*" is cursor-relative, reads the word per-cursor.
1810    feed('gg0')
1811    atom('*', '*', nil, 'motion')
1812    atom('g#', 'g#', nil, 'motion')
1813    -- Jumps: absolute, the target is independent of the cursor.
1814    feed('gg0')
1815    atom('G', 'G', nil, 'jump')
1816    atom('gg', 'gg', nil, 'jump')
1817    atom('go', 'go', nil, 'jump')
1818    atom('50%', '50%', nil, 'jump') -- "[count]%" is absolute, unlike "%".
1819    atom('L', 'L', nil, 'jump')
1820    atom('H', 'H', nil, 'jump')
1821    atom('M', 'M', nil, 'jump')
1822    atom('ma', 'ma', nil, 'normal') -- "m" sets state; it does not jump
1823    atom('`a', '`a', nil, 'jump')
1824    atom('<C-o>', '<C-O>', nil, 'jump')
1825    -- Non-redoable commands: still emitted, as type "command".
1826    atom('zz', 'zz', nil, 'normal')
1827    atom('u', 'u')
1828    atom('<C-r>', '<C-R>')
1829    -- "." emits its resolution (like "x" => "dl").
1830    feed('gg0')
1831    atom('x', 'dl', 'x')
1832    atom('.', 'dl', '.')
1833    atom('3.', '3dl', '3.') -- "3.": the new count replaces the captured one
1834    -- "." emits exactly ONE atom labeled ".": the repeated keys fold into its composite.
1835    atom('iQ<Esc>', '1iQ<Esc>')
1836    atom('.', '1iQ<Esc>', '.')
1837    atom('viwd', 'viwd')
1838    atom('.', 'viwd', '.')
1839    atom('cwZZ<Esc>', 'cwZZ<Esc>')
1840    atom('.', 'cwZZ<Esc>', '.')
1841    -- Payload commands: the interactively-typed cmdline completes the
1842    -- keysequence (not a bare "/" or ":" prefix).
1843    atom('/beta<CR>', '/beta<NL>')
1844    eq({ type = 'motion', text = 'beta' }, pick(atom_last(), 'type', 'text'))
1845    atom('?alpha<CR>', '?alpha<NL>')
1846    atom('2/beta<CR>', '2/beta<NL>')
1847    -- Ex commands: their own atom kind, the cmdline is the "text" payload.
1848    atom(':set tw=42<CR>', ':set<Space>tw=42<NL>')
1849    eq({ type = 'excmd', text = 'set tw=42' }, pick(atom_last(), 'type', 'text'))
1850    -- A nested cmdline opened by the command's own execution (":normal")
1851    -- does not hijack the payload.
1852    atom(':exe "normal! :echo 1\\r"<CR>', ':exe<Space>"normal!<Space>:echo<Space>1<Bslash>r"<NL>')
1853    -- A mapping that ends mid-operation captures its continuation. ",D" emits nothing until the
1854    -- typed "w" finishes the operation: one atom captures both.
1855    command('nnoremap ,D d')
1856    command('nnoremap ,V v')
1857    before = #atoms()
1858    feed(',D')
1859    eq(before, #atoms())
1860    atom('w', 'dw', ',Dw') -- The supplied motion finishes the operation
1861    -- Same for a mapping that opens Visual mode: ESC closes the selection (cursor stays on the
1862    -- selection end, where it moved during the Visual sequence).
1863    feed(',V')
1864    eq(before + 1, #atoms())
1865    feed('<Esc>')
1866    eq(
1867      { type = 'visual', lhs = k(',V<Esc>'), keys = k('v<Esc>') },
1868      pick(atom_last(), 'type', 'lhs', 'keys')
1869    )
1870    -- A mapping whose trailing prefix is completed by TYPED keys ("," + "w")
1871    -- ends where its own keys stop: each `lhs` owns only what it produced.
1872    command('set notimeout')
1873    command('nmap ,x j,')
1874    command('nnoremap ,w w')
1875    feed('gg0')
1876    before = #atoms()
1877    feed(',xw') -- no poke between: nvim awaits the pending "," under 'notimeout'
1878    eq(before + 2, #atoms())
1879    eq({
1880      { type = 'motion', lhs = ',x', keys = 'j' },
1881      { type = 'motion', lhs = ',w', keys = 'w' },
1882    }, atoms_tail(2, 'type', 'lhs', 'keys'))
1883    command('set notimeout&')
1884    command('nunmap ,x')
1885    command('nunmap ,w')
1886    -- An ABORTED mapping emits nothing: an error discards its remaining
1887    -- keys, and the composite with them.
1888    command('nnoremap ,E :NoSuchCmd<CR>x')
1889    local count = #atoms()
1890    feed(',E') -- E492 mid-mapping: the trailing "x" never runs
1891    eq(count, #atoms())
1892    atom('x', 'dl', 'x') -- the next command is not folded into the dead composite
1893    command('nmap ,A ,B')
1894    command('nmap ,B ,A')
1895    feed(',A') -- E223: recursive mapping
1896    atom('x', 'dl', 'x')
1897    -- Macro playback ("@q") emits its commands' atoms (capture-on-replay);
1898    -- "@q" itself is a translation, never an atom.
1899    local total = #atoms()
1900    feed('qqxq')
1901    feed('@q')
1902    eq(total + 4, #atoms())
1903    eq({ 'qq', 'dl', 'q', 'dl' }, atoms_tail(4))
1904    -- The macro's atoms fold into one "@x"-labeled composite, like a mapping.
1905    eq('@q', atom_last().lhs)
1906    -- A typed scroll emits its own (emit-only) atom kind.
1907    feed('<C-d>')
1908    eq(total + 5, #atoms())
1909    eq({ type = 'scroll', keys = k('<C-D>') }, pick(atom_last(), 'type', 'keys'))
1910    -- An 'indentexpr' that runs ":normal" opens a nested command-frame mid-operator: "gq" still
1911    -- pushes its own atom, after the edit.
1912    exec([[
1913      func Indent()
1914        exe "normal! \<Ignore>"
1915        return 0
1916      endfunc
1917      setlocal indentexpr=Indent() textwidth=20
1918    ]])
1919    atom('Vgq', 'Vgq')
1920    eq(true, atom_last().changed)
1921  end)
1922
1923  it('captures prep-exempt operators (zfap) and fold/view commands', function()
1924    fn.setline(1, { 'aa', 'aa', '' })
1925    feed('gg0')
1926    atoms_start()
1927    feed('zfap')
1928    eq({ 'zfap' }, atoms_tail(1))
1929    eq('operator', atom_last().type)
1930    eq(1, fn.foldclosed(1))
1931    feed('za')
1932    eq({ 'za' }, atoms_tail(1))
1933    -- Neither an operator nor a motion: its own kind.
1934    eq('normal', atom_last().type)
1935    eq(-1, fn.foldclosed(1))
1936  end)
1937
1938  it('captures "do"/"dp" (:diffget/:diffput); "." repeats them (unlike Vim)', function()
1939    atoms_start()
1940    command('new')
1941    fn.setline(1, { 'a', 'b', 'c', 'd' })
1942    command('diffthis | vnew')
1943    fn.setline(1, { 'a', 'XY', 'c', 'ZW' })
1944    command('diffthis')
1945    feed('2G')
1946    local before = #atoms()
1947    feed('do')
1948    eq(before + 1, #atoms())
1949    eq({ { type = 'operator', keys = 'do' } }, atoms_tail(1, 'type', 'keys'))
1950    eq('b', fn.getline(2))
1951    feed('2j.') -- Repeats "do" at the next hunk.
1952    eq('d', fn.getline(4))
1953    feed('2Gx')
1954    feed('dp')
1955    eq({ { type = 'operator', keys = 'dp' } }, atoms_tail(1, 'type', 'keys'))
1956    eq({ '' }, fn.getbufline(fn.bufnr('#'), 2))
1957  end)
1958
1959  it("operatorfunc atom includes the getchar()'d payload", function()
1960    n.exec(t_atom.minisurround_vim)
1961    fn.setline(1, { 'alpha beta' })
1962    feed('gg0')
1963    atoms_start()
1964    feed('ysiw"')
1965    -- One atom: the mapping captures the operation finished by "iw". `keys` is the redobuff plus
1966    -- the getchar() payload: a replayed opfunc reads the same wrap char.
1967    eq(
1968      { type = 'operator', keys = 'g@iw"', lhs = 'ysiw"' },
1969      pick(atom_last(), 'type', 'keys', 'lhs')
1970    )
1971    eq({ '"alpha" beta' }, get_lines())
1972  end)
1973
1974  it('operator completed by a Lua textobject (:omap) #41482', function()
1975    -- Lua :omap textobject (starts Visual mode, |omap-info|) captures the operator: `keys` is the
1976    -- redobuff (K_LUA + mapping-id).
1977    n.exec_lua([[
1978      vim.keymap.set('o', 'gt', function()
1979        vim.cmd('normal! viw')
1980      end)
1981    ]])
1982    fn.setline(1, { 'aaa xxx', 'bbb yyy', 'ccc zzz' })
1983    atoms_start()
1984    feed('gg0wdgt')
1985    eq('aaa ', fn.getline(1))
1986    local ev = atom_last()
1987    eq(
1988      { type = 'operator', operator = 'd', lhs = 'dgt', changed = true },
1989      pick(ev, 'type', 'operator', 'lhs', 'cmd', 'changed')
1990    )
1991    t.matches('^d\128', ev.keys) -- "d" + K_LUA…: the redobuf.
1992    feed('j0w')
1993    n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
1994    eq('bbb ', fn.getline(2))
1995    -- "." repeats it, captured as one "."-labeled operator atom.
1996    feed('j0w.')
1997    eq('ccc ', fn.getline(3))
1998    eq(
1999      { type = 'operator', operator = 'd', lhs = '.' },
2000      pick(atom_last(), 'type', 'operator', 'lhs')
2001    )
2002
2003    -- 'operatorfunc' + Lua textobject: "ghgt". Non-edit, still emits its operator atom.
2004    n.exec_lua([[
2005      _G.oplog = {}
2006      vim.keymap.set('n', 'gh', function()
2007        vim.o.operatorfunc = function(mtype)
2008          table.insert(_G.oplog, mtype)
2009        end
2010        return 'g@'
2011      end, { expr = true })
2012    ]])
2013    feed('gg0ghgt')
2014    eq({ 'char' }, n.exec_lua('return _G.oplog'))
2015    ev = atom_last()
2016    eq(
2017      { type = 'operator', operator = 'g@', lhs = 'ghgt', changed = false },
2018      pick(ev, 'type', 'operator', 'lhs', 'cmd', 'changed')
2019    )
2020    t.matches('^g@\128', ev.keys) -- "g@" + K_LUA….
2021    n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
2022    eq({ 'char', 'char' }, n.exec_lua('return _G.oplog'))
2023
2024    -- Lua 'operatorfunc' editing via ":norm!" must not clobber the captured "g@" redo/atom.
2025    n.exec_lua([[
2026      vim.keymap.set('n', 'gr', function()
2027        vim.o.operatorfunc = function()
2028          vim.cmd([=[normal! `[v`]rX]=])
2029        end
2030        return 'g@'
2031      end, { expr = true })
2032    ]])
2033    api.nvim_buf_set_lines(0, 0, -1, true, { 'mmm nnn', 'ooo ppp' })
2034    feed('gg0grgt')
2035    eq('XXX nnn', fn.getline(1))
2036    ev = atom_last()
2037    eq(
2038      { type = 'operator', operator = 'g@', lhs = 'grgt', changed = true },
2039      pick(ev, 'type', 'operator', 'lhs', 'changed')
2040    )
2041    t.matches('^g@\128', ev.keys) -- "g@" + K_LUA….
2042    feed('j0')
2043    n.exec_lua(([[vim.api.nvim_feedkeys(%q, 'nx', false)]]):format(ev.keys))
2044    eq('XXX ppp', fn.getline(2))
2045
2046    -- Aborted operator (cpo+=E empty region) cancels its redo: no atom captured.
2047    command('set cpo+=E')
2048    n.exec_lua([[vim.keymap.set('o', 'ge', function() end)]])
2049    feed('dge')
2050    eq('XXX ppp', fn.getline(2))
2051    eq(
2052      { type = 'mapping', lhs = 'dge', changed = false },
2053      pick(atom_last(), 'type', 'lhs', 'changed')
2054    )
2055    command('set cpo-=E')
2056  end)
2057
2058  it('does not capture inputsecret() input', function()
2059    api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa' })
2060    n.exec_lua(function()
2061      vim.keymap.set('n', 'sp', function()
2062        _G.pw = vim.fn.inputsecret('Password: ')
2063        vim.api.nvim_put({ 'X' }, 'c', false, true)
2064      end)
2065    end)
2066    feed('gg0')
2067    atoms_start()
2068    feed('sp')
2069    feed('hunter2<CR>')
2070    feed('<Esc>') -- The composite resolves at the next clock edge.
2071    eq('hunter2', n.exec_lua('return _G.pw')) -- The function gets the input.
2072    eq({ type = 'mapping', lhs = 'sp' }, pick(atoms()[1], 'type', 'lhs', 'keys')) -- Not CmdAtom.
2073  end)
2074
2075  it('reports the original buffer', function()
2076    n.exec_lua([[
2077      _G.evs = {}
2078      vim.api.nvim_create_autocmd('CmdAtom', {
2079        callback = function(ev)
2080          table.insert(_G.evs, { buf = ev.buf, keys = ev.data.keys, changed = ev.data.changed })
2081        end,
2082      })
2083    ]])
2084    command('let g:abufs = []')
2085    command("autocmd CmdAtom * call add(g:abufs, expand('<abuf>')->str2nr())")
2086    local a = api.nvim_get_current_buf()
2087    api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa bbb' })
2088    command('badd other')
2089    local b = api.nvim_list_bufs()[2]
2090    command('nnoremap ]b <Cmd>bprev<CR>')
2091
2092    -- An edit reports its own buffer, and `changed`.
2093    feed('gg0dw')
2094    -- Leaving the buffer reports the buffer the command ran IN, not the one it
2095    -- landed in. `changed` is about that same buffer: ":bnext" edits nothing.
2096    feed(':bnext<CR>')
2097    eq(b, api.nvim_get_current_buf())
2098    -- Same, from a mapping, in the other direction.
2099    feed(']b')
2100    eq(a, api.nvim_get_current_buf())
2101    local evs = n.exec_lua('return _G.evs')
2102    eq({
2103      { buf = a, keys = 'dw', changed = true },
2104      { buf = a, keys = ':bnext\n', changed = false },
2105      { buf = b, keys = ('%sbprev\n'):format(k('<Cmd>')), changed = false },
2106    }, { evs[#evs - 2], evs[#evs - 1], evs[#evs] })
2107    -- <abuf> agrees with the Lua callback's `buf`.
2108    local abufs = n.eval('g:abufs')
2109    eq({ a, a, b }, { abufs[#abufs - 2], abufs[#abufs - 1], abufs[#abufs] })
2110  end)
2111
2112  it('reports `moved`/`pos` for the original buffer+window', function()
2113    api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa bbb', 'ccc ddd', 'eee fff' })
2114    n.exec_lua([[
2115      _G.jump = function() vim.api.nvim_win_set_cursor(0, { 3, 0 }) end
2116      vim.keymap.set('n', ']c', '<Cmd>lua _G.jump()<CR>')
2117    ]])
2118    atoms_start()
2119
2120    -- A plugin motion via "<Cmd>" is type="excmd" (its RHS implementation); `moved`
2121    -- reports the same observed effect as the builtin motion below it.
2122    feed('gg0]c')
2123    eq(3, fn.line('.'))
2124    eq(
2125      { type = 'excmd', moved = true, changed = false, pos = { 1, 0 } },
2126      pick(atom_last(), 'type', 'moved', 'changed', 'pos')
2127    )
2128    feed('gg0w')
2129    eq(
2130      { type = 'motion', moved = true, changed = false },
2131      pick(atom_last(), 'type', 'moved', 'changed')
2132    )
2133    -- A motion that did not move is still a motion; `moved` is the separate question.
2134    eq(
2135      { { 'motion', false }, { 'motion', false }, { 'motion', false }, { 'normal', false } },
2136      vim.tbl_map(function(keys)
2137        feed(keys)
2138        local a = atom_last()
2139        return { a.type, a.moved }
2140      end, { 'G$w', 'gg0fz', 'gg0h', 'gg0zz' })
2141    )
2142
2143    -- Register-only operator also moves without changing: a motion carries no `operator`.
2144    feed('gg0wyb')
2145    eq(
2146      { moved = true, changed = false, operator = 'y' },
2147      pick(atom_last(), 'moved', 'changed', 'operator')
2148    )
2149
2150    -- Switching window is not a cursor-move, even on the SAME buffer: `pos` is per-window.
2151    command('split')
2152    feed('gg')
2153    command('wincmd j')
2154    feed('3G')
2155    command('wincmd k')
2156    feed('<C-w>w')
2157    eq(3, fn.line('.'))
2158    eq({ type = 'normal', moved = false }, pick(atom_last(), 'type', 'moved'))
2159
2160    -- Both are measured on the buffer/window the action STARTED in, so acting
2161    -- and then navigating away still reports the effect.
2162    command('nnoremap ]x <Cmd>normal! dd<CR><Cmd>wincmd w<CR>')
2163    command('nnoremap ]y <Cmd>normal! j<CR><Cmd>wincmd w<CR>')
2164    feed('gg]x')
2165    eq({ changed = true, moved = false }, pick(atom_last(), 'changed', 'moved'))
2166    command('wincmd w')
2167    feed('gg]y')
2168    eq({ changed = false, moved = true }, pick(atom_last(), 'changed', 'moved'))
2169
2170    -- Switching buffer is not a cursor-move.
2171    command('only')
2172    local main = api.nvim_get_current_buf()
2173    command('edit other')
2174    api.nvim_buf_set_lines(0, 0, -1, true, { 'x', 'y', 'z' })
2175    feed('3G')
2176    feed('<C-^>') -- back to `main`, whose cursor is on another line
2177    eq(main, api.nvim_get_current_buf())
2178    eq(
2179      { type = 'normal', moved = false, pos = { 3, 0 } },
2180      pick(atom_last(), 'type', 'moved', 'pos')
2181    )
2182  end)
2183end)