robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1*dev_arch.txt* Nvim 2 3 4 NVIM REFERENCE MANUAL 5 6 7How to develop Nvim, explanation of modules and subsystems *dev-arch* 8 9Module-specific details are documented at the top of each module 10(`terminal.c`, `undo.c`, …). The top of each major module has (or should have) 11an overview in a comment at the top of its file. 12 13The purpose of this document is to give: 14 151. an overview of how it all fits together 162. how-to guides for common tasks such as: 17 - (TODO) deprecating public functions 18 - (TODO) adding a new public (API) function or (UI) event 19 20 Type |gO| to see the table of contents. 21 22============================================================================== 23Project layout: where things go *dev-layout* 24 25C CODE 26 27- Nvim C code lives in `src/nvim/`. 28 - This includes third-party components which we have forked and fully 29 "own", meaning we no longer track the upstream. In particular: `vterm/` 30 and `tui/termkey/`. 31- Vendored third-party components live in `src/*`. 32 - `src/tee/` and `src/xxd/` have their own build files. They are shipped 33 with the Windows artifact to ensure those tools exists there. 34 - Other components like `src/cjson/` and `src/mpack/` are included with 35 Nvim itself. These vendored sources are synced from upstream, we do not 36 "own" them. 37 38See also "MAINTAIN.md". 39 40Generated C files use these filename conventions to hint their purpose: 41- `*.c`, `*.generated.c` - full C files, with all includes, etc. 42- `*.c.h` - parametrized C files, contain all necessary includes, but require 43 defining macros before actually using. Example: `typval_encode.c.h` 44- `*.h` - full headers, with all includes. Does not apply to `*.generated.h`. 45- `*.h.generated.h` - exported functions’ declarations. 46- `*.c.generated.h` - static functions’ declarations. 47 48 49LUA CODE 50 51Lua code lives in one of four places: 52 531. Plugins! Not everything needs to live on `vim.*`. Plugins are the correct 54 model for non-essential functionality which (1) has "autoload" behavior, 55 (2) the user may disable or replace with a third-party plugin, (3) is 56 primarily user-facing, not an API. 57 - "Opt-out" plugins (activated on startup): `runtime/plugin/` 58 - "Opt-in" plugins (activated via `:packadd`): `runtime/pack/dist/opt/` 59 - Note: Update |standard-plugin-list|. 60 - Note: New plugins should place Lua modules in the shared "nvim" 61 namespace: `require('nvim.foo')`, not `require('foo')`. 62 - Examples: 63 - ✅ spellfile `runtime/lua/nvim/spellfile.lua` 64 - ✅ tutor 65 - Don't use these legacy plugins as examples (their modules should live 66 in `lua/nvim/x.lua`, not `lua/x.lua`): 67 - ❌ editorconfig.lua 68 - ❌ man.lua 69 - ❌ nvim.difftool 70 - ❌ nvim.tohtml 71 - ❌ nvim.undotree 722. Stdlib: `runtime/lua/vim/`. Modules on `vim.*`, lazy-loaded (as opposed to 73 "Core" modules, see below). 74 - Examples: `vim.treesitter`, `vim.lpeg`. 753. Core: `runtime/lua/vim/_core/`. Internal-only, compiled-in modules. May 76 directly interact with Nvim internals. Only available in main thread. See 77 |dev-lua-builtin| below. 784. "Shared" core: `runtime/lua/vim/_core/shared.lua`. Pure Lua functions which 79 always are available. Used in the test runner, and worker threads/processes 80 launched from Nvim. 81 82The top-level `vim.` namespace is for fundamental Lua and editor features. Use 83submodules (`vim.foo`) for everything else (but avoid excessive "nesting"), or 84plugins (see above). 85 86Compatibility with Vim's `if_lua` is explicitly a non-goal. 87 88 *dev-lua-builtin* 89Lua modules that are necessary even if VIMRUNTIME is invalid (generally, data 90structures and essential utilities), must be compiled into the `nvim` binary. 91There are two ways to do that: 92- if they are private, put the code file in `runtime/lua/vim/_core/` 93- if they are public, choose a new filepath in `runtime/lua/vim/` 94 and add it to VIM_MODULE_FILE in src/nvim/CMakeLists.txt. 95 96 97============================================================================== 98Data structures 99 100- StringBuilder 101- kvec or garray.c for dynamic lists / vectors (use StringBuilder for strings) 102 103Use `kvec.h` for most lists. When you absolutely need a linked list, use 104`src/nvim/lib/queue_defs.h` which defines an "intrusive" linked list. 105 106Buffer text is stored as a tree of line segments, defined in `src/nvim/memline.c`. 107The central idea is found in `ml_find_line`. 108 109Many of the editor concepts are defined as Lua data files: 110 111- Events (autocmds): src/nvim/auevents.lua 112- Ex (cmdline) commands: src/nvim/ex_cmds.lua 113- Options: src/nvim/options.lua 114- Vimscript functions: src/nvim/eval.lua 115 - Functions can be implemented in C (`f_foo` in eval/funcs.c), or in Lua 116 (set `func_lua` in eval.lua, implement in _core/vimfn.lua). Lua impl is 117 preferred, for performance and maintainability. 118 - VimScript callers go through `lua_wrapper` (typval <=> Object conversion). 119 - Lua callers (`vim.fn.foo()`) take a fast path in `nlua_call()` that calls 120 the Lua function directly, avoiding any conversion. 121- v: variables: src/nvim/vvars.lua 122 123============================================================================== 124Events *dev-events* 125 126The events historically called "autocmds", referred to here as "editor events" 127or simply "events", are high-level events for use by plugins, user config, and 128the Nvim editor. (There is an unrelated, low-level concept defined by the 129`event/defs.h#Event` struct, which is just a bag of data passed along the 130internal |event-loop|.) 131 132Where possible, new editor events should be implemented using `aucmd_defer()` 133(and where possible, old events migrate to this), so they are processed in 134a predictable manner, which avoids crashes. See |dev-new-event|. 135 136============================================================================== 137UI events *dev-ui-events* 138 139The long-term vision is that UI events are just another type of "editor event" 140(formerly known as "autocmds"). There is no real reason that we have separate 141types of user-facing or plugin-facing events. Events are events. Their 142"transport" is irrelevant and any event should be possible to emit over any 143transport (editor or RPC). 144 145Meanwhile the current situation is that UI events are a particular RPC event 146packaged in a generic `redraw` notification. They also can be listened to 147in-process via |vim.ui_attach()|. 148 149UI events are deferred to UIs, which implies a deepcopy of the UI event data. 150 151The source files most directly involved with UI events are: 1521. `src/nvim/ui.*`: calls handler functions of registered UI structs (independent from msgpack-rpc) 1532. `src/nvim/api/ui.*`: forwards messages over msgpack-rpc to remote UIs. 154 155UI events are defined in `src/nvim/api/ui_events.in.h` , this file is not 156compiled directly, rather it parsed by 157`src/gen/gen_api_ui_events.lua` which autogenerates wrapper 158functions used by the source files above. It also generates metadata 159accessible as `api_info().ui_events`. 160 161See commit d3a8e9217f39c59dd7762bd22a76b8bd03ca85ff for an example of adding 162a new UI event. Remember to bump NVIM_API_LEVEL if it wasn't already during 163this development cycle. 164 165Other references: 166- |msgpack-rpc| 167- |ui| 168- https://github.com/neovim/neovim/pull/3246 169- https://github.com/neovim/neovim/pull/18375 170- https://github.com/neovim/neovim/pull/21605 171 172============================================================================== 173State *dev-state* 174 175"Editor state" is represented by these (sometimes overlapping) concepts: 176 177- shada (`src/nvim/shada.c`): user data: registers, marks, …. Msgpack format. 178- sessions/views (`src/nvim/ex_session.c`): windows/layout, per-window 179 cursor/options, CWD, …. Vimscript format: commands, not merged data. 180 Overlaps shada for the buffer list and global variables. 181- context (`src/nvim/context.c`): |nvim_get_context()|. Interfaces shada and 182 other state; also in-memory per-cursor state (`kCtxVisual`, `kCtxMarks`, …) 183 for |multicursor|. Needs more thought. 184- scoped execution ("temporary state"): `ctx_switch()`, `vim._with()`, 185 |nvim_win_call()|, |nvim_buf_call()|, `cmdmod_T`. Temporary switches, not 186 snapshots. The C mechanisms overlap with each other; `vim._with()` is the 187 unified interface. 188- reentrancy protection: save/restore around nested execution. `InsState`, 189 `RedoState`. 190 - TODO: ad hoc pairs remain for typeahead (`tasave_T`), |v:event|, view 191 state, cmdline, with inconsistent nesting semantics (stack vs refcount vs 192 single-shot). 193 194LONG-TERM VISION(?): shada is the authority on all user-data state, sessions 195on layout state? New state kinds extend the shada schema instead of adding 196a format or an in-memory sidecar. Eliminate context.c? 197 198LUA FUNCTIONS ACROSS PROCESSES 199 200The test harness transfers Lua closures between Nvim instances 201(`test/functional/testnvim/exec_lua.lua`). This works ONLY between same-build 202instances (LuaJIT bytecode not portable across versions/builds) and only for 203trusted peers. Upvalues are limited to msgpack-able values (not 204function/userdata; tables lose metatables and identity). 205 206============================================================================== 207Filesystem *dev-filesystem* 208 209https://github.com/neovim/neovim/issues/36112 Path handling, especially 210separator chars ("/" vs "\"), is designed as follows: "/" separators are used 211every except at the "edges", i.e. the separator chars are coverted 212just-in-time, and only when absolutely needed. This is similar to how UTF-8 213encoding is used internally for all text, but buffers can read/write various 214encodings. 215 216P.S. Windows handles "/" separators just fine, except in rare cases. It'll be 217fine, don't worry. Just use "/", for god's sake! 218 219============================================================================== 220API 221 222 *dev-api-fast* 223API functions and Vimscript "eval" functions may be marked as |api-fast| which 224means they are safe to call in Lua callbacks and other scenarios. A function 225CANNOT be marked as "fast" if it could trigger `os_breakcheck()`, which may 226"yield" the current execution and start a new execution of code not expecting 227this: 228- accidentally recursing into a function not expecting this. 229- changing (global) state without restoring it before returning to the 230 "yielded" callsite. 231 232In practice, this means any code that could trigger `os_breakcheck()` cannot 233be "fast". For example, commit 3940c435e405 fixed such a bug with 234`nvim__get_runtime` by explicitly disallowing `os_breakcheck()` via the 235`EW_NOBREAK` flag. 236 237Common examples of non-fast code: regexp matching, wildcard expansion, 238expression evaluation. 239 240============================================================================== 241Internal practices and patterns *dev-internals-howto* 242 243------------------------------------------------------------------------------ 244Add a new excmd or vimfn ("f_xx") function *dev-new-excmd* *dev-new-vimfn* 245 246To implement an Ex cmd or f_xx function, choose from one of three ways (in 247order of preference): 248 2491. Full Lua: the implementation lives in entirely in Lua. This has 250 a performance benefit: the Vimscript <=> Lua bridge is skipped when the 251 `vim.fn.xx()` function is called from Lua. Examples: 252 - `f_hostname` 2532. Partial Lua: the C implementation calls `nlua_call_typval` or 254 `nlua_call_excmd`. (Or in rare cases: `nlua_exec` / `NLUA_EXEC_STATIC`). 255 Examples: 256 - `ex_log` 257 - `ex_lsp` 258 - `f_serverlist` 2593. Legacy way: implement the function entirely in C. 260 Examples: 261 - `f_chansend` 262 - `f_flatten` 263 - `f_searchpos` 264 265------------------------------------------------------------------------------ 266Add a new event (autocmd) *dev-new-event* 267 268To add a new editor event (autocmd): 269 2701. Register the event name in `src/nvim/auevents.lua`. If the event is 271 Nvim-only (not in Vim), also update the `nvim_specific` table. 2722. Fire the event, by one of these approaches: 273 - From C, use `aucmd_defer()` to fire deferred (safe, predictable). See 274 `do_markset_autocmd` for example. 275 - From Lua, use `vim.api.nvim_exec_autocmds()`. 2763. Define the |event-data| type (if any) in `runtime/lua/vim/_meta/events.lua`. 2774. Document the event in `runtime/doc/autocmd.txt`. 278 279============================================================================== 280The event-loop *event-loop* 281 282The internal, low-level, libuv event-loop (|luv-event-loop|) is used to 283schedule arbitrary work in a predictable way. One such obvious use-case for 284scheduling is deferred editor-events (autocmds). Another example is 285|job-control|. 286 287ASYNC EVENT SUPPORT 288 289One of the features Nvim added is the support for handling arbitrary 290asynchronous events, which can include: 291 292- RPC requests 293- job control callbacks 294- timers 295 296Nvim implements this functionality by entering another event loop while 297waiting for characters, so instead of: >py 298 299 def state_enter(on_state, data): 300 do 301 key = readkey() # Read a key from the user 302 while on_state(data, key) # Invoke callback for the current state 303 304the Nvim program loop is more like: >py 305 306 def state_enter(on_state, data): 307 do 308 event = read_next_event() # Read an event from the OS 309 while on_state(data, event) # Invoke callback for current state 310 311where `event` is something the operating system delivers to us, including (but 312not limited to) user input. The `read_next_event()` part is internally 313implemented by libuv, the platform layer used by Nvim. 314 315Since Nvim inherited its code from Vim, the states are not prepared to receive 316"arbitrary events", so we use a special key to represent those (When a state 317receives an "arbitrary event", it normally doesn't do anything other than 318update the screen). 319 320MAIN LOOP 321 322The `Loop` structure (which describes `main_loop`) abstracts multiple queues 323into one loop: > 324 325 uv_loop_t uv; 326 MultiQueue *events; 327 MultiQueue *thread_events; 328 MultiQueue *fast_events; 329 330`loop_poll_events` checks `Loop.uv` and `Loop.fast_events` whenever Nvim is 331idle, and also at `os_breakcheck` intervals. 332 333MultiQueue is cool because you can attach throw-away "child queues" trivially. 334For example `do_os_system()` does this (for every spawned process!) to 335automatically route events onto the `main_loop`: > 336 337 Process *proc = &uvproc.process; 338 MultiQueue *events = multiqueue_new_child(main_loop.events); 339 proc->events = events; 340 341 342NVIM LIFECYCLE 343 344How Nvim processes input. 345 346Consider a typical Vim-like editing session: 347 34801. Vim displays the welcome screen 34902. User types: `:` 35003. Vim enters command-line mode 35104. User types: `edit README.txt<CR>` 35205. Vim opens the file and returns to normal mode 35306. User types: `G` 35407. Vim navigates to the end of the file 35509. User types: `5` 35610. Vim enters count-pending mode 35711. User types: `d` 35812. Vim enters operator-pending mode 35913. User types: `w` 36014. Vim deletes 5 words 36115. User types: `g` 36216. Vim enters the "g command mode" 36317. User types: `g` 36418. Vim goes to the beginning of the file 36519. User types: `i` 36620. Vim enters insert mode 36721. User types: `word<ESC>` 36822. Vim inserts "word" at the beginning and returns to normal mode 369 370Note that we split user actions into sequences of inputs that change the state 371of the editor. While there's no documentation about a "g command mode" (step 37216), internally it is implemented similarly to "operator-pending mode". 373 374From this we can see that Vim has the behavior of an input-driven state machine 375(more specifically, a pushdown automaton since it requires a stack for 376transitioning back from states). Assuming each state has a callback responsible 377for handling keys, this pseudocode represents the main program loop: >py 378 379 def state_enter(state_callback, data): 380 do 381 key = readkey() # read a key from the user 382 while state_callback(data, key) # invoke the callback for the current state 383< 384 385That is, each state is entered by calling `state_enter` and passing a 386state-specific callback and data. Here is a high-level pseudocode for a program 387that implements something like the workflow described above: >py 388 389 def main() 390 state_enter(normal_state, {}): 391 392 def normal_state(data, key): 393 if key == ':': 394 state_enter(command_line_state, {}) 395 elif key == 'i': 396 state_enter(insert_state, {}) 397 elif key == 'd': 398 state_enter(delete_operator_state, {}) 399 elif key == 'g': 400 state_enter(g_command_state, {}) 401 elif is_number(key): 402 state_enter(get_operator_count_state, {'count': key}) 403 elif key == 'G' 404 jump_to_eof() 405 return true 406 407 def command_line_state(data, key): 408 if key == '<cr>': 409 if data['input']: 410 execute_ex_command(data['input']) 411 return false 412 elif key == '<esc>' 413 return false 414 415 if not data['input']: 416 data['input'] = '' 417 418 data['input'] += key 419 return true 420 421 def delete_operator_state(data, key): 422 count = data['count'] or 1 423 if key == 'w': 424 delete_word(count) 425 elif key == '$': 426 delete_to_eol(count) 427 return false # return to normal mode 428 429 def g_command_state(data, key): 430 if key == 'g': 431 go_top() 432 elif key == 'v': 433 reselect() 434 return false # return to normal mode 435 436 def get_operator_count_state(data, key): 437 if is_number(key): 438 data['count'] += key 439 return true 440 unshift_key(key) # return key to the input buffer 441 state_enter(delete_operator_state, data) 442 return false 443 444 def insert_state(data, key): 445 if key == '<esc>': 446 return false # exit insert mode 447 self_insert(key) 448 return true 449< 450 451The above gives an idea of how Nvim is organized internally. Some states like 452the `g_command_state` or `get_operator_count_state` do not have a dedicated 453`state_enter` callback, but are implicitly embedded into other states (this 454will change later as we continue the refactoring effort). To start reading the 455actual code, here's the recommended order: 456 4571. `state_enter()` function (state.c). This is the actual program loop, 458 note that a `VimState` structure is used, which contains function pointers 459 for the callback and state data. 4602. `main()` function (main.c). After all startup, `normal_enter` is called 461 at the end of function to enter normal mode. 4623. `normal_enter()` function (normal.c) is a small wrapper for setting 463 up the NormalState structure and calling `state_enter`. 4644. `normal_check()` function (normal.c) is called before each iteration of 465 normal mode. 4665. `normal_execute()` function (normal.c) is called when a key is read in normal 467 mode. 468 469The basic structure described for normal mode in 3, 4 and 5 is used for other 470modes managed by the `state_enter` loop: 471 472- command-line mode: `command_line_{enter,check,execute}()`(`ex_getln.c`) 473- insert mode: `insert_{enter,check,execute}()`(`insert.c`) 474- terminal mode: `terminal_{enter,execute}()`(`terminal.c`) 475 476IMPORTANT VARIABLES 477 478The current mode is stored in `State`. The values it can have are `MODE_NORMAL`, 479`MODE_INSERT`, `MODE_CMDLINE`, and a few others. 480 481The current window is `curwin`. The current buffer is `curbuf`. These point 482to structures with the cursor position in the window, option values, the file 483name, etc. 484 485All the global variables are declared in `globals.h`. 486 487THE MAIN EVENT-LOOP 488 489The main loop is implemented in state_enter. The basic idea is that Nvim waits 490for the user to type a character and processes it until another character is 491needed. Thus there are several places where Nvim waits for a character to be 492typed. The `vgetc()` function is used for this. It also handles mapping. 493 494Internal logic "stuffs" keys (readahead) only for a consumer on the current 495call stack: `exec_stuffed()`, or a nested reader it invokes. See "Stuffing" 496in input.c. (This is simpler and more predictable than Vim, where a command 497may stuff chars, and let the main loop deal with them at some arbitrary future 498point, thus requiring global flags checked at the right time, scattered 499throughout the codebase.) 500 501What we consider the "Nvim event loop" is actually a wrapper around `uv_run` to 502handle both the `fast_events` queue and possibly (a suitable subset of) deferred 503events. Therefore "raw" `vim.uv.run()` is often not enough to yield from Lua; 504instead call `vim.wait(0)` and check its result. 505 506Updating the screen is mostly postponed until a command or a sequence of 507commands has finished. The work is done by `update_screen()`, which calls 508`win_update()` for every window, which calls `win_line()` for every line. 509See the start of [drawscreen.c](drawscreen.c) for more explanations. 510 511COMMAND-LINE MODE 512 513When typing a `:`, `normal_cmd()` will call `getcmdline()` to obtain a line with 514an Ex command. `getcmdline()` calls a loop that will handle each typed 515character. It returns when hitting `<CR>` or `<Esc>` or some other character that 516ends the command line mode. 517 518EX COMMANDS 519 520Ex commands are handled by the function `do_cmdline()`. It does the generic 521parsing of the `:` command line and calls `do_one_cmd()` for each separate 522command. It also takes care of while loops. 523 524`do_one_cmd()` parses the range and generic arguments and puts them in the 525exarg_t and passes it to the function that handles the command. 526 527The `:` commands are listed in [ex_cmds.lua](ex_cmds.lua). 528 529NORMAL MODE COMMANDS 530 531The Normal mode commands are handled by the `normal_cmd()` function. It also 532handles the optional count and an extra character for some commands. These 533are passed in a `cmdarg_T` to the function that handles the command. 534 535There is a table `nv_cmds` in [normal.c](normal.c) which 536lists the first character of every 537command. The second entry of each item is the name of the function that 538handles the command. 539 540INSERT MODE COMMANDS 541 542When doing an `i` or `a` command, `normal_cmd()` will call the `edit()` function. 543It contains a loop that waits for the next character and handles it. It 544returns when leaving Insert mode. 545 546============================================================================== 547Multicursor *dev-multicursor* *dev-cmdatom* 548 549Multicursor is essentially a bunch of extmarks that "cascade" the user action 550(|CmdAtom|) driven by the primary cursor. 551 552An "atom" is any user action, as a resolved ("elemental", post-mapping) 553keysequence, the same material ("redobuf") replayed by dot-repeat 554(|single-repeat|). Whereas a macro is a series of meaningless characters 555whose meaning is context-dependent, assigned at the moment of execution, an 556atom scopes an input sequence to one, semantic, user action. Examples: "x" is 557captured as "dl", an insert session as `ciwfoo<Esc>`, a Visual-mode edit as 558`viweed`. 559 560CONCEPTS 561 562- ATOM: A repeatable unit of user input: the resolved keysequence, plus 563 structured fields (`CmdSpec`). Every user action emits a |CmdAtom| event. 564 - SPAN: Fragment of an Insert or Visual sequence, cascades but does not emit 565 a CmdAtom. 566 - FRAME: Scopes one MODE_NORMAL command (Normal, Visual, Select, 567 Op-pending). Non-MODE_NORMAL modes (Insert, Cmdline) are "sessions", not 568 "frames". All emit atoms. 569- CASCADE: Replay queued atoms at the "clock edge" at every cursor. Visual 570 edits cascade span-by-span each preceded by "gv"; the non-edit "tail" 571 dry-runs to display the selection. 572- COMPOSITE: An atom composed of subatoms (`CmdAtom.atoms`): a mapping/macro, 573 or a Visual sequence. 574- INSERT-SESSION: All changes from an insert-mode session, until <Esc>. 575 - INSERTION: An `Ins.start`..cursor "undo unit" within a session. 576 - INSERT-CASCADE: Replay an insert-session span-by-span as it is typed (each 577 span is packaged as a quasi-session: `i` + keys + `<Esc>`), via nested 578 `edit()`. Pending literal text is a PREVIEW until its span completes. 579- LOSSY: When capture lost part of a composite (payload with no capturing 580 atom, incomplete insert-session): `keys` cannot replay it, `lhs` can. 581- PAYLOAD: Keys a command reads interactively while executing: a search/Ex 582 cmdline (`d/pat<CR>`), `f{char}`, a mapping's `getchar()`. 583- REPLAY: Execute keys (dot-repeat, or atom). 584- VOID: When a pending (Visual) atom's keys were tainted/poisoned (by: mouse, 585 Select mode, a scroll that drags the cursor, …), thus not replayable. 586 587IMPLEMENTATION 588 589Capture happens at the `atom_xx()` hooks. 590- `prep_redo()` marks a redoable command (operators, `r`, `J`, `p`, …). Then 591 `atom_cmd_end()` takes the final redobuff as the atom, (including 592 payloads, e.g. `d/pat<CR>`). Prep-exempt commands (yank, `D`, folds) are 593 reconstructed instead, in `atom_capture_op()`. 594- `atom_cmd_start()` delimits a command in `normal_execute()`. Everything not 595 covered above is decided here (motions, jumps, scrolls, mouse). 596- `atom_ins_start()` delimits an insert session. 597- `atom_map_start()`, `atom_macro_start()` delimit a composite. 598- `atom_visual_end()` completes the pending Visual atom, `viweex` => `viweed`. 599 <Esc> discards it; non-replayable commands VOID it. 600- `atom_cmdline_set()` gets an invoked cmdline payload (e.g. `/pat<CR>` is 601 a motion atom, `:cnext<CR>` is an "excmd" atom.) 602 603DOT-REPEAT 604 605The redo buffer is the pending change as a `CmdSpec` (`RedoState`): the 606`["x][count]` prefix is structured fields set by `prep_redo()`, and the 607command body is bytes appended during execution by the `redo_append_xx()` 608family (Vim's `AppendToRedobuff*`). Consumers rebuild the keysequence at 609the boundaries (`redo_keys()`, `start_redo()`, `atom_from_redo()`). 610 611THE CASCADE 612 613Cursors are extmarks with associated `Context` data (`mc_cursors`). The 614extmark is authoritative: it follows edits, and user code may delete cursors 615by deleting their extmarks. Cursor-local state is swapped-in on replay, so 616each cursor reads/writes its own registers, Visual area and change marks. 617 618CmdAtoms queued for cascade (`g_atoms`) are replayed at every cursor on the 619"clock edge": the completion of a toplevel `normal_execute()`. While 620a mapping is executing (its keys are still in typebuf) the edge is deferred 621(subatoms queue/accumulate). 622 623Undo is buffer-global and applied in bulk. Each cascade adds one undo state, 624and undo/redo itself is not cascaded. 625 626The insert-cascade PREVIEW/COMMIT model (why text is previewed instead of 627replayed) is documented at `mc_ins_span`. Sessions that cannot insert-cascade 628(count `3iZ`, Replace mode, blockwise `CTRL-V c`) are captured at <Esc>. 629- See `CmdAtomType` and `atom_key_class()` to understand how input is 630 classified to decide whether and how it can be replayed. 631 632RHS VS LHS 633 634Multicursor "cascade" is meaningful only for edits and motions. Example: while 635you have multicursors placed, you may want to scroll or switch to a window 636temporarily; it would be a chore if you had to exit multicursor before doing 637those actions. 638 639Thus, cascade prefers to replay, skip, or partially-apply RHS (the resolved 640`keys`) instead of naively replaying LHS (the unresolved, remap-enabled, user 641input). In general, RHS "degrades gracefully" by doing LESS (and a single "u" 642reverts it), whereas LHS worst-case is unbounded (it fails by doing MORE; "u" 643cannot revert its side-effects). 644 645LHS may resolve to arbitrary Excmds/Lua that make sense at the primary, but 646not at cascade. Whereas RHS classification allows multicursor to skip (or 647partially apply) a user action that involves unreplayable subatoms. Similar to 648how insert-completion does not show a menu at every cursor, but it does 649cascade. 650 651Examples where RHS replay behaves better than LHS: 652 653- Performance: 654 - LHS replays the entire callback per-cursor, which can be very slow if it 655 involves treesitter queries, LSP requests, etc. 656 - RHS replays only the resolved normal commands. 657- Viewport-relative commands (zt/<C-d>/H/L/… in mapping): 658 - LHS cascade is nonsense because cursors may be offscreen. 659- Jumps / global ops (absolute, not cursor-relative): 660 - `nnoremap X Gdd`: RHS replays only dd, per cursor. 661 - `nnoremap <Down> ]C`: LHS (follow-mode) moves each cursor to its neighbor. 662 - `nnoremap u u`: LHS would undo N times. 663- Editor state outside of current buffer: 664 - `nnoremap ]x <Cmd>cnext<CR>x`: 665 - LHS is nonsense. 666 - RHS: `:cnext` runs once at primary; only `x` cascades. 667 - `nnoremap X <Cmd>set wrap!<CR>x`: 668 - LHS toggles N times, the result depends on N. 669 - RHS does not cascade the `<Cmd>`. 670 671Examples where LHS replay behaves better (and RHS replay is wrong): 672 673- Conditional mappings, e.g. `nnoremap X <Cmd>if getline('.') =~ 'foo' \| normal! dd \| endif<CR>`. 674 - Unblocked by `setrepeat()` API: https://github.com/neovim/neovim/issues/42069 675 676RENDERING 677 678Display is owned by `runtime/lua/vim/_core/mcursor.lua`. The C core maintains 679the model, as extmarks: 680 681- "nvim.multicursor": the tracking marks (cursor positions). 682- "nvim.multicursor.cursor": selection-END display cursors, during Visual mode 683 (each cursor displays at its own selection end). Consumers (UIs) that 684 display cursors use these positions 685 while any exist, instead of the tracking marks. 686- "nvim.multicursor.visual": the pending selection ranges. 687 688GUI SUPPORT 689 690A GUI gets a working display for free, via cell highlights. If it wants to 691draw "real" cursors, it is expected to: 692- receive positions via the `win_extmark` UI event: the tracking marks are 693 ui_watched, so visible cursor positions are pushed per-redraw. (Known 694 issue: win_extmark does not give a removal signal; re-query when in doubt.) 695- or query the namespaces above with |nvim_buf_get_extmarks()|; prefer the 696 "nvim.multicursor.cursor" positions while any exist (in-progress Visual 697 selection). 698- render selections from "nvim.multicursor.visual", or simply keep their 699 |hl-MCursorVisual| grid highlights. 700 701============================================================================== 702 703vim:tw=78:ts=8:sw=4:et:ft=help:norl: