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