robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 71bool active ;///< Collecting subatoms. If false but `lhs` is set, collecting was deferred. 72bool open ;///< User action is in progress: set by its first toplevel cmd (frame). 73CmdOrigin origin ;///< State at the atom's start. 74TriState follow ;///< `CmdFrame.follow` at the atom's first motion (`kNone`: none yet). 75CmdAtomVec atoms ;///< Subatoms of the mapping/macro. 76char lhs [MAXMAPLEN + 4 ];///< Label: mapping LHS, macro "@x", or :omap's op+LHS. "": none. 77bool queued ;///< Subatom queued for cascade (`g_atoms`, or Visual), global op (undo), or 78///< jump. No LHS-replay needed. 79bool lossy ;///< Detected partial capture: `keys` cannot replay it, `lhs` can. 80///< When: incomplete insert, payload with no capturing atom. 81bool macro ;///< Macro execution: captured as an "@x"-labeled atom. 82uint64_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 { 88kVatomNone = 0 ,///< No pending Visual atom. 89 90// Kind: 91kVatomTyped = 1 ,///< User input (typed, or mapping/macro): emit/cascade. 92kVatomFed = 2 ,///< Non-user input (programmatic). See `atom_visual_typed`. 93 94kVatomVoid = 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 { 108CmdAtomVec atoms ;///< Accumulated subatoms. A void session collects them as the `lhs` label. 109VatomState state ; 110CmdOrigin origin ;///< State at session start (before the "v"). 111uint64_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). 113size_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 { 119kvec_t (uint8_t )keys ; 120size_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{ 141assert (cur_frame != NULL ); 142CmdFrame * frame = cur_frame ; 143while (frame -> parent != NULL ) { 144frame = frame -> parent ; 145 } 146return 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{ 153if (cur_frame == NULL || cur_frame -> parent == NULL ) { 154return false; 155 } 156const CmdFrame * root = root_frame (); 157// Excludes stuffed keys ("." payload, "x" => "dl"), they are already resolved. 158const bool fed = cur_frame -> ex_normal > root -> ex_normal ; 159// Excludes keys fed from K_EVENT (RPC/timer): no enclosing cmd. 160return fed && !(root -> keyclass & kKeySynthetic ); 161} 162 163/// Frees a CmdAtom's allocated members. 164void atom_free (CmdAtom * atom ) 165{ 166XFREE_CLEAR (atom -> keys ); 167XFREE_CLEAR (atom -> text ); 168XFREE_CLEAR (atom -> lhs ); 169atoms_free (& atom -> atoms ); 170kv_destroy (atom -> atoms ); 171} 172 173/// Frees and removes all atoms in `v` (keeps the vector's storage). 174void atoms_free (CmdAtomVec * v ) 175{ 176while (kv_size (* v )> 0 ) { 177CmdAtom atom = kv_pop (* v ); 178atom_free (& atom ); 179 } 180} 181 182#ifdef EXITFREE 183void atom_free_all (void ) 184{ 185atoms_free (& g_atoms ); 186kv_destroy (g_atoms ); 187// A mid-command exit (e.g. ":qa!" from an option-expr) leaves live frames with staged atoms. 188for (CmdFrame * frame = cur_frame ;frame != NULL ;frame = frame -> parent ) { 189atom_free (& frame -> staged ); 190XFREE_CLEAR (frame -> cmdline ); 191 } 192atom_composite_abort (); 193kv_destroy (composite .atoms ); 194kv_destroy (typed .keys ); 195atoms_free (& vatom .atoms ); 196kv_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"). 204bool operand = nv_is (cap -> cmdchar ,NV_LANG |NV_NCH_ARG ); 205return (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{ 217CmdOrigin 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 ) }; 220set_bufref (& origin .buf ,curbuf ); 221return origin ; 222} 223 224/// True if the buffer was edited. False if the buf disappeared. 225static bool atom_origin_changed (CmdOrigin origin ) 226{ 227return 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{ 233return 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{ 241return 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{ 247CmdOrigin o = composite .origin ; 248if (composite .open && o .buf .br_buf == buf && bufref_valid (& o .buf ) 249&& buf_get_changedtick (buf )== o .tick ) { 250return o .pos ; 251 } 252return 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{ 259assert (!mc_replaying ());// Captured material is never re-captured. 260char * keys = redo_keys (& spec ).data ; 261assert (keys != NULL );// A spec with no chars/count/reg composes to nothing. 262return keys ; 263} 264 265/// Gets the pending change as a CmdAtom. Caller owns `keys`. 266static CmdAtom atom_from_redo (CmdAtomType type ) 267{ 268String keys = redo_keys (NULL ); 269return (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{ 275return (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{ 284StringBuilder sb = KV_INITIAL_VALUE ; 285if (ca -> cmdchar != ':' && ca -> count0 != 0 ) { 286// Not for ":", its count already prefilled (":.,.+1"). But "<Cmd>" needs count in the keys. 287kv_printf (sb ,"%d" ,ca -> count0 ); 288 } 289sb_add_char (& sb ,ca -> cmdchar ); 290if (vis && ca -> cmdchar == ':' ) { 291sb_add_char (& sb ,Ctrl_U );// Clear the "'<,'>" prefill. 292 } 293if (IS_SPECIAL (ca -> cmdchar )) { 294sb_add_spec (& sb ,cmdline );// <Cmd> text, Lua mapping-id. 295 }else { 296sb_add_lit (& sb ,cmdline ,-1 );// Typed cmdline (":", "/"), interprets CTRL-V. 297 } 298sb_add_char (& sb ,NL ); 299kv_push (sb ,NUL ); 300return (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{ 311if (root -> cmdline != NULL && (ca -> cmdchar == ':' || ca -> cmdchar == K_COMMAND )) { 312return atom_from_cmdline (kAExcmd ,ca ,root -> cmdline ,vis ); 313 } 314if (ca -> cmdchar == K_LUA ) { 315char lua_id [NUMBUFLEN ]; 316// XXX: grabs LAST luamap; latent bug if "nested" (Lua mapping calls another via ":norm")... 317snprintf (lua_id ,sizeof (lua_id ),"%d" ,repeat_luamap ); 318return atom_from_cmdline (kANormal ,ca ,lua_id ,vis ); 319 } 320return (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{ 329StringBuilder keys = KV_INITIAL_VALUE ; 330for (size_t i = from ;i < kv_size (atoms );i ++ ) { 331kv_concat (keys ,kv_A (atoms ,i ).keys ); 332 } 333size_t len = kv_size (keys ); 334kv_push (keys ,NUL ); 335return (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{ 341if (c == NUL || c == K_LUA ) { 342return xstrdup ("" ); 343 } 344if (IS_SPECIAL (c )|| c < ' ' ) { 345// Covers <Tab>/<NL>/<CR>/<Esc> and the controls (as "<C-A>"). 346return xstrdup (get_special_key_name (c ,0 )); 347 } 348if (c == DEL ) { 349return xstrdup ("<Del>" );// key_names_table has K_DEL, not the ASCII byte. 350 } 351char buf [MB_MAXBYTES + 1 ]; 352buf [utf_char2bytes (c ,buf )]= NUL ; 353return xstrdup (buf ); 354} 355 356/// Gets an atom's (allocated) event-data. 357static Dict atom_dict (const CmdAtom * atom ) 358{ 359const CmdSpec * spec = & atom -> spec ; 360char regname [2 ]= { (char )spec -> regname ,NUL }; 361const 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). 364char * op = atom_key_name (spec -> op ); 365if (spec -> op_extra != NUL ) { 366char * extra = atom_key_name (spec -> op_extra ); 367op = xrealloc (op ,strlen (op )+ strlen (extra )+ 1 ); 368strcat (op ,extra ); 369xfree (extra ); 370 } 371char * cmd = atom_key_name (spec -> cmd ); 372if (spec -> cmd2 != NUL ) { 373// Two-char command name ("gJ", "iw", "gn"): compose it. 374char * cmd2 = atom_key_name (spec -> cmd2 ); 375cmd = xrealloc (cmd ,strlen (cmd )+ strlen (cmd2 )+ 1 ); 376strcat (cmd ,cmd2 ); 377xfree (cmd2 ); 378 } 379// Inapplicable fields are OMITTED, not defaulted. 380Dict d = ARRAY_DICT_INIT ; 381char * cmdarg = atom_key_name (spec -> cmdarg ); 382if (cmdarg != NULL && * cmdarg != NUL ) { 383PUT (d ,"cmdarg" ,CSTR_AS_OBJ (cmdarg )); 384 }else { 385xfree (cmdarg ); 386 } 387PUT (d ,"changed" ,BOOLEAN_OBJ (atom -> changed )); 388if (* cmd != NUL ) { 389PUT (d ,"cmd" ,CSTR_AS_OBJ (cmd )); 390 }else { 391xfree (cmd ); 392 } 393if (spec -> count > 0 ) { 394PUT (d ,"count" ,INTEGER_OBJ (spec -> count )); 395 } 396// Note: origin is undefined for an insert-session span, its cursor effect is undefined. 397if (atom -> origin .pos .lnum > 0 ) { 398PUT (d ,"moved" ,BOOLEAN_OBJ (atom -> moved )); 399Array pos = ARRAY_DICT_INIT ; 400ADD (pos ,INTEGER_OBJ (atom -> origin .pos .lnum )); 401ADD (pos ,INTEGER_OBJ (atom -> origin .pos .col )); 402PUT (d ,"pos" ,ARRAY_OBJ (pos )); 403PUT (d ,"undoseq" ,INTEGER_OBJ (atom -> undoseq )); 404 } 405// keys/lhs are RAW bytes (typeahead encoding). 406const char * keys = atom -> keys != NULL ?atom -> keys :"" ; 407if (!atom -> remap ) { 408PUT (d ,"keys" ,CSTR_TO_OBJ (keys )); 409 } 410PUT (d ,"lhs" ,CSTR_TO_OBJ (atom -> lhs != NULL && * atom -> lhs != NUL ?atom -> lhs :keys )); 411if (* force != NUL ) { 412PUT (d ,"motionforce" ,CSTR_TO_OBJ (force )); 413 } 414if (* op != NUL ) { 415PUT (d ,"operator" ,CSTR_AS_OBJ (op )); 416 }else { 417xfree (op ); 418 } 419if (spec -> regname != 0 ) { 420PUT (d ,"reg" ,CSTR_TO_OBJ (regname )); 421 } 422if (atom -> text != NULL && * atom -> text != NUL ) { 423PUT (d ,"text" ,CSTR_TO_OBJ (atom -> text )); 424 } 425PUT (d ,"type" ,CSTR_TO_OBJ (type_names [atom -> type ])); 426return d ; 427} 428 429/// Schedules a CmdAtom event. 430static void atom_emit (const CmdAtom * atom ) 431{ 432if (!has_event (EVENT_CMDATOM )) { 433return ; 434 } 435Dict data = atom_dict (atom ); 436if (kv_size (atom -> atoms )> 0 ) { 437Array atoms = ARRAY_DICT_INIT ; 438for (size_t i = 0 ;i < kv_size (atom -> atoms );i ++ ) { 439ADD (atoms ,DICT_OBJ (atom_dict (& kv_A (atom -> atoms ,i )))); 440 } 441PUT (data ,"atoms" ,ARRAY_OBJ (atoms )); 442 } 443buf_T * buf = atom -> origin .buf .br_buf != NULL ?atom -> origin .buf .br_buf :curbuf ; 444aucmd_defer (EVENT_CMDATOM , (char * )type_names [atom -> type ],NULL ,AUGROUP_ALL ,buf ,NULL , 445& DICT_OBJ (data )); 446api_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{ 457assert (atom -> keys != NULL ); 458if (atom -> origin .buf .br_buf != NULL ) { 459// Calculated here, from the atom's own baseline. 460atom -> changed = atom_origin_changed (atom -> origin ); 461atom -> moved = atom_origin_moved (atom -> origin ); 462atom -> 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. 466const bool collect = composite .active 467&& (cur_frame == NULL || cur_frame -> id != composite .frame ); 468if (atom_visual_pending ()) { 469if (vatom .state & kVatomTyped ) { 470// Not for kVatomFed: redo-prep must not mark the enclosing span as captured. 471atom_captures ++ ; 472 } 473if (collect ) { 474composite .queued = true; 475 } 476kv_push (vatom .atoms ,* atom ); 477vatom .frame = cur_frame != NULL ?cur_frame -> id :0 ; 478return ; 479 } 480atom_captures ++ ; 481if (atom -> type == kAVisual && kv_size (atom -> atoms )> 0 ) { 482// The completing operator is the only subatom that could have edited. 483CmdAtom * last = & kv_A (atom -> atoms ,kv_size (atom -> atoms )- 1 ); 484if (last -> type == kAOperator ) { 485last -> changed = atom -> changed ; 486 } 487 } 488if (cascade ) { 489CmdAtom copy = * atom ; 490copy .keys = xstrdup (atom -> keys ); 491copy .text = NULL ;// replay (mc_execute()) reads only type/keys/remap: not the text, 492copy .lhs = NULL ;// nor the label, 493copy .atoms = (CmdAtomVec )KV_INITIAL_VALUE ;// nor the decomposition 494kv_push (g_atoms ,copy ); 495if (collect ) { 496composite .queued = true; 497 } 498 } 499if (collect ) { 500kv_push (composite .atoms ,* atom ); 501 }else { 502if (atom -> type != kAInsertSpan ) { 503// Spans are cascade-internal; only emit the whole session (kAInsert). 504atom_emit (atom ); 505 } 506atom_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{ 514if (atom_blocked ()) { 515atom_free (atom ); 516return ; 517 } 518atom_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{ 525assert (cur_frame != NULL ); 526assert (!atom_staged ());// One stage per frame: a second would discard a captured command. 527atom_free (& cur_frame -> staged ); 528if (atom_blocked ()) { 529// Now, not at flush: drop the atom of an internal operator (atom_suppress()). 530atom_free (atom ); 531return ; 532 } 533assert (atom -> keys != NULL ); 534cur_frame -> staged = * atom ; 535} 536 537/// True if an atom is staged for the current command (frame). 538static bool atom_staged (void ) 539{ 540return 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{ 546if (frame -> staged .keys == NULL ) { 547return ; 548 } 549// Staged cmds are edits: cascade. Except if no keys (void Visual), already-cascaded as spans, or 550// a global op ("zq"). 551bool cascade = * frame -> staged .keys != NUL && !frame -> staged .cascaded 552&& global_ops == frame -> global_ops ; 553atom_push (cascade ,& frame -> staged ); 554frame -> 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{ 561StringBuilder keys = KV_INITIAL_VALUE ; 562kv_concat (keys ,composite .lhs ); 563kv_concat_len (keys , (char * )typed .keys .items + typed .map_start , 564kv_size (typed .keys )- typed .map_start ); 565kv_push (keys ,NUL ); 566return keys .items ; 567} 568 569/// Queues an internal-only (no emit) atom for mcursor cascade. 570void atom_lhs_replay_queue (void ) 571{ 572kv_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{ 579return composite .queued ; 580} 581 582/// True while a composite is collecting subatoms. 583bool atom_composite_active (void ) 584{ 585return 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{ 591len = MIN (len ,sizeof (composite .lhs )- 1 ); 592memcpy (composite .lhs ,lhs ,len ); 593composite .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{ 602if (lhs != NULL ) { 603atom_composite_label (lhs ,len ); 604 } 605composite .active = true; 606composite .queued = false; 607composite .lossy = false; 608composite .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{ 617composite .macro = false;// "@x" capture ends with its composite. 618if (!composite .active ) { 619return ; 620 } 621// LHS-replay when the capture is lossy, or captured nothing (Ex/Lua edits). 622const bool remap = composite .lossy || kv_size (composite .atoms )== 0 ; 623char * lhs = atom_composite_lhs (); 624composite .lhs [0 ]= NUL ; 625composite .active = false; 626CmdAtom atom ; 627if (kv_size (composite .atoms )== 1 ) { 628// Single subatom (simple mapping). "Unwrap" it: a motion mapping reports kAMotion, not kAComp. 629atom = kv_pop (composite .atoms ); 630xfree (atom .lhs ); 631atom .lhs = lhs ; 632atom .remap = remap ; 633 }else { 634// Zero subatoms (captured nothing (Ex/Lua, no-op); still a user action, identified by `lhs`), 635// or multiple subatoms. 636atom = (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 ) }; 641atom .atoms = composite .atoms ;// Subatoms. 642composite .atoms = (CmdAtomVec )KV_INITIAL_VALUE ;// Reset. 643 } 644atom_emit (& atom ); 645atom_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{ 652composite .macro = false; 653composite .lhs [0 ]= NUL ; 654composite .active = false; 655atoms_free (& composite .atoms ); 656composite .open = false; 657} 658 659/// Entering :terminal mode resolves (ends) the pending atom. Terminal keys are never captured. 660void atom_term_enter (void ) 661{ 662if (!mc_replaying ()) { 663atom_composite_end (); 664composite .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"). 673return !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"). 684return KeyTyped || (atom_is_user_cmd ()&& atom_composite_active ()); 685} 686 687/// Suppresses atom pushes. For internal operators. 688void atom_suppress (bool suppress ) 689{ 690atom_suppressed = suppress ; 691} 692 693/// Block atom pushes if: cascade in-progress, or internal op is executing. 694static bool atom_blocked (void ) 695{ 696return mc_replaying ()|| atom_suppressed ; 697} 698 699/// Decides if the command is capturable. 700static bool atom_capturable (bool consumers ,bool keytyped ) 701{ 702return 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{ 708return 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{ 716switch (cmd ) { 717case K_EVENT : 718case K_IGNORE : 719return kKeyOpaque |kKeySynthetic ; 720case K_COMMAND : 721case K_LUA : 722return kKeyOpaque ; 723case '/' : 724case '?' : 725case ':' : 726case '!' : 727return kKeyPayload ; 728case Ctrl_D : 729case Ctrl_U : 730return kKeyScrollMove |kKeyInsFlush ; 731case Ctrl_F : 732case Ctrl_B : 733return kKeyScrollMove ; 734case Ctrl_E : 735case Ctrl_Y : 736return kKeyScrollView ; 737case Ctrl_T : 738return kKeyInsFlush ; 739// Multiplexed: one nv_cmds entry => many commands. Classified by char 2, not NV_MOTION/…. 740case 'g' : 741if (arg == '\'' || arg == '`' ) { 742return atom_key_class (arg ,arg2 ,NUL );// "g'x", "g`x": like "'x", "`x". 743 } 744if (strchr (";,go" ,arg )!= NULL ) { 745return kKeyJump ; 746 } 747return strchr ("jk0^$_meEM*#" ,arg )!= NULL ?kKeyMotion :0 ; 748case '[' : 749case ']' : 750if (arg == 'C' ) { 751return kKeyJump ;// "]C"/"[C": jump to the next/previous cursor 752 } 753return strchr ("[](){}mMcsz#*/" ,arg )!= NULL ?kKeyMotion :0 ; 754case 'z' : 755return (arg == 'j' || arg == 'k' ) ?kKeyMotion :0 ; 756case '\'' : 757case '`' : 758// kCtxVisual|kCtxMarks and '( '{ etc. are cursor-relative; others are absolute. 759return arg != NUL && strchr ("<>[].^(){}" ,arg )!= NULL ?kKeyMotion :kKeyJump ; 760case K_DOWN : 761case K_END : 762case K_HOME : 763case K_LEFT : 764case K_RIGHT : 765case K_UP : 766return kKeyMotion |kKeyInsFlush ; 767case Ctrl_G : 768case Ctrl_H : 769case Ctrl_R :// "<C-R>x" (insert_reg()): reads per-cursor registers. 770case Ctrl_W : 771case K_BS : 772case K_DEL : 773case K_S_LEFT : 774case K_S_RIGHT : 775return kKeyInsFlush ; 776case K_LEFTMOUSE : 777case K_LEFTMOUSE_NM : 778case K_MIDDLEMOUSE : 779case K_RIGHTMOUSE : 780case K_X1MOUSE : 781case K_X2MOUSE : 782return kKeyMouse ; 783case K_MOUSEDOWN :// <ScrollWheelUp> 784case K_MOUSEUP :// <ScrollWheelDown> 785case K_MOUSELEFT : 786case K_MOUSERIGHT : 787return kKeyScrollView ; 788default : 789return 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). 798if (cur_frame == NULL || !atom_is_user_cmd ()|| (firstc != ':' && firstc != K_COMMAND )) { 799return ; 800 } 801CmdFrame * root = root_frame (); 802// The first accept is the payload, not a second one (":put ." => ":put _" translation). 803if (root -> cmdline == NULL ) { 804root -> 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{ 811return 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{ 818if (expr_map_lock == 0 // Do not append input read during expr EVALUATION. 819&& cur_frame != NULL && cur_frame -> payload_start == SIZE_MAX && !mc_replaying ()) { 820cur_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{ 827if (expr_map_lock == 0 && cur_frame != NULL && cur_frame -> payload_start != SIZE_MAX 828&& !mc_replaying ()) { 829cur_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{ 836size_t plen = frame -> payload_start == SIZE_MAX ?0 :frame -> payload_end - frame -> payload_start ; 837if (plen == 0 || atom -> keys == NULL ) { 838return ; 839 } 840size_t klen = strlen (atom -> keys ); 841atom -> keys = xrealloc (atom -> keys ,klen + plen + 1 ); 842memcpy (atom -> keys + klen ,typed .keys .items + frame -> payload_start ,plen ); 843atom -> keys [klen + plen ]= NUL ; 844frame -> 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{ 850if (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 ) { 853return ; 854 } 855if (len == 3 && chars [0 ]== K_SPECIAL 856&& (atom_key_class (TERMCAP2KEY (chars [1 ],chars [2 ]),NUL ,NUL )& kKeySynthetic )) { 857return ;// Not user input: K_IGNORE from a mapping resolved during peek/K_EVENT/… 858 } 859for (size_t i = 0 ;i < len ;i ++ ) { 860kv_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{ 868if (mc_replaying ()|| !atom_typed_collecting ()) { 869return ; 870 } 871kv_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{ 877if (!mc_replaying ()) { 878global_ops ++ ; 879composite .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{ 886if (mc_replaying ()) { 887return ; 888 } 889for (CmdFrame * frame = cur_frame ;frame != NULL ;frame = frame -> parent ) { 890if (!atom_origin_moved (frame -> origin )) { 891frame -> follow = mc_following (); 892 }else if (composite .follow == kNone ) { 893composite .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{ 901if (atom_is_user_cmd ()) { 902root_frame ()-> redo_frame = cur_frame -> id ; 903 } 904} 905 906/// Redo-prep was canceled (aborted operation). 907void atom_redo_cancel (void ) 908{ 909root_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{ 915if (atom_is_user_input ()) { 916composite .macro = true; 917if (!atom_composite_active ()) { 918// The macro's commands collapse into one "@x"-labeled atom. 919char lhs [3 ]= {'@' , (char )regname ,NUL }; 920atom_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"). 929if (mc_replaying ()|| atom_composite_active ()|| !atom_is_user_input ()) { 930return ; 931 } 932char * lhs = atom_redo_keys (atom_cmd_spec (cap )); 933atom_composite_start (lhs ,strlen (lhs )); 934xfree (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{ 942if (mc_replaying ()|| reg_executing != 0 || ex_normal_busy != 0 ) { 943return ; 944 } 945if (!(State & MODE_NORMAL )) { 946// Label the (potential, deferred) composite but don't start collecting (!MODE_NORMAL). 947atom_composite_label (lhs ,len ); 948return ; 949 } 950if (atom_composite_active ()) { 951if (get_real_state ()== MODE_OP_PENDING ) { 952// The pending operator's own composite ("gr" <expr> mapping => "g@") absorbs its operand. 953return ; 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. 957typed .map_start = kv_size (typed .keys ); 958atom_composite_end (); 959 } 960const char * op = get_vim_var_str (VV_OP );// v:operator 961if (get_real_state ()== MODE_OP_PENDING && * op != NUL ) { 962// Op-pending mapping (:omap) continues the operator (vim-sneak "dz(b"). 963assert (lhs [len ]== NUL ); 964char * full = concat_str (op ,lhs ); 965atom_composite_start (full ,strlen (full )); 966xfree (full ); 967typed .map_start = kv_size (typed .keys ); 968return ; 969 } 970atom_composite_start (lhs ,len ); 971if (peeked && cur_frame != NULL ) { 972composite .frame = cur_frame -> id ; 973 } 974typed .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{ 981vatom .state = kVatomNone ; 982atoms_free (& vatom .atoms ); 983vatom .origin = (CmdOrigin ){0 }; 984vatom .frame = 0 ; 985vatom .done = 0 ; 986mc_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{ 992return 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{ 998return 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{ 1005return 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{ 1011if (!atom_visual_replayable ()) { 1012return false; 1013 } 1014for (size_t i = 0 ;i < kv_size (vatom .atoms );i ++ ) { 1015const CmdSpec spec = kv_A (vatom .atoms ,i ).spec ; 1016if (spec .cmd == 'g' && spec .cmd2 == 'v' ) { 1017return false;// Found "gv" subatom. 1018 } 1019 } 1020return 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{ 1027if (!atom_visual_replayable ()) { 1028return (String )STRING_INIT ; 1029 } 1030String tail = atoms_concat_keys (vatom .atoms ,vatom .done ); 1031if (vatom .done == 0 ) { 1032return tail ; 1033 } 1034 1035// Prefix with "gv". 1036StringBuilder keys = KV_INITIAL_VALUE ; 1037kv_concat (keys ,"gv" ); 1038kv_concat_len (keys ,tail .data ,tail .size ); 1039size_t len = kv_size (keys ); 1040kv_push (keys ,NUL ); 1041api_free_string (tail ); 1042return (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{ 1051if (vatom .done >=kv_size (vatom .atoms )|| !atom_visual_replayable ()|| !atom_visual_typed () 1052|| !mc_buf_has_cursors (curbuf )) { 1053return ; 1054 } 1055bool edited = false; 1056for (size_t i = vatom .done ;i < kv_size (vatom .atoms );i ++ ) { 1057assert (kv_A (vatom .atoms ,i ).type != kAOperator );// Only atom_push_raw() computes `changed`. 1058edited |=kv_A (vatom .atoms ,i ).changed ; 1059 } 1060if (!edited ) { 1061return ; 1062 } 1063String span = atom_visual_span (); 1064vatom .done = kv_size (vatom .atoms ); 1065kv_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{ 1077if (mc_replaying ()|| atom_suppressed ) {// Replay, or internal op applied during another cmd. 1078xfree (suffix ); 1079return false; 1080 } 1081const CmdOrigin origin = vatom .origin ;// atom_visual_reset() clears the session. 1082const bool replayable = suffix != NULL && atom_visual_replayable (); 1083String 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. 1086const bool prepped = redoable && spec != NULL && suffix != NULL 1087&& (replayable || spec -> op != NUL ); 1088 1089if (prepped ) { 1090const bool redo_keys = atom_visual_redoable (); 1091prep_redo_visual (redo_keys ?v .data :"1v" ,redo_keys ?v .size :2 , (CmdSpec ){0 }); 1092redo_append_str (suffix ,-1 ); 1093 } 1094 1095if (is_child_frame ()) { 1096xfree (v .data ); 1097xfree (suffix ); 1098// Keep the session pending (no atom_visual_reset()), let the enclosing frame resolve it. #41956 1099return prepped ; 1100 } 1101 1102if (!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()). 1105bool emit = (vatom .state & kVatomVoid )&& atom_visual_typed ()&& spec != NULL 1106&& suffix != NULL && atom_is_user_cmd (); 1107char * label = NULL ; 1108if (emit ) { 1109String collected = atoms_concat_keys (vatom .atoms ,0 ); 1110label = xrealloc (collected .data ,collected .size + strlen (suffix )+ 1 ); 1111STRCPY (label + collected .size ,suffix ); 1112 } 1113xfree (suffix ); 1114atom_visual_reset ();// End the session before staging. 1115if (emit ) { 1116atom_stage_set (& (CmdAtom ){ .type = kAVisual , .spec = * spec , .keys = xstrdup ("" ), 1117 .lhs = label , .origin = origin }); 1118 } 1119return prepped ; 1120 } 1121 1122if (!atom_is_user_cmd ()|| !atom_visual_typed ()) { 1123// Internal input (":norm! vjd", fed keys): the redo prep above is the only effect; no emit. 1124xfree (v .data ); 1125xfree (suffix ); 1126atom_visual_reset (); 1127return prepped ; 1128 } 1129 1130// 1131// Typed, replayable session: stage its Visual atom. Ends the session. 1132// 1133char * keys = xrealloc (v .data ,v .size + strlen (suffix )+ 1 ); 1134STRCPY (keys + v .size ,suffix ); 1135CmdAtom 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 }; 1143if (spec != NULL ) { 1144kv_push (vatom .atoms , ((CmdAtom ){ .type = kAOperator , .spec = * spec , .keys = suffix , 1145 .origin = cur_frame -> origin })); 1146 }else { 1147xfree (suffix ); 1148 } 1149atom .cascaded = vatom .done > 0 ; 1150if (atom .cascaded && vatom .done < kv_size (vatom .atoms )) { 1151// Spans cascaded the selection's edits. This last one completes it (the operator). 1152String span = atom_visual_span (); 1153kv_push (g_atoms , ((CmdAtom ){ .type = kAVisualSpan , .keys = span .data , .origin = origin })); 1154 } 1155atom .atoms = vatom .atoms ; 1156vatom .atoms = (CmdAtomVec )KV_INITIAL_VALUE ; 1157atom_visual_reset (); 1158atom_stage_set (& atom ); 1159return 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{ 1167if (mc_replaying ()) { 1168return false; 1169 } 1170return 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{ 1184const bool redoable = op_redoable (oap -> op_type ,redo_yank ); 1185bool ins_op = oap -> op_type == OP_CHANGE || oap -> op_type == OP_INSERT 1186|| oap -> op_type == OP_APPEND ; 1187bool payload_motion = cap -> cmdchar >=0x100 1188|| (cap -> cmdchar != NUL && strchr ("/?:!" ,cap -> cmdchar )!= NULL ); 1189bool excmd = cap -> cmdchar == ':' || cap -> cmdchar == K_COMMAND ; 1190if (!ins_op && !payload_motion ) { 1191bool prep_exempt = !redoable || cap -> cmdchar == 'D' ; 1192CmdSpec 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 }; 1196if (prep_exempt && (!Visual .active || oap -> motion_force )) { 1197// Only capture _user_ input. 1198if (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"). 1200bool operand = nv_is (cap -> cmdchar ,NV_LANG |NV_NCH_ARG ); 1201spec .motion_force = oap -> motion_force ; 1202spec .cmd = cap -> cmdchar ; 1203spec .cmd2 = operand ?NUL :cap -> nchar ; 1204spec .cmdarg = operand ?cap -> nchar :NUL ; 1205CmdAtom op_atom = atom_from_spec (kAOperator ,spec ); 1206op_atom .origin = cur_frame -> origin ; 1207atom_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. 1214char suffix [4 ]= {'r' ,Ctrl_V ,cap -> nchar == REPLACE_CR_NCHAR ?CAR :NL ,NUL }; 1215atom_visual_end_suffix (xstrdup (suffix ),& spec ,redoable ); 1216 }else { 1217// Visual-mode op: complete the accumulated visual atom with the operator keys. 1218spec .cmdarg = oap -> op_type == OP_REPLACE ?cap -> nchar :NUL ; 1219if ((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. 1221spec .op_extra = spec .op ; 1222spec .op = 'g' ; 1223 } 1224atom_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"). 1230if (redoable && cap -> cmdchar != 'D' 1231&& ((!Visual .active || oap -> motion_force ) 1232// Also redo Operator-pending Visual mode mappings. 1233|| excmd || cap -> cmdchar == K_LUA )) { 1234prep_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 }); 1239if (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. 1242if (vim_strchr (p_cpo ,kCpoRedo )== NULL ) { 1243redo_append_lit (cap -> searchbuf ,-1 ); 1244 } 1245redo_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. 1249if (repeat_cmdline == NULL ) { 1250redo_new ((CmdSpec ){0 }); 1251 }else { 1252if (cap -> cmdchar == ':' ) { 1253redo_append_lit (repeat_cmdline ,-1 ); 1254 }else { 1255redo_append_spec (repeat_cmdline ); 1256 } 1257redo_append_str (S_LEN (NL_STR )); 1258XFREE_CLEAR (repeat_cmdline ); 1259 } 1260 }else if (cap -> cmdchar == K_LUA ) { 1261char lua_id [NUMBUFLEN ]; 1262redo_append_str (lua_id ,snprintf (lua_id ,sizeof (lua_id ),"%d" ,repeat_luamap )); 1263redo_append_str (S_LEN (NL_STR )); 1264 } 1265 }else if (Visual .active && redoable && oap -> motion_force == NUL ) { 1266if (op_self_select (cap )) { 1267prep_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.) 1276String v = atom_visual_redoable () ?atom_visual_span () : (String )STRING_INIT ; 1277prep_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 }); 1281xfree (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{ 1301InsSession 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 1309if (vis != kVInsNone && !mc_replaying ()&& !is_child_frame ()) { 1310if (vis == kVInsOther && atom_visual_replayable ()&& !atom_visual_redoable ()) { 1311session .vsel = atom_visual_span ().data ; 1312session .origin = vatom .origin ; 1313 } 1314if (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 1317session .typed = atom_visual_replayable ()&& atom_visual_typed (); 1318 } 1319// The selection is consumed: already in the redo body. Also clears selection display. 1320atom_visual_reset (); 1321 } 1322 1323bool repl = cmd == 'R' || cmd == 'V' || cmd == 'r' || cmd == 'v' ; 1324bool reexec = vis == kVInsNone || vis == kVInsKeys || session .vsel != NULL 1325|| (vis == kVInsMotion && cur_frame -> payload_start == SIZE_MAX ); 1326mc_ins_cascade_start (session .typed && count <=1 && !repl && !vblock && reexec , 1327session .origin ,root_frame ()-> id ,session .vsel ); 1328 1329return 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{ 1338bool visual = session -> vis != kVInsNone ; 1339bool user_input = session -> typed 1340// A session is user input, if user input occurred during it. #41516 1341|| maptick != session -> origin .maptick ; 1342 1343if (mc_replaying ()) { 1344 gototheend ; 1345 } 1346if (mc_ins_commit ()) { 1347// Not during a mapping: there the spans are subatoms of its composite. 1348if (has_event (EVENT_CMDATOM )&& !atom_composite_active ()) { 1349atom_ins_push (session , false); 1350 } 1351 gototheend ; 1352 } 1353if (!user_input || busy || restart_edit != 0 || !atom_buf_has_consumers () 1354|| (visual && session -> vis != kVInsKeys && session -> vsel == NULL )) { 1355if (user_input && (busy || restart_edit != 0 )&& atom_composite_active ()) { 1356// Incomplete session (i_CTRL-O): its resolution is never captured. 1357composite .lossy = true; 1358 } 1359 gototheend ; 1360 } 1361atom_ins_push (session ,mc_buf_has_cursors (curbuf )); 1362 1363theend : 1364XFREE_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{ 1371CmdAtom atom = atom_from_redo (session -> vis != kVInsNone ?kAVisual :kAInsert ); 1372if (session -> vsel != NULL && atom .keys != NULL ) { 1373assert (strncmp (atom .keys ,"1v" ,2 )== 0 );// Supplant redo's "1v" fallback. 1374char * keys = concat_str (session -> vsel ,atom .keys + 2 ); 1375xfree (atom .keys ); 1376atom .keys = keys ; 1377 } 1378size_t size = atom .keys != NULL ?strlen (atom .keys ) :0 ; 1379bool replace = atom .spec .cmd == 'r' || (atom .spec .cmd == 'g' && atom .spec .cmd2 == 'r' ); 1380if (size == 0 || (!replace && (uint8_t )atom .keys [size - 1 ]!= ESC )) { 1381atom_free (& atom ); 1382return ; 1383 } 1384atom .text = get_last_insert_save (); 1385atom .origin = session -> origin ; 1386atom_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{ 1392const 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 }; 1411cur_frame = old ; 1412if (old -> parent == NULL && !composite .open ) { 1413composite .open = true; 1414composite .origin = old -> origin ; 1415composite .follow = kNone ; 1416 } 1417// Deferred composite: now start collecting... 1418if (old -> parent == NULL && !mc_replaying ()&& !composite .active && composite .lhs [0 ]!= NUL ) { 1419if (!KeyTyped && consumers ) { 1420atom_composite_start (NULL ,0 ); 1421typed .map_start = kv_size (typed .keys ); 1422composite .follow = kNone ;// Sampled again later. 1423 }else {// Not from the mapping (typed), or no consumers. 1424composite .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()). 1429if (old -> parent == NULL && atom_is_user_cmd ()&& !atom_composite_active ()) { 1430kv_size (typed .keys )= 0 ; 1431typed .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{ 1444if (mc_replaying ()|| atom_suppressed ) { 1445return false; 1446 } 1447 1448// 1449// Classify 1450// 1451const bool user = atom_is_user_cmd (); 1452const CmdFrame * root = root_frame (); 1453const 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... 1459bool opaque = (keycls & kKeyOpaque )!= 0 ; 1460bool synthetic = (keycls & kKeySynthetic )!= 0 ; 1461bool 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 )); 1468if (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 ) { 1473return false; 1474 } 1475bool ins_cascaded = user && mc_ins_cascaded (root -> id ); 1476// Command from a mapping's RHS (typed keys have KeyTyped set). 1477bool mapped = user && !old -> keytyped && !synthetic ; 1478if (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 )) { 1484map_edit = true; 1485 } 1486 1487// 1488// Visual session: open/continue/close, and decide if this command is one of its subatoms. 1489// 1490const bool child = is_child_frame ();// Session kept pending until resolved by enclosing frame. 1491bool vis = false; 1492if (Visual .active && !child ) { 1493if (!old -> visual .active && vatom .frame <=old -> id ) { 1494atom_visual_reset (); 1495vatom .state = kVatomFed ;// Promoted below if this frame is user input. 1496vatom .origin = old -> origin ; 1497 } 1498if (atom_visual_pending ()&& user && !synthetic && (old -> keytyped || atom_composite_active ())) { 1499// Recalculated on every frame. 1500vatom .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). 1504vis = atom_visual_pending ()&& ca -> cmdchar != 'Q' && ca -> cmdchar != 'q' ; 1505if (vis 1506&& (Visual .select 1507|| ((keycls & (kKeyScrollMove |kKeyScrollView |kKeyMouse ))&& !unchanged ))) { 1508// Not replayable: Select-mode input; the selection moved by viewport-dependent keys. 1509vatom .state |=kVatomVoid ; 1510 } 1511 }else if (old -> visual .active && !child ) { 1512CmdAtom own 1513= atom_visual_pending () ?atom_from_frame (ca ,root ,old -> visual .active ) : (CmdAtom ){0 }; 1514if (own .keys != NULL ) { 1515// This frame's children ended the session (":norm!" op in Lua mapping). #41956 1516char * suffix = own .keys ; 1517own .keys = NULL ; 1518atom_free (& own ); 1519atom_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 1523char suffix [2 ]= {ESC ,NUL }; 1524atom_visual_end_suffix (xstrdup (suffix ),NULL , false); 1525 }else { 1526atom_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// 1533if ((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 )) { 1543const 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(). 1546bool special_motion = (keycls & kKeyMotion )!= 0 ; 1547bool scroll_cmd = (keycls & (kKeyScrollMove |kKeyScrollView ))!= 0 ; 1548bool mouse_cmd = (keycls & kKeyMouse )!= 0 ; 1549bool 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. 1554bool replayable = (ca -> cmdchar > 0 && ca -> cmdchar < 0x100 1555&& ca -> cmdchar != '"' && ca -> cmdchar != '@' && !scroll_cmd ) 1556|| special_motion ; 1557bool changed = atom_origin_changed (old -> origin ); 1558// Note: an operator's motion belongs to the operator (`finish_op`). 1559bool 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). 1562bool 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. 1564bool follow = (mc_following ()|| mapped )&& motion && !failed ; 1565 1566// 1567// Route: decide the atom type and push it. 1568// 1569if (root -> redo_frame == old -> id && !mouse_cmd ) { 1570// Redoable edit ("dw", "p", "rX", "g@…"): this frame's redobuf defines the atom. 1571CmdAtom atom = atom_from_redo (kAOperator ); 1572// The payload ('operatorfunc' getchar()) is not in the captured redo, append it. 1573atom_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). 1577bool effect = (changed || reg_max_ts (true)> old -> reg_ts 1578|| (mc_following ()&& atom_origin_moved (old -> origin ))) 1579&& global_ops == old -> global_ops ; 1580if (atom .keys != NULL && * atom .keys != NUL ) { 1581atom .origin = old -> origin ; 1582atom_push (effect ,& atom ); 1583 }else { 1584atom_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. 1589CmdAtom atom = atom_from_cmdline (kAMotion ,ca ,ca -> searchbuf ,old -> visual .active ); 1590atom .origin = old -> origin ; 1591atom_push (false,& atom ); 1592 }else if (root -> cmdline != NULL && (ca -> cmdchar == ':' || ca -> cmdchar == K_COMMAND )) { 1593// Same for ":cnext<CR>" or "<Cmd>cnext<CR>". 1594CmdAtom atom = atom_from_cmdline (kAExcmd ,ca ,root -> cmdline ,old -> visual .active ); 1595// Payload read during the cmdline execution (`ds)` getchar() => ")"). 1596atom_payload_append (& atom ,old ); 1597atom .origin = old -> origin ; 1598atom_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 1601CmdAtom atom = atom_from_frame (ca ,root ,old -> visual .active ); 1602atom .origin = old -> origin ; 1603atom_push (false,& atom ); 1604 }else if (replayable && (!vis || ((keycls & kKeyPayload )== 0 && !failed ))) { 1605// Non-redoable command (u, zz, q=): never cascaded as an edit. 1606CmdSpec spec = atom_cmd_spec (ca ); 1607if (vis ) { 1608// Omit `regname`: would prefix '"x' to every command collected; op-end re-adds it later. 1609spec .regname = 0 ; 1610 } 1611CmdAtom atom = atom_from_spec (motion ?kAMotion :jump_cmd ?kAJump :kANormal ,spec ); 1612atom .origin = old -> origin ; 1613atom_push (follow ,& atom ); 1614if (jump_cmd && atom_composite_active ()) { 1615composite .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). 1619CmdSpec spec = atom_cmd_spec (ca ); 1620if (IS_SPECIAL (ca -> cmdchar )) { 1621// Wheel/mouse count is never typed: do_mousescroll() wrote its internal step there. 1622spec .count = 0 ; 1623 } 1624CmdAtom atom = atom_from_spec (scroll_cmd ?kAScroll :kAMouse ,spec ); 1625atom .origin = old -> origin ; 1626atom_push (false,& atom ); 1627 } 1628if (vis && kv_size (vatom .atoms )== collected && !unchanged ) { 1629// Not replayable: moved the selection by non-captured keys (mouse), or by API. 1630vatom .state |=kVatomVoid ; 1631 } 1632 } 1633 1634if (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. 1637vatom .state |=kVatomVoid ; 1638 } 1639atom_visual_span_flush (); 1640 1641return 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{ 1648if (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. 1651composite .follow = old -> follow ?kTrue :kFalse ; 1652 } 1653const bool refresh_visual = atom_capture_cmd (ca ,old ); 1654atom_stage_flush (old ); 1655if (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()). 1658composite .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). 1665if (old -> parent == NULL && !mc_replaying ()&& typebuf_typed ()&& stuff_empty ()) { 1666bool map_moved = atom_composite_active ()&& atom_origin_moved (composite .origin ); 1667mc_clock_edge (map_edit ,map_moved ,composite .follow == kTrue ); 1668 1669map_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"`. 1672if (ca -> oap -> op_type == OP_NOP && !Visual .active && restart_edit == 0 ) { 1673atom_composite_end (); 1674composite .open = false;// Resolved. 1675 } 1676 } 1677if (refresh_visual ) { 1678mc_vsel_refresh (); 1679 } 1680XFREE_CLEAR (old -> cmdline ); 1681cur_frame = old -> parent ; 1682}