autocmd.txt (72334B)
1 *autocmd.txt* Nvim 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7 Automatic commands *autocmd* *autocommand* 8 9 For a basic explanation, see section |40.3| in the user manual. 10 11 Type |gO| to see the table of contents. 12 13 ============================================================================== 14 1. Introduction *autocmd-intro* 15 16 You can specify commands to be executed automatically when reading or writing 17 a file, when entering or leaving a buffer or window, and when exiting Vim. 18 For example, you can create an autocommand to set the 'cindent' option for 19 files matching `*.c`. You can also use autocommands to implement advanced 20 features, such as editing compressed files (see |gzip-example|). The usual 21 place to put autocommands is in your vimrc file. 22 23 *E203* *E204* *E143* *E855* *E937* *E952* 24 WARNING: Using autocommands is very powerful, and may lead to unexpected side 25 effects. Be careful not to destroy your text. 26 - It's a good idea to do some testing on an expendable copy of a file first. 27 For example: If you use autocommands to decompress a file when starting to 28 edit it, make sure that the autocommands for compressing when writing work 29 correctly. 30 - Be prepared for an error halfway through (e.g., disk full). Vim will mostly 31 be able to undo the changes to the buffer, but you may have to clean up the 32 changes to other files by hand (e.g., compress a file that has been 33 decompressed). 34 - If the BufRead* events allow you to edit a compressed file, the FileRead* 35 events should do the same (this makes recovery possible in some rare cases). 36 It's a good idea to use the same autocommands for the File* and Buf* events 37 when possible. 38 39 ============================================================================== 40 2. Defining autocommands *autocmd-define* 41 42 *:au* *:autocmd* 43 :au[tocmd] [group] {event} {aupat} [++once] [++nested] {cmd} 44 Add {cmd} to the list of commands that Vim will 45 execute automatically on {event} for a file matching 46 {aupat} |autocmd-pattern|. 47 Note: A quote character is seen as argument to the 48 :autocmd and won't start a comment. 49 Nvim always adds {cmd} after existing autocommands so 50 they execute in the order in which they were defined. 51 See |autocmd-nested| for [++nested]. 52 *autocmd-once* 53 If [++once] is supplied the command is executed once, 54 then removed ("one shot"). 55 56 The special pattern <buffer> or <buffer=N> defines a buffer-local autocommand. 57 See |autocmd-buflocal|. 58 59 Note: The ":autocmd" command can only be followed by another command when the 60 "|" appears where the pattern is expected. This works: > 61 :augroup mine | au! BufRead | augroup END 62 But this sees "augroup" as part of the defined command: > 63 :augroup mine | au! BufRead * | augroup END 64 :augroup mine | au BufRead * set tw=70 | augroup END 65 Instead you can put the group name into the command: > 66 :au! mine BufRead * 67 :au mine BufRead * set tw=70 68 Or use `:execute`: > 69 :augroup mine | exe "au! BufRead *" | augroup END 70 :augroup mine | exe "au BufRead * set tw=70" | augroup END 71 72 < *autocmd-expand* 73 Note that special characters (e.g., "%", "<cword>") in the ":autocmd" 74 arguments are not expanded when the autocommand is defined. These will be 75 expanded when the Event is recognized, and the {cmd} is executed. The only 76 exception is that "<sfile>" (unlike "<script>") is expanded when the autocmd 77 is defined. Example: 78 > 79 :au BufNewFile,BufRead *.html so <sfile>:h/html.vim 80 81 Here Vim expands <sfile> to the name of the file containing this line. 82 However, <sfile> works differently in a function, in which case it's better to 83 use `:execute` with <script> to achieve the same purpose: 84 > 85 :exe $'au BufNewFile,BufRead *.html so {expand("<script>:h")}/html.vim' 86 87 `:autocmd` adds to the list of autocommands regardless of whether they are 88 already present. When your .vimrc file is sourced twice, the autocommands 89 will appear twice. To avoid this, define your autocommands in a group, so 90 that you can easily clear them: > 91 92 augroup vimrc 93 " Remove all vimrc autocommands 94 autocmd! 95 au BufNewFile,BufRead *.html so <sfile>:h/html.vim 96 augroup END 97 98 If you don't want to remove all autocommands, you can instead use a variable 99 to ensure that Vim includes the autocommands only once: > 100 101 :if !exists("autocommands_loaded") 102 : let autocommands_loaded = 1 103 : au ... 104 :endif 105 106 When the [group] argument is not given, Vim uses the current group (as defined 107 with ":augroup"); otherwise, Vim uses the group defined with [group]. Note 108 that [group] must have been defined before. You cannot define a new group 109 with ":au group ..."; use ":augroup" for that. 110 111 While testing autocommands, you might find the 'verbose' option to be useful: > 112 :set verbose=9 113 This setting makes Vim echo the autocommands as it executes them. 114 115 When defining an autocommand in a script, it will be able to call functions 116 local to the script and use mappings local to the script. When the event is 117 triggered and the command executed, it will run in the context of the script 118 it was defined in. This matters if |<SID>| is used in a command. 119 120 When executing the commands, the message from one command overwrites a 121 previous message. This is different from when executing the commands 122 manually. Mostly the screen will not scroll up, thus there is no hit-enter 123 prompt. When one command outputs two messages this can happen anyway. 124 125 ============================================================================== 126 3. Removing autocommands *autocmd!* *autocmd-remove* 127 128 :au[tocmd]! [group] {event} {aupat} [++once] [++nested] {cmd} 129 Remove all autocommands associated with {event} and 130 {aupat}, and add the command {cmd}. 131 See |autocmd-once| for [++once]. 132 See |autocmd-nested| for [++nested]. 133 134 :au[tocmd]! [group] {event} {aupat} 135 Remove all autocommands associated with {event} and 136 {aupat}. 137 138 :au[tocmd]! [group] * {aupat} 139 Remove all autocommands associated with {aupat} for 140 all events. 141 142 :au[tocmd]! [group] {event} 143 Remove ALL autocommands for {event}. 144 Warning: You should not do this without a group for 145 |BufRead| and other common events, it can break 146 plugins, syntax highlighting, etc. 147 148 :au[tocmd]! [group] Remove ALL autocommands. 149 Note: a quote will be seen as argument to the :autocmd 150 and won't start a comment. 151 Warning: You should normally not do this without a 152 group, it breaks plugins, syntax highlighting, etc. 153 154 When the [group] argument is not given, Vim uses the current group (as defined 155 with ":augroup"); otherwise, Vim uses the group defined with [group]. 156 157 ============================================================================== 158 4. Listing autocommands *autocmd-list* 159 160 :au[tocmd] [group] {event} {aupat} 161 Show the autocommands associated with {event} and 162 {aupat}. 163 164 :au[tocmd] [group] * {aupat} 165 Show the autocommands associated with {aupat} for all 166 events. 167 168 :au[tocmd] [group] {event} 169 Show all autocommands for {event}. 170 171 :au[tocmd] [group] Show all autocommands. 172 173 If you provide the [group] argument, Vim lists only the autocommands for 174 [group]; otherwise, Vim lists the autocommands for ALL groups. Note that this 175 argument behavior differs from that for defining and removing autocommands. 176 177 In order to list buffer-local autocommands, use a pattern in the form <buffer> 178 or <buffer=N>. See |autocmd-buflocal|. 179 180 *:autocmd-verbose* 181 When 'verbose' is non-zero, listing an autocommand will also display where it 182 was last defined. Example: > 183 184 :verbose autocmd BufEnter 185 FileExplorer BufEnter 186 * call s:LocalBrowse(expand("<amatch>")) 187 Last set from /usr/share/vim/vim-7.0/plugin/NetrwPlugin.vim 188 < 189 See |:verbose-cmd| for more information. 190 191 ============================================================================== 192 5. Events *autocmd-events* *E215* *E216* 193 194 You can specify a comma-separated list of event names. No white space can be 195 used in this list. The command applies to all the events in the list. 196 197 For READING FILES there are four kinds of events possible: 198 BufNewFile starting to edit a non-existent file 199 BufReadPre BufReadPost starting to edit an existing file 200 FilterReadPre FilterReadPost read the temp file with filter output 201 FileReadPre FileReadPost any other file read 202 Vim uses only one of these four kinds when reading a file. The "Pre" and 203 "Post" events are both triggered, before and after reading the file. 204 205 Note that the autocommands for the "*ReadPre" events and all the Filter events 206 are not allowed to change the current buffer (you will get an error message if 207 this happens). This is to prevent the file to be read into the wrong buffer. 208 209 Note that the 'modified' flag is reset AFTER executing the BufReadPost 210 and BufNewFile autocommands. But when the 'modified' option was set by the 211 autocommands, this doesn't happen. 212 213 You can use the 'eventignore' option to ignore a number of events or all 214 events. 215 216 *events* *{event}* 217 Nvim recognizes the following events. Names are case-insensitive. 218 219 *BufAdd* 220 BufAdd After adding a new buffer or existing unlisted 221 buffer to the buffer list (except during 222 startup, see |VimEnter|), or renaming a listed 223 buffer. 224 Before |BufEnter|. 225 NOTE: Current buffer "%" is not the target 226 buffer "<afile>", "<abuf>". |<buffer=abuf>| 227 *BufDelete* 228 BufDelete Before deleting a buffer from the buffer list. 229 The BufUnload may be called first (if the 230 buffer was loaded). 231 Also used just before a buffer in the buffer 232 list is renamed. 233 NOTE: Current buffer "%" is not the target 234 buffer "<afile>", "<abuf>". |<buffer=abuf>| 235 Do not change to another buffer. 236 *BufEnter* 237 BufEnter After entering (visiting, switching-to) a new 238 or existing buffer. Useful for setting 239 filetype options. Compare |BufNew| which 240 does not trigger for existing buffers. 241 After |BufAdd|. 242 After |BufReadPost|. 243 *BufFilePost* 244 BufFilePost After changing the name of the current buffer 245 with the ":file" or ":saveas" command. 246 *BufFilePre* 247 BufFilePre Before changing the name of the current buffer 248 with the ":file" or ":saveas" command. 249 *BufHidden* 250 BufHidden Before a buffer becomes hidden: when there are 251 no longer windows that show the buffer, but 252 the buffer is not unloaded or deleted. 253 254 Not used for ":qa" or ":q" when exiting Vim. 255 NOTE: Current buffer "%" is not the target 256 buffer "<afile>", "<abuf>". |<buffer=abuf>| 257 *BufLeave* 258 BufLeave Before leaving to another buffer. Also when 259 leaving or closing the current window and the 260 new current window is not for the same buffer. 261 262 Not used for ":qa" or ":q" when exiting Vim. 263 *BufModifiedSet* 264 BufModifiedSet After the `'modified'` value of a buffer has 265 been changed. Special-case of |OptionSet|. 266 *BufNew* 267 BufNew After creating a new buffer (except during 268 startup, see |VimEnter|) or renaming an 269 existing buffer. Unlike |BufEnter|, visiting 270 (switching to) an existing buffer will not 271 trigger this again. 272 NOTE: Current buffer "%" is not the target 273 buffer "<afile>", "<abuf>". |<buffer=abuf>| 274 See also |BufAdd|, |BufNewFile|. 275 *BufNewFile* 276 BufNewFile When starting to edit a file that doesn't 277 exist. Can be used to read in a skeleton 278 file. 279 *BufRead* *BufReadPost* 280 BufRead or BufReadPost When starting to edit a new buffer, after 281 reading the file into the buffer, before 282 processing modelines. See |BufWinEnter| to do 283 something after processing modelines. 284 Also triggered: 285 - when writing an unnamed buffer in a way that 286 the buffer gets a name 287 - after successfully recovering a file 288 - for the "filetypedetect" group when 289 executing ":filetype detect" 290 Not triggered: 291 - for the `:read file` command 292 - when the file doesn't exist 293 *BufReadCmd* 294 BufReadCmd Before starting to edit a new buffer. Should 295 read the file into the buffer. |Cmd-event| 296 *BufReadPre* *E200* *E201* 297 BufReadPre When starting to edit a new buffer, before 298 reading the file into the buffer. Not used 299 if the file doesn't exist. 300 *BufUnload* 301 BufUnload Before unloading a buffer, when the text in 302 the buffer is going to be freed. 303 After BufWritePost. 304 Before BufDelete. 305 Triggers for all loaded buffers when Vim is 306 going to exit. 307 NOTE: Current buffer "%" is not the target 308 buffer "<afile>", "<abuf>". |<buffer=abuf>| 309 *E1546* 310 Do not switch buffers or windows! 311 Not triggered when exiting and v:dying is 2 or 312 more. 313 *BufWinEnter* 314 BufWinEnter After a buffer is displayed in a window. This 315 may be when the buffer is loaded (after 316 processing modelines) or when a hidden buffer 317 is displayed (and is no longer hidden). 318 319 Not triggered for |:split| without arguments, 320 since the buffer does not change, or :split 321 with a file already open in a window. 322 Triggered for ":split" with the name of the 323 current buffer, since it reloads that buffer. 324 *BufWinLeave* 325 BufWinLeave Before a buffer is removed from a window. 326 Not when it's still visible in another window. 327 Also triggered when exiting. 328 Before BufUnload, BufHidden. 329 NOTE: Current buffer "%" is not the target 330 buffer "<afile>", "<abuf>". |<buffer=abuf>| 331 Not triggered when exiting and v:dying is 2 or 332 more. 333 *BufWipeout* 334 BufWipeout Before completely deleting a buffer. The 335 BufUnload and BufDelete events may be called 336 first (if the buffer was loaded and was in the 337 buffer list). Also used just before a buffer 338 is renamed (also when it's not in the buffer 339 list). 340 NOTE: Current buffer "%" is not the target 341 buffer "<afile>", "<abuf>". |<buffer=abuf>| 342 Do not change to another buffer. 343 *BufWrite* *BufWritePre* 344 BufWrite or BufWritePre Before writing the whole buffer to a file. 345 *BufWriteCmd* 346 BufWriteCmd Before writing the whole buffer to a file. 347 Should do the writing of the file and reset 348 'modified' if successful, unless '+' is in 349 'cpo' and writing to another file |cpo-+|. 350 The buffer contents should not be changed. 351 When the command resets 'modified' the undo 352 information is adjusted to mark older undo 353 states as 'modified', like |:write| does. Use 354 the |'[| and |']| marks for the range of lines. 355 |Cmd-event| 356 *BufWritePost* 357 BufWritePost After writing the whole buffer to a file 358 (should undo the commands for BufWritePre). 359 *ChanInfo* 360 ChanInfo State of channel changed, for instance the 361 client of a RPC channel described itself. 362 This is triggered even when inside an 363 autocommand defined without |autocmd-nested|. 364 Sets these |v:event| keys: 365 info as from |nvim_get_chan_info()| 366 *ChanOpen* 367 ChanOpen Just after a channel was opened. 368 This is triggered even when inside an 369 autocommand defined without |autocmd-nested|. 370 Sets these |v:event| keys: 371 info as from |nvim_get_chan_info()| 372 *CmdUndefined* 373 CmdUndefined When a user command is used but it isn't 374 defined. Useful for defining a command only 375 when it's used. The pattern is matched 376 against the command name. Both <amatch> and 377 <afile> expand to the command name. 378 This is triggered even when inside an 379 autocommand defined without |autocmd-nested|. 380 NOTE: Autocompletion won't work until the 381 command is defined. An alternative is to 382 always define the user command and have it 383 invoke an autoloaded function. See |autoload|. 384 *CmdlineChanged* 385 CmdlineChanged After EVERY change inside command line. Also 386 triggered during mappings! Use |<Cmd>| instead 387 of ":" in mappings, to avoid that. 388 389 <afile> expands to the |cmdline-char|. 390 *CmdlineEnter* 391 CmdlineEnter After entering the command-line (including 392 non-interactive use of ":" in a mapping: use 393 |<Cmd>| instead to avoid this). 394 The pattern is matched against |cmdline-char|. 395 <afile> expands to the |cmdline-char|. 396 Sets these |v:event| keys: 397 cmdlevel 398 cmdtype 399 *CmdlineLeave* 400 CmdlineLeave Before leaving the command-line (including 401 non-interactive use of ":" in a mapping: use 402 |<Cmd>| instead to avoid this). 403 <afile> expands to the |cmdline-char|. 404 Sets the |v:char| to the key that exited the 405 command-line (e.g. <CR>, <CTRL-C>, <Esc>). 406 Sets these |v:event| keys: 407 abort (mutable) 408 cmdlevel 409 cmdtype 410 Note: `abort` can only be changed from false 411 to true: cannot execute an already aborted 412 cmdline by changing it to false. 413 *CmdlineLeavePre* 414 CmdlineLeavePre Just before leaving the command line, and 415 before |CmdlineLeave|. Useful for capturing 416 completion info with |cmdcomplete_info()|, as 417 this information is cleared before 418 |CmdlineLeave| is triggered. Triggered for 419 non-interactive use of ":" in a mapping, but 420 not when using |<Cmd>|. Also triggered when 421 abandoning the command line by typing CTRL-C 422 or <Esc>. <afile> is set to |cmdline-char|. 423 Sets |v:char| as with |CmdlineLeave|. 424 *CmdwinEnter* 425 CmdwinEnter After entering the command-line window. 426 Useful for setting options specifically for 427 this special type of window. 428 <afile> expands to a single character, 429 indicating the type of command-line. 430 |cmdwin-char| 431 *CmdwinLeave* 432 CmdwinLeave Before leaving the command-line window. 433 Useful to clean up any global setting done 434 with CmdwinEnter. 435 <afile> expands to a single character, 436 indicating the type of command-line. 437 |cmdwin-char| 438 *ColorScheme* 439 ColorScheme After loading a color scheme. |:colorscheme| 440 Not triggered if the color scheme is not 441 found. 442 The pattern is matched against the 443 colorscheme name. <afile> can be used for the 444 name of the actual file where this option was 445 set, and <amatch> for the new colorscheme 446 name. 447 448 *ColorSchemePre* 449 ColorSchemePre Before loading a color scheme. |:colorscheme| 450 Useful to setup removing things added by a 451 color scheme, before another one is loaded. 452 453 CompleteChanged *CompleteChanged* 454 After each time the Insert mode completion 455 menu changed. Not fired on popup menu hide, 456 use |CompleteDonePre| or |CompleteDone| for 457 that. 458 459 Sets these |v:event| keys: 460 completed_item See |complete-items|. 461 height nr of items visible 462 width screen cells 463 row top screen row 464 col leftmost screen column 465 size total nr of items 466 scrollbar TRUE if visible 467 468 Non-recursive (event cannot trigger itself). 469 Cannot change the text. |textlock| 470 471 The size and position of the popup are also 472 available by calling |pum_getpos()|. 473 474 *CompleteDonePre* 475 CompleteDonePre After Insert mode completion is done. Either 476 when something was completed or discarded. 477 |ins-completion| 478 |complete_info()| is valid during this event. 479 |v:completed_item| gives the completed item. 480 481 *CompleteDone* 482 CompleteDone After Insert mode completion is done. Either 483 when something was completed or discarded. 484 |ins-completion| 485 |complete_info()| is cleared before this; use 486 CompleteDonePre if you need it. 487 |v:completed_item| gives the completed item, 488 or empty dict if completion was discarded. 489 490 Sets these |v:event| keys: 491 complete_word The word that was 492 selected, empty if 493 completion was 494 abandoned (discarded). 495 complete_type |complete_info_mode| 496 reason Reason for completion being 497 done. Can be one of: 498 - "accept": completion was 499 accepted by |complete_CTRL-Y|. 500 - "cancel": completion was 501 stopped by |complete_CTRL-E|. 502 - "discard": completion was 503 abandoned for other reason. 504 505 *CursorHold* 506 CursorHold When there is no user input for 'updatetime' 507 duration, in Normal-mode. Not triggered while 508 waiting for a command argument or movement 509 after an operator, nor while |recording| 510 a macro. See |CursorHold-example|. 511 512 Note: Interactive commands cannot be used for 513 this event. There is no hit-enter prompt, 514 the screen is updated directly (when needed). 515 Note: In the future there will probably be 516 another option to set the time. 517 Hint: to force an update of the status lines 518 use: > 519 :let &ro = &ro 520 < 521 *CursorHoldI* 522 CursorHoldI Like CursorHold, but in Insert mode. Not 523 triggered when waiting for another key, e.g. 524 after CTRL-V, and not in CTRL-X mode 525 |insert_expand|. 526 527 *CursorMoved* 528 CursorMoved After the cursor was moved in Normal or Visual 529 mode or to another window. Also when the text 530 of the cursor line has been changed, e.g. with 531 "x", "rx" or "p". 532 Not always triggered when there is typeahead, 533 while executing commands in a script file, or 534 when an operator is pending. 535 For an example see |match-parens|. 536 Note: Cannot be skipped with |:noautocmd|. 537 Careful: This is triggered very often, don't 538 do anything that the user does not expect or 539 that is slow. 540 *CursorMovedC* 541 CursorMovedC After the cursor was moved in the command 542 line. Be careful not to mess up the command 543 line, it may cause Vim to lock up. 544 <afile> expands to the |cmdline-char|. 545 *CursorMovedI* 546 CursorMovedI After the cursor was moved in Insert mode. 547 Not triggered when the popup menu is visible. 548 Otherwise the same as CursorMoved. 549 *DiffUpdated* 550 DiffUpdated After diffs have been updated. Depending on 551 what kind of diff is being used (internal or 552 external) this can be triggered on every 553 change or when doing |:diffupdate|. 554 *DirChanged* 555 DirChanged After the |current-directory| was changed. 556 The pattern can be: 557 "window" to trigger on `:lcd` 558 "tabpage" to trigger on `:tcd` 559 "global" to trigger on `:cd` 560 "auto" to trigger on 'autochdir'. 561 Sets these |v:event| keys: 562 cwd: current working directory 563 scope: "global", "tabpage", "window" 564 changed_window: v:true if we fired the event 565 switching window (or tab) 566 <afile> is set to the new directory name. 567 Non-recursive (event cannot trigger itself). 568 *DirChangedPre* 569 DirChangedPre When the |current-directory| is going to be 570 changed, as with |DirChanged|. 571 The pattern is like with |DirChanged|. 572 Sets these |v:event| keys: 573 directory: new working directory 574 scope: "global", "tabpage", "window" 575 changed_window: v:true if we fired the event 576 switching window (or tab) 577 <afile> is set to the new directory name. 578 Non-recursive (event cannot trigger itself). 579 *ExitPre* 580 ExitPre When using `:quit`, `:wq` in a way it makes 581 Vim exit, or using `:qall`, just after 582 |QuitPre|. Can be used to close any 583 non-essential window. Exiting may still be 584 cancelled if there is a modified buffer that 585 isn't automatically saved, use |VimLeavePre| 586 for really exiting. 587 See also |QuitPre|, |WinClosed|. 588 *FileAppendCmd* 589 FileAppendCmd Before appending to a file. Should do the 590 appending to the file. Use the '[ and '] 591 marks for the range of lines. |Cmd-event| 592 *FileAppendPost* 593 FileAppendPost After appending to a file. 594 *FileAppendPre* 595 FileAppendPre Before appending to a file. Use the '[ and '] 596 marks for the range of lines. 597 *FileChangedRO* 598 FileChangedRO Before making the first change to a read-only 599 file. Can be used to checkout the file from 600 a source control system. Not triggered when 601 the change was caused by an autocommand. 602 Triggered when making the first change in 603 a buffer or the first change after 'readonly' 604 was set, just before the change is applied to 605 the text. 606 WARNING: If the autocommand moves the cursor 607 the effect of the change is undefined. 608 *E788* 609 Cannot switch buffers. You can reload the 610 buffer but not edit another one. 611 *E881* 612 If the number of lines changes saving for undo 613 may fail and the change will be aborted. 614 *FileChangedShell* 615 FileChangedShell When Vim notices that the modification time of 616 a file has changed since editing started. 617 Also when the file attributes of the file 618 change or when the size of the file changes. 619 |timestamp| 620 Triggered for each changed file, after: 621 - executing a shell command 622 - |:checktime| 623 - |FocusGained| 624 625 Not used when 'autoread' is set and the buffer 626 was not changed. If a FileChangedShell 627 autocommand exists the warning message and 628 prompt is not given. 629 |v:fcs_reason| indicates what happened. Set 630 |v:fcs_choice| to control what happens next. 631 NOTE: Current buffer "%" is not the target 632 buffer "<afile>" and "<abuf>". |<buffer=abuf>| 633 *E246* *E811* 634 Cannot switch, jump to or delete buffers. 635 Non-recursive (event cannot trigger itself). 636 *FileChangedShellPost* 637 FileChangedShellPost After handling a file that was changed outside 638 of Vim. Can be used to update the statusline. 639 *FileReadCmd* 640 FileReadCmd Before reading a file with a ":read" command. 641 Should do the reading of the file. |Cmd-event| 642 *FileReadPost* 643 FileReadPost After reading a file with a ":read" command. 644 Note that Vim sets the '[ and '] marks to the 645 first and last line of the read. This can be 646 used to operate on the lines just read. 647 *FileReadPre* 648 FileReadPre Before reading a file with a ":read" command. 649 *FileType* 650 FileType When the 'filetype' option has been set. The 651 pattern is matched against the filetype. 652 <afile> is the name of the file where this 653 option was set. <amatch> is the new value of 654 'filetype'. 655 Cannot switch windows or buffers. 656 See |filetypes|. 657 *FileWriteCmd* 658 FileWriteCmd Before writing to a file, when not writing the 659 whole buffer. Should do the writing to the 660 file. Should not change the buffer. Use the 661 |'[| and |']| marks for the range of lines. 662 |Cmd-event| 663 *FileWritePost* 664 FileWritePost After writing to a file, when not writing the 665 whole buffer. 666 *FileWritePre* 667 FileWritePre Before writing to a file, when not writing the 668 whole buffer. Use the |'[| and |']| marks for the 669 range of lines. 670 *FilterReadPost* 671 FilterReadPost After reading a file from a filter command. 672 Vim checks the pattern against the name of 673 the current buffer as with FilterReadPre. 674 Not triggered when 'shelltemp' is off. 675 *FilterReadPre* *E135* 676 FilterReadPre Before reading a file from a filter command. 677 Vim checks the pattern against the name of 678 the current buffer, not the name of the 679 temporary file that is the output of the 680 filter command. 681 Not triggered when 'shelltemp' is off. 682 *FilterWritePost* 683 FilterWritePost After writing a file for a filter command or 684 making a diff with an external diff (see 685 |DiffUpdated| for internal diff). 686 Vim checks the pattern against the name of 687 the current buffer as with FilterWritePre. 688 Not triggered when 'shelltemp' is off. 689 *FilterWritePre* 690 FilterWritePre Before writing a file for a filter command or 691 making a diff with an external diff. 692 Vim checks the pattern against the name of 693 the current buffer, not the name of the 694 temporary file that is the output of the 695 filter command. 696 Not triggered when 'shelltemp' is off. 697 *FocusGained* 698 FocusGained Nvim got focus. 699 *FocusLost* 700 FocusLost Nvim lost focus. Also (potentially) when 701 a GUI dialog pops up. 702 *FuncUndefined* 703 FuncUndefined When a user function is used but it isn't 704 defined. Useful for defining a function only 705 when it's used. The pattern is matched 706 against the function name. Both <amatch> and 707 <afile> are set to the name of the function. 708 This is triggered even when inside an 709 autocommand defined without |autocmd-nested|. 710 NOTE: When writing Vim scripts a better 711 alternative is to use an autoloaded function. 712 See |autoload-functions|. 713 *UIEnter* 714 UIEnter After a UI connects via |nvim_ui_attach()|, or 715 after builtin TUI is started, after |VimEnter|. 716 Sets these |v:event| keys: 717 chan: |channel-id| of the UI 718 *UILeave* 719 UILeave After a UI disconnects from Nvim, or after 720 builtin TUI is stopped, after |VimLeave|. 721 Sets these |v:event| keys: 722 chan: |channel-id| of the UI 723 *InsertChange* 724 InsertChange When typing <Insert> while in Insert or 725 Replace mode. The |v:insertmode| variable 726 indicates the new mode. 727 Be careful not to move the cursor or do 728 anything else that the user does not expect. 729 *InsertCharPre* 730 InsertCharPre When a character is typed in Insert mode, 731 before inserting the char. 732 The |v:char| variable indicates the char typed 733 and can be changed during the event to insert 734 a different character. When |v:char| is set 735 to more than one character this text is 736 inserted literally. 737 738 Cannot change the text. |textlock| 739 *InsertEnter* 740 InsertEnter Just before starting Insert mode. Also for 741 Replace mode and Virtual Replace mode. The 742 |v:insertmode| variable indicates the mode. 743 Be careful not to do anything else that the 744 user does not expect. 745 The cursor is restored afterwards. If you do 746 not want that set |v:char| to a non-empty 747 string. 748 *InsertLeavePre* 749 InsertLeavePre Just before leaving Insert mode. Also when 750 using CTRL-O |i_CTRL-O|. Be careful not to 751 change mode or use `:normal`, it will likely 752 cause trouble. 753 *InsertLeave* 754 InsertLeave Just after leaving Insert mode. Also when 755 using CTRL-O |i_CTRL-O|. But not for |i_CTRL-C|. 756 LspAttach See |LspAttach| 757 LspDetach See |LspDetach| 758 LspNotify See |LspNotify| 759 LspProgress See |LspProgress| 760 LspRequest See |LspRequest| 761 LspTokenUpdate See |LspTokenUpdate| 762 *MarkSet* 763 MarkSet After a |mark| is set by |m|, |:mark|, and 764 |nvim_buf_set_mark()|. Supports `[a-zA-Z]` 765 marks (may support more in the future). 766 The |autocmd-pattern| is matched against the 767 mark name (e.g. `[ab]` matches `a` or `b`, `*` 768 matches all). 769 770 The |event-data| has these keys: 771 - name: Mark name (e.g. "a") 772 - line: Mark line. 773 - col: Mark column. 774 775 *MenuPopup* 776 MenuPopup Just before showing the popup menu (under the 777 right mouse button). Useful for adjusting the 778 menu for what is under the cursor or mouse 779 pointer. 780 The pattern is matched against one or two 781 characters representing the mode: 782 n Normal 783 v Visual 784 o Operator-pending 785 i Insert 786 c Command line 787 tl Terminal 788 *ModeChanged* 789 ModeChanged After changing the mode. The pattern is 790 matched against `'old_mode:new_mode'`, for 791 example match against `*:c*` to simulate 792 |CmdlineEnter|. 793 The following values of |v:event| are set: 794 old_mode The mode before it changed. 795 new_mode The new mode as also returned 796 by |mode()| called with a 797 non-zero argument. 798 When ModeChanged is triggered, old_mode will 799 have the value of new_mode when the event was 800 last triggered. 801 This will be triggered on every minor mode 802 change. 803 Usage example to use relative line numbers 804 when entering visual mode: > 805 :au ModeChanged [vV\x16]*:* let &l:rnu = mode() =~# '^[vV\x16]' 806 :au ModeChanged *:[vV\x16]* let &l:rnu = mode() =~# '^[vV\x16]' 807 :au WinEnter,WinLeave * let &l:rnu = mode() =~# '^[vV\x16]' 808 Progress *Progress* 809 After a progress message is created or updated via 810 `nvim_echo`. The pattern is matched against 811 title of the message. The |event-data| contains: 812 id: id of the message 813 text: text of the message 814 title: title of the progress message 815 status: status of the progress message 816 percent: how much progress has been 817 made for this progress item 818 Usage example: 819 > 820 vim.api.nvim_create_autocmd('Progress', { 821 pattern={"term"}, 822 callback = function(ev) 823 print(string.format('event fired: %s', vim.inspect(ev))) 824 end 825 }) 826 local id = vim.api.nvim_echo({{'searching...'}}, true, 827 {kind='progress', status='running', percent=10, title="term"}) 828 vim.api.nvim_echo({{'searching'}}, true, 829 {id = id, kind='progress', status='running', percent=50, title="term"}) 830 vim.api.nvim_echo({{'done'}}, true, 831 {id = id, kind='progress', status='success', percent=100, title="term"}) 832 833 < *OptionSet* 834 OptionSet After setting an option (except during 835 |startup|). The |autocmd-pattern| is matched 836 against the long option name. |<amatch>| 837 indicates what option has been set. 838 839 |v:option_type| indicates whether it's global 840 or local scoped. 841 |v:option_command| indicates what type of 842 set/let command was used (follow the tag to 843 see the table). 844 |v:option_new| indicates the newly set value. 845 |v:option_oldlocal| has the old local value. 846 |v:option_oldglobal| has the old global value. 847 |v:option_old| indicates the old option value. 848 849 |v:option_oldlocal| is only set when |:set| 850 or |:setlocal| or a |modeline| was used to set 851 the option. Similarly |v:option_oldglobal| is 852 only set when |:set| or |:setglobal| was used. 853 854 This does not set |<abuf>|, you could use 855 |bufnr()|. 856 857 Note that when setting a |global-local| option 858 with |:set|, then |v:option_old| is the old 859 global value. However, for all options that 860 are not global-local it is the old local 861 value. 862 863 Usage example: Check for the existence of the 864 directory in the 'backupdir' and 'undodir' 865 options, create the directory if it doesn't 866 exist yet. 867 868 Note: Do not reset the same option during this 869 autocommand, that may break plugins. You can 870 always use |:noautocmd| to prevent triggering 871 OptionSet. 872 873 Note: Not triggered by the 'modified' option; 874 the |BufModifiedSet| event may be used to 875 handle that. 876 877 Non-recursive: |:set| in the autocommand does 878 not trigger OptionSet again. 879 880 Not triggered on startup. 881 882 *QuickFixCmdPre* 883 QuickFixCmdPre Before a quickfix command is run (|:make|, 884 |:lmake|, |:grep|, |:lgrep|, |:grepadd|, 885 |:lgrepadd|, |:vimgrep|, |:lvimgrep|, 886 |:vimgrepadd|, |:lvimgrepadd|, 887 |:cfile|, |:cgetfile|, |:caddfile|, |:lfile|, 888 |:lgetfile|, |:laddfile|, |:helpgrep|, 889 |:lhelpgrep|, |:cexpr|, |:cgetexpr|, 890 |:caddexpr|, |:cbuffer|, |:cgetbuffer|, 891 |:caddbuffer|). 892 The pattern is matched against the command 893 being run. When |:grep| is used but 'grepprg' 894 is set to "internal" it still matches "grep". 895 This command cannot be used to set the 896 'makeprg' and 'grepprg' variables. 897 If this command causes an error, the quickfix 898 command is not executed. 899 *QuickFixCmdPost* 900 QuickFixCmdPost Like QuickFixCmdPre, but after a quickfix 901 command is run, before jumping to the first 902 location. For |:cfile| and |:lfile| commands 903 it is run after the error file is read and 904 before moving to the first error. 905 See |QuickFixCmdPost-example|. 906 *QuitPre* 907 QuitPre When using `:quit`, `:wq` or `:qall`, before 908 deciding whether it closes the current window 909 or quits Vim. For `:wq` the buffer is written 910 before QuitPre is triggered. Can be used to 911 close any non-essential window if the current 912 window is the last ordinary window. 913 See also |ExitPre|, |WinClosed|. 914 *RemoteReply* 915 RemoteReply When a reply from a Vim that functions as 916 server was received server2client(). The 917 pattern is matched against the {serverid}. 918 <amatch> is equal to the {serverid} from which 919 the reply was sent, and <afile> is the actual 920 reply string. 921 Note that even if an autocommand is defined, 922 the reply should be read with remote_read() 923 to consume it. 924 *SearchWrapped* 925 SearchWrapped After making a search with |n| or |N| if the 926 search wraps around the document back to 927 the start/finish respectively. 928 *RecordingEnter* 929 RecordingEnter When a macro starts recording. 930 The pattern is the current file name, and 931 |reg_recording()| is the current register that 932 is used. 933 *RecordingLeave* 934 RecordingLeave When a macro stops recording. 935 The pattern is the current file name, and 936 |reg_recording()| is the recorded 937 register. 938 |reg_recorded()| is only updated after this 939 event. 940 Sets these |v:event| keys: 941 regcontents 942 regname 943 *SafeState* 944 SafeState When nothing is pending, going to wait for the 945 user to type a character. 946 This will not be triggered when: 947 - an operator is pending 948 - a register was entered with "r 949 - halfway executing a command 950 - executing a mapping 951 - there is typeahead 952 - Insert mode completion is active 953 - Command line completion is active 954 You can use `mode()` to find out what state 955 Vim is in. That may be: 956 - Visual mode 957 - Normal mode 958 - Insert mode 959 - Command-line mode 960 Depending on what you want to do, you may also 961 check more with `state()`, e.g. whether the 962 screen was scrolled for messages. 963 964 *SessionLoadPre* 965 SessionLoadPre Before loading the session file created using 966 the |:mksession| command. 967 *SessionLoadPost* 968 SessionLoadPost After loading the session file created using 969 the |:mksession| command. 970 *SessionWritePost* 971 SessionWritePost After writing a session file by calling 972 the |:mksession| command. 973 *ShellCmdPost* 974 ShellCmdPost After executing a shell command with |:!cmd|, 975 |:make| and |:grep|. Can be used to check for 976 any changed files. 977 For non-blocking shell commands, see 978 |job-control|. 979 *Signal* 980 Signal After Nvim receives a signal. The pattern is 981 matched against the signal name. Only 982 "SIGUSR1" and "SIGWINCH" are supported. 983 This is triggered even when inside an 984 autocommand defined without |autocmd-nested|. 985 Example: >vim 986 autocmd Signal SIGUSR1 call some#func() 987 < *ShellFilterPost* 988 ShellFilterPost After executing a shell command with 989 ":{range}!cmd", ":w !cmd" or ":r !cmd". 990 Can be used to check for any changed files. 991 *SourcePre* 992 SourcePre Before sourcing a Vimscript/Lua file. |:source| 993 <afile> is the name of the file being sourced. 994 *SourcePost* 995 SourcePost After sourcing a Vimscript/Lua file. |:source| 996 <afile> is the name of the file being sourced. 997 Not triggered when sourcing was interrupted. 998 Also triggered after a SourceCmd autocommand 999 was triggered. 1000 *SourceCmd* 1001 SourceCmd When sourcing a Vimscript/Lua file. |:source| 1002 <afile> is the name of the file being sourced. 1003 The autocommand must source that file. 1004 |Cmd-event| 1005 *SpellFileMissing* 1006 SpellFileMissing When trying to load a spell checking file and 1007 it can't be found. The pattern is matched 1008 against the language. <amatch> is the 1009 language, 'encoding' also matters. See 1010 |spell-SpellFileMissing|. 1011 *StdinReadPost* 1012 StdinReadPost During startup, after reading from stdin into 1013 the buffer, before executing modelines. |--| 1014 *StdinReadPre* 1015 StdinReadPre During startup, before reading from stdin into 1016 the buffer. |--| 1017 *SwapExists* 1018 SwapExists Detected an existing swap file when starting 1019 to edit a file. Only when it is possible to 1020 select a way to handle the situation, when Vim 1021 would ask the user what to do. 1022 The |v:swapname| variable holds the name of 1023 the swap file found, <afile> the file being 1024 edited. |v:swapcommand| may contain a command 1025 to be executed in the opened file. 1026 The commands should set the |v:swapchoice| 1027 variable to a string with one character to 1028 tell Vim what should be done next: 1029 'o' open read-only 1030 'e' edit the file anyway 1031 'r' recover 1032 'd' delete the swap file 1033 'q' quit, don't edit the file 1034 'a' abort, like hitting CTRL-C 1035 When set to an empty string the user will be 1036 asked, as if there was no SwapExists autocmd. 1037 *E812* 1038 Cannot change to another buffer, change 1039 the buffer name or change directory. 1040 *Syntax* 1041 Syntax When the 'syntax' option has been set. The 1042 pattern is matched against the syntax name. 1043 <afile> expands to the name of the file where 1044 this option was set. <amatch> expands to the 1045 new value of 'syntax'. 1046 See |:syn-on|. 1047 *TabClosed* 1048 TabClosed After closing a tab page. <afile> expands to 1049 the tab page number. 1050 *TabClosedPre* 1051 TabClosedPre Before closing a tab page. The window layout 1052 is locked, thus opening and closing of windows 1053 is prohibited. 1054 *TabEnter* 1055 TabEnter Just after entering a tab page. |tab-page| 1056 After WinEnter. 1057 Before BufEnter. 1058 *TabLeave* 1059 TabLeave Just before leaving a tab page. |tab-page| 1060 After WinLeave. 1061 *TabNew* 1062 TabNew When creating a new tab page. |tab-page| 1063 After WinEnter. 1064 Before TabEnter. 1065 *TabNewEntered* 1066 TabNewEntered After entering a new tab page. |tab-page| 1067 After BufEnter. 1068 *TermOpen* 1069 TermOpen When a |terminal| job is starting. Can be 1070 used to configure the terminal buffer. To get 1071 the terminal process details: >lua 1072 vim.print(vim.api.nvim_get_chan_info(vim.bo.channel)) 1073 < 1074 *TermEnter* 1075 TermEnter After entering |Terminal-mode|. 1076 After TermOpen. 1077 *TermLeave* 1078 TermLeave After leaving |Terminal-mode|. 1079 After TermClose. 1080 *TermClose* 1081 TermClose When a |terminal| job ends. 1082 Sets these |v:event| keys: 1083 status job exit status, or -1 if the 1084 terminal buffer is deleted 1085 *TermRequest* 1086 TermRequest When a |:terminal| child process emits an OSC, 1087 DCS, or APC sequence. Sets |v:termrequest|. The 1088 |event-data| is a table with the following 1089 fields: 1090 1091 - sequence: the received sequence 1092 - terminator: the received sequence terminator (i.e. BEL or ST) 1093 - cursor: (1,0)-indexed, buffer-relative 1094 position of the cursor when the sequence was 1095 received (line number may be <= 0 if the 1096 position is no longer in the buffer) 1097 1098 This is triggered even when inside an 1099 autocommand defined without |autocmd-nested|. 1100 1101 *TermResponse* 1102 TermResponse When Nvim receives a DA1, OSC, DCS, or APC response from 1103 the host terminal. Sets |v:termresponse|. The 1104 |event-data| is a table with the following fields: 1105 1106 - sequence: the received sequence 1107 1108 This is triggered even when inside an 1109 autocommand defined without |autocmd-nested|. 1110 1111 May be triggered during another event (file 1112 I/O, a shell command, or anything else that 1113 takes time). 1114 1115 Example: >lua 1116 1117 -- Query the terminal palette for the RGB value of color 1 1118 -- (red) using OSC 4 1119 vim.api.nvim_create_autocmd('TermResponse', { 1120 once = true, 1121 callback = function(args) 1122 local resp = args.data.sequence 1123 local r, g, b = resp:match("\027%]4;1;rgb:(%w+)/(%w+)/(%w+)") 1124 end, 1125 }) 1126 vim.api.nvim_ui_send("\027]4;1;?\027\\") 1127 < 1128 *TextChanged* 1129 TextChanged After a change was made to the text in the 1130 current buffer in Normal mode. That is after 1131 |b:changedtick| has changed (also when that 1132 happened before the TextChanged autocommand 1133 was defined). 1134 Not triggered when there is typeahead or when 1135 an operator is pending. 1136 Note: Cannot be skipped with `:noautocmd`. 1137 Careful: This is triggered very often, don't 1138 do anything that the user does not expect or 1139 that is slow. 1140 *TextChangedI* 1141 TextChangedI After a change was made to the text in the 1142 current buffer in Insert mode. 1143 Not triggered when the popup menu is visible. 1144 Otherwise the same as TextChanged. 1145 *TextChangedP* 1146 TextChangedP After a change was made to the text in the 1147 current buffer in Insert mode, only when the 1148 popup menu is visible. Otherwise the same as 1149 TextChanged. 1150 *TextChangedT* 1151 TextChangedT After a change was made to the text in the 1152 current buffer in |Terminal-mode|. Otherwise 1153 the same as TextChanged. 1154 *TextYankPost* 1155 TextYankPost Just after a |yank| or |deleting| command, but not 1156 if the black hole register |quote_| is used nor 1157 for |setreg()|. Pattern must be "*". 1158 Sets these |v:event| keys: 1159 inclusive 1160 operator 1161 regcontents 1162 regname 1163 regtype 1164 visual 1165 The `inclusive` flag combined with the |'[| 1166 and |']| marks can be used to calculate the 1167 precise region of the operation. 1168 1169 Non-recursive (event cannot trigger itself). 1170 Cannot change the text. |textlock| 1171 *User* 1172 User Not executed automatically. Use |:doautocmd| 1173 to trigger this, typically for "custom events" 1174 in a plugin. Example: > 1175 :autocmd User MyPlugin echom 'got MyPlugin event' 1176 :doautocmd User MyPlugin 1177 < *UserGettingBored* 1178 UserGettingBored When the user presses the same key 42 times. 1179 Just kidding! :-) 1180 *VimEnter* 1181 VimEnter After doing all the startup stuff, including 1182 loading vimrc files, executing the "-c cmd" 1183 arguments, creating all windows and loading 1184 the buffers in them. 1185 Just before this event is triggered the 1186 |v:vim_did_enter| variable is set, so that you 1187 can do: > 1188 if v:vim_did_enter 1189 call s:init() 1190 else 1191 au VimEnter * call s:init() 1192 endif 1193 < *VimLeave* 1194 VimLeave Before exiting Vim, just after writing the 1195 .shada file. Executed only once, like 1196 VimLeavePre. 1197 Use |v:dying| to detect an abnormal exit. 1198 Use |v:exiting| to get the exit code. 1199 Not triggered if |v:dying| is 2 or more. 1200 *VimLeavePre* 1201 VimLeavePre Before exiting Vim, just before writing the 1202 |shada| file. Executed only once, if the 1203 pattern matches the current buffer on exit. 1204 Mostly useful with a "*" pattern. > 1205 :autocmd VimLeavePre * call CleanupStuff() 1206 < Use |v:dying| to detect an abnormal exit. 1207 Use |v:exiting| to get the exit code. 1208 Not triggered if |v:dying| is 2 or more. 1209 *VimResized* 1210 VimResized After the Vim window was resized, thus 'lines' 1211 and/or 'columns' changed. Not when starting 1212 up though. 1213 *VimResume* 1214 VimResume After Nvim resumes from |suspend| state. 1215 *VimSuspend* 1216 VimSuspend Before Nvim enters |suspend| state. 1217 *WinClosed* 1218 WinClosed When closing a window, just before it is 1219 removed from the window layout. The pattern 1220 is matched against the |window-ID|. Both 1221 <amatch> and <afile> are set to the |window-ID|. 1222 After WinLeave. 1223 Non-recursive (event cannot trigger itself). 1224 See also |ExitPre|, |QuitPre|. 1225 *WinEnter* 1226 WinEnter After entering another window. Not done for 1227 the first window, when Vim has just started. 1228 Useful for setting the window height. 1229 If the window is for another buffer, Vim 1230 executes the BufEnter autocommands after the 1231 WinEnter autocommands. 1232 Note: For split and tabpage commands the 1233 WinEnter event is triggered after the split 1234 or tab command but before the file is loaded. 1235 1236 *WinLeave* 1237 WinLeave Before leaving a window. If the window to be 1238 entered next is for a different buffer, Vim 1239 executes the BufLeave autocommands before the 1240 WinLeave autocommands (but not for ":new"). 1241 Not used for ":qa" or ":q" when exiting Vim. 1242 Before WinClosed. 1243 *WinNewPre* 1244 WinNewPre Before creating a new window. Triggered 1245 before commands that modify window layout by 1246 creating a split. 1247 Not done when creating tab pages and for the 1248 first window, as the window structure is not 1249 initialized yet and so is generally not safe. 1250 It is not allowed to modify window layout 1251 while executing commands for the WinNewPre 1252 event. 1253 Most useful to store current window layout 1254 and compare it with the new layout after the 1255 Window has been created. 1256 1257 *WinNew* 1258 WinNew When a new window was created. Not done for 1259 the first window, when Vim has just started. 1260 Before WinEnter. 1261 1262 *WinScrolled* 1263 WinScrolled After any window in the current tab page 1264 scrolled the text (horizontally or vertically) 1265 or changed width or height. See 1266 |win-scrolled-resized|. 1267 1268 Note: This can not be skipped with 1269 `:noautocmd`, because it triggers after 1270 processing normal commands when Vim is back in 1271 the main loop. If you want to disable this, 1272 consider setting the 'eventignore' option 1273 instead. 1274 1275 The pattern is matched against the |window-ID| 1276 of the first window that scrolled or resized. 1277 Both <amatch> and <afile> are set to the 1278 |window-ID|. 1279 1280 |v:event| is set with information about size 1281 and scroll changes. |WinScrolled-event| 1282 1283 Only starts triggering after startup finished 1284 and the first screen redraw was done. 1285 Does not trigger when defining the first 1286 WinScrolled or WinResized event, but may 1287 trigger when adding more. 1288 1289 Non-recursive: the event will not trigger 1290 while executing commands for the WinScrolled 1291 event. However, if the command causes a 1292 window to scroll or change size, then another 1293 WinScrolled event will be triggered later. 1294 1295 1296 *WinResized* 1297 WinResized After a window in the current tab page changed 1298 width or height. 1299 See |win-scrolled-resized|. 1300 1301 |v:event| is set with information about size 1302 changes. |WinResized-event| 1303 1304 Same behavior as |WinScrolled| for the 1305 pattern, triggering and recursiveness. 1306 1307 ============================================================================== 1308 6. Patterns *autocmd-pattern* *{aupat}* 1309 1310 The {aupat} argument of `:autocmd` can be a comma-separated list. This works as 1311 if the command was given with each pattern separately. Thus this command: > 1312 :autocmd BufRead *.txt,*.info set et 1313 Is equivalent to: > 1314 :autocmd BufRead *.txt set et 1315 :autocmd BufRead *.info set et 1316 1317 The file pattern {aupat} is tested for a match against the file name in one of 1318 two ways: 1319 1. When there is no '/' in the pattern, Vim checks for a match against only 1320 the tail part of the file name (without its leading directory path). 1321 2. When there is a '/' in the pattern, Vim checks for a match against both the 1322 short file name (as you typed it) and the full file name (after expanding 1323 it to a full path and resolving symbolic links). 1324 1325 The special pattern <buffer> or <buffer=N> is used for buffer-local 1326 autocommands |autocmd-buflocal|. This pattern is not matched against the name 1327 of a buffer. 1328 1329 Examples: > 1330 :autocmd BufRead *.txt set et 1331 Set the 'et' option for all text files. > 1332 1333 :autocmd BufRead /vim/src/*.c set cindent 1334 Set the 'cindent' option for C files in the /vim/src directory. > 1335 1336 :autocmd BufRead /tmp/*.c set ts=5 1337 If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", and 1338 you start editing "/tmp/test.c", this autocommand will match. 1339 1340 Note: To match part of a path, but not from the root directory, use a "*" as 1341 the first character. Example: > 1342 :autocmd BufRead */doc/*.txt set tw=78 1343 This autocommand will for example be executed for "/tmp/doc/xx.txt" and 1344 "/usr/home/piet/doc/yy.txt". The number of directories does not matter here. 1345 1346 1347 The file name that the pattern is matched against is after expanding 1348 wildcards. Thus if you issue this command: > 1349 :e $ROOTDIR/main.$EXT 1350 The argument is first expanded to: > 1351 /usr/root/main.py 1352 Before it's matched with the pattern of the autocommand. Careful with this 1353 when using events like FileReadCmd, the value of <amatch> may not be what you 1354 expect. 1355 1356 1357 Environment variables can be used in a pattern: > 1358 :autocmd BufRead $VIMRUNTIME/doc/*.txt set expandtab 1359 And ~ can be used for the home directory (if $HOME is defined): > 1360 :autocmd BufWritePost ~/.config/nvim/init.vim so <afile> 1361 :autocmd BufRead ~archive/* set readonly 1362 The environment variable is expanded when the autocommand is defined, not when 1363 the autocommand is executed. This is different from the command! 1364 1365 *file-pattern* 1366 The pattern is interpreted like mostly used in file names: 1367 * matches any sequence of characters; Unusual: includes path 1368 separators 1369 ? matches any single character 1370 \? matches a '?' 1371 . matches a '.' 1372 ~ matches a '~' 1373 , separates patterns 1374 \, matches a ',' 1375 { } like \( \) in a |pattern| 1376 , inside { }: like \| in a |pattern| 1377 \} literal } 1378 \{ literal { 1379 \\\{n,m\} like \{n,m} in a |pattern| 1380 \ special meaning like in a |pattern| 1381 [ch] matches 'c' or 'h' 1382 [^ch] match any character but 'c' and 'h' 1383 1384 Note that for all systems the '/' character is used for path separator (even 1385 for MS-Windows). This was done because the backslash is difficult to use in a 1386 pattern and to make the autocommands portable across different systems. To 1387 only match a '/' on all platforms (e.g. in a non-file pattern), use "\/". 1388 1389 It is possible to use |pattern| items, but they may not work as expected, 1390 because of the translation done for the above. 1391 1392 *autocmd-changes* 1393 Matching with the pattern is done when an event is triggered. Changing the 1394 buffer name in one of the autocommands, or even deleting the buffer, does not 1395 change which autocommands will be executed. Example: > 1396 1397 au BufEnter *.foo bdel 1398 au BufEnter *.foo set modified 1399 1400 This will delete the current buffer and then set 'modified' in what has become 1401 the current buffer instead. Vim doesn't take into account that "*.foo" 1402 doesn't match with that buffer name. It matches "*.foo" with the name of the 1403 buffer at the moment the event was triggered. 1404 1405 However, buffer-local autocommands will not be executed for a buffer that has 1406 been wiped out with |:bwipe|. After deleting the buffer with |:bdel| the 1407 buffer actually still exists (it becomes unlisted), thus the autocommands are 1408 still executed. 1409 1410 ============================================================================== 1411 7. Buffer-local autocommands *autocmd-buflocal* *autocmd-buffer-local* 1412 *<buffer>* *<buffer=N>* *<buffer=abuf>* *E680* 1413 1414 Buffer-local autocommands are attached to a specific buffer. They are useful 1415 if the buffer does not have a name and when the name does not match a specific 1416 pattern. But it also means they must be explicitly added to each buffer. 1417 1418 Instead of a pattern buffer-local autocommands use one of these forms: 1419 <buffer> current buffer 1420 <buffer=99> buffer number 99 1421 <buffer=abuf> using <abuf> (only when executing autocommands) 1422 |<abuf>| 1423 1424 Examples: > 1425 :au CursorHold <buffer> echo 'hold' 1426 :au CursorHold <buffer=33> echo 'hold' 1427 :au BufNewFile * au CursorHold <buffer=abuf> echo 'hold' 1428 1429 All the commands for autocommands also work with buffer-local autocommands, 1430 simply use the special string instead of the pattern. Examples: > 1431 :au! * <buffer> " remove buffer-local autocommands for 1432 " current buffer 1433 :au! * <buffer=33> " remove buffer-local autocommands for 1434 " buffer #33 1435 :bufdo :au! CursorHold <buffer> " remove autocmd for given event for all 1436 " buffers 1437 :au * <buffer> " list buffer-local autocommands for 1438 " current buffer 1439 1440 Note that when an autocommand is defined for the current buffer, it is stored 1441 with the buffer number. Thus it uses the form "<buffer=12>", where 12 is the 1442 number of the current buffer. You will see this when listing autocommands, 1443 for example. 1444 1445 To test for presence of buffer-local autocommands use the |exists()| function 1446 as follows: > 1447 :if exists("#CursorHold#<buffer=12>") | ... | endif 1448 :if exists("#CursorHold#<buffer>") | ... | endif " for current buffer 1449 1450 When a buffer is wiped out its buffer-local autocommands are also gone, of 1451 course. Note that when deleting a buffer, e.g., with ":bdel", it is only 1452 unlisted, the autocommands are still present. In order to see the removal of 1453 buffer-local autocommands: > 1454 :set verbose=6 1455 1456 It is not possible to define buffer-local autocommands for a non-existent 1457 buffer. 1458 1459 ============================================================================== 1460 8. Groups *autocmd-groups* 1461 1462 Autocommands can be put together in a group. This is useful for removing or 1463 executing a group of autocommands. For example, all the autocommands for 1464 syntax highlighting are put in the "highlight" group, to be able to execute 1465 ":doautoall highlight BufRead" when the GUI starts. 1466 1467 When no specific group is selected, Vim uses the default group. The default 1468 group does not have a name. You cannot execute the autocommands from the 1469 default group separately; you can execute them only by executing autocommands 1470 for all groups. 1471 1472 Normally, when executing autocommands automatically, Vim uses the autocommands 1473 for all groups. The group only matters when executing autocommands with 1474 ":doautocmd" or ":doautoall", or when defining or deleting autocommands. 1475 1476 The group name can contain any characters except white space. The group name 1477 "end" is reserved (also in uppercase). 1478 1479 The group name is case sensitive. Note that this is different from the event 1480 name! 1481 1482 *:aug* *:augroup* 1483 :aug[roup] {name} Define the autocmd group name for the 1484 following ":autocmd" commands. The name "end" 1485 or "END" selects the default group. 1486 To avoid confusion, the name should be 1487 different from existing {event} names, as this 1488 most likely will not do what you intended. 1489 1490 *:augroup-delete* *E367* *W19* *E936* 1491 :aug[roup]! {name} Delete the autocmd group {name}. Don't use 1492 this if there is still an autocommand using 1493 this group! You will get a warning if doing 1494 it anyway. When the group is the current 1495 group you will get error E936. 1496 1497 To enter autocommands for a specific group, use this method: 1498 1. Select the group with ":augroup {name}". 1499 2. Delete any old autocommands with ":au!". 1500 3. Define the autocommands. 1501 4. Go back to the default group with "augroup END". 1502 1503 Example: > 1504 :augroup uncompress 1505 : au! 1506 : au BufEnter *.gz %!gunzip 1507 :augroup END 1508 1509 This prevents having the autocommands defined twice (e.g., after sourcing the 1510 vimrc file again). 1511 1512 *FileExplorer* 1513 There is one group that is recognized by Vim: FileExplorer. If this group 1514 exists Vim assumes that editing a directory is possible and will trigger a 1515 plugin that lists the files in that directory. This is used by directory 1516 browser plugins. This allows you to do: > 1517 browse edit 1518 1519 ============================================================================== 1520 9. Executing autocommands *autocmd-execute* 1521 1522 Vim can also execute Autocommands non-automatically. This is useful if you 1523 have changed autocommands, or when Vim has executed the wrong autocommands 1524 (e.g., the file pattern match was wrong). 1525 1526 Note that the 'eventignore' option applies here too. Events listed in this 1527 option will not cause any commands to be executed. 1528 1529 *:do* *:doau* *:doaut* *:doautocmd* *E217* 1530 :do[autocmd] [<nomodeline>] [group] {event} [fname] 1531 Apply the autocommands matching [fname] (default: 1532 current file name) for {event} to the current buffer. 1533 You can use this when the current file name does not 1534 match the right pattern, after changing settings, or 1535 to execute autocommands for a certain event. 1536 It's possible to use this inside an autocommand too, 1537 so you can base the autocommands for one extension on 1538 another extension. Example: > 1539 :au BufEnter *.cpp so ~/.config/nvim/init_cpp.vim 1540 :au BufEnter *.cpp doau BufEnter x.c 1541 < Be careful to avoid endless loops. |autocmd-nested| 1542 1543 When the [group] argument is not given, Vim executes 1544 the autocommands for all groups. When the [group] 1545 argument is included, Vim executes only the matching 1546 autocommands for that group. Undefined group is an 1547 error. 1548 *<nomodeline>* 1549 After applying the autocommands the modelines are 1550 processed, so that their settings overrule the 1551 settings from autocommands when editing a file. This 1552 is skipped if <nomodeline> is specified. You probably 1553 want to use <nomodeline> for events not used when 1554 loading a buffer, such as |User|. 1555 Modelines are also skipped when no matching 1556 autocommands were executed. 1557 1558 *:doautoa* *:doautoall* 1559 :doautoa[ll] [<nomodeline>] [group] {event} [fname] 1560 Like ":doautocmd", but apply the autocommands to each 1561 loaded buffer. The current buffer is done last. 1562 1563 Note that [fname] is used to select the autocommands, 1564 not the buffers to which they are applied. Example: > 1565 augroup mine 1566 autocmd! 1567 autocmd FileType * echo expand('<amatch>') 1568 augroup END 1569 doautoall mine FileType Loaded-Buffer 1570 < Sourcing this script, you'll see as many 1571 "Loaded-Buffer" echoed as there are loaded buffers. 1572 1573 Careful: Don't use this for autocommands that delete a 1574 buffer, change to another buffer or change the 1575 contents of a buffer; the result is unpredictable. 1576 This command is intended for autocommands that set 1577 options, change highlighting, and things like that. 1578 1579 ============================================================================== 1580 10. Using autocommands *autocmd-use* 1581 1582 For WRITING FILES there are four possible sets of events. Vim uses only one 1583 of these sets for a write command: 1584 1585 BufWriteCmd BufWritePre BufWritePost writing the whole buffer 1586 FilterWritePre FilterWritePost writing to filter temp file 1587 FileAppendCmd FileAppendPre FileAppendPost appending to a file 1588 FileWriteCmd FileWritePre FileWritePost any other file write 1589 1590 When there is a matching "*Cmd" autocommand, it is assumed it will do the 1591 writing. No further writing is done and the other events are not triggered. 1592 |Cmd-event| 1593 1594 Note that the "*WritePost" commands should undo any changes to the buffer that 1595 were caused by the "*WritePre" commands; otherwise, writing the file will have 1596 the side effect of changing the buffer. 1597 1598 Before executing the autocommands, the buffer from which the lines are to be 1599 written temporarily becomes the current buffer. Unless the autocommands 1600 change the current buffer or delete the previously current buffer, the 1601 previously current buffer is made the current buffer again. 1602 1603 The "*WritePre" and "*AppendPre" autocommands must not delete the buffer from 1604 which the lines are to be written. 1605 1606 The '[ and '] marks have a special position: 1607 - Before the "*ReadPre" event the '[ mark is set to the line just above where 1608 the new lines will be inserted. 1609 - Before the "*ReadPost" event the '[ mark is set to the first line that was 1610 just read, the '] mark to the last line. 1611 - Before executing the "*WriteCmd", "*WritePre" and "*AppendPre" autocommands the '[ 1612 mark is set to the first line that will be written, the '] mark to the last 1613 line. 1614 Careful: '[ and '] change when using commands that change the buffer. 1615 1616 In commands which expect a file name, you can use "<afile>" for the file name 1617 that is being read |:<afile>| (you can also use "%" for the current file 1618 name). "<abuf>" can be used for the buffer number of the currently effective 1619 buffer. This also works for buffers that don't have a name. But it doesn't 1620 work for files without a buffer (e.g., with ":r file"). 1621 1622 *gzip-example* 1623 Examples for reading and writing compressed files: > 1624 :augroup gzip 1625 : autocmd! 1626 : autocmd BufReadPre,FileReadPre *.gz set bin 1627 : autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip 1628 : autocmd BufReadPost,FileReadPost *.gz set nobin 1629 : autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " .. expand("%:r") 1630 : autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r 1631 : autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r 1632 1633 : autocmd FileAppendPre *.gz !gunzip <afile> 1634 : autocmd FileAppendPre *.gz !mv <afile>:r <afile> 1635 : autocmd FileAppendPost *.gz !mv <afile> <afile>:r 1636 : autocmd FileAppendPost *.gz !gzip <afile>:r 1637 :augroup END 1638 1639 The "gzip" group is used to be able to delete any existing autocommands with 1640 ":autocmd!", for when the file is sourced twice. 1641 1642 ("<afile>:r" is the file name without the extension, see |:_%:|) 1643 1644 The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost, 1645 FileAppendPost and VimLeave events do not set or reset the changed flag of the 1646 buffer. When you decompress the buffer with the BufReadPost autocommands, you 1647 can still exit with ":q". When you use ":undo" in BufWritePost to undo the 1648 changes made by BufWritePre commands, you can still do ":q" (this also makes 1649 "ZZ" work). If you do want the buffer to be marked as modified, set the 1650 'modified' option. 1651 1652 To execute Normal mode commands from an autocommand, use the ":normal" 1653 command. Use with care! If the Normal mode command is not finished, the user 1654 needs to type characters (e.g., after ":normal m" you need to type a mark 1655 name). 1656 1657 If you want the buffer to be unmodified after changing it, reset the 1658 'modified' option. This makes it possible to exit the buffer with ":q" 1659 instead of ":q!". 1660 1661 *autocmd-nested* *E218* 1662 By default, autocommands do not nest. For example, if you use ":e" or ":w" in 1663 an autocommand, Vim does not execute the BufRead and BufWrite autocommands for 1664 those commands. If you do want this, use the "++nested" flag for those 1665 commands in which you want nesting. For example: > 1666 :autocmd FileChangedShell *.c ++nested e! 1667 The nesting is limited to 10 levels to get out of recursive loops. 1668 1669 It's possible to use the ":au" command in an autocommand. This can be a 1670 self-modifying command! This can be useful for an autocommand that should 1671 execute only once. 1672 1673 If you want to skip autocommands for one command, use the |:noautocmd| command 1674 modifier or the 'eventignore' option. 1675 1676 Note: When reading a file (with ":read file" or with a filter command) and the 1677 last line in the file does not have an <EOL>, Vim remembers this. At the next 1678 write (with ":write file" or with a filter command), if the same line is 1679 written again as the last line in a file AND 'binary' is set, Vim does not 1680 supply an <EOL>. This makes a filter command on the just read lines write the 1681 same file as was read, and makes a write command on just filtered lines write 1682 the same file as was read from the filter. For example, another way to write 1683 a compressed file: > 1684 1685 :autocmd FileWritePre *.gz set bin|'[,']!gzip 1686 :autocmd FileWritePost *.gz undo|set nobin 1687 < 1688 *autocommand-pattern* 1689 You can specify multiple patterns, separated by commas. Here are some 1690 examples: > 1691 1692 :autocmd BufRead * set tw=79 nocin ic infercase fo=2croq 1693 :autocmd BufRead .letter set tw=72 fo=2tcrq 1694 :autocmd BufEnter .letter set dict=/usr/lib/dict/words 1695 :autocmd BufLeave .letter set dict= 1696 :autocmd BufRead,BufNewFile *.c,*.h set tw=0 cin noic 1697 :autocmd BufEnter *.c,*.h abbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O 1698 :autocmd BufLeave *.c,*.h unabbr FOR 1699 1700 For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.): > 1701 1702 :autocmd BufEnter ?akefile* set include=^s\=include 1703 :autocmd BufLeave ?akefile* set include& 1704 1705 To always start editing C files at the first function: > 1706 1707 :autocmd BufRead *.c,*.h 1;/^{ 1708 1709 Without the "1;" above, the search would start from wherever the file was 1710 entered, rather than from the start of the file. 1711 1712 *skeleton* *template* 1713 To read a skeleton (template) file when opening a new file: > 1714 1715 :autocmd BufNewFile *.c 0r ~/vim/skeleton.c 1716 :autocmd BufNewFile *.h 0r ~/vim/skeleton.h 1717 :autocmd BufNewFile *.java 0r ~/vim/skeleton.java 1718 1719 To insert the current date and time in a "*.html" file when writing it: > 1720 1721 :autocmd BufWritePre,FileWritePre *.html ks|call LastMod()|'s 1722 :fun LastMod() 1723 : if line("$") > 20 1724 : let l = 20 1725 : else 1726 : let l = line("$") 1727 : endif 1728 : exe "1," .. l .. "g/Last modified: /s/Last modified: .*/Last modified: " .. 1729 : \ strftime("%Y %b %d") 1730 :endfun 1731 1732 You need to have a line "Last modified: <date time>" in the first 20 lines 1733 of the file for this to work. Vim replaces <date time> (and anything in the 1734 same line after it) with the current date and time. Explanation: 1735 ks mark current position with mark 's' 1736 call LastMod() call the LastMod() function to do the work 1737 's return the cursor to the old position 1738 The LastMod() function checks if the file is shorter than 20 lines, and then 1739 uses the ":g" command to find lines that contain "Last modified: ". For those 1740 lines the ":s" command is executed to replace the existing date with the 1741 current one. The ":execute" command is used to be able to use an expression 1742 for the ":g" and ":s" commands. The date is obtained with the strftime() 1743 function. You can change its argument to get another date string. 1744 1745 When entering :autocmd on the command-line, completion of events and command 1746 names may be done (with <Tab>, CTRL-D, etc.) where appropriate. 1747 1748 Vim executes all matching autocommands in the order that you specify them. 1749 It is recommended that your first autocommand be used for all files by using 1750 "*" as the file pattern. This means that you can define defaults you like 1751 here for any settings, and if there is another matching autocommand it will 1752 override these. But if there is no other matching autocommand, then at least 1753 your default settings are recovered (if entering this file from another for 1754 which autocommands did match). Note that "*" will also match files starting 1755 with ".", unlike Unix shells. 1756 1757 *autocmd-searchpat* 1758 Autocommands do not change the current search patterns. Vim saves the current 1759 search patterns before executing autocommands then restores them after the 1760 autocommands finish. This means that autocommands do not affect the strings 1761 highlighted with the 'hlsearch' option. Within autocommands, you can still 1762 use search patterns normally, e.g., with the "n" command. 1763 If you want an autocommand to set the search pattern, such that it is used 1764 after the autocommand finishes, use the ":let @/ =" command. 1765 The search-highlighting cannot be switched off with ":nohlsearch" in an 1766 autocommand. Use the 'h' flag in the 'shada' option to disable search- 1767 highlighting when starting Vim. 1768 1769 *Cmd-event* 1770 When using one of the "*Cmd" events, the matching autocommands are expected to 1771 do the file reading, writing or sourcing. This can be used when working with 1772 a special kind of file, for example on a remote system. 1773 CAREFUL: If you use these events in a wrong way, it may have the effect of 1774 making it impossible to read or write the matching files! Make sure you test 1775 your autocommands properly. Best is to use a pattern that will never match a 1776 normal file name, for example "ftp://*". 1777 1778 When defining a BufReadCmd it will be difficult for Vim to recover a crashed 1779 editing session. When recovering from the original file, Vim reads only those 1780 parts of a file that are not found in the swap file. Since that is not 1781 possible with a BufReadCmd, use the |:preserve| command to make sure the 1782 original file isn't needed for recovery. You might want to do this only when 1783 you expect the file to be modified. 1784 1785 For file read and write commands the |v:cmdarg| variable holds the "++enc=" 1786 and "++ff=" argument that are effective. These should be used for the command 1787 that reads/writes the file. The |v:cmdbang| variable is one when "!" was 1788 used, zero otherwise. 1789 1790 See the $VIMRUNTIME/pack/dist/opt/netrw/plugin/netrwPlugin.vim for examples. 1791 1792 ============================================================================== 1793 11. Disabling autocommands *autocmd-disable* 1794 1795 To disable autocommands for some time use the 'eventignore' option. Note that 1796 this may cause unexpected behavior, make sure you restore 'eventignore' 1797 afterwards, using a |:try| block with |:finally|. 1798 1799 To disable autocmds indefinitely in a specific window use the 'eventignorewin' 1800 option. This can only be used to ignore window and buffer related events. 1801 1802 *:noautocmd* *:noa* 1803 To disable autocommands for just one command use the ":noautocmd" command 1804 modifier. This will set 'eventignore' to "all" for the duration of the 1805 following command. Example: > 1806 1807 :noautocmd w fname.gz 1808 1809 This will write the file without triggering the autocommands defined by the 1810 gzip plugin. 1811 1812 Note that some autocommands are not triggered right away, but only later. 1813 This specifically applies to |CursorMoved| and |TextChanged|. 1814 1815 1816 vim:tw=78:ts=8:noet:ft=help:norl: