Autocmd
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
For a basic explanation, see section
40.3 in the user manual.
You can specify commands to be executed automatically when reading or writinga file, when entering or leaving a buffer or window, and when exiting Vim.For example, you can create an autocommand to set the
'cindent' option forfiles matching
*.c. You can also use autocommands to implement advancedfeatures, such as editing compressed files (see
gzip-example). The usualplace to put autocommands is in your vimrc file.
E203E204E143E855E937E952WARNING: Using autocommands is very powerful, and may lead to unexpected sideeffects. Be careful not to destroy your text.
It's a good idea to do some testing on an expendable copy of a file first. For example: If you use autocommands to decompress a file when starting to edit it, make sure that the autocommands for compressing when writing work correctly.
Be prepared for an error halfway through (e.g., disk full). Vim will mostly be able to undo the changes to the buffer, but you may have to clean up the changes to other files by hand (e.g., compress a file that has been decompressed).
If the BufRead* events allow you to edit a compressed file, the FileRead* events should do the same (this makes recovery possible in some rare cases). It's a good idea to use the same autocommands for the File* and Buf* events when possible.
:au:autocmd:au[tocmd] [group]
{event}{aupat} [++once] [++nested]
{cmd}Add
{cmd} to the list of commands that Vim willexecute automatically on
{event} for a file matching
{aupat}autocmd-pattern.
Note: A quote character is seen as argument to the:autocmd and won't start a comment.Nvim always adds
{cmd} after existing autocommands sothey execute in the order in which they were defined.See
autocmd-nested for [++nested].
autocmd-onceIf [++once] is supplied the command is executed once,then removed ("one shot").
The special pattern
<buffer> or <buffer=N> defines a buffer-local autocommand.See
autocmd-buflocal.
Note: The ":autocmd" command can only be followed by another command when the"|" appears where the pattern is expected. This works:
:augroup mine | au! BufRead | augroup END
But this sees "augroup" as part of the defined command:
:augroup mine | au! BufRead * | augroup END:augroup mine | au BufRead * set tw=70 | augroup END
Instead you can put the group name into the command:
:au! mine BufRead *:au mine BufRead * set tw=70
Or use
:execute:
:augroup mine | exe "au! BufRead *" | augroup END:augroup mine | exe "au BufRead * set tw=70" | augroup END
autocmd-expandNote that special characters (e.g., "%", "<cword>") in the ":autocmd"arguments are not expanded when the autocommand is defined. These will beexpanded when the Event is recognized, and the
{cmd} is executed. The onlyexception is that "<sfile>" (unlike "<script>") is expanded when the autocmdis defined. Example:
:au BufNewFile,BufRead *.html so <sfile>:h/html.vim
Here Vim expands
<sfile> to the name of the file containing this line.However,
<sfile> works differently in a function, in which case 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 the list of autocommands regardless of whether they arealready present. When your .vimrc file is sourced twice, the autocommandswill appear twice. To avoid this, define your autocommands in a group, sothat you can easily clear them:
augroup vimrc " Remove all vimrc autocommands autocmd! au BufNewFile,BufRead *.html so <sfile>:h/html.vimaugroup END
If you don't want to remove all autocommands, you can instead use a variableto ensure that Vim includes the autocommands only once:
:if !exists("autocommands_loaded"): let autocommands_loaded = 1: au ...:endifWhen the [group] argument is 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 define a new groupwith ":au group ..."; use ":augroup" for that.
While testing autocommands, you might find the
'verbose' option to be useful:
:set verbose=9
This setting makes Vim echo the autocommands as it executes them.
When defining an autocommand in a script, it will be able to call functionslocal to the script and use mappings local to the script. When the event istriggered and the command executed, it will run in the context of the scriptit was defined in. This matters if
<SID> is used in a command.
When executing the commands, the message from one command overwrites aprevious message. This is different from when executing the commandsmanually. Mostly the screen will not scroll up, thus there is no hit-enterprompt. When one command outputs two messages this can happen anyway.
:au[tocmd]! [group]
{event}{aupat} [++once] [++nested]
{cmd}Remove all autocommands associated with
{event} and
{aupat}, and add the command
{cmd}.See
autocmd-once for [++once].See
autocmd-nested for [++nested].
:au[tocmd]! [group]{event}{aupat}Remove all autocommands associated with{event} and{aupat}.
:au[tocmd]! [group] *{aupat}Remove all autocommands associated with{aupat} forall events.
:au[tocmd]! [group]
{event}Remove ALL autocommands for
{event}.
Warning: You should not do this without a group for
BufRead and other common events, it can breakplugins, syntax highlighting, etc.
:au[tocmd]! [group]Remove ALL autocommands.Note: a quote will be seen as argument to the :autocmdand won't start a comment.Warning: You should normally not do this without agroup, it breaks plugins, syntax highlighting, etc.
When the [group] argument is not given, Vim uses the current group (as definedwith ":augroup"); otherwise, Vim uses the group defined with [group].
:au[tocmd] [group]{event}{aupat}Show the autocommands associated with{event} and{aupat}.
:au[tocmd] [group] *{aupat}Show the autocommands associated with{aupat} for allevents.
:au[tocmd] [group]{event}Show all autocommands for{event}.
:au[tocmd] [group]Show all autocommands.
If you provide the [group] argument, Vim lists only the autocommands for[group]; otherwise, Vim lists the autocommands for ALL groups. Note that thisargument behavior differs from that for defining and removing autocommands.
In order to list buffer-local autocommands, use a pattern in the form
<buffer>or <buffer=N>. See
autocmd-buflocal.
:autocmd-verboseWhen
'verbose' is non-zero, listing an autocommand will also display where itwas last defined. Example:
:verbose autocmd BufEnterFileExplorer BufEnter * call s:LocalBrowse(expand("<amatch>")) Last set from /usr/share/vim/vim-7.0/plugin/NetrwPlugin.vim You can specify a comma-separated list of event names. No white space 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 edit a non-existent fileBufReadPreBufReadPoststarting to edit an existing fileFilterReadPreFilterReadPostread the temp file with filter outputFileReadPreFileReadPostany other file readVim uses only one of these four kinds when reading a file. The "Pre" and"Post" events are both triggered, before and after reading the file.
Note that the autocommands for the "*ReadPre" events and all the Filter eventsare not allowed to change the current buffer (you will get an error message ifthis happens). This is to prevent the file to be read into the wrong buffer.
Note that the
'modified' flag is reset AFTER executing the BufReadPostand BufNewFile autocommands. But when the
'modified' option was set by theautocommands, this doesn't happen.
You can use the
'eventignore' option to ignore a number of events or allevents.
events{event}Nvim recognizes the following events. Names are case-insensitive.
BufAddBufAddAfter adding a new buffer or existing unlistedbuffer to the buffer list (except duringstartup, see
VimEnter), or renaming a listedbuffer.Before
BufEnter.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>BufDeleteBufDeleteBefore deleting a buffer from the buffer list.The BufUnload may be called first (if thebuffer was loaded).Also used just before a buffer in the bufferlist is renamed.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>Do not change to another buffer.
BufEnterBufEnterAfter entering (visiting, switching-to) a newor existing buffer. Useful for settingfiletype options. Compare
BufNew whichdoes not trigger for existing buffers.After
BufAdd.After
BufReadPost.
BufFilePostBufFilePostAfter changing the name of the current bufferwith the ":file" or ":saveas" command.
BufFilePreBufFilePreBefore changing the name of the current bufferwith the ":file" or ":saveas" command.
BufHiddenBufHiddenBefore a buffer becomes hidden: when there areno longer windows that show the buffer, butthe buffer is not unloaded or deleted.
Not used for ":qa" or ":q" when exiting Vim.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>BufLeaveBufLeaveBefore leaving to another buffer. Also whenleaving or closing the current window and thenew current window is not for the same buffer.
Not used for ":qa" or ":q" when exiting Vim.
BufModifiedSetBufModifiedSetAfter the
'modified' value of a buffer hasbeen changed. Special-case of
OptionSet.
BufNewBufNewAfter creating a new buffer (except duringstartup, see
VimEnter) or renaming anexisting buffer. Unlike
BufEnter, visiting(switching to) an existing buffer will nottrigger this again.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>See also
BufAdd,
BufNewFile.
BufNewFileBufNewFileWhen starting to edit a file that doesn'texist. Can be used to read in a skeletonfile.
BufReadBufReadPostBufRead or BufReadPostWhen starting to edit a new buffer, afterreading the file into the buffer, beforeprocessing modelines. See
BufWinEnter to dosomething after processing modelines.Also triggered:
when writing an unnamed buffer in a way that the buffer gets a name
after successfully recovering a file
for the "filetypedetect" group when executing ":filetype detect"Not triggered:
for the:read file command
when the file doesn't exist
BufReadCmdBufReadCmdBefore starting to edit a new buffer. Shouldread the file into the buffer.
Cmd-eventBufReadPreE200E201BufReadPreWhen starting to edit a new buffer, beforereading the file into the buffer. Not usedif the file doesn't exist.
BufUnloadBufUnloadBefore unloading a buffer, when the text inthe buffer is going to be freed.After BufWritePost.Before BufDelete.Triggers for all loaded buffers when Vim isgoing to exit.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>E1546Do not switch buffers or windows!Not triggered when exiting and v:dying is 2 ormore.
BufWinEnterBufWinEnterAfter a buffer is displayed in a window. Thismay be when the buffer is loaded (afterprocessing modelines) or when a hidden bufferis displayed (and is no longer hidden).
Not triggered for
:split without arguments,since the buffer does not change, or :splitwith a file already open in a window.Triggered for ":split" with the name of thecurrent buffer, since it reloads that buffer.
BufWinLeaveBufWinLeaveBefore a buffer is removed from a window.Not when it's still visible in another window.Also triggered when exiting.Before BufUnload, BufHidden.
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>Not triggered when exiting and v:dying is 2 ormore.
BufWipeoutBufWipeoutBefore completely deleting a buffer. TheBufUnload and BufDelete events may be calledfirst (if the buffer was loaded and was in thebuffer list). Also used just before a bufferis renamed (also when it's not in the bufferlist).
NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".
<buffer=abuf>Do not change to another buffer.
BufWriteBufWritePreBufWrite or BufWritePreBefore writing the whole buffer to a file.
BufWriteCmdBufWriteCmdBefore writing the whole buffer to a file.Should do the writing of the file and reset
'modified' if successful, unless '+' is in
'cpo' and writing to another file
cpo-+.The buffer contents should not be changed.When the command resets
'modified' the undoinformation is adjusted to mark older undostates as
'modified', like
:write does. Usethe
'[ and
'] marks for the range of lines.
Cmd-eventBufWritePostBufWritePostAfter writing the whole buffer to a file(should undo the commands for BufWritePre).
ChanInfoChanInfoState of channel changed, for instance theclient of a RPC channel described itself.This is triggered even when inside anautocommand defined without
autocmd-nested.Sets these
v:event keys: infoas from
nvim_get_chan_info()ChanOpenChanOpenJust after a channel was opened.This is triggered even when inside anautocommand defined without
autocmd-nested.Sets these
v:event keys: infoas from
nvim_get_chan_info()CmdUndefinedCmdUndefinedWhen a user command is used but it isn'tdefined. Useful for defining a command onlywhen it's used. The pattern is matchedagainst the command name. Both
<amatch> and
<afile> expand to the command name.This is triggered even when inside anautocommand defined without
autocmd-nested.
NOTE: Autocompletion won't work until thecommand is defined. An alternative is toalways define the user command and have itinvoke an autoloaded function. See
autoload.
CmdlineChangedCmdlineChangedAfter EVERY change inside command line. Alsotriggered during mappings! Use
<Cmd> insteadof ":" in mappings, to avoid that.
<afile> expands to the
cmdline-char.
CmdlineEnterCmdlineEnterAfter entering the command-line (includingnon-interactive use of ":" in a mapping: use
<Cmd> instead to avoid this).The pattern is matched against
cmdline-char.
<afile> expands to the
cmdline-char.Sets these
v:event keys: cmdlevel cmdtype
CmdlineLeaveCmdlineLeaveBefore leaving the command-line (includingnon-interactive use of ":" in a mapping: use
<Cmd> instead to avoid this).
<afile> expands to the
cmdline-char.Sets the
v:char to the key that exited thecommand-line (e.g.
<CR>,
<CTRL-C>,
<Esc>).Sets these
v:event keys: abort (mutable) cmdlevel cmdtype
Note:abort can only be changed from falseto true: cannot execute an already abortedcmdline by changing it to false.
CmdlineLeavePreCmdlineLeavePreJust before leaving the command line, andbefore
CmdlineLeave. Useful for capturingcompletion info with
cmdcomplete_info(), asthis information is cleared before
CmdlineLeave is triggered. Triggered fornon-interactive use of ":" in a mapping, butnot when using
<Cmd>. Also triggered whenabandoning the command line by typing
CTRL-Cor
<Esc>.
<afile> is set to
cmdline-char.Sets
v:char as with
CmdlineLeave.
CmdwinEnterCmdwinEnterAfter entering the command-line window.Useful for setting options specifically forthis special type of window.
<afile> expands to a 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> expands to a single character,indicating the type of command-line.
cmdwin-charColorSchemeColorSchemeAfter loading a color scheme.
:colorschemeNot triggered if the color scheme is notfound.The pattern is 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 loading a color scheme.
:colorschemeUseful to setup removing things added by acolor scheme, before another one is loaded.
Sets these
v:event keys: completed_itemSee
complete-items. heightnr of items visible widthscreen cells rowtop screen row colleftmost screen column sizetotal nr of items scrollbarTRUE if visible
Non-recursive (event cannot trigger itself).Cannot change the text.
textlockThe size and position of the popup are alsoavailable by calling
pum_getpos().
Sets these
v:event keys: complete_wordThe word that wasselected, empty ifcompletion wasabandoned (discarded). complete_type
complete_info_mode reasonReason for completion beingdone. Can be one of:
"discard": completion was abandoned for other reason.
Note: Interactive commands cannot be used forthis event. There is no hit-enter prompt,the screen is 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
CursorHoldICursorHoldILike CursorHold, but in Insert mode. Nottriggered when waiting for another key, e.g.after
CTRL-V, and not in
CTRL-X mode
insert_expand.
CursorMovedCursorMovedAfter the cursor was moved in Normal or Visualmode or to another window. Also when the textof the cursor line has been changed, e.g. with"x", "rx" or "p".Not always triggered when there is typeahead,while executing commands in a script file, orwhen an operator is pending.For an example see
match-parens.
Note: Cannot be skipped with
:noautocmd.Careful: This is triggered very often, don'tdo anything that the user does not expect orthat is 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> expands to the
cmdline-char.
CursorMovedICursorMovedIAfter the cursor was moved in Insert mode.Not triggered when the popup menu is visible.Otherwise the same as CursorMoved.
DiffUpdatedDiffUpdatedAfter diffs have been updated. Depending onwhat kind of diff is being used (internal orexternal) this can be triggered on everychange or when doing
:diffupdate.
DirChangedDirChangedAfter the
current-directory was changed.The pattern can be:"window" to trigger on
:lcd"tabpage" to trigger on
:tcd"global" to trigger on
:cd"auto" to trigger on
'autochdir'.Sets these
v:event keys: cwd: current working directory scope: "global", "tabpage", "window" changed_window: v:true if we fired the event switching window (or tab)
<afile> is set to the new directory name.Non-recursive (event cannot trigger itself).
DirChangedPreDirChangedPreWhen the
current-directory is going to bechanged, as with
DirChanged.The pattern is like with
DirChanged.Sets these
v:event keys: directory: new working directory scope: "global", "tabpage", "window" changed_window: v:true if we fired the event switching window (or tab)
<afile> is set to the new directory name.Non-recursive (event cannot trigger itself).
ExitPreExitPreWhen using
:quit,
:wq in a way it makesVim exit, or using
:qall, just after
QuitPre. Can be used to close anynon-essential window. Exiting may still becancelled if there is a modified buffer thatisn't automatically saved, use
VimLeavePrefor really exiting.See also
QuitPre,
WinClosed.
FileAppendCmdFileAppendCmdBefore appending to a file. Should do theappending to the file. Use the '[ and ']marks for the range of lines.
Cmd-eventFileAppendPostFileAppendPostAfter appending to a file.
FileAppendPreFileAppendPreBefore appending to a file. Use the '[ and ']marks for the range of lines.
FileChangedROFileChangedROBefore making the first change to a read-onlyfile. Can be used to checkout the file froma source control system. Not triggered whenthe change was caused by an autocommand.Triggered when making the first change ina buffer or the first change after
'readonly'was set, just before the change is applied tothe text.
WARNING: If the autocommand moves the cursorthe effect of the change is undefined.
E788Cannot switch buffers. You can reload thebuffer but not edit another one.
E881If the number of lines changes saving for undomay 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.
timestamp Triggered for each changed file, after:
executing a shell command
Not used when
'autoread' is set and the bufferwas not changed. If a FileChangedShellautocommand exists the warning message andprompt is not given.
v:fcs_reason indicates what happened. Set
v:fcs_choice to control what happens next.
NOTE: Current buffer "%" is not the targetbuffer "<afile>" and "<abuf>".
<buffer=abuf>E246E811Cannot switch, jump to or delete buffers.Non-recursive (event cannot trigger itself).
FileChangedShellPostFileChangedShellPostAfter handling a file that was changed outsideof Vim. Can be used to update the statusline.
FileReadCmdFileReadCmdBefore reading a file with a ":read" command.Should do the reading of the file.
Cmd-eventFileReadPostFileReadPostAfter reading a file with a ":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 reading a file with a ":read" command.
FileTypeFileTypeWhen the
'filetype' option has been set. Thepattern is matched against the filetype.
<afile> is the name of the file where thisoption was set.
<amatch> is the new value of
'filetype'.Cannot switch windows or buffers.See
filetypes.
FileWriteCmdFileWriteCmdBefore writing to a file, when not writing thewhole buffer. Should do the writing to thefile. Should not change the buffer. Use the
'[ and
'] marks for the range of lines.
Cmd-eventFileWritePostFileWritePostAfter writing to a file, when not writing thewhole buffer.
FileWritePreFileWritePreBefore writing to a file, when not writing thewhole buffer. Use the
'[ and
'] marks for therange of lines.
FilterReadPostFilterReadPostAfter reading a file from a filter command.Vim checks the pattern against the name ofthe current buffer as with FilterReadPre.Not triggered when
'shelltemp' is off.
FilterReadPreE135FilterReadPreBefore reading a file from a filter command.Vim checks the pattern against the name ofthe current buffer, not the name of thetemporary file that is the output of thefilter command.Not triggered when
'shelltemp' is off.
FilterWritePostFilterWritePostAfter writing a file for a filter command ormaking a diff with an external diff (see
DiffUpdated for internal diff).Vim checks the pattern against the name ofthe current buffer as with FilterWritePre.Not triggered when
'shelltemp' is off.
FilterWritePreFilterWritePreBefore writing a file for a filter command ormaking a diff with an external diff.Vim checks the pattern against the name ofthe current buffer, not the name of thetemporary file that is the output of thefilter command.Not triggered when
'shelltemp' is off.
FocusGainedFocusGainedNvim got focus.
FocusLostFocusLostNvim lost focus. Also (potentially) whena GUI dialog pops up.
FuncUndefinedFuncUndefinedWhen a user function is used but it isn'tdefined. Useful for defining a function onlywhen it's used. The pattern is matchedagainst the function name. Both
<amatch> and
<afile> are set to the name of the function.This is triggered even when inside anautocommand defined without
autocmd-nested.
NOTE: When writing Vim scripts a betteralternative is to use an autoloaded function.See
autoload-functions.
UIEnterUIEnterAfter a UI connects via
nvim_ui_attach(), orafter builtin TUI is started, after
VimEnter.Sets these
v:event keys: chan:
channel-id of the UI
UILeaveUILeaveAfter a UI disconnects from Nvim, or afterbuiltin TUI is stopped, after
VimLeave.Sets these
v:event keys: chan:
channel-id of the UI
InsertChangeInsertChangeWhen typing
<Insert> while in Insert orReplace mode. The
v:insertmode variableindicates the new mode.Be careful not to move the cursor or doanything else that the user does not expect.
InsertCharPreInsertCharPreWhen a character is typed in Insert mode,before inserting the char.The
v:char variable indicates the char typedand can be changed during the event to inserta different character. When
v:char is setto more than one character this text isinserted literally.
Cannot change the text.
textlockInsertEnterInsertEnterJust before starting Insert mode. Also forReplace mode and Virtual Replace mode. The
v:insertmode variable indicates the mode.Be careful not to do anything else that theuser does not expect.The cursor is restored afterwards. If you donot want that set
v:char to a non-emptystring.
InsertLeavePreInsertLeavePreJust before leaving Insert mode. Also whenusing
CTRL-Oi_CTRL-O. Be careful not tochange mode or use
:normal, it will likelycause trouble.
InsertLeaveInsertLeaveJust after leaving Insert mode. Also whenusing
CTRL-Oi_CTRL-O. But not for
i_CTRL-C.LspAttachSee
LspAttachLspDetachSee
LspDetachLspNotifySee
LspNotifyLspProgressSee
LspProgressLspRequestSee
LspRequestLspTokenUpdateSee
LspTokenUpdateMenuPopupMenuPopupJust before showing the popup menu (under theright mouse button). Useful for adjusting themenu for what is under the cursor or mousepointer.The pattern is matched against one or twocharacters representing the mode:nNormalvVisualoOperator-pendingiInsertcCommand linetlTerminal
ModeChangedModeChangedAfter changing the mode. The pattern ismatched against
'old_mode:new_mode', forexample match against
*:c* to simulate
CmdlineEnter.The following values of
v:event are set: old_modeThe mode before it changed. new_modeThe new mode as also returnedby
mode() called with anon-zero argument.When ModeChanged is 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 entering visual 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]'
Progress
ProgressAfter a progress message is created or updated via
nvim_echo. The pattern is matched againsttitle of the message. The
event-data contains:id: id of the messagetext: text of the messagetitle: title of the progress messagestatus: status of the progress messagepercent: how much progress has been made for this progress itemUsage example:
vim.api.nvim_create_autocmd('Progress', { pattern={"term"}, callback = function(ev) print(string.format('event fired: %s', vim.inspect(ev))) end})local id = vim.api.nvim_echo({{'searching...'}}, true, {kind='progress', status='running', percent=10, title="term"})vim.api.nvim_echo({{'searching'}}, true, {id = id, kind='progress', status='running', percent=50, title="term"})vim.api.nvim_echo({{'done'}}, true, {id = id, kind='progress', status='success', percent=100, title="term"})Note that when setting a
global-local optionwith
:set, then
v:option_old is the oldglobal value. However, for all options thatare not global-local it is the old localvalue.
Usage example: Check for the existence of thedirectory in the
'backupdir' and
'undodir'options, create the directory if it doesn'texist yet.
Note: Do not reset the same option during thisautocommand, that may break plugins. You canalways use
:noautocmd to prevent triggeringOptionSet.
Non-recursive:
:set in the autocommand doesnot trigger OptionSet again.
Not triggered on startup.
QuickFixCmdPreQuickFixCmdPreBefore a quickfix command is run (
:make,
:lmake,
:grep,
:lgrep,
:grepadd,
:lgrepadd,
:vimgrep,
:lvimgrep,
:vimgrepadd,
:lvimgrepadd,
:cfile,
:cgetfile,
:caddfile,
:lfile,
:lgetfile,
:laddfile,
:helpgrep,
:lhelpgrep,
:cexpr,
:cgetexpr,
:caddexpr,
:cbuffer,
:cgetbuffer,
:caddbuffer).The pattern is matched against the commandbeing run. When
:grep is 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, the quickfixcommand is not executed.
QuickFixCmdPostQuickFixCmdPostLike QuickFixCmdPre, but after a quickfixcommand is run, before jumping to the firstlocation. For
:cfile and
:lfile commandsit is run after the error file is read andbefore moving to the first error.See
QuickFixCmdPost-example.
QuitPreQuitPreWhen using
:quit,
:wq or
:qall, beforedeciding whether it closes the current windowor quits Vim. For
:wq the buffer is writtenbefore QuitPre is triggered. Can be used toclose any non-essential window if the currentwindow is the last ordinary window.See also
ExitPre,
WinClosed.
RemoteReplyRemoteReplyWhen a reply from a Vim that functions asserver was received server2client(). Thepattern is 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 an autocommand is defined,the reply should be read with remote_read()to consume it.
SearchWrappedSearchWrappedAfter making a search with
n or
N if thesearch wraps around the document back tothe start/finish respectively.
RecordingEnterRecordingEnterWhen a macro starts recording.The pattern is the current file name, and
reg_recording() is the current register thatis used.
RecordingLeaveRecordingLeaveWhen a macro stops recording.The pattern is the current file name, and
reg_recording() is the recordedregister.
reg_recorded() is only updated after thisevent.Sets these
v:event keys: regcontents regname
SafeStateSafeStateWhen nothing is pending, going to wait for theuser to type a character.This will not be triggered when:
an operator is pending
a register was entered with "r
halfway executing a command
executing a mapping
there is typeahead
Insert mode completion is active
Command line completion is activeYou can usemode() to find out what stateVim is 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.
SessionLoadPostSessionLoadPostAfter loading the session file created usingthe
:mksession command.
SessionWritePostSessionWritePostAfter writing a session file by callingthe
:mksession command.
ShellCmdPostShellCmdPostAfter executing a shell command with
:!cmd,
:make and
:grep. Can be used to check forany changed files.For non-blocking shell commands, see
job-control.
SignalSignalAfter Nvim receives a signal. The pattern ismatched against the signal name. Only"SIGUSR1" and "SIGWINCH" are supported.This is triggered even when inside anautocommand defined without
autocmd-nested.Example:
autocmd Signal SIGUSR1 call some#func()
ShellFilterPostShellFilterPostAfter executing a shell command with":{range}!cmd", ":w !cmd" or ":r !cmd".Can be used to check for any changed files.
SourcePreSourcePreBefore sourcing a Vimscript/Lua file.
:source<afile> is the name of the file being sourced.
SourcePostSourcePostAfter sourcing a Vimscript/Lua file.
:source<afile> is the name of the file being sourced.Not triggered when sourcing was interrupted.Also triggered after a SourceCmd autocommandwas triggered.
SourceCmdSourceCmdWhen sourcing a Vimscript/Lua file.
:source<afile> is the name of the file being sourced.The autocommand must source that file.
Cmd-eventSpellFileMissingSpellFileMissingWhen trying to load a spell checking file andit can't be found. The pattern is matchedagainst the language.
<amatch> is thelanguage,
'encoding' also matters. See
spell-SpellFileMissing.
StdinReadPostStdinReadPostDuring startup, after reading from stdin intothe buffer, before executing modelines.
--StdinReadPreStdinReadPreDuring startup, before reading from stdin intothe buffer.
--SwapExistsSwapExistsDetected an existing swap file when startingto edit a file. Only when it is possible toselect a way to handle the situation, when Vimwould ask the user what to do.The
v:swapname variable holds the name ofthe swap file found,
<afile> the file beingedited.
v:swapcommand may contain a commandto be executed in the opened file.The commands should set the
v:swapchoicevariable to a string 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 hitting
CTRL-CWhen set to an empty string the user will beasked, as if there was no SwapExists autocmd.
E812Cannot change to another buffer, changethe buffer name or change directory.
SyntaxSyntaxWhen the
'syntax' option has been set. Thepattern is matched against the syntax name.
<afile> expands to the name of the file wherethis option was set.
<amatch> expands to thenew value of
'syntax'.See
:syn-on.
TabEnterTabEnterJust after entering a tab page.
tab-pageAfter WinEnter.Before BufEnter.
TabLeaveTabLeaveJust before leaving a tab page.
tab-pageAfter WinLeave.
TabNewTabNewWhen creating a new tab page.
tab-pageAfter WinEnter.Before TabEnter.
TabNewEnteredTabNewEnteredAfter entering a new tab page.
tab-pageAfter BufEnter.
TabClosedTabClosedAfter closing a tab page.
<afile> expands tothe tab page number.
TermOpenTermOpenWhen a
terminal job is starting. Can beused to configure the terminal buffer.
TermEnterTermEnterAfter entering
Terminal-mode.After TermOpen.
TermLeaveTermLeaveAfter leaving
Terminal-mode.After TermClose.
TermCloseTermCloseWhen a
terminal job ends.Sets these
v:event keys: status
TermRequestTermRequestWhen a
:terminal child process emits an OSC,DCS, or APC sequence. Sets
v:termrequest. The
event-data is a table with the followingfields:
sequence: the received sequence
cursor: (1,0)-indexed, buffer-relative position of the cursor when the sequence was received (line number may be <= 0 if the position is no longer in the buffer)
This is triggered even when inside anautocommand defined without
autocmd-nested.
sequence: the received sequence
This is triggered even when inside anautocommand defined without
autocmd-nested.
May be triggered during another event (fileI/O, a shell command, or anything else thattakes time).
Example:
-- Query the terminal palette for the RGB value of color 1-- (red) using OSC 4vim.api.nvim_create_autocmd('TermResponse', { once = true, callback = function(args) local resp = args.data.sequence local r, g, b = resp:match("\027%]4;1;rgb:(%w+)/(%w+)/(%w+)") end,})vim.api.nvim_ui_send("\027]4;1;?\027\\")
TextChangedTextChangedAfter a change was made to the text in thecurrent buffer in Normal mode. That is after
b:changedtick has changed (also when thathappened before the TextChanged autocommandwas defined).Not triggered when there is typeahead or whenan operator is pending.
Note: Cannot be skipped with
:noautocmd.Careful: This is triggered very often, don'tdo anything that the user does not expect orthat is slow.
TextChangedITextChangedIAfter a change was made to the text in thecurrent buffer in Insert mode.Not triggered when the popup menu is visible.Otherwise the same as TextChanged.
TextChangedPTextChangedPAfter a change was made to the text in thecurrent buffer in Insert mode, only when thepopup menu is visible. Otherwise the same asTextChanged.
TextChangedTTextChangedTAfter a change was made to the text in thecurrent buffer in
Terminal-mode. Otherwisethe same as TextChanged.
TextYankPostTextYankPostJust after a
yank or
deleting command, but notif the black hole register
quote_ is used norfor
setreg(). Pattern must be "*".Sets these
v:event keys: inclusive operator regcontents regname regtype visualThe
inclusive flag combined with the
'[and
'] marks can be used to calculate theprecise region of the operation.
Non-recursive (event cannot trigger itself).Cannot change the text.
textlockUserUserNot executed automatically. Use
:doautocmdto trigger this, typically for "custom events"in a plugin. Example:
:autocmd User MyPlugin echom 'got MyPlugin event':doautocmd User MyPlugin
UserGettingBoredUserGettingBoredWhen the user presses the same key 42 times.Just kidding! :-)
VimEnterVimEnterAfter doing all the startup stuff, includingloading vimrc files, executing the "-c cmd"arguments, creating all windows and loadingthe buffers in them.Just before this event is triggered the
v:vim_did_enter variable is set, so that youcan do:
if v:vim_did_enter call s:init()else au VimEnter * call s:init()endif
VimLeaveVimLeaveBefore exiting Vim, just after writing the.shada file. Executed only once, likeVimLeavePre.Use
v:dying to detect an abnormal exit.Use
v:exiting to get the exit code.Not triggered if
v:dying is 2 or more.
VimLeavePreVimLeavePreBefore exiting Vim, just before writing the
shada file. Executed only once, if thepattern matches the current buffer on exit.Mostly useful with a "*" pattern.
:autocmd VimLeavePre * call CleanupStuff()
Use
v:dying to detect an abnormal exit.Use
v:exiting to get the exit code.Not triggered if
v:dying is 2 or more.
VimResizedVimResizedAfter the Vim window was resized, thus
'lines'and/or
'columns' changed. Not when startingup though.
VimResumeVimResumeAfter Nvim resumes from
suspend state.
VimSuspendVimSuspendBefore Nvim enters
suspend state.
WinClosedWinClosedWhen closing a window, just before it isremoved from the window layout. The patternis matched against the
window-ID. Both
<amatch> and
<afile> are set to the
window-ID.After WinLeave.Non-recursive (event cannot trigger itself).See also
ExitPre,
QuitPre.
WinEnterWinEnterAfter entering another window. Not done forthe first window, when Vim has just started.Useful for setting the window height.If the window is for another buffer, Vimexecutes the BufEnter autocommands after theWinEnter autocommands.
Note: For split and tabpage commands theWinEnter event is triggered after the splitor tab command but before the file is loaded.
WinLeaveWinLeaveBefore leaving a window. If the window to beentered next is for a different buffer, Vimexecutes the BufLeave autocommands before theWinLeave autocommands (but not for ":new").Not used for ":qa" or ":q" when exiting Vim.Before WinClosed.
WinNewWinNewWhen a new window was created. Not done forthe first window, when Vim has just started.Before WinEnter.
WinScrolledWinScrolledAfter any window in the current tab pagescrolled the text (horizontally or vertically)or changed width or height. See
win-scrolled-resized.
Note: This can not be skipped with
:noautocmd, because it triggers afterprocessing normal commands when Vim is back inthe main loop. If you want to disable this,consider setting the
'eventignore' optioninstead.
The pattern is matched against the
window-IDof the first window that scrolled or resized.Both
<amatch> and
<afile> are set to the
window-ID.
Only starts triggering after startup finishedand the first screen redraw was done.Does not trigger when defining the firstWinScrolled or WinResized event, but maytrigger when adding more.
Non-recursive: the event will not triggerwhile executing commands for the WinScrolledevent. However, if the command causes awindow to scroll or change size, then anotherWinScrolled event will be triggered later.
Same behavior as
WinScrolled for thepattern, triggering and recursiveness.
The
{aupat} argument of
:autocmd can be a comma-separated list. This works asif the command was given with each pattern separately. Thus this command:
:autocmd BufRead *.txt,*.info set et
Is equivalent to:
:autocmd BufRead *.txt set et:autocmd BufRead *.info set et
The file pattern
{aupat} is tested for a match against the file name in one oftwo ways:1. When there is no '/' in the pattern, Vim checks for a match against only the tail part of the file name (without its leading directory path).2. When there is a '/' in the pattern, Vim checks for a match against both the short file name (as you typed it) and the full file name (after expanding it to a full path and resolving symbolic links).
The special pattern
<buffer> or <buffer=N> is used for buffer-localautocommands
autocmd-buflocal. This pattern is not matched against the nameof a buffer.
Examples:
:autocmd BufRead *.txtset et
Set the
'et' option for all text files.
:autocmd BufRead /vim/src/*.cset cindent
Set the
'cindent' option for C files in the /vim/src directory.
:autocmd BufRead /tmp/*.cset ts=5
If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", andyou start editing "/tmp/test.c", this autocommand will match.
Note: To match part of a path, but not from the root directory, use a "*" asthe first character. Example:
:autocmd BufRead */doc/*.txtset tw=78
This autocommand 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 the pattern is matched against is after expandingwildcards. Thus if you issue this command:
:e $ROOTDIR/main.$EXT
The argument is first expanded to:
/usr/root/main.py
Before it's matched with the pattern of the autocommand. Careful with thiswhen using events like FileReadCmd, the value of
<amatch> may not be what youexpect.
Environment variables can be used in a pattern:
:autocmd BufRead $VIMRUNTIME/doc/*.txt set expandtab
And ~ can be used for the home directory (if $HOME is defined):
:autocmd BufWritePost ~/.config/nvim/init.vim so <afile>:autocmd BufRead ~archive/* set readonly
The environment variable is expanded when the autocommand is defined, not whenthe autocommand is executed. This is different from the command!
file-patternThe pattern is interpreted like mostly used in file names:*matches any sequence of characters; Unusual: includes pathseparators?matches any single character\?matches a '?'.matches a '.'~matches a '~',separates patterns\,matches a ','{ }like \( \) in a
pattern,inside { }: like \| in a
pattern\}literal }\{literal {\\\{n,m\} like \{n,m} in a
pattern\special meaning like in a
pattern[ch]matches 'c' or 'h'[^ch] match any character but 'c' and 'h'
Note that for all systems the '/' character is used for path separator (evenfor MS-Windows). This was done because the backslash is difficult to use in apattern and to make the autocommands portable across different systems. Toonly match a '/' on all platforms (e.g. in a non-file pattern), use "\/".
It is possible to use
pattern items, but they may not work as expected,because of the translation done for the above.
autocmd-changesMatching with the pattern is done when an event is triggered. Changing thebuffer name in one of the autocommands, or even deleting the buffer, does notchange which autocommands will be executed. Example:
au BufEnter *.foo bdelau BufEnter *.foo set modified
This 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 thebuffer at the moment the event was triggered.
However, buffer-local autocommands will not be executed for a buffer that hasbeen wiped out with
:bwipe. After deleting the buffer with
:bdel thebuffer actually still exists (it becomes unlisted), thus the autocommands arestill executed.
Buffer-local autocommands are attached to a specific buffer. They are usefulif the buffer does not have a name and when the name does not match a specificpattern. But it also means they must be explicitly added to each buffer.
Instead of a pattern buffer-local autocommands 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 for autocommands also work with buffer-local autocommands,simply use the special string 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 buffer
Note that when an autocommand is defined for the current buffer, it is storedwith the buffer number. Thus it uses the form "<buffer=12>", where 12 is thenumber of the current buffer. You will see this when listing autocommands,for example.
To test for presence of buffer-local autocommands use the
exists() functionas follows:
:if exists("#CursorHold#<buffer=12>") | ... | endif:if exists("#CursorHold#<buffer>") | ... | endif " for current bufferWhen a buffer is wiped out its buffer-local autocommands are also gone, ofcourse. Note that when deleting a buffer, e.g., with ":bdel", it is onlyunlisted, the autocommands are still present. In order to see the removal ofbuffer-local autocommands:
:set verbose=6
It is not possible to define buffer-local autocommands for a non-existentbuffer.
Autocommands can be put together in a group. This is useful for removing orexecuting a group of autocommands. For example, all the autocommands forsyntax highlighting are put in the "highlight" group, to be able to execute":doautoall highlight BufRead" when the GUI starts.
When no specific group is selected, Vim uses the default group. The defaultgroup does not have a name. You cannot execute the autocommands from thedefault group separately; you can execute them only by executing autocommandsfor all groups.
Normally, when executing autocommands automatically, Vim uses the autocommandsfor all groups. The group only matters when executing autocommands with":doautocmd" or ":doautoall", or when defining or deleting autocommands.
The group name can contain any characters except white space. The group name"end" is reserved (also in uppercase).
The group name is case sensitive. Note that this is 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 not do what you intended.
:augroup-deleteE367W19E936:aug[roup]!
{name}Delete the autocmd group
{name}. Don't usethis if there is still an autocommand usingthis group! You will get a warning if doingit anyway. When the group is the currentgroup you will get error E936.
To enter autocommands for a specific group, use this method:1. Select the group with ":augroup{name}".2. Delete any old autocommands 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 END
This prevents having the autocommands defined twice (e.g., after sourcing thevimrc file again).
FileExplorerThere is one group that is recognized by Vim: FileExplorer. If this groupexists Vim assumes that editing a directory is possible and will trigger aplugin that lists the files in that directory. This is used by directorybrowser plugins. This allows you to do:
browse edit
Vim can also execute Autocommands non-automatically. This is useful if youhave changed autocommands, or when Vim has executed the wrong autocommands(e.g., the file pattern 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 the autocommands 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, after changing settings, orto execute autocommands for a certain event.It's possible to use this inside an autocommand too,so you can base the autocommands for one extension onanother extension. Example:
:au BufEnter *.cpp so ~/.config/nvim/init_cpp.vim:au BufEnter *.cpp doau BufEnter x.c
When the [group] argument is not given, Vim executesthe autocommands for all groups. When the [group]argument is included, Vim executes only the matchingautocommands for that group. Undefined group is anerror.
<nomodeline>After applying the autocommands the modelines areprocessed, so that their settings overrule thesettings from autocommands when editing a file. Thisis skipped if
<nomodeline> is specified. You probablywant to use
<nomodeline> for events not used whenloading a buffer, such as
User.Modelines are also skipped when no matchingautocommands were executed.
:doautoa:doautoall:doautoa[ll] [
<nomodeline>] [group]
{event} [fname]Like ":doautocmd", but apply the autocommands to eachloaded buffer. The current buffer is done last.
Note that [fname] is used to select the autocommands,not the buffers to which they are applied. Example:
augroup mine autocmd! autocmd FileType * echo expand('<amatch>')augroup ENDdoautoall mine FileType Loaded-BufferSourcing this script, you'll see as many"Loaded-Buffer" echoed as there are loaded buffers.
Careful: Don't use this for autocommands that delete abuffer, change to another buffer or change thecontents of a buffer; the result is unpredictable.This command is intended for autocommands that setoptions, change highlighting, and things like that.
For WRITING FILES there are four possible sets of events. Vim uses only oneof these sets for a write command:
BufWriteCmdBufWritePreBufWritePostwriting the whole bufferFilterWritePreFilterWritePostwriting to filter temp fileFileAppendCmdFileAppendPreFileAppendPostappending to a fileFileWriteCmdFileWritePreFileWritePostany other file write
When there is a matching "*Cmd" autocommand, it is assumed it will do thewriting. No further writing is done and the other events are not triggered.
Cmd-eventNote that the "*WritePost" commands should undo any changes to the buffer thatwere caused by the "*WritePre" commands; otherwise, writing the file will havethe side effect of changing the buffer.
Before executing the autocommands, the buffer from which the lines are to bewritten temporarily becomes the current buffer. Unless the autocommandschange the current buffer or delete the previously current buffer, thepreviously current buffer is made the current buffer again.
The "*WritePre" and "*AppendPre" autocommands must not delete the buffer fromwhich the lines are to be written.
The '[ and '] marks have a special position:
Before the "*ReadPre" event the '[ mark is set to the line just above where the new lines will be inserted.
Before the "*ReadPost" event the '[ mark is set to the first line that was just read, the '] mark to the last line.
Before executing the "*WriteCmd", "*WritePre" and "*AppendPre" autocommands the '[ mark is 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 expect a file name, you can use "<afile>" for the file namethat is 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 for buffers that don't have a name. But it doesn'twork for files without a buffer (e.g., with ":r file").
gzip-exampleExamples for reading and writing 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" group is used to be able to delete any existing autocommands with":autocmd!", for when the file is sourced twice.
("<afile>:r" is the file name without the extension, see
:_%:)
The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,FileAppendPost and VimLeave events do not set or reset the changed flag of thebuffer. When you decompress the buffer with the BufReadPost autocommands, youcan still exit with ":q". When you use ":undo" in BufWritePost to undo thechanges made by BufWritePre commands, you can still do ":q" (this also makes"ZZ" work). If you do want the buffer to be marked as modified, set the
'modified' option.
To execute Normal mode commands from an autocommand, use the ":normal"command. Use with care! If the Normal mode command is not finished, the userneeds to type characters (e.g., after ":normal m" you need to type a markname).
If you want the buffer to be unmodified after changing it, reset the
'modified' option. This makes it possible to exit the buffer with ":q"instead of ":q!".
autocmd-nestedE218By default, autocommands do not nest. For example, if you use ":e" or ":w" inan autocommand, Vim does not execute the BufRead and BufWrite autocommands forthose commands. If you do want this, use the "++nested" flag for thosecommands in which you want nesting. For example:
:autocmd FileChangedShell *.c ++nested e!
The nesting is limited to 10 levels to get out of recursive loops.
It's possible to use the ":au" command in an autocommand. This can be aself-modifying command! This can be useful for an autocommand that shouldexecute only once.
Note: When reading a file (with ":read file" or with a filter command) and thelast line in the file does not have an
<EOL>, Vim remembers this. At the nextwrite (with ":write file" or with a filter command), if the same line iswritten again as the last line in a file AND
'binary' is set, Vim does notsupply an
<EOL>. This makes a filter command on the just read lines write thesame file as was read, and makes a write command on just filtered lines writethe same file as was read from the filter. For example, another way to writea compressed file:
:autocmd FileWritePre *.gz set bin|'[,']!gzip:autocmd FileWritePost *.gz undo|set nobin
autocommand-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 editing C files at 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 read a skeleton (template) file when opening a new file:
:autocmd BufNewFile *.c0r ~/vim/skeleton.c:autocmd BufNewFile *.h0r ~/vim/skeleton.h:autocmd BufNewFile *.java0r ~/vim/skeleton.java
To insert the current date and time in a "*.html" file when writing 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 have a 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 with mark 's'call LastMod() call the LastMod() function to do the work'sreturn the cursor to the old positionThe LastMod() function checks if the file is shorter than 20 lines, and thenuses the ":g" command to find lines that contain "Last modified: ". For thoselines the ":s" command is executed to replace the existing date with thecurrent one. The ":execute" command is used to be able to use an expressionfor the ":g" and ":s" commands. The date is obtained with the strftime()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 matching autocommands in the order that you specify them.It is recommended that your first autocommand 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 there is another matching autocommand it willoverride these. But if there is no other matching autocommand, then at leastyour default settings are recovered (if entering this file from another forwhich autocommands did match). Note that "*" will also match files startingwith ".", unlike Unix shells.
autocmd-searchpatAutocommands do not change the current search patterns. Vim saves the currentsearch patterns before executing autocommands then restores them after theautocommands finish. This means that autocommands do 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 an autocommand to set the search pattern, such that it is usedafter the autocommand finishes, use the ":let @/ =" command.The search-highlighting cannot be switched off with ":nohlsearch" in anautocommand. Use the 'h' flag in the
'shada' option to disable search-highlighting when starting Vim.
Cmd-eventWhen using one of the "*Cmd" events, the matching autocommands are expected todo the file reading, writing or sourcing. This can be used when working witha special kind of file, for example on a remote system.CAREFUL: If you use these events in a wrong way, it may have the effect ofmaking it impossible to read or write the matching files! Make sure you testyour autocommands properly. Best is to use a pattern that will never match anormal file name, for example "ftp://*".
When defining a BufReadCmd it will be difficult for Vim to recover a crashedediting session. When recovering from the original file, Vim reads only thoseparts of a file that are not found in the swap file. Since that is notpossible with a BufReadCmd, use the
:preserve command to make sure theoriginal file isn't needed for recovery. You might want to do this only whenyou expect the file to be modified.
For file read and write commands the
v:cmdarg variable holds the "++enc="and "++ff=" argument that are effective. These should be used for the commandthat reads/writes the file. The
v:cmdbang variable is one when "!" wasused, zero otherwise.
See the $VIMRUNTIME/pack/dist/opt/netrw/plugin/netrwPlugin.vim for examples.
To disable autocmds indefinitely in a specific window use the
'eventignorewin'option. This can only be used to ignore window and buffer related events.
:noautocmd:noaTo disable autocommands for just one command use the ":noautocmd" commandmodifier. This will set
'eventignore' to "all" for the duration of thefollowing command. Example:
:noautocmd w fname.gz
This will write the file without triggering the autocommands defined by thegzip plugin.
Note that some autocommands are not triggered right away, but only later.This specifically applies to
CursorMoved and
TextChanged.