robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1*repeat.txt* Nvim 2 3 4 NVIM REFERENCE MANUAL 5 6 7Repeating commands *repeating* 8 9Chapter 26 of the user manual introduces repeating |usr_26.txt|. 10 11 Type |gO| to see the table of contents. 12 13============================================================================== 14Single repeat *single-repeat* 15 16 *.* *dot-repeat* 17. Repeat last change, with count replaced with [count]. 18 Also repeat a yank command, when the 'y' flag is 19 included in 'cpoptions'. Does not repeat a 20 command-line command. 21 22 *@:* 23@: Repeat last command-line [count] times. 24 25Simple changes (edits) can be repeated with the "." command. Without a count, 26the count of the last change is used. If you enter a count, it will replace 27the last one. |v:count| and |v:count1| will be set. 28 29If the last change included a specification of a numbered register, the 30register number will be incremented. See |redo-register| for an example how 31to use this. 32 33Repeating an insert |ins-repeat| re-executes the whole session, including 34non-jump cursor-moves: "iab<Left>c<Esc>." produces "acb", not "c". Note that 35jumps (mouse, |i_<PageUp>|, …) split an insert session. 36 37Repeating a Visual-mode command re-executes the captured keysequence, 38selection included. See |visual-repeat|. 39 40To repeat non-changes, see |motion-repeat|. To repeat multiple actions, see 41|cmdatom-macro| and |complex-repeat|. 42 43============================================================================== 44Semantic repeat *action-repeat* *cmdatom* *excalibur* 🗡️ 45 46Every user action emits a |CmdAtom| event. This avoids the need for plugins to 47"announce" the repeatable unit, thus plugins like vim-repeat aren't needed. 48 49`CmdAtom.lhs` is the high-level user input collected during an action, 50including getchar() input. This is signficant: it reflects the semantic 51intent. `CmdAtom.keys` reveals the low-level internal commands that were 52produced. 53 54 INPUT (`lhs`) RESOLUTION (`keys`) ~ 55 dw "dw" Not translated. 56 zfa{ "zfa{" Not an edit (`changed=false`). 57 x "dl" Translated builtin. 58 ,d "dl" Mapping `:nnoremap ,d x`. 59 @q "dl" Macro `@q = "x"`. 60 <F6> "dlw" Composite `:nnoremap <F6> xw`: 61 `type='mapping'`, subatoms "dl" and "w" 62 concat to the composite keys. 63 ,Dw "dw" Incomplete mapping: ended mid- 64 operation (`:nnoremap ,D d`), 65 captures its continuation ("w"). 66 ds) ":call …<NL>)" "Payload" mapping (e.g. vim-surround 67 "ds'" reads |getchar()|). 68 ]q nil Lua mapping. 69 V<C-E>d "" Unreplayable: viewport-dependent 70 Visual sequence; `lhs` is only 71 a hint/label. 72 73To repeat an atom, feed `keys` (mode "n"), or `lhs` (mode "m") if `keys=nil`. >lua 74 75 local function replay(a) 76 vim.api.nvim_feedkeys(a.keys or a.lhs, a.keys and 'n' or 'm', false) 77 end 78< 79 *motion-repeat* 80Example: This "," mapping repeats the last motion ("zj", "3w", "fx", 81"/pat<CR>", "]c", any mapping/command that sets `moved=true`). >lua 82 83 local last ---@type vim.event.cmdatom.data? 84 vim.api.nvim_create_autocmd('CmdAtom', { 85 callback = function(ev) 86 -- Skip edits, and the "," mapping itself. 87 local motion = ev.data.moved or ev.match == 'motion' 88 if motion and not (ev.data.changed or ev.data.lhs == ',') then 89 last = ev.data 90 end 91 end, 92 }) 93 vim.keymap.set('n', ',', function() 94 -- CmdAtom is deferred; schedule the replay, in case "," follows a motion. 95 vim.schedule(function() 96 if last then 97 vim.api.nvim_feedkeys(last.keys or last.lhs, last.keys and 'n' or 'm', false) 98 end 99 end) 100 end) 101< 102 *edit-repeat* 103Example: This "." mapping repeats ANY edit (except undo/redo), including 104operations provided by plugins, without the need for "announcement" via 105vim-repeat or similar. >lua 106 107 local last ---@type vim.event.cmdatom.data? 108 vim.api.nvim_create_autocmd('CmdAtom', { 109 callback = function(ev) 110 local is_redo_or_undo = ev.data.changed and (ev.data.undoseq or 0) <= (vim.b[ev.buf].maxseq or 0) 111 vim.b[ev.buf].maxseq = math.max(vim.b[ev.buf].maxseq or 0, ev.data.undoseq or 0) 112 if ev.data.changed and not is_redo_or_undo and ev.data.lhs ~= '.' then 113 last = ev.data 114 end 115 end, 116 }) 117 vim.keymap.set('n', '.', function() 118 -- Multicursors: degrade to builtin "." (cascades). 119 local mc = vim.api.nvim_create_namespace('nvim.multicursor') 120 if #vim.api.nvim_buf_get_extmarks(0, mc, 0, -1, { limit = 1 }) > 0 then 121 vim.api.nvim_feedkeys('.', 'n', false) 122 return 123 end 124 -- CmdAtom is deferred; schedule the replay, in case "." follows an edit. 125 vim.schedule(function() 126 if last then 127 vim.api.nvim_feedkeys(last.keys or last.lhs, last.keys and 'n' or 'm', false) 128 end 129 end) 130 end) 131< 132 *cmdatom-macro* 133Example: This "[count]<Space>" mapping saves the last [count] atoms as an 134editable macro: "2<Space>" opens the |cmdwin| with the last [count] atoms 135listed (you can delete/edit steps if you want), <Enter> saves it. "<Space>" 136without a count replays the macro. >lua 137 138 -- Track the last 20 atoms. 139 local atom_ring = {} ---@type vim.event.cmdatom.data[] 140 vim.api.nvim_create_autocmd('CmdAtom', { 141 callback = function(ev) 142 -- Skip this mapping itself, and cmdwin edits. 143 if ev.data.lhs ~= ' ' and vim.fn.getcmdwintype() == '' then 144 atom_ring[#atom_ring + 1] = ev.data 145 if #atom_ring > 20 then 146 table.remove(atom_ring, 1) 147 end 148 end 149 end, 150 }) 151 -- [count]<space> shows a cmdwin where the user can edit/save the last [count] atoms as a "macro". 152 -- <space> (no count) replays it. 153 vim.keymap.set('n', '<Space>', function() 154 local count = vim.v.count 155 -- CmdAtom is deferred; schedule it so pending events land in the ring first. 156 vim.schedule(function() 157 count = math.min(count, #atom_ring) 158 if count == 0 then -- Replay the saved macro. 159 for _, step in ipairs(vim.g.atom_macro or {}) do 160 vim.api.nvim_feedkeys(vim.keycode(step.keys or step.lhs), step.keys and 'n' or 'm', false) 161 end 162 return 163 end 164 local parts = {} 165 for i = #atom_ring - count + 1, #atom_ring do 166 local a = atom_ring[i] 167 local keys = a.keys or ('%s%s'):format(a.count or '', a.lhs) 168 local field = a.keys and 'keys' or 'lhs' 169 parts[#parts + 1] = ('{%s=%q},'):format(field, vim.fn.keytrans(keys)) 170 end 171 local cmd = ('lua vim.g.atom_macro = { %s }'):format(table.concat(parts, ' ')) 172 -- Draft it on the cmdline; CTRL-F opens the cmdwin to edit it. 173 vim.api.nvim_feedkeys((':%s%s'):format(cmd, vim.keycode('<C-f>')), 'n', false) 174 end) 175 end) 176< 177 *restore-undo-cursor* 178By default, |undo| returns the cursor to its original position. If you don't 179like that, you can use this snippet to get Vim's behavior instead: >lua 180 181 vim.api.nvim_create_autocmd('CmdAtom', { 182 callback = function(ev) 183 -- Undo/redo: the buffer changed to an already-seen undo state. 184 local undid = ev.data.changed and (ev.data.undoseq or 0) <= (vim.b[ev.buf].maxseq or 0) 185 vim.b[ev.buf].maxseq = math.max(vim.b[ev.buf].maxseq or 0, ev.data.undoseq or 0) 186 if undid then 187 vim.cmd('normal! `[') -- Start of the changed text. 188 end 189 end, 190 }) 191< 192 193============================================================================== 194Multiple repeat *multi-repeat* 195 196 *:g* *:global* *E148* 197:[range]g[lobal]/{pattern}/[cmd] 198 Execute the Ex command [cmd] (default ":p") on the 199 lines within [range] where {pattern} matches. 200 201:[range]g[lobal]!/{pattern}/[cmd] 202 Execute the Ex command [cmd] (default ":p") on the 203 lines within [range] where {pattern} does NOT match. 204 205 *:v* *:vglobal* 206:[range]v[global]/{pattern}/[cmd] 207 Same as :g!. 208 209Example: > 210 :g/^Obsolete/d _ 211Using the underscore after `:d` avoids clobbering registers or the clipboard. 212This also makes it faster. 213 214Instead of the '/' which surrounds the {pattern}, you can use any other 215single byte character, but not an alphabetic character, '\', '"', '|' or '!'. 216This is useful if you want to include a '/' in the search pattern or 217replacement string. 218 219For the definition of a pattern, see |pattern|. 220 221NOTE [cmd] may contain a range; see |collapse| and |edit-paragraph-join| for 222examples. 223 224The global commands work by first scanning through the [range] lines and 225marking each line where a match occurs (for a multi-line pattern, only the 226start of the match matters). 227In a second scan the [cmd] is executed for each marked line, as if the cursor 228was in that line. For ":v" and ":g!" the command is executed for each not 229marked line. If a line is deleted its mark disappears. 230The default for [range] is the whole buffer (1,$). Use "CTRL-C" to interrupt 231the command. If an error message is given for a line, the command for that 232line is aborted and the global command continues with the next marked or 233unmarked line. 234 *E147* 235When the command is used recursively, it only works on one line. Giving a 236range is then not allowed. This is useful to find all lines that match a 237pattern and do not match another pattern: > 238 :g/found/v/notfound/{cmd} 239This first finds all lines containing "found", but only executes {cmd} when 240there is no match for "notfound". 241 242Any Ex command can be used, see |ex-cmd-index|. To execute a Normal mode 243command, you can use the `:normal` command: > 244 :g/pat/normal {commands} 245Make sure that {commands} ends with a whole command, otherwise Vim will wait 246for you to type the rest of the command for each match. The screen will not 247have been updated, so you don't know what you are doing. See |:normal|. 248 249The undo/redo command will undo/redo the whole global command at once. 250The previous context mark will only be set once (with "''" you go back to 251where the cursor was before the global command). 252 253The global command sets both the last used search pattern and the last used 254substitute pattern (this is vi compatible). This makes it easy to globally 255replace a string: > 256 :g/pat/s//PAT/g 257This replaces all occurrences of "pat" with "PAT". The same can be done with: > 258 :%s/pat/PAT/g 259Which is two characters shorter! 260 261============================================================================== 262Complex repeat *complex-repeat* 263 264 *q* *recording* *macro* 265q{0-9a-zA-Z"} Record typed characters into register {0-9a-zA-Z"} 266 (uppercase to append). The 'q' command is disabled 267 while executing a register, and it doesn't work inside 268 a mapping and |:normal|. 269 270 Note: If the register being used for recording is also 271 used for |y| and |p| the result is most likely not 272 what is expected, because the put will paste the 273 recorded macro and the yank will overwrite the 274 recorded macro. 275 276 Note: The recording happens while you type, replaying 277 the register happens as if the keys come from a 278 mapping. This matters, for example, for undo, which 279 only syncs when commands were typed. 280 281q Stops recording. 282 Implementation note: The 'q' that stops recording is 283 not stored in the register, unless it was the result 284 of a mapping 285 286 *@* 287@{0-9a-z".=*+} Execute the contents of register {0-9a-z".=*+} [count] 288 times. Note that register '%' (name of the current 289 file) and '#' (name of the alternate file) cannot be 290 used. 291 The register is executed like a mapping, that means 292 that the difference between 'wildchar' and 'wildcharm' 293 applies, and undo might not be synced in the same way. 294 For "@=" you are prompted to enter an expression. The 295 result of the expression is then executed. 296 See also |@:|. 297 298 *@@* *E748* 299@@ Repeat the previous @{0-9a-z":*} [count] times. 300 301 *v_@-default* 302{Visual}@{0-9a-z".=*+} In linewise Visual mode, execute the contents of the 303{Visual}@@ register for each selected line. 304 See |visual-repeat|, |default-mappings|. 305 306 *:@* 307:[addr]@{0-9a-z".=*+} Execute the contents of register {0-9a-z".=*+} as an 308 Ex command. First set cursor at line [addr] (default 309 is current line). When the last line in the register 310 does not have a <CR> it will be added automatically 311 when the 'e' flag is present in 'cpoptions'. 312 For ":@=" the last used expression is used. The 313 result of evaluating the expression is executed as an 314 Ex command. 315 Mappings are not recognized in these commands. 316 When the |line-continuation| character (\) is present 317 at the beginning of a line in a linewise register, 318 then it is combined with the previous line. This is 319 useful for yanking and executing parts of a Vim 320 script. 321 322 *:@:* 323:[addr]@: Repeat last command-line. First set cursor at line 324 [addr] (default is current line). 325 326:[addr]@ *:@@* 327:[addr]@@ Repeat the previous :@{register}. First set cursor at 328 line [addr] (default is current line). 329 330============================================================================== 331Multiple cursors *mcursor* *multicursor* 332 333You can place extra cursors ("multicursor") in a buffer, to repeat operations 334at each cursor as-you-type. Unlike a |macro| (a stream of keys without any 335context), multicursor replays actions "semantically" (|CmdAtom|). 336 337- Normal-mode commands, Mappings, and even Macros (|@|) replay at each cursor. 338- Insert-mode edits appear at each cursor as you type. 339- Motions (|q=|) and Visual sequences replay at each cursor: "viweex" 340 re-executes the selection so the extents are per-cursor (each cursor's own 341 word, block, …). 342- Undo is atomic: |u| reverts the aggregate edits from all cursors at once. 343- Registers are cursor-local. Each cursor reads/writes its own registers. 344 The yanks are joined (linewise) when the multicursor session ends. 345- Marks |'<| |'>| (|gv|), |'[| |']|, |'.| |'^| are cursor-local: "`." at each 346 cursor goes to its own last change. The |jumplist| and |changelist| are 347 global. 348- Folds are ignored during replay. Edits replay within folds ("dd" deletes the 349 line at cursor, not the entire folded contents). Motions step into folds 350 instead of skipping over them. The primary cursor keeps the usual 351 |fold-behavior|. 352- Cursors are per-buffer, and cascade only while their buffer is current. 353- Multicursors are presented as |hl-MCursor| highlights, unless your 354 (terminal) UI supports the Kitty multiple-cursors protocol. 355- CTRL-C interrupts the cascade. 356 357Example: place a cursor on every matching pattern: > 358 :g/pattern/normal! nQ 359 360Example: place a cursor at each |quickfix| item, or a range: > 361 :cdo normal! Q 362 :2,4cdo normal! Q 363 364Example: place a cursor at every named mark: > 365 zq]` 366< 367 368COMMANDS 369 *Q* 370Q Toggles a multicursor at the current cursor position. 371 Disables 'follow' mode. 372 373 Use [count] to force (un)placement instead of toggling: 374 "1Q" adds, "2Q" removes. 375 376 *zq* 377zq{motion} Places a cursor at {motion}, repeated from the current 378 position until end of buffer (or limited to a Visual 379 selection: |v_zq|). Think of it like `%:g` as an operator. 380 381 A search motion ("zq*", "zqn", "zqgn") places a cursor 382 at every match, wrapping if 'wrapscan' is enabled. 383 Sets the Visual area (|gv|) per-cursor, so "gv" 384 selects the match at each cursor. 385 386 Examples: 387 - "zqw": every word. 388 - "zqgn": every match. 389 - "zq*gvc" changes each match of the word under the cursor. 390 391 Not supported: 392 - Text objects 393 - Lua, |<Cmd>| or ":" mappings (except |:map-<expr>|). 394 395 396 *v_zq* 397{Visual}zq{motion} Like |zq|, but limited to the Visual range. 398 399 |blockwise-visual| acts on each line of the block, 400 from the block's left column (or the end of a short 401 line, like |v_b_A|). 402 403 Examples: 404 - "vipzqw": each word in the paragraph. 405 - "vipzqj" (or "zq+"): each line. 406 - "vipzq*": each match. 407 - "<C-V>3jzql": each line of the blockwise column. 408 409 *v_Q* 410{Visual}Q Places a cursor on each line of the selection, at the 411 cursor column. Same as "{Visual}zqj". |v_zq| 412 Enables 'follow' mode. 413 414 *mcursor-mouse* *<C-LeftMouse>* 415<C-LeftMouse> Toggles a multicursor at the click position, without 416 moving the primary cursor (or changing windows). No-op 417 in Insert-mode. 418 419 *q=* 420q= Toggles 'follow' mode: cursor-relative motions ("w", 421 "fx", "*", …) are replayed per-cursor. Cursors 422 arriving at the same position (e.g. "9j" on the last 423 line) are merged (deduplicated). 424 425 Not replayed: 426 - Absolute motions (scrolls/jumps: "G", global marks, 427 CTRL-O). 428 - Motions that fail/beep ("j" on the last line). 429 430 Use [count] to force the mode instead of toggling: 431 "1q=" on, "2q=" off. 432 433 *mcursor-clear* 434CTRL-L Clears multicursors in the current buffer. 435 |CTRL-L-default| 436 437 Cursors can also be cleared by clearing the namespace: >lua 438 local mc_ns = vim.api.nvim_create_namespace('nvim.multicursor') 439 vim.api.nvim_buf_clear_namespace(0, mc_ns, 0, -1) 440< 441 *gQ* 442gQ Restores the previous multicursors, and the primary 443 cursor position. No-op during a multicursor session. 444 445 *g_CTRL-A* 446g CTRL-A During a multicursor session, inserts an ascending 447 number ("counter") at each cursor, so a column of 448 cursors becomes 1, 2, 3, …. Use [count] to choose the 449 initial number. 450 451 *]C* 452]C Jump to the [count]'th next cursor. 453 Hint: "]CQ" removes cursors one at a time. 454 455 *[C* 456[C Jump to the [count]'th previous cursor. 457 458 459API *mcursor-api* 460 461Plugins can place cursors by setting or deleting |extmarks| in the 462"nvim.multicursor" namespace, and inspect user actions via the |CmdAtom| 463event. 464 465Adding an extmark (|nvim_buf_set_extmark()|) adds a cursor, unless one is 466already there. Query them with |nvim_buf_get_extmarks()|. Deleting an extmark 467deletes the cursor. 468 469You can also use |:marks| to peek at cursors: > 470 :marks nvim.multicursor 471< 472 473EXAMPLES *mcursor-examples* 474 475Example: a "]C" mapping which places a cursor before jumping to the next, so 476you can "rotate" through the cursors. >lua 477 478 local ns = vim.api.nvim_create_namespace('nvim.multicursor') 479 vim.keymap.set('n', ']C', function() 480 local row, col = vim.pos.cursor(0):to_extmark() 481 vim.api.nvim_buf_set_extmark(0, ns, row, col, {}) 482 vim.cmd('normal! ]C') 483 end) 484< 485Example: a "follow-once" mapping: "q-{motion}" replays {motion} at every 486cursor, then disables 'follow' mode again. >lua 487 488 vim.keymap.set('n', 'q-', function() 489 vim.cmd('normal! 1q=') 490 vim.api.nvim_create_autocmd('CmdAtom', { 491 callback = function(ev) 492 if ev.data.lhs == 'q-' then 493 return -- Skip the mapping itself. 494 end 495 vim.cmd('normal! 2q=') 496 return true -- Delete the handler. 497 end, 498 }) 499 end) 500< 501Example: place a cursor at every match, using the API: >lua 502 503 local ns = vim.api.nvim_create_namespace('nvim.multicursor') 504 for _, m in ipairs(vim.fn.matchbufline('%', [[pattern]], 1, '$')) do 505 vim.api.nvim_buf_set_extmark(0, ns, m.lnum - 1, m.byteidx, {}) 506 end 507< 508 509LIMITATIONS *mcursor-limitations* 510 511- During Insert-mode completion, live mirroring pauses if a preview could 512 shift or overlap the primary's completion (same-line edits before the 513 primary, or line insertions/deletions before it). 514- Cursor is removed if its Insert-entering operation fails. E.g. "ct;" on 515 a line without ";", "cgn" with no match. 516- Explicit clipboard registers (`"*yy`, `"+yy`) are global, not per-cursor. On 517 multicursor exit, you can set the clipboard to the joined yank: > 518 :let @+=@" 519- Implicit 'clipboard' ("unnamed"/"unnamedplus") updates the clipboard on 520 multicursor exit. 521- Same-line cursors may be lost/misplaced by an edit that shifts columns (e.g. 522 inserting text). 523- Time-travel undo (|g-|, |g+|, |:earlier|) clears all cursors. 524- Reloading/unloading a buffer (|:edit!|, 'autoread') clears its cursors 525 (extmarks limitation). 526- |Q|, |zq|, |gQ| are not allowed while recording or executing a macro. 527- A mapping or function that does not re-read its input will not cascade 528 correctly. 529 530 531 vim:tw=78:ts=8:noet:ft=help:norl: