blob: 4cc7472112661c584dbaeca83c8f2c4659fe8261 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001*autocmd.txt* For Vim version 7.0aa. Last change: 2004 Apr 20
2
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
27You can specify commands to be executed automatically for when reading or
28writing a file, when entering or leaving a buffer or window, and when exiting
29Vim. For example, you can create an autocommand to set the 'cindent' option
30for files matching *.c. You can also use autocommands to implement advanced
31features, 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
237 whole buffer.
238 *FileWritePost*
239FileWritePost After writing to a file, when not writing the
240 whole buffer.
241 *FileWriteCmd*
242FileWriteCmd Before writing to a file, when not writing the
243 whole buffer. Should do the writing to the
244 file. Should not change the buffer.
245 |Cmd-event|
246 *FileAppendPre*
247FileAppendPre Before appending to a file.
248 *FileAppendPost*
249FileAppendPost After appending to a file.
250 *FileAppendCmd*
251FileAppendCmd Before appending to a file. Should do the
252 appending to the file. |Cmd-event|
253 *FilterWritePre*
254FilterWritePre Before writing a file for a filter command or
255 making a diff.
256 Vim checks the pattern against the name of
257 the current buffer, not the name of the
258 temporary file that is the output of the
259 filter command.
260 *FilterWritePost*
261FilterWritePost After writing a file for a filter command or
262 making a diff.
263 Vim checks the pattern against the name of
264 the current buffer as with FilterWritePre.
265 *FileChangedShell*
266FileChangedShell When Vim notices that the modification time of
267 a file has changed since editing started.
268 Also when the file attributes of the file
269 change. |timestamp|
270 Mostly triggered after executing a shell
271 command, but also with a |:checktime| command
272 or when Vim regains input focus.
273 This autocommand is triggered for each changed
274 file. It is not used when 'autoread' is set
275 and the buffer was not changed. If a
276 FileChangedShell autocommand is present the
277 warning message and prompt is not given.
278 This is useful for reloading related buffers
279 which are affected by a single command.
280 NOTE: When this autocommand is executed, the
281 current buffer "%" may be different from the
282 buffer that was changed "<afile>".
283 NOTE: The commands must not change the current
284 buffer, jump to another buffer or delete a
285 buffer. *E246*
286 NOTE: This event never nests, to avoid an
287 endless loop. This means that while executing
288 commands for the FileChangedShell event no
289 other FileChangedShell event will be
290 triggered.
291 *FileChangedRO*
292FileChangedRO Before making the first change to a read-only
293 file. Can be used to check-out the file from
294 a source control system. Not triggered when
295 the change was caused by an autocommand.
296 WARNING: This event is triggered when making a
297 change, just before the change is applied to
298 the text. If the autocommand moves the cursor
299 the effect of the change is undefined.
300 *FocusGained*
301FocusGained When Vim got input focus. Only for the GUI
302 version and a few console versions where this
303 can be detected.
304 *FocusLost*
305FocusLost When Vim lost input focus. Only for the GUI
306 version and a few console versions where this
307 can be detected.
308 *FuncUndefined*
309FuncUndefined When a user function is used but it isn't
310 defined. Useful for defining a function only
311 when it's used. Both <amatch> and <afile> are
312 set to the name of the function.
313 *CursorHold*
314CursorHold When the user doesn't press a key for the time
315 specified with 'updatetime'. Not re-triggered
316 until the user has pressed a key (i.e. doesn't
317 fire every 'updatetime' ms if you leave Vim to
318 make some coffee. :) See |CursorHold-example|
319 for previewing tags.
320 This event is only triggered in Normal mode.
321 Note: Interactive commands cannot be used for
322 this event. There is no hit-enter prompt,
323 the screen is updated directly (when needed).
324 Note: In the future there will probably be
325 another option to set the time.
326 Hint: to force an update of the status lines
327 use: >
328 :let &ro = &ro
329< {only on Amiga, Unix, Win32, MSDOS and all GUI
330 versions}
331 *BufEnter*
332BufEnter After entering a buffer. Useful for setting
333 options for a file type. Also executed when
334 starting to edit a buffer, after the
335 BufReadPost autocommands.
336 *BufLeave*
337BufLeave Before leaving to another buffer. Also when
338 leaving or closing the current window and the
339 new current window is not for the same buffer.
340 Not used for ":qa" or ":q" when exiting Vim.
341 *BufWinEnter*
342BufWinEnter After a buffer is displayed in a window. This
343 can be when the buffer is loaded (after
344 processing the modelines), when a hidden
345 buffer is displayed in a window (and is no
346 longer hidden) or a buffer already visible in
347 a window is also displayed in another window.
348 *BufWinLeave*
349BufWinLeave Before a buffer is removed from a window.
350 Not when it's still visible in another window.
351 Also triggered when exiting. It's triggered
352 before BufUnload or BufHidden.
353 NOTE: When this autocommand is executed, the
354 current buffer "%" may be different from the
355 buffer being unloaded "<afile>".
356 *BufUnload*
357BufUnload Before unloading a buffer. This is when the
358 text in the buffer is going to be freed. This
359 may be after a BufWritePost and before a
360 BufDelete. Also used for all buffers that are
361 loaded when Vim is going to exit.
362 NOTE: When this autocommand is executed, the
363 current buffer "%" may be different from the
364 buffer being unloaded "<afile>".
365 *BufHidden*
366BufHidden Just after a buffer has become hidden. That
367 is, when there are no longer windows that show
368 the buffer, but the buffer is not unloaded or
369 deleted. Not used for ":qa" or ":q" when
370 exiting Vim.
371 NOTE: When this autocommand is executed, the
372 current buffer "%" may be different from the
373 buffer being unloaded "<afile>".
374 *BufNew*
375BufNew Just after creating a new buffer. Also used
376 just after a buffer has been renamed. When
377 the buffer is added to the buffer list BufAdd
378 will be triggered too.
379 NOTE: When this autocommand is executed, the
380 current buffer "%" may be different from the
381 buffer being created "<afile>".
382 *BufCreate* *BufAdd*
383BufAdd or BufCreate Just after creating a new buffer which is
384 added to the buffer list, or adding a buffer
385 to the buffer list.
386 Also used just after a buffer in the buffer
387 list has been renamed.
388 The BufCreate event is for historic reasons.
389 NOTE: When this autocommand is executed, the
390 current buffer "%" may be different from the
391 buffer being created "<afile>".
392 *BufDelete*
393BufDelete Before deleting a buffer from the buffer list.
394 The BufUnload may be called first (if the
395 buffer was loaded).
396 Also used just before a buffer in the buffer
397 list is renamed.
398 NOTE: When this autocommand is executed, the
399 current buffer "%" may be different from the
400 buffer being deleted "<afile>".
401 *BufWipeout*
402BufWipeout Before completely deleting a buffer. The
403 BufUnload and BufDelete events may be called
404 first (if the buffer was loaded and was in the
405 buffer list). Also used just before a buffer
406 is renamed (also when it's not in the buffer
407 list).
408 NOTE: When this autocommand is executed, the
409 current buffer "%" may be different from the
410 buffer being deleted "<afile>".
411 *WinEnter*
412WinEnter After entering another window. Not done for
413 the first window, when Vim has just started.
414 Useful for setting the window height.
415 If the window is for another buffer, Vim
416 executes the BufEnter autocommands after the
417 WinEnter autocommands.
418 Note: When using ":split fname" the WinEnter
419 event is triggered after the split but before
420 the file "fname" is loaded.
421 *WinLeave*
422WinLeave Before leaving a window. If the window to be
423 entered next is for a different buffer, Vim
424 executes the BufLeave autocommands before the
425 WinLeave autocommands (but not for ":new").
426 Not used for ":qa" or ":q" when exiting Vim.
427 *CmdwinEnter*
428CmdwinEnter After entering the command-line window.
429 Useful for setting options specifically for
430 this special type of window. This is
431 triggered _instead_ of BufEnter and WinEnter.
432 <afile> is set to a single character,
433 indicating the type of command-line.
434 |cmdwin-char|
435 *CmdwinLeave*
436CmdwinLeave Before leaving the command-line window.
437 Useful to clean up any global setting done
438 with CmdwinEnter. This is triggered _instead_
439 of BufLeave and WinLeave.
440 <afile> is set to a single character,
441 indicating the type of command-line.
442 |cmdwin-char|
443 *GUIEnter*
444GUIEnter After starting the GUI successfully, and after
445 opening the window. It is triggered before
446 VimEnter when using gvim. Can be used to
447 position the window from a .gvimrc file: >
448 :autocmd GUIEnter * winpos 100 50
449< *VimEnter*
450VimEnter After doing all the startup stuff, including
451 loading .vimrc files, executing the "-c cmd"
452 arguments, creating all windows and loading
453 the buffers in them.
454 *VimLeavePre*
455VimLeavePre Before exiting Vim, just before writing the
456 .viminfo file. This is executed only once,
457 if there is a match with the name of what
458 happens to be the current buffer when exiting.
459 Mostly useful with a "*" pattern. >
460 :autocmd VimLeavePre * call CleanupStuff()
461< To detect an abnormal exit use |v:dying|.
462 *VimLeave*
463VimLeave Before exiting Vim, just after writing the
464 .viminfo file. Executed only once, like
465 VimLeavePre.
466 To detect an abnormal exit use |v:dying|.
467 *EncodingChanged*
468EncodingChanged Fires off when the 'encoding' option is
469 changed. Useful to set up fonts, for example.
470 *FileEncoding*
471FileEncoding Obsolete. It still works and is equivalent
472 to |EncodingChanged|.
473 *RemoteReply*
474RemoteReply When a reply from a Vim that functions as
475 server was received |server2client()|.
476 <amatch> is equal to the {serverid} from which
477 the reply was sent, and <afile> is the actual
478 reply string.
479 Note that even if an autocommand is defined,
480 the reply should be read with |remote_read()|
481 to consume it.
482 *TermChanged*
483TermChanged After the value of 'term' has changed. Useful
484 for re-loading the syntax file to update the
485 colors, fonts and other terminal-dependent
486 settings. Executed for all loaded buffers.
487 *TermResponse*
488TermResponse After the response to |t_RV| is received from
489 the terminal. The value of |v:termresponse|
490 can be used to do things depending on the
491 terminal version.
492 *UserGettingBored*
493UserGettingBored When the user hits CTRL-C. Just kidding! :-)
494 *User*
495User Never executed automatically. To be used for
496 autocommands that are only executed with
497 ":doautocmd".
498
499You can specify a comma-separated list of event names. No white space can be
500used in this list. The command applies to all the events in the list.
501
502For READING FILES there are four kinds of events possible:
503 BufNewFile starting to edit a non-existent file
504 BufReadPre BufReadPost starting to edit an existing file
505 FilterReadPre FilterReadPost read the temp file with filter output
506 FileReadPre FileReadPost any other file read
507Vim uses only one of these four kinds when reading a file. The "Pre" and
508"Post" events are both triggered, before and after reading the file.
509
510Note that the autocommands for the *ReadPre events and all the Filter events
511are not allowed to change the current buffer (you will get an error message if
512this happens). This is to prevent the file to be read into the wrong buffer.
513
514Note that the 'modified' flag is reset AFTER executing the BufReadPost
515and BufNewFile autocommands. But when the 'modified' option was set by the
516autocommands, this doesn't happen.
517
518You can use the 'eventignore' option to ignore a number of events or all
519events.
520
521==============================================================================
5226. Patterns *autocmd-patterns* *{pat}*
523
524The file pattern {pat} is tested for a match against the file name in one of
525two ways:
5261. When there is no '/' in the pattern, Vim checks for a match against only
527 the tail part of the file name (without its leading directory path).
5282. When there is a '/' in the pattern, Vim checks for a match against the
529 both short file name (as you typed it) and the full file name (after
530 expanding it to a full path and resolving symbolic links).
531
532Examples: >
533 :autocmd BufRead *.txt set et
534Set the 'et' option for all text files. >
535
536 :autocmd BufRead /vim/src/*.c set cindent
537Set the 'cindent' option for C files in the /vim/src directory. >
538
539 :autocmd BufRead /tmp/*.c set ts=5
540If you have a link from "/tmp/test.c" to "/home/nobody/vim/src/test.c", and
541you start editing "/tmp/test.c", this autocommand will match.
542
543Note: To match part of a path, but not from the root directory, use a '*' as
544the first character. Example: >
545 :autocmd BufRead */doc/*.txt set tw=78
546This autocommand will for example be executed for "/tmp/doc/xx.txt" and
547"/usr/home/piet/doc/yy.txt". The number of directories does not matter here.
548
549
550The file name that the pattern is matched against is after expanding
551wildcards. Thus is you issue this command: >
552 :e $ROOTDIR/main.$EXT
553The argument is first expanded to: >
554 /usr/root/main.py
555Before it's matched with the pattern of the autocommand. Careful with this
556when using events like FileReadCmd, the value of <amatch> may not be what you
557expect.
558
559
560Environment variables can be used in a pattern: >
561 :autocmd BufRead $VIMRUNTIME/doc/*.txt set expandtab
562And ~ can be used for the home directory (if $HOME is defined): >
563 :autocmd BufWritePost ~/.vimrc so ~/.vimrc
564 :autocmd BufRead ~archive/* set readonly
565The environment variable is expanded when the autocommand is defined, not when
566the autocommand is executed. This is different from the command!
567
568 *file-pattern*
569The pattern is interpreted like mostly used in file names:
570 * matches any sequence of characters
571 ? matches any single character
572 \? matches a '?'
573 . matches a '.'
574 ~ matches a '~'
575 , separates patterns
576 \, matches a ','
577 { } like \( \) in a |pattern|
578 , inside { }: like \| in a |pattern|
579 \ special meaning like in a |pattern|
580 [ch] matches 'c' or 'h'
581 [^ch] match any character but 'c' and 'h'
582
583Note that for all systems the '/' character is used for path separator (even
584MS-DOS and OS/2). This was done because the backslash is difficult to use
585in a pattern and to make the autocommands portable across different systems.
586
587
588Matching with the pattern is done when an event is triggered. Changing the
589buffer name in one of the autocommands, or even deleting the buffer, does not
590change which autocommands will be executed. Example: >
591
592 au BufEnter *.foo bdel
593 au BufEnter *.foo set modified
594
595This will delete the current buffer and then set 'modified' in what has become
596the current buffer instead. Vim doesn't take into account that "*.foo"
597doesn't match with that buffer name. It matches "*.foo" with the name of the
598buffer at the moment the event was triggered.
599
600==============================================================================
6017. Groups *autocmd-groups*
602
603Autocommands can be put together in a group. This is useful for removing or
604executing a group of autocommands. For example, all the autocommands for
605syntax highlighting are put in the "highlight" group, to be able to execute
606":doautoall highlight BufRead" when the GUI starts.
607
608When no specific group is selected, Vim uses the default group. The default
609group does not have a name. You cannot execute the autocommands from the
610default group separately; you can execute them only by executing autocommands
611for all groups.
612
613Normally, when executing autocommands automatically, Vim uses the autocommands
614for all groups. The group only matters when executing autocommands with
615":doautocmd" or ":doautoall", or when defining or deleting autocommands.
616
617The group name can contain any characters except white space. The group name
618"end" is reserved (also in uppercase).
619
620The group name is case sensitive. Note that this is different from the event
621name!
622
623 *:aug* *:augroup*
624:aug[roup] {name} Define the autocmd group name for the
625 following ":autocmd" commands. The name "end"
626 or "END" selects the default group.
627
628 *:augroup-delete* *E367*
629:aug[roup]! {name} Delete the autocmd group {name}. Don't use
630 this if there is still an autocommand using
631 this group! This is not checked.
632
633To enter autocommands for a specific group, use this method:
6341. Select the group with ":augroup {name}".
6352. Delete any old autocommands with ":au!".
6363. Define the autocommands.
6374. Go back to the default group with "augroup END".
638
639Example: >
640 :augroup uncompress
641 : au!
642 : au BufEnter *.gz %!gunzip
643 :augroup END
644
645This prevents having the autocommands defined twice (e.g., after sourcing the
646.vimrc file again).
647
648==============================================================================
6498. Executing autocommands *autocmd-execute*
650
651Vim can also execute Autocommands non-automatically. This is useful if you
652have changed autocommands, or when Vim has executed the wrong autocommands
653(e.g., the file pattern match was wrong).
654
655Note that the 'eventignore' option applies here too. Events listed in this
656option will not cause any commands to be executed.
657
658 *:do* *:doau* *:doautocmd* *E217*
659:do[autocmd] [group] {event} [fname]
660 Apply the autocommands matching [fname] (default:
661 current file name) for {event} to the current buffer.
662 You can use this when the current file name does not
663 match the right pattern, after changing settings, or
664 to execute autocommands for a certain event.
665 It's possible to use this inside an autocommand too,
666 so you can base the autocommands for one extension on
667 another extension. Example: >
668 :au Bufenter *.cpp so ~/.vimrc_cpp
669 :au Bufenter *.cpp doau BufEnter x.c
670< Be careful to avoid endless loops. See
671 |autocmd-nested|.
672
673 When the [group] argument is not given, Vim executes
674 the autocommands for all groups. When the [group]
675 argument is included, Vim executes only the matching
676 autocommands for that group. Note: if you use an
677 undefined group name, Vim gives you an error message.
678
679 *:doautoa* *:doautoall*
680:doautoa[ll] [group] {event} [fname]
681 Like ":doautocmd", but apply the autocommands to each
682 loaded buffer. Note that {fname} is used to select
683 the autocommands, not the buffers to which they are
684 applied.
685 Careful: Don't use this for autocommands that delete a
686 buffer, change to another buffer or change the
687 contents of a buffer; the result is unpredictable.
688 This command is intended for autocommands that set
689 options, change highlighting, and things like that.
690
691==============================================================================
6929. Using autocommands *autocmd-use*
693
694For WRITING FILES there are four possible sets of events. Vim uses only one
695of these sets for a write command:
696
697BufWriteCmd BufWritePre BufWritePost writing the whole buffer
698 FilterWritePre FilterWritePost writing to filter temp file
699FileAppendCmd FileAppendPre FileAppendPost appending to a file
700FileWriteCmd FileWritePre FileWritePost any other file write
701
702When there is a matching "*Cmd" autocommand, it is assumed it will do the
703writing. No further writing is done and the other events are not triggered.
704|Cmd-event|
705
706Note that the *WritePost commands should undo any changes to the buffer that
707were caused by the *WritePre commands; otherwise, writing the file will have
708the side effect of changing the buffer.
709
710Before executing the autocommands, the buffer from which the lines are to be
711written temporarily becomes the current buffer. Unless the autocommands
712change the current buffer or delete the previously current buffer, the
713previously current buffer is made the current buffer again.
714
715The *WritePre and *AppendPre autocommands must not delete the buffer from
716which the lines are to be written.
717
718The '[ and '] marks have a special position:
719- Before the *ReadPre event the '[ mark is set to the line just above where
720 the new lines will be inserted.
721- Before the *ReadPost event the '[ mark is set to the first line that was
722 just read, the '] mark to the last line.
723- Before executing the *WritePre and *AppendPre autocommands the '[ mark is
724 set to the first line that will be written, the '] mark to the last line.
725Careful: '[ and '] change when using commands that change the buffer.
726
727In commands which expect a file name, you can use "<afile>" for the file name
728that is being read |:<afile>| (you can also use "%" for the current file
729name). "<abuf>" can be used for the buffer number of the currently effective
730buffer. This also works for buffers that doesn't have a name. But it doesn't
731work for files without a buffer (e.g., with ":r file").
732
733 *gzip-example*
734Examples for reading and writing compressed files: >
735 :augroup gzip
736 : autocmd!
737 : autocmd BufReadPre,FileReadPre *.gz set bin
738 : autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip
739 : autocmd BufReadPost,FileReadPost *.gz set nobin
740 : autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " . expand("%:r")
741 : autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r
742 : autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r
743
744 : autocmd FileAppendPre *.gz !gunzip <afile>
745 : autocmd FileAppendPre *.gz !mv <afile>:r <afile>
746 : autocmd FileAppendPost *.gz !mv <afile> <afile>:r
747 : autocmd FileAppendPost *.gz !gzip <afile>:r
748 :augroup END
749
750The "gzip" group is used to be able to delete any existing autocommands with
751":autocmd!", for when the file is sourced twice.
752
753("<afile>:r" is the file name without the extension, see |:_%:|)
754
755The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,
756FileAppendPost and VimLeave events do not set or reset the changed flag of the
757buffer. When you decompress the buffer with the BufReadPost autocommands, you
758can still exit with ":q". When you use ":undo" in BufWritePost to undo the
759changes made by BufWritePre commands, you can still do ":q" (this also makes
760"ZZ" work). If you do want the buffer to be marked as modified, set the
761'modified' option.
762
763To execute Normal mode commands from an autocommand, use the ":normal"
764command. Use with care! If the Normal mode command is not finished, the user
765needs to type characters (e.g., after ":normal m" you need to type a mark
766name).
767
768If you want the buffer to be unmodified after changing it, reset the
769'modified' option. This makes it possible to exit the buffer with ":q"
770instead of ":q!".
771
772 *autocmd-nested* *E218*
773By default, autocommands do not nest. If you use ":e" or ":w" in an
774autocommand, Vim does not execute the BufRead and BufWrite autocommands for
775those commands. If you do want this, use the "nested" flag for those commands
776in which you want nesting. For example: >
777 :autocmd FileChangedShell *.c nested e!
778The nesting is limited to 10 levels to get out of recursive loops.
779
780It's possible to use the ":au" command in an autocommand. This can be a
781self-modifying command! This can be useful for an autocommand that should
782execute only once.
783
784There is currently no way to disable the autocommands. If you want to write a
785file without executing the autocommands for that type of file, write it under
786another name and rename it with a shell command. In some situations you can
787use the 'eventignore' option.
788
789Note: When reading a file (with ":read file" or with a filter command) and the
790last line in the file does not have an <EOL>, Vim remembers this. At the next
791write (with ":write file" or with a filter command), if the same line is
792written again as the last line in a file AND 'binary' is set, Vim does not
793supply an <EOL>. This makes a filter command on the just read lines write the
794same file as was read, and makes a write command on just filtered lines write
795the same file as was read from the filter. For example, another way to write
796a compressed file: >
797
798 :autocmd FileWritePre *.gz set bin|'[,']!gzip
799 :autocmd FileWritePost *.gz undo|set nobin
800<
801 *autocommand-pattern*
802You can specify multiple patterns, separated by commas. Here are some
803examples: >
804
805 :autocmd BufRead * set tw=79 nocin ic infercase fo=2croq
806 :autocmd BufRead .letter set tw=72 fo=2tcrq
807 :autocmd BufEnter .letter set dict=/usr/lib/dict/words
808 :autocmd BufLeave .letter set dict=
809 :autocmd BufRead,BufNewFile *.c,*.h set tw=0 cin noic
810 :autocmd BufEnter *.c,*.h abbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O
811 :autocmd BufLeave *.c,*.h unabbr FOR
812
813For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.): >
814
815 :autocmd BufEnter ?akefile* set include=^s\=include
816 :autocmd BufLeave ?akefile* set include&
817
818To always start editing C files at the first function: >
819
820 :autocmd BufRead *.c,*.h 1;/^{
821
822Without the "1;" above, the search would start from wherever the file was
823entered, rather than from the start of the file.
824
825 *skeleton* *template*
826To read a skeleton (template) file when opening a new file: >
827
828 :autocmd BufNewFile *.c 0r ~/vim/skeleton.c
829 :autocmd BufNewFile *.h 0r ~/vim/skeleton.h
830 :autocmd BufNewFile *.java 0r ~/vim/skeleton.java
831
832To insert the current date and time in a *.html file when writing it: >
833
834 :autocmd BufWritePre,FileWritePre *.html ks|call LastMod()|'s
835 :fun LastMod()
836 : if line("$") > 20
837 : let l = 20
838 : else
839 : let l = line("$")
840 : endif
841 : exe "1," . l . "g/Last modified: /s/Last modified: .*/Last modified: " .
842 : \ strftime("%Y %b %d")
843 :endfun
844
845You need to have a line "Last modified: <date time>" in the first 20 lines
846of the file for this to work. Vim replaces <date time> (and anything in the
847same line after it) with the current date and time. Explanation:
848 ks mark current position with mark 's'
849 call LastMod() call the LastMod() function to do the work
850 's return the cursor to the old position
851The LastMod() function checks if the file is shorter than 20 lines, and then
852uses the ":g" command to find lines that contain "Last modified: ". For those
853lines the ":s" command is executed to replace the existing date with the
854current one. The ":execute" command is used to be able to use an expression
855for the ":g" and ":s" commands. The date is obtained with the strftime()
856function. You can change its argument to get another date string.
857
858When entering :autocmd on the command-line, completion of events and command
859names may be done (with <Tab>, CTRL-D, etc.) where appropriate.
860
861Vim executes all matching autocommands in the order that you specify them.
862It is recommended that your first autocommand be used for all files by using
863"*" as the file pattern. This means that you can define defaults you like
864here for any settings, and if there is another matching autocommand it will
865override these. But if there is no other matching autocommand, then at least
866your default settings are recovered (if entering this file from another for
867which autocommands did match). Note that "*" will also match files starting
868with ".", unlike Unix shells.
869
870 *autocmd-searchpat*
871Autocommands do not change the current search patterns. Vim saves the current
872search patterns before executing autocommands then restores them after the
873autocommands finish. This means that autocommands do not affect the strings
874highlighted with the 'hlsearch' option. Within autocommands, you can still
875use search patterns normally, e.g., with the "n" command.
876If you want an autocommand to set the search pattern, such that it is used
877after the autocommand finishes, use the ":let @/ =" command.
878The search-highlighting cannot be switched off with ":nohlsearch" in an
879autocommand. Use the 'h' flag in the 'viminfo' option to disable search-
880highlighting when starting Vim.
881
882 *Cmd-event*
883When using one of the "*Cmd" events, the matching autocommands are expected to
884do the file reading or writing. This can be used when working with a special
885kind of file, for example on a remote system.
886CAREFUL: If you use these events in a wrong way, it may have the effect of
887making it impossible to read or write the matching files! Make sure you test
888your autocommands properly. Best is to use a pattern that will never match a
889normal file name, for example "ftp://*".
890
891When defining a BufReadCmd it will be difficult for Vim to recover a crashed
892editing session. When recovering from the original file, Vim reads only those
893parts of a file that are not found in the swap file. Since that is not
894possible with a BufReadCmd, use the |:preserve| command to make sure the
895original file isn't needed for recovery. You might want to do this only when
896you expect the file to be modified.
897
898The |v:cmdarg| variable holds the "++enc=" and "++ff=" argument that are
899effective. These should be used for the command that reads/writes the file.
900The |v:cmdbang| variable is one when "!" was used, zero otherwise.
901
902See the $VIMRUNTIME/plugin/netrw.vim for examples.
903
904 vim:tw=78:ts=8:ft=help:norl: