robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
61.4 KiB1718 linesraw
1// Multicursor. Cursors are Context snapshots (mc_cursors) tracked by extmarks; user actions
2// (CmdAtoms) are replayed at each cursor at the "clock edge" (the cascade). See dev_arch.txt.
3
4#include <assert.h>
5#include <stdbool.h>
6#include <stddef.h>
7#include <stdint.h>
8#include <stdio.h>
9#include <string.h>
10
11#include "klib/kvec.h"
12#include "nvim/api/buffer.h"
13#include "nvim/api/extmark.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/helpers.h"
16#include "nvim/api/vim.h"
17#include "nvim/ascii_defs.h"
18#include "nvim/autocmd.h"
19#include "nvim/buffer.h"
20#include "nvim/buffer_defs.h"
21#include "nvim/charset.h"
22#include "nvim/clipboard.h"
23#include "nvim/context.h"
24#include "nvim/cursor.h"
25#include "nvim/decoration.h"
26#include "nvim/drawscreen.h"
27#include "nvim/errors.h"
28#include "nvim/eval/typval_defs.h"
29#include "nvim/ex_docmd.h"
30#include "nvim/extmark.h"
31#include "nvim/gettext_defs.h"
32#include "nvim/globals.h"
33#include "nvim/highlight_group.h"
34#include "nvim/input.h"
35#include "nvim/input_cmdatom.h"
36#include "nvim/insert.h"
37#include "nvim/insexpand.h"
38#include "nvim/keycodes.h"
39#include "nvim/log.h"
40#include "nvim/lua/executor.h"
41#include "nvim/macros_defs.h"
42#include "nvim/mark.h"
43#include "nvim/marktree.h"
44#include "nvim/mbyte.h"
45#include "nvim/mcursor.h"
46#include "nvim/memline.h"
47#include "nvim/memory.h"
48#include "nvim/message.h"
49#include "nvim/move.h"
50#include "nvim/normal.h"
51#include "nvim/ops.h"
52#include "nvim/option.h"
53#include "nvim/option_vars.h"
54#include "nvim/os/input.h"
55#include "nvim/os/time.h"
56#include "nvim/plines.h"
57#include "nvim/popupmenu.h"
58#include "nvim/pos_defs.h"
59#include "nvim/register.h"
60#include "nvim/register_defs.h"
61#include "nvim/search.h"
62#include "nvim/shada.h"
63#include "nvim/state.h"
64#include "nvim/state_defs.h"
65#include "nvim/strings.h"
66#include "nvim/types_defs.h"
67#include "nvim/ui.h"
68#include "nvim/undo.h"
69#include "nvim/vim_defs.h"
70
71/// Primary-cursor state saved across a replay sandbox.
72typedef struct {
73  Context primary;        ///< Editor state, registers.
74  uint32_t cursor_mark;   ///< Extmark tracking `primary.pos` across replay edits.
75  uint32_t topline_mark;  ///< Extmark tracking `view.vs_topline` across replay edits.
76  viewstate_T view;
77  // Replay isolation: the primary's in-flight input machinery.
78  save_state_T sst;       ///< mode, typeahead, reg_executing, …
79  RedoState redo;
80  VisualState visual;     ///< The active selection (globals.h:Visual), not the '<,'> region.
81} McSandbox;
82
83/// Primary cursor's insert-session, saved across nested edit() sessions during insert-cascade.
84typedef struct {
85  InsState ins;
86  varnumber_T last_changedtick;
87  varnumber_T last_changedtick_i;
88} McInsSaved;
89
90#include "mcursor.c.generated.h"
91
92/// Insert-cascade state.
93///
94/// PREVIEW/COMMIT model: the entry command ("A"/"cw") replays at each cursor on insert enter;
95/// while the user types, the primary's inserted text (`region` extmark) previews as literal text
96/// at each cursor; at session-end the previews are deleted and typed keys (batch) replay at each
97/// cursor (the COMMIT: abbreviations, 'textwidth', … re-execute per cursor).
98///
99/// XXX: Why text preview instead of LHS-replay? Two things cannot LHS-replay:
100/// 1. ins-completion
101/// 2. pending keys are not an append-only stream (compl/abbrevs rewrite them mid-session)
102///
103/// The boundary:
104/// - literal text is previewed
105/// - non-literal keys (mc_ins_keys_nonliteral) have per-cursor effects, so flush (early commit).
106static struct {
107  CmdOrigin origin;  ///< State at session start: the session's atoms diff against it.
108  kvec_t(uint32_t) regions;  ///< Per-cursor preview regions (`mc_session_ns`).
109  bool active;      ///< Current insert-session is cascading.
110  bool first;       ///< Entry-command not yet cascaded (no span pushed yet).
111  uint64_t frame;   ///< Root frame that started the insert-session.
112  size_t done_len;  ///< Bytes of the capture already consumed by replayed spans; tail is pending.
113  uint32_t region;  ///< Primary cursor's inserted text.
114  const char *vsel;  ///< Supplants the capture's "1v" (see `InsSession.vsel`).
115} mc_ins_span;
116
117/// Editor state when the mc session started, which every cursor replays against.
118static struct {
119  Timestamp time;  ///< When the session started (nanoseconds).
120  Context ctx;     ///< Registers, marks. Perf: per-cursor registers are "sparse".
121} mc_start = { .ctx = CONTEXT_INIT };
122
123/// Registers that can carry per-cursor values (skips the read-only/special ones).
124static const char MC_REGS[] = "abcdefghijklmnopqrstuvwxyz0123456789\"-";
125
126/// Buffer holding the fake Visual selections (0: none).
127static handle_T mc_vsel_buf;
128/// Primary cursor's current insert span deleted a line break (BS/CTRL-U at col 0).
129static bool mc_ins_joined;
130/// The mcursors, in creation order. Each is a Context snapshot: an extmark-tracked position
131/// plus editor state (registers) scoped to that cursor.
132static ContextVec mc_cursors = KV_INITIAL_VALUE;
133/// Replay is in progress: keys re-executing internally, hooks suppressed.
134static bool mc_replay = false;
135
136void mc_init(void)
137{
138  mc_ns();  // Eagerly create the namespace so mc_on_extmark_set() can assume it exists.
139}
140
141/// Namespace for tracking multicursor positions.
142static uint32_t mc_ns(void)
143{
144  static uint32_t ns = 0;
145  if (ns == 0) {
146    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.multicursor"));
147  }
148  return ns;
149}
150
151/// Namespace for the selection-end cursors. While they exist they are the display positions;
152/// "nvim.multicursor" holds the selection anchors.
153static uint32_t mc_vcur_ns(void)
154{
155  static uint32_t ns = 0;
156  if (ns == 0) {
157    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.multicursor.cursor"));
158  }
159  return ns;
160}
161
162/// Namespace for the fake Visual selections.
163static uint32_t mc_vsel_ns(void)
164{
165  static uint32_t ns = 0;
166  if (ns == 0) {
167    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.multicursor.visual"));
168  }
169  return ns;
170}
171
172/// Namespace for the previous session's cursor positions, snapshotted on clear ("gQ" restores).
173/// Mark id 1 is the primary-cursor position.
174static uint32_t mc_last_ns(void)
175{
176  static uint32_t ns = 0;
177  if (ns == 0) {
178    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.multicursor.last"));
179  }
180  return ns;
181}
182
183/// Namespace for session-internal marks (live text regions, transient primary-cursor tracker).
184static uint32_t mc_session_ns(void)
185{
186  static uint32_t ns = 0;
187  if (ns == 0) {
188    ns = (uint32_t)nvim_create_namespace(STATIC_CSTR_AS_STRING("nvim.multicursor._session"));
189  }
190  return ns;
191}
192
193/// Number of mcursors, excluding the primary cursor. 0: no multicursor session.
194size_t mc_count(void)
195{
196  return kv_size(mc_cursors);
197}
198
199/// Formats the multicursor 'showcmd' indicator ("=3× ") into `buf`.
200///
201/// @return  Length in bytes; 0 (buf="") if there are no cursors.
202size_t mc_showcmd(char *buf, size_t size)
203{
204  if (kv_size(mc_cursors) == 0) {
205    buf[0] = NUL;
206    return 0;
207  }
208  return (size_t)snprintf(buf, size, "%s%zu× ", mc_following() ? "=" : "", kv_size(mc_cursors));
209}
210
211/// True during a replay: re-executing keys internally, not new user input.
212bool mc_replaying(void)
213{
214  return mc_replay;
215}
216
217/// Creates or updates the (ui_watched) extmark tracking a multicursor position.
218/// Decor handled by mcursor.lua. TODO(justinmk): #41576
219static void mc_mark_upd(buf_T *buf, uint32_t *mark, pos_T pos)
220{
221  extmark_set_pos(buf, mc_ns(), mark, pos, true, false, true);
222}
223
224/// Session-internal variant of mc_mark_upd(): tracks a transient, undecorated position (primary
225/// cursor/topline across a cascade, the preview-apply cursor).
226static void mc_track_upd(buf_T *buf, uint32_t *mark, pos_T pos)
227{
228  extmark_set_pos(buf, mc_session_ns(), mark, pos, true, true, false);
229}
230
231/// Enters a replay sandbox, so keys fed (cascaded) per-cursor do not modify pending typeahead nor
232/// the primary-cursor state.
233///
234/// @param save_regs  Registers too. Perf: skipped for pure motions.
235static void mc_sandbox_enter(McSandbox *sb, bool save_regs)
236{
237  assert(!mc_replay);
238  mc_replay = true;  // Capture hooks will ignore keys fed during the sandbox.
239  sb->primary = (Context)CONTEXT_INIT;
240  // Change/Visual marks belong to the primary cursor's (already executed) operation.
241  // (jumplist/changelist are owned by the primary.)
242  ctx_save(&sb->primary, kCtxCursor | kCtxVisual | kCtxMarks | (save_regs ? kCtxRegs : 0));
243  sb->cursor_mark = 0;
244  mc_track_upd(curbuf, &sb->cursor_mark, sb->primary.pos);
245  save_viewstate(curwin, &sb->view);
246  sb->topline_mark = 0;
247  mc_track_upd(curbuf, &sb->topline_mark, (pos_T){ .lnum = sb->view.vs_topline });
248  sb->visual = Visual;
249  save_current_state(&sb->sst);  // hint: see call_user_func()
250  save_search_patterns();
251  save_redobuff(&sb->redo);
252}
253
254/// @see mc_sandbox_enter
255static void mc_sandbox_leave(McSandbox *sb)
256{
257  if (sb->primary.regs.data != NULL) {
258    ctx_load(&sb->primary, kCtxRegs, 0);
259  }
260  restore_redobuff(&sb->redo);
261  restore_search_patterns();
262  // Visual first: restore_current_state() updates the cursor shape, and check_cursor() below keeps
263  // a blockwise 'virtualedit' selection's coladd.
264  Visual = sb->visual;
265  restore_current_state(&sb->sst);
266  buf_T *buf = handle_get_buffer(sb->primary.buf);
267  pos_T topline = { 0 };
268  bool topline_valid = false;
269  if (buf != NULL) {
270    // Shifted by replay edits; an unshifted position keeps its coladd.
271    extmark_get_pos(buf, mc_session_ns(), sb->cursor_mark, &sb->primary.pos);
272    extmark_del_id(buf, mc_session_ns(), sb->cursor_mark);
273    topline_valid = extmark_get_pos(buf, mc_session_ns(), sb->topline_mark, &topline);
274    extmark_del_id(buf, mc_session_ns(), sb->topline_mark);
275  }
276  if (buf == curbuf) {
277    restore_viewstate(curwin, &sb->view);  // Before ctx_load, which decides curswant.
278    ctx_load(&sb->primary, kCtxCursor | kCtxVisual | kCtxMarks, 0);
279    check_cursor(curwin);
280    if (topline_valid) {
281      set_topline(curwin, MIN(topline.lnum, curbuf->b_ml.ml_line_count));
282      // Scroll (minimally) if an edit moved the primary cursor off-view.
283      update_topline(curwin);
284    }
285  }
286  ctx_free(&sb->primary);
287  mc_replay = false;
288}
289
290/// Cascade step: replays an atom at `cursoridx` and updates Context.
291static void mc_execute(size_t cursoridx, size_t atomidx)
292{
293  Context ctx = kv_A(mc_cursors, cursoridx);
294  CmdAtom atom = kv_A(g_atoms, atomidx);
295
296  if (handle_get_buffer(ctx.buf) != curbuf) {
297    // Cursors cascade only if their buffer is the current buffer.
298    return;
299  }
300
301  // Get the tracked position: edits by other cursors (etc) may have shifted it since last update.
302  if (ctx.mark != 0 && !extmark_get_pos(curbuf, mc_ns(), ctx.mark, &ctx.pos)) {
303    // The extmark was deleted, thus the cursor is deleted (swept by mc_cleanup()).
304    return;
305  }
306  if (ctx.visual.vi_start.lnum == 0 && strncmp(atom.keys, "gv", 2) == 0) {
307    // Replaying "gv", but Visual-reselect area is not defined for this cursor.
308    return;
309  }
310
311  // Perf: skip per-cursor registers-swap for motions, so "l" in follow-mode is fast.
312  const bool swap_regs = atom.type != kAMotion;
313  Timestamp regs_ts = 0;
314  if (swap_regs) {
315    if (reg_max_ts(false) >= mc_start.time) {
316      // Registers written globally are the previous cursor's; reset to baseline.
317      ctx_load(&mc_start.ctx, kCtxRegs, 0);
318    }
319    if (ctx.regs.data != NULL) {
320      ctx_load(&ctx, kCtxRegs, kCtxMergeReg);  // This cursor's own writes; merge w/ baseline.
321    }
322    regs_ts = reg_max_ts(false);
323  }
324
325  // Perf: motions never set cursor-local marks; skip save/restore.
326  // Except motions (`.) that read them, and LHS-replay.
327  const int mark_cmd = atom.spec.cmd == 'g' ? atom.spec.cmd2 : atom.spec.cmd;  // g`. like `.
328  const bool swap_marks = atom.type != kAMotion || atom.remap || mark_cmd == '\''
329                          || mark_cmd == '`';
330
331  ctx_load(&ctx, swap_marks ? kCtxVisual | kCtxMarks | kCtxCursor : kCtxCursor, 0);
332
333  // Edits by other cursors may have invalidated this cursor's position.
334  if (atom.type == kAInsertSpan) {
335    // The anchor may be one past EOL (the insertion point); edit() accepts that.
336    // Not check_cursor(): would clamp onto last char (a previous span may have set MODE_NORMAL).
337    check_pos(curbuf, &curwin->w_cursor);
338  } else {
339    check_cursor(curwin);
340  }
341
342  // The active selection is global (ctx_load() does not swap it per cursor).
343  if (atom.type == kAVisualSpan) {
344    Visual.active = false;  // A leading "v" would toggle it OFF.
345    Visual.select = false;
346  }
347
348  if (atom.type == kAInsertSpan) {
349    // exec_normal() clamps a past-EOL cursor via check_cursor() unless Insert-mode; a previous span
350    // replay may have left MODE_NORMAL, making later cursors insert one char left of their anchor.
351    State = MODE_INSERT;
352  }
353
354  // Replay the atom using wholesome, tasty feedkeys. Usually noremap ("nix"), but `atom.remap=true`
355  // means we must replay LHS (re-run the mapping at cursor, e.g. vim-surround "ds'").
356  const uint64_t beeps = did_beep;
357  const varnumber_T tick = buf_get_changedtick(curbuf);
358  nvim_feedkeys(cstr_as_string(atom.keys), cstr_as_string(atom.remap ? "ix" : "nix"), false);
359
360  if (atom.type == kAInsertSpan && mc_ins_span.first && did_beep != beeps
361      && buf_get_changedtick(curbuf) == tick) {
362    // XXX: Insert-entering cmd failed ("ct;" did not match ";"). Drop the cursor. #41960
363    extmark_del_id(curbuf, mc_ns(), ctx.mark);
364    return;
365  }
366
367  // emsg() may flush the remaining keys, eating a terminating (Visual) ESC/op; don't "leak" Visual.
368  if (Visual.active) {
369    if (atom.type == kAVisualSpan) {
370      // Persist this cursor's selection. The next span reselects it with "gv".
371      curbuf->b_visual = visualinfo();
372      curbuf->b_visual_mode_eval = Visual.mode;
373    }
374    Visual.active = false;
375    Visual.select = false;
376  }
377
378  const bool wrote_regs = swap_regs && reg_max_ts(false) != regs_ts;
379
380  if (cursoridx >= kv_size(mc_cursors)) {
381    // Cursors were removed during replay (e.g. gQ via autocmd); already freed.
382    return;
383  }
384  if (!extmark_get_pos(curbuf, mc_ns(), ctx.mark, &ctx.pos)) {
385    // Extmark was deleted during replay; mc_cleanup() will sweep the cursor state.
386    return;
387  }
388
389  if (wrote_regs) {
390    // Re-encode this cursor's registers, as a delta vs mc_start.ctx (for performance).
391    api_free_string(ctx.regs);
392    ctx.regs = shada_encode_regs(false, mc_start.time);
393  }
394  ctx_save(&ctx, swap_marks ? kCtxVisual | kCtxMarks | kCtxCursor : kCtxCursor);
395
396  if (atom.type == kAInsertSpan && curbuf->b_last_insert.mark.lnum > 0) {
397    // Anchor at the insertion point ('^ mark): this is where the primary cursor, still in Insert
398    // mode, displays its cursor, and where the next span continues inserting.
399    ctx.pos = curbuf->b_last_insert.mark;
400  }
401  // The extmark's decor redraws both the old and the new line (extmark_set()).
402  mc_mark_upd(curbuf, &ctx.mark, ctx.pos);
403  kv_A(mc_cursors, cursoridx) = ctx;  // Update the cursor info.
404}
405
406/// Runs the cascade: replays queued atoms (g_atoms) at every cursor, as one batch.
407static void mc_cascade(void)
408{
409  assert(kv_size(g_atoms) >= 1);
410  const CmdOrigin *origin = &kv_A(g_atoms, 0).origin;
411  // Primary-overlapping cursor (if any). Its replay is skipped, pos follows primary.
412  const uint32_t mcursor = origin->buf.br_buf == curbuf ? origin->mcursor : 0;
413  assert(kv_size(mc_cursors) > 0);
414  assert(!mc_replaying());
415
416  // Consume a pending interrupt: CTRL-C already did its job, it should not also abort the replays.
417  // Note: a new CTRL-C still aborts the cascade; consume BEFORE the dedupe below.
418  got_int = false;
419
420  // Merge overlapping cursors before replaying an edit. Not for pure-motion cascades ("q=" follow):
421  // an overlap with the primary is transient, that cursor is about to make the same move.
422  bool edits = false;
423  for (size_t i = 0; i < kv_size(g_atoms); i++) {
424    edits |= kv_A(g_atoms, i).type != kAMotion;
425  }
426  if (edits) {
427    mc_cleanup(true, NULL, 0);
428    if (kv_size(mc_cursors) == 0) {
429      atoms_free(&g_atoms);
430      return;
431    }
432  }
433
434  // Sync the primary-overlapping cursor (if any) to primary. Edit may have displaced it. #42081
435  pos_T mcursor_pos;
436  if (mcursor != 0 && extmark_get_pos(curbuf, mc_ns(), mcursor, &mcursor_pos)) {
437    uint32_t mark = mcursor;
438    mc_mark_upd(curbuf, &mark, curwin->w_cursor);
439  }
440
441  McSandbox sb;
442  mc_sandbox_enter(&sb, edits);
443
444  // Replay each atom at each cursor (a composite queues its subatoms, e.g. mapping "xx").
445  for (size_t ai = 0; ai < kv_size(g_atoms); ai++) {
446    CmdAtom *atom = &kv_A(g_atoms, ai);
447    if (atom->origin.buf.br_buf != NULL
448        && (!bufref_valid(&atom->origin.buf) || atom->origin.buf.br_buf != curbuf)) {
449      // Cascade only in the atom's origin buffer (a mapping may switch buffers).
450      // Assume current-buffer if `atom.origin` is missing.
451      continue;
452    }
453    for (size_t ci = 0; ci < kv_size(mc_cursors); ci++) {
454      // Replays consume `typebuf` only, so check for CTRL-C in OS/RPC input here.
455      line_breakcheck();
456      if (got_int) {
457        // Interrupted (CTRL-C), abort the cascade. Keep the partial edit; a "u" will undo it.
458        goto done;
459      }
460      if (mcursor == 0 || kv_A(mc_cursors, ci).mark != mcursor) {  // Skip cursor at primary.
461        mc_execute(ci, ai);
462      }
463    }
464  }
465done:
466  atoms_free(&g_atoms);
467  const handle_T bufnr = sb.primary.buf;  // mc_sandbox_leave() frees `sb.primary`.
468  mc_sandbox_leave(&sb);
469
470  mc_cleanup(true, &curwin->w_cursor, mcursor);
471  if (handle_get_buffer(bufnr) == curbuf && !curbuf->b_u_synced
472      && curbuf->b_u_newhead != NULL) {
473    // Store the primary's post-cascade position in the still-open undo block; redo restores it.
474    curbuf->b_u_newhead->uh_cursor_after = curwin->w_cursor;
475  }
476}
477
478/// The clock edge: cascades the current composite, and queued atoms (g_atoms), at every cursor.
479/// Called at the completion of a toplevel, typed command.
480///
481/// @param map_edit  The composite edited the buffer (or insert-cascaded).
482/// @param map_moved  The composite moved the cursor.
483/// @param follow  Follow-mode ("q=") when the queued motions ran.
484void mc_clock_edge(bool map_edit, bool map_moved, bool follow)
485{
486  if ((map_edit || (follow && map_moved && !Visual.active))
487      && !atom_composite_queued() && kv_size(g_atoms) == 0
488      && atom_composite_active() && mc_buf_has_cursors(curbuf)) {
489    // XXX: Fallback to LHS-replay if the mapping edited the buffer or moved the cursor (in
490    // follow-mode) via :norm/Lua/… (thus no atom was captured/queued).
491    atom_lhs_replay_queue();
492  }
493  if (mc_buf_has_cursors(curbuf) && kv_size(g_atoms) > 0) {
494    bool has_edit = map_edit;
495    for (size_t i = 0; !has_edit && i < kv_size(g_atoms); i++) {
496      has_edit = kv_A(g_atoms, i).type != kAMotion;
497    }
498    if (has_edit || follow
499        // Cascade if a mapping left a selection open ("nn x w<Cmd>norm! viw<CR>").
500        || Visual.active) {
501      mc_cascade();
502    } else {
503      // A pure-motion mapping without "q=" follow-motion: do not cascade
504      // (the atoms are still emitted as one composite CmdAtom).
505      atoms_free(&g_atoms);
506    }
507  }
508}
509
510/// Prunes dead cursors, ends empty sessions, restores marks. Optionally dedupes.
511///
512/// @param dedupe  Also removes overlapping cursors at cascade boundaries.
513/// @param primary  Primary cursor pos, for `dedupe`. NULL: dedupe cursors only among themselves.
514/// @param keep_mark  Primary-overlapping cursor (mark id). 0: none.
515static void mc_cleanup(bool dedupe, const pos_T *primary, uint32_t keep_mark)
516{
517  const bool had_cursors = kv_size(mc_cursors) > 0;
518  size_t n = 0;
519  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
520    Context *ctx = &kv_A(mc_cursors, i);
521    buf_T *buf = handle_get_buffer(ctx->buf);
522    if (buf == NULL
523        || (ctx->mark != 0 && !extmark_get_pos(buf, mc_ns(), ctx->mark, &ctx->pos))) {
524      // Buffer was freed, or the cursor's extmark was deleted.
525      ctx_free(ctx);
526      continue;
527    }
528    // Deduplicate/merge: cursor is a duplicate if it coincides with the primary (which always
529    // wins), or another cursor's mark is first at its position (first wins).
530    const bool dup = dedupe && ctx->mark != 0
531                     && ((curwin != NULL && buf == curbuf
532                          && primary != NULL && equalpos(ctx->pos, *primary)
533                          && ctx->mark != keep_mark)
534                         || mc_mark_at(buf, ctx->pos, 0) != ctx->mark);
535    if (dup) {
536      extmark_del_id(buf, mc_ns(), ctx->mark);
537      ctx_free(ctx);
538    } else {
539      kv_A(mc_cursors, n) = *ctx;
540      n++;
541    }
542  }
543  kv_size(mc_cursors) = n;
544  if (n == 0 && had_cursors) {
545    ctx_load(&mc_start.ctx, kCtxVisual, 0);  // Restore primary '< '> marks.
546    ctx_free(&mc_start.ctx);
547    mc_start.time = 0;
548    mc_lua_enable(false);
549  }
550}
551
552/// Called when insert-mode backspacing deletes a linebreak.
553void mc_ins_join(void)
554{
555  if (!mc_replaying()) {
556    mc_ins_joined = true;
557  }
558}
559
560/// Decides if a replay may delete a linebreak: only if the primary's own span did. A replayed
561/// BS/CTRL-U reaching col 0 where the primary's had more to delete must not join, it could collapse
562/// other cursors' lines into one.
563bool mc_ins_replay_can_join(void)
564{
565  return !mc_replaying() || mc_ins_joined;
566}
567
568/// Starts an insert-cascade. Call before entering insert mode from a normal-mode command.
569///
570/// @param cascade  The session qualifies for insert-cascading.
571/// @param origin   State at session start.
572/// @param vsel     See `InsSession.vsel`. Borrowed.
573void mc_ins_cascade_start(bool cascade, CmdOrigin origin, uint64_t root_frame, const char *vsel)
574{
575  if (mc_replaying()) {
576    // Nested replay session: don't clobber the primary session's state.
577    return;
578  }
579  mc_ins_span.vsel = vsel;
580  mc_ins_joined = false;
581  mc_ins_span.active = cascade && mc_buf_has_cursors(curbuf);
582  mc_ins_span.first = true;
583  mc_ins_span.frame = root_frame;
584  mc_ins_span.done_len = 0;
585  mc_ins_span.origin = origin;
586  mc_ins_span.region = 0;
587  mc_ins_regions_clear();
588
589  if (mc_ins_span.active) {
590    // Cover the line-range of all cursors with one undo-entry. #41822
591    // If the insert-session changes nothing, mc_ins_commit() drops it. #41883
592    //
593    // Undo entries apply in reverse save-order, so this (first) entry "wins", even though
594    // per-cursor newline-shifting edits may record conflicting undo entries. Same approach is used
595    // by Vim for linewise-op/range-command (see u_save in op_shift, ex_sort, …).
596    linenr_T lo = curwin->w_cursor.lnum;
597    linenr_T hi = curwin->w_cursor.lnum;
598    for (size_t i = 0; i < kv_size(mc_cursors); i++) {
599      pos_T pos;
600      if (mc_ctx_resolve(&kv_A(mc_cursors, i), &pos)) {
601        lo = MIN(lo, pos.lnum);
602        hi = MAX(hi, pos.lnum);
603      }
604    }
605    (void)u_save(lo - 1, hi + 1);  // Ignore FAIL result: only relevant if undo is unavailable.
606  }
607}
608
609/// Saves the primary's insert-session state: each span replay runs a nested edit().
610static McInsSaved mc_ins_save_state(void)
611{
612  McInsSaved saved;
613  saved.ins = Ins;
614  // The span replay starts clean, like a new session.
615  Ins.did_ai = false;
616  Ins.ai_col = 0;
617  Ins.end_comment_pending = NUL;
618  Ins.did_si = false;
619  Ins.can_si = false;
620  Ins.can_si_back = false;
621  // The nested sessions advance these even with autocmds blocked; unrestored, the primary
622  // session's pending TextChanged(I) would be swallowed (no tick delta left).
623  saved.last_changedtick = curbuf->b_last_changedtick;
624  saved.last_changedtick_i = curbuf->b_last_changedtick_i;
625  return saved;
626}
627
628static void mc_ins_restore_state(const McInsSaved *saved)
629{
630  Ins = saved->ins;
631  curbuf->b_last_changedtick = saved->last_changedtick;
632  curbuf->b_last_changedtick_i = saved->last_changedtick_i;
633}
634
635/// Pushes one span and immediately cascades it, plus any pending mapping atoms.
636/// Takes ownership of `keys` and `text`.
637static void mc_ins_span_push(char *keys, char *text)
638{
639  // If all cursors disappear mid-session (e.g. dedupe), emit but don't cascade.
640  bool cascade = mc_buf_has_cursors(curbuf);
641  atom_push_raw(cascade, &(CmdAtom){
642    .type = kAInsertSpan,
643    .keys = keys,
644    .text = text,
645    .origin = mc_ins_span.origin,
646  });
647  if (cascade) {
648    McInsSaved saved = mc_ins_save_state();
649    block_autocmds();  // The span replay would fire InsertEnter/InsertLeave on every key.
650    mc_cascade();  // Still `first` during the entry span.
651    unblock_autocmds();
652    mc_ins_restore_state(&saved);
653    mc_ins_joined = false;  // The next span decides whether its replays may join.
654  }
655  mc_ins_span.first = false;
656}
657
658/// Deletes the per-cursor preview-region marks.
659static void mc_ins_regions_clear(void)
660{
661  while (kv_size(mc_ins_span.regions) > 0) {
662    extmark_del_id(curbuf, mc_session_ns(), kv_pop(mc_ins_span.regions));
663  }
664}
665
666/// Resolves cursor's tracked position.
667///
668/// @return  False: the cursor is in another buffer, or its mark is gone.
669static bool mc_ctx_resolve(const Context *ctx, pos_T *pos)
670{
671  return handle_get_buffer(ctx->buf) == curbuf && ctx->mark != 0
672         && extmark_get_pos(curbuf, mc_ns(), ctx->mark, pos);
673}
674
675/// Places a paired session mark at `pos` (left-gravity anchor .. right-gravity end): text
676/// inserted at `pos` lands inside the pair.
677static void mc_region_mark_set(uint32_t *mark, pos_T pos)
678{
679  // no_undo: an undo-recorded extmark op mid-session breaks stop_arrow().
680  extmark_set(curbuf, mc_session_ns(), mark, (int)pos.lnum - 1, pos.col,
681              (int)pos.lnum - 1, pos.col, (DecorInline)DECOR_INLINE_INIT, 0,
682              false, true, true, false, NULL);
683}
684
685/// (Re)places the primary text-region mark at the cursor, and a per-cursor paired mark tracking
686/// each cursor's preview region. The preview text lands between the pair, exactly like the
687/// primary's `region` mark).
688static void mc_ins_preview_rebase(void)
689{
690  mc_region_mark_set(&mc_ins_span.region, curwin->w_cursor);
691  mc_ins_regions_clear();
692  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
693    Context *ctx = &kv_A(mc_cursors, i);
694    pos_T pos = { 0 };
695    uint32_t mark = 0;
696    if (mc_ctx_resolve(ctx, &pos) && ctx->mark != mc_ins_span.origin.mcursor) {
697      mc_region_mark_set(&mark, pos);
698      kv_push(mc_ins_span.regions, mark);
699    }
700  }
701}
702
703/// First live per-cursor preview region, or `start.id == 0` if none. A live region's buffer
704/// content is the applied preview text, and `start == end` means no preview is applied.
705/// All live regions hold the same preview, so any one represents the batch.
706static MTPair mc_ins_region_first(void)
707{
708  for (size_t i = 0; i < kv_size(mc_ins_span.regions); i++) {
709    MTPair p = extmark_from_id(curbuf, mc_session_ns(), kv_A(mc_ins_span.regions, i));
710    if (p.start.id != 0) {
711      return p;
712    }
713  }
714  return (MTPair){ 0 };
715}
716
717/// The buffer range (start/end positions) of region mark `p`.
718static void mc_region_range(MTPair p, pos_T *start, pos_T *end)
719{
720  *start = (pos_T){ .lnum = p.start.pos.row + 1, .col = p.start.pos.col };
721  *end = (pos_T){ .lnum = p.end_pos.row + 1, .col = p.end_pos.col };
722}
723
724/// Resolves a session extmark to its buffer range (start/end). Returns false if the mark is gone
725/// (deleted mid-session by a script?).
726static bool mc_region_mark_range(uint32_t mark, pos_T *start, pos_T *end)
727{
728  MTPair p = extmark_from_id(curbuf, mc_session_ns(), mark);
729  if (p.start.id == 0) {
730    return false;
731  }
732  mc_region_range(p, start, end);
733  return true;
734}
735
736/// Replaces buffer text (end-exclusive) with `text` (multiline), preserving marks and undo.
737static void mc_ins_preview_replace(pos_T start, pos_T end, const String *text)
738{
739  Arena arena = ARENA_EMPTY;
740  Error err = ERROR_INIT;
741  // Empty text (a delete) has NULL data; an empty array deletes the range.
742  Array lines = string_to_array(text->data != NULL ? *text : (String)STRING_INIT, false, &arena);
743  nvim_buf_set_text(LUA_INTERNAL_CALL, 0, start.lnum - 1, start.col,
744                    end.lnum - 1, end.col, lines, &arena, &err);
745  if (ERROR_SET(&err)) {
746    DLOG("preview replace failed: %s", err.msg);
747    api_clear_error(&err);
748  }
749  arena_mem_free(arena_finish(&arena));
750}
751
752/// Sets the preview at every cursor, replacing the previous one.
753static void mc_ins_preview_set(const String *new)
754{
755  // The primary's own insert session must not notice the preview edits.
756  McInsSaved saved = mc_ins_save_state();
757  // Track the primary cursor across the preview edits.
758  uint32_t primary = 0;
759  mc_track_upd(curbuf, &primary, curwin->w_cursor);
760  const int save_cmod_flags = cmdmod.cmod_flags;
761  cmdmod.cmod_flags |= CMOD_KEEPJUMPS;  // Not a change of the user: keeps '. and the changelist.
762  for (size_t i = 0; i < kv_size(mc_ins_span.regions); i++) {
763    pos_T rs, re;
764    // Re-resolve each region, previous loop iterations may have shifted it.
765    if (!mc_region_mark_range(kv_A(mc_ins_span.regions, i), &rs, &re)) {
766      continue;
767    }
768    // Cursor display mark (right-gravity) is pushed by the replacement to the new preview end.
769    mc_ins_preview_replace(rs, re, new);
770  }
771  cmdmod.cmod_flags = save_cmod_flags;
772  pos_T pos = curwin->w_cursor;
773  if (extmark_get_pos(curbuf, mc_session_ns(), primary, &pos)) {
774    curwin->w_cursor = pos;
775  }
776  extmark_del_id(curbuf, mc_session_ns(), primary);
777  mc_ins_restore_state(&saved);
778}
779
780/// True if `keys` has a non-literal key (kKeyInsFlush): a literal preview cannot represent it.
781static bool mc_ins_keys_nonliteral(const char *keys, size_t len)
782{
783  for (size_t i = 0; i < len; i++) {
784    int key = (uint8_t)keys[i];
785    if (key == K_SPECIAL && i + 2 < len) {
786      key = TO_SPECIAL((uint8_t)keys[i + 1], (uint8_t)keys[i + 2]);
787      i += 2;
788    }
789    if ((atom_key_class(key, NUL, NUL) & kKeyInsFlush) != 0) {
790      return true;
791    }
792  }
793  return false;
794}
795
796/// Capture restarted mid insert-session (stop_arrow(), after a non-captured cursor-move: mouse,
797/// <PageUp>, …). The previews stay; rebase and continue the insert-cascade.
798void mc_ins_cascade_restart(void)
799{
800  if (!mc_ins_span.active || mc_replaying() || !(State & MODE_INSERT)
801      || !mc_buf_has_cursors(curbuf) || kv_size(g_atoms) != 0) {
802    return;
803  }
804  String ins = redo_keys(NULL);
805  mc_ins_span.done_len = ins.size;
806  api_free_string(ins);
807  mc_ins_preview_rebase();
808}
809
810/// True during a span replay. The replay's synthetic <Esc> does not end the primary insert-session,
811/// so session-end cleanup must not run.
812bool mc_ins_replaying(void)
813{
814  return mc_replaying() && mc_ins_cascading();
815}
816
817/// True during insert-cascade.
818bool mc_ins_cascading(void)
819{
820  return mc_ins_span.active;
821}
822
823/// True if the insert-session started by `root_frame` cascaded a span.
824bool mc_ins_cascaded(uint64_t root_frame)
825{
826  return !mc_ins_span.first && mc_ins_span.frame == root_frame;
827}
828
829/// Cascades the insert-session. Called after each key in insert-mode. Updates the preview or
830/// flushes a span and cascades it.
831void mc_ins_cascade(void)
832{
833  if (!mc_ins_span.active || mc_replaying() || !(State & MODE_INSERT)
834      || !mc_buf_has_cursors(curbuf)) {
835    return;
836  }
837
838  pos_T start, end;  // The primary cursor's insert-span region.
839  String ins = redo_keys(NULL);
840  assert(ins.data != NULL || ins.size == 0);  // Coverity: NULL only when empty.
841
842  if (mc_ins_span.first) {
843    // Not with a pending autoindent ("o" + 'autoindent'): the entry span's replay ends in <Esc>,
844    // which would delete the indent.
845    if (!Ins.did_ai && ins.data != NULL && ins.size > 0) {
846      // Entry replay.
847      StringBuilder keys = KV_INITIAL_VALUE;
848      size_t skip = 0;
849      if (mc_ins_span.vsel != NULL) {
850        assert(ins.size >= 2 && strncmp(ins.data, "1v", 2) == 0);
851        kv_concat(keys, mc_ins_span.vsel);  // Supplant redo's "1v" fallback.
852        skip = 2;
853        mc_ins_span.vsel = NULL;
854      }
855      kv_concat_len(keys, ins.data + skip, ins.size - skip);
856      kv_push(keys, ESC);
857      kv_push(keys, NUL);
858      mc_ins_span.done_len = ins.size;
859      mc_ins_span_push(keys.items, NULL);
860      mc_ins_preview_rebase();
861    }
862  } else if (ins.data != NULL && ins.size < mc_ins_span.done_len) {
863    // Capture shrank without a restart signal, e.g. completion surgery rewrote the pending keys.
864    mc_ins_cascade_restart();
865  } else if (ins.size > mc_ins_span.done_len
866             && mc_ins_keys_nonliteral(ins.data + mc_ins_span.done_len,
867                                       ins.size - mc_ins_span.done_len)) {
868    // Non-literal keys pending (BS, CTRL-U, …): re-execute instead of previewing.
869    // Not during completion: edit() would raise E565. #41602
870    if (!ins_compl_active() && !pum_visible()) {
871      mc_ins_span_flush(&ins, false);
872    }
873  } else if (mc_region_mark_range(mc_ins_span.region, &start, &end)) {
874    // Live preview: mirror the primary's inserted text, without replay.
875    // Skip if unchanged, or if completion-preview could shift/overlap the primary's span.
876
877    String text = ml_region_text(curbuf, start, end);
878    bool update = true;
879    MTPair fp = mc_ins_region_first();
880    if (fp.start.id != 0) {
881      pos_T frs, fre;
882      mc_region_range(fp, &frs, &fre);
883      String cur = ml_region_text(curbuf, frs, fre);
884      // Preview-text changed?
885      update = cur.size != text.size
886               || (text.size > 0 && memcmp(cur.data, text.data, text.size) != 0);
887      api_free_string(cur);
888    }
889    if (update && (ins_compl_active() || pum_visible())) {
890      // Completion active. check all cursor-preview regions; if one would disturb completion, defer
891      // (skip) the entire preview update (all-or-none: mc_ins_region_first() assumes all previews
892      // have the same text).
893      //
894      // TODO(justinmk): if completion positions (e.g. `compl_col`) followed extmarks, we wouldn't
895      // have this problem, and live-preview could allow (non-conflicting) text-shifts. #41719
896      for (size_t i = 0; i < kv_size(mc_ins_span.regions); i++) {
897        pos_T rs, re;
898        if (!mc_region_mark_range(kv_A(mc_ins_span.regions, i), &rs, &re)) {
899          continue;
900        }
901        // A preview after `end` is safe. Otherwise, multiline old or new preview text could shift
902        // the primary's rows.
903        if (!lt(end, rs) && (re.lnum >= start.lnum || rs.lnum != re.lnum
904                             || start.lnum != end.lnum)) {
905          update = false;
906          break;
907        }
908      }
909    }
910    if (update) {
911      mc_ins_preview_set(&text);
912    }
913    api_free_string(text);
914  }
915  api_free_string(ins);
916}
917
918/// Flushes a span from the capture tail and cascades it: deletes the previews, then replays the
919/// pending keys ("i" + tail) at each cursor.
920///
921/// @param commit  Session-end flush: the tail already ends with <Esc>; attach the "."-register text
922///                and don't rebase. Else, mid-session flush: append <Esc> to end the replayed
923///                session, and rebase for the continuing preview.
924static void mc_ins_span_flush(const String *ins, bool commit)
925{
926  static const String empty = STRING_INIT;
927  MTPair fp = mc_ins_region_first();
928  if (fp.start.id != 0
929      && (fp.start.pos.row != fp.end_pos.row || fp.start.pos.col != fp.end_pos.col)) {
930    mc_ins_preview_set(&empty);  // Delete the preview at every cursor.
931  }
932  size_t dlen = ins->size - mc_ins_span.done_len;
933  StringBuilder keys = KV_INITIAL_VALUE;
934  kv_push(keys, 'i');
935  kv_concat_len(keys, ins->data + mc_ins_span.done_len, dlen);
936  if (!commit) {
937    kv_push(keys, ESC);
938  }
939  kv_push(keys, NUL);
940  char *text = commit && dlen > 1 ? xmemdupz(ins->data + mc_ins_span.done_len, dlen - 1) : NULL;
941  mc_ins_span.done_len = ins->size;
942  mc_ins_span_push(keys.items, text);
943  if (!commit) {
944    mc_ins_preview_rebase();
945  }
946}
947
948/// Reads `reg` (current global state), allocated, one trailing newline stripped; "" if empty.
949static char *mc_reg_read(int reg)
950{
951  char *s = get_reg_contents(reg, 0);
952  if (s == NULL) {
953    return xstrdup("");
954  }
955  size_t len = strlen(s);
956  if (len > 0 && s[len - 1] == NL) {
957    s[len - 1] = NUL;
958  }
959  return s;
960}
961
962/// qsort() comparator, document-order (lnum, then col).
963static int mc_ctx_pos_cmp(const void *a, const void *b)
964{
965  const Context *ca = *(Context *const *)a;
966  const Context *cb = *(Context *const *)b;
967  if (ca->pos.lnum != cb->pos.lnum) {
968    return ca->pos.lnum < cb->pos.lnum ? -1 : 1;
969  }
970  return ca->pos.col == cb->pos.col ? 0 : (ca->pos.col < cb->pos.col ? -1 : 1);
971}
972
973/// On exit, any registers the user yanked-to are newline-concatenated (document-order)
974/// and written to the primary-cursor registers.
975static void mc_reg_gather(void)
976{
977  if (kv_size(mc_cursors) == 0
978      // Exiting: windows were freed, shada was already written.
979      || exiting) {
980    return;
981  }
982  // Decide which registers were written this session, before updating (which bumps timestamps).
983  bool gather[sizeof(MC_REGS)] = { false };
984  bool any = false;
985  for (int i = 0; MC_REGS[i] != NUL; i++) {
986    const int r = (uint8_t)MC_REGS[i];
987    const int idx = r == '"' ? get_unname_register() : op_reg_index(r);
988    if (idx >= 0 && get_y_register(idx)->timestamp >= mc_start.time) {
989      gather[i] = any = true;
990    }
991  }
992  if (!any) {
993    return;
994  }
995
996  // Sort primary + cursors by position: the reg join below concatenates in document-order.
997  Context primary = { .pos = curwin->w_cursor, .regs = shada_encode_regs(false, mc_start.time) };
998  kvec_t(Context *) order = KV_INITIAL_VALUE;
999  kv_push(order, &primary);
1000  for (size_t c = 0; c < kv_size(mc_cursors); c++) {
1001    Context *ctx = &kv_A(mc_cursors, c);
1002    if (ctx->regs.size > 0 && handle_get_buffer(ctx->buf) == curbuf) {
1003      kv_push(order, ctx);
1004    }
1005  }
1006  if (kv_size(order) == 1) {  // No cursor registers to join (buffer disappeared?).
1007    kv_destroy(order);
1008    api_free_string(primary.regs);
1009    return;
1010  }
1011  qsort(order.items, kv_size(order), sizeof(Context *), mc_ctx_pos_cmp);
1012  Context save = CONTEXT_INIT;
1013  ctx_save(&save, kCtxRegs);  // Primary's registers, restored after the reads.
1014
1015  // Join each gathered register's non-empty values.
1016  kvec_t(char) joined[sizeof(MC_REGS)] = { { 0, 0, NULL } };
1017  for (size_t o = 0; o < kv_size(order); o++) {
1018    // Exact (not merged):
1019    ctx_load(kv_A(order, o), kCtxRegs, 0);
1020    for (int i = 0; MC_REGS[i] != NUL; i++) {
1021      if (!gather[i]) {
1022        continue;
1023      }
1024      char *text = mc_reg_read(MC_REGS[i]);
1025      if (*text != NUL) {
1026        if (kv_size(joined[i]) > 0) {
1027          kv_push(joined[i], NL);
1028        }
1029        kv_concat(joined[i], text);
1030      }
1031      xfree(text);
1032    }
1033  }
1034  kv_destroy(order);
1035  api_free_string(primary.regs);
1036  ctx_load(&save, kCtxRegs, 0);  // Restore the primary's registers.
1037  ctx_free(&save);
1038
1039  // Write each register back linewise. Skip an empty join (every value was empty).
1040  for (int i = 0; MC_REGS[i] != NUL; i++) {
1041    if (gather[i] && kv_size(joined[i]) > 0) {
1042      write_reg_contents_ex(MC_REGS[i], joined[i].items, (ssize_t)kv_size(joined[i]), false,
1043                            kMTLineWise, 0);
1044      if (MC_REGS[i] == '"') {
1045        // If implicit clipboard is enabled (clipboard=unnamed[plus]): write the joined result.
1046        set_clipboard(NUL, get_y_previous());
1047      }
1048    }
1049    kv_destroy(joined[i]);
1050  }
1051}
1052
1053/// Removes the fake Visual selections, clears their namespaces.
1054void mc_vsel_clear(void)
1055{
1056  buf_T *buf = handle_get_buffer(mc_vsel_buf);
1057  if (buf != NULL) {
1058    extmark_clear(buf, mc_vsel_ns(), 0, 0, MAXLNUM, MAXCOL);
1059    extmark_clear(buf, mc_vcur_ns(), 0, 0, MAXLNUM, MAXCOL);
1060  }
1061  mc_vsel_buf = 0;
1062}
1063
1064/// Stores a fake-selection range (end-exclusive) as an extmark.
1065static void mc_vsel_mark(linenr_T start_lnum, colnr_T start_col, linenr_T end_lnum, colnr_T end_col)
1066{
1067  DecorInline decor = DECOR_INLINE_INIT;
1068  decor.data.hl.hl_id = syn_check_group(S_LEN("MCursorVisual"));
1069  uint32_t mark = 0;
1070  extmark_set(curbuf, mc_vsel_ns(), &mark, (int)start_lnum - 1, start_col,
1071              (int)end_lnum - 1, end_col, decor, MT_FLAG_DECOR_HL,
1072              false, false, true, false, NULL);
1073  mc_vsel_buf = curbuf->handle;
1074}
1075
1076/// Displays a fake Visual selection (dry-runs the primary's selection keys) at each cursor.
1077/// XXX: The keys must not edit the buffer. #42005
1078void mc_vsel_refresh(void)
1079{
1080  mc_vsel_clear();
1081  String span = atom_visual_span();
1082  if (span.data == NULL || span.size == 0 || !mc_buf_has_cursors(curbuf)) {
1083    xfree(span.data);
1084    return;
1085  }
1086
1087  McSandbox sb;  // Save the primary-cursor state (selection included), like a cascade replay.
1088  mc_sandbox_enter(&sb, false);
1089  block_autocmds();
1090  emsg_silent++;
1091
1092  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
1093    Context *ctx = &kv_A(mc_cursors, i);
1094    if (!mc_ctx_resolve(ctx, &ctx->pos)) {
1095      continue;
1096    }
1097    ctx_load(ctx, kCtxCursor | kCtxVisual | kCtxMarks, 0);
1098    check_cursor(curwin);
1099    Visual.active = false;
1100    Visual.select = false;
1101    nvim_feedkeys(span, cstr_as_string("nix"), false);
1102    if (!Visual.active) {
1103      continue;
1104    }
1105    pos_T s = Visual.start;
1106    pos_T e = curwin->w_cursor;
1107    const MotionType type = Visual.mode == 'V' ? kMTLineWise
1108                                               : Visual.mode == Ctrl_V ? kMTBlockWise : kMTCharWise;
1109    bool inclusive = true;
1110    oparg_T oa;
1111    virtual_op = virtual_active(curwin);
1112    getregionpos_prep(&s, &e, type, *p_sel == 'e', 0, &inclusive, &oa);
1113    if (type == kMTLineWise) {
1114      mc_vsel_mark(s.lnum, 0, e.lnum, ml_get_len(e.lnum));
1115    } else if (type == kMTBlockWise) {
1116      if (curwin->w_curswant == MAXCOL) {
1117        oa.end_vcol = MAXCOL;  // "$": to the end of every line.
1118      }
1119      // One range per line.
1120      for (linenr_T lnum = s.lnum; lnum <= e.lnum; lnum++) {
1121        pos_T rs, re;
1122        getregionpos_line(lnum, s, e, inclusive, type, &oa, false, &rs, &re);  // 1-indexed cols.
1123        if (rs.col > 0) {  // Else no part of the block is on this line.
1124          mc_vsel_mark(lnum, rs.col - 1, lnum, re.col);
1125        }
1126      }
1127    } else {
1128      // Charwise: `e` is on the last byte of the last char, or on NUL (eol cell is selected).
1129      mc_vsel_mark(s.lnum, s.col, e.lnum, e.col + 1);
1130    }
1131    // Selection-end cursor; the anchor extmark stays put (the eventual replay position).
1132    uint32_t cmark = 0;
1133    extmark_set_pos(curbuf, mc_vcur_ns(), &cmark, curwin->w_cursor, false, true, true);
1134    mc_vsel_buf = curbuf->handle;
1135    Visual.active = false;
1136  }
1137
1138  emsg_silent--;
1139  unblock_autocmds();
1140  mc_sandbox_leave(&sb);
1141  xfree(span.data);
1142}
1143
1144/// Time-travel undo (g-/g+, :earlier/:later) crosses cascade boundaries, where per-cursor state is
1145/// meaningless: delete the buffer's cursors.
1146void mc_undo_time(void)
1147{
1148  atom_did_global_op();  // Undo must not cascade, even via a mapping.
1149  extmark_clear(curbuf, mc_ns(), 0, 0, MAXLNUM, MAXCOL);
1150}
1151
1152/// Insert-cascade "commit": run at insert-session end (atom_ins_end()). Replaces the previews with
1153/// a real replay. No-op if the session did not insert-cascade.
1154bool mc_ins_commit(void)
1155{
1156  bool active = mc_ins_span.active;
1157  bool ins_cascaded = active && !mc_ins_span.first;
1158  mc_ins_span.active = false;
1159  mc_ins_span.vsel = NULL;
1160
1161  if (ins_cascaded) {
1162    // COMMIT: replace the previews with a real replay: abbrev, 'textwidth', … re-exec per cursor.
1163    String ins = redo_keys(NULL);
1164    if (ins.data != NULL && ins.size > mc_ins_span.done_len
1165        // Not <Esc>-terminated, e.g. CTRL-C: the previews stay.
1166        && (uint8_t)ins.data[ins.size - 1] == ESC) {
1167      mc_ins_span_flush(&ins, true);
1168    }
1169    api_free_string(ins);
1170  }
1171
1172  // Session is over, drop its marks. (region=0: none, and mc_session_ns() must not be created by
1173  // a plain insert: namespace ids are user-observable.)
1174  if (mc_ins_span.region != 0) {
1175    extmark_del_id(curbuf, mc_session_ns(), mc_ins_span.region);
1176    mc_ins_span.region = 0;
1177  }
1178  mc_ins_regions_clear();
1179
1180  if (active && buf_get_changedtick(curbuf) == mc_ins_span.origin.tick) {
1181    // Nothing changed; drop the "umbrella" undo-entry added by mc_ins_cascade_start. #41883
1182    u_forget_unchanged(curbuf);
1183  }
1184
1185  if (!ins_cascaded) {
1186    return false;
1187  }
1188  // The commit edits belong to the session (already reported in TextChangedI). Absorb their ticks,
1189  // for TextChanged(I) parity, once per action.
1190  curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
1191  curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
1192  // The mcursors were anchored at their insertion points; now that the session ended,
1193  // shift them onto the last-inserted char, like <Esc> did for the primary cursor.
1194  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
1195    Context *ctx = &kv_A(mc_cursors, i);
1196    if (!mc_ctx_resolve(ctx, &ctx->pos)) {
1197      continue;
1198    }
1199    if (ctx->mark == mc_ins_span.origin.mcursor) {
1200      ctx->pos = curwin->w_cursor;  // ESC moved the primary; update primary-overlapping cursor.
1201    } else if (ctx->pos.col > 0) {
1202      dec(&ctx->pos);  // one char left, like <Esc> (but never crossing lines)
1203    }
1204    mc_mark_upd(curbuf, &ctx->mark, ctx->pos);
1205  }
1206  return true;
1207}
1208
1209/// Whether `buf` has mcursors. Hot: called on every key.
1210bool mc_buf_has_cursors(buf_T *buf)
1211{
1212  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
1213    if (kv_A(mc_cursors, i).buf == buf->handle) {
1214      return true;
1215    }
1216  }
1217  return false;
1218}
1219
1220/// Whether 'follow' mode is enabled.
1221bool mc_following(void)
1222{
1223  return curbuf->b_p_follow;
1224}
1225
1226/// Notifies mcursor.lua that the session started (first cursor) or ended (last cursor removed).
1227static void mc_lua_enable(bool enable)
1228{
1229  if (exiting) {
1230    return;
1231  }
1232  typval_T tv_args[] = {
1233    { .v_type = VAR_BOOL, .vval.v_bool = enable ? kBoolVarTrue : kBoolVarFalse },
1234    { .v_type = VAR_UNKNOWN },
1235  };
1236  nlua_call_typval("vim._core.mcursor", "enable", tv_args, NULL);
1237}
1238
1239/// The first cursor extmark (except `skip`) at `pos` in `buf`, or 0 if none.
1240uint32_t mc_mark_at(buf_T *buf, pos_T pos, uint32_t skip)
1241{
1242  if (kv_size(mc_cursors) == 0) {
1243    return 0;
1244  }
1245  MarkTreeIter itr[1] = { 0 };
1246  marktree_itr_get(buf->b_marktree, (int32_t)pos.lnum - 1, pos.col, itr);
1247  MTKey k;
1248  // Perf: bisect the marktree, instead of scanning mc_cursors (quadratic).
1249  while ((k = marktree_itr_current(itr)).id != 0
1250         && k.pos.row == pos.lnum - 1 && k.pos.col == pos.col) {
1251    if (k.ns == mc_ns() && !mt_end(k) && k.id != skip) {
1252      return k.id;
1253    }
1254    if (!marktree_itr_next(buf->b_marktree, itr)) {
1255      break;
1256    }
1257  }
1258  return 0;
1259}
1260
1261/// For "zq{motion}": runs motion `keys` at `pos`.
1262///
1263/// @return  Where the motion moved the cursor. lnum=0: it failed (beeped).
1264static pos_T mc_zq_step(const char *keys, pos_T pos)
1265{
1266  curwin->w_cursor = pos;
1267  curwin->w_set_curswant = false;  // Keep the primary's curswant.
1268  // Searches must not "hit BOTTOM" or wrap noisily, and failed motions must not beep.
1269  msg_silent++;
1270  emsg_silent++;
1271  const int save_cmod_flags = cmdmod.cmod_flags;
1272  cmdmod.cmod_flags |= CMOD_KEEPJUMPS;
1273  // Internal steps, not user actions. Not captured/cascaded, no autocmds.
1274  // Like ":normal": not fed the mapping's pending keys ("xmap I Q0i"), keeps `finish_op`.
1275  atom_suppress(true);
1276  block_autocmds();
1277  save_state_T sst;
1278  save_current_state(&sst);
1279  const uint64_t beeps = did_beep_silent;
1280  exec_normal_cmd((char *)keys, REMAP_NONE, true);
1281  const bool failed = did_beep_silent != beeps;
1282  restore_current_state(&sst);
1283  unblock_autocmds();
1284  atom_suppress(false);
1285  cmdmod.cmod_flags = save_cmod_flags;
1286  emsg_silent--;
1287  msg_silent--;
1288  return failed ? (pos_T){ 0 } : curwin->w_cursor;
1289}
1290
1291/// Visual area ('< '>) of the target at `step`: its search match, else the char (or line).
1292///
1293/// @param ctx  Saves the target into it (kCtxVisual), or NULL.
1294static visualinfo_T mc_zq_target(pos_T step, bool search, MotionType motion_type, Context *ctx)
1295{
1296  const visualinfo_T save = curbuf->b_visual;
1297  const int save_mode_eval = curbuf->b_visual_mode_eval;
1298  // Search: lnum=0 if "gn" finds no match.
1299  curbuf->b_visual = search ? (visualinfo_T){ 0 }
1300                            : (visualinfo_T){ .vi_start = step, .vi_end = step,
1301                                              .vi_curswant = step.col,
1302                                              .vi_mode = motion_type == kMTLineWise ? 'V' : 'v' };
1303  curbuf->b_visual_mode_eval = curbuf->b_visual.vi_mode;
1304  if (search) {
1305    mc_zq_step("gn\033", step);  // Selects the match at `step`; <Esc> stores it as '< '>.
1306  }
1307  if (ctx != NULL) {
1308    curwin->w_cursor = step;
1309    ctx_save(ctx, kCtxVisual);  // Tracks the marks by extmark.
1310  }
1311  const visualinfo_T target = curbuf->b_visual;
1312  curbuf->b_visual = save;
1313  curbuf->b_visual_mode_eval = save_mode_eval;
1314  return target;
1315}
1316
1317/// First step of motion `keys` in `bounds`: where it lands from just before the start ("w", "l"),
1318/// or on the start's line at its kept column ("j"), else where it lands from the start itself.
1319///
1320/// Given "  aa bb":
1321/// - "w" => "aa"
1322/// - "^" => "aa"
1323/// - "0" => col 0
1324///
1325/// @return  false: no step in `bounds`.
1326static bool mc_zq_first(const char *keys, bool search, MotionType motion_type, const pos_T *bounds,
1327                        pos_T *step)
1328{
1329  const pos_T start = bounds[0];
1330  pos_T before = start;
1331  const bool bof = dec(&before) == -1;  // Beginning of file.
1332  step->lnum = 0;
1333  if (!bof) {
1334    // Just before a start at column 0 is the line above: "l" (<Space>, <Right>) crosses the
1335    // linebreak to land on the start ('whichwrap').
1336    char *const save_ww = p_ww;
1337    p_ww = "s,l,>";  // 'whichwrap'
1338    const pos_T s = mc_zq_step(keys, before);
1339    p_ww = save_ww;
1340    if (ltoreq(start, s) && ltoreq(s, bounds[1])) {
1341      *step = s;
1342    }
1343  }
1344  curwin->w_cursor = start;
1345  check_cursor_col(curwin);  // Not past a short line's end.
1346  const pos_T from = curwin->w_cursor;
1347  const pos_T s = mc_zq_step(keys, from);
1348  if (s.lnum > from.lnum && !curwin->w_set_curswant) {
1349    // A motion keeping its column ("j", "2$") has a step on the start's line too, at that column.
1350    pos_T c = from;
1351    getvpos(curwin, &c, curwin->w_curswant);
1352    if (ltoreq(start, c) && ltoreq(c, bounds[1]) && (step->lnum == 0 || lt(c, *step))) {
1353      *step = c;
1354    }
1355  }
1356  if (step->lnum != 0) {
1357    return true;
1358  }
1359  const bool failed = s.lnum == 0;
1360  if (failed && motion_type != kMTLineWise && equalpos(from, start)) {
1361    return false;  // Fails from the start ("fx" without "x"): no step.
1362  }
1363  if (bof
1364      && (!search || equalpos(mc_zq_target(start, true, motion_type, NULL).vi_start, start))) {
1365    *step = start;  // Buffer start, nothing before it: a step (search: if a match starts there).
1366    return true;
1367  }
1368  if (failed || equalpos(s, from)) {
1369    *step = start;  // Stays: the start is a step ("0", "j" on the last line, a short line's end).
1370    return true;
1371  }
1372  *step = s;
1373  return ltoreq(start, s) && ltoreq(s, bounds[1]);
1374}
1375
1376/// Runs the "zq" steps: places a cursor at `first`, then at repeated `keys` motion, until `end`.
1377///
1378/// @param end  Last position for a step. `end.lnum == MAXLNUM`: the buffer, wrapping around once.
1379/// @return  Number of cursors placed.
1380static int mc_zq_run(const char *keys, bool search, MotionType motion_type, pos_T end, pos_T first)
1381{
1382  const bool wrap = end.lnum == MAXLNUM;
1383  bool wrapped = false;
1384  int placed = 0;
1385  pos_T step = first;
1386  while (!got_int) {
1387    mc_zq_target(step, search, motion_type, mc_add(curbuf, step));
1388    placed++;
1389    const pos_T prev = step;
1390    pos_T from = prev;
1391    step = mc_zq_step(keys, from);
1392    if (equalpos(step, from) && inc(&from) != -1) {
1393      // Retry from next char. The motion neither failed nor advanced ("ti" before an "i").
1394      step = mc_zq_step(keys, from);
1395    }
1396    if (step.lnum == 0 || equalpos(step, prev) || equalpos(step, from)) {
1397      break;  // Failed, or did not advance (after retry).
1398    }
1399    if (lt(step, prev)) {  // Wrapped around the end of the buffer ('wrapscan'), or backward.
1400      if (!wrap || wrapped) {
1401        break;
1402      }
1403      wrapped = true;
1404    }
1405    if (wrapped ? ltoreq(first, step) : lt(end, step)) {
1406      break;  // Back at the first step, or out of bounds.
1407    }
1408  }
1409  return placed;
1410}
1411
1412/// Starts "zq", before its motion. Ends Visual mode.
1413void mc_zq_start(cmdarg_T *cap)
1414{
1415  cap->oap->from_visual = Visual.active;
1416  cap->oap->motion_type = kMTUnknown;  // Set by a motion, else the cmd was non-motion ("zqx").
1417  if (Visual.active) {
1418    atom_visual_reset();  // "zq" consumes the selection, its keys ("Vj") must not cascade.
1419    end_visual_mode();
1420    check_cursor_col(curwin);  // Past-EOL ("vj" onto a shorter line) is Visual-only.
1421  }
1422}
1423
1424/// "zq{motion}": places a cursor at repeated {motion} ("zqw": each word). A search motion ("*",
1425/// "gn", "?pat<CR>", …) steps through its matches like "/<CR>".
1426///
1427/// Sets per-cursor Visual area ('< '>, "gv", mc_zq_target), so "zq*" + "gv" selects every match.
1428///
1429/// Forward motions: stops when the motion fails, does not advance, or passes the first step again
1430/// after wrapping ('wrapscan'). "{Visual}zq": steps begin at selection start and stop at its end.
1431/// Blockwise: each line of the block, from its left col (or end of a short line, like "v_b_A").
1432///
1433/// The motion decides the steps; not cancelled by failure at the cursor ("j" on the last line).
1434///
1435/// @param origin  Where the operator started: the cursor.
1436void mc_zq(oparg_T *oap, cmdarg_T *cap, pos_T origin)
1437{
1438  atom_did_global_op();
1439  if (mc_replaying() || oap->motion_type == kMTUnknown || cap->cmdchar == 'i'
1440      || cap->cmdchar == 'a' || cap->cmdchar == K_LUA || cap->cmdchar == K_COMMAND
1441      || cap->cmdchar == ':') {
1442    beep_flush();  // Not a motion, or not supported.
1443    curwin->w_cursor = origin;
1444    return;
1445  }
1446  pos_T primary = origin;
1447
1448  // "zq": from primary to end of buffer.
1449  // "{Visual}zq": the selection ('< '>). Linewise, blockwise: whole lines (blockwise: `vcols`).
1450  visualinfo_T v = curbuf->b_visual;
1451  pos_T bounds[2] = { primary, { .lnum = MAXLNUM } };
1452  if (oap->from_visual) {
1453    bounds[0] = mark_get_visual(curbuf, '<')->mark;
1454    bounds[1] = mark_get_visual(curbuf, '>')->mark;
1455  }
1456
1457  const bool lines = oap->motion_type == kMTLineWise;  // Linewise motion ("j") steps by lines.
1458  if (lines) {
1459    bounds[0].col = 0;
1460    bounds[1].col = MAXCOL;
1461  }
1462  colnr_T vcols[2] = { 0, MAXCOL };
1463  const bool blockwise = oap->from_visual && v.vi_mode == Ctrl_V && !lines;
1464  if (blockwise) {
1465    getvcols(curwin, &v.vi_start, &v.vi_end, &vcols[0], &vcols[1], 0);
1466    vcols[1] = v.vi_curswant == MAXCOL ? MAXCOL : vcols[1];  // "$": to the end of every line.
1467  }
1468  // The steps use the primary's column, not the column they start from.
1469  curwin->w_cursor = primary;
1470  update_curswant();
1471  viewstate_T view;
1472  save_viewstate(curwin, &view);
1473  save_search_patterns();
1474
1475  const bool search = (cap->cmdchar != NUL && strchr("*#/?nN", cap->cmdchar) != NULL)
1476                      || (cap->cmdchar == 'g' && cap->nchar != NUL
1477                          && strchr("*#nN", cap->nchar) != NULL);
1478  int placed = 0;
1479  pos_T first = { 0 };
1480  CmdSpec spec = atom_cmd_spec(cap);
1481  spec.regname = 0;  // The operator's ("\"azq").
1482  // The search motion already set the pattern. Each step is "/<CR>".
1483  String keys = search ? cstr_to_string("/\n") : redo_keys(&spec);
1484  if (!oap->from_visual && search) {
1485    first = mc_zq_target(primary, true, oap->motion_type, NULL).vi_start;  // Match at/after it.
1486    if (first.lnum != 0) {
1487      placed = mc_zq_run(keys.data, search, oap->motion_type, bounds[1], first);
1488    }
1489  } else if (!blockwise) {
1490    if (mc_zq_first(keys.data, search, oap->motion_type, bounds, &first)) {
1491      placed = mc_zq_run(keys.data, search, oap->motion_type, bounds[1], first);
1492    }
1493  } else {
1494    // Blockwise: each line's part of the block is its own charwise selection.
1495    for (linenr_T lnum = bounds[0].lnum; lnum <= bounds[1].lnum; lnum++) {
1496      pos_T line[2] = { { .lnum = lnum }, { .lnum = lnum, .col = MAXCOL } };
1497      if (getvpos(curwin, &line[0], vcols[0]) == FAIL) {
1498        line[0].col = ml_get_len(lnum);  // Short line: its end, like "v_b_A".
1499      } else if (vcols[1] != MAXCOL) {
1500        getvpos(curwin, &line[1], vcols[1]);
1501      }
1502      pos_T step;
1503      if (mc_zq_first(keys.data, search, oap->motion_type, line, &step)) {
1504        first = first.lnum == 0 ? step : first;
1505        placed += mc_zq_run(keys.data, search, oap->motion_type, line[1], step);
1506      }
1507    }
1508  }
1509
1510  api_free_string(keys);
1511  restore_search_patterns();
1512  restore_viewstate(curwin, &view);
1513
1514  if (placed > 0) {
1515    if (mc_mark_at(curbuf, primary, 0) == 0) {
1516      primary = first;  // Not on a step; move the primary to the first placement.
1517      curwin->w_set_curswant = true;
1518    }
1519    curbuf->b_visual = mc_zq_target(primary, search, oap->motion_type, NULL);  // Its own target.
1520    curbuf->b_visual_mode_eval = curbuf->b_visual.vi_mode;
1521    // Do ":nohlsearch" so cursors are visible. #41629
1522    set_no_hlsearch(true);
1523    redraw_all_later(UPD_SOME_VALID);
1524  }
1525  curwin->w_cursor = primary;
1526}
1527
1528/// "g CTRL-A": insert an ascending number at each cursor.
1529void mc_counter(long count1)
1530{
1531  atom_did_global_op();
1532  typval_T tv_args[] = {
1533    { .v_type = VAR_NUMBER, .vval.v_number = count1 },
1534    { .v_type = VAR_UNKNOWN },
1535  };
1536  nlua_call_typval("vim._core.mcursor", "number", tv_args, NULL);
1537}
1538
1539/// Sets 'follow' mode ("q="), which applies to the executing CmdAtom.
1540///
1541/// @param on  kNone: toggle. kTrue/kFalse: force it ("1q=" on, "2q=" off).
1542void mc_follow_set(TriState on)
1543{
1544  if (mc_replaying()) {
1545    return;  // Follow-mode is session state, not per-cursor.
1546  }
1547  bool follow = on == kNone ? !curbuf->b_p_follow : on == kTrue;
1548  if (curbuf->b_p_follow != follow) {
1549    set_option_value_give_err(kOptFollow, BOOLEAN_OBJ(follow), OPT_LOCAL);
1550  }
1551}
1552
1553/// Places an mcursor, or removes the cursor already at the given position.
1554///
1555/// @param on  kNone: toggle. kTrue: add only ("1Q"). kFalse: remove only ("2Q").
1556void mc_toggle(buf_T *buf, pos_T pos, bool end_follow, TriState on)
1557{
1558  if (mc_replaying()) {
1559    // Replayed input ("Q" in a mapping's atom) must not manage cursors; see mc_add().
1560    return;
1561  }
1562  if (end_follow) {
1563    mc_follow_set(kFalse);
1564  }
1565  uint32_t mark = mc_mark_at(buf, pos, 0);
1566  if (mark != 0 && on != kTrue) {
1567    extmark_del_id(buf, mc_ns(), mark);
1568    mc_cleanup(false, NULL, 0);
1569  } else if (mark == 0 && on != kFalse) {
1570    mc_add(buf, pos);
1571  }
1572}
1573
1574/// Places an mcursor at position `pos` in `buf`.
1575///
1576/// @return  The (new or existing) cursor at `pos`. NULL if not placed (cascade).
1577Context *mc_add(buf_T *buf, pos_T pos)
1578{
1579  const uint32_t existing = mc_mark_at(buf, pos, 0);
1580  for (size_t i = 0; existing != 0 && i < kv_size(mc_cursors); i++) {
1581    if (kv_A(mc_cursors, i).buf == buf->handle && kv_A(mc_cursors, i).mark == existing) {
1582      return &kv_A(mc_cursors, i);
1583    }
1584  }
1585  const size_t count = kv_size(mc_cursors);
1586  uint32_t mark = 0;
1587  mc_mark_upd(buf, &mark, pos);
1588  return kv_size(mc_cursors) > count ? &kv_last(mc_cursors) : NULL;
1589}
1590
1591/// Called when an extmark is set. Extmarks added to the "nvim.multicursor" namespace are cursors.
1592///
1593/// Deletes the new extmark if a cursor already exists there, or during cascade (not supported).
1594void mc_on_extmark_set(buf_T *buf, uint32_t ns_id, uint32_t id, pos_T pos)
1595{
1596  if (ns_id != mc_ns()) {
1597    return;
1598  }
1599  if (mc_replaying()) {
1600    extmark_del_id(buf, ns_id, id);  // Can't add cursors while the cascade iterates them.
1601    return;
1602  }
1603  if (mc_mark_at(buf, pos, id) != 0) {
1604    extmark_del_id(buf, ns_id, id);  // Duplicate cursor (e.g. repeated "1Q").
1605    return;
1606  }
1607  mc_mark_upd(buf, &id, pos);  // Ensure our extmark flags.
1608  // Discard the pending Visual atom, else it would cascade to the cursor created below.
1609  atom_visual_reset();
1610  if (kv_size(mc_cursors) == 0) {
1611    // Session start: snapshot primary regs, '< '>; hand the display to mcursor.lua.
1612    mc_start.time = (Timestamp)os_realtime();
1613    ctx_save(&mc_start.ctx, kCtxRegs | kCtxVisual);
1614    mc_lua_enable(true);
1615  }
1616  kv_push(mc_cursors, (Context)CONTEXT_INIT);
1617  Context *ctx = &kv_last(mc_cursors);
1618  ctx->buf = buf->handle;
1619  ctx->pos = pos;
1620  ctx->mark = id;
1621}
1622
1623/// A reload/wipe invalidated the tracked positions: deletes the mcursors + "gQ" snapshot.
1624void mc_buf_clear(buf_T *buf)
1625{
1626  if (mc_replaying()) {
1627    return;
1628  }
1629  extmark_clear(buf, mc_ns(), 0, 0, MAXLNUM, MAXCOL);
1630  extmark_clear(buf, mc_last_ns(), 0, 0, MAXLNUM, MAXCOL);
1631}
1632
1633/// Called when a buffer's extmarks were freed. Deleting a cursor's extmark deletes the cursor.
1634void mc_buf_free(buf_T *buf)
1635{
1636  if (mc_replaying()) {
1637    // Can't mutate (mc_cleanup) mc_cursors during cascade.
1638    return;
1639  }
1640  mc_cleanup(false, NULL, 0);
1641  if (mc_vsel_buf == buf->handle) {
1642    // The selection extmarks died with the buffer too.
1643    mc_vsel_buf = 0;
1644  }
1645}
1646
1647/// Called before extmark_clear() deletes a namespace's extmarks. Refreshes the cursor-position
1648/// cache, so mc_ns_cleared()'s "gQ" snapshot sees positions shifted by non-cascading edits.
1649void mc_ns_clearing(buf_T *buf, uint32_t ns_id)
1650{
1651  if ((ns_id != mc_ns() && ns_id != 0) || mc_replaying()) {
1652    return;
1653  }
1654  for (size_t i = 0; i < kv_size(mc_cursors); i++) {
1655    Context *ctx = &kv_A(mc_cursors, i);
1656    if (ctx->buf == buf->handle && ctx->mark != 0) {
1657      extmark_get_pos(buf, mc_ns(), ctx->mark, &ctx->pos);
1658    }
1659  }
1660}
1661
1662/// Deleting the "nvim.multicursor" namespace deletes its cursors. Saves snapshot for "gQ" (and
1663/// reserves extmark-id 1 for the primary cursor).
1664void mc_ns_cleared(buf_T *buf, uint32_t ns_id)
1665{
1666  if ((ns_id != mc_ns() && ns_id != 0) || mc_replaying() || !mc_buf_has_cursors(buf)) {
1667    return;
1668  }
1669
1670  // End the session only if no cursors are alive.
1671  bool others = false;
1672  for (size_t i = 0; i < kv_size(mc_cursors) && !others; i++) {
1673    Context *ctx = &kv_A(mc_cursors, i);
1674    pos_T pos;
1675    others = ctx->buf != buf->handle
1676             || (ctx->mark != 0 && extmark_get_pos(buf, mc_ns(), ctx->mark, &pos));
1677  }
1678  if (!others) {
1679    // "DWIM yank": before the multicursor session ends, join per-cursor yanks to primary.
1680    mc_reg_gather();
1681  }
1682
1683  // Snapshot the positions into "nvim.multicursor.last" ("gQ").
1684  if (!exiting) {
1685    extmark_clear(buf, mc_last_ns(), 0, 0, MAXLNUM, MAXCOL);
1686    if (curbuf == buf) {
1687      uint32_t primary = 1;  // Reserve id 1 for the primary cursor.
1688      extmark_set_pos(buf, mc_last_ns(), &primary, curwin->w_cursor, true, false, false);
1689    }
1690    for (size_t i = 0; i < kv_size(mc_cursors); i++) {
1691      Context *ctx = &kv_A(mc_cursors, i);
1692      if (ctx->buf != buf->handle) {
1693        continue;
1694      }
1695      uint32_t mark = 0;
1696      extmark_set_pos(buf, mc_last_ns(), &mark, ctx->pos, true, false, false);
1697    }
1698  }
1699  mc_cleanup(false, NULL, 0);
1700  if (kv_size(mc_cursors) == 0) {
1701    // Session ended; drop the pending cascade.
1702    atoms_free(&g_atoms);
1703  }
1704}
1705
1706#ifdef EXITFREE
1707/// Frees all multicursor state on exit.
1708void mc_free_all(void)
1709{
1710  while (kv_size(mc_cursors) > 0) {
1711    Context ctx = kv_pop(mc_cursors);
1712    ctx_free(&ctx);
1713  }
1714  kv_destroy(mc_cursors);
1715  kv_destroy(mc_ins_span.regions);
1716  ctx_free(&mc_start.ctx);
1717}
1718#endif