Movatterモバイル変換


[0]ホーム

URL:


Autocmd

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Automatic commandsautocommand
For a basic explanation, see section40.3 in the user manual.

1. Introductionautocmd-intro

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 (seegzip-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.

2. Defining autocommandsautocmd-define

: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.Seeautocmd-nested for [++nested].autocmd-once
If [++once] is supplied the command is executed once,then removed ("one shot").
The special pattern<buffer> or <buffer=N> defines a buffer-local autocommand.Seeautocmd-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-expand
Note 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 ...:endif
When 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.

3. Removing autocommandsautocmd!autocmd-remove

:au[tocmd]! [group]{event}{aupat} [++once] [++nested]{cmd}Remove all autocommands associated with{event} and{aupat}, and add the command{cmd}.Seeautocmd-once for [++once].Seeautocmd-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 forBufRead 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].

4. Listing autocommandsautocmd-list

: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>. Seeautocmd-buflocal.
:autocmd-verbose
When'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
See:verbose-cmd for more information.

5. Eventsautocmd-eventsE215E216

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.
BufAdd
BufAddAfter adding a new buffer or existing unlistedbuffer to the buffer list (except duringstartup, seeVimEnter), or renaming a listedbuffer.BeforeBufEnter.NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".<buffer=abuf>BufDelete
BufDeleteBefore 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.BufEnter
BufEnterAfter entering (visiting, switching-to) a newor existing buffer. Useful for settingfiletype options. CompareBufNew whichdoes not trigger for existing buffers.AfterBufAdd.AfterBufReadPost.BufFilePost
BufFilePostAfter changing the name of the current bufferwith the ":file" or ":saveas" command.BufFilePre
BufFilePreBefore changing the name of the current bufferwith the ":file" or ":saveas" command.BufHidden
BufHiddenBefore 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>BufLeave
BufLeaveBefore 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.BufModifiedSet
BufModifiedSetAfter the'modified' value of a buffer hasbeen changed. Special-case ofOptionSet.BufNew
BufNewAfter creating a new buffer (except duringstartup, seeVimEnter) or renaming anexisting buffer. UnlikeBufEnter, visiting(switching to) an existing buffer will nottrigger this again.NOTE: Current buffer "%" is not the targetbuffer "<afile>", "<abuf>".<buffer=abuf>See alsoBufAdd,BufNewFile.BufNewFile
BufNewFileWhen 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. SeeBufWinEnter 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 existBufReadCmd
BufReadCmdBefore 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.BufUnload
BufUnloadBefore 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>E1546
Do not switch buffers or windows!Not triggered when exiting and v:dying is 2 ormore.BufWinEnter
BufWinEnterAfter 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.BufWinLeave
BufWinLeaveBefore 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.BufWipeout
BufWipeoutBefore 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.BufWriteCmd
BufWriteCmdBefore 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 filecpo-+.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-eventBufWritePost
BufWritePostAfter writing the whole buffer to a file(should undo the commands for BufWritePre).ChanInfo
ChanInfoState of channel changed, for instance theclient of a RPC channel described itself.This is triggered even when inside anautocommand defined withoutautocmd-nested.Sets thesev:event keys: infoas fromnvim_get_chan_info()ChanOpen
ChanOpenJust after a channel was opened.This is triggered even when inside anautocommand defined withoutautocmd-nested.Sets thesev:event keys: infoas fromnvim_get_chan_info()CmdUndefined
CmdUndefinedWhen 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 withoutautocmd-nested.NOTE: Autocompletion won't work until thecommand is defined. An alternative is toalways define the user command and have itinvoke an autoloaded function. Seeautoload.CmdlineChanged
CmdlineChangedAfter EVERY change inside command line. Alsotriggered during mappings! Use<Cmd> insteadof ":" in mappings, to avoid that.
<afile> expands to thecmdline-char.CmdlineEnter
CmdlineEnterAfter entering the command-line (includingnon-interactive use of ":" in a mapping: use<Cmd> instead to avoid this).The pattern is matched againstcmdline-char.<afile> expands to thecmdline-char.Sets thesev:event keys: cmdlevel cmdtypeCmdlineLeave
CmdlineLeaveBefore leaving the command-line (includingnon-interactive use of ":" in a mapping: use<Cmd> instead to avoid this).<afile> expands to thecmdline-char.Sets thev:char to the key that exited thecommand-line (e.g.<CR>,<CTRL-C>,<Esc>).Sets thesev:event keys: abort (mutable) cmdlevel cmdtypeNote:abort can only be changed from falseto true: cannot execute an already abortedcmdline by changing it to false.CmdlineLeavePre
CmdlineLeavePreJust before leaving the command line, andbeforeCmdlineLeave. Useful for capturingcompletion info withcmdcomplete_info(), asthis information is cleared beforeCmdlineLeave is triggered. Triggered fornon-interactive use of ":" in a mapping, butnot when using<Cmd>. Also triggered whenabandoning the command line by typingCTRL-Cor<Esc>.<afile> is set tocmdline-char.Setsv:char as withCmdlineLeave.CmdwinEnter
CmdwinEnterAfter 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-charCmdwinLeave
CmdwinLeaveBefore 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-charColorScheme
ColorSchemeAfter 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.
ColorSchemePre
ColorSchemePreBefore loading a color scheme.:colorschemeUseful to setup removing things added by acolor scheme, before another one is loaded.
CompleteChangedCompleteChanged
After each time the Insert mode completionmenu changed. Not fired on popup menu hide,useCompleteDonePre orCompleteDone forthat.
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 visible
Non-recursive (event cannot trigger itself).Cannot change the text.textlock
The size and position of the popup are alsoavailable by callingpum_getpos().
CompleteDonePre
CompleteDonePreAfter Insert mode completion is done. Eitherwhen something was completed or discarded.ins-completioncomplete_info() is valid during this event.v:completed_item gives the completed item.
CompleteDone
CompleteDoneAfter Insert mode completion is done. Eitherwhen something was completed or discarded.ins-completioncomplete_info() is cleared before this; useCompleteDonePre if you need it.v:completed_item gives the completed item,or empty dict if completion was discarded.
Sets thesev:event keys: complete_wordThe word that wasselected, empty ifcompletion wasabandoned (discarded). complete_typecomplete_info_mode reasonReason for completion beingdone. Can be one of:
"accept": completion was accepted bycomplete_CTRL-Y.
"cancel": completion was stopped bycomplete_CTRL-E.
"discard": completion was abandoned for other reason.
CursorHold
CursorHoldWhen there is no user input for'updatetime'duration, in Normal-mode. Not triggered whilewaiting for a command argument or movementafter an operator, nor whilerecordinga macro. SeeCursorHold-example.
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
CursorHoldI
CursorHoldILike CursorHold, but in Insert mode. Nottriggered when waiting for another key, e.g.afterCTRL-V, and not inCTRL-X modeinsert_expand.
CursorMoved
CursorMovedAfter 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 seematch-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.CursorMovedC
CursorMovedCAfter 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 thecmdline-char.CursorMovedI
CursorMovedIAfter the cursor was moved in Insert mode.Not triggered when the popup menu is visible.Otherwise the same as CursorMoved.DiffUpdated
DiffUpdatedAfter diffs have been updated. Depending onwhat kind of diff is being used (internal orexternal) this can be triggered on everychange or when doing:diffupdate.DirChanged
DirChangedAfter thecurrent-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 thesev: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).DirChangedPre
DirChangedPreWhen thecurrent-directory is going to bechanged, as withDirChanged.The pattern is like withDirChanged.Sets thesev: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).ExitPre
ExitPreWhen using:quit,:wq in a way it makesVim exit, or using:qall, just afterQuitPre. Can be used to close anynon-essential window. Exiting may still becancelled if there is a modified buffer thatisn't automatically saved, useVimLeavePrefor really exiting.See alsoQuitPre,WinClosed.FileAppendCmd
FileAppendCmdBefore appending to a file. Should do theappending to the file. Use the '[ and ']marks for the range of lines.Cmd-eventFileAppendPost
FileAppendPostAfter appending to a file.FileAppendPre
FileAppendPreBefore appending to a file. Use the '[ and ']marks for the range of lines.FileChangedRO
FileChangedROBefore 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.E788
Cannot switch buffers. You can reload thebuffer but not edit another one.E881
If the number of lines changes saving for undomay fail and the change will be aborted.FileChangedShell
FileChangedShellWhen 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
:checktime
FocusGained
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. Setv: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).FileChangedShellPost
FileChangedShellPostAfter handling a file that was changed outsideof Vim. Can be used to update the statusline.FileReadCmd
FileReadCmdBefore reading a file with a ":read" command.Should do the reading of the file.Cmd-eventFileReadPost
FileReadPostAfter 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.FileReadPre
FileReadPreBefore reading a file with a ":read" command.FileType
FileTypeWhen 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.Seefiletypes.FileWriteCmd
FileWriteCmdBefore 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-eventFileWritePost
FileWritePostAfter writing to a file, when not writing thewhole buffer.FileWritePre
FileWritePreBefore writing to a file, when not writing thewhole buffer. Use the'[ and'] marks for therange of lines.FilterReadPost
FilterReadPostAfter 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.FilterWritePost
FilterWritePostAfter writing a file for a filter command ormaking a diff with an external diff (seeDiffUpdated for internal diff).Vim checks the pattern against the name ofthe current buffer as with FilterWritePre.Not triggered when'shelltemp' is off.FilterWritePre
FilterWritePreBefore 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.FocusGained
FocusGainedNvim got focus.FocusLost
FocusLostNvim lost focus. Also (potentially) whena GUI dialog pops up.FuncUndefined
FuncUndefinedWhen 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 withoutautocmd-nested.NOTE: When writing Vim scripts a betteralternative is to use an autoloaded function.Seeautoload-functions.UIEnter
UIEnterAfter a UI connects vianvim_ui_attach(), orafter builtin TUI is started, afterVimEnter.Sets thesev:event keys: chan:channel-id of the UIUILeave
UILeaveAfter a UI disconnects from Nvim, or afterbuiltin TUI is stopped, afterVimLeave.Sets thesev:event keys: chan:channel-id of the UIInsertChange
InsertChangeWhen typing<Insert> while in Insert orReplace mode. Thev:insertmode variableindicates the new mode.Be careful not to move the cursor or doanything else that the user does not expect.InsertCharPre
InsertCharPreWhen a character is typed in Insert mode,before inserting the char.Thev:char variable indicates the char typedand can be changed during the event to inserta different character. Whenv:char is setto more than one character this text isinserted literally.
Cannot change the text.textlockInsertEnter
InsertEnterJust before starting Insert mode. Also forReplace mode and Virtual Replace mode. Thev: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 setv:char to a non-emptystring.InsertLeavePre
InsertLeavePreJust before leaving Insert mode. Also whenusingCTRL-Oi_CTRL-O. Be careful not tochange mode or use:normal, it will likelycause trouble.InsertLeave
InsertLeaveJust after leaving Insert mode. Also whenusingCTRL-Oi_CTRL-O. But not fori_CTRL-C.LspAttachSeeLspAttachLspDetachSeeLspDetachLspNotifySeeLspNotifyLspProgressSeeLspProgressLspRequestSeeLspRequestLspTokenUpdateSeeLspTokenUpdateMenuPopup
MenuPopupJust 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 linetlTerminalModeChanged
ModeChangedAfter changing the mode. The pattern ismatched against'old_mode:new_mode', forexample match against*:c* to simulateCmdlineEnter.The following values ofv:event are set: old_modeThe mode before it changed. new_modeThe new mode as also returnedbymode() 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]'
ProgressProgress
After a progress message is created or updated vianvim_echo. The pattern is matched againsttitle of the message. Theevent-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"})
OptionSet
OptionSetAfter setting an option (except duringstartup). Theautocmd-pattern is matchedagainst 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 the tag 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_oldlocal is only set when:setor:setlocal or amodeline was used to setthe option. Similarlyv:option_oldglobal isonly set when:set or:setglobal was used.
This does not set<abuf>, you could usebufnr().
Note that when setting aglobal-local optionwith:set, thenv: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.
Note: Not triggered by the'modified' option;theBufModifiedSet event may be used tohandle that.
Non-recursive::set in the autocommand doesnot trigger OptionSet again.
Not triggered on startup.
QuickFixCmdPre
QuickFixCmdPreBefore 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.QuickFixCmdPost
QuickFixCmdPostLike 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.SeeQuickFixCmdPost-example.QuitPre
QuitPreWhen 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 alsoExitPre,WinClosed.RemoteReply
RemoteReplyWhen 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.SearchWrapped
SearchWrappedAfter making a search withn orN if thesearch wraps around the document back tothe start/finish respectively.RecordingEnter
RecordingEnterWhen a macro starts recording.The pattern is the current file name, andreg_recording() is the current register thatis used.RecordingLeave
RecordingLeaveWhen a macro stops recording.The pattern is the current file name, andreg_recording() is the recordedregister.reg_recorded() is only updated after thisevent.Sets thesev:event keys: regcontents regnameSafeState
SafeStateWhen 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.
SessionLoadPost
SessionLoadPostAfter loading the session file created usingthe:mksession command.SessionWritePost
SessionWritePostAfter writing a session file by callingthe:mksession command.ShellCmdPost
ShellCmdPostAfter executing a shell command with:!cmd,:make and:grep. Can be used to check forany changed files.For non-blocking shell commands, seejob-control.Signal
SignalAfter 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 withoutautocmd-nested.Example:
autocmd Signal SIGUSR1 call some#func()
ShellFilterPost
ShellFilterPostAfter executing a shell command with":{range}!cmd", ":w !cmd" or ":r !cmd".Can be used to check for any changed files.SourcePre
SourcePreBefore sourcing a Vimscript/Lua file.:source<afile> is the name of the file being sourced.SourcePost
SourcePostAfter 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.SourceCmd
SourceCmdWhen sourcing a Vimscript/Lua file.:source<afile> is the name of the file being sourced.The autocommand must source that file.Cmd-eventSpellFileMissing
SpellFileMissingWhen trying to load a spell checking file andit can't be found. The pattern is matchedagainst the language.<amatch> is thelanguage,'encoding' also matters. Seespell-SpellFileMissing.StdinReadPost
StdinReadPostDuring startup, after reading from stdin intothe buffer, before executing modelines.--StdinReadPre
StdinReadPreDuring startup, before reading from stdin intothe buffer.--SwapExists
SwapExistsDetected 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.Thev: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 thev: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 hittingCTRL-CWhen set to an empty string the user will beasked, as if there was no SwapExists autocmd.E812
Cannot change to another buffer, changethe buffer name or change directory.Syntax
SyntaxWhen 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.TabEnter
TabEnterJust after entering a tab page.tab-pageAfter WinEnter.Before BufEnter.TabLeave
TabLeaveJust before leaving a tab page.tab-pageAfter WinLeave.TabNew
TabNewWhen creating a new tab page.tab-pageAfter WinEnter.Before TabEnter.TabNewEntered
TabNewEnteredAfter entering a new tab page.tab-pageAfter BufEnter.TabClosed
TabClosedAfter closing a tab page.<afile> expands tothe tab page number.TermOpen
TermOpenWhen aterminal job is starting. Can beused to configure the terminal buffer.TermEnter
TermEnterAfter enteringTerminal-mode.After TermOpen.TermLeave
TermLeaveAfter leavingTerminal-mode.After TermClose.TermClose
TermCloseWhen aterminal job ends.Sets thesev:event keys: statusTermRequest
TermRequestWhen a:terminal child process emits an OSC,DCS, or APC sequence. Setsv:termrequest. Theevent-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 withoutautocmd-nested.
TermResponse
TermResponseWhen Nvim receives a DA1, OSC, DCS, or APC response fromthe host terminal. Setsv:termresponse. Theevent-data is a table with the following fields:
sequence: the received sequence
This is triggered even when inside anautocommand defined withoutautocmd-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\\")
TextChanged
TextChangedAfter a change was made to the text in thecurrent buffer in Normal mode. That is afterb: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.TextChangedI
TextChangedIAfter 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.TextChangedP
TextChangedPAfter a change was made to the text in thecurrent buffer in Insert mode, only when thepopup menu is visible. Otherwise the same asTextChanged.TextChangedT
TextChangedTAfter a change was made to the text in thecurrent buffer inTerminal-mode. Otherwisethe same as TextChanged.TextYankPost
TextYankPostJust after ayank ordeleting command, but notif the black hole registerquote_ is used norforsetreg(). Pattern must be "*".Sets thesev:event keys: inclusive operator regcontents regname regtype visualTheinclusive 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.textlockUser
UserNot executed automatically. Use:doautocmdto trigger this, typically for "custom events"in a plugin. Example:
:autocmd User MyPlugin echom 'got MyPlugin event':doautocmd User MyPlugin
UserGettingBored
UserGettingBoredWhen the user presses the same key 42 times.Just kidding! :-)VimEnter
VimEnterAfter 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 thev: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
VimLeave
VimLeaveBefore exiting Vim, just after writing the.shada file. Executed only once, likeVimLeavePre.Usev:dying to detect an abnormal exit.Usev:exiting to get the exit code.Not triggered ifv:dying is 2 or more.VimLeavePre
VimLeavePreBefore exiting Vim, just before writing theshada file. Executed only once, if thepattern matches the current buffer on exit.Mostly useful with a "*" pattern.
:autocmd VimLeavePre * call CleanupStuff()
Usev:dying to detect an abnormal exit.Usev:exiting to get the exit code.Not triggered ifv:dying is 2 or more.VimResized
VimResizedAfter the Vim window was resized, thus'lines'and/or'columns' changed. Not when startingup though.VimResume
VimResumeAfter Nvim resumes fromsuspend state.VimSuspend
VimSuspendBefore Nvim enterssuspend state.WinClosed
WinClosedWhen closing a window, just before it isremoved from the window layout. The patternis matched against thewindow-ID. Both<amatch> and<afile> are set to thewindow-ID.After WinLeave.Non-recursive (event cannot trigger itself).See alsoExitPre,QuitPre.WinEnter
WinEnterAfter 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.
WinLeave
WinLeaveBefore 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.WinNew
WinNewWhen a new window was created. Not done forthe first window, when Vim has just started.Before WinEnter.
WinScrolled
WinScrolledAfter any window in the current tab pagescrolled the text (horizontally or vertically)or changed width or height. Seewin-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 thewindow-IDof the first window that scrolled or resized.Both<amatch> and<afile> are set to thewindow-ID.
v:event is set with information about sizeand scroll changes.WinScrolled-event
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.
WinResized
WinResizedAfter a window in the current tab page changedwidth or height.Seewin-scrolled-resized.
v:event is set with information about sizechanges.WinResized-event
Same behavior asWinScrolled for thepattern, triggering and recursiveness.

6. Patternsautocmd-pattern{aupat}

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-localautocommandsautocmd-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-pattern
The 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 apattern,inside { }: like \| in apattern\}literal }\{literal {\\\{n,m\} like \{n,m} in apattern\special meaning like in apattern[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 usepattern items, but they may not work as expected,because of the translation done for the above.
autocmd-changes
Matching 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.

7. Buffer-local autocommandsautocmd-buflocalautocmd-buffer-local

<buffer><buffer=N><buffer=abuf>E680
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 theexists() functionas follows:
:if exists("#CursorHold#<buffer=12>") | ... | endif:if exists("#CursorHold#<buffer>") | ... | endif    " for current buffer
When 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.

8. Groupsautocmd-groups

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).
FileExplorer
There 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

9. Executing autocommandsautocmd-execute

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
Be careful to avoid endless loops.autocmd-nested
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 asUser.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-Buffer
Sourcing 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.

10. Using autocommandsautocmd-use

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-event
Note 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-example
Examples 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 END
The "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.
If you want to skip autocommands for one command, use the:noautocmd commandmodifier or the'eventignore' option.
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-pattern
You 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 FOR
For 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"):endfun
You 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-searchpat
Autocommands 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-event
When 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 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 variable is one when "!" wasused, zero otherwise.
See the $VIMRUNTIME/pack/dist/opt/netrw/plugin/netrwPlugin.vim for examples.

11. Disabling autocommandsautocmd-disable

To disable autocommands for some time use the'eventignore' option. Note thatthis may cause unexpected behavior, make sure you restore'eventignore'afterwards, using a:try block with:finally.
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 toCursorMoved andTextChanged.
Main
Commands index
Quick reference

1. Introduction
2. Defining autocommands
3. Removing autocommands
4. Listing autocommands
5. Events
6. Patterns
7. Buffer-local autocommands
8. Groups
9. Executing autocommands
10. Using autocommands
11. Disabling autocommands

[8]ページ先頭

©2009-2025 Movatter.jp