robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
154.9 KiB4178 linesraw
1-- Multicursor tests.
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 pending = t.pending
10local clear = n.clear
11local command = n.command
12local feed = n.feed
13local fn = n.fn
14local eq = t.eq
15local api = n.api
16local get_lines = t_atom.get_lines
17local k = t_atom.k
18local atoms_start = t_atom.atoms_start
19local atoms = t_atom.atoms
20local atoms_tail = t_atom.atoms_tail
21local atom_last = t_atom.atom_last
22local subatoms = t_atom.subatoms
23
24--- Clears the buffer mcursors like the default CTRL-L mapping (test-harness "mapclear" removed it).
25local function clear_cursors()
26  n.exec_lua(
27    [[vim.api.nvim_buf_clear_namespace(0, vim.api.nvim_create_namespace('nvim.multicursor'), 0, -1)]]
28  )
29end
30
31--- Number of multicursors.
32local function ncursors()
33  local ns = api.nvim_create_namespace('nvim.multicursor')
34  return #api.nvim_buf_get_extmarks(0, ns, 0, -1, {})
35end
36
37--- Positions ({row, col}, 0-based, in position order) of the mcursors.
38local function anchors()
39  local ns = api.nvim_create_namespace('nvim.multicursor')
40  local positions = {}
41  for _, m in ipairs(api.nvim_buf_get_extmarks(0, ns, 0, -1, {})) do
42    positions[#positions + 1] = { m[2], m[3] }
43  end
44  return positions
45end
46
47--- Adds a cursor at `pos` in `buf`, via extmark API.
48local function add_cursor(buf, pos)
49  local ns = api.nvim_create_namespace('nvim.multicursor')
50  api.nvim_buf_set_extmark(buf, ns, pos[1] - 1, pos[2], {})
51end
52
53--- Sets the buffer lines, then places cursors by "Q".
54local function cursors(lines, place)
55  api.nvim_buf_set_lines(0, 0, -1, true, lines)
56  feed('gg0')
57  feed(place or 'QjQj')
58end
59
60--- Asserts table-driven cascade rows.
61--- - `row.place` (default: "gg0") places the primary.
62--- - `row.keys` input (the "Q" placements and the operation), then compare the whole buffer.
63--- - `row.after` optionally feeds a key after the operation.
64--- - `row.pre` runs a :command first (such rows go last: the option persists).
65local function assert_rows(rows)
66  for _, row in ipairs(rows) do
67    clear_cursors()
68    if row.pre then
69      command(row.pre)
70    end
71    api.nvim_buf_set_lines(0, 0, -1, true, row.lines)
72    feed(row.place or 'gg0')
73    feed(row.keys)
74    eq(row.expect, get_lines(), row.keys)
75    if row.after then
76      feed(row.after)
77      eq(row.after_expect, get_lines(), ('%s ; %s'):format(row.keys, row.after))
78    end
79  end
80end
81
82describe('multicursor', function()
83  before_each(function()
84    clear()
85    command('hi MCursor guifg=Black guibg=LightGrey')
86  end)
87
88  describe('Q', function()
89    it('creates a cursor again after clearing all', function()
90      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQ')
91      clear_cursors()
92      clear_cursors() -- Repeated clear (nothing to remove) is a no-op.
93      eq(0, ncursors())
94      eq(false, n.exec_lua("return require('vim._core.mcursor').active()"))
95      feed('Q')
96      eq(1, ncursors())
97      eq(true, n.exec_lua("return require('vim._core.mcursor').active()"))
98      feed('gg0x')
99      eq({ 'aa', 'bb', 'ccc' }, get_lines())
100    end)
101
102    it('entering a buffer with mcursors via a nav mapping keeps them', function()
103      -- A navigation mapping ("nnoremap <C-l> <C-w>l") ending in another buffer must not count as
104      -- "the mapping edited the buffer".
105      command('nnoremap <F5> <C-w>p')
106      fn.setline(1, { 'aaa', 'bbb' })
107      feed('gg0Q') -- Cursor in buf1, at the primary position.
108      eq(1, ncursors())
109      command('set hidden')
110      command('vsplit | enew')
111      fn.setline(1, { 'xxx', 'yyy' })
112      feed('gg0Q') -- Cursor in buf2.
113      eq(1, ncursors())
114      feed('<F5>') -- Mapped switch to win1/buf1.
115      eq(1, ncursors()) -- buf1 cursor still exists
116      feed('<F5>') -- and back
117      eq(1, ncursors()) -- buf2 cursor also
118    end)
119
120    it('"qQ" is macro-recording, not cursor-add', function()
121      -- "q" is the recording command; a stray "q" before "Q" starts recording into reg Q.
122      feed('qQ')
123      eq('Q', fn.reg_recording())
124      eq(0, ncursors())
125      feed('q') -- stop recording: "Q" creates cursors again
126      eq('', fn.reg_recording())
127      feed('Q')
128      eq(1, ncursors())
129    end)
130
131    it('gQ restores the cleared cursors (like gv)', function()
132      cursors({ 'aaa', 'bbb', 'ccc', 'ddd' }, 'QjQ')
133      eq({ { 0, 0 }, { 1, 0 } }, anchors())
134      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
135      clear_cursors()
136      eq(0, ncursors())
137      feed('G$') -- Move the primary away.
138      feed('gQ')
139      eq({ { 0, 0 }, { 1, 0 } }, anchors())
140      eq({ 2, 0 }, api.nvim_win_get_cursor(0)) -- Primary cursor position is restored too.
141      feed('Gx') -- The restored cursors cascade.
142      eq({ 'aa', 'bb', 'ccc', 'dd' }, get_lines())
143      -- The snapshot extmarks are shifted by intervening edits.
144      clear_cursors()
145      feed('ggO<Esc>') -- New line on top shifts the snapshot down.
146      feed('gQ')
147      eq({ { 1, 0 }, { 2, 0 } }, anchors())
148      -- No-op if multicursor is already active.
149      feed('gQ')
150      eq('gQ: multicursor session is active', n.exec_capture('1messages'))
151    end)
152
153    it(':g//normal! Q places a cursor at each match', function()
154      fn.setline(1, { 'foo a', 'bar b', 'foo c', 'baz d', 'foo e' })
155      command('g/foo/normal! Q')
156      eq(3, ncursors())
157      feed('A!<Esc>') -- edit applies once per line (primary ends on the last match)
158      eq({ 'foo a!', 'bar b', 'foo c!', 'baz d', 'foo e!' }, get_lines())
159    end)
160
161    it('Q in operator-pending mode aborts the operator', function()
162      -- nv_Q: checkclearop() clears the pending operator, no cursor.
163      fn.setline(1, { 'one two' })
164      feed('gg0')
165      feed('dQ')
166      eq({ 'one two' }, get_lines())
167      eq(0, ncursors())
168      feed('wx') -- "w" moves (the "d" is gone), then x deletes one char
169      eq({ 'one wo' }, get_lines())
170    end)
171
172    it('Q then edit applies once; primary-overlapping cursor stays synced', function()
173      fn.setline(1, { 'ab', 'cd' })
174      feed('Q')
175      eq(1, ncursors())
176      feed('x') -- The primary's own edit covers the cursor under it, applied only once.
177      eq({ 'b', 'cd' }, get_lines())
178      eq({ { 0, 0 } }, anchors())
179      feed('jx') -- Move with follow=OFF, the cursor is no longer "primary-overlapping".
180      eq({ '', 'd' }, get_lines())
181
182      -- Insert-session ESC moves the primary; the primary-overlapping cursor stays synced.
183      for _, keys in ipairs({ 'i<Esc>', 'a<Esc>', 'aX<Esc>', 'A<Esc>', 'cwX<Esc>', 'oX<Esc>' }) do
184        clear_cursors()
185        cursors({ 'abcd', 'efgh' }, 'lQjQ')
186        feed(keys)
187        local cur = api.nvim_win_get_cursor(0)
188        eq({ cur[1] - 1, cur[2] }, anchors()[2], keys)
189      end
190    end)
191
192    it('Q on an existing cursor removes it (toggle)', function()
193      fn.setline(1, { 'aaa', 'bbb' })
194      feed('Q')
195      eq(1, ncursors())
196      feed('Q') -- toggle off: multicursor mode ends
197      eq(0, ncursors())
198      feed('QjQk')
199      eq(2, ncursors())
200      feed('Q') -- removes only the cursor under the primary
201      eq(1, ncursors())
202      feed('x') -- the remaining cursor still cascades
203      eq({ 'aa', 'bb' }, get_lines())
204    end)
205
206    it('Q not allowed in a macro (recording or executing)', function()
207      -- |mcursor-limitations|: Q beeps (no cursor) while recording or executing a macro.
208      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
209      feed('gg0')
210      feed('qq')
211      feed('Q') -- Recording a macro: not allowed (but still recorded).
212      feed('zqj') -- Likewise "zq".
213      feed('q')
214      eq(0, ncursors())
215      feed('@q') -- executing the recorded "Q": not allowed either
216      eq(0, ncursors())
217      feed('Q') -- outside a macro: works
218      eq(1, ncursors())
219    end)
220
221    it('1Q adds, 2Q removes (no toggle); "zq" adds to existing cursors', function()
222      fn.setline(1, { 'foo bar foo' })
223      feed('gg0fbQ') -- A cursor on "bar".
224      feed('0*') -- Sets the last search pattern; the cursor lands on the second "foo".
225      feed('zqn') -- Place a cursor at each "foo".
226      -- Also under the primary: "zq" does not cascade, so its dedupe does not drop that cursor.
227      eq({ { 0, 0 }, { 0, 4 }, { 0, 8 } }, anchors())
228      feed('0fb')
229      feed('1Q1Q') -- No-op (idempotent).
230      eq(3, ncursors())
231      feed('0')
232      feed('2Q2Q') -- Removes the first "foo" cursor, then no-op.
233      eq(2, ncursors())
234      feed('1Q')
235      eq(3, ncursors())
236      feed('$') -- The primary edits a fourth position.
237      feed('x')
238      eq({ 'oo ar o' }, get_lines())
239    end)
240  end)
241
242  describe('{Visual}Q', function()
243    it('places cursor on each selected line', function()
244      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
245      feed('ggvjQ') -- selection spans lines 1-2, cursor ends on line 2
246      eq('n', fn.mode()) -- Visual mode ended
247      eq({ 2, 0 }, api.nvim_win_get_cursor(0)) -- primary: unmoved, where the selection ended
248      eq({ { 0, 0 }, { 1, 0 } }, anchors()) -- One per selected line, including under the primary.
249
250      -- Cursors align by screen (not byte) column. A multibyte char before the cursor must not
251      -- shift other cursors.
252      clear_cursors()
253      api.nvim_buf_set_lines(0, 0, -1, true, { 'é123', 'abcdef' })
254      feed('gg0llvjQ') -- Visual from "2" (line 1) down; cursor ends on "c" (screen column 3)
255      eq({ 2, 2 }, api.nvim_win_get_cursor(0)) -- primary: unmoved, on "c" (screen column 3)
256      feed('x')
257      eq({ 'é13', 'abdef' }, get_lines())
258
259      -- Each line, also where the cursor column is outside the selection: before '< (charwise), or
260      -- past a short line (blockwise).
261      clear_cursors()
262      api.nvim_buf_set_lines(0, 0, -1, true, { 'hello world', 'foo', '' })
263      feed('gg0wv}Q') -- From "world" to the blank line: the cursor column is 0.
264      eq({ { 0, 0 }, { 1, 0 }, { 2, 0 } }, anchors())
265      clear_cursors()
266      api.nvim_buf_set_lines(0, 0, -1, true, { 'abc', 'd', 'efg' })
267      feed('gg0ll<C-v>jjQ')
268      eq({ { 0, 2 }, { 1, 0 }, { 2, 2 } }, anchors())
269    end)
270
271    it('V{motion}Q keeps primary at selection-end; "$": each line end', function()
272      fn.setline(1, { 'aaaa', 'cc', 'dddd', 'eeee' })
273      feed('gg0ll') -- screen column 3 on line 1
274      feed('Vjj') -- linewise down to line 3; the cursor ends on line 3
275      feed('Q')
276      eq({ 3, 2 }, api.nvim_win_get_cursor(0)) -- Primary is unmoved (line 3).
277      -- One cursor per selected line at the shared screen column; a short line at its end ("j").
278      feed('iX<Esc>')
279      eq({ 'aaXaa', 'cXc', 'ddXdd', 'eeee' }, get_lines())
280      -- {Visual}Q enabled follow-mode (q=).
281      feed('$')
282      eq({ { 0, 4 }, { 1, 2 }, { 2, 4 } }, anchors())
283      -- After "$" (curswant): a cursor at each line end. Also on the last buffer line.
284      clear_cursors()
285      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaa', 'cc', 'dddd' })
286      feed('ggVG$Q')
287      eq({ { 0, 3 }, { 1, 1 }, { 2, 3 } }, anchors())
288    end)
289
290    it('after an <expr> mapping does not replay the mapping keys #41857', function()
291      command('xnoremap <expr> is "ip"') -- selects the inner paragraph
292      api.nvim_buf_set_lines(0, 0, -1, true, { 'a1', 'a2', 'a3', '', 'b1', 'b2' })
293      feed('gg0j') -- line 2, inside the first paragraph
294      feed('vis') -- Visual + the <expr> mapping: selects lines 1-3
295      feed('Q') -- a cursor on each selected line
296      eq(3, ncursors())
297      feed('iX<Esc>') -- the mapping keys ("s", "Q") must NOT be replayed
298      eq({ 'Xa1', 'Xa2', 'Xa3', '', 'b1', 'b2' }, get_lines())
299    end)
300  end)
301
302  describe('zq', function()
303    it('zq{search} places a cursor at each match', function()
304      fn.setline(1, { 'foo bar foo', 'baz foo qux', 'foobar foo' })
305      feed('gg0') -- on the first "foo"
306      feed('*') -- whole-word pattern; the cursor moves to the next match
307      eq(1, api.nvim_get_vvar('hlsearch'))
308      feed('zqn')
309      eq(0, api.nvim_get_vvar('hlsearch')) -- ":nohlsearch", workaround for #41629.
310      -- 4 whole-word "foo" matches ("foobar" excluded), including the primary's.
311      eq(4, ncursors())
312      -- The primary cursor does not move ("*" left it on the second match).
313      eq({ 1, 8 }, api.nvim_win_get_cursor(0))
314      feed('cwXXX<Esc>')
315      eq({ 'XXX bar XXX', 'baz XXX qux', 'foobar XXX' }, get_lines())
316      -- "zqgn" is the same; so is a backward search ("zq#").
317      clear_cursors()
318      feed('uzqgn')
319      eq(4, ncursors())
320      clear_cursors()
321      feed('zq#')
322      eq(4, ncursors())
323      eq(0, api.nvim_get_vvar('searchforward')) -- The motion's direction is preserved.
324
325      -- A "/" search likewise, also with several matches per line.
326      clear_cursors()
327      api.nvim_buf_set_lines(0, 0, -1, true, { 'ab ab ab', 'xx ab' })
328      feed('gg0/ab<CR>') -- the cursor lands on the second "ab"
329      feed('zqn')
330      eq(4, ncursors())
331      feed('x')
332      eq({ 'b b b', 'xx b' }, get_lines())
333
334      -- In mappings: an operator alias ("gz"); an edit after "zq" applies at every cursor it placed.
335      clear_cursors()
336      n.exec_lua(function()
337        vim.keymap.set('n', 'gz', function()
338          return 'zq'
339        end, { expr = true })
340      end)
341      command('nnoremap <F3> zq*cgnX<Esc>')
342      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo bar', 'foo baz', 'qux foo' })
343      feed('gg0gz*')
344      eq(3, ncursors())
345      clear_cursors()
346      feed('<F3>')
347      eq({ 'X bar', 'X baz', 'qux X' }, get_lines())
348
349      -- Placement uses the real search engine, so it matches what "n" finds under the current
350      -- case options. 'ignorecase': "/foo" matches all three cases.
351      clear_cursors()
352      command('set ignorecase')
353      api.nvim_buf_set_lines(0, 0, -1, true, { 'Foo foo FOO' })
354      feed('gg0/foo<CR>')
355      feed('zqn')
356      eq(3, ncursors())
357      feed('gUiw')
358      eq({ 'FOO FOO FOO' }, get_lines())
359
360      -- 'smartcase': an uppercase letter in the pattern forces case-sensitivity.
361      clear_cursors()
362      command('set smartcase')
363      api.nvim_buf_set_lines(0, 0, -1, true, { 'Foo foo Foo' })
364      feed('gg0/Foo<CR>') -- only the two "Foo"s, not "foo"
365      feed('zqn')
366      eq(2, ncursors())
367      feed('x')
368      eq({ 'oo foo oo' }, get_lines())
369
370      -- 'nowrapscan': from the match at (or after) primary; none if no match.
371      clear_cursors()
372      command('set nowrapscan')
373      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo x' })
374      fn.setreg('/', 'foo')
375      feed('$zqN') -- Backwards. Places at "x".
376      eq(0, ncursors())
377      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo bar foo' })
378      feed('$hzq#') -- Mid-word on the last "foo": at its start.
379      eq({ { 0, 8 } }, anchors())
380      eq({ 1, 8 }, api.nvim_win_get_cursor(0))
381    end)
382
383    it('zq{motion} {Visual} bounds, per-cursor gv', function()
384      -- Motion: each step, like typing the motion again. The primary stays, and gets a cursor.
385      local screen = Screen.new(30, 5)
386      cursors({ 'aa bb cc', 'dd ee' }, '')
387      feed('zqw')
388      eq({ 1, 0 }, api.nvim_win_get_cursor(0))
389      screen:expect({
390        condition = function()
391          eq('normal', screen.mode) -- Not "operator".
392        end,
393      })
394      -- ("w" on the last word stops at its end.)
395      eq({ { 0, 0 }, { 0, 3 }, { 0, 6 }, { 1, 0 }, { 1, 3 }, { 1, 4 } }, anchors())
396      -- A count applies to the motion ("2zqw" is "zq2w": every 2nd word).
397      clear_cursors()
398      cursors({ 'aa bb cc dd ee' }, '')
399      feed('2zqw')
400      eq({ { 0, 0 }, { 0, 6 }, { 0, 12 }, { 0, 13 } }, anchors())
401      -- Forward motions only: a backward motion has no step after the cursor.
402      clear_cursors()
403      feed('$zqb')
404      eq(0, ncursors())
405      -- A step that stays ("ti" before an "i") retries from the next char.
406      clear_cursors()
407      cursors({ '#include <limits.h>' }, '')
408      feed('zqti')
409      eq({ { 0, 0 }, { 0, 10 }, { 0, 12 } }, anchors())
410      -- A search that wraps on its first step (no match after the cursor).
411      clear_cursors()
412      fn.setline(1, { 'foo x foo y' })
413      feed('/foo<CR>$zqn')
414      eq({ 1, 0 }, api.nvim_win_get_cursor(0)) -- Not on a match: moves to the next one, like "n".
415      eq({ { 0, 0 }, { 0, 6 } }, anchors())
416      clear_cursors()
417      feed('Gzqj') -- "j" fails on the last line.
418      eq(1, ncursors())
419      -- 3-key motion ("g`a").
420      clear_cursors()
421      feed('0fxmagg0zqg`a')
422      eq({ { 0, 0 }, { 0, 4 } }, anchors())
423      -- The steps do not scroll the window.
424      clear_cursors()
425      api.nvim_buf_set_lines(0, 0, -1, true, fn['repeat']({ 'x' }, 100))
426      feed('50Gztzqj')
427      eq({ 50, 50 }, { fn.line('w0'), fn.line('.') })
428      -- The primary is considered a zq "step" only if the motion lands on it.
429      clear_cursors()
430      cursors({ 'xx', 'xbc a da' }, 'jl')
431      feed('zqfa')
432      eq({ 2, 4 }, api.nvim_win_get_cursor(0))
433      eq({ { 1, 4 }, { 1, 7 } }, anchors())
434      clear_cursors()
435      feed('zqfz') -- Fails from the primary (no "z").
436      eq({ 2, 4 }, api.nvim_win_get_cursor(0))
437      eq(0, ncursors())
438
439      -- {Visual}zq{motion} limits to the selection. Primary + existing cursor (1:3) stays.
440      clear_cursors()
441      cursors({ 'aa bb', 'cc dd', 'ee ff', 'gg hh' }, 'j')
442      feed('gg3lQ2G0Vjzqw')
443      eq({ 3, 0 }, api.nvim_win_get_cursor(0))
444      eq({ { 0, 3 }, { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, anchors())
445      -- Follow mode ("q="): the motion is the operator's ("operator" atom), not followed.
446      clear_cursors()
447      cursors({ 'aa bb', 'cc dd', 'ee ff', 'gg hh' }, '')
448      feed('3lQ2G01q=')
449      atoms_start()
450      feed('zqw')
451      eq({ { type = 'operator', keys = 'zqw' } }, atoms_tail(1, 'type', 'keys'))
452      eq(
453        { { 0, 3 }, { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 }, { 3, 0 }, { 3, 3 }, { 3, 4 } },
454        anchors()
455      )
456      feed('2q=')
457      -- "*" searches the word at the cursor, not at the selection start.
458      clear_cursors()
459      cursors({ 'aa bb', 'bb aa', 'aa bb' }, '')
460      feed('Vjzq*')
461      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
462      eq({ { 0, 3 }, { 1, 0 } }, anchors())
463
464      -- Failed motion does not place cursors.
465      clear_cursors()
466      feed('Vkzq/zz<CR>') -- Failed motion: no cursors, the cursor stays.
467      eq({ 1, 0 }, api.nvim_win_get_cursor(0))
468      eq(0, ncursors())
469      feed('Vjzqfx') -- Failed from selection start (no "x").
470      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
471      eq(0, ncursors())
472
473      -- The steps iterate from the selection-start until selection-end.
474      -- The steps are internal, not captured/cascaded.
475      command('xnoremap j gj')
476      command('autocmd CmdAtom * let g:atoms = 1')
477      for motion, want in pairs({
478        ['0'] = { { 1, 0 } },
479        ['^'] = { { 1, 2 } },
480        ['$'] = { { 1, 6 } },
481        w = { { 1, 2 }, { 1, 5 }, { 2, 0 }, { 3, 2 } },
482        j = { { 1, 0 }, { 2, 0 }, { 3, 0 } }, -- One per line, at the cursor column.
483        ['+'] = { { 1, 2 }, { 2, 0 }, { 3, 2 } },
484      }) do
485        clear_cursors()
486        cursors({ 'x', '  aa bb', 'cc', '  dd', 'y' }, '')
487        feed('jV2jzq' .. motion)
488        eq(want, anchors(), motion)
489        -- The primary (4:0) is a "j" step and stays; else it moves to the first step.
490        local first = want[1]
491        local cursor = motion == 'j' and { 4, 0 } or { first[1] + 1, first[2] }
492        eq(cursor, api.nvim_win_get_cursor(0), motion)
493      end
494
495      -- {Visual}zq blockwise: each line, bounded by blockwise columns (or short-line end).
496      clear_cursors()
497      cursors({ 'abc', 'def', 'g', '', 'hij' }, '')
498      feed('<C-v>4jzql')
499      eq({ { 0, 0 }, { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 } }, anchors())
500      clear_cursors()
501      cursors({ 'abc', 'def', 'g', '', 'hij' }, '')
502      feed('l<C-v>4jzql')
503      eq({ 5, 1 }, api.nvim_win_get_cursor(0))
504      eq({ { 0, 1 }, { 1, 1 }, { 2, 1 }, { 3, 0 }, { 4, 1 } }, anchors())
505      feed('A;<Esc>')
506      eq({ 'abc;', 'def;', 'g;', ';', 'hij;' }, get_lines())
507      feed('u')
508
509      -- A search motion only stops at a match.
510      clear_cursors()
511      fn.setreg('/', 'e')
512      feed('gg0l<C-v>4jzqn')
513      eq({ 2, 1 }, api.nvim_win_get_cursor(0))
514      eq({ { 1, 1 } }, anchors())
515      clear_cursors()
516      cursors({ 'aa bb cc dd', 'ee ff gg hh' }, '')
517      feed('3l<C-v>j4lzqw')
518      eq({ { 0, 3 }, { 0, 6 }, { 1, 3 }, { 1, 6 } }, anchors())
519      eq({ 1, 3 }, api.nvim_win_get_cursor(0)) -- Not on a step: moved to the first.
520
521      -- "gv" selects per-cursor visual areas defined by "zq{search}".
522      clear_cursors()
523      cursors({ 'foo x foo', 'bar foo' }, '')
524      feed('zq*gvcX<Esc>')
525      eq({ 'X x X', 'bar X' }, get_lines())
526      -- Also an existing cursor (its '< '> "fo").
527      clear_cursors()
528      cursors({ 'foo bar foo' }, 'Qwvly')
529      feed('/foo<CR>zqngvcX<Esc>')
530      eq({ 'X bar X' }, get_lines())
531      -- A zq step on an existing cursor sets its '< '> too. Matches "foo" (not "fo" from "vly").
532      clear_cursors()
533      cursors({ 'x foo', 'y foo', 'z foo' }, '')
534      feed('Vjzq/foo<CR>')
535      eq({ 1, 2 }, api.nvim_win_get_cursor(0))
536      feed('gvcX<Esc>')
537      eq({ 'x X', 'y X', 'z foo' }, get_lines())
538      clear_cursors()
539      feed('<Esc>')
540      eq({ 'V', 1, 2 }, { fn.visualmode(), fn.line("'<"), fn.line("'>") })
541
542      -- Not supported: textobjects, non-motions ("zqx"), non-repeatable ("label" plugin).
543      clear_cursors()
544      cursors({ 'aa bb cc' }, '')
545      n.exec_lua(function()
546        vim.keymap.set('o', '<F2>', function()
547          vim.api.nvim_win_set_cursor(0, { 1, 6 })
548        end)
549      end)
550      for _, keys in ipairs({ 'zqiw', 'zqx', 'zq<F2>' }) do
551        feed(keys)
552        eq(0, ncursors(), keys)
553        eq({ 1, 0 }, api.nvim_win_get_cursor(0), keys)
554      end
555      eq({ 'aa bb cc' }, get_lines())
556    end)
557
558    it('does nothing without a previous search (E35)', function()
559      fn.setline(1, { 'foo foo' })
560      feed('zqn')
561      eq(0, ncursors())
562      feed('vlzqgn') -- {Visual}zq likewise adds nothing.
563      eq(0, ncursors())
564    end)
565
566    it('{Visual}zqgn limits matches to selection (linewise)', function()
567      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo one', 'foo foo', 'foo y foo', 'foo end' })
568      feed('gg0/foo<CR>') -- pattern; cursor lands on line 2's first "foo"
569      feed('Vj') -- linewise: lines 2-3
570      feed('zqgn')
571      -- 4 matches within lines 2-3 (line 1/4 "foo" are excluded), including the primary's.
572      eq(4, ncursors())
573      eq({ 3, 0 }, api.nvim_win_get_cursor(0)) -- primary stays put (selection end), not moved
574      feed('x') -- the selection ended on a match, so the primary edits with the others
575      eq({ 'foo one', 'oo oo', 'oo y oo', 'foo end' }, get_lines())
576
577      -- Charwise selection only matches within its columns.
578      clear_cursors()
579      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo foo', 'bar', 'foo foo' })
580      feed('gg0/foo<CR>') -- cursor on line 1's second "foo"
581      feed('vj') -- Charwise from line 1's second "foo" into line 2.
582      feed('zqgn')
583      -- Not line 1's first "foo" (before the selection), nor line 3.
584      eq({ 1, 4 }, api.nvim_win_get_cursor(0))
585      eq({ { 0, 4 } }, anchors())
586    end)
587  end)
588
589  describe('mouse', function()
590    it('<C-LeftMouse> toggles a cursor at the click, without moving the primary', function()
591      command('set mousetime=0') -- repeated clicks must not count as double-clicks
592      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
593      feed('gg0')
594      api.nvim_input_mouse('left', 'press', 'C', 0, 2, 0) -- ctrl-click on line 3
595      api.nvim_input_mouse('left', 'release', 'C', 0, 2, 0)
596      -- The primary did not move; a cursor was added at left-click.
597      eq(1, fn.line('.'))
598      eq({ { 2, 0 } }, anchors())
599      feed('x') -- cascades to the clicked position
600      eq({ 'aa', 'bbb', 'cc' }, get_lines())
601      -- CTRL-click on the existing cursor removes it (toggle).
602      api.nvim_input_mouse('left', 'press', 'C', 0, 2, 0)
603      api.nvim_input_mouse('left', 'release', 'C', 0, 2, 0)
604      eq(0, ncursors())
605
606      -- Toggling another cursor keeps the cursor under the primary.
607      feed('Q')
608      for _ = 1, 2 do
609        api.nvim_input_mouse('left', 'press', 'C', 0, 2, 0)
610        api.nvim_input_mouse('left', 'release', 'C', 0, 2, 0)
611      end
612      eq({ { 0, 0 } }, anchors())
613      feed('Q')
614
615      -- CTRL-click keeps "q=" follow-mode (unlike Q).
616      feed('ggQj')
617      feed('q=')
618      api.nvim_input_mouse('left', 'press', 'C', 0, 2, 0)
619      api.nvim_input_mouse('left', 'release', 'C', 0, 2, 0)
620      feed('l')
621      eq({ { 0, 1 }, { 2, 1 } }, anchors()) -- Still following: the motion cascaded.
622      feed('q=') -- Off.
623      -- No-op in Insert mode.
624      feed('i')
625      api.nvim_input_mouse('left', 'press', 'C', 0, 0, 1)
626      api.nvim_input_mouse('left', 'release', 'C', 0, 0, 1)
627      eq(2, ncursors())
628      eq(2, fn.line('.'))
629      eq('i', fn.mode())
630      feed('<Esc>')
631    end)
632
633    it('middle-click paste applies once', function()
634      -- Fake clipboard provider: "*" must not touch the real system clipboard.
635      clear('--cmd', 'set rtp^=test/functional/fixtures')
636      fn.setline(1, { 'abc', 'def', 'ghi' })
637      fn.setreg('*', 'NEW') -- middle-click pastes the * register
638      feed('gg0')
639      api.nvim_input_mouse('middle', 'press', '', 0, 2, 0)
640      api.nvim_input_mouse('middle', 'release', '', 0, 2, 0)
641      feed('<Ignore>')
642      -- Sanity: middle-click pastes (no cursors yet).
643      local _, pasted = table.concat(get_lines(), '\n'):gsub('NEW', '')
644      eq(1, pasted)
645      feed('ggQjQ2j') -- cursors on lines 1-2, primary below
646      api.nvim_input_mouse('middle', 'press', '', 0, 0, 0)
647      api.nvim_input_mouse('middle', 'release', '', 0, 0, 0)
648      feed('<Ignore>')
649      -- One more paste at the click position; no paste at the other cursors.
650      _, pasted = table.concat(get_lines(), '\n'):gsub('NEW', '')
651      eq(2, pasted)
652    end)
653  end)
654
655  describe('normal-mode cascade', function()
656    it("cursor-local marks ('[ '] '. '^)", function()
657      cursors({ 'aa bb', 'cc dd' }, 'Qj')
658      feed('gUiw')
659      eq({ 'AA bb', 'CC dd' }, get_lines())
660      -- Each cursor's replay set its own change marks, so a mapping reading them acts per cursor.
661      command('nnoremap <F2> `[v`]u')
662      feed('<F2>')
663      eq({ 'aa bb', 'cc dd' }, get_lines())
664
665      -- '. and '^ are per-cursor: a cascaded mapping jumps to their cursor-local positions.
666      clear_cursors()
667      cursors({ 'abord1 line', 'abord2 line', 'abord3 line' })
668      command([[nnoremap <F4> lx$`.iZ<Esc>]])
669      feed('<F4>')
670      eq({ 'aZord1 line', 'aZord2 line', 'aZord3 line' }, get_lines())
671      eq({ 3, 1 }, api.nvim_buf_get_mark(0, '.'))
672      eq({ 3, 2 }, api.nvim_buf_get_mark(0, '^'))
673
674      -- The primary's marks are shifted by edits from other cursors.
675      clear_cursors()
676      cursors({ 'a', 'b', 'c', 'd', 'e' }, 'Q3j')
677      feed('dd') -- Delete line 1.
678      eq({ 'b', 'c', 'e' }, get_lines())
679      eq(3, fn.getpos("'[")[2])
680
681      -- A cursor without a change yet has no '., like a new editor, so "`." fails there (E20).
682      clear_cursors()
683      command('let v:errmsg = ""')
684      api.nvim_buf_set_lines(0, 0, -1, true, { 'abc', 'def', 'ghi', 'jkl' })
685      feed('Gx') -- The primary's change.
686      feed('ggQjQjq=`.q=')
687      eq({ { 0, 0 }, { 1, 0 } }, anchors())
688      eq({ 4, 0 }, api.nvim_win_get_cursor(0))
689      eq('E20: Mark not set', api.nvim_get_vvar('errmsg'))
690    end)
691
692    it('CTRL-C interrupts the cascade; one "u" undoes the partial edit', function()
693      local nlines = 5000
694      local lines = {} ---@type string[]
695      for i = 1, nlines do
696        lines[i] = 'aaa'
697      end
698      api.nvim_buf_set_lines(0, 0, -1, true, lines)
699      api.nvim_win_set_cursor(0, { 1, 0 })
700      for i = 2, nlines do
701        add_cursor(0, { i, 0 })
702      end
703      eq(nlines - 1, ncursors())
704
705      -- Interrupt from in-process on_key handler. The cascade runs too fast for test-runner CTRL-C.
706      n.exec_lua(function()
707        _G.keys_seen, _G.cascading_seen = 0, false
708        vim.on_key(function()
709          _G.keys_seen = _G.keys_seen + 1
710          _G.cascading_seen = _G.cascading_seen or vim.api.nvim__mcursor_cascading()
711          if _G.keys_seen == 1000 then
712            vim.fn.interrupt()
713          end
714        end)
715      end)
716
717      feed('x') -- Primary edit + cascade over ~5000 cursors...
718      n.poke_eventloop()
719      eq(true, n.exec_lua('return _G.cascading_seen'))
720      local edited, unedited = 0, 0
721      for _, l in ipairs(get_lines()) do
722        if l == 'aa' then
723          edited = edited + 1
724        elseif l == 'aaa' then
725          unedited = unedited + 1
726        end
727      end
728      eq(nlines, edited + unedited) -- no line was half-edited
729      eq(true, edited >= 1) -- the primary's own edit happened
730      eq(true, unedited >= 1) -- >=1 cursor did NOT cascade
731      -- The partial cascade is still one undo block.
732      feed('u')
733      eq(lines, get_lines())
734    end)
735
736    it('line inserts shift other cursors; u restores them', function()
737      -- "o" inserts a line at each cursor; cursors below must shift. With the primary between the
738      -- cursors, its own insert shifts the other cursors' extmarks BEFORE the replays.
739      for _, case in ipairs({ { 'QjQj', 6 }, { 'QjjQk', 4 } }) do
740        local place, primary = case[1], case[2]
741        clear_cursors()
742        cursors({ 'aaa', 'bbb', 'ccc' }, place)
743        feed('oX<Esc>')
744        eq({ 'aaa', 'X', 'bbb', 'X', 'ccc', 'X' }, get_lines(), place)
745        eq(primary, fn.line('.'), place) -- The primary shifted too.
746        -- Undo moves every cursor back (cursor extmarks restore on undo).
747        feed('u')
748        eq({ 'aaa', 'bbb', 'ccc' }, get_lines(), place)
749        feed('x')
750        eq({ 'aa', 'bb', 'cc' }, get_lines(), place)
751      end
752    end)
753
754    it('per-cursor on fold contents, not the fold itself', function()
755      -- If the primary cursor operates on a closed fold it applies to the whole fold
756      -- (|fold-behavior|); but *replayed* edits/motions ignore folds, and operate on the per-cursor
757      -- text within folds (if there happens to be one at the given cursor).
758
759      fn.setline(1, { 'aaa', 'bbb', 'ccc', 'ddd' })
760      feed('3G0Q')
761      command('2,4fold')
762      eq(2, fn.foldclosed(3))
763      feed('gg0')
764      feed('x')
765      eq({ 'aa', 'bbb', 'cc', 'ddd' }, get_lines())
766      feed('dd')
767
768      -- Replayed "dd" deletes only the line (within the fold) at cursor. And the stays closed.
769      eq({ 'bbb', 'ddd' }, get_lines())
770      eq({ 1, 2 }, { fn.foldclosed(1), fn.foldclosedend(1) })
771      eq({ { 1, 0 } }, anchors())
772
773      -- Insert-cascade entry ("cc") acts on the fold contents, not the fold itself.
774      clear_cursors()
775      feed('zE') -- Eliminate the fold above, it would misdirect "3j" below.
776      cursors({ 'aaa', 'bbb', 'ccc', 'ddd', 'eee' }, '3jQgg')
777      command('3,5fold')
778      eq(3, fn.foldclosed(4))
779      feed('gg')
780      feed('ccX<Esc>')
781      eq({ 'X', 'bbb', 'ccc', 'X', 'eee' }, get_lines())
782      eq({ 3, 5 }, { fn.foldclosed(4), fn.foldclosedend(4) })
783      eq({ { 3, 0 } }, anchors())
784
785      -- Replayed fold command ("zN") must not re-enable fold semantics mid-cascade.
786      clear_cursors()
787      feed('zE')
788      command('nnoremap X zN:normal! dd<CR>')
789      cursors({ 'aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff' }, '3jQgg')
790      command('3,5fold')
791      feed('gg')
792      feed('X') -- Performs "dd".
793      eq({ 'bbb', 'ccc', 'eee', 'fff' }, get_lines())
794      eq({ 2, 3 }, { fn.foldclosed(2), fn.foldclosedend(2) })
795
796      -- Primary cursor keeps the usual |fold-behavior|: its "dd" deletes the whole fold.
797      -- But the replay does not: it only deletes the line at each cursor.
798      clear_cursors()
799      feed('zE')
800      cursors({ 'aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff' }, '4jQgg')
801      command('2,3fold')
802      feed('2G') -- Into the closed fold.
803      feed('dd')
804      eq({ 'aaa', 'ddd', 'fff' }, get_lines())
805      eq({ { 2, 0 } }, anchors())
806
807      -- Follow-mode motions also ignore closed folds. Replayed "j" steps into the fold.
808      clear_cursors()
809      feed('zE')
810      cursors({ 'aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg' }, 'Q4j')
811      command('2,4fold')
812      feed('q=')
813      feed('jj')
814      eq({ { 2, 0 } }, anchors())
815      eq(7, fn.line('.'))
816      eq(2, fn.foldclosed(3))
817    end)
818
819    it('CTRL-D scrolling does not affect the other cursors', function()
820      local screen = Screen.new(30, 10)
821      local l = {}
822      for i = 1, 50 do
823        l[#l + 1] = ('line%d'):format(i)
824      end
825      cursors(l)
826      -- Scrolling is viewport-dependent, not repeatable. Other cursors do not move, even in
827      -- follow-mode.
828      feed('<C-d>')
829      eq({ { 0, 0 }, { 1, 0 } }, anchors())
830      feed('q=')
831      feed('<C-d>')
832      feed('q=')
833      eq({ { 0, 0 }, { 1, 0 } }, anchors())
834      feed('<C-u>')
835      -- An edit still cascades to the off-screen cursors, and the viewport stays anchored
836      -- (replays scroll the window; the cascade restores it).
837      feed('x')
838      eq({ 'ine1', 'ine2' }, { get_lines()[1], get_lines()[2] })
839      screen:expect([[
840        line5                         |
841        line6                         |
842        ^ine7                          |
843        line8                         |
844        line9                         |
845        line10                        |
846        line11                        |
847        line12                        |
848        line13                        |
849                                      |
850      ]])
851    end)
852  end)
853
854  describe('composite/mapping', function()
855    it('Visual-mode mapping that creates cursors (Q) #41694', function()
856      command('xmap I Q0i')
857
858      -- The mapping itself creates the cursors; until then, nothing consumes atoms.
859      cursors({ 'test', 'nvim', '', 'test', 'nvim' }, '')
860      feed('gg$jjjVjI')
861      feed('bad<Esc>')
862      eq({ 'test', 'nvim', '', 'badtest', 'badnvim' }, get_lines())
863
864      -- Existing cursors, and a CmdAtom consumer:
865      clear_cursors()
866      cursors({ 'test', 'nvim', '', 'test', 'nvim' }, '')
867      feed('gg$Qjjj')
868      atoms_start()
869      feed('VjI')
870      feed('bad<Esc>')
871      eq({ 'badtest', 'nvim', '', 'badtest', 'badnvim' }, get_lines())
872      -- "Q" is excluded: it is cursor-management, not part of the edit.
873      eq({ '01i\27ibad\27' }, atoms_tail(1))
874    end)
875
876    it('jump (absolute motion) in a mapping is not replayed, like a mark', function()
877      -- "G" would move every cursor to the same line; only the edit replays per-cursor.
878      command('nnoremap X Gdd')
879      cursors({ 'a', 'b', 'c', 'd' }, 'jQ')
880      feed('X')
881      eq({ 'a', 'c' }, get_lines())
882    end)
883
884    it('global op (undo/redo, g CTRL-A) does not cascade', function()
885      -- Mapping that performs a "global op" must not cascade.
886
887      -- vim-repeat maps u/U/<C-R> to undo/redo wrappers.
888      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
889      feed('gg0Qj0Qj0') -- 3 cursors
890      feed('x') -- one cascade: aa,bb,cc
891      eq({ 'aa', 'bb', 'cc' }, get_lines())
892      command('nnoremap <silent> u :<C-U>undo<CR>')
893      command('nnoremap <silent> <C-R> :<C-U>redo<CR>')
894      feed('u') -- One undo of the cascade, not per-cursor.
895      eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
896      feed('<C-R>') -- Redo mapping does not cascade.
897      eq({ 'aa', 'bb', 'cc' }, get_lines())
898      -- Nested normal_execute() after the undo, in the same mapping.
899      command('nnoremap <silent> u :<C-U>undo <Bar> normal! l<CR>')
900      feed('u')
901      eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
902
903      -- Follow-mode, where the undo's cursor-move would attempt LHS-replay. #42037
904      clear_cursors()
905      command('nnoremap u u<Cmd>let g:did_u = 1<CR>') -- Multi-command RHS.
906      command('nnoremap <C-R> <C-R>')
907      command('nnoremap gm yiwp')
908      cursors({ 'aa', 'bb' }, 'vipQ')
909      feed('gmgm')
910      eq({ 'aaaaaaaa', 'bbbbbbbb' }, get_lines())
911      feed('u')
912      eq({ 'aaaa', 'bbbb' }, get_lines())
913      feed('u')
914      eq({ 'aa', 'bb' }, get_lines())
915      feed('<C-R>')
916      eq({ 'aaaa', 'bbbb' }, get_lines())
917      feed('0x') -- Cursors are still in place.
918      eq({ 'aaa', 'bbb' }, get_lines())
919
920      -- "U" (line-undo) is also treated as a "global op".
921      clear_cursors()
922      command('nnoremap U U<Cmd>let g:did_U = 1<CR>')
923      cursors({ 'aaa', 'bbb' }, 'Qj0')
924      feed('x')
925      eq({ 'aa', 'bb' }, get_lines())
926      feed('U')
927      eq({ 'aaa', 'bb' }, get_lines())
928
929      -- g CTRL-A (counter) applies once, not per-cursor. Also in follow-mode.
930      command('nnoremap ,n g<C-A><Cmd>let g:did_n = 1<CR>')
931      for _, place in ipairs({ 'Qj0Qj0', 'VGQ' }) do
932        clear_cursors()
933        cursors({ 'a', 'b', 'c' }, place)
934        feed(',n')
935        eq({ '1a', '2b', '3c' }, get_lines(), place)
936      end
937    end)
938  end)
939
940  describe('. (dot-repeat)', function()
941    it('repeats operators, pre-cursor edits, inserts and changes at all cursors', function()
942      -- Operator.
943      cursors({ 'aaa', 'bbb', 'ccc' })
944      feed('x')
945      eq({ 'aa', 'bb', 'cc' }, get_lines())
946      feed('.')
947      eq({ 'a', 'b', 'c' }, get_lines())
948      -- An edit made before placing cursors repeats at all of them.
949      clear_cursors()
950      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa', 'bbb', 'ccc' })
951      feed('gg0')
952      feed('x')
953      eq({ 'aa', 'bbb', 'ccc' }, get_lines())
954      feed('QjQj')
955      feed('.')
956      eq({ 'a', 'bb', 'cc' }, get_lines())
957      -- Insert.
958      clear_cursors()
959      cursors({ 'aaa', 'bbb' }, 'Qj')
960      feed('iZ<Esc>')
961      eq({ 'Zaaa', 'Zbbb' }, get_lines())
962      feed('.')
963      eq({ 'ZZaaa', 'ZZbbb' }, get_lines())
964      -- Change, with a q= move between the change and the repeat.
965      clear_cursors()
966      cursors({ 'one two', 'one two' }, 'Qj')
967      feed('cwX<Esc>')
968      eq({ 'X two', 'X two' }, get_lines())
969      feed('q=')
970      feed('w')
971      feed('q=')
972      feed('.')
973      eq({ 'X X', 'X X' }, get_lines())
974    end)
975  end)
976
977  describe('per-cursor registers', function()
978    it('yy/p roundtrips each cursor through its own register', function()
979      cursors({ 'aaa', 'bbb' }, 'Qj')
980      feed('yy')
981      feed('p')
982      eq({ 'aaa', 'aaa', 'bbb', 'bbb' }, get_lines())
983    end)
984
985    it('insert-mode <C-R>x #41933', function()
986      for _, case in ipairs({
987        { '0', 'yiw', { 'aaa x-aaa', 'ccc y-ccc' } },
988        { 'a', '"ayiw', { 'aaa x-aaa', 'ccc y-ccc' } },
989        { '"', 'yiw', { 'aaa x-aaa', 'ccc y-ccc' } },
990        { '-', 'diw', { ' x-aaa', ' y-ccc' } },
991      }) do
992        local reg, fill, want = case[1], case[2], case[3]
993        clear_cursors()
994        cursors({ 'aaa x', 'ccc y' }, 'Qj0')
995        feed(fill)
996        feed(('A-<C-R>%s'):format(reg))
997        eq(want, get_lines(), reg) -- Live, before <Esc>.
998        feed('Z<Esc>')
999        eq({ want[1] .. 'Z', want[2] .. 'Z' }, get_lines(), reg)
1000      end
1001    end)
1002
1003    it('empty at cursor init restores as empty', function()
1004      fn.setline(1, { 'one two', 'three four' })
1005      feed('gg0')
1006      feed('Q') -- this cursor's snapshot: @a is EMPTY
1007      feed('j0')
1008      command([[let @a = 'LEAK']]) -- primary-only write (synthetic: no cascade)
1009      feed('"ap')
1010      -- The replay loads the other cursor's register snapshot, where @a was empty: nothing
1011      -- pastes there (empty registers are omitted; the primary's @a must not leak through).
1012      eq({ 'one two', 'tLEAKhree four' }, get_lines())
1013    end)
1014
1015    it('dW + p swaps words using each cursor register', function()
1016      cursors({ 'one two', 'three four' }, 'Qj')
1017      feed('q=')
1018      feed('dW')
1019      eq({ 'two', 'four' }, get_lines())
1020      feed('E')
1021      feed('p')
1022      feed('q=')
1023      eq({ 'twoone ', 'fourthree ' }, get_lines())
1024    end)
1025
1026    it('clearing joins/gathers the per-cursor registers (DWIM)', function()
1027      cursors({ 'one two', 'three four' }, 'Qj')
1028      feed('dW')
1029      eq({ 'two', 'four' }, get_lines())
1030      clear_cursors()
1031      -- On exit, each cursor's delete is joined (document order) into '"'.
1032      eq('one \nthree \n', fn.getreg('"'))
1033      feed('Go<Esc>p')
1034      eq({ 'two', 'four', '', 'one ', 'three ' }, get_lines())
1035
1036      -- A cursor whose replays never wrote a register contributes nothing: it has no snapshot,
1037      -- so the pre-session '"' cannot be joined in as if it were that cursor's delete.
1038      fn.setreg('"', 'STALE')
1039      cursors({ '', 'abc' }, 'Qj')
1040      feed('x') -- writes a register at the primary only: "x" on the cursor's empty line is a no-op
1041      clear_cursors()
1042      eq('a', fn.getreg('"')) -- No contributions to join; primary's register is untouched.
1043      eq('v', fn.getregtype('"'))
1044
1045      -- Partial-range clear deletes cursors without ending the session; no join/gather (yet).
1046      cursors({ 'one two', 'three four', 'five six' })
1047      feed('dW')
1048      eq({ 'two', 'four', 'six' }, get_lines())
1049      n.exec_lua(
1050        [[vim.api.nvim_buf_clear_namespace(0, vim.api.nvim_create_namespace('nvim.multicursor'), 0, 1)]]
1051      )
1052      eq('five ', fn.getreg('"')) -- Primary's own delete, unjoined.
1053      clear_cursors()
1054      eq('three \nfive \n', fn.getreg('"')) -- All cursors cleared => yanks joined.
1055    end)
1056
1057    it('visual p pastes each cursor register over the selection', function()
1058      cursors({ 'aaa X', 'bbb Y' }, 'Qj')
1059      feed('yiw')
1060      feed('q=')
1061      feed('w')
1062      feed('q=')
1063      feed('viwp')
1064      eq({ 'aaa aaa', 'bbb bbb' }, get_lines())
1065    end)
1066  end)
1067
1068  describe('operator matrix', function()
1069    it('operators cascade at each cursor', function()
1070      assert_rows({
1071        -- x deletes a char at each cursor.
1072        { lines = { 'aaa', 'bbb', 'ccc' }, keys = 'QjQjx', expect = { 'aa', 'bb', 'cc' } },
1073        -- dw deletes a word at each cursor.
1074        {
1075          lines = { 'hello world', 'foo bar', 'one two' },
1076          keys = 'QjQjdw',
1077          expect = { 'world', 'bar', 'two' },
1078        },
1079        -- 2x deletes 2 chars at each cursor.
1080        { lines = { 'aaaa', 'bbbb', 'cccc' }, keys = 'QjQj2x', expect = { 'aa', 'bb', 'cc' } },
1081        -- dd deletes a line at each cursor.
1082        {
1083          lines = { 'a1', 'a2', 'b1', 'b2', 'c1', 'c2' },
1084          keys = 'Q2jQ2jdd',
1085          expect = { 'a2', 'b2', 'c2' },
1086        },
1087        -- D deletes to EOL, C changes to EOL.
1088        {
1089          lines = { 'one two', 'three four' },
1090          place = 'gg0ll',
1091          keys = 'QjD',
1092          expect = { 'on', 'th' },
1093        },
1094        {
1095          lines = { 'one two', 'three four' },
1096          place = 'gg0ll',
1097          keys = 'QjCX<Esc>',
1098          expect = { 'onX', 'thX' },
1099        },
1100        -- 2cl changes 2 chars.
1101        { lines = { 'abcd', 'efgh' }, keys = 'Qj2clXY<Esc>', expect = { 'XYcd', 'XYgh' } },
1102        -- ~ toggles case and advances.
1103        { lines = { 'abc', 'def' }, keys = 'Qj~~', expect = { 'ABc', 'DEf' } },
1104        -- cT{char} changes backwards.
1105        {
1106          lines = { 'x_abcY', 'w_defgZ' },
1107          place = 'gg$',
1108          keys = 'Qj$cT_M<Esc>',
1109          expect = { 'x_MY', 'w_MZ' },
1110        },
1111        -- d4h deletes backwards.
1112        { lines = { 'abcdef', 'ghijkl' }, place = 'gg$', keys = 'Qj$d4h', expect = { 'af', 'gl' } },
1113        -- c2aw changes counted text objects.
1114        {
1115          lines = { 'one two three', 'foo bar baz' },
1116          keys = 'Qjc2awX<Esc>',
1117          expect = { 'Xthree', 'Xbaz' },
1118        },
1119        -- ci( on empty parens inserts inside.
1120        {
1121          lines = { 'a()b', 'c()d' },
1122          place = 'gg0l',
1123          keys = 'Qjci(X<Esc>',
1124          expect = { 'a(X)b', 'c(X)d' },
1125        },
1126        -- ci" seeks forward to the quotes.
1127        {
1128          lines = { 'x "aa" y', 'z "bbb" w' },
1129          keys = 'Qjci"NEW<Esc>',
1130          expect = { 'x "NEW" y', 'z "NEW" w' },
1131        },
1132        -- df{char} cascades with its payload char.
1133        { lines = { 'ab,cd', 'wxy,z' }, keys = 'Qjdf,', expect = { 'cd', 'z' } },
1134        -- [count]r{char} replaces.
1135        { lines = { 'abc', 'def' }, keys = 'Qj2rZ', expect = { 'ZZc', 'ZZf' } },
1136        -- r<CR> and gr{char}: self-terminating replace sessions (no trailing <Esc>) cascade.
1137        {
1138          lines = { 'abcd', 'efgh' },
1139          place = 'gg0l',
1140          keys = 'Qjr<CR>',
1141          expect = { 'a', 'cd', 'e', 'gh' },
1142        },
1143        { lines = { 'abc', 'def' }, keys = 'QjgrZ', expect = { 'Zbc', 'Zef' } },
1144        -- x deletes one multibyte char at each cursor.
1145        { lines = { 'éàü', '日本語' }, keys = 'Qjx', expect = { 'àü', '本語' } },
1146        -- diw leaves the cursor at the deleted region (the "x" probes every cursor).
1147        {
1148          lines = { 'foo bar', 'baz qux', 'aaa bbb' },
1149          place = 'gg0l',
1150          keys = 'QjQjdiw',
1151          expect = { ' bar', ' qux', ' bbb' },
1152          after = 'x',
1153          after_expect = { 'bar', 'qux', 'bbb' },
1154        },
1155        -- guiW lowercases and leaves the cursor at the region start.
1156        {
1157          lines = { 'FOO BAR', 'BAZ QUX' },
1158          place = 'gg0l',
1159          keys = 'QjguiW',
1160          expect = { 'foo BAR', 'baz QUX' },
1161          after = 'x',
1162          after_expect = { 'oo BAR', 'az QUX' },
1163        },
1164        -- An operator with a search-motion payload cascades whole (the atom IS the redobuff);
1165        -- each cursor finds its own match.
1166        {
1167          lines = { 'aaa find end', 'bbb find end' },
1168          keys = 'Qjd/find<CR>',
1169          expect = { 'find end', 'find end' },
1170        },
1171        -- cc preserves per-line indent with 'autoindent'.
1172        {
1173          lines = { '  aaa', '      bbb' },
1174          pre = 'set autoindent',
1175          keys = 'QjccX<Esc>',
1176          expect = { '  X', '      X' },
1177        },
1178        -- >> indents the line at each cursor.
1179        {
1180          lines = { 'foo', 'bar' },
1181          pre = 'set shiftwidth=2',
1182          keys = 'Qj>>',
1183          expect = { '  foo', '  bar' },
1184        },
1185      })
1186    end)
1187  end)
1188
1189  describe('g CTRL-A (counter)', function()
1190    it('inserts an ascending number at each cursor', function()
1191      cursors({ 'a', 'b', 'c' }, 'Qj0Qj0')
1192      feed('g<C-A>')
1193      eq({ '1a', '2b', '3c' }, get_lines())
1194      -- A count sets the starting number.
1195      clear_cursors()
1196      cursors({ 'a', 'b' }, 'Qj0')
1197      feed('5g<C-A>')
1198      eq({ '5a', '6b' }, get_lines())
1199      -- Number overlapping primary/multicursor positions once, without deleting the multicursor.
1200      clear_cursors()
1201      cursors({ 'x', 'y', 'z' }, 'QjQj')
1202      feed('gg0g<C-A>')
1203      eq({ '1x', '2y', 'z' }, get_lines())
1204      eq(2, ncursors())
1205    end)
1206
1207    it('without cursors, g CTRL-A is not a command', function()
1208      fn.setline(1, { 'x 5' })
1209      feed('gg0g<C-A>')
1210      eq({ 'x 5' }, get_lines()) -- beeps, no counter and no increment
1211      feed('<C-A>') -- plain CTRL-A increments as usual
1212      eq({ 'x 6' }, get_lines())
1213    end)
1214
1215    it('number() takes start/step/format', function()
1216      cursors({ 'x', 'x', 'x' }, 'Qj0Qj0')
1217      n.exec_lua([[require('vim._core.mcursor').number(10, 2, '%d) ')]])
1218      eq({ '10) x', '12) x', '14) x' }, get_lines())
1219    end)
1220  end)
1221
1222  describe('extmarks', function()
1223    it('adding an extmark adds a cursor, which cascades', function()
1224      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
1225      add_cursor(0, { 1, 0 })
1226      add_cursor(0, { 2, 0 })
1227      eq({ { 0, 0 }, { 1, 0 } }, anchors())
1228      feed('Gx')
1229      eq({ 'aa', 'bb', 'cc' }, get_lines())
1230
1231      -- Also in a hidden buffer.
1232      command('set hidden')
1233      local other = api.nvim_create_buf(true, false)
1234      api.nvim_buf_set_lines(other, 0, -1, true, { 'xxx', 'yyy' })
1235      add_cursor(other, { 1, 0 })
1236      api.nvim_set_current_buf(other)
1237      feed('Gx')
1238      eq({ 'xx', 'yy' }, get_lines())
1239
1240      -- Ignored if a cursor already exists (no double-apply), unlike "Q" which toggles.
1241      clear_cursors()
1242      fn.setline(1, { 'abcdef', 'ghijkl' })
1243      feed('gg0')
1244      add_cursor(0, { 1, 0 })
1245      add_cursor(0, { 1, 0 })
1246      eq({ { 0, 0 } }, anchors())
1247      feed('j0x')
1248      eq({ 'bcdef', 'hijkl' }, get_lines())
1249    end)
1250
1251    it('deleting an extmark deletes its cursor', function()
1252      cursors({ 'aaa', 'bbb', 'ccc' })
1253      local ns = api.nvim_create_namespace('nvim.multicursor')
1254      local marks = api.nvim_buf_get_extmarks(0, ns, 0, -1, {})
1255      eq(2, #marks)
1256      api.nvim_buf_del_extmark(0, ns, marks[1][1])
1257      feed('x') -- the cursor without a mark is swept; the other cascades
1258      eq({ 'aaa', 'bb', 'cc' }, get_lines())
1259      eq(1, ncursors())
1260    end)
1261
1262    it('exit with cursors active in multiple buffers', function()
1263      cursors({ 'aaa', 'bbb' }, 'Qj')
1264      feed('yy') -- Session-written register, exit path reaches mc_reg_gather.
1265      command('new')
1266      fn.setline(1, { 'ccc' })
1267      add_cursor(0, { 1, 0 })
1268      n.expect_exit(command, 'qall!')
1269    end)
1270
1271    it('cursors are disposed with their buffer', function()
1272      local screen = Screen.new(30, 5)
1273      command('set showcmd')
1274      fn.setline(1, { 'aaa', 'bbb' })
1275      local buf = api.nvim_get_current_buf()
1276      add_cursor(0, { 1, 0 })
1277      add_cursor(0, { 2, 0 })
1278
1279      -- Deleting an unrelated buffer does not dedupe the cursor under the primary. #41651
1280      for _, has_cursor in ipairs({ false, true }) do
1281        local scratch = api.nvim_create_buf(false, true)
1282        if has_cursor then
1283          add_cursor(scratch, { 1, 0 })
1284        end
1285        api.nvim_buf_delete(scratch, { force = true })
1286        eq({ { 0, 0 }, { 1, 0 } }, anchors())
1287      end
1288
1289      command('new')
1290      fn.setreg('"', 'KEEP')
1291      command('bwipeout! ' .. buf)
1292      -- Registers NOT gathered/joined, the cleared cursors are not in curbuf.
1293      eq('KEEP', fn.getreg('"'))
1294      eq('v', fn.getregtype('"'))
1295      fn.setline(1, { 'xxx', 'yyy' })
1296      add_cursor(0, { 1, 0 })
1297      feed('Gx')
1298      eq({ 'xx', 'yy' }, get_lines())
1299      -- The wiped buffer's cursors are gone: only the new one counts.
1300      screen:expect({ any = ' 1×' })
1301    end)
1302  end)
1303
1304  describe('buffers and windows', function()
1305    it('cursors/cascade are per-buffer', function()
1306      -- Cursors cascade only if their buffer is the current buffer.
1307      command('set hidden')
1308      cursors({ 'aaa', 'bbb' }, 'Qj')
1309      local buf_a = api.nvim_get_current_buf()
1310      feed(':enew<CR>') -- Typed, so the buffer switch goes through atom capture.
1311      eq(0, ncursors())
1312      cursors({ 'xxx', 'yyy' }, 'Qj')
1313      local buf_b = api.nvim_get_current_buf()
1314      eq(1, ncursors())
1315      feed('x') -- Cascades only in the current buffer.
1316      eq({ 'xx', 'yy' }, get_lines())
1317      eq({ 'aaa', 'bbb' }, api.nvim_buf_get_lines(buf_a, 0, -1, true))
1318      command('buffer #')
1319      eq(1, ncursors()) -- The extmark-tracked cursor survived the round-trip.
1320      feed('2G0x') -- The cascade resumes.
1321      eq({ 'aa', 'bb' }, get_lines())
1322      eq({ 'xx', 'yy' }, api.nvim_buf_get_lines(buf_b, 0, -1, true))
1323      -- Likewise from another window.
1324      command('split | buffer ' .. buf_b)
1325      feed('2G0x')
1326      eq({ 'x', 'y' }, get_lines())
1327      command('wincmd p')
1328      feed('2G0x')
1329      eq({ 'a', 'b' }, get_lines())
1330    end)
1331
1332    it('atom queued in one buffer does not cascade in another buffer', function()
1333      command('set hidden')
1334      cursors({ 'aaa', 'bbb' }, 'Qj')
1335      local buf_a = api.nvim_get_current_buf()
1336      command('enew')
1337      fn.setline(1, { 'ccc', 'ddd' })
1338      feed('gg0Qj')
1339      local buf_b = api.nvim_get_current_buf()
1340      command('buffer #')
1341      command('nnoremap X x:bnext<CR>')
1342      feed('2G0X')
1343      -- The "x" atom was captured in A but resolves in B. It should not cascade to B's cursors.
1344      -- A's cursors are skipped, except the edit done by the primary cursor.
1345      eq({ a = { 'aaa', 'bb' }, b = { 'ccc', 'ddd' } }, {
1346        a = api.nvim_buf_get_lines(buf_a, 0, -1, true),
1347        b = api.nvim_buf_get_lines(buf_b, 0, -1, true),
1348      })
1349      -- Same-buffer edit still cascades.
1350      feed('2G0x')
1351      eq({ 'cc', 'dd' }, api.nvim_buf_get_lines(buf_b, 0, -1, true))
1352
1353      -- TEMPORARY buffer-switch is allowed. A mapping may do work in a throwaway buffer, then apply
1354      -- edits to curbuf.
1355      command('nnoremap Y :new<CR>ihello<Esc>:bwipe!<CR>x')
1356      feed('2G0Y')
1357      eq({ 'c', 'd' }, api.nvim_buf_get_lines(buf_b, 0, -1, true))
1358    end)
1359
1360    it('edits cascade from any window showing the buffer (:split)', function()
1361      -- Cascade is conditional on the buffer, not the window.
1362      cursors({ 'aaa', 'bbb' }, 'Q')
1363      command('split')
1364      feed('jx') -- edit from the new window
1365      eq({ 'aa', 'bb' }, get_lines())
1366    end)
1367
1368    it('clearing is per-buffer', function()
1369      command('set hidden')
1370      cursors({ 'aaa', 'bbb' }, 'Qj')
1371      command('enew')
1372      clear_cursors()
1373      command('buffer #')
1374      eq(1, ncursors())
1375      clear_cursors()
1376      eq(0, ncursors())
1377      feed('gg0x') -- only the primary edits
1378      eq({ 'aa', 'bbb' }, get_lines())
1379    end)
1380
1381    it('nvim_buf_clear_namespace("nvim.multicursor") deletes the cursors', function()
1382      cursors({ 'aaa', 'bbb' }, 'Qj')
1383      eq(1, ncursors())
1384      n.exec_lua([[
1385        vim.api.nvim_buf_clear_namespace(0, vim.api.nvim_create_namespace('nvim.multicursor'), 0, -1)
1386      ]])
1387      eq(0, ncursors())
1388      feed('gQ') -- the deletion snapshotted the cursors: restorable
1389      eq(1, ncursors())
1390      feed('x') -- both cursors edit again (primary still on line 2)
1391      eq({ 'aa', 'bb' }, get_lines())
1392
1393      -- Partially clearing the namespace does not "dedupe" the cursor under the primary.
1394      feed('Q')
1395      api.nvim_buf_clear_namespace(0, api.nvim_create_namespace('nvim.multicursor'), 0, 1)
1396      eq({ { 1, 0 } }, anchors())
1397    end)
1398
1399    it(':edit! (reload) clears the cursors and the gQ snapshot', function()
1400      local fname = t.tmpname()
1401      fn.writefile({ 'aaa', 'bbb' }, fname)
1402      command('edit ' .. fname)
1403      feed('gg0QjQ')
1404      clear_cursors() -- Snapshots the cursors (gQ).
1405      feed('Q')
1406      eq(1, ncursors())
1407      command('edit!')
1408      eq(0, ncursors())
1409      feed('gQ')
1410      eq(0, ncursors()) -- Nothing to restore: the snapshot died with the text.
1411      feed('Q') -- A new session starts cleanly.
1412      eq(1, ncursors())
1413    end)
1414  end)
1415
1416  describe('insert-mode', function()
1417    it('"cgn" cascades live; failed cursor is removed #41960', function()
1418      -- "gn" searches per-cursor. Insert-entry cascades, and typed text previews live, before ESC.
1419      cursors({ 'a x foo', 'b foo', 'c y z foo' }, 'QjQj0')
1420      feed('/foo<CR>')
1421      feed('cgn')
1422      eq({ 'a x ', 'b ', 'c y z ' }, get_lines())
1423      eq({ { 0, 4 }, { 1, 2 } }, anchors()) -- Each cursor moved to its match.
1424      feed('X')
1425      eq({ 'a x X', 'b X', 'c y z X' }, get_lines())
1426      feed('<Esc>')
1427      eq({ 'a x X', 'b X', 'c y z X' }, get_lines())
1428      feed('u') -- One undo step.
1429      eq({ 'a x foo', 'b foo', 'c y z foo' }, get_lines())
1430
1431      -- Cursor is removed when insert-entry fails at a cursor ("ct;" where there is no ";").
1432      clear_cursors()
1433      cursors({ 'a;b', 'cd', 'e;f' }, 'QjQj0')
1434      eq(2, ncursors())
1435      feed('ct;X<Esc>')
1436      eq({ 'X;b', 'cd', 'X;f' }, get_lines())
1437      eq(1, ncursors())
1438      -- Same for "cgn" at a cursor with no match left (the primary's replay consumed it).
1439      clear_cursors()
1440      cursors({ 'a foo', 'b', 'c' }, 'jQjQgg0')
1441      feed('/foo<CR>')
1442      feed('cgnX<Esc>')
1443      eq({ 'a X', 'b', 'c' }, get_lines())
1444      eq(0, ncursors())
1445    end)
1446
1447    it('CTRL-U cascades before <Esc> (deletion crossing the session anchor)', function()
1448      -- Deleting typed text cascades live (the region shrinks). But CTRL-U here eats the "o"
1449      -- autoindent, which precedes the tracked region, invisible to the preview diff.
1450      -- Non-literal keys flush instead: the pending keys replay as a span immediately.
1451      command('set autoindent')
1452      cursors({ '    indented aa', '    indented cc' }, 'Q')
1453      feed('2gg0')
1454      feed('o')
1455      feed('<C-u>')
1456      -- Mid-session (no <Esc> yet): the cursor's line must match the
1457      -- primary's (indent eaten at both).
1458      eq({ '    indented aa', '', '    indented cc', '' }, get_lines())
1459    end)
1460
1461    it('o + CTRL-U does not join lines at less-indented cursors; ESC or CTRL-C ends', function()
1462      -- 'autoindent': "o" opens an indented line at the indented cursors, an empty line at the flat
1463      -- cursor. The replayed CTRL-U there has nothing to delete; it must not backspace through the
1464      -- line boundary ('backspace' includes "eol") and join lines.
1465      command('set autoindent')
1466
1467      for _, esc in ipairs({ '<Esc>', '<C-c>' }) do
1468        clear_cursors()
1469        cursors({ '    indented aa', 'flat bb', '    indented cc' })
1470        feed('o<C-u><Tab>yay')
1471        -- Drain first: a CTRL-C pending in typeahead cancels the queued keys before they execute
1472        -- (unrelated to multicursor).
1473        n.poke_eventloop()
1474        feed(esc)
1475        -- CTRL-C ends the insert session like <Esc>; it must not also abort the commit replay (the
1476        -- primary keeps its text on CTRL-C, so the cursors do too).
1477        eq({
1478          '    indented aa',
1479          '\tyay',
1480          'flat bb',
1481          '\tyay',
1482          '    indented cc',
1483          '\tyay',
1484        }, get_lines(), esc)
1485        -- The cursors survive: a subsequent edit still cascades to all three.
1486        feed('x')
1487        eq({
1488          '    indented aa',
1489          '\tya',
1490          'flat bb',
1491          '\tya',
1492          '    indented cc',
1493          '\tya',
1494        }, get_lines(), esc)
1495      end
1496    end)
1497
1498    it('cursor-moves cascade live at each cursor', function()
1499      cursors({ 'alpha one', 'beta two', 'gamma three' })
1500      -- A cursor-move key is a cmd, not text: it flushes pending keys as a span (like CTRL-U).
1501      feed('Aab<Left><Left>X')
1502      -- Mid-session (no <Esc> yet): the cursor-move already applied everywhere.
1503      eq({ 'alpha oneXab', 'beta twoXab', 'gamma threeXab' }, get_lines())
1504      feed('<Esc>')
1505      feed('AZ<Home>Y<Esc>')
1506      eq({ 'Yalpha oneXabZ', 'Ybeta twoXabZ', 'Ygamma threeXabZ' }, get_lines())
1507      -- Word-wise cursor-move: per-cursor word boundaries, not a copied column offset.
1508      feed('A<S-Left>W<Esc>')
1509      eq({ 'Yalpha WoneXabZ', 'Ybeta WtwoXabZ', 'Ygamma WthreeXabZ' }, get_lines())
1510    end)
1511
1512    it('CTRL-G U cursor-move cascades live; one undo block', function()
1513      cursors({ 'aa', 'bb' }, 'Qj')
1514      feed('i12<C-g>U<Left>3')
1515      -- Mid-session: the CTRL-G U move flushed and cascaded.
1516      eq({ '132aa', '132bb' }, get_lines())
1517      feed('<Esc>')
1518      -- CTRL-G U does not split undo (unlike plain <Left>).
1519      feed('u')
1520      eq({ 'aa', 'bb' }, get_lines())
1521    end)
1522
1523    it('absolute jump (<C-Home>) splits: previews stay, the live cascade re-anchors', function()
1524      fn.setline(1, { 'alpha', 'beta', 'gamma' })
1525      feed('j0Q')
1526      feed('j0Q')
1527      feed('gg$')
1528      feed('ix<C-Home>y')
1529      -- Mid-session: "x" stays as text; "y" (after jump) continues at the re-anchored positions.
1530      eq({ 'yalphxa', 'xybeta', 'xygamma' }, get_lines())
1531      feed('<Esc>')
1532      eq({ 'yalphxa', 'xybeta', 'xygamma' }, get_lines())
1533    end)
1534
1535    it('EOL insertion points display as virtual cells', function()
1536      local screen = Screen.new(40, 5)
1537      command('hi MCursor guifg=NONE guibg=Red')
1538      cursors({ 'aa', 'bbbb', 'cc' })
1539      -- "A": each insertion point is past EOL (no char cell), a virtual cell overlays it. #41576
1540      feed('A')
1541      screen:add_extra_attr_ids({
1542        [100] = { background = Screen.colors.Red },
1543      })
1544      screen:expect([[
1545        aa{100: }                                     |
1546        bbbb{100: }                                   |
1547        cc^                                      |
1548        {1:~                                       }|
1549        {5:-- INSERT --}                            |
1550      ]])
1551      -- Ending the session moves cursors onto last char (real text); the virtual cell disappears.
1552      feed('!<Esc>')
1553      screen:expect([[
1554        aa{100:!}                                     |
1555        bbbb{100:!}                                   |
1556        cc^!                                     |
1557        {1:~                                       }|
1558                                                |
1559      ]])
1560    end)
1561
1562    it('typed text live-mirrors at cursors', function()
1563      command('let v:oldfiles = ["/a", "/b"] | let @a = "reg"')
1564      local screen = Screen.new(30, 6)
1565      cursors({ 'aaa', 'bbb', 'ccc' })
1566      -- Still in insert mode (no <Esc> yet): the text already cascaded; each cursor displays
1567      -- at its insertion point, like the primary.
1568      feed('iXY')
1569      screen:expect([[
1570        XY{17:a}aa                         |
1571        XY{17:b}bb                         |
1572        XY^ccc                         |
1573        {1:~                             }|*2
1574        {5:-- INSERT --}                  |
1575      ]])
1576      feed('<Esc>')
1577      eq({ 'XYaaa', 'XYbbb', 'XYccc' }, get_lines())
1578      -- The session end shifts every cursor onto the last inserted char.
1579      screen:expect([[
1580        X{17:Y}aaa                         |
1581        X{17:Y}bbb                         |
1582        X^Yccc                         |
1583        {1:~                             }|*2
1584                                      |
1585      ]])
1586      -- Cascade context-management should not clobber v:oldfiles.
1587      eq({ '/a', '/b' }, api.nvim_get_vvar('oldfiles'))
1588
1589      -- Entering insert mode ("a") displays each cursor at its insertion-point immediately.
1590      feed('a')
1591      screen:expect([[
1592        XY{17:a}aa                         |
1593        XY{17:b}bb                         |
1594        XY^ccc                         |
1595        {1:~                             }|*2
1596        {5:-- INSERT --}                  |
1597      ]])
1598      feed('<Esc>')
1599      -- Operator entry ("ciw") live-mirrors the per-cursor change, still in insert mode.
1600      feed('0ciwZ')
1601      screen:expect([[
1602        Z{17: }                            |
1603        Z{17: }                            |
1604        Z^                             |
1605        {1:~                             }|*2
1606        {5:-- INSERT --}                  |
1607      ]])
1608      feed('<Esc>')
1609      -- Visual-change entry ("viwc") live-mirrors the selection at each cursor.
1610      feed('viwcW')
1611      screen:expect([[
1612        W{17: }                            |
1613        W{17: }                            |
1614        W^                             |
1615        {1:~                             }|*2
1616        {5:-- INSERT --}                  |
1617      ]])
1618      feed('<Esc>')
1619      -- Programmatic Visual selection followed by a typed change. #41705
1620      command('normal! viw')
1621      feed('cV')
1622      screen:expect([[
1623        V{17: }                            |
1624        V{17: }                            |
1625        V^                             |
1626        {1:~                             }|*2
1627        {5:-- INSERT --}                  |
1628      ]])
1629      feed('<Esc>')
1630      -- Also when "c" is a Visual-mode operator mapping. #41605
1631      command('xnoremap c "_c')
1632      feed('viwcM')
1633      screen:expect([[
1634        M{17: }                            |
1635        M{17: }                            |
1636        M^                             |
1637        {1:~                             }|*2
1638        {5:-- INSERT --}                  |
1639      ]])
1640      feed('<Esc>')
1641      -- Also when another key maps to "c".
1642      command('xnoremap - c')
1643      feed('viw-N')
1644      screen:expect([[
1645        N{17: }                            |
1646        N{17: }                            |
1647        N^                             |
1648        {1:~                             }|*2
1649        {5:-- INSERT --}                  |
1650      ]])
1651      feed('<Esc>')
1652
1653      -- Also when a Normal-mode mapping moves before entering Insert. #41605
1654      clear_cursors()
1655      cursors({ 'aaaa', 'bbbb', 'cccc' }, 'llQjQj')
1656      eq({ { 0, 2 }, { 1, 2 } }, anchors())
1657      eq({ 3, 2 }, api.nvim_win_get_cursor(0))
1658      command('nnoremap i ^i')
1659      atoms_start()
1660      feed('iX')
1661      screen:expect([[
1662        X{17:a}aaa                         |
1663        X{17:b}bbb                         |
1664        X^cccc                         |
1665        {1:~                             }|*2
1666        {5:-- INSERT --}                  |
1667      ]])
1668      feed('<Esc>')
1669      eq({ 'Xaaaa', 'Xbbbb', 'Xcccc' }, get_lines())
1670      local ev = atom_last()
1671      eq(
1672        { type = 'mapping', lhs = k('iX<Esc>'), changed = true },
1673        t.pick(atom_last(), 'type', 'lhs', 'changed')
1674      )
1675      eq({
1676        { type = 'motion', keys = '^' },
1677        { type = 'insert', keys = k('1i<Esc>') },
1678        { type = 'insert', keys = k('iX<Esc>') },
1679      }, subatoms(ev, 'type', 'keys'))
1680    end)
1681
1682    it('session survives all cursors deduping away mid-session', function()
1683      -- "A" entry replay lands on the primary and dedupe removes it mid-session; the ESC commit
1684      -- must not cascade into the empty set.
1685      fn.setline(1, { 'x' })
1686      feed('Q')
1687      feed('Ahi<Esc>')
1688      n.assert_alive()
1689      eq({ 'xhi' }, get_lines())
1690    end)
1691
1692    it('sessions cascade at each cursor', function()
1693      assert_rows({
1694        -- iZ: after <Esc> the cursors sit ON the last inserted char (like the primary cursor).
1695        {
1696          lines = { 'aaa', 'bbb', 'ccc' },
1697          keys = 'QjQjiZ<Esc>',
1698          expect = { 'Zaaa', 'Zbbb', 'Zccc' },
1699          after = 'x',
1700          after_expect = { 'aaa', 'bbb', 'ccc' },
1701        },
1702        -- A: distinct chars and line lengths, so an off-by-one anchor (e.g. a past-EOL anchor
1703        -- clamped by a replay in MODE_NORMAL) inserts before the last char, which identical
1704        -- chars ("!!") would mask.
1705        {
1706          lines = { 'a', 'bb bb', 'c cc' },
1707          keys = 'QjQjA!?<Esc>',
1708          expect = { 'a!?', 'bb bb!?', 'c cc!?' },
1709          after = 'x',
1710          after_expect = { 'a!', 'bb bb!', 'c cc!' },
1711        },
1712        -- cw changes a word at each cursor.
1713        {
1714          lines = { 'aaa one', 'bbb two', 'ccc three' },
1715          keys = 'QjQjcwFOO<Esc>',
1716          expect = { 'FOO one', 'FOO two', 'FOO three' },
1717        },
1718        -- <BS> cascades deletion.
1719        { lines = { 'aaa', 'bbb' }, keys = 'QjiXY<BS>Z<Esc>', expect = { 'XZaaa', 'XZbbb' } },
1720        -- <BS> deletes before the insert start.
1721        {
1722          lines = { 'abc', 'def' },
1723          place = 'gg0l',
1724          keys = 'Qji<BS>Z<Esc>',
1725          expect = { 'Zbc', 'Zef' },
1726        },
1727        -- <BS> at col 0 joins with the line above.
1728        {
1729          lines = { 'aa', 'bb', 'cc', 'dd' },
1730          place = 'ggj0',
1731          keys = 'Q2ji<BS><Esc>',
1732          expect = { 'aabb', 'ccdd' },
1733        },
1734        -- <CR> mid-insert splits the line.
1735        {
1736          lines = { 'aaXbb', 'ccXdd' },
1737          place = 'gg02l',
1738          keys = 'QjiAB<CR>CD<Esc>',
1739          expect = { 'aaAB', 'CDXbb', 'ccAB', 'CDXdd' },
1740        },
1741        -- O opens a line above.
1742        {
1743          lines = { 'aaa', 'bbb', 'ccc' },
1744          keys = 'Q2jOX<Esc>',
1745          expect = { 'X', 'aaa', 'bbb', 'X', 'ccc' },
1746        },
1747        -- a appends after the cursor char.
1748        { lines = { 'abc', 'def' }, keys = 'QjaZ<Esc>', expect = { 'aZbc', 'dZef' } },
1749        -- I inserts at the first non-blank.
1750        {
1751          lines = { '  aa', '    bb' },
1752          place = 'gg$',
1753          keys = 'Qj$IX<Esc>',
1754          expect = { '  Xaa', '    Xbb' },
1755        },
1756        -- i_CTRL-W deletes a word.
1757        {
1758          lines = { 'zz', 'yy' },
1759          keys = 'Qjifoo bar<C-w>X<Esc>',
1760          expect = { 'foo Xzz', 'foo Xyy' },
1761        },
1762        -- i_CTRL-V inserts a unicode char; after <Esc> the cursors sit ON it.
1763        {
1764          lines = { 'aaa', 'bbb' },
1765          keys = 'Qji<C-v>u00e9<Esc>',
1766          expect = { 'éaaa', 'ébbb' },
1767          after = 'x',
1768          after_expect = { 'aaa', 'bbb' },
1769        },
1770        -- i<Esc> at col 0 keeps the cursor at col 0.
1771        {
1772          lines = { 'abc', 'def' },
1773          keys = 'Qji<Esc>',
1774          expect = { 'abc', 'def' },
1775          after = 'x',
1776          after_expect = { 'bc', 'ef' },
1777        },
1778        -- 3iZ (counted insert) cascades the whole session.
1779        { lines = { 'aaa', 'bbb' }, keys = 'Qj3iZ<Esc>', expect = { 'ZZZaaa', 'ZZZbbb' } },
1780        -- R replaces; R + <BS> restores the replaced chars.
1781        { lines = { 'abcdef', 'ghijkl' }, keys = 'QjRXY<Esc>', expect = { 'XYcdef', 'XYijkl' } },
1782        {
1783          lines = { 'abcdef', 'ghijkl' },
1784          keys = 'QjRXY<BS><BS><Esc>',
1785          expect = { 'abcdef', 'ghijkl' },
1786        },
1787        -- Abbreviations expand identically at each cursor.
1788        {
1789          lines = { 'aaa', 'bbb' },
1790          pre = 'iabbrev teh the',
1791          keys = 'Qjiteh <Esc>',
1792          expect = { 'the aaa', 'the bbb' },
1793        },
1794        -- 'autoindent' applies per cursor with o.
1795        {
1796          lines = { '  aa', '      bb' },
1797          pre = 'set autoindent',
1798          keys = 'QjoX<Esc>',
1799          expect = { '  aa', '  X', '      bb', '      X' },
1800        },
1801      })
1802    end)
1803
1804    it('ea (with q=)', function()
1805      cursors({ 'one two', 'three four' }, 'Qj')
1806      feed('q=')
1807      feed('ea!<Esc>')
1808      feed('q=')
1809      eq({ 'one! two', 'three! four' }, get_lines())
1810    end)
1811
1812    it('completion: i_CTRL-N completes existing text at each cursor', function()
1813      command('set completeopt=menuone')
1814      cursors({ 'wombat', 'wo', 'wo' }, 'jQj')
1815      feed('A<C-n><Esc>')
1816      eq({ 'wombat', 'wombat', 'wombat' }, get_lines())
1817    end)
1818
1819    it('completion: live-mirrors cursors on separate lines', function()
1820      command('set completeopt=menuone')
1821      cursors({ 'wombat', '', '' }, 'jQj')
1822      feed('iwo<C-n>')
1823      eq(1, fn.pumvisible())
1824      eq({ 'wombat', 'wombat', 'wombat' }, get_lines())
1825      feed('<Esc>')
1826      eq({ 'wombat', 'wombat', 'wombat' }, get_lines())
1827    end)
1828
1829    it('completion: ESC commits with stale previews #41719', function()
1830      command('set completeopt=menuone,noselect')
1831      cursors({ 'aa', 'bb cc dd', 'ee' }, 'GQkQww')
1832      feed('ciwa<C-n>a')
1833      eq(1, fn.pumvisible())
1834      eq({ 'aa', 'a cc aa', 'a' }, get_lines())
1835      feed('<Esc>')
1836      eq({ 'aa', 'aa cc aa', 'aa' }, get_lines())
1837    end)
1838
1839    it('completion: live-mirrors same-line cursor AFTER the primary', function()
1840      command('set completeopt=menuone,noselect')
1841      cursors({ 'aa', 'bb cc dd' }, 'jwwQ0')
1842      feed('ciw<C-n>a')
1843      eq(1, fn.pumvisible())
1844      eq({ 'aa', 'a cc a' }, get_lines())
1845      feed('<C-e>x<Esc>')
1846      eq({ 'aa', 'ax cc ax' }, get_lines())
1847    end)
1848
1849    it('completion: defers preview of multiline edit BEFORE primary #41719', function()
1850      command('set completeopt=menuone')
1851      cursors({ '', '' }, 'Qj')
1852      feed('ia')
1853      fn.complete(1, { 'aa\nbb', 'ac' })
1854      eq(1, fn.pumvisible())
1855      eq({ 'a', 'aa', 'bb' }, get_lines())
1856      feed('<C-c>')
1857    end)
1858
1859    it('completion: defers preview of same-line cursor BEFORE primary #41719', function()
1860      command('set completeopt=menu,noselect')
1861      -- Place cursor1 on its own line, to exercise whole-batch deferral.
1862      -- Place cursor2 on same line as the primary, to test same-line handling.
1863      for _, case in ipairs({
1864        { 'aa', 'aa', '' },
1865        { 'a<C-e>', 'a', 'a' },
1866        { 'a<C-n><C-y>', 'aa', 'aa' },
1867        { 'a<BS>a', 'a', 'a' },
1868      }) do
1869        local keys, text, preview = unpack(case)
1870        clear_cursors()
1871        cursors({ 'aa', 'bb cc dd', 'ee' }, 'GQkQww')
1872        eq({ { 1, 0 }, { 2, 0 } }, anchors())
1873        eq({ 2, 6 }, api.nvim_win_get_cursor(0))
1874        feed('ciw<C-n>')
1875        eq(1, fn.pumvisible())
1876        feed(keys)
1877        eq({ 'aa', ('%s cc %s'):format(preview, text), preview }, get_lines())
1878        feed('aa')
1879        eq(0, fn.pumvisible())
1880        feed(' ')
1881        eq({ 'aa', ('%saa  cc %saa '):format(text, text), ('%saa '):format(text) }, get_lines())
1882        feed('x<Esc>')
1883        eq({ 'aa', ('%saa x cc %saa x'):format(text, text), ('%saa x'):format(text) }, get_lines())
1884      end
1885    end)
1886
1887    it('mapping ending in a Normal-mode "tail", cascades #41864', function()
1888      command('inoremap <Esc> <Esc>l') -- the "<Esc>" leaves a Normal-mode tail ("l")
1889      api.nvim_buf_set_lines(0, 0, -1, true, { 'echo hi', 'echo bye' })
1890      feed('WQjq=') -- cursor (1,5), primary (2,5); follow-mode ON
1891      feed('i<Esc>')
1892      -- The empty insert and its "l" tail cascade: both cursors end on column 5, not 4.
1893      eq({ { 0, 5 } }, anchors())
1894      eq({ 2, 5 }, api.nvim_win_get_cursor(0))
1895      feed('x')
1896      eq({ 'echo i', 'echo ye' }, get_lines())
1897
1898      -- Without follow-mode, the tail "l" is a motion, so primary-only.
1899      api.nvim_buf_set_lines(0, 0, -1, true, { 'echo hi', 'echo bye' })
1900      clear_cursors()
1901      feed('gg0WQj') -- follow-mode OFF
1902      feed('i<Esc>')
1903      eq({ { 0, 4 } }, anchors())
1904      eq({ 2, 5 }, api.nvim_win_get_cursor(0))
1905
1906      -- A mapping that explicitly invokes ("1q=…2q=") can force the tail "l" to cascade.
1907      command('iunmap <Esc>')
1908      command('inoremap <Esc> <Esc>1q=l2q=')
1909      api.nvim_buf_set_lines(0, 0, -1, true, { 'echo hi', 'echo bye' })
1910      clear_cursors()
1911      feed('gg0WQj') -- follow-mode OFF
1912      feed('i<Esc>')
1913      eq({ { 0, 5 } }, anchors())
1914      eq({ 2, 5 }, api.nvim_win_get_cursor(0))
1915      -- Follow-mode is off again: a typed motion stays primary-only.
1916      feed('l')
1917      eq({ { 0, 5 } }, anchors())
1918      eq({ 2, 6 }, api.nvim_win_get_cursor(0))
1919    end)
1920  end)
1921
1922  describe('navigation state (primary-only)', function()
1923    it('jumplist, changelist and marks follow only the primary', function()
1924      local l = {}
1925      for i = 1, 30 do
1926        l[#l + 1] = ('word%d line'):format(i)
1927      end
1928      cursors(l)
1929      -- Change marks and changelist: one edit at 3 cursors records the primary's position only.
1930      local nchanges = #fn.getchangelist()[1]
1931      feed('x')
1932      eq({ 3, 0 }, api.nvim_buf_get_mark(0, '['))
1933      eq({ 3, 0 }, api.nvim_buf_get_mark(0, ']'))
1934      eq({ 3, 0 }, api.nvim_buf_get_mark(0, '.'))
1935      eq(nchanges + 1, #fn.getchangelist()[1])
1936      -- Likewise an Insert-mode edit (previewed, then replayed at the cursors).
1937      feed('iab<Esc>')
1938      eq({ 3, 0 }, api.nvim_buf_get_mark(0, '.'))
1939      eq(nchanges + 1, #fn.getchangelist()[1])
1940      eq(3, fn.getchangelist()[1][nchanges + 1].lnum)
1941
1942      -- Visual marks: the primary's selection.
1943      feed('viwy')
1944      eq({ 3, 0 }, api.nvim_buf_get_mark(0, '<'))
1945      eq({ 3, 5 }, api.nvim_buf_get_mark(0, '>'))
1946
1947      -- Jumplist: a followed jump records one entry (the primary's).
1948      -- (Last: all cursors land on line 30 and merge.)
1949      command('clearjumps')
1950      feed('q=')
1951      feed('G')
1952      feed('q=')
1953      eq(1, #fn.getjumplist()[1])
1954    end)
1955  end)
1956
1957  describe('completion', function()
1958    -- While a completion is active, the cascade pauses: redobuff is frozen, and spans cannot replay
1959    -- into a busy completion (edit() refuses nesting). The cursors catch up when completion ends.
1960
1961    --- Three empty lines under "foo*" completion candidates; cursors on lines 4-5, primary on 6.
1962    local function ac_setup()
1963      command('setlocal autocomplete')
1964      cursors({ 'foo', 'foobar', 'foobarbaz', '', '', '' }, '3jQjQj')
1965    end
1966
1967    it("'autocomplete' popup: cursors catch up when the completion ends", function()
1968      local screen = Screen.new(40, 12)
1969      ac_setup()
1970      feed('if')
1971      feed('o')
1972      screen:expect({ any = 'INSERT' })
1973      -- The preview updates live (even during completion); cursors intact.
1974      eq(2, ncursors())
1975      feed('<Esc>')
1976      eq({ 'foo', 'foobar', 'foobarbaz', 'fo', 'fo', 'fo' }, get_lines())
1977      eq(2, ncursors())
1978    end)
1979
1980    it("'autocomplete': accepting a completion applies at all cursors", function()
1981      ac_setup()
1982      feed('if')
1983      feed('<C-n>') -- select the first popup entry
1984      feed('<C-y>') -- accept
1985      feed(' tail<Esc>') -- and keep typing
1986      local l = get_lines()
1987      eq({ l[4], l[4] }, { l[5], l[6] })
1988    end)
1989
1990    it("'autocomplete': <BS>, <C-e>", function()
1991      -- BS/C-e cancel propagation.
1992      ac_setup()
1993      feed('ifoo<BS>x<Esc>')
1994      eq({ 'fox', 'fox', 'fox' }, { get_lines()[4], get_lines()[5], get_lines()[6] })
1995      feed('cc')
1996      feed('f<C-n><C-n><C-e><Esc>') -- cycle, then cancel back to the leader
1997      eq({ 'f', 'f', 'f' }, { get_lines()[4], get_lines()[5], get_lines()[6] })
1998
1999      -- No candidates, {Visual}Q cursors: <BS> mid-completion. #41602
2000      clear_cursors()
2001      api.nvim_buf_set_lines(0, 0, -1, true, { '', '', '' })
2002      command('let v:errmsg = ""')
2003      feed('VggQ')
2004      feed('i a<BS>')
2005      eq('', api.nvim_get_vvar('errmsg'))
2006      feed('<Esc>')
2007      eq('', api.nvim_get_vvar('errmsg'))
2008      eq({ ' ', ' ', ' ' }, get_lines())
2009
2010      -- Live-mirrors after <BS> ends autocompletion; popup shows on new input.
2011      clear_cursors()
2012      ac_setup()
2013      feed('ifo')
2014      eq(1, fn.pumvisible())
2015      feed('<BS>')
2016      eq(1, fn.pumvisible())
2017      feed('<BS>')
2018      eq(0, fn.pumvisible())
2019      feed('fo')
2020      eq(1, fn.pumvisible())
2021      eq({ 'fo', 'fo', 'fo' }, { get_lines()[4], get_lines()[5], get_lines()[6] })
2022      feed('<Esc>')
2023      eq({ 'fo', 'fo', 'fo' }, { get_lines()[4], get_lines()[5], get_lines()[6] })
2024
2025      -- Live-mirrors if <BS> ends autocompletion then restarts it immediately ('autocomplete' with
2026      -- printable char before the cursor). #41605
2027      clear_cursors()
2028      cursors({ 'foo', 'foobar', 'foobarbaz' })
2029      feed('A f')
2030      eq(1, fn.pumvisible())
2031      feed('<BS>')
2032      eq({ 'foo ', 'foobar ', 'foobarbaz ' }, get_lines())
2033      feed(' fo')
2034      eq(1, fn.pumvisible())
2035      eq({ 'foo  fo', 'foobar  fo', 'foobarbaz  fo' }, get_lines())
2036      feed('<Esc>')
2037      eq({ 'foo  fo', 'foobar  fo', 'foobarbaz  fo' }, get_lines())
2038    end)
2039
2040    it('InsertCharPre-driven complete() plugin (cmp-style)', function()
2041      local screen = Screen.new(40, 12)
2042      -- Typical third-party completion plugin: an InsertCharPre handler
2043      -- that schedules complete() (textlock forbids calling it directly).
2044      n.exec_lua([[
2045        vim.api.nvim_create_autocmd('InsertCharPre', {
2046          callback = function()
2047            vim.schedule(function()
2048              if vim.fn.mode():find('i') and vim.fn.pumvisible() == 0 then
2049                vim.fn.complete(1, { 'foobar', 'foolish' })
2050              end
2051            end)
2052          end,
2053        })
2054      ]])
2055      cursors({ '', '', '' })
2056      feed('if')
2057      screen:expect({ any = 'foolish' }) -- wait for the popup
2058      feed('<C-y>') -- accept the (pre-inserted) first candidate
2059      feed('<Esc>')
2060      eq({ 'foobar', 'foobar', 'foobar' }, get_lines())
2061      screen:expect({ none = 'foolish' }) -- popup closed
2062      -- <Esc> with the popup still visible keeps all cursors equal too.
2063      feed('cc')
2064      feed('x')
2065      screen:expect({ any = 'foolish' }) -- wait for the new popup
2066      feed('<Esc>')
2067      local l = get_lines()
2068      eq({ l[3], l[3] }, { l[1], l[2] })
2069    end)
2070  end)
2071
2072  describe('visual-mode cascade', function()
2073    it('failed motion mid-replay does not eat the keys after it', function()
2074      fn.setline(1, { 'alpha bravo', 'golf hotel', 'mike november' })
2075      feed('ggVjjQ') -- cursor on each line; enables "q=" follow-mode
2076      feed('gg0')
2077      -- The abandoned selection replays "vloh<Esc>" at each cursor ("q=" follow). The "h" fails
2078      -- (col 0 after "o" swap); Visual mode must not leak into next cursor replay.
2079      feed('vloh<Esc>')
2080      eq({ 'alpha bravo', 'golf hotel', 'mike november' }, get_lines())
2081      eq('n', api.nvim_get_mode().mode)
2082
2083      -- Per-cursor behavior: "t;" fails if cursor-line has no ";". The op still applies to the
2084      -- existing Visual selection.
2085      clear_cursors()
2086      cursors({ 'a;b', 'cd', 'e;f' }, 'jQjQgg0')
2087      feed('vt;d')
2088      eq({ ';b', 'd', ';f' }, get_lines())
2089      eq(2, ncursors()) -- The cursor where "t;" failed is kept.
2090      clear_cursors()
2091      cursors({ 'a;b', 'cd', 'e;f' }, 'jQjQgg0')
2092      feed('vt;cX<Esc>')
2093      eq({ 'X;b', 'Xd', 'X;f' }, get_lines())
2094    end)
2095
2096    it('per-cursor selection', function()
2097      local screen = Screen.new(30, 6)
2098      cursors({ 'longword x', 'ab y', 'medium z' })
2099      -- Each cursor shows its own selection ("iw" = that cursor's word), previewed live.
2100      feed('viw')
2101      screen:expect([[
2102        {17:longword} x                    |
2103        {17:ab} y                          |
2104        {17:mediu^m} z                      |
2105        {1:~                             }|*2
2106        {5:-- VISUAL --}                  |
2107      ]])
2108      eq('visual', screen.mode) -- The UI mode ('guicursor'). #41631
2109      feed('e')
2110      screen:expect([[
2111        {17:longword x}                    |
2112        {17:ab y}                          |
2113        {17:medium ^z}                      |
2114        {1:~                             }|*2
2115        {5:-- VISUAL --}                  |
2116      ]])
2117      -- <Esc>: cursors move to the selection-end, like the primary.
2118      feed('<Esc>')
2119      screen:expect([[
2120        longword {17:x}                    |
2121        ab {17:y}                          |
2122        medium ^z                      |
2123        {1:~                             }|*2
2124                                      |
2125      ]])
2126      eq('normal', screen.mode)
2127    end)
2128
2129    it('linewise/blockwise selections', function()
2130      local screen = Screen.new(30, 6)
2131      cursors({ 'aaaa', 'bbbb', 'cccc', 'dddd' }, 'Q2j')
2132      feed('Vj') -- linewise: primary lines 3-4, fake lines 1-2
2133      screen:expect([[
2134        {17:aaaa}                          |
2135        {17:bbbb}                          |
2136        {17:cccc}                          |
2137        {17:^dddd}                          |
2138        {1:~                             }|
2139        {5:-- VISUAL LINE --}             |
2140      ]])
2141      feed('<Esc>')
2142      clear_cursors()
2143      cursors({ 'aaaa', 'bbbb', 'cccc', 'dddd' }, 'Q2jl')
2144      feed('<C-v>jl') -- blockwise: primary (3,1)-(4,2), fake (1,0)-(2,1)
2145      screen:expect([[
2146        {17:aa}aa                          |
2147        {17:bb}bb                          |
2148        c{17:cc}c                          |
2149        d{17:d^d}d                          |
2150        {1:~                             }|
2151        {5:-- VISUAL BLOCK --}            |
2152      ]])
2153    end)
2154
2155    it('gv reselects per-cursor #41606', function()
2156      local screen = Screen.new(30, 6)
2157      cursors({ 'aa bb cc dd', 'ee ff gg hh', 'ii jj kk ll' })
2158      feed('v3l<Esc>')
2159      -- Per-cursor '< '> marks: "gv" reselects that (absolute) area.
2160      feed('gv')
2161      screen:expect([[
2162        {17:aa b}b cc dd                   |
2163        {17:ee f}f gg hh                   |
2164        {17:ii ^j}j kk ll                   |
2165        {1:~                             }|*2
2166        {5:-- VISUAL --}                  |
2167      ]])
2168      feed('d')
2169      eq({ 'b cc dd', 'f gg hh', 'j kk ll' }, get_lines())
2170      -- "." redoes a same-size region ("1v"), like Vim: not "gv" (the collapsed area).
2171      feed('.')
2172      eq({ ' dd', ' hh', ' ll' }, get_lines())
2173
2174      -- The per-cursor "gv" regions are shifted by edits.
2175      clear_cursors()
2176      cursors({ 'a', 'b', 'c', 'd', 'e', 'f' }, '2jQgg')
2177      feed('Vj<Esc>') -- Primary: lines 1-2. Cursor: lines 3-4.
2178      feed('gvd')
2179      eq({ 'e', 'f' }, get_lines())
2180      -- ...and a cursor's delete shifts the primary's area.
2181      clear_cursors()
2182      cursors({ 'a', 'b', 'c', 'd', 'e', 'f' }, 'Q3j')
2183      feed('Vj<Esc>') -- Cursor: lines 1-2. Primary: lines 4-5.
2184      feed('gvd')
2185      eq({ 'c', 'f' }, get_lines())
2186      feed('gv')
2187      screen:expect([[
2188        {17:c}                             |
2189        {17:^f}                             |
2190        {1:~                             }|*3
2191        {5:-- VISUAL LINE --}             |
2192      ]])
2193      feed('<Esc>')
2194
2195      -- A cursor without a previous area (added after the selection) has nothing to reselect.
2196      clear_cursors()
2197      cursors({ 'aa bb', 'cc dd', 'ee ff' }, 'Qj')
2198      feed('viw<Esc>')
2199      feed('jQk') -- Cursor on line 3: no area.
2200      feed('gvd')
2201      eq({ ' bb', ' dd', 'ee ff' }, get_lines())
2202      eq(2, ncursors())
2203      clear_cursors()
2204      cursors({ 'aa bb', 'cc dd', 'ee ff' }, 'Qj')
2205      feed('viw<Esc>')
2206      feed('jQk')
2207      feed('gvrZ') -- Not Normal-mode "rZ".
2208      eq({ 'ZZ bb', 'ZZ dd', 'ee ff' }, get_lines())
2209
2210      -- Per-cursor "gv" + Insert-entering cmd ("gvc…").
2211      clear_cursors()
2212      cursors({ 'aa bb', 'cc dd', 'ee ff' })
2213      feed('viw<Esc>')
2214      feed('gvcX<Esc>')
2215      eq({ 'X bb', 'X dd', 'X ff' }, get_lines())
2216      -- Cursor without a previous area is skipped.
2217      clear_cursors()
2218      cursors({ 'aa bb', 'cc dd', 'ee ff' }, 'Qj')
2219      feed('<C-v>l<Esc>')
2220      feed('jQk') -- Cursor on line 3: no area.
2221      feed('gvIX<Esc>')
2222      eq('ee ff', fn.getline(3))
2223    end)
2224
2225    it('selection moved by mapping via API/Lua #41956', function()
2226      local screen = Screen.new(30, 6)
2227      n.exec_lua(function()
2228        -- Extends the selection by 2 via the API, around a fed "o".
2229        vim.keymap.set('x', 'gh', function()
2230          local cursor = vim.api.nvim_win_get_cursor(0)
2231          vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 1 })
2232          vim.cmd('normal! o')
2233          vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 3 })
2234        end)
2235        -- Starts a selection with a fed "v", extends it via the API.
2236        vim.keymap.set('n', 'gL', function()
2237          local cursor = vim.api.nvim_win_get_cursor(0)
2238          vim.cmd('normal! v')
2239          vim.api.nvim_win_set_cursor(0, { cursor[1], cursor[2] + 2 })
2240        end)
2241      end)
2242      cursors({ 'aaaaaaa', 'bbbbbbb', 'ccccccc' })
2243      atoms_start()
2244      -- Fed "o" does not describe the resulting selection, so the mapping itself is the subatom.
2245      feed('vgh')
2246      screen:expect([[
2247        a{17:aaa}aaa                       |
2248        b{17:bbb}bbb                       |
2249        c{17:cc^c}ccc                       |
2250        {1:~                             }|*2
2251        {5:-- VISUAL --}                  |
2252      ]])
2253      feed('d')
2254      eq({ 'aaaa', 'bbbb', 'cccc' }, get_lines())
2255      eq({ { type = 'visual' } }, atoms_tail(1, 'type'))
2256      -- Mapping that starts the selection: same.
2257      feed('gL')
2258      screen:expect([[
2259        a{17:aaa}                          |
2260        b{17:bbb}                          |
2261        c{17:cc^c}                          |
2262        {1:~                             }|*2
2263        {5:-- VISUAL --}                  |
2264      ]])
2265      feed('d')
2266      eq({ 'a', 'b', 'c' }, get_lines())
2267
2268      -- Fed "gv" reselects marks set by the mapping.
2269      n.exec_lua(function()
2270        vim.keymap.set('x', 'gs', function()
2271          local row, col = unpack(vim.api.nvim_win_get_cursor(0))
2272          vim.fn.setpos("'<", { 0, row, col + 1, 0 })
2273          vim.fn.setpos("'>", { 0, row, col + 3, 0 })
2274          vim.cmd.normal({ 'gv', bang = true })
2275        end)
2276      end)
2277      clear_cursors()
2278      cursors({ 'aaaaaaa', 'bbbbbbb', 'ccccccc' })
2279      feed('vgs')
2280      screen:expect([[
2281        {17:aaa}aaaa                       |
2282        {17:bbb}bbbb                       |
2283        {17:cc^c}cccc                       |
2284        {1:~                             }|*2
2285        {5:-- VISUAL --}                  |
2286      ]])
2287      feed('d')
2288      eq({ 'aaaa', 'bbbb', 'cccc' }, get_lines())
2289
2290      -- Mapping that ends the selection by operator and starts a new one: session is kept across
2291      -- the operator.
2292      n.exec_lua(function()
2293        vim.keymap.set('x', 'gl', function()
2294          vim.cmd('normal! "_y')
2295          vim.cmd('normal! 2l')
2296          vim.cmd('normal! 1v')
2297        end)
2298      end)
2299      clear_cursors()
2300      cursors({ 'aaaaaaa', 'bbbbbbb', 'ccccccc' })
2301      feed('vlgl')
2302      screen:expect([[
2303        aa{17:aa}aaa                       |
2304        bb{17:bb}bbb                       |
2305        cc{17:c^c}ccc                       |
2306        {1:~                             }|*2
2307        {5:-- VISUAL --}                  |
2308      ]])
2309      feed('d')
2310      eq({ 'aaaaa', 'bbbbb', 'ccccc' }, get_lines())
2311    end)
2312
2313    it('mapping that edits during the selection #42005', function()
2314      local screen = Screen.new(30, 6)
2315      -- "Shift right": the mapping edits, then reselects the moved text.
2316      command([[xnoremap gl <Cmd>normal! xp`[1v<CR>]])
2317      cursors({ 'abcd', 'efgh', 'ijkl' })
2318      feed('vgl')
2319      screen:expect([[
2320        b{17:a}cd                          |
2321        f{17:e}gh                          |
2322        j{17:^i}kl                          |
2323        {1:~                             }|*2
2324        {5:-- VISUAL --}                  |
2325      ]])
2326      eq({ 'bacd', 'fegh', 'jikl' }, get_lines())
2327      feed('gl') -- span 2 continues from each cursor's own selection.
2328      eq({ 'bcad', 'fgeh', 'jkil' }, get_lines())
2329      feed('d') -- Operator completes the session as the last span.
2330      eq({ 'bcd', 'fgh', 'jkl' }, get_lines())
2331
2332      -- Mapping that acts only in Visual mode ("mini.move").
2333      n.exec_lua(function()
2334        vim.keymap.set('x', 'gm', function()
2335          if vim.fn.mode() ~= 'v' then
2336            return
2337          end
2338          vim.cmd('normal! xp`[1v')
2339        end)
2340      end)
2341      clear_cursors()
2342      cursors({ 'abcd', 'efgh', 'ijkl' })
2343      feed('vgm')
2344      eq({ 'bacd', 'fegh', 'jikl' }, get_lines())
2345    end)
2346
2347    it('primary-overlapping cursor is not replayed; stays synced #42025', function()
2348      -- The command may move the primary before the cascade ("yiwp")!
2349      command('nnoremap gm yiwp') -- "Multiply" the word at cursor.
2350      cursors({ 'aa', 'bb' }, 'QjQ') -- Primary-overlapping cursor.
2351      feed('gm')
2352      eq({ 'aaaa', 'bbbb' }, get_lines())
2353      -- Primary-overlapping cursor settles on the primary's new position (the paste moved it).
2354      local cur = api.nvim_win_get_cursor(0)
2355      eq({ { 0, 2 }, { cur[1] - 1, cur[2] } }, anchors())
2356
2357      -- Also when the edit displaces the overlapping cursor's (right-gravity) mark.
2358      for _, place in ipairs({ 'QjQ', 'vipQ' }) do
2359        for _, case in ipairs({
2360          { 'rx', { 'xa', 'xb' } },
2361          { '~', { 'Aa', 'Bb' } },
2362          { 'g~~', { 'AA', 'BB' } },
2363        }) do
2364          clear_cursors()
2365          cursors({ 'aa', 'bb' }, place)
2366          feed(case[1])
2367          eq(case[2], get_lines(), place .. ' ' .. case[1])
2368          local cur = api.nvim_win_get_cursor(0)
2369          eq({ cur[1] - 1, cur[2] }, anchors()[2], place .. ' ' .. case[1]) -- Re-synced.
2370        end
2371      end
2372
2373      -- Also for LHS-replayed mapping.
2374      n.exec_lua(function()
2375        -- "rx" via API, which also samples the cursors when replayed at the other cursor.
2376        _G.peek = function()
2377          local row, col = unpack(vim.api.nvim_win_get_cursor(0))
2378          vim.api.nvim_buf_set_text(0, row - 1, col, row - 1, col + 1, { 'x' })
2379          if row == 1 then
2380            local ns = vim.api.nvim_create_namespace('nvim.multicursor')
2381            _G.seen = vim.api.nvim_buf_get_extmarks(0, ns, 0, -1, {})[2]
2382          end
2383        end
2384      end)
2385      command('nnoremap gr <Cmd>lua _G.peek()<CR>')
2386      clear_cursors()
2387      cursors({ 'aa', 'bb' }, 'QjQ')
2388      feed('gr')
2389      eq({ 'xa', 'xb' }, get_lines())
2390      eq({ 1, 0 }, n.exec_lua('return { _G.seen[2], _G.seen[3] }'))
2391
2392      -- Same for a Visual span: the primary sits at selection-end.
2393      command([[xnoremap gl <Cmd>normal! xp`[1v<CR>]])
2394      clear_cursors()
2395      cursors({ 'abcd', 'efgh', 'ijkl' }, 'QjQjQ')
2396      feed('0vgl')
2397      eq({ 'bacd', 'fegh', 'jikl' }, get_lines())
2398      -- Also when Visual selection moves the primary first.
2399      for _, keys in ipairs({ 'va)d', 'va)cX<Esc>', 'ca)X<Esc>' }) do
2400        feed('<Esc>')
2401        clear_cursors()
2402        cursors({ 'aa (bb) (cc)', 'aa (bb) (cc)' }, 'vipQ')
2403        feed(keys)
2404        local x = keys:find('X') and 'X' or ''
2405        eq({ ('aa %s (cc)'):format(x), ('aa %s (cc)'):format(x) }, get_lines(), keys)
2406        local cur = api.nvim_win_get_cursor(0)
2407        eq({ cur[1] - 1, cur[2] }, anchors()[2], keys) -- Primary-overlapping cursor stays synced.
2408      end
2409      -- Motion does not cascade, so it must not dedupe the cursor under the primary.
2410      clear_cursors()
2411      cursors({ 'abc', 'def' }, 'Q')
2412      feed('l')
2413      eq(1, ncursors())
2414    end)
2415
2416    it('replays the full visual keysequence', function()
2417      cursors({ 'one two three x', 'aa bb cc d' }, 'Qj')
2418      -- Select word, extend twice, delete: selection re-executes at each cursor, so the extents are
2419      -- per-cursor (not a fixed-size reselect).
2420      atoms_start()
2421      feed('viweex')
2422      eq({ ' x', ' d' }, get_lines())
2423      -- The operator is normalized ("translated"): visual "x" == "d".
2424      eq({ 'viweed' }, atoms_tail(1))
2425
2426      -- A motion that fails (beeps) at primary is skipped. E.g. "j" at EOB.
2427      clear_cursors()
2428      cursors({ 'a', 'b', 'c', 'd', 'e', 'f' }, 'QjQ4j') -- Cursors at lines 1-2, primary on the last.
2429      feed('Vjd')
2430      eq({ 'c', 'd', 'e' }, get_lines())
2431      eq({ 'Vd' }, atoms_tail(1))
2432    end)
2433
2434    it('selections opened by :normal #41705', function()
2435      local screen = Screen.new(30, 6)
2436      command('nnoremap <F2> <Cmd>normal! viw<CR>')
2437      n.exec_lua(function()
2438        vim.keymap.set('x', 'Z', '<Cmd>normal! iw<CR>')
2439        vim.keymap.set('n', '<F3>', function()
2440          vim.cmd.normal('vZ')
2441        end)
2442      end)
2443      atoms_start()
2444      -- Each entry opens the selection from a different enclosing frame: typed cmdline, <Cmd>
2445      -- mapping, Lua mapping (nested x-mapping), RPC. Result does not depend on follow-mode.
2446      for i, keys in ipairs({ ':normal! viw<CR>', '<F2>', '<F3>', 'api' }) do
2447        clear_cursors()
2448        cursors({ 'longword x', 'ab y', 'medium z' })
2449        feed(i % 2 == 0 and '2q=' or '1q=')
2450        if keys == 'api' then
2451          command('normal! viw')
2452        else
2453          feed(keys)
2454        end
2455        screen:expect([[
2456          {17:longword} x                    |
2457          {17:ab} y                          |
2458          {17:mediu^m} z                      |
2459          {1:~                             }|*2
2460          {5:-- VISUAL --}                  |
2461        ]])
2462        -- Preview does not advance the anchors, even when a mapping opens the selection.
2463        eq({ { 0, 0 }, { 1, 0 } }, anchors(), keys)
2464        feed('d')
2465        eq({ ' x', ' y', ' z' }, get_lines(), keys)
2466
2467        -- The atom is the literal input: a command is captured as itself, not any keys it "feeds".
2468        -- But fed input with no enclosing command (RPC) collects its own keys.
2469        local expected = ({
2470          [':normal! viw<CR>'] = k(':normal! viw<NL>d'),
2471          ['<F2>'] = k('<Cmd>normal! viw<NL>d'),
2472          ['api'] = 'viwd',
2473        })[keys]
2474        if expected then
2475          eq({ expected }, atoms_tail(1), keys)
2476        else
2477          t.matches('^\128\253g%d+\nd$', atoms_tail(1)[1]) -- "<F3>": K_LUA + mapping id.
2478        end
2479
2480        screen:expect({
2481          condition = function()
2482            eq('normal', screen.mode)
2483          end,
2484        })
2485      end
2486    end)
2487
2488    it('selections after mapping motions', function()
2489      local screen = Screen.new(30, 6)
2490      cursors({ 'a longword x', 'bbbb ab y', 'cc medium z' })
2491      command('nnoremap <F2> w<Cmd>normal! viw<CR>')
2492      atoms_start()
2493      feed('<F2>')
2494      -- The mapping's "w" places the selection anchors, even without follow-mode.
2495      eq({ { 0, 2 }, { 1, 5 } }, anchors())
2496      screen:expect([[
2497        a {17:longword} x                  |
2498        bbbb {17:ab} y                     |
2499        cc {17:mediu^m} z                   |
2500        {1:~                             }|*2
2501        {5:-- VISUAL --}                  |
2502      ]])
2503      feed('d')
2504      eq({ 'a  x', 'bbbb  y', 'cc  z' }, get_lines())
2505      eq({ k('w<Cmd>normal! viw<NL>d') }, atoms_tail(1))
2506    end)
2507
2508    it('refreshes a nested selection even if the primary selection is unchanged', function()
2509      local screen = Screen.new(30, 5)
2510      cursors({ 'foo.bar tail', 'word tail' }, 'Qj')
2511      n.exec_lua(function()
2512        vim.keymap.set('x', 'Z', function()
2513          vim.cmd.normal({ vim.keycode('<Esc>viW'), bang = true })
2514        end)
2515      end)
2516      feed('viw')
2517      screen:expect([[
2518        {17:foo}.bar tail                  |
2519        {17:wor^d} tail                     |
2520        {1:~                             }|*2
2521        {5:-- VISUAL --}                  |
2522      ]])
2523      feed('Z')
2524      screen:expect([[
2525        {17:foo.bar} tail                  |
2526        {17:wor^d} tail                     |
2527        {1:~                             }|*2
2528        {5:-- VISUAL --}                  |
2529      ]])
2530      feed('d')
2531      eq({ ' tail', ' tail' }, get_lines())
2532    end)
2533
2534    it('operators cascade at each cursor', function()
2535      assert_rows({
2536        -- Vjd deletes two lines.
2537        { lines = { 'a', 'b', 'c', 'd', 'e', 'f' }, keys = 'Q4jVjd', expect = { 'c', 'd' } },
2538        -- r replaces the selection.
2539        { lines = { 'one two', 'ab cd' }, keys = 'QjviwrX', expect = { 'XXX two', 'XX cd' } },
2540        -- Blockwise c changes the block, I inserts before it, A appends after it.
2541        {
2542          lines = { 'ab', 'cd', 'ef', 'gh' },
2543          keys = 'Q2j<C-v>jcX<Esc>',
2544          expect = { 'Xb', 'Xd', 'Xf', 'Xh' },
2545        },
2546        {
2547          lines = { 'ab', 'cd', 'ef', 'gh' },
2548          keys = 'Q2j<C-v>jIX<Esc>',
2549          expect = { 'Xab', 'Xcd', 'Xef', 'Xgh' },
2550        },
2551        {
2552          lines = { 'ab', 'cd', 'ef', 'gh' },
2553          keys = 'Q2j<C-v>jA!<Esc>',
2554          expect = { 'a!b', 'c!d', 'e!f', 'g!h' },
2555        },
2556      })
2557    end)
2558
2559    it('ESC moves cursors to selection-end', function()
2560      cursors({ 'abc', 'def' }, 'Qj')
2561      feed('viw<Esc>')
2562      feed('x') -- cascades normally; no stray visual replay
2563      eq({ 'ab', 'de' }, get_lines())
2564      -- Without follow-mode a plain motion ("0") stays primary-only.
2565      -- But the selection itself moves every cursor to its selection-end.
2566      clear_cursors()
2567      cursors({ 'aaa bbb ccc', 'ddd eee fff', 'ggg hhh iii' }, '4lQjQj')
2568      feed('viw<Esc>')
2569      eq({ { 0, 6 }, { 1, 6 } }, anchors())
2570      feed('0viwe<Esc>')
2571      eq({ { 0, 10 }, { 1, 10 } }, anchors())
2572    end)
2573
2574    it('cursor displays at each selection end; o swaps it', function()
2575      local screen = Screen.new(40, 6)
2576      command('hi MCursor guifg=NONE guibg=Red')
2577      command('hi MCursorVisual guibg=Blue')
2578      cursors({ 'aaa bbb ccc', 'ddd eee fff', 'ggg hhh iii' }, '4lQjQj')
2579      feed('vl')
2580      screen:add_extra_attr_ids({
2581        [100] = { background = Screen.colors.Blue1 },
2582      })
2583      -- The (red) display cursor sits at each selection end; the (blue)
2584      -- anchor cell shows only the selection.
2585      screen:expect([[
2586        aaa {100:b}{30:b}b ccc                             |
2587        ddd {100:e}{30:e}e fff                             |
2588        ggg {17:h^h}h iii                             |
2589        {1:~                                       }|*2
2590        {5:-- VISUAL --}                            |
2591      ]])
2592      feed('o')
2593      screen:expect([[
2594        aaa {30:b}{100:b}b ccc                             |
2595        ddd {30:e}{100:e}e fff                             |
2596        ggg {17:^hh}h iii                             |
2597        {1:~                                       }|*2
2598        {5:-- VISUAL --}                            |
2599      ]])
2600      feed('<Esc>')
2601      -- Back to normal mode: the cursor highlight returns to the anchors.
2602      screen:expect([[
2603        aaa {30:b}bb ccc                             |
2604        ddd {30:e}ee fff                             |
2605        ggg ^hhh iii                             |
2606        {1:~                                       }|*2
2607                                                |
2608      ]])
2609    end)
2610
2611    it('payload motions: f{char} and search', function()
2612      cursors({ 'abcd,ef', 'wxyz,gh' }, 'Qj')
2613      feed('vf,d') -- f-operand: replayable, cascades.
2614      eq({ 'ef', 'gh' }, get_lines())
2615      clear_cursors()
2616      cursors({ 'one two', 'one two' }, 'Qj')
2617      feed('v/two<CR>d') -- Search payload travels in the collected keys, cascades.
2618      eq({ 'wo', 'wo' }, get_lines())
2619      clear_cursors()
2620      -- Viewport scroll (C-E) that drags the cursor (viewport edge, 'scrolloff') changes the
2621      -- selection by a viewport-dependent amount: not replayable, edits primary only.
2622      local lines = {}
2623      for i = 1, 30 do
2624        lines[i] = 'x' .. i
2625      end
2626      fn.setline(1, lines)
2627      feed('10ggQgg')
2628      feed('V<C-e>') -- Drags the primary onto line 2: selection is lines 1-2.
2629      feed('d')
2630      eq(28, fn.line('$')) -- Primary deleted 2 lines; no cascade.
2631      eq({ 'x3', 'x4' }, { fn.getline(1), fn.getline(2) })
2632    end)
2633  end)
2634
2635  describe('q= (follow-mode)', function()
2636    it("'follow' option", function()
2637      -- :setlocal is the same as "q=".
2638      cursors({ 'abcd', 'efgh' }, 'Qj')
2639      command('setlocal follow')
2640      feed('lx')
2641      eq({ 'acd', 'egh' }, get_lines())
2642      -- Buffer-local.
2643      command('new')
2644      eq(false, api.nvim_get_option_value('follow', {}))
2645      command('bwipe!')
2646      eq(true, api.nvim_get_option_value('follow', {}))
2647      -- LHS-replay does not re-run "q=" (toggle) at each cursor.
2648      clear_cursors()
2649      command('setlocal nofollow')
2650      command('let g:optionset = 0 | autocmd OptionSet follow let g:optionset += 1')
2651      command([[nnoremap gx <Cmd>exe 'normal! q='<Bar>call setline('.', 'X'..getline('.'))<CR>]])
2652      cursors({ 'aa', 'bb' }, 'Qj')
2653      feed('gx')
2654      eq({ 'Xaa', 'Xbb' }, get_lines())
2655      eq(true, api.nvim_get_option_value('follow', {}))
2656      eq(1, n.eval('g:optionset'))
2657    end)
2658
2659    it('cursors follow primary-cursor motions', function()
2660      cursors({ 'abcd', 'efgh' }, 'Q')
2661      feed('j') -- No cascade/follow.
2662      feed('q=')
2663      feed('ll') -- Cascade, both cursors move 2 chars rightwards.
2664      feed('x')
2665      eq({ 'abd', 'efh' }, get_lines())
2666      -- Toggle off: "h" moves only primary, the other cursor still deletes at its unmoved position.
2667      feed('q=')
2668      feed('h')
2669      feed('x')
2670      eq({ 'ab', 'eh' }, get_lines())
2671      -- [count]q= forces the mode instead of toggling.
2672      feed('1q=') -- Force "on".
2673      feed('1q=')
2674      feed('h')
2675      feed('x')
2676      eq({ 'b', 'h' }, get_lines())
2677      feed('2q=') -- Force "off".
2678      feed('2q=')
2679      feed('A!<Esc>')
2680      feed('h')
2681      feed('x')
2682      eq({ 'b', '!' }, get_lines())
2683    end)
2684
2685    it("ending the mc-session keeps 'follow'; Q disables it", function()
2686      -- Explicit clear.
2687      cursors({ 'aaa', 'bbb', 'ccc' })
2688      feed('q=')
2689      clear_cursors()
2690      eq(true, api.nvim_get_option_value('follow', {}))
2691
2692      -- Implicit exit (cursors deduped) clear.
2693      cursors({ 'aaa', 'bbb', 'ccc' })
2694      feed('q=')
2695      feed('9k') -- Every cursor clamps to line 1, onto the primary: all deduped.
2696      eq(0, ncursors())
2697      eq(true, api.nvim_get_option_value('follow', {}))
2698      feed('Q') -- Disables follow-mode, else it would dedupe on "j".
2699      eq(false, api.nvim_get_option_value('follow', {}))
2700      feed('j')
2701      eq(1, ncursors())
2702
2703      -- During a session: Q adds a cursor at the primary, and exits follow-mode.
2704      clear_cursors()
2705      cursors({ 'aaa', 'bbb', 'ccc' }, 'Qj')
2706      feed('q=')
2707      feed('l') -- Sanity: cascades.
2708      eq({ { 0, 1 } }, anchors())
2709      feed('Q')
2710      eq(false, api.nvim_get_option_value('follow', {}))
2711      feed('j') -- No follow: nothing converges or dedupes.
2712      eq({ { 0, 1 }, { 1, 1 } }, anchors())
2713      -- Partial-range clear does not end the mc-session; the remaining cursors keep "q=".
2714      clear_cursors()
2715      cursors({ 'aaa', 'bbb', 'ccc' }) -- Cursors on lines 1-2, primary on line 3.
2716      feed('q=')
2717      n.exec_lua(
2718        [[vim.api.nvim_buf_clear_namespace(0, vim.api.nvim_create_namespace('nvim.multicursor'), 0, 1)]]
2719      )
2720      eq(1, ncursors()) -- Cursor 1 is gone, cursor 2 still exists.
2721      feed('l')
2722      eq({ { 1, 1 } }, anchors()) -- Still in follow-mode.
2723    end)
2724
2725    it('follows a mapping that moves the cursor via API (no motion key) #41646', function()
2726      command(
2727        'nnoremap gm <Cmd>lua local p = vim.api.nvim_win_get_cursor(0); '
2728          .. 'p[2] = p[2] + 1; vim.api.nvim_win_set_cursor(0, p)<CR>'
2729      )
2730      cursors({ 'abcd', 'efgh', 'ijkl' }, 'QjQj') -- A cursor on each line.
2731      feed('q=')
2732      feed('gm') -- Every cursor moves one column right.
2733      feed('x')
2734      eq({ 'acd', 'egh', 'ikl' }, get_lines())
2735
2736      -- <Cmd> mapping uses nested ":normal!" to move the cursor. #41653
2737      clear_cursors()
2738      command('nnoremap gh <Cmd>normal! $<CR>')
2739      cursors({ 'a b', 'c d', 'e f' }, 'QjQj')
2740      feed('q=')
2741      feed('gh') -- Every cursor moves to EOL.
2742      feed('x')
2743      eq({ 'a ', 'c ', 'e ' }, get_lines())
2744
2745      -- matchit "%" mapping (uses ":call" to move the cursor).
2746      command('packadd matchit')
2747      clear_cursors()
2748      cursors({ '(aa)', '(bb)', '(cc)' }, 'QjQj') -- All cursors on "(".
2749      feed('q=')
2750      feed('%') -- Every cursor jumps to its ")".
2751      feed('x')
2752      eq({ '(aa', '(bb', '(cc' }, get_lines())
2753    end)
2754
2755    it("is decided at a mapping's first move #41836", function()
2756      -- Cursors on lines 2-4, primary line 5, follow=ON.
2757      cursors({ 'l1', 'l2', 'l3', 'l4', 'l5' }, 'jQjQjQj1q=')
2758      -- Mapping toggles follow OFF, moves, then toggles ON: the move should NOT cascade.
2759      n.exec_lua([[vim.keymap.set('n', '<F1>', function() vim.cmd('norm! 2q=gg1q=') end)]])
2760      feed('<F1>')
2761      eq({ { 1, 0 }, { 2, 0 }, { 3, 0 } }, anchors()) -- cursors stay on lines 2-4 (not cascaded)
2762      eq({ 1, 0 }, api.nvim_win_get_cursor(0)) -- primary moved to line 1
2763      -- Follow is ON again (trailing "1q="): a plain motion now cascades.
2764      feed('jx')
2765      eq({ 'l1', '2', '3', '4', '5' }, get_lines())
2766      eq({ { 2, 0 }, { 3, 0 }, { 4, 0 } }, anchors()) -- Cursors followed to lines 3-5.
2767
2768      -- Toggles as separate mapping keys (not ":norm!"): ON around the move, it cascades.
2769      feed('2q=') -- follow OFF; primary line 2, cursors on lines 3-5
2770      command('nnoremap <F2> 1q=k2q=')
2771      feed('<F2>')
2772      eq({ { 1, 0 }, { 2, 0 }, { 3, 0 } }, anchors()) -- Cursors followed to lines 2-4.
2773      eq({ 1, 0 }, api.nvim_win_get_cursor(0))
2774      -- OFF at the move (toggled after it): no cascade.
2775      command('nnoremap <F3> j1q=2q=')
2776      feed('<F3>')
2777      eq({ { 1, 0 }, { 2, 0 }, { 3, 0 } }, anchors()) -- Cursors did not move.
2778      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
2779
2780      -- Cursor-move by API in-between the toggles is not followed, even with follow=ON initially.
2781      clear_cursors()
2782      n.exec_lua([[
2783        vim.keymap.set('n', '<Up>', function()
2784          local next_pos = vim.pos.cursor(0)
2785          next_pos.row = math.max(next_pos.row - 1, 1)
2786          vim.cmd('norm! Q')
2787          vim.cmd('norm! 2q=')
2788          vim.api.nvim_win_set_cursor(0, next_pos:to_cursor())
2789          vim.cmd('norm! 1q=')
2790        end)
2791      ]])
2792      -- Follow=OFF: cursor on line 5, primary line 4.
2793      cursors({ 'l1', 'l2', 'l3', 'l4', 'l5' }, 'G0<Up>')
2794      eq({ { 4, 0 } }, anchors())
2795      feed('<Up>') -- follow=ON ("1q="): cursor on line 4, primary line 3
2796      eq({ { 3, 0 }, { 4, 0 } }, anchors())
2797      feed('k') -- follow=ON again: cursors follow the motion
2798      eq({ { 2, 0 }, { 3, 0 } }, anchors())
2799      eq({ 2, 0 }, api.nvim_win_get_cursor(0))
2800    end)
2801
2802    it('jumps (absolute motions) are not followed', function()
2803      cursors({ 'abcd', 'efgh', 'ijkl' }, 'Q')
2804      feed('3G') -- Jumps fill the jumplist; no cascade.
2805      feed('2G')
2806      feed('q=') -- Follow-mode.
2807      feed('l') -- Sanity: motions cascade.
2808      eq({ { 0, 1 } }, anchors())
2809      feed('<C-o>') -- Jump.
2810      feed('``') -- Jump.
2811      feed('G')
2812      feed('gg')
2813      feed('L')
2814      eq({ { 0, 1 } }, anchors())
2815
2816      -- Jump from a mapping (no LHS-replay fallback). #41995
2817      command('nnoremap <Down> ]C')
2818      clear_cursors()
2819      cursors({ 'a', 'b', 'c', 'd' }, 'QjQjQj')
2820      feed('1q=')
2821      eq({ { 0, 0 }, { 1, 0 }, { 2, 0 } }, anchors())
2822      eq(4, fn.line('.'))
2823      for _, line in ipairs({ 1, 2, 3, 1 }) do
2824        feed('<Down>')
2825        eq(line, fn.line('.')) -- The primary jumps to the next cursor (wraps)...
2826        eq({ { 0, 0 }, { 1, 0 }, { 2, 0 } }, anchors()) -- ...the cursors stay put.
2827      end
2828    end)
2829
2830    it('"*" follows per-cursor (its own word); keeps the primary search pattern', function()
2831      cursors({ 'foo bar', 'bar baz', 'foo', 'bar', 'baz' }, 'Qj0')
2832      feed('q=')
2833      feed('*') -- Each cursor goes to the next occurrence of its own word.
2834      eq({ { 2, 0 } }, anchors())
2835      eq({ 4, 1 }, { fn.line('.'), fn.col('.') })
2836      eq([[\<bar\>]], fn.getreg('/'))
2837      feed('n') -- The primary's pattern, at each cursor.
2838      eq({ { 3, 0 } }, anchors())
2839      eq({ 1, 5 }, { fn.line('.'), fn.col('.') })
2840    end)
2841
2842    it('cursors follow j/k, gj/gk, arrow keys, and $', function()
2843      cursors({ 'a1', 'a2', 'a3', 'b1', 'b2', 'b3' }, 'Q')
2844      feed('3j') -- Cursors at "a1" and "b1".
2845      feed('q=')
2846      feed('j') -- Both cursors move down.
2847      feed('x')
2848      eq({ 'a1', '2', 'a3', 'b1', '2', 'b3' }, get_lines())
2849      feed('k') -- Both cursors move back up.
2850      feed('x')
2851      eq({ '1', '2', 'a3', '1', '2', 'b3' }, get_lines())
2852      feed('gj') -- Display-line motions follow too.
2853      feed('x')
2854      eq({ '1', '', 'a3', '1', '', 'b3' }, get_lines())
2855      feed('gk')
2856      feed('x')
2857      eq({ '', '', 'a3', '', '', 'b3' }, get_lines())
2858      -- Arrow keys follow.
2859      clear_cursors()
2860      cursors({ 'abcd', 'efgh', 'ijkl', 'mnop' }, 'Q2j') -- Cursors at "abcd" and "ijkl".
2861      feed('q=')
2862      feed('<Down>')
2863      feed('<Right>')
2864      feed('x')
2865      eq({ 'abcd', 'egh', 'ijkl', 'mop' }, get_lines())
2866      feed('<Up>')
2867      feed('<Left>')
2868      feed('x')
2869      eq({ 'bcd', 'egh', 'jkl', 'mop' }, get_lines())
2870      feed('q=')
2871      -- $ moves each cursor to its own EOL.
2872      clear_cursors()
2873      cursors({ 'abc', 'defgh' }, 'Qj')
2874      feed('q=')
2875      feed('$')
2876      feed('x')
2877      eq({ 'ab', 'defg' }, get_lines())
2878
2879      -- A motion that fails (beeps) at primary is not replayed. E.g. "j" at EOB.
2880      clear_cursors()
2881      cursors({ 'a', 'b', 'c' }, 'QjQj') -- Cursors at lines 1-2, primary on the last line.
2882      feed('q=')
2883      feed('j')
2884      feed('x')
2885      eq({ '', '', '' }, get_lines())
2886      -- "0" at col 0 does not move the primary, but also does not fail/beep, so it cascades.
2887      clear_cursors()
2888      cursors({ 'abc', 'def' }, 'llQj0') -- Cursor at column 2, primary at column 0.
2889      feed('q=')
2890      feed('0')
2891      feed('x')
2892      eq({ 'bc', 'ef' }, get_lines())
2893    end)
2894
2895    it('cursors follow mapped motions (nnoremap j gj)', function()
2896      command('nnoremap j gj')
2897      cursors({ 'a1', 'a2', 'b1', 'b2' }, 'Q2j')
2898      feed('q=')
2899      feed('j')
2900      feed('x')
2901      eq({ 'a1', '2', 'b1', '2' }, get_lines())
2902      -- Expr-mapping results follow the same way.
2903      command([[nnoremap <expr> j v:count == 0 ? 'gk' : 'k']])
2904      feed('j')
2905      feed('x')
2906      eq({ '1', '2', '1', '2' }, get_lines())
2907      -- No follow: a motion mapping does not cascade; the "x" does.
2908      feed('q=')
2909      feed('j') -- gk: moves only the primary.
2910      feed('x')
2911      eq({ '', '', '1', '2' }, get_lines())
2912    end)
2913
2914    it('q= while macro-recording does not toggle', function()
2915      fn.setline(1, { 'a1', 'a2', 'b1', 'b2' })
2916      feed('gg0')
2917      feed('Q') -- Cursor placed before recording starts.
2918      feed('qa') -- Start recording.
2919      feed('2j')
2920      feed('q=') -- q stops recording; = is a pending operator...
2921      feed('<Esc>')
2922      feed('j')
2923      feed('x')
2924      -- Follow did not toggle.
2925      eq({ '1', 'a2', 'b1', '2' }, get_lines())
2926    end)
2927
2928    it('per-cursor curswant is kept over short lines', function()
2929      fn.setline(1, { 'ABCDEF', 'xy', 'GHIJKL', 'MNOPQR', 'zw', 'STUVWX' })
2930      feed('gg04l') -- Cursor at (1,4).
2931      feed('Q')
2932      feed('3jhh') -- Primary at (4,2), a different column.
2933      feed('q=')
2934      feed('jj') -- Over the short lines: each cursor keeps its column.
2935      feed('q=')
2936      feed('x')
2937      eq({ 'ABCDEF', 'xy', 'GHIJL', 'MNOPQR', 'zw', 'STVWX' }, get_lines())
2938    end)
2939  end)
2940
2941  describe('parity', function()
2942    it('mapped command cascades its resolved atom', function()
2943      command('nnoremap ,d dw')
2944      cursors({ 'one two aa bb', 'three four cc dd' }, 'Qj')
2945      atoms_start()
2946      feed(',d')
2947      eq({ 'two aa bb', 'four cc dd' }, get_lines())
2948      -- With mcursors: still exactly one CmdAtom event; cascade replays do not emit CmdAtoms.
2949      eq(1, #atoms())
2950      -- Operator + insert mapping: also one unit.
2951      command('nnoremap ,x dwiFOO <esc>')
2952      feed(',x')
2953      eq({ 'FOO aa bb', 'FOO cc dd' }, get_lines())
2954    end)
2955
2956    it('mapping with edits and motions cascades as one unit', function()
2957      -- Split the line at the cursor, ending at the EOL of the first half.
2958      command('nnoremap gj i<c-j><esc>k$')
2959      cursors({ 'aaa bbb', 'ccc ddd', 'eee fff' }, '4lQjQj')
2960      atoms_start()
2961      feed('gj')
2962      eq({ 'aaa ', 'bbb', 'ccc ', 'ddd', 'eee ', 'fff' }, get_lines())
2963      -- The mapping is the atom: exactly one CmdAtom event. Never re-resolved.
2964      local evs = atoms()
2965      eq(1, #evs)
2966      eq({ type = 'mapping', lhs = 'gj', keys = k('1i<Esc>i<NL><Esc>k$'), changed = true }, {
2967        type = evs[1].type,
2968        lhs = evs[1].lhs,
2969        keys = evs[1].keys,
2970        changed = evs[1].changed,
2971      })
2972      -- `atoms` is non-empty iff the atom is a composite of more than one command;
2973      eq({
2974        -- Spans display as "insert" (cascade-internal type).
2975        { type = 'insert', keys = k('1i<Esc>') },
2976        { type = 'insert', keys = k('i<NL><Esc>') },
2977        { type = 'motion', keys = 'k' },
2978        { type = 'motion', keys = '$' },
2979      }, subatoms(evs[1], 'type', 'keys'))
2980      eq({ 'k', false }, { evs[1].atoms[3].cmd, evs[1].atoms[3].changed })
2981      -- The mapping's motions (k$) cascade too, even without "q=", because the mapping edits.
2982      feed('x')
2983      eq({ 'aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff' }, get_lines())
2984    end)
2985
2986    it('live insert cascade emits one whole-session atom', function()
2987      cursors({ 'aaa', 'bbb' }, 'Qj')
2988      atoms_start()
2989      -- Typed key-by-key (event-loop pulses between keys): cascades span-by-span, yet emits one
2990      -- insert-session atom. Spans are cascade-internal, never CmdAtom events.
2991      feed('i')
2992      n.poke_eventloop()
2993      feed('X')
2994      n.poke_eventloop()
2995      feed('Y')
2996      n.poke_eventloop()
2997      feed('<Esc>')
2998      local evs = atoms()
2999      eq(1, #evs)
3000      eq({ type = 'insert', text = 'XY', keys = k('1iXY<Esc>') }, {
3001        type = evs[#evs].type,
3002        text = evs[#evs].text,
3003        keys = evs[#evs].keys,
3004      })
3005      -- Session marks (preview regions, trackers) do not leak: a second session adds none.
3006      local function session_marks()
3007        return n.exec_lua([[
3008          local ns = vim.api.nvim_get_namespaces()['nvim.multicursor._session']
3009          return ns and #vim.api.nvim_buf_get_extmarks(0, ns, 0, -1, {}) or 0
3010        ]])
3011      end
3012      local marks = session_marks()
3013      feed('i')
3014      n.poke_eventloop()
3015      feed('Z')
3016      n.poke_eventloop()
3017      feed('<Esc>')
3018      eq(marks, session_marks())
3019      -- A Visual-entered session keeps its "visual" type: each nested span-replay bracket owns
3020      -- its own InsSession, so it cannot clobber the primary session's `vis`.
3021      clear_cursors()
3022      cursors({ 'alpha one', 'beta two' }, 'Qj')
3023      feed('viwcX<Esc>')
3024      eq({ 'X one', 'X two' }, get_lines())
3025      eq('visual', atom_last().type)
3026    end)
3027
3028    it('InsertEnter/InsertLeave/TextChanged(I) fire once per action', function()
3029      command('let [g:ie, g:il, g:tci, g:tc] = [0, 0, 0, 0]')
3030      command('autocmd InsertEnter * let g:ie += 1')
3031      command('autocmd InsertLeave * let g:il += 1')
3032      command('autocmd TextChangedI * let g:tci += 1')
3033      command('autocmd TextChanged * let g:tc += 1')
3034      cursors({ 'aaa', 'bbb' }, 'Qj')
3035      -- Drain input between keys: TextChanged(I) fires only at idle.
3036      -- The expected counts below are exactly what this sequence produces WITHOUT multicursors.
3037      feed('i')
3038      n.poke_eventloop()
3039      feed('X')
3040      n.poke_eventloop()
3041      feed('Y')
3042      n.poke_eventloop()
3043      feed('<Esc>')
3044      n.poke_eventloop()
3045      eq({ 'XYaaa', 'XYbbb' }, get_lines())
3046      eq(1, api.nvim_get_var('ie'))
3047      eq(1, api.nvim_get_var('il'))
3048      eq(2, api.nvim_get_var('tci')) -- Once per typed char, not per cursor.
3049      eq(1, api.nvim_get_var('tc')) -- Once for the whole session.
3050    end)
3051
3052    it('InsertCharPre fires once per typed char, result applies everywhere', function()
3053      command('let g:icp = 0')
3054      command('autocmd InsertCharPre * let g:icp += 1 | let v:char = toupper(v:char)')
3055      cursors({ 'aaa', 'bbb' }, 'Qj')
3056      feed('ixy<Esc>')
3057      eq({ 'XYaaa', 'XYbbb' }, get_lines())
3058      eq(2, api.nvim_get_var('icp'))
3059    end)
3060
3061    it('TextYankPost fires per cursor with per-cursor contents', function()
3062      command('let g:yanks = []')
3063      command(
3064        'autocmd TextYankPost * let g:yanks += [[v:event.regcontents, luaeval("vim.api.nvim__mcursor_cascading()")]]'
3065      )
3066      cursors({ 'aaa', 'bbb' }, 'Qj')
3067      feed('yy')
3068      -- The primary's own yank fires first and is not a replay.
3069      eq({ { { 'bbb' }, false }, { { 'aaa' }, true } }, api.nvim_get_var('yanks'))
3070      -- The primary's registers win, it is the effective yank.
3071      eq('bbb\n', fn.getreg('"'))
3072    end)
3073  end)
3074
3075  describe('yank DWIM (concat on exit)', function()
3076    it('joins per-cursor yanks (document order) into the register on exit', function()
3077      cursors({ 'foo x', 'bar y', 'baz z' }, 'Qj0Q')
3078      feed('j0') -- Cursors on lines 1,2; primary on line 3 (yanked first).
3079      feed('yiw')
3080      -- During multicursor, the register is the primary's own yank.
3081      eq('baz', fn.getreg('"'))
3082      clear_cursors() -- Exit: concat, in document-order (not yank-order).
3083      eq('foo\nbar\nbaz\n', fn.getreg('"'))
3084      eq('V', fn.getregtype('"')) -- Linewise.
3085    end)
3086
3087    it('a named register concatenates, an untouched one is preserved', function()
3088      fn.setreg('z', 'PRESET') -- 'z' is untouched during multicursor.
3089      cursors({ 'foo', 'bar' }, 'Qj0')
3090      feed('"ayiw')
3091      clear_cursors()
3092      eq('foo\nbar\n', fn.getreg('a')) -- The used register is joined.
3093      eq('PRESET', fn.getreg('z')) -- An untouched register is not tripled.
3094    end)
3095
3096    it('last-write-wins: delete after yank yields the deletes', function()
3097      cursors({ 'aa', 'bb' }, 'Qj0')
3098      feed('yl') -- Yank a char into '"'.
3099      feed('x') -- Delete a char into '"' (overwrites, per register semantics).
3100      clear_cursors()
3101      eq('a\nb\n', fn.getreg('"')) -- The deletes, not the yanks.
3102    end)
3103  end)
3104
3105  describe('options', function()
3106    it("'textwidth' auto-wrap applies at each cursor", function()
3107      api.nvim_set_option_value('textwidth', 10, {})
3108      cursors({ 'aaa', 'bbb' }, 'Qj')
3109      feed('Awww xxx yyy zzz<Esc>')
3110      local lines = get_lines()
3111      -- The text of both cursors wrapped the same way (same number of lines each).
3112      eq(0, #lines % 2)
3113      local half = #lines / 2
3114      for i = 1, half do
3115        local a = lines[i]:gsub('^aaa', '')
3116        local b = lines[half + i]:gsub('^bbb', '')
3117        eq(a, b)
3118      end
3119      -- The primary's line actually wrapped.
3120      eq(true, #lines > 2)
3121    end)
3122  end)
3123
3124  describe('undo', function()
3125    it('redo (CTRL-R) restores the cursors to their post-edit positions', function()
3126      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQj$')
3127      feed('IX <Esc>')
3128      eq({ 'X aaa', 'X bbb', 'X ccc' }, get_lines())
3129      eq({ { 0, 1 }, { 1, 1 } }, anchors())
3130      feed('u')
3131      eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
3132      eq({ { 0, 0 }, { 1, 0 } }, anchors())
3133      feed('<C-r>')
3134      eq({ 'X aaa', 'X bbb', 'X ccc' }, get_lines())
3135      -- Splice adjustment alone would drift the marks to col 2: the
3136      -- explicit post-session positions must be restored.
3137      eq({ { 0, 1 }, { 1, 1 } }, anchors())
3138      -- The primary restores to its recorded post-edit position too (the undo header's cursor is
3139      -- the PRE-change position, it serves undo), in sync with the mcursors.
3140      eq({ 3, 1 }, api.nvim_win_get_cursor(0))
3141      feed('x')
3142      eq({ 'Xaaa', 'Xbbb', 'Xccc' }, get_lines())
3143    end)
3144
3145    it('uu undoes two cascaded edits step by step', function()
3146      cursors({ 'abc', 'def' }, 'Q')
3147      feed('jx')
3148      eq({ 'bc', 'ef' }, get_lines())
3149      feed('x')
3150      eq({ 'c', 'f' }, get_lines())
3151      feed('u')
3152      eq({ 'bc', 'ef' }, get_lines())
3153      feed('u')
3154      eq({ 'abc', 'def' }, get_lines())
3155      feed('<C-r><C-r>')
3156      eq({ 'c', 'f' }, get_lines())
3157      -- Counted undo (2u) likewise treats each cascade as one change.
3158      feed('2u')
3159      eq({ 'abc', 'def' }, get_lines())
3160    end)
3161
3162    it('bulk undo across a live insert then a cascaded delete (one step each)', function()
3163      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQj0')
3164      feed('IX<Esc>') -- live insert at all cursors
3165      eq({ 'Xaaa', 'Xbbb', 'Xccc' }, get_lines())
3166      feed('x') -- cascaded delete at all cursors
3167      eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
3168      feed('u') -- revert the delete everywhere
3169      eq({ 'Xaaa', 'Xbbb', 'Xccc' }, get_lines())
3170      feed('u') -- revert the insert everywhere
3171      eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
3172      eq(3, fn.line('.')) -- primary placement after undoing a live insert
3173    end)
3174
3175    it('one undo reverts a per-cursor newline-insert #41822', function()
3176      -- A newline shifts the line count between the per-cursor replays; single "u" restores it.
3177      cursors({ 'aa', 'bb', 'cc' }, 'Qjj')
3178      feed('A{<CR><Esc>') -- Append + newline at cursor (line 1) and primary (line 3).
3179      eq({ 'aa{', '', 'bb', 'cc{', '' }, get_lines())
3180      feed('u')
3181      eq({ 'aa', 'bb', 'cc' }, get_lines())
3182      feed('<C-r>')
3183      eq({ 'aa{', '', 'bb', 'cc{', '' }, get_lines())
3184      -- "o" opens the line before Insert starts: the range still covers it.
3185      clear_cursors()
3186      cursors({ 'aa', 'bb', 'cc' }, 'Qjj')
3187      feed('ox<Esc>')
3188      eq({ 'aa', 'x', 'bb', 'cc', 'x' }, get_lines())
3189      feed('u')
3190      eq({ 'aa', 'bb', 'cc' }, get_lines())
3191    end)
3192
3193    it('empty insert-session does not add undo state #41883', function()
3194      cursors({ 'abc', 'def', 'ghi' }, 'Qj')
3195      local seq = fn.undotree().seq_last
3196      feed('i<Esc>')
3197      eq(seq, fn.undotree().seq_last)
3198      feed('a<Esc>') -- Move the cursors (records extmark undo), but don't edit.
3199      eq(seq, fn.undotree().seq_last)
3200      -- In a mapping the session shares the mapping's undo state: only its own entry is dropped.
3201      command('nnoremap <F5> xi<Esc>')
3202      feed('<F5>')
3203      eq({ 'bc', 'ef', 'ghi' }, get_lines())
3204      eq(seq + 1, fn.undotree().seq_last)
3205      feed('u')
3206      eq({ 'abc', 'def', 'ghi' }, get_lines())
3207      -- After an undo, the redo branch survives.
3208      feed('i<Esc>')
3209      eq(seq + 1, fn.undotree().seq_last)
3210      feed('<C-r>')
3211      eq({ 'bc', 'ef', 'ghi' }, get_lines())
3212    end)
3213
3214    it('u/CTRL-R ping-pong toggles without drift', function()
3215      -- Repeated undo/redo of one cascade must stabilize (no extmark drift).
3216      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQ')
3217      feed('jx')
3218      eq({ 'aa', 'bb', 'cc' }, get_lines())
3219      for _ = 1, 2 do
3220        feed('u')
3221        eq({ 'aaa', 'bbb', 'ccc' }, get_lines())
3222        eq({ { 0, 0 }, { 1, 0 } }, anchors())
3223        feed('<C-r>')
3224        eq({ 'aa', 'bb', 'cc' }, get_lines())
3225        eq({ { 0, 0 }, { 1, 0 } }, anchors())
3226      end
3227    end)
3228
3229    it('undo steps across the mc-enter boundary', function()
3230      -- Q is placement, not an edit: the undo tree spans pre-mc and in-mc
3231      -- edits with no extra step in between.
3232      fn.setline(1, { 'xxx', 'yyy' })
3233      feed('gg0x')
3234      eq({ 'xx', 'yyy' }, get_lines())
3235      feed('Q')
3236      feed('jx')
3237      eq({ 'x', 'yy' }, get_lines())
3238      feed('u')
3239      eq({ 'xx', 'yyy' }, get_lines())
3240      feed('u')
3241      eq({ 'xxx', 'yyy' }, get_lines())
3242    end)
3243
3244    it('one u/CTRL-R reverts a whole macro (@q) cascade', function()
3245      -- "@x" cascades as ONE unit, so it is one undo block.
3246      fn.setreg('q', 'iX\027')
3247      cursors({ 'aaa', 'bbb' }, 'Qj')
3248      feed('@q')
3249      eq({ 'Xaaa', 'Xbbb' }, get_lines())
3250      feed('u')
3251      eq({ 'aaa', 'bbb' }, get_lines())
3252      feed('<C-r>')
3253      eq({ 'Xaaa', 'Xbbb' }, get_lines())
3254    end)
3255
3256    it('u undoes a visual-mode cascade at all cursors', function()
3257      cursors({ 'abc def', 'ghi jkl' }, 'Qj')
3258      feed('viwd')
3259      eq({ ' def', ' jkl' }, get_lines())
3260      feed('u')
3261      eq({ 'abc def', 'ghi jkl' }, get_lines())
3262      -- The cursors are back at their pre-edit positions.
3263      feed('x')
3264      eq({ 'bc def', 'hi jkl' }, get_lines())
3265    end)
3266
3267    it('g-/g+ (time-travel) exits multicursor mode', function()
3268      -- Out of scope forever (mcursor.md): time-travel jumps across cascade
3269      -- boundaries, where per-cursor state is meaningless: all cursors are
3270      -- removed instead.
3271      cursors({ 'aaa', 'bbb' }, 'Q')
3272      feed('jx')
3273      eq({ 'aa', 'bb' }, get_lines())
3274      eq(1, ncursors())
3275      feed('g-')
3276      eq(0, ncursors())
3277      eq({ 'aaa', 'bbb' }, get_lines()) -- one step back: the whole cascade
3278      feed('g+')
3279      eq(0, ncursors()) -- still out of multicursor mode
3280      eq({ 'aa', 'bb' }, get_lines())
3281      feed('Q') -- a new session starts cleanly
3282      eq(1, ncursors())
3283    end)
3284
3285    it('u restores the buffer but NOT the registers (Vim parity)', function()
3286      -- Undo never restores registers.
3287      cursors({ 'foo x', 'bar y' }, 'Qj0')
3288      feed('diw') -- each cursor deletes its word into its own register
3289      eq({ ' x', ' y' }, get_lines())
3290      feed('u')
3291      eq({ 'foo x', 'bar y' }, get_lines())
3292      -- The primary's register still holds its deletion...
3293      eq('bar', fn.getreg('"'))
3294      -- ...and the per-cursor values persist too: exiting concatenates them
3295      -- (yank DWIM) as if the undo never happened.
3296      clear_cursors()
3297      eq('foo\nbar\n', fn.getreg('"'))
3298    end)
3299  end)
3300
3301  describe('same-line cursors', function()
3302    it('two cursors on one line edit at their own columns', function()
3303      cursors({ 'abcdef' }, 'Q4l')
3304      feed('x')
3305      eq({ 'bcdf' }, get_lines())
3306      feed('x')
3307      eq({ 'cd' }, get_lines())
3308    end)
3309
3310    it('linewise op with two cursors on one line applies once', function()
3311      pending('policy: dedup linewise ops for same-line cursors (mcursor.md)')
3312    end)
3313
3314    it('coincident cursors merge', function()
3315      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQ')
3316      feed('q=')
3317      feed('9j') -- All cursors to the last line.
3318      feed('q=')
3319      feed('x') -- One deletion, not three.
3320      eq({ 'aaa', 'bbb', 'cc' }, get_lines())
3321    end)
3322  end)
3323
3324  describe('multibyte', function()
3325    it('cursor highlight covers a double-width char', function()
3326      local screen = Screen.new(20, 4)
3327      cursors({ '日本語', '中文字' }, 'Qj')
3328      screen:expect([[
3329        {17:日}本語              |
3330        ^中文字              |
3331        {1:~                   }|
3332                            |
3333      ]])
3334    end)
3335  end)
3336
3337  describe('terminal multiple-cursors protocol', function()
3338    local exec_lua = n.exec_lua
3339
3340    before_each(function()
3341      -- Stub the UI channel: record emitted sequences instead of sending.
3342      exec_lua([[
3343        _G.sent = {}
3344        vim.api.nvim_ui_send = function(s)
3345          table.insert(_G.sent, s)
3346        end
3347      ]])
3348    end)
3349
3350    --- Runs detect() and replies to its support query with the given TermResponse `sequence`.
3351    local function detect(sequence)
3352      exec_lua(([[
3353        require('vim._core.mcursor').detect({ chan = 1 })
3354        vim.api.nvim_exec_autocmds('TermResponse', {
3355          data = { sequence = %q, chan = 1 },
3356        })
3357      ]]):format(sequence))
3358    end
3359
3360    it('enabled only if the terminal reply lists shape 29', function()
3361      detect('\027[>1;2;3 q') -- no shape 29
3362      -- The support query was sent, but no cursor updates follow.
3363      eq({ '\027[> q' }, exec_lua('return _G.sent'))
3364      feed('Q')
3365      exec_lua('vim.wait(10)')
3366      eq({ '\027[> q' }, exec_lua('return _G.sent'))
3367    end)
3368
3369    it('displays multicursors as terminal cursors', function()
3370      local screen = Screen.new(30, 6)
3371      detect('\027[>1;2;3;29;30;40;100;101 q')
3372
3373      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQ')
3374      exec_lua('vim.wait(10)') -- drain the scheduled refresh
3375      -- Clear-all, text color (30), cursor color (40), then positions (29).
3376      local sent = exec_lua('return _G.sent')
3377      t.matches(
3378        '^\027%[>0;4 q\027%[>30;2:%d+:%d+:%d+ q\027%[>40;2:%d+:%d+:%d+ q\027%[>29;2:1:1;2:2:1 q$',
3379        sent[#sent]
3380      )
3381
3382      -- The cell-highlight fallback is suppressed (no {17:} on line 1).
3383      screen:expect([[
3384        aaa                           |
3385        ^bbb                           |
3386        ccc                           |
3387        {1:~                             }|*2
3388                                      |
3389      ]])
3390
3391      -- Removing all cursors clears the terminal cursors.
3392      clear_cursors()
3393      exec_lua('vim.wait(10)')
3394      sent = exec_lua('return _G.sent')
3395      eq('\027[>0;4 q', sent[#sent])
3396
3397      -- tty_cursors(false) restores the cell-highlight fallback.
3398      feed('Q')
3399      exec_lua("require('vim._core.mcursor').tty_cursors(false)")
3400      screen:expect([[
3401        aaa                           |
3402        {17:^b}bb                           |
3403        ccc                           |
3404        {1:~                             }|*2
3405                                      |
3406      ]])
3407    end)
3408
3409    it('displays the cursors of every visible window (splits)', function()
3410      local _ = Screen.new(30, 9)
3411      detect('\027[>1;2;3;29;30;40;100;101 q')
3412      fn.setline(1, { 'aaa', 'bbb' })
3413      feed('gg0Q') -- cursor in buffer 1
3414      command('split | enew') -- top window: a second buffer
3415      fn.setline(1, { 'xxx', 'yyy' })
3416      feed('gg0Q') -- cursor in buffer 2
3417      exec_lua('vim.wait(10)')
3418      -- The last sequence draws BOTH cursors: buffer 2's in the focused top
3419      -- window, and buffer 1's in the (unfocused) bottom window.
3420      local sent = exec_lua('return _G.sent') ---@type string[]
3421      local seq = sent[#sent]
3422      local win1 = fn.win_getid(fn.winnr('j'))
3423      local pos1 = fn.screenpos(win1, 1, 1)
3424      t.ok(
3425        seq:find(('2:%d:%d'):format(pos1.row, pos1.col), 1, true) ~= nil,
3426        'buf1 cursor drawn',
3427        seq
3428      )
3429      local pos2 = fn.screenpos(0, 1, 1)
3430      t.ok(
3431        seq:find(('2:%d:%d'):format(pos2.row, pos2.col), 1, true) ~= nil,
3432        'buf2 cursor drawn',
3433        seq
3434      )
3435    end)
3436  end)
3437
3438  describe("'operatorfunc' (g@)", function()
3439    it('VISUAL-mode surround ("S") cascades', function()
3440      pending('visual ":" LHS-replay: the visual selection differs per cursor; TODO')
3441      -- Minimal vim-surround "S": VSurround is an Ex command plus a getchar()
3442      -- payload: `:<C-U>call <SID>opfunc(visualmode(),...)<CR>` + the wrap char.
3443      n.exec([=[
3444        function! VisualSurround() abort
3445          let c = nr2char(getchar())
3446          let [l1, c1] = getpos("'<")[1:2]
3447          let [l2, c2] = getpos("'>")[1:2]
3448          call setpos('.', [0, l2, c2, 0])
3449          exe "normal! a" . c
3450          call setpos('.', [0, l1, c1, 0])
3451          exe "normal! i" . c
3452        endfunction
3453        xnoremap <silent> S :<C-U>call VisualSurround()<CR>
3454      ]=])
3455      cursors({ 'foo one', 'bar two' }, 'Qj0')
3456      feed('viwS"')
3457      -- Each cursor's own word is wrapped (per-cursor extents, like "viwd").
3458      eq({ '"foo" one', '"bar" two' }, get_lines())
3459    end)
3460
3461    it('surround plugin (w/ getchar() payload) cascades; one u/CTRL-R reverts', function()
3462      -- The op edits each cursor's region through :normal + register juggling (a full
3463      -- exec_normal() per cursor).
3464      n.exec(t_atom.minisurround_vim)
3465      cursors({ 'alpha beta', 'gamma delta', 'epsilon zeta' }, 'Qj0Qj0')
3466      atoms_start()
3467      feed('ysiw"')
3468      -- The atom is the redobuff plus the getchar()'d payload: the replayed
3469      -- opfunc reads the same wrap char.
3470      eq({ 'g@iw"' }, atoms_tail(1))
3471      eq({ '"alpha" beta', '"gamma" delta', '"epsilon" zeta' }, get_lines())
3472      -- The whole cascade (primary + replays) is ONE undo step: a single
3473      -- u/CTRL-R reverts or reapplies it at every cursor.
3474      feed('u')
3475      eq({ 'alpha beta', 'gamma delta', 'epsilon zeta' }, get_lines())
3476      feed('<C-r>')
3477      eq({ '"alpha" beta', '"gamma" delta', '"epsilon" zeta' }, get_lines())
3478    end)
3479
3480    it('no-effect operator (aborted "ysa[") does not cascade', function()
3481      -- vim-surround "ysa[" whose surround char is <Esc>/CTRL-C: a redoable g@ whose opfunc does
3482      -- nothing. Its "a[" textobject jumps EVERY cursor to the same "[", so a cascade would
3483      -- collapse them (dedupe). No edit and no register write = no per-cursor effect: must not
3484      -- cascade.
3485      n.exec([[
3486        function! Noop(type) abort
3487          call getchar()
3488        endfunction
3489        function! NoopSetup() abort
3490          set operatorfunc=Noop
3491          return 'g@'
3492        endfunction
3493        nnoremap <expr> ,s NoopSetup()
3494      ]])
3495      fn.setline(1, { 'aaa', 'bbb', 'ccc', 'x [y] z' }) -- only line 4 has brackets
3496      feed('gg0Qj0') -- cursor on line 1, primary on line 2 (neither has brackets)
3497      feed(',sa[z') -- g@ + a[ jumps primary to line 4's "["; opfunc getchar()'s "z", does nothing
3498      eq(1, ncursors()) -- the cursor survives
3499    end)
3500
3501    it('motion-only operator cascades during follow-mode #41612', function()
3502      -- The operator does not change text/registers; it only moves the cursor.
3503      n.exec_lua([[
3504        local function test_op(motion)
3505          if motion == nil then
3506            vim.o.operatorfunc = test_op
3507            return 'g@'
3508          end
3509          local pos = vim.pos.cursor()
3510          local line = vim.api.nvim_buf_get_lines(pos.buf, pos.row, pos.row + 1, false)[1]
3511          pos.col = #line
3512          vim.api.nvim_win_set_cursor(0, pos:to_cursor())
3513        end
3514        vim.keymap.set('n', 'gm', test_op, { expr = true })
3515      ]])
3516      cursors({ 'aaaa', 'bbbbb', 'cccccc' }, 'QjQj')
3517      feed('1q=')
3518      atoms_start()
3519      feed('gmil')
3520      eq({ { 0, 3 }, { 1, 4 } }, anchors())
3521      eq(6, fn.col('.'))
3522      -- Exactly one type=operator atom.
3523      eq(1, #atoms())
3524      eq({
3525        type = 'operator',
3526        keys = 'g@il',
3527        lhs = 'gmil',
3528        operator = 'g@',
3529        changed = false,
3530        moved = true,
3531      }, t.pick(atom_last(), 'type', 'keys', 'lhs', 'operator', 'changed', 'moved'))
3532    end)
3533
3534    it('cursors placed inside the opfunc are live for the next typed cascade', function()
3535      -- Occurrence-operator pattern (vim-mode-plus "co{motion}", issue #21334): the
3536      -- 'operatorfunc' places a cursor at each occurrence of the word within the motion, then
3537      -- a following typed edit cascades to all of them. Rule: extmarks added from WITHIN
3538      -- an opfunc yield cursors the next command cascades to (the g@ itself has no
3539      -- effect, so it does not cascade and the placed cursors survive, like |v_Q| placement).
3540      n.exec_lua([==[
3541        _G.occur_opfunc = function()
3542          local ms = vim.fn.matchbufline('%', _G.occur_pat, vim.fn.line("'["), vim.fn.line("']"))
3543          vim.api.nvim_win_set_cursor(0, { ms[1].lnum, ms[1].byteidx })
3544          local ns = vim.api.nvim_create_namespace('nvim.multicursor')
3545          for i = 2, #ms do
3546            vim.api.nvim_buf_set_extmark(0, ns, ms[i].lnum - 1, ms[i].byteidx, {})
3547          end
3548        end
3549        vim.keymap.set('n', 'co', function()
3550          _G.occur_pat = ([[\<%s\>]]):format(vim.fn.expand('<cword>')) -- before g@ moves the cursor
3551          vim.o.operatorfunc = 'v:lua.occur_opfunc'
3552          return 'g@'
3553        end, { expr = true })
3554      ]==])
3555      fn.setline(1, { 'text a text', 'b text c' })
3556      api.nvim_win_set_cursor(0, { 1, 0 }) -- on the first "text"
3557      feed('coip') -- place a cursor at every "text" in the paragraph
3558      eq(2, ncursors()) -- 3 matches: primary + 2 multicursors
3559      feed('ciwWORD<Esc>') -- a typed edit cascades to the opfunc-placed cursors
3560      eq({ 'WORD a WORD', 'b WORD c' }, get_lines())
3561    end)
3562
3563    it(
3564      'payload mapping (":call" + getchar, like vim-surround "ds") cascades via LHS-replay',
3565      function()
3566        -- A mapping whose edit is done through :normal is invisible to atom
3567        -- capture (decide-once sees nothing). It cascades by re-running the
3568        -- mapping (LHS + the getchar()'d target) at each cursor: LHS-replay.
3569        n.exec(t_atom.delsurround_vim)
3570        fn.setline(1, { 'a (one)', 'b (two)', 'c (three)' })
3571        feed('gg0f(Qj0f(Qj0f(')
3572        atoms_start()
3573        feed('ds)') -- ")" is the getchar()'d payload
3574        eq({ 'a one', 'b two', 'c three' }, get_lines())
3575        -- The emitted atom carries the resolution plus the getchar()'d payload; the cascade
3576        -- itself re-runs `lhs` (the edit is invisible, so nothing was queued for it).
3577        local ev = atoms()[#atoms()]
3578        eq({ lhs = 'ds)', keys = ':call DelSurround()\n)' }, { lhs = ev.lhs, keys = ev.keys })
3579
3580        -- Same for a mapping that produces NO capturable keys at all (kKeyOpaque):
3581        -- "<Cmd>" (K_COMMAND) and a Lua callback (K_LUA). Both are real user
3582        -- keystrokes, so their edit is a mapping edit and cascades by LHS-replay.
3583        command('nnoremap <F3> <Cmd>normal! x<CR>')
3584        n.exec_lua([[vim.keymap.set('n', '<F4>', function() vim.cmd('normal! x') end)]])
3585        for _, lhs in ipairs({ '<F3>', '<F4>' }) do
3586          clear_cursors()
3587          fn.setline(1, { 'aaa', 'bbb', 'ccc' })
3588          feed('gg0QjQj')
3589          feed(lhs)
3590          eq({ 'aa', 'bb', 'cc' }, get_lines())
3591        end
3592
3593        -- Op-pending payload mapping (vim-sneak :omap) cascades by `keys`.
3594        n.exec(t_atom.minisneak_vim)
3595        clear_cursors()
3596        fn.setline(1, { 'aa (x) here', 'bb (y) here', 'cc (z) here' })
3597        feed('gg0QjQj')
3598        feed('dzhe')
3599        eq({ 'here', 'here', 'here' }, get_lines())
3600
3601        -- Lua :omap textobject (starts Visual mode, |omap-info|) cascades by `keys` too. #41482
3602        n.exec_lua([[
3603          vim.keymap.set('o', 'gt', function()
3604            vim.cmd('normal! viw')
3605          end)
3606        ]])
3607        clear_cursors()
3608        fn.setline(1, { 'aaa xxx', 'bbb yyy', 'ccc zzz' })
3609        feed('gg0wQj0wQj0w')
3610        feed('dgt')
3611        eq({ 'aaa ', 'bbb ', 'ccc ' }, get_lines())
3612      end
3613    )
3614  end)
3615
3616  describe(']C and [C', function()
3617    local function cur()
3618      return { fn.line('.'), fn.col('.') - 1 }
3619    end
3620
3621    -- The default mappings require the standard startup.
3622    before_each(function()
3623      n.clear({ args_rm = { '--cmd' } })
3624    end)
3625
3626    it(']C scrolls the viewport to an off-screen cursor', function()
3627      local screen = Screen.new(30, 6)
3628      local lines = {} ---@type string[]
3629      for i = 1, 40 do
3630        lines[i] = ('line %d'):format(i)
3631      end
3632      fn.setline(1, lines)
3633      feed('gg0Q')
3634      add_cursor(0, { 30, 0 })
3635      feed(']C') -- jump to line 30: the viewport must follow
3636      eq(30, fn.line('.'))
3637      screen:expect({ any = 'ine 30' }) -- ("l" is under the painted cursor cell)
3638    end)
3639
3640    it('cycle through the cursors, wrapping', function()
3641      cursors({ 'aaa', 'bbb', 'ccc', 'ddd' }, 'Q2jllQ')
3642      feed('gg0j')
3643      feed(']C')
3644      eq({ 3, 2 }, cur())
3645      eq({ { 0, 0 }, { 2, 2 } }, anchors())
3646      feed(']C') -- wraps
3647      eq({ 1, 0 }, cur())
3648      feed('2]C') -- count
3649      eq({ 1, 0 }, cur())
3650      feed('[C')
3651      eq({ 3, 2 }, cur())
3652      feed('[C')
3653      eq({ 1, 0 }, cur())
3654      feed(']CQ') -- "]CQ" removes the cursor it lands on.
3655      eq({ { 0, 0 } }, anchors())
3656      -- |mcursor-examples| mapping: ]C lays an egg before jumping.
3657      n.exec_lua([[
3658        local ns = vim.api.nvim_create_namespace('nvim.multicursor')
3659        vim.keymap.set('n', ']C', function()
3660          local row, col = vim.pos.cursor(0):to_extmark()
3661          vim.api.nvim_buf_set_extmark(0, ns, row, col, {})
3662          vim.cmd('normal! ]C')
3663        end)
3664      ]])
3665      feed(']C')
3666      eq({ 1, 0 }, cur())
3667      eq({ { 0, 0 }, { 2, 2 } }, anchors())
3668      feed(']C')
3669      eq({ 3, 2 }, cur())
3670      eq({ { 0, 0 }, { 2, 2 } }, anchors())
3671    end)
3672
3673    it('does not move the other cursors in q= mode', function()
3674      cursors({ 'aaa', 'bbb', 'ccc' }, 'Qj')
3675      feed('q=')
3676      feed(']C')
3677      eq({ 1, 0 }, cur())
3678      eq({ { 0, 0 } }, anchors())
3679      feed('q=')
3680    end)
3681
3682    it('beeps and does not move without cursors', function()
3683      fn.setline(1, { 'aaa' })
3684      feed('gg0')
3685      eq(0, fn.assert_beeps('normal! ]C'))
3686      eq({ 1, 0 }, cur())
3687    end)
3688  end)
3689
3690  describe('treesitter', function()
3691    it('incremental selections at each cursor #41716', function()
3692      -- The default ts "an"/"in" mappings: setpos("'<") + "gv" in Lua.
3693      clear({ args_rm = { '--cmd' } })
3694      command(n.nvim_set)
3695      command('colorscheme vim')
3696      command('hi MCursor guifg=Black guibg=LightGrey')
3697      local screen = Screen.new(30, 6)
3698      command('set filetype=lua')
3699      cursors({ 'foo(one, two)', 'bar(three, four)', 'baz(five, six)' }, 'ftQj0ffQj0fs')
3700      eq({ { 0, 9 }, { 1, 11 } }, anchors())
3701      eq({ 3, 10 }, api.nvim_win_get_cursor(0))
3702      feed('van')
3703      screen:expect([[
3704        foo(one, {17:two})                 |
3705        bar(three, {17:four})              |
3706        baz(five, {17:si^x})                |
3707        {1:~                             }|*2
3708        {5:-- VISUAL --}                  |
3709      ]])
3710      feed('an')
3711      screen:expect([[
3712        foo{17:(one, two)}                 |
3713        bar{17:(three, four)}              |
3714        baz{17:(five, six^)}                |
3715        {1:~                             }|*2
3716        {5:-- VISUAL --}                  |
3717      ]])
3718      -- TODO: "in" after "an": the primary selects the first child. #42000
3719      -- feed('in')
3720      -- screen:expect([[
3721      --   foo(one, {17:two})                 |
3722      --   bar(three, {17:four})              |
3723      --   baz(five, {17:si}^x)                |
3724      --   {1:~                             }|*2
3725      --   {5:-- VISUAL --}                  |
3726      -- ]])
3727      feed('cX')
3728      eq({ 'fooX', 'barX', 'bazX' }, get_lines())
3729      eq('i', fn.mode())
3730      feed('<Esc>')
3731      eq({ 'fooX', 'barX', 'bazX' }, get_lines())
3732
3733      clear_cursors()
3734      cursors({ 'foo(one, two)', 'bar(three, four)', 'baz(five, six)' }, 'ftQj0ffQj0fs')
3735      feed('canX')
3736      eq({ 'foo(one, X)', 'bar(three, X)', 'baz(five, X)' }, get_lines())
3737      eq('i', fn.mode())
3738      feed('<Esc>')
3739      eq({ 'foo(one, X)', 'bar(three, X)', 'baz(five, X)' }, get_lines())
3740    end)
3741
3742    it('markdown highlighting survives a live insert', function()
3743      n.exec_lua([[
3744        -- Large, injection-heavy buffer: multi-slice ASYNC parses (the
3745        -- crash lived in a resumed parse's external scanner).
3746        local lines = {}
3747        for i = 1, 800 do
3748          vim.list_extend(lines, {
3749            ('# Section %d'):format(i),
3750            '',
3751            '- item with `code` and *emphasis*',
3752            '  - nested [link](http://x)',
3753            '',
3754            '```lua',
3755            'local x = ' .. i,
3756            '```',
3757            '',
3758          })
3759        end
3760        vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
3761        vim.treesitter.start(0, 'markdown')
3762      ]])
3763      feed('gg0Q2jQ2jQ4j')
3764      feed('A')
3765      for c in ('hello world'):gmatch('.') do
3766        feed(c)
3767        n.poke_eventloop()
3768      end
3769      feed('<Esc>')
3770      feed('u')
3771      feed('<C-r>')
3772      n.assert_alive()
3773    end)
3774  end)
3775
3776  describe('clipboard', function()
3777    it("does not crash after jumping to an empty line with 'clipboard'", function()
3778      n.exec_lua([[
3779        _G.content = {}
3780        vim.g.clipboard = {
3781          name = 'test',
3782          copy = {
3783            ['+'] = function(lines)
3784              _G.content = lines
3785            end,
3786          },
3787          paste = {
3788            ['+'] = function()
3789              return _G.content
3790            end,
3791          },
3792        }
3793        vim.o.clipboard = 'unnamedplus'
3794      ]])
3795      cursors({ '', 'aa' }, 'QjQ') -- Cursors on both lines, primary on the non-empty line.
3796      feed(']C') -- Make the empty-line cursor primary.
3797      feed('C')
3798      n.assert_alive()
3799      feed('<Esc>')
3800      eq({ '', '' }, get_lines())
3801    end)
3802
3803    it('clipboard: implicit clipboard=unnamed[plus], explicit "+', function()
3804      n.exec_lua([[
3805        _G.copies, _G.pastes = 0, 0
3806        _G.content = {}
3807        vim.g.clipboard = {
3808          name = 'test',
3809          copy = {
3810            ['+'] = function(lines)
3811              _G.copies = _G.copies + 1
3812              _G.content = lines
3813            end,
3814          },
3815          paste = {
3816            ['+'] = function()
3817              _G.pastes = _G.pastes + 1
3818              return _G.content
3819            end,
3820          },
3821        }
3822      ]])
3823      local function provider()
3824        return n.exec_lua('return { _G.copies, _G.pastes, _G.content }')
3825      end
3826
3827      -- Implicit clipboard (clipboard=unnamed[plus]) is ignored during cascade.
3828      -- On multicursor exit, the unnamed (") join is written to the clipboard.
3829      command('set clipboard=unnamedplus')
3830      cursors({ 'aa bb', 'cc dd', 'ee ff' })
3831      feed('dw')
3832      eq({ 'bb', 'dd', 'ff' }, get_lines())
3833      -- Clipboard provider was updated only by the primary's "dw". Not cascaded.
3834      eq({ 1, 0, { 'ee ' } }, provider())
3835      feed('p') -- Pastes unnamed reg (not clipboard) per-cursor.
3836      eq({ 'baa b', 'dcc d', 'fee f' }, get_lines())
3837      eq({ 1, 1, { 'ee ' } }, provider())
3838      clear_cursors() -- Exit: the joined yank is written to the clipboard.
3839      eq({ 2, 1, { 'aa ', 'cc ', 'ee ', '' } }, provider())
3840
3841      -- Explicit clipboard "+".
3842      command('set clipboard=')
3843      cursors({ 'aa', 'bb' }, 'Qj0')
3844      feed('"+yy') -- Explicit "+: writes the primary's yank to the clipboard.
3845      eq({ 3, 1, { 'bb', '' } }, provider())
3846      feed('"+p') -- Explicit "+: pastes the primary's clipboard at every cursor.
3847      eq({ 'aa', 'bb', 'bb', 'bb' }, get_lines())
3848      eq({ 3, 2, { 'bb', '' } }, provider())
3849      clear_cursors()
3850      eq({ 3, 2, { 'bb', '' } }, provider())
3851    end)
3852  end)
3853
3854  describe('UI integration', function()
3855    it('cursor positions are pushed to UIs (win_extmark)', function()
3856      local screen = Screen.new(30, 5)
3857      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjlQj')
3858      local ns = api.nvim_create_namespace('nvim.multicursor')
3859      local marks = api.nvim_buf_get_extmarks(0, ns, 0, -1, {})
3860      eq(2, #marks)
3861      screen:expect({
3862        grid = [[
3863        {17:a}aa                           |
3864        b{17:b}b                           |
3865        c^cc                           |
3866        {1:~                             }|
3867                                      |
3868      ]],
3869        extmarks = {
3870          [2] = {
3871            { 1000, ns, marks[1][1], 0, 0 },
3872            { 1000, ns, marks[2][1], 1, 1 },
3873          },
3874        },
3875      })
3876    end)
3877
3878    it('showcmd area shows the cursor count ("N×"), also with ui2', function()
3879      local screen ---@type test.functional.ui.screen
3880      for _, ui2 in ipairs({ false, true }) do
3881        clear()
3882        command('hi MCursor guifg=Black guibg=LightGrey')
3883        screen = Screen.new(30, 5)
3884        command('set showcmd') -- the test env defaults to 'noshowcmd'
3885        if ui2 then
3886          n.exec_lua([[require('vim._core.ui2').enable({})]])
3887        end
3888        cursors({ 'aaa', 'bbb', 'ccc' }, 'Q')
3889        screen:expect({ any = '1×' })
3890        feed('jQ')
3891        screen:expect({ any = '2×' })
3892        feed('q=') -- Follow mode: "=" prefix.
3893        feed('l') -- Tickle showcmd redraw.
3894        screen:expect({ any = '=2×' })
3895        feed('q=') -- Follow mode off.
3896        feed('h') --  Tickle showcmd redraw.
3897        clear_cursors() -- cleared with the cursors
3898        feed('<Esc>') -- the indicator refreshes on the next command
3899        screen:expect({ none = '×' })
3900      end
3901
3902      -- ui2 redraws on 'showcmd', which should only update AFTER cascade, not during. #42081 #41659
3903      n.exec_lua(function()
3904        _G.seen = {}
3905        local ns = vim.api.nvim_create_namespace('nvim.multicursor.cursor')
3906        vim.ui_attach(vim.api.nvim_create_namespace('test'), { ext_messages = true }, function(ev)
3907          if ev == 'msg_showcmd' then
3908            -- Buffer text, cursor column, and selection-end columns.
3909            local ends = vim.tbl_map(function(m)
3910              return m[3]
3911            end, vim.api.nvim_buf_get_extmarks(0, ns, 0, -1, {}))
3912            _G.seen[#_G.seen + 1] = ('%s %d %s'):format(
3913              table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, true), ','),
3914              vim.fn.col('.') - 1,
3915              table.concat(ends, ',')
3916            )
3917          end
3918        end)
3919      end)
3920      clear_cursors()
3921      cursors({ 'aaa', 'bbb', 'ccc' }, 'QjQjQ')
3922      screen:expect({ any = '3×' }) -- Input processed, before resetting `seen`.
3923      n.exec_lua('_G.seen = {}')
3924      feed('rx')
3925      screen:expect([[
3926        {17:x}aa                           |
3927        {17:x}bb                           |
3928        {17:^x}cc                           |
3929        {1:~                             }|
3930                            3×        |
3931      ]])
3932      eq({ 'aaa,bbb,ccc 0 ', 'xaa,xbb,xcc 0 ' }, n.exec_lua('return _G.seen'))
3933      n.exec_lua('_G.seen = {}')
3934      feed('vl')
3935      screen:expect([[
3936        {17:xa}a                           |
3937        {17:xb}b                           |
3938        {17:x^c}c                           |
3939        {1:~                             }|
3940        {5:-- VISUAL --}        3× 2      |
3941      ]])
3942      eq(
3943        { 'xaa,xbb,xcc 0 0,0,0', 'xaa,xbb,xcc 1 1,1,1', 'xaa,xbb,xcc 1 1,1,1' },
3944        n.exec_lua('return _G.seen')
3945      )
3946    end)
3947  end)
3948
3949  describe('workflows', function()
3950    it('follow-once mapping', function()
3951      n.exec_lua([[
3952        vim.keymap.set('n', 'q-', function()
3953          vim.cmd('normal! 1q=')
3954          vim.api.nvim_create_autocmd('CmdAtom', {
3955            callback = function(ev)
3956              if ev.data.lhs == 'q-' then
3957                return
3958              end
3959              vim.cmd('normal! 2q=')
3960              return true
3961            end,
3962          })
3963        end)
3964      ]])
3965      cursors({ '  aaa', '  bbb', '  ccc' })
3966      feed('q-')
3967      feed('^') -- Cascades: every cursor moves to the first non-blank.
3968      eq({ { 0, 2 }, { 1, 2 } }, anchors())
3969      feed('l') -- Follow already ended: primary only.
3970      eq({ { 0, 2 }, { 1, 2 } }, anchors())
3971      eq(4, fn.col('.'))
3972    end)
3973
3974    it('place a cursor at a range of quickfix items: :cdo normal! Q', function()
3975      fn.setline(1, { 'aaa', 'bbb', 'ccc', 'ddd' })
3976      fn.setqflist({
3977        { bufnr = fn.bufnr(''), lnum = 1, col = 1 },
3978        { bufnr = fn.bufnr(''), lnum = 2, col = 1 },
3979        { bufnr = fn.bufnr(''), lnum = 4, col = 1 },
3980      })
3981      command('cdo normal! Q')
3982      eq(3, ncursors())
3983      feed('3G0') -- Move the primary off the last item's cursor (it would double-apply).
3984      feed('x')
3985      eq({ 'aa', 'bb', 'cc', 'dd' }, get_lines())
3986      -- A range addresses quickfix items: cursors on items 2-3 only.
3987      clear_cursors()
3988      command('2,3cdo normal! Q')
3989      eq(2, ncursors())
3990    end)
3991
3992    it('CTRL-X/CTRL-A apply at each cursor; g CTRL-A is the counter', function()
3993      cursors({ 'x = 5', 'y = 5' }, 'Qj')
3994      feed('<C-x>')
3995      eq({ 'x = 4', 'y = 4' }, get_lines())
3996      feed('<C-a>')
3997      eq({ 'x = 5', 'y = 5' }, get_lines())
3998      -- g_CTRL-A inserts counter at the cursor positions.
3999      feed('g<C-a>')
4000      eq({ 'x = 15', 'y = 25' }, get_lines())
4001    end)
4002
4003    it('typeahead behind the cascade-triggering key is not consumed by replays', function()
4004      -- Batch input: "x" cascades; queued "yy" must survive the replays (save_current_state), then
4005      -- cascade (per-cursor registers prove the yank ran at both cursors).
4006      cursors({ 'abc', 'def' }, 'Qj')
4007      feed('xyy')
4008      eq({ 'bc', 'ef' }, get_lines())
4009      feed('p')
4010      eq({ 'bc', 'bc', 'ef', 'ef' }, get_lines())
4011    end)
4012
4013    it('x then p at EOL on lines of different lengths', function()
4014      -- Jagged EOL: each cursor deletes last char into its own register, then pastes at its own
4015      -- (shorter) EOL.
4016      fn.setline(1, { 'abc', 'de' })
4017      feed('gg$Q')
4018      feed('j$')
4019      feed('x')
4020      eq({ 'ab', 'd' }, get_lines())
4021      feed('p')
4022      eq({ 'abc', 'de' }, get_lines())
4023    end)
4024
4025    it('type=excmd CmdAtoms are emit-only, ":s" does not cascade', function()
4026      -- cmdline payloads are captured but never cascaded: only the primary's ":s" runs.
4027      cursors({ 'foo', 'foo' }, 'Qj')
4028      atoms_start()
4029      feed(':s/o/O/<CR>')
4030      eq({ 'foo', 'fOo' }, get_lines())
4031      local ev = atoms()[#atoms()]
4032      eq('excmd', ev.type)
4033      eq('s/o/O/', ev.text)
4034    end)
4035  end)
4036
4037  describe('@ (macro replay)', function()
4038    it('cascades at each cursor', function()
4039      fn.setline(1, { 'aaa', 'bbb', 'ccc' })
4040      feed('gg0qqxq') -- record "x"; line 1 becomes "aa"
4041      feed('jQ')
4042      feed('j0')
4043      feed('@q')
4044      eq({ 'aa', 'bb', 'cc' }, get_lines())
4045      -- "@@" repeats, still cascading.
4046      feed('@@')
4047      eq({ 'aa', 'b', 'c' }, get_lines())
4048      -- A macro with an insert session cascades too.
4049      clear_cursors()
4050      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaa', 'bbb', 'ccc' })
4051      feed('gg0qwA!<Esc>q') -- record "A!<Esc>"; line 1 becomes "aaa!"
4052      feed('jQ')
4053      feed('j0')
4054      feed('@w')
4055      eq({ 'aaa!', 'bbb!', 'ccc!' }, get_lines())
4056      -- A count applies at each cursor.
4057      clear_cursors()
4058      api.nvim_buf_set_lines(0, 0, -1, true, { 'aaaa', 'bbbb', 'cccc' })
4059      feed('gg0')
4060      feed('jQ')
4061      feed('j0')
4062      feed('2@q') -- the "x" macro, twice per cursor
4063      eq({ 'aaaa', 'bb', 'cc' }, get_lines())
4064    end)
4065
4066    it('from a cursorless buffer, cascades in the buffer it enters', function()
4067      -- Capture starts before the macro runs (buffer unknown). A macro typed where there are no
4068      -- cursors, cascades in the buffer it navigates into, like a mapping.
4069      command('set hidden')
4070      cursors({ 'aaa', 'bbb' }, 'jQk') -- buf1: primary on line 1, cursor on line 2.
4071      command('vsplit | enew') -- buf2: no cursors.
4072      fn.setreg('q', k('<C-w>px'))
4073      feed('@q')
4074      eq({ 'aa', 'bb' }, get_lines())
4075    end)
4076  end)
4077
4078  describe('CmdAtom', function()
4079    it('fires for a cascaded operation', function()
4080      cursors({ 'aaa', 'bbb' }, 'Q')
4081      atoms_start()
4082      feed('jx')
4083      -- Atom shape: see cmdatom_spec. With cursors: no extra atoms from the cascade replays.
4084      eq({ 'j', 'dl' }, atoms_tail(2))
4085      -- A yank cascades (per-cursor registers) but does not edit.
4086      feed('yy')
4087      eq(false, atoms()[#atoms()].changed)
4088    end)
4089
4090    it('non-edit operator (zfap) cascades; fold toggles (za) do not', function()
4091      fn.setline(1, { 'aa', 'aa', '', 'bb', 'bb', '' })
4092      feed('4G0Q')
4093      feed('gg0')
4094      atoms_start()
4095      feed('zfap')
4096      -- With cursors: the cascade adds no atoms. (Atom shape is covered in cmdatom_spec.)
4097      eq({ 'zfap' }, atoms_tail(1))
4098      -- The fold operator cascades: each cursor folds its own paragraph.
4099      eq({ { 1, 3 }, { 4, 6 } }, {
4100        { fn.foldclosed(1), fn.foldclosedend(1) },
4101        { fn.foldclosed(4), fn.foldclosedend(4) },
4102      })
4103      feed('za')
4104      eq({ 'za' }, atoms_tail(1))
4105      -- Fold toggles are view state: emitted, not cascaded.
4106      eq({ -1, 4 }, { fn.foldclosed(1), fn.foldclosed(4) })
4107    end)
4108
4109    it('records q= motions', function()
4110      cursors({ 'abcd', 'efgh' }, 'Qj')
4111      atoms_start()
4112      feed('q=')
4113      feed('l')
4114      feed('l')
4115      feed('q=')
4116      eq({ 'q=', 'l', 'l', 'q=' }, atoms_tail(4))
4117      eq('motion', atoms()[#atoms() - 1].type)
4118    end)
4119  end)
4120
4121  describe('programmatic edits', function()
4122    it('API edits do not cascade; they shift the cursors, which then track', function()
4123      -- Extmarks are authoritative: the cascade re-queries positions, so an interleaved API edit
4124      -- just shifts where the replays land.
4125      cursors({ 'aaa', 'bbb', 'ccc' })
4126      n.exec_lua("vim.api.nvim_buf_set_lines(0, 0, 0, true, { 'zzz' })")
4127      eq({ 'zzz', 'aaa', 'bbb', 'ccc' }, get_lines())
4128      feed('x')
4129      eq({ 'zzz', 'aa', 'bb', 'cc' }, get_lines())
4130    end)
4131
4132    it('TextChanged autocmd editing the buffer does not re-cascade', function()
4133      fn.setline(1, { 'top', 'aaa', 'bbb' })
4134      feed('2G0Q')
4135      feed('j')
4136      n.exec_lua([[
4137        _G.fired = 0
4138        vim.api.nvim_create_autocmd('TextChanged', {
4139          callback = function()
4140            _G.fired = _G.fired + 1
4141            if _G.fired == 1 then
4142              vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, { 'X' })
4143            end
4144          end,
4145        })
4146      ]])
4147      feed('x')
4148      n.poke_eventloop()
4149      eq({ 'Xtop', 'aa', 'bb' }, get_lines())
4150      -- Once for the whole cascade + once for the autocmd's own API edit.
4151      -- Not once per cursor, and the autocmd edit did not cascade.
4152      eq(2, n.exec_lua('return _G.fired'))
4153    end)
4154
4155    it('replacing the whole buffer via API does not crash the cascade', function()
4156      cursors({ 'aaa', 'bbb', 'ccc' })
4157      n.exec_lua("vim.api.nvim_buf_set_lines(0, 0, -1, true, { 'fresh', 'stuff' })")
4158      -- The cursor lines are gone: both marks collapse to the edit boundary (past the last line),
4159      -- where they merge/dedupe into one cursor; its replay clamps onto the last line.
4160      feed('x')
4161      eq({ 'fresh', 'uff' }, get_lines())
4162      eq(0, ncursors())
4163    end)
4164
4165    it(':normal! never cascades (programmatic input)', function()
4166      cursors({ 'aaa', 'bbb' }, 'Qj')
4167      atoms_start()
4168      command('normal! x') -- Programmatic, no cascade (primary only).
4169      eq({ 'aaa', 'bb' }, get_lines())
4170      command('normal! viwd') -- The entire Visual op is programmatic, not just selection.
4171      eq({ 'aaa', '' }, get_lines())
4172      eq({}, atoms())
4173      feed('u')
4174      feed('x') -- User input, cascades.
4175      eq({ 'aa', 'b' }, get_lines())
4176    end)
4177  end)
4178end)