robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
7e778205ab
master
1*usr_40.txt* Nvim 2 3 4 VIM USER MANUAL by Bram Moolenaar 5 6 7 Make new commands 8 9 10Vim is an extensible editor. You can take a sequence of commands you use 11often and turn it into a new command. Or redefine an existing command. 12Autocommands make it possible to execute commands automatically. 13 14|40.1| Key mapping 15|40.2| Defining command-line commands 16|40.3| Autocommands 17 18 Next chapter: |usr_41.txt| Write a Vim script 19 Previous chapter: |usr_32.txt| The undo tree 20Table of contents: |usr_toc.txt| 21 22============================================================================== 23*40.1* Key mapping 24 25A simple mapping was explained in section |05.3|. The principle is that one 26sequence of key strokes is translated into another sequence of key strokes. 27This is a simple, yet powerful mechanism. 28 The simplest form is that one key is mapped to a sequence of keys. Since 29the function keys, except <F1>, have no predefined meaning in Vim, these are 30good choices to map. Example: > 31 32 :map <F2> GoDate: <Esc>:read !date<CR>kJ 33 34This shows how three modes are used. After going to the last line with "G", 35the "o" command opens a new line and starts Insert mode. The text "Date: " is 36inserted and <Esc> takes you out of insert mode. 37 Notice the use of special keys inside <>. This is called angle bracket 38notation. You type these as separate characters, not by pressing the key 39itself. This makes the mappings better readable and you can copy and paste 40the text without problems. 41 The ":" character takes Vim to the command line. The ":read !date" command 42reads the output from the "date" command and appends it below the current 43line. The <CR> is required to execute the ":read" command. 44 At this point of execution the text looks like this: 45 46 Date: ~ 47 Fri Jun 15 12:54:34 CEST 2001 ~ 48 49Now "kJ" moves the cursor up and joins the lines together. 50 To decide which key or keys you use for mapping, see |map-which-keys|. 51 52 53MAPPING AND MODES 54 55The ":map" command defines remapping for keys in Normal mode. You can also 56define mappings for other modes. For example, ":imap" applies to Insert mode. 57You can use it to insert a date below the cursor: > 58 59 :imap <F2> <CR>Date: <Esc>:read !date<CR>kJ 60 61It looks a lot like the mapping for <F2> in Normal mode, only the start is 62different. The <F2> mapping for Normal mode is still there. Thus you can map 63the same key differently for each mode. 64 Notice that, although this mapping starts in Insert mode, it ends in Normal 65mode. If you want it to continue in Insert mode, append an "a" to the 66mapping. 67 68Here is an overview of map commands and in which mode they work: 69 70 :map Normal, Visual and Operator-pending 71 :vmap Visual 72 :nmap Normal 73 :omap Operator-pending 74 :map! Insert and Command-line 75 :imap Insert 76 :cmap Command-line 77 78Operator-pending mode is when you typed an operator character, such as "d" or 79"y", and you are expected to type the motion command or a text object. Thus 80when you type "dw", the "w" is entered in operator-pending mode. 81 82Suppose that you want to define <F7> so that the command d<F7> deletes a C 83program block (text enclosed in curly braces, {}). Similarly y<F7> would yank 84the program block into the unnamed register. Therefore, what you need to do 85is to define <F7> to select the current program block. You can do this with 86the following command: > 87 88 :omap <F7> a{ 89 90This causes <F7> to perform a select block "a{" in operator-pending mode, just 91like you typed it. This mapping is useful if typing a { on your keyboard is a 92bit difficult. 93 94 95LISTING MAPPINGS 96 97To see the currently defined mappings, use ":map" without arguments. Or one 98of the variants that include the mode in which they work. The output could 99look like this: 100 101 _g :call MyGrep(1)<CR> ~ 102 v <F2> :s/^/> /<CR>:noh<CR>`` ~ 103 n <F2> :.,$s/^/> /<CR>:noh<CR>`` ~ 104 <xHome> <Home> 105 <xEnd> <End> 106 107 108The first column of the list shows in which mode the mapping is effective. 109This is "n" for Normal mode, "i" for Insert mode, etc. A blank is used for a 110mapping defined with ":map", thus effective in both Normal and Visual mode. 111 One useful purpose of listing the mapping is to check if special keys in <> 112form have been recognized (this only works when color is supported). For 113example, when <Esc> is displayed in color, it stands for the escape character. 114When it has the same color as the other text, it is five characters. 115 116 117REMAPPING 118 119The result of a mapping is inspected for other mappings in it. For example, 120the mappings for <F2> above could be shortened to: > 121 122 :map <F2> G<F3> 123 :imap <F2> <Esc><F3> 124 :map <F3> oDate: <Esc>:read !date<CR>kJ 125 126For Normal mode <F2> is mapped to go to the last line, and then behave like 127<F3> was pressed. In Insert mode <F2> stops Insert mode with <Esc> and then 128also uses <F3>. Then <F3> is mapped to do the actual work. 129 130Suppose you hardly ever use Ex mode, and want to use the "Q" command to format 131text (this was so in old versions of Vim). This mapping will do it: > 132 133 :map Q gq 134 135But, in rare cases you need to use Ex mode anyway. Let's map "gQ" to Q, so 136that you can still go to Ex mode: > 137 138 :map gQ Q 139 140What happens now is that when you type "gQ" it is mapped to "Q". So far so 141good. But then "Q" is mapped to "gq", thus typing "gQ" results in "gq", and 142you don't get to Ex mode at all. 143 To avoid keys to be mapped again, use the ":noremap" command: > 144 145 :noremap gQ Q 146 147Now Vim knows that the "Q" is not to be inspected for mappings that apply to 148it. There is a similar command for every mode: 149 150 :noremap Normal, Visual and Operator-pending 151 :vnoremap Visual 152 :nnoremap Normal 153 :onoremap Operator-pending 154 :noremap! Insert and Command-line 155 :inoremap Insert 156 :cnoremap Command-line 157 158 159RECURSIVE MAPPING 160 161When a mapping triggers itself, it will run forever. This can be used to 162repeat an action an unlimited number of times. 163 For example, you have a list of files that contain a version number in the 164first line. You edit these files with `vim *.txt`. You are now editing the 165first file. Define this mapping: > 166 167 :map ,, :s/5.1/5.2/<CR>:wnext<CR>,, 168 169Now you type ",,". This triggers the mapping. It replaces "5.1" with "5.2" 170in the first line. Then it does a ":wnext" to write the file and edit the 171next one. The mapping ends in ",,". This triggers the same mapping again, 172thus doing the substitution, etc. 173 This continues until there is an error. In this case it could be a file 174where the substitute command doesn't find a match for "5.1". You can then 175make a change to insert "5.1" and continue by typing ",," again. Or the 176":wnext" fails, because you are in the last file in the list. 177 When a mapping runs into an error halfway, the rest of the mapping is 178discarded. CTRL-C interrupts the mapping (CTRL-Break on MS-Windows). 179 180 181DELETE A MAPPING 182 183To remove a mapping use the ":unmap" command. Again, the mode the unmapping 184applies to depends on the command used: 185 186 :unmap Normal, Visual and Operator-pending 187 :vunmap Visual 188 :nunmap Normal 189 :ounmap Operator-pending 190 :unmap! Insert and Command-line 191 :iunmap Insert 192 :cunmap Command-line 193 194There is a trick to define a mapping that works in Normal and Operator-pending 195mode, but not in Visual mode. First define it for all three modes, then 196delete it for Visual mode: > 197 198 :map <C-A> /---><CR> 199 :vunmap <C-A> 200 201Notice that the five characters "<C-A>" stand for the single key CTRL-A. 202 203To remove all mappings use the |:mapclear| command. You can guess the 204variations for different modes by now. Be careful with this command, it can't 205be undone. 206 207 208SPECIAL CHARACTERS 209 210The ":map" command can be followed by another command. A | character 211separates the two commands. This also means that a | character can't be used 212inside a map command. To include one, use <Bar> (five characters). Example: 213> 214 :map <F8> :write <Bar> !checkin %:S<CR> 215 216The same problem applies to the ":unmap" command, with the addition that you 217have to watch out for trailing white space. These two commands are different: 218> 219 :unmap a | unmap b 220 :unmap a| unmap b 221 222The first command tries to unmap "a ", with a trailing space. 223 224When using a space inside a mapping, use <Space> (seven characters): > 225 226 :map <Space> W 227 228This makes the spacebar move a blank-separated word forward. 229 230It is not possible to put a comment directly after a mapping, because the " 231character is considered to be part of the mapping. You can use `|"`, this 232starts a new, empty command with a comment. Example: > 233 234 :map <Space> W| " Use spacebar to move forward a word 235 236 237MAPPINGS AND ABBREVIATIONS 238 239Abbreviations are a lot like Insert mode mappings. The arguments are handled 240in the same way. The main difference is the way they are triggered. An 241abbreviation is triggered by typing a non-word character after the word. A 242mapping is triggered when typing the last character. 243 Another difference is that the characters you type for an abbreviation are 244inserted in the text while you type them. When the abbreviation is triggered 245these characters are deleted and replaced by what the abbreviation produces. 246When typing the characters for a mapping, nothing is inserted until you type 247the last character that triggers it. If the 'showcmd' option is set, the 248typed characters are displayed in the last line of the Vim window. 249 An exception is when a mapping is ambiguous. Suppose you have done two 250mappings: > 251 252 :imap aa foo 253 :imap aaa bar 254 255Now, when you type "aa", Vim doesn't know if it should apply the first or the 256second mapping. It waits for another character to be typed. If it is an "a", 257the second mapping is applied and results in "bar". If it is a space, for 258example, the first mapping is applied, resulting in "foo", and then the space 259is inserted. 260 261 262ADDITIONALLY... 263 264The <script> keyword can be used to make a mapping local to a script. See 265|:map-<script>|. 266 267The <buffer> keyword can be used to make a mapping local to a specific buffer. 268See |:map-<buffer>| 269 270The <unique> keyword can be used to make defining a new mapping fail when it 271already exists. Otherwise a new mapping simply overwrites the old one. See 272|:map-<unique>|. 273 274To make a key do nothing, map it to <Nop> (five characters). This will make 275the <F7> key do nothing at all: > 276 277 :map <F7> <Nop>| map! <F7> <Nop> 278 279There must be no space after <Nop>. 280 281============================================================================== 282*40.2* Defining command-line commands 283 284The Vim editor enables you to define your own commands. You execute these 285commands just like any other Command-line mode command. 286 To define a command, use the ":command" command, as follows: > 287 288 :command DeleteFirst 1delete 289 290Now when you execute the command ":DeleteFirst" Vim executes ":1delete", which 291deletes the first line. 292 293 Note: 294 User-defined commands must start with a capital letter. You cannot 295 use ":Next". The underscore cannot be used! You can use digits, but 296 this is discouraged. 297 298To list the user-defined commands, execute the following command: > 299 300 :command 301 302Just like with the builtin commands, the user defined commands can be 303abbreviated. You need to type just enough to distinguish the command from 304another. Command line completion can be used to get the full name. 305 306 307NUMBER OF ARGUMENTS 308 309User-defined commands can take a series of arguments. The number of arguments 310must be specified by the -nargs option. For instance, the example 311:DeleteFirst command takes no arguments, so you could have defined it as 312follows: > 313 314 :command -nargs=0 DeleteFirst 1delete 315 316However, because zero arguments is the default, you do not need to add 317"-nargs=0". The other values of -nargs are as follows: 318 319 -nargs=0 No arguments 320 -nargs=1 One argument 321 -nargs=* Any number of arguments 322 -nargs=? Zero or one argument 323 -nargs=+ One or more arguments 324 325 326USING THE ARGUMENTS 327 328Inside the command definition, the arguments are represented by the 329<args> keyword. For example: > 330 331 :command -nargs=+ Say :echo "<args>" 332 333Now when you type > 334 335 :Say Hello World 336 337Vim echoes "Hello World". However, if you add a double quote, it won't work. 338For example: > 339 340 :Say he said "hello" 341 342To get special characters turned into a string, properly escaped to use as an 343expression, use "<q-args>": > 344 345 :command -nargs=+ Say :echo <q-args> 346 347Now the above ":Say" command will result in this to be executed: > 348 349 :echo "he said \"hello\"" 350 351The <f-args> keyword contains the same information as the <args> keyword, 352except in a format suitable for use as function call arguments. For example: 353> 354 :command -nargs=* DoIt :call AFunction(<f-args>) 355 :DoIt a b c 356 357Executes the following command: > 358 359 :call AFunction("a", "b", "c") 360 361 362LINE RANGE 363 364Some commands take a range as their argument. To tell Vim that you are 365defining such a command, you need to specify a -range option. The values for 366this option are as follows: 367 368 -range Range is allowed; default is the current line. 369 -range=% Range is allowed; default is the whole file. 370 -range={count} Range is allowed; the last number in it is used as a 371 single number whose default is {count}. 372 373When a range is specified, the keywords <line1> and <line2> get the values of 374the first and last line in the range. For example, the following command 375defines the SaveIt command, which writes out the specified range to the file 376"save_file": > 377 378 :command -range=% SaveIt :<line1>,<line2>write! save_file 379 380 381OTHER OPTIONS 382 383Some of the other options and keywords are as follows: 384 385 -count={number} The command can take a count whose default is 386 {number}. The resulting count can be used 387 through the <count> keyword. 388 -bang You can use a !. If present, using <bang> 389 will result in a !. 390 -register You can specify a register. (The default is 391 the unnamed register.) 392 The register specification is available as 393 <reg> (a.k.a. <register>). 394 -complete={type} Type of command-line completion used. See 395 |:command-completion| for the list of possible 396 values. 397 -bar The command can be followed by | and another 398 command, or " and a comment. 399 -buffer The command is only available for the current 400 buffer. 401 402Finally, you have the <lt> keyword. It stands for the character <. Use this 403to escape the special meaning of the <> items mentioned. 404 405 406REDEFINING AND DELETING 407 408To redefine the same command use the ! argument: > 409 410 :command -nargs=+ Say :echo "<args>" 411 :command! -nargs=+ Say :echo <q-args> 412 413To delete a user command use ":delcommand". It takes a single argument, which 414is the name of the command. Example: > 415 416 :delcommand SaveIt 417 418To delete all the user commands: > 419 420 :comclear 421 422Careful, this can't be undone! 423 424More details about all this in the reference manual: |user-commands|. 425 426============================================================================== 427*40.3* Autocommands 428 429An autocommand is a command that is executed automatically in response to some 430event, such as a file being read or written or a buffer change. Through the 431use of autocommands you can train Vim to edit compressed files, for example. 432That is used in the |gzip| plugin. 433 Autocommands are very powerful. Use them with care and they will help you 434avoid typing many commands. Use them carelessly and they will cause a lot of 435trouble. 436 437Suppose you want to replace a datestamp on the end of a file every time it is 438written. First you define a function: > 439 440 :function DateInsert() 441 : $delete 442 : read !date 443 :endfunction 444 445You want this function to be called each time, just before a buffer is written 446to a file. This will make that happen: > 447 448 :autocmd BufWritePre * call DateInsert() 449 450"BufWritePre" is the event for which this autocommand is triggered: Just 451before (pre) writing a buffer to a file. The "*" is a pattern to match with 452the file name. In this case it matches all files. 453 With this command enabled, when you do a ":write", Vim checks for any 454matching BufWritePre autocommands and executes them, and then it 455performs the ":write". 456 The general form of the :autocmd command is as follows: > 457 458 :autocmd [group] {events} {file-pattern} [++nested] {command} 459 460The [group] name is optional. It is used in managing and calling the commands 461(more on this later). The {events} parameter is a list of events (comma 462separated) that trigger the command. 463 {file-pattern} is a filename, usually with wildcards. For example, using 464"*.txt" makes the autocommand be used for all files whose name end in ".txt". 465The optional [++nested] flag allows for nesting of autocommands (see below), 466and finally, {command} is the command to be executed. 467 468When adding an autocommand the already existing ones remain. To avoid adding 469the autocommand several times you should use this form: > 470 471 :augroup updateDate 472 : autocmd! 473 : autocmd BufWritePre * call DateInsert() 474 :augroup END 475 476This will delete any previously defined autocommand with `:autocmd!` before 477defining the new one. Groups are explained later. 478 479 480EVENTS 481 482One of the most useful events is BufReadPost. It is triggered after a new 483file is being edited. It is commonly used to set option values. For example, 484you know that "*.gsm" files are GNU assembly language. To get the syntax file 485right, define this autocommand: > 486 487 :autocmd BufReadPost *.gsm set filetype=asm 488 489If Vim is able to detect the type of file, it will set the 'filetype' option 490for you. This triggers the Filetype event. Use this to do something when a 491certain type of file is edited. For example, to load a list of abbreviations 492for text files: > 493 494 :autocmd Filetype text source ~/.config/nvim/abbrevs.vim 495 496When starting to edit a new file, you could make Vim insert a skeleton: > 497 498 :autocmd BufNewFile *.[ch] 0read ~/skeletons/skel.c 499 500See |autocmd-events| for a complete list of events. 501 502 503PATTERNS 504 505The {file-pattern} argument can actually be a comma-separated list of file 506patterns. For example: `*.c,*.h` matches files ending in ".c" and ".h". 507 The usual file wildcards can be used. Here is a summary of the most often 508used ones: 509 510 * Match any character any number of times 511 ? Match any character once 512 [abc] Match the character a, b or c 513 . Matches a dot 514 a{b,c} Matches "ab" and "ac" 515 516When the pattern includes a slash (/) Vim will compare directory names. 517Without the slash only the last part of a file name is used. For example, 518"*.txt" matches "/home/biep/readme.txt". The pattern "/home/biep/*" would 519also match it. But "home/foo/*.txt" wouldn't. 520 When including a slash, Vim matches the pattern against both the full path 521of the file ("/home/biep/readme.txt") and the relative path (e.g., 522"biep/readme.txt"). 523 524 Note: 525 When working on a system that uses a backslash as file separator, such 526 as MS-Windows, you still use forward slashes in autocommands. This 527 makes it easier to write the pattern, since a backslash has a special 528 meaning. It also makes the autocommands portable. 529 530 531DELETING 532 533To delete an autocommand, use the same command as what it was defined with, 534but leave out the {command} at the end and use a !. Example: > 535 536 :autocmd! FileWritePre * 537 538This will delete all autocommands for the "FileWritePre" event that use the 539"*" pattern. 540 541 542LISTING 543 544To list all the currently defined autocommands, use this: > 545 546 :autocmd 547 548The list can be very long, especially when filetype detection is used. To 549list only part of the commands, specify the group, event and/or pattern. For 550example, to list all BufNewFile autocommands: > 551 552 :autocmd BufNewFile 553 554To list all autocommands for the pattern "*.c": > 555 556 :autocmd * *.c 557 558Using "*" for the event will list all the events. To list all autocommands 559for the cprograms group: > 560 561 :autocmd cprograms 562 563 564GROUPS 565 566The {group} item, used when defining an autocommand, groups related 567autocommands together. This can be used to delete all the autocommands in a 568certain group, for example. 569 When defining several autocommands for a certain group, use the ":augroup" 570command. For example, let's define autocommands for C programs: > 571 572 :augroup cprograms 573 : autocmd BufReadPost *.c,*.h :set sw=4 sts=4 574 : autocmd BufReadPost *.cpp :set sw=3 sts=3 575 :augroup END 576 577This will do the same as: > 578 579 :autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4 580 :autocmd cprograms BufReadPost *.cpp :set sw=3 sts=3 581 582To delete all autocommands in the "cprograms" group: > 583 584 :autocmd! cprograms 585 586 587NESTING 588 589Generally, commands executed as the result of an autocommand event will not 590trigger any new events. If you read a file in response to a FileChangedShell 591event, it will not trigger the autocommands that would set the syntax, for 592example. To make the events triggered, add the "++nested" flag: > 593 594 :autocmd FileChangedShell * ++nested edit 595 596 597EXECUTING AUTOCOMMANDS 598 599It is possible to trigger an autocommand by pretending an event has occurred. 600This is useful to have one autocommand trigger another one. Example: > 601 602 :autocmd BufReadPost *.new execute "doautocmd BufReadPost " .. expand("<afile>:r") 603 604This defines an autocommand that is triggered when a new file has been edited. 605The file name must end in ".new". The ":execute" command uses expression 606evaluation to form a new command and execute it. When editing the file 607"tryout.c.new" the executed command will be: > 608 609 :doautocmd BufReadPost tryout.c 610 611The expand() function takes the "<afile>" argument, which stands for the file 612name the autocommand was executed for, and takes the root of the file name 613with ":r". 614 615":doautocmd" executes on the current buffer. The ":doautoall" command works 616like "doautocmd" except it executes on all the buffers. 617 618 619USING NORMAL MODE COMMANDS 620 621The commands executed by an autocommand are Command-line commands. If you 622want to use a Normal mode command, the ":normal" command can be used. 623Example: > 624 625 :autocmd BufReadPost *.log normal G 626 627This will make the cursor jump to the last line of `*.log` files when you start 628to edit it. 629 Using the ":normal" command is a bit tricky. First of all, make sure its 630argument is a complete command, including all the arguments. When you use "i" 631to go to Insert mode, there must also be a <Esc> to leave Insert mode again. 632If you use a "/" to start a search pattern, there must be a <CR> to execute 633it. 634 The ":normal" command uses all the text after it as commands. Thus there 635can be no | and another command following. To work around this, put the 636":normal" command inside an ":execute" command. This also makes it possible 637to pass unprintable characters in a convenient way. Example: > 638 639 :autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" | 640 \ 1read !date 641 642This also shows the use of a backslash to break a long command into more 643lines. This can be used in Vim scripts (not at the command line). 644 645When you want the autocommand do something complicated, which involves jumping 646around in the file and then returning to the original position, you may want 647to restore the view on the file. See |restore-position| for an example. 648 649 650IGNORING EVENTS 651 652At times, you will not want to trigger an autocommand. The 'eventignore' 653option contains a list of events that will be totally ignored. For example, 654the following causes events for entering and leaving a window to be ignored: > 655 656 :set eventignore=WinEnter,WinLeave 657 658To ignore all events, use the following command: > 659 660 :set eventignore=all 661 662To set it back to the normal behavior, make 'eventignore' empty: 663> 664 :set eventignore= 665< 666============================================================================== 667 668Next chapter: |usr_41.txt| Write a Vim script 669 670Copyright: see |manual-copyright| 671 672vim:tw=78:ts=8:noet:ft=help:norl: