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