blob: eddfead8a0d409c8f1eef8281d233632acfc8a08 [file] [log] [blame]
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001*autocmd.txt* For Vim version 7.0aa. Last change: 2004 Sep 17
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Automatic commands *autocommand*
8
9For a basic explanation, see section |40.3| in the user manual.
10
111. Introduction |autocmd-intro|
122. Defining autocommands |autocmd-define|
133. Removing autocommands |autocmd-remove|
144. Listing autocommands |autocmd-list|
155. Events |autocmd-events|
166. Patterns |autocmd-patterns|
177. Groups |autocmd-groups|
188. Executing autocommands |autocmd-execute|
199. Using autocommands |autocmd-use|
20
21{Vi does not have any of these commands}
22{only when the |+autocmd| feature has not been disabled at compile time}
23
24==============================================================================
251. Introduction *autocmd-intro*
26
Bram Moolenaard4755bb2004-09-02 19:12:26 +000027You can specify commands to be executed automatically when reading or writing
28a file, when entering or leaving a buffer or window, and when exiting Vim.
29For example, you can create an autocommand to set the 'cindent' option for
30files matching *.c. You can also use autocommands to implement advanced
Bram Moolenaar071d4272004-06-13 20:20:40 +000031features, such as editing compressed files (see |gzip-example|). The usual
32place to put autocommands is in your .vimrc or .exrc file.
33
34 *E203* *E204* *E143*
35WARNING: Using autocommands is very powerful, and may lead to unexpected side
36effects. Be careful not to destroy your text.
37- It's a good idea to do some testing on an expendable copy of a file first.
38 For example: If you use autocommands to decompress a file when starting to
39 edit it, make sure that the autocommands for compressing when writing work
40 correctly.
41- Be prepared for an error halfway through (e.g., disk full). Vim will mostly
42 be able to undo the changes to the buffer, but you may have to clean up the
43 changes to other files by hand (e.g., compress a file that has been
44 decompressed).
45- If the BufRead* events allow you to edit a compressed file, the FileRead*
46 events should do the same (this makes recovery possible in some rare cases).
47 It's a good idea to use the same autocommands for the File* and Buf* events
48 when possible.
49
50==============================================================================
512. Defining autocommands *autocmd-define*
52
53Note: The ":autocmd" command cannot be followed by another command, since any
54'|' is considered part of the command.
55
56 *:au* *:autocmd*
57:au[tocmd] [group] {event} {pat} [nested] {cmd}
58 Add {cmd} to the list of commands that Vim will
59 execute automatically on {event} for a file matching
60 {pat}. Vim always adds the {cmd} after existing
61 autocommands, so that the autocommands execute in the
62 order in which they were given. See |autocmd-nested|
63 for [nested].
64
65Note that special characters (e.g., "%", "<cword>") in the ":autocmd"
66arguments are not expanded when the autocommand is defined. These will be
67expanded when the Event is recognized, and the {cmd} is executed. The only
68exception is that "<sfile>" is expanded when the autocmd is defined. Example:
69>
70 :au BufNewFile,BufRead *.html so <sfile>:h/html.vim
71
72Here Vim expands <sfile> to the name of the file containing this line.
73
74When your .vimrc file is sourced twice, the autocommands will appear twice.
75To avoid this, put this command in your .vimrc file, before defining
76autocommands: >
77
78 :autocmd! " Remove ALL autocommands for the current group.
79
80If you don't want to remove all autocommands, you can instead use a variable
81to ensure that Vim includes the autocommands only once: >
82
83 :if !exists("autocommands_loaded")
84 : let autocommands_loaded = 1
85 : au ...
86 :endif
87
88When the [group] argument is not given, Vim uses the current group (as defined
89with ":augroup"); otherwise, Vim uses the group defined with [group]. Note
90that [group] must have been defined before. You cannot define a new group
91with ":au group ..."; use ":augroup" for that.
92
93While testing autocommands, you might find the 'verbose' option to be useful: >
94 :set verbose=9
95This setting makes Vim echo the autocommands as it executes them.
96
97When defining an autocommand in a script, it will be able to call functions
98local to the script and use mappings local to the script. When the event is
99triggered and the command executed, it will run in the context of the script
100it was defined in. This matters if |<SID>| is used in a command.
101
102When executing the commands, the messages from one command overwrites a
103previous message. This is different from when executing the commands
104manually. Mostly the screen will not scroll up, thus there is no hit-enter
105prompt. When one command outputs two messages this can happen anyway.
106
107==============================================================================
1083. Removing autocommands *autocmd-remove*
109
110:au[tocmd]! [group] {event} {pat} [nested] {cmd}
111 Remove all autocommands associated with {event} and
112 {pat}, and add the command {cmd}. See
113 |autocmd-nested| for [nested].
114
115:au[tocmd]! [group] {event} {pat}
116 Remove all autocommands associated with {event} and
117 {pat}.
118
119:au[tocmd]! [group] * {pat}
120 Remove all autocommands associated with {pat} for all
121 events.
122
123:au[tocmd]! [group] {event}
124 Remove ALL autocommands for {event}.
125
126:au[tocmd]! [group] Remove ALL autocommands.
127
128When the [group] argument is not given, Vim uses the current group (as defined
129with ":augroup"); otherwise, Vim uses the group defined with [group].
130
131==============================================================================
1324. Listing autocommands *autocmd-list*
133
134:au[tocmd] [group] {event} {pat}
135 Show the autocommands associated with {event} and
136 {pat}.
137
138:au[tocmd] [group] * {pat}
139 Show the autocommands associated with {pat} for all
140 events.
141
142:au[tocmd] [group] {event}
143 Show all autocommands for {event}.
144
145:au[tocmd] [group] Show all autocommands.
146
147If you provide the [group] argument, Vim lists only the autocommands for
148[group]; otherwise, Vim lists the autocommands for ALL groups. Note that this
149argument behavior differs from that for defining and removing autocommands.
150
151==============================================================================
1525. Events *autocmd-events* *E215* *E216*
153
154 *autocommand-events* *{event}*
155Vim recognizes the following events. Vim ignores the case of event names
156(e.g., you can use "BUFread" or "bufread" instead of "BufRead").
157
158 *BufNewFile*
159BufNewFile When starting to edit a file that doesn't
160 exist. Can be used to read in a skeleton
161 file.
162 *BufReadPre* *E200* *E201*
163BufReadPre When starting to edit a new buffer, before
164 reading the file into the buffer. Not used
165 if the file doesn't exist.
166 *BufRead* *BufReadPost*
167BufRead or BufReadPost When starting to edit a new buffer, after
168 reading the file into the buffer, before
169 executing the modelines. See |BufWinEnter|
170 for when you need to do something after
171 processing the modelines.
172 This does NOT work for ":r file". Not used
173 when the file doesn't exist. Also used after
174 successfully recovering a file.
175 *BufReadCmd*
176BufReadCmd Before starting to edit a new buffer. Should
177 read the file into the buffer. |Cmd-event|
178 *BufFilePre*
179BufFilePre Before changing the name of the current buffer
180 with the ":file" or ":saveas" command.
181 *BufFilePost*
182BufFilePost After changing the name of the current buffer
183 with the ":file" or ":saveas" command.
184 *FileReadPre*
185FileReadPre Before reading a file with a ":read" command.
186 *FileReadPost*
187FileReadPost After reading a file with a ":read" command.
188 Note that Vim sets the '[ and '] marks to the
189 first and last line of the read. This can be
190 used to operate on the lines just read.
191 *FileReadCmd*
192FileReadCmd Before reading a file with a ":read" command.
193 Should do the reading of the file. |Cmd-event|
194 *FilterReadPre* *E135*
195FilterReadPre Before reading a file from a filter command.
196 Vim checks the pattern against the name of
197 the current buffer, not the name of the
198 temporary file that is the output of the
199 filter command.
200 *FilterReadPost*
201FilterReadPost After reading a file from a filter command.
202 Vim checks the pattern against the name of
203 the current buffer as with FilterReadPre.
204 *FileType*
205FileType When the 'filetype' option has been set.
206 <afile> can be used for the name of the file
207 where this option was set, and <amatch> for
208 the new value of 'filetype'.
209 See |filetypes|.
210 *Syntax*
211Syntax When the 'syntax' option has been set.
212 <afile> can be used for the name of the file
213 where this option was set, and <amatch> for
214 the new value of 'syntax'.
215 See |:syn-on|.
216 *StdinReadPre*
217StdinReadPre Before reading from stdin into the buffer.
218 Only used when the "-" argument was used when
219 Vim was started |--|.
220 *StdinReadPost*
221StdinReadPost After reading from the stdin into the buffer,
222 before executing the modelines. Only used
223 when the "-" argument was used when Vim was
224 started |--|.
225 *BufWrite* *BufWritePre*
226BufWrite or BufWritePre Before writing the whole buffer to a file.
227 *BufWritePost*
228BufWritePost After writing the whole buffer to a file
229 (should undo the commands for BufWritePre).
230 *BufWriteCmd*
231BufWriteCmd Before writing the whole buffer to a file.
232 Should do the writing of the file and reset
233 'modified' if successful. The buffer contents
234 should not be changed. |Cmd-event|
235 *FileWritePre*
236FileWritePre Before writing to a file, when not writing the
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000237 whole buffer. Use the '[ and '] marks for the
238 range of lines.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000239 *FileWritePost*
240FileWritePost After writing to a file, when not writing the
241 whole buffer.
242 *FileWriteCmd*
243FileWriteCmd Before writing to a file, when not writing the
244 whole buffer. Should do the writing to the
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000245 file. Should not change the buffer. Use the
246 '[ and '] marks for the range of lines.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 |Cmd-event|
248 *FileAppendPre*
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000249FileAppendPre Before appending to a file. Use the '[ and ']
250 marks for the range of lines.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251 *FileAppendPost*
252FileAppendPost After appending to a file.
253 *FileAppendCmd*
254FileAppendCmd Before appending to a file. Should do the
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000255 appending to the file. Use the '[ and ']
256 marks for the range of lines.|Cmd-event|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257 *FilterWritePre*
258FilterWritePre Before writing a file for a filter command or
259 making a diff.
260 Vim checks the pattern against the name of
261 the current buffer, not the name of the
262 temporary file that is the output of the
263 filter command.
264 *FilterWritePost*
265FilterWritePost After writing a file for a filter command or
266 making a diff.
267 Vim checks the pattern against the name of
268 the current buffer as with FilterWritePre.
269 *FileChangedShell*
270FileChangedShell When Vim notices that the modification time of
271 a file has changed since editing started.
272 Also when the file attributes of the file
273 change. |timestamp|
274 Mostly triggered after executing a shell
275 command, but also with a |:checktime| command
276 or when Vim regains input focus.
277 This autocommand is triggered for each changed
278 file. It is not used when 'autoread' is set
279 and the buffer was not changed. If a
280 FileChangedShell autocommand is present the
281 warning message and prompt is not given.
282 This is useful for reloading related buffers
283 which are affected by a single command.
284 NOTE: When this autocommand is executed, the
285 current buffer "%" may be different from the
286 buffer that was changed "<afile>".
287 NOTE: The commands must not change the current
288 buffer, jump to another buffer or delete a
289 buffer. *E246*
290 NOTE: This event never nests, to avoid an
291 endless loop. This means that while executing
292 commands for the FileChangedShell event no
293 other FileChangedShell event will be
294 triggered.
295 *FileChangedRO*
296FileChangedRO Before making the first change to a read-only
297 file. Can be used to check-out the file from
298 a source control system. Not triggered when
299 the change was caused by an autocommand.
300 WARNING: This event is triggered when making a
301 change, just before the change is applied to
302 the text. If the autocommand moves the cursor
303 the effect of the change is undefined.
304 *FocusGained*
305FocusGained When Vim got input focus. Only for the GUI
306 version and a few console versions where this
307 can be detected.
308 *FocusLost*
309FocusLost When Vim lost input focus. Only for the GUI
310 version and a few console versions where this
Bram Moolenaar843ee412004-06-30 16:16:41 +0000311 can be detected. May also happen when a
312 dialog pops up.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000313 *FuncUndefined*
314FuncUndefined When a user function is used but it isn't
315 defined. Useful for defining a function only
316 when it's used. Both <amatch> and <afile> are
317 set to the name of the function.
318 *CursorHold*
319CursorHold When the user doesn't press a key for the time
320 specified with 'updatetime'. Not re-triggered
321 until the user has pressed a key (i.e. doesn't
322 fire every 'updatetime' ms if you leave Vim to
323 make some coffee. :) See |CursorHold-example|
324 for previewing tags.
325 This event is only triggered in Normal mode.
326 Note: Interactive commands cannot be used for
327 this event. There is no hit-enter prompt,
328 the screen is updated directly (when needed).
329 Note: In the future there will probably be
330 another option to set the time.
331 Hint: to force an update of the status lines
332 use: >
333 :let &ro = &ro
334< {only on Amiga, Unix, Win32, MSDOS and all GUI
335 versions}
336 *BufEnter*
337BufEnter After entering a buffer. Useful for setting
338 options for a file type. Also executed when
339 starting to edit a buffer, after the
340 BufReadPost autocommands.
341 *BufLeave*
342BufLeave Before leaving to another buffer. Also when
343 leaving or closing the current window and the
344 new current window is not for the same buffer.
345 Not used for ":qa" or ":q" when exiting Vim.
346 *BufWinEnter*
347BufWinEnter After a buffer is displayed in a window. This
348 can be when the buffer is loaded (after
349 processing the modelines), when a hidden
350 buffer is displayed in a window (and is no
351 longer hidden) or a buffer already visible in
352 a window is also displayed in another window.
353 *BufWinLeave*
354BufWinLeave Before a buffer is removed from a window.
355 Not when it's still visible in another window.
356 Also triggered when exiting. It's triggered
357 before BufUnload or BufHidden.
358 NOTE: When this autocommand is executed, the
359 current buffer "%" may be different from the
360 buffer being unloaded "<afile>".
361 *BufUnload*
362BufUnload Before unloading a buffer. This is when the
363 text in the buffer is going to be freed. This
364 may be after a BufWritePost and before a
365 BufDelete. Also used for all buffers that are
366 loaded when Vim is going to exit.
367 NOTE: When this autocommand is executed, the
368 current buffer "%" may be different from the
369 buffer being unloaded "<afile>".
370 *BufHidden*
371BufHidden Just after a buffer has become hidden. That
372 is, when there are no longer windows that show
373 the buffer, but the buffer is not unloaded or
374 deleted. Not used for ":qa" or ":q" when
375 exiting Vim.
376 NOTE: When this autocommand is executed, the
377 current buffer "%" may be different from the
378 buffer being unloaded "<afile>".
379 *BufNew*
380BufNew Just after creating a new buffer. Also used
381 just after a buffer has been renamed. When
382 the buffer is added to the buffer list BufAdd
383 will be triggered too.
384 NOTE: When this autocommand is executed, the
385 current buffer "%" may be different from the
386 buffer being created "<afile>".
387 *BufCreate* *BufAdd*
388BufAdd or BufCreate Just after creating a new buffer which is
389 added to the buffer list, or adding a buffer
390 to the buffer list.
391 Also used just after a buffer in the buffer
392 list has been renamed.
393 The BufCreate event is for historic reasons.
394 NOTE: When this autocommand is executed, the
395 current buffer "%" may be different from the
396 buffer being created "<afile>".
397 *BufDelete*
398BufDelete Before deleting a buffer from the buffer list.
399 The BufUnload may be called first (if the
400 buffer was loaded).
401 Also used just before a buffer in the buffer
402 list is renamed.
403 NOTE: When this autocommand is executed, the
404 current buffer "%" may be different from the
405 buffer being deleted "<afile>".
406 *BufWipeout*
407BufWipeout Before completely deleting a buffer. The
408 BufUnload and BufDelete events may be called
409 first (if the buffer was loaded and was in the
410 buffer list). Also used just before a buffer
411 is renamed (also when it's not in the buffer
412 list).
413 NOTE: When this autocommand is executed, the
414 current buffer "%" may be different from the
415 buffer being deleted "<afile>".
416 *WinEnter*
417WinEnter After entering another window. Not done for
418 the first window, when Vim has just started.
419 Useful for setting the window height.
420 If the window is for another buffer, Vim
421 executes the BufEnter autocommands after the
422 WinEnter autocommands.
423 Note: When using ":split fname" the WinEnter
424 event is triggered after the split but before
425 the file "fname" is loaded.
426 *WinLeave*
427WinLeave Before leaving a window. If the window to be
428 entered next is for a different buffer, Vim
429 executes the BufLeave autocommands before the
430 WinLeave autocommands (but not for ":new").
431 Not used for ":qa" or ":q" when exiting Vim.
432 *CmdwinEnter*
433CmdwinEnter After entering the command-line window.
434 Useful for setting options specifically for
435 this special type of window. This is
436 triggered _instead_ of BufEnter and WinEnter.
437 <afile> is set to a single character,
438 indicating the type of command-line.
439 |cmdwin-char|
440 *CmdwinLeave*
441CmdwinLeave Before leaving the command-line window.
442 Useful to clean up any global setting done
443 with CmdwinEnter. This is triggered _instead_
444 of BufLeave and WinLeave.
445 <afile> is set to a single character,
446 indicating the type of command-line.
447 |cmdwin-char|
448 *GUIEnter*
449GUIEnter After starting the GUI successfully, and after
450 opening the window. It is triggered before
451 VimEnter when using gvim. Can be used to
452 position the window from a .gvimrc file: >
453 :autocmd GUIEnter * winpos 100 50
454< *VimEnter*
455VimEnter After doing all the startup stuff, including
456 loading .vimrc files, executing the "-c cmd"
457 arguments, creating all windows and loading
458 the buffers in them.
459 *VimLeavePre*
460VimLeavePre Before exiting Vim, just before writing the
461 .viminfo file. This is executed only once,
462 if there is a match with the name of what
463 happens to be the current buffer when exiting.
464 Mostly useful with a "*" pattern. >
465 :autocmd VimLeavePre * call CleanupStuff()
466< To detect an abnormal exit use |v:dying|.
467 *VimLeave*
468VimLeave Before exiting Vim, just after writing the
469 .viminfo file. Executed only once, like
470 VimLeavePre.
471 To detect an abnormal exit use |v:dying|.
472 *EncodingChanged*
473EncodingChanged Fires off when the 'encoding' option is
474 changed. Useful to set up fonts, for example.
Bram Moolenaar843ee412004-06-30 16:16:41 +0000475 *InsertEnter*
476InsertEnter When starting Insert mode. Also for Replace
477 mode and Virtual Replace mode. The
478 |v:insertmode| variable indicates the mode.
479 Be careful not to move the cursor or do
480 anything else that the user does not expect.
481 *InsertChange*
482InsertChange When typing <Insert> while in Insert or
483 Replace mode. The |v:insertmode| variable
484 indicates the new mode.
485 Be careful not to move the cursor or do
486 anything else that the user does not expect.
487 *InsertLeave*
488InsertLeave When leaving Insert mode. Also when using
489 CTRL-O |i_CTRL-O|.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490 *FileEncoding*
491FileEncoding Obsolete. It still works and is equivalent
492 to |EncodingChanged|.
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +0000493 *ColorScheme*
494ColorScheme After loading a color scheme. |:colorscheme|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 *RemoteReply*
496RemoteReply When a reply from a Vim that functions as
497 server was received |server2client()|.
498 <amatch> is equal to the {serverid} from which
499 the reply was sent, and <afile> is the actual
500 reply string.
501 Note that even if an autocommand is defined,
502 the reply should be read with |remote_read()|
503 to consume it.
504 *TermChanged*
505TermChanged After the value of 'term' has changed. Useful
506 for re-loading the syntax file to update the
507 colors, fonts and other terminal-dependent
508 settings. Executed for all loaded buffers.
509 *TermResponse*
510TermResponse After the response to |t_RV| is received from
511 the terminal. The value of |v:termresponse|
512 can be used to do things depending on the
513 terminal version.
514 *UserGettingBored*
515UserGettingBored When the user hits CTRL-C. Just kidding! :-)
516 *User*
517User Never executed automatically. To be used for
518 autocommands that are only executed with
519 ":doautocmd".
520
521You can specify a comma-separated list of event names. No white space can be
522used in this list. The command applies to all the events in the list.
523
524For READING FILES there are four kinds of events possible:
525 BufNewFile starting to edit a non-existent file
526 BufReadPre BufReadPost starting to edit an existing file
527 FilterReadPre FilterReadPost read the temp file with filter output
528 FileReadPre FileReadPost any other file read
529Vim uses only one of these four kinds when reading a file. The "Pre" and
530"Post" events are both triggered, before and after reading the file.
531
532Note that the autocommands for the *ReadPre events and all the Filter events
533are not allowed to change the current buffer (you will get an error message if
534this happens). This is to prevent the file to be read into the wrong buffer.
535
536Note that the 'modified' flag is reset AFTER executing the BufReadPost
537and BufNewFile autocommands. But when the 'modified' option was set by the
538autocommands, this doesn't happen.
539
540You can use the 'eventignore' option to ignore a number of events or all
541events.
542
543==============================================================================
5446. Patterns *autocmd-patterns* *{pat}*
545
546The file pattern {pat} is tested for a match against the file name in one of
547two ways:
5481. When there is no '/' in the pattern, Vim checks for a match against only
549 the tail part of the file name (without its leading directory path).
5502. When there is a '/' in the pattern, Vim checks for a match against the
551 both short file name (as you typed it) and the full file name (after
552 expanding it to a full path and resolving symbolic links).
553
554Examples: >
555 :autocmd BufRead *.txt set et
556Set the 'et' option for all text files. >
557
558 :autocmd BufRead /vim/src/*.c set cindent
559Set the 'cindent' option for C files in the /vim/src directory. >
560
561 :autocmd BufRead /tmp/*.c set ts=5
562If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", and
563you start editing "/tmp/test.c", this autocommand will match.
564
565Note: To match part of a path, but not from the root directory, use a '*' as
566the first character. Example: >
567 :autocmd BufRead */doc/*.txt set tw=78
568This autocommand will for example be executed for "/tmp/doc/xx.txt" and
569"/usr/home/piet/doc/yy.txt". The number of directories does not matter here.
570
571
572The file name that the pattern is matched against is after expanding
573wildcards. Thus is you issue this command: >
574 :e $ROOTDIR/main.$EXT
575The argument is first expanded to: >
576 /usr/root/main.py
577Before it's matched with the pattern of the autocommand. Careful with this
578when using events like FileReadCmd, the value of <amatch> may not be what you
579expect.
580
581
582Environment variables can be used in a pattern: >
583 :autocmd BufRead $VIMRUNTIME/doc/*.txt set expandtab
584And ~ can be used for the home directory (if $HOME is defined): >
585 :autocmd BufWritePost ~/.vimrc so ~/.vimrc
586 :autocmd BufRead ~archive/* set readonly
587The environment variable is expanded when the autocommand is defined, not when
588the autocommand is executed. This is different from the command!
589
590 *file-pattern*
591The pattern is interpreted like mostly used in file names:
592 * matches any sequence of characters
593 ? matches any single character
594 \? matches a '?'
595 . matches a '.'
596 ~ matches a '~'
597 , separates patterns
598 \, matches a ','
599 { } like \( \) in a |pattern|
600 , inside { }: like \| in a |pattern|
601 \ special meaning like in a |pattern|
602 [ch] matches 'c' or 'h'
603 [^ch] match any character but 'c' and 'h'
604
605Note that for all systems the '/' character is used for path separator (even
606MS-DOS and OS/2). This was done because the backslash is difficult to use
607in a pattern and to make the autocommands portable across different systems.
608
609
610Matching with the pattern is done when an event is triggered. Changing the
611buffer name in one of the autocommands, or even deleting the buffer, does not
612change which autocommands will be executed. Example: >
613
614 au BufEnter *.foo bdel
615 au BufEnter *.foo set modified
616
617This will delete the current buffer and then set 'modified' in what has become
618the current buffer instead. Vim doesn't take into account that "*.foo"
619doesn't match with that buffer name. It matches "*.foo" with the name of the
620buffer at the moment the event was triggered.
621
622==============================================================================
6237. Groups *autocmd-groups*
624
625Autocommands can be put together in a group. This is useful for removing or
626executing a group of autocommands. For example, all the autocommands for
627syntax highlighting are put in the "highlight" group, to be able to execute
628":doautoall highlight BufRead" when the GUI starts.
629
630When no specific group is selected, Vim uses the default group. The default
631group does not have a name. You cannot execute the autocommands from the
632default group separately; you can execute them only by executing autocommands
633for all groups.
634
635Normally, when executing autocommands automatically, Vim uses the autocommands
636for all groups. The group only matters when executing autocommands with
637":doautocmd" or ":doautoall", or when defining or deleting autocommands.
638
639The group name can contain any characters except white space. The group name
640"end" is reserved (also in uppercase).
641
642The group name is case sensitive. Note that this is different from the event
643name!
644
645 *:aug* *:augroup*
646:aug[roup] {name} Define the autocmd group name for the
647 following ":autocmd" commands. The name "end"
648 or "END" selects the default group.
649
650 *:augroup-delete* *E367*
651:aug[roup]! {name} Delete the autocmd group {name}. Don't use
652 this if there is still an autocommand using
653 this group! This is not checked.
654
655To enter autocommands for a specific group, use this method:
6561. Select the group with ":augroup {name}".
6572. Delete any old autocommands with ":au!".
6583. Define the autocommands.
6594. Go back to the default group with "augroup END".
660
661Example: >
662 :augroup uncompress
663 : au!
664 : au BufEnter *.gz %!gunzip
665 :augroup END
666
667This prevents having the autocommands defined twice (e.g., after sourcing the
668.vimrc file again).
669
670==============================================================================
6718. Executing autocommands *autocmd-execute*
672
673Vim can also execute Autocommands non-automatically. This is useful if you
674have changed autocommands, or when Vim has executed the wrong autocommands
675(e.g., the file pattern match was wrong).
676
677Note that the 'eventignore' option applies here too. Events listed in this
678option will not cause any commands to be executed.
679
680 *:do* *:doau* *:doautocmd* *E217*
681:do[autocmd] [group] {event} [fname]
682 Apply the autocommands matching [fname] (default:
683 current file name) for {event} to the current buffer.
684 You can use this when the current file name does not
685 match the right pattern, after changing settings, or
686 to execute autocommands for a certain event.
687 It's possible to use this inside an autocommand too,
688 so you can base the autocommands for one extension on
689 another extension. Example: >
690 :au Bufenter *.cpp so ~/.vimrc_cpp
691 :au Bufenter *.cpp doau BufEnter x.c
692< Be careful to avoid endless loops. See
693 |autocmd-nested|.
694
695 When the [group] argument is not given, Vim executes
696 the autocommands for all groups. When the [group]
697 argument is included, Vim executes only the matching
698 autocommands for that group. Note: if you use an
699 undefined group name, Vim gives you an error message.
700
701 *:doautoa* *:doautoall*
702:doautoa[ll] [group] {event} [fname]
703 Like ":doautocmd", but apply the autocommands to each
704 loaded buffer. Note that {fname} is used to select
705 the autocommands, not the buffers to which they are
706 applied.
707 Careful: Don't use this for autocommands that delete a
708 buffer, change to another buffer or change the
709 contents of a buffer; the result is unpredictable.
710 This command is intended for autocommands that set
711 options, change highlighting, and things like that.
712
713==============================================================================
7149. Using autocommands *autocmd-use*
715
716For WRITING FILES there are four possible sets of events. Vim uses only one
717of these sets for a write command:
718
719BufWriteCmd BufWritePre BufWritePost writing the whole buffer
720 FilterWritePre FilterWritePost writing to filter temp file
721FileAppendCmd FileAppendPre FileAppendPost appending to a file
722FileWriteCmd FileWritePre FileWritePost any other file write
723
724When there is a matching "*Cmd" autocommand, it is assumed it will do the
725writing. No further writing is done and the other events are not triggered.
726|Cmd-event|
727
728Note that the *WritePost commands should undo any changes to the buffer that
729were caused by the *WritePre commands; otherwise, writing the file will have
730the side effect of changing the buffer.
731
732Before executing the autocommands, the buffer from which the lines are to be
733written temporarily becomes the current buffer. Unless the autocommands
734change the current buffer or delete the previously current buffer, the
735previously current buffer is made the current buffer again.
736
737The *WritePre and *AppendPre autocommands must not delete the buffer from
738which the lines are to be written.
739
740The '[ and '] marks have a special position:
741- Before the *ReadPre event the '[ mark is set to the line just above where
742 the new lines will be inserted.
743- Before the *ReadPost event the '[ mark is set to the first line that was
744 just read, the '] mark to the last line.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000745- Before executing the *WriteCmd, *WritePre and *AppendPre autocommands the '[
746 mark is set to the first line that will be written, the '] mark to the last
747 line.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748Careful: '[ and '] change when using commands that change the buffer.
749
750In commands which expect a file name, you can use "<afile>" for the file name
751that is being read |:<afile>| (you can also use "%" for the current file
752name). "<abuf>" can be used for the buffer number of the currently effective
753buffer. This also works for buffers that doesn't have a name. But it doesn't
754work for files without a buffer (e.g., with ":r file").
755
756 *gzip-example*
757Examples for reading and writing compressed files: >
758 :augroup gzip
759 : autocmd!
760 : autocmd BufReadPre,FileReadPre *.gz set bin
761 : autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip
762 : autocmd BufReadPost,FileReadPost *.gz set nobin
763 : autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " . expand("%:r")
764 : autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r
765 : autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r
766
767 : autocmd FileAppendPre *.gz !gunzip <afile>
768 : autocmd FileAppendPre *.gz !mv <afile>:r <afile>
769 : autocmd FileAppendPost *.gz !mv <afile> <afile>:r
770 : autocmd FileAppendPost *.gz !gzip <afile>:r
771 :augroup END
772
773The "gzip" group is used to be able to delete any existing autocommands with
774":autocmd!", for when the file is sourced twice.
775
776("<afile>:r" is the file name without the extension, see |:_%:|)
777
778The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,
779FileAppendPost and VimLeave events do not set or reset the changed flag of the
780buffer. When you decompress the buffer with the BufReadPost autocommands, you
781can still exit with ":q". When you use ":undo" in BufWritePost to undo the
782changes made by BufWritePre commands, you can still do ":q" (this also makes
783"ZZ" work). If you do want the buffer to be marked as modified, set the
784'modified' option.
785
786To execute Normal mode commands from an autocommand, use the ":normal"
787command. Use with care! If the Normal mode command is not finished, the user
788needs to type characters (e.g., after ":normal m" you need to type a mark
789name).
790
791If you want the buffer to be unmodified after changing it, reset the
792'modified' option. This makes it possible to exit the buffer with ":q"
793instead of ":q!".
794
795 *autocmd-nested* *E218*
796By default, autocommands do not nest. If you use ":e" or ":w" in an
797autocommand, Vim does not execute the BufRead and BufWrite autocommands for
798those commands. If you do want this, use the "nested" flag for those commands
799in which you want nesting. For example: >
800 :autocmd FileChangedShell *.c nested e!
801The nesting is limited to 10 levels to get out of recursive loops.
802
803It's possible to use the ":au" command in an autocommand. This can be a
804self-modifying command! This can be useful for an autocommand that should
805execute only once.
806
807There is currently no way to disable the autocommands. If you want to write a
808file without executing the autocommands for that type of file, write it under
809another name and rename it with a shell command. In some situations you can
810use the 'eventignore' option.
811
812Note: When reading a file (with ":read file" or with a filter command) and the
813last line in the file does not have an <EOL>, Vim remembers this. At the next
814write (with ":write file" or with a filter command), if the same line is
815written again as the last line in a file AND 'binary' is set, Vim does not
816supply an <EOL>. This makes a filter command on the just read lines write the
817same file as was read, and makes a write command on just filtered lines write
818the same file as was read from the filter. For example, another way to write
819a compressed file: >
820
821 :autocmd FileWritePre *.gz set bin|'[,']!gzip
822 :autocmd FileWritePost *.gz undo|set nobin
823<
824 *autocommand-pattern*
825You can specify multiple patterns, separated by commas. Here are some
826examples: >
827
828 :autocmd BufRead * set tw=79 nocin ic infercase fo=2croq
829 :autocmd BufRead .letter set tw=72 fo=2tcrq
830 :autocmd BufEnter .letter set dict=/usr/lib/dict/words
831 :autocmd BufLeave .letter set dict=
832 :autocmd BufRead,BufNewFile *.c,*.h set tw=0 cin noic
833 :autocmd BufEnter *.c,*.h abbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O
834 :autocmd BufLeave *.c,*.h unabbr FOR
835
836For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.): >
837
838 :autocmd BufEnter ?akefile* set include=^s\=include
839 :autocmd BufLeave ?akefile* set include&
840
841To always start editing C files at the first function: >
842
843 :autocmd BufRead *.c,*.h 1;/^{
844
845Without the "1;" above, the search would start from wherever the file was
846entered, rather than from the start of the file.
847
848 *skeleton* *template*
849To read a skeleton (template) file when opening a new file: >
850
851 :autocmd BufNewFile *.c 0r ~/vim/skeleton.c
852 :autocmd BufNewFile *.h 0r ~/vim/skeleton.h
853 :autocmd BufNewFile *.java 0r ~/vim/skeleton.java
854
855To insert the current date and time in a *.html file when writing it: >
856
857 :autocmd BufWritePre,FileWritePre *.html ks|call LastMod()|'s
858 :fun LastMod()
859 : if line("$") > 20
860 : let l = 20
861 : else
862 : let l = line("$")
863 : endif
864 : exe "1," . l . "g/Last modified: /s/Last modified: .*/Last modified: " .
865 : \ strftime("%Y %b %d")
866 :endfun
867
868You need to have a line "Last modified: <date time>" in the first 20 lines
869of the file for this to work. Vim replaces <date time> (and anything in the
870same line after it) with the current date and time. Explanation:
871 ks mark current position with mark 's'
872 call LastMod() call the LastMod() function to do the work
873 's return the cursor to the old position
874The LastMod() function checks if the file is shorter than 20 lines, and then
875uses the ":g" command to find lines that contain "Last modified: ". For those
876lines the ":s" command is executed to replace the existing date with the
877current one. The ":execute" command is used to be able to use an expression
878for the ":g" and ":s" commands. The date is obtained with the strftime()
879function. You can change its argument to get another date string.
880
881When entering :autocmd on the command-line, completion of events and command
882names may be done (with <Tab>, CTRL-D, etc.) where appropriate.
883
884Vim executes all matching autocommands in the order that you specify them.
885It is recommended that your first autocommand be used for all files by using
886"*" as the file pattern. This means that you can define defaults you like
887here for any settings, and if there is another matching autocommand it will
888override these. But if there is no other matching autocommand, then at least
889your default settings are recovered (if entering this file from another for
890which autocommands did match). Note that "*" will also match files starting
891with ".", unlike Unix shells.
892
893 *autocmd-searchpat*
894Autocommands do not change the current search patterns. Vim saves the current
895search patterns before executing autocommands then restores them after the
896autocommands finish. This means that autocommands do not affect the strings
897highlighted with the 'hlsearch' option. Within autocommands, you can still
898use search patterns normally, e.g., with the "n" command.
899If you want an autocommand to set the search pattern, such that it is used
900after the autocommand finishes, use the ":let @/ =" command.
901The search-highlighting cannot be switched off with ":nohlsearch" in an
902autocommand. Use the 'h' flag in the 'viminfo' option to disable search-
903highlighting when starting Vim.
904
905 *Cmd-event*
906When using one of the "*Cmd" events, the matching autocommands are expected to
907do the file reading or writing. This can be used when working with a special
908kind of file, for example on a remote system.
909CAREFUL: If you use these events in a wrong way, it may have the effect of
910making it impossible to read or write the matching files! Make sure you test
911your autocommands properly. Best is to use a pattern that will never match a
912normal file name, for example "ftp://*".
913
914When defining a BufReadCmd it will be difficult for Vim to recover a crashed
915editing session. When recovering from the original file, Vim reads only those
916parts of a file that are not found in the swap file. Since that is not
917possible with a BufReadCmd, use the |:preserve| command to make sure the
918original file isn't needed for recovery. You might want to do this only when
919you expect the file to be modified.
920
921The |v:cmdarg| variable holds the "++enc=" and "++ff=" argument that are
922effective. These should be used for the command that reads/writes the file.
923The |v:cmdbang| variable is one when "!" was used, zero otherwise.
924
925See the $VIMRUNTIME/plugin/netrw.vim for examples.
926
927 vim:tw=78:ts=8:ft=help:norl: