robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
61.8 KiB1682 linesraw
1// input_cmdatom.c: The input engine "policy layer" (input.c. is the "bytes layer").
2//
3// Decides _structure_ of user input and captures it as a "CmdAtom": a repeatable unit (edit,
4// motion, visual sequence, insert session, mapping), a dot-repeat-style keysequence plus structured
5// fields (CmdSpec).
6//
7// Every "user action" is an atom (emits CmdAtom event), but not every atom is "replayable".
8// - Replayable (cascade, dot-repeat) requires the full command grammar.
9// - No atoms for: mouse drag/release (TODO(justinmk)?), terminal-mode input, aborted operations.
10
11#include <assert.h>
12#include <stdint.h>
13#include <string.h>
14
15#include "klib/kvec.h"
16#include "nvim/api/private/defs.h"
17#include "nvim/api/private/helpers.h"
18#include "nvim/ascii_defs.h"
19#include "nvim/autocmd.h"
20#include "nvim/buffer.h"
21#include "nvim/eval/typval_defs.h"
22#include "nvim/eval/vars.h"
23#include "nvim/ex_docmd.h"
24#include "nvim/globals.h"
25#include "nvim/input.h"
26#include "nvim/input_cmdatom.h"
27#include "nvim/insert.h"
28#include "nvim/keycodes.h"
29#include "nvim/log.h"
30#include "nvim/macros_defs.h"
31#include "nvim/mapping.h"
32#include "nvim/mbyte.h"
33#include "nvim/mcursor.h"
34#include "nvim/memory.h"
35#include "nvim/normal.h"
36#include "nvim/normal_defs.h"
37#include "nvim/ops.h"
38#include "nvim/option_vars.h"
39#include "nvim/register.h"
40#include "nvim/state.h"
41#include "nvim/state_defs.h"
42#include "nvim/strings.h"
43#include "nvim/vim_defs.h"
44#include "nvim/window.h"
45
46#include "input_cmdatom.c.generated.h"
47
48CmdAtomVec g_atoms = KV_INITIAL_VALUE;
49/// Capture clock: ticks on any kind of capture (atom push, Visual subatom). Used to answer "was
50/// anything captured during this command (including its nested frames)?".
51static uint64_t atom_captures = 0;
52/// "Cursor-global" op (undo, "g CTRL-A"), possibly in a nested frame. Command must not cascade.
53static uint64_t global_ops = 0;
54/// Suppresses atom pushes.
55static bool atom_suppressed = false;
56/// Mapping edited the buffer, or its insert-session cascaded: cascades as one unit, incl. motions.
57static bool map_edit = false;
58/// Incremented per command frame (CmdFrame.id).
59static uint64_t frame_id = 0;
60/// The executing command's frame; its `parent` chain spans nested `normal_execute()`.
61static CmdFrame *cur_frame = NULL;
62
63/// Accumulates one CmdAtom across its CmdFrames. May span multiple toplevel cmds. Always collects,
64/// because a mapping may itself create consumers ("xmap I Q0i" => creates a mcursor => which
65/// listens to atoms).
66///
67/// See `vatom` for Visual composite (different lifetime).
68///
69/// Also used by undo, to restore cursor position.
70static struct {
71  bool active;        ///< Collecting subatoms. If false but `lhs` is set, collecting was deferred.
72  bool open;          ///< User action is in progress: set by its first toplevel cmd (frame).
73  CmdOrigin origin;   ///< State at the atom's start.
74  TriState follow;    ///< `CmdFrame.follow` at the atom's first motion (`kNone`: none yet).
75  CmdAtomVec atoms;   ///< Subatoms of the mapping/macro.
76  char lhs[MAXMAPLEN + 4];  ///< Label: mapping LHS, macro "@x", or :omap's op+LHS. "": none.
77  bool queued;        ///< Subatom queued for cascade (`g_atoms`, or Visual), global op (undo), or
78                      ///< jump. No LHS-replay needed.
79  bool lossy;         ///< Detected partial capture: `keys` cannot replay it, `lhs` can.
80                      ///< When: incomplete insert, payload with no capturing atom.
81  bool macro;         ///< Macro execution: captured as an "@x"-labeled atom.
82  uint64_t frame;     ///< CmdFrame already executing when a lookahead resolved this mapping
83                      ///< ("f(" + mapped key in one batch). 0: none.
84} composite;
85
86/// State of a Visual session atom.
87typedef enum {
88  kVatomNone = 0,   ///< No pending Visual atom.
89
90  // Kind:
91  kVatomTyped = 1,  ///< User input (typed, or mapping/macro): emit/cascade.
92  kVatomFed = 2,    ///< Non-user input (programmatic). See `atom_visual_typed`.
93
94  kVatomVoid = 4,   ///< Not replayable: tainted/poisoned (by mouse, Select, …). But may emit CmdAtom.
95} VatomState;
96
97/// Accumulating Visual session atom: the full Visual keysequence (selection keys + operator).
98///
99/// NOTE: Modeled separately from `composite` bc they may overlap (not clean nesting): a mapping can
100/// open before "v" and end mid-selection ("nmap X vjj" followed by "d").
101///
102/// Visual session may overlap CmdFrames: ":norm!" children are not captured, the cmd itself is the
103/// subatom (re-executes per cursor). #41956
104/// - "<Cmd>normal! e<CR>" during a session => subatom "<Cmd>normal! e<CR>", not "e".
105/// - ":norm! viw" typed at cmdline => subatom ":norm! viw<CR>"; enclosing frame resolves a session
106///   its children opened, ended (":norm! d"), or moved by API. #41705
107static struct {
108  CmdAtomVec atoms;  ///< Accumulated subatoms. A void session collects them as the `lhs` label.
109  VatomState state;
110  CmdOrigin origin;  ///< State at session start (before the "v").
111  uint64_t frame;    ///< Frame that pushed the last subatom. An enclosing frame must not recapture
112                     ///< its keys, restart its session, nor void it (`frame` > its own id).
113  size_t done;       ///< Subatoms already-cascaded as spans; `atoms[done..]` is the pending tail.
114} vatom;
115
116/// Interactively typed keys of the executing command. Collected during a composite (its `lhs`
117/// suffix) and eval-read (the frame's payload slice, see atom_payload_start()).
118static struct {
119  kvec_t(uint8_t) keys;
120  size_t map_start;  ///< This composite's slice: keys[map_start..kv_size(keys)), its lhs suffix.
121} typed;
122
123static const char *const type_names[] = {
124  [kAComp] = "mapping",
125  [kAExcmd] = "excmd",
126  [kAInsertSpan] = "insert",  // Span displays as "insert" (as composite's `atoms`).
127  [kAInsert] = "insert",
128  [kAJump] = "jump",
129  [kAMotion] = "motion",
130  [kAMouse] = "mouse",
131  [kANormal] = "normal",
132  [kAOperator] = "operator",
133  [kAScroll] = "scroll",
134  [kAVisualSpan] = "visual",  // Span displays as "visual" (as composite's `atoms`).
135  [kAVisual] = "visual",
136};
137
138/// The toplevel command frame (`cur_frame` root).
139static CmdFrame *root_frame(void)
140{
141  assert(cur_frame != NULL);
142  CmdFrame *frame = cur_frame;
143  while (frame->parent != NULL) {
144    frame = frame->parent;
145  }
146  return frame;
147}
148
149/// True while a command's :norm/feedkeys("x") child executes. Its subatoms are not captured; the
150/// cmd is captured as itself, so a Visual session is kept pending until that frame resolves it.
151static bool is_child_frame(void)
152{
153  if (cur_frame == NULL || cur_frame->parent == NULL) {
154    return false;
155  }
156  const CmdFrame *root = root_frame();
157  // Excludes stuffed keys ("." payload, "x" => "dl"), they are already resolved.
158  const bool fed = cur_frame->ex_normal > root->ex_normal;
159  // Excludes keys fed from K_EVENT (RPC/timer): no enclosing cmd.
160  return fed && !(root->keyclass & kKeySynthetic);
161}
162
163/// Frees a CmdAtom's allocated members.
164void atom_free(CmdAtom *atom)
165{
166  XFREE_CLEAR(atom->keys);
167  XFREE_CLEAR(atom->text);
168  XFREE_CLEAR(atom->lhs);
169  atoms_free(&atom->atoms);
170  kv_destroy(atom->atoms);
171}
172
173/// Frees and removes all atoms in `v` (keeps the vector's storage).
174void atoms_free(CmdAtomVec *v)
175{
176  while (kv_size(*v) > 0) {
177    CmdAtom atom = kv_pop(*v);
178    atom_free(&atom);
179  }
180}
181
182#ifdef EXITFREE
183void atom_free_all(void)
184{
185  atoms_free(&g_atoms);
186  kv_destroy(g_atoms);
187  // A mid-command exit (e.g. ":qa!" from an option-expr) leaves live frames with staged atoms.
188  for (CmdFrame *frame = cur_frame; frame != NULL; frame = frame->parent) {
189    atom_free(&frame->staged);
190    XFREE_CLEAR(frame->cmdline);
191  }
192  atom_composite_abort();
193  kv_destroy(composite.atoms);
194  kv_destroy(typed.keys);
195  atoms_free(&vatom.atoms);
196  kv_destroy(vatom.atoms);
197}
198#endif
199
200/// Gets a structured spec of a normal-mode command.
201CmdSpec atom_cmd_spec(const cmdarg_T *cap)
202{
203  // Cmd's second char is a typed operand ("fx", "ma"), not part of its name ("gJ", "iw").
204  bool operand = nv_is(cap->cmdchar, NV_LANG | NV_NCH_ARG);
205  return (CmdSpec){
206    .regname = cap->oap->regname,
207    .count = cap->count0,
208    .cmd = cap->cmdchar,
209    .cmd2 = operand ? NUL : cap->nchar,
210    .cmdarg = operand ? cap->nchar : cap->extra_char,  // "g`a" => 'a'.
211  };
212}
213
214/// Gets the current buffer/window/cursor state.
215static CmdOrigin atom_origin(void)
216{
217  CmdOrigin origin = { .win = curwin, .pos = curwin->w_cursor,
218                       .tick = buf_get_changedtick(curbuf), .maptick = maptick,
219                       .mcursor = mc_mark_at(curbuf, curwin->w_cursor, 0) };
220  set_bufref(&origin.buf, curbuf);
221  return origin;
222}
223
224/// True if the buffer was edited. False if the buf disappeared.
225static bool atom_origin_changed(CmdOrigin origin)
226{
227  return bufref_valid(&origin.buf) && buf_get_changedtick(origin.buf.br_buf) != origin.tick;
228}
229
230/// True if the cursor moved (in original buf). False if the win or buf disappeared.
231static bool atom_origin_moved(CmdOrigin origin)
232{
233  return bufref_valid(&origin.buf) && win_valid(origin.win)
234         && origin.win->w_buffer == origin.buf.br_buf
235         && !equalpos(origin.pos, origin.win->w_cursor);
236}
237
238/// Undo state of the buffer now, or 0 if the buffer disappeared.
239static int atom_origin_undoseq(CmdOrigin origin)
240{
241  return bufref_valid(&origin.buf) ? origin.buf.br_buf->b_u_seq_cur : 0;
242}
243
244/// Cursor position from the pending atom's start, or else `w_cursor`.
245pos_T atom_origin_pos(buf_T *buf)
246{
247  CmdOrigin o = composite.origin;
248  if (composite.open && o.buf.br_buf == buf && bufref_valid(&o.buf)
249      && buf_get_changedtick(buf) == o.tick) {
250    return o.pos;
251  }
252  return curwin->w_cursor;
253}
254
255/// Composes a CmdSpec into `redo_keys` format.
256/// @return Allocated key sequence.
257static char *atom_redo_keys(CmdSpec spec)
258{
259  assert(!mc_replaying());  // Captured material is never re-captured.
260  char *keys = redo_keys(&spec).data;
261  assert(keys != NULL);  // A spec with no chars/count/reg composes to nothing.
262  return keys;
263}
264
265/// Gets the pending change as a CmdAtom. Caller owns `keys`.
266static CmdAtom atom_from_redo(CmdAtomType type)
267{
268  String keys = redo_keys(NULL);
269  return (CmdAtom){ .type = type, .spec = redo_spec(), .keys = keys.data };
270}
271
272/// Gets a CmdAtom from a CmdSpec.
273static CmdAtom atom_from_spec(CmdAtomType type, CmdSpec spec)
274{
275  return (CmdAtom){ .type = type, .spec = spec, .keys = atom_redo_keys(spec) };
276}
277
278/// Gets a typed cmdline as a CmdAtom.
279///   ":cnext<CR>" => CmdAtom{ kAExcmd, keys=":cnext<NL>", text="cnext" }
280///
281/// @param vis  Cmdline was entered from Visual mode.
282static CmdAtom atom_from_cmdline(CmdAtomType type, cmdarg_T *ca, const char *cmdline, bool vis)
283{
284  StringBuilder sb = KV_INITIAL_VALUE;
285  if (ca->cmdchar != ':' && ca->count0 != 0) {
286    // Not for ":", its count already prefilled (":.,.+1"). But "<Cmd>" needs count in the keys.
287    kv_printf(sb, "%d", ca->count0);
288  }
289  sb_add_char(&sb, ca->cmdchar);
290  if (vis && ca->cmdchar == ':') {
291    sb_add_char(&sb, Ctrl_U);  // Clear the "'<,'>" prefill.
292  }
293  if (IS_SPECIAL(ca->cmdchar)) {
294    sb_add_spec(&sb, cmdline);  // <Cmd> text, Lua mapping-id.
295  } else {
296    sb_add_lit(&sb, cmdline, -1);  // Typed cmdline (":", "/"), interprets CTRL-V.
297  }
298  sb_add_char(&sb, NL);
299  kv_push(sb, NUL);
300  return (CmdAtom){
301    .type = type,
302    .spec = { .count = ca->count0, .cmd = ca->cmdchar },
303    .keys = sb.items,
304    .text = xstrdup(cmdline),
305  };
306}
307
308/// Gets an Ex/Lua frame as a CmdAtom: "<Cmd>…", ":…", or Lua mapping-id (K_LUA + id).
309static CmdAtom atom_from_frame(cmdarg_T *ca, const CmdFrame *root, bool vis)
310{
311  if (root->cmdline != NULL && (ca->cmdchar == ':' || ca->cmdchar == K_COMMAND)) {
312    return atom_from_cmdline(kAExcmd, ca, root->cmdline, vis);
313  }
314  if (ca->cmdchar == K_LUA) {
315    char lua_id[NUMBUFLEN];
316    // XXX: grabs LAST luamap; latent bug if "nested" (Lua mapping calls another via ":norm")...
317    snprintf(lua_id, sizeof(lua_id), "%d", repeat_luamap);
318    return atom_from_cmdline(kANormal, ca, lua_id, vis);
319  }
320  return (CmdAtom){ 0 };  // Frame is not a Ex/Lua cmd: keys=NULL.
321}
322
323/// Joins the `keys` of a list of (composite) subatoms, starting at index `from`. Plain concat
324/// (assumes `subatom.keys` is in `redo_keys` format).
325///
326/// @return Allocated keysequence, "" if empty (never NULL).
327static String atoms_concat_keys(CmdAtomVec atoms, size_t from)
328{
329  StringBuilder keys = KV_INITIAL_VALUE;
330  for (size_t i = from; i < kv_size(atoms); i++) {
331    kv_concat(keys, kv_A(atoms, i).keys);
332  }
333  size_t len = kv_size(keys);
334  kv_push(keys, NUL);
335  return (String){ .data = keys.items, .size = len };
336}
337
338/// Renders a (cmd, arg, op) char for CmdAtom: key-notation for special keys, else UTF-8. NUL => "".
339static char *atom_key_name(int c)
340{
341  if (c == NUL || c == K_LUA) {
342    return xstrdup("");
343  }
344  if (IS_SPECIAL(c) || c < ' ') {
345    // Covers <Tab>/<NL>/<CR>/<Esc> and the controls (as "<C-A>").
346    return xstrdup(get_special_key_name(c, 0));
347  }
348  if (c == DEL) {
349    return xstrdup("<Del>");  // key_names_table has K_DEL, not the ASCII byte.
350  }
351  char buf[MB_MAXBYTES + 1];
352  buf[utf_char2bytes(c, buf)] = NUL;
353  return xstrdup(buf);
354}
355
356/// Gets an atom's (allocated) event-data.
357static Dict atom_dict(const CmdAtom *atom)
358{
359  const CmdSpec *spec = &atom->spec;
360  char regname[2] = { (char)spec->regname, NUL };
361  const char *force = spec->motion_force == Ctrl_V
362                      ? "<C-V>" : (char[]){ (char)spec->motion_force, NUL };
363  // The operator char can be a control char ("g<C-A>" counter op: CTRL-A).
364  char *op = atom_key_name(spec->op);
365  if (spec->op_extra != NUL) {
366    char *extra = atom_key_name(spec->op_extra);
367    op = xrealloc(op, strlen(op) + strlen(extra) + 1);
368    strcat(op, extra);
369    xfree(extra);
370  }
371  char *cmd = atom_key_name(spec->cmd);
372  if (spec->cmd2 != NUL) {
373    // Two-char command name ("gJ", "iw", "gn"): compose it.
374    char *cmd2 = atom_key_name(spec->cmd2);
375    cmd = xrealloc(cmd, strlen(cmd) + strlen(cmd2) + 1);
376    strcat(cmd, cmd2);
377    xfree(cmd2);
378  }
379  // Inapplicable fields are OMITTED, not defaulted.
380  Dict d = ARRAY_DICT_INIT;
381  char *cmdarg = atom_key_name(spec->cmdarg);
382  if (cmdarg != NULL && *cmdarg != NUL) {
383    PUT(d, "cmdarg", CSTR_AS_OBJ(cmdarg));
384  } else {
385    xfree(cmdarg);
386  }
387  PUT(d, "changed", BOOLEAN_OBJ(atom->changed));
388  if (*cmd != NUL) {
389    PUT(d, "cmd", CSTR_AS_OBJ(cmd));
390  } else {
391    xfree(cmd);
392  }
393  if (spec->count > 0) {
394    PUT(d, "count", INTEGER_OBJ(spec->count));
395  }
396  // Note: origin is undefined for an insert-session span, its cursor effect is undefined.
397  if (atom->origin.pos.lnum > 0) {
398    PUT(d, "moved", BOOLEAN_OBJ(atom->moved));
399    Array pos = ARRAY_DICT_INIT;
400    ADD(pos, INTEGER_OBJ(atom->origin.pos.lnum));
401    ADD(pos, INTEGER_OBJ(atom->origin.pos.col));
402    PUT(d, "pos", ARRAY_OBJ(pos));
403    PUT(d, "undoseq", INTEGER_OBJ(atom->undoseq));
404  }
405  // keys/lhs are RAW bytes (typeahead encoding).
406  const char *keys = atom->keys != NULL ? atom->keys : "";
407  if (!atom->remap) {
408    PUT(d, "keys", CSTR_TO_OBJ(keys));
409  }
410  PUT(d, "lhs", CSTR_TO_OBJ(atom->lhs != NULL && *atom->lhs != NUL ? atom->lhs : keys));
411  if (*force != NUL) {
412    PUT(d, "motionforce", CSTR_TO_OBJ(force));
413  }
414  if (*op != NUL) {
415    PUT(d, "operator", CSTR_AS_OBJ(op));
416  } else {
417    xfree(op);
418  }
419  if (spec->regname != 0) {
420    PUT(d, "reg", CSTR_TO_OBJ(regname));
421  }
422  if (atom->text != NULL && *atom->text != NUL) {
423    PUT(d, "text", CSTR_TO_OBJ(atom->text));
424  }
425  PUT(d, "type", CSTR_TO_OBJ(type_names[atom->type]));
426  return d;
427}
428
429/// Schedules a CmdAtom event.
430static void atom_emit(const CmdAtom *atom)
431{
432  if (!has_event(EVENT_CMDATOM)) {
433    return;
434  }
435  Dict data = atom_dict(atom);
436  if (kv_size(atom->atoms) > 0) {
437    Array atoms = ARRAY_DICT_INIT;
438    for (size_t i = 0; i < kv_size(atom->atoms); i++) {
439      ADD(atoms, DICT_OBJ(atom_dict(&kv_A(atom->atoms, i))));
440    }
441    PUT(data, "atoms", ARRAY_OBJ(atoms));
442  }
443  buf_T *buf = atom->origin.buf.br_buf != NULL ? atom->origin.buf.br_buf : curbuf;
444  aucmd_defer(EVENT_CMDATOM, (char *)type_names[atom->type], NULL, AUGROUP_ALL, buf, NULL,
445              &DICT_OBJ(data));
446  api_free_dict(data);
447}
448
449/// Emits a CmdAtom event, or collects it as a subatom of an open scope. If `cascade` is true,
450/// queues a copy for mcursor cascade. Takes ownership: `*atom` is invalid after.
451///
452/// Both scopes (composite, Visual session) can be open. Routed by scope kind, not depth:
453/// a collecting Visual session takes the atom, its atom then lands in the composite (",v"+"d").
454/// Depth would invert "v@q", where the "@q" composite opened LAST yet collects nothing.
455void atom_push_raw(bool cascade, CmdAtom *atom)
456{
457  assert(atom->keys != NULL);
458  if (atom->origin.buf.br_buf != NULL) {
459    // Calculated here, from the atom's own baseline.
460    atom->changed = atom_origin_changed(atom->origin);
461    atom->moved = atom_origin_moved(atom->origin);
462    atom->undoseq = atom_origin_undoseq(atom->origin);
463  }
464  // `composite.frame`: the command that was executing when a peek opened the composite is not part
465  // of it.
466  const bool collect = composite.active
467                       && (cur_frame == NULL || cur_frame->id != composite.frame);
468  if (atom_visual_pending()) {
469    if (vatom.state & kVatomTyped) {
470      // Not for kVatomFed: redo-prep must not mark the enclosing span as captured.
471      atom_captures++;
472    }
473    if (collect) {
474      composite.queued = true;
475    }
476    kv_push(vatom.atoms, *atom);
477    vatom.frame = cur_frame != NULL ? cur_frame->id : 0;
478    return;
479  }
480  atom_captures++;
481  if (atom->type == kAVisual && kv_size(atom->atoms) > 0) {
482    // The completing operator is the only subatom that could have edited.
483    CmdAtom *last = &kv_A(atom->atoms, kv_size(atom->atoms) - 1);
484    if (last->type == kAOperator) {
485      last->changed = atom->changed;
486    }
487  }
488  if (cascade) {
489    CmdAtom copy = *atom;
490    copy.keys = xstrdup(atom->keys);
491    copy.text = NULL;  // replay (mc_execute()) reads only type/keys/remap: not the text,
492    copy.lhs = NULL;   // nor the label,
493    copy.atoms = (CmdAtomVec)KV_INITIAL_VALUE;  // nor the decomposition
494    kv_push(g_atoms, copy);
495    if (collect) {
496      composite.queued = true;
497    }
498  }
499  if (collect) {
500    kv_push(composite.atoms, *atom);
501  } else {
502    if (atom->type != kAInsertSpan) {
503      // Spans are cascade-internal; only emit the whole session (kAInsert).
504      atom_emit(atom);
505    }
506    atom_free(atom);
507  }
508}
509
510/// Pushes an atom (emit + maybe cascade), or drops it if replay/Visual/internal-op already
511/// in-progress.
512static void atom_push(bool cascade, CmdAtom *atom)
513{
514  if (atom_blocked()) {
515    atom_free(atom);
516    return;
517  }
518  atom_push_raw(cascade && mc_buf_has_cursors(curbuf), atom);
519}
520
521/// Stages an atom built before its command executes (do_pending_operator() prep-exempt, Visual
522/// ops), in the command's frame; pushed at frame end, once `changed` is known.
523static void atom_stage_set(CmdAtom *atom)
524{
525  assert(cur_frame != NULL);
526  assert(!atom_staged());  // One stage per frame: a second would discard a captured command.
527  atom_free(&cur_frame->staged);
528  if (atom_blocked()) {
529    // Now, not at flush: drop the atom of an internal operator (atom_suppress()).
530    atom_free(atom);
531    return;
532  }
533  assert(atom->keys != NULL);
534  cur_frame->staged = *atom;
535}
536
537/// True if an atom is staged for the current command (frame).
538static bool atom_staged(void)
539{
540  return cur_frame != NULL && cur_frame->staged.keys != NULL;
541}
542
543/// Pushes the frame's staged atom (no-op if none).
544static void atom_stage_flush(CmdFrame *frame)
545{
546  if (frame->staged.keys == NULL) {
547    return;
548  }
549  // Staged cmds are edits: cascade. Except if no keys (void Visual), already-cascaded as spans, or
550  // a global op ("zq").
551  bool cascade = *frame->staged.keys != NUL && !frame->staged.cascaded
552                 && global_ops == frame->global_ops;
553  atom_push(cascade, &frame->staged);
554  frame->staged = (CmdAtom){ 0 };
555}
556
557/// The composite's trigger: its LHS plus the keys typed while it ran, i.e. the user "intention".
558/// @return Allocated.
559static char *atom_composite_lhs(void)
560{
561  StringBuilder keys = KV_INITIAL_VALUE;
562  kv_concat(keys, composite.lhs);
563  kv_concat_len(keys, (char *)typed.keys.items + typed.map_start,
564                kv_size(typed.keys) - typed.map_start);
565  kv_push(keys, NUL);
566  return keys.items;
567}
568
569/// Queues an internal-only (no emit) atom for mcursor cascade.
570void atom_lhs_replay_queue(void)
571{
572  kv_push(g_atoms, ((CmdAtom){ .type = kAComp, .keys = atom_composite_lhs(), .remap = true,
573                               .origin = composite.origin }));
574}
575
576/// True if the composite should NOT LHS-replay (see `composite.queued`).
577bool atom_composite_queued(void)
578{
579  return composite.queued;
580}
581
582/// True while a composite is collecting subatoms.
583bool atom_composite_active(void)
584{
585  return composite.active;
586}
587
588/// Labels a composite, without necessarily starting to "collect" (active=false).
589static void atom_composite_label(const char *lhs, size_t len)
590{
591  len = MIN(len, sizeof(composite.lhs) - 1);
592  memcpy(composite.lhs, lhs, len);
593  composite.lhs[len] = NUL;
594}
595
596/// Starts collecting subatoms.
597///
598/// @param lhs  Label. NULL: keep the (deferred) label.
599/// @param len  Length of `lhs`.
600static void atom_composite_start(const char *lhs, size_t len)
601{
602  if (lhs != NULL) {
603    atom_composite_label(lhs, len);
604  }
605  composite.active = true;
606  composite.queued = false;
607  composite.lossy = false;
608  composite.frame = 0;
609}
610
611/// Emits the composite atom with its collected subatoms (`CmdAtom.atoms`).
612///
613///      :nnoremap gj i<C-J><Esc>k$
614///      "gj" => CmdAtom{ .lhs="gj", .keys="1i<NL><Esc>k$", kAComp }
615static void atom_composite_end(void)
616{
617  composite.macro = false;  // "@x" capture ends with its composite.
618  if (!composite.active) {
619    return;
620  }
621  // LHS-replay when the capture is lossy, or captured nothing (Ex/Lua edits).
622  const bool remap = composite.lossy || kv_size(composite.atoms) == 0;
623  char *lhs = atom_composite_lhs();
624  composite.lhs[0] = NUL;
625  composite.active = false;
626  CmdAtom atom;
627  if (kv_size(composite.atoms) == 1) {
628    // Single subatom (simple mapping). "Unwrap" it: a motion mapping reports kAMotion, not kAComp.
629    atom = kv_pop(composite.atoms);
630    xfree(atom.lhs);
631    atom.lhs = lhs;
632    atom.remap = remap;
633  } else {
634    // Zero subatoms (captured nothing (Ex/Lua, no-op); still a user action, identified by `lhs`),
635    // or multiple subatoms.
636    atom = (CmdAtom){ .type = kAComp, .keys = atoms_concat_keys(composite.atoms, 0).data,
637                      .lhs = lhs, .remap = remap, .origin = composite.origin,
638                      .changed = atom_origin_changed(composite.origin),
639                      .moved = atom_origin_moved(composite.origin),
640                      .undoseq = atom_origin_undoseq(composite.origin) };
641    atom.atoms = composite.atoms;  // Subatoms.
642    composite.atoms = (CmdAtomVec)KV_INITIAL_VALUE;  // Reset.
643  }
644  atom_emit(&atom);
645  atom_free(&atom);
646}
647
648/// Discards the pending atom and its subatoms: error/interrupt voided it (but the continuation
649/// keys, typeahead/stuff, were flushed).
650void atom_composite_abort(void)
651{
652  composite.macro = false;
653  composite.lhs[0] = NUL;
654  composite.active = false;
655  atoms_free(&composite.atoms);
656  composite.open = false;
657}
658
659/// Entering :terminal mode resolves (ends) the pending atom. Terminal keys are never captured.
660void atom_term_enter(void)
661{
662  if (!mc_replaying()) {
663    atom_composite_end();
664    composite.open = false;
665  }
666}
667
668/// True if the just-executed command is user input. Excludes re-execution of captured
669/// material: "@r" (unless composite.macro), ":normal", cascade replays.
670bool atom_is_user_cmd(void)
671{
672  // reg_executing is already reset for a macro's LAST command (its trailing "x" stuffs "dl").
673  return !mc_replaying()
674         && ((reg_executing == 0 && !pending_end_reg_executing) || composite.macro)
675         && ex_normal_busy == 0;
676}
677
678/// Like atom_is_user_cmd(), for sampling before a command consumes its keys.
679/// - typed "i", mapped "gj" => true
680/// - "." (stuffed redo), "@r", feedkeys() without "t" => false
681static bool atom_is_user_input(void)
682{
683  // An open composite is user input even after its keys were consumed (":nnoremap ,i i").
684  return KeyTyped || (atom_is_user_cmd() && atom_composite_active());
685}
686
687/// Suppresses atom pushes. For internal operators.
688void atom_suppress(bool suppress)
689{
690  atom_suppressed = suppress;
691}
692
693/// Block atom pushes if: cascade in-progress, or internal op is executing.
694static bool atom_blocked(void)
695{
696  return mc_replaying() || atom_suppressed;
697}
698
699/// Decides if the command is capturable.
700static bool atom_capturable(bool consumers, bool keytyped)
701{
702  return consumers && atom_is_user_cmd() && (keytyped || atom_composite_active());
703}
704
705/// True if anything consumes atoms from `curbuf`. For performance: skip capture if no consumers.
706static bool atom_buf_has_consumers(void)
707{
708  return mc_buf_has_cursors(curbuf) || has_event(EVENT_CMDATOM);
709}
710
711/// Classifies key/command `cmd`. arg/arg2 are its argument chars, for commands like g; or g`a.
712///
713/// @return  kKeyXx flags, or 0 for an ordinary key.
714unsigned atom_key_class(int cmd, int arg, int arg2)
715{
716  switch (cmd) {
717  case K_EVENT:
718  case K_IGNORE:
719    return kKeyOpaque | kKeySynthetic;
720  case K_COMMAND:
721  case K_LUA:
722    return kKeyOpaque;
723  case '/':
724  case '?':
725  case ':':
726  case '!':
727    return kKeyPayload;
728  case Ctrl_D:
729  case Ctrl_U:
730    return kKeyScrollMove | kKeyInsFlush;
731  case Ctrl_F:
732  case Ctrl_B:
733    return kKeyScrollMove;
734  case Ctrl_E:
735  case Ctrl_Y:
736    return kKeyScrollView;
737  case Ctrl_T:
738    return kKeyInsFlush;
739  // Multiplexed: one nv_cmds entry => many commands. Classified by char 2, not NV_MOTION/….
740  case 'g':
741    if (arg == '\'' || arg == '`') {
742      return atom_key_class(arg, arg2, NUL);  // "g'x", "g`x": like "'x", "`x".
743    }
744    if (strchr(";,go", arg) != NULL) {
745      return kKeyJump;
746    }
747    return strchr("jk0^$_meEM*#", arg) != NULL ? kKeyMotion : 0;
748  case '[':
749  case ']':
750    if (arg == 'C') {
751      return kKeyJump;  // "]C"/"[C": jump to the next/previous cursor
752    }
753    return strchr("[](){}mMcsz#*/", arg) != NULL ? kKeyMotion : 0;
754  case 'z':
755    return (arg == 'j' || arg == 'k') ? kKeyMotion : 0;
756  case '\'':
757  case '`':
758    // kCtxVisual|kCtxMarks and '( '{ etc. are cursor-relative; others are absolute.
759    return arg != NUL && strchr("<>[].^(){}", arg) != NULL ? kKeyMotion : kKeyJump;
760  case K_DOWN:
761  case K_END:
762  case K_HOME:
763  case K_LEFT:
764  case K_RIGHT:
765  case K_UP:
766    return kKeyMotion | kKeyInsFlush;
767  case Ctrl_G:
768  case Ctrl_H:
769  case Ctrl_R:  // "<C-R>x" (insert_reg()): reads per-cursor registers.
770  case Ctrl_W:
771  case K_BS:
772  case K_DEL:
773  case K_S_LEFT:
774  case K_S_RIGHT:
775    return kKeyInsFlush;
776  case K_LEFTMOUSE:
777  case K_LEFTMOUSE_NM:
778  case K_MIDDLEMOUSE:
779  case K_RIGHTMOUSE:
780  case K_X1MOUSE:
781  case K_X2MOUSE:
782    return kKeyMouse;
783  case K_MOUSEDOWN:   // <ScrollWheelUp>
784  case K_MOUSEUP:     // <ScrollWheelDown>
785  case K_MOUSELEFT:
786  case K_MOUSERIGHT:
787    return kKeyScrollView;
788  default:
789    return 0;
790  }
791}
792
793/// Captures an accepted ":" or "<Cmd>" cmdline payload.
794void atom_cmdline_set(int firstc, const char *line, size_t len)
795{
796  // Not for nested cmdlines (":norm", macros), nor a prompt (input()) from a timer/RPC callback
797  // (no command executing).
798  if (cur_frame == NULL || !atom_is_user_cmd() || (firstc != ':' && firstc != K_COMMAND)) {
799    return;
800  }
801  CmdFrame *root = root_frame();
802  // The first accept is the payload, not a second one (":put ." => ":put _" translation).
803  if (root->cmdline == NULL) {
804    root->cmdline = xmemdupz(line, len);
805  }
806}
807
808/// True while collecting typed keys: during a composite (for `lhs`), or a CmdFrame's payload slice.
809static bool atom_typed_collecting(void)
810{
811  return atom_composite_active()
812         || (cur_frame != NULL && cur_frame->payload_start != SIZE_MAX);
813}
814
815/// Opens the CmdFrame's payload slice: keys from getchar()/input()/… append to `CmdAtom.keys`.
816void atom_payload_start(void)
817{
818  if (expr_map_lock == 0  // Do not append input read during expr EVALUATION.
819      && cur_frame != NULL && cur_frame->payload_start == SIZE_MAX && !mc_replaying()) {
820    cur_frame->payload_start = cur_frame->payload_end = kv_size(typed.keys);
821  }
822}
823
824/// Closes (or extends) the payload slice.
825void atom_payload_end(void)
826{
827  if (expr_map_lock == 0 && cur_frame != NULL && cur_frame->payload_start != SIZE_MAX
828      && !mc_replaying()) {
829    cur_frame->payload_end = kv_size(typed.keys);
830  }
831}
832
833/// Drains the CmdFrame's payload slice to `CmdAtom.keys`.
834static void atom_payload_append(CmdAtom *atom, CmdFrame *frame)
835{
836  size_t plen = frame->payload_start == SIZE_MAX ? 0 : frame->payload_end - frame->payload_start;
837  if (plen == 0 || atom->keys == NULL) {
838    return;
839  }
840  size_t klen = strlen(atom->keys);
841  atom->keys = xrealloc(atom->keys, klen + plen + 1);
842  memcpy(atom->keys + klen, typed.keys.items + frame->payload_start, plen);
843  atom->keys[klen + plen] = NUL;
844  frame->payload_start = SIZE_MAX;
845}
846
847/// Collects a typed key (gotchars()) into the stream.
848void atom_typed_add(const uint8_t *chars, size_t len)
849{
850  if (mc_replaying() || !atom_typed_collecting()
851      // Skip inputsecret(), to avoid leaking a password e.g. if a plugin logs `CmdAtom.keys`.
852      || cmdline_star > 0) {
853    return;
854  }
855  if (len == 3 && chars[0] == K_SPECIAL
856      && (atom_key_class(TERMCAP2KEY(chars[1], chars[2]), NUL, NUL) & kKeySynthetic)) {
857    return;  // Not user input: K_IGNORE from a mapping resolved during peek/K_EVENT/…
858  }
859  for (size_t i = 0; i < len; i++) {
860    kv_push(typed.keys, chars[i]);
861  }
862}
863
864/// Undoes atom_typed_add() for the last `len` bytes: a key that was read is being re-queued
865/// into typeahead and will be collected again (ungetchars()).
866void atom_typed_del(size_t len)
867{
868  if (mc_replaying() || !atom_typed_collecting()) {
869    return;
870  }
871  kv_size(typed.keys) -= MIN(len, kv_size(typed.keys));
872}
873
874/// Flags the running command as already applying to every cursor. E.g.: undo, "g CTRL-A"
875void atom_did_global_op(void)
876{
877  if (!mc_replaying()) {
878    global_ops++;
879    composite.queued = true;  // Already applied at every cursor: no LHS-replay.
880  }
881}
882
883/// Applies "q=" change to the current command, and later moves.
884void atom_follow_changed(void)
885{
886  if (mc_replaying()) {
887    return;
888  }
889  for (CmdFrame *frame = cur_frame; frame != NULL; frame = frame->parent) {
890    if (!atom_origin_moved(frame->origin)) {
891      frame->follow = mc_following();
892    } else if (composite.follow == kNone) {
893      composite.follow = frame->follow ? kTrue : kFalse;
894    }
895  }
896}
897
898/// Declares that the current frame prepped redo. Not for nested frames (":norm").
899void atom_redo_prepped(void)
900{
901  if (atom_is_user_cmd()) {
902    root_frame()->redo_frame = cur_frame->id;
903  }
904}
905
906/// Redo-prep was canceled (aborted operation).
907void atom_redo_cancel(void)
908{
909  root_frame()->redo_frame = 0;
910}
911
912/// Starts accumulating a composite for a macro's commands, labeled "@x".
913void atom_macro_start(int regname)
914{
915  if (atom_is_user_input()) {
916    composite.macro = true;
917    if (!atom_composite_active()) {
918      // The macro's commands collapse into one "@x"-labeled atom.
919      char lhs[3] = { '@', (char)regname, NUL };
920      atom_composite_start(lhs, 2);
921    }
922  }
923}
924
925/// Starts accumulating composite for a cmd that stuffs its translation ("x" => "dl", "." => redo).
926void atom_stuff_start(const cmdarg_T *cap)
927{
928  // Not while another composite collects: a mapping's own label wins ("nnoremap <F6> xw").
929  if (mc_replaying() || atom_composite_active() || !atom_is_user_input()) {
930    return;
931  }
932  char *lhs = atom_redo_keys(atom_cmd_spec(cap));
933  atom_composite_start(lhs, strlen(lhs));
934  xfree(lhs);
935}
936
937/// Starts a composite for a mapping resolved from typed keys.
938///
939/// @param peeked  The executing command did not consume the mapping's keys.
940void atom_map_start(const char *lhs, size_t len, bool peeked)
941{
942  if (mc_replaying() || reg_executing != 0 || ex_normal_busy != 0) {
943    return;
944  }
945  if (!(State & MODE_NORMAL)) {
946    // Label the (potential, deferred) composite but don't start collecting (!MODE_NORMAL).
947    atom_composite_label(lhs, len);
948    return;
949  }
950  if (atom_composite_active()) {
951    if (get_real_state() == MODE_OP_PENDING) {
952      // The pending operator's own composite ("gr" <expr> mapping => "g@") absorbs its operand.
953      return;
954    }
955    // Mapping resolved from another's trailing prefix ("nmap x j," + "nnoremap ,w w"): end the
956    // pending composite, so each `lhs` owns only the keys it produced.
957    typed.map_start = kv_size(typed.keys);
958    atom_composite_end();
959  }
960  const char *op = get_vim_var_str(VV_OP);  // v:operator
961  if (get_real_state() == MODE_OP_PENDING && *op != NUL) {
962    // Op-pending mapping (:omap) continues the operator (vim-sneak "dz(b").
963    assert(lhs[len] == NUL);
964    char *full = concat_str(op, lhs);
965    atom_composite_start(full, strlen(full));
966    xfree(full);
967    typed.map_start = kv_size(typed.keys);
968    return;
969  }
970  atom_composite_start(lhs, len);
971  if (peeked && cur_frame != NULL) {
972    composite.frame = cur_frame->id;
973  }
974  typed.map_start = kv_size(typed.keys);
975}
976
977/// Discards the pending visual atom. Not a lifecycle end: also runs before a session starts, and
978/// when a selection is consumed by a non-operator.
979void atom_visual_reset(void)
980{
981  vatom.state = kVatomNone;
982  atoms_free(&vatom.atoms);
983  vatom.origin = (CmdOrigin){ 0 };
984  vatom.frame = 0;
985  vatom.done = 0;
986  mc_vsel_clear();
987}
988
989/// Visual atom is pending. A void session still accumulates, for the `lhs` label.
990static bool atom_visual_pending(void)
991{
992  return vatom.state != kVatomNone;
993}
994
995/// True if the selection started as user input, or received typed input (`maptick`).
996static bool atom_visual_typed(void)
997{
998  return atom_visual_pending()
999         && ((vatom.state & kVatomTyped) || maptick != vatom.origin.maptick);
1000}
1001
1002/// Pending Visual atom is replayable (not voided).
1003bool atom_visual_replayable(void)
1004{
1005  return atom_visual_pending() && !(vatom.state & kVatomVoid);
1006}
1007
1008/// Pending Visual atom's keys can redo: replayable, and no "gv".
1009bool atom_visual_redoable(void)
1010{
1011  if (!atom_visual_replayable()) {
1012    return false;
1013  }
1014  for (size_t i = 0; i < kv_size(vatom.atoms); i++) {
1015    const CmdSpec spec = kv_A(vatom.atoms, i).spec;
1016    if (spec.cmd == 'g' && spec.cmd2 == 'v') {
1017      return false;  // Found "gv" subatom.
1018    }
1019  }
1020  return true;
1021}
1022
1023/// The pending visual atom's uncascaded "tail" keys (allocated; NULL data if inactive/void).
1024/// Replaying produces the per-cursor selection. Prefixed with "gv" if a span cascaded.
1025String atom_visual_span(void)
1026{
1027  if (!atom_visual_replayable()) {
1028    return (String)STRING_INIT;
1029  }
1030  String tail = atoms_concat_keys(vatom.atoms, vatom.done);
1031  if (vatom.done == 0) {
1032    return tail;
1033  }
1034
1035  // Prefix with "gv".
1036  StringBuilder keys = KV_INITIAL_VALUE;
1037  kv_concat(keys, "gv");
1038  kv_concat_len(keys, tail.data, tail.size);
1039  size_t len = kv_size(keys);
1040  kv_push(keys, NUL);
1041  api_free_string(tail);
1042  return (String){ .data = keys.items, .size = len };
1043}
1044
1045/// Cascades the Visual session's uncascaded subatoms as a span, if one of them edited the buffer.
1046///
1047/// The session's own atom must not cascade again (`CmdAtom.cascaded`). Pure selection keys stay
1048/// pending; the dry-run previews them (mc_vsel_refresh).
1049static void atom_visual_span_flush(void)
1050{
1051  if (vatom.done >= kv_size(vatom.atoms) || !atom_visual_replayable() || !atom_visual_typed()
1052      || !mc_buf_has_cursors(curbuf)) {
1053    return;
1054  }
1055  bool edited = false;
1056  for (size_t i = vatom.done; i < kv_size(vatom.atoms); i++) {
1057    assert(kv_A(vatom.atoms, i).type != kAOperator);  // Only atom_push_raw() computes `changed`.
1058    edited |= kv_A(vatom.atoms, i).changed;
1059  }
1060  if (!edited) {
1061    return;
1062  }
1063  String span = atom_visual_span();
1064  vatom.done = kv_size(vatom.atoms);
1065  kv_push(g_atoms, ((CmdAtom){ .type = kAVisualSpan, .keys = span.data, .origin = vatom.origin }));
1066}
1067
1068/// Ends the pending visual atom, appends `suffix`, and stages it. Or discards if unreplayable.
1069///
1070/// @param suffix  Owned.
1071/// @param spec  The completing operator, or NULL.
1072/// @param redoable  Prep redo. Unreplayable (or "gv") selection preps "1v" + op (fixed-size
1073///                  visual-repeat).
1074/// @return  True if the redo was prepped.
1075static bool atom_visual_end_suffix(char *suffix, const CmdSpec *spec, bool redoable)
1076{
1077  if (mc_replaying() || atom_suppressed) {  // Replay, or internal op applied during another cmd.
1078    xfree(suffix);
1079    return false;
1080  }
1081  const CmdOrigin origin = vatom.origin;  // atom_visual_reset() clears the session.
1082  const bool replayable = suffix != NULL && atom_visual_replayable();
1083  String v = replayable ? atoms_concat_keys(vatom.atoms, 0) : (String)STRING_INIT;
1084  // Redo: the collected keys, else "1v" fallback. The tail (reg/count/op) comes from the suffix:
1085  // prep/atom cannot diverge, and suffixes inexpressible as spec ("r<C-V><CR>") stay replayable.
1086  const bool prepped = redoable && spec != NULL && suffix != NULL
1087                       && (replayable || spec->op != NUL);
1088
1089  if (prepped) {
1090    const bool redo_keys = atom_visual_redoable();
1091    prep_redo_visual(redo_keys ? v.data : "1v", redo_keys ? v.size : 2, (CmdSpec){ 0 });
1092    redo_append_str(suffix, -1);
1093  }
1094
1095  if (is_child_frame()) {
1096    xfree(v.data);
1097    xfree(suffix);
1098    // Keep the session pending (no atom_visual_reset()), let the enclosing frame resolve it. #41956
1099    return prepped;
1100  }
1101
1102  if (!replayable) {
1103    // A poisoned selection is still a user action: emit it with lhs + empty keys, like a mapping
1104    // whose commands captured nothing (atom_composite_end()).
1105    bool emit = (vatom.state & kVatomVoid) && atom_visual_typed() && spec != NULL
1106                && suffix != NULL && atom_is_user_cmd();
1107    char *label = NULL;
1108    if (emit) {
1109      String collected = atoms_concat_keys(vatom.atoms, 0);
1110      label = xrealloc(collected.data, collected.size + strlen(suffix) + 1);
1111      STRCPY(label + collected.size, suffix);
1112    }
1113    xfree(suffix);
1114    atom_visual_reset();  // End the session before staging.
1115    if (emit) {
1116      atom_stage_set(&(CmdAtom){ .type = kAVisual, .spec = *spec, .keys = xstrdup(""),
1117                                 .lhs = label, .origin = origin });
1118    }
1119    return prepped;
1120  }
1121
1122  if (!atom_is_user_cmd() || !atom_visual_typed()) {
1123    // Internal input (":norm! vjd", fed keys): the redo prep above is the only effect; no emit.
1124    xfree(v.data);
1125    xfree(suffix);
1126    atom_visual_reset();
1127    return prepped;
1128  }
1129
1130  //
1131  // Typed, replayable session: stage its Visual atom. Ends the session.
1132  //
1133  char *keys = xrealloc(v.data, v.size + strlen(suffix) + 1);
1134  STRCPY(keys + v.size, suffix);
1135  CmdAtom atom = {
1136    .type = kAVisual,
1137    // The completing operator's fields; per-command counts/registers are
1138    // embedded in `keys` (and decomposed in `atoms`).
1139    .spec = spec != NULL ? *spec : (CmdSpec){ 0 },
1140    .keys = keys,
1141    .origin = origin,
1142  };
1143  if (spec != NULL) {
1144    kv_push(vatom.atoms, ((CmdAtom){ .type = kAOperator, .spec = *spec, .keys = suffix,
1145                                     .origin = cur_frame->origin }));
1146  } else {
1147    xfree(suffix);
1148  }
1149  atom.cascaded = vatom.done > 0;
1150  if (atom.cascaded && vatom.done < kv_size(vatom.atoms)) {
1151    // Spans cascaded the selection's edits. This last one completes it (the operator).
1152    String span = atom_visual_span();
1153    kv_push(g_atoms, ((CmdAtom){ .type = kAVisualSpan, .keys = span.data, .origin = origin }));
1154  }
1155  atom.atoms = vatom.atoms;
1156  vatom.atoms = (CmdAtomVec)KV_INITIAL_VALUE;
1157  atom_visual_reset();
1158  atom_stage_set(&atom);
1159  return prepped;
1160}
1161
1162/// Ends the pending visual atom with the operator `spec` ("viwee" + "x").
1163///
1164/// @return  True if redo was prepped.
1165bool atom_visual_end(CmdSpec spec, bool redoable)
1166{
1167  if (mc_replaying()) {
1168    return false;
1169  }
1170  return atom_visual_end_suffix(atom_redo_keys(spec), &spec, redoable);
1171}
1172
1173/// Captures a pending operator's atom and preps its redo, before it executes. Prep-exempt commands
1174/// (yank without cpo-y, "D", folds) build no redo, so atom_cmd_end() cannot derive their atom from
1175/// redobuff; reconstruct it here (staged).
1176///
1177/// Not captured (prep only):
1178/// - OP_CHANGE/OP_INSERT/OP_APPEND (the insert session is the atom)
1179/// - motions with an interactively-typed payload (search, Ex, Lua)
1180///
1181/// @param redo_yank  True when a yank builds a redo ("y" in 'cpoptions', not a GUI yank).
1182void atom_capture_op(oparg_T *oap, cmdarg_T *cap, bool redo_yank)
1183{
1184  const bool redoable = op_redoable(oap->op_type, redo_yank);
1185  bool ins_op = oap->op_type == OP_CHANGE || oap->op_type == OP_INSERT
1186                || oap->op_type == OP_APPEND;
1187  bool payload_motion = cap->cmdchar >= 0x100
1188                        || (cap->cmdchar != NUL && strchr("/?:!", cap->cmdchar) != NULL);
1189  bool excmd = cap->cmdchar == ':' || cap->cmdchar == K_COMMAND;
1190  if (!ins_op && !payload_motion) {
1191    bool prep_exempt = !redoable || cap->cmdchar == 'D';
1192    CmdSpec spec = {
1193      .regname = oap->regname, .count = cap->count0,
1194      .op = get_op_char(oap->op_type), .op_extra = get_extra_op_char(oap->op_type),
1195    };
1196    if (prep_exempt && (!Visual.active || oap->motion_force)) {
1197      // Only capture _user_ input.
1198      if (atom_capturable(atom_buf_has_consumers(), KeyTyped)) {
1199        // Cmd's second char is a typed operand ("fx", "ma"), not part of its name ("gJ", "iw").
1200        bool operand = nv_is(cap->cmdchar, NV_LANG | NV_NCH_ARG);
1201        spec.motion_force = oap->motion_force;
1202        spec.cmd = cap->cmdchar;
1203        spec.cmd2 = operand ? NUL : cap->nchar;
1204        spec.cmdarg = operand ? cap->nchar : NUL;
1205        CmdAtom op_atom = atom_from_spec(kAOperator, spec);
1206        op_atom.origin = cur_frame->origin;
1207        atom_stage_set(&op_atom);
1208      }
1209    } else if (!Visual.active || oap->motion_force) {
1210      // Prepped: atom_cmd_end() derives the atom from redobuff.
1211    } else if (oap->op_type == OP_REPLACE && cap->nchar <= 0) {
1212      // Visual "r<C-V><CR>": `spec.cmdarg` cannot represent the sentinel (REPLACE_CR_NCHAR), so
1213      // hand-compose the literal suffix keys.
1214      char suffix[4] = { 'r', Ctrl_V, cap->nchar == REPLACE_CR_NCHAR ? CAR : NL, NUL };
1215      atom_visual_end_suffix(xstrdup(suffix), &spec, redoable);
1216    } else {
1217      // Visual-mode op: complete the accumulated visual atom with the operator keys.
1218      spec.cmdarg = oap->op_type == OP_REPLACE ? cap->nchar : NUL;
1219      if ((oap->op_type == OP_NR_ADD || oap->op_type == OP_NR_SUB) && cap->arg) {
1220        // g<C-A>: the "g" variant is distinguished by cap->arg, not the op char: compose it back.
1221        spec.op_extra = spec.op;
1222        spec.op = 'g';
1223      }
1224      atom_visual_end(spec, redoable);
1225    }
1226  }
1227
1228  // The prep decision. Runs after the capture above: a self-selecting op's prep overrides the
1229  // equal-size fallback the visual end may have prepped ("dgn").
1230  if (redoable && cap->cmdchar != 'D'
1231      && ((!Visual.active || oap->motion_force)
1232          // Also redo Operator-pending Visual mode mappings.
1233          || excmd || cap->cmdchar == K_LUA)) {
1234    prep_redo(true, false, (CmdSpec){
1235      .regname = oap->regname, .count = cap->count0,
1236      .op = get_op_char(oap->op_type), .op_extra = get_extra_op_char(oap->op_type),
1237      .motion_force = oap->motion_force, .cmd = cap->cmdchar, .cmd2 = cap->nchar,
1238    });
1239    if (cap->cmdchar == '/' || cap->cmdchar == '?') {     // was a search
1240      // If 'cpoptions' does not contain 'r', insert the search pattern to really repeat the
1241      // same command.
1242      if (vim_strchr(p_cpo, kCpoRedo) == NULL) {
1243        redo_append_lit(cap->searchbuf, -1);
1244      }
1245      redo_append_str(S_LEN(NL_STR));
1246    } else if (excmd) {
1247      // do_cmdline() has stored the first typed line in "repeat_cmdline". When several lines are
1248      // typed repeating won't be possible.
1249      if (repeat_cmdline == NULL) {
1250        redo_new((CmdSpec){ 0 });
1251      } else {
1252        if (cap->cmdchar == ':') {
1253          redo_append_lit(repeat_cmdline, -1);
1254        } else {
1255          redo_append_spec(repeat_cmdline);
1256        }
1257        redo_append_str(S_LEN(NL_STR));
1258        XFREE_CLEAR(repeat_cmdline);
1259      }
1260    } else if (cap->cmdchar == K_LUA) {
1261      char lua_id[NUMBUFLEN];
1262      redo_append_str(lua_id, snprintf(lua_id, sizeof(lua_id), "%d", repeat_luamap));
1263      redo_append_str(S_LEN(NL_STR));
1264    }
1265  } else if (Visual.active && redoable && oap->motion_force == NUL) {
1266    if (op_self_select(cap)) {
1267      prep_redo(true, false, (CmdSpec){
1268        .regname = oap->regname, .count = cap->count0,
1269        .op = get_op_char(oap->op_type), .op_extra = get_extra_op_char(oap->op_type),
1270        .motion_force = oap->motion_force, .cmd = cap->cmdchar, .cmd2 = cap->nchar,
1271      });
1272    } else if (ins_op && !excmd && cap->cmdchar != K_LUA) {
1273      // Visual-entered Insert: redo body opens with the selection's captured keys; appends the
1274      // op+text+<Esc>. Unreplayable (void, "gv") selection falls back to "1v" (fixed-size reselect).
1275      // (Ex/Lua-motion selections were already prepped above, as the motion's keys.)
1276      String v = atom_visual_redoable() ? atom_visual_span() : (String)STRING_INIT;
1277      prep_redo_visual(v.data != NULL ? v.data : "1v", v.data != NULL ? v.size : 2, (CmdSpec){
1278        .regname = oap->regname,
1279        .op = get_op_char(oap->op_type), .op_extra = get_extra_op_char(oap->op_type),
1280      });
1281      xfree(v.data);
1282    }
1283  }
1284}
1285
1286/// Delimits an insert-session, called before its edit(). The session either insert-cascades (spans
1287/// replay at every cursor) or is captured whole at <Esc>.
1288///
1289/// No insert-cascade when:
1290/// - Count is given ("[count]i…").
1291/// - Replace mode (R, gR, r<CR>, gr): continuation spans re-enter with "i".
1292/// - Blockwise ("1vI", CTRL-V+"jc").
1293/// - Entered from Visual without captured keys, or by Ex/Lua motion that read input: unreplayable.
1294///
1295/// @param cmd     Entry command char, edit()-style ('i', 'a', 'R', 'v' = gr, …).
1296/// @param count   Count given to the entry command.
1297/// @param vis     How the session was entered from Visual mode.
1298/// @param vblock  The Visual selection was blockwise.
1299InsSession atom_ins_start(int cmd, long count, VisualIns vis, bool vblock)
1300{
1301  InsSession session = {
1302    .typed = atom_is_user_input(),  // Sampled before the session.
1303    .vis = vis,
1304    // A consumed selection opens the redo body, so the atom starts where the selection did.
1305    // Else the CmdFrame origin, from before the entry moved the cursor (a/A/…).
1306    .origin = vis == kVInsKeys ? vatom.origin : cur_frame->origin,
1307  };
1308
1309  if (vis != kVInsNone && !mc_replaying() && !is_child_frame()) {
1310    if (vis == kVInsOther && atom_visual_replayable() && !atom_visual_redoable()) {
1311      session.vsel = atom_visual_span().data;
1312      session.origin = vatom.origin;
1313    }
1314    if (vis == kVInsKeys || session.vsel != NULL) {
1315      // Internal keys (":norm", scheduled feedkeys) are not user-input.
1316      // But a Visual-mode operator mapping ("xnoremap c c") is user-input. #41605
1317      session.typed = atom_visual_replayable() && atom_visual_typed();
1318    }
1319    // The selection is consumed: already in the redo body. Also clears selection display.
1320    atom_visual_reset();
1321  }
1322
1323  bool repl = cmd == 'R' || cmd == 'V' || cmd == 'r' || cmd == 'v';
1324  bool reexec = vis == kVInsNone || vis == kVInsKeys || session.vsel != NULL
1325                || (vis == kVInsMotion && cur_frame->payload_start == SIZE_MAX);
1326  mc_ins_cascade_start(session.typed && count <= 1 && !repl && !vblock && reexec,
1327                       session.origin, root_frame()->id, session.vsel);
1328
1329  return session;
1330}
1331
1332/// Ends the insert-session delimited by atom_ins_start(), capturing it as one atom. Replaying the
1333/// whole session (not spans), applies the entry cursor placement ("A", "o", "cw") and autocommands.
1334///
1335/// @param busy  True when edit() returned early (i_CTRL-O): session incomplete.
1336void atom_ins_end(InsSession *session, bool busy)
1337{
1338  bool visual = session->vis != kVInsNone;
1339  bool user_input = session->typed
1340                    // A session is user input, if user input occurred during it. #41516
1341                    || maptick != session->origin.maptick;
1342
1343  if (mc_replaying()) {
1344    goto theend;
1345  }
1346  if (mc_ins_commit()) {
1347    // Not during a mapping: there the spans are subatoms of its composite.
1348    if (has_event(EVENT_CMDATOM) && !atom_composite_active()) {
1349      atom_ins_push(session, false);
1350    }
1351    goto theend;
1352  }
1353  if (!user_input || busy || restart_edit != 0 || !atom_buf_has_consumers()
1354      || (visual && session->vis != kVInsKeys && session->vsel == NULL)) {
1355    if (user_input && (busy || restart_edit != 0) && atom_composite_active()) {
1356      // Incomplete session (i_CTRL-O): its resolution is never captured.
1357      composite.lossy = true;
1358    }
1359    goto theend;
1360  }
1361  atom_ins_push(session, mc_buf_has_cursors(curbuf));
1362
1363theend:
1364  XFREE_CLEAR(session->vsel);
1365}
1366
1367/// Pushes the ended insert-session as one atom. Skips a session not ending in <Esc>, except
1368/// self-terminating "r<CR>"/"grx".
1369static void atom_ins_push(const InsSession *session, bool cascade)
1370{
1371  CmdAtom atom = atom_from_redo(session->vis != kVInsNone ? kAVisual : kAInsert);
1372  if (session->vsel != NULL && atom.keys != NULL) {
1373    assert(strncmp(atom.keys, "1v", 2) == 0);  // Supplant redo's "1v" fallback.
1374    char *keys = concat_str(session->vsel, atom.keys + 2);
1375    xfree(atom.keys);
1376    atom.keys = keys;
1377  }
1378  size_t size = atom.keys != NULL ? strlen(atom.keys) : 0;
1379  bool replace = atom.spec.cmd == 'r' || (atom.spec.cmd == 'g' && atom.spec.cmd2 == 'r');
1380  if (size == 0 || (!replace && (uint8_t)atom.keys[size - 1] != ESC)) {
1381    atom_free(&atom);
1382    return;
1383  }
1384  atom.text = get_last_insert_save();
1385  atom.origin = session->origin;
1386  atom_push_raw(cascade, &atom);
1387}
1388
1389/// Toplevel entry: starts a new atom. Samples the pre-cmd state (`origin`); pushes the frame.
1390void atom_cmd_start(CmdFrame *old, int cmdchar)
1391{
1392  const bool consumers = atom_buf_has_consumers();
1393  *old = (CmdFrame){
1394    .origin = atom_origin(),
1395    .visual = Visual,
1396    .keytyped = KeyTyped,
1397    .keyclass = atom_key_class(cmdchar, NUL, NUL),
1398    .ex_normal = ex_normal_busy,
1399    .captures = atom_captures,
1400    .global_ops = global_ops,
1401    .beeps = did_beep,
1402    .id = ++frame_id,
1403    // Sampled; a later "q=" applies only to later moves.
1404    .follow = mc_following(),
1405    .consumers = consumers,
1406    // Diffed at command end to detect a register-write (yank).
1407    .reg_ts = consumers ? reg_max_ts(true) : 0,
1408    .payload_start = SIZE_MAX,
1409    .parent = cur_frame,
1410  };
1411  cur_frame = old;
1412  if (old->parent == NULL && !composite.open) {
1413    composite.open = true;
1414    composite.origin = old->origin;
1415    composite.follow = kNone;
1416  }
1417  // Deferred composite: now start collecting...
1418  if (old->parent == NULL && !mc_replaying() && !composite.active && composite.lhs[0] != NUL) {
1419    if (!KeyTyped && consumers) {
1420      atom_composite_start(NULL, 0);
1421      typed.map_start = kv_size(typed.keys);
1422      composite.follow = kNone;  // Sampled again later.
1423    } else {  // Not from the mapping (typed), or no consumers.
1424      composite.lhs[0] = NUL;
1425    }
1426  }
1427  // A toplevel user command starts a new typed stream, unless a mapping slice is still open (its
1428  // composite spans commands). Not for a nested frame (":norm!", exec_stuffed()).
1429  if (old->parent == NULL && atom_is_user_cmd() && !atom_composite_active()) {
1430    kv_size(typed.keys) = 0;
1431    typed.map_start = 0;
1432  }
1433}
1434
1435/// Captures the typed command's atom: one atom per command, produced from the CmdFrame diff and
1436/// routed by atom_push_raw() (emit, or collect as a mapping/Visual subatom).
1437///
1438/// Skipped for a command that stuffed keys ("x" stuffs "dl": its resolution is the atom), or that
1439/// already captured its own atom (do_pending_operator(), insert spans).
1440///
1441/// @return  True if the selection preview needs a refresh.
1442static bool atom_capture_cmd(cmdarg_T *ca, CmdFrame *old)
1443{
1444  if (mc_replaying() || atom_suppressed) {
1445    return false;
1446  }
1447
1448  //
1449  // Classify
1450  //
1451  const bool user = atom_is_user_cmd();
1452  const CmdFrame *root = root_frame();
1453  const unsigned keycls = atom_key_class(ca->cmdchar, ca->nchar, ca->extra_char);
1454  // Opaque cmd that changed nothing is invisible; one that changed the buffer/selection voids the
1455  // pending visual atom (see `kKeyOpaque`).
1456  //
1457  // XXX: This "state diff" is ad hoc: a synthetic change to unobserved state (e.g. only w_curswant)
1458  // counts as no-op. Extend this (or atom_key_class()) when such a case is reported...
1459  bool opaque = (keycls & kKeyOpaque) != 0;
1460  bool synthetic = (keycls & kKeySynthetic) != 0;
1461  bool unchanged = curbuf == old->origin.buf.br_buf && curwin == old->origin.win
1462                   && !atom_origin_moved(old->origin)
1463                   && !atom_origin_changed(old->origin)
1464                   && Visual.active == old->visual.active
1465                   && (!Visual.active
1466                       || (equalpos(old->visual.start, Visual.start)
1467                           && old->visual.mode == Visual.mode));
1468  if (opaque && unchanged
1469      // Ran child frames (:norm) during a Visual session; per-cursor semantics.
1470      && !(atom_visual_pending() && frame_id > old->id)
1471      // Operator atom? (non-edit Lua/<Cmd> 'operatorfunc'). #41482
1472      && root->redo_frame != old->id) {
1473    return false;
1474  }
1475  bool ins_cascaded = user && mc_ins_cascaded(root->id);
1476  // Command from a mapping's RHS (typed keys have KeyTyped set).
1477  bool mapped = user && !old->keytyped && !synthetic;
1478  if (mapped
1479      // NOT if cursor-global op (cascading per-cursor would be nonsense).
1480      && global_ops == old->global_ops
1481      // NOT if it ended in another buffer: a navigation mapping ("nnoremap <M-l> <C-w>l")
1482      // entering a buffer with cursors must not cascade.
1483      && ((curbuf == old->origin.buf.br_buf && atom_origin_changed(old->origin)) || ins_cascaded)) {
1484    map_edit = true;
1485  }
1486
1487  //
1488  // Visual session: open/continue/close, and decide if this command is one of its subatoms.
1489  //
1490  const bool child = is_child_frame();  // Session kept pending until resolved by enclosing frame.
1491  bool vis = false;
1492  if (Visual.active && !child) {
1493    if (!old->visual.active && vatom.frame <= old->id) {
1494      atom_visual_reset();
1495      vatom.state = kVatomFed;  // Promoted below if this frame is user input.
1496      vatom.origin = old->origin;
1497    }
1498    if (atom_visual_pending() && user && !synthetic && (old->keytyped || atom_composite_active())) {
1499      // Recalculated on every frame.
1500      vatom.state = (vatom.state & kVatomVoid) | kVatomTyped;
1501    }
1502    // Decided by the session (not atom_capturable()), so fed selections (":normal! vjd") still
1503    // accumulate for redo-prep. Recording/replay commands are meta (not part of the edit).
1504    vis = atom_visual_pending() && ca->cmdchar != 'Q' && ca->cmdchar != 'q';
1505    if (vis
1506        && (Visual.select
1507            || ((keycls & (kKeyScrollMove | kKeyScrollView | kKeyMouse)) && !unchanged))) {
1508      // Not replayable: Select-mode input; the selection moved by viewport-dependent keys.
1509      vatom.state |= kVatomVoid;
1510    }
1511  } else if (old->visual.active && !child) {
1512    CmdAtom own
1513      = atom_visual_pending() ? atom_from_frame(ca, root, old->visual.active) : (CmdAtom){ 0 };
1514    if (own.keys != NULL) {
1515      // This frame's children ended the session (":norm!" op in Lua mapping). #41956
1516      char *suffix = own.keys;
1517      own.keys = NULL;
1518      atom_free(&own);
1519      atom_visual_end_suffix(suffix, NULL, false);
1520    } else if (user && atom_visual_replayable() && kv_size(vatom.atoms) > 0) {
1521      // Cursor moved to selection-end after ESC/"v"-toggle. Even though this is technically
1522      // a "motion", it's more intuitive to always replay it? #41631
1523      char suffix[2] = { ESC, NUL };
1524      atom_visual_end_suffix(xstrdup(suffix), NULL, false);
1525    } else {
1526      atom_visual_end_suffix(NULL, NULL, false);  // Discards, or keeps for the user frame.
1527    }
1528  }
1529
1530  //
1531  // Capture: does this command own an atom?
1532  //
1533  if ((vis && vatom.frame <= old->id && atom_captures == old->captures
1534       && ca->oap->op_type == OP_NOP)
1535      || (!Visual.active
1536          && !old->visual.active
1537          && atom_capturable(old->consumers, old->keytyped)
1538          && atom_captures == old->captures
1539          && !atom_staged()
1540          && ca->oap->op_type == OP_NOP
1541          && stuff_empty()
1542          && !ins_cascaded)) {
1543    const size_t collected = kv_size(vatom.atoms);
1544    // KeyTyped survives stuffing but not macro playback; mapping/macro-fed commands are covered by
1545    // atom_composite_active().
1546    bool special_motion = (keycls & kKeyMotion) != 0;
1547    bool scroll_cmd = (keycls & (kKeyScrollMove | kKeyScrollView)) != 0;
1548    bool mouse_cmd = (keycls & kKeyMouse) != 0;
1549    bool jump_cmd = nv_is(ca->cmdchar, NV_JUMP) || (keycls & kKeyJump) != 0
1550                    // "[count]%" is absolute, unlike "%".
1551                    || (ca->cmdchar == '%' && ca->count0 > 0);
1552    // Replayable? Register prefix ('"x') is captured as part of the command it prefixes; "@x" is
1553    // a translation, its resolution is the atom stream.
1554    bool replayable = (ca->cmdchar > 0 && ca->cmdchar < 0x100
1555                       && ca->cmdchar != '"' && ca->cmdchar != '@' && !scroll_cmd)
1556                      || special_motion;
1557    bool changed = atom_origin_changed(old->origin);
1558    // Note: an operator's motion belongs to the operator (`finish_op`).
1559    bool motion = (nv_is(ca->cmdchar, NV_MOTION) || special_motion) && !changed
1560                  && !finish_op && !jump_cmd;
1561    // Beeped without moving (e.g. "j" on the last line).
1562    bool failed = did_beep != old->beeps && !atom_origin_moved(old->origin);
1563    // Mapping-internal motions are part of its recipe: queue them, the clock edge decides.
1564    bool follow = (mc_following() || mapped) && motion && !failed;
1565
1566    //
1567    // Route: decide the atom type and push it.
1568    //
1569    if (root->redo_frame == old->id && !mouse_cmd) {
1570      // Redoable edit ("dw", "p", "rX", "g@…"): this frame's redobuf defines the atom.
1571      CmdAtom atom = atom_from_redo(kAOperator);
1572      // The payload ('operatorfunc' getchar()) is not in the captured redo, append it.
1573      atom_payload_append(&atom, old);
1574
1575      // Cascade only an observable, non-global-op "effect": edit, register-write, or cursor-move
1576      // (only during follow-mode).
1577      bool effect = (changed || reg_max_ts(true) > old->reg_ts
1578                     || (mc_following() && atom_origin_moved(old->origin)))
1579                    && global_ops == old->global_ops;
1580      if (atom.keys != NULL && *atom.keys != NUL) {
1581        atom.origin = old->origin;
1582        atom_push(effect, &atom);
1583      } else {
1584        atom_free(&atom);
1585      }
1586    } else if (ca->searchbuf != NULL && (ca->cmdchar == '/' || ca->cmdchar == '?')
1587               && !(vis && unchanged)) {
1588      // Payload typed in search cmdline ("/pat<CR>"). Emit-only. Not if pattern was not found.
1589      CmdAtom atom = atom_from_cmdline(kAMotion, ca, ca->searchbuf, old->visual.active);
1590      atom.origin = old->origin;
1591      atom_push(false, &atom);
1592    } else if (root->cmdline != NULL && (ca->cmdchar == ':' || ca->cmdchar == K_COMMAND)) {
1593      // Same for ":cnext<CR>" or "<Cmd>cnext<CR>".
1594      CmdAtom atom = atom_from_cmdline(kAExcmd, ca, root->cmdline, old->visual.active);
1595      // Payload read during the cmdline execution (`ds)` getchar() => ")").
1596      atom_payload_append(&atom, old);
1597      atom.origin = old->origin;
1598      atom_push(false, &atom);
1599    } else if (vis && ca->cmdchar == K_LUA) {
1600      // Lua mapping moved the selection. Ignore subatoms, use use atom_from_frame() instead. #41956
1601      CmdAtom atom = atom_from_frame(ca, root, old->visual.active);
1602      atom.origin = old->origin;
1603      atom_push(false, &atom);
1604    } else if (replayable && (!vis || ((keycls & kKeyPayload) == 0 && !failed))) {
1605      // Non-redoable command (u, zz, q=): never cascaded as an edit.
1606      CmdSpec spec = atom_cmd_spec(ca);
1607      if (vis) {
1608        // Omit `regname`: would prefix '"x' to every command collected; op-end re-adds it later.
1609        spec.regname = 0;
1610      }
1611      CmdAtom atom = atom_from_spec(motion ? kAMotion : jump_cmd ? kAJump : kANormal, spec);
1612      atom.origin = old->origin;
1613      atom_push(follow, &atom);
1614      if (jump_cmd && atom_composite_active()) {
1615        composite.queued = true;  // Do not LHS-replay a mapped jump ("nnoremap <Down> ]C").
1616      }
1617    } else if ((scroll_cmd || mouse_cmd) && !atom_composite_active()) {
1618      // Emit-only (viewport-dependent).
1619      CmdSpec spec = atom_cmd_spec(ca);
1620      if (IS_SPECIAL(ca->cmdchar)) {
1621        // Wheel/mouse count is never typed: do_mousescroll() wrote its internal step there.
1622        spec.count = 0;
1623      }
1624      CmdAtom atom = atom_from_spec(scroll_cmd ? kAScroll : kAMouse, spec);
1625      atom.origin = old->origin;
1626      atom_push(false, &atom);
1627    }
1628    if (vis && kv_size(vatom.atoms) == collected && !unchanged) {
1629      // Not replayable: moved the selection by non-captured keys (mouse), or by API.
1630      vatom.state |= kVatomVoid;
1631    }
1632  }
1633
1634  if (vis && (curbuf != old->origin.buf.br_buf
1635              || (atom_origin_changed(old->origin) && vatom.frame != old->id))) {
1636    // Not replayable: edited during visual, and this frame pushed no subatom describing it.
1637    vatom.state |= kVatomVoid;
1638  }
1639  atom_visual_span_flush();
1640
1641  return Visual.active && user && old->parent == NULL;
1642}
1643
1644/// Completes a normal_execute(): captures its atom, pushes its staged one, ends the composite.
1645/// Pops the frame.
1646void atom_cmd_end(cmdarg_T *ca, CmdFrame *old)
1647{
1648  if (composite.follow == kNone && !mc_replaying()
1649      && (atom_origin_moved(old->origin) || nv_is(ca->cmdchar, NV_MOTION))) {
1650    // First motion (or cursor-move, e.g. API) of the atom; innermost frame wins.
1651    composite.follow = old->follow ? kTrue : kFalse;
1652  }
1653  const bool refresh_visual = atom_capture_cmd(ca, old);
1654  atom_stage_flush(old);
1655  if (atom_composite_active() && old->payload_start != SIZE_MAX
1656      && old->payload_end > old->payload_start) {
1657    // An eval-read payload with no capturing atom (Lua mapping's getchar()).
1658    composite.lossy = true;
1659  }
1660
1661  // The clock edge. Only at toplevel: cascading from a nested normal_execute() would recurse.
1662  // Deferred while a mapping executes (keys in typebuf), so its commands collapse as one unit;
1663  // likewise while stuffed keys are pending (i_CTRL-O dance, or exec_stuffed() deferred under
1664  // textlock).
1665  if (old->parent == NULL && !mc_replaying() && typebuf_typed() && stuff_empty()) {
1666    bool map_moved = atom_composite_active() && atom_origin_moved(composite.origin);
1667    mc_clock_edge(map_edit, map_moved, composite.follow == kTrue);
1668
1669    map_edit = false;
1670    // One atom spans its continuation: while op-pending, selection-active, or insert-will-resume
1671    // (i_CTRL-O), it stays open. ",Dw" (":nnoremap ,D d") is one atom, `keys="dw"`.
1672    if (ca->oap->op_type == OP_NOP && !Visual.active && restart_edit == 0) {
1673      atom_composite_end();
1674      composite.open = false;  // Resolved.
1675    }
1676  }
1677  if (refresh_visual) {
1678    mc_vsel_refresh();
1679  }
1680  XFREE_CLEAR(old->cmdline);
1681  cur_frame = old->parent;
1682}