map.txt (86122B)
1 *map.txt* For Vim version 9.2. Last change: 2026 Jun 13 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7 Key mapping, abbreviations and user-defined commands. 8 9 This subject is introduced in sections |05.4|, |24.7| and |40.1| of the user 10 manual. 11 12 1. Key mapping |key-mapping| 13 1.1 MAP COMMANDS |:map-commands| 14 1.2 Special arguments |:map-arguments| 15 1.3 Mapping and modes |:map-modes| 16 1.4 Listing mappings |map-listing| 17 1.5 Mapping special keys |:map-special-keys| 18 1.6 Special characters |:map-special-chars| 19 1.7 What keys to map |map-which-keys| 20 1.8 Examples |map-examples| 21 1.9 Using mappings |map-typing| 22 1.10 Mapping alt-keys |:map-alt-keys| 23 1.11 Mapping meta-keys |:map-meta-keys| 24 1.12 Mapping super-keys or command keys |:map-super-keys| 25 1.13 Mapping in modifyOtherKeys mode |modifyOtherKeys| 26 1.14 Mapping with Kitty keyboard protocol |kitty-keyboard-protocol| 27 1.15 Mapping an operator |:map-operator| 28 2. Abbreviations |abbreviations| 29 3. Local mappings and functions |script-local| 30 4. User-defined commands |user-commands| 31 32 ============================================================================== 33 1. Key mapping *key-mapping* *mapping* *macro* 34 35 Key mapping is used to change the meaning of typed keys. The most common use 36 is to define a sequence of commands for a function key. Example: > 37 38 :map <F2> a<C-R>=strftime("%c")<CR><Esc> 39 40 This appends the current date and time after the cursor (in <> notation |<>|). 41 42 43 1.1 MAP COMMANDS *:map-commands* 44 45 There are commands to enter new mappings, remove mappings and list mappings. 46 See |map-overview| for the various forms of "map" and their relationships with 47 modes. 48 49 {lhs} means left-hand-side *{lhs}* 50 {rhs} means right-hand-side *{rhs}* 51 52 :map {lhs} {rhs} |mapmode-nvo| *:map* 53 :nm[ap] {lhs} {rhs} |mapmode-n| *:nm* *:nmap* 54 :vm[ap] {lhs} {rhs} |mapmode-v| *:vm* *:vmap* 55 :xm[ap] {lhs} {rhs} |mapmode-x| *:xm* *:xmap* 56 :smap {lhs} {rhs} |mapmode-s| *:smap* 57 :om[ap] {lhs} {rhs} |mapmode-o| *:om* *:omap* 58 :map! {lhs} {rhs} |mapmode-ic| *:map!* 59 :im[ap] {lhs} {rhs} |mapmode-i| *:im* *:imap* 60 :lm[ap] {lhs} {rhs} |mapmode-l| *:lm* *:lma* *:lmap* 61 :cm[ap] {lhs} {rhs} |mapmode-c| *:cm* *:cmap* 62 :tma[p] {lhs} {rhs} |mapmode-t| *:tma* *:tmap* 63 Map the key sequence {lhs} to {rhs} for the modes 64 where the map command applies. The result, including 65 {rhs}, is then further scanned for mappings. This 66 allows for nested and recursive use of mappings. 67 Note: Trailing spaces are included in the {rhs}, 68 because space is a valid Normal mode command. 69 See |map-trailing-white|. 70 71 *:nore* *:norem* 72 :no[remap] {lhs} {rhs} |mapmode-nvo| *:no* *:noremap* *:nor* 73 :nn[oremap] {lhs} {rhs} |mapmode-n| *:nn* *:nnoremap* 74 :vn[oremap] {lhs} {rhs} |mapmode-v| *:vn* *:vnoremap* 75 :xn[oremap] {lhs} {rhs} |mapmode-x| *:xn* *:xnoremap* 76 :snor[emap] {lhs} {rhs} |mapmode-s| *:snor* *:snore* *:snoremap* 77 :ono[remap] {lhs} {rhs} |mapmode-o| *:ono* *:onoremap* 78 :no[remap]! {lhs} {rhs} |mapmode-ic| *:no!* *:noremap!* 79 :ino[remap] {lhs} {rhs} |mapmode-i| *:ino* *:inor* *:inoremap* 80 :ln[oremap] {lhs} {rhs} |mapmode-l| *:ln* *:lnoremap* 81 :cno[remap] {lhs} {rhs} |mapmode-c| *:cno* *:cnor* *:cnoremap* 82 :tno[remap] {lhs} {rhs} |mapmode-t| *:tno* *:tnoremap* 83 Map the key sequence {lhs} to {rhs} for the modes 84 where the map command applies. Disallow mapping of 85 {rhs}, to avoid nested and recursive mappings. Often 86 used to redefine a command. 87 Note: Keys in {rhs} also won't trigger abbreviation, 88 with the exception of |i_CTRL-]| and |c_CTRL-]|. 89 Note: When <Plug> appears in the {rhs} this part is 90 always applied even if remapping is disallowed. 91 92 93 :unm[ap] {lhs} |mapmode-nvo| *:unm* *:unmap* 94 :nun[map] {lhs} |mapmode-n| *:nun* *:nunmap* 95 :vu[nmap] {lhs} |mapmode-v| *:vu* *:vunmap* 96 :xu[nmap] {lhs} |mapmode-x| *:xu* *:xunmap* 97 :sunm[ap] {lhs} |mapmode-s| *:sunm* *:sunmap* 98 :ou[nmap] {lhs} |mapmode-o| *:ou* *:ounmap* 99 :unm[ap]! {lhs} |mapmode-ic| *:unm!* *:unmap!* 100 :iu[nmap] {lhs} |mapmode-i| *:iu* *:iunmap* 101 :lu[nmap] {lhs} |mapmode-l| *:lu* *:lunmap* 102 :cu[nmap] {lhs} |mapmode-c| *:cu* *:cun* *:cunmap* 103 :tunma[p] {lhs} |mapmode-t| *:tunma* *:tunmap* 104 Remove the mapping of {lhs} for the modes where the 105 map command applies. The mapping may remain defined 106 for other modes where it applies. 107 It also works when {lhs} matches the {rhs} of a 108 mapping. This is for when an abbreviation applied. 109 Note: Trailing spaces are included in the {lhs}. 110 See |map-trailing-white|. 111 112 :mapc[lear] |mapmode-nvo| *:mapc* *:mapclear* 113 :nmapc[lear] |mapmode-n| *:nmapc* *:nmapclear* 114 :vmapc[lear] |mapmode-v| *:vmapc* *:vmapclear* 115 :xmapc[lear] |mapmode-x| *:xmapc* *:xmapclear* 116 :smapc[lear] |mapmode-s| *:smapc* *:smapclear* 117 :omapc[lear] |mapmode-o| *:omapc* *:omapclear* 118 :mapc[lear]! |mapmode-ic| *:mapc!* *:mapclear!* 119 :imapc[lear] |mapmode-i| *:imapc* *:imapclear* 120 :lmapc[lear] |mapmode-l| *:lmapc* *:lmapclear* 121 :cmapc[lear] |mapmode-c| *:cmapc* *:cmapclear* 122 :tmapc[lear] |mapmode-t| *:tmapc* *:tmapclear* 123 Remove ALL mappings for the modes where the map 124 command applies. 125 Use the <buffer> argument to remove buffer-local 126 mappings |:map-<buffer>| 127 Warning: This also removes the |mac-standard-mappings| 128 and the |dos-standard-mappings|. 129 130 :map |mapmode-nvo| 131 :nm[ap] |mapmode-n| 132 :vm[ap] |mapmode-v| 133 :xm[ap] |mapmode-x| 134 :sm[ap] |mapmode-s| 135 :om[ap] |mapmode-o| 136 :map! |mapmode-ic| 137 :im[ap] |mapmode-i| 138 :lm[ap] |mapmode-l| 139 :cm[ap] |mapmode-c| 140 :tma[p] |mapmode-t| 141 List all key mappings for the modes where the map 142 command applies. Note that ":map" and ":map!" are 143 used most often, because they include the other modes. 144 145 :map {lhs} |mapmode-nvo| *:map_l* 146 :nm[ap] {lhs} |mapmode-n| *:nmap_l* 147 :vm[ap] {lhs} |mapmode-v| *:vmap_l* 148 :xm[ap] {lhs} |mapmode-x| *:xmap_l* 149 :sm[ap] {lhs} |mapmode-s| *:smap_l* 150 :om[ap] {lhs} |mapmode-o| *:omap_l* 151 :map! {lhs} |mapmode-ic| *:map_l!* 152 :im[ap] {lhs} |mapmode-i| *:imap_l* 153 :lm[ap] {lhs} |mapmode-l| *:lmap_l* 154 :cm[ap] {lhs} |mapmode-c| *:cmap_l* 155 :tma[p] {lhs} |mapmode-t| *:tmap_l* 156 List the key mappings for the key sequences starting 157 with {lhs} in the modes where the map command applies. 158 159 These commands are used to map a key or key sequence to a string of 160 characters. You can use this to put command sequences under function keys, 161 translate one key into another, etc. See |:mkexrc| for how to save and 162 restore the current mappings. 163 164 *map-ambiguous* 165 When two mappings start with the same sequence of characters, they are 166 ambiguous. Example: > 167 :imap aa foo 168 :imap aaa bar 169 When Vim has read "aa", it will need to get another character to be able to 170 decide if "aa" or "aaa" should be mapped. This means that after typing "aa" 171 that mapping won't get expanded yet, Vim is waiting for another character. 172 If you type a space, then "foo" will get inserted, plus the space. If you 173 type "a", then "bar" will get inserted. 174 175 Trailing white space ~ 176 *map-trailing-white* 177 This unmap command does NOT work: > 178 :map @@ foo 179 :unmap @@ | print 180 181 Because it tries to unmap "@@ ", including the white space before the command 182 separator "|". Other examples with trailing white space: > 183 unmap @@ 184 unmap @@ # Vim9 script comment 185 unmap @@ " legacy script comment 186 187 An error will be issued, which is very hard to identify, because the ending 188 whitespace character in `unmap @@ ` is not visible. 189 190 A generic solution is to put the command separator "|" right after the mapped 191 keys. After that white space and a comment may follow: > 192 193 unmap @@| # Vim9 script comment 194 unmap @@| " legacy script comment 195 196 197 1.2 SPECIAL ARGUMENTS *:map-arguments* 198 199 "<buffer>", "<nowait>", "<silent>", "<special>", "<script>", "<expr>" and 200 "<unique>" can be used in any order. They must appear right after the 201 command, before any other arguments. 202 203 *:map-local* *:map-<buffer>* *:map-buffer* 204 *E224* *E225* 205 If the first argument to one of these commands is "<buffer>" the mapping will 206 be effective in the current buffer only. Example: > 207 :map <buffer> ,w /[.,;]<CR> 208 Then you can map ",w" to something else in another buffer: > 209 :map <buffer> ,w /[#&!]<CR> 210 The local buffer mappings are used before the global ones. See <nowait> below 211 to make a short local mapping take effect when a longer global one exists. 212 The "<buffer>" argument can also be used to clear mappings: > 213 :unmap <buffer> ,w 214 :mapclear <buffer> 215 Local mappings are also cleared when a buffer is deleted, but not when it is 216 unloaded. Just like local option values. 217 Also see |map-precedence|. 218 219 *:map-<nowait>* *:map-nowait* 220 When defining a buffer-local mapping for "," there may be a global mapping 221 that starts with ",". Then you need to type another character for Vim to know 222 whether to use the "," mapping or the longer one. To avoid this add the 223 <nowait> argument. Then the mapping will be used when it matches, Vim does 224 not wait for more characters to be typed. However, if the characters were 225 already typed they are used. 226 Note that this works when the <nowait> mapping fully matches and is found 227 before any partial matches. This works when: 228 - There is only one matching buffer-local mapping, since these are always 229 found before global mappings. 230 - There is another buffer-local mapping that partly matches, but it is 231 defined earlier (last defined mapping is found first). 232 233 *:map-<silent>* *:map-silent* 234 To define a mapping which will not be echoed on the command line, add 235 "<silent>" as the first argument. Example: > 236 :map <silent> ,h /Header<CR> 237 The search string will not be echoed when using this mapping. Messages from 238 the executed command are still given though. To shut them up too, add a 239 ":silent" in the executed command: > 240 :map <silent> ,h :exe ":silent normal /Header\r"<CR> 241 Note that the effect of a command might also be silenced, e.g., when the 242 mapping selects another entry for command line completion it won't be 243 displayed. 244 Prompts will still be given, e.g., for inputdialog(). 245 Using "<silent>" for an abbreviation is possible, but will cause redrawing of 246 the command line to fail. 247 248 *:map-<special>* *:map-special* 249 Define a mapping with <> notation for special keys, even though the "<" flag 250 may appear in 'cpoptions'. This is useful if the side effect of setting 251 'cpoptions' is not desired. Example: > 252 :map <special> <F12> /Header<CR> 253 < 254 *:map-<script>* *:map-script* 255 If the first argument to one of these commands is "<script>" and it is used to 256 define a new mapping or abbreviation, the mapping will only remap characters 257 in the {rhs} using mappings that were defined local to a script, starting with 258 "<SID>". This can be used to avoid that mappings from outside a script 259 interfere (e.g., when CTRL-V is remapped in mswin.vim), but do use other 260 mappings defined in the script. 261 Note: ":map <script>" and ":noremap <script>" do the same thing. The 262 "<script>" overrules the command name. Using ":noremap <script>" is 263 preferred, because it's clearer that remapping is (mostly) disabled. 264 265 *:map-<unique>* *:map-unique* *E226* *E227* 266 If the first argument to one of these commands is "<unique>" and it is used to 267 define a new mapping or abbreviation, the command will fail if the mapping or 268 abbreviation already exists. Example: > 269 :map <unique> ,w /[#&!]<CR> 270 When defining a local mapping, there will also be a check if a global map 271 already exists which is equal. 272 Example of what will fail: > 273 :map ,w /[#&!]<CR> 274 :map <buffer> <unique> ,w /[.,;]<CR> 275 If you want to map a key and then have it do what it was originally mapped to, 276 have a look at |maparg()|. 277 278 *:map-<expr>* *:map-expression* 279 If the first argument to one of these commands is "<expr>" and it is used to 280 define a new mapping or abbreviation, the argument is an expression. The 281 expression is evaluated to obtain the {rhs} that is used. Example: > 282 :inoremap <expr> . <SID>InsertDot() 283 The result of the s:InsertDot() function will be inserted. It could check the 284 text before the cursor and start omni completion when some condition is met. 285 Using a script-local function is preferred, to avoid polluting the global 286 namespace. Use <SID> in the RHS so that the script that the mapping was 287 defined in can be found. 288 289 For abbreviations |v:char| is set to the character that was typed to trigger 290 the abbreviation. You can use this to decide how to expand the {lhs}. You 291 should not either insert or change the v:char. 292 293 In case you want the mapping to not do anything, you can have the expression 294 evaluate to an empty string. If something changed that requires Vim to 295 go through the main loop (e.g. to update the display), return "\<Ignore>". 296 This is similar to "nothing" but makes Vim return from the loop that waits for 297 input. Example: > 298 func s:OpenPopup() 299 call popup_create(... arguments ...) 300 return "\<Ignore>" 301 endfunc 302 nnoremap <expr> <F3> <SID>OpenPopup() 303 304 Keep in mind that the expression may be evaluated when looking for 305 typeahead, before the previous command has been executed. For example: > 306 func StoreColumn() 307 let g:column = col('.') 308 return 'x' 309 endfunc 310 nnoremap <expr> x StoreColumn() 311 nmap ! f!x 312 You will notice that g:column has the value from before executing "f!", 313 because "x" is evaluated before "f!" is executed. 314 This can be solved by inserting <Ignore> before the character that is 315 expression-mapped: > 316 nmap ! f!<Ignore>x 317 318 When defining a mapping in a |Vim9| script, the expression will be evaluated 319 in the context of that script. This means that script-local items can be 320 accessed in the expression. 321 322 Be very careful about side effects! The expression is evaluated while 323 obtaining characters, you may very well make the command dysfunctional. 324 For this reason the following is blocked: 325 - Changing the buffer text |textlock|. 326 - Editing another buffer. 327 - The |:normal| command. 328 - Moving the cursor is allowed, but it is restored afterwards. 329 If you want the mapping to do any of these let the returned characters do 330 that, or use a |<Cmd>| mapping instead. 331 332 You can use getchar(), it consumes typeahead if there is any. E.g., if you 333 have these mappings: > 334 inoremap <expr> <C-L> nr2char(getchar()) 335 inoremap <expr> <C-L>x "foo" 336 If you now type CTRL-L nothing happens yet, Vim needs the next character to 337 decide what mapping to use. If you type 'x' the second mapping is used and 338 "foo" is inserted. If you type any other key the first mapping is used, 339 getchar() gets the typed key and returns it. 340 341 Here is an example that inserts a list number that increases: > 342 let counter = 0 343 inoremap <expr> <C-L> ListItem() 344 inoremap <expr> <C-R> ListReset() 345 346 func ListItem() 347 let g:counter += 1 348 return g:counter .. '. ' 349 endfunc 350 351 func ListReset() 352 let g:counter = 0 353 return '' 354 endfunc 355 356 CTRL-L inserts the next number, CTRL-R resets the count. CTRL-R returns an 357 empty string, so that nothing is inserted. 358 359 Note that using 0x80 as a single byte before other text does not work, it will 360 be seen as a special key. 361 362 *<Cmd>* *:map-cmd* 363 The special text <Cmd> begins a "command mapping", it executes the command 364 directly without changing modes. Where you might use ":...<CR>" in the 365 {rhs} of a mapping, you can instead use "<Cmd>...<CR>". 366 Example: > 367 noremap x <Cmd>echo mode(1)<CR> 368 < 369 This is more flexible than `:<C-U>` in Visual and Operator-pending mode, or 370 `<C-O>:` in Insert mode, because the commands are executed directly in the 371 current mode, instead of always going to Normal mode. Visual mode is 372 preserved, so tricks with |gv| are not needed. Commands can be invoked 373 directly in Command-line mode (which would otherwise require timer hacks). 374 Example of using <Cmd> halfway Insert mode: > 375 nnoremap <F3> aText <Cmd>echo mode(1)<CR> Added<Esc> 376 377 Unlike <expr> mappings, there are no special restrictions on the <Cmd> 378 command: it is executed as if an (unrestricted) |autocommand| was invoked. 379 380 *<ScriptCmd>* 381 <ScriptCmd> is like <Cmd> but sets the context to the script the mapping was 382 defined in, for the duration of the command execution. This is especially 383 useful for |Vim9| script. It also works to access an import, which is useful 384 in a plugin using a, possibly autoloaded, script: > 385 vim9script 386 import autoload 'implementation.vim' as impl 387 nnoremap <F4> <ScriptCmd>impl.DoTheWork()<CR> 388 < 389 No matter where <F4> is typed, the "impl" import will be found in the script 390 context of where the mapping was defined. When it's an autoload import, as in 391 the example, the "implementation.vim" script will only be loaded once <F4> is 392 typed, not when the mapping is defined. 393 394 Without <ScriptCmd> using "s:impl" would result in "E121: Undefined variable". 395 396 Note: 397 - Because <Cmd> and <ScriptCmd> avoid mode-changes it does not trigger 398 |CmdlineEnter| and |CmdlineLeave| events, because no user interaction is 399 expected. 400 - For the same reason, |keycodes| like <C-R><C-W> are interpreted as plain, 401 unmapped keys. 402 - The command is not echo'ed, no need for <silent>. 403 - The {rhs} is not subject to abbreviations nor to other mappings, even if the 404 mapping is recursive. 405 - In Visual mode you can use `line('v')` and `col('v')` to get one end of the 406 Visual area, the cursor is at the other end. 407 408 *E1255* *E1136* 409 <Cmd> and <ScriptCmd> commands must terminate, that is, they must be followed 410 by <CR> in the {rhs} of the mapping definition. |Command-line| mode is never 411 entered. To use a literal <CR> in the {rhs}, use |<lt>|. 412 413 414 1.3 MAPPING AND MODES *:map-modes* 415 *mapmode-nvo* *mapmode-n* *mapmode-v* *mapmode-o* 416 417 There are seven sets of mappings 418 - For Normal mode: When typing commands. 419 - For Visual mode: When typing commands while the Visual area is highlighted. 420 - For Select mode: like Visual mode but typing text replaces the selection. 421 - For Operator-pending mode: When an operator is pending (after "d", "y", "c", 422 etc.). See below: |omap-info|. 423 - For Insert mode. These are also used in Replace mode. 424 - For Command-line mode: When entering a ":" or "/" command. 425 - For Terminal mode: When typing in a |:terminal| buffer. 426 427 Special case: While typing a count for a command in Normal mode, mapping zero 428 is disabled. This makes it possible to map zero without making it impossible 429 to type a count with a zero. 430 431 *map-overview* *map-modes* 432 Overview of which map command works in which mode. More details below. 433 COMMANDS MODES ~ 434 :map :noremap :unmap Normal, Visual, Select, Operator-pending 435 :nmap :nnoremap :nunmap Normal 436 :vmap :vnoremap :vunmap Visual and Select 437 :smap :snoremap :sunmap Select 438 :xmap :xnoremap :xunmap Visual 439 :omap :onoremap :ounmap Operator-pending 440 :map! :noremap! :unmap! Insert and Command-line 441 :imap :inoremap :iunmap Insert 442 :lmap :lnoremap :lunmap Insert, Command-line, Lang-Arg 443 :cmap :cnoremap :cunmap Command-line 444 :tmap :tnoremap :tunmap Terminal-Job 445 446 Same information in a table: 447 *map-table* 448 Mode | Norm | Ins | Cmd | Vis | Sel | Opr | Term | Lang | ~ 449 Command +------+-----+-----+-----+-----+-----+------+------+ ~ 450 [nore]map | yes | - | - | yes | yes | yes | - | - | 451 n[nore]map | yes | - | - | - | - | - | - | - | 452 [nore]map! | - | yes | yes | - | - | - | - | - | 453 i[nore]map | - | yes | - | - | - | - | - | - | 454 c[nore]map | - | - | yes | - | - | - | - | - | 455 v[nore]map | - | - | - | yes | yes | - | - | - | 456 x[nore]map | - | - | - | yes | - | - | - | - | 457 s[nore]map | - | - | - | - | yes | - | - | - | 458 o[nore]map | - | - | - | - | - | yes | - | - | 459 t[nore]map | - | - | - | - | - | - | yes | - | 460 l[nore]map | - | yes | yes | - | - | - | - | yes | 461 462 463 COMMANDS MODES ~ 464 Normal Visual+Select Operator-pending ~ 465 :map :noremap :unmap :mapclear yes yes yes 466 :nmap :nnoremap :nunmap :nmapclear yes - - 467 :vmap :vnoremap :vunmap :vmapclear - yes - 468 :omap :onoremap :ounmap :omapclear - - yes 469 470 :nunmap can also be used outside of a monastery. 471 *mapmode-x* *mapmode-s* 472 Some commands work both in Visual and Select mode, some in only one. Note 473 that quite often "Visual" is mentioned where both Visual and Select mode 474 apply. |Select-mode-mapping| 475 NOTE: Mapping a printable character in Select mode may confuse the user. It's 476 better to explicitly use :xmap and :smap for printable characters. Or use 477 :sunmap after defining the mapping. 478 479 COMMANDS MODES ~ 480 Visual Select ~ 481 :vmap :vnoremap :vunmap :vmapclear yes yes 482 :xmap :xnoremap :xunmap :xmapclear yes - 483 :smap :snoremap :sunmap :smapclear - yes 484 485 *mapmode-ic* *mapmode-i* *mapmode-c* *mapmode-l* 486 Some commands work both in Insert mode and Command-line mode, some not: 487 488 COMMANDS MODES ~ 489 Insert Command-line Lang-Arg ~ 490 :map! :noremap! :unmap! :mapclear! yes yes - 491 :imap :inoremap :iunmap :imapclear yes - - 492 :cmap :cnoremap :cunmap :cmapclear - yes - 493 :lmap :lnoremap :lunmap :lmapclear yes* yes* yes* 494 495 * If 'iminsert' is 1, see |language-mapping| below. 496 497 The original Vi did not have separate mappings for 498 Normal/Visual/Operator-pending mode and for Insert/Command-line mode. 499 Therefore the ":map" and ":map!" commands enter and display mappings for 500 several modes. In Vim you can use the ":nmap", ":vmap", ":omap", ":cmap" and 501 ":imap" commands to enter mappings for each mode separately. 502 503 *mapmode-t* 504 The terminal mappings are used in a terminal window, when typing keys for the 505 job running in the terminal. See |terminal-typing|. 506 507 *omap-info* 508 Operator-pending mappings can be used to define a movement command that can be 509 used with any operator. Simple example: > 510 :omap { w 511 makes "y{" work like "yw" and "d{" like "dw". 512 513 To ignore the starting cursor position and select different text, you can have 514 the omap start Visual mode to select the text to be operated upon. Example 515 that operates on a function name in the current line: > 516 onoremap <silent> F :<C-U>normal! 0f(hviw<CR> 517 The CTRL-U (<C-U>) is used to remove the range that Vim may insert. The 518 Normal mode commands find the first '(' character and select the first word 519 before it. That usually is the function name. 520 521 To enter a mapping for Normal and Visual mode, but not Operator-pending mode, 522 first define it for all three modes, then unmap it for 523 Operator-pending mode: > 524 :map xx something-difficult 525 :ounmap xx 526 527 Likewise for a mapping for Visual and Operator-pending mode or Normal and 528 Operator-pending mode. 529 530 *language-mapping* 531 ":lmap" defines a mapping that applies to: 532 - Insert mode 533 - Command-line mode 534 - when entering a search pattern 535 - the argument of the commands that accept a text character, such as "r" and 536 "f" 537 - for the input() line 538 Generally: Whenever a character is to be typed that is part of the text in the 539 buffer, not a Vim command character. "Lang-Arg" isn't really another mode, 540 it's just used here for this situation. 541 The simplest way to load a set of related language mappings is by using the 542 'keymap' option. See |45.5|. 543 In Insert mode and in Command-line mode the mappings can be disabled with 544 the CTRL-^ command |i_CTRL-^| |c_CTRL-^|. These commands change the value of 545 the 'iminsert' option. When starting to enter a normal command line (not a 546 search pattern) the mappings are disabled until a CTRL-^ is typed. The state 547 last used is remembered for Insert mode and Search patterns separately. The 548 state for Insert mode is also used when typing a character as an argument to 549 command like "f" or "t". 550 Language mappings will never be applied to already mapped characters. They 551 are only used for typed characters. This assumes that the language mapping 552 was already done when typing the mapping. 553 554 555 1.4 LISTING MAPPINGS *map-listing* 556 557 When listing mappings the characters in the first two columns are: 558 559 CHAR MODE ~ 560 <Space> Normal, Visual, Select and Operator-pending 561 n Normal 562 v Visual and Select 563 s Select 564 x Visual 565 o Operator-pending 566 ! Insert and Command-line 567 i Insert 568 l ":lmap" mappings for Insert, Command-line and Lang-Arg 569 c Command-line 570 t Terminal-Job 571 572 Just before the {rhs} a special character can appear: 573 * indicates that it is not remappable 574 & indicates that only script-local mappings are remappable 575 @ indicates a buffer-local mapping 576 577 Everything from the first non-blank after {lhs} up to the end of the line 578 (or '|') is considered to be part of {rhs}. This allows the {rhs} to end 579 with a space. 580 581 Note: When using mappings for Visual mode, you can use the "'<" mark, which 582 is the start of the last selected Visual area in the current buffer |'<|. 583 584 The |:filter| command can be used to select what mappings to list. The 585 pattern is matched against the {lhs} and {rhs} in the raw form. 586 587 While mappings are being listed, it is not possible to add or clear mappings, 588 e.g. from a timer callback. *E1309* 589 590 *:map-verbose* 591 When 'verbose' is non-zero, the detected and used 'keyprotocol' value will be 592 displayed in the first line. Also a key map will also display where it was 593 last defined. Example: > 594 595 :verbose map <C-W>* 596 Kitty keyboard protocol: Cleared 597 n <C-W>* * <C-W><C-S>* 598 Last set from /home/abcd/.vimrc 599 600 See |:verbose-cmd| for more information. 601 602 603 1.5 MAPPING SPECIAL KEYS *:map-special-keys* 604 605 There are three ways to map a special key: 606 1. The Vi-compatible method: Map the key code. Often this is a sequence that 607 starts with <Esc>. To enter a mapping like this you type ":map " and then 608 you have to type CTRL-V before hitting the function key. Note that when 609 the key code for the key is in the termcap (the t_ options), it will 610 automatically be translated into the internal code and become the second 611 way of mapping (unless the 'k' flag is included in 'cpoptions'). 612 2. The second method is to use the internal code for the function key. To 613 enter such a mapping type CTRL-K and then hit the function key, or use 614 the form "#1", "#2", .. "#9", "#0", "<Up>", "<S-Down>", "<S-F7>", etc. 615 (see table of keys |key-notation|, all keys from <Up> can be used). The 616 first ten function keys can be defined in two ways: Just the number, like 617 "#2", and with "<F>", like "<F2>". Both stand for function key 2. "#0" 618 refers to function key 10, defined with option 't_f10', which may be 619 function key zero on some keyboards. The <> form cannot be used when 620 'cpoptions' includes the '<' flag. 621 3. Use the termcap entry, with the form <t_xx>, where "xx" is the name of the 622 termcap entry. Any string entry can be used. For example: > 623 :map <t_F3> G 624 < Maps function key 13 to "G". This does not work if 'cpoptions' includes 625 the '<' flag. 626 627 The advantage of the second and third method is that the mapping will work on 628 different terminals without modification (the function key will be 629 translated into the same internal code or the actual key code, no matter what 630 terminal you are using. The termcap must be correct for this to work, and you 631 must use the same mappings). 632 633 DETAIL: Vim first checks if a sequence from the keyboard is mapped. If it 634 isn't the terminal key codes are tried (see |terminal-options|). If a 635 terminal code is found it is replaced with the internal code. Then the check 636 for a mapping is done again (so you can map an internal code to something 637 else). What is written into the script file depends on what is recognized. 638 If the terminal key code was recognized as a mapping the key code itself is 639 written to the script file. If it was recognized as a terminal code the 640 internal code is written to the script file. 641 642 643 1.6 SPECIAL CHARACTERS *:map-special-chars* 644 *map_backslash* *map-backslash* 645 Note that only CTRL-V is mentioned here as a special character for mappings 646 and abbreviations. When 'cpoptions' does not contain 'B', a backslash can 647 also be used like CTRL-V. The <> notation can be fully used then |<>|. But 648 you cannot use "<C-V>" like CTRL-V to escape the special meaning of what 649 follows. 650 651 To map a backslash, or use a backslash literally in the {rhs}, the special 652 sequence "<Bslash>" can be used. This avoids the need to double backslashes 653 when using nested mappings. 654 655 *map_CTRL-C* *map-CTRL-C* 656 Using CTRL-C in the {lhs} is possible, but it will only work when Vim is 657 waiting for a key, not when Vim is busy with something. When Vim is busy 658 CTRL-C interrupts/breaks the command. 659 When using the GUI version on MS-Windows CTRL-C can be mapped to allow a Copy 660 command to the clipboard. Use CTRL-Break to interrupt Vim. 661 662 *map_space_in_lhs* *map-space_in_lhs* 663 To include a space in {lhs} precede it with a CTRL-V (type two CTRL-Vs for 664 each space). 665 *map_space_in_rhs* *map-space_in_rhs* 666 If you want a {rhs} that starts with a space, use "<Space>". To be fully Vi 667 compatible (but unreadable) don't use the |<>| notation, precede {rhs} with a 668 single CTRL-V (you have to type CTRL-V two times). 669 *map_empty_rhs* *map-empty-rhs* 670 You can create an empty {rhs} by typing nothing after a single CTRL-V (you 671 have to type CTRL-V two times). Unfortunately, you cannot do this in a vimrc 672 file. 673 *<Nop>* 674 An easier way to get a mapping that doesn't produce anything, is to use 675 "<Nop>" for the {rhs}. This only works when the |<>| notation is enabled. 676 For example, to make sure that function key 8 does nothing at all: > 677 :map <F8> <Nop> 678 :map! <F8> <Nop> 679 < 680 *map-multibyte* 681 It is possible to map multibyte characters, but only the whole character. You 682 cannot map the first byte only. This was done to prevent problems in this 683 scenario: > 684 :set encoding=latin1 685 :imap <M-C> foo 686 :set encoding=utf-8 687 The mapping for <M-C> is defined with the latin1 encoding, resulting in a 0xc3 688 byte. If you type the character á (0xe1 <M-a>) in UTF-8 encoding this is the 689 two bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then or 690 otherwise it would be impossible to type the á character. 691 692 *<Leader>* *mapleader* 693 To define a mapping which uses the "g:mapleader" variable, the special string 694 "<Leader>" can be used. It is replaced with the string value of 695 "g:mapleader". If "g:mapleader" is not set or empty, a backslash is used 696 instead. Example: > 697 map <Leader>A oanother line<Esc> 698 Works like: > 699 map \A oanother line<Esc> 700 But after (legacy script): > 701 let mapleader = "," 702 Or (Vim9 script): > 703 g:mapleader = "," 704 It works like: > 705 map ,A oanother line<Esc> 706 707 Note that the value of "g:mapleader" is used at the moment the mapping is 708 defined. Changing "g:mapleader" after that has no effect for already defined 709 mappings. 710 711 *<LocalLeader>* *maplocalleader* 712 <LocalLeader> is just like <Leader>, except that it uses "maplocalleader" 713 instead of "mapleader". <LocalLeader> is to be used for mappings which are 714 local to a buffer. Example: > 715 :map <buffer> <LocalLeader>A oanother line<Esc> 716 < 717 In a global plugin <Leader> should be used and in a filetype plugin 718 <LocalLeader>. "mapleader" and "maplocalleader" can be equal. Although, if 719 you make them different, there is a smaller chance of mappings from global 720 plugins to clash with mappings for filetype plugins. For example, you could 721 keep "mapleader" at the default backslash, and set "maplocalleader" to an 722 underscore. 723 724 *map-<SID>* 725 In a script the special key name "<SID>" can be used to define a mapping 726 that's local to the script. See |<SID>| for details. 727 728 *<Plug>* 729 The special key name "<Plug>" can be used for an internal mapping, which is 730 not to be matched with any key sequence. This is useful in plugins 731 |using-<Plug>|. 732 733 *<MouseMove>* 734 The special key name "<MouseMove>" can be used to handle mouse movement. It 735 needs to be enabled with 'mousemoveevent'. Currently only works in the GUI. 736 The |getmousepos()| function can be used to obtain the mouse position. 737 738 *<Char>* *<Char->* 739 To map a character by its decimal, octal or hexadecimal number the <Char> 740 construct can be used: 741 <Char-123> character 123 742 <Char-033> character 27 743 <Char-0x7f> character 127 744 <S-Char-114> character 114 ('r') shifted ('R') 745 This is useful to specify a (multibyte) character in a 'keymap' file. 746 Upper and lowercase differences are ignored. 747 748 *map-comments* 749 It is not possible to put a comment after these commands, because the '"' 750 character is considered to be part of the {lhs} or {rhs}. However, one can 751 use |", since this starts a new, empty command with a comment. 752 753 *map_bar* *map-bar* 754 Since the '|' character is used to separate a map command from the next 755 command, you will have to do something special to include a '|' in {rhs}. 756 There are three methods: 757 use works when example ~ 758 <Bar> '<' is not in 'cpoptions' :map _l :!ls <Bar> more^M 759 \| 'b' is not in 'cpoptions' :map _l :!ls \| more^M 760 ^V| always, in Vim and Vi :map _l :!ls ^V| more^M 761 762 (here ^V stands for CTRL-V; to get one CTRL-V you have to type it twice; you 763 cannot use the <> notation "<C-V>" here). 764 765 All three work when you use the default setting for 'cpoptions'. 766 767 When 'b' is present in 'cpoptions', "\|" will be recognized as a mapping 768 ending in a '\' and then another command. This is Vi compatible, but 769 illogical when compared to other commands. 770 771 *map_return* *map-return* 772 When you have a mapping that contains an Ex command, you need to put a line 773 terminator after it to have it executed. The use of <CR> is recommended for 774 this (see |<>|). Example: > 775 :map _ls :!ls -l %:S<CR>:echo "the end"<CR> 776 777 To avoid mapping of the characters you type in insert or Command-line mode, 778 type a CTRL-V first. The mapping in Insert mode is disabled if the 'paste' 779 option is on. 780 *map-error* 781 Note that when an error is encountered (that causes an error message or might 782 cause a beep) the rest of the mapping is not executed. This is Vi-compatible. 783 784 Note that the second character (argument) of the commands @zZtTfF[]rm'`"v 785 and CTRL-X is not mapped. This was done to be able to use all the named 786 registers and marks, even when the command with the same name has been 787 mapped. 788 789 790 1.7 WHAT KEYS TO MAP *map-which-keys* 791 792 If you are going to map something, you will need to choose which key(s) to use 793 for the {lhs}. You will have to avoid keys that are used for Vim commands, 794 otherwise you would not be able to use those commands anymore. Here are a few 795 suggestions: 796 - Function keys <F2>, <F3>, etc.. Also the shifted function keys <S-F1>, 797 <S-F2>, etc. Note that <F1> is already used for the help command. 798 - Any key with the Alt or Meta key pressed. Depending on your keyboard 799 accented characters may be used as well. |:map-alt-keys| 800 - Use the '_' or ',' character and then any other character. The "_" and "," 801 commands do exist in Vim (see |_| and |,|), but you probably never use them. 802 - Use a key that is a synonym for another command. For example: CTRL-P and 803 CTRL-N. Use an extra character to allow more mappings. 804 - The key defined by <Leader> and one or more other keys. This is especially 805 useful in scripts. |mapleader| 806 807 See the file "index" for keys that are not used and thus can be mapped without 808 losing any builtin function. You can also use ":help {key}^D" to find out if 809 a key is used for some command. ({key} is the specific key you want to find 810 out about, ^D is CTRL-D). 811 812 813 1.8 EXAMPLES *map-examples* 814 815 A few examples (given as you type them, for "<CR>" you type four characters; 816 the '<' flag must not be present in 'cpoptions' for this to work). > 817 818 :map <F3> o#include 819 :map <M-g> /foo<CR>cwbar<Esc> 820 :map _x d/END/e<CR> 821 :map! qq quadrillion questions 822 823 824 Multiplying a count 825 826 When you type a count before triggering a mapping, it's like the count was 827 typed before the {lhs}. For example, with this mapping: > 828 :map <F4> 3w 829 Typing 2<F4> will result in "23w". Thus not moving 2 * 3 words but 23 words. 830 If you want to multiply counts use the expression register: > 831 :map <F4> @='3w'<CR> 832 The part between quotes is the expression being executed. |@=| 833 834 835 1.9 USING MAPPINGS *map-typing* 836 837 Vim will compare what you type with the start of a mapped sequence. If there 838 is an incomplete match, it will get more characters until there either is a 839 complete match or until there is no match at all. Example: If you map! "qq", 840 the first 'q' will not appear on the screen until you type another 841 character. This is because Vim cannot know if the next character will be a 842 'q' or not. If the 'timeout' option is on (which is the default) Vim will 843 only wait for one second (or as long as specified with the 'timeoutlen' 844 option). After that it assumes that the 'q' is to be interpreted as such. If 845 you type slowly, or your system is slow, reset the 'timeout' option. Then you 846 might want to set the 'ttimeout' option. 847 848 *map-precedence* 849 Buffer-local mappings (defined using |:map-<buffer>|) take precedence over 850 global mappings. When a buffer-local mapping is the same as a global mapping, 851 Vim will use the buffer-local mapping. In addition, Vim will use a complete 852 mapping immediately if it was defined with <nowait>, even if a longer mapping 853 has the same prefix. For example, given the following two mappings: > 854 :map <buffer> <nowait> \a :echo "Local \a"<CR> 855 :map \abc :echo "Global \abc"<CR> 856 When typing \a the buffer-local mapping will be used immediately. Vim will 857 not wait for more characters to see if the user might be typing \abc. 858 859 *map-keys-fails* 860 There are situations where key codes might not be recognized: 861 - Vim can only read part of the key code. Mostly this is only the first 862 character. This happens on some Unix versions in an xterm. 863 - The key code is after character(s) that are mapped. E.g., "<F1><F1>" or 864 "g<F1>". 865 866 The result is that the key code is not recognized in this situation, and the 867 mapping fails. There are two actions needed to avoid this problem: 868 869 - Remove the 'K' flag from 'cpoptions'. This will make Vim wait for the rest 870 of the characters of the function key. 871 - When using <F1> to <F4> the actual key code generated may correspond to 872 <xF1> to <xF4>. There are mappings from <xF1> to <F1>, <xF2> to <F2>, etc., 873 but these are not recognized after another half a mapping. Make sure the 874 key codes for <F1> to <F4> are correct: > 875 :set <F1>=<type CTRL-V><type F1> 876 < Type the <F1> as four characters. The part after the "=" must be done with 877 the actual keys, not the literal text. 878 Another solution is to use the actual key code in the mapping for the second 879 special key: > 880 :map <F1><Esc>OP :echo "yes"<CR> 881 Don't type a real <Esc>, Vim will recognize the key code and replace it with 882 <F1> anyway. 883 884 Another problem may be that when keeping ALT or Meta pressed the terminal 885 prepends ESC instead of setting the 8th bit. See |:map-alt-keys|. 886 887 *recursive_mapping* 888 If you include the {lhs} in the {rhs} you have a recursive mapping. When 889 {lhs} is typed, it will be replaced with {rhs}. When the {lhs} which is 890 included in {rhs} is encountered it will be replaced with {rhs}, and so on. 891 This makes it possible to repeat a command an infinite number of times. The 892 only problem is that the only way to stop this is by causing an error. The 893 macros to solve a maze uses this, look there for an example. There is one 894 exception: If the {rhs} starts with {lhs}, the first character is not mapped 895 again (this is Vi compatible). 896 For example: > 897 :map ab abcd 898 will execute the "a" command and insert "bcd" in the text. The "ab" in the 899 {rhs} will not be mapped again. 900 901 If you want to exchange the meaning of two keys you should use the :noremap 902 command. For example: > 903 :noremap k j 904 :noremap j k 905 This will exchange the cursor up and down commands. 906 907 With the normal :map command, when the 'remap' option is on, mapping takes 908 place until the text is found not to be a part of a {lhs}. For example, if 909 you use: > 910 :map x y 911 :map y x 912 Vim will replace x with y, and then y with x, etc. When this has happened 913 'maxmapdepth' times (default 1000), Vim will give the error message 914 "recursive mapping". 915 916 *:map-undo* 917 If you include an undo command inside a mapped sequence, this will bring the 918 text back in the state before executing the macro. This is compatible with 919 the original Vi, as long as there is only one undo command in the mapped 920 sequence (having two undo commands in a mapped sequence did not make sense 921 in the original Vi, you would get back the text before the first undo). 922 923 924 1.10 MAPPING ALT-KEYS *:map-alt-keys* 925 926 For a readable mapping command the <A-k> form can be used. Note that <A-k> 927 and <A-K> are different, the latter will use an upper case letter. Actually, 928 <A-K> and <A-S-K> are the same. Instead of "A" you can use "M". If you have 929 an actual Meta modifier key, please see |:map-meta-keys|. 930 931 In the GUI Vim handles the Alt key itself, thus mapping keys with ALT should 932 always work. But in a terminal Vim gets a sequence of bytes and has to figure 933 out whether ALT was pressed or not. 934 935 If the terminal supports the modifyOtherKeys mode and it has been enabled, 936 then Vim can recognize more key combinations, see |modifyOtherKeys| below. 937 The Kitty keyboard protocol works in a similar way, see 938 |kitty-keyboard-protocol|. 939 940 By default Vim assumes that pressing the ALT key sets the 8th bit of a typed 941 character. Most decent terminals can work that way, such as xterm, aterm and 942 rxvt. If your <A-k> mappings don't work it might be that the terminal is 943 prefixing the character with an ESC character. But you can just as well type 944 ESC before a character, thus Vim doesn't know what happened (except for 945 checking the delay between characters, which is not reliable). 946 947 As of this writing, some mainstream terminals like gnome-terminal and konsole 948 use the ESC prefix. There doesn't appear a way to have them use the 8th bit 949 instead. Xterm should work well by default. Aterm and rxvt should work well 950 when started with the "--meta8" argument. You can also tweak resources like 951 "metaSendsEscape", "eightBitInput" and "eightBitOutput". 952 953 On the Linux console, this behavior can be toggled with the "setmetamode" 954 command. Bear in mind that not using an ESC prefix could get you in trouble 955 with other programs. You should make sure that bash has the "convert-meta" 956 option set to "on" in order for your Meta keybindings to still work on it 957 (it's the default readline behavior, unless changed by specific system 958 configuration). For that, you can add the line: > 959 960 set convert-meta on 961 962 to your ~/.inputrc file. If you're creating the file, you might want to use: > 963 964 $include /etc/inputrc 965 966 as the first line, if that file exists on your system, to keep global options. 967 This may cause a problem for entering special characters, such as the umlaut. 968 Then you should use CTRL-V before that character. 969 970 Bear in mind that convert-meta has been reported to have troubles when used in 971 UTF-8 locales. On terminals like xterm, the "metaSendsEscape" resource can be 972 toggled on the fly through the "Main Options" menu, by pressing Ctrl-LeftClick 973 on the terminal; that's a good last resource in case you want to send ESC when 974 using other applications but not when inside Vim. 975 976 977 1.11 MAPPING META-KEYS *:map-meta-keys* 978 979 Mapping keys with the Meta modifier works very similar to using the Alt key. 980 What key on your keyboard produces the Meta modifier depends on your keyboard 981 and configuration. 982 983 Note that mapping <M-a> actually is for using the Alt key. That can be 984 confusing! It cannot be changed, it would not be backwards compatible. 985 986 For the Meta modifier the "T" character is used. For example, to map Meta-b 987 in Insert mode: > 988 :imap <T-b> terrible 989 990 1.12 MAPPING SUPER-KEYS or COMMAND-KEYS *:map-super-keys* *:map-cmd-key* 991 992 The Super modifier is available in GUI mode (when |gui_running| is 1) for gVim 993 on Linux and MacVim on Mac OS. If you're on a Mac, this represents the 994 Command key, on Linux with the GTK GUI it represents the Super key. 995 The character "D" is used for the Super / Command modifier. 996 997 For example, to map Command-b in Insert mode: > 998 :imap <D-b> barritone 999 1000 1.13 MAPPING IN modifyOtherKeys mode *modifyOtherKeys* 1001 1002 Xterm and a few other terminals can be put in a mode where keys with modifiers 1003 are sent with a special escape code. Vim recognizes these codes and can then 1004 make a difference between CTRL-H and Backspace, even when Backspace sends the 1005 character 8. And many more special keys, such as Tab and CTRL-I, which cannot 1006 be mapped separately otherwise. 1007 1008 For xterm modifyOtherKeys is enabled in the builtin termcap entry. If this is 1009 not used you can enable modifyOtherKeys with these lines in your vimrc: > 1010 let &t_TI = "\<Esc>[>4;2m" 1011 let &t_TE = "\<Esc>[>4;m" 1012 1013 This sets modifyOtherKeys to level 2. Note that modifyOtherKeys level 1 does 1014 not work. Some terminals do not support level 2 and then send key codes that 1015 Vim will not be able to correctly recognize. 1016 1017 In case the modifyOtherKeys mode causes problems you can disable it: > 1018 let &t_TI = "" 1019 let &t_TE = "" 1020 It does not take effect immediately. To have this work without restarting Vim 1021 execute a shell command, e.g.: `!ls` Or put the lines in your |vimrc|. 1022 1023 When modifyOtherKeys is enabled you can map <C-[> and <C-S-{>: > 1024 imap <C-[> [[[ 1025 imap <C-{> {{{ 1026 Without modifyOtherKeys <C-[> and <C-{> are indistinguishable from Esc. 1027 Note that <C-{> is used and not <C-S-[> or <C-S-{>. This works on most 1028 keyboards. Similarly, <C-}> is used instead of <C-S-]> or <C-S-}> and 1029 <C-|> instead of <C-S-\> or <C-S-|>. Note that '|' has a special meaning in a 1030 mapping, see |map-bar|. 1031 1032 WARNING: if you map <C-[> you may very well break any key codes that start 1033 with Esc. Make sure it comes AFTER other mappings. 1034 1035 Starting with xterm version 377 Vim can detect the modifyOtherKeys state by 1036 requesting it. For this the 't_RK' termcap entry is used. When the response 1037 is found then Vim will know whether modifyOtherKeys level 2 is enabled, and 1038 handle mappings accordingly. 1039 1040 Before version 377 Vim automatically detects if the modifyOtherKeys mode was 1041 enabled when it spots an escape sequence that must have been created by it. 1042 To see if Vim detected such an escape sequence use `:verbose map`, the first 1043 line will then show "Seen modifyOtherKeys: true" (possibly translated). 1044 1045 This automatic detection depends on receiving an escape code starting with 1046 "<1b>[27;". This is the normal way xterm sends these key codes. However, if 1047 the *formatOtherKeys* resource is set another form is used that is not 1048 recognized, therefore you must not set formatOtherKeys. 1049 1050 A known side effect is that in Insert mode the raw escape sequence is inserted 1051 after the CTRL-V key. This can be used to check whether modifyOtherKeys is 1052 enabled: In Insert mode type CTRL-SHIFT-V CTRL-V, if you get one byte then 1053 modifyOtherKeys is off, if you get <1b>[27;5;118~ then it is on. 1054 1055 Note that xterm up to version 376 has a bug that makes Shift-Esc send a 1056 regular Esc code, the Shift modifier is dropped. 1057 1058 When the 'esckeys' option is off, then modifyOtherKeys will be disabled in 1059 Insert mode to avoid every key with a modifier causing Insert mode to end. 1060 1061 1062 1.14 MAPPING WITH KITTY KEYBOARD PROTOCOL *kitty-keyboard-protocol* 1063 1064 If the value of 'term' contains "kitty" then Vim will send out an escape 1065 sequence to enable the Kitty keyboard protocol. This can be changed with the 1066 'keyprotocol' option. 1067 1068 Like modifyOtherKeys, this will make it possible to distinguish between more 1069 keys with modifiers. Also, this protocol sends an escape sequence for the Esc 1070 key, so that Vim does not need to use a timeout to know whether receiving an 1071 Esc character means the Esc key was pressed or it's the start of an escape 1072 sequence. 1073 1074 Vim automatically detects if the Kitty keyboard protocol was enabled when it 1075 spots the response to the status request (this should be part of the |t_TI| 1076 termcap entry). To see if Vim detected such an escape sequence use: > 1077 :verbose map 1078 The first line will then show "Kitty keyboard protocol: {value}" (possibly 1079 translated). The meaning of {value}: 1080 Unknown no status received yet 1081 Off protocol is not used 1082 On protocol is used 1083 Disabled protocol was used but expected to have been disabled 1084 by 't_TE' 1085 Cleared protocol expected to have been disabled by 't_TE', 1086 previous state is unknown 1087 1088 1089 1.15 MAPPING AN OPERATOR *:map-operator* 1090 1091 An operator is used before a {motion} command. To define your own operator 1092 you must create a mapping that first sets the 'operatorfunc' option and then 1093 invoke the |g@| operator. After the user types the {motion} command the 1094 specified function will be called. 1095 1096 *g@* *E774* *E775* 1097 g@{motion} Call the function set by the 'operatorfunc' option. 1098 The '[ mark is positioned at the start of the text 1099 moved over by {motion}, the '] mark on the last 1100 character of the text. 1101 The function is called with one String argument: 1102 "line" {motion} was |linewise| 1103 "char" {motion} was |characterwise| 1104 "block" {motion} was |blockwise-visual| 1105 The type can be forced, see |forced-motion|. 1106 {not available when compiled without the |+eval| 1107 feature} 1108 1109 Here is an example that counts the number of spaces with <F4>: > 1110 1111 nnoremap <expr> <F4> CountSpaces() 1112 xnoremap <expr> <F4> CountSpaces() 1113 " doubling <F4> works on a line 1114 nnoremap <expr> <F4><F4> CountSpaces() .. '_' 1115 1116 function CountSpaces(context = {}, type = '') abort 1117 if a:type == '' 1118 let context = #{ 1119 \ dot_command: v:false, 1120 \ extend_block: '', 1121 \ virtualedit: [&l:virtualedit, &g:virtualedit], 1122 \ } 1123 let &operatorfunc = function('CountSpaces', [context]) 1124 set virtualedit=block 1125 return 'g@' 1126 endif 1127 1128 let save = #{ 1129 \ clipboard: &clipboard, 1130 \ selection: &selection, 1131 \ virtualedit: [&l:virtualedit, &g:virtualedit], 1132 \ register: getreginfo('"'), 1133 \ visual_marks: [getpos("'<"), getpos("'>")], 1134 \ } 1135 1136 try 1137 set clipboard= selection=inclusive virtualedit= 1138 let commands = #{ 1139 \ line: "'[V']", 1140 \ char: "`[v`]", 1141 \ block: "`[\<C-V>`]", 1142 \ }[a:type] 1143 let [_, _, col, off] = getpos("']") 1144 if off != 0 1145 let vcol = getline("'[")->strpart(0, col + off)->strdisplaywidth() 1146 if vcol >= [line("'["), '$']->virtcol() - 1 1147 let a:context.extend_block = '$' 1148 else 1149 let a:context.extend_block = vcol .. '|' 1150 endif 1151 endif 1152 if a:context.extend_block != '' 1153 let commands ..= 'oO' .. a:context.extend_block 1154 endif 1155 let commands ..= 'y' 1156 execute 'silent noautocmd keepjumps normal! ' .. commands 1157 echomsg getreg('"')->count(' ') 1158 finally 1159 call setreg('"', save.register) 1160 call setpos("'<", save.visual_marks[0]) 1161 call setpos("'>", save.visual_marks[1]) 1162 let &clipboard = save.clipboard 1163 let &selection = save.selection 1164 let [&l:virtualedit, &g:virtualedit] = get(a:context.dot_command ? save : a:context, 'virtualedit') 1165 let a:context.dot_command = v:true 1166 endtry 1167 endfunction 1168 1169 An <expr> mapping is used to be able to fetch any prefixed count and register. 1170 This also avoids using a command line, which would trigger CmdlineEnter and 1171 CmdlineLeave autocommands. 1172 1173 Note that the 'selection' option is temporarily set to "inclusive" to be able 1174 to yank exactly the right text by using Visual mode from the '[ to the '] 1175 mark. 1176 1177 Also note that the 'clipboard' option is temporarily emptied to avoid 1178 clobbering the `"*` or `"+` registers, if its value contains the item `unnamed` 1179 or `unnamedplus`. 1180 1181 The `mode()` function will return the state as it will be after applying the 1182 operator. 1183 1184 Here is an example for using a lambda function to create a normal-mode 1185 operator to add quotes around text in the current line: > 1186 1187 nnoremap <F4> <Cmd>let &opfunc='{t -> 1188 \ getline(".") 1189 \ ->split("\\zs") 1190 \ ->insert("\"", col("'']")) 1191 \ ->insert("\"", col("''[") - 1) 1192 \ ->join("") 1193 \ ->setline(".")}'<CR>g@ 1194 1195 ============================================================================== 1196 2. Abbreviations *abbreviations* *Abbreviations* 1197 1198 Abbreviations are used in Insert mode, Replace mode and Command-line mode. 1199 If you enter a word that is an abbreviation, it is replaced with the word it 1200 stands for. This can be used to save typing for often used long words. And 1201 you can use it to automatically correct obvious spelling errors. 1202 Examples: 1203 1204 :iab ms Microsoft 1205 :iab tihs this 1206 1207 There are three types of abbreviations: 1208 1209 full-id The "full-id" type consists entirely of keyword characters (letters 1210 and characters from 'iskeyword' option). This is the most common 1211 abbreviation. 1212 1213 Examples: "foo", "g3", "-1" 1214 1215 end-id The "end-id" type ends in a keyword character, but all the other 1216 characters are not keyword characters. 1217 1218 Examples: "#i", "..f", "$/7" 1219 1220 non-id The "non-id" type ends in a non-keyword character, the other 1221 characters may be of any type, excluding space and tab. {this type 1222 is not supported by Vi} 1223 1224 Examples: "def#", "4/7$" 1225 1226 Examples of strings that cannot be abbreviations: "a.b", "#def", "a b", "_$r" 1227 1228 An abbreviation is only recognized when you type a non-keyword character. 1229 This can also be the <Esc> that ends Insert mode or the <CR> that ends a 1230 command. The non-keyword character which ends the abbreviation is inserted 1231 after the expanded abbreviation. An exception to this is the character <C-]>, 1232 which is used to expand an abbreviation without inserting any extra 1233 characters. 1234 1235 Example: > 1236 :ab hh hello 1237 < "hh<Space>" is expanded to "hello<Space>" 1238 "hh<C-]>" is expanded to "hello" 1239 1240 The characters before the cursor must match the abbreviation. Each type has 1241 an additional rule: 1242 1243 full-id In front of the match is a non-keyword character, or this is where 1244 the line or insertion starts. Exception: When the abbreviation is 1245 only one character, it is not recognized if there is a non-keyword 1246 character in front of it, other than a space or a tab. However, for 1247 the command line "'<,'>" (or any other marks) is ignored, as if the 1248 command line starts after it. 1249 1250 end-id In front of the match is a keyword character, or a space or a tab, 1251 or this is where the line or insertion starts. 1252 1253 non-id In front of the match is a space, tab or the start of the line or 1254 the insertion. 1255 1256 Examples: ({CURSOR} is where you type a non-keyword character) > 1257 :ab foo four old otters 1258 < " foo{CURSOR}" is expanded to " four old otters" 1259 " foobar{CURSOR}" is not expanded 1260 "barfoo{CURSOR}" is not expanded 1261 > 1262 :ab #i #include 1263 < "#i{CURSOR}" is expanded to "#include" 1264 ">#i{CURSOR}" is not expanded 1265 > 1266 :ab ;; <endofline> 1267 < "test;;" is not expanded 1268 "test ;;" is expanded to "test <endofline>" 1269 1270 To avoid the abbreviation in Insert mode: Type CTRL-V before the character 1271 that would trigger the abbreviation. E.g. CTRL-V <Space>. Or type part of 1272 the abbreviation, exit insert mode with <Esc>, re-enter insert mode with "a" 1273 and type the rest. 1274 1275 To avoid the abbreviation in Command-line mode: Type CTRL-V twice somewhere in 1276 the abbreviation to avoid it to be replaced. A CTRL-V in front of a normal 1277 character is mostly ignored otherwise. 1278 1279 It is possible to move the cursor after an abbreviation: > 1280 :iab if if ()<Left> 1281 This does not work if 'cpoptions' includes the '<' flag. |<>| 1282 1283 You can even do more complicated things. For example, to consume the space 1284 typed after an abbreviation: > 1285 func Eatchar(pat) 1286 let c = nr2char(getchar(0)) 1287 return (c =~ a:pat) ? '' : c 1288 endfunc 1289 iabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR> 1290 1291 There are no default abbreviations. 1292 1293 Abbreviations are never recursive. You can use ":ab f f-o-o" without any 1294 problem. But abbreviations can be mapped. {some versions of Vi support 1295 recursive abbreviations, for no apparent reason} 1296 1297 Abbreviations are disabled if the 'paste' option is on. 1298 1299 *:abbreviate-local* *:abbreviate-<buffer>* 1300 Just like mappings, abbreviations can be local to a buffer. This is mostly 1301 used in a |filetype-plugin| file. Example for a C plugin file: > 1302 :abb <buffer> FF for (i = 0; i < ; ++i) 1303 < 1304 *:ab* *:abbreviate* 1305 :ab[breviate] list all abbreviations. The character in the first 1306 column indicates the mode where the abbreviation is 1307 used: 'i' for insert mode, 'c' for Command-line 1308 mode, '!' for both. These are the same as for 1309 mappings, see |map-listing|. 1310 1311 *:abbreviate-verbose* 1312 When 'verbose' is non-zero, listing an abbreviation will also display where it 1313 was last defined. Example: > 1314 1315 :verbose abbreviate 1316 ! teh the 1317 Last set from /home/abcd/vim/abbr.vim 1318 1319 See |:verbose-cmd| for more information. 1320 1321 :ab[breviate] {lhs} list the abbreviations that start with {lhs} 1322 You may need to insert a CTRL-V (type it twice) to 1323 avoid that a typed {lhs} is expanded, since 1324 command-line abbreviations apply here. 1325 1326 :ab[breviate] [<expr>] [<buffer>] {lhs} {rhs} 1327 add abbreviation for {lhs} to {rhs}. If {lhs} already 1328 existed it is replaced with the new {rhs}. {rhs} may 1329 contain spaces. 1330 See |:map-<expr>| for the optional <expr> argument. 1331 See |:map-<buffer>| for the optional <buffer> argument. 1332 1333 *:una* *:unabbreviate* 1334 :una[bbreviate] [<buffer>] {lhs} 1335 Remove abbreviation for {lhs} from the list. If none 1336 is found, remove abbreviations in which {lhs} matches 1337 with the {rhs}. This is done so that you can even 1338 remove abbreviations after expansion. To avoid 1339 expansion insert a CTRL-V (type it twice). 1340 1341 *:norea* *:noreabbrev* 1342 :norea[bbrev] [<expr>] [<buffer>] [lhs] [rhs] 1343 Same as ":ab", but no remapping for this {rhs}. 1344 1345 *:ca* *:cab* *:cabbrev* 1346 :ca[bbrev] [<expr>] [<buffer>] [lhs] [rhs] 1347 Same as ":ab", but for Command-line mode only. 1348 1349 *:cuna* *:cunabbrev* 1350 :cuna[bbrev] [<buffer>] {lhs} 1351 Same as ":una", but for Command-line mode only. 1352 1353 *:cnorea* *:cnoreabbrev* 1354 :cnorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs] 1355 same as ":ab", but for Command-line mode only and no 1356 remapping for this {rhs} 1357 1358 *:ia* *:iabbrev* 1359 :ia[bbrev] [<expr>] [<buffer>] [lhs] [rhs] 1360 Same as ":ab", but for Insert mode only. 1361 1362 *:iuna* *:iunabbrev* 1363 :iuna[bbrev] [<buffer>] {lhs} 1364 Same as ":una", but for insert mode only. 1365 1366 *:inorea* *:inoreabbrev* 1367 :inorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs] 1368 Same as ":ab", but for Insert mode only and no 1369 remapping for this {rhs}. 1370 1371 *:abc* *:abclear* 1372 :abc[lear] [<buffer>] Remove all abbreviations. 1373 1374 *:iabc* *:iabclear* 1375 :iabc[lear] [<buffer>] Remove all abbreviations for Insert mode. 1376 1377 *:cabc* *:cabclear* 1378 :cabc[lear] [<buffer>] Remove all abbreviations for Command-line mode. 1379 1380 *using_CTRL-V* 1381 It is possible to use special characters in the rhs of an abbreviation. 1382 CTRL-V has to be used to avoid the special meaning of most non printable 1383 characters. How many CTRL-Vs need to be typed depends on how you enter the 1384 abbreviation. This also applies to mappings. Let's use an example here. 1385 1386 Suppose you want to abbreviate "esc" to enter an <Esc> character. When you 1387 type the ":ab" command in Vim, you have to enter this: (here ^V is a CTRL-V 1388 and ^[ is <Esc>) 1389 1390 You type: ab esc ^V^V^V^V^V^[ 1391 1392 All keyboard input is subjected to ^V quote interpretation, so 1393 the first, third, and fifth ^V characters simply allow the second, 1394 and fourth ^Vs, and the ^[, to be entered into the command-line. 1395 1396 You see: ab esc ^V^V^[ 1397 1398 The command-line contains two actual ^Vs before the ^[. This is 1399 how it should appear in your .exrc file, if you choose to go that 1400 route. The first ^V is there to quote the second ^V; the :ab 1401 command uses ^V as its own quote character, so you can include quoted 1402 whitespace or the | character in the abbreviation. The :ab command 1403 doesn't do anything special with the ^[ character, so it doesn't need 1404 to be quoted. (Although quoting isn't harmful; that's why typing 7 1405 [but not 8!] ^Vs works.) 1406 1407 Stored as: esc ^V^[ 1408 1409 After parsing, the abbreviation's short form ("esc") and long form 1410 (the two characters "^V^[") are stored in the abbreviation table. 1411 If you give the :ab command with no arguments, this is how the 1412 abbreviation will be displayed. 1413 1414 Later, when the abbreviation is expanded because the user typed in 1415 the word "esc", the long form is subjected to the same type of 1416 ^V interpretation as keyboard input. So the ^V protects the ^[ 1417 character from being interpreted as the "exit Insert mode" character. 1418 Instead, the ^[ is inserted into the text. 1419 1420 Expands to: ^[ 1421 1422 [example given by Steve Kirkendall] 1423 1424 ============================================================================== 1425 3. Local mappings and functions *script-local* 1426 1427 When using several Vim script files, there is the danger that mappings and 1428 functions used in one script use the same name as in other scripts. To avoid 1429 this, they can be made local to the script. 1430 1431 *<SID>* *<SNR>* *E81* 1432 The string "<SID>" can be used in a mapping or menu. This requires that the 1433 '<' flag is not present in 'cpoptions'. This is useful if you have a 1434 script-local function that you want to call from a mapping in the same script. 1435 When executing the map command, Vim will replace "<SID>" with the special 1436 key code <SNR>, followed by a number that's unique for the script, and an 1437 underscore. Example: > 1438 :map <SID>Add 1439 would define a mapping "<SNR>23_Add". 1440 1441 When defining a function in a script, "s:" can be prepended to the name to 1442 make it local to the script (in |Vim9| script functions without a prefix are 1443 local to the script). But when a mapping is executed from outside of 1444 the script, it doesn't know in which script the function was defined. To 1445 avoid this problem, use "<SID>" instead of "s:". The same translation is done 1446 as for mappings. This makes it possible to define a call to the function in 1447 a mapping. 1448 1449 When a local function is executed, it runs in the context of the script it was 1450 defined in. This means that new functions and mappings it defines can also 1451 use "s:" or "<SID>" and it will use the same unique number as when the 1452 function itself was defined. Also, the "s:var" local script variables can be 1453 used. 1454 1455 When executing an autocommand or a user command, it will run in the context of 1456 the script it was defined in. This makes it possible that the command calls a 1457 local function or uses a local mapping. 1458 1459 In case the value is used in a context where <SID> cannot be correctly 1460 expanded, use the expand() function: > 1461 let &includexpr = expand('<SID>') .. 'My_includeexpr()' 1462 1463 Otherwise, using "<SID>" outside of a script context is an error. 1464 1465 If you need to get the script number to use in a complicated script, you can 1466 use this function: > 1467 func s:ScriptNumber() 1468 return matchstr(expand('<SID>'), '<SNR>\zs\d\+\ze_') 1469 endfunc 1470 1471 The "<SNR>" will be shown when listing functions and mappings. This is useful 1472 to find out what they are defined to. 1473 1474 The |:scriptnames| command can be used to see which scripts have been sourced 1475 and what their <SNR> number is. 1476 1477 This is all {not available when compiled without the |+eval| feature}. 1478 1479 ============================================================================== 1480 4. User-defined commands *user-commands* 1481 1482 It is possible to define your own Ex commands. A user-defined command can act 1483 just like a built-in command (it can have a range or arguments, arguments can 1484 be completed as filenames or buffer names, etc), except that when the command 1485 is executed, it is transformed into a normal Ex command and then executed. 1486 1487 For starters: See section |40.2| in the user manual. 1488 1489 *E183* *E841* *user-cmd-ambiguous* 1490 All user defined commands must start with an uppercase letter, to avoid 1491 confusion with builtin commands. Exceptions are these builtin commands: 1492 :Next 1493 :X 1494 They cannot be used for a user defined command. ":Print" is also an existing 1495 command, but it is deprecated and can be overruled. 1496 1497 The other characters of the user command can be uppercase letters, lowercase 1498 letters or digits. When using digits, note that other commands that take a 1499 numeric argument may become ambiguous. For example, the command ":Cc2" could 1500 be the user command ":Cc2" without an argument, or the command ":Cc" with 1501 argument "2". It is advised to put a space between the command name and the 1502 argument to avoid these problems. 1503 1504 When using a user-defined command, the command can be abbreviated. However, 1505 if an abbreviation is not unique, an error will be issued. Furthermore, a 1506 built-in command will always take precedence. 1507 1508 Example: > 1509 :command Rename ... 1510 :command Renumber ... 1511 :Rena " Means "Rename" 1512 :Renu " Means "Renumber" 1513 :Ren " Error - ambiguous 1514 :command Paste ... 1515 :P " The built-in :Print 1516 1517 It is recommended that full names for user-defined commands are used in 1518 scripts. 1519 1520 :com[mand] *:com* *:command* 1521 List all user-defined commands. When listing 1522 commands, the characters in the first columns are: 1523 ! Command has the -bang attribute 1524 " Command has the -register attribute 1525 | Command has the -bar attribute 1526 b Command is local to current buffer 1527 (see below for details on attributes) 1528 The list can be filtered on command name with 1529 |:filter|, e.g., to list all commands with "Pyth" in 1530 the name: > 1531 filter Pyth command 1532 1533 :com[mand] {cmd} List the user-defined commands that start with {cmd} 1534 1535 *:command-verbose* 1536 When 'verbose' is non-zero, listing a command will also display where it was 1537 last defined and any completion argument. Example: > 1538 1539 :verbose command TOhtml 1540 < Name Args Range Complete Definition ~ 1541 TOhtml 0 % :call Convert2HTML(<line1>, <line2>) ~ 1542 Last set from /usr/share/vim/vim-7.0/plugin/tohtml.vim ~ 1543 1544 See |:verbose-cmd| for more information. 1545 1546 *E174* *E182* 1547 :com[mand][!] [{attr}...] {cmd} {repl} 1548 Define a user command. The name of the command is 1549 {cmd} and its replacement text is {repl}. The 1550 command's attributes (see below) are {attr}. If the 1551 command already exists, an error is reported, unless a 1552 ! is specified, in which case the command is 1553 redefined. There is one exception: When sourcing a 1554 script again, a command that was previously defined in 1555 that script will be silently replaced. 1556 1557 1558 :delc[ommand] {cmd} *:delc* *:delcommand* *E184* 1559 Delete the user-defined command {cmd}. 1560 This is not allowed while listing commands, e.g. from 1561 a timer. *E1311* 1562 1563 :delc[ommand] -buffer {cmd} *E1237* 1564 Delete the user-defined command {cmd} that was defined 1565 for the current buffer. 1566 1567 :comc[lear] *:comc* *:comclear* 1568 Delete all user-defined commands. 1569 1570 1571 Command attributes ~ 1572 *command-attributes* 1573 User-defined commands are treated by Vim just like any other Ex commands. 1574 They can have arguments, or have a range specified. Arguments are subject to 1575 completion as filenames, buffers, etc. Exactly how this works depends upon 1576 the command's attributes, which are specified when the command is defined. 1577 1578 When defining a user command in a script, it will be able to call functions 1579 local to the script and use mappings local to the script. When the user 1580 invokes the user command, it will run in the context of the script it was 1581 defined in. This matters if |<SID>| is used in a command. 1582 1583 There are a number of attributes, split into four categories: argument 1584 handling, completion behavior, range handling, and special cases. The 1585 attributes are described below, by category. 1586 1587 1588 Argument handling ~ 1589 *E175* *E176* *:command-nargs* 1590 By default, a user defined command will take no arguments (and an error is 1591 reported if any are supplied). However, it is possible to specify that the 1592 command can take arguments, using the -nargs attribute. Valid cases are: 1593 1594 -nargs=0 No arguments are allowed (the default) 1595 -nargs=1 Exactly one argument is required, it includes spaces; 1596 completion treats white spaces as argument separation 1597 -nargs=_ Exactly one argument is required, it includes spaces; 1598 completion treats white spaces as part of the argument 1599 -nargs=* Any number of arguments are allowed (0, 1, or many), 1600 separated by white space 1601 -nargs=? 0 or 1 arguments are allowed 1602 -nargs=+ Arguments must be supplied, but any number are allowed 1603 1604 Arguments are considered to be separated by (unescaped) spaces or tabs in this 1605 context, except when there is one argument, then the white space is part of 1606 the argument. The difference between the "-nargs=1" and "-nargs=_": > 1607 1608 func MyComplete(ArgLead, CmdLine, CursorPos) 1609 return ["one value", "two values", "three values"] 1610 \->matchfuzzy(a:ArgLead) 1611 endfunc 1612 :command -nargs=1 -complete=customlist,MyComplete MyCmd1 echo <q-args> 1613 :command -nargs=_ -complete=customlist,MyComplete MyCmd2 echo <q-args> 1614 1615 Completing ":MyCmd1 two va<tab>" will complete with: > 1616 1617 :MyCmd1 two one value 1618 1619 Completing ":MyCmd2 two va<tab>" will complete with: > 1620 1621 :MyCmd2 two values 1622 1623 Use -nargs=_ when the whole argument area should be taken as a single value 1624 as-is. When you need several arguments and an individual argument may itself 1625 contain spaces (so the splitter must keep running), use -nargs=+/* together 1626 with |:command-completeopt| (-completeopt=escape) instead. 1627 1628 1629 Note that arguments are used as text, not as expressions. Specifically, 1630 "s:var" will use the script-local variable in the script where the command was 1631 defined, not where it is invoked! Example: 1632 script1.vim: > 1633 :let s:error = "None" 1634 :command -nargs=1 Error echoerr <args> 1635 < script2.vim: > 1636 :source script1.vim 1637 :let s:error = "Wrong!" 1638 :Error s:error 1639 Executing script2.vim will result in "None" being echoed. Not what you 1640 intended! Calling a function may be an alternative. 1641 1642 1643 Completion behavior ~ 1644 *:command-completion* *E179* *E180* *E181* 1645 *:command-complete* 1646 By default, the arguments of user defined commands do not undergo completion. 1647 However, by specifying one or the other of the following attributes, argument 1648 completion can be enabled: 1649 1650 -complete=arglist file names in argument list 1651 -complete=augroup autocmd groups 1652 -complete=behave |:behave| suboptions 1653 -complete=breakpoint |:breakadd| suboptions 1654 -complete=buffer buffer names 1655 -complete=color color schemes 1656 -complete=command Ex command (and arguments) 1657 -complete=compiler compilers 1658 -complete=cscope |:cscope| suboptions 1659 -complete=diff_buffer diff buffer names 1660 -complete=dir directory names 1661 -complete=dir_in_path directory names in 'cdpath' 1662 -complete=environment environment variable names 1663 -complete=event autocommand events 1664 -complete=expression Vim expression 1665 -complete=file file and directory names 1666 -complete=file_in_path file and directory names in 'path' 1667 -complete=filetype filetype names 'filetype' 1668 -complete=function function name 1669 -complete=help help subjects 1670 -complete=highlight highlight groups 1671 -complete=history |:history| suboptions 1672 -complete=keymap keyboard mappings 1673 -complete=locale locale names (as output of locale -a) 1674 -complete=mapclear buffer argument 1675 -complete=mapping mapping name 1676 -complete=menu menus 1677 -complete=messages |:messages| suboptions 1678 -complete=option options 1679 -complete=packadd optional package |pack-add| names 1680 -complete=retab |:retab| suboptions 1681 -complete=runtime file and directory names in 'runtimepath' 1682 -complete=scriptnames sourced script names 1683 -complete=shellcmd Shell command 1684 -complete=shellcmdline First is a shell command and subsequent ones 1685 are filenames. The same behavior as |:!cmd|. 1686 To get correct completion, |:command-nargs| 1687 should be '*' or '+' 1688 -complete=sign |:sign| suboptions 1689 -complete=syntax syntax file names 'syntax' 1690 -complete=syntime |:syntime| suboptions 1691 -complete=tag tags 1692 -complete=tag_listfiles tags, file names are shown when CTRL-D is hit 1693 -complete=user user names 1694 -complete=var user variables 1695 -complete=custom,{func} custom completion, defined via {func} 1696 -complete=customlist,{func} custom completion, defined via {func} 1697 1698 If you specify completion while there is nothing to complete (-nargs=0, the 1699 default) then you get error *E1208* . 1700 Note: That some completion methods might expand environment variables. 1701 1702 1703 Custom completion ~ 1704 *:command-completion-custom* 1705 *:command-completion-customlist* *E467* *E468* 1706 It is possible to define customized completion schemes via the "custom,{func}" 1707 or the "customlist,{func}" completion argument. The {func} part should be a 1708 function with the following signature: > 1709 1710 :function {func}(ArgLead, CmdLine, CursorPos) 1711 1712 The function need not use all these arguments. The function should provide 1713 the completion candidates as the return value. 1714 1715 For the "custom" argument, the function should return the completion 1716 candidates one per line in a newline separated string. 1717 *E1303* 1718 For the "customlist" argument, the function should return the completion 1719 candidates as a Vim List. Each item may be either a string or a |Dictionary|. 1720 A Dictionary item may have the following keys: 1721 word (required) the text inserted into the command line when the 1722 item is selected 1723 abbr alternative text shown in the popup menu in place of "word", 1724 when 'wildoptions' contains "pum"; useful when the inserted 1725 text and the displayed text should differ 1726 kind short kind text (one or two characters), shown in the popup 1727 menu when 'wildoptions' contains "pum" 1728 menu extra text shown after the match in the popup menu 1729 info long description shown in the info popup; the |+popupwin| 1730 feature is required to display it 1731 Items that are neither a string nor a Dictionary, and Dictionary items without 1732 a "word" key, are ignored. When 'wildoptions' does not contain "pum", only 1733 "word" is shown. 1734 1735 The function arguments are: 1736 ArgLead the leading portion of the argument currently being 1737 completed on; note that this only captures the current 1738 space-separated word, even when using "-nargs=1" 1739 CmdLine the entire command line 1740 CursorPos the cursor position in it (byte index) 1741 The function may use these for determining context. For the "custom" 1742 argument, it is not necessary to filter candidates against the (implicit 1743 pattern in) ArgLead. Vim will filter the candidates with its regexp engine 1744 after function return, and this is probably more efficient in most cases. If 1745 'wildoptions' contains "fuzzy", then the candidates will be filtered using 1746 |fuzzy-matching|. For the "customlist" argument, Vim will not 1747 filter the returned completion candidates and the user supplied function 1748 should filter the candidates. 1749 1750 The following example lists user names to a Finger command > 1751 :com -complete=custom,ListUsers -nargs=1 Finger !finger <args> 1752 :fun ListUsers(A,L,P) 1753 : return system("cut -d: -f1 /etc/passwd") 1754 :endfun 1755 1756 The following example completes filenames from the directories specified in 1757 the 'path' option: > 1758 :com -nargs=1 -bang -complete=customlist,EditFileComplete 1759 \ EditFile edit<bang> <args> 1760 :fun EditFileComplete(A,L,P) 1761 : return split(globpath(&path, a:A), "\n") 1762 :endfun 1763 < 1764 This example does not work for file names with spaces! 1765 1766 *:command-completeopt* 1767 For the "custom" and "customlist" types you can further opt into specific 1768 behaviors with the -completeopt= attribute. It takes a comma-separated list 1769 of option names; currently only "escape" is recognized: 1770 1771 -completeopt=escape 1772 The completion function may return matches containing spaces, 1773 tabs or backslashes. When such a match is inserted into the 1774 command line each space, tab and backslash is preceded by a 1775 backslash so the value is preserved as a single argument. The 1776 unescaped form is used for display (popup menu / wildmenu / 1777 |getcompletion()|). The ArgLead passed to the completion 1778 function is also unescaped: when the user types 1779 `:Cmd foo\ b<Tab>` the function is called with `foo b`, not 1780 `foo\ b` . In the command's replacement text |<q-args>| and 1781 |<f-args>| likewise yield the unescaped value. 1782 1783 Example: > 1784 :func MyComplete(ArgLead, CmdLine, CursorPos) 1785 : return filter(['hello world', 'good morning'], 1786 : \ {_, v -> stridx(v, a:ArgLead) ==# 0}) 1787 :endfunc 1788 :com! -nargs=1 -complete=customlist,MyComplete -completeopt=escape MyCmd 1789 \ echo <q-args> 1790 < 1791 After `:MyCmd <Tab>` the popup shows `hello world` and `good morning`. Typing 1792 `:MyCmd hello\ w<Tab>` calls MyComplete with ArgLead set to `hello w` (the 1793 backslash before the space is removed), the filter finds `hello world`, and 1794 `<Tab>` inserts it as `:MyCmd hello\ world`. `<q-args>` then evaluates to the 1795 logical `hello world`. 1796 1797 Without -completeopt=escape the literal string `hello world` would be inserted 1798 into the command line, so Vim's argument splitter would treat it as two 1799 arguments. 1800 1801 -completeopt=escape and -nargs=_ (see |:command-nargs|) target different 1802 shapes; they are not competing solutions for the same one: 1803 "whole line as one argument, no escaping" 1804 use -nargs=_ 1805 "multiple arguments, each may contain spaces" 1806 use -nargs=+ or -nargs=* with -completeopt=escape 1807 Because -nargs=_ disables the argument splitter, escaping has no effect there, 1808 so combining -nargs=_ with -completeopt=escape is an error (E1579). 1809 1810 1811 Range handling ~ 1812 *E177* *E178* *:command-range* *:command-count* 1813 By default, user-defined commands do not accept a line number range. However, 1814 it is possible to specify that the command does take a range (the -range 1815 attribute), or that it takes an arbitrary count value, either in the line 1816 number position (-range=N, like the |:split| command) or as a "count" 1817 argument (-count=N, like the |:Next| command). The count will then be 1818 available in the argument with |<count>|. 1819 1820 Possible attributes are: 1821 1822 -range Range allowed, default is current line 1823 -range=% Range allowed, default is whole file (1,$) 1824 -range=N A count (default N) which is specified in the line 1825 number position (like |:split|); allows for zero line 1826 number. 1827 -count=N A count (default N) which is specified either in the line 1828 number position, or as an initial argument (like |:Next|). 1829 -count Acts like -count=0 1830 1831 Note that -range=N and -count=N are mutually exclusive - only one should be 1832 specified. 1833 1834 *:command-addr* 1835 It is possible that the special characters in the range like ., $ or % which 1836 by default correspond to the current line, last line and the whole buffer, 1837 relate to arguments, (loaded) buffers, windows or tab pages. 1838 1839 Possible values are (second column is the short name used in listing): 1840 -addr=lines Range of lines (the default for -range) 1841 -addr=arguments arg Range for arguments 1842 -addr=buffers buf Range for buffers (also not loaded buffers) 1843 -addr=loaded_buffers load Range for loaded buffers 1844 -addr=windows win Range for windows 1845 -addr=tabs tab Range for tab pages 1846 -addr=quickfix qf Range for quickfix entries 1847 -addr=other ? Other kind of range; can use ".", "$" and "%" 1848 as with "lines" (the default for -count) 1849 1850 1851 Special cases ~ 1852 *:command-bang* *:command-bar* 1853 *:command-register* *:command-buffer* 1854 *:command-keepscript* 1855 There are some special cases as well: 1856 1857 -bang The command can take a ! modifier (like :q or :w) 1858 -bar The command can be followed by a "|" and another command. 1859 A "|" inside the command argument is not allowed then. 1860 Also checks for a " to start a comment. 1861 -register The first argument to the command can be an optional 1862 register name (like :del, :put, :yank). 1863 -buffer The command will only be available in the current buffer. 1864 -keepscript Do not use the location of where the user command was 1865 defined for verbose messages, use the location of where 1866 the user command was invoked. 1867 1868 In the cases of the -count and -register attributes, if the optional argument 1869 is supplied, it is removed from the argument list and is available to the 1870 replacement text separately. 1871 Note that these arguments can be abbreviated, but that is a deprecated 1872 feature. Use the full name for new scripts. 1873 1874 1875 Replacement text ~ 1876 *:command-repl* 1877 The {repl} argument is normally one long string, possibly with "|" separated 1878 commands. A special case is when the argument is "{", then the following 1879 lines, up to a line starting with "}" are used and |Vim9| syntax applies. 1880 Example: > 1881 :command MyCommand { 1882 echo 'hello' 1883 g:calledMyCommand = true 1884 } 1885 < *E1231* 1886 There must be white space before the "{". No nesting is supported, inline 1887 functions cannot be used. Commands where a "|" may appear in the argument, 1888 such as commands with an expression argument, cannot be followed by a "|" and 1889 another command. 1890 1891 If the command is defined in Vim9 script (a script that starts with 1892 `:vim9script` and in a `:def` function) then {repl} will be executed as in Vim9 1893 script. Thus this depends on where the command is defined, not where it is 1894 used. 1895 1896 The replacement text {repl} for a user defined command is scanned for special 1897 escape sequences, using <...> notation. Escape sequences are replaced with 1898 values from the entered command line, and all other text is copied unchanged. 1899 The resulting string is executed as an Ex command. To avoid the replacement 1900 use <lt> in place of the initial <. Thus to include "<bang>" literally use 1901 "<lt>bang>". 1902 1903 The valid escape sequences are 1904 1905 *<line1>* 1906 <line1> The starting line of the command range. 1907 *<line2>* 1908 <line2> The final line of the command range. 1909 *<range>* 1910 <range> The number of items in the command range: 0, 1 or 2 1911 *<count>* 1912 <count> Any count supplied (as described for the '-range' 1913 and '-count' attributes). 1914 *<bang>* 1915 <bang> (See the '-bang' attribute) Expands to a ! if the 1916 command was executed with a ! modifier, otherwise 1917 expands to nothing. 1918 *<mods>* *<q-mods>* *:command-modifiers* 1919 <mods> The command modifiers, if specified. Otherwise, expands to 1920 nothing. Supported modifiers are |:aboveleft|, |:belowright|, 1921 |:botright|, |:browse|, |:confirm|, |:hide|, |:horizontal|, 1922 |:keepalt|, |:keepjumps|, |:keepmarks|, |:keeppatterns|, 1923 |:leftabove|, |:lockmarks|, |:noautocmd|, |:noswapfile|, 1924 |:rightbelow|, |:sandbox|, |:silent|, |:tab|, |:topleft|, 1925 |:unsilent|, |:verbose|, and |:vertical|. 1926 Note that |:filter| is not supported. 1927 Examples: > 1928 command! -nargs=+ -complete=file MyEdit 1929 \ for f in expand(<q-args>, 0, 1) | 1930 \ exe '<mods> split ' .. f | 1931 \ endfor 1932 1933 function! SpecialEdit(files, mods) 1934 for f in expand(a:files, 0, 1) 1935 exe a:mods .. ' split ' .. f 1936 endfor 1937 endfunction 1938 command! -nargs=+ -complete=file Sedit 1939 \ call SpecialEdit(<q-args>, <q-mods>) 1940 < 1941 *<reg>* *<register>* 1942 <reg> (See the '-register' attribute) The optional register, 1943 if specified. Otherwise, expands to nothing. <register> 1944 is a synonym for this. 1945 *<args>* 1946 <args> The command arguments, exactly as supplied (but as 1947 noted above, any count or register can consume some 1948 of the arguments, which are then not part of <args>). 1949 <lt> A single '<' (Less-Than) character. This is needed if you 1950 want to get a literal copy of one of these escape sequences 1951 into the expansion - for example, to get <bang>, use 1952 <lt>bang>. 1953 1954 *<q-args>* 1955 If the first two characters of an escape sequence are "q-" (for example, 1956 <q-args>) then the value is quoted in such a way as to make it a valid value 1957 for use in an expression. This uses the argument as one single value. 1958 When there is no argument <q-args> is an empty string. See the 1959 |q-args-example| below. 1960 *<f-args>* 1961 To allow commands to pass their arguments on to a user-defined function, there 1962 is a special form <f-args> ("function args"). This splits the command 1963 arguments at spaces and tabs, quotes each argument individually, and the 1964 <f-args> sequence is replaced by the comma-separated list of quoted arguments. 1965 See the Mycmd example below. If no arguments are given <f-args> is removed. 1966 To embed whitespace into an argument of <f-args>, prepend a backslash. 1967 <f-args> replaces every pair of backslashes (\\) with one backslash. A 1968 backslash followed by a character other than white space or a backslash 1969 remains unmodified. Also see |f-args-example| below. Overview: 1970 1971 command <f-args> ~ 1972 XX ab 'ab' 1973 XX a\b 'a\b' 1974 XX a\ b 'a b' 1975 XX a\ b 'a ', 'b' 1976 XX a\\b 'a\b' 1977 XX a\\ b 'a\', 'b' 1978 XX a\\\b 'a\\b' 1979 XX a\\\ b 'a\ b' 1980 XX a\\\\b 'a\\b' 1981 XX a\\\\ b 'a\\', 'b' 1982 XX [nothing] 1983 1984 1985 Note that if the "no arguments" situation is to be handled, you have to make 1986 sure that the function can be called without arguments. For a compiled 1987 function you might want to use variable arguments, see 1988 |vim9-variable-arguments|. 1989 1990 Examples for user commands: > 1991 1992 " Delete everything after here to the end 1993 :com Ddel +,$d 1994 1995 " Rename the current buffer 1996 :com -nargs=1 -bang -complete=file Ren f <args>|w<bang> 1997 1998 " Replace a range with the contents of a file 1999 " (Enter this all as one line) 2000 :com -range -nargs=1 -complete=file 2001 Replace <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d 2002 2003 " Count the number of lines in the range 2004 :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines" 2005 2006 < *f-args-example* 2007 Call a user function (example of <f-args>) > 2008 :com -nargs=* Mycmd call Myfunc(<f-args>) 2009 2010 When executed as: > 2011 :Mycmd arg1 arg2 2012 This will invoke: > 2013 :call Myfunc("arg1","arg2") 2014 2015 < *q-args-example* 2016 A more substantial example: > 2017 :function Allargs(command) 2018 : let i = 0 2019 : while i < argc() 2020 : if filereadable(argv(i)) 2021 : execute "e " .. argv(i) 2022 : execute a:command 2023 : endif 2024 : let i = i + 1 2025 : endwhile 2026 :endfunction 2027 :command -nargs=+ -complete=command Allargs call Allargs(<q-args>) 2028 2029 The command Allargs takes any Vim command(s) as argument and executes it on 2030 all files in the argument list. Usage example (note use of the "e" flag to 2031 ignore errors and the "update" command to write modified buffers): > 2032 :Allargs %s/foo/bar/ge|update 2033 This will invoke: > 2034 :call Allargs("%s/foo/bar/ge|update") 2035 < 2036 2037 vim:tw=78:ts=8:noet:ft=help:norl: