autocmd.txt ForVim version 9.1. Last change: 2025 Jun 19VIM REFERENCE MANUAL by Bram MoolenaarAutomatic commandsautocommandautocommandsFora basic explanation, seesection40.3 in the user manual.1. Introductionautocmd-intro2. Definingautocommandsautocmd-define3. Removingautocommandsautocmd-remove4. Listingautocommandsautocmd-list5. Eventsautocmd-events6. Patternsautocmd-patterns7. Buffer-localautocommandsautocmd-buflocal8. Groupsautocmd-groups9. Executingautocommandsautocmd-execute10. Usingautocommandsautocmd-use11. Disablingautocommandsautocmd-disable==============================================================================1. Introductionautocmd-introYou can specify commands to be executed automatically when reading orwritinga file, when entering or leavinga buffer or window, and whenexiting Vim.For example, you can create anautocommand to set the'cindent' option forfiles matching *.c. You can also useautocommands to implement advancedfeatures, suchas editing compressed files (seegzip-example). The usualplace toputautocommandsis in your.vimrc or.exrc file.E203E204E143E855E937E952WARNING: Usingautocommandsis very powerful, and may lead to unexpected sideeffects. Be careful not to destroy your text.- It'sa good idea todo sometesting on an expendable copy ofa file first. For example: If you useautocommands to decompressa file whenstarting to edit it, make sure that theautocommands for compressing whenwriting work correctly.- Be prepared for an error halfway through (e.g., disk full). Vim will mostly be able toundo the changes to the buffer, but you may have to clean up the changes to other files by hand (e.g.,compressa file that has been decompressed).- If theBufRead* events allow you to edita compressed file, the FileRead* events shoulddo the same (this makesrecovery possible in some rare cases). It'sa good idea to use the sameautocommands for the File* and Buf* events when possible.Recommended use:- Always usea group, so that it'seasy to delete the autocommand.- Keep the command itself short, calla function todo more work.- Makeit so that thescriptitis defined in can be sourced several times without theautocommand being repeated.Example inVim9 script: autocmd_add([{replace: true,group: 'DemoGroup',event: 'BufEnter',pattern: '*.txt',cmd: 'call DemoBufEnter()'}])In legacy script: call autocmd_add([#{replace: v:true, \ group: 'DemoGroup', \ event: 'BufEnter', \ pattern: '*.txt', \ cmd: 'call DemoBufEnter()' \ }])==============================================================================2. Definingautocommandsautocmd-define:au:autocmd:au[tocmd][group]{event}{aupat} [++once] [++nested]{cmd}Add{cmd} to thelist of commands that Vim willexecute automatically on{event} fora file matching{aupat}autocmd-patterns.Here{event} cannot be "*".E1155Note:Aquote characteris seenas argument to the:autocmd and won't starta comment.Vim always adds the{cmd} after existing autocommands,so that theautocommands execute in the order in whichthey were given.Seeautocmd-nested for [++nested]. "nested"(without the ++) can also be used, for backwardscompatibility, but not inVim9 script.E1078autocmd-onceIf [++once]is supplied the commandis executed once,then removed("one shot").The specialpattern<buffer> or<buffer=N> definesa buffer-local autocommand.Seeautocmd-buflocal.If the:autocmdis inVim9script (ascript that starts with:vim9scriptand ina:def function) then{cmd} will be executedas inVim9script. Thus this depends on where the autocmdis defined, not whereitistriggered.:autocmd-block{cmd} can bea block, like with:command, see:command-repl. Example:au BufReadPost *.xml { setlocal matchpairs+=<:> /<start}Theautocmd_add() function can be used to addalist of autocmds and autocmdgroups froma Vim script. Itis preferred if you have anything that wouldrequire using:execute with:autocmd.Note: The ":autocmd" command can only be followed by another command when the'|' appears where thepatternis expected. This works::augroup mine | au! BufRead | augroup ENDBut this sees "augroup"as part of the defined command::augroup mine | au! BufRead * | augroup END:augroup mine | au BufRead * set tw=70 | augroup ENDInstead you canput the group name into the command::au! mine BufRead *:au mine BufRead * set tw=70Or use:execute::augroup mine | exe "au! BufRead *" | augroup END:augroup mine | exe "au BufRead * set tw=70" | augroup ENDautocmd-expandNote that special characters (e.g., "%", "<cword>") in the ":autocmd"arguments are not expanded when theautocommandis defined. These will beexpanded when the Eventis recognized, and the{cmd}is executed. The onlyexceptionis that "<sfile>"is expanded when the autocmdis defined. Example::au BufNewFile,BufRead *.html so <sfile>:h/html.vimHere Vim expands<sfile> to the name of the file containing this line.However,<sfile> works differently ina function, in whichcase it's better touse:execute with<script> to achieve the same purpose::exe $'au BufNewFile,BufRead *.html so {expand("<script>:h")}/html.vim':autocmd adds to thelist ofautocommands regardless of whether they arealready present. When your.vimrc fileis sourced twice, theautocommandswill appear twice. To avoid this, define yourautocommands ina group, sothat you can easily clear them:augroup vimrc " Remove all vimrc autocommands autocmd! au BufNewFile,BufRead *.html so <sfile>:h/html.vimaugroup ENDIf you don't want to remove all autocommands, you can instead usea variableto ensure that Vim includes theautocommands only once::if !exists("autocommands_loaded"): let autocommands_loaded = 1: au ...:endifWhen the[group] argumentis not given, Vim uses the current group (as definedwith ":augroup"); otherwise, Vim uses the group defined with[group].Notethat[group]must have been defined before. You cannot definea new groupwith ":au group..."; use ":augroup" for that.Whiletesting autocommands, you might find the'verbose' option to be useful::set verbose=9This setting makes Vim echo theautocommandsasit executes them.When defining anautocommand ina script,it will be able to callfunctionslocal to thescript and use mappings local to the script. When the eventistriggered and the command executed,it will run in the context of thescriptit was defined in. This matters if<SID>is used ina command.When executing the commands, the message from one command overwritesaprevious message. Thisis different from when executing the commandsmanually. Mostly the screen will not scroll up, thus thereis nohit-enterprompt. When one command outputs twomessages this can happen anyway.==============================================================================3. Removingautocommandsautocmd-removeIn addition to the below described commands, theautocmd_delete() function canbe used to removealist of autocmds and autocmd groups froma Vim script.:au[tocmd]![group]{event}{aupat} [++once] [++nested]{cmd}Remove allautocommands associated with{event} and{aupat}, and add the command{cmd}.Seeautocmd-once for [++once].Seeautocmd-nested for [++nested].:au[tocmd]![group]{event}{aupat}Remove allautocommands associated with{event} and{aupat}.:au[tocmd]![group] *{aupat}Remove allautocommands associated with{aupat} forall events.:au[tocmd]![group]{event}Remove ALLautocommands for{event}.Warning: You should notdo this withouta group forBufRead and other common events,it can breakplugins,syntax highlighting, etc.:au[tocmd]![group]Remove ALL autocommands.Note:aquote will be seenas argument to the:autocmdand won't starta comment.Warning: You should normally notdo this withoutagroup,it breaks plugins,syntax highlighting, etc.When the[group] argumentis not given, Vim uses the current group (as definedwith ":augroup"); otherwise, Vim uses the group defined with[group].==============================================================================4. Listingautocommandsautocmd-list:au[tocmd][group]{event}{aupat}Show theautocommands associated with{event} and{aupat}.:au[tocmd][group] *{aupat}Show theautocommands associated with{aupat} for allevents.:au[tocmd][group]{event}Show allautocommands for{event}.:au[tocmd][group]Show all autocommands.If you provide the[group] argument, Vim lists only theautocommands for[group]; otherwise, Vim lists theautocommands for ALL groups.Note that thisargument behavior differs from that for defining and removing autocommands.In order tolist buffer-local autocommands, useapattern in the form<buffer>or <buffer=N>. Seeautocmd-buflocal.Theautocmd_get() function can be used froma Vimscript to getalist ofautocmds.:autocmd-verboseWhen'verbose'is non-zero, listing anautocommand will also display whereitwas last defined. Example: :verbose autocmd BufEnter FileExplorer BufEnter* call s:LocalBrowse(expand("<amatch>")) Last set from /usr/share/vim/vim-7.0/plugin/NetrwPlugin.vimSee:verbose-cmd for more information.==============================================================================5. Eventsautocmd-eventsE215E216You can specifya comma-separatedlist of event names. No whitespace can beused in this list. The command applies to all the events in the list.For READING FILES there are four kinds of events possible:BufNewFilestarting to edita non-existent fileBufReadPreBufReadPoststarting to edit an existing fileFilterReadPreFilterReadPostread the temp file withfilter outputFileReadPreFileReadPostany other file readVim uses only one of these four kinds when readinga file. The "Pre" and"Post" events are both triggered, before and after reading the file.Note that theautocommands for the *ReadPre events and all the Filter eventsare not allowed to change the current buffer (you will get an error message ifthis happens). Thisis to prevent the file to be read into the wrong buffer.Note that the'modified' flagis reset AFTER executing theBufReadPostandBufNewFile autocommands. But when the'modified' option was set by theautocommands, this doesn't happen.You can use the'eventignore' option to ignorea number of events or allevents.autocommand-events{event}Vim recognizes the following events. Vim ignores thecase of event names(e.g., you can use "BUFread" or "bufread" instead of "BufRead").First an overview by function witha short explanation. Then thelistalphabetically with full explanationsautocmd-events-abc.Nametriggered byReadingBufNewFilestarting to edita file that doesn't existBufReadPrestarting to edita new buffer, before reading the fileBufReadstarting to edita new buffer, after reading the fileBufReadPoststarting to edita new buffer, after reading the fileBufReadCmd beforestarting to edita new bufferCmd-eventFileReadPre before readinga file witha ":read" commandFileReadPost after readinga file witha ":read" commandFileReadCmd before readinga file witha ":read" commandCmd-eventFilterReadPre before readinga file fromafilter commandFilterReadPost after readinga file fromafilter commandStdinReadPre before reading from stdin into the bufferStdinReadPost After reading from the stdin into the bufferWritingBufWritestarting to write the whole buffer toa fileBufWritePrestarting to write the whole buffer toa fileBufWritePost afterwriting the whole buffer toa fileBufWriteCmd beforewriting the whole buffer toa fileCmd-eventFileWritePrestarting to write part ofa buffer toa fileFileWritePost afterwriting part ofa buffer toa fileFileWriteCmd beforewriting part ofa buffer toa fileCmd-eventFileAppendPrestarting to append toa fileFileAppendPost after appending toa fileFileAppendCmd before appending toa fileCmd-eventFilterWritePrestarting to writea file forafilter command ordiffFilterWritePost afterwritinga file forafilter command ordiffBuffersBufAdd just after addinga buffer to the bufferlistBufCreate just after addinga buffer to the bufferlistBufDelete beforedeletinga buffer from the bufferlistBufWipeout before completelydeletinga bufferBufFilePre beforechanging the name of the current bufferBufFilePost afterchanging the name of the current bufferBufEnter after enteringa bufferBufLeave before leaving to another bufferBufWinEnter aftera bufferis displayed inawindowBufWinLeave beforea bufferis removed fromawindowBufUnload before unloadinga bufferBufHidden just beforea buffer becomes hiddenBufNew just after creatinga new bufferSwapExists detected an existing swap fileOptionsFileType when the'filetype' option has been setSyntax when the'syntax' option has been setEncodingChanged after the'encoding' option has been changedTermChanged after the value of'term' has changedOptionSet after setting any optionStartup and exitVimEnter after doing all thestartup stuffGUIEnter afterstarting theGUI successfullyGUIFailed afterstarting theGUI failedTermResponse after theterminal response tot_RVis receivedTermResponseAll after theterminal response tot_RV and othersis receivedQuitPre when using:quit, before deciding whether to exitExitPre when usinga command that may make Vim exitVimLeavePre beforeexiting Vim, beforewriting theviminfo fileVimLeave beforeexiting Vim, afterwriting theviminfo fileVimSuspend when suspending VimVimResume when Vimis resumed after being suspendedTerminalTerminalOpen afteraterminal buffer was createdTerminalWinOpen afteraterminal buffer was created ina newwindowVariousFileChangedShell Vim notices thata file changed since editing startedFileChangedShellPost After handlinga file changed since editing startedFileChangedRO before making the first change toa read-only fileDiffUpdated after diffs have been updatedDirChangedPre before the working directory will changeDirChanged after the working directory has changedShellCmdPost after executinga shell commandShellFilterPost after filtering witha shell commandCmdUndefineda user commandis used butit isn't definedFuncUndefineda user functionis used butit isn't definedSpellFileMissingaspell fileis used butit can't be foundSourcePre before sourcinga VimscriptSourcePost after sourcinga VimscriptSourceCmd before sourcinga VimscriptCmd-eventVimResized after the Vimwindow size changedFocusGained Vim got input focusFocusLost Vim lost input focusCursorHold the user doesn't pressa key fora whileCursorHoldI the user doesn't pressa key fora while inInsert modeCursorMoved the cursor was moved inNormal modeCursorMovedC the cursor was moved in theCommand-lineCursorMovedI the cursor was moved inInsert modeWinNewPre before creatinga newwindowWinNew after creatinga newwindowTabNew after creatinga newtab pageWinClosed after closingawindowTabClosed after closingatab pageTabClosedPre before closingatab pageWinEnter after entering anotherwindowWinLeave before leavingawindowTabEnter after entering anothertab pageTabLeave before leavingatab pageCmdwinEnter after entering the command-linewindowCmdwinLeave before leaving the command-linewindowCmdlineChanged aftera change was made to the command-line textCmdlineEnter after the cursor moves to the command lineCmdlineLeave before the cursor leaves the command lineCmdlineLeavePre before preparing to leave the command lineInsertEnterstartingInsert modeInsertChange when typing<Insert> while inInsert orReplace modeInsertLeave when leavingInsert modeInsertLeavePre just before leavingInsert modeInsertCharPre whena character was typed inInsert mode, beforeinsertingitModeChanged afterchanging the modeTextChanged aftera change was made to the text inNormal modeTextChangedI aftera change was made to the text inInsert modewhenpopup menuis not visibleTextChangedP aftera change was made to the text inInsert modewhenpopup menu visibleTextChangedT aftera change was made to the text in Terminal modeTextYankPost after text has been yanked or deletedSafeState nothing pending, going to wait for the user to typeacharacterSafeStateAgain repeatedSafeStateColorSchemePre before loadinga color schemeColorScheme after loadinga color schemeRemoteReplya reply froma server Vim was receivedQuickFixCmdPre beforeaquickfix commandis runQuickFixCmdPost afteraquickfix commandis runSessionLoadPost after loadinga session fileSessionWritePost afterwriting the session file usingthe:mksession commandMenuPopup just before showing thepopup menuCompleteChanged afterInsert mode completion menu changedCompleteDonePre afterInsert mode completionis done, before clearinginfoCompleteDone afterInsert mode completionis done, after clearinginfoKeyInputPre just beforea keyis processedUser to be used in combination with ":doautocmd"SigUSR1 after the SIGUSR1 signal has been detectedWinScrolled afterscrolling or resizingawindowThe alphabeticallist ofautocommand events:autocmd-events-abcBufCreateBufAddBufAdd orBufCreateJust after creatinga new buffer whichisadded to the buffer list, or addinga bufferto the buffer list.Also used just aftera buffer in the bufferlist has been renamed.Not triggered for the initialbuffers createdduring startup.TheBufCreate eventis for historic reasons.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being created "<afile>".BufDeleteBufDeleteBeforedeletinga buffer from the buffer list.TheBufUnload may be called first (if thebuffer was loaded).Also used just beforea buffer in the bufferlistis renamed.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being deleted "<afile>" and "<abuf>".Don't change to another buffer,it will causeproblems.BufEnterBufEnterAfter enteringa buffer. Useful for settingoptions fora file type. Also executed whenstarting to edita buffer, after theBufReadPost autocommands.BufFilePostBufFilePostAfterchanging the name of the current bufferwith the ":file" or ":saveas" command.BufFilePreBufFilePreBeforechanging the name of the current bufferwith the ":file" or ":saveas" command.BufHiddenBufHiddenJust beforea buffer becomes hidden. That is,when there are no longerwindows that showthe buffer, but the bufferis not unloaded ordeleted. Not used for ":qa" or ":q" whenexiting Vim.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being unloaded "<afile>".BufLeaveBufLeaveBefore leaving to another buffer. Also whenleaving or closing the currentwindow and thenew currentwindowis not for the same buffer.Not used for ":qa" or ":q" whenexiting Vim.BufNewBufNewJust after creatinga new buffer. Also usedjust aftera buffer has been renamed. Whenthe bufferis added to the bufferlistBufAddwill be triggered too.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being created "<afile>".BufNewFileBufNewFileWhenstarting to edita file that doesn'texist. Can be used to read inaskeletonfile.BufReadBufReadPostBufRead orBufReadPostWhenstarting to edita new buffer, afterreading the file into the buffer, beforeexecuting the modelines. SeeBufWinEnterfor when you need todo something afterprocessing the modelines.Also triggered:- whenwriting an unnamed buffer ina way that the buffer getsa name- after successfully recoveringa file- for the filetypedetect group when executing ":filetype detect"Not triggered:- for the `:read file` command- when the file doesn't existBufReadCmdBufReadCmdBeforestarting to edita new buffer. Shouldread the file into the buffer.Cmd-eventBufReadPreE200E201BufReadPreWhenstarting to edita new buffer, beforereading the file into the buffer. Not usedif the file doesn't exist.BufUnloadBufUnloadBefore unloadinga buffer. Thisis when thetext in the bufferis going to be freed. Thismay be afteraBufWritePost and beforeaBufDelete. Also used for allbuffers that areloaded when Vimis going to exit.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being unloaded "<afile>".Don't change to another buffer or window,itwill cause problems!Whenexiting andv:dyingis 2 or more thiseventis not triggered.BufWinEnterBufWinEnterAftera bufferis displayed ina window. Thiscan be when the bufferis loaded (afterprocessing the modelines) or whena hiddenbufferis displayed inawindow (andis nolonger hidden).Does not happen for:split withoutarguments, since you keep editing the samebuffer, or ":split" witha file that's alreadyopen ina window, becauseit re-uses anexisting buffer. Butit does happen fora":split" with the name of the current buffer,sinceit reloads that buffer.Does not happen foraterminal window, becauseit starts inTerminal-Job mode andNormal modecommands won't work. UseTerminalOpen instead.BufWinLeaveBufWinLeaveBeforea bufferis removed froma window.Not when it's still visible in another window.Also triggered when exiting. It's triggeredbeforeBufUnload or BufHidden.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being unloaded "<afile>".Whenexiting andv:dyingis 2 or more thiseventis not triggered.BufWipeoutBufWipeoutBefore completelydeletinga buffer. TheBufUnload andBufDelete events may be calledfirst (if the buffer was loaded and was in thebuffer list). Also used just beforea bufferis renamed (also when it's not in the bufferlist).NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer being deleted "<afile>".Don't change to another buffer,it will causeproblems.BufWriteBufWritePreBufWrite orBufWritePreBeforewriting the whole buffer toa file.BufWriteCmdBufWriteCmdBeforewriting the whole buffer toa file.Shoulddo thewriting of the file and reset'modified' if successful, unless '+'is in'cpo' andwriting to another filecpo-+.The buffer contents should not be changed.When the command resets'modified' theundoinformationis adjusted tomark olderundostatesas'modified', like:write does. Usethe'[ and'] marks for the range of lines.Cmd-eventBufWritePostBufWritePostAfterwriting the whole buffer toa file(shouldundo the commands for BufWritePre).CmdUndefinedCmdUndefinedWhena user commandis used butit isn'tdefined. Useful for defininga command onlywhen it's used. Thepatternis matchedagainst the command name. Both<amatch> and<afile> are set to the name of the command.Thisis triggered even when inside anautocommand defined withoutautocmd-nested.NOTE: Autocompletion won't work until thecommandis defined. An alternativeis toalways define the user command and haveitinvoke an autoloaded function. Seeautoload.CmdlineChangedCmdlineChangedAftera change was made to the text in thecommand line. Be careful not to mess upthe command line,it may cause Vim to lock up.<afile>is set toa single character,indicating the type of command-line.cmdwin-charCmdlineEnterCmdlineEnterAfter moving the cursor to the command line,where the user can typea command or searchstring; including non-interactive use of ":"ina mapping, but not when using<Cmd>.Thepatternis matched against the characterrepresenting the type of command-line.cmdwin-char<afile>is set toa single character,indicating the type of command-line.CmdlineLeaveCmdlineLeaveBefore leaving the command line; includingnon-interactive use of ":" ina mapping, butnot when using<Cmd>.Also when abandoning the command line, aftertypingCTRL-C or<Esc>.When the commands result in an error thecommand lineis still executed.<afile>is set toa single character,indicating the type of command-line.cmdwin-charCmdlineLeavePreCmdlineLeavePreJust before leaving the command line, andbeforeCmdlineLeave. Useful for capturingcompletion info withcmdcomplete_info(),asthis informationis cleared beforeCmdlineLeaveis triggered. Triggered fornon-interactive use of ":" ina mapping, butnot when using<Cmd>. Also triggered whenabandoning the command line by typingCTRL-Cor<Esc>.<afile>is set toa singlecharacter indicating the command-line type.Seecmdwin-char for details.CmdwinEnterCmdwinEnterAfter entering the command-line window.Useful for settingoptions specifically forthis special type of window.<afile>is set toa single character,indicating the type of command-line.cmdwin-charCmdwinLeaveCmdwinLeaveBefore leaving the command-line window.Useful to clean up any global setting donewith CmdwinEnter.<afile>is set toa single character,indicating the type of command-line.cmdwin-charColorSchemeColorSchemeAfter loadinga color scheme.:colorschemeNot triggered if the color schemeis notfound.Thepatternis matched against thecolorscheme name.<afile> can be used for thename of the actual file where this option wasset, and<amatch> for the new colorschemename.ColorSchemePreColorSchemePreBefore loadinga color scheme.:colorschemeUseful to setup removing things added byacolor scheme, before another oneis loaded.CompleteChangedCompleteChangedAfter each time theInsert mode completionmenu changed. Not fired onpopup menu hide,useCompleteDonePre orCompleteDone forthat. Never triggered recursively.Sets thesev:event keys: completed_itemSeecomplete-items. heightnr of items visible widthscreen cells rowtop screen row colleftmost screen column sizetotal nr of items scrollbarTRUE if visibleItis not allowed to change the texttextlock.The size and position of thepopup are alsoavailable by callingpum_getpos().CompleteDonePreCompleteDonePreAfterInsert mode completionis done. Eitherwhen something was completed or abandoningcompletion.ins-completioncomplete_info() can be used, the infoiscleared after triggering CompleteDonePre.Thev:completed_item variable containsinformation about the completed item.CompleteDoneCompleteDoneAfterInsert mode completionis done. Eitherwhen something was completed or abandoningcompletion.ins-completioncomplete_info() cannot be used, the infoiscleared before triggering CompleteDone. UseCompleteDonePre if you need it.Thev:completed_item variable containsinformation about the completed item.Sets thesev:event keys: complete_wordTheword that wasselected, empty ifabandoned complete. complete_typecomplete_info_modeCursorHoldCursorHoldWhen the user doesn't pressa key for the timespecified with'updatetime'. Not triggereduntil the user has presseda key (i.e. doesn'tfire every'updatetime' ms if you leave Vim tomake some coffee. :) SeeCursorHold-examplefor previewing tags.This eventis only triggered inNormal mode.Itis not triggered when waiting fora commandargument to be typed, oramovement after anoperator.Whilerecording theCursorHold eventis nottriggered.q<CursorHold>Internally theautocommandis triggered by the<CursorHold> key. In anexpressionmappinggetchar() may see this character.Note: Interactive commands cannot be used forthis event. Thereis nohit-enter prompt,the screenis updated directly (when needed).Note: In the future there will probably beanother option to set the time.Hint: to force an update of the status linesuse::let &ro = &ro{only on Amiga, Unix,Win32 and allGUIversions}CursorHoldICursorHoldIJust like CursorHold, but inInsert mode.Not triggered when waiting for another key,e.g. afterCTRL-V, and not when inCTRL-X modeinsert_expand.CursorMovedCursorMovedAfter the cursor was moved inNormal orVisualmode. Also when the text of the cursor linehas been changed, e.g., with "x", "rx" or "p".Not always triggered when thereis typeahead,while executing commands inascript file,when anoperatoris pending or when moving toanotherwindow while remainingat the samecursor position.For an example seematch-parens.Note: This can not be skipped with:noautocmd.Careful: Thisis triggered very often, don'tdo anything that the user does not expect orthatis slow.CursorMovedCCursorMovedCAfter the cursor was moved in the commandline. Be careful not to mess up the commandline,it may cause Vim to lock up.<afile>is set toa single character,indicating the type of command-line.cmdwin-charCursorMovedICursorMovedIAfter the cursor was moved inInsert mode.Not triggered when thepopup menuis visible.Otherwise the sameas CursorMoved.DiffUpdatedDiffUpdatedAfter diffs have been updated. Depending onwhat kind ofdiffis being used (internal orexternal) this can be triggered on everychange or when doing:diffupdate.DirChangedPreDirChangedPreThe working directoryis going to be changed,as withDirChanged. Thepatternis likewithDirChanged. The new directory can befound in v:event.directory.DirChangedDirChangedThe working directory has changed in responseto the:cd or:tcd or:lcd commands, orasa result of the'autochdir' option.Thepattern can be:"window" to trigger on:lcd"tabpage" to trigger on:tcd"global" to trigger on:cd"auto" to trigger on'autochdir'."drop" to trigger on editinga file<afile>is set to the new directory name.EncodingChangedEncodingChangedFires off after the'encoding' option has beenchanged. Useful to set up fonts, for example.ExitPreExitPreWhen using:quit,:wq ina wayit makesVim exit, or using:qall, just afterQuitPre. Can be used to close anynon-essential window. Exiting may still becancelled if thereisa modified buffer thatisn't automatically saved, useVimLeavePrefor really exiting.FileAppendCmdFileAppendCmdBefore appending toa file. Shoulddo theappending to the file. Use the'[ and']marks for the range of lines.Cmd-eventFileAppendPostFileAppendPostAfter appending toa file.FileAppendPreFileAppendPreBefore appending toa file. Use the'[ and']marks for the range of lines.FileChangedROFileChangedROBefore making the first change toa read-onlyfile. Can be used to check-out the file froma sourcecontrol system. Not triggered whenthe change was caused by an autocommand.This eventis triggered when making the firstchange ina buffer or the first change after'readonly' was set, just before the changeisapplied to the text.WARNING: If theautocommand moves the cursorthe effect of the changeis undefined.E788Itis not allowed to change to another bufferhere. You canreload the buffer but not editanother one.E881If the number of lines changes saving forundomay fail and the change will be aborted.FileChangedShellFileChangedShellWhen Vim notices that the modification time ofa file has changed since editing started.Also when the file attributes of the filechange or when the size of the file changes.timestampMostly triggered after executinga shellcommand, but also witha:checktime commandor whengvim regains input focus.Thisautocommandis triggered for each changedfile. Itis not used when'autoread'is setand the buffer was not changed. IfaFileChangedShellautocommandis present thewarning message and promptis not given.Thev:fcs_reason variableis set to indicatewhat happened andv:fcs_choice can be usedto tell Vim what todo next.NOTE: When thisautocommandis executed, thecurrent buffer "%" may be different from thebuffer that was changed, whichis in "<afile>".NOTE: The commandsmust not change the currentbuffer, jump to another buffer or deleteabuffer.E246E811NOTE: This event never nests, to avoid anendless loop. This means that while executingcommands for theFileChangedShell event nootherFileChangedShell event will betriggered.FileChangedShellPostFileChangedShellPostAfter handlinga file that was changed outsideof Vim. Can be used to update the statusline.FileEncodingFileEncodingObsolete. It still works andis equivalenttoEncodingChanged.FileReadCmdFileReadCmdBefore readinga file witha ":read" command.Shoulddo the reading of the file.Cmd-eventFileReadPostFileReadPostAfter readinga file witha ":read" command.Note that Vim sets the'[ and'] marks to thefirst and last line of the read. This can beused to operate on the lines just read.FileReadPreFileReadPreBefore readinga file witha ":read" command.FileTypeFileTypeWhen the'filetype' option has been set. Thepatternis matched against the filetype.<afile> can be used for the name of the filewhere this option was set, and<amatch> forthe new value of'filetype'. Navigating toanotherwindow or bufferis not allowed.Seefiletypes.FileWriteCmdFileWriteCmdBeforewriting toa file, when notwriting thewhole buffer. Shoulddo thewriting to thefile. Should not change the buffer. Use the'[ and'] marks for the range of lines.Cmd-eventFileWritePostFileWritePostAfterwriting toa file, when notwriting thewhole buffer.FileWritePreFileWritePreBeforewriting toa file, when notwriting thewhole buffer. Use the'[ and'] marks for therange of lines.FilterReadPostFilterReadPostAfter readinga file fromafilter command.Vim checks thepattern against the name ofthe current bufferas with FilterReadPre.Not triggered when'shelltemp'is off.FilterReadPreE135FilterReadPreBefore readinga file fromafilter command.Vim checks thepattern against the name ofthe current buffer, not the name of thetemporary file thatis the output of thefilter command.Not triggered when'shelltemp'is off.FilterWritePostFilterWritePostAfterwritinga file forafilter command ormakingadiff with an externaldiff (seeDiffUpdated for internal diff).Vim checks thepattern against the name ofthe current bufferas with FilterWritePre.Not triggered when'shelltemp'is off.FilterWritePreFilterWritePreBeforewritinga file forafilter command ormakingadiff with an external diff.Vim checks thepattern against the name ofthe current buffer, not the name of thetemporary file thatis the output of thefilter command.Not triggered when'shelltemp'is off.FocusGainedFocusGainedWhen Vim got input focus. Only for theGUIversion anda few console versions where thiscan be detected.xterm-focus-eventFocusLostFocusLostWhen Vim lost input focus. Only for theGUIversion anda few console versions where thiscan be detected.xterm-focus-eventMay also happen whenadialog pops up.FuncUndefinedFuncUndefinedWhena user functionis used butit isn'tdefined. Useful for defininga function onlywhen it's used. Thepatternis matchedagainst the function name. Both<amatch> and<afile> are set to the name of the function.Thisis triggered even when inside anautocommand defined withoutautocmd-nested,but not triggered when compilingaVim9function.NOTE: Whenwriting Vim scriptsa betteralternativeis to use an autoloaded function.Seeautoload-functions.GUIEnterGUIEnterAfterstarting theGUI successfully, and afteropening the window. Itis triggered beforeVimEnter when using gvim. Can be used toposition thewindow froma.gvimrc file::autocmd GUIEnter * winpos 100 50GUIFailedGUIFailedAfterstarting theGUI failed. Vim maycontinue to run in the terminal, if possible(only onUnix and alikes, when connecting theX server fails). You may want to quit Vim::autocmd GUIFailed * qallInsertChangeInsertChangeWhen typing<Insert> while inInsert orReplace mode. Thev:insertmode variableindicates the new mode.Be careful not to move the cursor ordoanything else that the user does not expect.InsertCharPreInsertCharPreWhena characteris typed inInsert mode,beforeinserting the char.Thev:char variable indicates the char typedand can be changed during the event toinserta different character. Whenv:charis setto more than one character this textisinserted literally.Itis not allowed to change the texttextlock.The eventis not triggered when'paste'isset.{only with the +eval feature}InsertEnterInsertEnterJust beforestartingInsert mode. Also forReplace mode and VirtualReplace mode. Thev:insertmode variable indicates the mode.Be careful not todo anything else that theuser does not expect.The cursoris restored afterwards. If youdonot want that setv:char toa non-emptystring.InsertLeavePreInsertLeavePreJust before leavingInsert mode. Also whenusingCTRL-Oi_CTRL-O. Be careful not tochange mode or use:normal,it will likelycause trouble.InsertLeaveInsertLeaveJust after leavingInsert mode. Also whenusingCTRL-Oi_CTRL-O. But not fori_CTRL-C.KeyInputPreKeyInputPreJust beforea keyis processed after mappingshave been applied. Thepatternis matchedagainstastring that indicates the currentmode, whichis the sameas whatis returned bymode(1).Thev:char variable indicates the key typedand can be changed during the event to processa different key. Whenv:charis notasingle character ora special key, the firstcharacteris used.The following values ofv:event are set: typedThe keyis typed or not. typedcharThe (actual) typed key sincethe lastKeyInputPre call.Note: "typedchar" may be empty if successiveKeyInputPre autocmds are processed.Itis not allowed to change the texttextlock or the current mode.{only with the +eval feature}MenuPopupMenuPopupJust before showing thepopup menu (under theright mouse button). Useful for adjusting themenu for whatis under the cursor or mousepointer.Thepatternis matched against one or twocharacters representing the mode:nNormalvVisualoOperator-pendingiInsertcCommand linetlTerminalModeChangedModeChangedAfterchanging the mode. Thepatternismatched against'old_mode:new_mode', forexample match against*:c* to simulateCmdlineEnter.The following values ofv:event are set: old_modeThe mode beforeit changed. new_modeThe new modeas also returnedbymode() called withanon-zero argument.WhenModeChangedis triggered, old_mode willhave the value of new_mode when the event waslast triggered.This will be triggered on every minor modechange.Usage example to use relative line numberswhen enteringVisual mode::au ModeChanged [vV\x16]*:* let &l:rnu = mode() =~# '^[vV\x16]':au ModeChanged *:[vV\x16]* let &l:rnu = mode() =~# '^[vV\x16]':au WinEnter,WinLeave * let &l:rnu = mode() =~# '^[vV\x16]'OptionSetOptionSetAfter setting an option. Thepatternismatched against the long option name.<amatch> indicates what option has been set.v:option_type indicates whether it's globalor local scoped.v:option_command indicates what type ofset/let command was used (follow thetag tosee the table).v:option_new indicates the newly set value.v:option_oldlocal has the old local value.v:option_oldglobal has the old global value.v:option_old indicates the old option value.v:option_oldlocalis only set when:setor:setlocal oramodeline was used to setthe option. Similarlyv:option_oldglobalisonly set when:set or:setglobal was used.This does not set<abuf>, you could usebufnr().Note that when settingaglobal-localstringoption with:set, thenv:option_oldis theold global value. However, for all other kindsofoptions (localstring options,global-localnumber options, ...)itis the old localvalue.OptionSetis not triggered onstartup and forthe'key' option for obvious reasons.Usage example: Check for the existence of thedirectory in the'backupdir' and'undodir'options, create the directory ifit doesn'texist yet.Note: It'sa bad idea to reset an optionduring this autocommand, this may breakaplugin. You can always use:noa to preventtriggering this autocommand.When using:set in theautocommand the eventis not triggered again.QuickFixCmdPreQuickFixCmdPreBeforeaquickfix commandis run(:make,:lmake,:grep,:lgrep,:grepadd,:lgrepadd,:vimgrep,:lvimgrep,:vimgrepadd,:lvimgrepadd,:cscope,:cfile,:cgetfile,:caddfile,:lfile,:lgetfile,:laddfile,:helpgrep,:lhelpgrep,:cexpr,:cgetexpr,:caddexpr,:cbuffer,:cgetbuffer,:caddbuffer).Thepatternis matched against the commandbeing run. When:grepis used but'grepprg'is set to "internal"it still matches "grep".This command cannot be used to set the'makeprg' and'grepprg' variables.If this command causes an error, thequickfixcommandis not executed.QuickFixCmdPostQuickFixCmdPostLike QuickFixCmdPre, but afteraquickfixcommandis run, before jumping to the firstlocation. For:cfile and:lfile commandsitis run after the error fileis read andbefore moving to the first error.SeeQuickFixCmdPost-example.QuitPreQuitPreWhen using:quit,:wq or:qall, beforedeciding whetherit closes the currentwindowor quits Vim. For:wq the bufferis writtenbeforeQuitPreis triggered. Can be used toclose any non-essentialwindow if the currentwindowis the last ordinary window.Also seeExitPre.RemoteReplyRemoteReplyWhena reply froma Vim thatfunctionsasserver was receivedserver2client(). Thepatternis matched against the{serverid}.<amatch>is equal to the{serverid} from whichthe reply was sent, and<afile>is the actualreply string.Note that even if anautocommandis defined,the reply should be read withremote_read()to consume it.SafeStateSafeStateWhen nothingis pending, going to wait for theuser to typea character.This will not be triggered when:- anoperatoris pending-aregister was entered with "r- halfway executinga command- executingamapping- thereis typeahead-Insert mode completionis active- Command line completionis activeYou can usemode() to find out what stateVimis in. That may be:-Visual mode-Normal mode-Insert mode-Command-line modeDepending on what you want to do, you may alsocheck more withstate(), e.g. whether thescreen was scrolled for messages.SafeStateAgainSafeStateAgainLikeSafeState but after processing anymessages and invoking callbacks. This may betriggered often, don'tdo something that takestime.SessionLoadPostSessionLoadPostAfter loading the session file created usingthe:mksession command.SessionWritePostSessionWritePostAfterwritinga session file by callingthe:mksession command.ShellCmdPostShellCmdPostAfter executinga shell command with:!cmd,:shell,:make and:grep. Can be used tocheck for any changed files.ShellFilterPostShellFilterPostAfter executinga shell command with":{range}!cmd", ":w !cmd" or ":r !cmd".Can be used to check for any changed files.SourcePreSourcePreBefore sourcinga Vim script.:source<afile>is the name of the file being sourced.SourcePostSourcePostAfter sourcinga Vim script.:source<afile>is the name of the file being sourced.Not triggered when sourcing was interrupted.Also triggered afteraSourceCmdautocommandwas triggered.SourceCmdSourceCmdWhen sourcinga Vim script.:source<afile>is the name of the file being sourced.Theautocommandmust source this file.Cmd-eventSpellFileMissingSpellFileMissingWhen trying to loadaspell checking file andit can't be found. Thepatternis matchedagainst the language.<amatch>is thelanguage,'encoding' also matters. Seespell-SpellFileMissing.StdinReadPostStdinReadPostAfter reading from the stdin into the buffer,before executing the modelines. Only usedwhen the "-" argument was used when Vim wasstarted--.StdinReadPreStdinReadPreBefore reading from stdin into the buffer.Only used when the "-" argument was used whenVim was started--.SwapExistsSwapExistsDetected an existing swap file whenstartingto edita file. Only whenitis possible toselecta way to handle the situation, when Vimwould ask the user what to do.Thev:swapname variable holds the name ofthe swap file found,<afile> the file beingedited.v:swapcommand may containa commandto be executed in the opened file.The commands should set thev:swapchoicevariable toastring with one character totell Vim what should be done next:'o'open read-only'e'edit the file anyway'r'recover'd'delete the swap file'q'quit, don't edit the file'a'abort, like hittingCTRL-CWhen set to an emptystring the user will beasked,as if there was noSwapExists autocmd.E812Itis not allowed to change to another buffer,changea buffer name or change directoryhere.{only available with the +eval feature}SyntaxSyntaxWhen the'syntax' option has been set. Thepatternis matched against thesyntax name.<afile> can be used for the name of the filewhere this option was set, and<amatch> forthe new value of'syntax'.See:syn-on.TabClosedTabClosedAfter closingatab page.TabClosedPreTabClosedPreBefore closingatab page. Thewindow layoutis locked, thus opening and closing ofwindowsis prohibited.TabEnterTabEnterJust after enteringatab page.tab-pageAfter triggering theWinEnter and beforetriggering theBufEnter event.TabLeaveTabLeaveJust before leavingatab page.tab-pageAWinLeave event will have been triggeredfirst.TabNewTabNewWhenatab page was created.tab-pageAWinEnter event will have been triggeredfirst,TabEnter follows.TermChangedTermChangedAfter the value of'term' has changed. Usefulfor re-loading thesyntax file to update thecolors, fonts and other terminal-dependentsettings. Executed for all loaded buffers.TerminalOpenTerminalOpenJust afteraterminal buffer was created, with:terminal orterm_start(). This eventistriggered even if the bufferis createdwithouta window, with the ++hidden option.TerminalWinOpenTerminalWinOpenJust afteraterminal buffer was created, with:terminal orterm_start(). This eventistriggered only if the bufferis createdwitha window. Can be used to setwindowlocaloptions for theterminal window.TermResponseTermResponseAfter the response tot_RVis received fromthe terminal. The value ofv:termresponsecan be used todo things depending on theterminal version.Thisis used indefaults.vim to detectputtyterminal and seta dark background:au TermResponse *\ if v:termresponse == "\e[>0;136;0c"\ set bg=dark\ endifNote: that this event may be triggered halfwayexecuting another event, especially if fileI/O,a shell command or anything else thattakes timeis involved.TermResponseAllTermResponseAllAfter the response tot_RV,t_RC,t_RS,t_RB,t_RF, ort_u7 are received fromthe terminal. The value ofv:termresponse,v:termblinkresp,v:termstyleresp,v:termrbgresp,v:termrfgresp, andv:termu7resp, correspondingly, can be used.<amatch> will be set to any of: "version", "cursorblink", "cursorshape", "background", "foreground", "ambiguouswidth"Note that this event may be triggered halfwayexecuting another event, especially if file I/O,a shell command or anything else that takes timeis involved.TextChangedTextChangedAftera change was made to the text in thecurrent buffer inNormal mode. Thatis afterb:changedtick has changed (also when thathappened before theTextChangedautocommandwas defined).Not triggered when thereis typeahead or whenanoperatoris pending.Note: This can not be skipped with:noautocmd.Careful: Thisis triggered very often, don'tdo anything that the user does not expect orthatis slow.TextChangedITextChangedIAftera change was made to the text in thecurrent buffer inInsert mode.Not triggered when thepopup menuis visible.Otherwise the sameas TextChanged.TextChangedPTextChangedPAftera change was made to the text in thecurrent buffer inInsert mode, only when thepopup menuis visible. Otherwise the sameasTextChanged.TextChangedTTextChangedTAftera change was made to the text in thecurrent buffer in Terminal mode.Otherwise the sameas TextChanged.TextYankPostTextYankPostAfter text has been yanked or deleted in thecurrent buffer. The following values ofv:event can be used to determine the operationthat triggered this autocmd:inclusiveTRUE if the motionisinclusive else the motionisexclusive.operatorThe operation performed. regcontentsText that was stored in theregister,asalist of lines,like with:getreg(r, 1, 1) regnameName of theregister or emptystring for the unnamedregister, seeregisters. regtypeType of the register, seegetregtype(). visualTrue if the operationisperformed onaVisual area.Not triggered whenquote_is used nor whencalled recursively.Itis not allowed to change the buffer text,seetextlock.E1064Also triggered indirectly when Vim tries tobecome owner of theVisual selection becauseof setting "autoselect" for'guioptions' or'clipboard'.{only when compiled with the +eval feature}UserUserNever executed automatically. To be used forautocommands that are only executed with":doautocmd".Note that when `:doautocmdUser MyEvent`isused while there are no matching autocommands,you will get an error. If you don't wantthat, either check whether anautocommandisdefined usingexists('#User#MyEvent') ordefinea dummyautocommand yourself.Example: if exists('#User#MyEvent')doautocmd User MyEvent endifSigUSR1SigUSR1After the SIGUSR1 signal has been detected.Could be used if other ways of notifying Vimare not feasible. E.g. to check for theresult ofa build that takesa long time, orwhena motion sensoris triggered.{only on Unix}UserGettingBoredUserGettingBoredWhen the user presses the same key42 times.Just kidding! :-)VimEnterVimEnterAfter doing all thestartup stuff, includingloading.vimrc files, executing the "-c cmd"arguments, creating allwindows and loadingthebuffers in them.Just before this eventis triggered thev:vim_did_enter variableis set, so that youcan do: if v:vim_did_enter call s:init() else au VimEnter * call s:init() endifVimLeaveVimLeaveBeforeexiting Vim, just afterwriting the.viminfo file. Executed only once, likeVimLeavePre.To detect an abnormal exit usev:dying.Whenv:dyingis 2 or more this eventis nottriggered.To get the exit code usev:exiting.VimLeavePreVimLeavePreBeforeexiting Vim, just beforewriting the.viminfo file. Thisis executed only once,if thereisa match with the name of whathappens to be the current buffer when exiting.Mostly useful witha "*" pattern.:autocmd VimLeavePre * call CleanupStuff()To detect an abnormal exit usev:dying.Whenv:dyingis 2 or more this eventis nottriggered.To get the exit code usev:exiting.VimResizedVimResizedAfter the Vimwindow was resized, thus'lines'and/or'columns' changed. Not whenstartingup though.VimResumeVimResumeWhen the Vim instanceis resumed after beingsuspended andVimSuspend was triggered.Useful for triggering:checktime and ensurethebuffers content did not change while Vimwas suspended::autocmd VimResume * checktimeVimSuspendVimSuspendWhen the Vim instanceis suspended. Only whenCTRL-Z was typed inside Vim, or when the SIGTSTPsignal was sent to Vim, but not for SIGSTOP.WinClosedWinClosedWhen closinga window, just beforeitisremoved from thewindow layout. Thepatternis matched against thewindow-ID. Both<amatch> and<afile> are set to thewindow-ID. Non-recursive (event cannottrigger itself).WinEnterWinEnterAfter entering another window. Not done forthe first window, when Vim has just started.Useful for setting thewindow height.If thewindowis for another buffer, Vimexecutes theBufEnterautocommands after theWinEnter autocommands.Note: For split andtabpage commands theWinEnter eventis triggered after the splitortab command but before the fileis loaded.WinLeaveWinLeaveBefore leavinga window. If thewindow to beentered nextis fora different buffer, Vimexecutes theBufLeaveautocommands before theWinLeaveautocommands (but not for ":new").Not used for ":qa" or ":q" whenexiting Vim.WinNewPreWinNewPreBefore creatinga new window. Triggeredbefore commands that modifywindow layout bycreatinga split.Not done when creatingtab pages and for thefirst window,as thewindow structureis notinitialized yet and sois generally not safe.Itis not allowed to modifywindow layoutwhile executing commands for theWinNewPreevent.Most useful to store currentwindow layoutand compareit with the new layout after theWindow has been created.WinNewWinNewWhena newwindow was created. Not done forthe first window, when Vim has just started.BeforeaWinEnter event.WinScrolledWinScrolledAfter anywindow in the currenttab pagescrolled the text (horizontally or vertically)or changed width or height. Seewin-scrolled-resized.Note: This can not be skipped with:noautocmd, becauseit triggers afterprocessing normal commands when Vimis back inthe main loop. If you want to disable this,consider setting the'eventignore' optioninstead.Thepatternis matched against thewindow-IDof the firstwindow that scrolled or resized.Both<amatch> and<afile> are set to thewindow-ID.v:eventis set with information about sizeand scroll changes.WinScrolled-eventOnly starts triggering afterstartup finishedand the first screen redraw was done.Does not trigger when defining the firstWinScrolled orWinResized event, but maytrigger when adding more.Non-recursive: the event will not triggerwhile executing commands for theWinScrolledevent. However, if the command causesawindow to scroll or change size, then anotherWinScrolled event will be triggered later.WinResizedWinResizedAfterawindow in the currenttab page changedwidth or height.Seewin-scrolled-resized.v:eventis set with information about sizechanges.WinResized-eventSame behaviorasWinScrolled for thepattern, triggering and recursiveness.==============================================================================6. Patternsautocmd-patterns{aupat}The{aupat} argument of:autocmd can bea comma-separated list. This worksasif the command was given with eachpattern separately. Thus this command::autocmd BufRead *.txt,*.info set etIs equivalent to::autocmd BufRead *.txt set et:autocmd BufRead *.info set etThe filepattern{aupat}is tested fora match against the file name in one oftwo ways:1. When thereis no '/' in the pattern, Vim checks fora match against only the tail part of the file name (without its leading directory path).2. When thereisa '/' in the pattern, Vim checks fora match against both the short file name (as you typed it) and the full file name (after expandingit toa full path and resolving symbolic links).The specialpattern<buffer> or<buffer=N>is used for buffer-localautocommandsautocmd-buflocal. Thispatternis not matched against the nameofa buffer.Examples::autocmd BufRead *.txtset etSet the'et' option for all text files.:autocmd BufRead /vim/src/*.cset cindentSet the'cindent' option forC files in the /vim/src directory.:autocmd BufRead /tmp/*.cset ts=5If you havea link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", andyou start editing "/tmp/test.c", thisautocommand will match.Note: To match part ofa path, but not from the root directory, usea'*'asthe first character. Example::autocmd BufRead */doc/*.txtset tw=78Thisautocommand will for example be executed for "/tmp/doc/xx.txt" and"/usr/home/piet/doc/yy.txt". The number of directories does not matter here.The file name that thepatternis matched againstis after expandingwildcards. Thus if you issue this command::e $ROOTDIR/main.$EXTThe argumentis first expanded to:/usr/root/main.pyBefore it's matched with thepattern of the autocommand. Careful with thiswhen using events like FileReadCmd, the value of<amatch> may not be what youexpect.Environmentvariables can be used ina pattern::autocmd BufRead $VIMRUNTIME/doc/*.txt set expandtabAnd~ can be used for thehome directory (if$HOMEis defined)::autocmd BufWritePost ~/.vimrc so ~/.vimrc:autocmd BufRead ~archive/* set readonlyThe environment variableis expanded when theautocommandis defined, not whentheautocommandis executed. Thisis different from the command!file-patternThepatternis interpreted like mostly used in file names:*matches any sequence of characters; Unusual: includes pathseparators?matches any single character\?matchesa '?'.matchesa '.'~matchesa '~',separates patterns\,matchesa ','{ }like \( \) inapattern,inside{ }: like \| inapattern\}literal}\{literal{\\\{n,m\} like \{n,m} inapattern\special meaning like inapattern[ch]matches 'c' or 'h'[^ch] match any character but 'c' and 'h'Note that for all systems the '/' characteris used for path separator (evenfor MS-Windows). This was done because thebackslashis difficult to use inapattern and to make theautocommands portable across different systems.Itis possible to usepattern items, but they may not workas expected,because of the translation done for the above.autocmd-changesMatching with thepatternis done when an eventis triggered. Changing thebuffer name in one of the autocommands, or evendeleting the buffer, does notchange whichautocommands will be executed. Example:au BufEnter *.foo bdelau BufEnter *.foo set modifiedThis will delete the current buffer and then set'modified' in what has becomethe current buffer instead. Vim doesn't take into account that "*.foo"doesn't match with that buffer name. It matches "*.foo" with the name of thebufferat the moment the event was triggered.However, buffer-localautocommands will not be executed fora buffer that hasbeen wiped out with:bwipe. Afterdeleting the buffer with:bdel thebuffer actually still exists (it becomes unlisted), thus theautocommands arestill executed.==============================================================================7. Buffer-localautocommandsautocmd-buflocalautocmd-buffer-local<buffer=N><buffer=abuf>E680Buffer-localautocommands are attached toa specific buffer. They are usefulif the buffer does not havea name and when the name does not matcha specificpattern. Butit also means theymust be explicitly added to each buffer.Instead ofapattern buffer-localautocommands use one of these forms:<buffer>current buffer<buffer=99>buffer number 99<buffer=abuf>using<abuf> (only when executing autocommands)<abuf>Examples: :au CursorHold <buffer> echo 'hold' :au CursorHold <buffer=33> echo 'hold' :au BufNewFile * au CursorHold <buffer=abuf> echo 'hold'All the commands forautocommands also work with buffer-local autocommands,simply use the specialstring instead of the pattern. Examples: :au! * <buffer> " remove buffer-local autocommands for " current buffer :au! * <buffer=33> " remove buffer-local autocommands for " buffer #33 :bufdo :au! CursorHold <buffer> " remove autocmd for given event for all " buffers :au * <buffer> " list buffer-local autocommands for " current bufferNote that when anautocommandis defined for the current buffer,itis storedwith the buffer number. Thusit uses the form "<buffer=12>", where 12is thenumber of the current buffer. You will see this when listing autocommands,for example.To test for presence of buffer-localautocommands use theexists() functionas follows: :if exists("#CursorHold#<buffer=12>") | ... | endif :if exists("#CursorHold#<buffer>") | ... | endif " for current bufferWhena bufferis wiped out its buffer-localautocommands are also gone, ofcourse.Note that whendeletinga buffer, e.g., with ":bdel",itis onlyunlisted, theautocommands are still present. In order to see the removal ofbuffer-local autocommands: :set verbose=6Itis not possible to define buffer-localautocommands fora non-existentbuffer.==============================================================================8. Groupsautocmd-groupsAutocommands can beput together ina group. Thisis useful for removing orexecutinga group of autocommands. For example, all theautocommands forsyntax highlighting areput in the "highlight" group, to be able to execute":doautoall highlightBufRead" when theGUI starts.When no specific groupis selected, Vim uses the default group. The defaultgroup does not havea name. You cannot execute theautocommands from thedefault group separately; you can execute them only by executingautocommandsfor all groups.Normally, when executingautocommands automatically, Vim uses theautocommandsfor all groups. The group only matters when executingautocommands with":doautocmd" or ":doautoall", or when defining ordeleting autocommands.The group name can contain any characters except white space. The group name"end"is reserved (also in uppercase).The group nameiscase sensitive.Note that thisis different from the eventname!:aug:augroup:aug[roup]{name}Define the autocmd group name for thefollowing ":autocmd" commands. The name "end"or "END" selects the default group.To avoid confusion, the name should bedifferent from existing{event} names,as thismost likely will notdo what you intended.:augroup-deleteE367W19E936:aug[roup]!{name}Delete the autocmd group{name}. Don't usethis if thereis still anautocommand usingthis group! You will geta warning if doingit anyway. When the groupis the currentgroup you will get error E936.To enterautocommands fora specific group, use this method:1.Select the group with ":augroup{name}".2. Delete any oldautocommands with ":au!".3. Define the autocommands.4. Go back to the default group with "augroup END".Example::augroup uncompress: au!: au BufEnter *.gz%!gunzip:augroup ENDThis prevents having theautocommands defined twice (e.g., after sourcing the.vimrc file again).FileExplorerThereis one group thatis recognized by Vim: FileExplorer. If this groupexists Vim assumes that editinga directoryis possible and will triggeraplugin that lists the files in that directory. Thisis used by thenetrwplugin. This allows you to do:browse edit==============================================================================9. Executingautocommandsautocmd-executeVim can also execute Autocommands non-automatically. Thisis useful if youhave changed autocommands, or when Vim has executed the wrongautocommands(e.g., the filepattern match was wrong).Note that the'eventignore' option applies here too. Events listed in thisoption will not cause any commands to be executed.:do:doau:doaut:doautocmdE217:do[autocmd] [<nomodeline>][group]{event}[fname]Apply theautocommands matching[fname] (default:current file name) for{event} to the current buffer.You can use this when the current file name does notmatch the right pattern, afterchanging settings, orto executeautocommands fora certain event.It's possible to use this inside anautocommand too,so you can base theautocommands for one extension onanother extension. Example::au BufEnter *.cpp so ~/.vimrc_cpp:au BufEnter *.cpp doau BufEnter x.cBe careful to avoid endless loops. Seeautocmd-nested.When the[group] argumentis not given, Vim executestheautocommands for all groups. When the[group]argumentis included, Vim executes only the matchingautocommands for that group.Note: if you use anundefined group name, Vim gives you an error message.<nomodeline>After applying theautocommands the modelines areprocessed, so that their settings overrule thesettings from autocommands, like what happens wheneditinga file. Thisis skipped when the<nomodeline>argumentis present. You probably want to use<nomodeline> for events that are not used when loadinga buffer, suchasUser.Processing modelinesis also skipped when nomatchingautocommands were executed.:doautoa:doautoall:doautoa[ll] [<nomodeline>][group]{event}[fname]Like ":doautocmd", but apply theautocommands to eachloaded buffer. The current bufferis done last.Note that[fname]is used to select the autocommands,not thebuffers to which they are applied. Example:augroup mine autocmd! autocmd FileType * echo expand('<amatch>')augroup ENDdoautoall mine FileType Loaded-BufferSourcing this script, you'll seeas many"Loaded-Buffer" echoedas there are loaded buffers.Careful: Don't use this forautocommands that deleteabuffer, change to another buffer or change thecontents ofa buffer; the resultis unpredictable.This commandis intended forautocommands that setoptions, change highlighting, and things like that.==============================================================================10. Usingautocommandsautocmd-useFor WRITING FILES there are four possible sets of events. Vim uses only oneof these sets fora write command:BufWriteCmdBufWritePreBufWritePostwriting the whole bufferFilterWritePreFilterWritePostwriting tofilter temp fileFileAppendCmdFileAppendPreFileAppendPostappending toa fileFileWriteCmdFileWritePreFileWritePostany other file writeWhen thereisa matching "*Cmd" autocommand,itis assumedit willdo thewriting. No furtherwritingis done and the other events are not triggered.Cmd-eventNote that the *WritePost commands shouldundo any changes to the buffer thatwere caused by the *WritePre commands; otherwise,writing the file will havethe side effect ofchanging the buffer.Before executing the autocommands, the buffer from which the lines are to bewritten temporarily becomes the current buffer. Unless theautocommandschange the current buffer or delete the previously current buffer, thepreviously current bufferis made the current buffer again.The *WritePre and *AppendPreautocommandsmust not delete the buffer fromwhich the lines are to be written.The'[ and'] marks havea special position:- Before the *ReadPre event the'[markis set to the line just above where the new lines will be inserted.- Before the *ReadPost event the'[markis set to the first line that was just read, the']mark to the last line.- Before executing the *WriteCmd, *WritePre and *AppendPreautocommands the'[markis set to the first line that will be written, the']mark to the last line.Careful:'[ and'] change when using commands that change the buffer.In commands which expecta file name, you can use "<afile>" for the file namethatis being read:<afile> (you can also use "%" for the current filename). "<abuf>" can be used for the buffer number of the currently effectivebuffer. This also works forbuffers that don't havea name. Butit doesn'twork for files withouta buffer (e.g., with ":r file").gzip-exampleExamples for reading andwriting compressed files: :augroup gzip : autocmd! : autocmd BufReadPre,FileReadPre*.gz set bin : autocmd BufReadPost,FileReadPost*.gz '[,']!gunzip : autocmd BufReadPost,FileReadPost*.gz set nobin : autocmd BufReadPost,FileReadPost*.gz execute ":doautocmd BufReadPost " .. expand("%:r") : autocmd BufWritePost,FileWritePost*.gz !mv <afile> <afile>:r : autocmd BufWritePost,FileWritePost*.gz !gzip <afile>:r : autocmd FileAppendPre*.gz !gunzip <afile> : autocmd FileAppendPre*.gz !mv <afile>:r <afile> : autocmd FileAppendPost*.gz !mv <afile> <afile>:r : autocmd FileAppendPost*.gz !gzip <afile>:r :augroup ENDThe "gzip" groupis used to be able to delete any existingautocommands with":autocmd!", for when the fileis sourced twice.("<afile>:r"is the file name without the extension, see:_%:)The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,FileAppendPost andVimLeave eventsdo not set or reset the changed flag of thebuffer. When you decompress the buffer with theBufReadPost autocommands, youcan still exit with ":q". When you use ":undo" inBufWritePost toundo thechanges made byBufWritePre commands, you can stilldo ":q" (this also makes"ZZ" work). If youdo want the buffer to be markedas modified, set the'modified' option.To executeNormal mode commands from an autocommand, use the ":normal"command. Use with care! If theNormal mode commandis not finished, the userneeds to type characters (e.g., after ":normalm" you need to typeamarkname).If you want the buffer to be unmodified afterchanging it, reset the'modified' option. This makesit possible to exit the buffer with ":q"instead of ":q!".autocmd-nestedE218By default,autocommandsdo not nest. For example, if you use ":e" or ":w" inan autocommand, Vim does not execute theBufRead andBufWriteautocommands forthose commands. If youdo want this, use the "nested" flag for those commandsin which you want nesting. For example: :autocmd FileChangedShell *.c ++nested e!The nestingis limited to 10 levels to get out of recursive loops.It's possible to use the ":au" command in an autocommand. This can beaself-modifying command! This can be useful for anautocommand that shouldexecute only once.If you want to skipautocommands for one command, use the:noautocmd commandmodifier or the'eventignore' option.Note: When readinga file (with ":read file" or withafilter command) and thelast line in the file does not have an<EOL>, Vim remembers this. At the nextwrite (with ":write file" or withafilter command), if the same lineiswritten againas the last line ina file AND'binary'is set, Vim does notsupply an<EOL>. This makesafilter command on the just read lines write thesame fileas was read, and makesa write command on just filtered lines writethe same fileas was read from the filter. For example, another way to writea compressed file: :autocmd FileWritePre *.gz set bin|'[,']!gzip :autocmd FileWritePost *.gz undo|set nobinautocommand-patternYou can specify multiple patterns, separated by commas. Here are someexamples: :autocmd BufRead *set tw=79 nocin ic infercase fo=2croq :autocmd BufRead .letterset tw=72 fo=2tcrq :autocmd BufEnter .letterset dict=/usr/lib/dict/words :autocmd BufLeave .letterset dict= :autocmd BufRead,BufNewFile *.c,*.hset tw=0 cin noic :autocmd BufEnter *.c,*.habbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O :autocmd BufLeave *.c,*.hunabbr FORFor makefiles (makefile, Makefile, imakefile, makefile.unix, etc.): :autocmd BufEnter ?akefile*set include=^s\=include :autocmd BufLeave ?akefile*set include&To always start editingC filesat the first function: :autocmd BufRead *.c,*.h1;/^{Without the "1;" above, the search would start from wherever the file wasentered, rather than from the start of the file.skeletontemplateTo readaskeleton (template) file when openinga new file: :autocmd BufNewFile *.c0r ~/vim/skeleton.c :autocmd BufNewFile *.h0r ~/vim/skeleton.h :autocmd BufNewFile *.java0r ~/vim/skeleton.javaToinsert the current date and time ina *.html file whenwriting it: :autocmd BufWritePre,FileWritePre *.html ks|call LastMod()|'s :fun LastMod() : if line("$") > 20 : let l = 20 : else : let l = line("$") : endif : exe "1," .. l .. "g/Last modified: /s/Last modified: .*/Last modified: " .. : \ strftime("%Y %b %d") :endfunYou need to havea line "Last modified: <date time>" in the first 20 linesof the file for this to work. Vim replaces <date time> (and anything in thesame line after it) with the current date and time. Explanation:ksmark current position withmark 's'call LastMod() call the LastMod() function todo the work'sreturn the cursor to the old positionThe LastMod() function checks if the fileis shorter than 20 lines, and thenuses the ":g" command to find lines that contain "Last modified: ". For thoselines the ":s" commandis executed to replace the existing date with thecurrent one. The ":execute" commandis used to be able to use anexpressionfor the ":g" and ":s" commands. The dateis obtained with thestrftime()function. You can change its argument to get another date string.When entering:autocmd on the command-line, completion of events and commandnames may be done (with<Tab>,CTRL-D, etc.) where appropriate.Vim executes all matchingautocommands in the order that you specify them.Itis recommended that your firstautocommand be used for all files by using"*"as the file pattern. This means that you can define defaults you likehere for any settings, and if thereis another matchingautocommandit willoverride these. But if thereis no other matching autocommand, thenat leastyour default settings are recovered (if entering this file from another forwhichautocommands did match).Note that "*" will also match filesstartingwith ".", unlikeUnix shells.autocmd-searchpatAutocommandsdo not change the current search patterns. Vim saves the currentsearch patterns before executingautocommands then restores them after theautocommands finish. This means thatautocommandsdo not affect the stringshighlighted with the'hlsearch' option. Within autocommands, you can stilluse search patterns normally, e.g., with the "n" command.If you want anautocommand to set the search pattern, such thatitis usedafter theautocommand finishes, use the ":let@/=" command.The search-highlighting cannot be switched off with ":nohlsearch" in anautocommand. Use the 'h' flag in the'viminfo' option to disable search-highlighting whenstarting Vim.Cmd-eventWhen using one of the "*Cmd" events, the matchingautocommands are expected todo the file reading,writing or sourcing. This can be used when working witha special kind of file, for example ona remote system.CAREFUL: If you use these events ina wrong way,it may have the effect ofmakingit impossible to read or write the matching files! Make sure you testyourautocommands properly. Bestis to useapattern that will never matchanormal file name, for example "ftp://*".When definingaBufReadCmdit will be difficult for Vim to recovera crashedediting session. When recovering from the original file, Vim reads only thoseparts ofa file that are not found in the swap file. Since thatis notpossible witha BufReadCmd, use the:preserve command to make sure theoriginal file isn't needed for recovery. You might want todo this only whenyou expect the file to be modified.For file read and write commands thev:cmdarg variable holds the "++enc="and "++ff=" argument that are effective. These should be used for the commandthat reads/writes the file. Thev:cmdbang variableis one when "!" wasused, zero otherwise.See the $VIMRUNTIME/plugin/netrwPlugin.vim for examples.==============================================================================11. Disablingautocommandsautocmd-disableTo disableautocommands for some time use the'eventignore' option.Note thatthis may cause unexpected behavior, make sure you restore'eventignore'afterwards, usinga:try block with:finally.To disable autocmds indefinitely ina specificwindow use the'eventignorewin'option. This can only be used to ignorewindow and buffer related events.:noautocmd:noaTo disableautocommands for just one command use the ":noautocmd" commandmodifier. This will set'eventignore' to "all" for the duration of thefollowing command. Example::noautocmd w fname.gzThis will write the file without triggering theautocommands defined by thegzip plugin.Note that someautocommands are not triggered right away, but only later.This specifically applies toCursorMoved andTextChanged. vim:tw=78:ts=8:noet:ft=help:norl: